1 //===- ShapeToShapeLowering.cpp - Prepare for lowering to Standard --------===//
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/Shape/IR/Shape.h"
11 #include "mlir/Dialect/Shape/Transforms/Passes.h"
12 #include "mlir/IR/Builders.h"
13 #include "mlir/IR/PatternMatch.h"
14 #include "mlir/Pass/Pass.h"
15 #include "mlir/Transforms/DialectConversion.h"
16 
17 using namespace mlir;
18 using namespace mlir::shape;
19 
20 namespace {
21 /// Converts `shape.num_elements` to `shape.reduce`.
22 struct NumElementsOpConverter : public OpRewritePattern<NumElementsOp> {
23 public:
24   using OpRewritePattern::OpRewritePattern;
25 
26   LogicalResult matchAndRewrite(NumElementsOp op,
27                                 PatternRewriter &rewriter) const final;
28 };
29 } // namespace
30 
31 LogicalResult
32 NumElementsOpConverter::matchAndRewrite(NumElementsOp op,
33                                         PatternRewriter &rewriter) const {
34   auto loc = op.getLoc();
35   Value init = rewriter.create<ConstSizeOp>(loc, rewriter.getIndexAttr(1));
36   ReduceOp reduce = rewriter.create<ReduceOp>(loc, op.shape(), init);
37 
38   // Generate reduce operator.
39   Block *body = reduce.getBody();
40   OpBuilder b = OpBuilder::atBlockEnd(body);
41   Value product =
42       b.create<MulOp>(loc, body->getArgument(1), body->getArgument(2));
43   b.create<YieldOp>(loc, product);
44 
45   rewriter.replaceOp(op, reduce.result());
46   return success();
47 }
48 
49 namespace {
50 struct ShapeToShapeLowering
51     : public ShapeToShapeLoweringBase<ShapeToShapeLowering> {
52   void runOnFunction() override;
53 };
54 } // namespace
55 
56 void ShapeToShapeLowering::runOnFunction() {
57   MLIRContext &ctx = getContext();
58 
59   OwningRewritePatternList patterns;
60   populateShapeRewritePatterns(&ctx, patterns);
61 
62   ConversionTarget target(getContext());
63   target.addLegalDialect<ShapeDialect>();
64   target.addIllegalOp<NumElementsOp>();
65   if (failed(mlir::applyPartialConversion(getFunction(), target, patterns)))
66     signalPassFailure();
67 }
68 
69 void mlir::populateShapeRewritePatterns(MLIRContext *context,
70                                         OwningRewritePatternList &patterns) {
71   patterns.insert<NumElementsOpConverter>(context);
72 }
73 
74 std::unique_ptr<Pass> mlir::createShapeToShapeLowering() {
75   return std::make_unique<ShapeToShapeLowering>();
76 }
77