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 #ifndef TENSORFLOW_COMPILER_MLIR_TENSORFLOW_ANALYSIS_PER_FUNCTION_AGGREGATE_ANALYSIS_H_ 17 #define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_ANALYSIS_PER_FUNCTION_AGGREGATE_ANALYSIS_H_ 18 19 #include <cstddef> 20 #include <cstdint> 21 #include <memory> 22 23 #include "llvm/ADT/DenseMap.h" 24 #include "mlir/IR/BuiltinOps.h" // from @llvm-project 25 #include "mlir/Pass/Pass.h" // from @llvm-project 26 27 namespace mlir { 28 namespace TF { 29 namespace detail { 30 31 // This template defines an aggregate analysis base class, which analyzes a 32 // module but the analysis info is stored per function. 33 template <typename InfoT> 34 class PerFunctionAggregateAnalysis { 35 public: 36 using Info = InfoT; 37 38 // Returns the analysis info for the given function. GetAnalysisForFunc(FuncOp func)39 const Info& GetAnalysisForFunc(FuncOp func) const { 40 auto it = info_map_.find(func); 41 assert(it != info_map_.end()); 42 return it->second; 43 } 44 45 protected: 46 // Since `InfoT` might be large, DenseMap is used instead of SmallDenseMap to 47 // avoid stack overflow. 48 llvm::DenseMap<FuncOp, InfoT> info_map_; 49 }; 50 51 } // namespace detail 52 53 // Base CRTP class to help write passes that are consumes a per-function 54 // aggregate analysis and operate on all non-extern functions (similar to a 55 // FunctionPass, but with no concurrency between functions). The derived classes 56 // need to provide a runOnFunction() method that accepts the function and the 57 // analysis information for that function. 58 template <typename DerivedT, typename AnalysisT> 59 class PerFunctionAggregateAnalysisConsumerPass 60 : public PassWrapper< 61 PerFunctionAggregateAnalysisConsumerPass<DerivedT, AnalysisT>, 62 OperationPass<ModuleOp>> { runOnOperation()63 void runOnOperation() override { 64 ModuleOp op = this->getOperation(); 65 DerivedT& derived = *static_cast<DerivedT*>(this); 66 auto& analysis = this->template getAnalysis<AnalysisT>(); 67 68 for (auto func : op.getOps<FuncOp>()) 69 if (!func.isExternal()) 70 derived.runOnFunction(func, analysis.GetAnalysisForFunc(func)); 71 } 72 }; 73 74 } // namespace TF 75 } // namespace mlir 76 77 #endif // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_ANALYSIS_PER_FUNCTION_AGGREGATE_ANALYSIS_H_ 78