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 implements logic for some optimizations to reduce size on export. 17 18 #include <memory> 19 20 #include "mlir/IR/BuiltinAttributes.h" // from @llvm-project 21 #include "mlir/IR/BuiltinOps.h" // from @llvm-project 22 #include "mlir/IR/BuiltinTypes.h" // from @llvm-project 23 #include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project 24 #include "mlir/IR/Matchers.h" // from @llvm-project 25 #include "mlir/IR/Operation.h" // from @llvm-project 26 #include "mlir/IR/Types.h" // from @llvm-project 27 #include "mlir/Pass/Pass.h" // from @llvm-project 28 #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" 29 #include "tensorflow/compiler/mlir/xla/transforms/xla_passes_detail.h" 30 31 #define DEBUG_TYPE "xla-prepare-for-export" 32 33 namespace mlir { 34 namespace mhlo { 35 namespace { 36 37 // Prepare module for export to XLA HLO. 38 struct PrepareForExportPass 39 : public PrepareForExportPassBase<PrepareForExportPass> { 40 void runOnFunction() override; 41 }; 42 43 } // end namespace 44 runOnFunction()45void PrepareForExportPass::runOnFunction() { 46 getFunction().walk([&](Operation *op) { 47 mlir::SplatElementsAttr attr; 48 if (!matchPattern(op, m_Constant(&attr))) return; 49 // Only consider int or floats for now. 50 if (!attr.getType().getElementType().isIntOrFloat()) return; 51 // Arbitrarialy chosen "small" number. This could be chosen based on the 52 // proto size too. 53 if (attr.getNumElements() < 32) return; 54 ShapedType return_type = op->getResultTypes().front().cast<ShapedType>(); 55 ImplicitLocOpBuilder b(op->getLoc(), op); 56 auto cst = b.create<::mlir::mhlo::ConstOp>(attr.getSplatValue()); 57 auto broadcast = b.create<::mlir::mhlo::BroadcastInDimOp>( 58 return_type, cst, b.getI64TensorAttr({})); 59 op->replaceAllUsesWith(broadcast); 60 op->erase(); 61 }); 62 } 63 CreatePrepareForExport()64std::unique_ptr<OperationPass<FuncOp>> CreatePrepareForExport() { 65 return std::make_unique<PrepareForExportPass>(); 66 } 67 68 } // end namespace mhlo 69 } // end namespace mlir 70