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 /// Can wrap any type which implements a suitable invalidate member and model
198 /// the AnalysisResultConcept for the AnalysisManager.
199 template <typename IRUnitT, typename ResultT>
200 struct AnalysisResultModel : AnalysisResultConcept<IRUnitT> {
201 AnalysisResultModel(ResultT Result) : Result(llvm_move(Result)) {}
202 virtual AnalysisResultModel *clone() {
203 return new AnalysisResultModel(Result);
206 /// \brief The model delegates to the \c ResultT method.
207 virtual bool invalidate(IRUnitT *IR) { return Result.invalidate(IR); }
212 /// \brief Abstract concept of an analysis pass.
214 /// This concept is parameterized over the IR unit that it can run over and
215 /// produce an analysis result.
216 template <typename IRUnitT> struct AnalysisPassConcept {
217 virtual ~AnalysisPassConcept() {}
218 virtual AnalysisPassConcept *clone() = 0;
220 /// \brief Method to run this analysis over a unit of IR.
221 /// \returns The analysis result object to be queried by users, the caller
223 virtual AnalysisResultConcept<IRUnitT> *run(IRUnitT *IR) = 0;
226 /// \brief Wrapper to model the analysis pass concept.
228 /// Can wrap any type which implements a suitable \c run method. The method
229 /// must accept the IRUnitT as an argument and produce an object which can be
230 /// wrapped in a \c AnalysisResultModel.
231 template <typename PassT>
232 struct AnalysisPassModel : AnalysisPassConcept<typename PassT::IRUnitT> {
233 AnalysisPassModel(PassT Pass) : Pass(llvm_move(Pass)) {}
234 virtual AnalysisPassModel *clone() { return new AnalysisPassModel(Pass); }
236 // FIXME: Replace PassT::IRUnitT with type traits when we use C++11.
237 typedef typename PassT::IRUnitT IRUnitT;
239 // FIXME: Replace PassT::Result with type traits when we use C++11.
240 typedef AnalysisResultModel<IRUnitT, typename PassT::Result> ResultModelT;
242 /// \brief The model delegates to the \c PassT::run method.
244 /// The return is wrapped in an \c AnalysisResultModel.
245 virtual ResultModelT *run(IRUnitT *IR) {
246 return new ResultModelT(Pass.run(IR));
254 class ModuleAnalysisManager;
256 class ModulePassManager {
258 explicit ModulePassManager(ModuleAnalysisManager *AM = 0) : AM(AM) {}
260 /// \brief Run all of the module passes in this module pass manager over
263 /// This method should only be called for a single module as there is the
264 /// expectation that the lifetime of a pass is bounded to that of a module.
265 PreservedAnalyses run(Module *M);
267 template <typename ModulePassT> void addPass(ModulePassT Pass) {
268 Passes.push_back(new ModulePassModel<ModulePassT>(llvm_move(Pass)));
272 // Pull in the concept type and model template specialized for modules.
273 typedef detail::PassConcept<Module *> ModulePassConcept;
274 template <typename PassT>
275 struct ModulePassModel : detail::PassModel<Module *, PassT> {
276 ModulePassModel(PassT Pass) : detail::PassModel<Module *, PassT>(Pass) {}
279 ModuleAnalysisManager *AM;
280 std::vector<polymorphic_ptr<ModulePassConcept> > Passes;
283 class FunctionAnalysisManager;
285 class FunctionPassManager {
287 explicit FunctionPassManager(FunctionAnalysisManager *AM = 0) : AM(AM) {}
289 template <typename FunctionPassT> void addPass(FunctionPassT Pass) {
290 Passes.push_back(new FunctionPassModel<FunctionPassT>(llvm_move(Pass)));
293 PreservedAnalyses run(Function *F);
296 // Pull in the concept type and model template specialized for functions.
297 typedef detail::PassConcept<Function *> FunctionPassConcept;
298 template <typename PassT>
299 struct FunctionPassModel : detail::PassModel<Function *, PassT> {
300 FunctionPassModel(PassT Pass)
301 : detail::PassModel<Function *, PassT>(Pass) {}
304 FunctionAnalysisManager *AM;
305 std::vector<polymorphic_ptr<FunctionPassConcept> > Passes;
308 /// \brief A module analysis pass manager with lazy running and caching of
310 class ModuleAnalysisManager {
312 ModuleAnalysisManager() {}
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> const typename PassT::Result &getResult(Module *M) {
319 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
320 "The analysis pass must be over a Module.");
321 assert(ModuleAnalysisPasses.count(PassT::ID()) &&
322 "This analysis pass was not registered prior to being queried");
324 const detail::AnalysisResultConcept<Module> &ResultConcept =
325 getResultImpl(PassT::ID(), M);
326 typedef detail::AnalysisResultModel<Module, typename PassT::Result>
328 return static_cast<const ResultModelT &>(ResultConcept).Result;
331 /// \brief Register an analysis pass with the manager.
333 /// This provides an initialized and set-up analysis pass to the
335 /// manager. Whomever is setting up analysis passes must use this to
337 /// the manager with all of the analysis passes available.
338 template <typename PassT> void registerPass(PassT Pass) {
339 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
340 "The analysis pass must be over a Module.");
341 assert(!ModuleAnalysisPasses.count(PassT::ID()) &&
342 "Registered the same analysis pass twice!");
343 ModuleAnalysisPasses[PassT::ID()] =
344 new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
347 /// \brief Invalidate a specific analysis pass for an IR module.
349 /// Note that the analysis result can disregard invalidation.
350 template <typename PassT> void invalidate(Module *M) {
351 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Module>::value),
352 "The analysis pass must be over a Module.");
353 assert(ModuleAnalysisPasses.count(PassT::ID()) &&
354 "This analysis pass was not registered prior to being invalidated");
355 invalidateImpl(PassT::ID(), M);
358 /// \brief Invalidate analyses cached for an IR Module.
360 /// Walk through all of the analyses pertaining to this module and invalidate
361 /// them unless they are preserved by the PreservedAnalyses set.
362 void invalidate(Module *M, const PreservedAnalyses &PA);
365 /// \brief Get a module pass result, running the pass if necessary.
366 const detail::AnalysisResultConcept<Module> &getResultImpl(void *PassID,
369 /// \brief Invalidate a module pass result.
370 void invalidateImpl(void *PassID, Module *M);
372 /// \brief Map type from module analysis pass ID to pass concept pointer.
373 typedef DenseMap<void *,
374 polymorphic_ptr<detail::AnalysisPassConcept<Module> > >
375 ModuleAnalysisPassMapT;
377 /// \brief Collection of module analysis passes, indexed by ID.
378 ModuleAnalysisPassMapT ModuleAnalysisPasses;
380 /// \brief Map type from module analysis pass ID to pass result concept pointer.
381 typedef DenseMap<void *,
382 polymorphic_ptr<detail::AnalysisResultConcept<Module> > >
383 ModuleAnalysisResultMapT;
385 /// \brief Cache of computed module analysis results for this module.
386 ModuleAnalysisResultMapT ModuleAnalysisResults;
389 /// \brief A function analysis manager to coordinate and cache analyses run over
391 class FunctionAnalysisManager {
393 FunctionAnalysisManager() {}
395 /// \brief Get the result of an analysis pass for a function.
397 /// If there is not a valid cached result in the manager already, this will
398 /// re-run the analysis to produce a valid result.
399 template <typename PassT>
400 const typename PassT::Result &getResult(Function *F) {
401 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
402 "The analysis pass must be over a Function.");
403 assert(FunctionAnalysisPasses.count(PassT::ID()) &&
404 "This analysis pass was not registered prior to being queried");
406 const detail::AnalysisResultConcept<Function> &ResultConcept =
407 getResultImpl(PassT::ID(), F);
408 typedef detail::AnalysisResultModel<Function, typename PassT::Result>
410 return static_cast<const ResultModelT &>(ResultConcept).Result;
413 /// \brief Register an analysis pass with the manager.
415 /// This provides an initialized and set-up analysis pass to the
417 /// manager. Whomever is setting up analysis passes must use this to
419 /// the manager with all of the analysis passes available.
420 template <typename PassT> void registerPass(PassT Pass) {
421 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
422 "The analysis pass must be over a Function.");
423 assert(!FunctionAnalysisPasses.count(PassT::ID()) &&
424 "Registered the same analysis pass twice!");
425 FunctionAnalysisPasses[PassT::ID()] =
426 new detail::AnalysisPassModel<PassT>(llvm_move(Pass));
429 /// \brief Invalidate a specific analysis pass for an IR module.
431 /// Note that the analysis result can disregard invalidation.
432 template <typename PassT> void invalidate(Function *F) {
433 LLVM_STATIC_ASSERT((is_same<typename PassT::IRUnitT, Function>::value),
434 "The analysis pass must be over a Function.");
435 assert(FunctionAnalysisPasses.count(PassT::ID()) &&
436 "This analysis pass was not registered prior to being invalidated");
437 invalidateImpl(PassT::ID(), F);
440 /// \brief Invalidate analyses cached for an IR Function.
442 /// Walk through all of the analyses cache for this IR function and
443 /// invalidate them unless they are preserved by the provided
444 /// PreservedAnalyses set.
445 void invalidate(Function *F, const PreservedAnalyses &PA);
447 /// \brief Returns true if the analysis manager has an empty results cache.
450 /// \brief Clear the function analysis result cache.
452 /// This routine allows cleaning up when the set of functions itself has
453 /// potentially changed, and thus we can't even look up a a result and
454 /// invalidate it directly. Notably, this does *not* call invalidate
455 /// functions as there is nothing to be done for them.
459 /// \brief Get a function pass result, running the pass if necessary.
460 const detail::AnalysisResultConcept<Function> &getResultImpl(void *PassID,
463 /// \brief Invalidate a function pass result.
464 void invalidateImpl(void *PassID, Function *F);
466 /// \brief Map type from function analysis pass ID to pass concept pointer.
467 typedef DenseMap<void *,
468 polymorphic_ptr<detail::AnalysisPassConcept<Function> > >
469 FunctionAnalysisPassMapT;
471 /// \brief Collection of function analysis passes, indexed by ID.
472 FunctionAnalysisPassMapT FunctionAnalysisPasses;
474 /// \brief List of function analysis pass IDs and associated concept pointers.
476 /// Requires iterators to be valid across appending new entries and arbitrary
477 /// erases. Provides both the pass ID and concept pointer such that it is
478 /// half of a bijection and provides storage for the actual result concept.
479 typedef std::list<std::pair<
480 void *, polymorphic_ptr<detail::AnalysisResultConcept<Function> > > >
481 FunctionAnalysisResultListT;
483 /// \brief Map type from function pointer to our custom list type.
484 typedef DenseMap<Function *, FunctionAnalysisResultListT>
485 FunctionAnalysisResultListMapT;
487 /// \brief Map from function to a list of function analysis results.
489 /// Provides linear time removal of all analysis results for a function and
490 /// the ultimate storage for a particular cached analysis result.
491 FunctionAnalysisResultListMapT FunctionAnalysisResultLists;
493 /// \brief Map type from a pair of analysis ID and function pointer to an
494 /// iterator into a particular result list.
495 typedef DenseMap<std::pair<void *, Function *>,
496 FunctionAnalysisResultListT::iterator>
497 FunctionAnalysisResultMapT;
499 /// \brief Map from an analysis ID and function to a particular cached
501 FunctionAnalysisResultMapT FunctionAnalysisResults;
504 /// \brief A module analysis which acts as a proxy for a function analysis
507 /// This primarily proxies invalidation information from the module analysis
508 /// manager and module pass manager to a function analysis manager. You should
509 /// never use a function analysis manager from within (transitively) a module
510 /// pass manager unless your parent module pass has received a proxy result
513 /// FIXME: It might be really nice to "enforce" this (softly) by making this
514 /// proxy the API path to access a function analysis manager within a module
516 class FunctionAnalysisModuleProxy {
518 typedef Module IRUnitT;
521 static void *ID() { return (void *)&PassID; }
523 FunctionAnalysisModuleProxy(FunctionAnalysisManager &FAM) : FAM(FAM) {}
525 /// \brief Run the analysis pass and create our proxy result object.
527 /// This doesn't do any interesting work, it is primarily used to insert our
528 /// proxy result object into the module analysis cache so that we can proxy
529 /// invalidation to the function analysis manager.
531 /// In debug builds, it will also assert that the analysis manager is empty
532 /// as no queries should arrive at the function analysis manager prior to
533 /// this analysis being requested.
534 Result run(Module *M);
539 FunctionAnalysisManager &FAM;
542 /// \brief The result proxy object for the \c FunctionAnalysisModuleProxy.
544 /// See its documentation for more information.
545 class FunctionAnalysisModuleProxy::Result {
547 Result(FunctionAnalysisManager &FAM) : FAM(FAM) {}
550 /// \brief Handler for invalidation of the module.
551 bool invalidate(Module *M);
554 FunctionAnalysisManager &FAM;
557 /// \brief Trivial adaptor that maps from a module to its functions.
559 /// Designed to allow composition of a FunctionPass(Manager) and a
560 /// ModulePassManager. Note that if this pass is constructed with a pointer to
561 /// a \c ModuleAnalysisManager it will run the \c FunctionAnalysisModuleProxy
562 /// analysis prior to running the function pass over the module to enable a \c
563 /// FunctionAnalysisManager to be used within this run safely.
564 template <typename FunctionPassT>
565 class ModuleToFunctionPassAdaptor {
567 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass,
568 ModuleAnalysisManager *MAM = 0)
569 : Pass(llvm_move(Pass)), MAM(MAM) {}
571 /// \brief Runs the function pass across every function in the module.
572 PreservedAnalyses run(Module *M) {
574 // Pull in the analysis proxy so that the function analysis manager is
575 // appropriately set up.
576 (void)MAM->getResult<FunctionAnalysisModuleProxy>(M);
578 PreservedAnalyses PA = PreservedAnalyses::all();
579 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
580 PreservedAnalyses PassPA = Pass.run(I);
581 PA.intersect(llvm_move(PassPA));
588 ModuleAnalysisManager *MAM;
591 /// \brief A function to deduce a function pass type and wrap it in the
592 /// templated adaptor.
594 /// \param MAM is an optional \c ModuleAnalysisManager which (if provided) will
595 /// be queried for a \c FunctionAnalysisModuleProxy to enable the function
596 /// pass(es) to safely interact with a \c FunctionAnalysisManager.
597 template <typename FunctionPassT>
598 ModuleToFunctionPassAdaptor<FunctionPassT>
599 createModuleToFunctionPassAdaptor(FunctionPassT Pass,
600 ModuleAnalysisManager *MAM = 0) {
601 return ModuleToFunctionPassAdaptor<FunctionPassT>(llvm_move(Pass), MAM);