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 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/polymorphic_ptr.h"
41 #include "llvm/Support/type_traits.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Module.h"
52 /// \brief An abstract set of preserved analyses following a transformation pass
55 /// When a transformation pass is run, it can return a set of analyses whose
56 /// results were preserved by that transformation. The default set is "none",
57 /// and preserving analyses must be done explicitly.
59 /// There is also an explicit all state which can be used (for example) when
60 /// the IR is not mutated at all.
61 class PreservedAnalyses {
63 /// \brief Convenience factory function for the empty preserved set.
64 static PreservedAnalyses none() { return PreservedAnalyses(); }
66 /// \brief Construct a special preserved set that preserves all passes.
67 static PreservedAnalyses all() {
69 PA.PreservedPassIDs.insert((void *)AllPassesID);
73 PreservedAnalyses &operator=(PreservedAnalyses Arg) {
78 void swap(PreservedAnalyses &Arg) {
79 PreservedPassIDs.swap(Arg.PreservedPassIDs);
82 /// \brief Mark a particular pass as preserved, adding it to the set.
83 template <typename PassT> void preserve() {
84 if (!areAllPreserved())
85 PreservedPassIDs.insert(PassT::ID());
88 /// \brief Intersect this set with another in place.
90 /// This is a mutating operation on this preserved set, removing all
91 /// preserved passes which are not also preserved in the argument.
92 void intersect(const PreservedAnalyses &Arg) {
93 if (Arg.areAllPreserved())
95 if (areAllPreserved()) {
96 PreservedPassIDs = Arg.PreservedPassIDs;
99 for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
100 E = PreservedPassIDs.end();
102 if (!Arg.PreservedPassIDs.count(*I))
103 PreservedPassIDs.erase(*I);
106 #if LLVM_HAS_RVALUE_REFERENCES
107 /// \brief Intersect this set with a temporary other set in place.
109 /// This is a mutating operation on this preserved set, removing all
110 /// preserved passes which are not also preserved in the argument.
111 void intersect(PreservedAnalyses &&Arg) {
112 if (Arg.areAllPreserved())
114 if (areAllPreserved()) {
115 PreservedPassIDs = std::move(Arg.PreservedPassIDs);
118 for (SmallPtrSet<void *, 2>::const_iterator I = PreservedPassIDs.begin(),
119 E = PreservedPassIDs.end();
121 if (!Arg.PreservedPassIDs.count(*I))
122 PreservedPassIDs.erase(*I);
126 /// \brief Query whether a pass is marked as preserved by this set.
127 template <typename PassT> bool preserved() const {
128 return preserved(PassT::ID());
131 /// \brief Query whether an abstract pass ID is marked as preserved by this
133 bool preserved(void *PassID) const {
134 return PreservedPassIDs.count((void *)AllPassesID) ||
135 PreservedPassIDs.count(PassID);
139 // Note that this must not be -1 or -2 as those are already used by the
141 static const uintptr_t AllPassesID = (intptr_t)-3;
143 bool areAllPreserved() const { return PreservedPassIDs.count((void *)AllPassesID); }
145 SmallPtrSet<void *, 2> PreservedPassIDs;
148 inline void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
152 /// \brief Implementation details of the pass manager interfaces.
155 /// \brief Template for the abstract base class used to dispatch
156 /// polymorphically over pass objects.
157 template <typename T> struct PassConcept {
158 // Boiler plate necessary for the container of derived classes.
159 virtual ~PassConcept() {}
160 virtual PassConcept *clone() = 0;
162 /// \brief The polymorphic API which runs the pass over a given IR entity.
163 virtual PreservedAnalyses run(T Arg) = 0;
166 /// \brief A template wrapper used to implement the polymorphic API.
168 /// Can be instantiated for any object which provides a \c run method
169 /// accepting a \c T. It requires the pass to be a copyable
171 template <typename T, typename PassT> struct PassModel : PassConcept<T> {
172 PassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
173 virtual PassModel *clone() { return new PassModel(Pass); }
174 virtual PreservedAnalyses run(T Arg) { return Pass.run(Arg); }
178 /// \brief Abstract concept of an analysis result.
180 /// This concept is parameterized over the IR unit that this result pertains
182 template <typename IRUnitT> struct AnalysisResultConcept {
183 virtual ~AnalysisResultConcept() {}
184 virtual AnalysisResultConcept *clone() = 0;
186 /// \brief Method to try and mark a result as invalid.
188 /// When the outer \c AnalysisManager detects a change in some underlying
189 /// unit of the IR, it will call this method on all of the results cached.
191 /// \returns true if the result should indeed be invalidated (the default).
192 virtual bool invalidate(IRUnitT *IR) = 0;
195 /// \brief Wrapper to model the analysis result concept.
197 /// By default, this will implement the invalidate method with a trivial
198 /// implementation so that the actual analysis result doesn't need to provide
199 /// an invalidation handler. It is only selected when the invalidation handler
200 /// is not part of the ResultT's interface.
201 template <typename IRUnitT, typename ResultT, bool HasInvalidateHandler = false>
202 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
203 AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
204 virtual AnalysisResultModel *clone() {
205 return new AnalysisResultModel(Result);
208 /// \brief The model returns true to allow the invalidation.
210 // FIXME: We should actually use two different concepts for analysis results
211 // rather than two different models, and avoid the indirect function call for
212 // ones that use the trivial behavior.
213 virtual bool invalidate(IRUnitT *) { return true; }
218 /// \brief Wrapper to model the analysis result concept.
220 /// Can wrap any type which implements a suitable invalidate member and model
221 /// the AnalysisResultConcept for the AnalysisManager.
222 template <typename IRUnitT, typename ResultT>
223 struct AnalysisResultModel<IRUnitT, ResultT, true> : AnalysisResultConcept<IRUnitT> {
224 AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
225 virtual AnalysisResultModel *clone() {
226 return new AnalysisResultModel(Result);
229 /// \brief The model delegates to the \c ResultT method.
230 virtual bool invalidate(IRUnitT *IR) { return Result.invalidate(IR); }
235 /// \brief SFINAE metafunction for computing whether \c ResultT provides an
236 /// \c invalidate member function.
237 template <typename IRUnitT, typename ResultT> class ResultHasInvalidateMethod {
238 typedef char SmallType;
239 struct BigType { char a, b; };
240 template <typename T, bool (T::*)(IRUnitT *)> struct Checker;
241 template <typename T> static SmallType f(Checker<T, &T::invalidate> *);
242 template <typename T> static BigType f(...);
245 enum { Value = sizeof(f<ResultT>(0)) == sizeof(SmallType) };
248 /// \brief Abstract concept of an analysis pass.
250 /// This concept is parameterized over the IR unit that it can run over and
251 /// produce an analysis result.
252 template <typename IRUnitT> struct AnalysisPassConcept {
253 virtual ~AnalysisPassConcept() {}
254 virtual AnalysisPassConcept *clone() = 0;
256 /// \brief Method to run this analysis over a unit of IR.
257 /// \returns The analysis result object to be queried by users, the caller
259 virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
262 /// \brief Wrapper to model the analysis pass concept.
264 /// Can wrap any type which implements a suitable \c run method. The method
265 /// must accept the IRUnitT as an argument and produce an object which can be
266 /// wrapped in a \c AnalysisResultModel.
267 template <typename PassT>
268 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
269 AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
270 virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
272 // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
273 typedef typename PassT::IRUnitT IRUnitT;
275 // FIXME: Replace PassT::Result with type traits when we use C++11.
276 typedef AnalysisResultModel<
277 IRUnitT, typename PassT::Result,
278 ResultHasInvalidateMethod<IRUnitT, typename PassT::Result>::Value>
281 /// \brief The model delegates to the \c PassT::run method.
283 /// The return is wrapped in an \c AnalysisResultModel.
284 virtual ResultModelT *run(IRUnitT *IR) {
285 return new ResultModelT(Pass.run(IR));
293 class ModuleAnalysisManager;
295 class ModulePassManager {
297 explicit ModulePassManager(ModuleAnalysisManager *AM = 0) : AM(AM) {}
299 /// \brief Run all of the module passes in this module pass manager over
302 /// This method should only be called for a single module as there is the
303 /// expectation that the lifetime of a pass is bounded to that of a module.
304 PreservedAnalyses run(Module *M);
306 template <typename ModulePassT> void addPass(ModulePassT Pass) {
307 Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
311 // Pull in the concept type and model template specialized for modules.
312 typedef detail::PassConcept<Module *> ModulePassConcept;
313 template <typename PassT>
314 struct ModulePassModel : detail::PassModel<Module *, PassT> {
315 ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
318 ModuleAnalysisManager *AM;
319 std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
322 class FunctionAnalysisManager;
324 class FunctionPassManager {
326 explicit FunctionPassManager(FunctionAnalysisManager *AM = 0) : AM(AM) {}
328 template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
329 Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
332 PreservedAnalyses run(Function *F);
335 // Pull in the concept type and model template specialized for functions.
336 typedef detail::PassConcept<Function *> FunctionPassConcept;
337 template <typename PassT>
338 struct FunctionPassModel : detail::PassModel<Function *, PassT> {
339 FunctionPassModel(PassT Pass)
340 : detail::PassModel<Function *, PassT>(Pass) {}
343 FunctionAnalysisManager *AM;
344 std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
347 /// \brief A module analysis pass manager with lazy running and caching of
349 class ModuleAnalysisManager {
351 ModuleAnalysisManager() {}
353 /// \brief Get the result of an analysis pass for this module.
355 /// If there is not a valid cached result in the manager already, this will
356 /// re-run the analysis to produce a valid result.
357 template <typename PassT> const typename PassT::Result &getResult(Module *M) {
358 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
359 "The analysis pass must be over a Module.");
360 assert(ModuleAnalysisPasses.count(PassT::ID()) &&
361 "This analysis pass was not registered prior to being queried");
363 const detail::AnalysisResultConcept<Module> &ResultConcept =
364 getResultImpl(PassT::ID(), M);
365 typedef detail::AnalysisResultModel<
366 Module, typename PassT::Result,
367 detail::ResultHasInvalidateMethod<
368 Module, typename PassT::Result>::Value> ResultModelT;
369 return static_cast<const ResultModelT &>(ResultConcept).Result;
372 /// \brief Register an analysis pass with the manager.
374 /// This provides an initialized and set-up analysis pass to the
376 /// manager. Whomever is setting up analysis passes must use this to
378 /// the manager with all of the analysis passes available.
379 template <typename PassT> void registerPass(PassT Pass) {
380 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
381 "The analysis pass must be over a Module.");
382 assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
383 "Registered the same analysis pass twice!");
384 ModuleAnalysisPasses[PassT::ID()] =
385 new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
388 /// \brief Invalidate a specific analysis pass for an IR module.
390 /// Note that the analysis result can disregard invalidation.
391 template <typename PassT> void invalidate(Module *M) {
392 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
393 "The analysis pass must be over a Module.");
394 assert(ModuleAnalysisPasses.count(PassT::ID()) &&
395 "This analysis pass was not registered prior to being invalidated");
396 invalidateImpl(PassT::ID(), M);
399 /// \brief Invalidate analyses cached for an IR Module.
401 /// Walk through all of the analyses pertaining to this module and invalidate
402 /// them unless they are preserved by the PreservedAnalyses set.
403 void invalidate(Module *M, const PreservedAnalyses &PA);
406 /// \brief Get a module pass result, running the pass if necessary.
407 const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
410 /// \brief Invalidate a module pass result.
411 void invalidateImpl(void *PassID, Module *M);
413 /// \brief Map type from module analysis pass ID to pass concept pointer.
414 typedef DenseMap<void *,
415 polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
416 ModuleAnalysisPassMapT;
418 /// \brief Collection of module analysis passes, indexed by ID.
419 ModuleAnalysisPassMapT ModuleAnalysisPasses;
421 /// \brief Map type from module analysis pass ID to pass result concept pointer.
422 typedef DenseMap<void *,
423 polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
424 ModuleAnalysisResultMapT;
426 /// \brief Cache of computed module analysis results for this module.
427 ModuleAnalysisResultMapT ModuleAnalysisResults;
430 /// \brief A function analysis manager to coordinate and cache analyses run over
432 class FunctionAnalysisManager {
434 FunctionAnalysisManager() {}
436 /// \brief Get the result of an analysis pass for a function.
438 /// If there is not a valid cached result in the manager already, this will
439 /// re-run the analysis to produce a valid result.
440 template <typename PassT>
441 const typename PassT::Result &getResult(Function *F) {
442 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
443 "The analysis pass must be over a Function.");
444 assert(FunctionAnalysisPasses.count(PassT::ID()) &&
445 "This analysis pass was not registered prior to being queried");
447 const detail::AnalysisResultConcept<Function> &ResultConcept =
448 getResultImpl(PassT::ID(), F);
449 typedef detail::AnalysisResultModel<
450 Function, typename PassT::Result,
451 detail::ResultHasInvalidateMethod<
452 Function, typename PassT::Result>::Value> ResultModelT;
453 return static_cast<const ResultModelT &>(ResultConcept).Result;
456 /// \brief Register an analysis pass with the manager.
458 /// This provides an initialized and set-up analysis pass to the
460 /// manager. Whomever is setting up analysis passes must use this to
462 /// the manager with all of the analysis passes available.
463 template <typename PassT> void registerPass(PassT Pass) {
464 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
465 "The analysis pass must be over a Function.");
466 assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
467 "Registered the same analysis pass twice!");
468 FunctionAnalysisPasses[PassT::ID()] =
469 new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
472 /// \brief Invalidate a specific analysis pass for an IR module.
474 /// Note that the analysis result can disregard invalidation.
475 template <typename PassT> void invalidate(Function *F) {
476 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
477 "The analysis pass must be over a Function.");
478 assert(FunctionAnalysisPasses.count(PassT::ID()) &&
479 "This analysis pass was not registered prior to being invalidated");
480 invalidateImpl(PassT::ID(), F);
483 /// \brief Invalidate analyses cached for an IR Function.
485 /// Walk through all of the analyses cache for this IR function and
486 /// invalidate them unless they are preserved by the provided
487 /// PreservedAnalyses set.
488 void invalidate(Function *F, const PreservedAnalyses &PA);
490 /// \brief Returns true if the analysis manager has an empty results cache.
493 /// \brief Clear the function analysis result cache.
495 /// This routine allows cleaning up when the set of functions itself has
496 /// potentially changed, and thus we can't even look up a a result and
497 /// invalidate it directly. Notably, this does *not* call invalidate
498 /// functions as there is nothing to be done for them.
502 /// \brief Get a function pass result, running the pass if necessary.
503 const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
506 /// \brief Invalidate a function pass result.
507 void invalidateImpl(void *PassID, Function *F);
509 /// \brief Map type from function analysis pass ID to pass concept pointer.
510 typedef DenseMap<void *,
511 polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
512 FunctionAnalysisPassMapT;
514 /// \brief Collection of function analysis passes, indexed by ID.
515 FunctionAnalysisPassMapT FunctionAnalysisPasses;
517 /// \brief List of function analysis pass IDs and associated concept pointers.
519 /// Requires iterators to be valid across appending new entries and arbitrary
520 /// erases. Provides both the pass ID and concept pointer such that it is
521 /// half of a bijection and provides storage for the actual result concept.
522 typedef std::list<std::pair<
523 void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
524 FunctionAnalysisResultListT;
526 /// \brief Map type from function pointer to our custom list type.
527 typedef DenseMap<Function *, FunctionAnalysisResultListT>
528 FunctionAnalysisResultListMapT;
530 /// \brief Map from function to a list of function analysis results.
532 /// Provides linear time removal of all analysis results for a function and
533 /// the ultimate storage for a particular cached analysis result.
534 FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
536 /// \brief Map type from a pair of analysis ID and function pointer to an
537 /// iterator into a particular result list.
538 typedef DenseMap<std::pair<void *, Function *>,
539 FunctionAnalysisResultListT::iterator>
540 FunctionAnalysisResultMapT;
542 /// \brief Map from an analysis ID and function to a particular cached
544 FunctionAnalysisResultMapT FunctionAnalysisResults;
547 /// \brief A module analysis which acts as a proxy for a function analysis
550 /// This primarily proxies invalidation information from the module analysis
551 /// manager and module pass manager to a function analysis manager. You should
552 /// never use a function analysis manager from within (transitively) a module
553 /// pass manager unless your parent module pass has received a proxy result
556 /// FIXME: It might be really nice to "enforce" this (softly) by making this
557 /// proxy the API path to access a function analysis manager within a module
559 class FunctionAnalysisModuleProxy {
561 typedef Module IRUnitT;
564 static void *ID() { return (void *)&PassID; }
566 FunctionAnalysisModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
568 /// \brief Run the analysis pass and create our proxy result object.
570 /// This doesn't do any interesting work, it is primarily used to insert our
571 /// proxy result object into the module analysis cache so that we can proxy
572 /// invalidation to the function analysis manager.
574 /// In debug builds, it will also assert that the analysis manager is empty
575 /// as no queries should arrive at the function analysis manager prior to
576 /// this analysis being requested.
577 Result run(Module *M);
582 FunctionAnalysisManager &FAM;
585 /// \brief The result proxy object for the \c FunctionAnalysisModuleProxy.
587 /// See its documentation for more information.
588 class FunctionAnalysisModuleProxy::Result {
590 Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
593 /// \brief Handler for invalidation of the module.
594 bool invalidate(Module *M);
597 FunctionAnalysisManager &FAM;
600 /// \brief Trivial adaptor that maps from a module to its functions.
602 /// Designed to allow composition of a FunctionPass(Manager) and a
603 /// ModulePassManager. Note that if this pass is constructed with a pointer to
604 /// a \c ModuleAnalysisManager it will run the \c FunctionAnalysisModuleProxy
605 /// analysis prior to running the function pass over the module to enable a \c
606 /// FunctionAnalysisManager to be used within this run safely.
607 template <typename FunctionPassT>
608 class ModuleToFunctionPassAdaptor {
610 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass,
611 ModuleAnalysisManager *MAM = 0)
612 : Pass(llvm_move(Pass)), MAM(MAM) {}
614 /// \brief Runs the function pass across every function in the module.
615 PreservedAnalyses run(Module *M) {
617 // Pull in the analysis proxy so that the function analysis manager is
618 // appropriately set up.
619 (void)MAM->getResult<FunctionAnalysisModuleProxy>(M);
621 PreservedAnalyses PA = PreservedAnalyses::all();
622 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
623 PreservedAnalyses PassPA = Pass.run(I);
624 PA.intersect(llvm_move(PassPA));
631 ModuleAnalysisManager *MAM;
634 /// \brief A function to deduce a function pass type and wrap it in the
635 /// templated adaptor.
637 /// \param MAM is an optional \c ModuleAnalysisManager which (if provided) will
638 /// be queried for a \c FunctionAnalysisModuleProxy to enable the function
639 /// pass(es) to safely interact with a \c FunctionAnalysisManager.
640 template <typename FunctionPassT>
641 ModuleToFunctionPassAdaptor<FunctionPassT>
642 createModuleToFunctionPassAdaptor(FunctionPassT Pass,
643 ModuleAnalysisManager *MAM = 0) {
644 return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass), MAM);