]> git.proxmox.com Git - rustc.git/blob - src/llvm/include/llvm/IR/PassManager.h
Imported Upstream version 1.0.0+dfsg1
[rustc.git] / src / llvm / include / llvm / IR / PassManager.h
1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
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.
20 ///
21 /// The core IR library provides managers for running passes over
22 /// modules and functions.
23 ///
24 /// * FunctionPassManager can run over a Module, runs each pass over
25 /// a Function.
26 /// * ModulePassManager must be directly run, runs each pass over the Module.
27 ///
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
35 ///
36 //===----------------------------------------------------------------------===//
37
38 #ifndef LLVM_IR_PASSMANAGER_H
39 #define LLVM_IR_PASSMANAGER_H
40
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"
50 #include <list>
51 #include <memory>
52 #include <vector>
53
54 namespace llvm {
55
56 class Module;
57 class Function;
58
59 /// \brief An abstract set of preserved analyses following a transformation pass
60 /// run.
61 ///
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.
65 ///
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 {
69 public:
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) {
78 using std::swap;
79 swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
80 }
81 PreservedAnalyses &operator=(PreservedAnalyses RHS) {
82 swap(*this, RHS);
83 return *this;
84 }
85
86 /// \brief Convenience factory function for the empty preserved set.
87 static PreservedAnalyses none() { return PreservedAnalyses(); }
88
89 /// \brief Construct a special preserved set that preserves all passes.
90 static PreservedAnalyses all() {
91 PreservedAnalyses PA;
92 PA.PreservedPassIDs.insert((void *)AllPassesID);
93 return PA;
94 }
95
96 /// \brief Mark a particular pass as preserved, adding it to the set.
97 template <typename PassT> void preserve() { preserve(PassT::ID()); }
98
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);
103 }
104
105 /// \brief Intersect this set with another in place.
106 ///
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())
111 return;
112 if (areAllPreserved()) {
113 PreservedPassIDs = Arg.PreservedPassIDs;
114 return;
115 }
116 for (void *P : PreservedPassIDs)
117 if (!Arg.PreservedPassIDs.count(P))
118 PreservedPassIDs.erase(P);
119 }
120
121 /// \brief Intersect this set with a temporary other set in place.
122 ///
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())
127 return;
128 if (areAllPreserved()) {
129 PreservedPassIDs = std::move(Arg.PreservedPassIDs);
130 return;
131 }
132 for (void *P : PreservedPassIDs)
133 if (!Arg.PreservedPassIDs.count(P))
134 PreservedPassIDs.erase(P);
135 }
136
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());
140 }
141
142 /// \brief Query whether an abstract pass ID is marked as preserved by this
143 /// set.
144 bool preserved(void *PassID) const {
145 return PreservedPassIDs.count((void *)AllPassesID) ||
146 PreservedPassIDs.count(PassID);
147 }
148
149 /// \brief Test whether all passes are preserved.
150 ///
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);
155 }
156
157 private:
158 // Note that this must not be -1 or -2 as those are already used by the
159 // SmallPtrSet.
160 static const uintptr_t AllPassesID = (intptr_t)(-3);
161
162 SmallPtrSet<void *, 2> PreservedPassIDs;
163 };
164
165 // Forward declare the analysis manager template.
166 template <typename IRUnitT> class AnalysisManager;
167
168 /// \brief Manages a sequence of passes over units of IR.
169 ///
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.
174 ///
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
178 /// runs.
179 template <typename IRUnitT> class PassManager {
180 public:
181 /// \brief Construct a pass manager.
182 ///
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);
193 return *this;
194 }
195
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();
199
200 if (DebugLogging)
201 dbgs() << "Starting pass manager run.\n";
202
203 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
204 if (DebugLogging)
205 dbgs() << "Running pass: " << Passes[Idx]->name() << "\n";
206
207 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM);
208
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.
214 if (AM)
215 PassPA = AM->invalidate(IR, std::move(PassPA));
216
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));
220
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();
226 }
227
228 if (DebugLogging)
229 dbgs() << "Finished pass manager run.\n";
230
231 return PA;
232 }
233
234 template <typename PassT> void addPass(PassT Pass) {
235 typedef detail::PassModel<IRUnitT, PassT> PassModelT;
236 Passes.emplace_back(new PassModelT(std::move(Pass)));
237 }
238
239 static StringRef name() { return "PassManager"; }
240
241 private:
242 typedef detail::PassConcept<IRUnitT> PassConceptT;
243
244 PassManager(const PassManager &) LLVM_DELETED_FUNCTION;
245 PassManager &operator=(const PassManager &) LLVM_DELETED_FUNCTION;
246
247 std::vector<std::unique_ptr<PassConceptT>> Passes;
248
249 /// \brief Flag indicating whether we should do debug logging.
250 bool DebugLogging;
251 };
252
253 /// \brief Convenience typedef for a pass manager over modules.
254 typedef PassManager<Module> ModulePassManager;
255
256 /// \brief Convenience typedef for a pass manager over functions.
257 typedef PassManager<Function> FunctionPassManager;
258
259 namespace detail {
260
261 /// \brief A CRTP base used to implement analysis managers.
262 ///
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:
266 ///
267 /// - getResultImpl
268 /// - getCachedResultImpl
269 /// - invalidateImpl
270 ///
271 /// The details of the call pattern are within.
272 ///
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);
282 }
283
284 AnalysisManagerBase(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
285 AnalysisManagerBase &
286 operator=(const AnalysisManagerBase &) LLVM_DELETED_FUNCTION;
287
288 protected:
289 typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
290 typedef detail::AnalysisPassConcept<IRUnitT> PassConceptT;
291
292 // FIXME: Provide template aliases for the models when we're using C++11 in
293 // a mode supporting them.
294
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);
302 return *this;
303 }
304
305 public:
306 /// \brief Get the result of an analysis pass for this module.
307 ///
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");
313
314 ResultConceptT &ResultConcept =
315 derived_this()->getResultImpl(PassT::ID(), IR);
316 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
317 ResultModelT;
318 return static_cast<ResultModelT &>(ResultConcept).Result;
319 }
320
321 /// \brief Get the cached result of an analysis pass for this module.
322 ///
323 /// This method never runs the analysis.
324 ///
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");
330
331 ResultConceptT *ResultConcept =
332 derived_this()->getCachedResultImpl(PassT::ID(), IR);
333 if (!ResultConcept)
334 return nullptr;
335
336 typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
337 ResultModelT;
338 return &static_cast<ResultModelT *>(ResultConcept)->Result;
339 }
340
341 /// \brief Register an analysis pass with the manager.
342 ///
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)));
351 }
352
353 /// \brief Invalidate a specific analysis pass for an IR module.
354 ///
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);
360 }
361
362 /// \brief Invalidate analyses cached for an IR unit.
363 ///
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));
371 }
372
373 protected:
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!");
379 return *PI->second;
380 }
381
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!");
387 return *PI->second;
388 }
389
390 private:
391 /// \brief Map type from module analysis pass ID to pass concept pointer.
392 typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
393
394 /// \brief Collection of module analysis passes, indexed by ID.
395 AnalysisPassMapT AnalysisPasses;
396 };
397
398 } // End namespace detail
399
400 /// \brief A generic analysis pass manager with lazy running and caching of
401 /// results.
402 ///
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;
413
414 public:
415 // Most public APIs are inherited from the CRTP base class.
416
417 /// \brief Construct an empty analysis manager.
418 ///
419 /// A flag can be passed to indicate that the manager should perform debug
420 /// logging.
421 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
422
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);
433 return *this;
434 }
435
436 /// \brief Returns true if the analysis manager has an empty results cache.
437 bool empty() const {
438 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
439 "The storage and index of analysis results disagree on how many "
440 "there are!");
441 return AnalysisResults.empty();
442 }
443
444 /// \brief Clear the analysis result cache.
445 ///
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.
450 void clear() {
451 AnalysisResults.clear();
452 AnalysisResultLists.clear();
453 }
454
455 private:
456 AnalysisManager(const AnalysisManager &) LLVM_DELETED_FUNCTION;
457 AnalysisManager &operator=(const AnalysisManager &) LLVM_DELETED_FUNCTION;
458
459 /// \brief Get an analysis result, running the pass if necessary.
460 ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
461 typename AnalysisResultMapT::iterator RI;
462 bool Inserted;
463 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
464 std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
465
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.
468 if (Inserted) {
469 auto &P = this->lookupPass(PassID);
470 if (DebugLogging)
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());
475 }
476
477 return *RI->second->second;
478 }
479
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;
485 }
486
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())
492 return;
493
494 if (DebugLogging)
495 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
496 << "\n";
497 AnalysisResultLists[&IR].erase(RI->second);
498 AnalysisResults.erase(RI);
499 }
500
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);
506
507 if (DebugLogging)
508 dbgs() << "Invalidating all non-preserved analyses for: "
509 << IR.getName() << "\n";
510
511 // Clear all the invalidated results associated specifically with this
512 // function.
513 SmallVector<void *, 8> InvalidatedPassIDs;
514 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
515 for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
516 E = ResultsList.end();
517 I != E;) {
518 void *PassID = I->first;
519
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)) {
524 if (DebugLogging)
525 dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
526 << "\n";
527
528 InvalidatedPassIDs.push_back(I->first);
529 I = ResultsList.erase(I);
530 } else {
531 ++I;
532 }
533
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.
537 PA.preserve(PassID);
538 }
539 while (!InvalidatedPassIDs.empty())
540 AnalysisResults.erase(
541 std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
542 if (ResultsList.empty())
543 AnalysisResultLists.erase(&IR);
544
545 return std::move(PA);
546 }
547
548 /// \brief List of function analysis pass IDs and associated concept pointers.
549 ///
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>>>>
555 AnalysisResultListT;
556
557 /// \brief Map type from function pointer to our custom list type.
558 typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
559
560 /// \brief Map from function to a list of function analysis results.
561 ///
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;
565
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;
570
571 /// \brief Map from an analysis ID and function to a particular cached
572 /// analysis result.
573 AnalysisResultMapT AnalysisResults;
574
575 /// \brief A flag indicating whether debug logging is enabled.
576 bool DebugLogging;
577 };
578
579 /// \brief Convenience typedef for the Module analysis manager.
580 typedef AnalysisManager<Module> ModuleAnalysisManager;
581
582 /// \brief Convenience typedef for the Function analysis manager.
583 typedef AnalysisManager<Function> FunctionAnalysisManager;
584
585 /// \brief A module analysis which acts as a proxy for a function analysis
586 /// manager.
587 ///
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
592 /// object for it.
593 class FunctionAnalysisManagerModuleProxy {
594 public:
595 class Result;
596
597 static void *ID() { return (void *)&PassID; }
598
599 static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
600
601 explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
602 : FAM(&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)
607 : FAM(Arg.FAM) {}
608 FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
609 : FAM(std::move(Arg.FAM)) {}
610 FunctionAnalysisManagerModuleProxy &
611 operator=(FunctionAnalysisManagerModuleProxy RHS) {
612 std::swap(FAM, RHS.FAM);
613 return *this;
614 }
615
616 /// \brief Run the analysis pass and create our proxy result object.
617 ///
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.
621 ///
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);
626
627 private:
628 static char PassID;
629
630 FunctionAnalysisManager *FAM;
631 };
632
633 /// \brief The result proxy object for the
634 /// \c FunctionAnalysisManagerModuleProxy.
635 ///
636 /// See its documentation for more information.
637 class FunctionAnalysisManagerModuleProxy::Result {
638 public:
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);
646 return *this;
647 }
648 ~Result();
649
650 /// \brief Accessor for the \c FunctionAnalysisManager.
651 FunctionAnalysisManager &getManager() { return *FAM; }
652
653 /// \brief Handler for invalidation of the module.
654 ///
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.
659 ///
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);
664
665 private:
666 FunctionAnalysisManager *FAM;
667 };
668
669 /// \brief A function analysis which acts as a proxy for a module analysis
670 /// manager.
671 ///
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.
677 ///
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 {
682 public:
683 /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
684 class Result {
685 public:
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);
693 return *this;
694 }
695
696 const ModuleAnalysisManager &getManager() const { return *MAM; }
697
698 /// \brief Handle invalidation by ignoring it, this pass is immutable.
699 bool invalidate(Function &) { return false; }
700
701 private:
702 const ModuleAnalysisManager *MAM;
703 };
704
705 static void *ID() { return (void *)&PassID; }
706
707 static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
708
709 ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
710 : MAM(&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)
715 : MAM(Arg.MAM) {}
716 ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
717 : MAM(std::move(Arg.MAM)) {}
718 ModuleAnalysisManagerFunctionProxy &
719 operator=(ModuleAnalysisManagerFunctionProxy RHS) {
720 std::swap(MAM, RHS.MAM);
721 return *this;
722 }
723
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
726 /// result.
727 Result run(Function &) { return Result(*MAM); }
728
729 private:
730 static char PassID;
731
732 const ModuleAnalysisManager *MAM;
733 };
734
735 /// \brief Trivial adaptor that maps from a module to its functions.
736 ///
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.
743 ///
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.
750 ///
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
754 /// module.
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 {
758 public:
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)
764 : Pass(Arg.Pass) {}
765 ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
766 : Pass(std::move(Arg.Pass)) {}
767 friend void swap(ModuleToFunctionPassAdaptor &LHS,
768 ModuleToFunctionPassAdaptor &RHS) {
769 using std::swap;
770 swap(LHS.Pass, RHS.Pass);
771 }
772 ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
773 swap(*this, RHS);
774 return *this;
775 }
776
777 /// \brief Runs the function pass across every function in the module.
778 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
779 FunctionAnalysisManager *FAM = nullptr;
780 if (AM)
781 // Setup the function analysis manager from its proxy.
782 FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
783
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);
787
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
792 // handled.
793 if (FAM)
794 PassPA = FAM->invalidate(*I, std::move(PassPA));
795
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));
799 }
800
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>();
806 return PA;
807 }
808
809 static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
810
811 private:
812 FunctionPassT Pass;
813 };
814
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)));
821 }
822
823 /// \brief A template utility pass to force an analysis result to be available.
824 ///
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.
829 ///
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) {
836 if (AM)
837 (void)AM->template getResult<AnalysisT>(Arg);
838
839 return PreservedAnalyses::all();
840 }
841
842 static StringRef name() { return "RequireAnalysisPass"; }
843 };
844
845 /// \brief A template utility pass to force an analysis result to be
846 /// invalidated.
847 ///
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.
852 ///
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) {
859 if (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);
863
864 return PreservedAnalyses::all();
865 }
866
867 static StringRef name() { return "InvalidateAnalysisPass"; }
868 };
869
870 /// \brief A utility pass that does nothing but preserves no analyses.
871 ///
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();
878 }
879
880 static StringRef name() { return "InvalidateAllAnalysesPass"; }
881 };
882
883 }
884
885 #endif