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 transformation pass converts existing compilation and replication
17 // attributes into unified attributes. For example, A _tpu_replicate=X
18 // should be replaced with _xla_compile_device_type=TPU and
19 // _replication_info=X attributes by the conversion.
20 
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Support/Debug.h"
23 #include "mlir/IR/Builders.h"  // from @llvm-project
24 #include "mlir/IR/Operation.h"  // from @llvm-project
25 #include "mlir/Pass/Pass.h"  // from @llvm-project
26 #include "mlir/Support/LLVM.h"  // from @llvm-project
27 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
28 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h"
29 #include "tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h"
30 
31 #define DEBUG_TYPE "tf-canonicalize-compile-and-replicate-attributes"
32 
33 namespace mlir {
34 namespace TFTPU {
35 
36 namespace {
37 
38 struct CanonicalizeCompileAndReplicateAttributesPass
39     : public TF::CanonicalizeCompileAndReplicateAttributesPassBase<
40           CanonicalizeCompileAndReplicateAttributesPass> {
41   void runOnOperation() override;
42 };
43 
runOnOperation()44 void CanonicalizeCompileAndReplicateAttributesPass::runOnOperation() {
45   func::FuncOp func_op = getOperation();
46   ModuleOp module_op = func_op->getParentOfType<ModuleOp>();
47   mlir::OpBuilder builder(module_op.getContext());
48   func_op->walk([&](mlir::Operation* op) {
49     if (op->hasAttr(TF::kTpuReplicateAttr)) {
50       op->setAttr(TF::kReplicationInfoAttr, op->getAttr(TF::kTpuReplicateAttr));
51       op->removeAttr(TF::kTpuReplicateAttr);
52       op->setAttr(TF::kCompileDeviceTypeAttr,
53                   builder.getStringAttr(TF::kTpuDevice));
54     }
55     return mlir::WalkResult::advance();
56   });
57 }
58 
59 }  // namespace
60 
61 std::unique_ptr<OperationPass<func::FuncOp>>
CreateCanonicalizeCompileAndReplicateAttributesPass()62 CreateCanonicalizeCompileAndReplicateAttributesPass() {
63   return std::make_unique<CanonicalizeCompileAndReplicateAttributesPass>();
64 }
65 
66 }  // namespace TFTPU
67 }  // namespace mlir
68