d6e97419def19785c25fbfb05244c7326c4a10ff
[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 IRUnitT, typename AnalysisManagerT> 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   ///
164   /// Note that actual pass object can omit the analysis manager argument if
165   /// desired. Also that the analysis manager may be null if there is no
166   /// analysis manager in the pass pipeline.
167   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) = 0;
168 };
169
170 /// \brief SFINAE metafunction for computing whether \c PassT has a run method
171 /// accepting an \c AnalysisManagerT.
172 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
173           typename ResultT>
174 class PassRunAcceptsAnalysisManager {
175   typedef char SmallType;
176   struct BigType { char a, b; };
177
178   template <typename T, ResultT (T::*)(IRUnitT, AnalysisManagerT *)>
179   struct Checker;
180
181   template <typename T> static SmallType f(Checker<T, &T::run> *);
182   template <typename T> static BigType f(...);
183
184 public:
185   enum { Value = sizeof(f<PassT>(0)) == sizeof(SmallType) };
186 };
187
188 /// \brief A template wrapper used to implement the polymorphic API.
189 ///
190 /// Can be instantiated for any object which provides a \c run method accepting
191 /// an \c IRUnitT. It requires the pass to be a copyable object. When the
192 /// \c run method also accepts an \c AnalysisManagerT*, we pass it along.
193 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
194           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
195               IRUnitT, AnalysisManagerT, PassT, PreservedAnalyses>::Value>
196 struct PassModel;
197
198 /// \brief Specialization of \c PassModel for passes that accept an analyis
199 /// manager.
200 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
201 struct PassModel<IRUnitT, AnalysisManagerT, PassT,
202                  true> : PassConcept<IRUnitT, AnalysisManagerT> {
203   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
204   virtual PassModel *clone() { return new PassModel(Pass); }
205   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
206     return Pass.run(IR, AM);
207   }
208   PassT Pass;
209 };
210
211 /// \brief Specialization of \c PassModel for passes that accept an analyis
212 /// manager.
213 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
214 struct PassModel<IRUnitT, AnalysisManagerT, PassT,
215                  false> : PassConcept<IRUnitT, AnalysisManagerT> {
216   PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
217   virtual PassModel *clone() { return new PassModel(Pass); }
218   virtual PreservedAnalyses run(IRUnitT IR, AnalysisManagerT *AM) {
219     return Pass.run(IR);
220   }
221   PassT Pass;
222 };
223
224 /// \brief Abstract concept of an analysis result.
225 ///
226 /// This concept is parameterized over the IR unit that this result pertains
227 /// to.
228 template <typename IRUnitT> struct AnalysisResultConcept {
229   virtual ~AnalysisResultConcept() {}
230   virtual AnalysisResultConcept *clone() = 0;
231
232   /// \brief Method to try and mark a result as invalid.
233   ///
234   /// When the outer analysis manager detects a change in some underlying
235   /// unit of the IR, it will call this method on all of the results cached.
236   ///
237   /// This method also receives a set of preserved analyses which can be used
238   /// to avoid invalidation because the pass which changed the underlying IR
239   /// took care to update or preserve the analysis result in some way.
240   ///
241   /// \returns true if the result is indeed invalid (the default).
242   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) = 0;
243 };
244
245 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
246 /// \c invalidate member function.
247 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
248   typedef char SmallType;
249   struct BigType { char a, b; };
250
251   template <typename T, bool (T::*)(IRUnitT, const PreservedAnalyses &)>
252   struct Checker;
253
254   template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
255   template <typename T> static BigType f(...);
256
257 public:
258   enum { Value = sizeof(f<ResultT>(0)) == sizeof(SmallType) };
259 };
260
261 /// \brief Wrapper to model the analysis result concept.
262 ///
263 /// By default, this will implement the invalidate method with a trivial
264 /// implementation so that the actual analysis result doesn't need to provide
265 /// an invalidation handler. It is only selected when the invalidation handler
266 /// is not part of the ResultT's interface.
267 template <typename IRUnitT, typename PassT, typename ResultT,
268           bool HasInvalidateHandler =
269               ResultHasInvalidateMethod<IRUnitT, ResultT>::Value>
270 struct AnalysisResultModel;
271
272 /// \brief Specialization of \c AnalysisResultModel which provides the default
273 /// invalidate functionality.
274 template <typename IRUnitT, typename PassT, typename ResultT>
275 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
276                            false> : AnalysisResultConcept<IRUnitT> {
277   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
278   virtual AnalysisResultModel *clone() {
279     return new AnalysisResultModel(Result);
280   }
281
282   /// \brief The model bases invalidation solely on being in the preserved set.
283   //
284   // FIXME: We should actually use two different concepts for analysis results
285   // rather than two different models, and avoid the indirect function call for
286   // ones that use the trivial behavior.
287   virtual bool invalidate(IRUnitT, const PreservedAnalyses &PA) {
288     return !PA.preserved(PassT::ID());
289   }
290
291   ResultT Result;
292 };
293
294 /// \brief Specialization of \c AnalysisResultModel which delegates invalidate
295 /// handling to \c ResultT.
296 template <typename IRUnitT, typename PassT, typename ResultT>
297 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
298                            true> : AnalysisResultConcept<IRUnitT> {
299   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
300   virtual AnalysisResultModel *clone() {
301     return new AnalysisResultModel(Result);
302   }
303
304   /// \brief The model delegates to the \c ResultT method.
305   virtual bool invalidate(IRUnitT IR, const PreservedAnalyses &PA) {
306     return Result.invalidate(IR, PA);
307   }
308
309   ResultT Result;
310 };
311
312 /// \brief Abstract concept of an analysis pass.
313 ///
314 /// This concept is parameterized over the IR unit that it can run over and
315 /// produce an analysis result.
316 template <typename IRUnitT, typename AnalysisManagerT>
317 struct AnalysisPassConcept {
318   virtual ~AnalysisPassConcept() {}
319   virtual AnalysisPassConcept *clone() = 0;
320
321   /// \brief Method to run this analysis over a unit of IR.
322   /// \returns The analysis result object to be queried by users, the caller
323   /// takes ownership.
324   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT IR,
325                                               AnalysisManagerT *AM) = 0;
326 };
327
328 /// \brief Wrapper to model the analysis pass concept.
329 ///
330 /// Can wrap any type which implements a suitable \c run method. The method
331 /// must accept the IRUnitT as an argument and produce an object which can be
332 /// wrapped in a \c AnalysisResultModel.
333 template <typename IRUnitT, typename AnalysisManagerT, typename PassT,
334           bool AcceptsAnalysisManager = PassRunAcceptsAnalysisManager<
335               IRUnitT, AnalysisManagerT, PassT,
336               typename PassT::Result>::Value> struct AnalysisPassModel;
337
338 /// \brief Specialization of \c AnalysisPassModel which passes an
339 /// \c AnalysisManager to PassT's run method.
340 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
341 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT,
342                          true> : AnalysisPassConcept<IRUnitT,
343                                                      AnalysisManagerT> {
344   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
345   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
346
347   // FIXME: Replace PassT::Result with type traits when we use C++11.
348   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
349       ResultModelT;
350
351   /// \brief The model delegates to the \c PassT::run method.
352   ///
353   /// The return is wrapped in an \c AnalysisResultModel.
354   virtual ResultModelT *run(IRUnitT IR, AnalysisManagerT *AM) {
355     return new ResultModelT(Pass.run(IR, AM));
356   }
357
358   PassT Pass;
359 };
360
361 /// \brief Specialization of \c AnalysisPassModel which does not pass an
362 /// \c AnalysisManager to PassT's run method.
363 template <typename IRUnitT, typename AnalysisManagerT, typename PassT>
364 struct AnalysisPassModel<IRUnitT, AnalysisManagerT, PassT,
365                          false> : AnalysisPassConcept<IRUnitT,
366                                                      AnalysisManagerT> {
367   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
368   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
369
370   // FIXME: Replace PassT::Result with type traits when we use C++11.
371   typedef AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
372       ResultModelT;
373
374   /// \brief The model delegates to the \c PassT::run method.
375   ///
376   /// The return is wrapped in an \c AnalysisResultModel.
377   virtual ResultModelT *run(IRUnitT IR, AnalysisManagerT *) {
378     return new ResultModelT(Pass.run(IR));
379   }
380
381   PassT Pass;
382 };
383
384 }
385
386 class ModuleAnalysisManager;
387
388 class ModulePassManager {
389 public:
390   explicit ModulePassManager() {}
391
392   /// \brief Run all of the module passes in this module pass manager over
393   /// a module.
394   ///
395   /// This method should only be called for a single module as there is the
396   /// expectation that the lifetime of a pass is bounded to that of a module.
397   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM = 0);
398
399   template <typename ModulePassT> void addPass(ModulePassT Pass) {
400     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
401   }
402
403 private:
404   // Pull in the concept type and model template specialized for modules.
405   typedef detail::PassConcept<Module *, ModuleAnalysisManager> ModulePassConcept;
406   template <typename PassT>
407   struct ModulePassModel
408       : detail::PassModel<Module *, ModuleAnalysisManager, PassT> {
409     ModulePassModel(PassT Pass)
410         : detail::PassModel<Module *, ModuleAnalysisManager, PassT>(Pass) {}
411   };
412
413   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
414 };
415
416 class FunctionAnalysisManager;
417
418 class FunctionPassManager {
419 public:
420   explicit FunctionPassManager() {}
421
422   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
423     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
424   }
425
426   PreservedAnalyses run(Function *F, FunctionAnalysisManager *AM = 0);
427
428 private:
429   // Pull in the concept type and model template specialized for functions.
430   typedef detail::PassConcept<Function *, FunctionAnalysisManager>
431       FunctionPassConcept;
432   template <typename PassT>
433   struct FunctionPassModel
434       : detail::PassModel<Function *, FunctionAnalysisManager, PassT> {
435     FunctionPassModel(PassT Pass)
436         : detail::PassModel<Function *, FunctionAnalysisManager, PassT>(Pass) {}
437   };
438
439   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
440 };
441
442 /// \brief A module analysis pass manager with lazy running and caching of
443 /// results.
444 class ModuleAnalysisManager {
445 public:
446   ModuleAnalysisManager() {}
447
448   /// \brief Get the result of an analysis pass for this module.
449   ///
450   /// If there is not a valid cached result in the manager already, this will
451   /// re-run the analysis to produce a valid result.
452   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
453     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
454            "This analysis pass was not registered prior to being queried");
455
456     const detail::AnalysisResultConcept<Module *> &ResultConcept =
457         getResultImpl(PassT::ID(), M);
458     typedef detail::AnalysisResultModel<Module *, PassT, typename PassT::Result>
459         ResultModelT;
460     return static_cast<const ResultModelT &>(ResultConcept).Result;
461   }
462
463   /// \brief Get the cached result of an analysis pass for this module.
464   ///
465   /// This method never runs the analysis.
466   ///
467   /// \returns null if there is no cached result.
468   template <typename PassT>
469   const typename PassT::Result *getCachedResult(Module *M) const {
470     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
471            "This analysis pass was not registered prior to being queried");
472
473     const detail::AnalysisResultConcept<Module *> *ResultConcept =
474         getCachedResultImpl(PassT::ID(), M);
475     if (!ResultConcept)
476       return 0;
477
478     typedef detail::AnalysisResultModel<Module *, PassT, typename PassT::Result>
479         ResultModelT;
480     return &static_cast<const ResultModelT *>(ResultConcept)->Result;
481   }
482
483   /// \brief Register an analysis pass with the manager.
484   ///
485   /// This provides an initialized and set-up analysis pass to the
486   /// analysis
487   /// manager. Whomever is setting up analysis passes must use this to
488   /// populate
489   /// the manager with all of the analysis passes available.
490   template <typename PassT> void registerPass(PassT Pass) {
491     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
492            "Registered the same analysis pass twice!");
493     ModuleAnalysisPasses[PassT::ID()] =
494         new detail::AnalysisPassModel<Module *, ModuleAnalysisManager, PassT>(
495             llvm_move(Pass));
496   }
497
498   /// \brief Invalidate a specific analysis pass for an IR module.
499   ///
500   /// Note that the analysis result can disregard invalidation.
501   template <typename PassT> void invalidate(Module *M) {
502     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
503            "This analysis pass was not registered prior to being invalidated");
504     invalidateImpl(PassT::ID(), M);
505   }
506
507   /// \brief Invalidate analyses cached for an IR Module.
508   ///
509   /// Walk through all of the analyses pertaining to this module and invalidate
510   /// them unless they are preserved by the PreservedAnalyses set.
511   void invalidate(Module *M, const PreservedAnalyses &PA);
512
513 private:
514   /// \brief Get a module pass result, running the pass if necessary.
515   const detail::AnalysisResultConcept<Module *> &getResultImpl(void *PassID,
516                                                                Module *M);
517
518   /// \brief Get a cached module pass result or return null.
519   const detail::AnalysisResultConcept<Module *> *
520   getCachedResultImpl(void *PassID, Module *M) const;
521
522   /// \brief Invalidate a module pass result.
523   void invalidateImpl(void *PassID, Module *M);
524
525   /// \brief Map type from module analysis pass ID to pass concept pointer.
526   typedef DenseMap<void *, polymorphic_ptr<detail::AnalysisPassConcept<
527                                Module *, ModuleAnalysisManager> > >
528       ModuleAnalysisPassMapT;
529
530   /// \brief Collection of module analysis passes, indexed by ID.
531   ModuleAnalysisPassMapT ModuleAnalysisPasses;
532
533   /// \brief Map type from module analysis pass ID to pass result concept pointer.
534   typedef DenseMap<void *,
535                    polymorphic_ptr<detail::AnalysisResultConcept<Module *> > >
536       ModuleAnalysisResultMapT;
537
538   /// \brief Cache of computed module analysis results for this module.
539   ModuleAnalysisResultMapT ModuleAnalysisResults;
540 };
541
542 /// \brief A function analysis manager to coordinate and cache analyses run over
543 /// a module.
544 class FunctionAnalysisManager {
545 public:
546   FunctionAnalysisManager() {}
547
548   /// \brief Get the result of an analysis pass for a function.
549   ///
550   /// If there is not a valid cached result in the manager already, this will
551   /// re-run the analysis to produce a valid result.
552   template <typename PassT>
553   const typename PassT::Result &getResult(Function *F) {
554     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
555            "This analysis pass was not registered prior to being queried");
556
557     const detail::AnalysisResultConcept<Function *> &ResultConcept =
558         getResultImpl(PassT::ID(), F);
559     typedef detail::AnalysisResultModel<Function *, PassT,
560                                         typename PassT::Result> ResultModelT;
561     return static_cast<const ResultModelT &>(ResultConcept).Result;
562   }
563
564   /// \brief Get the cached result of an analysis pass for a function if
565   /// available.
566   ///
567   /// Does not run the analysis ever.
568   /// \returns null if a cached result is not available.
569   template <typename PassT>
570   const typename PassT::Result *getCachedResult(Function *F) {
571     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
572            "This analysis pass was not registered prior to being queried");
573
574     const detail::AnalysisResultConcept<Function *> *ResultConcept =
575         getCachedResultImpl(PassT::ID(), F);
576     if (!ResultConcept)
577       return 0;
578
579     typedef detail::AnalysisResultModel<Function *, PassT,
580                                         typename PassT::Result> ResultModelT;
581     return &static_cast<const ResultModelT *>(ResultConcept)->Result;
582   }
583
584   /// \brief Register an analysis pass with the manager.
585   ///
586   /// This provides an initialized and set-up analysis pass to the
587   /// analysis
588   /// manager. Whomever is setting up analysis passes must use this to
589   /// populate
590   /// the manager with all of the analysis passes available.
591   template <typename PassT> void registerPass(PassT Pass) {
592     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
593            "Registered the same analysis pass twice!");
594     FunctionAnalysisPasses[PassT::ID()] = new detail::AnalysisPassModel<
595         Function *, FunctionAnalysisManager, PassT>(llvm_move(Pass));
596   }
597
598   /// \brief Invalidate a specific analysis pass for an IR module.
599   ///
600   /// Note that the analysis result can disregard invalidation.
601   template <typename PassT> void invalidate(Function *F) {
602     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
603            "This analysis pass was not registered prior to being invalidated");
604     invalidateImpl(PassT::ID(), F);
605   }
606
607   /// \brief Invalidate analyses cached for an IR Function.
608   ///
609   /// Walk through all of the analyses cache for this IR function and
610   /// invalidate them unless they are preserved by the provided
611   /// PreservedAnalyses set.
612   void invalidate(Function *F, const PreservedAnalyses &PA);
613
614   /// \brief Returns true if the analysis manager has an empty results cache.
615   bool empty() const;
616
617   /// \brief Clear the function analysis result cache.
618   ///
619   /// This routine allows cleaning up when the set of functions itself has
620   /// potentially changed, and thus we can't even look up a a result and
621   /// invalidate it directly. Notably, this does *not* call invalidate
622   /// functions as there is nothing to be done for them.
623   void clear();
624
625 private:
626   /// \brief Get a function pass result, running the pass if necessary.
627   const detail::AnalysisResultConcept<Function *> &getResultImpl(void *PassID,
628                                                                  Function *F);
629
630   /// \brief Get a cached function pass result or return null.
631   const detail::AnalysisResultConcept<Function *> *
632   getCachedResultImpl(void *PassID, Function *F) const;
633
634   /// \brief Invalidate a function pass result.
635   void invalidateImpl(void *PassID, Function *F);
636
637   /// \brief Map type from function analysis pass ID to pass concept pointer.
638   typedef DenseMap<void *, polymorphic_ptr<detail::AnalysisPassConcept<
639                                Function *, FunctionAnalysisManager> > >
640       FunctionAnalysisPassMapT;
641
642   /// \brief Collection of function analysis passes, indexed by ID.
643   FunctionAnalysisPassMapT FunctionAnalysisPasses;
644
645   /// \brief List of function analysis pass IDs and associated concept pointers.
646   ///
647   /// Requires iterators to be valid across appending new entries and arbitrary
648   /// erases. Provides both the pass ID and concept pointer such that it is
649   /// half of a bijection and provides storage for the actual result concept.
650   typedef std::list<std::pair<
651       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function *> > > >
652       FunctionAnalysisResultListT;
653
654   /// \brief Map type from function pointer to our custom list type.
655   typedef DenseMap<Function *, FunctionAnalysisResultListT>
656   FunctionAnalysisResultListMapT;
657
658   /// \brief Map from function to a list of function analysis results.
659   ///
660   /// Provides linear time removal of all analysis results for a function and
661   /// the ultimate storage for a particular cached analysis result.
662   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
663
664   /// \brief Map type from a pair of analysis ID and function pointer to an
665   /// iterator into a particular result list.
666   typedef DenseMap<std::pair<void *, Function *>,
667                    FunctionAnalysisResultListT::iterator>
668       FunctionAnalysisResultMapT;
669
670   /// \brief Map from an analysis ID and function to a particular cached
671   /// analysis result.
672   FunctionAnalysisResultMapT FunctionAnalysisResults;
673 };
674
675 /// \brief A module analysis which acts as a proxy for a function analysis
676 /// manager.
677 ///
678 /// This primarily proxies invalidation information from the module analysis
679 /// manager and module pass manager to a function analysis manager. You should
680 /// never use a function analysis manager from within (transitively) a module
681 /// pass manager unless your parent module pass has received a proxy result
682 /// object for it.
683 class FunctionAnalysisManagerModuleProxy {
684 public:
685   class Result;
686
687   static void *ID() { return (void *)&PassID; }
688
689   FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
690
691   /// \brief Run the analysis pass and create our proxy result object.
692   ///
693   /// This doesn't do any interesting work, it is primarily used to insert our
694   /// proxy result object into the module analysis cache so that we can proxy
695   /// invalidation to the function analysis manager.
696   ///
697   /// In debug builds, it will also assert that the analysis manager is empty
698   /// as no queries should arrive at the function analysis manager prior to
699   /// this analysis being requested.
700   Result run(Module *M);
701
702 private:
703   static char PassID;
704
705   FunctionAnalysisManager &FAM;
706 };
707
708 /// \brief The result proxy object for the
709 /// \c FunctionAnalysisManagerModuleProxy.
710 ///
711 /// See its documentation for more information.
712 class FunctionAnalysisManagerModuleProxy::Result {
713 public:
714   Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
715   ~Result();
716
717   /// \brief Accessor for the \c FunctionAnalysisManager.
718   FunctionAnalysisManager &getManager() const { return FAM; }
719
720   /// \brief Handler for invalidation of the module.
721   ///
722   /// If this analysis itself is preserved, then we assume that the set of \c
723   /// Function objects in the \c Module hasn't changed and thus we don't need
724   /// to invalidate *all* cached data associated with a \c Function* in the \c
725   /// FunctionAnalysisManager.
726   ///
727   /// Regardless of whether this analysis is marked as preserved, all of the
728   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
729   /// based on the set of preserved analyses.
730   bool invalidate(Module *M, const PreservedAnalyses &PA);
731
732 private:
733   FunctionAnalysisManager &FAM;
734 };
735
736 /// \brief Trivial adaptor that maps from a module to its functions.
737 ///
738 /// Designed to allow composition of a FunctionPass(Manager) and
739 /// a ModulePassManager. Note that if this pass is constructed with a pointer
740 /// to a \c ModuleAnalysisManager it will run the
741 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
742 /// pass over the module to enable a \c FunctionAnalysisManager to be used
743 /// within this run safely.
744 template <typename FunctionPassT>
745 class ModuleToFunctionPassAdaptor {
746 public:
747   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
748       : Pass(llvm_move(Pass)) {}
749
750   /// \brief Runs the function pass across every function in the module.
751   PreservedAnalyses run(Module *M, ModuleAnalysisManager *AM) {
752     FunctionAnalysisManager *FAM = 0;
753     if (AM)
754       // Setup the function analysis manager from its proxy.
755       FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
756
757     PreservedAnalyses PA = PreservedAnalyses::all();
758     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
759       PreservedAnalyses PassPA = Pass.run(I, FAM);
760
761       // We know that the function pass couldn't have invalidated any other
762       // function's analyses (that's the contract of a function pass), so
763       // directly handle the function analysis manager's invalidation here.
764       if (FAM)
765         FAM->invalidate(I, PassPA);
766
767       // Then intersect the preserved set so that invalidation of module
768       // analyses will eventually occur when the module pass completes.
769       PA.intersect(llvm_move(PassPA));
770     }
771
772     // By definition we preserve the proxy. This precludes *any* invalidation
773     // of function analyses by the proxy, but that's OK because we've taken
774     // care to invalidate analyses in the function analysis manager
775     // incrementally above.
776     PA.preserve<FunctionAnalysisManagerModuleProxy>();
777     return PA;
778   }
779
780 private:
781   FunctionPassT Pass;
782 };
783
784 /// \brief A function to deduce a function pass type and wrap it in the
785 /// templated adaptor.
786 template <typename FunctionPassT>
787 ModuleToFunctionPassAdaptor<FunctionPassT>
788 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
789   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass));
790 }
791
792 }