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/IR/Function.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/PassManagerInternal.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/type_traits.h"
61 // Declare our debug option here so we can refer to it from templates.
62 extern cl::opt<bool> DebugPM;
64 } // End detail namespace
66 /// \brief An abstract set of preserved analyses following a transformation pass
69 /// When a transformation pass is run, it can return a set of analyses whose
70 /// results were preserved by that transformation. The default set is "none",
71 /// and preserving analyses must be done explicitly.
73 /// There is also an explicit all state which can be used (for example) when
74 /// the IR is not mutated at all.
75 class PreservedAnalyses {
77 // We have to explicitly define all the special member functions because MSVC
78 // refuses to generate them.
79 PreservedAnalyses() {}
80 PreservedAnalyses(const PreservedAnalyses &Arg)
81 : PreservedPassIDs(Arg.PreservedPassIDs) {}
82 PreservedAnalyses(PreservedAnalyses &&Arg)
83 : PreservedPassIDs(std::move(Arg.PreservedPassIDs)) {}
84 friend void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
86 swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
88 PreservedAnalyses &operator=(PreservedAnalyses RHS) {
93 /// \brief Convenience factory function for the empty preserved set.
94 static PreservedAnalyses none() { return PreservedAnalyses(); }
96 /// \brief Construct a special preserved set that preserves all passes.
97 static PreservedAnalyses all() {
99 PA.PreservedPassIDs.insert((void *)AllPassesID);
103 /// \brief Mark a particular pass as preserved, adding it to the set.
104 template <typename PassT> void preserve() { preserve(PassT::ID()); }
106 /// \brief Mark an abstract PassID as preserved, adding it to the set.
107 void preserve(void *PassID) {
108 if (!areAllPreserved())
109 PreservedPassIDs.insert(PassID);
112 /// \brief Intersect this set with another in place.
114 /// This is a mutating operation on this preserved set, removing all
115 /// preserved passes which are not also preserved in the argument.
116 void intersect(const PreservedAnalyses &Arg) {
117 if (Arg.areAllPreserved())
119 if (areAllPreserved()) {
120 PreservedPassIDs = Arg.PreservedPassIDs;
123 for (void *P : PreservedPassIDs)
124 if (!Arg.PreservedPassIDs.count(P))
125 PreservedPassIDs.erase(P);
128 /// \brief Intersect this set with a temporary other set in place.
130 /// This is a mutating operation on this preserved set, removing all
131 /// preserved passes which are not also preserved in the argument.
132 void intersect(PreservedAnalyses &&Arg) {
133 if (Arg.areAllPreserved())
135 if (areAllPreserved()) {
136 PreservedPassIDs = std::move(Arg.PreservedPassIDs);
139 for (void *P : PreservedPassIDs)
140 if (!Arg.PreservedPassIDs.count(P))
141 PreservedPassIDs.erase(P);
144 /// \brief Query whether a pass is marked as preserved by this set.
145 template <typename PassT> bool preserved() const {
146 return preserved(PassT::ID());
149 /// \brief Query whether an abstract pass ID is marked as preserved by this
151 bool preserved(void *PassID) const {
152 return PreservedPassIDs.count((void *)AllPassesID) ||
153 PreservedPassIDs.count(PassID);
156 /// \brief Test whether all passes are preserved.
158 /// This is used primarily to optimize for the case of no changes which will
159 /// common in many scenarios.
160 bool areAllPreserved() const {
161 return PreservedPassIDs.count((void *)AllPassesID);
165 // Note that this must not be -1 or -2 as those are already used by the
167 static const uintptr_t AllPassesID = (intptr_t)(-3);
169 SmallPtrSet<void *, 2> PreservedPassIDs;
172 // Forward declare the analysis manager template and two typedefs used in the
174 template <typename IRUnitT> class AnalysisManager;
175 typedef AnalysisManager<Module> ModuleAnalysisManager;
176 typedef AnalysisManager<Function> FunctionAnalysisManager;
178 /// \brief Manages a sequence of passes over Modules of IR.
180 /// A module pass manager contains a sequence of module passes. It is also
181 /// itself a module pass. When it is run over a module of LLVM IR, it will
182 /// sequentially run each pass it contains over that module.
184 /// If it is run with a \c ModuleAnalysisManager argument, it will propagate
185 /// that analysis manager to each pass it runs, as well as calling the analysis
186 /// manager's invalidation routine with the PreservedAnalyses of each pass it
189 /// Module passes can rely on having exclusive access to the module they are
190 /// run over. No other threads will access that module, and they can mutate it
191 /// freely. However, they must not mutate other LLVM IR modules.
192 class ModulePassManager {
194 // We have to explicitly define all the special member functions because MSVC
195 // refuses to generate them.
196 ModulePassManager() {}
197 ModulePassManager(ModulePassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
198 ModulePassManager &operator=(ModulePassManager &&RHS) {
199 Passes = std::move(RHS.Passes);
203 /// \brief Run all of the module passes in this module pass manager over
206 /// This method should only be called for a single module as there is the
207 /// expectation that the lifetime of a pass is bounded to that of a module.
208 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM = nullptr);
210 template <typename ModulePassT> void addPass(ModulePassT Pass) {
211 Passes.emplace_back(new ModulePassModel<ModulePassT>(std::move(Pass)));
214 static StringRef name() { return "ModulePassManager"; }
217 // Pull in the concept type and model template specialized for modules.
218 typedef detail::PassConcept<Module, ModuleAnalysisManager> ModulePassConcept;
219 template <typename PassT>
220 struct ModulePassModel
221 : detail::PassModel<Module, ModuleAnalysisManager, PassT> {
222 ModulePassModel(PassT Pass)
223 : detail::PassModel<Module, ModuleAnalysisManager, PassT>(
227 ModulePassManager(const ModulePassManager &) LLVM_DELETED_FUNCTION;
228 ModulePassManager &operator=(const ModulePassManager &) LLVM_DELETED_FUNCTION;
230 std::vector<std::unique_ptr<ModulePassConcept>> Passes;
233 /// \brief Manages a sequence of passes over a Function of IR.
235 /// A function pass manager contains a sequence of function passes. It is also
236 /// itself a function pass. When it is run over a function of LLVM IR, it will
237 /// sequentially run each pass it contains over that function.
239 /// If it is run with a \c FunctionAnalysisManager argument, it will propagate
240 /// that analysis manager to each pass it runs, as well as calling the analysis
241 /// manager's invalidation routine with the PreservedAnalyses of each pass it
244 /// Function passes can rely on having exclusive access to the function they
245 /// are run over. They should not read or modify any other functions! Other
246 /// threads or systems may be manipulating other functions in the module, and
247 /// so their state should never be relied on.
248 /// FIXME: Make the above true for all of LLVM's actual passes, some still
249 /// violate this principle.
251 /// Function passes can also read the module containing the function, but they
252 /// should not modify that module outside of the use lists of various globals.
253 /// For example, a function pass is not permitted to add functions to the
255 /// FIXME: Make the above true for all of LLVM's actual passes, some still
256 /// violate this principle.
257 class FunctionPassManager {
259 // We have to explicitly define all the special member functions because MSVC
260 // refuses to generate them.
261 FunctionPassManager() {}
262 FunctionPassManager(FunctionPassManager &&Arg)
263 : Passes(std::move(Arg.Passes)) {}
264 FunctionPassManager &operator=(FunctionPassManager &&RHS) {
265 Passes = std::move(RHS.Passes);
269 template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
270 Passes.emplace_back(new FunctionPassModel<FunctionPassT>(std::move(Pass)));
273 PreservedAnalyses run(Function &F, FunctionAnalysisManager *AM = nullptr);
275 static StringRef name() { return "FunctionPassManager"; }
278 // Pull in the concept type and model template specialized for functions.
279 typedef detail::PassConcept<Function, FunctionAnalysisManager>
281 template <typename PassT>
282 struct FunctionPassModel
283 : detail::PassModel<Function, FunctionAnalysisManager, PassT> {
284 FunctionPassModel(PassT Pass)
285 : detail::PassModel<Function, FunctionAnalysisManager, PassT>(
289 FunctionPassManager(const FunctionPassManager &) LLVM_DELETED_FUNCTION;
290 FunctionPassManager &
291 operator=(const FunctionPassManager &) LLVM_DELETED_FUNCTION;
293 std::vector<std::unique_ptr<FunctionPassConcept>> Passes;
298 /// \brief A CRTP base used to implement analysis managers.
300 /// This class template serves as the boiler plate of an analysis manager. Any
301 /// analysis manager can be implemented on top of this base class. Any
302 /// implementation will be required to provide specific hooks:
305 /// - getCachedResultImpl
308 /// The details of the call pattern are within.
310 /// Note that there is also a generic analysis manager template which implements
311 /// the above required functions along with common datastructures used for
312 /// managing analyses. This base class is factored so that if you need to
313 /// customize the handling of a specific IR unit, you can do so without
314 /// replicating *all* of the boilerplate.
315 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
316 DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
317 const DerivedT *derived_this() const {
318 return static_cast<const DerivedT *>(this);
321 AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
322 AnalysisManagerBase &
323 operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
326 typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
327 typedef detail::AnalysisPassConcept<IRUnitT, DerivedT> PassConceptT;
329 // FIXME: Provide template aliases for the models when we're using C++11 in
330 // a mode supporting them.
332 // We have to explicitly define all the special member functions because MSVC
333 // refuses to generate them.
334 AnalysisManagerBase() {}
335 AnalysisManagerBase(AnalysisManagerBase &&Arg)
336 : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
337 AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
338 AnalysisPasses = std::move(RHS.AnalysisPasses);
343 /// \brief Get the result of an analysis pass for this module.
345 /// If there is not a valid cached result in the manager already, this will
346 /// re-run the analysis to produce a valid result.
347 template <typename PassT> typename PassT::Result &getResult(IRUnitT &IR) {
348 assert(AnalysisPasses.count(PassT::ID()) &&
349 "This analysis pass was not registered prior to being queried");
351 ResultConceptT &ResultConcept =
352 derived_this()->getResultImpl(PassT::ID(), IR);
353 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
355 return static_cast<ResultModelT &>(ResultConcept).Result;
358 /// \brief Get the cached result of an analysis pass for this module.
360 /// This method never runs the analysis.
362 /// \returns null if there is no cached result.
363 template <typename PassT>
364 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
365 assert(AnalysisPasses.count(PassT::ID()) &&
366 "This analysis pass was not registered prior to being queried");
368 ResultConceptT *ResultConcept =
369 derived_this()->getCachedResultImpl(PassT::ID(), IR);
373 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
375 return &static_cast<ResultModelT *>(ResultConcept)->Result;
378 /// \brief Register an analysis pass with the manager.
380 /// This provides an initialized and set-up analysis pass to the analysis
381 /// manager. Whomever is setting up analysis passes must use this to populate
382 /// the manager with all of the analysis passes available.
383 template <typename PassT> void registerPass(PassT Pass) {
384 assert(!AnalysisPasses.count(PassT::ID()) &&
385 "Registered the same analysis pass twice!");
386 typedef detail::AnalysisPassModel<IRUnitT, DerivedT, PassT> PassModelT;
387 AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
390 /// \brief Invalidate a specific analysis pass for an IR module.
392 /// Note that the analysis result can disregard invalidation.
393 template <typename PassT> void invalidate(IRUnitT &IR) {
394 assert(AnalysisPasses.count(PassT::ID()) &&
395 "This analysis pass was not registered prior to being invalidated");
396 derived_this()->invalidateImpl(PassT::ID(), IR);
399 /// \brief Invalidate analyses cached for an IR unit.
401 /// Walk through all of the analyses pertaining to this unit of IR and
402 /// invalidate them unless they are preserved by the PreservedAnalyses set.
403 /// We accept the PreservedAnalyses set by value and update it with each
404 /// analyis pass which has been successfully invalidated and thus can be
405 /// preserved going forward. The updated set is returned.
406 PreservedAnalyses invalidate(IRUnitT &IR, PreservedAnalyses PA) {
407 return derived_this()->invalidateImpl(IR, std::move(PA));
411 /// \brief Lookup a registered analysis pass.
412 PassConceptT &lookupPass(void *PassID) {
413 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
414 assert(PI != AnalysisPasses.end() &&
415 "Analysis passes must be registered prior to being queried!");
419 /// \brief Lookup a registered analysis pass.
420 const PassConceptT &lookupPass(void *PassID) const {
421 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
422 assert(PI != AnalysisPasses.end() &&
423 "Analysis passes must be registered prior to being queried!");
428 /// \brief Map type from module analysis pass ID to pass concept pointer.
429 typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
431 /// \brief Collection of module analysis passes, indexed by ID.
432 AnalysisPassMapT AnalysisPasses;
435 } // End namespace detail
437 /// \brief A generic analysis pass manager with lazy running and caching of
440 /// This analysis manager can be used for any IR unit where the address of the
441 /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
442 /// the address of each unit of IR cached.
443 template <typename IRUnitT>
444 class AnalysisManager
445 : public detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> {
446 friend class detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT>;
447 typedef detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> BaseT;
448 typedef typename BaseT::ResultConceptT ResultConceptT;
449 typedef typename BaseT::PassConceptT PassConceptT;
452 // Most public APIs are inherited from the CRTP base class.
454 // We have to explicitly define all the special member functions because MSVC
455 // refuses to generate them.
457 AnalysisManager(AnalysisManager &&Arg)
458 : BaseT(std::move(static_cast<BaseT &>(Arg))),
459 AnalysisResults(std::move(Arg.AnalysisResults)) {}
460 AnalysisManager &operator=(AnalysisManager &&RHS) {
461 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
462 AnalysisResults = std::move(RHS.AnalysisResults);
466 /// \brief Returns true if the analysis manager has an empty results cache.
468 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
469 "The storage and index of analysis results disagree on how many "
471 return AnalysisResults.empty();
474 /// \brief Clear the analysis result cache.
476 /// This routine allows cleaning up when the set of IR units itself has
477 /// potentially changed, and thus we can't even look up a a result and
478 /// invalidate it directly. Notably, this does *not* call invalidate functions
479 /// as there is nothing to be done for them.
481 AnalysisResults.clear();
482 AnalysisResultLists.clear();
486 AnalysisManager(const AnalysisManager &) LLVM_DELETED_FUNCTION;
487 AnalysisManager &operator=(const AnalysisManager &) LLVM_DELETED_FUNCTION;
489 /// \brief Get an analysis result, running the pass if necessary.
490 ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
491 typename AnalysisResultMapT::iterator RI;
493 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
494 std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
496 // If we don't have a cached result for this function, look up the pass and
497 // run it to produce a result, which we then add to the cache.
499 auto &P = this->lookupPass(PassID);
501 dbgs() << "Running analysis: " << P.name() << "\n";
502 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
503 ResultList.emplace_back(PassID, P.run(IR, this));
504 RI->second = std::prev(ResultList.end());
507 return *RI->second->second;
510 /// \brief Get a cached analysis result or return null.
511 ResultConceptT *getCachedResultImpl(void *PassID, IRUnitT &IR) const {
512 typename AnalysisResultMapT::const_iterator RI =
513 AnalysisResults.find(std::make_pair(PassID, &IR));
514 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
517 /// \brief Invalidate a function pass result.
518 void invalidateImpl(void *PassID, IRUnitT &IR) {
519 typename AnalysisResultMapT::iterator RI =
520 AnalysisResults.find(std::make_pair(PassID, &IR));
521 if (RI == AnalysisResults.end())
525 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
527 AnalysisResultLists[&IR].erase(RI->second);
528 AnalysisResults.erase(RI);
531 /// \brief Invalidate the results for a function..
532 PreservedAnalyses invalidateImpl(IRUnitT &IR, PreservedAnalyses PA) {
533 // Short circuit for a common case of all analyses being preserved.
534 if (PA.areAllPreserved())
535 return std::move(PA);
538 dbgs() << "Invalidating all non-preserved analyses for: "
539 << IR.getName() << "\n";
541 // Clear all the invalidated results associated specifically with this
543 SmallVector<void *, 8> InvalidatedPassIDs;
544 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
545 for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
546 E = ResultsList.end();
548 void *PassID = I->first;
550 // Pass the invalidation down to the pass itself to see if it thinks it is
551 // necessary. The analysis pass can return false if no action on the part
552 // of the analysis manager is required for this invalidation event.
553 if (I->second->invalidate(IR, PA)) {
555 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
558 InvalidatedPassIDs.push_back(I->first);
559 I = ResultsList.erase(I);
564 // After handling each pass, we mark it as preserved. Once we've
565 // invalidated any stale results, the rest of the system is allowed to
566 // start preserving this analysis again.
569 while (!InvalidatedPassIDs.empty())
570 AnalysisResults.erase(
571 std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
572 if (ResultsList.empty())
573 AnalysisResultLists.erase(&IR);
575 return std::move(PA);
578 /// \brief List of function analysis pass IDs and associated concept pointers.
580 /// Requires iterators to be valid across appending new entries and arbitrary
581 /// erases. Provides both the pass ID and concept pointer such that it is
582 /// half of a bijection and provides storage for the actual result concept.
583 typedef std::list<std::pair<
584 void *, std::unique_ptr<detail::AnalysisResultConcept<IRUnitT>>>>
587 /// \brief Map type from function pointer to our custom list type.
588 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
590 /// \brief Map from function to a list of function analysis results.
592 /// Provides linear time removal of all analysis results for a function and
593 /// the ultimate storage for a particular cached analysis result.
594 AnalysisResultListMapT AnalysisResultLists;
596 /// \brief Map type from a pair of analysis ID and function pointer to an
597 /// iterator into a particular result list.
598 typedef DenseMap<std::pair<void *, IRUnitT *>,
599 typename AnalysisResultListT::iterator> AnalysisResultMapT;
601 /// \brief Map from an analysis ID and function to a particular cached
603 AnalysisResultMapT AnalysisResults;
606 /// \brief A module analysis which acts as a proxy for a function analysis
609 /// This primarily proxies invalidation information from the module analysis
610 /// manager and module pass manager to a function analysis manager. You should
611 /// never use a function analysis manager from within (transitively) a module
612 /// pass manager unless your parent module pass has received a proxy result
614 class FunctionAnalysisManagerModuleProxy {
618 static void *ID() { return (void *)&PassID; }
620 static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
622 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
624 // We have to explicitly define all the special member functions because MSVC
625 // refuses to generate them.
626 FunctionAnalysisManagerModuleProxy(
627 const FunctionAnalysisManagerModuleProxy &Arg)
629 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
630 : FAM(std::move(Arg.FAM)) {}
631 FunctionAnalysisManagerModuleProxy &
632 operator=(FunctionAnalysisManagerModuleProxy RHS) {
633 std::swap(FAM, RHS.FAM);
637 /// \brief Run the analysis pass and create our proxy result object.
639 /// This doesn't do any interesting work, it is primarily used to insert our
640 /// proxy result object into the module analysis cache so that we can proxy
641 /// invalidation to the function analysis manager.
643 /// In debug builds, it will also assert that the analysis manager is empty
644 /// as no queries should arrive at the function analysis manager prior to
645 /// this analysis being requested.
646 Result run(Module &M);
651 FunctionAnalysisManager *FAM;
654 /// \brief The result proxy object for the
655 /// \c FunctionAnalysisManagerModuleProxy.
657 /// See its documentation for more information.
658 class FunctionAnalysisManagerModuleProxy::Result {
660 explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
661 // We have to explicitly define all the special member functions because MSVC
662 // refuses to generate them.
663 Result(const Result &Arg) : FAM(Arg.FAM) {}
664 Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
665 Result &operator=(Result RHS) {
666 std::swap(FAM, RHS.FAM);
671 /// \brief Accessor for the \c FunctionAnalysisManager.
672 FunctionAnalysisManager &getManager() { return *FAM; }
674 /// \brief Handler for invalidation of the module.
676 /// If this analysis itself is preserved, then we assume that the set of \c
677 /// Function objects in the \c Module hasn't changed and thus we don't need
678 /// to invalidate *all* cached data associated with a \c Function* in the \c
679 /// FunctionAnalysisManager.
681 /// Regardless of whether this analysis is marked as preserved, all of the
682 /// analyses in the \c FunctionAnalysisManager are potentially invalidated
683 /// based on the set of preserved analyses.
684 bool invalidate(Module &M, const PreservedAnalyses &PA);
687 FunctionAnalysisManager *FAM;
690 /// \brief A function analysis which acts as a proxy for a module analysis
693 /// This primarily provides an accessor to a parent module analysis manager to
694 /// function passes. Only the const interface of the module analysis manager is
695 /// provided to indicate that once inside of a function analysis pass you
696 /// cannot request a module analysis to actually run. Instead, the user must
697 /// rely on the \c getCachedResult API.
699 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
700 /// the recursive return path of each layer of the pass manager and the
701 /// returned PreservedAnalysis set.
702 class ModuleAnalysisManagerFunctionProxy {
704 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
707 explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
708 // We have to explicitly define all the special member functions because
709 // MSVC refuses to generate them.
710 Result(const Result &Arg) : MAM(Arg.MAM) {}
711 Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
712 Result &operator=(Result RHS) {
713 std::swap(MAM, RHS.MAM);
717 const ModuleAnalysisManager &getManager() const { return *MAM; }
719 /// \brief Handle invalidation by ignoring it, this pass is immutable.
720 bool invalidate(Function &) { return false; }
723 const ModuleAnalysisManager *MAM;
726 static void *ID() { return (void *)&PassID; }
728 static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
730 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
732 // We have to explicitly define all the special member functions because MSVC
733 // refuses to generate them.
734 ModuleAnalysisManagerFunctionProxy(
735 const ModuleAnalysisManagerFunctionProxy &Arg)
737 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
738 : MAM(std::move(Arg.MAM)) {}
739 ModuleAnalysisManagerFunctionProxy &
740 operator=(ModuleAnalysisManagerFunctionProxy RHS) {
741 std::swap(MAM, RHS.MAM);
745 /// \brief Run the analysis pass and create our proxy result object.
746 /// Nothing to see here, it just forwards the \c MAM reference into the
748 Result run(Function &) { return Result(*MAM); }
753 const ModuleAnalysisManager *MAM;
756 /// \brief Trivial adaptor that maps from a module to its functions.
758 /// Designed to allow composition of a FunctionPass(Manager) and
759 /// a ModulePassManager. Note that if this pass is constructed with a pointer
760 /// to a \c ModuleAnalysisManager it will run the
761 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
762 /// pass over the module to enable a \c FunctionAnalysisManager to be used
763 /// within this run safely.
764 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
766 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
767 : Pass(std::move(Pass)) {}
768 // We have to explicitly define all the special member functions because MSVC
769 // refuses to generate them.
770 ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
772 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
773 : Pass(std::move(Arg.Pass)) {}
774 friend void swap(ModuleToFunctionPassAdaptor &LHS,
775 ModuleToFunctionPassAdaptor &RHS) {
777 swap(LHS.Pass, RHS.Pass);
779 ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
784 /// \brief Runs the function pass across every function in the module.
785 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
786 FunctionAnalysisManager *FAM = nullptr;
788 // Setup the function analysis manager from its proxy.
789 FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
791 PreservedAnalyses PA = PreservedAnalyses::all();
792 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
793 PreservedAnalyses PassPA = Pass.run(*I, FAM);
795 // We know that the function pass couldn't have invalidated any other
796 // function's analyses (that's the contract of a function pass), so
797 // directly handle the function analysis manager's invalidation here and
798 // update our preserved set to reflect that these have already been
801 PassPA = FAM->invalidate(*I, std::move(PassPA));
803 // Then intersect the preserved set so that invalidation of module
804 // analyses will eventually occur when the module pass completes.
805 PA.intersect(std::move(PassPA));
808 // By definition we preserve the proxy. This precludes *any* invalidation
809 // of function analyses by the proxy, but that's OK because we've taken
810 // care to invalidate analyses in the function analysis manager
811 // incrementally above.
812 PA.preserve<FunctionAnalysisManagerModuleProxy>();
816 static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
822 /// \brief A function to deduce a function pass type and wrap it in the
823 /// templated adaptor.
824 template <typename FunctionPassT>
825 ModuleToFunctionPassAdaptor<FunctionPassT>
826 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
827 return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
830 /// \brief A template utility pass to force an analysis result to be available.
832 /// This is a no-op pass which simply forces a specific analysis pass's result
833 /// to be available when it is run.
834 template <typename AnalysisT> struct RequireAnalysisPass {
835 /// \brief Run this pass over some unit of IR.
837 /// This pass can be run over any unit of IR and use any analysis manager
838 /// provided they satisfy the basic API requirements. When this pass is
839 /// created, these methods can be instantiated to satisfy whatever the
840 /// context requires.
841 template <typename IRUnitT, typename AnalysisManagerT>
842 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT *AM) {
844 (void)AM->template getResult<AnalysisT>(Arg);
846 return PreservedAnalyses::all();
849 static StringRef name() { return "RequireAnalysisPass"; }
852 /// \brief A template utility pass to force an analysis result to be
855 /// This is a no-op pass which simply forces a specific analysis result to be
856 /// invalidated when it is run.
857 template <typename AnalysisT> struct InvalidateAnalysisPass {
858 /// \brief Run this pass over some unit of IR.
860 /// This pass can be run over any unit of IR and use any analysis manager
861 /// provided they satisfy the basic API requirements. When this pass is
862 /// created, these methods can be instantiated to satisfy whatever the
863 /// context requires.
864 template <typename IRUnitT, typename AnalysisManagerT>
865 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT *AM) {
867 // We have to directly invalidate the analysis result as we can't
868 // enumerate all other analyses and use the preserved set to control it.
869 (void)AM->template invalidate<AnalysisT>(Arg);
871 return PreservedAnalyses::all();
874 static StringRef name() { return "InvalidateAnalysisPass"; }
877 /// \brief A utility pass that does nothing but preserves no analyses.
879 /// As a consequence fo not preserving any analyses, this pass will force all
880 /// analysis passes to be re-run to produce fresh results if any are needed.
881 struct InvalidateAllAnalysesPass {
882 /// \brief Run this pass over some unit of IR.
883 template <typename IRUnitT> PreservedAnalyses run(IRUnitT &Arg) {
884 return PreservedAnalyses::none();
887 static StringRef name() { return "InvalidateAllAnalysesPass"; }