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