1 //===- LegacyPassManagers.h - Legacy Pass Infrastructure --------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file declares the LLVM Pass Manager infrastructure.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_IR_LEGACYPASSMANAGERS_H
14 #define LLVM_IR_LEGACYPASSMANAGERS_H
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Pass.h"
23 //===----------------------------------------------------------------------===//
25 // The Pass Manager Infrastructure manages passes. It's responsibilities are:
27 // o Manage optimization pass execution order
28 // o Make required Analysis information available before pass P is run
29 // o Release memory occupied by dead passes
30 // o If Analysis information is dirtied by a pass then regenerate Analysis
31 // information before it is consumed by another pass.
33 // Pass Manager Infrastructure uses multiple pass managers. They are
34 // PassManager, FunctionPassManager, MPPassManager, FPPassManager, BBPassManager.
35 // This class hierarchy uses multiple inheritance but pass managers do not
36 // derive from another pass manager.
38 // PassManager and FunctionPassManager are two top-level pass manager that
39 // represents the external interface of this entire pass manager infrastucture.
41 // Important classes :
43 // [o] class PMTopLevelManager;
45 // Two top level managers, PassManager and FunctionPassManager, derive from
46 // PMTopLevelManager. PMTopLevelManager manages information used by top level
47 // managers such as last user info.
49 // [o] class PMDataManager;
51 // PMDataManager manages information, e.g. list of available analysis info,
52 // used by a pass manager to manage execution order of passes. It also provides
53 // a place to implement common pass manager APIs. All pass managers derive from
56 // [o] class BBPassManager : public FunctionPass, public PMDataManager;
58 // BBPassManager manages BasicBlockPasses.
60 // [o] class FunctionPassManager;
62 // This is a external interface used to manage FunctionPasses. This
63 // interface relies on FunctionPassManagerImpl to do all the tasks.
65 // [o] class FunctionPassManagerImpl : public ModulePass, PMDataManager,
66 // public PMTopLevelManager;
68 // FunctionPassManagerImpl is a top level manager. It manages FPPassManagers
70 // [o] class FPPassManager : public ModulePass, public PMDataManager;
72 // FPPassManager manages FunctionPasses and BBPassManagers
74 // [o] class MPPassManager : public Pass, public PMDataManager;
76 // MPPassManager manages ModulePasses and FPPassManagers
78 // [o] class PassManager;
80 // This is a external interface used by various tools to manages passes. It
81 // relies on PassManagerImpl to do all the tasks.
83 // [o] class PassManagerImpl : public Pass, public PMDataManager,
84 // public PMTopLevelManager
86 // PassManagerImpl is a top level pass manager responsible for managing
88 //===----------------------------------------------------------------------===//
90 #include "llvm/Support/PrettyStackTrace.h"
93 template <typename T
> class ArrayRef
;
101 // enums for debugging strings
102 enum PassDebuggingString
{
103 EXECUTION_MSG
, // "Executing Pass '" + PassName
104 MODIFICATION_MSG
, // "Made Modification '" + PassName
105 FREEING_MSG
, // " Freeing Pass '" + PassName
106 ON_BASICBLOCK_MSG
, // "' on BasicBlock '" + InstructionName + "'...\n"
107 ON_FUNCTION_MSG
, // "' on Function '" + FunctionName + "'...\n"
108 ON_MODULE_MSG
, // "' on Module '" + ModuleName + "'...\n"
109 ON_REGION_MSG
, // "' on Region '" + Msg + "'...\n'"
110 ON_LOOP_MSG
, // "' on Loop '" + Msg + "'...\n'"
111 ON_CG_MSG
// "' on Call Graph Nodes '" + Msg + "'...\n'"
114 /// PassManagerPrettyStackEntry - This is used to print informative information
115 /// about what pass is running when/if a stack trace is generated.
116 class PassManagerPrettyStackEntry
: public PrettyStackTraceEntry
{
122 explicit PassManagerPrettyStackEntry(Pass
*p
)
123 : P(p
), V(nullptr), M(nullptr) {} // When P is releaseMemory'd.
124 PassManagerPrettyStackEntry(Pass
*p
, Value
&v
)
125 : P(p
), V(&v
), M(nullptr) {} // When P is run on V
126 PassManagerPrettyStackEntry(Pass
*p
, Module
&m
)
127 : P(p
), V(nullptr), M(&m
) {} // When P is run on M
129 /// print - Emit information about this stack frame to OS.
130 void print(raw_ostream
&OS
) const override
;
133 //===----------------------------------------------------------------------===//
136 /// PMStack - This class implements a stack data structure of PMDataManager
139 /// Top level pass managers (see PassManager.cpp) maintain active Pass Managers
140 /// using PMStack. Each Pass implements assignPassManager() to connect itself
141 /// with appropriate manager. assignPassManager() walks PMStack to find
142 /// suitable manager.
145 typedef std::vector
<PMDataManager
*>::const_reverse_iterator iterator
;
146 iterator
begin() const { return S
.rbegin(); }
147 iterator
end() const { return S
.rend(); }
150 PMDataManager
*top() const { return S
.back(); }
151 void push(PMDataManager
*PM
);
152 bool empty() const { return S
.empty(); }
157 std::vector
<PMDataManager
*> S
;
160 //===----------------------------------------------------------------------===//
163 /// PMTopLevelManager manages LastUser info and collects common APIs used by
164 /// top level pass managers.
165 class PMTopLevelManager
{
167 explicit PMTopLevelManager(PMDataManager
*PMDM
);
169 unsigned getNumContainedManagers() const {
170 return (unsigned)PassManagers
.size();
173 void initializeAllAnalysisInfo();
176 virtual PMDataManager
*getAsPMDataManager() = 0;
177 virtual PassManagerType
getTopLevelPassManagerType() = 0;
180 /// Schedule pass P for execution. Make sure that passes required by
181 /// P are run before P is run. Update analysis info maintained by
182 /// the manager. Remove dead passes. This is a recursive function.
183 void schedulePass(Pass
*P
);
185 /// Set pass P as the last user of the given analysis passes.
186 void setLastUser(ArrayRef
<Pass
*> AnalysisPasses
, Pass
*P
);
188 /// Collect passes whose last user is P
189 void collectLastUses(SmallVectorImpl
<Pass
*> &LastUses
, Pass
*P
);
191 /// Find the pass that implements Analysis AID. Search immutable
192 /// passes and all pass managers. If desired pass is not found
193 /// then return NULL.
194 Pass
*findAnalysisPass(AnalysisID AID
);
196 /// Retrieve the PassInfo for an analysis.
197 const PassInfo
*findAnalysisPassInfo(AnalysisID AID
) const;
199 /// Find analysis usage information for the pass P.
200 AnalysisUsage
*findAnalysisUsage(Pass
*P
);
202 virtual ~PMTopLevelManager();
204 /// Add immutable pass and initialize it.
205 void addImmutablePass(ImmutablePass
*P
);
207 inline SmallVectorImpl
<ImmutablePass
*>& getImmutablePasses() {
208 return ImmutablePasses
;
211 void addPassManager(PMDataManager
*Manager
) {
212 PassManagers
.push_back(Manager
);
215 // Add Manager into the list of managers that are not directly
216 // maintained by this top level pass manager
217 inline void addIndirectPassManager(PMDataManager
*Manager
) {
218 IndirectPassManagers
.push_back(Manager
);
221 // Print passes managed by this top level manager.
222 void dumpPasses() const;
223 void dumpArguments() const;
225 // Active Pass Managers
229 /// Collection of pass managers
230 SmallVector
<PMDataManager
*, 8> PassManagers
;
233 /// Collection of pass managers that are not directly maintained
234 /// by this pass manager
235 SmallVector
<PMDataManager
*, 8> IndirectPassManagers
;
237 // Map to keep track of last user of the analysis pass.
238 // LastUser->second is the last user of Lastuser->first.
239 DenseMap
<Pass
*, Pass
*> LastUser
;
241 // Map to keep track of passes that are last used by a pass.
242 // This inverse map is initialized at PM->run() based on
244 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> > InversedLastUser
;
246 /// Immutable passes are managed by top level manager.
247 SmallVector
<ImmutablePass
*, 16> ImmutablePasses
;
249 /// Map from ID to immutable passes.
250 SmallDenseMap
<AnalysisID
, ImmutablePass
*, 8> ImmutablePassMap
;
253 /// A wrapper around AnalysisUsage for the purpose of uniqueing. The wrapper
254 /// is used to avoid needing to make AnalysisUsage itself a folding set node.
255 struct AUFoldingSetNode
: public FoldingSetNode
{
257 AUFoldingSetNode(const AnalysisUsage
&AU
) : AU(AU
) {}
258 void Profile(FoldingSetNodeID
&ID
) const {
261 static void Profile(FoldingSetNodeID
&ID
, const AnalysisUsage
&AU
) {
262 // TODO: We could consider sorting the dependency arrays within the
263 // AnalysisUsage (since they are conceptually unordered).
264 ID
.AddBoolean(AU
.getPreservesAll());
265 auto ProfileVec
= [&](const SmallVectorImpl
<AnalysisID
>& Vec
) {
266 ID
.AddInteger(Vec
.size());
267 for(AnalysisID AID
: Vec
)
270 ProfileVec(AU
.getRequiredSet());
271 ProfileVec(AU
.getRequiredTransitiveSet());
272 ProfileVec(AU
.getPreservedSet());
273 ProfileVec(AU
.getUsedSet());
277 // Contains all of the unique combinations of AnalysisUsage. This is helpful
278 // when we have multiple instances of the same pass since they'll usually
279 // have the same analysis usage and can share storage.
280 FoldingSet
<AUFoldingSetNode
> UniqueAnalysisUsages
;
282 // Allocator used for allocating UAFoldingSetNodes. This handles deletion of
283 // all allocated nodes in one fell swoop.
284 SpecificBumpPtrAllocator
<AUFoldingSetNode
> AUFoldingSetNodeAllocator
;
286 // Maps from a pass to it's associated entry in UniqueAnalysisUsages. Does
287 // not own the storage associated with either key or value..
288 DenseMap
<Pass
*, AnalysisUsage
*> AnUsageMap
;
290 /// Collection of PassInfo objects found via analysis IDs and in this top
291 /// level manager. This is used to memoize queries to the pass registry.
292 /// FIXME: This is an egregious hack because querying the pass registry is
293 /// either slow or racy.
294 mutable DenseMap
<AnalysisID
, const PassInfo
*> AnalysisPassInfos
;
297 //===----------------------------------------------------------------------===//
300 /// PMDataManager provides the common place to manage the analysis data
301 /// used by pass managers.
302 class PMDataManager
{
304 explicit PMDataManager() : TPM(nullptr), Depth(0) {
305 initializeAnalysisInfo();
308 virtual ~PMDataManager();
310 virtual Pass
*getAsPass() = 0;
312 /// Augment AvailableAnalysis by adding analysis made available by pass P.
313 void recordAvailableAnalysis(Pass
*P
);
315 /// verifyPreservedAnalysis -- Verify analysis presreved by pass P.
316 void verifyPreservedAnalysis(Pass
*P
);
318 /// Remove Analysis that is not preserved by the pass
319 void removeNotPreservedAnalysis(Pass
*P
);
321 /// Remove dead passes used by P.
322 void removeDeadPasses(Pass
*P
, StringRef Msg
,
323 enum PassDebuggingString
);
326 void freePass(Pass
*P
, StringRef Msg
,
327 enum PassDebuggingString
);
329 /// Add pass P into the PassVector. Update
330 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
331 void add(Pass
*P
, bool ProcessAnalysis
= true);
333 /// Add RequiredPass into list of lower level passes required by pass P.
334 /// RequiredPass is run on the fly by Pass Manager when P requests it
335 /// through getAnalysis interface.
336 virtual void addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
);
338 virtual Pass
*getOnTheFlyPass(Pass
*P
, AnalysisID PI
, Function
&F
);
340 /// Initialize available analysis information.
341 void initializeAnalysisInfo() {
342 AvailableAnalysis
.clear();
343 for (unsigned i
= 0; i
< PMT_Last
; ++i
)
344 InheritedAnalysis
[i
] = nullptr;
347 // Return true if P preserves high level analysis used by other
348 // passes that are managed by this manager.
349 bool preserveHigherLevelAnalysis(Pass
*P
);
351 /// Populate UsedPasses with analysis pass that are used or required by pass
352 /// P and are available. Populate ReqPassNotAvailable with analysis pass that
353 /// are required by pass P but are not available.
354 void collectRequiredAndUsedAnalyses(
355 SmallVectorImpl
<Pass
*> &UsedPasses
,
356 SmallVectorImpl
<AnalysisID
> &ReqPassNotAvailable
, Pass
*P
);
358 /// All Required analyses should be available to the pass as it runs! Here
359 /// we fill in the AnalysisImpls member of the pass so that it can
360 /// successfully use the getAnalysis() method to retrieve the
361 /// implementations it needs.
362 void initializeAnalysisImpl(Pass
*P
);
364 /// Find the pass that implements Analysis AID. If desired pass is not found
365 /// then return NULL.
366 Pass
*findAnalysisPass(AnalysisID AID
, bool Direction
);
368 // Access toplevel manager
369 PMTopLevelManager
*getTopLevelManager() { return TPM
; }
370 void setTopLevelManager(PMTopLevelManager
*T
) { TPM
= T
; }
372 unsigned getDepth() const { return Depth
; }
373 void setDepth(unsigned newDepth
) { Depth
= newDepth
; }
375 // Print routines used by debug-pass
376 void dumpLastUses(Pass
*P
, unsigned Offset
) const;
377 void dumpPassArguments() const;
378 void dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
379 enum PassDebuggingString S2
, StringRef Msg
);
380 void dumpRequiredSet(const Pass
*P
) const;
381 void dumpPreservedSet(const Pass
*P
) const;
382 void dumpUsedSet(const Pass
*P
) const;
384 unsigned getNumContainedPasses() const {
385 return (unsigned)PassVector
.size();
388 virtual PassManagerType
getPassManagerType() const {
389 assert ( 0 && "Invalid use of getPassManagerType");
393 DenseMap
<AnalysisID
, Pass
*> *getAvailableAnalysis() {
394 return &AvailableAnalysis
;
397 // Collect AvailableAnalysis from all the active Pass Managers.
398 void populateInheritedAnalysis(PMStack
&PMS
) {
400 for (PMStack::iterator I
= PMS
.begin(), E
= PMS
.end();
402 InheritedAnalysis
[Index
++] = (*I
)->getAvailableAnalysis();
405 /// Set the initial size of the module if the user has specified that they
406 /// want remarks for size.
407 /// Returns 0 if the remark was not requested.
408 unsigned initSizeRemarkInfo(
410 StringMap
<std::pair
<unsigned, unsigned>> &FunctionToInstrCount
);
412 /// Emit a remark signifying that the number of IR instructions in the module
414 /// \p F is optionally passed by passes which run on Functions, and thus
415 /// always know whether or not a non-empty function is available.
417 /// \p FunctionToInstrCount maps the name of a \p Function to a pair. The
418 /// first member of the pair is the IR count of the \p Function before running
419 /// \p P, and the second member is the IR count of the \p Function after
421 void emitInstrCountChangedRemark(
422 Pass
*P
, Module
&M
, int64_t Delta
, unsigned CountBefore
,
423 StringMap
<std::pair
<unsigned, unsigned>> &FunctionToInstrCount
,
424 Function
*F
= nullptr);
427 // Top level manager.
428 PMTopLevelManager
*TPM
;
430 // Collection of pass that are managed by this manager
431 SmallVector
<Pass
*, 16> PassVector
;
433 // Collection of Analysis provided by Parent pass manager and
434 // used by current pass manager. At at time there can not be more
435 // then PMT_Last active pass mangers.
436 DenseMap
<AnalysisID
, Pass
*> *InheritedAnalysis
[PMT_Last
];
438 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
439 /// or higher is specified.
440 bool isPassDebuggingExecutionsOrMore() const;
443 void dumpAnalysisUsage(StringRef Msg
, const Pass
*P
,
444 const AnalysisUsage::VectorType
&Set
) const;
446 // Set of available Analysis. This information is used while scheduling
447 // pass. If a pass requires an analysis which is not available then
448 // the required analysis pass is scheduled to run before the pass itself is
450 DenseMap
<AnalysisID
, Pass
*> AvailableAnalysis
;
452 // Collection of higher level analysis used by the pass managed by
454 SmallVector
<Pass
*, 16> HigherLevelAnalysis
;
459 //===----------------------------------------------------------------------===//
462 /// FPPassManager manages BBPassManagers and FunctionPasses.
463 /// It batches all function passes and basic block pass managers together and
464 /// sequence them to process one function at a time before processing next
466 class FPPassManager
: public ModulePass
, public PMDataManager
{
469 explicit FPPassManager()
470 : ModulePass(ID
), PMDataManager() { }
472 /// run - Execute all of the passes scheduled for execution. Keep track of
473 /// whether any of the passes modifies the module, and if so, return true.
474 bool runOnFunction(Function
&F
);
475 bool runOnModule(Module
&M
) override
;
477 /// cleanup - After running all passes, clean up pass manager cache.
480 /// doInitialization - Overrides ModulePass doInitialization for global
481 /// initialization tasks
483 using ModulePass::doInitialization
;
485 /// doInitialization - Run all of the initializers for the function passes.
487 bool doInitialization(Module
&M
) override
;
489 /// doFinalization - Overrides ModulePass doFinalization for global
490 /// finalization tasks
492 using ModulePass::doFinalization
;
494 /// doFinalization - Run all of the finalizers for the function passes.
496 bool doFinalization(Module
&M
) override
;
498 PMDataManager
*getAsPMDataManager() override
{ return this; }
499 Pass
*getAsPass() override
{ return this; }
501 /// Pass Manager itself does not invalidate any analysis info.
502 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
503 Info
.setPreservesAll();
506 // Print passes managed by this manager
507 void dumpPassStructure(unsigned Offset
) override
;
509 StringRef
getPassName() const override
{ return "Function Pass Manager"; }
511 FunctionPass
*getContainedPass(unsigned N
) {
512 assert ( N
< PassVector
.size() && "Pass number out of range!");
513 FunctionPass
*FP
= static_cast<FunctionPass
*>(PassVector
[N
]);
517 PassManagerType
getPassManagerType() const override
{
518 return PMT_FunctionPassManager
;