1 /* Copyright 2022 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 implements a set of sparse MHLO rewriting rules.
17 
18 #include <utility>
19 
20 #include "llvm/Support/Debug.h"
21 #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
22 #include "mlir-hlo/Dialect/mhlo/transforms/PassDetail.h"
23 #include "mlir-hlo/Dialect/mhlo/transforms/passes.h"
24 #include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h"
25 #include "mlir/Dialect/Func/IR/FuncOps.h"
26 #include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
27 #include "mlir/IR/Operation.h"
28 #include "mlir/Pass/Pass.h"
29 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
30 
31 namespace mlir {
32 namespace mhlo {
33 namespace {
34 
35 /// Approves subsuming sparse types into operation.
36 // TODO(b/231360416): replace this list with "supports sparsity" trait?
canFuseWithSparseConvert(Operation * op)37 static bool canFuseWithSparseConvert(Operation *op) {
38   return isa<sparse_tensor::ConvertOp>(op) || isa<AbsOp>(op) ||
39          isa<CeilOp>(op) || isa<ConvertOp>(op) || isa<CosineOp>(op) ||
40          isa<Expm1Op>(op) || isa<FloorOp>(op) || isa<ImagOp>(op) ||
41          isa<LogOp>(op) || isa<Log1pOp>(op) || isa<NegOp>(op) ||
42          isa<RealOp>(op) || isa<RoundOp>(op) || isa<SignOp>(op) ||
43          isa<SineOp>(op) || isa<SqrtOp>(op) || isa<TanhOp>(op) ||
44          isa<AddOp>(op) || isa<DivOp>(op) || isa<MulOp>(op) || isa<RemOp>(op) ||
45          isa<TransposeOp>(op) || isa<SubtractOp>(op);
46 }
47 
48 /// Fuses a sparse tensor type from a conversion into a mhlo operation
49 /// where possible, essentially rewriting something like:
50 ///    %0 = mhlo.sign %arg : tensor<100xf64>
51 ///    %1 = sparse_tensor.convert %0 : tensor<100xf64> to tensor<100xf64, #SV>
52 ///    ... = ... %1 ...
53 /// into:
54 ///    %0 = mhlo.sign %arg : (tensor<100xf64>) -> tensor<100xf64, #SV>
55 ///    ... = ... %0 ...
56 /// This eventually yields better sparse code, since the intermediate
57 /// results do not need to be explicitly generated.
58 struct SparseConvertConverter
59     : public OpRewritePattern<sparse_tensor::ConvertOp> {
SparseConvertConvertermlir::mhlo::__anonc542a1b20111::SparseConvertConverter60   explicit SparseConvertConverter(MLIRContext *context)
61       : OpRewritePattern(context) {}
matchAndRewritemlir::mhlo::__anonc542a1b20111::SparseConvertConverter62   LogicalResult matchAndRewrite(sparse_tensor::ConvertOp op,
63                                 PatternRewriter &rewriter) const override {
64     if (Operation *def = op.getSource().getDefiningOp()) {
65       if (def->hasOneUse() && canFuseWithSparseConvert(def)) {
66         def->getResult(0).setType(op->getResultTypes()[0]);
67         rewriter.replaceOp(op, def->getResult(0));
68         return success();
69       }
70     }
71     return failure();
72   }
73 };
74 
75 struct SparseRewritingPass
76     : public SparseRewritingPassBase<SparseRewritingPass> {
runOnOperationmlir::mhlo::__anonc542a1b20111::SparseRewritingPass77   void runOnOperation() override {
78     RewritePatternSet patterns(&getContext());
79     populateSparseRewritingPatterns(&patterns, &getContext());
80     if (failed(applyPatternsAndFoldGreedily(getOperation(),
81                                             std::move(patterns)))) {
82       return signalPassFailure();
83     }
84   }
85 };
86 
87 }  // namespace
88 
populateSparseRewritingPatterns(RewritePatternSet * patterns,MLIRContext * ctx)89 void populateSparseRewritingPatterns(RewritePatternSet *patterns,
90                                      MLIRContext *ctx) {
91   patterns->add<SparseConvertConverter>(ctx);
92 }
93 
createSparseRewritingPass()94 std::unique_ptr<OperationPass<func::FuncOp>> createSparseRewritingPass() {
95   return std::make_unique<SparseRewritingPass>();
96 }
97 
98 }  // namespace mhlo
99 }  // namespace mlir
100