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