[PM] Widen the interface for invalidate on an analysis result now that
[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 analysis manager detects a change in some underlying
189   /// unit of the IR, it will call this method on all of the results cached.
190   ///
191   /// This method also receives a set of preserved analyses which can be used
192   /// to avoid invalidation because the pass which changed the underlying IR
193   /// took care to update or preserve the analysis result in some way.
194   ///
195   /// \returns true if the result is indeed invalid (the default).
196   virtual bool invalidate(IRUnitT *IR, const PreservedAnalyses &PA) = 0;
197 };
198
199 /// \brief Wrapper to model the analysis result concept.
200 ///
201 /// By default, this will implement the invalidate method with a trivial
202 /// implementation so that the actual analysis result doesn't need to provide
203 /// an invalidation handler. It is only selected when the invalidation handler
204 /// is not part of the ResultT's interface.
205 template <typename IRUnitT, typename PassT, typename ResultT,
206           bool HasInvalidateHandler = false>
207 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
208   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
209   virtual AnalysisResultModel *clone() {
210     return new AnalysisResultModel(Result);
211   }
212
213   /// \brief The model bases invalidation soley on being in the preserved set.
214   //
215   // FIXME: We should actually use two different concepts for analysis results
216   // rather than two different models, and avoid the indirect function call for
217   // ones that use the trivial behavior.
218   virtual bool invalidate(IRUnitT *, const PreservedAnalyses &PA) {
219     return !PA.preserved(PassT::ID());
220   }
221
222   ResultT Result;
223 };
224
225 /// \brief Wrapper to model the analysis result concept.
226 ///
227 /// Can wrap any type which implements a suitable invalidate member and model
228 /// the AnalysisResultConcept for the AnalysisManager.
229 template <typename IRUnitT, typename PassT, typename ResultT>
230 struct AnalysisResultModel<IRUnitT, PassT, ResultT,
231                            true> : AnalysisResultConcept<IRUnitT> {
232   AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
233   virtual AnalysisResultModel *clone() {
234     return new AnalysisResultModel(Result);
235   }
236
237   /// \brief The model delegates to the \c ResultT method.
238   virtual bool invalidate(IRUnitT *IR, const PreservedAnalyses &PA) {
239     return Result.invalidate(IR, PA);
240   }
241
242   ResultT Result;
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 Abstract concept of an analysis pass.
262 ///
263 /// This concept is parameterized over the IR unit that it can run over and
264 /// produce an analysis result.
265 template <typename IRUnitT> struct AnalysisPassConcept {
266   virtual ~AnalysisPassConcept() {}
267   virtual AnalysisPassConcept *clone() = 0;
268
269   /// \brief Method to run this analysis over a unit of IR.
270   /// \returns The analysis result object to be queried by users, the caller
271   /// takes ownership.
272   virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
273 };
274
275 /// \brief Wrapper to model the analysis pass concept.
276 ///
277 /// Can wrap any type which implements a suitable \c run method. The method
278 /// must accept the IRUnitT as an argument and produce an object which can be
279 /// wrapped in a \c AnalysisResultModel.
280 template <typename PassT>
281 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
282   AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
283   virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
284
285   // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
286   typedef typename PassT::IRUnitT IRUnitT;
287
288   // FIXME: Replace PassT::Result with type traits when we use C++11.
289   typedef AnalysisResultModel<
290       IRUnitT, PassT, typename PassT::Result,
291       ResultHasInvalidateMethod<IRUnitT, typename PassT::Result>::Value>
292           ResultModelT;
293
294   /// \brief The model delegates to the \c PassT::run method.
295   ///
296   /// The return is wrapped in an \c AnalysisResultModel.
297   virtual ResultModelT *run(IRUnitT *IR) {
298     return new ResultModelT(Pass.run(IR));
299   }
300
301   PassT Pass;
302 };
303
304 }
305
306 class ModuleAnalysisManager;
307
308 class ModulePassManager {
309 public:
310   explicit ModulePassManager(ModuleAnalysisManager *AM = 0) : AM(AM) {}
311
312   /// \brief Run all of the module passes in this module pass manager over
313   /// a module.
314   ///
315   /// This method should only be called for a single module as there is the
316   /// expectation that the lifetime of a pass is bounded to that of a module.
317   PreservedAnalyses run(Module *M);
318
319   template <typename ModulePassT> void addPass(ModulePassT Pass) {
320     Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
321   }
322
323 private:
324   // Pull in the concept type and model template specialized for modules.
325   typedef detail::PassConcept<Module *> ModulePassConcept;
326   template <typename PassT>
327   struct ModulePassModel : detail::PassModel<Module *, PassT> {
328     ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
329   };
330
331   ModuleAnalysisManager *AM;
332   std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
333 };
334
335 class FunctionAnalysisManager;
336
337 class FunctionPassManager {
338 public:
339   explicit FunctionPassManager(FunctionAnalysisManager *AM = 0) : AM(AM) {}
340
341   template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
342     Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
343   }
344
345   PreservedAnalyses run(Function *F);
346
347 private:
348   // Pull in the concept type and model template specialized for functions.
349   typedef detail::PassConcept<Function *> FunctionPassConcept;
350   template <typename PassT>
351   struct FunctionPassModel : detail::PassModel<Function *, PassT> {
352     FunctionPassModel(PassT Pass)
353         : detail::PassModel<Function *, PassT>(Pass) {}
354   };
355
356   FunctionAnalysisManager *AM;
357   std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
358 };
359
360 /// \brief A module analysis pass manager with lazy running and caching of
361 /// results.
362 class ModuleAnalysisManager {
363 public:
364   ModuleAnalysisManager() {}
365
366   /// \brief Get the result of an analysis pass for this module.
367   ///
368   /// If there is not a valid cached result in the manager already, this will
369   /// re-run the analysis to produce a valid result.
370   template <typename PassT> const typename PassT::Result &getResult(Module *M) {
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            "This analysis pass was not registered prior to being queried");
375
376     const detail::AnalysisResultConcept<Module> &ResultConcept =
377         getResultImpl(PassT::ID(), M);
378     typedef detail::AnalysisResultModel<
379         Module, PassT, typename PassT::Result,
380         detail::ResultHasInvalidateMethod<
381             Module, typename PassT::Result>::Value> ResultModelT;
382     return static_cast<const ResultModelT &>(ResultConcept).Result;
383   }
384
385   /// \brief Register an analysis pass with the manager.
386   ///
387   /// This provides an initialized and set-up analysis pass to the
388   /// analysis
389   /// manager. Whomever is setting up analysis passes must use this to
390   /// populate
391   /// the manager with all of the analysis passes available.
392   template <typename PassT> void registerPass(PassT Pass) {
393     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
394                        "The analysis pass must be over a Module.");
395     assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
396            "Registered the same analysis pass twice!");
397     ModuleAnalysisPasses[PassT::ID()] =
398         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
399   }
400
401   /// \brief Invalidate a specific analysis pass for an IR module.
402   ///
403   /// Note that the analysis result can disregard invalidation.
404   template <typename PassT> void invalidate(Module *M) {
405     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
406                        "The analysis pass must be over a Module.");
407     assert(ModuleAnalysisPasses.count(PassT::ID()) &&
408            "This analysis pass was not registered prior to being invalidated");
409     invalidateImpl(PassT::ID(), M);
410   }
411
412   /// \brief Invalidate analyses cached for an IR Module.
413   ///
414   /// Walk through all of the analyses pertaining to this module and invalidate
415   /// them unless they are preserved by the PreservedAnalyses set.
416   void invalidate(Module *M, const PreservedAnalyses &PA);
417
418 private:
419   /// \brief Get a module pass result, running the pass if necessary.
420   const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
421                                                              Module *M);
422
423   /// \brief Invalidate a module pass result.
424   void invalidateImpl(void *PassID, Module *M);
425
426   /// \brief Map type from module analysis pass ID to pass concept pointer.
427   typedef DenseMap<void *,
428                    polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
429       ModuleAnalysisPassMapT;
430
431   /// \brief Collection of module analysis passes, indexed by ID.
432   ModuleAnalysisPassMapT ModuleAnalysisPasses;
433
434   /// \brief Map type from module analysis pass ID to pass result concept pointer.
435   typedef DenseMap<void *,
436                    polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
437       ModuleAnalysisResultMapT;
438
439   /// \brief Cache of computed module analysis results for this module.
440   ModuleAnalysisResultMapT ModuleAnalysisResults;
441 };
442
443 /// \brief A function analysis manager to coordinate and cache analyses run over
444 /// a module.
445 class FunctionAnalysisManager {
446 public:
447   FunctionAnalysisManager() {}
448
449   /// \brief Get the result of an analysis pass for a function.
450   ///
451   /// If there is not a valid cached result in the manager already, this will
452   /// re-run the analysis to produce a valid result.
453   template <typename PassT>
454   const typename PassT::Result &getResult(Function *F) {
455     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
456                        "The analysis pass must be over a Function.");
457     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
458            "This analysis pass was not registered prior to being queried");
459
460     const detail::AnalysisResultConcept<Function> &ResultConcept =
461         getResultImpl(PassT::ID(), F);
462     typedef detail::AnalysisResultModel<
463         Function, PassT, typename PassT::Result,
464         detail::ResultHasInvalidateMethod<
465             Function, typename PassT::Result>::Value> ResultModelT;
466     return static_cast<const ResultModelT &>(ResultConcept).Result;
467   }
468
469   /// \brief Register an analysis pass with the manager.
470   ///
471   /// This provides an initialized and set-up analysis pass to the
472   /// analysis
473   /// manager. Whomever is setting up analysis passes must use this to
474   /// populate
475   /// the manager with all of the analysis passes available.
476   template <typename PassT> void registerPass(PassT Pass) {
477     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
478                        "The analysis pass must be over a Function.");
479     assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
480            "Registered the same analysis pass twice!");
481     FunctionAnalysisPasses[PassT::ID()] =
482         new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
483   }
484
485   /// \brief Invalidate a specific analysis pass for an IR module.
486   ///
487   /// Note that the analysis result can disregard invalidation.
488   template <typename PassT> void invalidate(Function *F) {
489     LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
490                        "The analysis pass must be over a Function.");
491     assert(FunctionAnalysisPasses.count(PassT::ID()) &&
492            "This analysis pass was not registered prior to being invalidated");
493     invalidateImpl(PassT::ID(), F);
494   }
495
496   /// \brief Invalidate analyses cached for an IR Function.
497   ///
498   /// Walk through all of the analyses cache for this IR function and
499   /// invalidate them unless they are preserved by the provided
500   /// PreservedAnalyses set.
501   void invalidate(Function *F, const PreservedAnalyses &PA);
502
503   /// \brief Returns true if the analysis manager has an empty results cache.
504   bool empty() const;
505
506   /// \brief Clear the function analysis result cache.
507   ///
508   /// This routine allows cleaning up when the set of functions itself has
509   /// potentially changed, and thus we can't even look up a a result and
510   /// invalidate it directly. Notably, this does *not* call invalidate
511   /// functions as there is nothing to be done for them.
512   void clear();
513
514 private:
515   /// \brief Get a function pass result, running the pass if necessary.
516   const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
517                                                                Function *F);
518
519   /// \brief Invalidate a function pass result.
520   void invalidateImpl(void *PassID, Function *F);
521
522   /// \brief Map type from function analysis pass ID to pass concept pointer.
523   typedef DenseMap<void *,
524                    polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
525       FunctionAnalysisPassMapT;
526
527   /// \brief Collection of function analysis passes, indexed by ID.
528   FunctionAnalysisPassMapT FunctionAnalysisPasses;
529
530   /// \brief List of function analysis pass IDs and associated concept pointers.
531   ///
532   /// Requires iterators to be valid across appending new entries and arbitrary
533   /// erases. Provides both the pass ID and concept pointer such that it is
534   /// half of a bijection and provides storage for the actual result concept.
535   typedef std::list<std::pair<
536       void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
537       FunctionAnalysisResultListT;
538
539   /// \brief Map type from function pointer to our custom list type.
540   typedef DenseMap<Function *, FunctionAnalysisResultListT>
541   FunctionAnalysisResultListMapT;
542
543   /// \brief Map from function to a list of function analysis results.
544   ///
545   /// Provides linear time removal of all analysis results for a function and
546   /// the ultimate storage for a particular cached analysis result.
547   FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
548
549   /// \brief Map type from a pair of analysis ID and function pointer to an
550   /// iterator into a particular result list.
551   typedef DenseMap<std::pair<void *, Function *>,
552                    FunctionAnalysisResultListT::iterator>
553       FunctionAnalysisResultMapT;
554
555   /// \brief Map from an analysis ID and function to a particular cached
556   /// analysis result.
557   FunctionAnalysisResultMapT FunctionAnalysisResults;
558 };
559
560 /// \brief A module analysis which acts as a proxy for a function analysis
561 /// manager.
562 ///
563 /// This primarily proxies invalidation information from the module analysis
564 /// manager and module pass manager to a function analysis manager. You should
565 /// never use a function analysis manager from within (transitively) a module
566 /// pass manager unless your parent module pass has received a proxy result
567 /// object for it.
568 ///
569 /// FIXME: It might be really nice to "enforce" this (softly) by making this
570 /// proxy the API path to access a function analysis manager within a module
571 /// pass.
572 class FunctionAnalysisModuleProxy {
573 public:
574   typedef Module IRUnitT;
575   class Result;
576
577   static void *ID() { return (void *)&PassID; }
578
579   FunctionAnalysisModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
580
581   /// \brief Run the analysis pass and create our proxy result object.
582   ///
583   /// This doesn't do any interesting work, it is primarily used to insert our
584   /// proxy result object into the module analysis cache so that we can proxy
585   /// invalidation to the function analysis manager.
586   ///
587   /// In debug builds, it will also assert that the analysis manager is empty
588   /// as no queries should arrive at the function analysis manager prior to
589   /// this analysis being requested.
590   Result run(Module *M);
591
592 private:
593   static char PassID;
594
595   FunctionAnalysisManager &FAM;
596 };
597
598 /// \brief The result proxy object for the \c FunctionAnalysisModuleProxy.
599 ///
600 /// See its documentation for more information.
601 class FunctionAnalysisModuleProxy::Result {
602 public:
603   Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
604   ~Result();
605
606   /// \brief Handler for invalidation of the module.
607   ///
608   /// If this analysis itself is preserved, then we assume that the set of \c
609   /// Function objects in the \c Module hasn't changed and thus we don't need
610   /// to invalidate *all* cached data associated with a \c Function* in the \c
611   /// FunctionAnalysisManager.
612   ///
613   /// Regardless of whether this analysis is marked as preserved, all of the
614   /// analyses in the \c FunctionAnalysisManager are potentially invalidated
615   /// based on the set of preserved analyses.
616   bool invalidate(Module *M, const PreservedAnalyses &PA);
617
618 private:
619   FunctionAnalysisManager &FAM;
620 };
621
622 /// \brief Trivial adaptor that maps from a module to its functions.
623 ///
624 /// Designed to allow composition of a FunctionPass(Manager) and a
625 /// ModulePassManager. Note that if this pass is constructed with a pointer to
626 /// a \c ModuleAnalysisManager it will run the \c FunctionAnalysisModuleProxy
627 /// analysis prior to running the function pass over the module to enable a \c
628 /// FunctionAnalysisManager to be used within this run safely.
629 template <typename FunctionPassT>
630 class ModuleToFunctionPassAdaptor {
631 public:
632   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass,
633                                        ModuleAnalysisManager *MAM = 0)
634       : Pass(llvm_move(Pass)), MAM(MAM) {}
635
636   /// \brief Runs the function pass across every function in the module.
637   PreservedAnalyses run(Module *M) {
638     if (MAM)
639       // Pull in the analysis proxy so that the function analysis manager is
640       // appropriately set up.
641       (void)MAM->getResult<FunctionAnalysisModuleProxy>(M);
642
643     PreservedAnalyses PA = PreservedAnalyses::all();
644     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
645       PreservedAnalyses PassPA = Pass.run(I);
646       PA.intersect(llvm_move(PassPA));
647     }
648     
649     // By definition we preserve the proxy.
650     PA.preserve<FunctionAnalysisModuleProxy>();
651     return PA;
652   }
653
654 private:
655   FunctionPassT Pass;
656   ModuleAnalysisManager *MAM;
657 };
658
659 /// \brief A function to deduce a function pass type and wrap it in the
660 /// templated adaptor.
661 ///
662 /// \param MAM is an optional \c ModuleAnalysisManager which (if provided) will
663 /// be queried for a \c FunctionAnalysisModuleProxy to enable the function
664 /// pass(es) to safely interact with a \c FunctionAnalysisManager.
665 template <typename FunctionPassT>
666 ModuleToFunctionPassAdaptor<FunctionPassT>
667 createModuleToFunctionPassAdaptor(FunctionPassT Pass,
668                                   ModuleAnalysisManager *MAM = 0) {
669   return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass), MAM);
670 }
671
672 }