1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
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 implements the legacy LLVM Pass Manager infrastructure.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/LegacyPassManager.h"
14 #include "llvm/ADT/MapVector.h"
15 #include "llvm/IR/DiagnosticInfo.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/PassTimingInfo.h"
21 #include "llvm/IR/PrintPasses.h"
22 #include "llvm/Support/Chrono.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/TimeProfiler.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
34 extern cl::opt
<bool> UseNewDbgInfoFormat
;
35 // See PassManagers.h for Pass Manager infrastructure overview.
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information. Often it is useful to find out what pass is
39 // running when a crash occurs in a utility. When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
45 // Different debug levels that can be enabled...
47 Disabled
, Arguments
, Structure
, Executions
, Details
51 static cl::opt
<enum PassDebugLevel
> PassDebugging(
52 "debug-pass", cl::Hidden
,
53 cl::desc("Print legacy PassManager debugging information"),
54 cl::values(clEnumVal(Disabled
, "disable debug output"),
55 clEnumVal(Arguments
, "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure
, "print pass structure before run()"),
57 clEnumVal(Executions
, "print pass name before it is executed"),
58 clEnumVal(Details
, "print pass details when it is executed")));
60 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
61 /// or higher is specified.
62 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
63 return PassDebugging
>= Executions
;
66 unsigned PMDataManager::initSizeRemarkInfo(
67 Module
&M
, StringMap
<std::pair
<unsigned, unsigned>> &FunctionToInstrCount
) {
68 // Only calculate getInstructionCount if the size-info remark is requested.
69 unsigned InstrCount
= 0;
71 // Collect instruction counts for every function. We'll use this to emit
72 // per-function size remarks later.
73 for (Function
&F
: M
) {
74 unsigned FCount
= F
.getInstructionCount();
76 // Insert a record into FunctionToInstrCount keeping track of the current
77 // size of the function as the first member of a pair. Set the second
78 // member to 0; if the function is deleted by the pass, then when we get
79 // here, we'll be able to let the user know that F no longer contributes to
81 FunctionToInstrCount
[F
.getName().str()] =
82 std::pair
<unsigned, unsigned>(FCount
, 0);
88 void PMDataManager::emitInstrCountChangedRemark(
89 Pass
*P
, Module
&M
, int64_t Delta
, unsigned CountBefore
,
90 StringMap
<std::pair
<unsigned, unsigned>> &FunctionToInstrCount
,
92 // If it's a pass manager, don't emit a remark. (This hinges on the assumption
93 // that the only passes that return non-null with getAsPMDataManager are pass
94 // managers.) The reason we have to do this is to avoid emitting remarks for
96 if (P
->getAsPMDataManager())
99 // Set to true if this isn't a module pass or CGSCC pass.
100 bool CouldOnlyImpactOneFunction
= (F
!= nullptr);
102 // Helper lambda that updates the changes to the size of some function.
103 auto UpdateFunctionChanges
=
104 [&FunctionToInstrCount
](Function
&MaybeChangedFn
) {
105 // Update the total module count.
106 unsigned FnSize
= MaybeChangedFn
.getInstructionCount();
108 // If we created a new function, then we need to add it to the map and
109 // say that it changed from 0 instructions to FnSize.
110 auto [It
, Inserted
] = FunctionToInstrCount
.try_emplace(
111 MaybeChangedFn
.getName(), 0, FnSize
);
114 // Insert the new function size into the second member of the pair. This
115 // tells us whether or not this function changed in size.
116 It
->second
.second
= FnSize
;
119 // We need to initially update all of the function sizes.
120 // If no function was passed in, then we're either a module pass or an
122 if (!CouldOnlyImpactOneFunction
)
123 std::for_each(M
.begin(), M
.end(), UpdateFunctionChanges
);
125 UpdateFunctionChanges(*F
);
127 // Do we have a function we can use to emit a remark?
128 if (!CouldOnlyImpactOneFunction
) {
129 // We need a function containing at least one basic block in order to output
130 // remarks. Since it's possible that the first function in the module
131 // doesn't actually contain a basic block, we have to go and find one that's
132 // suitable for emitting remarks.
133 auto It
= llvm::find_if(M
, [](const Function
&Fn
) { return !Fn
.empty(); });
135 // Didn't find a function. Quit.
139 // We found a function containing at least one basic block.
142 int64_t CountAfter
= static_cast<int64_t>(CountBefore
) + Delta
;
143 BasicBlock
&BB
= *F
->begin();
144 OptimizationRemarkAnalysis
R("size-info", "IRSizeChange",
145 DiagnosticLocation(), &BB
);
146 // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
147 // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
148 R
<< DiagnosticInfoOptimizationBase::Argument("Pass", P
->getPassName())
149 << ": IR instruction count changed from "
150 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore
)
152 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter
)
154 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta
);
155 F
->getContext().diagnose(R
); // Not using ORE for layering reasons.
157 // Emit per-function size change remarks separately.
158 std::string PassName
= P
->getPassName().str();
160 // Helper lambda that emits a remark when the size of a function has changed.
161 auto EmitFunctionSizeChangedRemark
= [&FunctionToInstrCount
, &F
, &BB
,
162 &PassName
](StringRef Fname
) {
163 unsigned FnCountBefore
, FnCountAfter
;
164 std::pair
<unsigned, unsigned> &Change
= FunctionToInstrCount
[Fname
];
165 std::tie(FnCountBefore
, FnCountAfter
) = Change
;
166 int64_t FnDelta
= static_cast<int64_t>(FnCountAfter
) -
167 static_cast<int64_t>(FnCountBefore
);
172 // FIXME: We shouldn't use BB for the location here. Unfortunately, because
173 // the function that we're looking at could have been deleted, we can't use
174 // it for the source location. We *want* remarks when a function is deleted
175 // though, so we're kind of stuck here as is. (This remark, along with the
176 // whole-module size change remarks really ought not to have source
177 // locations at all.)
178 OptimizationRemarkAnalysis
FR("size-info", "FunctionIRSizeChange",
179 DiagnosticLocation(), &BB
);
180 FR
<< DiagnosticInfoOptimizationBase::Argument("Pass", PassName
)
182 << DiagnosticInfoOptimizationBase::Argument("Function", Fname
)
183 << ": IR instruction count changed from "
184 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",
187 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",
190 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta
);
191 F
->getContext().diagnose(FR
);
193 // Update the function size.
194 Change
.first
= FnCountAfter
;
197 // Are we looking at more than one function? If so, emit remarks for all of
198 // the functions in the module. Otherwise, only emit one remark.
199 if (!CouldOnlyImpactOneFunction
)
200 std::for_each(FunctionToInstrCount
.keys().begin(),
201 FunctionToInstrCount
.keys().end(),
202 EmitFunctionSizeChangedRemark
);
204 EmitFunctionSizeChangedRemark(F
->getName().str());
207 void PassManagerPrettyStackEntry::print(raw_ostream
&OS
) const {
209 OS
<< "Releasing pass '";
211 OS
<< "Running pass '";
213 OS
<< P
->getPassName() << "'";
216 OS
<< " on module '" << M
->getModuleIdentifier() << "'.\n";
225 if (isa
<Function
>(V
))
227 else if (isa
<BasicBlock
>(V
))
233 V
->printAsOperand(OS
, /*PrintType=*/false, M
);
239 bool debugPassSpecified() { return PassDebugging
!= Disabled
; }
241 //===----------------------------------------------------------------------===//
242 // FunctionPassManagerImpl
244 /// FunctionPassManagerImpl manages FPPassManagers
245 class FunctionPassManagerImpl
: public Pass
,
246 public PMDataManager
,
247 public PMTopLevelManager
{
248 virtual void anchor();
253 explicit FunctionPassManagerImpl()
254 : Pass(PT_PassManager
, ID
), PMTopLevelManager(new FPPassManager()),
257 /// \copydoc FunctionPassManager::add()
262 /// createPrinterPass - Get a function printer pass.
263 Pass
*createPrinterPass(raw_ostream
&O
,
264 const std::string
&Banner
) const override
{
265 return createPrintFunctionPass(O
, Banner
);
268 // Prepare for running an on the fly pass, freeing memory if needed
269 // from a previous run.
270 void releaseMemoryOnTheFly();
272 /// run - Execute all of the passes scheduled for execution. Keep track of
273 /// whether any of the passes modifies the module, and if so, return true.
274 bool run(Function
&F
);
276 /// doInitialization - Run all of the initializers for the function passes.
278 bool doInitialization(Module
&M
) override
;
280 /// doFinalization - Run all of the finalizers for the function passes.
282 bool doFinalization(Module
&M
) override
;
285 PMDataManager
*getAsPMDataManager() override
{ return this; }
286 Pass
*getAsPass() override
{ return this; }
287 PassManagerType
getTopLevelPassManagerType() override
{
288 return PMT_FunctionPassManager
;
291 /// Pass Manager itself does not invalidate any analysis info.
292 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
293 Info
.setPreservesAll();
296 FPPassManager
*getContainedManager(unsigned N
) {
297 assert(N
< PassManagers
.size() && "Pass number out of range!");
298 FPPassManager
*FP
= static_cast<FPPassManager
*>(PassManagers
[N
]);
302 void dumpPassStructure(unsigned Offset
) override
{
303 for (unsigned I
= 0; I
< getNumContainedManagers(); ++I
)
304 getContainedManager(I
)->dumpPassStructure(Offset
);
308 void FunctionPassManagerImpl::anchor() {}
310 char FunctionPassManagerImpl::ID
= 0;
312 //===----------------------------------------------------------------------===//
313 // FunctionPassManagerImpl implementation
315 bool FunctionPassManagerImpl::doInitialization(Module
&M
) {
316 bool Changed
= false;
321 for (ImmutablePass
*ImPass
: getImmutablePasses())
322 Changed
|= ImPass
->doInitialization(M
);
324 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
325 Changed
|= getContainedManager(Index
)->doInitialization(M
);
330 bool FunctionPassManagerImpl::doFinalization(Module
&M
) {
331 bool Changed
= false;
333 for (int Index
= getNumContainedManagers() - 1; Index
>= 0; --Index
)
334 Changed
|= getContainedManager(Index
)->doFinalization(M
);
336 for (ImmutablePass
*ImPass
: getImmutablePasses())
337 Changed
|= ImPass
->doFinalization(M
);
342 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
345 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
346 FPPassManager
*FPPM
= getContainedManager(Index
);
347 for (unsigned Index
= 0; Index
< FPPM
->getNumContainedPasses(); ++Index
) {
348 FPPM
->getContainedPass(Index
)->releaseMemory();
354 // Execute all the passes managed by this top level manager.
355 // Return true if any function is modified by a pass.
356 bool FunctionPassManagerImpl::run(Function
&F
) {
357 bool Changed
= false;
359 initializeAllAnalysisInfo();
360 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
361 Changed
|= getContainedManager(Index
)->runOnFunction(F
);
362 F
.getContext().yield();
365 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
366 getContainedManager(Index
)->cleanup();
371 } // namespace legacy
375 //===----------------------------------------------------------------------===//
378 /// MPPassManager manages ModulePasses and function pass managers.
379 /// It batches all Module passes and function pass managers together and
380 /// sequences them to process one module.
381 class MPPassManager
: public Pass
, public PMDataManager
{
384 explicit MPPassManager() : Pass(PT_PassManager
, ID
) {}
386 // Delete on the fly managers.
387 ~MPPassManager() override
{
388 for (auto &OnTheFlyManager
: OnTheFlyManagers
) {
389 legacy::FunctionPassManagerImpl
*FPP
= OnTheFlyManager
.second
;
394 /// createPrinterPass - Get a module printer pass.
395 Pass
*createPrinterPass(raw_ostream
&O
,
396 const std::string
&Banner
) const override
{
397 return createPrintModulePass(O
, Banner
);
400 /// run - Execute all of the passes scheduled for execution. Keep track of
401 /// whether any of the passes modifies the module, and if so, return true.
402 bool runOnModule(Module
&M
);
404 using llvm::Pass::doInitialization
;
405 using llvm::Pass::doFinalization
;
407 /// Pass Manager itself does not invalidate any analysis info.
408 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
409 Info
.setPreservesAll();
412 /// Add RequiredPass into list of lower level passes required by pass P.
413 /// RequiredPass is run on the fly by Pass Manager when P requests it
414 /// through getAnalysis interface.
415 void addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) override
;
417 /// Return function pass corresponding to PassInfo PI, that is
418 /// required by module pass MP. Instantiate analysis pass, by using
419 /// its runOnFunction() for function F.
420 std::tuple
<Pass
*, bool> getOnTheFlyPass(Pass
*MP
, AnalysisID PI
,
421 Function
&F
) override
;
423 StringRef
getPassName() const override
{ return "Module Pass Manager"; }
425 PMDataManager
*getAsPMDataManager() override
{ return this; }
426 Pass
*getAsPass() override
{ return this; }
428 // Print passes managed by this manager
429 void dumpPassStructure(unsigned Offset
) override
{
430 dbgs().indent(Offset
*2) << "ModulePass Manager\n";
431 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
432 ModulePass
*MP
= getContainedPass(Index
);
433 MP
->dumpPassStructure(Offset
+ 1);
434 MapVector
<Pass
*, legacy::FunctionPassManagerImpl
*>::const_iterator I
=
435 OnTheFlyManagers
.find(MP
);
436 if (I
!= OnTheFlyManagers
.end())
437 I
->second
->dumpPassStructure(Offset
+ 2);
438 dumpLastUses(MP
, Offset
+1);
442 ModulePass
*getContainedPass(unsigned N
) {
443 assert(N
< PassVector
.size() && "Pass number out of range!");
444 return static_cast<ModulePass
*>(PassVector
[N
]);
447 PassManagerType
getPassManagerType() const override
{
448 return PMT_ModulePassManager
;
452 /// Collection of on the fly FPPassManagers. These managers manage
453 /// function passes that are required by module passes.
454 MapVector
<Pass
*, legacy::FunctionPassManagerImpl
*> OnTheFlyManagers
;
457 char MPPassManager::ID
= 0;
458 } // End anonymous namespace
462 //===----------------------------------------------------------------------===//
466 /// PassManagerImpl manages MPPassManagers
467 class PassManagerImpl
: public Pass
,
468 public PMDataManager
,
469 public PMTopLevelManager
{
470 virtual void anchor();
474 explicit PassManagerImpl()
475 : Pass(PT_PassManager
, ID
), PMTopLevelManager(new MPPassManager()) {}
477 /// \copydoc PassManager::add()
482 /// createPrinterPass - Get a module printer pass.
483 Pass
*createPrinterPass(raw_ostream
&O
,
484 const std::string
&Banner
) const override
{
485 return createPrintModulePass(O
, Banner
);
488 /// run - Execute all of the passes scheduled for execution. Keep track of
489 /// whether any of the passes modifies the module, and if so, return true.
492 using llvm::Pass::doInitialization
;
493 using llvm::Pass::doFinalization
;
495 /// Pass Manager itself does not invalidate any analysis info.
496 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
497 Info
.setPreservesAll();
500 PMDataManager
*getAsPMDataManager() override
{ return this; }
501 Pass
*getAsPass() override
{ return this; }
502 PassManagerType
getTopLevelPassManagerType() override
{
503 return PMT_ModulePassManager
;
506 MPPassManager
*getContainedManager(unsigned N
) {
507 assert(N
< PassManagers
.size() && "Pass number out of range!");
508 MPPassManager
*MP
= static_cast<MPPassManager
*>(PassManagers
[N
]);
513 void PassManagerImpl::anchor() {}
515 char PassManagerImpl::ID
= 0;
517 //===----------------------------------------------------------------------===//
518 // PassManagerImpl implementation
521 /// run - Execute all of the passes scheduled for execution. Keep track of
522 /// whether any of the passes modifies the module, and if so, return true.
523 bool PassManagerImpl::run(Module
&M
) {
524 bool Changed
= false;
529 // RemoveDIs: if a command line flag is given, convert to the
530 // DbgVariableRecord representation of debug-info for the duration of these
532 ScopedDbgInfoFormatSetter
FormatSetter(M
, UseNewDbgInfoFormat
);
534 for (ImmutablePass
*ImPass
: getImmutablePasses())
535 Changed
|= ImPass
->doInitialization(M
);
537 initializeAllAnalysisInfo();
538 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
539 Changed
|= getContainedManager(Index
)->runOnModule(M
);
540 M
.getContext().yield();
543 for (ImmutablePass
*ImPass
: getImmutablePasses())
544 Changed
|= ImPass
->doFinalization(M
);
548 } // namespace legacy
551 //===----------------------------------------------------------------------===//
552 // PMTopLevelManager implementation
554 /// Initialize top level manager. Create first pass manager.
555 PMTopLevelManager::PMTopLevelManager(PMDataManager
*PMDM
) {
556 PMDM
->setTopLevelManager(this);
557 addPassManager(PMDM
);
558 activeStack
.push(PMDM
);
561 /// Set pass P as the last user of the given analysis passes.
563 PMTopLevelManager::setLastUser(ArrayRef
<Pass
*> AnalysisPasses
, Pass
*P
) {
565 if (P
->getResolver())
566 PDepth
= P
->getResolver()->getPMDataManager().getDepth();
568 for (Pass
*AP
: AnalysisPasses
) {
569 // Record P as the new last user of AP.
570 auto &LastUserOfAP
= LastUser
[AP
];
572 InversedLastUser
[LastUserOfAP
].erase(AP
);
574 InversedLastUser
[P
].insert(AP
);
579 // Update the last users of passes that are required transitive by AP.
580 AnalysisUsage
*AnUsage
= findAnalysisUsage(AP
);
581 const AnalysisUsage::VectorType
&IDs
= AnUsage
->getRequiredTransitiveSet();
582 SmallVector
<Pass
*, 12> LastUses
;
583 SmallVector
<Pass
*, 12> LastPMUses
;
584 for (AnalysisID ID
: IDs
) {
585 Pass
*AnalysisPass
= findAnalysisPass(ID
);
586 assert(AnalysisPass
&& "Expected analysis pass to exist.");
587 AnalysisResolver
*AR
= AnalysisPass
->getResolver();
588 assert(AR
&& "Expected analysis resolver to exist.");
589 unsigned APDepth
= AR
->getPMDataManager().getDepth();
591 if (PDepth
== APDepth
)
592 LastUses
.push_back(AnalysisPass
);
593 else if (PDepth
> APDepth
)
594 LastPMUses
.push_back(AnalysisPass
);
597 setLastUser(LastUses
, P
);
599 // If this pass has a corresponding pass manager, push higher level
600 // analysis to this pass manager.
601 if (P
->getResolver())
602 setLastUser(LastPMUses
, P
->getResolver()->getPMDataManager().getAsPass());
604 // If AP is the last user of other passes then make P last user of
606 auto &LastUsedByAP
= InversedLastUser
[AP
];
607 for (Pass
*L
: LastUsedByAP
)
609 InversedLastUser
[P
].insert(LastUsedByAP
.begin(), LastUsedByAP
.end());
610 LastUsedByAP
.clear();
614 /// Collect passes whose last user is P
615 void PMTopLevelManager::collectLastUses(SmallVectorImpl
<Pass
*> &LastUses
,
617 auto DMI
= InversedLastUser
.find(P
);
618 if (DMI
== InversedLastUser
.end())
621 auto &LU
= DMI
->second
;
622 LastUses
.append(LU
.begin(), LU
.end());
625 AnalysisUsage
*PMTopLevelManager::findAnalysisUsage(Pass
*P
) {
626 AnalysisUsage
*AnUsage
= nullptr;
627 auto DMI
= AnUsageMap
.find(P
);
628 if (DMI
!= AnUsageMap
.end())
629 AnUsage
= DMI
->second
;
631 // Look up the analysis usage from the pass instance (different instances
632 // of the same pass can produce different results), but unique the
633 // resulting object to reduce memory usage. This helps to greatly reduce
634 // memory usage when we have many instances of only a few pass types
635 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
638 P
->getAnalysisUsage(AU
);
640 AUFoldingSetNode
* Node
= nullptr;
642 AUFoldingSetNode::Profile(ID
, AU
);
644 if (auto *N
= UniqueAnalysisUsages
.FindNodeOrInsertPos(ID
, IP
))
647 Node
= new (AUFoldingSetNodeAllocator
.Allocate()) AUFoldingSetNode(AU
);
648 UniqueAnalysisUsages
.InsertNode(Node
, IP
);
650 assert(Node
&& "cached analysis usage must be non null");
652 AnUsageMap
[P
] = &Node
->AU
;
658 /// Schedule pass P for execution. Make sure that passes required by
659 /// P are run before P is run. Update analysis info maintained by
660 /// the manager. Remove dead passes. This is a recursive function.
661 void PMTopLevelManager::schedulePass(Pass
*P
) {
663 // TODO : Allocate function manager for this pass, other wise required set
664 // may be inserted into previous function manager
666 // Give pass a chance to prepare the stage.
667 P
->preparePassManager(activeStack
);
669 // If P is an analysis pass and it is available then do not
670 // generate the analysis again. Stale analysis info should not be
671 // available at this point.
672 const PassInfo
*PI
= findAnalysisPassInfo(P
->getPassID());
673 if (PI
&& PI
->isAnalysis() && findAnalysisPass(P
->getPassID())) {
674 // Remove any cached AnalysisUsage information.
680 AnalysisUsage
*AnUsage
= findAnalysisUsage(P
);
682 bool checkAnalysis
= true;
683 while (checkAnalysis
) {
684 checkAnalysis
= false;
686 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
687 for (const AnalysisID ID
: RequiredSet
) {
689 Pass
*AnalysisPass
= findAnalysisPass(ID
);
691 const PassInfo
*PI
= findAnalysisPassInfo(ID
);
694 // Pass P is not in the global PassRegistry
695 dbgs() << "Pass '" << P
->getPassName() << "' is not initialized." << "\n";
696 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
697 dbgs() << "Required Passes:" << "\n";
698 for (const AnalysisID ID2
: RequiredSet
) {
701 Pass
*AnalysisPass2
= findAnalysisPass(ID2
);
703 dbgs() << "\t" << AnalysisPass2
->getPassName() << "\n";
705 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
706 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
707 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
712 assert(PI
&& "Expected required passes to be initialized");
713 AnalysisPass
= PI
->createPass();
714 if (P
->getPotentialPassManagerType () ==
715 AnalysisPass
->getPotentialPassManagerType())
716 // Schedule analysis pass that is managed by the same pass manager.
717 schedulePass(AnalysisPass
);
718 else if (P
->getPotentialPassManagerType () >
719 AnalysisPass
->getPotentialPassManagerType()) {
720 // Schedule analysis pass that is managed by a new manager.
721 schedulePass(AnalysisPass
);
722 // Recheck analysis passes to ensure that required analyses that
723 // are already checked are still available.
724 checkAnalysis
= true;
726 // Do not schedule this analysis. Lower level analysis
727 // passes are run on the fly.
733 // Now all required passes are available.
734 if (ImmutablePass
*IP
= P
->getAsImmutablePass()) {
735 // P is a immutable pass and it will be managed by this
736 // top level manager. Set up analysis resolver to connect them.
737 PMDataManager
*DM
= getAsPMDataManager();
738 AnalysisResolver
*AR
= new AnalysisResolver(*DM
);
740 DM
->initializeAnalysisImpl(P
);
741 addImmutablePass(IP
);
742 DM
->recordAvailableAnalysis(IP
);
746 if (PI
&& !PI
->isAnalysis() && shouldPrintBeforePass(PI
->getPassArgument())) {
748 P
->createPrinterPass(dbgs(), ("*** IR Dump Before " + P
->getPassName() +
749 " (" + PI
->getPassArgument() + ") ***")
751 PP
->assignPassManager(activeStack
, getTopLevelPassManagerType());
754 // Add the requested pass to the best available pass manager.
755 P
->assignPassManager(activeStack
, getTopLevelPassManagerType());
757 if (PI
&& !PI
->isAnalysis() && shouldPrintAfterPass(PI
->getPassArgument())) {
759 P
->createPrinterPass(dbgs(), ("*** IR Dump After " + P
->getPassName() +
760 " (" + PI
->getPassArgument() + ") ***")
762 PP
->assignPassManager(activeStack
, getTopLevelPassManagerType());
766 /// Find the pass that implements Analysis AID. Search immutable
767 /// passes and all pass managers. If desired pass is not found
768 /// then return NULL.
769 Pass
*PMTopLevelManager::findAnalysisPass(AnalysisID AID
) {
770 // For immutable passes we have a direct mapping from ID to pass, so check
772 if (Pass
*P
= ImmutablePassMap
.lookup(AID
))
775 // Check pass managers
776 for (PMDataManager
*PassManager
: PassManagers
)
777 if (Pass
*P
= PassManager
->findAnalysisPass(AID
, false))
780 // Check other pass managers
781 for (PMDataManager
*IndirectPassManager
: IndirectPassManagers
)
782 if (Pass
*P
= IndirectPassManager
->findAnalysisPass(AID
, false))
788 const PassInfo
*PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID
) const {
789 const PassInfo
*&PI
= AnalysisPassInfos
[AID
];
791 PI
= PassRegistry::getPassRegistry()->getPassInfo(AID
);
793 assert(PI
== PassRegistry::getPassRegistry()->getPassInfo(AID
) &&
794 "The pass info pointer changed for an analysis ID!");
799 void PMTopLevelManager::addImmutablePass(ImmutablePass
*P
) {
801 ImmutablePasses
.push_back(P
);
803 // Add this pass to the map from its analysis ID. We clobber any prior runs
804 // of the pass in the map so that the last one added is the one found when
806 AnalysisID AID
= P
->getPassID();
807 ImmutablePassMap
[AID
] = P
;
810 // Print passes managed by this top level manager.
811 void PMTopLevelManager::dumpPasses() const {
813 if (PassDebugging
< Structure
)
816 // Print out the immutable passes
817 for (ImmutablePass
*Pass
: ImmutablePasses
)
818 Pass
->dumpPassStructure(0);
820 // Every class that derives from PMDataManager also derives from Pass
821 // (sometimes indirectly), but there's no inheritance relationship
822 // between PMDataManager and Pass, so we have to getAsPass to get
823 // from a PMDataManager* to a Pass*.
824 for (PMDataManager
*Manager
: PassManagers
)
825 Manager
->getAsPass()->dumpPassStructure(1);
828 void PMTopLevelManager::dumpArguments() const {
830 if (PassDebugging
< Arguments
)
833 dbgs() << "Pass Arguments: ";
834 for (ImmutablePass
*P
: ImmutablePasses
)
835 if (const PassInfo
*PI
= findAnalysisPassInfo(P
->getPassID())) {
836 assert(PI
&& "Expected all immutable passes to be initialized");
837 dbgs() << " -" << PI
->getPassArgument();
839 for (PMDataManager
*PM
: PassManagers
)
840 PM
->dumpPassArguments();
844 void PMTopLevelManager::initializeAllAnalysisInfo() {
845 for (PMDataManager
*PM
: PassManagers
)
846 PM
->initializeAnalysisInfo();
848 // Initailize other pass managers
849 for (PMDataManager
*IPM
: IndirectPassManagers
)
850 IPM
->initializeAnalysisInfo();
854 PMTopLevelManager::~PMTopLevelManager() {
855 for (PMDataManager
*PM
: PassManagers
)
858 for (ImmutablePass
*P
: ImmutablePasses
)
862 //===----------------------------------------------------------------------===//
863 // PMDataManager implementation
865 /// Augement AvailableAnalysis by adding analysis made available by pass P.
866 void PMDataManager::recordAvailableAnalysis(Pass
*P
) {
867 AnalysisID PI
= P
->getPassID();
869 AvailableAnalysis
[PI
] = P
;
872 // Return true if P preserves high level analysis used by other
873 // passes managed by this manager
874 bool PMDataManager::preserveHigherLevelAnalysis(Pass
*P
) {
875 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
876 if (AnUsage
->getPreservesAll())
879 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
880 for (Pass
*P1
: HigherLevelAnalysis
) {
881 if (P1
->getAsImmutablePass() == nullptr &&
882 !is_contained(PreservedSet
, P1
->getPassID()))
889 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
890 void PMDataManager::verifyPreservedAnalysis(Pass
*P
) {
891 // Don't do this unless assertions are enabled.
895 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
896 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
898 // Verify preserved analysis
899 for (AnalysisID AID
: PreservedSet
) {
900 if (Pass
*AP
= findAnalysisPass(AID
, true)) {
901 TimeRegion
PassTimer(getPassTimer(AP
));
902 AP
->verifyAnalysis();
907 /// Remove Analysis not preserved by Pass P
908 void PMDataManager::removeNotPreservedAnalysis(Pass
*P
) {
909 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
910 if (AnUsage
->getPreservesAll())
913 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
914 for (DenseMap
<AnalysisID
, Pass
*>::iterator I
= AvailableAnalysis
.begin(),
915 E
= AvailableAnalysis
.end(); I
!= E
; ) {
916 DenseMap
<AnalysisID
, Pass
*>::iterator Info
= I
++;
917 if (Info
->second
->getAsImmutablePass() == nullptr &&
918 !is_contained(PreservedSet
, Info
->first
)) {
919 // Remove this analysis
920 if (PassDebugging
>= Details
) {
921 Pass
*S
= Info
->second
;
922 dbgs() << " -- '" << P
->getPassName() << "' is not preserving '";
923 dbgs() << S
->getPassName() << "'\n";
925 AvailableAnalysis
.erase(Info
);
929 // Check inherited analysis also. If P is not preserving analysis
930 // provided by parent manager then remove it here.
931 for (DenseMap
<AnalysisID
, Pass
*> *IA
: InheritedAnalysis
) {
935 for (DenseMap
<AnalysisID
, Pass
*>::iterator I
= IA
->begin(),
938 DenseMap
<AnalysisID
, Pass
*>::iterator Info
= I
++;
939 if (Info
->second
->getAsImmutablePass() == nullptr &&
940 !is_contained(PreservedSet
, Info
->first
)) {
941 // Remove this analysis
942 if (PassDebugging
>= Details
) {
943 Pass
*S
= Info
->second
;
944 dbgs() << " -- '" << P
->getPassName() << "' is not preserving '";
945 dbgs() << S
->getPassName() << "'\n";
953 /// Remove analysis passes that are not used any longer
954 void PMDataManager::removeDeadPasses(Pass
*P
, StringRef Msg
,
955 enum PassDebuggingString DBG_STR
) {
957 SmallVector
<Pass
*, 12> DeadPasses
;
959 // If this is a on the fly manager then it does not have TPM.
963 TPM
->collectLastUses(DeadPasses
, P
);
965 if (PassDebugging
>= Details
&& !DeadPasses
.empty()) {
966 dbgs() << " -*- '" << P
->getPassName();
967 dbgs() << "' is the last user of following pass instances.";
968 dbgs() << " Free these instances\n";
971 for (Pass
*P
: DeadPasses
)
972 freePass(P
, Msg
, DBG_STR
);
975 void PMDataManager::freePass(Pass
*P
, StringRef Msg
,
976 enum PassDebuggingString DBG_STR
) {
977 dumpPassInfo(P
, FREEING_MSG
, DBG_STR
, Msg
);
980 // If the pass crashes releasing memory, remember this.
981 PassManagerPrettyStackEntry
X(P
);
982 TimeRegion
PassTimer(getPassTimer(P
));
987 // Remove the pass itself (if it is not already removed).
988 AvailableAnalysis
.erase(P
->getPassID());
991 /// Add pass P into the PassVector. Update
992 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
993 void PMDataManager::add(Pass
*P
, bool ProcessAnalysis
) {
994 // This manager is going to manage pass P. Set up analysis resolver
996 AnalysisResolver
*AR
= new AnalysisResolver(*this);
999 // If a FunctionPass F is the last user of ModulePass info M
1000 // then the F's manager, not F, records itself as a last user of M.
1001 SmallVector
<Pass
*, 12> TransferLastUses
;
1003 if (!ProcessAnalysis
) {
1005 PassVector
.push_back(P
);
1009 // At the moment, this pass is the last user of all required passes.
1010 SmallVector
<Pass
*, 12> LastUses
;
1011 SmallVector
<Pass
*, 8> UsedPasses
;
1012 SmallVector
<AnalysisID
, 8> ReqAnalysisNotAvailable
;
1014 unsigned PDepth
= this->getDepth();
1016 collectRequiredAndUsedAnalyses(UsedPasses
, ReqAnalysisNotAvailable
, P
);
1017 for (Pass
*PUsed
: UsedPasses
) {
1018 unsigned RDepth
= 0;
1020 assert(PUsed
->getResolver() && "Analysis Resolver is not set");
1021 PMDataManager
&DM
= PUsed
->getResolver()->getPMDataManager();
1022 RDepth
= DM
.getDepth();
1024 if (PDepth
== RDepth
)
1025 LastUses
.push_back(PUsed
);
1026 else if (PDepth
> RDepth
) {
1027 // Let the parent claim responsibility of last use
1028 TransferLastUses
.push_back(PUsed
);
1029 // Keep track of higher level analysis used by this manager.
1030 HigherLevelAnalysis
.push_back(PUsed
);
1032 llvm_unreachable("Unable to accommodate Used Pass");
1035 // Set P as P's last user until someone starts using P.
1036 // However, if P is a Pass Manager then it does not need
1037 // to record its last user.
1038 if (!P
->getAsPMDataManager())
1039 LastUses
.push_back(P
);
1040 TPM
->setLastUser(LastUses
, P
);
1042 if (!TransferLastUses
.empty()) {
1043 Pass
*My_PM
= getAsPass();
1044 TPM
->setLastUser(TransferLastUses
, My_PM
);
1045 TransferLastUses
.clear();
1048 // Now, take care of required analyses that are not available.
1049 for (AnalysisID ID
: ReqAnalysisNotAvailable
) {
1050 const PassInfo
*PI
= TPM
->findAnalysisPassInfo(ID
);
1051 Pass
*AnalysisPass
= PI
->createPass();
1052 this->addLowerLevelRequiredPass(P
, AnalysisPass
);
1055 // Take a note of analysis required and made available by this pass.
1056 // Remove the analysis not preserved by this pass
1057 removeNotPreservedAnalysis(P
);
1058 recordAvailableAnalysis(P
);
1061 PassVector
.push_back(P
);
1065 /// Populate UP with analysis pass that are used or required by
1066 /// pass P and are available. Populate RP_NotAvail with analysis
1067 /// pass that are required by pass P but are not available.
1068 void PMDataManager::collectRequiredAndUsedAnalyses(
1069 SmallVectorImpl
<Pass
*> &UP
, SmallVectorImpl
<AnalysisID
> &RP_NotAvail
,
1071 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
1073 for (const auto &UsedID
: AnUsage
->getUsedSet())
1074 if (Pass
*AnalysisPass
= findAnalysisPass(UsedID
, true))
1075 UP
.push_back(AnalysisPass
);
1077 for (const auto &RequiredID
: AnUsage
->getRequiredSet())
1078 if (Pass
*AnalysisPass
= findAnalysisPass(RequiredID
, true))
1079 UP
.push_back(AnalysisPass
);
1081 RP_NotAvail
.push_back(RequiredID
);
1084 // All Required analyses should be available to the pass as it runs! Here
1085 // we fill in the AnalysisImpls member of the pass so that it can
1086 // successfully use the getAnalysis() method to retrieve the
1087 // implementations it needs.
1089 void PMDataManager::initializeAnalysisImpl(Pass
*P
) {
1090 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
1092 for (const AnalysisID ID
: AnUsage
->getRequiredSet()) {
1093 Pass
*Impl
= findAnalysisPass(ID
, true);
1095 // This may be analysis pass that is initialized on the fly.
1096 // If that is not the case then it will raise an assert when it is used.
1098 AnalysisResolver
*AR
= P
->getResolver();
1099 assert(AR
&& "Analysis Resolver is not set");
1100 AR
->addAnalysisImplsPair(ID
, Impl
);
1104 /// Find the pass that implements Analysis AID. If desired pass is not found
1105 /// then return NULL.
1106 Pass
*PMDataManager::findAnalysisPass(AnalysisID AID
, bool SearchParent
) {
1108 // Check if AvailableAnalysis map has one entry.
1109 DenseMap
<AnalysisID
, Pass
*>::const_iterator I
= AvailableAnalysis
.find(AID
);
1111 if (I
!= AvailableAnalysis
.end())
1114 // Search Parents through TopLevelManager
1116 return TPM
->findAnalysisPass(AID
);
1121 // Print list of passes that are last used by P.
1122 void PMDataManager::dumpLastUses(Pass
*P
, unsigned Offset
) const{
1123 if (PassDebugging
< Details
)
1126 SmallVector
<Pass
*, 12> LUses
;
1128 // If this is a on the fly manager then it does not have TPM.
1132 TPM
->collectLastUses(LUses
, P
);
1134 for (Pass
*P
: LUses
) {
1135 dbgs() << "--" << std::string(Offset
*2, ' ');
1136 P
->dumpPassStructure(0);
1140 void PMDataManager::dumpPassArguments() const {
1141 for (Pass
*P
: PassVector
) {
1142 if (PMDataManager
*PMD
= P
->getAsPMDataManager())
1143 PMD
->dumpPassArguments();
1144 else if (const PassInfo
*PI
= TPM
->findAnalysisPassInfo(P
->getPassID()))
1145 dbgs() << " -" << PI
->getPassArgument();
1149 void PMDataManager::dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
1150 enum PassDebuggingString S2
,
1152 if (PassDebugging
< Executions
)
1154 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1155 << std::string(getDepth() * 2 + 1, ' ');
1158 dbgs() << "Executing Pass '" << P
->getPassName();
1160 case MODIFICATION_MSG
:
1161 dbgs() << "Made Modification '" << P
->getPassName();
1164 dbgs() << " Freeing Pass '" << P
->getPassName();
1170 case ON_FUNCTION_MSG
:
1171 dbgs() << "' on Function '" << Msg
<< "'...\n";
1174 dbgs() << "' on Module '" << Msg
<< "'...\n";
1177 dbgs() << "' on Region '" << Msg
<< "'...\n";
1180 dbgs() << "' on Loop '" << Msg
<< "'...\n";
1183 dbgs() << "' on Call Graph Nodes '" << Msg
<< "'...\n";
1190 void PMDataManager::dumpRequiredSet(const Pass
*P
) const {
1191 if (PassDebugging
< Details
)
1194 AnalysisUsage analysisUsage
;
1195 P
->getAnalysisUsage(analysisUsage
);
1196 dumpAnalysisUsage("Required", P
, analysisUsage
.getRequiredSet());
1199 void PMDataManager::dumpPreservedSet(const Pass
*P
) const {
1200 if (PassDebugging
< Details
)
1203 AnalysisUsage analysisUsage
;
1204 P
->getAnalysisUsage(analysisUsage
);
1205 dumpAnalysisUsage("Preserved", P
, analysisUsage
.getPreservedSet());
1208 void PMDataManager::dumpUsedSet(const Pass
*P
) const {
1209 if (PassDebugging
< Details
)
1212 AnalysisUsage analysisUsage
;
1213 P
->getAnalysisUsage(analysisUsage
);
1214 dumpAnalysisUsage("Used", P
, analysisUsage
.getUsedSet());
1217 void PMDataManager::dumpAnalysisUsage(StringRef Msg
, const Pass
*P
,
1218 const AnalysisUsage::VectorType
&Set
) const {
1219 assert(PassDebugging
>= Details
);
1222 dbgs() << (const void*)P
<< std::string(getDepth()*2+3, ' ') << Msg
<< " Analyses:";
1223 for (unsigned i
= 0; i
!= Set
.size(); ++i
) {
1224 if (i
) dbgs() << ',';
1225 const PassInfo
*PInf
= TPM
->findAnalysisPassInfo(Set
[i
]);
1227 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1229 dbgs() << " Uninitialized Pass";
1232 dbgs() << ' ' << PInf
->getPassName();
1237 /// Add RequiredPass into list of lower level passes required by pass P.
1238 /// RequiredPass is run on the fly by Pass Manager when P requests it
1239 /// through getAnalysis interface.
1240 /// This should be handled by specific pass manager.
1241 void PMDataManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1243 TPM
->dumpArguments();
1247 // Module Level pass may required Function Level analysis info
1248 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1249 // to provide this on demand. In that case, in Pass manager terminology,
1250 // module level pass is requiring lower level analysis info managed by
1251 // lower level pass manager.
1253 // When Pass manager is not able to order required analysis info, Pass manager
1254 // checks whether any lower level manager will be able to provide this
1255 // analysis info on demand or not.
1257 dbgs() << "Unable to schedule '" << RequiredPass
->getPassName();
1258 dbgs() << "' required by '" << P
->getPassName() << "'\n";
1260 llvm_unreachable("Unable to schedule pass");
1263 std::tuple
<Pass
*, bool> PMDataManager::getOnTheFlyPass(Pass
*P
, AnalysisID PI
,
1265 llvm_unreachable("Unable to find on the fly pass");
1269 PMDataManager::~PMDataManager() {
1270 for (Pass
*P
: PassVector
)
1274 //===----------------------------------------------------------------------===//
1275 // NOTE: Is this the right place to define this method ?
1276 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1277 Pass
*AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID
) const {
1278 return PM
.findAnalysisPass(ID
, true);
1281 std::tuple
<Pass
*, bool>
1282 AnalysisResolver::findImplPass(Pass
*P
, AnalysisID AnalysisPI
, Function
&F
) {
1283 return PM
.getOnTheFlyPass(P
, AnalysisPI
, F
);
1289 //===----------------------------------------------------------------------===//
1290 // FunctionPassManager implementation
1292 /// Create new Function pass manager
1293 FunctionPassManager::FunctionPassManager(Module
*m
) : M(m
) {
1294 FPM
= new legacy::FunctionPassManagerImpl();
1295 // FPM is the top level manager.
1296 FPM
->setTopLevelManager(FPM
);
1298 AnalysisResolver
*AR
= new AnalysisResolver(*FPM
);
1299 FPM
->setResolver(AR
);
1302 FunctionPassManager::~FunctionPassManager() {
1306 void FunctionPassManager::add(Pass
*P
) {
1310 /// run - Execute all of the passes scheduled for execution. Keep
1311 /// track of whether any of the passes modifies the function, and if
1312 /// so, return true.
1314 bool FunctionPassManager::run(Function
&F
) {
1315 handleAllErrors(F
.materialize(), [&](ErrorInfoBase
&EIB
) {
1316 report_fatal_error(Twine("Error reading bitcode file: ") + EIB
.message());
1322 /// doInitialization - Run all of the initializers for the function passes.
1324 bool FunctionPassManager::doInitialization() {
1325 return FPM
->doInitialization(*M
);
1328 /// doFinalization - Run all of the finalizers for the function passes.
1330 bool FunctionPassManager::doFinalization() {
1331 return FPM
->doFinalization(*M
);
1333 } // namespace legacy
1336 /// cleanup - After running all passes, clean up pass manager cache.
1337 void FPPassManager::cleanup() {
1338 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1339 FunctionPass
*FP
= getContainedPass(Index
);
1340 AnalysisResolver
*AR
= FP
->getResolver();
1341 assert(AR
&& "Analysis Resolver is not set");
1342 AR
->clearAnalysisImpls();
1347 //===----------------------------------------------------------------------===//
1348 // FPPassManager implementation
1350 char FPPassManager::ID
= 0;
1351 /// Print passes managed by this manager
1352 void FPPassManager::dumpPassStructure(unsigned Offset
) {
1353 dbgs().indent(Offset
*2) << "FunctionPass Manager\n";
1354 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1355 FunctionPass
*FP
= getContainedPass(Index
);
1356 FP
->dumpPassStructure(Offset
+ 1);
1357 dumpLastUses(FP
, Offset
+1);
1361 /// Execute all of the passes scheduled for execution by invoking
1362 /// runOnFunction method. Keep track of whether any of the passes modifies
1363 /// the function, and if so, return true.
1364 bool FPPassManager::runOnFunction(Function
&F
) {
1365 if (F
.isDeclaration())
1368 bool Changed
= false;
1369 Module
&M
= *F
.getParent();
1370 // Collect inherited analysis from Module level pass manager.
1371 populateInheritedAnalysis(TPM
->activeStack
);
1373 unsigned InstrCount
, FunctionSize
= 0;
1374 StringMap
<std::pair
<unsigned, unsigned>> FunctionToInstrCount
;
1375 bool EmitICRemark
= M
.shouldEmitInstrCountChangedRemark();
1376 // Collect the initial size of the module.
1378 InstrCount
= initSizeRemarkInfo(M
, FunctionToInstrCount
);
1379 FunctionSize
= F
.getInstructionCount();
1382 // Store name outside of loop to avoid redundant calls.
1383 const StringRef Name
= F
.getName();
1384 llvm::TimeTraceScope
FunctionScope("OptFunction", Name
);
1386 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1387 FunctionPass
*FP
= getContainedPass(Index
);
1388 bool LocalChanged
= false;
1390 // Call getPassName only when required. The call itself is fairly cheap, but
1391 // still virtual and repeated calling adds unnecessary overhead.
1392 llvm::TimeTraceScope
PassScope(
1393 "RunPass", [FP
]() { return std::string(FP
->getPassName()); });
1395 dumpPassInfo(FP
, EXECUTION_MSG
, ON_FUNCTION_MSG
, Name
);
1396 dumpRequiredSet(FP
);
1398 initializeAnalysisImpl(FP
);
1401 PassManagerPrettyStackEntry
X(FP
, F
);
1402 TimeRegion
PassTimer(getPassTimer(FP
));
1403 #ifdef EXPENSIVE_CHECKS
1404 uint64_t RefHash
= FP
->structuralHash(F
);
1406 LocalChanged
|= FP
->runOnFunction(F
);
1408 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
1409 if (!LocalChanged
&& (RefHash
!= FP
->structuralHash(F
))) {
1410 llvm::errs() << "Pass modifies its input and doesn't report it: "
1411 << FP
->getPassName() << "\n";
1412 llvm_unreachable("Pass modifies its input and doesn't report it");
1417 unsigned NewSize
= F
.getInstructionCount();
1419 // Update the size of the function, emit a remark, and update the size
1421 if (NewSize
!= FunctionSize
) {
1422 int64_t Delta
= static_cast<int64_t>(NewSize
) -
1423 static_cast<int64_t>(FunctionSize
);
1424 emitInstrCountChangedRemark(FP
, M
, Delta
, InstrCount
,
1425 FunctionToInstrCount
, &F
);
1426 InstrCount
= static_cast<int64_t>(InstrCount
) + Delta
;
1427 FunctionSize
= NewSize
;
1432 Changed
|= LocalChanged
;
1434 dumpPassInfo(FP
, MODIFICATION_MSG
, ON_FUNCTION_MSG
, Name
);
1435 dumpPreservedSet(FP
);
1438 verifyPreservedAnalysis(FP
);
1440 removeNotPreservedAnalysis(FP
);
1441 recordAvailableAnalysis(FP
);
1442 removeDeadPasses(FP
, Name
, ON_FUNCTION_MSG
);
1448 bool FPPassManager::runOnModule(Module
&M
) {
1449 bool Changed
= false;
1451 for (Function
&F
: M
)
1452 Changed
|= runOnFunction(F
);
1457 bool FPPassManager::doInitialization(Module
&M
) {
1458 bool Changed
= false;
1460 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1461 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1466 bool FPPassManager::doFinalization(Module
&M
) {
1467 bool Changed
= false;
1469 for (int Index
= getNumContainedPasses() - 1; Index
>= 0; --Index
)
1470 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1475 //===----------------------------------------------------------------------===//
1476 // MPPassManager implementation
1478 /// Execute all of the passes scheduled for execution by invoking
1479 /// runOnModule method. Keep track of whether any of the passes modifies
1480 /// the module, and if so, return true.
1482 MPPassManager::runOnModule(Module
&M
) {
1483 llvm::TimeTraceScope
TimeScope("OptModule", M
.getName());
1485 bool Changed
= false;
1487 // Initialize on-the-fly passes
1488 for (auto &OnTheFlyManager
: OnTheFlyManagers
) {
1489 legacy::FunctionPassManagerImpl
*FPP
= OnTheFlyManager
.second
;
1490 Changed
|= FPP
->doInitialization(M
);
1493 // Initialize module passes
1494 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1495 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1497 unsigned InstrCount
;
1498 StringMap
<std::pair
<unsigned, unsigned>> FunctionToInstrCount
;
1499 bool EmitICRemark
= M
.shouldEmitInstrCountChangedRemark();
1500 // Collect the initial size of the module.
1502 InstrCount
= initSizeRemarkInfo(M
, FunctionToInstrCount
);
1504 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1505 ModulePass
*MP
= getContainedPass(Index
);
1506 bool LocalChanged
= false;
1508 dumpPassInfo(MP
, EXECUTION_MSG
, ON_MODULE_MSG
, M
.getModuleIdentifier());
1509 dumpRequiredSet(MP
);
1511 initializeAnalysisImpl(MP
);
1514 PassManagerPrettyStackEntry
X(MP
, M
);
1515 TimeRegion
PassTimer(getPassTimer(MP
));
1517 #ifdef EXPENSIVE_CHECKS
1518 uint64_t RefHash
= MP
->structuralHash(M
);
1521 LocalChanged
|= MP
->runOnModule(M
);
1523 #ifdef EXPENSIVE_CHECKS
1524 assert((LocalChanged
|| (RefHash
== MP
->structuralHash(M
))) &&
1525 "Pass modifies its input and doesn't report it.");
1529 // Update the size of the module.
1530 unsigned ModuleCount
= M
.getInstructionCount();
1531 if (ModuleCount
!= InstrCount
) {
1532 int64_t Delta
= static_cast<int64_t>(ModuleCount
) -
1533 static_cast<int64_t>(InstrCount
);
1534 emitInstrCountChangedRemark(MP
, M
, Delta
, InstrCount
,
1535 FunctionToInstrCount
);
1536 InstrCount
= ModuleCount
;
1541 Changed
|= LocalChanged
;
1543 dumpPassInfo(MP
, MODIFICATION_MSG
, ON_MODULE_MSG
,
1544 M
.getModuleIdentifier());
1545 dumpPreservedSet(MP
);
1548 verifyPreservedAnalysis(MP
);
1550 removeNotPreservedAnalysis(MP
);
1551 recordAvailableAnalysis(MP
);
1552 removeDeadPasses(MP
, M
.getModuleIdentifier(), ON_MODULE_MSG
);
1555 // Finalize module passes
1556 for (int Index
= getNumContainedPasses() - 1; Index
>= 0; --Index
)
1557 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1559 // Finalize on-the-fly passes
1560 for (auto &OnTheFlyManager
: OnTheFlyManagers
) {
1561 legacy::FunctionPassManagerImpl
*FPP
= OnTheFlyManager
.second
;
1562 // We don't know when is the last time an on-the-fly pass is run,
1563 // so we need to releaseMemory / finalize here
1564 FPP
->releaseMemoryOnTheFly();
1565 Changed
|= FPP
->doFinalization(M
);
1571 /// Add RequiredPass into list of lower level passes required by pass P.
1572 /// RequiredPass is run on the fly by Pass Manager when P requests it
1573 /// through getAnalysis interface.
1574 void MPPassManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1575 assert(RequiredPass
&& "No required pass?");
1576 assert(P
->getPotentialPassManagerType() == PMT_ModulePassManager
&&
1577 "Unable to handle Pass that requires lower level Analysis pass");
1578 assert((P
->getPotentialPassManagerType() <
1579 RequiredPass
->getPotentialPassManagerType()) &&
1580 "Unable to handle Pass that requires lower level Analysis pass");
1582 legacy::FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[P
];
1584 FPP
= new legacy::FunctionPassManagerImpl();
1585 // FPP is the top level manager.
1586 FPP
->setTopLevelManager(FPP
);
1588 OnTheFlyManagers
[P
] = FPP
;
1590 const PassInfo
*RequiredPassPI
=
1591 TPM
->findAnalysisPassInfo(RequiredPass
->getPassID());
1593 Pass
*FoundPass
= nullptr;
1594 if (RequiredPassPI
&& RequiredPassPI
->isAnalysis()) {
1596 ((PMTopLevelManager
*)FPP
)->findAnalysisPass(RequiredPass
->getPassID());
1599 FoundPass
= RequiredPass
;
1600 // This should be guaranteed to add RequiredPass to the passmanager given
1601 // that we checked for an available analysis above.
1602 FPP
->add(RequiredPass
);
1604 // Register P as the last user of FoundPass or RequiredPass.
1605 SmallVector
<Pass
*, 1> LU
;
1606 LU
.push_back(FoundPass
);
1607 FPP
->setLastUser(LU
, P
);
1610 /// Return function pass corresponding to PassInfo PI, that is
1611 /// required by module pass MP. Instantiate analysis pass, by using
1612 /// its runOnFunction() for function F.
1613 std::tuple
<Pass
*, bool> MPPassManager::getOnTheFlyPass(Pass
*MP
, AnalysisID PI
,
1615 legacy::FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
];
1616 assert(FPP
&& "Unable to find on the fly pass");
1618 FPP
->releaseMemoryOnTheFly();
1619 bool Changed
= FPP
->run(F
);
1620 return std::make_tuple(((PMTopLevelManager
*)FPP
)->findAnalysisPass(PI
),
1627 //===----------------------------------------------------------------------===//
1628 // PassManager implementation
1630 /// Create new pass manager
1631 PassManager::PassManager() {
1632 PM
= new PassManagerImpl();
1633 // PM is the top level manager
1634 PM
->setTopLevelManager(PM
);
1637 PassManager::~PassManager() {
1641 void PassManager::add(Pass
*P
) {
1645 /// run - Execute all of the passes scheduled for execution. Keep track of
1646 /// whether any of the passes modifies the module, and if so, return true.
1647 bool PassManager::run(Module
&M
) {
1650 } // namespace legacy
1653 //===----------------------------------------------------------------------===//
1654 // PMStack implementation
1657 // Pop Pass Manager from the stack and clear its analysis info.
1658 void PMStack::pop() {
1660 PMDataManager
*Top
= this->top();
1661 Top
->initializeAnalysisInfo();
1666 // Push PM on the stack and set its top level manager.
1667 void PMStack::push(PMDataManager
*PM
) {
1668 assert(PM
&& "Unable to push. Pass Manager expected");
1669 assert(PM
->getDepth()==0 && "Pass Manager depth set too early");
1671 if (!this->empty()) {
1672 assert(PM
->getPassManagerType() > this->top()->getPassManagerType()
1673 && "pushing bad pass manager to PMStack");
1674 PMTopLevelManager
*TPM
= this->top()->getTopLevelManager();
1676 assert(TPM
&& "Unable to find top level manager");
1677 TPM
->addIndirectPassManager(PM
);
1678 PM
->setTopLevelManager(TPM
);
1679 PM
->setDepth(this->top()->getDepth()+1);
1681 assert((PM
->getPassManagerType() == PMT_ModulePassManager
1682 || PM
->getPassManagerType() == PMT_FunctionPassManager
)
1683 && "pushing bad pass manager to PMStack");
1690 // Dump content of the pass manager stack.
1691 LLVM_DUMP_METHOD
void PMStack::dump() const {
1692 for (PMDataManager
*Manager
: S
)
1693 dbgs() << Manager
->getAsPass()->getPassName() << ' ';
1699 /// Find appropriate Module Pass Manager in the PM Stack and
1700 /// add self into that manager.
1701 void ModulePass::assignPassManager(PMStack
&PMS
,
1702 PassManagerType PreferredType
) {
1703 // Find Module Pass Manager
1705 while ((T
= PMS
.top()->getPassManagerType()) > PMT_ModulePassManager
&&
1708 PMS
.top()->add(this);
1711 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1712 /// in the PM Stack and add self into that manager.
1713 void FunctionPass::assignPassManager(PMStack
&PMS
,
1714 PassManagerType
/*PreferredType*/) {
1715 // Find Function Pass Manager
1717 while (PM
= PMS
.top(), PM
->getPassManagerType() > PMT_FunctionPassManager
)
1720 // Create new Function Pass Manager if needed.
1721 if (PM
->getPassManagerType() != PMT_FunctionPassManager
) {
1722 // [1] Create new Function Pass Manager
1723 auto *FPP
= new FPPassManager
;
1724 FPP
->populateInheritedAnalysis(PMS
);
1726 // [2] Set up new manager's top level manager
1727 PM
->getTopLevelManager()->addIndirectPassManager(FPP
);
1729 // [3] Assign manager to manage this new manager. This may create
1730 // and push new managers into PMS
1731 FPP
->assignPassManager(PMS
, PM
->getPassManagerType());
1733 // [4] Push new manager into PMS
1738 // Assign FPP as the manager of this pass.
1742 legacy::PassManagerBase::~PassManagerBase() = default;