1 /* Copyright 2020 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 #include <vector> 17 18 #include "llvm/ADT/DenseMap.h" 19 #include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project 20 #include "mlir/IR/BuiltinOps.h" // from @llvm-project 21 #include "mlir/Pass/Pass.h" // from @llvm-project 22 #include "mlir/Support/LLVM.h" // from @llvm-project 23 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" 24 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h" 25 #include "tensorflow/compiler/mlir/tensorflow/transforms/savedmodel_passes_detail.h" 26 27 namespace mlir { 28 namespace tf_saved_model { 29 namespace { 30 31 class DedupBoundInputBindingPass 32 : public DedupBoundInputBindingPassBase<DedupBoundInputBindingPass> { 33 void runOnOperation() final; 34 }; 35 runOnOperation()36void DedupBoundInputBindingPass::runOnOperation() { 37 func::FuncOp func = getOperation(); 38 if (!mlir::tf_saved_model::IsExported(func)) return; 39 llvm::SmallDenseMap<Attribute, unsigned, 8> unique_bound_inputs; 40 llvm::BitVector arg_indices_to_erase(func.getNumArguments()); 41 for (unsigned i = 0, e = func.getNumArguments(); i < e; i++) { 42 auto attr = func.getArgAttrOfType<FlatSymbolRefAttr>( 43 i, "tf_saved_model.bound_input"); 44 if (!attr) continue; 45 auto inserted = unique_bound_inputs.insert(std::make_pair(attr, i)); 46 if (inserted.second) continue; 47 auto duplicate_arg = func.getArgument(i); 48 auto original_arg = func.getArgument(unique_bound_inputs[attr]); 49 duplicate_arg.replaceAllUsesWith(original_arg); 50 arg_indices_to_erase.set(i); 51 } 52 func.eraseArguments(arg_indices_to_erase); 53 } 54 55 } // namespace 56 57 std::unique_ptr<OperationPass<func::FuncOp>> CreateDedupBoundInputBindingPass()58CreateDedupBoundInputBindingPass() { 59 return std::make_unique<DedupBoundInputBindingPass>(); 60 } 61 62 } // namespace tf_saved_model 63 } // namespace mlir 64