[PM] Make the function pass manager more regular.
[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(Function *F);
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 Trivial adaptor that maps from a module to its functions.
208 ///
209 /// Designed to allow composition of a FunctionPass(Manager) and a
210 /// ModulePassManager.
211 template <typename FunctionPassT>
212 class ModuleToFunctionPassAdaptor {
213 public:
214   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
215       : Pass(llvm_move(Pass)) {}
216
217   /// \brief Runs the function pass across every function in the module.
218   bool run(Module *M) {
219     bool Changed = false;
220     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
221       Changed |= Pass.run(I);
222     return Changed;
223   }
224
225 private:
226   FunctionPassT Pass;
227 };
228
229 /// \brief A function to deduce a function pass type and wrap it in the
230 /// templated adaptor.
231 template <typename FunctionPassT>
232 ModuleToFunctionPassAdaptor<FunctionPassT>
233 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
234   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
235 }
236
237 /// \brief A module analysis pass manager with lazy running and caching of
238 /// results.
239 class ModuleAnalysisManager {
240 public:
241   ModuleAnalysisManager() {}
242
243   /// \brief Get the result of an analysis pass for this module.
244   ///
245   /// If there is not a valid cached result in the manager already, this will
246   /// re-run the analysis to produce a valid result.
247   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
248     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
249                        "The analysis pass must be over a Module.");
250     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
251            "This analysis pass was not registered prior to being queried");
252
253     const detail::AnalysisResultConcept<Module> &ResultConcept =
254         getResultImpl(PassT::ID(), M);
255     typedef detail::AnalysisResultModel<Module, typename PassT::Result>
256         ResultModelT;
257     return static_cast<const ResultModelT &>(ResultConcept).Result;
258   }
259
260   /// \brief Register an analysis pass with the manager.
261   ///
262   /// This provides an initialized and set-up analysis pass to the
263   /// analysis
264   /// manager. Whomever is setting up analysis passes must use this to
265   /// populate
266   /// the manager with all of the analysis passes available.
267   template <typename PassT> void registerPass(PassT Pass) {
268     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
269                        "The analysis pass must be over a Module.");
270     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
271            "Registered the same analysis pass twice!");
272     ModuleAnalysisPasses[PassT::ID()] =
273         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
274   }
275
276   /// \brief Invalidate a specific analysis pass for an IR module.
277   ///
278   /// Note that the analysis result can disregard invalidation.
279   template <typename PassT> void invalidate(Module *M) {
280     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
281                        "The analysis pass must be over a Module.");
282     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
283            "This analysis pass was not registered prior to being invalidated");
284     invalidateImpl(PassT::ID(), M);
285   }
286
287   /// \brief Invalidate analyses cached for an IR Module.
288   ///
289   /// Note that specific analysis results can disregard invalidation by
290   /// overriding their invalidate method.
291   ///
292   /// The module must be the module this analysis manager was constructed
293   /// around.
294   void invalidateAll(Module *M);
295
296 private:
297   /// \brief Get a module pass result, running the pass if necessary.
298   const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
299                                                              Module *M);
300
301   /// \brief Invalidate a module pass result.
302   void invalidateImpl(void *PassID, Module *M);
303
304   /// \brief Map type from module analysis pass ID to pass concept pointer.
305   typedef DenseMap<void *,
306                    polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
307       ModuleAnalysisPassMapT;
308
309   /// \brief Collection of module analysis passes, indexed by ID.
310   ModuleAnalysisPassMapT ModuleAnalysisPasses;
311
312   /// \brief Map type from module analysis pass ID to pass result concept pointer.
313   typedef DenseMap<void *,
314                    polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
315       ModuleAnalysisResultMapT;
316
317   /// \brief Cache of computed module analysis results for this module.
318   ModuleAnalysisResultMapT ModuleAnalysisResults;
319 };
320
321 /// \brief A function analysis manager to coordinate and cache analyses run over
322 /// a module.
323 class FunctionAnalysisManager {
324 public:
325   FunctionAnalysisManager() {}
326
327   /// \brief Get the result of an analysis pass for a function.
328   ///
329   /// If there is not a valid cached result in the manager already, this will
330   /// re-run the analysis to produce a valid result.
331   template <typename PassT>
332   const typename PassT::Result &getResult(Function *F) {
333     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
334                        "The analysis pass must be over a Function.");
335     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
336            "This analysis pass was not registered prior to being queried");
337
338     const detail::AnalysisResultConcept<Function> &ResultConcept =
339         getResultImpl(PassT::ID(), F);
340     typedef detail::AnalysisResultModel<Function, typename PassT::Result>
341         ResultModelT;
342     return static_cast<const ResultModelT &>(ResultConcept).Result;
343   }
344
345   /// \brief Register an analysis pass with the manager.
346   ///
347   /// This provides an initialized and set-up analysis pass to the
348   /// analysis
349   /// manager. Whomever is setting up analysis passes must use this to
350   /// populate
351   /// the manager with all of the analysis passes available.
352   template <typename PassT> void registerPass(PassT Pass) {
353     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
354                        "The analysis pass must be over a Function.");
355     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
356            "Registered the same analysis pass twice!");
357     FunctionAnalysisPasses[PassT::ID()] =
358         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
359   }
360
361   /// \brief Invalidate a specific analysis pass for an IR module.
362   ///
363   /// Note that the analysis result can disregard invalidation.
364   template <typename PassT> void invalidate(Function *F) {
365     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
366                        "The analysis pass must be over a Function.");
367     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
368            "This analysis pass was not registered prior to being invalidated");
369     invalidateImpl(PassT::ID(), F);
370   }
371
372   /// \brief Invalidate analyses cached for an IR Function.
373   ///
374   /// Note that specific analysis results can disregard invalidation by
375   /// overriding the invalidate method.
376   void invalidateAll(Function *F);
377
378 private:
379   /// \brief Get a function pass result, running the pass if necessary.
380   const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
381                                                                Function *F);
382
383   /// \brief Invalidate a function pass result.
384   void invalidateImpl(void *PassID, Function *F);
385
386   /// \brief Map type from function analysis pass ID to pass concept pointer.
387   typedef DenseMap<void *,
388                    polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
389       FunctionAnalysisPassMapT;
390
391   /// \brief Collection of function analysis passes, indexed by ID.
392   FunctionAnalysisPassMapT FunctionAnalysisPasses;
393
394   /// \brief List of function analysis pass IDs and associated concept pointers.
395   ///
396   /// Requires iterators to be valid across appending new entries and arbitrary
397   /// erases. Provides both the pass ID and concept pointer such that it is
398   /// half of a bijection and provides storage for the actual result concept.
399   typedef std::list<std::pair<
400       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
401       FunctionAnalysisResultListT;
402
403   /// \brief Map type from function pointer to our custom list type.
404   typedef DenseMap<Function *, FunctionAnalysisResultListT>
405   FunctionAnalysisResultListMapT;
406
407   /// \brief Map from function to a list of function analysis results.
408   ///
409   /// Provides linear time removal of all analysis results for a function and
410   /// the ultimate storage for a particular cached analysis result.
411   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
412
413   /// \brief Map type from a pair of analysis ID and function pointer to an
414   /// iterator into a particular result list.
415   typedef DenseMap<std::pair<void *, Function *>,
416                    FunctionAnalysisResultListT::iterator>
417       FunctionAnalysisResultMapT;
418
419   /// \brief Map from an analysis ID and function to a particular cached
420   /// analysis result.
421   FunctionAnalysisResultMapT FunctionAnalysisResults;
422 };
423
424 }