• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "tensorflow/compiler/mlir/tensorflow/utils/visitor_util.h"
17 
18 #include "mlir/IR/Operation.h"  // from @llvm-project
19 
20 namespace tensorflow {
21 
WalkStage(mlir::Operation * op)22 WalkStage::WalkStage(mlir::Operation *op)
23     : num_regions_(op->getNumRegions()), next_region_(0) {}
24 
25 namespace detail {
26 
27 /// Walk all of the operations nested under and including the given operations.
WalkOperations(mlir::Operation * op,VoidCallback callback)28 void WalkOperations(mlir::Operation *op, VoidCallback callback) {
29   WalkStage stage(op);
30 
31   for (auto &region : op->getRegions()) {
32     // Invoke callback on the parent op before visiting each child region.
33     callback(op, stage);
34     stage.Advance();
35 
36     for (auto &block : region)
37       // Early increment here in the case where the operation is erased.
38       for (auto &nestedOp : llvm::make_early_inc_range(block))
39         WalkOperations(&nestedOp, callback);
40   }
41 
42   // Invoke callback after all regions have been visited.
43   callback(op, stage);
44 }
45 
46 /// Walk all of the operations nested under and including the given operations.
47 /// This methods walks operations until an interrupt signal is received.
WalkOperations(mlir::Operation * op,InterruptCallback callback)48 mlir::WalkResult WalkOperations(mlir::Operation *op,
49                                 InterruptCallback callback) {
50   WalkStage stage(op);
51 
52   for (auto &region : op->getRegions()) {
53     // Invoke callback on the parent op before visiting each child region.
54     if (callback(op, stage).wasInterrupted())
55       return mlir::WalkResult::interrupt();
56 
57     stage.Advance();
58 
59     for (auto &block : region) {
60       // Early increment here in the case where the operation is erased.
61       for (auto &nestedOp : llvm::make_early_inc_range(block))
62         if (WalkOperations(&nestedOp, callback).wasInterrupted())
63           return mlir::WalkResult::interrupt();
64     }
65   }
66   return callback(op, stage);
67 }
68 
69 }  // namespace detail
70 }  // namespace tensorflow
71