| 1 | //===- ConcatOpPatterns.cpp - Patterns related to tensor.concat lowering --===// |
| 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/Affine/IR/AffineOps.h" |
| 10 | #include "mlir/Dialect/Arith/IR/Arith.h" |
| 11 | #include "mlir/Dialect/Arith/Utils/Utils.h" |
| 12 | #include "mlir/Dialect/Tensor/IR/Tensor.h" |
| 13 | #include "mlir/Dialect/Tensor/Transforms/Transforms.h" |
| 14 | #include "mlir/IR/PatternMatch.h" |
| 15 | |
| 16 | using namespace mlir; |
| 17 | using namespace mlir::tensor; |
| 18 | |
| 19 | namespace { |
| 20 | |
| 21 | /// Decompose `tensor.concat` into `tensor.empty` and a chain of slice inserts. |
| 22 | /// |
| 23 | /// %concat = tensor.concat dim(1) %0, %1 : |
| 24 | /// (tensor<2x3xf32>, tensor<2x4xf32>) -> tensor<2x7xf32> |
| 25 | /// |
| 26 | /// Becomes |
| 27 | /// |
| 28 | /// %empty = tensor.empty() : tensor<2x7xf32> |
| 29 | /// %insert0 = tensor.insert_slice %0 into %empty[0, 0][2, 3][1, 1] |
| 30 | /// %concat = tensor.insert_slice %1 into %insert0[0, 3][2, 4][1, 1] |
| 31 | struct DecomposeTensorConcatOp : public OpRewritePattern<ConcatOp> { |
| 32 | using OpRewritePattern<ConcatOp>::OpRewritePattern; |
| 33 | |
| 34 | LogicalResult matchAndRewrite(ConcatOp concatOp, |
| 35 | PatternRewriter &rewriter) const override { |
| 36 | FailureOr<SmallVector<Value>> decomposed = |
| 37 | concatOp.decomposeOperation(rewriter); |
| 38 | if (failed(Result: decomposed)) { |
| 39 | return rewriter.notifyMatchFailure( |
| 40 | concatOp, "failed to get the decomposed insert slices" ); |
| 41 | } |
| 42 | rewriter.replaceOp(concatOp, decomposed.value()[0]); |
| 43 | return success(); |
| 44 | } |
| 45 | }; |
| 46 | |
| 47 | } // namespace |
| 48 | |
| 49 | void mlir::tensor::populateDecomposeTensorConcatPatterns( |
| 50 | RewritePatternSet &patterns) { |
| 51 | patterns.add<DecomposeTensorConcatOp>(arg: patterns.getContext()); |
| 52 | } |
| 53 | |