[C++11] Add 'override' keyword to virtual methods that override their base class.
[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 #ifndef LLVM_IR_PASS_MANAGER_H
39 #define LLVM_IR_PASS_MANAGER_H
40
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/polymorphic_ptr.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/type_traits.h"
47 #include <list>
48 #include <vector>
49
50 namespace llvm {
51
52 class Module;
53 class Function;
54
55 /// \brief An abstract set of preserved analyses following a transformation pass
56 /// run.
57 ///
58 /// When a transformation pass is run, it can return a set of analyses whose
59 /// results were preserved by that transformation. The default set is "none",
60 /// and preserving analyses must be done explicitly.
61 ///
62 /// There is also an explicit all state which can be used (for example) when
63 /// the IR is not mutated at all.
64 class PreservedAnalyses {
65 public:
66   /// \brief Convenience factory function for the empty preserved set.
67   static PreservedAnalyses none() { return PreservedAnalyses(); }
68
69   /// \brief Construct a special preserved set that preserves all passes.
70   static PreservedAnalyses all() {
71     PreservedAnalyses PA;
72     PA.PreservedPassIDs.insert((void *)AllPassesID);
73     return PA;
74   }
75
76   PreservedAnalyses &operator=(PreservedAnalyses Arg) {
77     swap(Arg);
78     return *this;
79   }
80
81   void swap(PreservedAnalyses &Arg) {
82     PreservedPassIDs.swap(Arg.PreservedPassIDs);
83   }
84
85   /// \brief Mark a particular pass as preserved, adding it to the set.
86   template <typename PassT> void preserve() {
87     if (!areAllPreserved())
88       PreservedPassIDs.insert(PassT::ID());
89   }
90
91   /// \brief Intersect this set with another in place.
92   ///
93   /// This is a mutating operation on this preserved set, removing all
94   /// preserved passes which are not also preserved in the argument.
95   void intersect(const PreservedAnalyses &Arg) {
96     if (Arg.areAllPreserved())
97       return;
98     if (areAllPreserved()) {
99       PreservedPassIDs = Arg.PreservedPassIDs;
100       return;
101     }
102     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
103                                                 E = PreservedPassIDs.end();
104          I != E; ++I)
105       if (!Arg.PreservedPassIDs.count(*I))
106         PreservedPassIDs.erase(*I);
107   }
108
109   /// \brief Intersect this set with a temporary other set in place.
110   ///
111   /// This is a mutating operation on this preserved set, removing all
112   /// preserved passes which are not also preserved in the argument.
113   void intersect(PreservedAnalyses &&Arg) {
114     if (Arg.areAllPreserved())
115       return;
116     if (areAllPreserved()) {
117       PreservedPassIDs = std::move(Arg.PreservedPassIDs);
118       return;
119     }
120     for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
121                                                 E = PreservedPassIDs.end();
122          I != E; ++I)
123       if (!Arg.PreservedPassIDs.count(*I))
124         PreservedPassIDs.erase(*I);
125   }
126
127   /// \brief Query whether a pass is marked as preserved by this set.
128   template <typename PassT> bool preserved() const {
129     return preserved(PassT::ID());
130   }
131
132   /// \brief Query whether an abstract pass ID is marked as preserved by this
133   /// set.
134   bool preserved(void *PassID) const {
135     return PreservedPassIDs.count((void *)AllPassesID) ||
136            PreservedPassIDs.count(PassID);
137   }
138
139 private:
140   // Note that this must not be -1 or -2 as those are already used by the
141   // SmallPtrSet.
142   static const uintptr_t AllPassesID = (intptr_t)-3;
143
144   bool areAllPreserved() const { return PreservedPassIDs.count((void *)AllPassesID); }
145
146   SmallPtrSet<void *, 2> PreservedPassIDs;
147 };
148
149 inline void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
150   LHS.swap(RHS);
151 }
152
153 /// \brief Implementation details of the pass manager interfaces.
154 namespace detail {
155
156 /// \brief Template for the abstract base class used to dispatch
157 /// polymorphically over pass objects.
158 template <typename IRUnitT, typename AnalysisManagerT> struct PassConcept {
159   // Boiler plate necessary for the container of derived classes.
160   virtual ~PassConcept() {}
161   virtual PassConcept *clone() = 0;
162
163   /// \brief The polymorphic API which runs the pass over a given IR entity.
164   ///
165   /// Note that actual pass object can omit the analysis manager argument if
166   /// desired. Also that the analysis manager may be null if there is no
167   /// analysis manager in the pass pipeline.
168   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) = 0;
169
170   /// \brief Polymorphic method to access the name of a pass.
171   virtual StringRef name() = 0;
172 };
173
174 /// \brief SFINAE metafunction for computing whether \c PassT has a run method
175 /// accepting an \c AnalysisManagerT.
176 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
177           typename ResultT>
178 class PassRunAcceptsAnalysisManager {
179   typedef char SmallType;
180   struct BigType { char a, b; };
181
182   template <typename T, ResultT (T::*)(IRUnitT, AnalysisManagerT *)>
183   struct Checker;
184
185   template <typename T> static SmallType f(Checker<T, &T::run> *);
186   template <typename T> static BigType f(...);
187
188 public:
189   enum { Value = sizeof(f<PassT>(0)) == sizeof(SmallType) };
190 };
191
192 /// \brief A template wrapper used to implement the polymorphic API.
193 ///
194 /// Can be instantiated for any object which provides a \c run method accepting
195 /// an \c IRUnitT. It requires the pass to be a copyable object. When the
196 /// \c run method also accepts an \c AnalysisManagerT*, we pass it along.
197 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
198           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
199               IRUnitT, AnalysisManagerT, PassT, PreservedAnalyses>::Value>
200 struct PassModel;
201
202 /// \brief Specialization of \c PassModel for passes that accept an analyis
203 /// manager.
204 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
205 struct PassModel<IRUnitT, AnalysisManagerT, PassT,
206                  true> : PassConcept<IRUnitT, AnalysisManagerT> {
207   PassModel(PassT Pass) : Pass(std::move(Pass)) {}
208   virtual PassModel *clone() { return new PassModel(Pass); }
209   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
210     return Pass.run(IR, AM);
211   }
212   virtual StringRef name() { return PassT::name(); }
213   PassT Pass;
214 };
215
216 /// \brief Specialization of \c PassModel for passes that accept an analyis
217 /// manager.
218 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
219 struct PassModel<IRUnitT, AnalysisManagerT, PassT,
220                  false> : PassConcept<IRUnitT, AnalysisManagerT> {
221   PassModel(PassT Pass) : Pass(std::move(Pass)) {}
222   virtual PassModel *clone() { return new PassModel(Pass); }
223   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
224     return Pass.run(IR);
225   }
226   virtual StringRef name() { return PassT::name(); }
227   PassT Pass;
228 };
229
230 /// \brief Abstract concept of an analysis result.
231 ///
232 /// This concept is parameterized over the IR unit that this result pertains
233 /// to.
234 template <typename IRUnitT> struct AnalysisResultConcept {
235   virtual ~AnalysisResultConcept() {}
236   virtual AnalysisResultConcept *clone() = 0;
237
238   /// \brief Method to try and mark a result as invalid.
239   ///
240   /// When the outer analysis manager detects a change in some underlying
241   /// unit of the IR, it will call this method on all of the results cached.
242   ///
243   /// This method also receives a set of preserved analyses which can be used
244   /// to avoid invalidation because the pass which changed the underlying IR
245   /// took care to update or preserve the analysis result in some way.
246   ///
247   /// \returns true if the result is indeed invalid (the default).
248   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) = 0;
249 };
250
251 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
252 /// \c invalidate member function.
253 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
254   typedef char SmallType;
255   struct BigType { char a, b; };
256
257   template <typename T, bool (T::*)(IRUnitT, const PreservedAnalyses &)>
258   struct Checker;
259
260   template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
261   template <typename T> static BigType f(...);
262
263 public:
264   enum { Value = sizeof(f<ResultT>(0)) == sizeof(SmallType) };
265 };
266
267 /// \brief Wrapper to model the analysis result concept.
268 ///
269 /// By default, this will implement the invalidate method with a trivial
270 /// implementation so that the actual analysis result doesn't need to provide
271 /// an invalidation handler. It is only selected when the invalidation handler
272 /// is not part of the ResultT's interface.
273 template <typename IRUnitT, typename PassT, typename ResultT,
274           bool HasInvalidateHandler =
275               ResultHasInvalidateMethod<IRUnitT, ResultT>::Value>
276 struct AnalysisResultModel;
277
278 /// \brief Specialization of \c AnalysisResultModel which provides the default
279 /// invalidate functionality.
280 template <typename IRUnitT, typename PassT, typename ResultT>
281 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
282                            false> : AnalysisResultConcept<IRUnitT> {
283   AnalysisResultModel(ResultT Result) : Result(std::move(Result)) {}
284   AnalysisResultModel *clone() override {
285     return new AnalysisResultModel(Result);
286   }
287
288   /// \brief The model bases invalidation solely on being in the preserved set.
289   //
290   // FIXME: We should actually use two different concepts for analysis results
291   // rather than two different models, and avoid the indirect function call for
292   // ones that use the trivial behavior.
293   bool invalidate(IRUnitT, const PreservedAnalyses &PA) override {
294     return !PA.preserved(PassT::ID());
295   }
296
297   ResultT Result;
298 };
299
300 /// \brief Specialization of \c AnalysisResultModel which delegates invalidate
301 /// handling to \c ResultT.
302 template <typename IRUnitT, typename PassT, typename ResultT>
303 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
304                            true> : AnalysisResultConcept<IRUnitT> {
305   AnalysisResultModel(ResultT Result) : Result(std::move(Result)) {}
306   virtual AnalysisResultModel *clone() {
307     return new AnalysisResultModel(Result);
308   }
309
310   /// \brief The model delegates to the \c ResultT method.
311   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
312     return Result.invalidate(IR, PA);
313   }
314
315   ResultT Result;
316 };
317
318 /// \brief Abstract concept of an analysis pass.
319 ///
320 /// This concept is parameterized over the IR unit that it can run over and
321 /// produce an analysis result.
322 template <typename IRUnitT, typename AnalysisManagerT>
323 struct AnalysisPassConcept {
324   virtual ~AnalysisPassConcept() {}
325   virtual AnalysisPassConcept *clone() = 0;
326
327   /// \brief Method to run this analysis over a unit of IR.
328   /// \returns The analysis result object to be queried by users, the caller
329   /// takes ownership.
330   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT IR,
331                                               AnalysisManagerT *AM) = 0;
332 };
333
334 /// \brief Wrapper to model the analysis pass concept.
335 ///
336 /// Can wrap any type which implements a suitable \c run method. The method
337 /// must accept the IRUnitT as an argument and produce an object which can be
338 /// wrapped in a \c AnalysisResultModel.
339 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
340           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
341               IRUnitT, AnalysisManagerT, PassT,
342               typename PassT::Result>::Value> struct AnalysisPassModel;
343
344 /// \brief Specialization of \c AnalysisPassModel which passes an
345 /// \c AnalysisManager to PassT's run method.
346 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
347 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT,
348                          true> : AnalysisPassConcept<IRUnitT,
349                                                      AnalysisManagerT> {
350   AnalysisPassModel(PassT Pass) : Pass(std::move(Pass)) {}
351   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
352
353   // FIXME: Replace PassT::Result with type traits when we use C++11.
354   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
355       ResultModelT;
356
357   /// \brief The model delegates to the \c PassT::run method.
358   ///
359   /// The return is wrapped in an \c AnalysisResultModel.
360   virtual ResultModelT *run(IRUnitT IR, AnalysisManagerT *AM) {
361     return new ResultModelT(Pass.run(IR, AM));
362   }
363
364   PassT Pass;
365 };
366
367 /// \brief Specialization of \c AnalysisPassModel which does not pass an
368 /// \c AnalysisManager to PassT's run method.
369 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
370 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT,
371                          false> : AnalysisPassConcept<IRUnitT,
372                                                      AnalysisManagerT> {
373   AnalysisPassModel(PassT Pass) : Pass(std::move(Pass)) {}
374   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
375
376   // FIXME: Replace PassT::Result with type traits when we use C++11.
377   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
378       ResultModelT;
379
380   /// \brief The model delegates to the \c PassT::run method.
381   ///
382   /// The return is wrapped in an \c AnalysisResultModel.
383   virtual ResultModelT *run(IRUnitT IR, AnalysisManagerT *) {
384     return new ResultModelT(Pass.run(IR));
385   }
386
387   PassT Pass;
388 };
389
390 }
391
392 class ModuleAnalysisManager;
393
394 class ModulePassManager {
395 public:
396   explicit ModulePassManager() {}
397
398   /// \brief Run all of the module passes in this module pass manager over
399   /// a module.
400   ///
401   /// This method should only be called for a single module as there is the
402   /// expectation that the lifetime of a pass is bounded to that of a module.
403   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM = 0);
404
405   template <typename ModulePassT> void addPass(ModulePassT Pass) {
406     Passes.push_back(new ModulePassModel<ModulePassT>(std::move(Pass)));
407   }
408
409   static StringRef name() { return "ModulePassManager"; }
410
411 private:
412   // Pull in the concept type and model template specialized for modules.
413   typedef detail::PassConcept<Module *, ModuleAnalysisManager> ModulePassConcept;
414   template <typename PassT>
415   struct ModulePassModel
416       : detail::PassModel<Module *, ModuleAnalysisManager, PassT> {
417     ModulePassModel(PassT Pass)
418         : detail::PassModel<Module *, ModuleAnalysisManager, PassT>(Pass) {}
419   };
420
421   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
422 };
423
424 class FunctionAnalysisManager;
425
426 class FunctionPassManager {
427 public:
428   explicit FunctionPassManager() {}
429
430   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
431     Passes.push_back(new FunctionPassModel<FunctionPassT>(std::move(Pass)));
432   }
433
434   PreservedAnalyses run(Function *F, FunctionAnalysisManager *AM = 0);
435
436   static StringRef name() { return "FunctionPassManager"; }
437
438 private:
439   // Pull in the concept type and model template specialized for functions.
440   typedef detail::PassConcept<Function *, FunctionAnalysisManager>
441       FunctionPassConcept;
442   template <typename PassT>
443   struct FunctionPassModel
444       : detail::PassModel<Function *, FunctionAnalysisManager, PassT> {
445     FunctionPassModel(PassT Pass)
446         : detail::PassModel<Function *, FunctionAnalysisManager, PassT>(Pass) {}
447   };
448
449   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
450 };
451
452 namespace detail {
453
454 /// \brief A CRTP base used to implement analysis managers.
455 ///
456 /// This class template serves as the boiler plate of an analysis manager. Any
457 /// analysis manager can be implemented on top of this base class. Any
458 /// implementation will be required to provide specific hooks:
459 ///
460 /// - getResultImpl
461 /// - getCachedResultImpl
462 /// - invalidateImpl
463 ///
464 /// The details of the call pattern are within.
465 template <typename DerivedT, typename IRUnitT>
466 class AnalysisManagerBase {
467   DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
468   const DerivedT *derived_this() const { return static_cast<const DerivedT *>(this); }
469
470 protected:
471   typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
472   typedef detail::AnalysisPassConcept<IRUnitT, DerivedT> PassConceptT;
473
474   // FIXME: Provide template aliases for the models when we're using C++11 in
475   // a mode supporting them.
476
477 public:
478   /// \brief Get the result of an analysis pass for this module.
479   ///
480   /// If there is not a valid cached result in the manager already, this will
481   /// re-run the analysis to produce a valid result.
482   template <typename PassT> typename PassT::Result &getResult(IRUnitT IR) {
483     assert(AnalysisPasses.count(PassT::ID()) &&
484            "This analysis pass was not registered prior to being queried");
485
486     ResultConceptT &ResultConcept =
487         derived_this()->getResultImpl(PassT::ID(), IR);
488     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
489         ResultModelT;
490     return static_cast<ResultModelT &>(ResultConcept).Result;
491   }
492
493   /// \brief Get the cached result of an analysis pass for this module.
494   ///
495   /// This method never runs the analysis.
496   ///
497   /// \returns null if there is no cached result.
498   template <typename PassT>
499   typename PassT::Result *getCachedResult(IRUnitT IR) const {
500     assert(AnalysisPasses.count(PassT::ID()) &&
501            "This analysis pass was not registered prior to being queried");
502
503     ResultConceptT *ResultConcept =
504         derived_this()->getCachedResultImpl(PassT::ID(), IR);
505     if (!ResultConcept)
506       return 0;
507
508     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
509         ResultModelT;
510     return &static_cast<ResultModelT *>(ResultConcept)->Result;
511   }
512
513   /// \brief Register an analysis pass with the manager.
514   ///
515   /// This provides an initialized and set-up analysis pass to the analysis
516   /// manager. Whomever is setting up analysis passes must use this to populate
517   /// the manager with all of the analysis passes available.
518   template <typename PassT> void registerPass(PassT Pass) {
519     assert(!AnalysisPasses.count(PassT::ID()) &&
520            "Registered the same analysis pass twice!");
521     typedef detail::AnalysisPassModel<IRUnitT, DerivedT, PassT> PassModelT;
522     AnalysisPasses[PassT::ID()] = new PassModelT(std::move(Pass));
523   }
524
525   /// \brief Invalidate a specific analysis pass for an IR module.
526   ///
527   /// Note that the analysis result can disregard invalidation.
528   template <typename PassT> void invalidate(Module *M) {
529     assert(AnalysisPasses.count(PassT::ID()) &&
530            "This analysis pass was not registered prior to being invalidated");
531     derived_this()->invalidateImpl(PassT::ID(), M);
532   }
533
534   /// \brief Invalidate analyses cached for an IR unit.
535   ///
536   /// Walk through all of the analyses pertaining to this unit of IR and
537   /// invalidate them unless they are preserved by the PreservedAnalyses set.
538   void invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
539     derived_this()->invalidateImpl(IR, PA);
540   }
541
542 protected:
543   /// \brief Lookup a registered analysis pass.
544   PassConceptT &lookupPass(void *PassID) {
545     typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
546     assert(PI != AnalysisPasses.end() &&
547            "Analysis passes must be registered prior to being queried!");
548     return *PI->second;
549   }
550
551   /// \brief Lookup a registered analysis pass.
552   const PassConceptT &lookupPass(void *PassID) const {
553     typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
554     assert(PI != AnalysisPasses.end() &&
555            "Analysis passes must be registered prior to being queried!");
556     return *PI->second;
557   }
558
559 private:
560   /// \brief Map type from module analysis pass ID to pass concept pointer.
561   typedef DenseMap<void *, polymorphic_ptr<PassConceptT> > AnalysisPassMapT;
562
563   /// \brief Collection of module analysis passes, indexed by ID.
564   AnalysisPassMapT AnalysisPasses;
565 };
566
567 }
568
569 /// \brief A module analysis pass manager with lazy running and caching of
570 /// results.
571 class ModuleAnalysisManager
572     : public detail::AnalysisManagerBase<ModuleAnalysisManager, Module *> {
573   friend class detail::AnalysisManagerBase<ModuleAnalysisManager, Module *>;
574   typedef detail::AnalysisManagerBase<ModuleAnalysisManager, Module *> BaseT;
575   typedef BaseT::ResultConceptT ResultConceptT;
576   typedef BaseT::PassConceptT PassConceptT;
577
578 public:
579   // Public methods provided by the base class.
580
581 private:
582   /// \brief Get a module pass result, running the pass if necessary.
583   ResultConceptT &getResultImpl(void *PassID, Module *M);
584
585   /// \brief Get a cached module pass result or return null.
586   ResultConceptT *getCachedResultImpl(void *PassID, Module *M) const;
587
588   /// \brief Invalidate a module pass result.
589   void invalidateImpl(void *PassID, Module *M);
590
591   /// \brief Invalidate results across a module.
592   void invalidateImpl(Module *M, const PreservedAnalyses &PA);
593
594   /// \brief Map type from module analysis pass ID to pass result concept pointer.
595   typedef DenseMap<void *,
596                    polymorphic_ptr<detail::AnalysisResultConcept<Module *> > >
597       ModuleAnalysisResultMapT;
598
599   /// \brief Cache of computed module analysis results for this module.
600   ModuleAnalysisResultMapT ModuleAnalysisResults;
601 };
602
603 /// \brief A function analysis manager to coordinate and cache analyses run over
604 /// a module.
605 class FunctionAnalysisManager
606     : public detail::AnalysisManagerBase<FunctionAnalysisManager, Function *> {
607   friend class detail::AnalysisManagerBase<FunctionAnalysisManager, Function *>;
608   typedef detail::AnalysisManagerBase<FunctionAnalysisManager, Function *> BaseT;
609   typedef BaseT::ResultConceptT ResultConceptT;
610   typedef BaseT::PassConceptT PassConceptT;
611
612 public:
613   // Most public APIs are inherited from the CRTP base class.
614
615   /// \brief Returns true if the analysis manager has an empty results cache.
616   bool empty() const;
617
618   /// \brief Clear the function analysis result cache.
619   ///
620   /// This routine allows cleaning up when the set of functions itself has
621   /// potentially changed, and thus we can't even look up a a result and
622   /// invalidate it directly. Notably, this does *not* call invalidate
623   /// functions as there is nothing to be done for them.
624   void clear();
625
626 private:
627   /// \brief Get a function pass result, running the pass if necessary.
628   ResultConceptT &getResultImpl(void *PassID, Function *F);
629
630   /// \brief Get a cached function pass result or return null.
631   ResultConceptT *getCachedResultImpl(void *PassID, Function *F) const;
632
633   /// \brief Invalidate a function pass result.
634   void invalidateImpl(void *PassID, Function *F);
635
636   /// \brief Invalidate the results for a function..
637   void invalidateImpl(Function *F, const PreservedAnalyses &PA);
638
639   /// \brief List of function analysis pass IDs and associated concept pointers.
640   ///
641   /// Requires iterators to be valid across appending new entries and arbitrary
642   /// erases. Provides both the pass ID and concept pointer such that it is
643   /// half of a bijection and provides storage for the actual result concept.
644   typedef std::list<std::pair<
645       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function *> > > >
646       FunctionAnalysisResultListT;
647
648   /// \brief Map type from function pointer to our custom list type.
649   typedef DenseMap<Function *, FunctionAnalysisResultListT>
650   FunctionAnalysisResultListMapT;
651
652   /// \brief Map from function to a list of function analysis results.
653   ///
654   /// Provides linear time removal of all analysis results for a function and
655   /// the ultimate storage for a particular cached analysis result.
656   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
657
658   /// \brief Map type from a pair of analysis ID and function pointer to an
659   /// iterator into a particular result list.
660   typedef DenseMap<std::pair<void *, Function *>,
661                    FunctionAnalysisResultListT::iterator>
662       FunctionAnalysisResultMapT;
663
664   /// \brief Map from an analysis ID and function to a particular cached
665   /// analysis result.
666   FunctionAnalysisResultMapT FunctionAnalysisResults;
667 };
668
669 /// \brief A module analysis which acts as a proxy for a function analysis
670 /// manager.
671 ///
672 /// This primarily proxies invalidation information from the module analysis
673 /// manager and module pass manager to a function analysis manager. You should
674 /// never use a function analysis manager from within (transitively) a module
675 /// pass manager unless your parent module pass has received a proxy result
676 /// object for it.
677 class FunctionAnalysisManagerModuleProxy {
678 public:
679   class Result;
680
681   static void *ID() { return (void *)&PassID; }
682
683   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
684
685   /// \brief Run the analysis pass and create our proxy result object.
686   ///
687   /// This doesn't do any interesting work, it is primarily used to insert our
688   /// proxy result object into the module analysis cache so that we can proxy
689   /// invalidation to the function analysis manager.
690   ///
691   /// In debug builds, it will also assert that the analysis manager is empty
692   /// as no queries should arrive at the function analysis manager prior to
693   /// this analysis being requested.
694   Result run(Module *M);
695
696 private:
697   static char PassID;
698
699   FunctionAnalysisManager &FAM;
700 };
701
702 /// \brief The result proxy object for the
703 /// \c FunctionAnalysisManagerModuleProxy.
704 ///
705 /// See its documentation for more information.
706 class FunctionAnalysisManagerModuleProxy::Result {
707 public:
708   Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
709   ~Result();
710
711   /// \brief Accessor for the \c FunctionAnalysisManager.
712   FunctionAnalysisManager &getManager() { return FAM; }
713
714   /// \brief Handler for invalidation of the module.
715   ///
716   /// If this analysis itself is preserved, then we assume that the set of \c
717   /// Function objects in the \c Module hasn't changed and thus we don't need
718   /// to invalidate *all* cached data associated with a \c Function* in the \c
719   /// FunctionAnalysisManager.
720   ///
721   /// Regardless of whether this analysis is marked as preserved, all of the
722   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
723   /// based on the set of preserved analyses.
724   bool invalidate(Module *M, const PreservedAnalyses &PA);
725
726 private:
727   FunctionAnalysisManager &FAM;
728 };
729
730 /// \brief A function analysis which acts as a proxy for a module analysis
731 /// manager.
732 ///
733 /// This primarily provides an accessor to a parent module analysis manager to
734 /// function passes. Only the const interface of the module analysis manager is
735 /// provided to indicate that once inside of a function analysis pass you
736 /// cannot request a module analysis to actually run. Instead, the user must
737 /// rely on the \c getCachedResult API.
738 ///
739 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
740 /// the recursive return path of each layer of the pass manager and the
741 /// returned PreservedAnalysis set.
742 class ModuleAnalysisManagerFunctionProxy {
743 public:
744   /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
745   class Result {
746   public:
747     Result(const ModuleAnalysisManager &MAM) : MAM(MAM) {}
748
749     const ModuleAnalysisManager &getManager() const { return MAM; }
750
751     /// \brief Handle invalidation by ignoring it, this pass is immutable.
752     bool invalidate(Function *) { return false; }
753
754   private:
755     const ModuleAnalysisManager &MAM;
756   };
757
758   static void *ID() { return (void *)&PassID; }
759
760   ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
761       : MAM(MAM) {}
762
763   /// \brief Run the analysis pass and create our proxy result object.
764   /// Nothing to see here, it just forwards the \c MAM reference into the
765   /// result.
766   Result run(Function *) { return Result(MAM); }
767
768 private:
769   static char PassID;
770
771   const ModuleAnalysisManager &MAM;
772 };
773
774 /// \brief Trivial adaptor that maps from a module to its functions.
775 ///
776 /// Designed to allow composition of a FunctionPass(Manager) and
777 /// a ModulePassManager. Note that if this pass is constructed with a pointer
778 /// to a \c ModuleAnalysisManager it will run the
779 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
780 /// pass over the module to enable a \c FunctionAnalysisManager to be used
781 /// within this run safely.
782 template <typename FunctionPassT>
783 class ModuleToFunctionPassAdaptor {
784 public:
785   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
786       : Pass(std::move(Pass)) {}
787
788   /// \brief Runs the function pass across every function in the module.
789   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM) {
790     FunctionAnalysisManager *FAM = 0;
791     if (AM)
792       // Setup the function analysis manager from its proxy.
793       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
794
795     PreservedAnalyses PA = PreservedAnalyses::all();
796     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
797       PreservedAnalyses PassPA = Pass.run(I, FAM);
798
799       // We know that the function pass couldn't have invalidated any other
800       // function's analyses (that's the contract of a function pass), so
801       // directly handle the function analysis manager's invalidation here.
802       if (FAM)
803         FAM->invalidate(I, PassPA);
804
805       // Then intersect the preserved set so that invalidation of module
806       // analyses will eventually occur when the module pass completes.
807       PA.intersect(std::move(PassPA));
808     }
809
810     // By definition we preserve the proxy. This precludes *any* invalidation
811     // of function analyses by the proxy, but that's OK because we've taken
812     // care to invalidate analyses in the function analysis manager
813     // incrementally above.
814     PA.preserve<FunctionAnalysisManagerModuleProxy>();
815     return PA;
816   }
817
818   static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
819
820 private:
821   FunctionPassT Pass;
822 };
823
824 /// \brief A function to deduce a function pass type and wrap it in the
825 /// templated adaptor.
826 template <typename FunctionPassT>
827 ModuleToFunctionPassAdaptor<FunctionPassT>
828 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
829   return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
830 }
831
832 }
833
834 #endif