xref: /aosp_15_r20/external/tensorflow/tensorflow/core/transforms/cse/pass.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 #include "tensorflow/core/transforms/cse/pass.h"
17 
18 #include <memory>
19 
20 #include "mlir/IR/MLIRContext.h"  // from @llvm-project
21 #include "mlir/Pass/Pass.h"  // from @llvm-project
22 #include "mlir/Pass/PassManager.h"  // from @llvm-project
23 #include "mlir/Support/LLVM.h"  // from @llvm-project
24 #include "mlir/Support/TypeID.h"  // from @llvm-project
25 #include "mlir/Transforms/Passes.h"  // from @llvm-project
26 #include "tensorflow/core/ir/dialect.h"
27 #include "tensorflow/core/ir/ops.h"
28 #include "tensorflow/core/transforms/pass_detail.h"
29 
30 namespace mlir {
31 namespace tfg {
32 namespace {
33 class CSEPass : public CSEPassBase<CSEPass> {
34  public:
initialize(MLIRContext * context)35   LogicalResult initialize(MLIRContext *context) override {
36     dialect_ = context->getOrLoadDialect<TFGraphDialect>();
37     return success();
38   }
39   void runOnOperation() override;
40 
41  private:
42   /// The cached TFG dialect instance.
43   TFGraphDialect *dialect_;
44 };
45 }  // namespace
46 
runOnOperation()47 void CSEPass::runOnOperation() {
48   GraphFuncOp func = getOperation();
49 
50   // Strip and save operation names.
51   DenseMap<Operation *, Attribute> op_names;
52   func.walk([&](Operation *op) {
53     if (Attribute name = op->removeAttr(dialect_->getNameAttrIdentifier())) {
54       op_names.insert({op, name});
55     }
56   });
57 
58   // Run a nested CSE pass.
59   OpPassManager nested_manager(func->getName());
60   nested_manager.addPass(createCSEPass());
61   if (failed(runPipeline(nested_manager, func))) {
62     return signalPassFailure();
63   }
64 
65   // Re-assign names to any remaining operations.
66   func.walk([&](Operation *op) {
67     if (Attribute name = op_names.lookup(op)) {
68       op->setAttr(dialect_->getNameAttrIdentifier(), name);
69     }
70   });
71 }
72 
CreateCSEPass()73 std::unique_ptr<Pass> CreateCSEPass() { return std::make_unique<CSEPass>(); }
74 }  // namespace tfg
75 }  // namespace mlir
76