1 //===- Utils.cpp - Utilities to support the Linalg dialect ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements utilities for the Linalg dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/Linalg/Utils/Utils.h"
14 
15 #include "mlir/Analysis/SliceAnalysis.h"
16 #include "mlir/Dialect/Affine/Analysis/AffineStructures.h"
17 #include "mlir/Dialect/Affine/IR/AffineOps.h"
18 #include "mlir/Dialect/Affine/IR/AffineValueMap.h"
19 #include "mlir/Dialect/Affine/LoopUtils.h"
20 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
21 #include "mlir/Dialect/Arithmetic/Utils/Utils.h"
22 #include "mlir/Dialect/Linalg/IR/Linalg.h"
23 #include "mlir/Dialect/MemRef/IR/MemRef.h"
24 #include "mlir/Dialect/SCF/SCF.h"
25 #include "mlir/Dialect/Tensor/IR/Tensor.h"
26 #include "mlir/Dialect/Tensor/Utils/Utils.h"
27 #include "mlir/Dialect/Utils/StaticValueUtils.h"
28 #include "mlir/IR/AffineExpr.h"
29 #include "mlir/IR/AffineExprVisitor.h"
30 #include "mlir/IR/AffineMap.h"
31 #include "mlir/IR/Matchers.h"
32 #include "mlir/IR/OpImplementation.h"
33 #include "mlir/Pass/Pass.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include "llvm/Support/Debug.h"
36 
37 #define DEBUG_TYPE "linalg-utils"
38 
39 using namespace mlir;
40 using namespace presburger;
41 using namespace mlir::linalg;
42 using namespace mlir::scf;
43 
44 static bool isZero(Value v) {
45   if (auto cst = v.getDefiningOp<arith::ConstantIndexOp>())
46     return cst.value() == 0;
47   return false;
48 }
49 
50 namespace {
51 
52 // Helper visitor to determine whether an AffineExpr is tiled.
53 // This is achieved by traversing every AffineDimExpr with position `pos` and
54 // checking whether the corresponding `tileSizes[pos]` is non-zero.
55 // This also enforces only positive coefficients occur in multiplications.
56 //
57 // Example:
58 //   `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0]
59 //
60 struct TileCheck : public AffineExprVisitor<TileCheck> {
61   TileCheck(ValueRange tileSizes) : tileSizes(tileSizes) {}
62 
63   void visitDimExpr(AffineDimExpr expr) {
64     isTiled |= !isZero(tileSizes[expr.getPosition()]);
65   }
66   void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
67     visit(expr.getLHS());
68     visit(expr.getRHS());
69     if (expr.getKind() == mlir::AffineExprKind::Mul)
70       assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 &&
71              "nonpositive multiplying coefficient");
72   }
73   bool isTiled = false;
74   ValueRange tileSizes;
75 };
76 
77 } // namespace
78 
79 static bool isTiled(AffineExpr expr, ValueRange tileSizes) {
80   if (!expr)
81     return false;
82   TileCheck t(tileSizes);
83   t.visit(expr);
84   return t.isTiled;
85 }
86 
87 // Checks whether the `map  varies with respect to a non-zero `tileSize`.
88 static bool isTiled(AffineMap map, ValueRange tileSizes) {
89   if (!map)
90     return false;
91   for (unsigned r = 0; r < map.getNumResults(); ++r)
92     if (isTiled(map.getResult(r), tileSizes))
93       return true;
94   return false;
95 }
96 
97 Optional<RegionMatcher::BinaryOpKind>
98 RegionMatcher::matchAsScalarBinaryOp(GenericOp op) {
99   auto &region = op.region();
100   if (!llvm::hasSingleElement(region))
101     return llvm::None;
102 
103   Block &block = region.front();
104   if (block.getNumArguments() != 2 ||
105       !block.getArgument(0).getType().isSignlessIntOrFloat() ||
106       !block.getArgument(1).getType().isSignlessIntOrFloat())
107     return llvm::None;
108 
109   auto &ops = block.getOperations();
110   if (!llvm::hasSingleElement(block.without_terminator()))
111     return llvm::None;
112 
113   using mlir::matchers::m_Val;
114   auto a = m_Val(block.getArgument(0));
115   auto b = m_Val(block.getArgument(1));
116 
117   auto addPattern = m_Op<linalg::YieldOp>(m_Op<arith::AddIOp>(a, b));
118   if (addPattern.match(&ops.back()))
119     return BinaryOpKind::IAdd;
120 
121   return llvm::None;
122 }
123 
124 /// Explicit instantiation of loop nest generator for different loop types.
125 template struct mlir::linalg::GenerateLoopNest<scf::ForOp>;
126 template struct mlir::linalg::GenerateLoopNest<scf::ParallelOp>;
127 template struct mlir::linalg::GenerateLoopNest<AffineForOp>;
128 
129 /// Given a list of subview ranges, extract individual values for lower, upper
130 /// bounds and steps and put them into the corresponding vectors.
131 static void unpackRanges(ArrayRef<Range> ranges, SmallVectorImpl<Value> &lbs,
132                          SmallVectorImpl<Value> &ubs,
133                          SmallVectorImpl<Value> &steps) {
134   for (Range range : ranges) {
135     lbs.emplace_back(range.offset);
136     ubs.emplace_back(range.size);
137     steps.emplace_back(range.stride);
138   }
139 }
140 
141 namespace mlir {
142 namespace linalg {
143 
144 bool isPermutation(ArrayRef<int64_t> permutation) {
145   // Count the number of appearances for all indices.
146   SmallVector<int64_t> indexCounts(permutation.size(), 0);
147   for (auto index : permutation) {
148     // Exit if the index is out-of-range.
149     if (index < 0 || index >= static_cast<int64_t>(permutation.size()))
150       return false;
151     indexCounts[index]++;
152   }
153   // Return true if all indices appear once.
154   return count(indexCounts, 1) == static_cast<int64_t>(permutation.size());
155 }
156 
157 /// Helper function that creates a memref::DimOp or tensor::DimOp depending on
158 /// the type of `source`.
159 Value createOrFoldDimOp(OpBuilder &b, Location loc, Value source, int64_t dim) {
160   if (source.getType().isa<UnrankedMemRefType, MemRefType>())
161     return b.createOrFold<memref::DimOp>(loc, source, dim);
162   if (source.getType().isa<UnrankedTensorType, RankedTensorType>())
163     return b.createOrFold<tensor::DimOp>(loc, source, dim);
164   llvm_unreachable("Expected MemRefType or TensorType");
165 }
166 
167 /// Given an operation, retrieves the value of each dynamic dimension through
168 /// constructing the necessary DimOp operators.
169 SmallVector<Value, 4> getDynOperands(Location loc, Value val, OpBuilder &b) {
170   SmallVector<Value, 4> dynOperands;
171   auto shapedType = val.getType().cast<ShapedType>();
172   for (const auto &dim : llvm::enumerate(shapedType.getShape())) {
173     if (dim.value() == ShapedType::kDynamicSize)
174       dynOperands.push_back(createOrFoldDimOp(b, loc, val, dim.index()));
175   }
176   return dynOperands;
177 }
178 
179 void getUpperBoundForIndex(Value value, AffineMap &boundMap,
180                            SmallVectorImpl<Value> &boundOperands) {
181   // Initialize `boundMap` and `boundOperands` to the identity returning
182   // `value`. This combination is the default result of the method if no
183   // simplification is possible.
184   assert(value.getType().isIndex() && "expect value to have index type");
185   boundMap = AffineMap::getMultiDimIdentityMap(1, value.getContext());
186   boundOperands.assign({value});
187   canonicalizeMapAndOperands(&boundMap, &boundOperands);
188 
189   // Continue only if there is an affine index computation to simplify.
190   Operation *definingOp = value.getDefiningOp();
191   if (!definingOp || !isa<AffineApplyOp, AffineMinOp>(definingOp))
192     return;
193 
194   // Get the backward slice containing the affine index computation.
195   SetVector<Operation *> backwardSlice;
196   getBackwardSlice(definingOp, &backwardSlice, [](Operation *op) {
197     return isa<AffineApplyOp, AffineMinOp>(op);
198   });
199   backwardSlice.insert(definingOp);
200 
201   // Setup a system of affine constraints that describe the index computation.
202   FlatAffineValueConstraints constraints;
203 
204   // Helper to find or create an identifier for the given value.
205   auto findOrCreateId = [&](Value value) {
206     if (!constraints.containsId(value)) {
207       constraints.appendDimId(value);
208       return true;
209     }
210     unsigned pos;
211     constraints.findId(value, &pos);
212     return pos < constraints.getNumDimIds();
213   };
214   // Helper to get the position for the given value.
215   auto getPosition = [&](Value value) {
216     unsigned pos;
217     bool exists = constraints.findId(value, &pos);
218     (void)exists;
219     assert(exists && "expect to find the identifier");
220     return pos;
221   };
222 
223   // Add the affine operations in `backwardSlice` to the constraints.
224   for (Operation *op : llvm::reverse(backwardSlice)) {
225     // Add an identifier for all op results and operands.
226     if (!(llvm::all_of(op->getResults(), findOrCreateId) &&
227           llvm::all_of(op->getOperands(), findOrCreateId)))
228       return;
229     // Add AffineApplyOps to the constraints.
230     if (auto applyOp = dyn_cast<AffineApplyOp>(op)) {
231       AffineValueMap valueMap(applyOp.getAffineMap(), applyOp.getOperands(),
232                               applyOp.getResult());
233       if (failed(constraints.composeMap(&valueMap)))
234         return;
235       continue;
236     }
237     // Add AffineMinOps to the constraints.
238     auto minOp = cast<AffineMinOp>(op);
239     AffineMap map = constraints.computeAlignedMap(minOp.getAffineMap(),
240                                                   minOp.getOperands());
241     if (failed(constraints.addBound(IntegerPolyhedron::UB,
242                                     getPosition(minOp.getResult()), map)))
243       return;
244   }
245 
246   // Obtain an upper bound for the affine index computation by projecting out
247   // all temporary results and expressing the upper bound for `value` in terms
248   // of the terminals of the index computation.
249   SmallVector<AffineMap> lowerBounds(1), upperBounds(1);
250   constraints.getSliceBounds(getPosition(value), 1, value.getContext(),
251                              &lowerBounds, &upperBounds);
252 
253   // Verify `upperBounds[0]` is valid and has at least one result.
254   if (!upperBounds[0] || upperBounds[0].getNumResults() == 0)
255     return;
256 
257   // Set `boundMap` and `boundOperands` to the computed upper bound.
258   boundMap = upperBounds[0];
259   constraints.getAllValues(&boundOperands);
260   erase_value(boundOperands, value);
261   canonicalizeMapAndOperands(&boundMap, &boundOperands);
262 }
263 
264 FailureOr<int64_t> getConstantUpperBoundForIndex(Value value) {
265   // Compute an upper bound for `value`.
266   AffineMap boundMap;
267   SmallVector<Value> boundOperands;
268   getUpperBoundForIndex(value, boundMap, boundOperands);
269 
270   // Search the results of `boundMap` for constant upper bounds.
271   SmallVector<int64_t> constantBounds;
272   for (AffineExpr result : boundMap.getResults())
273     if (auto constExpr = result.dyn_cast<AffineConstantExpr>())
274       constantBounds.push_back(constExpr.getValue());
275 
276   // Return the minimal upper bound or failure if none is found.
277   if (constantBounds.empty())
278     return failure();
279   return *std::min_element(constantBounds.begin(), constantBounds.end());
280 }
281 
282 tensor::ExtractSliceOp makeComposedExtractSliceOp(
283     OpBuilder &b, Location loc, Value source, ArrayRef<OpFoldResult> offsets,
284     ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) {
285   assert(source && "expect source to be nonzero");
286 
287   // Do not fold if the producer is not an ExtractSliceOp.
288   auto producerOp = source.getDefiningOp<tensor::ExtractSliceOp>();
289   if (!producerOp)
290     return b.create<tensor::ExtractSliceOp>(loc, source, offsets, sizes,
291                                             strides);
292 
293   // Do not fold if the producer is rank reducing or if there are any non-unit
294   // strides. Supporting non-unit strides complicates the offset computation
295   // since the consumer offsets need to be multiplied by the producer strides.
296   // TODO: support non-unit strides once there are use cases.
297   SmallVector<OpFoldResult> allStrides = producerOp.getMixedStrides();
298   allStrides.append(strides.begin(), strides.end());
299   bool hasNonUnitStride = any_of(allStrides, [](OpFoldResult ofr) {
300     return getConstantIntValue(ofr) != static_cast<int64_t>(1);
301   });
302   if (hasNonUnitStride ||
303       producerOp.getSourceType().getRank() !=
304           producerOp.getResult().getType().cast<ShapedType>().getRank())
305     return b.create<tensor::ExtractSliceOp>(loc, source, offsets, sizes,
306                                             strides);
307 
308   // Fold the producer by adding the offests and extracting the slice directly
309   // from the producer source tensor.
310   SmallVector<OpFoldResult> foldedOffsets(offsets.begin(), offsets.end());
311   AffineExpr dim1, dim2;
312   bindDims(b.getContext(), dim1, dim2);
313   for (const auto &en : enumerate(producerOp.getMixedOffsets())) {
314     SmallVector<Value> offsetValues = {
315         getValueOrCreateConstantIndexOp(b, loc, foldedOffsets[en.index()]),
316         getValueOrCreateConstantIndexOp(b, loc, en.value())};
317     foldedOffsets[en.index()] =
318         makeComposedAffineApply(b, loc, dim1 + dim2, offsetValues).getResult();
319   }
320   return b.create<tensor::ExtractSliceOp>(loc, producerOp.source(),
321                                           foldedOffsets, sizes, strides);
322 }
323 
324 Value makeComposedPadHighOp(OpBuilder &b, Location loc, RankedTensorType type,
325                             Value source, Value pad, bool nofold) {
326   // Exit if `source` is not defined by an ExtractSliceOp.
327   auto sliceOp = source.getDefiningOp<tensor::ExtractSliceOp>();
328   if (!sliceOp)
329     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
330 
331   // Search the `source` use-def chain for padded LinalgOps.
332   Value current = sliceOp.source();
333   while (current) {
334     auto linalgOp = current.getDefiningOp<LinalgOp>();
335     if (!linalgOp)
336       break;
337     OpResult opResult = current.cast<OpResult>();
338     current = linalgOp.getOutputOperand(opResult.getResultNumber())->get();
339   }
340   auto padOp = current ? current.getDefiningOp<tensor::PadOp>() : nullptr;
341 
342   // Exit if the search fails to match a tensor::PadOp at the end of the matched
343   // LinalgOp sequence.
344   if (!padOp)
345     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
346 
347   // Exit if the padded result type does not match.
348   if (sliceOp.source().getType() != type)
349     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
350 
351   // Exit if the LinalgOps are not high padded.
352   if (llvm::any_of(padOp.getMixedLowPad(), [](OpFoldResult ofr) {
353         return getConstantIntValue(ofr) != static_cast<int64_t>(0);
354       }))
355     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
356 
357   // Exit if `padOpSliceOp`, which defines the slice used by
358   // `padOp`, is rank-reducing.
359   auto padOpSliceOp = padOp.source().getDefiningOp<tensor::ExtractSliceOp>();
360   if (!padOpSliceOp ||
361       sliceOp.getMixedSizes().size() != padOpSliceOp.getMixedSizes().size())
362     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
363 
364   // Exit if the sizes of the dynamic sizes of `sliceOp` do not match the size
365   // of the slice padded by `padOp`.
366   if (llvm::any_of(
367           llvm::zip(sliceOp.getMixedSizes(), padOpSliceOp.getMixedSizes()),
368           [](std::tuple<OpFoldResult, OpFoldResult> it) {
369             return !isEqualConstantIntOrValue(std::get<0>(it), std::get<1>(it));
370           }))
371     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
372 
373   // Exit if the padding values do not match.
374   Attribute padOpPadAttr, padAttr;
375   Value padOpPad = padOp.getConstantPaddingValue();
376   if (!padOpPad || !matchPattern(padOpPad, m_Constant(&padOpPadAttr)) ||
377       !matchPattern(pad, m_Constant(&padAttr)) || padOpPadAttr != padAttr)
378     return tensor::createPadHighOp(type, source, pad, nofold, loc, b);
379 
380   // Return the padded result if the padding values and sizes match.
381   return sliceOp.source();
382 }
383 
384 GenericOp makeTransposeOp(OpBuilder &b, Location loc, Value inputTensor,
385                           Value outputTensor,
386                           ArrayRef<int64_t> transposeVector) {
387   auto resultTensorType = outputTensor.getType().cast<RankedTensorType>();
388   Type elementType = resultTensorType.getElementType();
389 
390   assert(isPermutation(transposeVector) &&
391          "expect transpose vector to be a permutation");
392   assert(transposeVector.size() ==
393              static_cast<size_t>(resultTensorType.getRank()) &&
394          "expect transpose vector size to match result tensor rank");
395 
396   // Compute the transpose and the indentity indexing maps.
397   SmallVector<AffineMap> indexingMaps = {
398       inversePermutation(AffineMap::getPermutationMap(
399           SmallVector<unsigned>(transposeVector.begin(), transposeVector.end()),
400           b.getContext())),
401       AffineMap::getMultiDimIdentityMap(transposeVector.size(),
402                                         b.getContext())};
403   SmallVector<llvm::StringRef> iteratorTypes(transposeVector.size(),
404                                              getParallelIteratorTypeName());
405 
406   // Create a GenericOp to transpose `inputTensor` into `outputTensor`.
407   auto transposeOp = b.create<GenericOp>(
408       loc, resultTensorType, inputTensor, outputTensor,
409       b.getAffineMapArrayAttr(indexingMaps), b.getStrArrayAttr(iteratorTypes),
410       /*doc=*/nullptr,
411       /*library_call=*/nullptr);
412   Region &body = transposeOp.getRegion();
413   body.push_back(new Block());
414   body.front().addArguments({elementType, elementType}, {loc, loc});
415 
416   // Create the body of the transpose operation.
417   OpBuilder::InsertionGuard g(b);
418   b.setInsertionPointToEnd(&body.front());
419   b.create<YieldOp>(loc, transposeOp.getRegion().front().getArgument(0));
420   return transposeOp;
421 }
422 
423 GenericOp makeMemRefCopyOp(OpBuilder &b, Location loc, Value from, Value to) {
424   auto memrefTypeTo = to.getType().cast<MemRefType>();
425 #ifndef NDEBUG
426   auto memrefTypeFrom = from.getType().cast<MemRefType>();
427   assert(memrefTypeFrom.getRank() == memrefTypeTo.getRank() &&
428          "`from` and `to` memref must have the same rank");
429 #endif // NDEBUG
430 
431   AffineMap id =
432       AffineMap::getMultiDimIdentityMap(memrefTypeTo.getRank(), b.getContext());
433   SmallVector<StringRef> iteratorTypes(memrefTypeTo.getRank(),
434                                        getParallelIteratorTypeName());
435   return b.create<linalg::GenericOp>(
436       loc,
437       /*inputs=*/from,
438       /*outputs=*/to,
439       /*indexingMaps=*/llvm::makeArrayRef({id, id}),
440       /*iteratorTypes=*/iteratorTypes,
441       [](OpBuilder &b, Location loc, ValueRange args) {
442         b.create<linalg::YieldOp>(loc, args.front());
443       });
444 }
445 
446 /// Specialization to build an scf "for" nest.
447 template <>
448 void GenerateLoopNest<scf::ForOp>::doit(
449     OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp,
450     ArrayRef<Attribute> iteratorTypes,
451     function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange,
452                                   ValueRange)>
453         bodyBuilderFn,
454     Optional<LinalgLoopDistributionOptions> distributionOptions,
455     ArrayRef<StringRef> distributionTypes) {
456   SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands();
457   // Create procInfo so it dominates loops, if appropriate.
458   SmallVector<ProcInfo, 4> procInfo;
459   SmallVector<DistributionMethod, 0> distributionMethod;
460   if (distributionOptions.hasValue()) {
461     // Collect loop ranges for parallel dimensions.
462     SmallVector<Range, 2> parallelLoopRanges;
463     for (const auto &iteratorType : enumerate(iteratorTypes))
464       if (isParallelIterator(iteratorType.value()))
465         parallelLoopRanges.push_back(loopRanges[iteratorType.index()]);
466 
467     // Get their distribution schemes.
468     distributionMethod = distributionOptions->distributionMethod;
469     if (distributionMethod.size() < parallelLoopRanges.size())
470       parallelLoopRanges.resize(distributionMethod.size());
471     procInfo = distributionOptions->procInfo(b, loc, parallelLoopRanges);
472   }
473 
474   SmallVector<Value, 4> lbs, ubs, steps;
475   unpackRanges(loopRanges, lbs, ubs, steps);
476   LoopNest loopNest = mlir::scf::buildLoopNest(
477       b, loc, lbs, ubs, steps, iterArgInitValues,
478       [&](OpBuilder &b, Location loc, ValueRange ivs, ValueRange iterArgs) {
479         assert(iterArgs.size() == linalgOp.getOutputTensorOperands().size() &&
480                "expect the number of output tensors and iter args to match");
481         SmallVector<Value> operandValuesToUse =
482             linalgOp.getInputAndOutputOperands();
483         if (!iterArgs.empty()) {
484           operandValuesToUse = linalgOp.getInputOperands();
485           operandValuesToUse.append(iterArgs.begin(), iterArgs.end());
486         }
487         return bodyBuilderFn(b, loc, ivs, operandValuesToUse);
488       });
489 
490   if (!distributionOptions || loopNest.loops.empty())
491     return;
492 
493   // Filter out scf.for loops that were created out of parallel dimensions.
494   SmallVector<scf::ForOp, 4> loops;
495   for (const auto &iteratorType : enumerate(iteratorTypes))
496     if (isParallelIterator(iteratorType.value()))
497       loops.push_back(loopNest.loops[iteratorType.index()]);
498 
499   // Distribute - only supports cyclic distribution for now.
500   for (auto it : llvm::zip(loops, procInfo, distributionMethod))
501     if (std::get<2>(it) == DistributionMethod::Cyclic)
502       mapLoopToProcessorIds(std::get<0>(it), std::get<1>(it).procId,
503                             std::get<1>(it).nprocs);
504 }
505 
506 /// Specialization to build affine "for" nest.
507 template <>
508 void GenerateLoopNest<AffineForOp>::doit(
509     OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp,
510     ArrayRef<Attribute> iteratorTypes,
511     function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange,
512                                   ValueRange)>
513         bodyBuilderFn,
514     Optional<LinalgLoopDistributionOptions>, ArrayRef<StringRef>) {
515   SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands();
516   assert(iterArgInitValues.empty() && "unexpected AffineForOp init values");
517   SmallVector<Value, 4> lbs, ubs, steps;
518   unpackRanges(loopRanges, lbs, ubs, steps);
519 
520   // Affine loops require constant steps.
521   SmallVector<int64_t, 4> constantSteps;
522   constantSteps.reserve(steps.size());
523   for (Value v : steps) {
524     auto op = v.getDefiningOp<arith::ConstantIndexOp>();
525     assert(op && "Affine loops require constant steps");
526     constantSteps.push_back(op.value());
527   }
528 
529   mlir::buildAffineLoopNest(b, loc, lbs, ubs, constantSteps,
530                             [&](OpBuilder &b, Location loc, ValueRange ivs) {
531                               SmallVector<Value> operandValuesToUse =
532                                   linalgOp.getInputAndOutputOperands();
533                               bodyBuilderFn(b, loc, ivs, operandValuesToUse);
534                             });
535 }
536 
537 /// Update the `lb`, `ub` and `step` to get per processor `lb`, `ub` and `step`.
538 void updateBoundsForCyclicDistribution(OpBuilder &b, Location loc, Value procId,
539                                        Value nprocs, Value &lb, Value &ub,
540                                        Value &step) {
541   AffineExpr d0, d1;
542   bindDims(b.getContext(), d0, d1);
543   AffineExpr s0 = getAffineSymbolExpr(0, b.getContext());
544   lb = makeComposedAffineApply(b, loc, d0 + d1 * s0, {lb, procId, step});
545   step = makeComposedAffineApply(b, loc, d0 * s0, {nprocs, step});
546 }
547 
548 /// Generates a loop nest consisting of scf.parallel and scf.for, depending
549 /// on the `iteratorTypes.` Consecutive parallel loops create a single
550 /// scf.parallel operation; each sequential loop creates a new scf.for
551 /// operation. The body of the innermost loop is populated by
552 /// `bodyBuilderFn` that accepts a range of induction variables for all
553 /// loops. `ivStorage` is used to store the partial list of induction
554 /// variables.
555 // TODO: this function can be made iterative instead. However, it
556 // will have at most as many recursive calls as nested loops, which rarely
557 // exceeds 10.
558 static void generateParallelLoopNest(
559     OpBuilder &b, Location loc, ValueRange lbs, ValueRange ubs,
560     ValueRange steps, ArrayRef<Attribute> iteratorTypes,
561     function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn,
562     SmallVectorImpl<Value> &ivStorage,
563     ArrayRef<DistributionMethod> distributionMethod = {}) {
564   assert(lbs.size() == ubs.size());
565   assert(lbs.size() == steps.size());
566   assert(lbs.size() == iteratorTypes.size());
567 
568   // If there are no (more) loops to be generated, generate the body and be
569   // done with it.
570   if (iteratorTypes.empty()) {
571     bodyBuilderFn(b, loc, ivStorage);
572     return;
573   }
574 
575   // Find the outermost parallel loops and drop their types from the list.
576   unsigned nLoops = iteratorTypes.size();
577   unsigned nOuterPar =
578       nLoops - iteratorTypes.drop_while(isParallelIterator).size();
579 
580   // If there are no outer parallel loops, generate one sequential loop and
581   // recurse. Note that we wouldn't have dropped anything from `iteratorTypes`
582   // in this case.
583   if (nOuterPar == 0) {
584     LoopNest singleLoop = buildLoopNest(
585         b, loc, lbs.take_front(), ubs.take_front(), steps.take_front(),
586         [&](OpBuilder &b, Location loc, ValueRange ivs) {
587           ivStorage.append(ivs.begin(), ivs.end());
588           generateParallelLoopNest(b, loc, lbs.drop_front(), ubs.drop_front(),
589                                    steps.drop_front(),
590                                    iteratorTypes.drop_front(), bodyBuilderFn,
591                                    ivStorage, distributionMethod);
592         });
593     return;
594   }
595   if (distributionMethod.empty()) {
596     // Generate a single parallel loop-nest operation for all outermost
597     // parallel loops and recurse.
598     b.create<scf::ParallelOp>(
599         loc, lbs.take_front(nOuterPar), ubs.take_front(nOuterPar),
600         steps.take_front(nOuterPar),
601         [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange localIvs) {
602           ivStorage.append(localIvs.begin(), localIvs.end());
603           generateParallelLoopNest(
604               nestedBuilder, nestedLoc, lbs.drop_front(nOuterPar),
605               ubs.drop_front(nOuterPar), steps.drop_front(nOuterPar),
606               iteratorTypes.drop_front(nOuterPar), bodyBuilderFn, ivStorage,
607               (distributionMethod.size() < nOuterPar)
608                   ? ArrayRef<DistributionMethod>()
609                   : distributionMethod.drop_front(nOuterPar));
610         });
611     return;
612   }
613 
614   // Process all consecutive similarly distributed loops simultaneously.
615   DistributionMethod methodToUse = distributionMethod[0];
616   unsigned numProcessed = 1;
617   for (unsigned i = 1; i < nOuterPar && i < distributionMethod.size(); ++i) {
618     if (distributionMethod[i] != methodToUse)
619       break;
620     numProcessed++;
621   }
622 
623   switch (methodToUse) {
624   case DistributionMethod::Cyclic: {
625     // Generate a single parallel loop-nest operation for all outermost
626     // parallel loops and recurse.
627     b.create<scf::ParallelOp>(
628         loc, lbs.take_front(numProcessed), ubs.take_front(numProcessed),
629         steps.take_front(numProcessed),
630         [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange localIvs) {
631           ivStorage.append(localIvs.begin(), localIvs.end());
632           generateParallelLoopNest(
633               nestedBuilder, nestedLoc, lbs.drop_front(numProcessed),
634               ubs.drop_front(numProcessed), steps.drop_front(numProcessed),
635               iteratorTypes.drop_front(numProcessed), bodyBuilderFn, ivStorage,
636               (distributionMethod.size() < numProcessed)
637                   ? ArrayRef<DistributionMethod>()
638                   : distributionMethod.drop_front(numProcessed));
639         });
640     return;
641   }
642   case DistributionMethod::CyclicNumProcsGeNumIters: {
643     // Check (for the processed loops) that the iteration is in-bounds.
644     ArithBuilder ab(b, loc);
645     Value cond = ab.slt(lbs[0], ubs[0]);
646     for (unsigned i = 1; i < numProcessed; ++i)
647       cond = ab._and(cond, ab.slt(lbs[i], ubs[i]));
648     ivStorage.append(lbs.begin(), std::next(lbs.begin(), numProcessed));
649     b.create<scf::IfOp>(loc, cond, [&](OpBuilder &b, Location loc) {
650       generateParallelLoopNest(
651           b, loc, lbs.drop_front(numProcessed), ubs.drop_front(numProcessed),
652           steps.drop_front(numProcessed),
653           iteratorTypes.drop_front(numProcessed), bodyBuilderFn, ivStorage,
654           distributionMethod.drop_front(numProcessed));
655       b.create<scf::YieldOp>(loc, ValueRange{});
656     });
657     return;
658   }
659   case DistributionMethod::CyclicNumProcsEqNumIters:
660     // No check/loops needed here. Set the `%iv` to be the `%lb` and proceed
661     // with inner loop generation.
662     ivStorage.append(lbs.begin(), std::next(lbs.begin(), numProcessed));
663     generateParallelLoopNest(
664         b, loc, lbs.drop_front(numProcessed), ubs.drop_front(numProcessed),
665         steps.drop_front(numProcessed), iteratorTypes.drop_front(numProcessed),
666         bodyBuilderFn, ivStorage, distributionMethod.drop_front(numProcessed));
667     return;
668   }
669 }
670 
671 /// Specialization for generating a mix of parallel and sequential scf loops.
672 template <>
673 void GenerateLoopNest<scf::ParallelOp>::doit(
674     OpBuilder &b, Location loc, ArrayRef<Range> loopRanges, LinalgOp linalgOp,
675     ArrayRef<Attribute> iteratorTypes,
676     function_ref<scf::ValueVector(OpBuilder &, Location, ValueRange,
677                                   ValueRange)>
678         bodyBuilderFn,
679     Optional<LinalgLoopDistributionOptions> distributionOptions,
680     ArrayRef<StringRef> distributionTypes) {
681   SmallVector<Value> iterArgInitValues = linalgOp.getOutputTensorOperands();
682   assert(iterArgInitValues.empty() && "unexpected ParallelOp init values");
683   // This function may be passed more iterator types than ranges.
684   assert(iteratorTypes.size() >= loopRanges.size() &&
685          "expected iterator type for all ranges");
686   iteratorTypes = iteratorTypes.take_front(loopRanges.size());
687   SmallVector<Value, 8> lbsStorage, ubsStorage, stepsStorage, ivs;
688   unsigned numLoops = iteratorTypes.size();
689   ivs.reserve(numLoops);
690   lbsStorage.reserve(numLoops);
691   ubsStorage.reserve(numLoops);
692   stepsStorage.reserve(numLoops);
693 
694   // Get the loop lb, ub, and step.
695   unpackRanges(loopRanges, lbsStorage, ubsStorage, stepsStorage);
696 
697   // Modify the lb, ub, and step based on the distribution options.
698   SmallVector<DistributionMethod, 0> distributionMethod;
699   if (distributionOptions) {
700     auto &options = distributionOptions.getValue();
701     distributionMethod.assign(distributionOptions->distributionMethod.begin(),
702                               distributionOptions->distributionMethod.end());
703     SmallVector<Range, 2> parallelLoopRanges;
704     for (const auto &iteratorType : enumerate(iteratorTypes)) {
705       if (isParallelIterator(iteratorType.value()))
706         parallelLoopRanges.push_back(loopRanges[iteratorType.index()]);
707     }
708     if (distributionMethod.size() < parallelLoopRanges.size())
709       parallelLoopRanges.resize(distributionMethod.size());
710     SmallVector<ProcInfo, 2> procInfo =
711         options.procInfo(b, loc, parallelLoopRanges);
712     unsigned index = 0;
713     for (const auto &iteratorType : enumerate(iteratorTypes)) {
714       if (index >= procInfo.size())
715         break;
716       if (isParallelIterator(iteratorType.value())) {
717         unsigned i = iteratorType.index();
718         updateBoundsForCyclicDistribution(b, loc, procInfo[index].procId,
719                                           procInfo[index].nprocs, lbsStorage[i],
720                                           ubsStorage[i], stepsStorage[i]);
721         index++;
722       }
723     }
724   }
725   ValueRange lbs(lbsStorage), ubs(ubsStorage), steps(stepsStorage);
726   generateParallelLoopNest(
727       b, loc, lbs, ubs, steps, iteratorTypes,
728       [&](OpBuilder &b, Location loc, ValueRange ivs) {
729         SmallVector<Value> operandValuesToUse =
730             linalgOp.getInputAndOutputOperands();
731         bodyBuilderFn(b, loc, ivs, operandValuesToUse);
732       },
733       ivs, distributionMethod);
734 
735   assert(ivs.size() == iteratorTypes.size() && "did not generate enough loops");
736 }
737 
738 static Value fullyComposeAndAffineApply(OpBuilder &b, Location loc,
739                                         AffineExpr expr, ValueRange operands) {
740   AffineMap map = AffineMap::inferFromExprList({expr}).front();
741   SmallVector<Value> normalizedOperands(operands.begin(), operands.end());
742   mlir::fullyComposeAffineMapAndOperands(&map, &normalizedOperands);
743   canonicalizeMapAndOperands(&map, &normalizedOperands);
744   return b.createOrFold<AffineApplyOp>(loc, map, normalizedOperands);
745 }
746 
747 Value makeTiledShape(OpBuilder &builder, Location loc, Value valueToTile,
748                      ValueRange tileSizes, AffineMap map, ValueRange lbs,
749                      ValueRange ubs, ValueRange subShapeSizes,
750                      bool omitPartialTileCheck) {
751   auto shapedType = valueToTile.getType().dyn_cast<ShapedType>();
752   assert(shapedType && "only shaped types can be tiled");
753   ArrayRef<int64_t> shape = shapedType.getShape();
754   int64_t rank = shapedType.getRank();
755 
756   // Construct a new subview / extract_slice for the tile.
757   SmallVector<OpFoldResult, 4> offsets, sizes, strides;
758   offsets.reserve(rank);
759   sizes.reserve(rank);
760   strides.reserve(rank);
761   for (unsigned r = 0; r < rank; ++r) {
762     LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: for dim#" << r);
763     if (!isTiled(map.getSubMap({r}), tileSizes)) {
764       offsets.push_back(builder.getIndexAttr(0));
765       Value dim = createOrFoldDimOp(builder, loc, valueToTile, r);
766       sizes.push_back(getAsOpFoldResult(dim));
767       strides.push_back(builder.getIndexAttr(1));
768       LLVM_DEBUG(llvm::dbgs() << ": not tiled: use size: " << dim << "\n");
769       continue;
770     }
771     LLVM_DEBUG(llvm::dbgs() << ": tiled: figure out subsize...\n");
772 
773     // Tiling creates a new slice at the proper index, the slice step is 1
774     // (i.e. the op does not subsample, stepping occurs in the loop).
775     auto m = map.getSubMap({r});
776     LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: submap: " << m << "\n");
777     auto offset = applyMapToValues(builder, loc, m, lbs).front();
778     offsets.push_back(getAsOpFoldResult(offset));
779     auto closedIntSize =
780         applyMapToValues(builder, loc, m, subShapeSizes).front();
781     // Resulting size needs to be made half open interval again.
782     AffineExpr s0 = getAffineSymbolExpr(0, builder.getContext());
783     Value size =
784         fullyComposeAndAffineApply(builder, loc, s0 + 1, closedIntSize);
785     LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: raw size: " << size << "\n");
786     LLVM_DEBUG(llvm::dbgs()
787                << "makeTiledShape: new offset: " << offset << "\n");
788     strides.push_back(builder.getIndexAttr(1));
789 
790     if (omitPartialTileCheck) {
791       // We statically know that the partial/boundary tile condition is
792       // unnecessary.
793       LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: new size: " << size << "\n");
794       sizes.push_back(getAsOpFoldResult(size));
795       continue;
796     }
797 
798     // The size of the subview / extract_slice should be trimmed to avoid
799     // out-of-bounds accesses, unless:
800     // a. We statically know the subshape size divides the shape size evenly.
801     // b. The subshape size is 1. According to the way the loops are set up,
802     //    tensors with "0" dimensions would never be constructed.
803     int64_t shapeSize = shape[r];
804     auto sizeCst = size.getDefiningOp<arith::ConstantIndexOp>();
805     auto hasTileSizeOne = sizeCst && sizeCst.value() == 1;
806     auto dividesEvenly = sizeCst && !ShapedType::isDynamic(shapeSize) &&
807                          ((shapeSize % sizeCst.value()) == 0);
808     if (!hasTileSizeOne && !dividesEvenly) {
809       LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: shapeSize=" << shapeSize
810                               << ", size: " << size
811                               << ": make sure in bound with affine.min\n");
812 
813       AffineExpr dim0, dim1, dim2;
814       bindDims(builder.getContext(), dim0, dim1, dim2);
815 
816       // Get the dimension size for this dimension. We need to first calculate
817       // the max index and then plus one. This is important because for
818       // convolution ops, we have its input window dimension's affine map of the
819       // form `(d0 * s0 + d1)`, where `d0`/`d1 is an output/filter window
820       // dimension and `s0` is stride. Directly use the dimension size of
821       // output/filer window dimensions will cause incorrect calculation.
822       AffineMap minusOneMap =
823           AffineMap::inferFromExprList({ArrayRef<AffineExpr>{dim0 - 1}})
824               .front();
825       AffineMap plusOneMap =
826           AffineMap::inferFromExprList({ArrayRef<AffineExpr>{dim0 + 1}})
827               .front();
828       auto maxIndices = llvm::to_vector<8>(llvm::map_range(ubs, [&](Value ub) {
829         return makeComposedAffineApply(builder, loc, minusOneMap, {ub})
830             .getResult();
831       }));
832       Value maxIndex = applyMapToValues(builder, loc, m, maxIndices).front();
833       Value d = makeComposedAffineApply(builder, loc, plusOneMap, {maxIndex});
834 
835       // Compute min(dim - offset, size) to avoid out-of-bounds accesses.
836       AffineMap minMap = AffineMap::inferFromExprList(
837                              {ArrayRef<AffineExpr>{dim1 - dim2, dim0}})
838                              .front();
839       SmallVector<Value, 4> operands{size, d, offset};
840       fullyComposeAffineMapAndOperands(&minMap, &operands);
841       canonicalizeMapAndOperands(&minMap, &operands);
842       size = builder.create<AffineMinOp>(loc, builder.getIndexType(), minMap,
843                                          operands);
844     }
845     LLVM_DEBUG(llvm::dbgs() << "makeTiledShape: new size: " << size << "\n");
846     sizes.push_back(getAsOpFoldResult(size));
847   }
848 
849   auto *sliceOp = TypeSwitch<ShapedType, Operation *>(shapedType)
850                       .Case([&](MemRefType) {
851                         return builder.create<memref::SubViewOp>(
852                             loc, valueToTile, offsets, sizes, strides);
853                       })
854                       .Case([&](RankedTensorType) {
855                         return makeComposedExtractSliceOp(
856                             builder, loc, valueToTile, offsets, sizes, strides);
857                       })
858                       .Default([](ShapedType) -> Operation * {
859                         llvm_unreachable("Unexpected shaped type");
860                       });
861   return sliceOp->getResult(0);
862 }
863 
864 SmallVector<Value> computeTileOffsets(OpBuilder &b, Location loc,
865                                       ValueRange ivs, ValueRange tileSizes) {
866   SmallVector<Value> offsets;
867   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
868     LLVM_DEBUG(llvm::dbgs() << "makeTiledShapes: for loop#" << idx << "\n");
869     bool isTiled = !isZero(tileSizes[idx]);
870     offsets.push_back(
871         isTiled ? ivs[idxIvs++]
872                 : b.create<arith::ConstantIndexOp>(loc, 0).getResult());
873     LLVM_DEBUG(llvm::dbgs()
874                << "computeTileOffsets: " << offsets.back() << "\n");
875   }
876   return offsets;
877 }
878 
879 SmallVector<Value> computeTileSizes(OpBuilder &b, Location loc, ValueRange ivs,
880                                     ValueRange tileSizes,
881                                     ArrayRef<Value> sizeBounds) {
882   SmallVector<Value> sizes;
883   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx) {
884     bool isTiled = !isZero(tileSizes[idx]);
885     // Before composing, we need to make range a closed interval.
886     Value size = isTiled ? tileSizes[idx] : sizeBounds[idx];
887     AffineExpr d0 = getAffineDimExpr(0, b.getContext());
888     sizes.push_back(fullyComposeAndAffineApply(b, loc, d0 - 1, size));
889     LLVM_DEBUG(llvm::dbgs() << "computeTileSizes: " << sizes.back() << "\n");
890   }
891   return sizes;
892 }
893 
894 SmallVector<Value, 4> makeTiledShapes(OpBuilder &b, Location loc,
895                                       LinalgOp linalgOp,
896                                       ArrayRef<Value> valuesToTile,
897                                       ValueRange ivs, ValueRange tileSizes,
898                                       ArrayRef<Value> sizeBounds,
899                                       bool omitPartialTileCheck) {
900   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
901                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
902                            [](Value v) { return !isZero(v); })) &&
903          "expected as many ivs as non-zero sizes");
904 
905   // Construct (potentially temporary) mins and maxes on which to apply maps
906   // that define tile subshapes.
907   SmallVector<Value> lbs = computeTileOffsets(b, loc, ivs, tileSizes);
908   SmallVector<Value> subShapeSizes =
909       computeTileSizes(b, loc, ivs, tileSizes, sizeBounds);
910 
911   assert(static_cast<int64_t>(valuesToTile.size()) ==
912              linalgOp.getNumInputsAndOutputs() &&
913          "expected one value to tile for every operand");
914   SmallVector<Value, 4> tiledShapes;
915   tiledShapes.reserve(valuesToTile.size());
916   for (OpOperand *opOperand : linalgOp.getInputAndOutputOperands()) {
917     Value shapedOp = valuesToTile[opOperand->getOperandNumber()];
918     LLVM_DEBUG(llvm::dbgs() << "makeTiledShapes: for operand " << shapedOp);
919     AffineMap map = linalgOp.getTiedIndexingMap(opOperand);
920     // Use `opOperand` as is if it is not tiled and not an output tensor. Having
921     // an extract/insert slice pair for all output tensors simplifies follow up
922     // transformations such as padding and bufferization since the
923     // extract/insert slice pairs make the accessed iteration argument
924     // subdomains explicit.
925     if (!isTiled(map, tileSizes) && !linalgOp.isOutputTensor(opOperand)) {
926       tiledShapes.push_back(shapedOp);
927       LLVM_DEBUG(llvm::dbgs() << ": not tiled: use shape: "
928                               << opOperand->get().getType() << "\n");
929       continue;
930     }
931     LLVM_DEBUG(llvm::dbgs() << ": tiled: figure out subshape...\n");
932 
933     tiledShapes.push_back(makeTiledShape(b, loc, shapedOp, tileSizes, map, lbs,
934                                          sizeBounds, subShapeSizes,
935                                          omitPartialTileCheck));
936   }
937 
938   return tiledShapes;
939 }
940 
941 void addTileLoopIvsToIndexOpResults(OpBuilder &b, LinalgOp tiledOp,
942                                     ArrayRef<Value> ivs) {
943   if (tiledOp.hasIndexSemantics()) {
944     for (IndexOp indexOp : tiledOp.getBlock()->getOps<IndexOp>()) {
945       if (ivs[indexOp.dim()] == nullptr)
946         continue;
947       OpBuilder::InsertionGuard guard(b);
948       b.setInsertionPointAfter(indexOp);
949       AffineExpr index, offset;
950       bindDims(b.getContext(), index, offset);
951       AffineApplyOp applyOp = makeComposedAffineApply(
952           b, indexOp.getLoc(), index + offset,
953           ValueRange{indexOp.getResult(), ivs[indexOp.dim()]});
954       indexOp.getResult().replaceAllUsesExcept(applyOp, applyOp);
955     }
956   }
957 }
958 
959 } // namespace linalg
960 } // namespace mlir
961