LLVM 24.0.0git
PassManager.h
Go to the documentation of this file.
1//===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// This header defines various interfaces for pass management in LLVM. There
11/// is no "pass" interface in LLVM per se. Instead, an instance of any class
12/// which supports a method to 'run' it over a unit of IR can be used as
13/// a pass. A pass manager is generally a tool to collect a sequence of passes
14/// which run over a particular IR construct, and run each of them in sequence
15/// over each such construct in the containing IR construct. As there is no
16/// containing IR construct for a Module, a manager for passes over modules
17/// forms the base case which runs its managed passes in sequence over the
18/// single module provided.
19///
20/// The core IR library provides managers for running passes over
21/// modules and functions.
22///
23/// * FunctionPassManager can run over a Module, runs each pass over
24/// a Function.
25/// * ModulePassManager must be directly run, runs each pass over the Module.
26///
27/// Note that the implementations of the pass managers use concept-based
28/// polymorphism as outlined in the "Value Semantics and Concept-based
29/// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base
30/// Class of Evil") by Sean Parent:
31/// * https://sean-parent.stlab.cc/papers-and-presentations
32/// * http://www.youtube.com/watch?v=_BpMYeUFXv8
33/// * https://learn.microsoft.com/en-us/shows/goingnative-2013/inheritance-base-class-of-evil
34///
35//===----------------------------------------------------------------------===//
36
37#ifndef LLVM_IR_PASSMANAGER_H
38#define LLVM_IR_PASSMANAGER_H
39
40#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/StringRef.h"
45#include "llvm/IR/Analysis.h"
49#include <cassert>
50#include <cstring>
51#include <list>
52#include <memory>
53#include <tuple>
54#include <type_traits>
55#include <utility>
56#include <vector>
57
58namespace llvm {
59
60namespace detail {
61template <typename DerivedT> struct InfoMixin {
62 /// Gets the name of the pass we are mixed into.
63 static StringRef name() {
64 static_assert(std::is_base_of<InfoMixin, DerivedT>::value,
65 "Must pass the derived type as the template argument!");
67 Name.consume_front("llvm::");
68 return Name;
69 }
70};
71} // namespace detail
72
73class Function;
74class Module;
75
76// Forward declare the analysis manager template.
77template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
78
79/// A CRTP mix-in to automatically provide informational APIs needed for
80/// passes.
81///
82/// This provides some boilerplate for types that are passes.
83///
84/// Actual passes should inherit from RequiredPassInfoMixin or
85/// OptionalPassInfoMixin.
86///
87/// TODO: move to a detail namespace once we've branched for LLVM 23.
88template <typename DerivedT>
89struct PassInfoMixin : detail::InfoMixin<DerivedT> {
91 function_ref<StringRef(StringRef)> MapClassName2PassName) {
92 StringRef ClassName = DerivedT::name();
93 auto PassName = MapClassName2PassName(ClassName);
94 OS << PassName;
95 }
96
97 // TODO: remove once out of tree users are updated.
98 static bool isRequired() { return false; }
99};
100
101/// A CRTP mix-in for passes that should not be skipped.
102template <typename DerivedT>
104 static bool isRequired() { return true; }
105};
106
107/// A CRTP mix-in for passes that can be skipped.
108template <typename DerivedT>
110 static bool isRequired() { return false; }
111};
112
113/// A CRTP mix-in that provides informational APIs needed for analysis passes.
114///
115/// This provides some boilerplate for types that are analysis passes. It
116/// automatically mixes in \c PassInfoMixin.
117template <typename DerivedT>
119 /// Returns an opaque, unique ID for this analysis type.
120 ///
121 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
122 /// suitable for use in sets, maps, and other data structures that use the low
123 /// bits of pointers.
124 ///
125 /// Note that this requires the derived type provide a static \c AnalysisKey
126 /// member called \c Key.
127 ///
128 /// FIXME: The only reason the mixin type itself can't declare the Key value
129 /// is that some compilers cannot correctly unique a templated static variable
130 /// so it has the same addresses in each instantiation. The only currently
131 /// known platform with this limitation is Windows DLL builds, specifically
132 /// building each part of LLVM as a DLL. If we ever remove that build
133 /// configuration, this mixin can provide the static key as well.
134 static AnalysisKey *ID() {
135 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
136 "Must pass the derived type as the template argument!");
137 return &DerivedT::Key;
138 }
139};
140
141namespace detail {
142
143/// Actual unpacker of extra arguments in getAnalysisResult,
144/// passes only those tuple arguments that are mentioned in index_sequence.
145template <typename PassT, typename IRUnitT, typename AnalysisManagerT,
146 typename... ArgTs, size_t... Ns>
147typename PassT::Result
148getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR,
149 std::tuple<ArgTs...> Args,
150 std::index_sequence<Ns...>) {
151 (void)Args;
152 return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
153}
154
155/// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
156///
157/// Arguments passed in tuple come from PassManager, so they might have extra
158/// arguments after those AnalysisManager's ExtraArgTs ones that we need to
159/// pass to getResult.
160template <typename PassT, typename IRUnitT, typename... AnalysisArgTs,
161 typename... MainArgTs>
162typename PassT::Result
164 std::tuple<MainArgTs...> Args) {
166 PassT, IRUnitT>)(AM, IR, Args,
167 std::index_sequence_for<AnalysisArgTs...>{});
168}
169
170} // namespace detail
171
172/// Manages a sequence of passes over a particular unit of IR.
173///
174/// A pass manager contains a sequence of passes to run over a particular unit
175/// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
176/// IR, and when run over some given IR will run each of its contained passes in
177/// sequence. Pass managers are the primary and most basic building block of a
178/// pass pipeline.
179///
180/// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
181/// argument. The pass manager will propagate that analysis manager to each
182/// pass it runs, and will call the analysis manager's invalidation routine with
183/// the PreservedAnalyses of each pass it runs.
184template <typename IRUnitT,
185 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
186 typename... ExtraArgTs>
188 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
189public:
190 /// Construct a pass manager.
191 explicit PassManager() = default;
192
193 // FIXME: These are equivalent to the default move constructor/move
194 // assignment. However, using = default triggers linker errors due to the
195 // explicit instantiations below. Find away to use the default and remove the
196 // duplicated code here.
198
200 Passes = std::move(RHS.Passes);
201 return *this;
202 }
203
205 function_ref<StringRef(StringRef)> MapClassName2PassName) {
206 ListSeparator LS(",");
207 for (auto &P : Passes) {
208 OS << LS;
209 P->printPipeline(OS, MapClassName2PassName);
210 }
211 }
212
213 /// Run all of the passes in this manager over the given unit of IR.
214 /// ExtraArgs are passed to each pass.
215 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
216 ExtraArgTs... ExtraArgs);
217
218 template <typename PassT>
219 LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v<PassT, PassManager>>
220 addPass(PassT &&Pass) {
221 using PassModelT =
222 detail::PassModel<IRUnitT, PassT, AnalysisManagerT, ExtraArgTs...>;
223 Passes.push_back(PassModelT::create(std::move(Pass)));
224 }
225
226 /// When adding a pass manager pass that has the same type as this pass
227 /// manager, simply move the passes over. This is because we don't have
228 /// use cases rely on executing nested pass managers. Doing this could
229 /// reduce implementation complexity and avoid potential invalidation
230 /// issues that may happen with nested pass managers of the same type.
231 template <typename PassT>
232 LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<std::is_same_v<PassT, PassManager>>
233 addPass(PassT &&Pass) {
234 for (auto &P : Pass.Passes)
235 Passes.push_back(std::move(P));
236 }
237
238 /// Returns if the pass manager contains any passes.
239 bool isEmpty() const { return Passes.empty(); }
240
241protected:
243 detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
244
245 std::vector<typename PassConceptT::unique_ptr> Passes;
246};
247
248template <typename IRUnitT>
250
251template <>
253 const Module &IR);
254
255extern template class LLVM_TEMPLATE_ABI PassManager<Module>;
256
257/// Convenience typedef for a pass manager over modules.
259
260template <>
262 const Function &IR);
263
264extern template class LLVM_TEMPLATE_ABI PassManager<Function>;
265
266/// Convenience typedef for a pass manager over functions.
268
269/// A container for analyses that lazily runs them and caches their
270/// results.
271///
272/// This class can manage analyses for any IR unit where the address of the IR
273/// unit sufficies as its identity.
274template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
275public:
276 class Invalidator;
277
278private:
279 // Now that we've defined our invalidator, we can define the concept types.
281 using PassConceptT =
282 detail::AnalysisPassConcept<IRUnitT, Invalidator, ExtraArgTs...>;
283
284 /// List of analysis pass IDs and associated concept pointers.
285 ///
286 /// Requires iterators to be valid across appending new entries and arbitrary
287 /// erases. Provides the analysis ID to enable finding iterators to a given
288 /// entry in maps below, and provides the storage for the actual result
289 /// concept.
290 using AnalysisResultListT =
291 std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>;
292
293 /// Map type from IRUnitT pointer to our custom list type.
294 using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>;
295
296 /// Map type from a pair of analysis ID and IRUnitT pointer to an
297 /// iterator into a particular result list (which is where the actual analysis
298 /// result is stored).
299 using AnalysisResultMapT =
301 typename AnalysisResultListT::iterator>;
302
303public:
304 /// API to communicate dependencies between analyses during invalidation.
305 ///
306 /// When an analysis result embeds handles to other analysis results, it
307 /// needs to be invalidated both when its own information isn't preserved and
308 /// when any of its embedded analysis results end up invalidated. We pass an
309 /// \c Invalidator object as an argument to \c invalidate() in order to let
310 /// the analysis results themselves define the dependency graph on the fly.
311 /// This lets us avoid building an explicit representation of the
312 /// dependencies between analysis results.
313 class Invalidator {
314 public:
315 /// Trigger the invalidation of some other analysis pass if not already
316 /// handled and return whether it was in fact invalidated.
317 ///
318 /// This is expected to be called from within a given analysis result's \c
319 /// invalidate method to trigger a depth-first walk of all inter-analysis
320 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
321 /// invalidate method should in turn be provided to this routine.
322 ///
323 /// The first time this is called for a given analysis pass, it will call
324 /// the corresponding result's \c invalidate method. Subsequent calls will
325 /// use a cache of the results of that initial call. It is an error to form
326 /// cyclic dependencies between analysis results.
327 ///
328 /// This returns true if the given analysis's result is invalid. Any
329 /// dependecies on it will become invalid as a result.
330 template <typename PassT>
331 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
332 using ResultModelT =
333 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
334 Invalidator>;
335
336 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
337 }
338
339 /// A type-erased variant of the above invalidate method with the same core
340 /// API other than passing an analysis ID rather than an analysis type
341 /// parameter.
342 ///
343 /// This is sadly less efficient than the above routine, which leverages
344 /// the type parameter to avoid the type erasure overhead.
345 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
346 return invalidateImpl<>(ID, IR, PA);
347 }
348
349 private:
350 friend class AnalysisManager;
351
352 template <typename ResultT = ResultConceptT>
353 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
354 const PreservedAnalyses &PA) {
355 // If we've already visited this pass, return true if it was invalidated
356 // and false otherwise.
357 auto IMapI = IsResultInvalidated.find(ID);
358 if (IMapI != IsResultInvalidated.end())
359 return IMapI->second;
360
361 // Otherwise look up the result object.
362 auto RI = Results.find({ID, &IR});
363 assert(RI != Results.end() &&
364 "Trying to invalidate a dependent result that isn't in the "
365 "manager's cache is always an error, likely due to a stale result "
366 "handle!");
367
368 auto &Result = static_cast<ResultT &>(*RI->second->second);
369
370 // Insert into the map whether the result should be invalidated and return
371 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
372 // as calling invalidate could (recursively) insert things into the map,
373 // making any iterator or reference invalid.
374 bool Inserted;
375 std::tie(IMapI, Inserted) =
376 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
377 (void)Inserted;
378 assert(Inserted && "Should not have already inserted this ID, likely "
379 "indicates a dependency cycle!");
380 return IMapI->second;
381 }
382
383 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
384 const AnalysisResultMapT &Results)
385 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
386
387 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
388 const AnalysisResultMapT &Results;
389 };
390
391 /// Construct an empty analysis manager.
395
396 /// Returns true if the analysis manager has an empty results cache.
397 bool empty() const {
398 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
399 "The storage and index of analysis results disagree on how many "
400 "there are!");
401 return AnalysisResults.empty();
402 }
403
404 /// Clear any cached analysis results for a single unit of IR.
405 ///
406 /// This doesn't invalidate, but instead simply deletes, the relevant results.
407 /// It is useful when the IR is being removed and we want to clear out all the
408 /// memory pinned for it.
409 void clear(IRUnitT &IR, llvm::StringRef Name);
410
411 /// Clear all analysis results cached by this AnalysisManager.
412 ///
413 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
414 /// deletes them. This lets you clean up the AnalysisManager when the set of
415 /// IR units itself has potentially changed, and thus we can't even look up a
416 /// a result and invalidate/clear it directly.
417 void clear() {
418 AnalysisResults.clear();
419 AnalysisResultLists.clear();
420 }
421
422 /// Returns true if the specified analysis pass is registered.
423 template <typename PassT> bool isPassRegistered() const {
424 return AnalysisPasses.count(PassT::ID());
425 }
426
427 /// Get the result of an analysis pass for a given IR unit.
428 ///
429 /// Runs the analysis if a cached result is not available.
430 template <typename PassT>
431 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
432 assert(AnalysisPasses.count(PassT::ID()) &&
433 "This analysis pass was not registered prior to being queried");
434 ResultConceptT &ResultConcept =
435 getResultImpl(PassT::ID(), IR, ExtraArgs...);
436
437 using ResultModelT =
438 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
439 Invalidator>;
440
441 return static_cast<ResultModelT &>(ResultConcept).Result;
442 }
443
444 /// Get the cached result of an analysis pass for a given IR unit.
445 ///
446 /// This method never runs the analysis.
447 ///
448 /// \returns null if there is no cached result.
449 template <typename PassT>
450 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
451 assert(AnalysisPasses.count(PassT::ID()) &&
452 "This analysis pass was not registered prior to being queried");
453
454 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
455 if (!ResultConcept)
456 return nullptr;
457
458 using ResultModelT =
459 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
460 Invalidator>;
461
462 return &static_cast<ResultModelT *>(ResultConcept)->Result;
463 }
464
465 /// Verify that the given Result cannot be invalidated, assert otherwise.
466 template <typename PassT>
467 void verifyNotInvalidated(IRUnitT &IR, typename PassT::Result *Result) const {
469 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
470 Invalidator Inv(IsResultInvalidated, AnalysisResults);
471 assert(!Result->invalidate(IR, PA, Inv) &&
472 "Cached result cannot be invalidated");
473 }
474
475 /// Register an analysis pass with the manager.
476 ///
477 /// The parameter is a callable whose result is an analysis pass. This allows
478 /// passing in a lambda to construct the analysis.
479 ///
480 /// The analysis type to register is the type returned by calling the \c
481 /// PassBuilder argument. If that type has already been registered, then the
482 /// argument will not be called and this function will return false.
483 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
484 /// and this function returns true.
485 ///
486 /// (Note: Although the return value of this function indicates whether or not
487 /// an analysis was previously registered, you should just register all the
488 /// analyses you might want and let this class run them lazily. This idiom
489 /// lets us minimize the number of times we have to look up analyses in our
490 /// hashtable.)
491 template <typename PassBuilderT>
492 bool registerPass(PassBuilderT &&PassBuilder) {
493 using PassT = decltype(PassBuilder());
494 using PassModelT =
495 detail::AnalysisPassModel<IRUnitT, PassT, Invalidator, ExtraArgTs...>;
496
497 auto &PassPtr = AnalysisPasses[PassT::ID()];
498 if (PassPtr)
499 // Already registered this pass type!
500 return false;
501
502 // Construct a new model around the instance returned by the builder.
503 PassPtr.reset(new PassModelT(PassBuilder()));
504 return true;
505 }
506
507 /// Invalidate cached analyses for an IR unit.
508 ///
509 /// Walk through all of the analyses pertaining to this unit of IR and
510 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
511 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA);
512
513 /// Directly clear a cached analysis for an IR unit.
514 ///
515 /// Using invalidate() over this is preferred unless you are really
516 /// sure you want to *only* clear this analysis without asking if it is
517 /// invalid.
518 template <typename AnalysisT> void clearAnalysis(IRUnitT &IR) {
519 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
520 AnalysisKey *ID = AnalysisT::ID();
521
522 auto I =
523 llvm::find_if(ResultsList, [&ID](auto &E) { return E.first == ID; });
524 assert(I != ResultsList.end() && "Analysis must be available");
525 ResultsList.erase(I);
526 AnalysisResults.erase({ID, &IR});
527 }
528
529private:
530 /// Look up a registered analysis pass.
531 PassConceptT &lookUpPass(AnalysisKey *ID) {
532 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
533 assert(PI != AnalysisPasses.end() &&
534 "Analysis passes must be registered prior to being queried!");
535 return *PI->second;
536 }
537
538 /// Look up a registered analysis pass.
539 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
540 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
541 assert(PI != AnalysisPasses.end() &&
542 "Analysis passes must be registered prior to being queried!");
543 return *PI->second;
544 }
545
546 /// Get an analysis result, running the pass if necessary.
547 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
548 ExtraArgTs... ExtraArgs);
549
550 /// Get a cached analysis result or return null.
551 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
552 typename AnalysisResultMapT::const_iterator RI =
553 AnalysisResults.find({ID, &IR});
554 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
555 }
556
557 /// Map type from analysis pass ID to pass concept pointer.
558 using AnalysisPassMapT =
559 DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>;
560
561 /// Collection of analysis passes, indexed by ID.
562 AnalysisPassMapT AnalysisPasses;
563
564 /// Map from IR unit to a list of analysis results.
565 ///
566 /// Provides linear time removal of all analysis results for a IR unit and
567 /// the ultimate storage for a particular cached analysis result.
568 AnalysisResultListMapT AnalysisResultLists;
569
570 /// Map from an analysis ID and IR unit to a particular cached
571 /// analysis result.
572 AnalysisResultMapT AnalysisResults;
573};
574
575extern template class LLVM_TEMPLATE_ABI AnalysisManager<Module>;
576
577/// Convenience typedef for the Module analysis manager.
579
580extern template class LLVM_TEMPLATE_ABI AnalysisManager<Function>;
581
582/// Convenience typedef for the Function analysis manager.
584
585/// An analysis over an "outer" IR unit that provides access to an
586/// analysis manager over an "inner" IR unit. The inner unit must be contained
587/// in the outer unit.
588///
589/// For example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
590/// an analysis over Modules (the "outer" unit) that provides access to a
591/// Function analysis manager. The FunctionAnalysisManager is the "inner"
592/// manager being proxied, and Functions are the "inner" unit. The inner/outer
593/// relationship is valid because each Function is contained in one Module.
594///
595/// If you're (transitively) within a pass manager for an IR unit U that
596/// contains IR unit V, you should never use an analysis manager over V, except
597/// via one of these proxies.
598///
599/// Note that the proxy's result is a move-only RAII object. The validity of
600/// the analyses in the inner analysis manager is tied to its lifetime.
601template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
603 : public AnalysisInfoMixin<
604 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
605public:
606 class Result {
607 public:
608 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
609
610 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
611 // We have to null out the analysis manager in the moved-from state
612 // because we are taking ownership of the responsibility to clear the
613 // analysis state.
614 Arg.InnerAM = nullptr;
615 }
616
618 // InnerAM is cleared in a moved from state where there is nothing to do.
619 if (!InnerAM)
620 return;
621
622 // Clear out the analysis manager if we're being destroyed -- it means we
623 // didn't even see an invalidate call when we got invalidated.
624 InnerAM->clear();
625 }
626
628 InnerAM = RHS.InnerAM;
629 // We have to null out the analysis manager in the moved-from state
630 // because we are taking ownership of the responsibility to clear the
631 // analysis state.
632 RHS.InnerAM = nullptr;
633 return *this;
634 }
635
636 /// Accessor for the analysis manager.
637 AnalysisManagerT &getManager() { return *InnerAM; }
638
639 /// Handler for invalidation of the outer IR unit, \c IRUnitT.
640 ///
641 /// If the proxy analysis itself is not preserved, we assume that the set of
642 /// inner IR objects contained in IRUnit may have changed. In this case,
643 /// we have to call \c clear() on the inner analysis manager, as it may now
644 /// have stale pointers to its inner IR objects.
645 ///
646 /// Regardless of whether the proxy analysis is marked as preserved, all of
647 /// the analyses in the inner analysis manager are potentially invalidated
648 /// based on the set of preserved analyses.
650 IRUnitT &IR, const PreservedAnalyses &PA,
652
653 private:
654 AnalysisManagerT *InnerAM;
655 };
656
657 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
658 : InnerAM(&InnerAM) {}
659
660 /// Run the analysis pass and create our proxy result object.
661 ///
662 /// This doesn't do any interesting work; it is primarily used to insert our
663 /// proxy result object into the outer analysis cache so that we can proxy
664 /// invalidation to the inner analysis manager.
666 ExtraArgTs...) {
667 return Result(*InnerAM);
668 }
669
670private:
671 friend AnalysisInfoMixin<
673
674 static AnalysisKey Key;
675
676 AnalysisManagerT *InnerAM;
677};
678
679// NOTE: The LLVM_ABI annotation cannot be used here because MSVC disallows
680// storage-class specifiers on class members outside of the class declaration
681// (C2720). LLVM_ATTRIBUTE_VISIBILITY_DEFAULT only applies to non-Windows
682// targets so it is used instead. Without this annotation, compiling LLVM as a
683// shared library with -fvisibility=hidden using GCC fails to export the symbol
684// even though InnerAnalysisManagerProxy is already annotated with LLVM_ABI.
685template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
687 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
688
689/// Provide the \c FunctionAnalysisManager to \c Module proxy.
692
693/// Specialization of the invalidate method for the \c
694/// FunctionAnalysisManagerModuleProxy's result.
695template <>
696LLVM_ABI bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
697 Module &M, const PreservedAnalyses &PA,
698 ModuleAnalysisManager::Invalidator &Inv);
699
700// Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
701// template.
703 Module>;
704
705/// An analysis over an "inner" IR unit that provides access to an
706/// analysis manager over a "outer" IR unit. The inner unit must be contained
707/// in the outer unit.
708///
709/// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
710/// analysis over Functions (the "inner" unit) which provides access to a Module
711/// analysis manager. The ModuleAnalysisManager is the "outer" manager being
712/// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
713/// is valid because each Function is contained in one Module.
714///
715/// This proxy only exposes the const interface of the outer analysis manager,
716/// to indicate that you cannot cause an outer analysis to run from within an
717/// inner pass. Instead, you must rely on the \c getCachedResult API. This is
718/// due to keeping potential future concurrency in mind. To give an example,
719/// running a module analysis before any function passes may give a different
720/// result than running it in a function pass. Both may be valid, but it would
721/// produce non-deterministic results. GlobalsAA is a good analysis example,
722/// because the cached information has the mod/ref info for all memory for each
723/// function at the time the analysis was computed. The information is still
724/// valid after a function transformation, but it may be *different* if
725/// recomputed after that transform. GlobalsAA is never invalidated.
726
727///
728/// This proxy doesn't manage invalidation in any way -- that is handled by the
729/// recursive return path of each layer of the pass manager. A consequence of
730/// this is the outer analyses may be stale. We invalidate the outer analyses
731/// only when we're done running passes over the inner IR units.
732template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
734 : public AnalysisInfoMixin<
735 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
736public:
737 /// Result proxy object for \c OuterAnalysisManagerProxy.
738 class Result {
739 public:
740 explicit Result(const AnalysisManagerT &OuterAM) : OuterAM(&OuterAM) {}
741
742 /// Get a cached analysis. If the analysis can be invalidated, this will
743 /// assert.
744 template <typename PassT, typename IRUnitTParam>
745 typename PassT::Result *getCachedResult(IRUnitTParam &IR) const {
746 typename PassT::Result *Res =
747 OuterAM->template getCachedResult<PassT>(IR);
748 if (Res)
749 OuterAM->template verifyNotInvalidated<PassT>(IR, Res);
750 return Res;
751 }
752
753 /// Method provided for unit testing, not intended for general use.
754 template <typename PassT, typename IRUnitTParam>
755 bool cachedResultExists(IRUnitTParam &IR) const {
756 typename PassT::Result *Res =
757 OuterAM->template getCachedResult<PassT>(IR);
758 return Res != nullptr;
759 }
760
761 /// When invalidation occurs, remove any registered invalidation events.
763 IRUnitT &IRUnit, const PreservedAnalyses &PA,
765 // Loop over the set of registered outer invalidation mappings and if any
766 // of them map to an analysis that is now invalid, clear it out.
768 for (auto &KeyValuePair : OuterAnalysisInvalidationMap) {
769 AnalysisKey *OuterID = KeyValuePair.first;
770 auto &InnerIDs = KeyValuePair.second;
771 llvm::erase_if(InnerIDs, [&](AnalysisKey *InnerID) {
772 return Inv.invalidate(InnerID, IRUnit, PA);
773 });
774 if (InnerIDs.empty())
775 DeadKeys.push_back(OuterID);
776 }
777
778 for (auto *OuterID : DeadKeys)
779 OuterAnalysisInvalidationMap.erase(OuterID);
780
781 // The proxy itself remains valid regardless of anything else.
782 return false;
783 }
784
785 /// Register a deferred invalidation event for when the outer analysis
786 /// manager processes its invalidations.
787 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
789 AnalysisKey *OuterID = OuterAnalysisT::ID();
790 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
791
792 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
793 // Note, this is a linear scan. If we end up with large numbers of
794 // analyses that all trigger invalidation on the same outer analysis,
795 // this entire system should be changed to some other deterministic
796 // data structure such as a `SetVector` of a pair of pointers.
797 if (!llvm::is_contained(InvalidatedIDList, InvalidatedID))
798 InvalidatedIDList.push_back(InvalidatedID);
799 }
800
801 /// Access the map from outer analyses to deferred invalidation requiring
802 /// analyses.
805 return OuterAnalysisInvalidationMap;
806 }
807
808 private:
809 const AnalysisManagerT *OuterAM;
810
811 /// A map from an outer analysis ID to the set of this IR-unit's analyses
812 /// which need to be invalidated.
814 OuterAnalysisInvalidationMap;
815 };
816
817 OuterAnalysisManagerProxy(const AnalysisManagerT &OuterAM)
818 : OuterAM(&OuterAM) {}
819
820 /// Run the analysis pass and create our proxy result object.
821 /// Nothing to see here, it just forwards the \c OuterAM reference into the
822 /// result.
824 ExtraArgTs...) {
825 return Result(*OuterAM);
826 }
827
828private:
829 friend AnalysisInfoMixin<
830 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
831
832 static AnalysisKey Key;
833
834 const AnalysisManagerT *OuterAM;
835};
836
837template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
838AnalysisKey
839 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
840
841extern template class LLVM_TEMPLATE_ABI
843/// Provide the \c ModuleAnalysisManager to \c Function proxy.
846
847/// Trivial adaptor that maps from a module to its functions.
848///
849/// Designed to allow composition of a FunctionPass(Manager) and
850/// a ModulePassManager, by running the FunctionPass(Manager) over every
851/// function in the module.
852///
853/// Function passes run within this adaptor can rely on having exclusive access
854/// to the function they are run over. They should not read or modify any other
855/// functions! Other threads or systems may be manipulating other functions in
856/// the module, and so their state should never be relied on.
857/// FIXME: Make the above true for all of LLVM's actual passes, some still
858/// violate this principle.
859///
860/// Function passes can also read the module containing the function, but they
861/// should not modify that module outside of the use lists of various globals.
862/// For example, a function pass is not permitted to add functions to the
863/// module.
864/// FIXME: Make the above true for all of LLVM's actual passes, some still
865/// violate this principle.
866///
867/// Note that although function passes can access module analyses, module
868/// analyses are not invalidated while the function passes are running, so they
869/// may be stale. Function analyses will not be stale.
872public:
874
876 bool EagerlyInvalidate)
877 : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate) {}
878
879 /// Runs the function pass across every function in the module.
881 LLVM_ABI void
882 printPipeline(raw_ostream &OS,
883 function_ref<StringRef(StringRef)> MapClassName2PassName);
884
885private:
886 PassConceptT::unique_ptr Pass;
887 bool EagerlyInvalidate;
888};
889
890/// A function to deduce a function pass type and wrap it in the
891/// templated adaptor.
892template <typename FunctionPassT>
893ModuleToFunctionPassAdaptor
895 bool EagerlyInvalidate = false) {
896 using PassModelT =
898 return ModuleToFunctionPassAdaptor(PassModelT::create(std::move(Pass)),
899 EagerlyInvalidate);
900}
901
902/// A utility pass template to force an analysis result to be available.
903///
904/// If there are extra arguments at the pass's run level there may also be
905/// extra arguments to the analysis manager's \c getResult routine. We can't
906/// guess how to effectively map the arguments from one to the other, and so
907/// this specialization just ignores them.
908///
909/// Specific patterns of run-method extra arguments and analysis manager extra
910/// arguments will have to be defined as appropriate specializations.
911template <typename AnalysisT, typename IRUnitT,
912 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
913 typename... ExtraArgTs>
915 : RequiredPassInfoMixin<RequireAnalysisPass<
916 AnalysisT, IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
917 /// Run this pass over some unit of IR.
918 ///
919 /// This pass can be run over any unit of IR and use any analysis manager
920 /// provided they satisfy the basic API requirements. When this pass is
921 /// created, these methods can be instantiated to satisfy whatever the
922 /// context requires.
923 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
924 ExtraArgTs &&... Args) {
925 (void)AM.template getResult<AnalysisT>(Arg,
926 std::forward<ExtraArgTs>(Args)...);
927
928 return PreservedAnalyses::all();
929 }
931 function_ref<StringRef(StringRef)> MapClassName2PassName) {
932 auto ClassName = AnalysisT::name();
933 auto PassName = MapClassName2PassName(ClassName);
934 OS << "require<" << PassName << '>';
935 }
936};
937
938/// A no-op pass template which simply forces a specific analysis result
939/// to be invalidated.
940template <typename AnalysisT>
942 : RequiredPassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
943 /// Run this pass over some unit of IR.
944 ///
945 /// This pass can be run over any unit of IR and use any analysis manager,
946 /// provided they satisfy the basic API requirements. When this pass is
947 /// created, these methods can be instantiated to satisfy whatever the
948 /// context requires.
949 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
950 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
951 auto PA = PreservedAnalyses::all();
952 PA.abandon<AnalysisT>();
953 return PA;
954 }
956 function_ref<StringRef(StringRef)> MapClassName2PassName) {
957 auto ClassName = AnalysisT::name();
958 auto PassName = MapClassName2PassName(ClassName);
959 OS << "invalidate<" << PassName << '>';
960 }
961};
962
963/// A utility pass that does nothing, but preserves no analyses.
964///
965/// Because this preserves no analyses, any analysis passes queried after this
966/// pass runs will recompute fresh results.
968 : OptionalPassInfoMixin<InvalidateAllAnalysesPass> {
969 /// Run this pass over some unit of IR.
970 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
971 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
973 }
974};
975
976} // end namespace llvm
977
978#endif // LLVM_IR_PASSMANAGER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis Results
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_TEMPLATE_ABI
Definition Compiler.h:216
#define LLVM_ATTRIBUTE_MINSIZE
Definition Compiler.h:330
#define LLVM_ATTRIBUTE_VISIBILITY_DEFAULT
Definition Compiler.h:126
This file defines the DenseMap class.
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:81
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define P(N)
This header provides internal APIs and implementation details used by the pass management interfaces ...
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
static const char PassName[]
Value * RHS
API to communicate dependencies between analyses during invalidation.
bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA)
A type-erased variant of the above invalidate method with the same core API other than passing an ana...
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Trigger the invalidation of some other analysis pass if not already handled and return whether it was...
A container for analyses that lazily runs them and caches their results.
bool isPassRegistered() const
Returns true if the specified analysis pass is registered.
AnalysisManager()
Construct an empty analysis manager.
void clear()
Clear all analysis results cached by this AnalysisManager.
AnalysisManager(AnalysisManager &&)
void verifyNotInvalidated(IRUnitT &IR, typename PassT::Result *Result) const
Verify that the given Result cannot be invalidated, assert otherwise.
AnalysisManager & operator=(AnalysisManager &&)
void clear(IRUnitT &IR, llvm::StringRef Name)
Clear any cached analysis results for a single unit of IR.
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
void clearAnalysis(IRUnitT &IR)
Directly clear a cached analysis for an IR unit.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
bool empty() const
Returns true if the analysis manager has an empty results cache.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA, typename AnalysisManager< IRUnitT, ExtraArgTs... >::Invalidator &Inv)
Handler for invalidation of the outer IR unit, IRUnitT.
Result(AnalysisManagerT &InnerAM)
AnalysisManagerT & getManager()
Accessor for the analysis manager.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Result run(IRUnitT &IR, AnalysisManager< IRUnitT, ExtraArgTs... > &AM, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
A helper class to return the specified delimiter string after the first invocation of operator String...
Trivial adaptor that maps from a module to its functions.
detail::PassConcept< Function, FunctionAnalysisManager > PassConceptT
ModuleToFunctionPassAdaptor(PassConceptT::unique_ptr Pass, bool EagerlyInvalidate)
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Result(const AnalysisManagerT &OuterAM)
PassT::Result * getCachedResult(IRUnitTParam &IR) const
Get a cached analysis.
bool invalidate(IRUnitT &IRUnit, const PreservedAnalyses &PA, typename AnalysisManager< IRUnitT, ExtraArgTs... >::Invalidator &Inv)
When invalidation occurs, remove any registered invalidation events.
bool cachedResultExists(IRUnitTParam &IR) const
Method provided for unit testing, not intended for general use.
const SmallDenseMap< AnalysisKey *, TinyPtrVector< AnalysisKey * >, 2 > & getOuterInvalidations() const
Access the map from outer analyses to deferred invalidation requiring analyses.
void registerOuterAnalysisInvalidation()
Register a deferred invalidation event for when the outer analysis manager processes its invalidation...
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Result run(IRUnitT &, AnalysisManager< IRUnitT, ExtraArgTs... > &, ExtraArgTs...)
Run the analysis pass and create our proxy result object.
OuterAnalysisManagerProxy(const AnalysisManagerT &OuterAM)
This class provides access to building LLVM's passes.
Manages a sequence of passes over a particular unit of IR.
PassManager(PassManager &&Arg)
PassManager & operator=(PassManager &&RHS)
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PassManager()=default
Construct a pass manager.
detail::PassConcept< LazyCallGraph::SCC, CGSCCAnalysisManager, ExtraArgTs... > PassConceptT
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t< std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
When adding a pass manager pass that has the same type as this pass manager, simply move the passes o...
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
bool isEmpty() const
Returns if the pass manager contains any passes.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Template for the abstract base class used to dispatch over pass objects.
A template wrapper used to implement PassConcept.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Pass manager infrastructure for declaring and invalidating analyses.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
A self-contained host- and target-independent arbitrary-precision floating-point software implementat...
Definition ADL.h:123
PassT::Result getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR, std::tuple< ArgTs... > Args, std::index_sequence< Ns... >)
Actual unpacker of extra arguments in getAnalysisResult, passes only those tuple arguments that are m...
PassT::Result getAnalysisResult(AnalysisManager< IRUnitT, AnalysisArgTs... > &AM, IRUnitT &IR, std::tuple< MainArgTs... > Args)
Helper for partial unpacking of extra arguments in getAnalysisResult.
This is an optimization pass for GlobalISel generic memory operations.
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_GET_TYPE_NAME_CONSTEXPR StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
Definition TypeName.h:40
LLVM_ABI void printIRUnitNameForStackTrace< Function >(raw_ostream &OS, const Function &IR)
void printIRUnitNameForStackTrace(raw_ostream &OS, const IRUnitT &IR)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI void printIRUnitNameForStackTrace< Module >(raw_ostream &OS, const Module &IR)
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
A CRTP mix-in that provides informational APIs needed for analysis passes.
static AnalysisKey * ID()
Returns an opaque, unique ID for this analysis type.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
A utility pass that does nothing, but preserves no analyses.
PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...)
Run this pass over some unit of IR.
A no-op pass template which simply forces a specific analysis result to be invalidated.
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...)
Run this pass over some unit of IR.
A CRTP mix-in for passes that can be skipped.
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:89
static bool isRequired()
Definition PassManager.h:98
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition PassManager.h:90
A utility pass template to force an analysis result to be available.
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&... Args)
Run this pass over some unit of IR.
A CRTP mix-in for passes that should not be skipped.
Abstract concept of an analysis pass.
Wrapper to model the analysis pass concept.
Abstract concept of an analysis result.
Wrapper to model the analysis result concept.
static StringRef name()
Gets the name of the pass we are mixed into.
Definition PassManager.h:63