1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
24 /// * FunctionPassManager can run over a Module, runs each pass over
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
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
36 //===----------------------------------------------------------------------===//
38 #ifndef LLVM_IR_PASSMANAGER_H
39 #define LLVM_IR_PASSMANAGER_H
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"
58 /// A special type used by analysis passes to provide an address that
59 /// identifies that particular analysis pass type.
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 {};
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
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 {};
76 /// A set of analyses that are preserved following a run of a transformation
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
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.
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.
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.
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 ...
107 class PreservedAnalyses {
109 /// \brief Convenience factory function for the empty preserved set.
110 static PreservedAnalyses none() { return PreservedAnalyses(); }
112 /// \brief Construct a special preserved set that preserves all passes.
113 static PreservedAnalyses all() {
114 PreservedAnalyses PA;
115 PA.PreservedIDs.insert(&AllAnalysesKey);
119 /// Mark an analysis as preserved.
120 template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
122 /// \brief Given an analysis's ID, mark the analysis as preserved, adding it
124 void preserve(AnalysisKey *ID) {
125 // Clear this ID from the explicit not-preserved set if present.
126 NotPreservedAnalysisIDs.erase(ID);
128 // If we're not already preserving all analyses (other than those in
129 // NotPreservedAnalysisIDs).
130 if (!areAllPreserved())
131 PreservedIDs.insert(ID);
134 /// Mark an analysis set as preserved.
135 template <typename AnalysisSetT> void preserveSet() {
136 preserveSet(AnalysisSetT::ID());
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);
146 /// Mark an analysis as abandoned.
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.
151 /// Note that you can only abandon a specific analysis, not a *set* of
153 template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); }
155 /// Mark an analysis as abandoned using its ID.
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.
160 /// Note that you can only abandon a specific analysis, not a *set* of
162 void abandon(AnalysisKey *ID) {
163 PreservedIDs.erase(ID);
164 NotPreservedAnalysisIDs.insert(ID);
167 /// \brief Intersect this set with another in place.
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())
174 if (areAllPreserved()) {
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);
184 for (auto ID : PreservedIDs)
185 if (!Arg.PreservedIDs.count(ID))
186 PreservedIDs.erase(ID);
189 /// \brief Intersect this set with a temporary other set in place.
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())
196 if (areAllPreserved()) {
197 *this = std::move(Arg);
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);
206 for (auto ID : PreservedIDs)
207 if (!Arg.PreservedIDs.count(ID))
208 PreservedIDs.erase(ID);
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;
216 const PreservedAnalyses &PA;
217 AnalysisKey *const ID;
218 const bool IsAbandoned;
220 /// A PreservedAnalysisChecker is tied to a particular Analysis because
221 /// `preserved()` and `preservedSet()` both return false if the Analysis
223 PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID)
224 : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
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.
231 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
232 PA.PreservedIDs.count(ID));
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));
245 /// Build a checker for this `PreservedAnalyses` and the specified analysis
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());
254 /// Build a checker for this `PreservedAnalyses` and the specified analysis
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);
263 /// Test whether all analyses are preserved (and none are abandoned).
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);
272 /// Directly test whether a set of analyses is preserved.
274 /// This is only true when no analyses have been explicitly abandoned.
275 template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
276 return allAnalysesInSetPreserved(AnalysisSetT::ID());
279 /// Directly test whether a set of analyses is preserved.
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));
288 /// A special key used to indicate all analyses.
289 static AnalysisSetKey AllAnalysesKey;
291 /// The IDs of analyses and analysis sets that are preserved.
292 SmallPtrSet<void *, 2> PreservedIDs;
294 /// The IDs of explicitly not-preserved analyses.
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`.
300 /// Also, a given ID should never occur both here and in `PreservedIDs`.
301 SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
304 // Forward declare the analysis manager template.
305 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
307 /// A CRTP mix-in to automatically provide informational APIs needed for
310 /// This provides some boilerplate for types that are passes.
311 template <typename DerivedT> struct PassInfoMixin {
312 /// Gets the name of the pass we are mixed into.
313 static StringRef name() {
314 static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
315 "Must pass the derived type as the template argument!");
316 StringRef Name = getTypeName<DerivedT>();
317 if (Name.startswith("llvm::"))
318 Name = Name.drop_front(strlen("llvm::"));
323 /// A CRTP mix-in that provides informational APIs needed for analysis passes.
325 /// This provides some boilerplate for types that are analysis passes. It
326 /// automatically mixes in \c PassInfoMixin.
327 template <typename DerivedT>
328 struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
329 /// Returns an opaque, unique ID for this analysis type.
331 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
332 /// suitable for use in sets, maps, and other data structures that use the low
333 /// bits of pointers.
335 /// Note that this requires the derived type provide a static \c AnalysisKey
336 /// member called \c Key.
338 /// FIXME: The only reason the mixin type itself can't declare the Key value
339 /// is that some compilers cannot correctly unique a templated static variable
340 /// so it has the same addresses in each instantiation. The only currently
341 /// known platform with this limitation is Windows DLL builds, specifically
342 /// building each part of LLVM as a DLL. If we ever remove that build
343 /// configuration, this mixin can provide the static key as well.
344 static AnalysisKey *ID() {
345 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
346 "Must pass the derived type as the template argument!");
347 return &DerivedT::Key;
351 /// This templated class represents "all analyses that operate over \<a
352 /// particular IR unit\>" (e.g. a Function or a Module) in instances of
353 /// PreservedAnalysis.
355 /// This lets a transformation say e.g. "I preserved all function analyses".
357 /// Note that you must provide an explicit instantiation declaration and
358 /// definition for this template in order to get the correct behavior on
359 /// Windows. Otherwise, the address of SetKey will not be stable.
360 template <typename IRUnitT>
361 class AllAnalysesOn {
363 static AnalysisSetKey *ID() { return &SetKey; }
366 static AnalysisSetKey SetKey;
369 template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
371 extern template class AllAnalysesOn<Module>;
372 extern template class AllAnalysesOn<Function>;
374 /// \brief Manages a sequence of passes over a particular unit of IR.
376 /// A pass manager contains a sequence of passes to run over a particular unit
377 /// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
378 /// IR, and when run over some given IR will run each of its contained passes in
379 /// sequence. Pass managers are the primary and most basic building block of a
382 /// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
383 /// argument. The pass manager will propagate that analysis manager to each
384 /// pass it runs, and will call the analysis manager's invalidation routine with
385 /// the PreservedAnalyses of each pass it runs.
386 template <typename IRUnitT,
387 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
388 typename... ExtraArgTs>
389 class PassManager : public PassInfoMixin<
390 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
392 /// \brief Construct a pass manager.
394 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
395 explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
397 // FIXME: These are equivalent to the default move constructor/move
398 // assignment. However, using = default triggers linker errors due to the
399 // explicit instantiations below. Find away to use the default and remove the
400 // duplicated code here.
401 PassManager(PassManager &&Arg)
402 : Passes(std::move(Arg.Passes)),
403 DebugLogging(std::move(Arg.DebugLogging)) {}
405 PassManager &operator=(PassManager &&RHS) {
406 Passes = std::move(RHS.Passes);
407 DebugLogging = std::move(RHS.DebugLogging);
411 /// \brief Run all of the passes in this manager over the given unit of IR.
412 /// ExtraArgs are passed to each pass.
413 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
414 ExtraArgTs... ExtraArgs) {
415 PreservedAnalyses PA = PreservedAnalyses::all();
418 dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n";
420 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
422 dbgs() << "Running pass: " << Passes[Idx]->name() << " on "
423 << IR.getName() << "\n";
425 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM, ExtraArgs...);
427 // Update the analysis manager as each pass runs and potentially
428 // invalidates analyses.
429 AM.invalidate(IR, PassPA);
431 // Finally, intersect the preserved analyses to compute the aggregate
432 // preserved set for this pass manager.
433 PA.intersect(std::move(PassPA));
435 // FIXME: Historically, the pass managers all called the LLVM context's
436 // yield function here. We don't have a generic way to acquire the
437 // context and it isn't yet clear what the right pattern is for yielding
438 // in the new pass manager so it is currently omitted.
439 //IR.getContext().yield();
442 // Invaliadtion was handled after each pass in the above loop for the
443 // current unit of IR. Therefore, the remaining analysis results in the
444 // AnalysisManager are preserved. We mark this with a set so that we don't
445 // need to inspect each one individually.
446 PA.preserveSet<AllAnalysesOn<IRUnitT>>();
449 dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n";
454 template <typename PassT> void addPass(PassT Pass) {
455 typedef detail::PassModel<IRUnitT, PassT, PreservedAnalyses,
456 AnalysisManagerT, ExtraArgTs...>
458 Passes.emplace_back(new PassModelT(std::move(Pass)));
462 typedef detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>
465 std::vector<std::unique_ptr<PassConceptT>> Passes;
467 /// \brief Flag indicating whether we should do debug logging.
471 extern template class PassManager<Module>;
472 /// \brief Convenience typedef for a pass manager over modules.
473 typedef PassManager<Module> ModulePassManager;
475 extern template class PassManager<Function>;
476 /// \brief Convenience typedef for a pass manager over functions.
477 typedef PassManager<Function> FunctionPassManager;
479 /// \brief A container for analyses that lazily runs them and caches their
482 /// This class can manage analyses for any IR unit where the address of the IR
483 /// unit sufficies as its identity.
484 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
489 // Now that we've defined our invalidator, we can define the concept types.
490 typedef detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>
492 typedef detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
496 /// \brief List of analysis pass IDs and associated concept pointers.
498 /// Requires iterators to be valid across appending new entries and arbitrary
499 /// erases. Provides the analysis ID to enable finding iterators to a given
500 /// entry in maps below, and provides the storage for the actual result
502 typedef std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>
505 /// \brief Map type from IRUnitT pointer to our custom list type.
506 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
508 /// \brief Map type from a pair of analysis ID and IRUnitT pointer to an
509 /// iterator into a particular result list (which is where the actual analysis
510 /// result is stored).
511 typedef DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
512 typename AnalysisResultListT::iterator>
516 /// API to communicate dependencies between analyses during invalidation.
518 /// When an analysis result embeds handles to other analysis results, it
519 /// needs to be invalidated both when its own information isn't preserved and
520 /// when any of its embedded analysis results end up invalidated. We pass an
521 /// \c Invalidator object as an argument to \c invalidate() in order to let
522 /// the analysis results themselves define the dependency graph on the fly.
523 /// This lets us avoid building building an explicit representation of the
524 /// dependencies between analysis results.
527 /// Trigger the invalidation of some other analysis pass if not already
528 /// handled and return whether it was in fact invalidated.
530 /// This is expected to be called from within a given analysis result's \c
531 /// invalidate method to trigger a depth-first walk of all inter-analysis
532 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
533 /// invalidate method should in turn be provided to this routine.
535 /// The first time this is called for a given analysis pass, it will call
536 /// the corresponding result's \c invalidate method. Subsequent calls will
537 /// use a cache of the results of that initial call. It is an error to form
538 /// cyclic dependencies between analysis results.
540 /// This returns true if the given analysis's result is invalid. Any
541 /// dependecies on it will become invalid as a result.
542 template <typename PassT>
543 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
544 typedef detail::AnalysisResultModel<IRUnitT, PassT,
545 typename PassT::Result,
546 PreservedAnalyses, Invalidator>
548 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
551 /// A type-erased variant of the above invalidate method with the same core
552 /// API other than passing an analysis ID rather than an analysis type
555 /// This is sadly less efficient than the above routine, which leverages
556 /// the type parameter to avoid the type erasure overhead.
557 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
558 return invalidateImpl<>(ID, IR, PA);
562 friend class AnalysisManager;
564 template <typename ResultT = ResultConceptT>
565 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
566 const PreservedAnalyses &PA) {
567 // If we've already visited this pass, return true if it was invalidated
568 // and false otherwise.
569 auto IMapI = IsResultInvalidated.find(ID);
570 if (IMapI != IsResultInvalidated.end())
571 return IMapI->second;
573 // Otherwise look up the result object.
574 auto RI = Results.find({ID, &IR});
575 assert(RI != Results.end() &&
576 "Trying to invalidate a dependent result that isn't in the "
577 "manager's cache is always an error, likely due to a stale result "
580 auto &Result = static_cast<ResultT &>(*RI->second->second);
582 // Insert into the map whether the result should be invalidated and return
583 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
584 // as calling invalidate could (recursively) insert things into the map,
585 // making any iterator or reference invalid.
587 std::tie(IMapI, Inserted) =
588 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
590 assert(Inserted && "Should not have already inserted this ID, likely "
591 "indicates a dependency cycle!");
592 return IMapI->second;
595 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
596 const AnalysisResultMapT &Results)
597 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
599 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
600 const AnalysisResultMapT &Results;
603 /// \brief Construct an empty analysis manager.
605 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
606 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
607 AnalysisManager(AnalysisManager &&) = default;
608 AnalysisManager &operator=(AnalysisManager &&) = default;
610 /// \brief Returns true if the analysis manager has an empty results cache.
612 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
613 "The storage and index of analysis results disagree on how many "
615 return AnalysisResults.empty();
618 /// \brief Clear any cached analysis results for a single unit of IR.
620 /// This doesn't invalidate, but instead simply deletes, the relevant results.
621 /// It is useful when the IR is being removed and we want to clear out all the
622 /// memory pinned for it.
623 void clear(IRUnitT &IR) {
625 dbgs() << "Clearing all analysis results for: " << IR.getName() << "\n";
627 auto ResultsListI = AnalysisResultLists.find(&IR);
628 if (ResultsListI == AnalysisResultLists.end())
630 // Delete the map entries that point into the results list.
631 for (auto &IDAndResult : ResultsListI->second)
632 AnalysisResults.erase({IDAndResult.first, &IR});
634 // And actually destroy and erase the results associated with this IR.
635 AnalysisResultLists.erase(ResultsListI);
638 /// \brief Clear all analysis results cached by this AnalysisManager.
640 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
641 /// deletes them. This lets you clean up the AnalysisManager when the set of
642 /// IR units itself has potentially changed, and thus we can't even look up a
643 /// a result and invalidate/clear it directly.
645 AnalysisResults.clear();
646 AnalysisResultLists.clear();
649 /// \brief Get the result of an analysis pass for a given IR unit.
651 /// Runs the analysis if a cached result is not available.
652 template <typename PassT>
653 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
654 assert(AnalysisPasses.count(PassT::ID()) &&
655 "This analysis pass was not registered prior to being queried");
656 ResultConceptT &ResultConcept =
657 getResultImpl(PassT::ID(), IR, ExtraArgs...);
658 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
659 PreservedAnalyses, Invalidator>
661 return static_cast<ResultModelT &>(ResultConcept).Result;
664 /// \brief Get the cached result of an analysis pass for a given IR unit.
666 /// This method never runs the analysis.
668 /// \returns null if there is no cached result.
669 template <typename PassT>
670 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
671 assert(AnalysisPasses.count(PassT::ID()) &&
672 "This analysis pass was not registered prior to being queried");
674 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
678 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
679 PreservedAnalyses, Invalidator>
681 return &static_cast<ResultModelT *>(ResultConcept)->Result;
684 /// \brief Register an analysis pass with the manager.
686 /// The parameter is a callable whose result is an analysis pass. This allows
687 /// passing in a lambda to construct the analysis.
689 /// The analysis type to register is the type returned by calling the \c
690 /// PassBuilder argument. If that type has already been registered, then the
691 /// argument will not be called and this function will return false.
692 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
693 /// and this function returns true.
695 /// (Note: Although the return value of this function indicates whether or not
696 /// an analysis was previously registered, there intentionally isn't a way to
697 /// query this directly. Instead, you should just register all the analyses
698 /// you might want and let this class run them lazily. This idiom lets us
699 /// minimize the number of times we have to look up analyses in our
701 template <typename PassBuilderT>
702 bool registerPass(PassBuilderT &&PassBuilder) {
703 typedef decltype(PassBuilder()) PassT;
704 typedef detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses,
705 Invalidator, ExtraArgTs...>
708 auto &PassPtr = AnalysisPasses[PassT::ID()];
710 // Already registered this pass type!
713 // Construct a new model around the instance returned by the builder.
714 PassPtr.reset(new PassModelT(PassBuilder()));
718 /// \brief Invalidate a specific analysis pass for an IR module.
720 /// Note that the analysis result can disregard invalidation, if it determines
721 /// it is in fact still valid.
722 template <typename PassT> void invalidate(IRUnitT &IR) {
723 assert(AnalysisPasses.count(PassT::ID()) &&
724 "This analysis pass was not registered prior to being invalidated");
725 invalidateImpl(PassT::ID(), IR);
728 /// \brief Invalidate cached analyses for an IR unit.
730 /// Walk through all of the analyses pertaining to this unit of IR and
731 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
732 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
733 // We're done if all analyses on this IR unit are preserved.
734 if (PA.allAnalysesInSetPreserved<AllAnalysesOn<IRUnitT>>())
738 dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName()
741 // Track whether each analysis's result is invalidated in
742 // IsResultInvalidated.
743 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
744 Invalidator Inv(IsResultInvalidated, AnalysisResults);
745 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
746 for (auto &AnalysisResultPair : ResultsList) {
747 // This is basically the same thing as Invalidator::invalidate, but we
748 // can't call it here because we're operating on the type-erased result.
749 // Moreover if we instead called invalidate() directly, it would do an
750 // unnecessary look up in ResultsList.
751 AnalysisKey *ID = AnalysisResultPair.first;
752 auto &Result = *AnalysisResultPair.second;
754 auto IMapI = IsResultInvalidated.find(ID);
755 if (IMapI != IsResultInvalidated.end())
756 // This result was already handled via the Invalidator.
759 // Try to invalidate the result, giving it the Invalidator so it can
760 // recursively query for any dependencies it has and record the result.
761 // Note that we cannot reuse 'IMapI' here or pre-insert the ID, as
762 // Result.invalidate may insert things into the map, invalidating our
765 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, Inv)})
768 assert(Inserted && "Should never have already inserted this ID, likely "
769 "indicates a cycle!");
772 // Now erase the results that were marked above as invalidated.
773 if (!IsResultInvalidated.empty()) {
774 for (auto I = ResultsList.begin(), E = ResultsList.end(); I != E;) {
775 AnalysisKey *ID = I->first;
776 if (!IsResultInvalidated.lookup(ID)) {
782 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
785 I = ResultsList.erase(I);
786 AnalysisResults.erase({ID, &IR});
790 if (ResultsList.empty())
791 AnalysisResultLists.erase(&IR);
795 /// \brief Look up a registered analysis pass.
796 PassConceptT &lookUpPass(AnalysisKey *ID) {
797 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
798 assert(PI != AnalysisPasses.end() &&
799 "Analysis passes must be registered prior to being queried!");
803 /// \brief Look up a registered analysis pass.
804 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
805 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
806 assert(PI != AnalysisPasses.end() &&
807 "Analysis passes must be registered prior to being queried!");
811 /// \brief Get an analysis result, running the pass if necessary.
812 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
813 ExtraArgTs... ExtraArgs) {
814 typename AnalysisResultMapT::iterator RI;
816 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
817 std::make_pair(ID, &IR), typename AnalysisResultListT::iterator()));
819 // If we don't have a cached result for this function, look up the pass and
820 // run it to produce a result, which we then add to the cache.
822 auto &P = this->lookUpPass(ID);
824 dbgs() << "Running analysis: " << P.name() << "\n";
825 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
826 ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...));
828 // P.run may have inserted elements into AnalysisResults and invalidated
830 RI = AnalysisResults.find({ID, &IR});
831 assert(RI != AnalysisResults.end() && "we just inserted it!");
833 RI->second = std::prev(ResultList.end());
836 return *RI->second->second;
839 /// \brief Get a cached analysis result or return null.
840 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
841 typename AnalysisResultMapT::const_iterator RI =
842 AnalysisResults.find({ID, &IR});
843 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
846 /// \brief Invalidate a function pass result.
847 void invalidateImpl(AnalysisKey *ID, IRUnitT &IR) {
848 typename AnalysisResultMapT::iterator RI =
849 AnalysisResults.find({ID, &IR});
850 if (RI == AnalysisResults.end())
854 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
856 AnalysisResultLists[&IR].erase(RI->second);
857 AnalysisResults.erase(RI);
860 /// \brief Map type from module analysis pass ID to pass concept pointer.
861 typedef DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
863 /// \brief Collection of module analysis passes, indexed by ID.
864 AnalysisPassMapT AnalysisPasses;
866 /// \brief Map from function to a list of function analysis results.
868 /// Provides linear time removal of all analysis results for a function and
869 /// the ultimate storage for a particular cached analysis result.
870 AnalysisResultListMapT AnalysisResultLists;
872 /// \brief Map from an analysis ID and function to a particular cached
874 AnalysisResultMapT AnalysisResults;
876 /// \brief Indicates whether we log to \c llvm::dbgs().
880 extern template class AnalysisManager<Module>;
881 /// \brief Convenience typedef for the Module analysis manager.
882 typedef AnalysisManager<Module> ModuleAnalysisManager;
884 extern template class AnalysisManager<Function>;
885 /// \brief Convenience typedef for the Function analysis manager.
886 typedef AnalysisManager<Function> FunctionAnalysisManager;
888 /// \brief An analysis over an "outer" IR unit that provides access to an
889 /// analysis manager over an "inner" IR unit. The inner unit must be contained
890 /// in the outer unit.
892 /// Fore example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
893 /// an analysis over Modules (the "outer" unit) that provides access to a
894 /// Function analysis manager. The FunctionAnalysisManager is the "inner"
895 /// manager being proxied, and Functions are the "inner" unit. The inner/outer
896 /// relationship is valid because each Function is contained in one Module.
898 /// If you're (transitively) within a pass manager for an IR unit U that
899 /// contains IR unit V, you should never use an analysis manager over V, except
900 /// via one of these proxies.
902 /// Note that the proxy's result is a move-only RAII object. The validity of
903 /// the analyses in the inner analysis manager is tied to its lifetime.
904 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
905 class InnerAnalysisManagerProxy
906 : public AnalysisInfoMixin<
907 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
911 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
912 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
913 // We have to null out the analysis manager in the moved-from state
914 // because we are taking ownership of the responsibilty to clear the
916 Arg.InnerAM = nullptr;
918 Result &operator=(Result &&RHS) {
919 InnerAM = RHS.InnerAM;
920 // We have to null out the analysis manager in the moved-from state
921 // because we are taking ownership of the responsibilty to clear the
923 RHS.InnerAM = nullptr;
927 // InnerAM is cleared in a moved from state where there is nothing to do.
931 // Clear out the analysis manager if we're being destroyed -- it means we
932 // didn't even see an invalidate call when we got invalidated.
936 /// \brief Accessor for the analysis manager.
937 AnalysisManagerT &getManager() { return *InnerAM; }
939 /// \brief Handler for invalidation of the outer IR unit, \c IRUnitT.
941 /// If the proxy analysis itself is not preserved, we assume that the set of
942 /// inner IR objects contained in IRUnit may have changed. In this case,
943 /// we have to call \c clear() on the inner analysis manager, as it may now
944 /// have stale pointers to its inner IR objects.
946 /// Regardless of whether the proxy analysis is marked as preserved, all of
947 /// the analyses in the inner analysis manager are potentially invalidated
948 /// based on the set of preserved analyses.
950 IRUnitT &IR, const PreservedAnalyses &PA,
951 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
954 AnalysisManagerT *InnerAM;
957 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
958 : InnerAM(&InnerAM) {}
960 /// \brief Run the analysis pass and create our proxy result object.
962 /// This doesn't do any interesting work; it is primarily used to insert our
963 /// proxy result object into the outer analysis cache so that we can proxy
964 /// invalidation to the inner analysis manager.
965 Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
967 return Result(*InnerAM);
971 friend AnalysisInfoMixin<
972 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
973 static AnalysisKey Key;
975 AnalysisManagerT *InnerAM;
978 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
980 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
982 /// Provide the \c FunctionAnalysisManager to \c Module proxy.
983 typedef InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>
984 FunctionAnalysisManagerModuleProxy;
986 /// Specialization of the invalidate method for the \c
987 /// FunctionAnalysisManagerModuleProxy's result.
989 bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
990 Module &M, const PreservedAnalyses &PA,
991 ModuleAnalysisManager::Invalidator &Inv);
993 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
995 extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
998 /// \brief An analysis over an "inner" IR unit that provides access to an
999 /// analysis manager over a "outer" IR unit. The inner unit must be contained
1000 /// in the outer unit.
1002 /// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
1003 /// analysis over Functions (the "inner" unit) which provides access to a Module
1004 /// analysis manager. The ModuleAnalysisManager is the "outer" manager being
1005 /// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
1006 /// is valid because each Function is contained in one Module.
1008 /// This proxy only exposes the const interface of the outer analysis manager,
1009 /// to indicate that you cannot cause an outer analysis to run from within an
1010 /// inner pass. Instead, you must rely on the \c getCachedResult API.
1012 /// This proxy doesn't manage invalidation in any way -- that is handled by the
1013 /// recursive return path of each layer of the pass manager. A consequence of
1014 /// this is the outer analyses may be stale. We invalidate the outer analyses
1015 /// only when we're done running passes over the inner IR units.
1016 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1017 class OuterAnalysisManagerProxy
1018 : public AnalysisInfoMixin<
1019 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
1021 /// \brief Result proxy object for \c OuterAnalysisManagerProxy.
1024 explicit Result(const AnalysisManagerT &AM) : AM(&AM) {}
1026 const AnalysisManagerT &getManager() const { return *AM; }
1028 /// \brief Handle invalidation by ignoring it; this pass is immutable.
1030 IRUnitT &, const PreservedAnalyses &,
1031 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &) {
1035 /// Register a deferred invalidation event for when the outer analysis
1036 /// manager processes its invalidations.
1037 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1038 void registerOuterAnalysisInvalidation() {
1039 AnalysisKey *OuterID = OuterAnalysisT::ID();
1040 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1042 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
1043 // Note, this is a linear scan. If we end up with large numbers of
1044 // analyses that all trigger invalidation on the same outer analysis,
1045 // this entire system should be changed to some other deterministic
1046 // data structure such as a `SetVector` of a pair of pointers.
1047 auto InvalidatedIt = std::find(InvalidatedIDList.begin(),
1048 InvalidatedIDList.end(), InvalidatedID);
1049 if (InvalidatedIt == InvalidatedIDList.end())
1050 InvalidatedIDList.push_back(InvalidatedID);
1053 /// Access the map from outer analyses to deferred invalidation requiring
1055 const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
1056 getOuterInvalidations() const {
1057 return OuterAnalysisInvalidationMap;
1061 const AnalysisManagerT *AM;
1063 /// A map from an outer analysis ID to the set of this IR-unit's analyses
1064 /// which need to be invalidated.
1065 SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
1066 OuterAnalysisInvalidationMap;
1069 OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {}
1071 /// \brief Run the analysis pass and create our proxy result object.
1072 /// Nothing to see here, it just forwards the \c AM reference into the
1074 Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
1080 friend AnalysisInfoMixin<
1081 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
1082 static AnalysisKey Key;
1084 const AnalysisManagerT *AM;
1087 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1089 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1091 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1093 /// Provide the \c ModuleAnalysisManager to \c Function proxy.
1094 typedef OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>
1095 ModuleAnalysisManagerFunctionProxy;
1097 /// \brief Trivial adaptor that maps from a module to its functions.
1099 /// Designed to allow composition of a FunctionPass(Manager) and
1100 /// a ModulePassManager, by running the FunctionPass(Manager) over every
1101 /// function in the module.
1103 /// Function passes run within this adaptor can rely on having exclusive access
1104 /// to the function they are run over. They should not read or modify any other
1105 /// functions! Other threads or systems may be manipulating other functions in
1106 /// the module, and so their state should never be relied on.
1107 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1108 /// violate this principle.
1110 /// Function passes can also read the module containing the function, but they
1111 /// should not modify that module outside of the use lists of various globals.
1112 /// For example, a function pass is not permitted to add functions to the
1114 /// FIXME: Make the above true for all of LLVM's actual passes, some still
1115 /// violate this principle.
1117 /// Note that although function passes can access module analyses, module
1118 /// analyses are not invalidated while the function passes are running, so they
1119 /// may be stale. Function analyses will not be stale.
1120 template <typename FunctionPassT>
1121 class ModuleToFunctionPassAdaptor
1122 : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> {
1124 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
1125 : Pass(std::move(Pass)) {}
1127 /// \brief Runs the function pass across every function in the module.
1128 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
1129 FunctionAnalysisManager &FAM =
1130 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1132 PreservedAnalyses PA = PreservedAnalyses::all();
1133 for (Function &F : M) {
1134 if (F.isDeclaration())
1137 PreservedAnalyses PassPA = Pass.run(F, FAM);
1139 // We know that the function pass couldn't have invalidated any other
1140 // function's analyses (that's the contract of a function pass), so
1141 // directly handle the function analysis manager's invalidation here.
1142 FAM.invalidate(F, PassPA);
1144 // Then intersect the preserved set so that invalidation of module
1145 // analyses will eventually occur when the module pass completes.
1146 PA.intersect(std::move(PassPA));
1149 // The FunctionAnalysisManagerModuleProxy is preserved because (we assume)
1150 // the function passes we ran didn't add or remove any functions.
1152 // We also preserve all analyses on Functions, because we did all the
1153 // invalidation we needed to do above.
1154 PA.preserveSet<AllAnalysesOn<Function>>();
1155 PA.preserve<FunctionAnalysisManagerModuleProxy>();
1163 /// \brief A function to deduce a function pass type and wrap it in the
1164 /// templated adaptor.
1165 template <typename FunctionPassT>
1166 ModuleToFunctionPassAdaptor<FunctionPassT>
1167 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
1168 return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
1171 /// \brief A utility pass template to force an analysis result to be available.
1173 /// If there are extra arguments at the pass's run level there may also be
1174 /// extra arguments to the analysis manager's \c getResult routine. We can't
1175 /// guess how to effectively map the arguments from one to the other, and so
1176 /// this specialization just ignores them.
1178 /// Specific patterns of run-method extra arguments and analysis manager extra
1179 /// arguments will have to be defined as appropriate specializations.
1180 template <typename AnalysisT, typename IRUnitT,
1181 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
1182 typename... ExtraArgTs>
1183 struct RequireAnalysisPass
1184 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1186 /// \brief Run this pass over some unit of IR.
1188 /// This pass can be run over any unit of IR and use any analysis manager
1189 /// provided they satisfy the basic API requirements. When this pass is
1190 /// created, these methods can be instantiated to satisfy whatever the
1191 /// context requires.
1192 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
1193 ExtraArgTs &&... Args) {
1194 (void)AM.template getResult<AnalysisT>(Arg,
1195 std::forward<ExtraArgTs>(Args)...);
1197 return PreservedAnalyses::all();
1201 /// \brief A no-op pass template which simply forces a specific analysis result
1202 /// to be invalidated.
1203 template <typename AnalysisT>
1204 struct InvalidateAnalysisPass
1205 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
1206 /// \brief Run this pass over some unit of IR.
1208 /// This pass can be run over any unit of IR and use any analysis manager,
1209 /// provided they satisfy the basic API requirements. When this pass is
1210 /// created, these methods can be instantiated to satisfy whatever the
1211 /// context requires.
1212 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1213 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
1214 auto PA = PreservedAnalyses::all();
1215 PA.abandon<AnalysisT>();
1220 /// \brief A utility pass that does nothing, but preserves no analyses.
1222 /// Because this preserves no analyses, any analysis passes queried after this
1223 /// pass runs will recompute fresh results.
1224 struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
1225 /// \brief Run this pass over some unit of IR.
1226 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1227 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
1228 return PreservedAnalyses::none();
1232 /// A utility pass template that simply runs another pass multiple times.
1234 /// This can be useful when debugging or testing passes. It also serves as an
1235 /// example of how to extend the pass manager in ways beyond composition.
1236 template <typename PassT>
1237 class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> {
1239 RepeatedPass(int Count, PassT P) : Count(Count), P(std::move(P)) {}
1241 template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
1242 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, Ts &&... Args) {
1243 auto PA = PreservedAnalyses::all();
1244 for (int i = 0; i < Count; ++i)
1245 PA.intersect(P.run(Arg, AM, std::forward<Ts>(Args)...));
1254 template <typename PassT>
1255 RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) {
1256 return RepeatedPass<PassT>(Count, std::move(P));