1 /* Copyright 2019 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 "tensorflow/compiler/mlir/tensorflow/transforms/decode_constant.h" 17 18 #include "mlir/IR/Attributes.h" // from @llvm-project 19 #include "mlir/IR/Builders.h" // from @llvm-project 20 #include "mlir/IR/Operation.h" // from @llvm-project 21 #include "mlir/Pass/Pass.h" // from @llvm-project 22 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" 23 #include "tensorflow/compiler/mlir/tensorflow/utils/convert_tensor.h" 24 25 namespace mlir { 26 namespace TF { 27 28 namespace { 29 30 // If the given `op` is an constant op with an opaque value, decodes and resets 31 // its value into a readable one. Otherwise, does nothing. This function returns 32 // false if the given `op` is a tf.Constant op and we cannot decode its value. DecodeOpaqueValueInConstantOp(Operation * op)33bool DecodeOpaqueValueInConstantOp(Operation *op) { 34 auto tfOp = dyn_cast<ConstOp>(op); 35 if (!tfOp) return true; 36 37 auto opaque_attr = tfOp.value().dyn_cast<OpaqueElementsAttr>(); 38 // Skip non-opaque values. 39 if (!opaque_attr) return true; 40 41 Builder builder(op->getContext()); 42 43 ElementsAttr decoded_attr; 44 if (opaque_attr.decode(decoded_attr)) { 45 op->emitOpError("has undecodable opaque value"); 46 return false; 47 } 48 49 op->setAttr("value", decoded_attr); 50 51 return true; 52 } 53 54 // A pass to decode opaque constant values into readable ones. 55 struct DecodeConstant : public PassWrapper<DecodeConstant, FunctionPass> { runOnFunctionmlir::TF::__anonb77dc60a0111::DecodeConstant56 void runOnFunction() override { 57 auto walk_result = getFunction().walk([](Operation *op) { 58 return DecodeOpaqueValueInConstantOp(op) ? WalkResult::advance() 59 : WalkResult::interrupt(); 60 }); 61 if (walk_result.wasInterrupted()) signalPassFailure(); 62 } 63 }; 64 65 } // namespace 66 CreateDecodeConstantPass()67std::unique_ptr<OperationPass<FuncOp>> CreateDecodeConstantPass() { 68 return std::make_unique<DecodeConstant>(); 69 } 70 71 static PassRegistration<DecodeConstant> pass( 72 "tf-decode-constant", "Decode opaque constant into human-readable ones"); 73 74 } // namespace TF 75 } // namespace mlir 76