PassManager.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. #ifndef LLVM_IR_PASSMANAGER_H
  38. #define LLVM_IR_PASSMANAGER_H
  39. #include "llvm/ADT/DenseMap.h"
  40. #include "llvm/ADT/STLExtras.h"
  41. #include "llvm/ADT/SmallPtrSet.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/Module.h"
  44. #include "llvm/IR/PassManagerInternal.h"
  45. #include "llvm/Support/CommandLine.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Support/type_traits.h"
  49. #include <list>
  50. #include <memory>
  51. #include <vector>
  52. namespace llvm {
  53. class Module;
  54. class Function;
  55. /// \brief An abstract set of preserved analyses following a transformation pass
  56. /// run.
  57. ///
  58. /// When a transformation pass is run, it can return a set of analyses whose
  59. /// results were preserved by that transformation. The default set is "none",
  60. /// and preserving analyses must be done explicitly.
  61. ///
  62. /// There is also an explicit all state which can be used (for example) when
  63. /// the IR is not mutated at all.
  64. class PreservedAnalyses {
  65. public:
  66. // We have to explicitly define all the special member functions because MSVC
  67. // refuses to generate them.
  68. PreservedAnalyses() {}
  69. PreservedAnalyses(const PreservedAnalyses &Arg)
  70. : PreservedPassIDs(Arg.PreservedPassIDs) {}
  71. PreservedAnalyses(PreservedAnalyses &&Arg)
  72. : PreservedPassIDs(std::move(Arg.PreservedPassIDs)) {}
  73. friend void swap(PreservedAnalyses &LHS, PreservedAnalyses &RHS) {
  74. using std::swap;
  75. swap(LHS.PreservedPassIDs, RHS.PreservedPassIDs);
  76. }
  77. PreservedAnalyses &operator=(PreservedAnalyses RHS) {
  78. swap(*this, RHS);
  79. return *this;
  80. }
  81. /// \brief Convenience factory function for the empty preserved set.
  82. static PreservedAnalyses none() { return PreservedAnalyses(); }
  83. /// \brief Construct a special preserved set that preserves all passes.
  84. static PreservedAnalyses all() {
  85. PreservedAnalyses PA;
  86. PA.PreservedPassIDs.insert((void *)AllPassesID);
  87. return PA;
  88. }
  89. /// \brief Mark a particular pass as preserved, adding it to the set.
  90. template <typename PassT> void preserve() { preserve(PassT::ID()); }
  91. /// \brief Mark an abstract PassID as preserved, adding it to the set.
  92. void preserve(void *PassID) {
  93. if (!areAllPreserved())
  94. PreservedPassIDs.insert(PassID);
  95. }
  96. /// \brief Intersect this set with another in place.
  97. ///
  98. /// This is a mutating operation on this preserved set, removing all
  99. /// preserved passes which are not also preserved in the argument.
  100. void intersect(const PreservedAnalyses &Arg) {
  101. if (Arg.areAllPreserved())
  102. return;
  103. if (areAllPreserved()) {
  104. PreservedPassIDs = Arg.PreservedPassIDs;
  105. return;
  106. }
  107. for (void *P : PreservedPassIDs)
  108. if (!Arg.PreservedPassIDs.count(P))
  109. PreservedPassIDs.erase(P);
  110. }
  111. /// \brief Intersect this set with a temporary other set in place.
  112. ///
  113. /// This is a mutating operation on this preserved set, removing all
  114. /// preserved passes which are not also preserved in the argument.
  115. void intersect(PreservedAnalyses &&Arg) {
  116. if (Arg.areAllPreserved())
  117. return;
  118. if (areAllPreserved()) {
  119. PreservedPassIDs = std::move(Arg.PreservedPassIDs);
  120. return;
  121. }
  122. for (void *P : PreservedPassIDs)
  123. if (!Arg.PreservedPassIDs.count(P))
  124. PreservedPassIDs.erase(P);
  125. }
  126. /// \brief Query whether a pass is marked as preserved by this set.
  127. template <typename PassT> bool preserved() const {
  128. return preserved(PassT::ID());
  129. }
  130. /// \brief Query whether an abstract pass ID is marked as preserved by this
  131. /// set.
  132. bool preserved(void *PassID) const {
  133. return PreservedPassIDs.count((void *)AllPassesID) ||
  134. PreservedPassIDs.count(PassID);
  135. }
  136. /// \brief Test whether all passes are preserved.
  137. ///
  138. /// This is used primarily to optimize for the case of no changes which will
  139. /// common in many scenarios.
  140. bool areAllPreserved() const {
  141. return PreservedPassIDs.count((void *)AllPassesID);
  142. }
  143. private:
  144. // Note that this must not be -1 or -2 as those are already used by the
  145. // SmallPtrSet.
  146. static const uintptr_t AllPassesID = (intptr_t)(-3);
  147. SmallPtrSet<void *, 2> PreservedPassIDs;
  148. };
  149. // Forward declare the analysis manager template.
  150. template <typename IRUnitT> class AnalysisManager;
  151. /// \brief Manages a sequence of passes over units of IR.
  152. ///
  153. /// A pass manager contains a sequence of passes to run over units of IR. It is
  154. /// itself a valid pass over that unit of IR, and when over some given IR will
  155. /// run each pass in sequence. This is the primary and most basic building
  156. /// block of a pass pipeline.
  157. ///
  158. /// If it is run with an \c AnalysisManager<IRUnitT> argument, it will propagate
  159. /// that analysis manager to each pass it runs, as well as calling the analysis
  160. /// manager's invalidation routine with the PreservedAnalyses of each pass it
  161. /// runs.
  162. template <typename IRUnitT> class PassManager {
  163. public:
  164. /// \brief Construct a pass manager.
  165. ///
  166. /// It can be passed a flag to get debug logging as the passes are run.
  167. PassManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
  168. // We have to explicitly define all the special member functions because MSVC
  169. // refuses to generate them.
  170. PassManager(PassManager &&Arg)
  171. : Passes(std::move(Arg.Passes)),
  172. DebugLogging(std::move(Arg.DebugLogging)) {}
  173. PassManager &operator=(PassManager &&RHS) {
  174. Passes = std::move(RHS.Passes);
  175. DebugLogging = std::move(RHS.DebugLogging);
  176. return *this;
  177. }
  178. /// \brief Run all of the passes in this manager over the IR.
  179. PreservedAnalyses run(IRUnitT &IR, AnalysisManager<IRUnitT> *AM = nullptr) {
  180. PreservedAnalyses PA = PreservedAnalyses::all();
  181. if (DebugLogging)
  182. dbgs() << "Starting pass manager run.\n";
  183. for (unsigned Idx = 0, Size = Passes.size(); Idx != Size; ++Idx) {
  184. if (DebugLogging)
  185. dbgs() << "Running pass: " << Passes[Idx]->name() << "\n";
  186. PreservedAnalyses PassPA = Passes[Idx]->run(IR, AM);
  187. // If we have an active analysis manager at this level we want to ensure
  188. // we update it as each pass runs and potentially invalidates analyses.
  189. // We also update the preserved set of analyses based on what analyses we
  190. // have already handled the invalidation for here and don't need to
  191. // invalidate when finished.
  192. if (AM)
  193. PassPA = AM->invalidate(IR, std::move(PassPA));
  194. // Finally, we intersect the final preserved analyses to compute the
  195. // aggregate preserved set for this pass manager.
  196. PA.intersect(std::move(PassPA));
  197. // FIXME: Historically, the pass managers all called the LLVM context's
  198. // yield function here. We don't have a generic way to acquire the
  199. // context and it isn't yet clear what the right pattern is for yielding
  200. // in the new pass manager so it is currently omitted.
  201. //IR.getContext().yield();
  202. }
  203. if (DebugLogging)
  204. dbgs() << "Finished pass manager run.\n";
  205. return PA;
  206. }
  207. template <typename PassT> void addPass(PassT Pass) {
  208. typedef detail::PassModel<IRUnitT, PassT> PassModelT;
  209. Passes.emplace_back(new PassModelT(std::move(Pass)));
  210. }
  211. static StringRef name() { return "PassManager"; }
  212. private:
  213. typedef detail::PassConcept<IRUnitT> PassConceptT;
  214. PassManager(const PassManager &) = delete;
  215. PassManager &operator=(const PassManager &) = delete;
  216. std::vector<std::unique_ptr<PassConceptT>> Passes;
  217. /// \brief Flag indicating whether we should do debug logging.
  218. bool DebugLogging;
  219. };
  220. /// \brief Convenience typedef for a pass manager over modules.
  221. typedef PassManager<Module> ModulePassManager;
  222. /// \brief Convenience typedef for a pass manager over functions.
  223. typedef PassManager<Function> FunctionPassManager;
  224. namespace detail {
  225. /// \brief A CRTP base used to implement analysis managers.
  226. ///
  227. /// This class template serves as the boiler plate of an analysis manager. Any
  228. /// analysis manager can be implemented on top of this base class. Any
  229. /// implementation will be required to provide specific hooks:
  230. ///
  231. /// - getResultImpl
  232. /// - getCachedResultImpl
  233. /// - invalidateImpl
  234. ///
  235. /// The details of the call pattern are within.
  236. ///
  237. /// Note that there is also a generic analysis manager template which implements
  238. /// the above required functions along with common datastructures used for
  239. /// managing analyses. This base class is factored so that if you need to
  240. /// customize the handling of a specific IR unit, you can do so without
  241. /// replicating *all* of the boilerplate.
  242. template <typename DerivedT, typename IRUnitT> class AnalysisManagerBase {
  243. DerivedT *derived_this() { return static_cast<DerivedT *>(this); }
  244. const DerivedT *derived_this() const {
  245. return static_cast<const DerivedT *>(this);
  246. }
  247. AnalysisManagerBase(const AnalysisManagerBase &) = delete;
  248. AnalysisManagerBase &
  249. operator=(const AnalysisManagerBase &) = delete;
  250. protected:
  251. typedef detail::AnalysisResultConcept<IRUnitT> ResultConceptT;
  252. typedef detail::AnalysisPassConcept<IRUnitT> PassConceptT;
  253. // FIXME: Provide template aliases for the models when we're using C++11 in
  254. // a mode supporting them.
  255. // We have to explicitly define all the special member functions because MSVC
  256. // refuses to generate them.
  257. AnalysisManagerBase() {}
  258. AnalysisManagerBase(AnalysisManagerBase &&Arg)
  259. : AnalysisPasses(std::move(Arg.AnalysisPasses)) {}
  260. AnalysisManagerBase &operator=(AnalysisManagerBase &&RHS) {
  261. AnalysisPasses = std::move(RHS.AnalysisPasses);
  262. return *this;
  263. }
  264. public:
  265. /// \brief Get the result of an analysis pass for this module.
  266. ///
  267. /// If there is not a valid cached result in the manager already, this will
  268. /// re-run the analysis to produce a valid result.
  269. template <typename PassT> typename PassT::Result &getResult(IRUnitT &IR) {
  270. assert(AnalysisPasses.count(PassT::ID()) &&
  271. "This analysis pass was not registered prior to being queried");
  272. ResultConceptT &ResultConcept =
  273. derived_this()->getResultImpl(PassT::ID(), IR);
  274. typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
  275. ResultModelT;
  276. return static_cast<ResultModelT &>(ResultConcept).Result;
  277. }
  278. /// \brief Get the cached result of an analysis pass for this module.
  279. ///
  280. /// This method never runs the analysis.
  281. ///
  282. /// \returns null if there is no cached result.
  283. template <typename PassT>
  284. typename PassT::Result *getCachedResult(IRUnitT &IR) const {
  285. assert(AnalysisPasses.count(PassT::ID()) &&
  286. "This analysis pass was not registered prior to being queried");
  287. ResultConceptT *ResultConcept =
  288. derived_this()->getCachedResultImpl(PassT::ID(), IR);
  289. if (!ResultConcept)
  290. return nullptr;
  291. typedef detail::AnalysisResultModel<IRUnitT, PassT, typename PassT::Result>
  292. ResultModelT;
  293. return &static_cast<ResultModelT *>(ResultConcept)->Result;
  294. }
  295. /// \brief Register an analysis pass with the manager.
  296. ///
  297. /// This provides an initialized and set-up analysis pass to the analysis
  298. /// manager. Whomever is setting up analysis passes must use this to populate
  299. /// the manager with all of the analysis passes available.
  300. template <typename PassT> void registerPass(PassT Pass) {
  301. assert(!AnalysisPasses.count(PassT::ID()) &&
  302. "Registered the same analysis pass twice!");
  303. typedef detail::AnalysisPassModel<IRUnitT, PassT> PassModelT;
  304. AnalysisPasses[PassT::ID()].reset(new PassModelT(std::move(Pass)));
  305. }
  306. /// \brief Invalidate a specific analysis pass for an IR module.
  307. ///
  308. /// Note that the analysis result can disregard invalidation.
  309. template <typename PassT> void invalidate(IRUnitT &IR) {
  310. assert(AnalysisPasses.count(PassT::ID()) &&
  311. "This analysis pass was not registered prior to being invalidated");
  312. derived_this()->invalidateImpl(PassT::ID(), IR);
  313. }
  314. /// \brief Invalidate analyses cached for an IR unit.
  315. ///
  316. /// Walk through all of the analyses pertaining to this unit of IR and
  317. /// invalidate them unless they are preserved by the PreservedAnalyses set.
  318. /// We accept the PreservedAnalyses set by value and update it with each
  319. /// analyis pass which has been successfully invalidated and thus can be
  320. /// preserved going forward. The updated set is returned.
  321. PreservedAnalyses invalidate(IRUnitT &IR, PreservedAnalyses PA) {
  322. return derived_this()->invalidateImpl(IR, std::move(PA));
  323. }
  324. protected:
  325. /// \brief Lookup a registered analysis pass.
  326. PassConceptT &lookupPass(void *PassID) {
  327. typename AnalysisPassMapT::iterator PI = AnalysisPasses.find(PassID);
  328. assert(PI != AnalysisPasses.end() &&
  329. "Analysis passes must be registered prior to being queried!");
  330. return *PI->second;
  331. }
  332. /// \brief Lookup a registered analysis pass.
  333. const PassConceptT &lookupPass(void *PassID) const {
  334. typename AnalysisPassMapT::const_iterator PI = AnalysisPasses.find(PassID);
  335. assert(PI != AnalysisPasses.end() &&
  336. "Analysis passes must be registered prior to being queried!");
  337. return *PI->second;
  338. }
  339. private:
  340. /// \brief Map type from module analysis pass ID to pass concept pointer.
  341. typedef DenseMap<void *, std::unique_ptr<PassConceptT>> AnalysisPassMapT;
  342. /// \brief Collection of module analysis passes, indexed by ID.
  343. AnalysisPassMapT AnalysisPasses;
  344. };
  345. } // End namespace detail
  346. /// \brief A generic analysis pass manager with lazy running and caching of
  347. /// results.
  348. ///
  349. /// This analysis manager can be used for any IR unit where the address of the
  350. /// IR unit sufficies as its identity. It manages the cache for a unit of IR via
  351. /// the address of each unit of IR cached.
  352. template <typename IRUnitT>
  353. class AnalysisManager
  354. : public detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> {
  355. friend class detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT>;
  356. typedef detail::AnalysisManagerBase<AnalysisManager<IRUnitT>, IRUnitT> BaseT;
  357. typedef typename BaseT::ResultConceptT ResultConceptT;
  358. typedef typename BaseT::PassConceptT PassConceptT;
  359. public:
  360. // Most public APIs are inherited from the CRTP base class.
  361. /// \brief Construct an empty analysis manager.
  362. ///
  363. /// A flag can be passed to indicate that the manager should perform debug
  364. /// logging.
  365. AnalysisManager(bool DebugLogging = false) : DebugLogging(DebugLogging) {}
  366. // We have to explicitly define all the special member functions because MSVC
  367. // refuses to generate them.
  368. AnalysisManager(AnalysisManager &&Arg)
  369. : BaseT(std::move(static_cast<BaseT &>(Arg))),
  370. AnalysisResults(std::move(Arg.AnalysisResults)),
  371. DebugLogging(std::move(Arg.DebugLogging)) {}
  372. AnalysisManager &operator=(AnalysisManager &&RHS) {
  373. BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
  374. AnalysisResults = std::move(RHS.AnalysisResults);
  375. DebugLogging = std::move(RHS.DebugLogging);
  376. return *this;
  377. }
  378. /// \brief Returns true if the analysis manager has an empty results cache.
  379. bool empty() const {
  380. assert(AnalysisResults.empty() == AnalysisResultLists.empty() &&
  381. "The storage and index of analysis results disagree on how many "
  382. "there are!");
  383. return AnalysisResults.empty();
  384. }
  385. /// \brief Clear the analysis result cache.
  386. ///
  387. /// This routine allows cleaning up when the set of IR units itself has
  388. /// potentially changed, and thus we can't even look up a a result and
  389. /// invalidate it directly. Notably, this does *not* call invalidate functions
  390. /// as there is nothing to be done for them.
  391. void clear() {
  392. AnalysisResults.clear();
  393. AnalysisResultLists.clear();
  394. }
  395. private:
  396. AnalysisManager(const AnalysisManager &) = delete;
  397. AnalysisManager &operator=(const AnalysisManager &) = delete;
  398. /// \brief Get an analysis result, running the pass if necessary.
  399. ResultConceptT &getResultImpl(void *PassID, IRUnitT &IR) {
  400. typename AnalysisResultMapT::iterator RI;
  401. bool Inserted;
  402. std::tie(RI, Inserted) = AnalysisResults.insert(std::make_pair(
  403. std::make_pair(PassID, &IR), typename AnalysisResultListT::iterator()));
  404. // If we don't have a cached result for this function, look up the pass and
  405. // run it to produce a result, which we then add to the cache.
  406. if (Inserted) {
  407. auto &P = this->lookupPass(PassID);
  408. if (DebugLogging)
  409. dbgs() << "Running analysis: " << P.name() << "\n";
  410. AnalysisResultListT &ResultList = AnalysisResultLists[&IR];
  411. ResultList.emplace_back(PassID, P.run(IR, this));
  412. // P.run may have inserted elements into AnalysisResults and invalidated
  413. // RI.
  414. RI = AnalysisResults.find(std::make_pair(PassID, &IR));
  415. assert(RI != AnalysisResults.end() && "we just inserted it!");
  416. RI->second = std::prev(ResultList.end());
  417. }
  418. return *RI->second->second;
  419. }
  420. /// \brief Get a cached analysis result or return null.
  421. ResultConceptT *getCachedResultImpl(void *PassID, IRUnitT &IR) const {
  422. typename AnalysisResultMapT::const_iterator RI =
  423. AnalysisResults.find(std::make_pair(PassID, &IR));
  424. return RI == AnalysisResults.end() ? nullptr : &*RI->second->second;
  425. }
  426. /// \brief Invalidate a function pass result.
  427. void invalidateImpl(void *PassID, IRUnitT &IR) {
  428. typename AnalysisResultMapT::iterator RI =
  429. AnalysisResults.find(std::make_pair(PassID, &IR));
  430. if (RI == AnalysisResults.end())
  431. return;
  432. if (DebugLogging)
  433. dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
  434. << "\n";
  435. AnalysisResultLists[&IR].erase(RI->second);
  436. AnalysisResults.erase(RI);
  437. }
  438. /// \brief Invalidate the results for a function..
  439. PreservedAnalyses invalidateImpl(IRUnitT &IR, PreservedAnalyses PA) {
  440. // Short circuit for a common case of all analyses being preserved.
  441. if (PA.areAllPreserved())
  442. return PA;
  443. if (DebugLogging)
  444. dbgs() << "Invalidating all non-preserved analyses for: "
  445. << IR.getName() << "\n";
  446. // Clear all the invalidated results associated specifically with this
  447. // function.
  448. SmallVector<void *, 8> InvalidatedPassIDs;
  449. AnalysisResultListT &ResultsList = AnalysisResultLists[&IR];
  450. for (typename AnalysisResultListT::iterator I = ResultsList.begin(),
  451. E = ResultsList.end();
  452. I != E;) {
  453. void *PassID = I->first;
  454. // Pass the invalidation down to the pass itself to see if it thinks it is
  455. // necessary. The analysis pass can return false if no action on the part
  456. // of the analysis manager is required for this invalidation event.
  457. if (I->second->invalidate(IR, PA)) {
  458. if (DebugLogging)
  459. dbgs() << "Invalidating analysis: " << this->lookupPass(PassID).name()
  460. << "\n";
  461. InvalidatedPassIDs.push_back(I->first);
  462. I = ResultsList.erase(I);
  463. } else {
  464. ++I;
  465. }
  466. // After handling each pass, we mark it as preserved. Once we've
  467. // invalidated any stale results, the rest of the system is allowed to
  468. // start preserving this analysis again.
  469. PA.preserve(PassID);
  470. }
  471. while (!InvalidatedPassIDs.empty())
  472. AnalysisResults.erase(
  473. std::make_pair(InvalidatedPassIDs.pop_back_val(), &IR));
  474. if (ResultsList.empty())
  475. AnalysisResultLists.erase(&IR);
  476. return PA;
  477. }
  478. /// \brief List of function analysis pass IDs and associated concept pointers.
  479. ///
  480. /// Requires iterators to be valid across appending new entries and arbitrary
  481. /// erases. Provides both the pass ID and concept pointer such that it is
  482. /// half of a bijection and provides storage for the actual result concept.
  483. typedef std::list<std::pair<
  484. void *, std::unique_ptr<detail::AnalysisResultConcept<IRUnitT>>>>
  485. AnalysisResultListT;
  486. /// \brief Map type from function pointer to our custom list type.
  487. typedef DenseMap<IRUnitT *, AnalysisResultListT> AnalysisResultListMapT;
  488. /// \brief Map from function to a list of function analysis results.
  489. ///
  490. /// Provides linear time removal of all analysis results for a function and
  491. /// the ultimate storage for a particular cached analysis result.
  492. AnalysisResultListMapT AnalysisResultLists;
  493. /// \brief Map type from a pair of analysis ID and function pointer to an
  494. /// iterator into a particular result list.
  495. typedef DenseMap<std::pair<void *, IRUnitT *>,
  496. typename AnalysisResultListT::iterator> AnalysisResultMapT;
  497. /// \brief Map from an analysis ID and function to a particular cached
  498. /// analysis result.
  499. AnalysisResultMapT AnalysisResults;
  500. /// \brief A flag indicating whether debug logging is enabled.
  501. bool DebugLogging;
  502. };
  503. /// \brief Convenience typedef for the Module analysis manager.
  504. typedef AnalysisManager<Module> ModuleAnalysisManager;
  505. /// \brief Convenience typedef for the Function analysis manager.
  506. typedef AnalysisManager<Function> FunctionAnalysisManager;
  507. /// \brief A module analysis which acts as a proxy for a function analysis
  508. /// manager.
  509. ///
  510. /// This primarily proxies invalidation information from the module analysis
  511. /// manager and module pass manager to a function analysis manager. You should
  512. /// never use a function analysis manager from within (transitively) a module
  513. /// pass manager unless your parent module pass has received a proxy result
  514. /// object for it.
  515. class FunctionAnalysisManagerModuleProxy {
  516. public:
  517. class Result;
  518. static void *ID() { return (void *)&PassID; }
  519. static StringRef name() { return "FunctionAnalysisManagerModuleProxy"; }
  520. explicit FunctionAnalysisManagerModuleProxy(FunctionAnalysisManager &FAM)
  521. : FAM(&FAM) {}
  522. // We have to explicitly define all the special member functions because MSVC
  523. // refuses to generate them.
  524. FunctionAnalysisManagerModuleProxy(
  525. const FunctionAnalysisManagerModuleProxy &Arg)
  526. : FAM(Arg.FAM) {}
  527. FunctionAnalysisManagerModuleProxy(FunctionAnalysisManagerModuleProxy &&Arg)
  528. : FAM(std::move(Arg.FAM)) {}
  529. FunctionAnalysisManagerModuleProxy &
  530. operator=(FunctionAnalysisManagerModuleProxy RHS) {
  531. std::swap(FAM, RHS.FAM);
  532. return *this;
  533. }
  534. /// \brief Run the analysis pass and create our proxy result object.
  535. ///
  536. /// This doesn't do any interesting work, it is primarily used to insert our
  537. /// proxy result object into the module analysis cache so that we can proxy
  538. /// invalidation to the function analysis manager.
  539. ///
  540. /// In debug builds, it will also assert that the analysis manager is empty
  541. /// as no queries should arrive at the function analysis manager prior to
  542. /// this analysis being requested.
  543. Result run(Module &M);
  544. private:
  545. static char PassID;
  546. FunctionAnalysisManager *FAM;
  547. };
  548. /// \brief The result proxy object for the
  549. /// \c FunctionAnalysisManagerModuleProxy.
  550. ///
  551. /// See its documentation for more information.
  552. class FunctionAnalysisManagerModuleProxy::Result {
  553. public:
  554. explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
  555. // We have to explicitly define all the special member functions because MSVC
  556. // refuses to generate them.
  557. Result(const Result &Arg) : FAM(Arg.FAM) {}
  558. Result(Result &&Arg) : FAM(std::move(Arg.FAM)) {}
  559. Result &operator=(Result RHS) {
  560. std::swap(FAM, RHS.FAM);
  561. return *this;
  562. }
  563. ~Result();
  564. /// \brief Accessor for the \c FunctionAnalysisManager.
  565. FunctionAnalysisManager &getManager() { return *FAM; }
  566. /// \brief Handler for invalidation of the module.
  567. ///
  568. /// If this analysis itself is preserved, then we assume that the set of \c
  569. /// Function objects in the \c Module hasn't changed and thus we don't need
  570. /// to invalidate *all* cached data associated with a \c Function* in the \c
  571. /// FunctionAnalysisManager.
  572. ///
  573. /// Regardless of whether this analysis is marked as preserved, all of the
  574. /// analyses in the \c FunctionAnalysisManager are potentially invalidated
  575. /// based on the set of preserved analyses.
  576. bool invalidate(Module &M, const PreservedAnalyses &PA);
  577. private:
  578. FunctionAnalysisManager *FAM;
  579. };
  580. /// \brief A function analysis which acts as a proxy for a module analysis
  581. /// manager.
  582. ///
  583. /// This primarily provides an accessor to a parent module analysis manager to
  584. /// function passes. Only the const interface of the module analysis manager is
  585. /// provided to indicate that once inside of a function analysis pass you
  586. /// cannot request a module analysis to actually run. Instead, the user must
  587. /// rely on the \c getCachedResult API.
  588. ///
  589. /// This proxy *doesn't* manage the invalidation in any way. That is handled by
  590. /// the recursive return path of each layer of the pass manager and the
  591. /// returned PreservedAnalysis set.
  592. class ModuleAnalysisManagerFunctionProxy {
  593. public:
  594. /// \brief Result proxy object for \c ModuleAnalysisManagerFunctionProxy.
  595. class Result {
  596. public:
  597. explicit Result(const ModuleAnalysisManager &MAM) : MAM(&MAM) {}
  598. // We have to explicitly define all the special member functions because
  599. // MSVC refuses to generate them.
  600. Result(const Result &Arg) : MAM(Arg.MAM) {}
  601. Result(Result &&Arg) : MAM(std::move(Arg.MAM)) {}
  602. Result &operator=(Result RHS) {
  603. std::swap(MAM, RHS.MAM);
  604. return *this;
  605. }
  606. const ModuleAnalysisManager &getManager() const { return *MAM; }
  607. /// \brief Handle invalidation by ignoring it, this pass is immutable.
  608. bool invalidate(Function &) { return false; }
  609. private:
  610. const ModuleAnalysisManager *MAM;
  611. };
  612. static void *ID() { return (void *)&PassID; }
  613. static StringRef name() { return "ModuleAnalysisManagerFunctionProxy"; }
  614. ModuleAnalysisManagerFunctionProxy(const ModuleAnalysisManager &MAM)
  615. : MAM(&MAM) {}
  616. // We have to explicitly define all the special member functions because MSVC
  617. // refuses to generate them.
  618. ModuleAnalysisManagerFunctionProxy(
  619. const ModuleAnalysisManagerFunctionProxy &Arg)
  620. : MAM(Arg.MAM) {}
  621. ModuleAnalysisManagerFunctionProxy(ModuleAnalysisManagerFunctionProxy &&Arg)
  622. : MAM(std::move(Arg.MAM)) {}
  623. ModuleAnalysisManagerFunctionProxy &
  624. operator=(ModuleAnalysisManagerFunctionProxy RHS) {
  625. std::swap(MAM, RHS.MAM);
  626. return *this;
  627. }
  628. /// \brief Run the analysis pass and create our proxy result object.
  629. /// Nothing to see here, it just forwards the \c MAM reference into the
  630. /// result.
  631. Result run(Function &) { return Result(*MAM); }
  632. private:
  633. static char PassID;
  634. const ModuleAnalysisManager *MAM;
  635. };
  636. /// \brief Trivial adaptor that maps from a module to its functions.
  637. ///
  638. /// Designed to allow composition of a FunctionPass(Manager) and
  639. /// a ModulePassManager. Note that if this pass is constructed with a pointer
  640. /// to a \c ModuleAnalysisManager it will run the
  641. /// \c FunctionAnalysisManagerModuleProxy analysis prior to running the function
  642. /// pass over the module to enable a \c FunctionAnalysisManager to be used
  643. /// within this run safely.
  644. ///
  645. /// Function passes run within this adaptor can rely on having exclusive access
  646. /// to the function they are run over. They should not read or modify any other
  647. /// functions! Other threads or systems may be manipulating other functions in
  648. /// the module, and so their state should never be relied on.
  649. /// FIXME: Make the above true for all of LLVM's actual passes, some still
  650. /// violate this principle.
  651. ///
  652. /// Function passes can also read the module containing the function, but they
  653. /// should not modify that module outside of the use lists of various globals.
  654. /// For example, a function pass is not permitted to add functions to the
  655. /// module.
  656. /// FIXME: Make the above true for all of LLVM's actual passes, some still
  657. /// violate this principle.
  658. template <typename FunctionPassT> class ModuleToFunctionPassAdaptor {
  659. public:
  660. explicit ModuleToFunctionPassAdaptor(FunctionPassT Pass)
  661. : Pass(std::move(Pass)) {}
  662. // We have to explicitly define all the special member functions because MSVC
  663. // refuses to generate them.
  664. ModuleToFunctionPassAdaptor(const ModuleToFunctionPassAdaptor &Arg)
  665. : Pass(Arg.Pass) {}
  666. ModuleToFunctionPassAdaptor(ModuleToFunctionPassAdaptor &&Arg)
  667. : Pass(std::move(Arg.Pass)) {}
  668. friend void swap(ModuleToFunctionPassAdaptor &LHS,
  669. ModuleToFunctionPassAdaptor &RHS) {
  670. using std::swap;
  671. swap(LHS.Pass, RHS.Pass);
  672. }
  673. ModuleToFunctionPassAdaptor &operator=(ModuleToFunctionPassAdaptor RHS) {
  674. swap(*this, RHS);
  675. return *this;
  676. }
  677. /// \brief Runs the function pass across every function in the module.
  678. PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM) {
  679. FunctionAnalysisManager *FAM = nullptr;
  680. if (AM)
  681. // Setup the function analysis manager from its proxy.
  682. FAM = &AM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  683. PreservedAnalyses PA = PreservedAnalyses::all();
  684. for (Function &F : M) {
  685. if (F.isDeclaration())
  686. continue;
  687. PreservedAnalyses PassPA = Pass.run(F, FAM);
  688. // We know that the function pass couldn't have invalidated any other
  689. // function's analyses (that's the contract of a function pass), so
  690. // directly handle the function analysis manager's invalidation here and
  691. // update our preserved set to reflect that these have already been
  692. // handled.
  693. if (FAM)
  694. PassPA = FAM->invalidate(F, std::move(PassPA));
  695. // Then intersect the preserved set so that invalidation of module
  696. // analyses will eventually occur when the module pass completes.
  697. PA.intersect(std::move(PassPA));
  698. }
  699. // By definition we preserve the proxy. This precludes *any* invalidation
  700. // of function analyses by the proxy, but that's OK because we've taken
  701. // care to invalidate analyses in the function analysis manager
  702. // incrementally above.
  703. PA.preserve<FunctionAnalysisManagerModuleProxy>();
  704. return PA;
  705. }
  706. static StringRef name() { return "ModuleToFunctionPassAdaptor"; }
  707. private:
  708. FunctionPassT Pass;
  709. };
  710. /// \brief A function to deduce a function pass type and wrap it in the
  711. /// templated adaptor.
  712. template <typename FunctionPassT>
  713. ModuleToFunctionPassAdaptor<FunctionPassT>
  714. createModuleToFunctionPassAdaptor(FunctionPassT Pass) {
  715. return ModuleToFunctionPassAdaptor<FunctionPassT>(std::move(Pass));
  716. }
  717. /// \brief A template utility pass to force an analysis result to be available.
  718. ///
  719. /// This is a no-op pass which simply forces a specific analysis pass's result
  720. /// to be available when it is run.
  721. template <typename AnalysisT> struct RequireAnalysisPass {
  722. /// \brief Run this pass over some unit of IR.
  723. ///
  724. /// This pass can be run over any unit of IR and use any analysis manager
  725. /// provided they satisfy the basic API requirements. When this pass is
  726. /// created, these methods can be instantiated to satisfy whatever the
  727. /// context requires.
  728. template <typename IRUnitT>
  729. PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
  730. if (AM)
  731. (void)AM->template getResult<AnalysisT>(Arg);
  732. return PreservedAnalyses::all();
  733. }
  734. static StringRef name() { return "RequireAnalysisPass"; }
  735. };
  736. /// \brief A template utility pass to force an analysis result to be
  737. /// invalidated.
  738. ///
  739. /// This is a no-op pass which simply forces a specific analysis result to be
  740. /// invalidated when it is run.
  741. template <typename AnalysisT> struct InvalidateAnalysisPass {
  742. /// \brief Run this pass over some unit of IR.
  743. ///
  744. /// This pass can be run over any unit of IR and use any analysis manager
  745. /// provided they satisfy the basic API requirements. When this pass is
  746. /// created, these methods can be instantiated to satisfy whatever the
  747. /// context requires.
  748. template <typename IRUnitT>
  749. PreservedAnalyses run(IRUnitT &Arg, AnalysisManager<IRUnitT> *AM) {
  750. if (AM)
  751. // We have to directly invalidate the analysis result as we can't
  752. // enumerate all other analyses and use the preserved set to control it.
  753. (void)AM->template invalidate<AnalysisT>(Arg);
  754. return PreservedAnalyses::all();
  755. }
  756. static StringRef name() { return "InvalidateAnalysisPass"; }
  757. };
  758. /// \brief A utility pass that does nothing but preserves no analyses.
  759. ///
  760. /// As a consequence fo not preserving any analyses, this pass will force all
  761. /// analysis passes to be re-run to produce fresh results if any are needed.
  762. struct InvalidateAllAnalysesPass {
  763. /// \brief Run this pass over some unit of IR.
  764. template <typename IRUnitT> PreservedAnalyses run(IRUnitT &Arg) {
  765. return PreservedAnalyses::none();
  766. }
  767. static StringRef name() { return "InvalidateAllAnalysesPass"; }
  768. };
  769. }
  770. #endif