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