blob: 47bad5b2f1995bc91c17db4d5111d7c646d2bcb8 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
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/// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations
32/// * http://www.youtube.com/watch?v=_BpMYeUFXv8
33/// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-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/SmallPtrSet.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/TinyPtrVector.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/Module.h"
Andrew Scull0372a572018-11-16 15:47:06 +000046#include "llvm/IR/PassInstrumentation.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010047#include "llvm/IR/PassManagerInternal.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/TypeName.h"
50#include "llvm/Support/raw_ostream.h"
51#include <algorithm>
52#include <cassert>
53#include <cstring>
54#include <iterator>
55#include <list>
56#include <memory>
57#include <tuple>
58#include <type_traits>
59#include <utility>
60#include <vector>
61
62namespace llvm {
63
64/// A special type used by analysis passes to provide an address that
65/// identifies that particular analysis pass type.
66///
67/// Analysis passes should have a static data member of this type and derive
68/// from the \c AnalysisInfoMixin to get a static ID method used to identify
69/// the analysis in the pass management infrastructure.
70struct alignas(8) AnalysisKey {};
71
72/// A special type used to provide an address that identifies a set of related
73/// analyses. These sets are primarily used below to mark sets of analyses as
74/// preserved.
75///
76/// For example, a transformation can indicate that it preserves the CFG of a
77/// function by preserving the appropriate AnalysisSetKey. An analysis that
78/// depends only on the CFG can then check if that AnalysisSetKey is preserved;
79/// if it is, the analysis knows that it itself is preserved.
80struct alignas(8) AnalysisSetKey {};
81
82/// This templated class represents "all analyses that operate over \<a
83/// particular IR unit\>" (e.g. a Function or a Module) in instances of
84/// PreservedAnalysis.
85///
86/// This lets a transformation say e.g. "I preserved all function analyses".
87///
88/// Note that you must provide an explicit instantiation declaration and
89/// definition for this template in order to get the correct behavior on
90/// Windows. Otherwise, the address of SetKey will not be stable.
91template <typename IRUnitT> class AllAnalysesOn {
92public:
93 static AnalysisSetKey *ID() { return &SetKey; }
94
95private:
96 static AnalysisSetKey SetKey;
97};
98
99template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey;
100
101extern template class AllAnalysesOn<Module>;
102extern template class AllAnalysesOn<Function>;
103
104/// Represents analyses that only rely on functions' control flow.
105///
106/// This can be used with \c PreservedAnalyses to mark the CFG as preserved and
107/// to query whether it has been preserved.
108///
109/// The CFG of a function is defined as the set of basic blocks and the edges
110/// between them. Changing the set of basic blocks in a function is enough to
111/// mutate the CFG. Mutating the condition of a branch or argument of an
112/// invoked function does not mutate the CFG, but changing the successor labels
113/// of those instructions does.
114class CFGAnalyses {
115public:
116 static AnalysisSetKey *ID() { return &SetKey; }
117
118private:
119 static AnalysisSetKey SetKey;
120};
121
122/// A set of analyses that are preserved following a run of a transformation
123/// pass.
124///
125/// Transformation passes build and return these objects to communicate which
126/// analyses are still valid after the transformation. For most passes this is
127/// fairly simple: if they don't change anything all analyses are preserved,
128/// otherwise only a short list of analyses that have been explicitly updated
129/// are preserved.
130///
131/// This class also lets transformation passes mark abstract *sets* of analyses
132/// as preserved. A transformation that (say) does not alter the CFG can
133/// indicate such by marking a particular AnalysisSetKey as preserved, and
134/// then analyses can query whether that AnalysisSetKey is preserved.
135///
136/// Finally, this class can represent an "abandoned" analysis, which is
137/// not preserved even if it would be covered by some abstract set of analyses.
138///
139/// Given a `PreservedAnalyses` object, an analysis will typically want to
140/// figure out whether it is preserved. In the example below, MyAnalysisType is
141/// preserved if it's not abandoned, and (a) it's explicitly marked as
142/// preserved, (b), the set AllAnalysesOn<MyIRUnit> is preserved, or (c) both
143/// AnalysisSetA and AnalysisSetB are preserved.
144///
145/// ```
146/// auto PAC = PA.getChecker<MyAnalysisType>();
147/// if (PAC.preserved() || PAC.preservedSet<AllAnalysesOn<MyIRUnit>>() ||
148/// (PAC.preservedSet<AnalysisSetA>() &&
149/// PAC.preservedSet<AnalysisSetB>())) {
150/// // The analysis has been successfully preserved ...
151/// }
152/// ```
153class PreservedAnalyses {
154public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100155 /// Convenience factory function for the empty preserved set.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100156 static PreservedAnalyses none() { return PreservedAnalyses(); }
157
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100158 /// Construct a special preserved set that preserves all passes.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100159 static PreservedAnalyses all() {
160 PreservedAnalyses PA;
161 PA.PreservedIDs.insert(&AllAnalysesKey);
162 return PA;
163 }
164
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100165 /// Construct a preserved analyses object with a single preserved set.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100166 template <typename AnalysisSetT>
167 static PreservedAnalyses allInSet() {
168 PreservedAnalyses PA;
169 PA.preserveSet<AnalysisSetT>();
170 return PA;
171 }
172
173 /// Mark an analysis as preserved.
174 template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); }
175
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100176 /// Given an analysis's ID, mark the analysis as preserved, adding it
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100177 /// to the set.
178 void preserve(AnalysisKey *ID) {
179 // Clear this ID from the explicit not-preserved set if present.
180 NotPreservedAnalysisIDs.erase(ID);
181
182 // If we're not already preserving all analyses (other than those in
183 // NotPreservedAnalysisIDs).
184 if (!areAllPreserved())
185 PreservedIDs.insert(ID);
186 }
187
188 /// Mark an analysis set as preserved.
189 template <typename AnalysisSetT> void preserveSet() {
190 preserveSet(AnalysisSetT::ID());
191 }
192
193 /// Mark an analysis set as preserved using its ID.
194 void preserveSet(AnalysisSetKey *ID) {
195 // If we're not already in the saturated 'all' state, add this set.
196 if (!areAllPreserved())
197 PreservedIDs.insert(ID);
198 }
199
200 /// Mark an analysis as abandoned.
201 ///
202 /// An abandoned analysis is not preserved, even if it is nominally covered
203 /// by some other set or was previously explicitly marked as preserved.
204 ///
205 /// Note that you can only abandon a specific analysis, not a *set* of
206 /// analyses.
207 template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); }
208
209 /// Mark an analysis as abandoned using its ID.
210 ///
211 /// An abandoned analysis is not preserved, even if it is nominally covered
212 /// by some other set or was previously explicitly marked as preserved.
213 ///
214 /// Note that you can only abandon a specific analysis, not a *set* of
215 /// analyses.
216 void abandon(AnalysisKey *ID) {
217 PreservedIDs.erase(ID);
218 NotPreservedAnalysisIDs.insert(ID);
219 }
220
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100221 /// Intersect this set with another in place.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100222 ///
223 /// This is a mutating operation on this preserved set, removing all
224 /// preserved passes which are not also preserved in the argument.
225 void intersect(const PreservedAnalyses &Arg) {
226 if (Arg.areAllPreserved())
227 return;
228 if (areAllPreserved()) {
229 *this = Arg;
230 return;
231 }
232 // The intersection requires the *union* of the explicitly not-preserved
233 // IDs and the *intersection* of the preserved IDs.
234 for (auto ID : Arg.NotPreservedAnalysisIDs) {
235 PreservedIDs.erase(ID);
236 NotPreservedAnalysisIDs.insert(ID);
237 }
238 for (auto ID : PreservedIDs)
239 if (!Arg.PreservedIDs.count(ID))
240 PreservedIDs.erase(ID);
241 }
242
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100243 /// Intersect this set with a temporary other set in place.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100244 ///
245 /// This is a mutating operation on this preserved set, removing all
246 /// preserved passes which are not also preserved in the argument.
247 void intersect(PreservedAnalyses &&Arg) {
248 if (Arg.areAllPreserved())
249 return;
250 if (areAllPreserved()) {
251 *this = std::move(Arg);
252 return;
253 }
254 // The intersection requires the *union* of the explicitly not-preserved
255 // IDs and the *intersection* of the preserved IDs.
256 for (auto ID : Arg.NotPreservedAnalysisIDs) {
257 PreservedIDs.erase(ID);
258 NotPreservedAnalysisIDs.insert(ID);
259 }
260 for (auto ID : PreservedIDs)
261 if (!Arg.PreservedIDs.count(ID))
262 PreservedIDs.erase(ID);
263 }
264
265 /// A checker object that makes it easy to query for whether an analysis or
266 /// some set covering it is preserved.
267 class PreservedAnalysisChecker {
268 friend class PreservedAnalyses;
269
270 const PreservedAnalyses &PA;
271 AnalysisKey *const ID;
272 const bool IsAbandoned;
273
274 /// A PreservedAnalysisChecker is tied to a particular Analysis because
275 /// `preserved()` and `preservedSet()` both return false if the Analysis
276 /// was abandoned.
277 PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID)
278 : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {}
279
280 public:
281 /// Returns true if the checker's analysis was not abandoned and either
282 /// - the analysis is explicitly preserved or
283 /// - all analyses are preserved.
284 bool preserved() {
285 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
286 PA.PreservedIDs.count(ID));
287 }
288
289 /// Returns true if the checker's analysis was not abandoned and either
290 /// - \p AnalysisSetT is explicitly preserved or
291 /// - all analyses are preserved.
292 template <typename AnalysisSetT> bool preservedSet() {
293 AnalysisSetKey *SetID = AnalysisSetT::ID();
294 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) ||
295 PA.PreservedIDs.count(SetID));
296 }
297 };
298
299 /// Build a checker for this `PreservedAnalyses` and the specified analysis
300 /// type.
301 ///
302 /// You can use the returned object to query whether an analysis was
303 /// preserved. See the example in the comment on `PreservedAnalysis`.
304 template <typename AnalysisT> PreservedAnalysisChecker getChecker() const {
305 return PreservedAnalysisChecker(*this, AnalysisT::ID());
306 }
307
308 /// Build a checker for this `PreservedAnalyses` and the specified analysis
309 /// ID.
310 ///
311 /// You can use the returned object to query whether an analysis was
312 /// preserved. See the example in the comment on `PreservedAnalysis`.
313 PreservedAnalysisChecker getChecker(AnalysisKey *ID) const {
314 return PreservedAnalysisChecker(*this, ID);
315 }
316
317 /// Test whether all analyses are preserved (and none are abandoned).
318 ///
319 /// This is used primarily to optimize for the common case of a transformation
320 /// which makes no changes to the IR.
321 bool areAllPreserved() const {
322 return NotPreservedAnalysisIDs.empty() &&
323 PreservedIDs.count(&AllAnalysesKey);
324 }
325
326 /// Directly test whether a set of analyses is preserved.
327 ///
328 /// This is only true when no analyses have been explicitly abandoned.
329 template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const {
330 return allAnalysesInSetPreserved(AnalysisSetT::ID());
331 }
332
333 /// Directly test whether a set of analyses is preserved.
334 ///
335 /// This is only true when no analyses have been explicitly abandoned.
336 bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const {
337 return NotPreservedAnalysisIDs.empty() &&
338 (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID));
339 }
340
341private:
342 /// A special key used to indicate all analyses.
343 static AnalysisSetKey AllAnalysesKey;
344
345 /// The IDs of analyses and analysis sets that are preserved.
346 SmallPtrSet<void *, 2> PreservedIDs;
347
348 /// The IDs of explicitly not-preserved analyses.
349 ///
350 /// If an analysis in this set is covered by a set in `PreservedIDs`, we
351 /// consider it not-preserved. That is, `NotPreservedAnalysisIDs` always
352 /// "wins" over analysis sets in `PreservedIDs`.
353 ///
354 /// Also, a given ID should never occur both here and in `PreservedIDs`.
355 SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs;
356};
357
358// Forward declare the analysis manager template.
359template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
360
361/// A CRTP mix-in to automatically provide informational APIs needed for
362/// passes.
363///
364/// This provides some boilerplate for types that are passes.
365template <typename DerivedT> struct PassInfoMixin {
366 /// Gets the name of the pass we are mixed into.
367 static StringRef name() {
368 static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value,
369 "Must pass the derived type as the template argument!");
370 StringRef Name = getTypeName<DerivedT>();
371 if (Name.startswith("llvm::"))
372 Name = Name.drop_front(strlen("llvm::"));
373 return Name;
374 }
375};
376
377/// A CRTP mix-in that provides informational APIs needed for analysis passes.
378///
379/// This provides some boilerplate for types that are analysis passes. It
380/// automatically mixes in \c PassInfoMixin.
381template <typename DerivedT>
382struct AnalysisInfoMixin : PassInfoMixin<DerivedT> {
383 /// Returns an opaque, unique ID for this analysis type.
384 ///
385 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus
386 /// suitable for use in sets, maps, and other data structures that use the low
387 /// bits of pointers.
388 ///
389 /// Note that this requires the derived type provide a static \c AnalysisKey
390 /// member called \c Key.
391 ///
392 /// FIXME: The only reason the mixin type itself can't declare the Key value
393 /// is that some compilers cannot correctly unique a templated static variable
394 /// so it has the same addresses in each instantiation. The only currently
395 /// known platform with this limitation is Windows DLL builds, specifically
396 /// building each part of LLVM as a DLL. If we ever remove that build
397 /// configuration, this mixin can provide the static key as well.
398 static AnalysisKey *ID() {
399 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value,
400 "Must pass the derived type as the template argument!");
401 return &DerivedT::Key;
402 }
403};
404
Andrew Scull0372a572018-11-16 15:47:06 +0000405namespace detail {
406
407/// Actual unpacker of extra arguments in getAnalysisResult,
408/// passes only those tuple arguments that are mentioned in index_sequence.
409template <typename PassT, typename IRUnitT, typename AnalysisManagerT,
410 typename... ArgTs, size_t... Ns>
411typename PassT::Result
412getAnalysisResultUnpackTuple(AnalysisManagerT &AM, IRUnitT &IR,
413 std::tuple<ArgTs...> Args,
414 llvm::index_sequence<Ns...>) {
415 (void)Args;
416 return AM.template getResult<PassT>(IR, std::get<Ns>(Args)...);
417}
418
419/// Helper for *partial* unpacking of extra arguments in getAnalysisResult.
420///
421/// Arguments passed in tuple come from PassManager, so they might have extra
422/// arguments after those AnalysisManager's ExtraArgTs ones that we need to
423/// pass to getResult.
424template <typename PassT, typename IRUnitT, typename... AnalysisArgTs,
425 typename... MainArgTs>
426typename PassT::Result
427getAnalysisResult(AnalysisManager<IRUnitT, AnalysisArgTs...> &AM, IRUnitT &IR,
428 std::tuple<MainArgTs...> Args) {
429 return (getAnalysisResultUnpackTuple<
430 PassT, IRUnitT>)(AM, IR, Args,
431 llvm::index_sequence_for<AnalysisArgTs...>{});
432}
433
434} // namespace detail
435
436// Forward declare the pass instrumentation analysis explicitly queried in
437// generic PassManager code.
438// FIXME: figure out a way to move PassInstrumentationAnalysis into its own
439// header.
440class PassInstrumentationAnalysis;
441
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100442/// Manages a sequence of passes over a particular unit of IR.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100443///
444/// A pass manager contains a sequence of passes to run over a particular unit
445/// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of
446/// IR, and when run over some given IR will run each of its contained passes in
447/// sequence. Pass managers are the primary and most basic building block of a
448/// pass pipeline.
449///
450/// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT>
451/// argument. The pass manager will propagate that analysis manager to each
452/// pass it runs, and will call the analysis manager's invalidation routine with
453/// the PreservedAnalyses of each pass it runs.
454template <typename IRUnitT,
455 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
456 typename... ExtraArgTs>
457class PassManager : public PassInfoMixin<
458 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> {
459public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100460 /// Construct a pass manager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100461 ///
462 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
463 explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
464
465 // FIXME: These are equivalent to the default move constructor/move
466 // assignment. However, using = default triggers linker errors due to the
467 // explicit instantiations below. Find away to use the default and remove the
468 // duplicated code here.
469 PassManager(PassManager &&Arg)
470 : Passes(std::move(Arg.Passes)),
471 DebugLogging(std::move(Arg.DebugLogging)) {}
472
473 PassManager &operator=(PassManager &&RHS) {
474 Passes = std::move(RHS.Passes);
475 DebugLogging = std::move(RHS.DebugLogging);
476 return *this;
477 }
478
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100479 /// Run all of the passes in this manager over the given unit of IR.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100480 /// ExtraArgs are passed to each pass.
481 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
482 ExtraArgTs... ExtraArgs) {
483 PreservedAnalyses PA = PreservedAnalyses::all();
484
Andrew Scull0372a572018-11-16 15:47:06 +0000485 // Request PassInstrumentation from analysis manager, will use it to run
486 // instrumenting callbacks for the passes later.
487 // Here we use std::tuple wrapper over getResult which helps to extract
488 // AnalysisManager's arguments out of the whole ExtraArgs set.
489 PassInstrumentation PI =
490 detail::getAnalysisResult<PassInstrumentationAnalysis>(
491 AM, IR, std::tuple<ExtraArgTs...>(ExtraArgs...));
492
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100493 if (DebugLogging)
494 dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n";
495
496 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
Andrew Scull0372a572018-11-16 15:47:06 +0000497 auto *P = Passes[Idx].get();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100498 if (DebugLogging)
Andrew Scull0372a572018-11-16 15:47:06 +0000499 dbgs() << "Running pass: " << P->name() << " on " << IR.getName()
500 << "\n";
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100501
Andrew Scull0372a572018-11-16 15:47:06 +0000502 // Check the PassInstrumentation's BeforePass callbacks before running the
503 // pass, skip its execution completely if asked to (callback returns
504 // false).
505 if (!PI.runBeforePass<IRUnitT>(*P, IR))
506 continue;
507
508 PreservedAnalyses PassPA = P->run(IR, AM, ExtraArgs...);
509
510 // Call onto PassInstrumentation's AfterPass callbacks immediately after
511 // running the pass.
512 PI.runAfterPass<IRUnitT>(*P, IR);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100513
514 // Update the analysis manager as each pass runs and potentially
515 // invalidates analyses.
516 AM.invalidate(IR, PassPA);
517
518 // Finally, intersect the preserved analyses to compute the aggregate
519 // preserved set for this pass manager.
520 PA.intersect(std::move(PassPA));
521
522 // FIXME: Historically, the pass managers all called the LLVM context's
523 // yield function here. We don't have a generic way to acquire the
524 // context and it isn't yet clear what the right pattern is for yielding
525 // in the new pass manager so it is currently omitted.
526 //IR.getContext().yield();
527 }
528
529 // Invalidation was handled after each pass in the above loop for the
530 // current unit of IR. Therefore, the remaining analysis results in the
531 // AnalysisManager are preserved. We mark this with a set so that we don't
532 // need to inspect each one individually.
533 PA.preserveSet<AllAnalysesOn<IRUnitT>>();
534
535 if (DebugLogging)
536 dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n";
537
538 return PA;
539 }
540
541 template <typename PassT> void addPass(PassT Pass) {
542 using PassModelT =
543 detail::PassModel<IRUnitT, PassT, PreservedAnalyses, AnalysisManagerT,
544 ExtraArgTs...>;
545
546 Passes.emplace_back(new PassModelT(std::move(Pass)));
547 }
548
549private:
550 using PassConceptT =
551 detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>;
552
553 std::vector<std::unique_ptr<PassConceptT>> Passes;
554
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100555 /// Flag indicating whether we should do debug logging.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100556 bool DebugLogging;
557};
558
559extern template class PassManager<Module>;
560
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100561/// Convenience typedef for a pass manager over modules.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100562using ModulePassManager = PassManager<Module>;
563
564extern template class PassManager<Function>;
565
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100566/// Convenience typedef for a pass manager over functions.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100567using FunctionPassManager = PassManager<Function>;
568
Andrew Scull0372a572018-11-16 15:47:06 +0000569/// Pseudo-analysis pass that exposes the \c PassInstrumentation to pass
570/// managers. Goes before AnalysisManager definition to provide its
571/// internals (e.g PassInstrumentationAnalysis::ID) for use there if needed.
572/// FIXME: figure out a way to move PassInstrumentationAnalysis into its own
573/// header.
574class PassInstrumentationAnalysis
575 : public AnalysisInfoMixin<PassInstrumentationAnalysis> {
576 friend AnalysisInfoMixin<PassInstrumentationAnalysis>;
577 static AnalysisKey Key;
578
579 PassInstrumentationCallbacks *Callbacks;
580
581public:
582 /// PassInstrumentationCallbacks object is shared, owned by something else,
583 /// not this analysis.
584 PassInstrumentationAnalysis(PassInstrumentationCallbacks *Callbacks = nullptr)
585 : Callbacks(Callbacks) {}
586
587 using Result = PassInstrumentation;
588
589 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
590 Result run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
591 return PassInstrumentation(Callbacks);
592 }
593};
594
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100595/// A container for analyses that lazily runs them and caches their
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100596/// results.
597///
598/// This class can manage analyses for any IR unit where the address of the IR
599/// unit sufficies as its identity.
600template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager {
601public:
602 class Invalidator;
603
604private:
605 // Now that we've defined our invalidator, we can define the concept types.
606 using ResultConceptT =
607 detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>;
608 using PassConceptT =
609 detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator,
610 ExtraArgTs...>;
611
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100612 /// List of analysis pass IDs and associated concept pointers.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100613 ///
614 /// Requires iterators to be valid across appending new entries and arbitrary
615 /// erases. Provides the analysis ID to enable finding iterators to a given
616 /// entry in maps below, and provides the storage for the actual result
617 /// concept.
618 using AnalysisResultListT =
619 std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>;
620
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100621 /// Map type from IRUnitT pointer to our custom list type.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100622 using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>;
623
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100624 /// Map type from a pair of analysis ID and IRUnitT pointer to an
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100625 /// iterator into a particular result list (which is where the actual analysis
626 /// result is stored).
627 using AnalysisResultMapT =
628 DenseMap<std::pair<AnalysisKey *, IRUnitT *>,
629 typename AnalysisResultListT::iterator>;
630
631public:
632 /// API to communicate dependencies between analyses during invalidation.
633 ///
634 /// When an analysis result embeds handles to other analysis results, it
635 /// needs to be invalidated both when its own information isn't preserved and
636 /// when any of its embedded analysis results end up invalidated. We pass an
637 /// \c Invalidator object as an argument to \c invalidate() in order to let
638 /// the analysis results themselves define the dependency graph on the fly.
639 /// This lets us avoid building building an explicit representation of the
640 /// dependencies between analysis results.
641 class Invalidator {
642 public:
643 /// Trigger the invalidation of some other analysis pass if not already
644 /// handled and return whether it was in fact invalidated.
645 ///
646 /// This is expected to be called from within a given analysis result's \c
647 /// invalidate method to trigger a depth-first walk of all inter-analysis
648 /// dependencies. The same \p IR unit and \p PA passed to that result's \c
649 /// invalidate method should in turn be provided to this routine.
650 ///
651 /// The first time this is called for a given analysis pass, it will call
652 /// the corresponding result's \c invalidate method. Subsequent calls will
653 /// use a cache of the results of that initial call. It is an error to form
654 /// cyclic dependencies between analysis results.
655 ///
656 /// This returns true if the given analysis's result is invalid. Any
657 /// dependecies on it will become invalid as a result.
658 template <typename PassT>
659 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
660 using ResultModelT =
661 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
662 PreservedAnalyses, Invalidator>;
663
664 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA);
665 }
666
667 /// A type-erased variant of the above invalidate method with the same core
668 /// API other than passing an analysis ID rather than an analysis type
669 /// parameter.
670 ///
671 /// This is sadly less efficient than the above routine, which leverages
672 /// the type parameter to avoid the type erasure overhead.
673 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) {
674 return invalidateImpl<>(ID, IR, PA);
675 }
676
677 private:
678 friend class AnalysisManager;
679
680 template <typename ResultT = ResultConceptT>
681 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR,
682 const PreservedAnalyses &PA) {
683 // If we've already visited this pass, return true if it was invalidated
684 // and false otherwise.
685 auto IMapI = IsResultInvalidated.find(ID);
686 if (IMapI != IsResultInvalidated.end())
687 return IMapI->second;
688
689 // Otherwise look up the result object.
690 auto RI = Results.find({ID, &IR});
691 assert(RI != Results.end() &&
692 "Trying to invalidate a dependent result that isn't in the "
693 "manager's cache is always an error, likely due to a stale result "
694 "handle!");
695
696 auto &Result = static_cast<ResultT &>(*RI->second->second);
697
698 // Insert into the map whether the result should be invalidated and return
699 // that. Note that we cannot reuse IMapI and must do a fresh insert here,
700 // as calling invalidate could (recursively) insert things into the map,
701 // making any iterator or reference invalid.
702 bool Inserted;
703 std::tie(IMapI, Inserted) =
704 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)});
705 (void)Inserted;
706 assert(Inserted && "Should not have already inserted this ID, likely "
707 "indicates a dependency cycle!");
708 return IMapI->second;
709 }
710
711 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated,
712 const AnalysisResultMapT &Results)
713 : IsResultInvalidated(IsResultInvalidated), Results(Results) {}
714
715 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated;
716 const AnalysisResultMapT &Results;
717 };
718
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100719 /// Construct an empty analysis manager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100720 ///
721 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs().
722 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
723 AnalysisManager(AnalysisManager &&) = default;
724 AnalysisManager &operator=(AnalysisManager &&) = default;
725
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100726 /// Returns true if the analysis manager has an empty results cache.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100727 bool empty() const {
728 assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
729 "The storage and index of analysis results disagree on how many "
730 "there are!");
731 return AnalysisResults.empty();
732 }
733
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100734 /// Clear any cached analysis results for a single unit of IR.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100735 ///
736 /// This doesn't invalidate, but instead simply deletes, the relevant results.
737 /// It is useful when the IR is being removed and we want to clear out all the
738 /// memory pinned for it.
739 void clear(IRUnitT &IR, llvm::StringRef Name) {
740 if (DebugLogging)
741 dbgs() << "Clearing all analysis results for: " << Name << "\n";
742
743 auto ResultsListI = AnalysisResultLists.find(&IR);
744 if (ResultsListI == AnalysisResultLists.end())
745 return;
746 // Delete the map entries that point into the results list.
747 for (auto &IDAndResult : ResultsListI->second)
748 AnalysisResults.erase({IDAndResult.first, &IR});
749
750 // And actually destroy and erase the results associated with this IR.
751 AnalysisResultLists.erase(ResultsListI);
752 }
753
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100754 /// Clear all analysis results cached by this AnalysisManager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100755 ///
756 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply
757 /// deletes them. This lets you clean up the AnalysisManager when the set of
758 /// IR units itself has potentially changed, and thus we can't even look up a
759 /// a result and invalidate/clear it directly.
760 void clear() {
761 AnalysisResults.clear();
762 AnalysisResultLists.clear();
763 }
764
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100765 /// Get the result of an analysis pass for a given IR unit.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100766 ///
767 /// Runs the analysis if a cached result is not available.
768 template <typename PassT>
769 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) {
770 assert(AnalysisPasses.count(PassT::ID()) &&
771 "This analysis pass was not registered prior to being queried");
772 ResultConceptT &ResultConcept =
773 getResultImpl(PassT::ID(), IR, ExtraArgs...);
774
775 using ResultModelT =
776 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
777 PreservedAnalyses, Invalidator>;
778
779 return static_cast<ResultModelT &>(ResultConcept).Result;
780 }
781
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100782 /// Get the cached result of an analysis pass for a given IR unit.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100783 ///
784 /// This method never runs the analysis.
785 ///
786 /// \returns null if there is no cached result.
787 template <typename PassT>
788 typename PassT::Result *getCachedResult(IRUnitT &IR) const {
789 assert(AnalysisPasses.count(PassT::ID()) &&
790 "This analysis pass was not registered prior to being queried");
791
792 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR);
793 if (!ResultConcept)
794 return nullptr;
795
796 using ResultModelT =
797 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result,
798 PreservedAnalyses, Invalidator>;
799
800 return &static_cast<ResultModelT *>(ResultConcept)->Result;
801 }
802
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100803 /// Register an analysis pass with the manager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100804 ///
805 /// The parameter is a callable whose result is an analysis pass. This allows
806 /// passing in a lambda to construct the analysis.
807 ///
808 /// The analysis type to register is the type returned by calling the \c
809 /// PassBuilder argument. If that type has already been registered, then the
810 /// argument will not be called and this function will return false.
811 /// Otherwise, we register the analysis returned by calling \c PassBuilder(),
812 /// and this function returns true.
813 ///
814 /// (Note: Although the return value of this function indicates whether or not
815 /// an analysis was previously registered, there intentionally isn't a way to
816 /// query this directly. Instead, you should just register all the analyses
817 /// you might want and let this class run them lazily. This idiom lets us
818 /// minimize the number of times we have to look up analyses in our
819 /// hashtable.)
820 template <typename PassBuilderT>
821 bool registerPass(PassBuilderT &&PassBuilder) {
822 using PassT = decltype(PassBuilder());
823 using PassModelT =
824 detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses,
825 Invalidator, ExtraArgTs...>;
826
827 auto &PassPtr = AnalysisPasses[PassT::ID()];
828 if (PassPtr)
829 // Already registered this pass type!
830 return false;
831
832 // Construct a new model around the instance returned by the builder.
833 PassPtr.reset(new PassModelT(PassBuilder()));
834 return true;
835 }
836
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100837 /// Invalidate a specific analysis pass for an IR module.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100838 ///
839 /// Note that the analysis result can disregard invalidation, if it determines
840 /// it is in fact still valid.
841 template <typename PassT> void invalidate(IRUnitT &IR) {
842 assert(AnalysisPasses.count(PassT::ID()) &&
843 "This analysis pass was not registered prior to being invalidated");
844 invalidateImpl(PassT::ID(), IR);
845 }
846
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100847 /// Invalidate cached analyses for an IR unit.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100848 ///
849 /// Walk through all of the analyses pertaining to this unit of IR and
850 /// invalidate them, unless they are preserved by the PreservedAnalyses set.
851 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA) {
852 // We're done if all analyses on this IR unit are preserved.
853 if (PA.allAnalysesInSetPreserved<AllAnalysesOn<IRUnitT>>())
854 return;
855
856 if (DebugLogging)
857 dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName()
858 << "\n";
859
860 // Track whether each analysis's result is invalidated in
861 // IsResultInvalidated.
862 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated;
863 Invalidator Inv(IsResultInvalidated, AnalysisResults);
864 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
865 for (auto &AnalysisResultPair : ResultsList) {
866 // This is basically the same thing as Invalidator::invalidate, but we
867 // can't call it here because we're operating on the type-erased result.
868 // Moreover if we instead called invalidate() directly, it would do an
869 // unnecessary look up in ResultsList.
870 AnalysisKey *ID = AnalysisResultPair.first;
871 auto &Result = *AnalysisResultPair.second;
872
873 auto IMapI = IsResultInvalidated.find(ID);
874 if (IMapI != IsResultInvalidated.end())
875 // This result was already handled via the Invalidator.
876 continue;
877
878 // Try to invalidate the result, giving it the Invalidator so it can
879 // recursively query for any dependencies it has and record the result.
880 // Note that we cannot reuse 'IMapI' here or pre-insert the ID, as
881 // Result.invalidate may insert things into the map, invalidating our
882 // iterator.
883 bool Inserted =
884 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, Inv)})
885 .second;
886 (void)Inserted;
887 assert(Inserted && "Should never have already inserted this ID, likely "
888 "indicates a cycle!");
889 }
890
891 // Now erase the results that were marked above as invalidated.
892 if (!IsResultInvalidated.empty()) {
893 for (auto I = ResultsList.begin(), E = ResultsList.end(); I != E;) {
894 AnalysisKey *ID = I->first;
895 if (!IsResultInvalidated.lookup(ID)) {
896 ++I;
897 continue;
898 }
899
900 if (DebugLogging)
901 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
902 << " on " << IR.getName() << "\n";
903
904 I = ResultsList.erase(I);
905 AnalysisResults.erase({ID, &IR});
906 }
907 }
908
909 if (ResultsList.empty())
910 AnalysisResultLists.erase(&IR);
911 }
912
913private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100914 /// Look up a registered analysis pass.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100915 PassConceptT &lookUpPass(AnalysisKey *ID) {
916 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID);
917 assert(PI != AnalysisPasses.end() &&
918 "Analysis passes must be registered prior to being queried!");
919 return *PI->second;
920 }
921
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100922 /// Look up a registered analysis pass.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100923 const PassConceptT &lookUpPass(AnalysisKey *ID) const {
924 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID);
925 assert(PI != AnalysisPasses.end() &&
926 "Analysis passes must be registered prior to being queried!");
927 return *PI->second;
928 }
929
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100930 /// Get an analysis result, running the pass if necessary.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100931 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR,
932 ExtraArgTs... ExtraArgs) {
933 typename AnalysisResultMapT::iterator RI;
934 bool Inserted;
935 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
936 std::make_pair(ID, &IR), typename AnalysisResultListT::iterator()));
937
938 // If we don't have a cached result for this function, look up the pass and
939 // run it to produce a result, which we then add to the cache.
940 if (Inserted) {
941 auto &P = this->lookUpPass(ID);
942 if (DebugLogging)
943 dbgs() << "Running analysis: " << P.name() << " on " << IR.getName()
944 << "\n";
Andrew Scull0372a572018-11-16 15:47:06 +0000945
946 PassInstrumentation PI;
947 if (ID != PassInstrumentationAnalysis::ID()) {
948 PI = getResult<PassInstrumentationAnalysis>(IR, ExtraArgs...);
949 PI.runBeforeAnalysis(P, IR);
950 }
951
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100952 AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
953 ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...));
954
Andrew Scull0372a572018-11-16 15:47:06 +0000955 PI.runAfterAnalysis(P, IR);
956
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100957 // P.run may have inserted elements into AnalysisResults and invalidated
958 // RI.
959 RI = AnalysisResults.find({ID, &IR});
960 assert(RI != AnalysisResults.end() && "we just inserted it!");
961
962 RI->second = std::prev(ResultList.end());
963 }
964
965 return *RI->second->second;
966 }
967
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100968 /// Get a cached analysis result or return null.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100969 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const {
970 typename AnalysisResultMapT::const_iterator RI =
971 AnalysisResults.find({ID, &IR});
972 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
973 }
974
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100975 /// Invalidate a function pass result.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100976 void invalidateImpl(AnalysisKey *ID, IRUnitT &IR) {
977 typename AnalysisResultMapT::iterator RI =
978 AnalysisResults.find({ID, &IR});
979 if (RI == AnalysisResults.end())
980 return;
981
982 if (DebugLogging)
983 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name()
984 << " on " << IR.getName() << "\n";
985 AnalysisResultLists[&IR].erase(RI->second);
986 AnalysisResults.erase(RI);
987 }
988
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100989 /// Map type from module analysis pass ID to pass concept pointer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100990 using AnalysisPassMapT =
991 DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>;
992
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100993 /// Collection of module analysis passes, indexed by ID.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100994 AnalysisPassMapT AnalysisPasses;
995
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100996 /// Map from function to a list of function analysis results.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100997 ///
998 /// Provides linear time removal of all analysis results for a function and
999 /// the ultimate storage for a particular cached analysis result.
1000 AnalysisResultListMapT AnalysisResultLists;
1001
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001002 /// Map from an analysis ID and function to a particular cached
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001003 /// analysis result.
1004 AnalysisResultMapT AnalysisResults;
1005
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001006 /// Indicates whether we log to \c llvm::dbgs().
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001007 bool DebugLogging;
1008};
1009
1010extern template class AnalysisManager<Module>;
1011
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001012/// Convenience typedef for the Module analysis manager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001013using ModuleAnalysisManager = AnalysisManager<Module>;
1014
1015extern template class AnalysisManager<Function>;
1016
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001017/// Convenience typedef for the Function analysis manager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001018using FunctionAnalysisManager = AnalysisManager<Function>;
1019
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001020/// An analysis over an "outer" IR unit that provides access to an
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001021/// analysis manager over an "inner" IR unit. The inner unit must be contained
1022/// in the outer unit.
1023///
Andrew Scull0372a572018-11-16 15:47:06 +00001024/// For example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001025/// an analysis over Modules (the "outer" unit) that provides access to a
1026/// Function analysis manager. The FunctionAnalysisManager is the "inner"
1027/// manager being proxied, and Functions are the "inner" unit. The inner/outer
1028/// relationship is valid because each Function is contained in one Module.
1029///
1030/// If you're (transitively) within a pass manager for an IR unit U that
1031/// contains IR unit V, you should never use an analysis manager over V, except
1032/// via one of these proxies.
1033///
1034/// Note that the proxy's result is a move-only RAII object. The validity of
1035/// the analyses in the inner analysis manager is tied to its lifetime.
1036template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1037class InnerAnalysisManagerProxy
1038 : public AnalysisInfoMixin<
1039 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> {
1040public:
1041 class Result {
1042 public:
1043 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {}
1044
1045 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) {
1046 // We have to null out the analysis manager in the moved-from state
1047 // because we are taking ownership of the responsibilty to clear the
1048 // analysis state.
1049 Arg.InnerAM = nullptr;
1050 }
1051
1052 ~Result() {
1053 // InnerAM is cleared in a moved from state where there is nothing to do.
1054 if (!InnerAM)
1055 return;
1056
1057 // Clear out the analysis manager if we're being destroyed -- it means we
1058 // didn't even see an invalidate call when we got invalidated.
1059 InnerAM->clear();
1060 }
1061
1062 Result &operator=(Result &&RHS) {
1063 InnerAM = RHS.InnerAM;
1064 // We have to null out the analysis manager in the moved-from state
1065 // because we are taking ownership of the responsibilty to clear the
1066 // analysis state.
1067 RHS.InnerAM = nullptr;
1068 return *this;
1069 }
1070
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001071 /// Accessor for the analysis manager.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001072 AnalysisManagerT &getManager() { return *InnerAM; }
1073
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001074 /// Handler for invalidation of the outer IR unit, \c IRUnitT.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001075 ///
1076 /// If the proxy analysis itself is not preserved, we assume that the set of
1077 /// inner IR objects contained in IRUnit may have changed. In this case,
1078 /// we have to call \c clear() on the inner analysis manager, as it may now
1079 /// have stale pointers to its inner IR objects.
1080 ///
1081 /// Regardless of whether the proxy analysis is marked as preserved, all of
1082 /// the analyses in the inner analysis manager are potentially invalidated
1083 /// based on the set of preserved analyses.
1084 bool invalidate(
1085 IRUnitT &IR, const PreservedAnalyses &PA,
1086 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv);
1087
1088 private:
1089 AnalysisManagerT *InnerAM;
1090 };
1091
1092 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM)
1093 : InnerAM(&InnerAM) {}
1094
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001095 /// Run the analysis pass and create our proxy result object.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001096 ///
1097 /// This doesn't do any interesting work; it is primarily used to insert our
1098 /// proxy result object into the outer analysis cache so that we can proxy
1099 /// invalidation to the inner analysis manager.
1100 Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM,
1101 ExtraArgTs...) {
1102 return Result(*InnerAM);
1103 }
1104
1105private:
1106 friend AnalysisInfoMixin<
1107 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>;
1108
1109 static AnalysisKey Key;
1110
1111 AnalysisManagerT *InnerAM;
1112};
1113
1114template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1115AnalysisKey
1116 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1117
1118/// Provide the \c FunctionAnalysisManager to \c Module proxy.
1119using FunctionAnalysisManagerModuleProxy =
1120 InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>;
1121
1122/// Specialization of the invalidate method for the \c
1123/// FunctionAnalysisManagerModuleProxy's result.
1124template <>
1125bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
1126 Module &M, const PreservedAnalyses &PA,
1127 ModuleAnalysisManager::Invalidator &Inv);
1128
1129// Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern
1130// template.
1131extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
1132 Module>;
1133
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001134/// An analysis over an "inner" IR unit that provides access to an
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001135/// analysis manager over a "outer" IR unit. The inner unit must be contained
1136/// in the outer unit.
1137///
1138/// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an
1139/// analysis over Functions (the "inner" unit) which provides access to a Module
1140/// analysis manager. The ModuleAnalysisManager is the "outer" manager being
1141/// proxied, and Modules are the "outer" IR unit. The inner/outer relationship
1142/// is valid because each Function is contained in one Module.
1143///
1144/// This proxy only exposes the const interface of the outer analysis manager,
1145/// to indicate that you cannot cause an outer analysis to run from within an
1146/// inner pass. Instead, you must rely on the \c getCachedResult API.
1147///
1148/// This proxy doesn't manage invalidation in any way -- that is handled by the
1149/// recursive return path of each layer of the pass manager. A consequence of
1150/// this is the outer analyses may be stale. We invalidate the outer analyses
1151/// only when we're done running passes over the inner IR units.
1152template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1153class OuterAnalysisManagerProxy
1154 : public AnalysisInfoMixin<
1155 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> {
1156public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001157 /// Result proxy object for \c OuterAnalysisManagerProxy.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001158 class Result {
1159 public:
1160 explicit Result(const AnalysisManagerT &AM) : AM(&AM) {}
1161
1162 const AnalysisManagerT &getManager() const { return *AM; }
1163
1164 /// When invalidation occurs, remove any registered invalidation events.
1165 bool invalidate(
1166 IRUnitT &IRUnit, const PreservedAnalyses &PA,
1167 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv) {
1168 // Loop over the set of registered outer invalidation mappings and if any
1169 // of them map to an analysis that is now invalid, clear it out.
1170 SmallVector<AnalysisKey *, 4> DeadKeys;
1171 for (auto &KeyValuePair : OuterAnalysisInvalidationMap) {
1172 AnalysisKey *OuterID = KeyValuePair.first;
1173 auto &InnerIDs = KeyValuePair.second;
1174 InnerIDs.erase(llvm::remove_if(InnerIDs, [&](AnalysisKey *InnerID) {
1175 return Inv.invalidate(InnerID, IRUnit, PA); }),
1176 InnerIDs.end());
1177 if (InnerIDs.empty())
1178 DeadKeys.push_back(OuterID);
1179 }
1180
1181 for (auto OuterID : DeadKeys)
1182 OuterAnalysisInvalidationMap.erase(OuterID);
1183
1184 // The proxy itself remains valid regardless of anything else.
1185 return false;
1186 }
1187
1188 /// Register a deferred invalidation event for when the outer analysis
1189 /// manager processes its invalidations.
1190 template <typename OuterAnalysisT, typename InvalidatedAnalysisT>
1191 void registerOuterAnalysisInvalidation() {
1192 AnalysisKey *OuterID = OuterAnalysisT::ID();
1193 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID();
1194
1195 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID];
1196 // Note, this is a linear scan. If we end up with large numbers of
1197 // analyses that all trigger invalidation on the same outer analysis,
1198 // this entire system should be changed to some other deterministic
1199 // data structure such as a `SetVector` of a pair of pointers.
1200 auto InvalidatedIt = std::find(InvalidatedIDList.begin(),
1201 InvalidatedIDList.end(), InvalidatedID);
1202 if (InvalidatedIt == InvalidatedIDList.end())
1203 InvalidatedIDList.push_back(InvalidatedID);
1204 }
1205
1206 /// Access the map from outer analyses to deferred invalidation requiring
1207 /// analyses.
1208 const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> &
1209 getOuterInvalidations() const {
1210 return OuterAnalysisInvalidationMap;
1211 }
1212
1213 private:
1214 const AnalysisManagerT *AM;
1215
1216 /// A map from an outer analysis ID to the set of this IR-unit's analyses
1217 /// which need to be invalidated.
1218 SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2>
1219 OuterAnalysisInvalidationMap;
1220 };
1221
1222 OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {}
1223
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001224 /// Run the analysis pass and create our proxy result object.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001225 /// Nothing to see here, it just forwards the \c AM reference into the
1226 /// result.
1227 Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &,
1228 ExtraArgTs...) {
1229 return Result(*AM);
1230 }
1231
1232private:
1233 friend AnalysisInfoMixin<
1234 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>;
1235
1236 static AnalysisKey Key;
1237
1238 const AnalysisManagerT *AM;
1239};
1240
1241template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs>
1242AnalysisKey
1243 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key;
1244
1245extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
1246 Function>;
1247/// Provide the \c ModuleAnalysisManager to \c Function proxy.
1248using ModuleAnalysisManagerFunctionProxy =
1249 OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>;
1250
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001251/// Trivial adaptor that maps from a module to its functions.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001252///
1253/// Designed to allow composition of a FunctionPass(Manager) and
1254/// a ModulePassManager, by running the FunctionPass(Manager) over every
1255/// function in the module.
1256///
1257/// Function passes run within this adaptor can rely on having exclusive access
1258/// to the function they are run over. They should not read or modify any other
1259/// functions! Other threads or systems may be manipulating other functions in
1260/// the module, and so their state should never be relied on.
1261/// FIXME: Make the above true for all of LLVM's actual passes, some still
1262/// violate this principle.
1263///
1264/// Function passes can also read the module containing the function, but they
1265/// should not modify that module outside of the use lists of various globals.
1266/// For example, a function pass is not permitted to add functions to the
1267/// module.
1268/// FIXME: Make the above true for all of LLVM's actual passes, some still
1269/// violate this principle.
1270///
1271/// Note that although function passes can access module analyses, module
1272/// analyses are not invalidated while the function passes are running, so they
1273/// may be stale. Function analyses will not be stale.
1274template <typename FunctionPassT>
1275class ModuleToFunctionPassAdaptor
1276 : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> {
1277public:
1278 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
1279 : Pass(std::move(Pass)) {}
1280
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001281 /// Runs the function pass across every function in the module.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001282 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
1283 FunctionAnalysisManager &FAM =
1284 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1285
Andrew Scull0372a572018-11-16 15:47:06 +00001286 // Request PassInstrumentation from analysis manager, will use it to run
1287 // instrumenting callbacks for the passes later.
1288 PassInstrumentation PI = AM.getResult<PassInstrumentationAnalysis>(M);
1289
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001290 PreservedAnalyses PA = PreservedAnalyses::all();
1291 for (Function &F : M) {
1292 if (F.isDeclaration())
1293 continue;
1294
Andrew Scull0372a572018-11-16 15:47:06 +00001295 // Check the PassInstrumentation's BeforePass callbacks before running the
1296 // pass, skip its execution completely if asked to (callback returns
1297 // false).
1298 if (!PI.runBeforePass<Function>(Pass, F))
1299 continue;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001300 PreservedAnalyses PassPA = Pass.run(F, FAM);
1301
Andrew Scull0372a572018-11-16 15:47:06 +00001302 PI.runAfterPass(Pass, F);
1303
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001304 // We know that the function pass couldn't have invalidated any other
1305 // function's analyses (that's the contract of a function pass), so
1306 // directly handle the function analysis manager's invalidation here.
1307 FAM.invalidate(F, PassPA);
1308
1309 // Then intersect the preserved set so that invalidation of module
1310 // analyses will eventually occur when the module pass completes.
1311 PA.intersect(std::move(PassPA));
1312 }
1313
1314 // The FunctionAnalysisManagerModuleProxy is preserved because (we assume)
1315 // the function passes we ran didn't add or remove any functions.
1316 //
1317 // We also preserve all analyses on Functions, because we did all the
1318 // invalidation we needed to do above.
1319 PA.preserveSet<AllAnalysesOn<Function>>();
1320 PA.preserve<FunctionAnalysisManagerModuleProxy>();
1321 return PA;
1322 }
1323
1324private:
1325 FunctionPassT Pass;
1326};
1327
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001328/// A function to deduce a function pass type and wrap it in the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001329/// templated adaptor.
1330template <typename FunctionPassT>
1331ModuleToFunctionPassAdaptor<FunctionPassT>
1332createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
1333 return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
1334}
1335
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001336/// A utility pass template to force an analysis result to be available.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001337///
1338/// If there are extra arguments at the pass's run level there may also be
1339/// extra arguments to the analysis manager's \c getResult routine. We can't
1340/// guess how to effectively map the arguments from one to the other, and so
1341/// this specialization just ignores them.
1342///
1343/// Specific patterns of run-method extra arguments and analysis manager extra
1344/// arguments will have to be defined as appropriate specializations.
1345template <typename AnalysisT, typename IRUnitT,
1346 typename AnalysisManagerT = AnalysisManager<IRUnitT>,
1347 typename... ExtraArgTs>
1348struct RequireAnalysisPass
1349 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
1350 ExtraArgTs...>> {
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001351 /// Run this pass over some unit of IR.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001352 ///
1353 /// This pass can be run over any unit of IR and use any analysis manager
1354 /// provided they satisfy the basic API requirements. When this pass is
1355 /// created, these methods can be instantiated to satisfy whatever the
1356 /// context requires.
1357 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM,
1358 ExtraArgTs &&... Args) {
1359 (void)AM.template getResult<AnalysisT>(Arg,
1360 std::forward<ExtraArgTs>(Args)...);
1361
1362 return PreservedAnalyses::all();
1363 }
1364};
1365
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001366/// A no-op pass template which simply forces a specific analysis result
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001367/// to be invalidated.
1368template <typename AnalysisT>
1369struct InvalidateAnalysisPass
1370 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> {
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001371 /// Run this pass over some unit of IR.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001372 ///
1373 /// This pass can be run over any unit of IR and use any analysis manager,
1374 /// provided they satisfy the basic API requirements. When this pass is
1375 /// created, these methods can be instantiated to satisfy whatever the
1376 /// context requires.
1377 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1378 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) {
1379 auto PA = PreservedAnalyses::all();
1380 PA.abandon<AnalysisT>();
1381 return PA;
1382 }
1383};
1384
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001385/// A utility pass that does nothing, but preserves no analyses.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001386///
1387/// Because this preserves no analyses, any analysis passes queried after this
1388/// pass runs will recompute fresh results.
1389struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> {
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001390 /// Run this pass over some unit of IR.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001391 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs>
1392 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) {
1393 return PreservedAnalyses::none();
1394 }
1395};
1396
1397/// A utility pass template that simply runs another pass multiple times.
1398///
1399/// This can be useful when debugging or testing passes. It also serves as an
1400/// example of how to extend the pass manager in ways beyond composition.
1401template <typename PassT>
1402class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> {
1403public:
1404 RepeatedPass(int Count, PassT P) : Count(Count), P(std::move(P)) {}
1405
1406 template <typename IRUnitT, typename AnalysisManagerT, typename... Ts>
Andrew Scull0372a572018-11-16 15:47:06 +00001407 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, Ts &&... Args) {
1408
1409 // Request PassInstrumentation from analysis manager, will use it to run
1410 // instrumenting callbacks for the passes later.
1411 // Here we use std::tuple wrapper over getResult which helps to extract
1412 // AnalysisManager's arguments out of the whole Args set.
1413 PassInstrumentation PI =
1414 detail::getAnalysisResult<PassInstrumentationAnalysis>(
1415 AM, IR, std::tuple<Ts...>(Args...));
1416
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001417 auto PA = PreservedAnalyses::all();
Andrew Scull0372a572018-11-16 15:47:06 +00001418 for (int i = 0; i < Count; ++i) {
1419 // Check the PassInstrumentation's BeforePass callbacks before running the
1420 // pass, skip its execution completely if asked to (callback returns
1421 // false).
1422 if (!PI.runBeforePass<IRUnitT>(P, IR))
1423 continue;
1424 PA.intersect(P.run(IR, AM, std::forward<Ts>(Args)...));
1425 PI.runAfterPass(P, IR);
1426 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001427 return PA;
1428 }
1429
1430private:
1431 int Count;
1432 PassT P;
1433};
1434
1435template <typename PassT>
1436RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) {
1437 return RepeatedPass<PassT>(Count, std::move(P));
1438}
1439
1440} // end namespace llvm
1441
1442#endif // LLVM_IR_PASSMANAGER_H