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