1 //===- PassManager.h - Pass management infrastructure -----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// 11 /// This header defines various interfaces for pass management in LLVM. There 12 /// is no "pass" interface in LLVM per se. Instead, an instance of any class 13 /// which supports a method to 'run' it over a unit of IR can be used as 14 /// a pass. A pass manager is generally a tool to collect a sequence of passes 15 /// which run over a particular IR construct, and run each of them in sequence 16 /// over each such construct in the containing IR construct. As there is no 17 /// containing IR construct for a Module, a manager for passes over modules 18 /// forms the base case which runs its managed passes in sequence over the 19 /// single module provided. 20 /// 21 /// The core IR library provides managers for running passes over 22 /// modules and functions. 23 /// 24 /// * FunctionPassManager can run over a Module, runs each pass over 25 /// a Function. 26 /// * ModulePassManager must be directly run, runs each pass over the Module. 27 /// 28 /// Note that the implementations of the pass managers use concept-based 29 /// polymorphism as outlined in the "Value Semantics and Concept-based 30 /// Polymorphism" talk (or its abbreviated sibling "Inheritance Is The Base 31 /// Class of Evil") by Sean Parent: 32 /// * http://github.com/sean-parent/sean-parent.github.com/wiki/Papers-and-Presentations 33 /// * http://www.youtube.com/watch?v=_BpMYeUFXv8 34 /// * http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil 35 /// 36 //===----------------------------------------------------------------------===// 37 38 #ifndef LLVM_IR_PASSMANAGER_H 39 #define LLVM_IR_PASSMANAGER_H 40 41 #include "llvm/ADT/DenseMap.h" 42 #include "llvm/ADT/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/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 62 namespace 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. 70 struct 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. 80 struct 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. 91 template <typename IRUnitT> class AllAnalysesOn { 92 public: 93 static AnalysisSetKey *ID() { return &SetKey; } 94 95 private: 96 static AnalysisSetKey SetKey; 97 }; 98 99 template <typename IRUnitT> AnalysisSetKey AllAnalysesOn<IRUnitT>::SetKey; 100 101 extern template class AllAnalysesOn<Module>; 102 extern 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. 114 class CFGAnalyses { 115 public: 116 static AnalysisSetKey *ID() { return &SetKey; } 117 118 private: 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 /// ``` 153 class PreservedAnalyses { 154 public: 155 /// \brief Convenience factory function for the empty preserved set. 156 static PreservedAnalyses none() { return PreservedAnalyses(); } 157 158 /// \brief Construct a special preserved set that preserves all passes. 159 static PreservedAnalyses all() { 160 PreservedAnalyses PA; 161 PA.PreservedIDs.insert(&AllAnalysesKey); 162 return PA; 163 } 164 165 /// Mark an analysis as preserved. 166 template <typename AnalysisT> void preserve() { preserve(AnalysisT::ID()); } 167 168 /// \brief Given an analysis's ID, mark the analysis as preserved, adding it 169 /// to the set. 170 void preserve(AnalysisKey *ID) { 171 // Clear this ID from the explicit not-preserved set if present. 172 NotPreservedAnalysisIDs.erase(ID); 173 174 // If we're not already preserving all analyses (other than those in 175 // NotPreservedAnalysisIDs). 176 if (!areAllPreserved()) 177 PreservedIDs.insert(ID); 178 } 179 180 /// Mark an analysis set as preserved. 181 template <typename AnalysisSetT> void preserveSet() { 182 preserveSet(AnalysisSetT::ID()); 183 } 184 185 /// Mark an analysis set as preserved using its ID. 186 void preserveSet(AnalysisSetKey *ID) { 187 // If we're not already in the saturated 'all' state, add this set. 188 if (!areAllPreserved()) 189 PreservedIDs.insert(ID); 190 } 191 192 /// Mark an analysis as abandoned. 193 /// 194 /// An abandoned analysis is not preserved, even if it is nominally covered 195 /// by some other set or was previously explicitly marked as preserved. 196 /// 197 /// Note that you can only abandon a specific analysis, not a *set* of 198 /// analyses. 199 template <typename AnalysisT> void abandon() { abandon(AnalysisT::ID()); } 200 201 /// Mark an analysis as abandoned using its ID. 202 /// 203 /// An abandoned analysis is not preserved, even if it is nominally covered 204 /// by some other set or was previously explicitly marked as preserved. 205 /// 206 /// Note that you can only abandon a specific analysis, not a *set* of 207 /// analyses. 208 void abandon(AnalysisKey *ID) { 209 PreservedIDs.erase(ID); 210 NotPreservedAnalysisIDs.insert(ID); 211 } 212 213 /// \brief Intersect this set with another in place. 214 /// 215 /// This is a mutating operation on this preserved set, removing all 216 /// preserved passes which are not also preserved in the argument. 217 void intersect(const PreservedAnalyses &Arg) { 218 if (Arg.areAllPreserved()) 219 return; 220 if (areAllPreserved()) { 221 *this = Arg; 222 return; 223 } 224 // The intersection requires the *union* of the explicitly not-preserved 225 // IDs and the *intersection* of the preserved IDs. 226 for (auto ID : Arg.NotPreservedAnalysisIDs) { 227 PreservedIDs.erase(ID); 228 NotPreservedAnalysisIDs.insert(ID); 229 } 230 for (auto ID : PreservedIDs) 231 if (!Arg.PreservedIDs.count(ID)) 232 PreservedIDs.erase(ID); 233 } 234 235 /// \brief Intersect this set with a temporary other set in place. 236 /// 237 /// This is a mutating operation on this preserved set, removing all 238 /// preserved passes which are not also preserved in the argument. 239 void intersect(PreservedAnalyses &&Arg) { 240 if (Arg.areAllPreserved()) 241 return; 242 if (areAllPreserved()) { 243 *this = std::move(Arg); 244 return; 245 } 246 // The intersection requires the *union* of the explicitly not-preserved 247 // IDs and the *intersection* of the preserved IDs. 248 for (auto ID : Arg.NotPreservedAnalysisIDs) { 249 PreservedIDs.erase(ID); 250 NotPreservedAnalysisIDs.insert(ID); 251 } 252 for (auto ID : PreservedIDs) 253 if (!Arg.PreservedIDs.count(ID)) 254 PreservedIDs.erase(ID); 255 } 256 257 /// A checker object that makes it easy to query for whether an analysis or 258 /// some set covering it is preserved. 259 class PreservedAnalysisChecker { 260 friend class PreservedAnalyses; 261 262 const PreservedAnalyses &PA; 263 AnalysisKey *const ID; 264 const bool IsAbandoned; 265 266 /// A PreservedAnalysisChecker is tied to a particular Analysis because 267 /// `preserved()` and `preservedSet()` both return false if the Analysis 268 /// was abandoned. 269 PreservedAnalysisChecker(const PreservedAnalyses &PA, AnalysisKey *ID) 270 : PA(PA), ID(ID), IsAbandoned(PA.NotPreservedAnalysisIDs.count(ID)) {} 271 272 public: 273 /// Returns true if the checker's analysis was not abandoned and either 274 /// - the analysis is explicitly preserved or 275 /// - all analyses are preserved. 276 bool preserved() { 277 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) || 278 PA.PreservedIDs.count(ID)); 279 } 280 281 /// Returns true if the checker's analysis was not abandoned and either 282 /// - \p AnalysisSetT is explicitly preserved or 283 /// - all analyses are preserved. 284 template <typename AnalysisSetT> bool preservedSet() { 285 AnalysisSetKey *SetID = AnalysisSetT::ID(); 286 return !IsAbandoned && (PA.PreservedIDs.count(&AllAnalysesKey) || 287 PA.PreservedIDs.count(SetID)); 288 } 289 }; 290 291 /// Build a checker for this `PreservedAnalyses` and the specified analysis 292 /// type. 293 /// 294 /// You can use the returned object to query whether an analysis was 295 /// preserved. See the example in the comment on `PreservedAnalysis`. 296 template <typename AnalysisT> PreservedAnalysisChecker getChecker() const { 297 return PreservedAnalysisChecker(*this, AnalysisT::ID()); 298 } 299 300 /// Build a checker for this `PreservedAnalyses` and the specified analysis 301 /// ID. 302 /// 303 /// You can use the returned object to query whether an analysis was 304 /// preserved. See the example in the comment on `PreservedAnalysis`. 305 PreservedAnalysisChecker getChecker(AnalysisKey *ID) const { 306 return PreservedAnalysisChecker(*this, ID); 307 } 308 309 /// Test whether all analyses are preserved (and none are abandoned). 310 /// 311 /// This is used primarily to optimize for the common case of a transformation 312 /// which makes no changes to the IR. 313 bool areAllPreserved() const { 314 return NotPreservedAnalysisIDs.empty() && 315 PreservedIDs.count(&AllAnalysesKey); 316 } 317 318 /// Directly test whether a set of analyses is preserved. 319 /// 320 /// This is only true when no analyses have been explicitly abandoned. 321 template <typename AnalysisSetT> bool allAnalysesInSetPreserved() const { 322 return allAnalysesInSetPreserved(AnalysisSetT::ID()); 323 } 324 325 /// Directly test whether a set of analyses is preserved. 326 /// 327 /// This is only true when no analyses have been explicitly abandoned. 328 bool allAnalysesInSetPreserved(AnalysisSetKey *SetID) const { 329 return NotPreservedAnalysisIDs.empty() && 330 (PreservedIDs.count(&AllAnalysesKey) || PreservedIDs.count(SetID)); 331 } 332 333 private: 334 /// A special key used to indicate all analyses. 335 static AnalysisSetKey AllAnalysesKey; 336 337 /// The IDs of analyses and analysis sets that are preserved. 338 SmallPtrSet<void *, 2> PreservedIDs; 339 340 /// The IDs of explicitly not-preserved analyses. 341 /// 342 /// If an analysis in this set is covered by a set in `PreservedIDs`, we 343 /// consider it not-preserved. That is, `NotPreservedAnalysisIDs` always 344 /// "wins" over analysis sets in `PreservedIDs`. 345 /// 346 /// Also, a given ID should never occur both here and in `PreservedIDs`. 347 SmallPtrSet<AnalysisKey *, 2> NotPreservedAnalysisIDs; 348 }; 349 350 // Forward declare the analysis manager template. 351 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager; 352 353 /// A CRTP mix-in to automatically provide informational APIs needed for 354 /// passes. 355 /// 356 /// This provides some boilerplate for types that are passes. 357 template <typename DerivedT> struct PassInfoMixin { 358 /// Gets the name of the pass we are mixed into. 359 static StringRef name() { 360 static_assert(std::is_base_of<PassInfoMixin, DerivedT>::value, 361 "Must pass the derived type as the template argument!"); 362 StringRef Name = getTypeName<DerivedT>(); 363 if (Name.startswith("llvm::")) 364 Name = Name.drop_front(strlen("llvm::")); 365 return Name; 366 } 367 }; 368 369 /// A CRTP mix-in that provides informational APIs needed for analysis passes. 370 /// 371 /// This provides some boilerplate for types that are analysis passes. It 372 /// automatically mixes in \c PassInfoMixin. 373 template <typename DerivedT> 374 struct AnalysisInfoMixin : PassInfoMixin<DerivedT> { 375 /// Returns an opaque, unique ID for this analysis type. 376 /// 377 /// This ID is a pointer type that is guaranteed to be 8-byte aligned and thus 378 /// suitable for use in sets, maps, and other data structures that use the low 379 /// bits of pointers. 380 /// 381 /// Note that this requires the derived type provide a static \c AnalysisKey 382 /// member called \c Key. 383 /// 384 /// FIXME: The only reason the mixin type itself can't declare the Key value 385 /// is that some compilers cannot correctly unique a templated static variable 386 /// so it has the same addresses in each instantiation. The only currently 387 /// known platform with this limitation is Windows DLL builds, specifically 388 /// building each part of LLVM as a DLL. If we ever remove that build 389 /// configuration, this mixin can provide the static key as well. 390 static AnalysisKey *ID() { 391 static_assert(std::is_base_of<AnalysisInfoMixin, DerivedT>::value, 392 "Must pass the derived type as the template argument!"); 393 return &DerivedT::Key; 394 } 395 }; 396 397 /// \brief Manages a sequence of passes over a particular unit of IR. 398 /// 399 /// A pass manager contains a sequence of passes to run over a particular unit 400 /// of IR (e.g. Functions, Modules). It is itself a valid pass over that unit of 401 /// IR, and when run over some given IR will run each of its contained passes in 402 /// sequence. Pass managers are the primary and most basic building block of a 403 /// pass pipeline. 404 /// 405 /// When you run a pass manager, you provide an \c AnalysisManager<IRUnitT> 406 /// argument. The pass manager will propagate that analysis manager to each 407 /// pass it runs, and will call the analysis manager's invalidation routine with 408 /// the PreservedAnalyses of each pass it runs. 409 template <typename IRUnitT, 410 typename AnalysisManagerT = AnalysisManager<IRUnitT>, 411 typename... ExtraArgTs> 412 class PassManager : public PassInfoMixin< 413 PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...>> { 414 public: 415 /// \brief Construct a pass manager. 416 /// 417 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs(). 418 explicit PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {} 419 420 // FIXME: These are equivalent to the default move constructor/move 421 // assignment. However, using = default triggers linker errors due to the 422 // explicit instantiations below. Find away to use the default and remove the 423 // duplicated code here. 424 PassManager(PassManager &&Arg) 425 : Passes(std::move(Arg.Passes)), 426 DebugLogging(std::move(Arg.DebugLogging)) {} 427 428 PassManager &operator=(PassManager &&RHS) { 429 Passes = std::move(RHS.Passes); 430 DebugLogging = std::move(RHS.DebugLogging); 431 return *this; 432 } 433 434 /// \brief Run all of the passes in this manager over the given unit of IR. 435 /// ExtraArgs are passed to each pass. 436 PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, 437 ExtraArgTs... ExtraArgs) { 438 PreservedAnalyses PA = PreservedAnalyses::all(); 439 440 if (DebugLogging) 441 dbgs() << "Starting " << getTypeName<IRUnitT>() << " pass manager run.\n"; 442 443 for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) { 444 if (DebugLogging) 445 dbgs() << "Running pass: " << Passes[Idx]->name() << " on " 446 << IR.getName() << "\n"; 447 448 PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM, ExtraArgs...); 449 450 // Update the analysis manager as each pass runs and potentially 451 // invalidates analyses. 452 AM.invalidate(IR, PassPA); 453 454 // Finally, intersect the preserved analyses to compute the aggregate 455 // preserved set for this pass manager. 456 PA.intersect(std::move(PassPA)); 457 458 // FIXME: Historically, the pass managers all called the LLVM context's 459 // yield function here. We don't have a generic way to acquire the 460 // context and it isn't yet clear what the right pattern is for yielding 461 // in the new pass manager so it is currently omitted. 462 //IR.getContext().yield(); 463 } 464 465 // Invaliadtion was handled after each pass in the above loop for the 466 // current unit of IR. Therefore, the remaining analysis results in the 467 // AnalysisManager are preserved. We mark this with a set so that we don't 468 // need to inspect each one individually. 469 PA.preserveSet<AllAnalysesOn<IRUnitT>>(); 470 471 if (DebugLogging) 472 dbgs() << "Finished " << getTypeName<IRUnitT>() << " pass manager run.\n"; 473 474 return PA; 475 } 476 477 template <typename PassT> void addPass(PassT Pass) { 478 using PassModelT = 479 detail::PassModel<IRUnitT, PassT, PreservedAnalyses, AnalysisManagerT, 480 ExtraArgTs...>; 481 482 Passes.emplace_back(new PassModelT(std::move(Pass))); 483 } 484 485 private: 486 using PassConceptT = 487 detail::PassConcept<IRUnitT, AnalysisManagerT, ExtraArgTs...>; 488 489 std::vector<std::unique_ptr<PassConceptT>> Passes; 490 491 /// \brief Flag indicating whether we should do debug logging. 492 bool DebugLogging; 493 }; 494 495 extern template class PassManager<Module>; 496 497 /// \brief Convenience typedef for a pass manager over modules. 498 using ModulePassManager = PassManager<Module>; 499 500 extern template class PassManager<Function>; 501 502 /// \brief Convenience typedef for a pass manager over functions. 503 using FunctionPassManager = PassManager<Function>; 504 505 /// \brief A container for analyses that lazily runs them and caches their 506 /// results. 507 /// 508 /// This class can manage analyses for any IR unit where the address of the IR 509 /// unit sufficies as its identity. 510 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager { 511 public: 512 class Invalidator; 513 514 private: 515 // Now that we've defined our invalidator, we can define the concept types. 516 using ResultConceptT = 517 detail::AnalysisResultConcept<IRUnitT, PreservedAnalyses, Invalidator>; 518 using PassConceptT = 519 detail::AnalysisPassConcept<IRUnitT, PreservedAnalyses, Invalidator, 520 ExtraArgTs...>; 521 522 /// \brief List of analysis pass IDs and associated concept pointers. 523 /// 524 /// Requires iterators to be valid across appending new entries and arbitrary 525 /// erases. Provides the analysis ID to enable finding iterators to a given 526 /// entry in maps below, and provides the storage for the actual result 527 /// concept. 528 using AnalysisResultListT = 529 std::list<std::pair<AnalysisKey *, std::unique_ptr<ResultConceptT>>>; 530 531 /// \brief Map type from IRUnitT pointer to our custom list type. 532 using AnalysisResultListMapT = DenseMap<IRUnitT *, AnalysisResultListT>; 533 534 /// \brief Map type from a pair of analysis ID and IRUnitT pointer to an 535 /// iterator into a particular result list (which is where the actual analysis 536 /// result is stored). 537 using AnalysisResultMapT = 538 DenseMap<std::pair<AnalysisKey *, IRUnitT *>, 539 typename AnalysisResultListT::iterator>; 540 541 public: 542 /// API to communicate dependencies between analyses during invalidation. 543 /// 544 /// When an analysis result embeds handles to other analysis results, it 545 /// needs to be invalidated both when its own information isn't preserved and 546 /// when any of its embedded analysis results end up invalidated. We pass an 547 /// \c Invalidator object as an argument to \c invalidate() in order to let 548 /// the analysis results themselves define the dependency graph on the fly. 549 /// This lets us avoid building building an explicit representation of the 550 /// dependencies between analysis results. 551 class Invalidator { 552 public: 553 /// Trigger the invalidation of some other analysis pass if not already 554 /// handled and return whether it was in fact invalidated. 555 /// 556 /// This is expected to be called from within a given analysis result's \c 557 /// invalidate method to trigger a depth-first walk of all inter-analysis 558 /// dependencies. The same \p IR unit and \p PA passed to that result's \c 559 /// invalidate method should in turn be provided to this routine. 560 /// 561 /// The first time this is called for a given analysis pass, it will call 562 /// the corresponding result's \c invalidate method. Subsequent calls will 563 /// use a cache of the results of that initial call. It is an error to form 564 /// cyclic dependencies between analysis results. 565 /// 566 /// This returns true if the given analysis's result is invalid. Any 567 /// dependecies on it will become invalid as a result. 568 template <typename PassT> 569 bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA) { 570 using ResultModelT = 571 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, 572 PreservedAnalyses, Invalidator>; 573 574 return invalidateImpl<ResultModelT>(PassT::ID(), IR, PA); 575 } 576 577 /// A type-erased variant of the above invalidate method with the same core 578 /// API other than passing an analysis ID rather than an analysis type 579 /// parameter. 580 /// 581 /// This is sadly less efficient than the above routine, which leverages 582 /// the type parameter to avoid the type erasure overhead. 583 bool invalidate(AnalysisKey *ID, IRUnitT &IR, const PreservedAnalyses &PA) { 584 return invalidateImpl<>(ID, IR, PA); 585 } 586 587 private: 588 friend class AnalysisManager; 589 590 template <typename ResultT = ResultConceptT> 591 bool invalidateImpl(AnalysisKey *ID, IRUnitT &IR, 592 const PreservedAnalyses &PA) { 593 // If we've already visited this pass, return true if it was invalidated 594 // and false otherwise. 595 auto IMapI = IsResultInvalidated.find(ID); 596 if (IMapI != IsResultInvalidated.end()) 597 return IMapI->second; 598 599 // Otherwise look up the result object. 600 auto RI = Results.find({ID, &IR}); 601 assert(RI != Results.end() && 602 "Trying to invalidate a dependent result that isn't in the " 603 "manager's cache is always an error, likely due to a stale result " 604 "handle!"); 605 606 auto &Result = static_cast<ResultT &>(*RI->second->second); 607 608 // Insert into the map whether the result should be invalidated and return 609 // that. Note that we cannot reuse IMapI and must do a fresh insert here, 610 // as calling invalidate could (recursively) insert things into the map, 611 // making any iterator or reference invalid. 612 bool Inserted; 613 std::tie(IMapI, Inserted) = 614 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, *this)}); 615 (void)Inserted; 616 assert(Inserted && "Should not have already inserted this ID, likely " 617 "indicates a dependency cycle!"); 618 return IMapI->second; 619 } 620 621 Invalidator(SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated, 622 const AnalysisResultMapT &Results) 623 : IsResultInvalidated(IsResultInvalidated), Results(Results) {} 624 625 SmallDenseMap<AnalysisKey *, bool, 8> &IsResultInvalidated; 626 const AnalysisResultMapT &Results; 627 }; 628 629 /// \brief Construct an empty analysis manager. 630 /// 631 /// If \p DebugLogging is true, we'll log our progress to llvm::dbgs(). 632 AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {} 633 AnalysisManager(AnalysisManager &&) = default; 634 AnalysisManager &operator=(AnalysisManager &&) = default; 635 636 /// \brief Returns true if the analysis manager has an empty results cache. 637 bool empty() const { 638 assert(AnalysisResults.empty() == AnalysisResultLists.empty() && 639 "The storage and index of analysis results disagree on how many " 640 "there are!"); 641 return AnalysisResults.empty(); 642 } 643 644 /// \brief Clear any cached analysis results for a single unit of IR. 645 /// 646 /// This doesn't invalidate, but instead simply deletes, the relevant results. 647 /// It is useful when the IR is being removed and we want to clear out all the 648 /// memory pinned for it. 649 void clear(IRUnitT &IR) { 650 if (DebugLogging) 651 dbgs() << "Clearing all analysis results for: " << IR.getName() << "\n"; 652 653 auto ResultsListI = AnalysisResultLists.find(&IR); 654 if (ResultsListI == AnalysisResultLists.end()) 655 return; 656 // Delete the map entries that point into the results list. 657 for (auto &IDAndResult : ResultsListI->second) 658 AnalysisResults.erase({IDAndResult.first, &IR}); 659 660 // And actually destroy and erase the results associated with this IR. 661 AnalysisResultLists.erase(ResultsListI); 662 } 663 664 /// \brief Clear all analysis results cached by this AnalysisManager. 665 /// 666 /// Like \c clear(IRUnitT&), this doesn't invalidate the results; it simply 667 /// deletes them. This lets you clean up the AnalysisManager when the set of 668 /// IR units itself has potentially changed, and thus we can't even look up a 669 /// a result and invalidate/clear it directly. 670 void clear() { 671 AnalysisResults.clear(); 672 AnalysisResultLists.clear(); 673 } 674 675 /// \brief Get the result of an analysis pass for a given IR unit. 676 /// 677 /// Runs the analysis if a cached result is not available. 678 template <typename PassT> 679 typename PassT::Result &getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs) { 680 assert(AnalysisPasses.count(PassT::ID()) && 681 "This analysis pass was not registered prior to being queried"); 682 ResultConceptT &ResultConcept = 683 getResultImpl(PassT::ID(), IR, ExtraArgs...); 684 685 using ResultModelT = 686 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, 687 PreservedAnalyses, Invalidator>; 688 689 return static_cast<ResultModelT &>(ResultConcept).Result; 690 } 691 692 /// \brief Get the cached result of an analysis pass for a given IR unit. 693 /// 694 /// This method never runs the analysis. 695 /// 696 /// \returns null if there is no cached result. 697 template <typename PassT> 698 typename PassT::Result *getCachedResult(IRUnitT &IR) const { 699 assert(AnalysisPasses.count(PassT::ID()) && 700 "This analysis pass was not registered prior to being queried"); 701 702 ResultConceptT *ResultConcept = getCachedResultImpl(PassT::ID(), IR); 703 if (!ResultConcept) 704 return nullptr; 705 706 using ResultModelT = 707 detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result, 708 PreservedAnalyses, Invalidator>; 709 710 return &static_cast<ResultModelT *>(ResultConcept)->Result; 711 } 712 713 /// \brief Register an analysis pass with the manager. 714 /// 715 /// The parameter is a callable whose result is an analysis pass. This allows 716 /// passing in a lambda to construct the analysis. 717 /// 718 /// The analysis type to register is the type returned by calling the \c 719 /// PassBuilder argument. If that type has already been registered, then the 720 /// argument will not be called and this function will return false. 721 /// Otherwise, we register the analysis returned by calling \c PassBuilder(), 722 /// and this function returns true. 723 /// 724 /// (Note: Although the return value of this function indicates whether or not 725 /// an analysis was previously registered, there intentionally isn't a way to 726 /// query this directly. Instead, you should just register all the analyses 727 /// you might want and let this class run them lazily. This idiom lets us 728 /// minimize the number of times we have to look up analyses in our 729 /// hashtable.) 730 template <typename PassBuilderT> 731 bool registerPass(PassBuilderT &&PassBuilder) { 732 using PassT = decltype(PassBuilder()); 733 using PassModelT = 734 detail::AnalysisPassModel<IRUnitT, PassT, PreservedAnalyses, 735 Invalidator, ExtraArgTs...>; 736 737 auto &PassPtr = AnalysisPasses[PassT::ID()]; 738 if (PassPtr) 739 // Already registered this pass type! 740 return false; 741 742 // Construct a new model around the instance returned by the builder. 743 PassPtr.reset(new PassModelT(PassBuilder())); 744 return true; 745 } 746 747 /// \brief Invalidate a specific analysis pass for an IR module. 748 /// 749 /// Note that the analysis result can disregard invalidation, if it determines 750 /// it is in fact still valid. 751 template <typename PassT> void invalidate(IRUnitT &IR) { 752 assert(AnalysisPasses.count(PassT::ID()) && 753 "This analysis pass was not registered prior to being invalidated"); 754 invalidateImpl(PassT::ID(), IR); 755 } 756 757 /// \brief Invalidate cached analyses for an IR unit. 758 /// 759 /// Walk through all of the analyses pertaining to this unit of IR and 760 /// invalidate them, unless they are preserved by the PreservedAnalyses set. 761 void invalidate(IRUnitT &IR, const PreservedAnalyses &PA) { 762 // We're done if all analyses on this IR unit are preserved. 763 if (PA.allAnalysesInSetPreserved<AllAnalysesOn<IRUnitT>>()) 764 return; 765 766 if (DebugLogging) 767 dbgs() << "Invalidating all non-preserved analyses for: " << IR.getName() 768 << "\n"; 769 770 // Track whether each analysis's result is invalidated in 771 // IsResultInvalidated. 772 SmallDenseMap<AnalysisKey *, bool, 8> IsResultInvalidated; 773 Invalidator Inv(IsResultInvalidated, AnalysisResults); 774 AnalysisResultListT &ResultsList = AnalysisResultLists[&IR]; 775 for (auto &AnalysisResultPair : ResultsList) { 776 // This is basically the same thing as Invalidator::invalidate, but we 777 // can't call it here because we're operating on the type-erased result. 778 // Moreover if we instead called invalidate() directly, it would do an 779 // unnecessary look up in ResultsList. 780 AnalysisKey *ID = AnalysisResultPair.first; 781 auto &Result = *AnalysisResultPair.second; 782 783 auto IMapI = IsResultInvalidated.find(ID); 784 if (IMapI != IsResultInvalidated.end()) 785 // This result was already handled via the Invalidator. 786 continue; 787 788 // Try to invalidate the result, giving it the Invalidator so it can 789 // recursively query for any dependencies it has and record the result. 790 // Note that we cannot reuse 'IMapI' here or pre-insert the ID, as 791 // Result.invalidate may insert things into the map, invalidating our 792 // iterator. 793 bool Inserted = 794 IsResultInvalidated.insert({ID, Result.invalidate(IR, PA, Inv)}) 795 .second; 796 (void)Inserted; 797 assert(Inserted && "Should never have already inserted this ID, likely " 798 "indicates a cycle!"); 799 } 800 801 // Now erase the results that were marked above as invalidated. 802 if (!IsResultInvalidated.empty()) { 803 for (auto I = ResultsList.begin(), E = ResultsList.end(); I != E;) { 804 AnalysisKey *ID = I->first; 805 if (!IsResultInvalidated.lookup(ID)) { 806 ++I; 807 continue; 808 } 809 810 if (DebugLogging) 811 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name() 812 << " on " << IR.getName() << "\n"; 813 814 I = ResultsList.erase(I); 815 AnalysisResults.erase({ID, &IR}); 816 } 817 } 818 819 if (ResultsList.empty()) 820 AnalysisResultLists.erase(&IR); 821 } 822 823 private: 824 /// \brief Look up a registered analysis pass. 825 PassConceptT &lookUpPass(AnalysisKey *ID) { 826 typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(ID); 827 assert(PI != AnalysisPasses.end() && 828 "Analysis passes must be registered prior to being queried!"); 829 return *PI->second; 830 } 831 832 /// \brief Look up a registered analysis pass. 833 const PassConceptT &lookUpPass(AnalysisKey *ID) const { 834 typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(ID); 835 assert(PI != AnalysisPasses.end() && 836 "Analysis passes must be registered prior to being queried!"); 837 return *PI->second; 838 } 839 840 /// \brief Get an analysis result, running the pass if necessary. 841 ResultConceptT &getResultImpl(AnalysisKey *ID, IRUnitT &IR, 842 ExtraArgTs... ExtraArgs) { 843 typename AnalysisResultMapT::iterator RI; 844 bool Inserted; 845 std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair( 846 std::make_pair(ID, &IR), typename AnalysisResultListT::iterator())); 847 848 // If we don't have a cached result for this function, look up the pass and 849 // run it to produce a result, which we then add to the cache. 850 if (Inserted) { 851 auto &P = this->lookUpPass(ID); 852 if (DebugLogging) 853 dbgs() << "Running analysis: " << P.name() << " on " << IR.getName() 854 << "\n"; 855 AnalysisResultListT &ResultList = AnalysisResultLists[&IR]; 856 ResultList.emplace_back(ID, P.run(IR, *this, ExtraArgs...)); 857 858 // P.run may have inserted elements into AnalysisResults and invalidated 859 // RI. 860 RI = AnalysisResults.find({ID, &IR}); 861 assert(RI != AnalysisResults.end() && "we just inserted it!"); 862 863 RI->second = std::prev(ResultList.end()); 864 } 865 866 return *RI->second->second; 867 } 868 869 /// \brief Get a cached analysis result or return null. 870 ResultConceptT *getCachedResultImpl(AnalysisKey *ID, IRUnitT &IR) const { 871 typename AnalysisResultMapT::const_iterator RI = 872 AnalysisResults.find({ID, &IR}); 873 return RI == AnalysisResults.end() ? nullptr : &*RI->second->second; 874 } 875 876 /// \brief Invalidate a function pass result. 877 void invalidateImpl(AnalysisKey *ID, IRUnitT &IR) { 878 typename AnalysisResultMapT::iterator RI = 879 AnalysisResults.find({ID, &IR}); 880 if (RI == AnalysisResults.end()) 881 return; 882 883 if (DebugLogging) 884 dbgs() << "Invalidating analysis: " << this->lookUpPass(ID).name() 885 << " on " << IR.getName() << "\n"; 886 AnalysisResultLists[&IR].erase(RI->second); 887 AnalysisResults.erase(RI); 888 } 889 890 /// \brief Map type from module analysis pass ID to pass concept pointer. 891 using AnalysisPassMapT = 892 DenseMap<AnalysisKey *, std::unique_ptr<PassConceptT>>; 893 894 /// \brief Collection of module analysis passes, indexed by ID. 895 AnalysisPassMapT AnalysisPasses; 896 897 /// \brief Map from function to a list of function analysis results. 898 /// 899 /// Provides linear time removal of all analysis results for a function and 900 /// the ultimate storage for a particular cached analysis result. 901 AnalysisResultListMapT AnalysisResultLists; 902 903 /// \brief Map from an analysis ID and function to a particular cached 904 /// analysis result. 905 AnalysisResultMapT AnalysisResults; 906 907 /// \brief Indicates whether we log to \c llvm::dbgs(). 908 bool DebugLogging; 909 }; 910 911 extern template class AnalysisManager<Module>; 912 913 /// \brief Convenience typedef for the Module analysis manager. 914 using ModuleAnalysisManager = AnalysisManager<Module>; 915 916 extern template class AnalysisManager<Function>; 917 918 /// \brief Convenience typedef for the Function analysis manager. 919 using FunctionAnalysisManager = AnalysisManager<Function>; 920 921 /// \brief An analysis over an "outer" IR unit that provides access to an 922 /// analysis manager over an "inner" IR unit. The inner unit must be contained 923 /// in the outer unit. 924 /// 925 /// Fore example, InnerAnalysisManagerProxy<FunctionAnalysisManager, Module> is 926 /// an analysis over Modules (the "outer" unit) that provides access to a 927 /// Function analysis manager. The FunctionAnalysisManager is the "inner" 928 /// manager being proxied, and Functions are the "inner" unit. The inner/outer 929 /// relationship is valid because each Function is contained in one Module. 930 /// 931 /// If you're (transitively) within a pass manager for an IR unit U that 932 /// contains IR unit V, you should never use an analysis manager over V, except 933 /// via one of these proxies. 934 /// 935 /// Note that the proxy's result is a move-only RAII object. The validity of 936 /// the analyses in the inner analysis manager is tied to its lifetime. 937 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs> 938 class InnerAnalysisManagerProxy 939 : public AnalysisInfoMixin< 940 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>> { 941 public: 942 class Result { 943 public: 944 explicit Result(AnalysisManagerT &InnerAM) : InnerAM(&InnerAM) {} 945 946 Result(Result &&Arg) : InnerAM(std::move(Arg.InnerAM)) { 947 // We have to null out the analysis manager in the moved-from state 948 // because we are taking ownership of the responsibilty to clear the 949 // analysis state. 950 Arg.InnerAM = nullptr; 951 } 952 953 ~Result() { 954 // InnerAM is cleared in a moved from state where there is nothing to do. 955 if (!InnerAM) 956 return; 957 958 // Clear out the analysis manager if we're being destroyed -- it means we 959 // didn't even see an invalidate call when we got invalidated. 960 InnerAM->clear(); 961 } 962 963 Result &operator=(Result &&RHS) { 964 InnerAM = RHS.InnerAM; 965 // We have to null out the analysis manager in the moved-from state 966 // because we are taking ownership of the responsibilty to clear the 967 // analysis state. 968 RHS.InnerAM = nullptr; 969 return *this; 970 } 971 972 /// \brief Accessor for the analysis manager. 973 AnalysisManagerT &getManager() { return *InnerAM; } 974 975 /// \brief Handler for invalidation of the outer IR unit, \c IRUnitT. 976 /// 977 /// If the proxy analysis itself is not preserved, we assume that the set of 978 /// inner IR objects contained in IRUnit may have changed. In this case, 979 /// we have to call \c clear() on the inner analysis manager, as it may now 980 /// have stale pointers to its inner IR objects. 981 /// 982 /// Regardless of whether the proxy analysis is marked as preserved, all of 983 /// the analyses in the inner analysis manager are potentially invalidated 984 /// based on the set of preserved analyses. 985 bool invalidate( 986 IRUnitT &IR, const PreservedAnalyses &PA, 987 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &Inv); 988 989 private: 990 AnalysisManagerT *InnerAM; 991 }; 992 993 explicit InnerAnalysisManagerProxy(AnalysisManagerT &InnerAM) 994 : InnerAM(&InnerAM) {} 995 996 /// \brief Run the analysis pass and create our proxy result object. 997 /// 998 /// This doesn't do any interesting work; it is primarily used to insert our 999 /// proxy result object into the outer analysis cache so that we can proxy 1000 /// invalidation to the inner analysis manager. 1001 Result run(IRUnitT &IR, AnalysisManager<IRUnitT, ExtraArgTs...> &AM, 1002 ExtraArgTs...) { 1003 return Result(*InnerAM); 1004 } 1005 1006 private: 1007 friend AnalysisInfoMixin< 1008 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT>>; 1009 1010 static AnalysisKey Key; 1011 1012 AnalysisManagerT *InnerAM; 1013 }; 1014 1015 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs> 1016 AnalysisKey 1017 InnerAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key; 1018 1019 /// Provide the \c FunctionAnalysisManager to \c Module proxy. 1020 using FunctionAnalysisManagerModuleProxy = 1021 InnerAnalysisManagerProxy<FunctionAnalysisManager, Module>; 1022 1023 /// Specialization of the invalidate method for the \c 1024 /// FunctionAnalysisManagerModuleProxy's result. 1025 template <> 1026 bool FunctionAnalysisManagerModuleProxy::Result::invalidate( 1027 Module &M, const PreservedAnalyses &PA, 1028 ModuleAnalysisManager::Invalidator &Inv); 1029 1030 // Ensure the \c FunctionAnalysisManagerModuleProxy is provided as an extern 1031 // template. 1032 extern template class InnerAnalysisManagerProxy<FunctionAnalysisManager, 1033 Module>; 1034 1035 /// \brief An analysis over an "inner" IR unit that provides access to an 1036 /// analysis manager over a "outer" IR unit. The inner unit must be contained 1037 /// in the outer unit. 1038 /// 1039 /// For example OuterAnalysisManagerProxy<ModuleAnalysisManager, Function> is an 1040 /// analysis over Functions (the "inner" unit) which provides access to a Module 1041 /// analysis manager. The ModuleAnalysisManager is the "outer" manager being 1042 /// proxied, and Modules are the "outer" IR unit. The inner/outer relationship 1043 /// is valid because each Function is contained in one Module. 1044 /// 1045 /// This proxy only exposes the const interface of the outer analysis manager, 1046 /// to indicate that you cannot cause an outer analysis to run from within an 1047 /// inner pass. Instead, you must rely on the \c getCachedResult API. 1048 /// 1049 /// This proxy doesn't manage invalidation in any way -- that is handled by the 1050 /// recursive return path of each layer of the pass manager. A consequence of 1051 /// this is the outer analyses may be stale. We invalidate the outer analyses 1052 /// only when we're done running passes over the inner IR units. 1053 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs> 1054 class OuterAnalysisManagerProxy 1055 : public AnalysisInfoMixin< 1056 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>> { 1057 public: 1058 /// \brief Result proxy object for \c OuterAnalysisManagerProxy. 1059 class Result { 1060 public: 1061 explicit Result(const AnalysisManagerT &AM) : AM(&AM) {} 1062 1063 const AnalysisManagerT &getManager() const { return *AM; } 1064 1065 /// \brief Handle invalidation by ignoring it; this pass is immutable. 1066 bool invalidate( 1067 IRUnitT &, const PreservedAnalyses &, 1068 typename AnalysisManager<IRUnitT, ExtraArgTs...>::Invalidator &) { 1069 return false; 1070 } 1071 1072 /// Register a deferred invalidation event for when the outer analysis 1073 /// manager processes its invalidations. 1074 template <typename OuterAnalysisT, typename InvalidatedAnalysisT> 1075 void registerOuterAnalysisInvalidation() { 1076 AnalysisKey *OuterID = OuterAnalysisT::ID(); 1077 AnalysisKey *InvalidatedID = InvalidatedAnalysisT::ID(); 1078 1079 auto &InvalidatedIDList = OuterAnalysisInvalidationMap[OuterID]; 1080 // Note, this is a linear scan. If we end up with large numbers of 1081 // analyses that all trigger invalidation on the same outer analysis, 1082 // this entire system should be changed to some other deterministic 1083 // data structure such as a `SetVector` of a pair of pointers. 1084 auto InvalidatedIt = std::find(InvalidatedIDList.begin(), 1085 InvalidatedIDList.end(), InvalidatedID); 1086 if (InvalidatedIt == InvalidatedIDList.end()) 1087 InvalidatedIDList.push_back(InvalidatedID); 1088 } 1089 1090 /// Access the map from outer analyses to deferred invalidation requiring 1091 /// analyses. 1092 const SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> & 1093 getOuterInvalidations() const { 1094 return OuterAnalysisInvalidationMap; 1095 } 1096 1097 private: 1098 const AnalysisManagerT *AM; 1099 1100 /// A map from an outer analysis ID to the set of this IR-unit's analyses 1101 /// which need to be invalidated. 1102 SmallDenseMap<AnalysisKey *, TinyPtrVector<AnalysisKey *>, 2> 1103 OuterAnalysisInvalidationMap; 1104 }; 1105 1106 OuterAnalysisManagerProxy(const AnalysisManagerT &AM) : AM(&AM) {} 1107 1108 /// \brief Run the analysis pass and create our proxy result object. 1109 /// Nothing to see here, it just forwards the \c AM reference into the 1110 /// result. 1111 Result run(IRUnitT &, AnalysisManager<IRUnitT, ExtraArgTs...> &, 1112 ExtraArgTs...) { 1113 return Result(*AM); 1114 } 1115 1116 private: 1117 friend AnalysisInfoMixin< 1118 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>>; 1119 1120 static AnalysisKey Key; 1121 1122 const AnalysisManagerT *AM; 1123 }; 1124 1125 template <typename AnalysisManagerT, typename IRUnitT, typename... ExtraArgTs> 1126 AnalysisKey 1127 OuterAnalysisManagerProxy<AnalysisManagerT, IRUnitT, ExtraArgTs...>::Key; 1128 1129 extern template class OuterAnalysisManagerProxy<ModuleAnalysisManager, 1130 Function>; 1131 /// Provide the \c ModuleAnalysisManager to \c Function proxy. 1132 using ModuleAnalysisManagerFunctionProxy = 1133 OuterAnalysisManagerProxy<ModuleAnalysisManager, Function>; 1134 1135 /// \brief Trivial adaptor that maps from a module to its functions. 1136 /// 1137 /// Designed to allow composition of a FunctionPass(Manager) and 1138 /// a ModulePassManager, by running the FunctionPass(Manager) over every 1139 /// function in the module. 1140 /// 1141 /// Function passes run within this adaptor can rely on having exclusive access 1142 /// to the function they are run over. They should not read or modify any other 1143 /// functions! Other threads or systems may be manipulating other functions in 1144 /// the module, and so their state should never be relied on. 1145 /// FIXME: Make the above true for all of LLVM's actual passes, some still 1146 /// violate this principle. 1147 /// 1148 /// Function passes can also read the module containing the function, but they 1149 /// should not modify that module outside of the use lists of various globals. 1150 /// For example, a function pass is not permitted to add functions to the 1151 /// module. 1152 /// FIXME: Make the above true for all of LLVM's actual passes, some still 1153 /// violate this principle. 1154 /// 1155 /// Note that although function passes can access module analyses, module 1156 /// analyses are not invalidated while the function passes are running, so they 1157 /// may be stale. Function analyses will not be stale. 1158 template <typename FunctionPassT> 1159 class ModuleToFunctionPassAdaptor 1160 : public PassInfoMixin<ModuleToFunctionPassAdaptor<FunctionPassT>> { 1161 public: 1162 explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass) 1163 : Pass(std::move(Pass)) {} 1164 1165 /// \brief Runs the function pass across every function in the module. 1166 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) { 1167 FunctionAnalysisManager &FAM = 1168 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1169 1170 PreservedAnalyses PA = PreservedAnalyses::all(); 1171 for (Function &F : M) { 1172 if (F.isDeclaration()) 1173 continue; 1174 1175 PreservedAnalyses PassPA = Pass.run(F, FAM); 1176 1177 // We know that the function pass couldn't have invalidated any other 1178 // function's analyses (that's the contract of a function pass), so 1179 // directly handle the function analysis manager's invalidation here. 1180 FAM.invalidate(F, PassPA); 1181 1182 // Then intersect the preserved set so that invalidation of module 1183 // analyses will eventually occur when the module pass completes. 1184 PA.intersect(std::move(PassPA)); 1185 } 1186 1187 // The FunctionAnalysisManagerModuleProxy is preserved because (we assume) 1188 // the function passes we ran didn't add or remove any functions. 1189 // 1190 // We also preserve all analyses on Functions, because we did all the 1191 // invalidation we needed to do above. 1192 PA.preserveSet<AllAnalysesOn<Function>>(); 1193 PA.preserve<FunctionAnalysisManagerModuleProxy>(); 1194 return PA; 1195 } 1196 1197 private: 1198 FunctionPassT Pass; 1199 }; 1200 1201 /// \brief A function to deduce a function pass type and wrap it in the 1202 /// templated adaptor. 1203 template <typename FunctionPassT> 1204 ModuleToFunctionPassAdaptor<FunctionPassT> 1205 createModuleToFunctionPassAdaptor(FunctionPassT Pass) { 1206 return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass)); 1207 } 1208 1209 /// \brief A utility pass template to force an analysis result to be available. 1210 /// 1211 /// If there are extra arguments at the pass's run level there may also be 1212 /// extra arguments to the analysis manager's \c getResult routine. We can't 1213 /// guess how to effectively map the arguments from one to the other, and so 1214 /// this specialization just ignores them. 1215 /// 1216 /// Specific patterns of run-method extra arguments and analysis manager extra 1217 /// arguments will have to be defined as appropriate specializations. 1218 template <typename AnalysisT, typename IRUnitT, 1219 typename AnalysisManagerT = AnalysisManager<IRUnitT>, 1220 typename... ExtraArgTs> 1221 struct RequireAnalysisPass 1222 : PassInfoMixin<RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT, 1223 ExtraArgTs...>> { 1224 /// \brief Run this pass over some unit of IR. 1225 /// 1226 /// This pass can be run over any unit of IR and use any analysis manager 1227 /// provided they satisfy the basic API requirements. When this pass is 1228 /// created, these methods can be instantiated to satisfy whatever the 1229 /// context requires. 1230 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, 1231 ExtraArgTs &&... Args) { 1232 (void)AM.template getResult<AnalysisT>(Arg, 1233 std::forward<ExtraArgTs>(Args)...); 1234 1235 return PreservedAnalyses::all(); 1236 } 1237 }; 1238 1239 /// \brief A no-op pass template which simply forces a specific analysis result 1240 /// to be invalidated. 1241 template <typename AnalysisT> 1242 struct InvalidateAnalysisPass 1243 : PassInfoMixin<InvalidateAnalysisPass<AnalysisT>> { 1244 /// \brief Run this pass over some unit of IR. 1245 /// 1246 /// This pass can be run over any unit of IR and use any analysis manager, 1247 /// provided they satisfy the basic API requirements. When this pass is 1248 /// created, these methods can be instantiated to satisfy whatever the 1249 /// context requires. 1250 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs> 1251 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, ExtraArgTs &&...) { 1252 auto PA = PreservedAnalyses::all(); 1253 PA.abandon<AnalysisT>(); 1254 return PA; 1255 } 1256 }; 1257 1258 /// \brief A utility pass that does nothing, but preserves no analyses. 1259 /// 1260 /// Because this preserves no analyses, any analysis passes queried after this 1261 /// pass runs will recompute fresh results. 1262 struct InvalidateAllAnalysesPass : PassInfoMixin<InvalidateAllAnalysesPass> { 1263 /// \brief Run this pass over some unit of IR. 1264 template <typename IRUnitT, typename AnalysisManagerT, typename... ExtraArgTs> 1265 PreservedAnalyses run(IRUnitT &, AnalysisManagerT &, ExtraArgTs &&...) { 1266 return PreservedAnalyses::none(); 1267 } 1268 }; 1269 1270 /// A utility pass template that simply runs another pass multiple times. 1271 /// 1272 /// This can be useful when debugging or testing passes. It also serves as an 1273 /// example of how to extend the pass manager in ways beyond composition. 1274 template <typename PassT> 1275 class RepeatedPass : public PassInfoMixin<RepeatedPass<PassT>> { 1276 public: 1277 RepeatedPass(int Count, PassT P) : Count(Count), P(std::move(P)) {} 1278 1279 template <typename IRUnitT, typename AnalysisManagerT, typename... Ts> 1280 PreservedAnalyses run(IRUnitT &Arg, AnalysisManagerT &AM, Ts &&... Args) { 1281 auto PA = PreservedAnalyses::all(); 1282 for (int i = 0; i < Count; ++i) 1283 PA.intersect(P.run(Arg, AM, std::forward<Ts>(Args)...)); 1284 return PA; 1285 } 1286 1287 private: 1288 int Count; 1289 PassT P; 1290 }; 1291 1292 template <typename PassT> 1293 RepeatedPass<PassT> createRepeatedPass(int Count, PassT P) { 1294 return RepeatedPass<PassT>(Count, std::move(P)); 1295 } 1296 1297 } // end namespace llvm 1298 1299 #endif // LLVM_IR_PASSMANAGER_H 1300