1 /* Copyright 2021 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 #ifndef TENSORFLOW_COMPILER_MLIR_TENSORFLOW_UTILS_RESOURCE_VALUE_TYPED_ANALYZER_H_
17 #define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_UTILS_RESOURCE_VALUE_TYPED_ANALYZER_H_
18 
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
22 #include "mlir/IR/BuiltinOps.h"  // from @llvm-project
23 
24 namespace mlir {
25 namespace TF {
26 
27 class ResourceAnalyzer {
28  public:
29   explicit ResourceAnalyzer(ModuleOp module, bool skip_session_init = false);
30 
31   bool IsPotentiallyWritten(Value resource) const;
32 
33  private:
34   // Analyze the specified region for resource mutating operations, namely
35   // TF::AssignVariableOp, if so, set the resource associated as "potentially
36   // written".
37   LogicalResult AnalyzeRegion(Region& region);
38 
39   // If an op is not one of the handled ones, we assume all resource usages
40   // within its purview are mutating in nature.
41   void PropagatePotentiallyWrittenWithinUnhandledOp(Operation* op);
42 
43   // Given a Region associated with the callee and operands from the
44   // corresponding callOp, propagate the potentially written decision to the
45   // callOp's operands, if the corresponding region's arguments are potentially
46   // written resources.
47   void PropagatePotentiallyWrittenUpFromCallee(
48       Region& region, Operation::operand_range propagate_to);
49 
50   // Marks 'resource' as written.
51   void SetPotentiallyWritten(Value resource);
52 
53   struct ResourceInfo {
54     bool potentially_written = false;
55   };
56   // Key: Resource Value's
57   // Value: Information we know about that Value.
58   // Note that these Value's are in general in different functions.
59   DenseMap<Value, ResourceInfo> resource_infos_;
60   // The set of regions we already discovered.
61   DenseSet<Region*> discovered_;
62   // Identifiers about mutable variables.
63   // All variables are identified by (device, container, shared_name).
64   DenseSet<std::tuple<llvm::StringRef, llvm::StringRef, llvm::StringRef>>
65       mutable_variables_;
66 };
67 
68 }  // namespace TF
69 }  // namespace mlir
70 
71 #endif  // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_UTILS_RESOURCE_VALUE_TYPED_ANALYZER_H_
72