LegacyPassManagers.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- LegacyPassManagers.h - Legacy Pass Infrastructure --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the LLVM Pass Manager infrastructure.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_IR_LEGACYPASSMANAGERS_H
  18. #define LLVM_IR_LEGACYPASSMANAGERS_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/FoldingSet.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/Pass.h"
  24. #include <vector>
  25. //===----------------------------------------------------------------------===//
  26. // Overview:
  27. // The Pass Manager Infrastructure manages passes. It's responsibilities are:
  28. //
  29. // o Manage optimization pass execution order
  30. // o Make required Analysis information available before pass P is run
  31. // o Release memory occupied by dead passes
  32. // o If Analysis information is dirtied by a pass then regenerate Analysis
  33. // information before it is consumed by another pass.
  34. //
  35. // Pass Manager Infrastructure uses multiple pass managers. They are
  36. // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
  37. // This class hierarchy uses multiple inheritance but pass managers do not
  38. // derive from another pass manager.
  39. //
  40. // PassManager and FunctionPassManager are two top-level pass manager that
  41. // represents the external interface of this entire pass manager infrastucture.
  42. //
  43. // Important classes :
  44. //
  45. // [o] class PMTopLevelManager;
  46. //
  47. // Two top level managers, PassManager and FunctionPassManager, derive from
  48. // PMTopLevelManager. PMTopLevelManager manages information used by top level
  49. // managers such as last user info.
  50. //
  51. // [o] class PMDataManager;
  52. //
  53. // PMDataManager manages information, e.g. list of available analysis info,
  54. // used by a pass manager to manage execution order of passes. It also provides
  55. // a place to implement common pass manager APIs. All pass managers derive from
  56. // PMDataManager.
  57. //
  58. // [o] class FunctionPassManager;
  59. //
  60. // This is a external interface used to manage FunctionPasses. This
  61. // interface relies on FunctionPassManagerImpl to do all the tasks.
  62. //
  63. // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
  64. // public PMTopLevelManager;
  65. //
  66. // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
  67. //
  68. // [o] class FPPassManager : public ModulePass, public PMDataManager;
  69. //
  70. // FPPassManager manages FunctionPasses and BBPassManagers
  71. //
  72. // [o] class MPPassManager : public Pass, public PMDataManager;
  73. //
  74. // MPPassManager manages ModulePasses and FPPassManagers
  75. //
  76. // [o] class PassManager;
  77. //
  78. // This is a external interface used by various tools to manages passes. It
  79. // relies on PassManagerImpl to do all the tasks.
  80. //
  81. // [o] class PassManagerImpl : public Pass, public PMDataManager,
  82. // public PMTopLevelManager
  83. //
  84. // PassManagerImpl is a top level pass manager responsible for managing
  85. // MPPassManagers.
  86. //===----------------------------------------------------------------------===//
  87. #include "llvm/Support/PrettyStackTrace.h"
  88. namespace llvm {
  89. template <typename T> class ArrayRef;
  90. class Module;
  91. class StringRef;
  92. class Value;
  93. class PMDataManager;
  94. // enums for debugging strings
  95. enum PassDebuggingString {
  96. EXECUTION_MSG, // "Executing Pass '" + PassName
  97. MODIFICATION_MSG, // "Made Modification '" + PassName
  98. FREEING_MSG, // " Freeing Pass '" + PassName
  99. ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
  100. ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
  101. ON_REGION_MSG, // "' on Region '" + Msg + "'...\n'"
  102. ON_LOOP_MSG, // "' on Loop '" + Msg + "'...\n'"
  103. ON_CG_MSG // "' on Call Graph Nodes '" + Msg + "'...\n'"
  104. };
  105. /// PassManagerPrettyStackEntry - This is used to print informative information
  106. /// about what pass is running when/if a stack trace is generated.
  107. class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
  108. Pass *P;
  109. Value *V;
  110. Module *M;
  111. public:
  112. explicit PassManagerPrettyStackEntry(Pass *p)
  113. : P(p), V(nullptr), M(nullptr) {} // When P is releaseMemory'd.
  114. PassManagerPrettyStackEntry(Pass *p, Value &v)
  115. : P(p), V(&v), M(nullptr) {} // When P is run on V
  116. PassManagerPrettyStackEntry(Pass *p, Module &m)
  117. : P(p), V(nullptr), M(&m) {} // When P is run on M
  118. /// print - Emit information about this stack frame to OS.
  119. void print(raw_ostream &OS) const override;
  120. };
  121. //===----------------------------------------------------------------------===//
  122. // PMStack
  123. //
  124. /// PMStack - This class implements a stack data structure of PMDataManager
  125. /// pointers.
  126. ///
  127. /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
  128. /// using PMStack. Each Pass implements assignPassManager() to connect itself
  129. /// with appropriate manager. assignPassManager() walks PMStack to find
  130. /// suitable manager.
  131. class PMStack {
  132. public:
  133. typedef std::vector<PMDataManager *>::const_reverse_iterator iterator;
  134. iterator begin() const { return S.rbegin(); }
  135. iterator end() const { return S.rend(); }
  136. void pop();
  137. PMDataManager *top() const { return S.back(); }
  138. void push(PMDataManager *PM);
  139. bool empty() const { return S.empty(); }
  140. void dump() const;
  141. private:
  142. std::vector<PMDataManager *> S;
  143. };
  144. //===----------------------------------------------------------------------===//
  145. // PMTopLevelManager
  146. //
  147. /// PMTopLevelManager manages LastUser info and collects common APIs used by
  148. /// top level pass managers.
  149. class PMTopLevelManager {
  150. protected:
  151. explicit PMTopLevelManager(PMDataManager *PMDM);
  152. unsigned getNumContainedManagers() const {
  153. return (unsigned)PassManagers.size();
  154. }
  155. void initializeAllAnalysisInfo();
  156. private:
  157. virtual PMDataManager *getAsPMDataManager() = 0;
  158. virtual PassManagerType getTopLevelPassManagerType() = 0;
  159. public:
  160. /// Schedule pass P for execution. Make sure that passes required by
  161. /// P are run before P is run. Update analysis info maintained by
  162. /// the manager. Remove dead passes. This is a recursive function.
  163. void schedulePass(Pass *P);
  164. /// Set pass P as the last user of the given analysis passes.
  165. void setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P);
  166. /// Collect passes whose last user is P
  167. void collectLastUses(SmallVectorImpl<Pass *> &LastUses, Pass *P);
  168. /// Find the pass that implements Analysis AID. Search immutable
  169. /// passes and all pass managers. If desired pass is not found
  170. /// then return NULL.
  171. Pass *findAnalysisPass(AnalysisID AID);
  172. /// Retrieve the PassInfo for an analysis.
  173. const PassInfo *findAnalysisPassInfo(AnalysisID AID) const;
  174. /// Find analysis usage information for the pass P.
  175. AnalysisUsage *findAnalysisUsage(Pass *P);
  176. virtual ~PMTopLevelManager();
  177. /// Add immutable pass and initialize it.
  178. void addImmutablePass(ImmutablePass *P);
  179. inline SmallVectorImpl<ImmutablePass *>& getImmutablePasses() {
  180. return ImmutablePasses;
  181. }
  182. void addPassManager(PMDataManager *Manager) {
  183. PassManagers.push_back(Manager);
  184. }
  185. // Add Manager into the list of managers that are not directly
  186. // maintained by this top level pass manager
  187. inline void addIndirectPassManager(PMDataManager *Manager) {
  188. IndirectPassManagers.push_back(Manager);
  189. }
  190. // Print passes managed by this top level manager.
  191. void dumpPasses() const;
  192. void dumpArguments() const;
  193. // Active Pass Managers
  194. PMStack activeStack;
  195. protected:
  196. /// Collection of pass managers
  197. SmallVector<PMDataManager *, 8> PassManagers;
  198. private:
  199. /// Collection of pass managers that are not directly maintained
  200. /// by this pass manager
  201. SmallVector<PMDataManager *, 8> IndirectPassManagers;
  202. // Map to keep track of last user of the analysis pass.
  203. // LastUser->second is the last user of Lastuser->first.
  204. // This is kept in sync with InversedLastUser.
  205. DenseMap<Pass *, Pass *> LastUser;
  206. // Map to keep track of passes that are last used by a pass.
  207. // This is kept in sync with LastUser.
  208. DenseMap<Pass *, SmallPtrSet<Pass *, 8> > InversedLastUser;
  209. /// Immutable passes are managed by top level manager.
  210. SmallVector<ImmutablePass *, 16> ImmutablePasses;
  211. /// Map from ID to immutable passes.
  212. SmallDenseMap<AnalysisID, ImmutablePass *, 8> ImmutablePassMap;
  213. /// A wrapper around AnalysisUsage for the purpose of uniqueing. The wrapper
  214. /// is used to avoid needing to make AnalysisUsage itself a folding set node.
  215. struct AUFoldingSetNode : public FoldingSetNode {
  216. AnalysisUsage AU;
  217. AUFoldingSetNode(const AnalysisUsage &AU) : AU(AU) {}
  218. void Profile(FoldingSetNodeID &ID) const {
  219. Profile(ID, AU);
  220. }
  221. static void Profile(FoldingSetNodeID &ID, const AnalysisUsage &AU) {
  222. // TODO: We could consider sorting the dependency arrays within the
  223. // AnalysisUsage (since they are conceptually unordered).
  224. ID.AddBoolean(AU.getPreservesAll());
  225. auto ProfileVec = [&](const SmallVectorImpl<AnalysisID>& Vec) {
  226. ID.AddInteger(Vec.size());
  227. for(AnalysisID AID : Vec)
  228. ID.AddPointer(AID);
  229. };
  230. ProfileVec(AU.getRequiredSet());
  231. ProfileVec(AU.getRequiredTransitiveSet());
  232. ProfileVec(AU.getPreservedSet());
  233. ProfileVec(AU.getUsedSet());
  234. }
  235. };
  236. // Contains all of the unique combinations of AnalysisUsage. This is helpful
  237. // when we have multiple instances of the same pass since they'll usually
  238. // have the same analysis usage and can share storage.
  239. FoldingSet<AUFoldingSetNode> UniqueAnalysisUsages;
  240. // Allocator used for allocating UAFoldingSetNodes. This handles deletion of
  241. // all allocated nodes in one fell swoop.
  242. SpecificBumpPtrAllocator<AUFoldingSetNode> AUFoldingSetNodeAllocator;
  243. // Maps from a pass to it's associated entry in UniqueAnalysisUsages. Does
  244. // not own the storage associated with either key or value..
  245. DenseMap<Pass *, AnalysisUsage*> AnUsageMap;
  246. /// Collection of PassInfo objects found via analysis IDs and in this top
  247. /// level manager. This is used to memoize queries to the pass registry.
  248. /// FIXME: This is an egregious hack because querying the pass registry is
  249. /// either slow or racy.
  250. mutable DenseMap<AnalysisID, const PassInfo *> AnalysisPassInfos;
  251. };
  252. //===----------------------------------------------------------------------===//
  253. // PMDataManager
  254. /// PMDataManager provides the common place to manage the analysis data
  255. /// used by pass managers.
  256. class PMDataManager {
  257. public:
  258. explicit PMDataManager() { initializeAnalysisInfo(); }
  259. virtual ~PMDataManager();
  260. virtual Pass *getAsPass() = 0;
  261. /// Augment AvailableAnalysis by adding analysis made available by pass P.
  262. void recordAvailableAnalysis(Pass *P);
  263. /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
  264. void verifyPreservedAnalysis(Pass *P);
  265. /// Remove Analysis that is not preserved by the pass
  266. void removeNotPreservedAnalysis(Pass *P);
  267. /// Remove dead passes used by P.
  268. void removeDeadPasses(Pass *P, StringRef Msg,
  269. enum PassDebuggingString);
  270. /// Remove P.
  271. void freePass(Pass *P, StringRef Msg,
  272. enum PassDebuggingString);
  273. /// Add pass P into the PassVector. Update
  274. /// AvailableAnalysis appropriately if ProcessAnalysis is true.
  275. void add(Pass *P, bool ProcessAnalysis = true);
  276. /// Add RequiredPass into list of lower level passes required by pass P.
  277. /// RequiredPass is run on the fly by Pass Manager when P requests it
  278. /// through getAnalysis interface.
  279. virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
  280. virtual std::tuple<Pass *, bool> getOnTheFlyPass(Pass *P, AnalysisID PI,
  281. Function &F);
  282. /// Initialize available analysis information.
  283. void initializeAnalysisInfo() {
  284. AvailableAnalysis.clear();
  285. for (auto &IA : InheritedAnalysis)
  286. IA = nullptr;
  287. }
  288. // Return true if P preserves high level analysis used by other
  289. // passes that are managed by this manager.
  290. bool preserveHigherLevelAnalysis(Pass *P);
  291. /// Populate UsedPasses with analysis pass that are used or required by pass
  292. /// P and are available. Populate ReqPassNotAvailable with analysis pass that
  293. /// are required by pass P but are not available.
  294. void collectRequiredAndUsedAnalyses(
  295. SmallVectorImpl<Pass *> &UsedPasses,
  296. SmallVectorImpl<AnalysisID> &ReqPassNotAvailable, Pass *P);
  297. /// All Required analyses should be available to the pass as it runs! Here
  298. /// we fill in the AnalysisImpls member of the pass so that it can
  299. /// successfully use the getAnalysis() method to retrieve the
  300. /// implementations it needs.
  301. void initializeAnalysisImpl(Pass *P);
  302. /// Find the pass that implements Analysis AID. If desired pass is not found
  303. /// then return NULL.
  304. Pass *findAnalysisPass(AnalysisID AID, bool Direction);
  305. // Access toplevel manager
  306. PMTopLevelManager *getTopLevelManager() { return TPM; }
  307. void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
  308. unsigned getDepth() const { return Depth; }
  309. void setDepth(unsigned newDepth) { Depth = newDepth; }
  310. // Print routines used by debug-pass
  311. void dumpLastUses(Pass *P, unsigned Offset) const;
  312. void dumpPassArguments() const;
  313. void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
  314. enum PassDebuggingString S2, StringRef Msg);
  315. void dumpRequiredSet(const Pass *P) const;
  316. void dumpPreservedSet(const Pass *P) const;
  317. void dumpUsedSet(const Pass *P) const;
  318. unsigned getNumContainedPasses() const {
  319. return (unsigned)PassVector.size();
  320. }
  321. virtual PassManagerType getPassManagerType() const {
  322. assert ( 0 && "Invalid use of getPassManagerType");
  323. return PMT_Unknown;
  324. }
  325. DenseMap<AnalysisID, Pass*> *getAvailableAnalysis() {
  326. return &AvailableAnalysis;
  327. }
  328. // Collect AvailableAnalysis from all the active Pass Managers.
  329. void populateInheritedAnalysis(PMStack &PMS) {
  330. unsigned Index = 0;
  331. for (PMDataManager *PMDM : PMS)
  332. InheritedAnalysis[Index++] = PMDM->getAvailableAnalysis();
  333. }
  334. /// Set the initial size of the module if the user has specified that they
  335. /// want remarks for size.
  336. /// Returns 0 if the remark was not requested.
  337. unsigned initSizeRemarkInfo(
  338. Module &M,
  339. StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount);
  340. /// Emit a remark signifying that the number of IR instructions in the module
  341. /// changed.
  342. /// \p F is optionally passed by passes which run on Functions, and thus
  343. /// always know whether or not a non-empty function is available.
  344. ///
  345. /// \p FunctionToInstrCount maps the name of a \p Function to a pair. The
  346. /// first member of the pair is the IR count of the \p Function before running
  347. /// \p P, and the second member is the IR count of the \p Function after
  348. /// running \p P.
  349. void emitInstrCountChangedRemark(
  350. Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
  351. StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
  352. Function *F = nullptr);
  353. protected:
  354. // Top level manager.
  355. PMTopLevelManager *TPM = nullptr;
  356. // Collection of pass that are managed by this manager
  357. SmallVector<Pass *, 16> PassVector;
  358. // Collection of Analysis provided by Parent pass manager and
  359. // used by current pass manager. At at time there can not be more
  360. // then PMT_Last active pass mangers.
  361. DenseMap<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
  362. /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
  363. /// or higher is specified.
  364. bool isPassDebuggingExecutionsOrMore() const;
  365. private:
  366. void dumpAnalysisUsage(StringRef Msg, const Pass *P,
  367. const AnalysisUsage::VectorType &Set) const;
  368. // Set of available Analysis. This information is used while scheduling
  369. // pass. If a pass requires an analysis which is not available then
  370. // the required analysis pass is scheduled to run before the pass itself is
  371. // scheduled to run.
  372. DenseMap<AnalysisID, Pass*> AvailableAnalysis;
  373. // Collection of higher level analysis used by the pass managed by
  374. // this manager.
  375. SmallVector<Pass *, 16> HigherLevelAnalysis;
  376. unsigned Depth = 0;
  377. };
  378. //===----------------------------------------------------------------------===//
  379. // FPPassManager
  380. //
  381. /// FPPassManager manages BBPassManagers and FunctionPasses.
  382. /// It batches all function passes and basic block pass managers together and
  383. /// sequence them to process one function at a time before processing next
  384. /// function.
  385. class FPPassManager : public ModulePass, public PMDataManager {
  386. public:
  387. static char ID;
  388. explicit FPPassManager() : ModulePass(ID) {}
  389. /// run - Execute all of the passes scheduled for execution. Keep track of
  390. /// whether any of the passes modifies the module, and if so, return true.
  391. bool runOnFunction(Function &F);
  392. bool runOnModule(Module &M) override;
  393. /// cleanup - After running all passes, clean up pass manager cache.
  394. void cleanup();
  395. /// doInitialization - Overrides ModulePass doInitialization for global
  396. /// initialization tasks
  397. ///
  398. using ModulePass::doInitialization;
  399. /// doInitialization - Run all of the initializers for the function passes.
  400. ///
  401. bool doInitialization(Module &M) override;
  402. /// doFinalization - Overrides ModulePass doFinalization for global
  403. /// finalization tasks
  404. ///
  405. using ModulePass::doFinalization;
  406. /// doFinalization - Run all of the finalizers for the function passes.
  407. ///
  408. bool doFinalization(Module &M) override;
  409. PMDataManager *getAsPMDataManager() override { return this; }
  410. Pass *getAsPass() override { return this; }
  411. /// Pass Manager itself does not invalidate any analysis info.
  412. void getAnalysisUsage(AnalysisUsage &Info) const override {
  413. Info.setPreservesAll();
  414. }
  415. // Print passes managed by this manager
  416. void dumpPassStructure(unsigned Offset) override;
  417. StringRef getPassName() const override { return "Function Pass Manager"; }
  418. FunctionPass *getContainedPass(unsigned N) {
  419. assert ( N < PassVector.size() && "Pass number out of range!");
  420. FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
  421. return FP;
  422. }
  423. PassManagerType getPassManagerType() const override {
  424. return PMT_FunctionPassManager;
  425. }
  426. };
  427. }
  428. #endif
  429. #ifdef __GNUC__
  430. #pragma GCC diagnostic pop
  431. #endif