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"
59 /// \brief An abstract set of preserved analyses following a transformation pass
62 /// When a transformation pass is run, it can return a set of analyses whose
63 /// results were preserved by that transformation. The default set is "none",
64 /// and preserving analyses must be done explicitly.
66 /// There is also an explicit all state which can be used (for example) when
67 /// the IR is not mutated at all.
68 class PreservedAnalyses
{
70 // We have to explicitly define all the special member functions because MSVC
71 // refuses to generate them.
72 PreservedAnalyses() {}
73 PreservedAnalyses(const PreservedAnalyses
&Arg
)
74 : PreservedPassIDs(Arg
.PreservedPassIDs
) {}
75 PreservedAnalyses(PreservedAnalyses
&&Arg
)
76 : PreservedPassIDs(std::move(Arg
.PreservedPassIDs
)) {}
77 friend void swap(PreservedAnalyses
&LHS
, PreservedAnalyses
&RHS
) {
79 swap(LHS
.PreservedPassIDs
, RHS
.PreservedPassIDs
);
81 PreservedAnalyses
&operator=(PreservedAnalyses RHS
) {
86 /// \brief Convenience factory function for the empty preserved set.
87 static PreservedAnalyses
none() { return PreservedAnalyses(); }
89 /// \brief Construct a special preserved set that preserves all passes.
90 static PreservedAnalyses
all() {
92 PA
.PreservedPassIDs
.insert((void *)AllPassesID
);
96 /// \brief Mark a particular pass as preserved, adding it to the set.
97 template <typename PassT
> void preserve() { preserve(PassT::ID()); }
99 /// \brief Mark an abstract PassID as preserved, adding it to the set.
100 void preserve(void *PassID
) {
101 if (!areAllPreserved())
102 PreservedPassIDs
.insert(PassID
);
105 /// \brief Intersect this set with another in place.
107 /// This is a mutating operation on this preserved set, removing all
108 /// preserved passes which are not also preserved in the argument.
109 void intersect(const PreservedAnalyses
&Arg
) {
110 if (Arg
.areAllPreserved())
112 if (areAllPreserved()) {
113 PreservedPassIDs
= Arg
.PreservedPassIDs
;
116 for (void *P
: PreservedPassIDs
)
117 if (!Arg
.PreservedPassIDs
.count(P
))
118 PreservedPassIDs
.erase(P
);
121 /// \brief Intersect this set with a temporary other set in place.
123 /// This is a mutating operation on this preserved set, removing all
124 /// preserved passes which are not also preserved in the argument.
125 void intersect(PreservedAnalyses
&&Arg
) {
126 if (Arg
.areAllPreserved())
128 if (areAllPreserved()) {
129 PreservedPassIDs
= std::move(Arg
.PreservedPassIDs
);
132 for (void *P
: PreservedPassIDs
)
133 if (!Arg
.PreservedPassIDs
.count(P
))
134 PreservedPassIDs
.erase(P
);
137 /// \brief Query whether a pass is marked as preserved by this set.
138 template <typename PassT
> bool preserved() const {
139 return preserved(PassT::ID());
142 /// \brief Query whether an abstract pass ID is marked as preserved by this
144 bool preserved(void *PassID
) const {
145 return PreservedPassIDs
.count((void *)AllPassesID
) ||
146 PreservedPassIDs
.count(PassID
);
149 /// \brief Test whether all passes are preserved.
151 /// This is used primarily to optimize for the case of no changes which will
152 /// common in many scenarios.
153 bool areAllPreserved() const {
154 return PreservedPassIDs
.count((void *)AllPassesID
);
158 // Note that this must not be -1 or -2 as those are already used by the
160 static const uintptr_t AllPassesID
= (intptr_t)(-3);
162 SmallPtrSet
<void *, 2> PreservedPassIDs
;
165 // Forward declare the analysis manager template.
166 template <typename IRUnitT
> class AnalysisManager
;
168 /// \brief Manages a sequence of passes over units of IR.
170 /// A pass manager contains a sequence of passes to run over units of IR. It is
171 /// itself a valid pass over that unit of IR, and when over some given IR will
172 /// run each pass in sequence. This is the primary and most basic building
173 /// block of a pass pipeline.
175 /// If it is run with an \c AnalysisManager<IRUnitT> argument, it will propagate
176 /// that analysis manager to each pass it runs, as well as calling the analysis
177 /// manager's invalidation routine with the PreservedAnalyses of each pass it
179 template <typename IRUnitT
> class PassManager
{
181 /// \brief Construct a pass manager.
183 /// It can be passed a flag to get debug logging as the passes are run.
184 PassManager(bool DebugLogging
= false) : DebugLogging(DebugLogging
) {}
185 // We have to explicitly define all the special member functions because MSVC
186 // refuses to generate them.
187 PassManager(PassManager
&&Arg
)
188 : Passes(std::move(Arg
.Passes
)),
189 DebugLogging(std::move(Arg
.DebugLogging
)) {}
190 PassManager
&operator=(PassManager
&&RHS
) {
191 Passes
= std::move(RHS
.Passes
);
192 DebugLogging
= std::move(RHS
.DebugLogging
);
196 /// \brief Run all of the passes in this manager over the IR.
197 PreservedAnalyses
run(IRUnitT
&IR
, AnalysisManager
<IRUnitT
> *AM
= nullptr) {
198 PreservedAnalyses PA
= PreservedAnalyses::all();
201 dbgs() << "Starting pass manager run.\n";
203 for (unsigned Idx
= 0, Size
= Passes
.size(); Idx
!= Size
; ++Idx
) {
205 dbgs() << "Running pass: " << Passes
[Idx
]->name() << "\n";
207 PreservedAnalyses PassPA
= Passes
[Idx
]->run(IR
, AM
);
209 // If we have an active analysis manager at this level we want to ensure
210 // we update it as each pass runs and potentially invalidates analyses.
211 // We also update the preserved set of analyses based on what analyses we
212 // have already handled the invalidation for here and don't need to
213 // invalidate when finished.
215 PassPA
= AM
->invalidate(IR
, std::move(PassPA
));
217 // Finally, we intersect the final preserved analyses to compute the
218 // aggregate preserved set for this pass manager.
219 PA
.intersect(std::move(PassPA
));
221 // FIXME: Historically, the pass managers all called the LLVM context's
222 // yield function here. We don't have a generic way to acquire the
223 // context and it isn't yet clear what the right pattern is for yielding
224 // in the new pass manager so it is currently omitted.
225 //IR.getContext().yield();
229 dbgs() << "Finished pass manager run.\n";
234 template <typename PassT
> void addPass(PassT Pass
) {
235 typedef detail::PassModel
<IRUnitT
, PassT
> PassModelT
;
236 Passes
.emplace_back(new PassModelT(std::move(Pass
)));
239 static StringRef
name() { return "PassManager"; }
242 typedef detail::PassConcept
<IRUnitT
> PassConceptT
;
244 PassManager(const PassManager
&) LLVM_DELETED_FUNCTION
;
245 PassManager
&operator=(const PassManager
&) LLVM_DELETED_FUNCTION
;
247 std::vector
<std::unique_ptr
<PassConceptT
>> Passes
;
249 /// \brief Flag indicating whether we should do debug logging.
253 /// \brief Convenience typedef for a pass manager over modules.
254 typedef PassManager
<Module
> ModulePassManager
;
256 /// \brief Convenience typedef for a pass manager over functions.
257 typedef PassManager
<Function
> FunctionPassManager
;
261 /// \brief A CRTP base used to implement analysis managers.
263 /// This class template serves as the boiler plate of an analysis manager. Any
264 /// analysis manager can be implemented on top of this base class. Any
265 /// implementation will be required to provide specific hooks:
268 /// - getCachedResultImpl
271 /// The details of the call pattern are within.
273 /// Note that there is also a generic analysis manager template which implements
274 /// the above required functions along with common datastructures used for
275 /// managing analyses. This base class is factored so that if you need to
276 /// customize the handling of a specific IR unit, you can do so without
277 /// replicating *all* of the boilerplate.
278 template <typename DerivedT
, typename IRUnitT
> class AnalysisManagerBase
{
279 DerivedT
*derived_this() { return static_cast<DerivedT
*>(this); }
280 const DerivedT
*derived_this() const {
281 return static_cast<const DerivedT
*>(this);
284 AnalysisManagerBase(const AnalysisManagerBase
&) LLVM_DELETED_FUNCTION
;
285 AnalysisManagerBase
&
286 operator=(const AnalysisManagerBase
&) LLVM_DELETED_FUNCTION
;
289 typedef detail::AnalysisResultConcept
<IRUnitT
> ResultConceptT
;
290 typedef detail::AnalysisPassConcept
<IRUnitT
> PassConceptT
;
292 // FIXME: Provide template aliases for the models when we're using C++11 in
293 // a mode supporting them.
295 // We have to explicitly define all the special member functions because MSVC
296 // refuses to generate them.
297 AnalysisManagerBase() {}
298 AnalysisManagerBase(AnalysisManagerBase
&&Arg
)
299 : AnalysisPasses(std::move(Arg
.AnalysisPasses
)) {}
300 AnalysisManagerBase
&operator=(AnalysisManagerBase
&&RHS
) {
301 AnalysisPasses
= std::move(RHS
.AnalysisPasses
);
306 /// \brief Get the result of an analysis pass for this module.
308 /// If there is not a valid cached result in the manager already, this will
309 /// re-run the analysis to produce a valid result.
310 template <typename PassT
> typename
PassT::Result
&getResult(IRUnitT
&IR
) {
311 assert(AnalysisPasses
.count(PassT::ID()) &&
312 "This analysis pass was not registered prior to being queried");
314 ResultConceptT
&ResultConcept
=
315 derived_this()->getResultImpl(PassT::ID(), IR
);
316 typedef detail::AnalysisResultModel
<IRUnitT
, PassT
, typename
PassT::Result
>
318 return static_cast<ResultModelT
&>(ResultConcept
).Result
;
321 /// \brief Get the cached result of an analysis pass for this module.
323 /// This method never runs the analysis.
325 /// \returns null if there is no cached result.
326 template <typename PassT
>
327 typename
PassT::Result
*getCachedResult(IRUnitT
&IR
) const {
328 assert(AnalysisPasses
.count(PassT::ID()) &&
329 "This analysis pass was not registered prior to being queried");
331 ResultConceptT
*ResultConcept
=
332 derived_this()->getCachedResultImpl(PassT::ID(), IR
);
336 typedef detail::AnalysisResultModel
<IRUnitT
, PassT
, typename
PassT::Result
>
338 return &static_cast<ResultModelT
*>(ResultConcept
)->Result
;
341 /// \brief Register an analysis pass with the manager.
343 /// This provides an initialized and set-up analysis pass to the analysis
344 /// manager. Whomever is setting up analysis passes must use this to populate
345 /// the manager with all of the analysis passes available.
346 template <typename PassT
> void registerPass(PassT Pass
) {
347 assert(!AnalysisPasses
.count(PassT::ID()) &&
348 "Registered the same analysis pass twice!");
349 typedef detail::AnalysisPassModel
<IRUnitT
, PassT
> PassModelT
;
350 AnalysisPasses
[PassT::ID()].reset(new PassModelT(std::move(Pass
)));
353 /// \brief Invalidate a specific analysis pass for an IR module.
355 /// Note that the analysis result can disregard invalidation.
356 template <typename PassT
> void invalidate(IRUnitT
&IR
) {
357 assert(AnalysisPasses
.count(PassT::ID()) &&
358 "This analysis pass was not registered prior to being invalidated");
359 derived_this()->invalidateImpl(PassT::ID(), IR
);
362 /// \brief Invalidate analyses cached for an IR unit.
364 /// Walk through all of the analyses pertaining to this unit of IR and
365 /// invalidate them unless they are preserved by the PreservedAnalyses set.
366 /// We accept the PreservedAnalyses set by value and update it with each
367 /// analyis pass which has been successfully invalidated and thus can be
368 /// preserved going forward. The updated set is returned.
369 PreservedAnalyses
invalidate(IRUnitT
&IR
, PreservedAnalyses PA
) {
370 return derived_this()->invalidateImpl(IR
, std::move(PA
));
374 /// \brief Lookup a registered analysis pass.
375 PassConceptT
&lookupPass(void *PassID
) {
376 typename
AnalysisPassMapT::iterator PI
= AnalysisPasses
.find(PassID
);
377 assert(PI
!= AnalysisPasses
.end() &&
378 "Analysis passes must be registered prior to being queried!");
382 /// \brief Lookup a registered analysis pass.
383 const PassConceptT
&lookupPass(void *PassID
) const {
384 typename
AnalysisPassMapT::const_iterator PI
= AnalysisPasses
.find(PassID
);
385 assert(PI
!= AnalysisPasses
.end() &&
386 "Analysis passes must be registered prior to being queried!");
391 /// \brief Map type from module analysis pass ID to pass concept pointer.
392 typedef DenseMap
<void *, std::unique_ptr
<PassConceptT
>> AnalysisPassMapT
;
394 /// \brief Collection of module analysis passes, indexed by ID.
395 AnalysisPassMapT AnalysisPasses
;
398 } // End namespace detail
400 /// \brief A generic analysis pass manager with lazy running and caching of
403 /// This analysis manager can be used for any IR unit where the address of the
404 /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
405 /// the address of each unit of IR cached.
406 template <typename IRUnitT
>
407 class AnalysisManager
408 : public detail::AnalysisManagerBase
<AnalysisManager
<IRUnitT
>, IRUnitT
> {
409 friend class detail::AnalysisManagerBase
<AnalysisManager
<IRUnitT
>, IRUnitT
>;
410 typedef detail::AnalysisManagerBase
<AnalysisManager
<IRUnitT
>, IRUnitT
> BaseT
;
411 typedef typename
BaseT::ResultConceptT ResultConceptT
;
412 typedef typename
BaseT::PassConceptT PassConceptT
;
415 // Most public APIs are inherited from the CRTP base class.
417 /// \brief Construct an empty analysis manager.
419 /// A flag can be passed to indicate that the manager should perform debug
421 AnalysisManager(bool DebugLogging
= false) : DebugLogging(DebugLogging
) {}
423 // We have to explicitly define all the special member functions because MSVC
424 // refuses to generate them.
425 AnalysisManager(AnalysisManager
&&Arg
)
426 : BaseT(std::move(static_cast<BaseT
&>(Arg
))),
427 AnalysisResults(std::move(Arg
.AnalysisResults
)),
428 DebugLogging(std::move(Arg
.DebugLogging
)) {}
429 AnalysisManager
&operator=(AnalysisManager
&&RHS
) {
430 BaseT::operator=(std::move(static_cast<BaseT
&>(RHS
)));
431 AnalysisResults
= std::move(RHS
.AnalysisResults
);
432 DebugLogging
= std::move(RHS
.DebugLogging
);
436 /// \brief Returns true if the analysis manager has an empty results cache.
438 assert(AnalysisResults
.empty() == AnalysisResultLists
.empty() &&
439 "The storage and index of analysis results disagree on how many "
441 return AnalysisResults
.empty();
444 /// \brief Clear the analysis result cache.
446 /// This routine allows cleaning up when the set of IR units itself has
447 /// potentially changed, and thus we can't even look up a a result and
448 /// invalidate it directly. Notably, this does *not* call invalidate functions
449 /// as there is nothing to be done for them.
451 AnalysisResults
.clear();
452 AnalysisResultLists
.clear();
456 AnalysisManager(const AnalysisManager
&) LLVM_DELETED_FUNCTION
;
457 AnalysisManager
&operator=(const AnalysisManager
&) LLVM_DELETED_FUNCTION
;
459 /// \brief Get an analysis result, running the pass if necessary.
460 ResultConceptT
&getResultImpl(void *PassID
, IRUnitT
&IR
) {
461 typename
AnalysisResultMapT::iterator RI
;
463 std::tie(RI
, Inserted
) = AnalysisResults
.insert(std::make_pair(
464 std::make_pair(PassID
, &IR
), typename
AnalysisResultListT::iterator()));
466 // If we don't have a cached result for this function, look up the pass and
467 // run it to produce a result, which we then add to the cache.
469 auto &P
= this->lookupPass(PassID
);
471 dbgs() << "Running analysis: " << P
.name() << "\n";
472 AnalysisResultListT
&ResultList
= AnalysisResultLists
[&IR
];
473 ResultList
.emplace_back(PassID
, P
.run(IR
, this));
474 RI
->second
= std::prev(ResultList
.end());
477 return *RI
->second
->second
;
480 /// \brief Get a cached analysis result or return null.
481 ResultConceptT
*getCachedResultImpl(void *PassID
, IRUnitT
&IR
) const {
482 typename
AnalysisResultMapT::const_iterator RI
=
483 AnalysisResults
.find(std::make_pair(PassID
, &IR
));
484 return RI
== AnalysisResults
.end() ? nullptr : &*RI
->second
->second
;
487 /// \brief Invalidate a function pass result.
488 void invalidateImpl(void *PassID
, IRUnitT
&IR
) {
489 typename
AnalysisResultMapT::iterator RI
=
490 AnalysisResults
.find(std::make_pair(PassID
, &IR
));
491 if (RI
== AnalysisResults
.end())
495 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID
).name()
497 AnalysisResultLists
[&IR
].erase(RI
->second
);
498 AnalysisResults
.erase(RI
);
501 /// \brief Invalidate the results for a function..
502 PreservedAnalyses
invalidateImpl(IRUnitT
&IR
, PreservedAnalyses PA
) {
503 // Short circuit for a common case of all analyses being preserved.
504 if (PA
.areAllPreserved())
505 return std::move(PA
);
508 dbgs() << "Invalidating all non-preserved analyses for: "
509 << IR
.getName() << "\n";
511 // Clear all the invalidated results associated specifically with this
513 SmallVector
<void *, 8> InvalidatedPassIDs
;
514 AnalysisResultListT
&ResultsList
= AnalysisResultLists
[&IR
];
515 for (typename
AnalysisResultListT::iterator I
= ResultsList
.begin(),
516 E
= ResultsList
.end();
518 void *PassID
= I
->first
;
520 // Pass the invalidation down to the pass itself to see if it thinks it is
521 // necessary. The analysis pass can return false if no action on the part
522 // of the analysis manager is required for this invalidation event.
523 if (I
->second
->invalidate(IR
, PA
)) {
525 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID
).name()
528 InvalidatedPassIDs
.push_back(I
->first
);
529 I
= ResultsList
.erase(I
);
534 // After handling each pass, we mark it as preserved. Once we've
535 // invalidated any stale results, the rest of the system is allowed to
536 // start preserving this analysis again.
539 while (!InvalidatedPassIDs
.empty())
540 AnalysisResults
.erase(
541 std::make_pair(InvalidatedPassIDs
.pop_back_val(), &IR
));
542 if (ResultsList
.empty())
543 AnalysisResultLists
.erase(&IR
);
545 return std::move(PA
);
548 /// \brief List of function analysis pass IDs and associated concept pointers.
550 /// Requires iterators to be valid across appending new entries and arbitrary
551 /// erases. Provides both the pass ID and concept pointer such that it is
552 /// half of a bijection and provides storage for the actual result concept.
553 typedef std::list
<std::pair
<
554 void *, std::unique_ptr
<detail::AnalysisResultConcept
<IRUnitT
>>>>
557 /// \brief Map type from function pointer to our custom list type.
558 typedef DenseMap
<IRUnitT
*, AnalysisResultListT
> AnalysisResultListMapT
;
560 /// \brief Map from function to a list of function analysis results.
562 /// Provides linear time removal of all analysis results for a function and
563 /// the ultimate storage for a particular cached analysis result.
564 AnalysisResultListMapT AnalysisResultLists
;
566 /// \brief Map type from a pair of analysis ID and function pointer to an
567 /// iterator into a particular result list.
568 typedef DenseMap
<std::pair
<void *, IRUnitT
*>,
569 typename
AnalysisResultListT::iterator
> AnalysisResultMapT
;
571 /// \brief Map from an analysis ID and function to a particular cached
573 AnalysisResultMapT AnalysisResults
;
575 /// \brief A flag indicating whether debug logging is enabled.
579 /// \brief Convenience typedef for the Module analysis manager.
580 typedef AnalysisManager
<Module
> ModuleAnalysisManager
;
582 /// \brief Convenience typedef for the Function analysis manager.
583 typedef AnalysisManager
<Function
> FunctionAnalysisManager
;
585 /// \brief A module analysis which acts as a proxy for a function analysis
588 /// This primarily proxies invalidation information from the module analysis
589 /// manager and module pass manager to a function analysis manager. You should
590 /// never use a function analysis manager from within (transitively) a module
591 /// pass manager unless your parent module pass has received a proxy result
593 class FunctionAnalysisManagerModuleProxy
{
597 static void *ID() { return (void *)&PassID
; }
599 static StringRef
name() { return "FunctionAnalysisManagerModuleProxy"; }
601 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager
&FAM
)
603 // We have to explicitly define all the special member functions because MSVC
604 // refuses to generate them.
605 FunctionAnalysisManagerModuleProxy(
606 const FunctionAnalysisManagerModuleProxy
&Arg
)
608 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy
&&Arg
)
609 : FAM(std::move(Arg
.FAM
)) {}
610 FunctionAnalysisManagerModuleProxy
&
611 operator=(FunctionAnalysisManagerModuleProxy RHS
) {
612 std::swap(FAM
, RHS
.FAM
);
616 /// \brief Run the analysis pass and create our proxy result object.
618 /// This doesn't do any interesting work, it is primarily used to insert our
619 /// proxy result object into the module analysis cache so that we can proxy
620 /// invalidation to the function analysis manager.
622 /// In debug builds, it will also assert that the analysis manager is empty
623 /// as no queries should arrive at the function analysis manager prior to
624 /// this analysis being requested.
625 Result
run(Module
&M
);
630 FunctionAnalysisManager
*FAM
;
633 /// \brief The result proxy object for the
634 /// \c FunctionAnalysisManagerModuleProxy.
636 /// See its documentation for more information.
637 class FunctionAnalysisManagerModuleProxy::Result
{
639 explicit Result(FunctionAnalysisManager
&FAM
) : FAM(&FAM
) {}
640 // We have to explicitly define all the special member functions because MSVC
641 // refuses to generate them.
642 Result(const Result
&Arg
) : FAM(Arg
.FAM
) {}
643 Result(Result
&&Arg
) : FAM(std::move(Arg
.FAM
)) {}
644 Result
&operator=(Result RHS
) {
645 std::swap(FAM
, RHS
.FAM
);
650 /// \brief Accessor for the \c FunctionAnalysisManager.
651 FunctionAnalysisManager
&getManager() { return *FAM
; }
653 /// \brief Handler for invalidation of the module.
655 /// If this analysis itself is preserved, then we assume that the set of \c
656 /// Function objects in the \c Module hasn't changed and thus we don't need
657 /// to invalidate *all* cached data associated with a \c Function* in the \c
658 /// FunctionAnalysisManager.
660 /// Regardless of whether this analysis is marked as preserved, all of the
661 /// analyses in the \c FunctionAnalysisManager are potentially invalidated
662 /// based on the set of preserved analyses.
663 bool invalidate(Module
&M
, const PreservedAnalyses
&PA
);
666 FunctionAnalysisManager
*FAM
;
669 /// \brief A function analysis which acts as a proxy for a module analysis
672 /// This primarily provides an accessor to a parent module analysis manager to
673 /// function passes. Only the const interface of the module analysis manager is
674 /// provided to indicate that once inside of a function analysis pass you
675 /// cannot request a module analysis to actually run. Instead, the user must
676 /// rely on the \c getCachedResult API.
678 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
679 /// the recursive return path of each layer of the pass manager and the
680 /// returned PreservedAnalysis set.
681 class ModuleAnalysisManagerFunctionProxy
{
683 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
686 explicit Result(const ModuleAnalysisManager
&MAM
) : MAM(&MAM
) {}
687 // We have to explicitly define all the special member functions because
688 // MSVC refuses to generate them.
689 Result(const Result
&Arg
) : MAM(Arg
.MAM
) {}
690 Result(Result
&&Arg
) : MAM(std::move(Arg
.MAM
)) {}
691 Result
&operator=(Result RHS
) {
692 std::swap(MAM
, RHS
.MAM
);
696 const ModuleAnalysisManager
&getManager() const { return *MAM
; }
698 /// \brief Handle invalidation by ignoring it, this pass is immutable.
699 bool invalidate(Function
&) { return false; }
702 const ModuleAnalysisManager
*MAM
;
705 static void *ID() { return (void *)&PassID
; }
707 static StringRef
name() { return "ModuleAnalysisManagerFunctionProxy"; }
709 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager
&MAM
)
711 // We have to explicitly define all the special member functions because MSVC
712 // refuses to generate them.
713 ModuleAnalysisManagerFunctionProxy(
714 const ModuleAnalysisManagerFunctionProxy
&Arg
)
716 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy
&&Arg
)
717 : MAM(std::move(Arg
.MAM
)) {}
718 ModuleAnalysisManagerFunctionProxy
&
719 operator=(ModuleAnalysisManagerFunctionProxy RHS
) {
720 std::swap(MAM
, RHS
.MAM
);
724 /// \brief Run the analysis pass and create our proxy result object.
725 /// Nothing to see here, it just forwards the \c MAM reference into the
727 Result
run(Function
&) { return Result(*MAM
); }
732 const ModuleAnalysisManager
*MAM
;
735 /// \brief Trivial adaptor that maps from a module to its functions.
737 /// Designed to allow composition of a FunctionPass(Manager) and
738 /// a ModulePassManager. Note that if this pass is constructed with a pointer
739 /// to a \c ModuleAnalysisManager it will run the
740 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
741 /// pass over the module to enable a \c FunctionAnalysisManager to be used
742 /// within this run safely.
744 /// Function passes run within this adaptor can rely on having exclusive access
745 /// to the function they are run over. They should not read or modify any other
746 /// functions! Other threads or systems may be manipulating other functions in
747 /// the module, and so their state should never be relied on.
748 /// FIXME: Make the above true for all of LLVM's actual passes, some still
749 /// violate this principle.
751 /// Function passes can also read the module containing the function, but they
752 /// should not modify that module outside of the use lists of various globals.
753 /// For example, a function pass is not permitted to add functions to the
755 /// FIXME: Make the above true for all of LLVM's actual passes, some still
756 /// violate this principle.
757 template <typename FunctionPassT
> class ModuleToFunctionPassAdaptor
{
759 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass
)
760 : Pass(std::move(Pass
)) {}
761 // We have to explicitly define all the special member functions because MSVC
762 // refuses to generate them.
763 ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor
&Arg
)
765 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor
&&Arg
)
766 : Pass(std::move(Arg
.Pass
)) {}
767 friend void swap(ModuleToFunctionPassAdaptor
&LHS
,
768 ModuleToFunctionPassAdaptor
&RHS
) {
770 swap(LHS
.Pass
, RHS
.Pass
);
772 ModuleToFunctionPassAdaptor
&operator=(ModuleToFunctionPassAdaptor RHS
) {
777 /// \brief Runs the function pass across every function in the module.
778 PreservedAnalyses
run(Module
&M
, ModuleAnalysisManager
*AM
) {
779 FunctionAnalysisManager
*FAM
= nullptr;
781 // Setup the function analysis manager from its proxy.
782 FAM
= &AM
->getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
784 PreservedAnalyses PA
= PreservedAnalyses::all();
785 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
) {
786 PreservedAnalyses PassPA
= Pass
.run(*I
, FAM
);
788 // We know that the function pass couldn't have invalidated any other
789 // function's analyses (that's the contract of a function pass), so
790 // directly handle the function analysis manager's invalidation here and
791 // update our preserved set to reflect that these have already been
794 PassPA
= FAM
->invalidate(*I
, std::move(PassPA
));
796 // Then intersect the preserved set so that invalidation of module
797 // analyses will eventually occur when the module pass completes.
798 PA
.intersect(std::move(PassPA
));
801 // By definition we preserve the proxy. This precludes *any* invalidation
802 // of function analyses by the proxy, but that's OK because we've taken
803 // care to invalidate analyses in the function analysis manager
804 // incrementally above.
805 PA
.preserve
<FunctionAnalysisManagerModuleProxy
>();
809 static StringRef
name() { return "ModuleToFunctionPassAdaptor"; }
815 /// \brief A function to deduce a function pass type and wrap it in the
816 /// templated adaptor.
817 template <typename FunctionPassT
>
818 ModuleToFunctionPassAdaptor
<FunctionPassT
>
819 createModuleToFunctionPassAdaptor(FunctionPassT Pass
) {
820 return std::move(ModuleToFunctionPassAdaptor
<FunctionPassT
>(std::move(Pass
)));
823 /// \brief A template utility pass to force an analysis result to be available.
825 /// This is a no-op pass which simply forces a specific analysis pass's result
826 /// to be available when it is run.
827 template <typename AnalysisT
> struct RequireAnalysisPass
{
828 /// \brief Run this pass over some unit of IR.
830 /// This pass can be run over any unit of IR and use any analysis manager
831 /// provided they satisfy the basic API requirements. When this pass is
832 /// created, these methods can be instantiated to satisfy whatever the
833 /// context requires.
834 template <typename IRUnitT
>
835 PreservedAnalyses
run(IRUnitT
&Arg
, AnalysisManager
<IRUnitT
> *AM
) {
837 (void)AM
->template getResult
<AnalysisT
>(Arg
);
839 return PreservedAnalyses::all();
842 static StringRef
name() { return "RequireAnalysisPass"; }
845 /// \brief A template utility pass to force an analysis result to be
848 /// This is a no-op pass which simply forces a specific analysis result to be
849 /// invalidated when it is run.
850 template <typename AnalysisT
> struct InvalidateAnalysisPass
{
851 /// \brief Run this pass over some unit of IR.
853 /// This pass can be run over any unit of IR and use any analysis manager
854 /// provided they satisfy the basic API requirements. When this pass is
855 /// created, these methods can be instantiated to satisfy whatever the
856 /// context requires.
857 template <typename IRUnitT
>
858 PreservedAnalyses
run(IRUnitT
&Arg
, AnalysisManager
<IRUnitT
> *AM
) {
860 // We have to directly invalidate the analysis result as we can't
861 // enumerate all other analyses and use the preserved set to control it.
862 (void)AM
->template invalidate
<AnalysisT
>(Arg
);
864 return PreservedAnalyses::all();
867 static StringRef
name() { return "InvalidateAnalysisPass"; }
870 /// \brief A utility pass that does nothing but preserves no analyses.
872 /// As a consequence fo not preserving any analyses, this pass will force all
873 /// analysis passes to be re-run to produce fresh results if any are needed.
874 struct InvalidateAllAnalysesPass
{
875 /// \brief Run this pass over some unit of IR.
876 template <typename IRUnitT
> PreservedAnalyses
run(IRUnitT
&Arg
) {
877 return PreservedAnalyses::none();
880 static StringRef
name() { return "InvalidateAllAnalysesPass"; }