]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/IR/PassManager.h
MFV r316928: 7256 low probability race in zfs_get_data
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/TinyPtrVector.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/IR/PassManagerInternal.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/TypeName.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Support/type_traits.h"
52 #include <list>
53 #include <memory>
54 #include <vector>
55
56 namespace llvm {
57
58 /// A special type used by analysis passes to provide an address that
59 /// identifies that particular analysis pass type.
60 ///
61 /// Analysis passes should have a static data member of this type and derive
62 /// from the \c AnalysisInfoMixin to get a static ID method used to identify
63 /// the analysis in the pass management infrastructure.
64 struct alignas(8) AnalysisKey {};
65
66 /// A special type used to provide an address that identifies a set of related
67 /// analyses.  These sets are primarily used below to mark sets of analyses as
68 /// preserved.
69 ///
70 /// For example, a transformation can indicate that it preserves the CFG of a
71 /// function by preserving the appropriate AnalysisSetKey.  An analysis that
72 /// depends only on the CFG can then check if that AnalysisSetKey is preserved;
73 /// if it is, the analysis knows that it itself is preserved.
74 struct alignas(8) AnalysisSetKey {};
75
76 /// A set of analyses that are preserved following a run of a transformation
77 /// pass.
78 ///
79 /// Transformation passes build and return these objects to communicate which
80 /// analyses are still valid after the transformation. For most passes this is
81 /// fairly simple: if they don't change anything all analyses are preserved,
82 /// otherwise only a short list of analyses that have been explicitly updated
83 /// are preserved.
84 ///
85 /// This class also lets transformation passes mark abstract *sets* of analyses
86 /// as preserved. A transformation that (say) does not alter the CFG can
87 /// indicate such by marking a particular AnalysisSetKey as preserved, and
88 /// then analyses can query whether that AnalysisSetKey is preserved.
89 ///
90 /// Finally, this class can represent an "abandoned" analysis, which is
91 /// not preserved even if it would be covered by some abstract set of analyses.
92 ///
93 /// Given a `PreservedAnalyses` object, an analysis will typically want to
94 /// figure out whether it is preserved. In the example below, MyAnalysisType is
95 /// preserved if it's not abandoned, and (a) it's explicitly marked as
96 /// preserved, (b), the set AllAnalysesOn<MyIRUnit> is preserved, or (c) both
97 /// AnalysisSetA and AnalysisSetB are preserved.
98 ///
99 /// ```
100 ///   auto PAC = PA.getChecker<MyAnalysisType>();
101 ///   if (PAC.preserved() || PAC.preservedSet<AllAnalysesOn<MyIRUnit>>() ||
102 ///       (PAC.preservedSet<AnalysisSetA>() &&
103 ///        PAC.preservedSet<AnalysisSetB>())) {
104 ///     // The analysis has been successfully preserved ...
105 ///   }
106 /// ```
107 class PreservedAnalyses {
108 public:
109   /// \brief Convenience factory function for the empty preserved set.
110   static PreservedAnalyses none() { return PreservedAnalyses(); }
111
112   /// \brief Construct a special preserved set that preserves all passes.
113   static PreservedAnalyses all() {
114     PreservedAnalyses PA;
115     PA.PreservedIDs.insert(&AllAnalysesKey);
116     return PA;
117   }
118
119   /// Mark an analysis as preserved.
120   template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
121
122   /// \brief Given an analysis's ID, mark the analysis as preserved, adding it
123   /// to the set.
124   void preserve(AnalysisKey *ID) {
125     // Clear this ID from the explicit not-preserved set if present.
126     NotPreservedAnalysisIDs.erase(ID);
127
128     // If we're not already preserving all analyses (other than those in
129     // NotPreservedAnalysisIDs).
130     if (!areAllPreserved())
131       PreservedIDs.insert(ID);
132   }
133
134   /// Mark an analysis set as preserved.
135   template <typename AnalysisSetT> void preserveSet() {
136     preserveSet(AnalysisSetT::ID());
137   }
138
139   /// Mark an analysis set as preserved using its ID.
140   void preserveSet(AnalysisSetKey *ID) {
141     // If we're not already in the saturated 'all' state, add this set.
142     if (!areAllPreserved())
143       PreservedIDs.insert(ID);
144   }
145
146   /// Mark an analysis as abandoned.
147   ///
148   /// An abandoned analysis is not preserved, even if it is nominally covered
149   /// by some other set or was previously explicitly marked as preserved.
150   ///
151   /// Note that you can only abandon a specific analysis, not a *set* of
152   /// analyses.
153   template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); }
154
155   /// Mark an analysis as abandoned using its ID.
156   ///
157   /// An abandoned analysis is not preserved, even if it is nominally covered
158   /// by some other set or was previously explicitly marked as preserved.
159   ///
160   /// Note that you can only abandon a specific analysis, not a *set* of
161   /// analyses.
162   void abandon(AnalysisKey *ID) {
163     PreservedIDs.erase(ID);
164     NotPreservedAnalysisIDs.insert(ID);
165   }
166
167   /// \brief Intersect this set with another in place.
168   ///
169   /// This is a mutating operation on this preserved set, removing all
170   /// preserved passes which are not also preserved in the argument.
171   void intersect(const PreservedAnalyses &Arg) {
172     if (Arg.areAllPreserved())
173       return;
174     if (areAllPreserved()) {
175       *this = Arg;
176       return;
177     }
178     // The intersection requires the *union* of the explicitly not-preserved
179     // IDs and the *intersection* of the preserved IDs.
180     for (auto ID : Arg.NotPreservedAnalysisIDs) {
181       PreservedIDs.erase(ID);
182       NotPreservedAnalysisIDs.insert(ID);
183     }
184     for (auto ID : PreservedIDs)
185       if (!Arg.PreservedIDs.count(ID))
186         PreservedIDs.erase(ID);
187   }
188
189   /// \brief Intersect this set with a temporary other set in place.
190   ///
191   /// This is a mutating operation on this preserved set, removing all
192   /// preserved passes which are not also preserved in the argument.
193   void intersect(PreservedAnalyses &&Arg) {
194     if (Arg.areAllPreserved())
195       return;
196     if (areAllPreserved()) {
197       *this = std::move(Arg);
198       return;
199     }
200     // The intersection requires the *union* of the explicitly not-preserved
201     // IDs and the *intersection* of the preserved IDs.
202     for (auto ID : Arg.NotPreservedAnalysisIDs) {
203       PreservedIDs.erase(ID);
204       NotPreservedAnalysisIDs.insert(ID);
205     }
206     for (auto ID : PreservedIDs)
207       if (!Arg.PreservedIDs.count(ID))
208         PreservedIDs.erase(ID);
209   }
210
211   /// A checker object that makes it easy to query for whether an analysis or
212   /// some set covering it is preserved.
213   class PreservedAnalysisChecker {
214     friend class PreservedAnalyses;
215
216     const PreservedAnalyses &PA;
217     AnalysisKey *const ID;
218     const bool IsAbandoned;
219
220     /// A PreservedAnalysisChecker is tied to a particular Analysis because
221     /// `preserved()` and `preservedSet()` both return false if the Analysis
222     /// was abandoned.
223     PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID)
224         : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
225
226   public:
227     /// Returns true if the checker's analysis was not abandoned and either
228     ///  - the analysis is explicitly preserved or
229     ///  - all analyses are preserved.
230     bool preserved() {
231       return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
232                               PA.PreservedIDs.count(ID));
233     }
234
235     /// Returns true if the checker's analysis was not abandoned and either
236     ///  - \p AnalysisSetT is explicitly preserved or
237     ///  - all analyses are preserved.
238     template <typename AnalysisSetT> bool preservedSet() {
239       AnalysisSetKey *SetID = AnalysisSetT::ID();
240       return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
241                               PA.PreservedIDs.count(SetID));
242     }
243   };
244
245   /// Build a checker for this `PreservedAnalyses` and the specified analysis
246   /// type.
247   ///
248   /// You can use the returned object to query whether an analysis was
249   /// preserved. See the example in the comment on `PreservedAnalysis`.
250   template <typename AnalysisT> PreservedAnalysisChecker getChecker() const {
251     return PreservedAnalysisChecker(*this, AnalysisT::ID());
252   }
253
254   /// Build a checker for this `PreservedAnalyses` and the specified analysis
255   /// ID.
256   ///
257   /// You can use the returned object to query whether an analysis was
258   /// preserved. See the example in the comment on `PreservedAnalysis`.
259   PreservedAnalysisChecker getChecker(AnalysisKey *ID) const {
260     return PreservedAnalysisChecker(*this, ID);
261   }
262
263   /// Test whether all analyses are preserved (and none are abandoned).
264   ///
265   /// This is used primarily to optimize for the common case of a transformation
266   /// which makes no changes to the IR.
267   bool areAllPreserved() const {
268     return NotPreservedAnalysisIDs.empty() &&
269            PreservedIDs.count(&AllAnalysesKey);
270   }
271
272   /// Directly test whether a set of analyses is preserved.
273   ///
274   /// This is only true when no analyses have been explicitly abandoned.
275   template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
276     return allAnalysesInSetPreserved(AnalysisSetT::ID());
277   }
278
279   /// Directly test whether a set of analyses is preserved.
280   ///
281   /// This is only true when no analyses have been explicitly abandoned.
282   bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const {
283     return NotPreservedAnalysisIDs.empty() &&
284            (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID));
285   }
286
287 private:
288   /// A special key used to indicate all analyses.
289   static AnalysisSetKey AllAnalysesKey;
290
291   /// The IDs of analyses and analysis sets that are preserved.
292   SmallPtrSet<void *, 2> PreservedIDs;
293
294   /// The IDs of explicitly not-preserved analyses.
295   ///
296   /// If an analysis in this set is covered by a set in `PreservedIDs`, we
297   /// consider it not-preserved. That is, `NotPreservedAnalysisIDs` always
298   /// "wins" over analysis sets in `PreservedIDs`.
299   ///
300   /// Also, a given ID should never occur both here and in `PreservedIDs`.
301   SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
302 };
303
304 // Forward declare the analysis manager template.
305 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
306
307 /// A CRTP mix-in to automatically provide informational APIs needed for
308 /// passes.
309 ///
310 /// This provides some boilerplate for types that are passes.
311 template <typename DerivedT> struct PassInfoMixin {
312   /// Gets the name of the pass we are mixed into.
313   static StringRef name() {
314     static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
315                   "Must pass the derived type as the template argument!");
316     StringRef Name = getTypeName<DerivedT>();
317     if (Name.startswith("llvm::"))
318       Name = Name.drop_front(strlen("llvm::"));
319     return Name;
320   }
321 };
322
323 /// A CRTP mix-in that provides informational APIs needed for analysis passes.
324 ///
325 /// This provides some boilerplate for types that are analysis passes. It
326 /// automatically mixes in \c PassInfoMixin.
327 template <typename DerivedT>
328 struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
329   /// Returns an opaque, unique ID for this analysis type.
330   ///
331   /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
332   /// suitable for use in sets, maps, and other data structures that use the low
333   /// bits of pointers.
334   ///
335   /// Note that this requires the derived type provide a static \c AnalysisKey
336   /// member called \c Key.
337   ///
338   /// FIXME: The only reason the mixin type itself can't declare the Key value
339   /// is that some compilers cannot correctly unique a templated static variable
340   /// so it has the same addresses in each instantiation. The only currently
341   /// known platform with this limitation is Windows DLL builds, specifically
342   /// building each part of LLVM as a DLL. If we ever remove that build
343   /// configuration, this mixin can provide the static key as well.
344   static AnalysisKey *ID() {
345     static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
346                   "Must pass the derived type as the template argument!");
347     return &DerivedT::Key;
348   }
349 };
350
351 /// This templated class represents "all analyses that operate over \<a
352 /// particular IR unit\>" (e.g. a Function or a Module) in instances of
353 /// PreservedAnalysis.
354 ///
355 /// This lets a transformation say e.g. "I preserved all function analyses".
356 ///
357 /// Note that you must provide an explicit instantiation declaration and
358 /// definition for this template in order to get the correct behavior on
359 /// Windows. Otherwise, the address of SetKey will not be stable.
360 template <typename IRUnitT>
361 class AllAnalysesOn {
362 public:
363   static AnalysisSetKey *ID() { return &SetKey; }
364
365 private:
366   static AnalysisSetKey SetKey;
367 };
368
369 template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
370
371 extern template class AllAnalysesOn<Module>;
372 extern template class AllAnalysesOn<Function>;
373
374 /// \brief Manages a sequence of passes over a particular unit of IR.
375 ///
376 /// A pass manager contains a sequence of passes to run over a particular unit
377 /// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
378 /// IR, and when run over some given IR will run each of its contained passes in
379 /// sequence. Pass managers are the primary and most basic building block of a
380 /// pass pipeline.
381 ///
382 /// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
383 /// argument. The pass manager will propagate that analysis manager to each
384 /// pass it runs, and will call the analysis manager's invalidation routine with
385 /// the PreservedAnalyses of each pass it runs.
386 template <typename IRUnitT,
387           typename AnalysisManagerT = AnalysisManager<IRUnitT>,
388           typename... ExtraArgTs>
389 class PassManager : public PassInfoMixin<
390                         PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
391 public:
392   /// \brief Construct a pass manager.
393   ///
394   /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
395   explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
396
397   // FIXME: These are equivalent to the default move constructor/move
398   // assignment. However, using = default triggers linker errors due to the
399   // explicit instantiations below. Find away to use the default and remove the
400   // duplicated code here.
401   PassManager(PassManager &&Arg)
402       : Passes(std::move(Arg.Passes)),
403         DebugLogging(std::move(Arg.DebugLogging)) {}
404
405   PassManager &operator=(PassManager &&RHS) {
406     Passes = std::move(RHS.Passes);
407     DebugLogging = std::move(RHS.DebugLogging);
408     return *this;
409   }
410
411   /// \brief Run all of the passes in this manager over the given unit of IR.
412   /// ExtraArgs are passed to each pass.
413   PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
414                         ExtraArgTs... ExtraArgs) {
415     PreservedAnalyses PA = PreservedAnalyses::all();
416
417     if (DebugLogging)
418       dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n";
419
420     for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
421       if (DebugLogging)
422         dbgs() << "Running pass: " << Passes[Idx]->name() << " on "
423                << IR.getName() << "\n";
424
425       PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM, ExtraArgs...);
426
427       // Update the analysis manager as each pass runs and potentially
428       // invalidates analyses.
429       AM.invalidate(IR, PassPA);
430
431       // Finally, intersect the preserved analyses to compute the aggregate
432       // preserved set for this pass manager.
433       PA.intersect(std::move(PassPA));
434
435       // FIXME: Historically, the pass managers all called the LLVM context's
436       // yield function here. We don't have a generic way to acquire the
437       // context and it isn't yet clear what the right pattern is for yielding
438       // in the new pass manager so it is currently omitted.
439       //IR.getContext().yield();
440     }
441
442     // Invaliadtion was handled after each pass in the above loop for the
443     // current unit of IR. Therefore, the remaining analysis results in the
444     // AnalysisManager are preserved. We mark this with a set so that we don't
445     // need to inspect each one individually.
446     PA.preserveSet<AllAnalysesOn<IRUnitT>>();
447
448     if (DebugLogging)
449       dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n";
450
451     return PA;
452   }
453
454   template <typename PassT> void addPass(PassT Pass) {
455     typedef detail::PassModel<IRUnitT, PassT, PreservedAnalyses,
456                               AnalysisManagerT, ExtraArgTs...>
457         PassModelT;
458     Passes.emplace_back(new PassModelT(std::move(Pass)));
459   }
460
461 private:
462   typedef detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>
463       PassConceptT;
464
465   std::vector<std::unique_ptr<PassConceptT>> Passes;
466
467   /// \brief Flag indicating whether we should do debug logging.
468   bool DebugLogging;
469 };
470
471 extern template class PassManager<Module>;
472 /// \brief Convenience typedef for a pass manager over modules.
473 typedef PassManager<Module> ModulePassManager;
474
475 extern template class PassManager<Function>;
476 /// \brief Convenience typedef for a pass manager over functions.
477 typedef PassManager<Function> FunctionPassManager;
478
479 /// \brief A container for analyses that lazily runs them and caches their
480 /// results.
481 ///
482 /// This class can manage analyses for any IR unit where the address of the IR
483 /// unit sufficies as its identity.
484 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
485 public:
486   class Invalidator;
487
488 private:
489   // Now that we've defined our invalidator, we can define the concept types.
490   typedef detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>
491       ResultConceptT;
492   typedef detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
493                                       ExtraArgTs...>
494       PassConceptT;
495
496   /// \brief List of analysis pass IDs and associated concept pointers.
497   ///
498   /// Requires iterators to be valid across appending new entries and arbitrary
499   /// erases. Provides the analysis ID to enable finding iterators to a given
500   /// entry in maps below, and provides the storage for the actual result
501   /// concept.
502   typedef std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>
503       AnalysisResultListT;
504
505   /// \brief Map type from IRUnitT pointer to our custom list type.
506   typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
507
508   /// \brief Map type from a pair of analysis ID and IRUnitT pointer to an
509   /// iterator into a particular result list (which is where the actual analysis
510   /// result is stored).
511   typedef DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
512                    typename AnalysisResultListT::iterator>
513       AnalysisResultMapT;
514
515 public:
516   /// API to communicate dependencies between analyses during invalidation.
517   ///
518   /// When an analysis result embeds handles to other analysis results, it
519   /// needs to be invalidated both when its own information isn't preserved and
520   /// when any of its embedded analysis results end up invalidated. We pass an
521   /// \c Invalidator object as an argument to \c invalidate() in order to let
522   /// the analysis results themselves define the dependency graph on the fly.
523   /// This lets us avoid building building an explicit representation of the
524   /// dependencies between analysis results.
525   class Invalidator {
526   public:
527     /// Trigger the invalidation of some other analysis pass if not already
528     /// handled and return whether it was in fact invalidated.
529     ///
530     /// This is expected to be called from within a given analysis result's \c
531     /// invalidate method to trigger a depth-first walk of all inter-analysis
532     /// dependencies. The same \p IR unit and \p PA passed to that result's \c
533     /// invalidate method should in turn be provided to this routine.
534     ///
535     /// The first time this is called for a given analysis pass, it will call
536     /// the corresponding result's \c invalidate method.  Subsequent calls will
537     /// use a cache of the results of that initial call.  It is an error to form
538     /// cyclic dependencies between analysis results.
539     ///
540     /// This returns true if the given analysis's result is invalid. Any
541     /// dependecies on it will become invalid as a result.
542     template <typename PassT>
543     bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
544       typedef detail::AnalysisResultModel<IRUnitT, PassT,
545                                           typename PassT::Result,
546                                           PreservedAnalyses, Invalidator>
547           ResultModelT;
548       return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
549     }
550
551     /// A type-erased variant of the above invalidate method with the same core
552     /// API other than passing an analysis ID rather than an analysis type
553     /// parameter.
554     ///
555     /// This is sadly less efficient than the above routine, which leverages
556     /// the type parameter to avoid the type erasure overhead.
557     bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
558       return invalidateImpl<>(ID, IR, PA);
559     }
560
561   private:
562     friend class AnalysisManager;
563
564     template <typename ResultT = ResultConceptT>
565     bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
566                         const PreservedAnalyses &PA) {
567       // If we've already visited this pass, return true if it was invalidated
568       // and false otherwise.
569       auto IMapI = IsResultInvalidated.find(ID);
570       if (IMapI != IsResultInvalidated.end())
571         return IMapI->second;
572
573       // Otherwise look up the result object.
574       auto RI = Results.find({ID, &IR});
575       assert(RI != Results.end() &&
576              "Trying to invalidate a dependent result that isn't in the "
577              "manager's cache is always an error, likely due to a stale result "
578              "handle!");
579
580       auto &Result = static_cast<ResultT &>(*RI->second->second);
581
582       // Insert into the map whether the result should be invalidated and return
583       // that. Note that we cannot reuse IMapI and must do a fresh insert here,
584       // as calling invalidate could (recursively) insert things into the map,
585       // making any iterator or reference invalid.
586       bool Inserted;
587       std::tie(IMapI, Inserted) =
588           IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
589       (void)Inserted;
590       assert(Inserted && "Should not have already inserted this ID, likely "
591                          "indicates a dependency cycle!");
592       return IMapI->second;
593     }
594
595     Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
596                 const AnalysisResultMapT &Results)
597         : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
598
599     SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
600     const AnalysisResultMapT &Results;
601   };
602
603   /// \brief Construct an empty analysis manager.
604   ///
605   /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
606   AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
607   AnalysisManager(AnalysisManager &&) = default;
608   AnalysisManager &operator=(AnalysisManager &&) = default;
609
610   /// \brief Returns true if the analysis manager has an empty results cache.
611   bool empty() const {
612     assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
613            "The storage and index of analysis results disagree on how many "
614            "there are!");
615     return AnalysisResults.empty();
616   }
617
618   /// \brief Clear any cached analysis results for a single unit of IR.
619   ///
620   /// This doesn't invalidate, but instead simply deletes, the relevant results.
621   /// It is useful when the IR is being removed and we want to clear out all the
622   /// memory pinned for it.
623   void clear(IRUnitT &IR) {
624     if (DebugLogging)
625       dbgs() << "Clearing all analysis results for: " << IR.getName() << "\n";
626
627     auto ResultsListI = AnalysisResultLists.find(&IR);
628     if (ResultsListI == AnalysisResultLists.end())
629       return;
630     // Delete the map entries that point into the results list.
631     for (auto &IDAndResult : ResultsListI->second)
632       AnalysisResults.erase({IDAndResult.first, &IR});
633
634     // And actually destroy and erase the results associated with this IR.
635     AnalysisResultLists.erase(ResultsListI);
636   }
637
638   /// \brief Clear all analysis results cached by this AnalysisManager.
639   ///
640   /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
641   /// deletes them.  This lets you clean up the AnalysisManager when the set of
642   /// IR units itself has potentially changed, and thus we can't even look up a
643   /// a result and invalidate/clear it directly.
644   void clear() {
645     AnalysisResults.clear();
646     AnalysisResultLists.clear();
647   }
648
649   /// \brief Get the result of an analysis pass for a given IR unit.
650   ///
651   /// Runs the analysis if a cached result is not available.
652   template <typename PassT>
653   typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
654     assert(AnalysisPasses.count(PassT::ID()) &&
655            "This analysis pass was not registered prior to being queried");
656     ResultConceptT &ResultConcept =
657         getResultImpl(PassT::ID(), IR, ExtraArgs...);
658     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
659                                         PreservedAnalyses, Invalidator>
660         ResultModelT;
661     return static_cast<ResultModelT &>(ResultConcept).Result;
662   }
663
664   /// \brief Get the cached result of an analysis pass for a given IR unit.
665   ///
666   /// This method never runs the analysis.
667   ///
668   /// \returns null if there is no cached result.
669   template <typename PassT>
670   typename PassT::Result *getCachedResult(IRUnitT &IR) const {
671     assert(AnalysisPasses.count(PassT::ID()) &&
672            "This analysis pass was not registered prior to being queried");
673
674     ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
675     if (!ResultConcept)
676       return nullptr;
677
678     typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
679                                         PreservedAnalyses, Invalidator>
680         ResultModelT;
681     return &static_cast<ResultModelT *>(ResultConcept)->Result;
682   }
683
684   /// \brief Register an analysis pass with the manager.
685   ///
686   /// The parameter is a callable whose result is an analysis pass. This allows
687   /// passing in a lambda to construct the analysis.
688   ///
689   /// The analysis type to register is the type returned by calling the \c
690   /// PassBuilder argument. If that type has already been registered, then the
691   /// argument will not be called and this function will return false.
692   /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
693   /// and this function returns true.
694   ///
695   /// (Note: Although the return value of this function indicates whether or not
696   /// an analysis was previously registered, there intentionally isn't a way to
697   /// query this directly.  Instead, you should just register all the analyses
698   /// you might want and let this class run them lazily.  This idiom lets us
699   /// minimize the number of times we have to look up analyses in our
700   /// hashtable.)
701   template <typename PassBuilderT>
702   bool registerPass(PassBuilderT &&PassBuilder) {
703     typedef decltype(PassBuilder()) PassT;
704     typedef detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses,
705                                       Invalidator, ExtraArgTs...>
706         PassModelT;
707
708     auto &PassPtr = AnalysisPasses[PassT::ID()];
709     if (PassPtr)
710       // Already registered this pass type!
711       return false;
712
713     // Construct a new model around the instance returned by the builder.
714     PassPtr.reset(new PassModelT(PassBuilder()));
715     return true;
716   }
717
718   /// \brief Invalidate a specific analysis pass for an IR module.
719   ///
720   /// Note that the analysis result can disregard invalidation, if it determines
721   /// it is in fact still valid.
722   template <typename PassT> void invalidate(IRUnitT &IR) {
723     assert(AnalysisPasses.count(PassT::ID()) &&
724            "This analysis pass was not registered prior to being invalidated");
725     invalidateImpl(PassT::ID(), IR);
726   }
727
728   /// \brief Invalidate cached analyses for an IR unit.
729   ///
730   /// Walk through all of the analyses pertaining to this unit of IR and
731   /// invalidate them, unless they are preserved by the PreservedAnalyses set.
732   void invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
733     // We're done if all analyses on this IR unit are preserved.
734     if (PA.allAnalysesInSetPreserved<AllAnalysesOn<IRUnitT>>())
735       return;
736
737     if (DebugLogging)
738       dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName()
739              << "\n";
740
741     // Track whether each analysis's result is invalidated in
742     // IsResultInvalidated.
743     SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
744     Invalidator Inv(IsResultInvalidated, AnalysisResults);
745     AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
746     for (auto &AnalysisResultPair : ResultsList) {
747       // This is basically the same thing as Invalidator::invalidate, but we
748       // can't call it here because we're operating on the type-erased result.
749       // Moreover if we instead called invalidate() directly, it would do an
750       // unnecessary look up in ResultsList.
751       AnalysisKey *ID = AnalysisResultPair.first;
752       auto &Result = *AnalysisResultPair.second;
753
754       auto IMapI = IsResultInvalidated.find(ID);
755       if (IMapI != IsResultInvalidated.end())
756         // This result was already handled via the Invalidator.
757         continue;
758
759       // Try to invalidate the result, giving it the Invalidator so it can
760       // recursively query for any dependencies it has and record the result.
761       // Note that we cannot reuse 'IMapI' here or pre-insert the ID, as
762       // Result.invalidate may insert things into the map, invalidating our
763       // iterator.
764       bool Inserted =
765           IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, Inv)})
766               .second;
767       (void)Inserted;
768       assert(Inserted && "Should never have already inserted this ID, likely "
769                          "indicates a cycle!");
770     }
771
772     // Now erase the results that were marked above as invalidated.
773     if (!IsResultInvalidated.empty()) {
774       for (auto I = ResultsList.begin(), E = ResultsList.end(); I != E;) {
775         AnalysisKey *ID = I->first;
776         if (!IsResultInvalidated.lookup(ID)) {
777           ++I;
778           continue;
779         }
780
781         if (DebugLogging)
782           dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
783                  << "\n";
784
785         I = ResultsList.erase(I);
786         AnalysisResults.erase({ID, &IR});
787       }
788     }
789
790     if (ResultsList.empty())
791       AnalysisResultLists.erase(&IR);
792   }
793
794 private:
795   /// \brief Look up a registered analysis pass.
796   PassConceptT &lookUpPass(AnalysisKey *ID) {
797     typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
798     assert(PI != AnalysisPasses.end() &&
799            "Analysis passes must be registered prior to being queried!");
800     return *PI->second;
801   }
802
803   /// \brief Look up a registered analysis pass.
804   const PassConceptT &lookUpPass(AnalysisKey *ID) const {
805     typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
806     assert(PI != AnalysisPasses.end() &&
807            "Analysis passes must be registered prior to being queried!");
808     return *PI->second;
809   }
810
811   /// \brief Get an analysis result, running the pass if necessary.
812   ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
813                                 ExtraArgTs... ExtraArgs) {
814     typename AnalysisResultMapT::iterator RI;
815     bool Inserted;
816     std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
817         std::make_pair(ID, &IR), typename AnalysisResultListT::iterator()));
818
819     // If we don't have a cached result for this function, look up the pass and
820     // run it to produce a result, which we then add to the cache.
821     if (Inserted) {
822       auto &P = this->lookUpPass(ID);
823       if (DebugLogging)
824         dbgs() << "Running analysis: " << P.name() << "\n";
825       AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
826       ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...));
827
828       // P.run may have inserted elements into AnalysisResults and invalidated
829       // RI.
830       RI = AnalysisResults.find({ID, &IR});
831       assert(RI != AnalysisResults.end() && "we just inserted it!");
832
833       RI->second = std::prev(ResultList.end());
834     }
835
836     return *RI->second->second;
837   }
838
839   /// \brief Get a cached analysis result or return null.
840   ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
841     typename AnalysisResultMapT::const_iterator RI =
842         AnalysisResults.find({ID, &IR});
843     return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
844   }
845
846   /// \brief Invalidate a function pass result.
847   void invalidateImpl(AnalysisKey *ID, IRUnitT &IR) {
848     typename AnalysisResultMapT::iterator RI =
849         AnalysisResults.find({ID, &IR});
850     if (RI == AnalysisResults.end())
851       return;
852
853     if (DebugLogging)
854       dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
855              << "\n";
856     AnalysisResultLists[&IR].erase(RI->second);
857     AnalysisResults.erase(RI);
858   }
859
860   /// \brief Map type from module analysis pass ID to pass concept pointer.
861   typedef DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
862
863   /// \brief Collection of module analysis passes, indexed by ID.
864   AnalysisPassMapT AnalysisPasses;
865
866   /// \brief Map from function to a list of function analysis results.
867   ///
868   /// Provides linear time removal of all analysis results for a function and
869   /// the ultimate storage for a particular cached analysis result.
870   AnalysisResultListMapT AnalysisResultLists;
871
872   /// \brief Map from an analysis ID and function to a particular cached
873   /// analysis result.
874   AnalysisResultMapT AnalysisResults;
875
876   /// \brief Indicates whether we log to \c llvm::dbgs().
877   bool DebugLogging;
878 };
879
880 extern template class AnalysisManager<Module>;
881 /// \brief Convenience typedef for the Module analysis manager.
882 typedef AnalysisManager<Module> ModuleAnalysisManager;
883
884 extern template class AnalysisManager<Function>;
885 /// \brief Convenience typedef for the Function analysis manager.
886 typedef AnalysisManager<Function> FunctionAnalysisManager;
887
888 /// \brief An analysis over an "outer" IR unit that provides access to an
889 /// analysis manager over an "inner" IR unit.  The inner unit must be contained
890 /// in the outer unit.
891 ///
892 /// Fore example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
893 /// an analysis over Modules (the "outer" unit) that provides access to a
894 /// Function analysis manager.  The FunctionAnalysisManager is the "inner"
895 /// manager being proxied, and Functions are the "inner" unit.  The inner/outer
896 /// relationship is valid because each Function is contained in one Module.
897 ///
898 /// If you're (transitively) within a pass manager for an IR unit U that
899 /// contains IR unit V, you should never use an analysis manager over V, except
900 /// via one of these proxies.
901 ///
902 /// Note that the proxy's result is a move-only RAII object.  The validity of
903 /// the analyses in the inner analysis manager is tied to its lifetime.
904 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
905 class InnerAnalysisManagerProxy
906     : public AnalysisInfoMixin<
907           InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
908 public:
909   class Result {
910   public:
911     explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
912     Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
913       // We have to null out the analysis manager in the moved-from state
914       // because we are taking ownership of the responsibilty to clear the
915       // analysis state.
916       Arg.InnerAM = nullptr;
917     }
918     Result &operator=(Result &&RHS) {
919       InnerAM = RHS.InnerAM;
920       // We have to null out the analysis manager in the moved-from state
921       // because we are taking ownership of the responsibilty to clear the
922       // analysis state.
923       RHS.InnerAM = nullptr;
924       return *this;
925     }
926     ~Result() {
927       // InnerAM is cleared in a moved from state where there is nothing to do.
928       if (!InnerAM)
929         return;
930
931       // Clear out the analysis manager if we're being destroyed -- it means we
932       // didn't even see an invalidate call when we got invalidated.
933       InnerAM->clear();
934     }
935
936     /// \brief Accessor for the analysis manager.
937     AnalysisManagerT &getManager() { return *InnerAM; }
938
939     /// \brief Handler for invalidation of the outer IR unit, \c IRUnitT.
940     ///
941     /// If the proxy analysis itself is not preserved, we assume that the set of
942     /// inner IR objects contained in IRUnit may have changed.  In this case,
943     /// we have to call \c clear() on the inner analysis manager, as it may now
944     /// have stale pointers to its inner IR objects.
945     ///
946     /// Regardless of whether the proxy analysis is marked as preserved, all of
947     /// the analyses in the inner analysis manager are potentially invalidated
948     /// based on the set of preserved analyses.
949     bool invalidate(
950         IRUnitT &IR, const PreservedAnalyses &PA,
951         typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
952
953   private:
954     AnalysisManagerT *InnerAM;
955   };
956
957   explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
958       : InnerAM(&InnerAM) {}
959
960   /// \brief Run the analysis pass and create our proxy result object.
961   ///
962   /// This doesn't do any interesting work; it is primarily used to insert our
963   /// proxy result object into the outer analysis cache so that we can proxy
964   /// invalidation to the inner analysis manager.
965   Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
966              ExtraArgTs...) {
967     return Result(*InnerAM);
968   }
969
970 private:
971   friend AnalysisInfoMixin<
972       InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
973   static AnalysisKey Key;
974
975   AnalysisManagerT *InnerAM;
976 };
977
978 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
979 AnalysisKey
980     InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
981
982 /// Provide the \c FunctionAnalysisManager to \c Module proxy.
983 typedef InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>
984     FunctionAnalysisManagerModuleProxy;
985
986 /// Specialization of the invalidate method for the \c
987 /// FunctionAnalysisManagerModuleProxy's result.
988 template <>
989 bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
990     Module &M, const PreservedAnalyses &PA,
991     ModuleAnalysisManager::Invalidator &Inv);
992
993 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
994 // template.
995 extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
996                                                 Module>;
997
998 /// \brief An analysis over an "inner" IR unit that provides access to an
999 /// analysis manager over a "outer" IR unit.  The inner unit must be contained
1000 /// in the outer unit.
1001 ///
1002 /// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
1003 /// analysis over Functions (the "inner" unit) which provides access to a Module
1004 /// analysis manager.  The ModuleAnalysisManager is the "outer" manager being
1005 /// proxied, and Modules are the "outer" IR unit.  The inner/outer relationship
1006 /// is valid because each Function is contained in one Module.
1007 ///
1008 /// This proxy only exposes the const interface of the outer analysis manager,
1009 /// to indicate that you cannot cause an outer analysis to run from within an
1010 /// inner pass.  Instead, you must rely on the \c getCachedResult API.
1011 ///
1012 /// This proxy doesn't manage invalidation in any way -- that is handled by the
1013 /// recursive return path of each layer of the pass manager.  A consequence of
1014 /// this is the outer analyses may be stale.  We invalidate the outer analyses
1015 /// only when we're done running passes over the inner IR units.
1016 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1017 class OuterAnalysisManagerProxy
1018     : public AnalysisInfoMixin<
1019           OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
1020 public:
1021   /// \brief Result proxy object for \c OuterAnalysisManagerProxy.
1022   class Result {
1023   public:
1024     explicit Result(const AnalysisManagerT &AM) : AM(&AM) {}
1025
1026     const AnalysisManagerT &getManager() const { return *AM; }
1027
1028     /// \brief Handle invalidation by ignoring it; this pass is immutable.
1029     bool invalidate(
1030         IRUnitT &, const PreservedAnalyses &,
1031         typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &) {
1032       return false;
1033     }
1034
1035     /// Register a deferred invalidation event for when the outer analysis
1036     /// manager processes its invalidations.
1037     template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1038     void registerOuterAnalysisInvalidation() {
1039       AnalysisKey *OuterID = OuterAnalysisT::ID();
1040       AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1041
1042       auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
1043       // Note, this is a linear scan. If we end up with large numbers of
1044       // analyses that all trigger invalidation on the same outer analysis,
1045       // this entire system should be changed to some other deterministic
1046       // data structure such as a `SetVector` of a pair of pointers.
1047       auto InvalidatedIt = std::find(InvalidatedIDList.begin(),
1048                                      InvalidatedIDList.end(), InvalidatedID);
1049       if (InvalidatedIt == InvalidatedIDList.end())
1050         InvalidatedIDList.push_back(InvalidatedID);
1051     }
1052
1053     /// Access the map from outer analyses to deferred invalidation requiring
1054     /// analyses.
1055     const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
1056     getOuterInvalidations() const {
1057       return OuterAnalysisInvalidationMap;
1058     }
1059
1060   private:
1061     const AnalysisManagerT *AM;
1062
1063     /// A map from an outer analysis ID to the set of this IR-unit's analyses
1064     /// which need to be invalidated.
1065     SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
1066         OuterAnalysisInvalidationMap;
1067   };
1068
1069   OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {}
1070
1071   /// \brief Run the analysis pass and create our proxy result object.
1072   /// Nothing to see here, it just forwards the \c AM reference into the
1073   /// result.
1074   Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
1075              ExtraArgTs...) {
1076     return Result(*AM);
1077   }
1078
1079 private:
1080   friend AnalysisInfoMixin<
1081       OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
1082   static AnalysisKey Key;
1083
1084   const AnalysisManagerT *AM;
1085 };
1086
1087 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1088 AnalysisKey
1089     OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1090
1091 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1092                                                 Function>;
1093 /// Provide the \c ModuleAnalysisManager to \c Function proxy.
1094 typedef OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>
1095     ModuleAnalysisManagerFunctionProxy;
1096
1097 /// \brief Trivial adaptor that maps from a module to its functions.
1098 ///
1099 /// Designed to allow composition of a FunctionPass(Manager) and
1100 /// a ModulePassManager, by running the FunctionPass(Manager) over every
1101 /// function in the module.
1102 ///
1103 /// Function passes run within this adaptor can rely on having exclusive access
1104 /// to the function they are run over. They should not read or modify any other
1105 /// functions! Other threads or systems may be manipulating other functions in
1106 /// the module, and so their state should never be relied on.
1107 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1108 /// violate this principle.
1109 ///
1110 /// Function passes can also read the module containing the function, but they
1111 /// should not modify that module outside of the use lists of various globals.
1112 /// For example, a function pass is not permitted to add functions to the
1113 /// module.
1114 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1115 /// violate this principle.
1116 ///
1117 /// Note that although function passes can access module analyses, module
1118 /// analyses are not invalidated while the function passes are running, so they
1119 /// may be stale.  Function analyses will not be stale.
1120 template <typename FunctionPassT>
1121 class ModuleToFunctionPassAdaptor
1122     : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> {
1123 public:
1124   explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
1125       : Pass(std::move(Pass)) {}
1126
1127   /// \brief Runs the function pass across every function in the module.
1128   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
1129     FunctionAnalysisManager &FAM =
1130         AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1131
1132     PreservedAnalyses PA = PreservedAnalyses::all();
1133     for (Function &F : M) {
1134       if (F.isDeclaration())
1135         continue;
1136
1137       PreservedAnalyses PassPA = Pass.run(F, FAM);
1138
1139       // We know that the function pass couldn't have invalidated any other
1140       // function's analyses (that's the contract of a function pass), so
1141       // directly handle the function analysis manager's invalidation here.
1142       FAM.invalidate(F, PassPA);
1143
1144       // Then intersect the preserved set so that invalidation of module
1145       // analyses will eventually occur when the module pass completes.
1146       PA.intersect(std::move(PassPA));
1147     }
1148
1149     // The FunctionAnalysisManagerModuleProxy is preserved because (we assume)
1150     // the function passes we ran didn't add or remove any functions.
1151     //
1152     // We also preserve all analyses on Functions, because we did all the
1153     // invalidation we needed to do above.
1154     PA.preserveSet<AllAnalysesOn<Function>>();
1155     PA.preserve<FunctionAnalysisManagerModuleProxy>();
1156     return PA;
1157   }
1158
1159 private:
1160   FunctionPassT Pass;
1161 };
1162
1163 /// \brief A function to deduce a function pass type and wrap it in the
1164 /// templated adaptor.
1165 template <typename FunctionPassT>
1166 ModuleToFunctionPassAdaptor<FunctionPassT>
1167 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
1168   return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
1169 }
1170
1171 /// \brief A utility pass template to force an analysis result to be available.
1172 ///
1173 /// If there are extra arguments at the pass's run level there may also be
1174 /// extra arguments to the analysis manager's \c getResult routine. We can't
1175 /// guess how to effectively map the arguments from one to the other, and so
1176 /// this specialization just ignores them.
1177 ///
1178 /// Specific patterns of run-method extra arguments and analysis manager extra
1179 /// arguments will have to be defined as appropriate specializations.
1180 template <typename AnalysisT, typename IRUnitT,
1181           typename AnalysisManagerT = AnalysisManager<IRUnitT>,
1182           typename... ExtraArgTs>
1183 struct RequireAnalysisPass
1184     : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1185                                         ExtraArgTs...>> {
1186   /// \brief Run this pass over some unit of IR.
1187   ///
1188   /// This pass can be run over any unit of IR and use any analysis manager
1189   /// provided they satisfy the basic API requirements. When this pass is
1190   /// created, these methods can be instantiated to satisfy whatever the
1191   /// context requires.
1192   PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
1193                         ExtraArgTs &&... Args) {
1194     (void)AM.template getResult<AnalysisT>(Arg,
1195                                            std::forward<ExtraArgTs>(Args)...);
1196
1197     return PreservedAnalyses::all();
1198   }
1199 };
1200
1201 /// \brief A no-op pass template which simply forces a specific analysis result
1202 /// to be invalidated.
1203 template <typename AnalysisT>
1204 struct InvalidateAnalysisPass
1205     : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
1206   /// \brief Run this pass over some unit of IR.
1207   ///
1208   /// This pass can be run over any unit of IR and use any analysis manager,
1209   /// provided they satisfy the basic API requirements. When this pass is
1210   /// created, these methods can be instantiated to satisfy whatever the
1211   /// context requires.
1212   template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1213   PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
1214     auto PA = PreservedAnalyses::all();
1215     PA.abandon<AnalysisT>();
1216     return PA;
1217   }
1218 };
1219
1220 /// \brief A utility pass that does nothing, but preserves no analyses.
1221 ///
1222 /// Because this preserves no analyses, any analysis passes queried after this
1223 /// pass runs will recompute fresh results.
1224 struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
1225   /// \brief Run this pass over some unit of IR.
1226   template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1227   PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
1228     return PreservedAnalyses::none();
1229   }
1230 };
1231
1232 /// A utility pass template that simply runs another pass multiple times.
1233 ///
1234 /// This can be useful when debugging or testing passes. It also serves as an
1235 /// example of how to extend the pass manager in ways beyond composition.
1236 template <typename PassT>
1237 class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> {
1238 public:
1239   RepeatedPass(int Count, PassT P) : Count(Count), P(std::move(P)) {}
1240
1241   template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
1242   PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, Ts &&... Args) {
1243     auto PA = PreservedAnalyses::all();
1244     for (int i = 0; i < Count; ++i)
1245       PA.intersect(P.run(Arg, AM, std::forward<Ts>(Args)...));
1246     return PA;
1247   }
1248
1249 private:
1250   int Count;
1251   PassT P;
1252 };
1253
1254 template <typename PassT>
1255 RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) {
1256   return RepeatedPass<PassT>(Count, std::move(P));
1257 }
1258
1259 }
1260
1261 #endif