[PM] Add the preservation system to the new pass manager.
[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/SmallPtrSet.h"
40 #include "llvm/ADT/polymorphic_ptr.h"
41 #include "llvm/Support/type_traits.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Module.h"
44 #include <list>
45 #include <vector>
46
47 namespace llvm {
48
49 class Module;
50 class Function;
51
52 /// \brief An abstract set of preserved analyses following a transformation pass
53 /// run.
54 ///
55 /// When a transformation pass is run, it can return a set of analyses whose
56 /// results were preserved by that transformation. The default set is "none",
57 /// and preserving analyses must be done explicitly.
58 ///
59 /// There is also an explicit all state which can be used (for example) when
60 /// the IR is not mutated at all.
61 class PreservedAnalyses {
62 public:
63   /// \brief Convenience factory function for the empty preserved set.
64   static PreservedAnalyses none() { return PreservedAnalyses(); }
65
66   /// \brief Construct a special preserved set that preserves all passes.
67   static PreservedAnalyses all() {
68     PreservedAnalyses PA;
69     PA.PreservedPassIDs.insert((void *)AllPassesID);
70     return PA;
71   }
72
73   PreservedAnalyses &operator=(PreservedAnalyses Arg) {
74     swap(Arg);
75     return *this;
76   }
77
78   void swap(PreservedAnalyses &Arg) {
79     PreservedPassIDs.swap(Arg.PreservedPassIDs);
80   }
81
82   /// \brief Mark a particular pass as preserved, adding it to the set.
83   template <typename PassT> void preserve() {
84     if (!areAllPreserved())
85       PreservedPassIDs.insert(PassT::ID());
86   }
87
88   /// \brief Intersect this set with another in place.
89   ///
90   /// This is a mutating operation on this preserved set, removing all
91   /// preserved passes which are not also preserved in the argument.
92   void intersect(const PreservedAnalyses &Arg) {
93     if (Arg.areAllPreserved())
94       return;
95     if (areAllPreserved()) {
96       PreservedPassIDs = Arg.PreservedPassIDs;
97       return;
98     }
99     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
100                                                 E = PreservedPassIDs.end();
101          I != E; ++I)
102       if (!Arg.PreservedPassIDs.count(*I))
103         PreservedPassIDs.erase(*I);
104   }
105
106 #if LLVM_HAS_RVALUE_REFERENCES
107   /// \brief Intersect this set with a temporary other set in place.
108   ///
109   /// This is a mutating operation on this preserved set, removing all
110   /// preserved passes which are not also preserved in the argument.
111   void intersect(PreservedAnalyses &&Arg) {
112     if (Arg.areAllPreserved())
113       return;
114     if (areAllPreserved()) {
115       PreservedPassIDs = std::move(Arg.PreservedPassIDs);
116       return;
117     }
118     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
119                                                 E = PreservedPassIDs.end();
120          I != E; ++I)
121       if (!Arg.PreservedPassIDs.count(*I))
122         PreservedPassIDs.erase(*I);
123   }
124 #endif
125
126   /// \brief Query whether a pass is marked as preserved by this set.
127   template <typename PassT> bool preserved() const {
128     return preserved(PassT::ID());
129   }
130
131   /// \brief Query whether an abstract pass ID is marked as preserved by this
132   /// set.
133   bool preserved(void *PassID) const {
134     return PreservedPassIDs.count((void *)AllPassesID) ||
135            PreservedPassIDs.count(PassID);
136   }
137
138 private:
139   // Note that this must not be -1 or -2 as those are already used by the
140   // SmallPtrSet.
141   static const uintptr_t AllPassesID = (intptr_t)-3;
142
143   bool areAllPreserved() const { return PreservedPassIDs.count((void *)AllPassesID); }
144
145   SmallPtrSet<void *, 2> PreservedPassIDs;
146 };
147
148 inline void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
149   LHS.swap(RHS);
150 }
151
152 /// \brief Implementation details of the pass manager interfaces.
153 namespace detail {
154
155 /// \brief Template for the abstract base class used to dispatch
156 /// polymorphically over pass objects.
157 template <typename T> struct PassConcept {
158   // Boiler plate necessary for the container of derived classes.
159   virtual ~PassConcept() {}
160   virtual PassConcept *clone() = 0;
161
162   /// \brief The polymorphic API which runs the pass over a given IR entity.
163   virtual PreservedAnalyses run(T Arg) = 0;
164 };
165
166 /// \brief A template wrapper used to implement the polymorphic API.
167 ///
168 /// Can be instantiated for any object which provides a \c run method
169 /// accepting a \c T. It requires the pass to be a copyable
170 /// object.
171 template <typename T, typename PassT> struct PassModel : PassConcept<T> {
172   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
173   virtual PassModel *clone() { return new PassModel(Pass); }
174   virtual PreservedAnalyses run(T Arg) { return Pass.run(Arg); }
175   PassT Pass;
176 };
177
178 /// \brief Abstract concept of an analysis result.
179 ///
180 /// This concept is parameterized over the IR unit that this result pertains
181 /// to.
182 template <typename IRUnitT> struct AnalysisResultConcept {
183   virtual ~AnalysisResultConcept() {}
184   virtual AnalysisResultConcept *clone() = 0;
185
186   /// \brief Method to try and mark a result as invalid.
187   ///
188   /// When the outer \c AnalysisManager detects a change in some underlying
189   /// unit of the IR, it will call this method on all of the results cached.
190   ///
191   /// \returns true if the result should indeed be invalidated (the default).
192   virtual bool invalidate(IRUnitT *IR) = 0;
193 };
194
195 /// \brief Wrapper to model the analysis result concept.
196 ///
197 /// Can wrap any type which implements a suitable invalidate member and model
198 /// the AnalysisResultConcept for the AnalysisManager.
199 template <typename IRUnitT, typename ResultT>
200 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
201   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
202   virtual AnalysisResultModel *clone() {
203     return new AnalysisResultModel(Result);
204   }
205
206   /// \brief The model delegates to the \c ResultT method.
207   virtual bool invalidate(IRUnitT *IR) { return Result.invalidate(IR); }
208
209   ResultT Result;
210 };
211
212 /// \brief Abstract concept of an analysis pass.
213 ///
214 /// This concept is parameterized over the IR unit that it can run over and
215 /// produce an analysis result.
216 template <typename IRUnitT> struct AnalysisPassConcept {
217   virtual ~AnalysisPassConcept() {}
218   virtual AnalysisPassConcept *clone() = 0;
219
220   /// \brief Method to run this analysis over a unit of IR.
221   /// \returns The analysis result object to be queried by users, the caller
222   /// takes ownership.
223   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
224 };
225
226 /// \brief Wrapper to model the analysis pass concept.
227 ///
228 /// Can wrap any type which implements a suitable \c run method. The method
229 /// must accept the IRUnitT as an argument and produce an object which can be
230 /// wrapped in a \c AnalysisResultModel.
231 template <typename PassT>
232 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
233   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
234   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
235
236   // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
237   typedef typename PassT::IRUnitT IRUnitT;
238
239   // FIXME: Replace PassT::Result with type traits when we use C++11.
240   typedef AnalysisResultModel<IRUnitT, typename PassT::Result> ResultModelT;
241
242   /// \brief The model delegates to the \c PassT::run method.
243   ///
244   /// The return is wrapped in an \c AnalysisResultModel.
245   virtual ResultModelT *run(IRUnitT *IR) {
246     return new ResultModelT(Pass.run(IR));
247   }
248
249   PassT Pass;
250 };
251
252 }
253
254 class ModuleAnalysisManager;
255
256 class ModulePassManager {
257 public:
258   explicit ModulePassManager(ModuleAnalysisManager *AM = 0) : AM(AM) {}
259
260   /// \brief Run all of the module passes in this module pass manager over
261   /// a module.
262   ///
263   /// This method should only be called for a single module as there is the
264   /// expectation that the lifetime of a pass is bounded to that of a module.
265   PreservedAnalyses run(Module *M);
266
267   template <typename ModulePassT> void addPass(ModulePassT Pass) {
268     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
269   }
270
271 private:
272   // Pull in the concept type and model template specialized for modules.
273   typedef detail::PassConcept<Module *> ModulePassConcept;
274   template <typename PassT>
275   struct ModulePassModel : detail::PassModel<Module *, PassT> {
276     ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
277   };
278
279   ModuleAnalysisManager *AM;
280   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
281 };
282
283 class FunctionAnalysisManager;
284
285 class FunctionPassManager {
286 public:
287   explicit FunctionPassManager(FunctionAnalysisManager *AM = 0) : AM(AM) {}
288
289   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
290     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
291   }
292
293   PreservedAnalyses run(Function *F);
294
295 private:
296   // Pull in the concept type and model template specialized for functions.
297   typedef detail::PassConcept<Function *> FunctionPassConcept;
298   template <typename PassT>
299   struct FunctionPassModel : detail::PassModel<Function *, PassT> {
300     FunctionPassModel(PassT Pass)
301         : detail::PassModel<Function *, PassT>(Pass) {}
302   };
303
304   FunctionAnalysisManager *AM;
305   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
306 };
307
308 /// \brief Trivial adaptor that maps from a module to its functions.
309 ///
310 /// Designed to allow composition of a FunctionPass(Manager) and a
311 /// ModulePassManager.
312 template <typename FunctionPassT>
313 class ModuleToFunctionPassAdaptor {
314 public:
315   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
316       : Pass(llvm_move(Pass)) {}
317
318   /// \brief Runs the function pass across every function in the module.
319   PreservedAnalyses run(Module *M) {
320     PreservedAnalyses PA = PreservedAnalyses::all();
321     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
322       PreservedAnalyses PassPA = Pass.run(I);
323       PA.intersect(llvm_move(PassPA));
324     }
325     return PA;
326   }
327
328 private:
329   FunctionPassT Pass;
330 };
331
332 /// \brief A function to deduce a function pass type and wrap it in the
333 /// templated adaptor.
334 template <typename FunctionPassT>
335 ModuleToFunctionPassAdaptor<FunctionPassT>
336 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
337   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
338 }
339
340 /// \brief A module analysis pass manager with lazy running and caching of
341 /// results.
342 class ModuleAnalysisManager {
343 public:
344   ModuleAnalysisManager() {}
345
346   /// \brief Get the result of an analysis pass for this module.
347   ///
348   /// If there is not a valid cached result in the manager already, this will
349   /// re-run the analysis to produce a valid result.
350   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
351     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
352                        "The analysis pass must be over a Module.");
353     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
354            "This analysis pass was not registered prior to being queried");
355
356     const detail::AnalysisResultConcept<Module> &ResultConcept =
357         getResultImpl(PassT::ID(), M);
358     typedef detail::AnalysisResultModel<Module, typename PassT::Result>
359         ResultModelT;
360     return static_cast<const ResultModelT &>(ResultConcept).Result;
361   }
362
363   /// \brief Register an analysis pass with the manager.
364   ///
365   /// This provides an initialized and set-up analysis pass to the
366   /// analysis
367   /// manager. Whomever is setting up analysis passes must use this to
368   /// populate
369   /// the manager with all of the analysis passes available.
370   template <typename PassT> void registerPass(PassT Pass) {
371     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
372                        "The analysis pass must be over a Module.");
373     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
374            "Registered the same analysis pass twice!");
375     ModuleAnalysisPasses[PassT::ID()] =
376         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
377   }
378
379   /// \brief Invalidate a specific analysis pass for an IR module.
380   ///
381   /// Note that the analysis result can disregard invalidation.
382   template <typename PassT> void invalidate(Module *M) {
383     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
384                        "The analysis pass must be over a Module.");
385     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
386            "This analysis pass was not registered prior to being invalidated");
387     invalidateImpl(PassT::ID(), M);
388   }
389
390   /// \brief Invalidate analyses cached for an IR Module.
391   ///
392   /// Walk through all of the analyses pertaining to this module and invalidate
393   /// them unless they are preserved by the PreservedAnalyses set.
394   void invalidate(Module *M, const PreservedAnalyses &PA);
395
396 private:
397   /// \brief Get a module pass result, running the pass if necessary.
398   const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
399                                                              Module *M);
400
401   /// \brief Invalidate a module pass result.
402   void invalidateImpl(void *PassID, Module *M);
403
404   /// \brief Map type from module analysis pass ID to pass concept pointer.
405   typedef DenseMap<void *,
406                    polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
407       ModuleAnalysisPassMapT;
408
409   /// \brief Collection of module analysis passes, indexed by ID.
410   ModuleAnalysisPassMapT ModuleAnalysisPasses;
411
412   /// \brief Map type from module analysis pass ID to pass result concept pointer.
413   typedef DenseMap<void *,
414                    polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
415       ModuleAnalysisResultMapT;
416
417   /// \brief Cache of computed module analysis results for this module.
418   ModuleAnalysisResultMapT ModuleAnalysisResults;
419 };
420
421 /// \brief A function analysis manager to coordinate and cache analyses run over
422 /// a module.
423 class FunctionAnalysisManager {
424 public:
425   FunctionAnalysisManager() {}
426
427   /// \brief Get the result of an analysis pass for a function.
428   ///
429   /// If there is not a valid cached result in the manager already, this will
430   /// re-run the analysis to produce a valid result.
431   template <typename PassT>
432   const typename PassT::Result &getResult(Function *F) {
433     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
434                        "The analysis pass must be over a Function.");
435     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
436            "This analysis pass was not registered prior to being queried");
437
438     const detail::AnalysisResultConcept<Function> &ResultConcept =
439         getResultImpl(PassT::ID(), F);
440     typedef detail::AnalysisResultModel<Function, typename PassT::Result>
441         ResultModelT;
442     return static_cast<const ResultModelT &>(ResultConcept).Result;
443   }
444
445   /// \brief Register an analysis pass with the manager.
446   ///
447   /// This provides an initialized and set-up analysis pass to the
448   /// analysis
449   /// manager. Whomever is setting up analysis passes must use this to
450   /// populate
451   /// the manager with all of the analysis passes available.
452   template <typename PassT> void registerPass(PassT Pass) {
453     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
454                        "The analysis pass must be over a Function.");
455     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
456            "Registered the same analysis pass twice!");
457     FunctionAnalysisPasses[PassT::ID()] =
458         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
459   }
460
461   /// \brief Invalidate a specific analysis pass for an IR module.
462   ///
463   /// Note that the analysis result can disregard invalidation.
464   template <typename PassT> void invalidate(Function *F) {
465     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
466                        "The analysis pass must be over a Function.");
467     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
468            "This analysis pass was not registered prior to being invalidated");
469     invalidateImpl(PassT::ID(), F);
470   }
471
472   /// \brief Invalidate analyses cached for an IR Function.
473   ///
474   /// Walk through all of the analyses cache for this IR function and
475   /// invalidate them unless they are preserved by the provided
476   /// PreservedAnalyses set.
477   void invalidate(Function *F, const PreservedAnalyses &PA);
478
479 private:
480   /// \brief Get a function pass result, running the pass if necessary.
481   const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
482                                                                Function *F);
483
484   /// \brief Invalidate a function pass result.
485   void invalidateImpl(void *PassID, Function *F);
486
487   /// \brief Map type from function analysis pass ID to pass concept pointer.
488   typedef DenseMap<void *,
489                    polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
490       FunctionAnalysisPassMapT;
491
492   /// \brief Collection of function analysis passes, indexed by ID.
493   FunctionAnalysisPassMapT FunctionAnalysisPasses;
494
495   /// \brief List of function analysis pass IDs and associated concept pointers.
496   ///
497   /// Requires iterators to be valid across appending new entries and arbitrary
498   /// erases. Provides both the pass ID and concept pointer such that it is
499   /// half of a bijection and provides storage for the actual result concept.
500   typedef std::list<std::pair<
501       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
502       FunctionAnalysisResultListT;
503
504   /// \brief Map type from function pointer to our custom list type.
505   typedef DenseMap<Function *, FunctionAnalysisResultListT>
506   FunctionAnalysisResultListMapT;
507
508   /// \brief Map from function to a list of function analysis results.
509   ///
510   /// Provides linear time removal of all analysis results for a function and
511   /// the ultimate storage for a particular cached analysis result.
512   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
513
514   /// \brief Map type from a pair of analysis ID and function pointer to an
515   /// iterator into a particular result list.
516   typedef DenseMap<std::pair<void *, Function *>,
517                    FunctionAnalysisResultListT::iterator>
518       FunctionAnalysisResultMapT;
519
520   /// \brief Map from an analysis ID and function to a particular cached
521   /// analysis result.
522   FunctionAnalysisResultMapT FunctionAnalysisResults;
523 };
524
525 }