Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:09

0001 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 /// \file
0009 ///
0010 /// This header defines various interfaces for pass management in LLVM. There
0011 /// is no "pass" interface in LLVM per se. Instead, an instance of any class
0012 /// which supports a method to 'run' it over a unit of IR can be used as
0013 /// a pass. A pass manager is generally a tool to collect a sequence of passes
0014 /// which run over a particular IR construct, and run each of them in sequence
0015 /// over each such construct in the containing IR construct. As there is no
0016 /// containing IR construct for a Module, a manager for passes over modules
0017 /// forms the base case which runs its managed passes in sequence over the
0018 /// single module provided.
0019 ///
0020 /// The core IR library provides managers for running passes over
0021 /// modules and functions.
0022 ///
0023 /// * FunctionPassManager can run over a Module, runs each pass over
0024 ///   a Function.
0025 /// * ModulePassManager must be directly run, runs each pass over the Module.
0026 ///
0027 /// Note that the implementations of the pass managers use concept-based
0028 /// polymorphism as outlined in the "Value Semantics and Concept-based
0029 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
0030 /// Class of Evil") by Sean Parent:
0031 /// * https://sean-parent.stlab.cc/papers-and-presentations
0032 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8
0033 /// * https://learn.microsoft.com/en-us/shows/goingnative-2013/inheritance-base-class-of-evil
0034 ///
0035 //===----------------------------------------------------------------------===//
0036 
0037 #ifndef LLVM_IR_PASSMANAGER_H
0038 #define LLVM_IR_PASSMANAGER_H
0039 
0040 #include "llvm/ADT/DenseMap.h"
0041 #include "llvm/ADT/STLExtras.h"
0042 #include "llvm/ADT/StringRef.h"
0043 #include "llvm/ADT/TinyPtrVector.h"
0044 #include "llvm/IR/Analysis.h"
0045 #include "llvm/IR/PassManagerInternal.h"
0046 #include "llvm/Support/TypeName.h"
0047 #include <cassert>
0048 #include <cstring>
0049 #include <iterator>
0050 #include <list>
0051 #include <memory>
0052 #include <tuple>
0053 #include <type_traits>
0054 #include <utility>
0055 #include <vector>
0056 
0057 namespace llvm {
0058 
0059 class Function;
0060 class Module;
0061 
0062 // Forward declare the analysis manager template.
0063 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
0064 
0065 /// A CRTP mix-in to automatically provide informational APIs needed for
0066 /// passes.
0067 ///
0068 /// This provides some boilerplate for types that are passes.
0069 template <typename DerivedT> struct PassInfoMixin {
0070   /// Gets the name of the pass we are mixed into.
0071   static StringRef name() {
0072     static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
0073                   "Must pass the derived type as the template argument!");
0074     StringRef Name = getTypeName<DerivedT>();
0075     Name.consume_front("llvm::");
0076     return Name;
0077   }
0078 
0079   void printPipeline(raw_ostream &OS,
0080                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
0081     StringRef ClassName = DerivedT::name();
0082     auto PassName = MapClassName2PassName(ClassName);
0083     OS << PassName;
0084   }
0085 };
0086 
0087 /// A CRTP mix-in that provides informational APIs needed for analysis passes.
0088 ///
0089 /// This provides some boilerplate for types that are analysis passes. It
0090 /// automatically mixes in \c PassInfoMixin.
0091 template <typename DerivedT>
0092 struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
0093   /// Returns an opaque, unique ID for this analysis type.
0094   ///
0095   /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
0096   /// suitable for use in sets, maps, and other data structures that use the low
0097   /// bits of pointers.
0098   ///
0099   /// Note that this requires the derived type provide a static \c AnalysisKey
0100   /// member called \c Key.
0101   ///
0102   /// FIXME: The only reason the mixin type itself can't declare the Key value
0103   /// is that some compilers cannot correctly unique a templated static variable
0104   /// so it has the same addresses in each instantiation. The only currently
0105   /// known platform with this limitation is Windows DLL builds, specifically
0106   /// building each part of LLVM as a DLL. If we ever remove that build
0107   /// configuration, this mixin can provide the static key as well.
0108   static AnalysisKey *ID() {
0109     static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
0110                   "Must pass the derived type as the template argument!");
0111     return &DerivedT::Key;
0112   }
0113 };
0114 
0115 namespace detail {
0116 
0117 /// Actual unpacker of extra arguments in getAnalysisResult,
0118 /// passes only those tuple arguments that are mentioned in index_sequence.
0119 template <typename PassT, typename IRUnitT, typename AnalysisManagerT,
0120           typename... ArgTs, size_t... Ns>
0121 typename PassT::Result
0122 getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR,
0123                              std::tuple<ArgTs...> Args,
0124                              std::index_sequence<Ns...>) {
0125   (void)Args;
0126   return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
0127 }
0128 
0129 /// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
0130 ///
0131 /// Arguments passed in tuple come from PassManager, so they might have extra
0132 /// arguments after those AnalysisManager's ExtraArgTs ones that we need to
0133 /// pass to getResult.
0134 template <typename PassT, typename IRUnitT, typename... AnalysisArgTs,
0135           typename... MainArgTs>
0136 typename PassT::Result
0137 getAnalysisResult(AnalysisManager<IRUnitT, AnalysisArgTs...> &AM, IRUnitT &IR,
0138                   std::tuple<MainArgTs...> Args) {
0139   return (getAnalysisResultUnpackTuple<
0140           PassT, IRUnitT>)(AM, IR, Args,
0141                            std::index_sequence_for<AnalysisArgTs...>{});
0142 }
0143 
0144 } // namespace detail
0145 
0146 /// Manages a sequence of passes over a particular unit of IR.
0147 ///
0148 /// A pass manager contains a sequence of passes to run over a particular unit
0149 /// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
0150 /// IR, and when run over some given IR will run each of its contained passes in
0151 /// sequence. Pass managers are the primary and most basic building block of a
0152 /// pass pipeline.
0153 ///
0154 /// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
0155 /// argument. The pass manager will propagate that analysis manager to each
0156 /// pass it runs, and will call the analysis manager's invalidation routine with
0157 /// the PreservedAnalyses of each pass it runs.
0158 template <typename IRUnitT,
0159           typename AnalysisManagerT = AnalysisManager<IRUnitT>,
0160           typename... ExtraArgTs>
0161 class PassManager : public PassInfoMixin<
0162                         PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
0163 public:
0164   /// Construct a pass manager.
0165   explicit PassManager() = default;
0166 
0167   // FIXME: These are equivalent to the default move constructor/move
0168   // assignment. However, using = default triggers linker errors due to the
0169   // explicit instantiations below. Find away to use the default and remove the
0170   // duplicated code here.
0171   PassManager(PassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
0172 
0173   PassManager &operator=(PassManager &&RHS) {
0174     Passes = std::move(RHS.Passes);
0175     return *this;
0176   }
0177 
0178   void printPipeline(raw_ostream &OS,
0179                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
0180     for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
0181       auto *P = Passes[Idx].get();
0182       P->printPipeline(OS, MapClassName2PassName);
0183       if (Idx + 1 < Size)
0184         OS << ',';
0185     }
0186   }
0187 
0188   /// Run all of the passes in this manager over the given unit of IR.
0189   /// ExtraArgs are passed to each pass.
0190   PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
0191                         ExtraArgTs... ExtraArgs);
0192 
0193   template <typename PassT>
0194   LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v<PassT, PassManager>>
0195   addPass(PassT &&Pass) {
0196     using PassModelT =
0197         detail::PassModel<IRUnitT, PassT, AnalysisManagerT, ExtraArgTs...>;
0198     // Do not use make_unique or emplace_back, they cause too many template
0199     // instantiations, causing terrible compile times.
0200     Passes.push_back(std::unique_ptr<PassConceptT>(
0201         new PassModelT(std::forward<PassT>(Pass))));
0202   }
0203 
0204   /// When adding a pass manager pass that has the same type as this pass
0205   /// manager, simply move the passes over. This is because we don't have
0206   /// use cases rely on executing nested pass managers. Doing this could
0207   /// reduce implementation complexity and avoid potential invalidation
0208   /// issues that may happen with nested pass managers of the same type.
0209   template <typename PassT>
0210   LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<std::is_same_v<PassT, PassManager>>
0211   addPass(PassT &&Pass) {
0212     for (auto &P : Pass.Passes)
0213       Passes.push_back(std::move(P));
0214   }
0215 
0216   /// Returns if the pass manager contains any passes.
0217   bool isEmpty() const { return Passes.empty(); }
0218 
0219   static bool isRequired() { return true; }
0220 
0221 protected:
0222   using PassConceptT =
0223       detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
0224 
0225   std::vector<std::unique_ptr<PassConceptT>> Passes;
0226 };
0227 
0228 template <typename IRUnitT>
0229 void printIRUnitNameForStackTrace(raw_ostream &OS, const IRUnitT &IR);
0230 
0231 template <>
0232 void printIRUnitNameForStackTrace<Module>(raw_ostream &OS, const Module &IR);
0233 
0234 extern template class PassManager<Module>;
0235 
0236 /// Convenience typedef for a pass manager over modules.
0237 using ModulePassManager = PassManager<Module>;
0238 
0239 template <>
0240 void printIRUnitNameForStackTrace<Function>(raw_ostream &OS,
0241                                             const Function &IR);
0242 
0243 extern template class PassManager<Function>;
0244 
0245 /// Convenience typedef for a pass manager over functions.
0246 using FunctionPassManager = PassManager<Function>;
0247 
0248 /// A container for analyses that lazily runs them and caches their
0249 /// results.
0250 ///
0251 /// This class can manage analyses for any IR unit where the address of the IR
0252 /// unit sufficies as its identity.
0253 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
0254 public:
0255   class Invalidator;
0256 
0257 private:
0258   // Now that we've defined our invalidator, we can define the concept types.
0259   using ResultConceptT = detail::AnalysisResultConcept<IRUnitT, Invalidator>;
0260   using PassConceptT =
0261       detail::AnalysisPassConcept<IRUnitT, Invalidator, ExtraArgTs...>;
0262 
0263   /// List of analysis pass IDs and associated concept pointers.
0264   ///
0265   /// Requires iterators to be valid across appending new entries and arbitrary
0266   /// erases. Provides the analysis ID to enable finding iterators to a given
0267   /// entry in maps below, and provides the storage for the actual result
0268   /// concept.
0269   using AnalysisResultListT =
0270       std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>;
0271 
0272   /// Map type from IRUnitT pointer to our custom list type.
0273   using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>;
0274 
0275   /// Map type from a pair of analysis ID and IRUnitT pointer to an
0276   /// iterator into a particular result list (which is where the actual analysis
0277   /// result is stored).
0278   using AnalysisResultMapT =
0279       DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
0280                typename AnalysisResultListT::iterator>;
0281 
0282 public:
0283   /// API to communicate dependencies between analyses during invalidation.
0284   ///
0285   /// When an analysis result embeds handles to other analysis results, it
0286   /// needs to be invalidated both when its own information isn't preserved and
0287   /// when any of its embedded analysis results end up invalidated. We pass an
0288   /// \c Invalidator object as an argument to \c invalidate() in order to let
0289   /// the analysis results themselves define the dependency graph on the fly.
0290   /// This lets us avoid building an explicit representation of the
0291   /// dependencies between analysis results.
0292   class Invalidator {
0293   public:
0294     /// Trigger the invalidation of some other analysis pass if not already
0295     /// handled and return whether it was in fact invalidated.
0296     ///
0297     /// This is expected to be called from within a given analysis result's \c
0298     /// invalidate method to trigger a depth-first walk of all inter-analysis
0299     /// dependencies. The same \p IR unit and \p PA passed to that result's \c
0300     /// invalidate method should in turn be provided to this routine.
0301     ///
0302     /// The first time this is called for a given analysis pass, it will call
0303     /// the corresponding result's \c invalidate method.  Subsequent calls will
0304     /// use a cache of the results of that initial call.  It is an error to form
0305     /// cyclic dependencies between analysis results.
0306     ///
0307     /// This returns true if the given analysis's result is invalid. Any
0308     /// dependecies on it will become invalid as a result.
0309     template <typename PassT>
0310     bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
0311       using ResultModelT =
0312           detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
0313                                       Invalidator>;
0314 
0315       return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
0316     }
0317 
0318     /// A type-erased variant of the above invalidate method with the same core
0319     /// API other than passing an analysis ID rather than an analysis type
0320     /// parameter.
0321     ///
0322     /// This is sadly less efficient than the above routine, which leverages
0323     /// the type parameter to avoid the type erasure overhead.
0324     bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
0325       return invalidateImpl<>(ID, IR, PA);
0326     }
0327 
0328   private:
0329     friend class AnalysisManager;
0330 
0331     template <typename ResultT = ResultConceptT>
0332     bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
0333                         const PreservedAnalyses &PA) {
0334       // If we've already visited this pass, return true if it was invalidated
0335       // and false otherwise.
0336       auto IMapI = IsResultInvalidated.find(ID);
0337       if (IMapI != IsResultInvalidated.end())
0338         return IMapI->second;
0339 
0340       // Otherwise look up the result object.
0341       auto RI = Results.find({ID, &IR});
0342       assert(RI != Results.end() &&
0343              "Trying to invalidate a dependent result that isn't in the "
0344              "manager's cache is always an error, likely due to a stale result "
0345              "handle!");
0346 
0347       auto &Result = static_cast<ResultT &>(*RI->second->second);
0348 
0349       // Insert into the map whether the result should be invalidated and return
0350       // that. Note that we cannot reuse IMapI and must do a fresh insert here,
0351       // as calling invalidate could (recursively) insert things into the map,
0352       // making any iterator or reference invalid.
0353       bool Inserted;
0354       std::tie(IMapI, Inserted) =
0355           IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
0356       (void)Inserted;
0357       assert(Inserted && "Should not have already inserted this ID, likely "
0358                          "indicates a dependency cycle!");
0359       return IMapI->second;
0360     }
0361 
0362     Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
0363                 const AnalysisResultMapT &Results)
0364         : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
0365 
0366     SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
0367     const AnalysisResultMapT &Results;
0368   };
0369 
0370   /// Construct an empty analysis manager.
0371   AnalysisManager();
0372   AnalysisManager(AnalysisManager &&);
0373   AnalysisManager &operator=(AnalysisManager &&);
0374 
0375   /// Returns true if the analysis manager has an empty results cache.
0376   bool empty() const {
0377     assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
0378            "The storage and index of analysis results disagree on how many "
0379            "there are!");
0380     return AnalysisResults.empty();
0381   }
0382 
0383   /// Clear any cached analysis results for a single unit of IR.
0384   ///
0385   /// This doesn't invalidate, but instead simply deletes, the relevant results.
0386   /// It is useful when the IR is being removed and we want to clear out all the
0387   /// memory pinned for it.
0388   void clear(IRUnitT &IR, llvm::StringRef Name);
0389 
0390   /// Clear all analysis results cached by this AnalysisManager.
0391   ///
0392   /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
0393   /// deletes them.  This lets you clean up the AnalysisManager when the set of
0394   /// IR units itself has potentially changed, and thus we can't even look up a
0395   /// a result and invalidate/clear it directly.
0396   void clear() {
0397     AnalysisResults.clear();
0398     AnalysisResultLists.clear();
0399   }
0400 
0401   /// Returns true if the specified analysis pass is registered.
0402   template <typename PassT> bool isPassRegistered() const {
0403     return AnalysisPasses.count(PassT::ID());
0404   }
0405 
0406   /// Get the result of an analysis pass for a given IR unit.
0407   ///
0408   /// Runs the analysis if a cached result is not available.
0409   template <typename PassT>
0410   typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
0411     assert(AnalysisPasses.count(PassT::ID()) &&
0412            "This analysis pass was not registered prior to being queried");
0413     ResultConceptT &ResultConcept =
0414         getResultImpl(PassT::ID(), IR, ExtraArgs...);
0415 
0416     using ResultModelT =
0417         detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
0418                                     Invalidator>;
0419 
0420     return static_cast<ResultModelT &>(ResultConcept).Result;
0421   }
0422 
0423   /// Get the cached result of an analysis pass for a given IR unit.
0424   ///
0425   /// This method never runs the analysis.
0426   ///
0427   /// \returns null if there is no cached result.
0428   template <typename PassT>
0429   typename PassT::Result *getCachedResult(IRUnitT &IR) const {
0430     assert(AnalysisPasses.count(PassT::ID()) &&
0431            "This analysis pass was not registered prior to being queried");
0432 
0433     ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
0434     if (!ResultConcept)
0435       return nullptr;
0436 
0437     using ResultModelT =
0438         detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
0439                                     Invalidator>;
0440 
0441     return &static_cast<ResultModelT *>(ResultConcept)->Result;
0442   }
0443 
0444   /// Verify that the given Result cannot be invalidated, assert otherwise.
0445   template <typename PassT>
0446   void verifyNotInvalidated(IRUnitT &IR, typename PassT::Result *Result) const {
0447     PreservedAnalyses PA = PreservedAnalyses::none();
0448     SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
0449     Invalidator Inv(IsResultInvalidated, AnalysisResults);
0450     assert(!Result->invalidate(IR, PA, Inv) &&
0451            "Cached result cannot be invalidated");
0452   }
0453 
0454   /// Register an analysis pass with the manager.
0455   ///
0456   /// The parameter is a callable whose result is an analysis pass. This allows
0457   /// passing in a lambda to construct the analysis.
0458   ///
0459   /// The analysis type to register is the type returned by calling the \c
0460   /// PassBuilder argument. If that type has already been registered, then the
0461   /// argument will not be called and this function will return false.
0462   /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
0463   /// and this function returns true.
0464   ///
0465   /// (Note: Although the return value of this function indicates whether or not
0466   /// an analysis was previously registered, you should just register all the
0467   /// analyses you might want and let this class run them lazily.  This idiom
0468   /// lets us minimize the number of times we have to look up analyses in our
0469   /// hashtable.)
0470   template <typename PassBuilderT>
0471   bool registerPass(PassBuilderT &&PassBuilder) {
0472     using PassT = decltype(PassBuilder());
0473     using PassModelT =
0474         detail::AnalysisPassModel<IRUnitT, PassT, Invalidator, ExtraArgTs...>;
0475 
0476     auto &PassPtr = AnalysisPasses[PassT::ID()];
0477     if (PassPtr)
0478       // Already registered this pass type!
0479       return false;
0480 
0481     // Construct a new model around the instance returned by the builder.
0482     PassPtr.reset(new PassModelT(PassBuilder()));
0483     return true;
0484   }
0485 
0486   /// Invalidate cached analyses for an IR unit.
0487   ///
0488   /// Walk through all of the analyses pertaining to this unit of IR and
0489   /// invalidate them, unless they are preserved by the PreservedAnalyses set.
0490   void invalidate(IRUnitT &IR, const PreservedAnalyses &PA);
0491 
0492 private:
0493   /// Look up a registered analysis pass.
0494   PassConceptT &lookUpPass(AnalysisKey *ID) {
0495     typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
0496     assert(PI != AnalysisPasses.end() &&
0497            "Analysis passes must be registered prior to being queried!");
0498     return *PI->second;
0499   }
0500 
0501   /// Look up a registered analysis pass.
0502   const PassConceptT &lookUpPass(AnalysisKey *ID) const {
0503     typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
0504     assert(PI != AnalysisPasses.end() &&
0505            "Analysis passes must be registered prior to being queried!");
0506     return *PI->second;
0507   }
0508 
0509   /// Get an analysis result, running the pass if necessary.
0510   ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
0511                                 ExtraArgTs... ExtraArgs);
0512 
0513   /// Get a cached analysis result or return null.
0514   ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
0515     typename AnalysisResultMapT::const_iterator RI =
0516         AnalysisResults.find({ID, &IR});
0517     return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
0518   }
0519 
0520   /// Map type from analysis pass ID to pass concept pointer.
0521   using AnalysisPassMapT =
0522       DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>;
0523 
0524   /// Collection of analysis passes, indexed by ID.
0525   AnalysisPassMapT AnalysisPasses;
0526 
0527   /// Map from IR unit to a list of analysis results.
0528   ///
0529   /// Provides linear time removal of all analysis results for a IR unit and
0530   /// the ultimate storage for a particular cached analysis result.
0531   AnalysisResultListMapT AnalysisResultLists;
0532 
0533   /// Map from an analysis ID and IR unit to a particular cached
0534   /// analysis result.
0535   AnalysisResultMapT AnalysisResults;
0536 };
0537 
0538 extern template class AnalysisManager<Module>;
0539 
0540 /// Convenience typedef for the Module analysis manager.
0541 using ModuleAnalysisManager = AnalysisManager<Module>;
0542 
0543 extern template class AnalysisManager<Function>;
0544 
0545 /// Convenience typedef for the Function analysis manager.
0546 using FunctionAnalysisManager = AnalysisManager<Function>;
0547 
0548 /// An analysis over an "outer" IR unit that provides access to an
0549 /// analysis manager over an "inner" IR unit.  The inner unit must be contained
0550 /// in the outer unit.
0551 ///
0552 /// For example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
0553 /// an analysis over Modules (the "outer" unit) that provides access to a
0554 /// Function analysis manager.  The FunctionAnalysisManager is the "inner"
0555 /// manager being proxied, and Functions are the "inner" unit.  The inner/outer
0556 /// relationship is valid because each Function is contained in one Module.
0557 ///
0558 /// If you're (transitively) within a pass manager for an IR unit U that
0559 /// contains IR unit V, you should never use an analysis manager over V, except
0560 /// via one of these proxies.
0561 ///
0562 /// Note that the proxy's result is a move-only RAII object.  The validity of
0563 /// the analyses in the inner analysis manager is tied to its lifetime.
0564 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
0565 class InnerAnalysisManagerProxy
0566     : public AnalysisInfoMixin<
0567           InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
0568 public:
0569   class Result {
0570   public:
0571     explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
0572 
0573     Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
0574       // We have to null out the analysis manager in the moved-from state
0575       // because we are taking ownership of the responsibilty to clear the
0576       // analysis state.
0577       Arg.InnerAM = nullptr;
0578     }
0579 
0580     ~Result() {
0581       // InnerAM is cleared in a moved from state where there is nothing to do.
0582       if (!InnerAM)
0583         return;
0584 
0585       // Clear out the analysis manager if we're being destroyed -- it means we
0586       // didn't even see an invalidate call when we got invalidated.
0587       InnerAM->clear();
0588     }
0589 
0590     Result &operator=(Result &&RHS) {
0591       InnerAM = RHS.InnerAM;
0592       // We have to null out the analysis manager in the moved-from state
0593       // because we are taking ownership of the responsibilty to clear the
0594       // analysis state.
0595       RHS.InnerAM = nullptr;
0596       return *this;
0597     }
0598 
0599     /// Accessor for the analysis manager.
0600     AnalysisManagerT &getManager() { return *InnerAM; }
0601 
0602     /// Handler for invalidation of the outer IR unit, \c IRUnitT.
0603     ///
0604     /// If the proxy analysis itself is not preserved, we assume that the set of
0605     /// inner IR objects contained in IRUnit may have changed.  In this case,
0606     /// we have to call \c clear() on the inner analysis manager, as it may now
0607     /// have stale pointers to its inner IR objects.
0608     ///
0609     /// Regardless of whether the proxy analysis is marked as preserved, all of
0610     /// the analyses in the inner analysis manager are potentially invalidated
0611     /// based on the set of preserved analyses.
0612     bool invalidate(
0613         IRUnitT &IR, const PreservedAnalyses &PA,
0614         typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
0615 
0616   private:
0617     AnalysisManagerT *InnerAM;
0618   };
0619 
0620   explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
0621       : InnerAM(&InnerAM) {}
0622 
0623   /// Run the analysis pass and create our proxy result object.
0624   ///
0625   /// This doesn't do any interesting work; it is primarily used to insert our
0626   /// proxy result object into the outer analysis cache so that we can proxy
0627   /// invalidation to the inner analysis manager.
0628   Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
0629              ExtraArgTs...) {
0630     return Result(*InnerAM);
0631   }
0632 
0633 private:
0634   friend AnalysisInfoMixin<
0635       InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
0636 
0637   static AnalysisKey Key;
0638 
0639   AnalysisManagerT *InnerAM;
0640 };
0641 
0642 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
0643 AnalysisKey
0644     InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
0645 
0646 /// Provide the \c FunctionAnalysisManager to \c Module proxy.
0647 using FunctionAnalysisManagerModuleProxy =
0648     InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>;
0649 
0650 /// Specialization of the invalidate method for the \c
0651 /// FunctionAnalysisManagerModuleProxy's result.
0652 template <>
0653 bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
0654     Module &M, const PreservedAnalyses &PA,
0655     ModuleAnalysisManager::Invalidator &Inv);
0656 
0657 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
0658 // template.
0659 extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
0660                                                 Module>;
0661 
0662 /// An analysis over an "inner" IR unit that provides access to an
0663 /// analysis manager over a "outer" IR unit.  The inner unit must be contained
0664 /// in the outer unit.
0665 ///
0666 /// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
0667 /// analysis over Functions (the "inner" unit) which provides access to a Module
0668 /// analysis manager.  The ModuleAnalysisManager is the "outer" manager being
0669 /// proxied, and Modules are the "outer" IR unit.  The inner/outer relationship
0670 /// is valid because each Function is contained in one Module.
0671 ///
0672 /// This proxy only exposes the const interface of the outer analysis manager,
0673 /// to indicate that you cannot cause an outer analysis to run from within an
0674 /// inner pass.  Instead, you must rely on the \c getCachedResult API.  This is
0675 /// due to keeping potential future concurrency in mind. To give an example,
0676 /// running a module analysis before any function passes may give a different
0677 /// result than running it in a function pass. Both may be valid, but it would
0678 /// produce non-deterministic results. GlobalsAA is a good analysis example,
0679 /// because the cached information has the mod/ref info for all memory for each
0680 /// function at the time the analysis was computed. The information is still
0681 /// valid after a function transformation, but it may be *different* if
0682 /// recomputed after that transform. GlobalsAA is never invalidated.
0683 
0684 ///
0685 /// This proxy doesn't manage invalidation in any way -- that is handled by the
0686 /// recursive return path of each layer of the pass manager.  A consequence of
0687 /// this is the outer analyses may be stale.  We invalidate the outer analyses
0688 /// only when we're done running passes over the inner IR units.
0689 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
0690 class OuterAnalysisManagerProxy
0691     : public AnalysisInfoMixin<
0692           OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
0693 public:
0694   /// Result proxy object for \c OuterAnalysisManagerProxy.
0695   class Result {
0696   public:
0697     explicit Result(const AnalysisManagerT &OuterAM) : OuterAM(&OuterAM) {}
0698 
0699     /// Get a cached analysis. If the analysis can be invalidated, this will
0700     /// assert.
0701     template <typename PassT, typename IRUnitTParam>
0702     typename PassT::Result *getCachedResult(IRUnitTParam &IR) const {
0703       typename PassT::Result *Res =
0704           OuterAM->template getCachedResult<PassT>(IR);
0705       if (Res)
0706         OuterAM->template verifyNotInvalidated<PassT>(IR, Res);
0707       return Res;
0708     }
0709 
0710     /// Method provided for unit testing, not intended for general use.
0711     template <typename PassT, typename IRUnitTParam>
0712     bool cachedResultExists(IRUnitTParam &IR) const {
0713       typename PassT::Result *Res =
0714           OuterAM->template getCachedResult<PassT>(IR);
0715       return Res != nullptr;
0716     }
0717 
0718     /// When invalidation occurs, remove any registered invalidation events.
0719     bool invalidate(
0720         IRUnitT &IRUnit, const PreservedAnalyses &PA,
0721         typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv) {
0722       // Loop over the set of registered outer invalidation mappings and if any
0723       // of them map to an analysis that is now invalid, clear it out.
0724       SmallVector<AnalysisKey *, 4> DeadKeys;
0725       for (auto &KeyValuePair : OuterAnalysisInvalidationMap) {
0726         AnalysisKey *OuterID = KeyValuePair.first;
0727         auto &InnerIDs = KeyValuePair.second;
0728         llvm::erase_if(InnerIDs, [&](AnalysisKey *InnerID) {
0729           return Inv.invalidate(InnerID, IRUnit, PA);
0730         });
0731         if (InnerIDs.empty())
0732           DeadKeys.push_back(OuterID);
0733       }
0734 
0735       for (auto *OuterID : DeadKeys)
0736         OuterAnalysisInvalidationMap.erase(OuterID);
0737 
0738       // The proxy itself remains valid regardless of anything else.
0739       return false;
0740     }
0741 
0742     /// Register a deferred invalidation event for when the outer analysis
0743     /// manager processes its invalidations.
0744     template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
0745     void registerOuterAnalysisInvalidation() {
0746       AnalysisKey *OuterID = OuterAnalysisT::ID();
0747       AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
0748 
0749       auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
0750       // Note, this is a linear scan. If we end up with large numbers of
0751       // analyses that all trigger invalidation on the same outer analysis,
0752       // this entire system should be changed to some other deterministic
0753       // data structure such as a `SetVector` of a pair of pointers.
0754       if (!llvm::is_contained(InvalidatedIDList, InvalidatedID))
0755         InvalidatedIDList.push_back(InvalidatedID);
0756     }
0757 
0758     /// Access the map from outer analyses to deferred invalidation requiring
0759     /// analyses.
0760     const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
0761     getOuterInvalidations() const {
0762       return OuterAnalysisInvalidationMap;
0763     }
0764 
0765   private:
0766     const AnalysisManagerT *OuterAM;
0767 
0768     /// A map from an outer analysis ID to the set of this IR-unit's analyses
0769     /// which need to be invalidated.
0770     SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
0771         OuterAnalysisInvalidationMap;
0772   };
0773 
0774   OuterAnalysisManagerProxy(const AnalysisManagerT &OuterAM)
0775       : OuterAM(&OuterAM) {}
0776 
0777   /// Run the analysis pass and create our proxy result object.
0778   /// Nothing to see here, it just forwards the \c OuterAM reference into the
0779   /// result.
0780   Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
0781              ExtraArgTs...) {
0782     return Result(*OuterAM);
0783   }
0784 
0785 private:
0786   friend AnalysisInfoMixin<
0787       OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
0788 
0789   static AnalysisKey Key;
0790 
0791   const AnalysisManagerT *OuterAM;
0792 };
0793 
0794 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
0795 AnalysisKey
0796     OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
0797 
0798 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
0799                                                 Function>;
0800 /// Provide the \c ModuleAnalysisManager to \c Function proxy.
0801 using ModuleAnalysisManagerFunctionProxy =
0802     OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>;
0803 
0804 /// Trivial adaptor that maps from a module to its functions.
0805 ///
0806 /// Designed to allow composition of a FunctionPass(Manager) and
0807 /// a ModulePassManager, by running the FunctionPass(Manager) over every
0808 /// function in the module.
0809 ///
0810 /// Function passes run within this adaptor can rely on having exclusive access
0811 /// to the function they are run over. They should not read or modify any other
0812 /// functions! Other threads or systems may be manipulating other functions in
0813 /// the module, and so their state should never be relied on.
0814 /// FIXME: Make the above true for all of LLVM's actual passes, some still
0815 /// violate this principle.
0816 ///
0817 /// Function passes can also read the module containing the function, but they
0818 /// should not modify that module outside of the use lists of various globals.
0819 /// For example, a function pass is not permitted to add functions to the
0820 /// module.
0821 /// FIXME: Make the above true for all of LLVM's actual passes, some still
0822 /// violate this principle.
0823 ///
0824 /// Note that although function passes can access module analyses, module
0825 /// analyses are not invalidated while the function passes are running, so they
0826 /// may be stale.  Function analyses will not be stale.
0827 class ModuleToFunctionPassAdaptor
0828     : public PassInfoMixin<ModuleToFunctionPassAdaptor> {
0829 public:
0830   using PassConceptT = detail::PassConcept<Function, FunctionAnalysisManager>;
0831 
0832   explicit ModuleToFunctionPassAdaptor(std::unique_ptr<PassConceptT> Pass,
0833                                        bool EagerlyInvalidate)
0834       : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate) {}
0835 
0836   /// Runs the function pass across every function in the module.
0837   PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
0838   void printPipeline(raw_ostream &OS,
0839                      function_ref<StringRef(StringRef)> MapClassName2PassName);
0840 
0841   static bool isRequired() { return true; }
0842 
0843 private:
0844   std::unique_ptr<PassConceptT> Pass;
0845   bool EagerlyInvalidate;
0846 };
0847 
0848 /// A function to deduce a function pass type and wrap it in the
0849 /// templated adaptor.
0850 template <typename FunctionPassT>
0851 ModuleToFunctionPassAdaptor
0852 createModuleToFunctionPassAdaptor(FunctionPassT &&Pass,
0853                                   bool EagerlyInvalidate = false) {
0854   using PassModelT =
0855       detail::PassModel<Function, FunctionPassT, FunctionAnalysisManager>;
0856   // Do not use make_unique, it causes too many template instantiations,
0857   // causing terrible compile times.
0858   return ModuleToFunctionPassAdaptor(
0859       std::unique_ptr<ModuleToFunctionPassAdaptor::PassConceptT>(
0860           new PassModelT(std::forward<FunctionPassT>(Pass))),
0861       EagerlyInvalidate);
0862 }
0863 
0864 /// A utility pass template to force an analysis result to be available.
0865 ///
0866 /// If there are extra arguments at the pass's run level there may also be
0867 /// extra arguments to the analysis manager's \c getResult routine. We can't
0868 /// guess how to effectively map the arguments from one to the other, and so
0869 /// this specialization just ignores them.
0870 ///
0871 /// Specific patterns of run-method extra arguments and analysis manager extra
0872 /// arguments will have to be defined as appropriate specializations.
0873 template <typename AnalysisT, typename IRUnitT,
0874           typename AnalysisManagerT = AnalysisManager<IRUnitT>,
0875           typename... ExtraArgTs>
0876 struct RequireAnalysisPass
0877     : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
0878                                         ExtraArgTs...>> {
0879   /// Run this pass over some unit of IR.
0880   ///
0881   /// This pass can be run over any unit of IR and use any analysis manager
0882   /// provided they satisfy the basic API requirements. When this pass is
0883   /// created, these methods can be instantiated to satisfy whatever the
0884   /// context requires.
0885   PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
0886                         ExtraArgTs &&... Args) {
0887     (void)AM.template getResult<AnalysisT>(Arg,
0888                                            std::forward<ExtraArgTs>(Args)...);
0889 
0890     return PreservedAnalyses::all();
0891   }
0892   void printPipeline(raw_ostream &OS,
0893                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
0894     auto ClassName = AnalysisT::name();
0895     auto PassName = MapClassName2PassName(ClassName);
0896     OS << "require<" << PassName << '>';
0897   }
0898   static bool isRequired() { return true; }
0899 };
0900 
0901 /// A no-op pass template which simply forces a specific analysis result
0902 /// to be invalidated.
0903 template <typename AnalysisT>
0904 struct InvalidateAnalysisPass
0905     : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
0906   /// Run this pass over some unit of IR.
0907   ///
0908   /// This pass can be run over any unit of IR and use any analysis manager,
0909   /// provided they satisfy the basic API requirements. When this pass is
0910   /// created, these methods can be instantiated to satisfy whatever the
0911   /// context requires.
0912   template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
0913   PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
0914     auto PA = PreservedAnalyses::all();
0915     PA.abandon<AnalysisT>();
0916     return PA;
0917   }
0918   void printPipeline(raw_ostream &OS,
0919                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
0920     auto ClassName = AnalysisT::name();
0921     auto PassName = MapClassName2PassName(ClassName);
0922     OS << "invalidate<" << PassName << '>';
0923   }
0924 };
0925 
0926 /// A utility pass that does nothing, but preserves no analyses.
0927 ///
0928 /// Because this preserves no analyses, any analysis passes queried after this
0929 /// pass runs will recompute fresh results.
0930 struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
0931   /// Run this pass over some unit of IR.
0932   template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
0933   PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
0934     return PreservedAnalyses::none();
0935   }
0936 };
0937 
0938 } // end namespace llvm
0939 
0940 #endif // LLVM_IR_PASSMANAGER_H