1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 // This file contains the patterns to convert std.index_cast on tensors to
17 // tensor ops and index_cast on scalars.
18 
19 #include <utility>
20 
21 #include "mlir/Dialect/StandardOps/IR/Ops.h"  // from @llvm-project
22 #include "mlir/Dialect/Tensor/IR/Tensor.h"  // from @llvm-project
23 #include "mlir/IR/PatternMatch.h"  // from @llvm-project
24 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"  // from @llvm-project
25 #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h"
26 
27 namespace mlir {
28 namespace kernel_gen {
29 namespace transforms {
30 namespace {
31 
32 // index_cast is not defined on tensors, so lower it to a tensor.generate.
33 struct IndexCastConverter : public OpRewritePattern<IndexCastOp> {
34  public:
35   using OpRewritePattern::OpRewritePattern;
matchAndRewritemlir::kernel_gen::transforms::__anonb703bef30111::IndexCastConverter36   LogicalResult matchAndRewrite(IndexCastOp op,
37                                 PatternRewriter &rewriter) const final {
38     // Only rank 1 is supported for now.
39     auto result_ty = op.getType().dyn_cast<ShapedType>();
40     if (!result_ty || result_ty.getRank() != 1) return failure();
41 
42     rewriter.replaceOpWithNewOp<tensor::GenerateOp>(
43         op, op.getType(),
44         result_ty.hasStaticShape() ? ValueRange{}
45                                    : ValueRange{rewriter.create<tensor::DimOp>(
46                                          op.getLoc(), op.in(), 0)},
47         [&](OpBuilder &b, Location loc, ValueRange args) {
48           Value dim = args.front();
49           Value extent = b.create<tensor::ExtractOp>(loc, op.in(), dim);
50           Value casted =
51               b.create<IndexCastOp>(loc, extent, result_ty.getElementType());
52           b.create<tensor::YieldOp>(loc, casted);
53         });
54     return success();
55   }
56 };
57 
58 #define GEN_PASS_CLASSES
59 #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc"
60 
61 struct LowerIndexCastPass : public LowerIndexCastPassBase<LowerIndexCastPass> {
getDependentDialectsmlir::kernel_gen::transforms::__anonb703bef30111::LowerIndexCastPass62   void getDependentDialects(DialectRegistry &registry) const override {
63     registry.insert<tensor::TensorDialect>();
64   }
65 
runOnFunctionmlir::kernel_gen::transforms::__anonb703bef30111::LowerIndexCastPass66   void runOnFunction() override {
67     RewritePatternSet patterns(&getContext());
68     patterns.add<IndexCastConverter>(patterns.getContext());
69     if (failed(
70             applyPatternsAndFoldGreedily(getFunction(), std::move(patterns))))
71       return signalPassFailure();
72   }
73 };
74 
75 }  // namespace
76 
CreateLowerIndexCastPass()77 std::unique_ptr<FunctionPass> CreateLowerIndexCastPass() {
78   return std::make_unique<LowerIndexCastPass>();
79 }
80 
81 }  // namespace transforms
82 }  // namespace kernel_gen
83 }  // namespace mlir
84