[PM] Split the analysis manager into a function-specific interface and
[oota-llvm.git] / include / llvm / IR / PassManager.h
1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This header defines various interfaces for pass management in LLVM. There
12 /// is no "pass" interface in LLVM per se. Instead, an instance of any class
13 /// which supports a method to 'run' it over a unit of IR can be used as
14 /// a pass. A pass manager is generally a tool to collect a sequence of passes
15 /// which run over a particular IR construct, and run each of them in sequence
16 /// over each such construct in the containing IR construct. As there is no
17 /// containing IR construct for a Module, a manager for passes over modules
18 /// forms the base case which runs its managed passes in sequence over the
19 /// single module provided.
20 ///
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
23 ///
24 /// * FunctionPassManager can run over a Module, runs each pass over
25 ///   a Function.
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
27 ///
28 /// Note that the implementations of the pass managers use concept-based
29 /// polymorphism as outlined in the "Value Semantics and Concept-based
30 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
31 /// Class of Evil") by Sean Parent:
32 /// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
33 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8
34 /// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
35 ///
36 //===----------------------------------------------------------------------===//
37
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/polymorphic_ptr.h"
40 #include "llvm/Support/type_traits.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/Module.h"
43 #include <list>
44 #include <vector>
45
46 namespace llvm {
47
48 class Module;
49 class Function;
50
51 /// \brief Implementation details of the pass manager interfaces.
52 namespace detail {
53
54 /// \brief Template for the abstract base class used to dispatch
55 /// polymorphically over pass objects.
56 template <typename T> struct PassConcept {
57   // Boiler plate necessary for the container of derived classes.
58   virtual ~PassConcept() {}
59   virtual PassConcept *clone() = 0;
60
61   /// \brief The polymorphic API which runs the pass over a given IR entity.
62   virtual bool run(T Arg) = 0;
63 };
64
65 /// \brief A template wrapper used to implement the polymorphic API.
66 ///
67 /// Can be instantiated for any object which provides a \c run method
68 /// accepting a \c T. It requires the pass to be a copyable
69 /// object.
70 template <typename T, typename PassT> struct PassModel : PassConcept<T> {
71   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
72   virtual PassModel *clone() { return new PassModel(Pass); }
73   virtual bool run(T Arg) { return Pass.run(Arg); }
74   PassT Pass;
75 };
76
77 /// \brief Abstract concept of an analysis result.
78 ///
79 /// This concept is parameterized over the IR unit that this result pertains
80 /// to.
81 template <typename IRUnitT> struct AnalysisResultConcept {
82   virtual ~AnalysisResultConcept() {}
83   virtual AnalysisResultConcept *clone() = 0;
84
85   /// \brief Method to try and mark a result as invalid.
86   ///
87   /// When the outer \c AnalysisManager detects a change in some underlying
88   /// unit of the IR, it will call this method on all of the results cached.
89   ///
90   /// \returns true if the result should indeed be invalidated (the default).
91   virtual bool invalidate(IRUnitT *IR) = 0;
92 };
93
94 /// \brief Wrapper to model the analysis result concept.
95 ///
96 /// Can wrap any type which implements a suitable invalidate member and model
97 /// the AnalysisResultConcept for the AnalysisManager.
98 template <typename IRUnitT, typename ResultT>
99 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
100   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
101   virtual AnalysisResultModel *clone() {
102     return new AnalysisResultModel(Result);
103   }
104
105   /// \brief The model delegates to the \c ResultT method.
106   virtual bool invalidate(IRUnitT *IR) { return Result.invalidate(IR); }
107
108   ResultT Result;
109 };
110
111 /// \brief Abstract concept of an analysis pass.
112 ///
113 /// This concept is parameterized over the IR unit that it can run over and
114 /// produce an analysis result.
115 template <typename IRUnitT> struct AnalysisPassConcept {
116   virtual ~AnalysisPassConcept() {}
117   virtual AnalysisPassConcept *clone() = 0;
118
119   /// \brief Method to run this analysis over a unit of IR.
120   /// \returns The analysis result object to be queried by users, the caller
121   /// takes ownership.
122   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
123 };
124
125 /// \brief Wrapper to model the analysis pass concept.
126 ///
127 /// Can wrap any type which implements a suitable \c run method. The method
128 /// must accept the IRUnitT as an argument and produce an object which can be
129 /// wrapped in a \c AnalysisResultModel.
130 template <typename PassT>
131 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
132   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
133   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
134
135   // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
136   typedef typename PassT::IRUnitT IRUnitT;
137
138   // FIXME: Replace PassT::Result with type traits when we use C++11.
139   typedef AnalysisResultModel<IRUnitT, typename PassT::Result> ResultModelT;
140
141   /// \brief The model delegates to the \c PassT::run method.
142   ///
143   /// The return is wrapped in an \c AnalysisResultModel.
144   virtual ResultModelT *run(IRUnitT *IR) {
145     return new ResultModelT(Pass.run(IR));
146   }
147
148   PassT Pass;
149 };
150
151 }
152
153 class ModuleAnalysisManager;
154
155 class ModulePassManager {
156 public:
157   explicit ModulePassManager(ModuleAnalysisManager *AM = 0) : AM(AM) {}
158
159   /// \brief Run all of the module passes in this module pass manager over
160   /// a module.
161   ///
162   /// This method should only be called for a single module as there is the
163   /// expectation that the lifetime of a pass is bounded to that of a module.
164   void run(Module *M);
165
166   template <typename ModulePassT> void addPass(ModulePassT Pass) {
167     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
168   }
169
170 private:
171   // Pull in the concept type and model template specialized for modules.
172   typedef detail::PassConcept<Module *> ModulePassConcept;
173   template <typename PassT>
174   struct ModulePassModel : detail::PassModel<Module *, PassT> {
175     ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
176   };
177
178   ModuleAnalysisManager *AM;
179   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
180 };
181
182 class FunctionAnalysisManager;
183
184 class FunctionPassManager {
185 public:
186   explicit FunctionPassManager(FunctionAnalysisManager *AM = 0) : AM(AM) {}
187
188   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
189     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
190   }
191
192   bool run(Module *M);
193
194 private:
195   // Pull in the concept type and model template specialized for functions.
196   typedef detail::PassConcept<Function *> FunctionPassConcept;
197   template <typename PassT>
198   struct FunctionPassModel : detail::PassModel<Function *, PassT> {
199     FunctionPassModel(PassT Pass)
200         : detail::PassModel<Function *, PassT>(Pass) {}
201   };
202
203   FunctionAnalysisManager *AM;
204   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
205 };
206
207 /// \brief A module analysis pass manager with lazy running and caching of
208 /// results.
209 class ModuleAnalysisManager {
210 public:
211   ModuleAnalysisManager() {}
212
213   /// \brief Get the result of an analysis pass for this module.
214   ///
215   /// If there is not a valid cached result in the manager already, this will
216   /// re-run the analysis to produce a valid result.
217   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
218     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
219                        "The analysis pass must be over a Module.");
220     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
221            "This analysis pass was not registered prior to being queried");
222
223     const detail::AnalysisResultConcept<Module> &ResultConcept =
224         getResultImpl(PassT::ID(), M);
225     typedef detail::AnalysisResultModel<Module, typename PassT::Result>
226         ResultModelT;
227     return static_cast<const ResultModelT &>(ResultConcept).Result;
228   }
229
230   /// \brief Register an analysis pass with the manager.
231   ///
232   /// This provides an initialized and set-up analysis pass to the
233   /// analysis
234   /// manager. Whomever is setting up analysis passes must use this to
235   /// populate
236   /// the manager with all of the analysis passes available.
237   template <typename PassT> void registerPass(PassT Pass) {
238     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
239                        "The analysis pass must be over a Module.");
240     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
241            "Registered the same analysis pass twice!");
242     ModuleAnalysisPasses[PassT::ID()] =
243         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
244   }
245
246   /// \brief Invalidate a specific analysis pass for an IR module.
247   ///
248   /// Note that the analysis result can disregard invalidation.
249   template <typename PassT> void invalidate(Module *M) {
250     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
251                        "The analysis pass must be over a Module.");
252     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
253            "This analysis pass was not registered prior to being invalidated");
254     invalidateImpl(PassT::ID(), M);
255   }
256
257   /// \brief Invalidate analyses cached for an IR Module.
258   ///
259   /// Note that specific analysis results can disregard invalidation by
260   /// overriding their invalidate method.
261   ///
262   /// The module must be the module this analysis manager was constructed
263   /// around.
264   void invalidateAll(Module *M);
265
266 private:
267   /// \brief Get a module pass result, running the pass if necessary.
268   const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
269                                                              Module *M);
270
271   /// \brief Invalidate a module pass result.
272   void invalidateImpl(void *PassID, Module *M);
273
274   /// \brief Map type from module analysis pass ID to pass concept pointer.
275   typedef DenseMap<void *,
276                    polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
277       ModuleAnalysisPassMapT;
278
279   /// \brief Collection of module analysis passes, indexed by ID.
280   ModuleAnalysisPassMapT ModuleAnalysisPasses;
281
282   /// \brief Map type from module analysis pass ID to pass result concept pointer.
283   typedef DenseMap<void *,
284                    polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
285       ModuleAnalysisResultMapT;
286
287   /// \brief Cache of computed module analysis results for this module.
288   ModuleAnalysisResultMapT ModuleAnalysisResults;
289 };
290
291 /// \brief A function analysis manager to coordinate and cache analyses run over
292 /// a module.
293 class FunctionAnalysisManager {
294 public:
295   FunctionAnalysisManager() {}
296
297   /// \brief Get the result of an analysis pass for a function.
298   ///
299   /// If there is not a valid cached result in the manager already, this will
300   /// re-run the analysis to produce a valid result.
301   template <typename PassT>
302   const typename PassT::Result &getResult(Function *F) {
303     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
304                        "The analysis pass must be over a Function.");
305     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
306            "This analysis pass was not registered prior to being queried");
307
308     const detail::AnalysisResultConcept<Function> &ResultConcept =
309         getResultImpl(PassT::ID(), F);
310     typedef detail::AnalysisResultModel<Function, typename PassT::Result>
311         ResultModelT;
312     return static_cast<const ResultModelT &>(ResultConcept).Result;
313   }
314
315   /// \brief Register an analysis pass with the manager.
316   ///
317   /// This provides an initialized and set-up analysis pass to the
318   /// analysis
319   /// manager. Whomever is setting up analysis passes must use this to
320   /// populate
321   /// the manager with all of the analysis passes available.
322   template <typename PassT> void registerPass(PassT Pass) {
323     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
324                        "The analysis pass must be over a Function.");
325     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
326            "Registered the same analysis pass twice!");
327     FunctionAnalysisPasses[PassT::ID()] =
328         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
329   }
330
331   /// \brief Invalidate a specific analysis pass for an IR module.
332   ///
333   /// Note that the analysis result can disregard invalidation.
334   template <typename PassT> void invalidate(Function *F) {
335     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
336                        "The analysis pass must be over a Function.");
337     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
338            "This analysis pass was not registered prior to being invalidated");
339     invalidateImpl(PassT::ID(), F);
340   }
341
342   /// \brief Invalidate analyses cached for an IR Function.
343   ///
344   /// Note that specific analysis results can disregard invalidation by
345   /// overriding the invalidate method.
346   void invalidateAll(Function *F);
347
348 private:
349   /// \brief Get a function pass result, running the pass if necessary.
350   const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
351                                                                Function *F);
352
353   /// \brief Invalidate a function pass result.
354   void invalidateImpl(void *PassID, Function *F);
355
356   /// \brief Map type from function analysis pass ID to pass concept pointer.
357   typedef DenseMap<void *,
358                    polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
359       FunctionAnalysisPassMapT;
360
361   /// \brief Collection of function analysis passes, indexed by ID.
362   FunctionAnalysisPassMapT FunctionAnalysisPasses;
363
364   /// \brief List of function analysis pass IDs and associated concept pointers.
365   ///
366   /// Requires iterators to be valid across appending new entries and arbitrary
367   /// erases. Provides both the pass ID and concept pointer such that it is
368   /// half of a bijection and provides storage for the actual result concept.
369   typedef std::list<std::pair<
370       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
371       FunctionAnalysisResultListT;
372
373   /// \brief Map type from function pointer to our custom list type.
374   typedef DenseMap<Function *, FunctionAnalysisResultListT>
375   FunctionAnalysisResultListMapT;
376
377   /// \brief Map from function to a list of function analysis results.
378   ///
379   /// Provides linear time removal of all analysis results for a function and
380   /// the ultimate storage for a particular cached analysis result.
381   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
382
383   /// \brief Map type from a pair of analysis ID and function pointer to an
384   /// iterator into a particular result list.
385   typedef DenseMap<std::pair<void *, Function *>,
386                    FunctionAnalysisResultListT::iterator>
387       FunctionAnalysisResultMapT;
388
389   /// \brief Map from an analysis ID and function to a particular cached
390   /// analysis result.
391   FunctionAnalysisResultMapT FunctionAnalysisResults;
392 };
393
394 }