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 units of IR.
180 /// A pass manager contains a sequence of passes to run over units of IR. It is
181 /// itself a valid pass over that unit of IR, and when over some given IR will
182 /// run each pass in sequence. This is the primary and most basic building
183 /// block of a pass pipeline.
185 /// If it is run with an \c AnalysisManager<IRUnitT> argument, it will propagate
186 /// that analysis manager to each pass it runs, as well as calling the analysis
187 /// manager's invalidation routine with the PreservedAnalyses of each pass it
189 template <typename IRUnitT> class PassManager {
191 // We have to explicitly define all the special member functions because MSVC
192 // refuses to generate them.
194 PassManager(PassManager &&Arg) : Passes(std::move(Arg.Passes)) {}
195 PassManager &operator=(PassManager &&RHS) {
196 Passes = std::move(RHS.Passes);
200 /// \brief Run all of the passes in this manager over the IR.
201 PreservedAnalyses run(IRUnitT &IR, AnalysisManager<IRUnitT> *AM = nullptr) {
202 PreservedAnalyses PA = PreservedAnalyses::all();
205 dbgs() << "Starting pass manager run.\n";
207 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
209 dbgs() << "Running pass: " << Passes[Idx]->name() << "\n";
211 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM);
213 // If we have an active analysis manager at this level we want to ensure
214 // we update it as each pass runs and potentially invalidates analyses.
215 // We also update the preserved set of analyses based on what analyses we
216 // have already handled the invalidation for here and don't need to
217 // invalidate when finished.
219 PassPA = AM->invalidate(IR, std::move(PassPA));
221 // Finally, we intersect the final preserved analyses to compute the
222 // aggregate preserved set for this pass manager.
223 PA.intersect(std::move(PassPA));
225 // FIXME: Historically, the pass managers all called the LLVM context's
226 // yield function here. We don't have a generic way to acquire the
227 // context and it isn't yet clear what the right pattern is for yielding
228 // in the new pass manager so it is currently omitted.
229 //IR.getContext().yield();
233 dbgs() << "Finished pass manager run.\n";
238 template <typename PassT> void addPass(PassT Pass) {
239 Passes.emplace_back(new PassModel<PassT>(std::move(Pass)));
242 static StringRef name() { return "PassManager"; }
245 // Pull in the concept type and model template specialized for modules.
246 typedef detail::PassConcept<IRUnitT, AnalysisManager<IRUnitT>> PassConcept;
247 template <typename PassT>
249 : detail::PassModel<IRUnitT, AnalysisManager<IRUnitT>, PassT> {
250 PassModel(PassT Pass)
251 : detail::PassModel<IRUnitT, AnalysisManager<IRUnitT>, PassT>(
255 PassManager(const PassManager &) LLVM_DELETED_FUNCTION;
256 PassManager &operator=(const PassManager &) LLVM_DELETED_FUNCTION;
258 std::vector<std::unique_ptr<PassConcept>> Passes;
261 /// \brief Convenience typedef for a pass manager over modules.
262 typedef PassManager<Module> ModulePassManager;
264 /// \brief Convenience typedef for a pass manager over functions.
265 typedef PassManager<Function> FunctionPassManager;
269 /// \brief A CRTP base used to implement analysis managers.
271 /// This class template serves as the boiler plate of an analysis manager. Any
272 /// analysis manager can be implemented on top of this base class. Any
273 /// implementation will be required to provide specific hooks:
276 /// - getCachedResultImpl
279 /// The details of the call pattern are within.
281 /// Note that there is also a generic analysis manager template which implements
282 /// the above required functions along with common datastructures used for
283 /// managing analyses. This base class is factored so that if you need to
284 /// customize the handling of a specific IR unit, you can do so without
285 /// replicating *all* of the boilerplate.
286 template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
287 DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
288 const DerivedT *derived_this() const {
289 return static_cast<const DerivedT *>(this);
292 AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
293 AnalysisManagerBase &
294 operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
297 typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
298 typedef detail::AnalysisPassConcept<IRUnitT, DerivedT> PassConceptT;
300 // FIXME: Provide template aliases for the models when we're using C++11 in
301 // a mode supporting them.
303 // We have to explicitly define all the special member functions because MSVC
304 // refuses to generate them.
305 AnalysisManagerBase() {}
306 AnalysisManagerBase(AnalysisManagerBase &&Arg)
307 : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
308 AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
309 AnalysisPasses = std::move(RHS.AnalysisPasses);
314 /// \brief Get the result of an analysis pass for this module.
316 /// If there is not a valid cached result in the manager already, this will
317 /// re-run the analysis to produce a valid result.
318 template <typename PassT> typename PassT::Result &getResult(IRUnitT &IR) {
319 assert(AnalysisPasses.count(PassT::ID()) &&
320 "This analysis pass was not registered prior to being queried");
322 ResultConceptT &ResultConcept =
323 derived_this()->getResultImpl(PassT::ID(), IR);
324 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
326 return static_cast<ResultModelT &>(ResultConcept).Result;
329 /// \brief Get the cached result of an analysis pass for this module.
331 /// This method never runs the analysis.
333 /// \returns null if there is no cached result.
334 template <typename PassT>
335 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
336 assert(AnalysisPasses.count(PassT::ID()) &&
337 "This analysis pass was not registered prior to being queried");
339 ResultConceptT *ResultConcept =
340 derived_this()->getCachedResultImpl(PassT::ID(), IR);
344 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
346 return &static_cast<ResultModelT *>(ResultConcept)->Result;
349 /// \brief Register an analysis pass with the manager.
351 /// This provides an initialized and set-up analysis pass to the analysis
352 /// manager. Whomever is setting up analysis passes must use this to populate
353 /// the manager with all of the analysis passes available.
354 template <typename PassT> void registerPass(PassT Pass) {
355 assert(!AnalysisPasses.count(PassT::ID()) &&
356 "Registered the same analysis pass twice!");
357 typedef detail::AnalysisPassModel<IRUnitT, DerivedT, PassT> PassModelT;
358 AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
361 /// \brief Invalidate a specific analysis pass for an IR module.
363 /// Note that the analysis result can disregard invalidation.
364 template <typename PassT> void invalidate(IRUnitT &IR) {
365 assert(AnalysisPasses.count(PassT::ID()) &&
366 "This analysis pass was not registered prior to being invalidated");
367 derived_this()->invalidateImpl(PassT::ID(), IR);
370 /// \brief Invalidate analyses cached for an IR unit.
372 /// Walk through all of the analyses pertaining to this unit of IR and
373 /// invalidate them unless they are preserved by the PreservedAnalyses set.
374 /// We accept the PreservedAnalyses set by value and update it with each
375 /// analyis pass which has been successfully invalidated and thus can be
376 /// preserved going forward. The updated set is returned.
377 PreservedAnalyses invalidate(IRUnitT &IR, PreservedAnalyses PA) {
378 return derived_this()->invalidateImpl(IR, std::move(PA));
382 /// \brief Lookup a registered analysis pass.
383 PassConceptT &lookupPass(void *PassID) {
384 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
385 assert(PI != AnalysisPasses.end() &&
386 "Analysis passes must be registered prior to being queried!");
390 /// \brief Lookup a registered analysis pass.
391 const PassConceptT &lookupPass(void *PassID) const {
392 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
393 assert(PI != AnalysisPasses.end() &&
394 "Analysis passes must be registered prior to being queried!");
399 /// \brief Map type from module analysis pass ID to pass concept pointer.
400 typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
402 /// \brief Collection of module analysis passes, indexed by ID.
403 AnalysisPassMapT AnalysisPasses;
406 } // End namespace detail
408 /// \brief A generic analysis pass manager with lazy running and caching of
411 /// This analysis manager can be used for any IR unit where the address of the
412 /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
413 /// the address of each unit of IR cached.
414 template <typename IRUnitT>
415 class AnalysisManager
416 : public detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> {
417 friend class detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT>;
418 typedef detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> BaseT;
419 typedef typename BaseT::ResultConceptT ResultConceptT;
420 typedef typename BaseT::PassConceptT PassConceptT;
423 // Most public APIs are inherited from the CRTP base class.
425 // We have to explicitly define all the special member functions because MSVC
426 // refuses to generate them.
428 AnalysisManager(AnalysisManager &&Arg)
429 : BaseT(std::move(static_cast<BaseT &>(Arg))),
430 AnalysisResults(std::move(Arg.AnalysisResults)) {}
431 AnalysisManager &operator=(AnalysisManager &&RHS) {
432 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
433 AnalysisResults = std::move(RHS.AnalysisResults);
437 /// \brief Returns true if the analysis manager has an empty results cache.
439 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
440 "The storage and index of analysis results disagree on how many "
442 return AnalysisResults.empty();
445 /// \brief Clear the analysis result cache.
447 /// This routine allows cleaning up when the set of IR units itself has
448 /// potentially changed, and thus we can't even look up a a result and
449 /// invalidate it directly. Notably, this does *not* call invalidate functions
450 /// as there is nothing to be done for them.
452 AnalysisResults.clear();
453 AnalysisResultLists.clear();
457 AnalysisManager(const AnalysisManager &) LLVM_DELETED_FUNCTION;
458 AnalysisManager &operator=(const AnalysisManager &) LLVM_DELETED_FUNCTION;
460 /// \brief Get an analysis result, running the pass if necessary.
461 ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
462 typename AnalysisResultMapT::iterator RI;
464 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
465 std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
467 // If we don't have a cached result for this function, look up the pass and
468 // run it to produce a result, which we then add to the cache.
470 auto &P = this->lookupPass(PassID);
472 dbgs() << "Running analysis: " << P.name() << "\n";
473 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
474 ResultList.emplace_back(PassID, P.run(IR, this));
475 RI->second = std::prev(ResultList.end());
478 return *RI->second->second;
481 /// \brief Get a cached analysis result or return null.
482 ResultConceptT *getCachedResultImpl(void *PassID, IRUnitT &IR) const {
483 typename AnalysisResultMapT::const_iterator RI =
484 AnalysisResults.find(std::make_pair(PassID, &IR));
485 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
488 /// \brief Invalidate a function pass result.
489 void invalidateImpl(void *PassID, IRUnitT &IR) {
490 typename AnalysisResultMapT::iterator RI =
491 AnalysisResults.find(std::make_pair(PassID, &IR));
492 if (RI == AnalysisResults.end())
496 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
498 AnalysisResultLists[&IR].erase(RI->second);
499 AnalysisResults.erase(RI);
502 /// \brief Invalidate the results for a function..
503 PreservedAnalyses invalidateImpl(IRUnitT &IR, PreservedAnalyses PA) {
504 // Short circuit for a common case of all analyses being preserved.
505 if (PA.areAllPreserved())
506 return std::move(PA);
509 dbgs() << "Invalidating all non-preserved analyses for: "
510 << IR.getName() << "\n";
512 // Clear all the invalidated results associated specifically with this
514 SmallVector<void *, 8> InvalidatedPassIDs;
515 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
516 for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
517 E = ResultsList.end();
519 void *PassID = I->first;
521 // Pass the invalidation down to the pass itself to see if it thinks it is
522 // necessary. The analysis pass can return false if no action on the part
523 // of the analysis manager is required for this invalidation event.
524 if (I->second->invalidate(IR, PA)) {
526 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
529 InvalidatedPassIDs.push_back(I->first);
530 I = ResultsList.erase(I);
535 // After handling each pass, we mark it as preserved. Once we've
536 // invalidated any stale results, the rest of the system is allowed to
537 // start preserving this analysis again.
540 while (!InvalidatedPassIDs.empty())
541 AnalysisResults.erase(
542 std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
543 if (ResultsList.empty())
544 AnalysisResultLists.erase(&IR);
546 return std::move(PA);
549 /// \brief List of function analysis pass IDs and associated concept pointers.
551 /// Requires iterators to be valid across appending new entries and arbitrary
552 /// erases. Provides both the pass ID and concept pointer such that it is
553 /// half of a bijection and provides storage for the actual result concept.
554 typedef std::list<std::pair<
555 void *, std::unique_ptr<detail::AnalysisResultConcept<IRUnitT>>>>
558 /// \brief Map type from function pointer to our custom list type.
559 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
561 /// \brief Map from function to a list of function analysis results.
563 /// Provides linear time removal of all analysis results for a function and
564 /// the ultimate storage for a particular cached analysis result.
565 AnalysisResultListMapT AnalysisResultLists;
567 /// \brief Map type from a pair of analysis ID and function pointer to an
568 /// iterator into a particular result list.
569 typedef DenseMap<std::pair<void *, IRUnitT *>,
570 typename AnalysisResultListT::iterator> AnalysisResultMapT;
572 /// \brief Map from an analysis ID and function to a particular cached
574 AnalysisResultMapT AnalysisResults;
577 /// \brief A module analysis which acts as a proxy for a function analysis
580 /// This primarily proxies invalidation information from the module analysis
581 /// manager and module pass manager to a function analysis manager. You should
582 /// never use a function analysis manager from within (transitively) a module
583 /// pass manager unless your parent module pass has received a proxy result
585 class FunctionAnalysisManagerModuleProxy {
589 static void *ID() { return (void *)&PassID; }
591 static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
593 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
595 // We have to explicitly define all the special member functions because MSVC
596 // refuses to generate them.
597 FunctionAnalysisManagerModuleProxy(
598 const FunctionAnalysisManagerModuleProxy &Arg)
600 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
601 : FAM(std::move(Arg.FAM)) {}
602 FunctionAnalysisManagerModuleProxy &
603 operator=(FunctionAnalysisManagerModuleProxy RHS) {
604 std::swap(FAM, RHS.FAM);
608 /// \brief Run the analysis pass and create our proxy result object.
610 /// This doesn't do any interesting work, it is primarily used to insert our
611 /// proxy result object into the module analysis cache so that we can proxy
612 /// invalidation to the function analysis manager.
614 /// In debug builds, it will also assert that the analysis manager is empty
615 /// as no queries should arrive at the function analysis manager prior to
616 /// this analysis being requested.
617 Result run(Module &M);
622 FunctionAnalysisManager *FAM;
625 /// \brief The result proxy object for the
626 /// \c FunctionAnalysisManagerModuleProxy.
628 /// See its documentation for more information.
629 class FunctionAnalysisManagerModuleProxy::Result {
631 explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
632 // We have to explicitly define all the special member functions because MSVC
633 // refuses to generate them.
634 Result(const Result &Arg) : FAM(Arg.FAM) {}
635 Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
636 Result &operator=(Result RHS) {
637 std::swap(FAM, RHS.FAM);
642 /// \brief Accessor for the \c FunctionAnalysisManager.
643 FunctionAnalysisManager &getManager() { return *FAM; }
645 /// \brief Handler for invalidation of the module.
647 /// If this analysis itself is preserved, then we assume that the set of \c
648 /// Function objects in the \c Module hasn't changed and thus we don't need
649 /// to invalidate *all* cached data associated with a \c Function* in the \c
650 /// FunctionAnalysisManager.
652 /// Regardless of whether this analysis is marked as preserved, all of the
653 /// analyses in the \c FunctionAnalysisManager are potentially invalidated
654 /// based on the set of preserved analyses.
655 bool invalidate(Module &M, const PreservedAnalyses &PA);
658 FunctionAnalysisManager *FAM;
661 /// \brief A function analysis which acts as a proxy for a module analysis
664 /// This primarily provides an accessor to a parent module analysis manager to
665 /// function passes. Only the const interface of the module analysis manager is
666 /// provided to indicate that once inside of a function analysis pass you
667 /// cannot request a module analysis to actually run. Instead, the user must
668 /// rely on the \c getCachedResult API.
670 /// This proxy *doesn't* manage the invalidation in any way. That is handled by
671 /// the recursive return path of each layer of the pass manager and the
672 /// returned PreservedAnalysis set.
673 class ModuleAnalysisManagerFunctionProxy {
675 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
678 explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
679 // We have to explicitly define all the special member functions because
680 // MSVC refuses to generate them.
681 Result(const Result &Arg) : MAM(Arg.MAM) {}
682 Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
683 Result &operator=(Result RHS) {
684 std::swap(MAM, RHS.MAM);
688 const ModuleAnalysisManager &getManager() const { return *MAM; }
690 /// \brief Handle invalidation by ignoring it, this pass is immutable.
691 bool invalidate(Function &) { return false; }
694 const ModuleAnalysisManager *MAM;
697 static void *ID() { return (void *)&PassID; }
699 static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
701 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
703 // We have to explicitly define all the special member functions because MSVC
704 // refuses to generate them.
705 ModuleAnalysisManagerFunctionProxy(
706 const ModuleAnalysisManagerFunctionProxy &Arg)
708 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
709 : MAM(std::move(Arg.MAM)) {}
710 ModuleAnalysisManagerFunctionProxy &
711 operator=(ModuleAnalysisManagerFunctionProxy RHS) {
712 std::swap(MAM, RHS.MAM);
716 /// \brief Run the analysis pass and create our proxy result object.
717 /// Nothing to see here, it just forwards the \c MAM reference into the
719 Result run(Function &) { return Result(*MAM); }
724 const ModuleAnalysisManager *MAM;
727 /// \brief Trivial adaptor that maps from a module to its functions.
729 /// Designed to allow composition of a FunctionPass(Manager) and
730 /// a ModulePassManager. Note that if this pass is constructed with a pointer
731 /// to a \c ModuleAnalysisManager it will run the
732 /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
733 /// pass over the module to enable a \c FunctionAnalysisManager to be used
734 /// within this run safely.
736 /// Function passes run within this adaptor can rely on having exclusive access
737 /// to the function they are run over. They should not read or modify any other
738 /// functions! Other threads or systems may be manipulating other functions in
739 /// the module, and so their state should never be relied on.
740 /// FIXME: Make the above true for all of LLVM's actual passes, some still
741 /// violate this principle.
743 /// Function passes can also read the module containing the function, but they
744 /// should not modify that module outside of the use lists of various globals.
745 /// For example, a function pass is not permitted to add functions to the
747 /// FIXME: Make the above true for all of LLVM's actual passes, some still
748 /// violate this principle.
749 template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
751 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
752 : Pass(std::move(Pass)) {}
753 // We have to explicitly define all the special member functions because MSVC
754 // refuses to generate them.
755 ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
757 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
758 : Pass(std::move(Arg.Pass)) {}
759 friend void swap(ModuleToFunctionPassAdaptor &LHS,
760 ModuleToFunctionPassAdaptor &RHS) {
762 swap(LHS.Pass, RHS.Pass);
764 ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
769 /// \brief Runs the function pass across every function in the module.
770 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
771 FunctionAnalysisManager *FAM = nullptr;
773 // Setup the function analysis manager from its proxy.
774 FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
776 PreservedAnalyses PA = PreservedAnalyses::all();
777 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
778 PreservedAnalyses PassPA = Pass.run(*I, FAM);
780 // We know that the function pass couldn't have invalidated any other
781 // function's analyses (that's the contract of a function pass), so
782 // directly handle the function analysis manager's invalidation here and
783 // update our preserved set to reflect that these have already been
786 PassPA = FAM->invalidate(*I, std::move(PassPA));
788 // Then intersect the preserved set so that invalidation of module
789 // analyses will eventually occur when the module pass completes.
790 PA.intersect(std::move(PassPA));
793 // By definition we preserve the proxy. This precludes *any* invalidation
794 // of function analyses by the proxy, but that's OK because we've taken
795 // care to invalidate analyses in the function analysis manager
796 // incrementally above.
797 PA.preserve<FunctionAnalysisManagerModuleProxy>();
801 static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
807 /// \brief A function to deduce a function pass type and wrap it in the
808 /// templated adaptor.
809 template <typename FunctionPassT>
810 ModuleToFunctionPassAdaptor<FunctionPassT>
811 createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
812 return std::move(ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)));
815 /// \brief A template utility pass to force an analysis result to be available.
817 /// This is a no-op pass which simply forces a specific analysis pass's result
818 /// to be available when it is run.
819 template <typename AnalysisT> struct RequireAnalysisPass {
820 /// \brief Run this pass over some unit of IR.
822 /// This pass can be run over any unit of IR and use any analysis manager
823 /// provided they satisfy the basic API requirements. When this pass is
824 /// created, these methods can be instantiated to satisfy whatever the
825 /// context requires.
826 template <typename IRUnitT, typename AnalysisManagerT>
827 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT *AM) {
829 (void)AM->template getResult<AnalysisT>(Arg);
831 return PreservedAnalyses::all();
834 static StringRef name() { return "RequireAnalysisPass"; }
837 /// \brief A template utility pass to force an analysis result to be
840 /// This is a no-op pass which simply forces a specific analysis result to be
841 /// invalidated when it is run.
842 template <typename AnalysisT> struct InvalidateAnalysisPass {
843 /// \brief Run this pass over some unit of IR.
845 /// This pass can be run over any unit of IR and use any analysis manager
846 /// provided they satisfy the basic API requirements. When this pass is
847 /// created, these methods can be instantiated to satisfy whatever the
848 /// context requires.
849 template <typename IRUnitT, typename AnalysisManagerT>
850 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT *AM) {
852 // We have to directly invalidate the analysis result as we can't
853 // enumerate all other analyses and use the preserved set to control it.
854 (void)AM->template invalidate<AnalysisT>(Arg);
856 return PreservedAnalyses::all();
859 static StringRef name() { return "InvalidateAnalysisPass"; }
862 /// \brief A utility pass that does nothing but preserves no analyses.
864 /// As a consequence fo not preserving any analyses, this pass will force all
865 /// analysis passes to be re-run to produce fresh results if any are needed.
866 struct InvalidateAllAnalysesPass {
867 /// \brief Run this pass over some unit of IR.
868 template <typename IRUnitT> PreservedAnalyses run(IRUnitT &Arg) {
869 return PreservedAnalyses::none();
872 static StringRef name() { return "InvalidateAllAnalysesPass"; }