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