1 //===- LinalgInterfaces.cpp - Linalg interfaces implementation ------------===//
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 "mlir/Dialect/Linalg/IR/LinalgInterfaces.h"
10 
11 #include "mlir/Dialect/Affine/IR/AffineOps.h"
12 #include "mlir/Dialect/MemRef/IR/MemRef.h"
13 #include "mlir/IR/AffineExprVisitor.h"
14 #include "mlir/IR/AffineMap.h"
15 #include "llvm/ADT/SmallSet.h"
16 
17 using namespace mlir;
18 using namespace mlir::linalg;
19 
20 /// Include the definitions of the copy operation interface.
21 #include "mlir/Dialect/Linalg/IR/LinalgInterfaces.cpp.inc"
22 
23 //===----------------------------------------------------------------------===//
24 // ContractionOpInterface implementation
25 //===----------------------------------------------------------------------===//
26 
27 /// Return true if the use-def chain from `v` to `from` consists of 0 or more
28 /// unary single-operand operations.
29 // TODO: relax to multi-operands with constants, which are technically unary ops
30 // as needed (e.g. add5).
31 static bool isChainOfUnaryOpsFrom(Value v, Value from) {
32   while (true) {
33     if (v == from)
34       return true;
35     Operation *op = v.getDefiningOp();
36     if (!op || op->getNumOperands() != 1)
37       return false;
38     v = op->getOperand(0);
39   };
40 }
41 
42 /// Return the unique instance of OpType in `block` if it is indeed unique.
43 /// Return null if none or more than 1 instances exist.
44 template <typename OpType>
45 static OpType getSingleOpOfType(Block &block) {
46   OpType res = nullptr;
47   block.walk([&](OpType op) {
48     if (res) {
49       res = nullptr;
50       return WalkResult::interrupt();
51     }
52     res = op;
53     return WalkResult::advance();
54   });
55   return res;
56 }
57 
58 /// Detect whether res is any permutation of `u5(u1(c) + u2(u3(a) * u4(b)))`
59 /// on the field (AddOpType, MulOpType), where u1, u2, u3, u4 and u5 represent
60 /// unary operations that may change the type.
61 template <typename AddOpType, typename MulOpType>
62 static bool isAddMul(Block &block) {
63   if (block.getNumArguments() != 3)
64     return false;
65   Operation *yieldOp = block.getTerminator();
66   if (yieldOp->getNumOperands() != 1)
67     return false;
68 
69   AddOpType addOp = getSingleOpOfType<AddOpType>(block);
70   MulOpType mulOp = getSingleOpOfType<MulOpType>(block);
71   if (!addOp || !mulOp)
72     return false;
73 
74   Value argA = block.getArgument(0), argB = block.getArgument(1);
75   Value a = mulOp->getOperand(0), b = mulOp->getOperand(1);
76   Value mul = mulOp->getResult(0);
77   Value argC = block.getArgument(2);
78   Value c1 = addOp->getOperand(0), c2 = addOp->getOperand(1);
79   Value add = addOp->getResult(0);
80   Value res = yieldOp->getOperand(0);
81   // Result traces back to add.
82   auto un = isChainOfUnaryOpsFrom;
83   bool success = un(res, add);
84   // One of the operands of add traces back to argC, the other to the mul.
85   success |= (un(c1, argC) && un(c2, mul)) || ((un(c1, mul)) && un(c2, argC));
86   // One of the operands of mul traces back to argA, the other to argB.
87   success |= (un(a, argA) && un(b, argB)) || ((un(a, argB)) && un(b, argA));
88   return success;
89 }
90 
91 enum MatchContractionResult {
92   Success = 0,
93   NotLinalgOp,
94   WrongNumOperands,
95   NoReduction,
96   NotProjectedPermutations,
97   NotAddMul
98 };
99 static MatchContractionResult isContractionInterfaceImpl(Operation *op) {
100   auto linalgOp = dyn_cast<linalg::LinalgOp>(op);
101   if (!linalgOp)
102     return MatchContractionResult::NotLinalgOp;
103   if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1)
104     return MatchContractionResult::WrongNumOperands;
105   auto mapRange = linalgOp.indexing_maps().getAsValueRange<AffineMapAttr>();
106   if (linalgOp.getNumReductionLoops() == 0)
107     return MatchContractionResult::NoReduction;
108   if (llvm::any_of(mapRange,
109                    [](AffineMap m) { return !m.isProjectedPermutation(); }))
110     return MatchContractionResult::NotProjectedPermutations;
111   // TODO: more fields than add/mul.
112   if (!isAddMul<AddFOp, MulFOp>(linalgOp->getRegion(0).front()) &&
113       !isAddMul<AddIOp, MulIOp>(linalgOp->getRegion(0).front()))
114     return MatchContractionResult::NotAddMul;
115   return MatchContractionResult::Success;
116 }
117 
118 bool mlir::linalg::isaContractionOpInterface(LinalgOp linalgOp) {
119   if (!linalgOp)
120     return false;
121   Operation *op = linalgOp.getOperation();
122   return isa<ContractionOpInterface>(op) ||
123          (isContractionInterfaceImpl(op) == MatchContractionResult::Success);
124 }
125 
126 /// Verify that a LinalgOp `op` is a contraction.
127 /// A Linalg contraction is defined in general terms:
128 ///   1. Has 2 input and 1 output shapes.
129 ///   2. Has at least one reduction dimension.
130 ///   3. Has only projected permutation indexing maps.
131 ///   4. its body computes `u5(u1(c) + u2(u3(a) * u4(b)))` on some field
132 ///   (AddOpType, MulOpType), where u1, u2, u3, u4 and u5 represent scalar unary
133 ///   operations that may change the type (e.g. for mixed-precision).
134 /// As a consequence, when vectorization of such an op occurs, the only special
135 /// behavior is that the (unique) MulOpType is vectorized into a
136 /// `vector.contract`. All other ops are handled in a generic fashion.
137 /// In the future, we may wish to allow more input arguments and elementwise and
138 /// constant operations that do not involve the reduction dimension(s).
139 LogicalResult mlir::linalg::detail::verifyContractionInterface(Operation *op) {
140   auto res = isContractionInterfaceImpl(op);
141   if (res == MatchContractionResult::NotLinalgOp)
142     return op->emitError("expected a LinalgOp");
143   if (res == MatchContractionResult::WrongNumOperands)
144     return op->emitError("expected op with 2 inputs and 1 outputs");
145   if (res == MatchContractionResult::NoReduction)
146     return op->emitError("expected at least a reduction loop");
147   if (res == MatchContractionResult::NotProjectedPermutations)
148     return op->emitError("expected all indexings to be projected permutations");
149   if (res == MatchContractionResult::NotAddMul)
150     return op->emitError("(add, mul) operations not found");
151   return success();
152 }
153 
154 //===----------------------------------------------------------------------===//
155 // StructuredOpInterface implementation
156 //===----------------------------------------------------------------------===//
157 
158 /// Fully compose map with operands and canonicalize the result.
159 /// Return the `createOrFold`'ed AffineApply op.
160 static Value createFoldedComposedAffineApply(OpBuilder &b, Location loc,
161                                              AffineMap map,
162                                              ValueRange operandsRef) {
163   SmallVector<Value, 4> operands(operandsRef.begin(), operandsRef.end());
164   fullyComposeAffineMapAndOperands(&map, &operands);
165   canonicalizeMapAndOperands(&map, &operands);
166   return b.createOrFold<AffineApplyOp>(loc, map, operands);
167 }
168 
169 SmallVector<Value, 4> mlir::linalg::applyMapToValues(OpBuilder &b, Location loc,
170                                                      AffineMap map,
171                                                      ValueRange values) {
172   SmallVector<Value, 4> res;
173   res.reserve(map.getNumResults());
174   unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols();
175   // For each `expr` in `map`, applies the `expr` to the values extracted from
176   // ranges. If the resulting application can be folded into a Value, the
177   // folding occurs eagerly.
178   for (auto expr : map.getResults()) {
179     AffineMap map = AffineMap::get(numDims, numSym, expr);
180     res.push_back(createFoldedComposedAffineApply(b, loc, map, values));
181   }
182   return res;
183 }
184 
185 SmallVector<Value, 4> LinalgOp::createFlatListOfOperandDims(OpBuilder &b,
186                                                             Location loc) {
187   SmallVector<Value, 4> res;
188   for (Value v : getShapedOperands()) {
189     ShapedType t = v.getType().template cast<ShapedType>();
190     for (unsigned i = 0, e = t.getRank(); i < e; ++i)
191       res.push_back(b.createOrFold<memref::DimOp>(loc, v, i));
192   }
193   return res;
194 }
195 
196 SmallVector<Range, 4> LinalgOp::createLoopRanges(OpBuilder &b, Location loc) {
197   AffineMap map = getLoopsToShapesMap();
198   unsigned numDims = map.getNumDims(), numRes = map.getNumResults();
199   auto viewSizes = createFlatListOfOperandDims(b, loc);
200   SmallVector<Range, 4> res(numDims);
201   Value zeroVal = b.create<ConstantIndexOp>(loc, 0);
202   Value oneVal = b.create<ConstantIndexOp>(loc, 1);
203   for (unsigned idx = 0; idx < numRes; ++idx) {
204     auto result = map.getResult(idx);
205     if (auto d = result.dyn_cast<AffineDimExpr>()) {
206       if (res[d.getPosition()].offset)
207         continue;
208       res[d.getPosition()] = Range{zeroVal, viewSizes[idx], oneVal};
209     }
210   }
211   return res;
212 }
213 
214 /// Visitor to check if any of the given set of positions from AffineDimExprs
215 /// are used within an AffineExpr.
216 struct HasAffineDimExprVisitor
217     : public AffineExprVisitor<HasAffineDimExprVisitor, bool> {
218   HasAffineDimExprVisitor(llvm::SmallSet<unsigned, 4> &positions)
219       : positions(positions) {}
220 
221   bool visitAffineBinaryOpExpr(AffineBinaryOpExpr binaryOpExpr) {
222     return visit(binaryOpExpr.getLHS()) || visit(binaryOpExpr.getRHS());
223   }
224 
225   bool visitDimExpr(AffineDimExpr dimExpr) {
226     return positions.count(dimExpr.getPosition());
227   }
228 
229   bool visitConstantExpr(AffineConstantExpr constExpr) { return false; }
230 
231   bool visitSymbolExpr(AffineSymbolExpr symbolExpr) { return false; }
232 
233 private:
234   llvm::SmallSet<unsigned, 4> positions;
235 };
236 
237 LogicalResult LinalgOp::reifyReturnTypeShapesPerResultDim(
238     OpBuilder &b, SmallVectorImpl<SmallVector<Value>> &reifiedReturnShapes) {
239   // An example that helps understand the logic below.
240   // Consider the following expression O(i+j, j) += A(i,k) * B(k, j)
241   // We want to express the shape of dim 0 of O in terms of shape of the inputs.
242   // This is achieved as follows.
243   //   loopsToShapesMap = (d0, d1, d2) -> (d0, d2, d2, d1, d0 + d1, d1)
244   //   subMapOfResultShapes = (d0, d1, d2) -> (d0 + d1, d1)
245   //   shapesToLoopsMap = (d0, d2, d2, d3, d4, d5) -> (d0, d3, d2)
246   //   resultShapesFromInputShapes = subMapOfResultDim.compose(shapesToLoopMap)
247   //     = (d0, d1, d2, d3, d4, d5) -> (d0 + d1, d1)
248   AffineMap loopsToShapesMap = getLoopsToShapesMap();
249 
250   // Find the position in the above map that represents the shape of the
251   // result:dim being inferred.
252   auto resultShapesSubMapPos = getResultsPositionInLoopsToShapeMap();
253 
254   /// From loopsToShapesMap extract the submap that represents the shape of the
255   /// (resultIdx, dim) needed.
256   SmallVector<unsigned, 4> resultPosRange =
257       llvm::to_vector<4>(llvm::seq<unsigned>(resultShapesSubMapPos.first,
258                                              resultShapesSubMapPos.second));
259   AffineMap loopToResultsShapeMap = loopsToShapesMap.getSubMap(resultPosRange);
260   AffineMap resultShapesFromInputShapesMap =
261       loopToResultsShapeMap.compose(getShapesToLoopsMap());
262 
263   // Check that the result dim map does not contain the positions corresponding
264   // to the outputs.
265   llvm::SmallSet<unsigned, 4> outputDims;
266   llvm::for_each(resultPosRange,
267                  [&outputDims](unsigned dim) { outputDims.insert(dim); });
268   HasAffineDimExprVisitor checkDimExpr(outputDims);
269   Location loc = getOperation()->getLoc();
270   auto allResultDimValues =
271       applyMapToValues(b, loc, resultShapesFromInputShapesMap,
272                        createFlatListOfOperandDims(b, loc));
273   unsigned pos = 0;
274   ArrayRef<AffineExpr> shapeExprs = resultShapesFromInputShapesMap.getResults();
275   for (auto resultIdx : llvm::seq<unsigned>(0, getNumOutputs())) {
276     ShapedType resultType = getOutputShapedType(resultIdx);
277     SmallVector<Value> shapes;
278     for (unsigned dim : llvm::seq<unsigned>(0, resultType.getRank())) {
279       if (checkDimExpr.visit(shapeExprs[pos]))
280         shapes.push_back(
281             b.createOrFold<memref::DimOp>(loc, getOutput(resultIdx), dim));
282       else
283         shapes.push_back(allResultDimValues[pos]);
284       pos++;
285     }
286     reifiedReturnShapes.emplace_back(std::move(shapes));
287   }
288   return success();
289 }
290 
291 LogicalResult mlir::linalg::detail::verifyStructuredOpInterface(Operation *op) {
292   LinalgOp linalgOp = cast<LinalgOp>(op);
293   // Expect at least one shaped operand.
294   // This means an op that constructs a tensor out of indices cannot be a
295   // LinalgOp at the moment. For now this will have to be a special op until we
296   // have output shape operands that are not tensors.
297   auto nShapedOperands = linalgOp.getNumShapedOperands();
298   if (nShapedOperands == 0)
299     return linalgOp.emitOpError("expected at least 1 Shaped operand");
300   if (failed(OpTrait::impl::verifyAtLeastNOperands(op, nShapedOperands)))
301     return failure();
302   // Should have at least one output tensor per result tensor.
303   // Can also have outbut buffers that do not correspond to results.
304   if (op->getNumResults() > linalgOp.getNumOutputTensors())
305     return op->emitError("unexpected #results > #outputs");
306 
307   // Before checking indexing maps, we need to make sure the attributes
308   // referenced by it are valid.
309   if (linalgOp.hasDynamicIndexingMaps())
310     if (failed(linalgOp.verifyIndexingMapRequiredAttributes()))
311       return failure();
312 
313   // All shaped operands must be indexed.
314   if (linalgOp.indexing_maps().size() != linalgOp.getNumShapedOperands())
315     return linalgOp.emitOpError("expected the number of indexing_map (")
316            << linalgOp.indexing_maps().size()
317            << ") to be equal to the number of shaped operands ("
318            << linalgOp.getNumShapedOperands() << ")";
319 
320   SmallVector<AffineMap, 4> indexingMaps;
321   indexingMaps.reserve(linalgOp.indexing_maps().size());
322   for (auto en : llvm::enumerate(linalgOp.indexing_maps())) {
323     auto idx = en.index();
324     auto m = en.value().template cast<AffineMapAttr>().getValue();
325     indexingMaps.push_back(m); // Save reference to map for further checks.
326     auto shapedValue = linalgOp.getShapedType(idx);
327 
328     // Symbols disallowed.
329     if (m.getNumSymbols() != 0)
330       return linalgOp.emitOpError("unexpected symbols in indexing_map #")
331              << idx;
332 
333     // Domain must be consistent.
334     auto nLoops = linalgOp.getNumLoops();
335     if (m.getNumDims() != nLoops)
336       return linalgOp.emitOpError("expected indexing_map #")
337              << idx << " to have " << nLoops
338              << " dim(s) to match the number of loops";
339 
340     if (m.getNumResults() != shapedValue.getRank())
341       return linalgOp.emitOpError("expected shaped value rank (")
342              << shapedValue.getRank()
343              << ") to match the result rank of indexing_map #" << idx << " ("
344              << m.getNumResults() << ")";
345   }
346 
347   SmallVector<AffineExpr, 4> redDims;
348   linalgOp.getReductionDims(redDims);
349 
350   // Simplifying assumption: either full tensor or full buffer mode.
351   // This allows simpler verification of output operands vs result types
352   // without premature tracking of which operand is what in mixed-mode.
353   // TODO: relax when mixed-mode needs to pass verification.
354   if (linalgOp.getNumOutputBuffers() > 0 && linalgOp.getNumOutputTensors() > 0)
355     return op->emitError("expected output operands to all have tensor type or "
356                          "all have buffer type");
357 
358   for (auto it :
359        llvm::zip(linalgOp.getOutputOpOperands(), op->getResultTypes())) {
360     if (!std::get<0>(it).get().getType().isa<RankedTensorType>())
361       continue;
362     if (std::get<0>(it).get().getType() != std::get<1>(it))
363       return op->emitError("expected type of operand #")
364              << std::get<0>(it).getOperandNumber() << " ("
365              << std::get<0>(it).get().getType() << ")"
366              << " to match type of corresponding result (" << std::get<1>(it)
367              << ")";
368   }
369 
370   // Output tensor indexing map may not depend on reduction indices.
371   for (OpOperand &opOperand : linalgOp.getOutputOpOperands()) {
372     AffineMap outputMap = linalgOp.getIndexingMap(opOperand.getOperandNumber());
373     for (auto expr : outputMap.getResults()) {
374       for (auto dim : redDims) {
375         unsigned pos = dim.cast<AffineDimExpr>().getPosition();
376         if (expr.isFunctionOfDim(pos)) {
377           std::string exprStr;
378           {
379             llvm::raw_string_ostream os(exprStr);
380             os << expr;
381           }
382           return op->emitError(
383                      "unexpected output tensor expression in indexing map #")
384                  << (opOperand.getOperandNumber() - linalgOp.getNumInputs())
385                  << " a.k.a '" << exprStr
386                  << "' is function of reduction iterator 'd" << pos << "'";
387         }
388       }
389     }
390   }
391 
392   // Named ops that are defined manually have a region builder but no region at
393   // this time. Assume the region is well-formed by specification.
394   // TODO: use linalg-ods-gen for all ops when we have enough expressive power.
395   if (linalgOp->getNumRegions() == 0) {
396     assert(!linalgOp.getRegionBuilder() && "regionBuilder but no region");
397     return success();
398   }
399 
400   auto &region = linalgOp->getRegion(0);
401   if (linalgOp->getNumRegions() > 1 || !llvm::hasSingleElement(region))
402     return op->emitOpError("expected 1 region with 1 block");
403 
404   if (!linalgOp.getShapesToLoopsMap())
405     return op->emitOpError("expected the shape-to-loops map to be non-null");
406 
407   // Simplifying assumption: bbargs match 1-1 with shape operands elemental
408   // types.
409   // TODO: once ranked shape types are plugged in, we may want to drop the
410   // corresponding bbargs, that can never be read from. This will be subject to
411   // consistency discussions (i.e. what to do with output tensors whose bbarg is
412   // not used).
413   Block &block = linalgOp->getRegion(0).front();
414   unsigned numBBIvs = linalgOp.getNumPayloadInductionVariables();
415 
416   if (linalgOp.getNumShapedOperands() + numBBIvs != block.getNumArguments())
417     return op->emitError("expected as many non-induction variable region "
418                          "arguments as the number of shaped operands");
419 
420   // Note: the number and type of yield values are checked in the YieldOp.
421   for (unsigned i = 0; i < numBBIvs; ++i)
422     if (!block.getArgument(i).getType().isIndex())
423       return op->emitOpError("expected index block argument #") << i;
424 
425   unsigned idx = 0;
426   for (auto it : llvm::zip(linalgOp.getShapedOperandTypes(),
427                            block.getArguments().drop_front(numBBIvs))) {
428     if (std::get<0>(it).getElementType() != std::get<1>(it).getType())
429       return op->emitError("expected type of bb argument #")
430              << (idx + numBBIvs) << " (" << std::get<1>(it).getType() << ")"
431              << " to match element type of corresponding shaped operand ("
432              << std::get<0>(it).getElementType() << ")";
433     ++idx;
434   }
435 
436   // Check if given shapes match to inferred shapes.
437   Optional<SmallVector<int64_t, 4>> loopRanges = linalgOp.getStaticLoopRanges();
438   if (!loopRanges)
439     return linalgOp.emitError("unable to find loop range for operation");
440 
441   // Verify only static cases since we can't get exact dimension sizes and loop
442   // ranges for dynamic cases in this stage.
443   if (llvm::none_of(*loopRanges, [](int64_t &range) {
444         return range == ShapedType::kDynamicSize;
445       })) {
446     for (int64_t &range : *loopRanges)
447       range -= 1;
448     for (const auto &en : llvm::enumerate(linalgOp.getShapedOperandTypes())) {
449       auto indices = indexingMaps[en.index()].compose(*loopRanges);
450       for (auto j : llvm::seq<unsigned>(0, en.value().getRank())) {
451 
452         // Ignore dynamic dimension or the case that the inferred last index is
453         // zero. The index is increasing or decreasing in Linalg, for example,
454         // the last index should be `0` or `size-1`. We only check the cases
455         // that are non-zero because most of cases are increasing and it is too
456         // expensive to find the shape of decreasing cases.
457         if (en.value().isDynamicDim(j) || indices[j] == 0)
458           continue;
459 
460         // The size of shaped operands and inferred dimension size should be
461         // same. But, for now we check if the inferred sizes are in boundary of
462         // shaped operands' size or not in case that Affine Expressions are
463         // complicated such as d0 * 3 + d1 since it is not easy to handle the
464         // issues.
465         auto inferredSize = indices[j] + 1;
466         auto shapedDimSize = en.value().getDimSize(j);
467         if (indexingMaps[en.index()].getResult(j).dyn_cast<AffineDimExpr>()) {
468           if (inferredSize != shapedDimSize) {
469             return linalgOp.emitOpError("inferred shaped operand #")
470                    << en.index() << " has shape's dimension #" << j << " to be "
471                    << inferredSize << ", but found " << shapedDimSize;
472           }
473         } else {
474           if (inferredSize > shapedDimSize) {
475             return linalgOp.emitOpError("inferred shaped operand #")
476                    << en.index() << " has shape's dimension #" << j
477                    << " to be greater than or equal to " << inferredSize
478                    << ", but found " << shapedDimSize;
479           }
480         }
481       }
482     }
483   }
484 
485   return success();
486 }
487