1 //===- LegacyPassManagers.h - Legacy Pass Infrastructure --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_LEGACYPASSMANAGERS_H
15 #define LLVM_IR_LEGACYPASSMANAGERS_H
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Pass.h"
26 //===----------------------------------------------------------------------===//
28 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
30 // o Manage optimization pass execution order
31 // o Make required Analysis information available before pass P is run
32 // o Release memory occupied by dead passes
33 // o If Analysis information is dirtied by a pass then regenerate Analysis
34 // information before it is consumed by another pass.
36 // Pass Manager Infrastructure uses multiple pass managers. They are
37 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
38 // This class hierarchy uses multiple inheritance but pass managers do not
39 // derive from another pass manager.
41 // PassManager and FunctionPassManager are two top-level pass manager that
42 // represents the external interface of this entire pass manager infrastucture.
44 // Important classes :
46 // [o] class PMTopLevelManager;
48 // Two top level managers, PassManager and FunctionPassManager, derive from
49 // PMTopLevelManager. PMTopLevelManager manages information used by top level
50 // managers such as last user info.
52 // [o] class PMDataManager;
54 // PMDataManager manages information, e.g. list of available analysis info,
55 // used by a pass manager to manage execution order of passes. It also provides
56 // a place to implement common pass manager APIs. All pass managers derive from
59 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
61 // BBPassManager manages BasicBlockPasses.
63 // [o] class FunctionPassManager;
65 // This is a external interface used to manage FunctionPasses. This
66 // interface relies on FunctionPassManagerImpl to do all the tasks.
68 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
69 // public PMTopLevelManager;
71 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
73 // [o] class FPPassManager : public ModulePass, public PMDataManager;
75 // FPPassManager manages FunctionPasses and BBPassManagers
77 // [o] class MPPassManager : public Pass, public PMDataManager;
79 // MPPassManager manages ModulePasses and FPPassManagers
81 // [o] class PassManager;
83 // This is a external interface used by various tools to manages passes. It
84 // relies on PassManagerImpl to do all the tasks.
86 // [o] class PassManagerImpl : public Pass, public PMDataManager,
87 // public PMTopLevelManager
89 // PassManagerImpl is a top level pass manager responsible for managing
91 //===----------------------------------------------------------------------===//
93 #include "llvm/Support/PrettyStackTrace.h"
103 // enums for debugging strings
104 enum PassDebuggingString {
105 EXECUTION_MSG, // "Executing Pass '" + PassName
106 MODIFICATION_MSG, // "Made Modification '" + PassName
107 FREEING_MSG, // " Freeing Pass '" + PassName
108 ON_BASICBLOCK_MSG, // "' on BasicBlock '" + InstructionName + "'...\n"
109 ON_FUNCTION_MSG, // "' on Function '" + FunctionName + "'...\n"
110 ON_MODULE_MSG, // "' on Module '" + ModuleName + "'...\n"
111 ON_REGION_MSG, // "' on Region '" + Msg + "'...\n'"
112 ON_LOOP_MSG, // "' on Loop '" + Msg + "'...\n'"
113 ON_CG_MSG // "' on Call Graph Nodes '" + Msg + "'...\n'"
116 /// PassManagerPrettyStackEntry - This is used to print informative information
117 /// about what pass is running when/if a stack trace is generated.
118 class PassManagerPrettyStackEntry : public PrettyStackTraceEntry {
124 explicit PassManagerPrettyStackEntry(Pass *p)
125 : P(p), V(nullptr), M(nullptr) {} // When P is releaseMemory'd.
126 PassManagerPrettyStackEntry(Pass *p, Value &v)
127 : P(p), V(&v), M(nullptr) {} // When P is run on V
128 PassManagerPrettyStackEntry(Pass *p, Module &m)
129 : P(p), V(nullptr), M(&m) {} // When P is run on M
131 /// print - Emit information about this stack frame to OS.
132 void print(raw_ostream &OS) const override;
135 //===----------------------------------------------------------------------===//
138 /// PMStack - This class implements a stack data structure of PMDataManager
141 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
142 /// using PMStack. Each Pass implements assignPassManager() to connect itself
143 /// with appropriate manager. assignPassManager() walks PMStack to find
144 /// suitable manager.
147 typedef std::vector<PMDataManager *>::const_reverse_iterator iterator;
148 iterator begin() const { return S.rbegin(); }
149 iterator end() const { return S.rend(); }
152 PMDataManager *top() const { return S.back(); }
153 void push(PMDataManager *PM);
154 bool empty() const { return S.empty(); }
159 std::vector<PMDataManager *> S;
162 //===----------------------------------------------------------------------===//
165 /// PMTopLevelManager manages LastUser info and collects common APIs used by
166 /// top level pass managers.
167 class PMTopLevelManager {
169 explicit PMTopLevelManager(PMDataManager *PMDM);
171 unsigned getNumContainedManagers() const {
172 return (unsigned)PassManagers.size();
175 void initializeAllAnalysisInfo();
178 virtual PMDataManager *getAsPMDataManager() = 0;
179 virtual PassManagerType getTopLevelPassManagerType() = 0;
182 /// Schedule pass P for execution. Make sure that passes required by
183 /// P are run before P is run. Update analysis info maintained by
184 /// the manager. Remove dead passes. This is a recursive function.
185 void schedulePass(Pass *P);
187 /// Set pass P as the last user of the given analysis passes.
188 void setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P);
190 /// Collect passes whose last user is P
191 void collectLastUses(SmallVectorImpl<Pass *> &LastUses, Pass *P);
193 /// Find the pass that implements Analysis AID. Search immutable
194 /// passes and all pass managers. If desired pass is not found
195 /// then return NULL.
196 Pass *findAnalysisPass(AnalysisID AID);
198 /// Retrieve the PassInfo for an analysis.
199 const PassInfo *findAnalysisPassInfo(AnalysisID AID) const;
201 /// Find analysis usage information for the pass P.
202 AnalysisUsage *findAnalysisUsage(Pass *P);
204 virtual ~PMTopLevelManager();
206 /// Add immutable pass and initialize it.
207 void addImmutablePass(ImmutablePass *P);
209 inline SmallVectorImpl<ImmutablePass *>& getImmutablePasses() {
210 return ImmutablePasses;
213 void addPassManager(PMDataManager *Manager) {
214 PassManagers.push_back(Manager);
217 // Add Manager into the list of managers that are not directly
218 // maintained by this top level pass manager
219 inline void addIndirectPassManager(PMDataManager *Manager) {
220 IndirectPassManagers.push_back(Manager);
223 // Print passes managed by this top level manager.
224 void dumpPasses() const;
225 void dumpArguments() const;
227 // Active Pass Managers
231 /// Collection of pass managers
232 SmallVector<PMDataManager *, 8> PassManagers;
235 /// Collection of pass managers that are not directly maintained
236 /// by this pass manager
237 SmallVector<PMDataManager *, 8> IndirectPassManagers;
239 // Map to keep track of last user of the analysis pass.
240 // LastUser->second is the last user of Lastuser->first.
241 DenseMap<Pass *, Pass *> LastUser;
243 // Map to keep track of passes that are last used by a pass.
244 // This inverse map is initialized at PM->run() based on
246 DenseMap<Pass *, SmallPtrSet<Pass *, 8> > InversedLastUser;
248 /// Immutable passes are managed by top level manager.
249 SmallVector<ImmutablePass *, 16> ImmutablePasses;
251 /// Map from ID to immutable passes.
252 SmallDenseMap<AnalysisID, ImmutablePass *, 8> ImmutablePassMap;
255 /// A wrapper around AnalysisUsage for the purpose of uniqueing. The wrapper
256 /// is used to avoid needing to make AnalysisUsage itself a folding set node.
257 struct AUFoldingSetNode : public FoldingSetNode {
259 AUFoldingSetNode(const AnalysisUsage &AU) : AU(AU) {}
260 void Profile(FoldingSetNodeID &ID) const {
263 static void Profile(FoldingSetNodeID &ID, const AnalysisUsage &AU) {
264 // TODO: We could consider sorting the dependency arrays within the
265 // AnalysisUsage (since they are conceptually unordered).
266 ID.AddBoolean(AU.getPreservesAll());
267 auto ProfileVec = [&](const SmallVectorImpl<AnalysisID>& Vec) {
268 ID.AddInteger(Vec.size());
269 for(AnalysisID AID : Vec)
272 ProfileVec(AU.getRequiredSet());
273 ProfileVec(AU.getRequiredTransitiveSet());
274 ProfileVec(AU.getPreservedSet());
275 ProfileVec(AU.getUsedSet());
279 // Contains all of the unique combinations of AnalysisUsage. This is helpful
280 // when we have multiple instances of the same pass since they'll usually
281 // have the same analysis usage and can share storage.
282 FoldingSet<AUFoldingSetNode> UniqueAnalysisUsages;
284 // Allocator used for allocating UAFoldingSetNodes. This handles deletion of
285 // all allocated nodes in one fell swoop.
286 BumpPtrAllocator AUFoldingSetNodeAllocator;
288 // Maps from a pass to it's associated entry in UniqueAnalysisUsages. Does
289 // not own the storage associated with either key or value..
290 DenseMap<Pass *, AnalysisUsage*> AnUsageMap;
292 /// Collection of PassInfo objects found via analysis IDs and in this top
293 /// level manager. This is used to memoize queries to the pass registry.
294 /// FIXME: This is an egregious hack because querying the pass registry is
295 /// either slow or racy.
296 mutable DenseMap<AnalysisID, const PassInfo *> AnalysisPassInfos;
299 //===----------------------------------------------------------------------===//
302 /// PMDataManager provides the common place to manage the analysis data
303 /// used by pass managers.
304 class PMDataManager {
306 explicit PMDataManager() : TPM(nullptr), Depth(0) {
307 initializeAnalysisInfo();
310 virtual ~PMDataManager();
312 virtual Pass *getAsPass() = 0;
314 /// Augment AvailableAnalysis by adding analysis made available by pass P.
315 void recordAvailableAnalysis(Pass *P);
317 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
318 void verifyPreservedAnalysis(Pass *P);
320 /// Remove Analysis that is not preserved by the pass
321 void removeNotPreservedAnalysis(Pass *P);
323 /// Remove dead passes used by P.
324 void removeDeadPasses(Pass *P, StringRef Msg,
325 enum PassDebuggingString);
328 void freePass(Pass *P, StringRef Msg,
329 enum PassDebuggingString);
331 /// Add pass P into the PassVector. Update
332 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
333 void add(Pass *P, bool ProcessAnalysis = true);
335 /// Add RequiredPass into list of lower level passes required by pass P.
336 /// RequiredPass is run on the fly by Pass Manager when P requests it
337 /// through getAnalysis interface.
338 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
340 virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
342 /// Initialize available analysis information.
343 void initializeAnalysisInfo() {
344 AvailableAnalysis.clear();
345 for (unsigned i = 0; i < PMT_Last; ++i)
346 InheritedAnalysis[i] = nullptr;
349 // Return true if P preserves high level analysis used by other
350 // passes that are managed by this manager.
351 bool preserveHigherLevelAnalysis(Pass *P);
353 /// Populate UsedPasses with analysis pass that are used or required by pass
354 /// P and are available. Populate ReqPassNotAvailable with analysis pass that
355 /// are required by pass P but are not available.
356 void collectRequiredAndUsedAnalyses(
357 SmallVectorImpl<Pass *> &UsedPasses,
358 SmallVectorImpl<AnalysisID> &ReqPassNotAvailable, Pass *P);
360 /// All Required analyses should be available to the pass as it runs! Here
361 /// we fill in the AnalysisImpls member of the pass so that it can
362 /// successfully use the getAnalysis() method to retrieve the
363 /// implementations it needs.
364 void initializeAnalysisImpl(Pass *P);
366 /// Find the pass that implements Analysis AID. If desired pass is not found
367 /// then return NULL.
368 Pass *findAnalysisPass(AnalysisID AID, bool Direction);
370 // Access toplevel manager
371 PMTopLevelManager *getTopLevelManager() { return TPM; }
372 void setTopLevelManager(PMTopLevelManager *T) { TPM = T; }
374 unsigned getDepth() const { return Depth; }
375 void setDepth(unsigned newDepth) { Depth = newDepth; }
377 // Print routines used by debug-pass
378 void dumpLastUses(Pass *P, unsigned Offset) const;
379 void dumpPassArguments() const;
380 void dumpPassInfo(Pass *P, enum PassDebuggingString S1,
381 enum PassDebuggingString S2, StringRef Msg);
382 void dumpRequiredSet(const Pass *P) const;
383 void dumpPreservedSet(const Pass *P) const;
384 void dumpUsedSet(const Pass *P) const;
386 unsigned getNumContainedPasses() const {
387 return (unsigned)PassVector.size();
390 virtual PassManagerType getPassManagerType() const {
391 assert ( 0 && "Invalid use of getPassManagerType");
395 DenseMap<AnalysisID, Pass*> *getAvailableAnalysis() {
396 return &AvailableAnalysis;
399 // Collect AvailableAnalysis from all the active Pass Managers.
400 void populateInheritedAnalysis(PMStack &PMS) {
402 for (PMStack::iterator I = PMS.begin(), E = PMS.end();
404 InheritedAnalysis[Index++] = (*I)->getAvailableAnalysis();
408 // Top level manager.
409 PMTopLevelManager *TPM;
411 // Collection of pass that are managed by this manager
412 SmallVector<Pass *, 16> PassVector;
414 // Collection of Analysis provided by Parent pass manager and
415 // used by current pass manager. At at time there can not be more
416 // then PMT_Last active pass mangers.
417 DenseMap<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
419 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
420 /// or higher is specified.
421 bool isPassDebuggingExecutionsOrMore() const;
424 void dumpAnalysisUsage(StringRef Msg, const Pass *P,
425 const AnalysisUsage::VectorType &Set) const;
427 // Set of available Analysis. This information is used while scheduling
428 // pass. If a pass requires an analysis which is not available then
429 // the required analysis pass is scheduled to run before the pass itself is
431 DenseMap<AnalysisID, Pass*> AvailableAnalysis;
433 // Collection of higher level analysis used by the pass managed by
435 SmallVector<Pass *, 16> HigherLevelAnalysis;
440 //===----------------------------------------------------------------------===//
443 /// FPPassManager manages BBPassManagers and FunctionPasses.
444 /// It batches all function passes and basic block pass managers together and
445 /// sequence them to process one function at a time before processing next
447 class FPPassManager : public ModulePass, public PMDataManager {
450 explicit FPPassManager()
451 : ModulePass(ID), PMDataManager() { }
453 /// run - Execute all of the passes scheduled for execution. Keep track of
454 /// whether any of the passes modifies the module, and if so, return true.
455 bool runOnFunction(Function &F);
456 bool runOnModule(Module &M) override;
458 /// cleanup - After running all passes, clean up pass manager cache.
461 /// doInitialization - Overrides ModulePass doInitialization for global
462 /// initialization tasks
464 using ModulePass::doInitialization;
466 /// doInitialization - Run all of the initializers for the function passes.
468 bool doInitialization(Module &M) override;
470 /// doFinalization - Overrides ModulePass doFinalization for global
471 /// finalization tasks
473 using ModulePass::doFinalization;
475 /// doFinalization - Run all of the finalizers for the function passes.
477 bool doFinalization(Module &M) override;
479 PMDataManager *getAsPMDataManager() override { return this; }
480 Pass *getAsPass() override { return this; }
482 /// Pass Manager itself does not invalidate any analysis info.
483 void getAnalysisUsage(AnalysisUsage &Info) const override {
484 Info.setPreservesAll();
487 // Print passes managed by this manager
488 void dumpPassStructure(unsigned Offset) override;
490 const char *getPassName() const override {
491 return "Function Pass Manager";
494 FunctionPass *getContainedPass(unsigned N) {
495 assert ( N < PassVector.size() && "Pass number out of range!");
496 FunctionPass *FP = static_cast<FunctionPass *>(PassVector[N]);
500 PassManagerType getPassManagerType() const override {
501 return PMT_FunctionPassManager;
505 Timer *getPassTimer(Pass *);