1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
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 implements the legacy LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/LegacyPassManager.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/DiagnosticInfo.h"
18 #include "llvm/IR/IRPrintingPasses.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/LegacyPassManagers.h"
21 #include "llvm/IR/LegacyPassNameParser.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/PassTimingInfo.h"
24 #include "llvm/Support/Chrono.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
34 #include <unordered_set>
36 using namespace llvm::legacy
;
38 // See PassManagers.h for Pass Manager infrastructure overview.
40 //===----------------------------------------------------------------------===//
41 // Pass debugging information. Often it is useful to find out what pass is
42 // running when a crash occurs in a utility. When this library is compiled with
43 // debugging on, a command line option (--debug-pass) is enabled that causes the
44 // pass name to be printed before it executes.
48 // Different debug levels that can be enabled...
50 Disabled
, Arguments
, Structure
, Executions
, Details
54 static cl::opt
<enum PassDebugLevel
>
55 PassDebugging("debug-pass", cl::Hidden
,
56 cl::desc("Print PassManager debugging information"),
58 clEnumVal(Disabled
, "disable debug output"),
59 clEnumVal(Arguments
, "print pass arguments to pass to 'opt'"),
60 clEnumVal(Structure
, "print pass structure before run()"),
61 clEnumVal(Executions
, "print pass name before it is executed"),
62 clEnumVal(Details
, "print pass details when it is executed")));
65 typedef llvm::cl::list
<const llvm::PassInfo
*, bool, PassNameParser
>
69 // Print IR out before/after specified passes.
71 PrintBefore("print-before",
72 llvm::cl::desc("Print IR before specified passes"),
76 PrintAfter("print-after",
77 llvm::cl::desc("Print IR after specified passes"),
80 static cl::opt
<bool> PrintBeforeAll("print-before-all",
81 llvm::cl::desc("Print IR before each pass"),
82 cl::init(false), cl::Hidden
);
83 static cl::opt
<bool> PrintAfterAll("print-after-all",
84 llvm::cl::desc("Print IR after each pass"),
85 cl::init(false), cl::Hidden
);
88 PrintModuleScope("print-module-scope",
89 cl::desc("When printing IR for print-[before|after]{-all} "
90 "always print a module IR"),
91 cl::init(false), cl::Hidden
);
93 static cl::list
<std::string
>
94 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
95 cl::desc("Only print IR for functions whose name "
96 "match this for all print-[before|after][-all] "
98 cl::CommaSeparated
, cl::Hidden
);
100 /// This is a helper to determine whether to print IR before or
103 static bool ShouldPrintBeforeOrAfterPass(const PassInfo
*PI
,
104 PassOptionList
&PassesToPrint
) {
105 for (auto *PassInf
: PassesToPrint
) {
107 if (PassInf
->getPassArgument() == PI
->getPassArgument()) {
114 /// This is a utility to check whether a pass should have IR dumped
116 static bool ShouldPrintBeforePass(const PassInfo
*PI
) {
117 return PrintBeforeAll
|| ShouldPrintBeforeOrAfterPass(PI
, PrintBefore
);
120 /// This is a utility to check whether a pass should have IR dumped
122 static bool ShouldPrintAfterPass(const PassInfo
*PI
) {
123 return PrintAfterAll
|| ShouldPrintBeforeOrAfterPass(PI
, PrintAfter
);
126 bool llvm::forcePrintModuleIR() { return PrintModuleScope
; }
128 bool llvm::isFunctionInPrintList(StringRef FunctionName
) {
129 static std::unordered_set
<std::string
> PrintFuncNames(PrintFuncsList
.begin(),
130 PrintFuncsList
.end());
131 return PrintFuncNames
.empty() || PrintFuncNames
.count(FunctionName
);
133 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
134 /// or higher is specified.
135 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
136 return PassDebugging
>= Executions
;
139 unsigned PMDataManager::initSizeRemarkInfo(
140 Module
&M
, StringMap
<std::pair
<unsigned, unsigned>> &FunctionToInstrCount
) {
141 // Only calculate getInstructionCount if the size-info remark is requested.
142 unsigned InstrCount
= 0;
144 // Collect instruction counts for every function. We'll use this to emit
145 // per-function size remarks later.
146 for (Function
&F
: M
) {
147 unsigned FCount
= F
.getInstructionCount();
149 // Insert a record into FunctionToInstrCount keeping track of the current
150 // size of the function as the first member of a pair. Set the second
151 // member to 0; if the function is deleted by the pass, then when we get
152 // here, we'll be able to let the user know that F no longer contributes to
154 FunctionToInstrCount
[F
.getName().str()] =
155 std::pair
<unsigned, unsigned>(FCount
, 0);
156 InstrCount
+= FCount
;
161 void PMDataManager::emitInstrCountChangedRemark(
162 Pass
*P
, Module
&M
, int64_t Delta
, unsigned CountBefore
,
163 StringMap
<std::pair
<unsigned, unsigned>> &FunctionToInstrCount
,
165 // If it's a pass manager, don't emit a remark. (This hinges on the assumption
166 // that the only passes that return non-null with getAsPMDataManager are pass
167 // managers.) The reason we have to do this is to avoid emitting remarks for
169 if (P
->getAsPMDataManager())
172 // Set to true if this isn't a module pass or CGSCC pass.
173 bool CouldOnlyImpactOneFunction
= (F
!= nullptr);
175 // Helper lambda that updates the changes to the size of some function.
176 auto UpdateFunctionChanges
=
177 [&FunctionToInstrCount
](Function
&MaybeChangedFn
) {
178 // Update the total module count.
179 unsigned FnSize
= MaybeChangedFn
.getInstructionCount();
180 auto It
= FunctionToInstrCount
.find(MaybeChangedFn
.getName());
182 // If we created a new function, then we need to add it to the map and
183 // say that it changed from 0 instructions to FnSize.
184 if (It
== FunctionToInstrCount
.end()) {
185 FunctionToInstrCount
[MaybeChangedFn
.getName()] =
186 std::pair
<unsigned, unsigned>(0, FnSize
);
189 // Insert the new function size into the second member of the pair. This
190 // tells us whether or not this function changed in size.
191 It
->second
.second
= FnSize
;
194 // We need to initially update all of the function sizes.
195 // If no function was passed in, then we're either a module pass or an
197 if (!CouldOnlyImpactOneFunction
)
198 std::for_each(M
.begin(), M
.end(), UpdateFunctionChanges
);
200 UpdateFunctionChanges(*F
);
202 // Do we have a function we can use to emit a remark?
203 if (!CouldOnlyImpactOneFunction
) {
204 // We need a function containing at least one basic block in order to output
205 // remarks. Since it's possible that the first function in the module
206 // doesn't actually contain a basic block, we have to go and find one that's
207 // suitable for emitting remarks.
208 auto It
= std::find_if(M
.begin(), M
.end(),
209 [](const Function
&Fn
) { return !Fn
.empty(); });
211 // Didn't find a function. Quit.
215 // We found a function containing at least one basic block.
218 int64_t CountAfter
= static_cast<int64_t>(CountBefore
) + Delta
;
219 BasicBlock
&BB
= *F
->begin();
220 OptimizationRemarkAnalysis
R("size-info", "IRSizeChange",
221 DiagnosticLocation(), &BB
);
222 // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
223 // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
224 R
<< DiagnosticInfoOptimizationBase::Argument("Pass", P
->getPassName())
225 << ": IR instruction count changed from "
226 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore
)
228 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter
)
230 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta
);
231 F
->getContext().diagnose(R
); // Not using ORE for layering reasons.
233 // Emit per-function size change remarks separately.
234 std::string PassName
= P
->getPassName().str();
236 // Helper lambda that emits a remark when the size of a function has changed.
237 auto EmitFunctionSizeChangedRemark
= [&FunctionToInstrCount
, &F
, &BB
,
238 &PassName
](const std::string
&Fname
) {
239 unsigned FnCountBefore
, FnCountAfter
;
240 std::pair
<unsigned, unsigned> &Change
= FunctionToInstrCount
[Fname
];
241 std::tie(FnCountBefore
, FnCountAfter
) = Change
;
242 int64_t FnDelta
= static_cast<int64_t>(FnCountAfter
) -
243 static_cast<int64_t>(FnCountBefore
);
248 // FIXME: We shouldn't use BB for the location here. Unfortunately, because
249 // the function that we're looking at could have been deleted, we can't use
250 // it for the source location. We *want* remarks when a function is deleted
251 // though, so we're kind of stuck here as is. (This remark, along with the
252 // whole-module size change remarks really ought not to have source
253 // locations at all.)
254 OptimizationRemarkAnalysis
FR("size-info", "FunctionIRSizeChange",
255 DiagnosticLocation(), &BB
);
256 FR
<< DiagnosticInfoOptimizationBase::Argument("Pass", PassName
)
258 << DiagnosticInfoOptimizationBase::Argument("Function", Fname
)
259 << ": IR instruction count changed from "
260 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",
263 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",
266 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta
);
267 F
->getContext().diagnose(FR
);
269 // Update the function size.
270 Change
.first
= FnCountAfter
;
273 // Are we looking at more than one function? If so, emit remarks for all of
274 // the functions in the module. Otherwise, only emit one remark.
275 if (!CouldOnlyImpactOneFunction
)
276 std::for_each(FunctionToInstrCount
.keys().begin(),
277 FunctionToInstrCount
.keys().end(),
278 EmitFunctionSizeChangedRemark
);
280 EmitFunctionSizeChangedRemark(F
->getName().str());
283 void PassManagerPrettyStackEntry::print(raw_ostream
&OS
) const {
285 OS
<< "Releasing pass '";
287 OS
<< "Running pass '";
289 OS
<< P
->getPassName() << "'";
292 OS
<< " on module '" << M
->getModuleIdentifier() << "'.\n";
301 if (isa
<Function
>(V
))
303 else if (isa
<BasicBlock
>(V
))
309 V
->printAsOperand(OS
, /*PrintTy=*/false, M
);
315 //===----------------------------------------------------------------------===//
318 /// BBPassManager manages BasicBlockPass. It batches all the
319 /// pass together and sequence them to process one basic block before
320 /// processing next basic block.
321 class BBPassManager
: public PMDataManager
, public FunctionPass
{
325 explicit BBPassManager()
326 : PMDataManager(), FunctionPass(ID
) {}
328 /// Execute all of the passes scheduled for execution. Keep track of
329 /// whether any of the passes modifies the function, and if so, return true.
330 bool runOnFunction(Function
&F
) override
;
332 /// Pass Manager itself does not invalidate any analysis info.
333 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
334 Info
.setPreservesAll();
337 bool doInitialization(Module
&M
) override
;
338 bool doInitialization(Function
&F
);
339 bool doFinalization(Module
&M
) override
;
340 bool doFinalization(Function
&F
);
342 PMDataManager
*getAsPMDataManager() override
{ return this; }
343 Pass
*getAsPass() override
{ return this; }
345 StringRef
getPassName() const override
{ return "BasicBlock Pass Manager"; }
347 // Print passes managed by this manager
348 void dumpPassStructure(unsigned Offset
) override
{
349 dbgs().indent(Offset
*2) << "BasicBlockPass Manager\n";
350 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
351 BasicBlockPass
*BP
= getContainedPass(Index
);
352 BP
->dumpPassStructure(Offset
+ 1);
353 dumpLastUses(BP
, Offset
+1);
357 BasicBlockPass
*getContainedPass(unsigned N
) {
358 assert(N
< PassVector
.size() && "Pass number out of range!");
359 BasicBlockPass
*BP
= static_cast<BasicBlockPass
*>(PassVector
[N
]);
363 PassManagerType
getPassManagerType() const override
{
364 return PMT_BasicBlockPassManager
;
368 char BBPassManager::ID
= 0;
369 } // End anonymous namespace
373 //===----------------------------------------------------------------------===//
374 // FunctionPassManagerImpl
376 /// FunctionPassManagerImpl manages FPPassManagers
377 class FunctionPassManagerImpl
: public Pass
,
378 public PMDataManager
,
379 public PMTopLevelManager
{
380 virtual void anchor();
385 explicit FunctionPassManagerImpl() :
386 Pass(PT_PassManager
, ID
), PMDataManager(),
387 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
389 /// \copydoc FunctionPassManager::add()
394 /// createPrinterPass - Get a function printer pass.
395 Pass
*createPrinterPass(raw_ostream
&O
,
396 const std::string
&Banner
) const override
{
397 return createPrintFunctionPass(O
, Banner
);
400 // Prepare for running an on the fly pass, freeing memory if needed
401 // from a previous run.
402 void releaseMemoryOnTheFly();
404 /// run - Execute all of the passes scheduled for execution. Keep track of
405 /// whether any of the passes modifies the module, and if so, return true.
406 bool run(Function
&F
);
408 /// doInitialization - Run all of the initializers for the function passes.
410 bool doInitialization(Module
&M
) override
;
412 /// doFinalization - Run all of the finalizers for the function passes.
414 bool doFinalization(Module
&M
) override
;
417 PMDataManager
*getAsPMDataManager() override
{ return this; }
418 Pass
*getAsPass() override
{ return this; }
419 PassManagerType
getTopLevelPassManagerType() override
{
420 return PMT_FunctionPassManager
;
423 /// Pass Manager itself does not invalidate any analysis info.
424 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
425 Info
.setPreservesAll();
428 FPPassManager
*getContainedManager(unsigned N
) {
429 assert(N
< PassManagers
.size() && "Pass number out of range!");
430 FPPassManager
*FP
= static_cast<FPPassManager
*>(PassManagers
[N
]);
435 void FunctionPassManagerImpl::anchor() {}
437 char FunctionPassManagerImpl::ID
= 0;
438 } // End of legacy namespace
439 } // End of llvm namespace
442 //===----------------------------------------------------------------------===//
445 /// MPPassManager manages ModulePasses and function pass managers.
446 /// It batches all Module passes and function pass managers together and
447 /// sequences them to process one module.
448 class MPPassManager
: public Pass
, public PMDataManager
{
451 explicit MPPassManager() :
452 Pass(PT_PassManager
, ID
), PMDataManager() { }
454 // Delete on the fly managers.
455 ~MPPassManager() override
{
456 for (auto &OnTheFlyManager
: OnTheFlyManagers
) {
457 FunctionPassManagerImpl
*FPP
= OnTheFlyManager
.second
;
462 /// createPrinterPass - Get a module printer pass.
463 Pass
*createPrinterPass(raw_ostream
&O
,
464 const std::string
&Banner
) const override
{
465 return createPrintModulePass(O
, Banner
);
468 /// run - Execute all of the passes scheduled for execution. Keep track of
469 /// whether any of the passes modifies the module, and if so, return true.
470 bool runOnModule(Module
&M
);
472 using llvm::Pass::doInitialization
;
473 using llvm::Pass::doFinalization
;
475 /// Pass Manager itself does not invalidate any analysis info.
476 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
477 Info
.setPreservesAll();
480 /// Add RequiredPass into list of lower level passes required by pass P.
481 /// RequiredPass is run on the fly by Pass Manager when P requests it
482 /// through getAnalysis interface.
483 void addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) override
;
485 /// Return function pass corresponding to PassInfo PI, that is
486 /// required by module pass MP. Instantiate analysis pass, by using
487 /// its runOnFunction() for function F.
488 Pass
* getOnTheFlyPass(Pass
*MP
, AnalysisID PI
, Function
&F
) override
;
490 StringRef
getPassName() const override
{ return "Module Pass Manager"; }
492 PMDataManager
*getAsPMDataManager() override
{ return this; }
493 Pass
*getAsPass() override
{ return this; }
495 // Print passes managed by this manager
496 void dumpPassStructure(unsigned Offset
) override
{
497 dbgs().indent(Offset
*2) << "ModulePass Manager\n";
498 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
499 ModulePass
*MP
= getContainedPass(Index
);
500 MP
->dumpPassStructure(Offset
+ 1);
501 MapVector
<Pass
*, FunctionPassManagerImpl
*>::const_iterator I
=
502 OnTheFlyManagers
.find(MP
);
503 if (I
!= OnTheFlyManagers
.end())
504 I
->second
->dumpPassStructure(Offset
+ 2);
505 dumpLastUses(MP
, Offset
+1);
509 ModulePass
*getContainedPass(unsigned N
) {
510 assert(N
< PassVector
.size() && "Pass number out of range!");
511 return static_cast<ModulePass
*>(PassVector
[N
]);
514 PassManagerType
getPassManagerType() const override
{
515 return PMT_ModulePassManager
;
519 /// Collection of on the fly FPPassManagers. These managers manage
520 /// function passes that are required by module passes.
521 MapVector
<Pass
*, FunctionPassManagerImpl
*> OnTheFlyManagers
;
524 char MPPassManager::ID
= 0;
525 } // End anonymous namespace
529 //===----------------------------------------------------------------------===//
533 /// PassManagerImpl manages MPPassManagers
534 class PassManagerImpl
: public Pass
,
535 public PMDataManager
,
536 public PMTopLevelManager
{
537 virtual void anchor();
541 explicit PassManagerImpl() :
542 Pass(PT_PassManager
, ID
), PMDataManager(),
543 PMTopLevelManager(new MPPassManager()) {}
545 /// \copydoc PassManager::add()
550 /// createPrinterPass - Get a module printer pass.
551 Pass
*createPrinterPass(raw_ostream
&O
,
552 const std::string
&Banner
) const override
{
553 return createPrintModulePass(O
, Banner
);
556 /// run - Execute all of the passes scheduled for execution. Keep track of
557 /// whether any of the passes modifies the module, and if so, return true.
560 using llvm::Pass::doInitialization
;
561 using llvm::Pass::doFinalization
;
563 /// Pass Manager itself does not invalidate any analysis info.
564 void getAnalysisUsage(AnalysisUsage
&Info
) const override
{
565 Info
.setPreservesAll();
568 PMDataManager
*getAsPMDataManager() override
{ return this; }
569 Pass
*getAsPass() override
{ return this; }
570 PassManagerType
getTopLevelPassManagerType() override
{
571 return PMT_ModulePassManager
;
574 MPPassManager
*getContainedManager(unsigned N
) {
575 assert(N
< PassManagers
.size() && "Pass number out of range!");
576 MPPassManager
*MP
= static_cast<MPPassManager
*>(PassManagers
[N
]);
581 void PassManagerImpl::anchor() {}
583 char PassManagerImpl::ID
= 0;
584 } // End of legacy namespace
585 } // End of llvm namespace
587 //===----------------------------------------------------------------------===//
588 // PMTopLevelManager implementation
590 /// Initialize top level manager. Create first pass manager.
591 PMTopLevelManager::PMTopLevelManager(PMDataManager
*PMDM
) {
592 PMDM
->setTopLevelManager(this);
593 addPassManager(PMDM
);
594 activeStack
.push(PMDM
);
597 /// Set pass P as the last user of the given analysis passes.
599 PMTopLevelManager::setLastUser(ArrayRef
<Pass
*> AnalysisPasses
, Pass
*P
) {
601 if (P
->getResolver())
602 PDepth
= P
->getResolver()->getPMDataManager().getDepth();
604 for (Pass
*AP
: AnalysisPasses
) {
610 // Update the last users of passes that are required transitive by AP.
611 AnalysisUsage
*AnUsage
= findAnalysisUsage(AP
);
612 const AnalysisUsage::VectorType
&IDs
= AnUsage
->getRequiredTransitiveSet();
613 SmallVector
<Pass
*, 12> LastUses
;
614 SmallVector
<Pass
*, 12> LastPMUses
;
615 for (AnalysisID ID
: IDs
) {
616 Pass
*AnalysisPass
= findAnalysisPass(ID
);
617 assert(AnalysisPass
&& "Expected analysis pass to exist.");
618 AnalysisResolver
*AR
= AnalysisPass
->getResolver();
619 assert(AR
&& "Expected analysis resolver to exist.");
620 unsigned APDepth
= AR
->getPMDataManager().getDepth();
622 if (PDepth
== APDepth
)
623 LastUses
.push_back(AnalysisPass
);
624 else if (PDepth
> APDepth
)
625 LastPMUses
.push_back(AnalysisPass
);
628 setLastUser(LastUses
, P
);
630 // If this pass has a corresponding pass manager, push higher level
631 // analysis to this pass manager.
632 if (P
->getResolver())
633 setLastUser(LastPMUses
, P
->getResolver()->getPMDataManager().getAsPass());
636 // If AP is the last user of other passes then make P last user of
638 for (auto LU
: LastUser
) {
640 // DenseMap iterator is not invalidated here because
641 // this is just updating existing entries.
642 LastUser
[LU
.first
] = P
;
647 /// Collect passes whose last user is P
648 void PMTopLevelManager::collectLastUses(SmallVectorImpl
<Pass
*> &LastUses
,
650 DenseMap
<Pass
*, SmallPtrSet
<Pass
*, 8> >::iterator DMI
=
651 InversedLastUser
.find(P
);
652 if (DMI
== InversedLastUser
.end())
655 SmallPtrSet
<Pass
*, 8> &LU
= DMI
->second
;
656 for (Pass
*LUP
: LU
) {
657 LastUses
.push_back(LUP
);
662 AnalysisUsage
*PMTopLevelManager::findAnalysisUsage(Pass
*P
) {
663 AnalysisUsage
*AnUsage
= nullptr;
664 auto DMI
= AnUsageMap
.find(P
);
665 if (DMI
!= AnUsageMap
.end())
666 AnUsage
= DMI
->second
;
668 // Look up the analysis usage from the pass instance (different instances
669 // of the same pass can produce different results), but unique the
670 // resulting object to reduce memory usage. This helps to greatly reduce
671 // memory usage when we have many instances of only a few pass types
672 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
675 P
->getAnalysisUsage(AU
);
677 AUFoldingSetNode
* Node
= nullptr;
679 AUFoldingSetNode::Profile(ID
, AU
);
681 if (auto *N
= UniqueAnalysisUsages
.FindNodeOrInsertPos(ID
, IP
))
684 Node
= new (AUFoldingSetNodeAllocator
.Allocate()) AUFoldingSetNode(AU
);
685 UniqueAnalysisUsages
.InsertNode(Node
, IP
);
687 assert(Node
&& "cached analysis usage must be non null");
689 AnUsageMap
[P
] = &Node
->AU
;
695 /// Schedule pass P for execution. Make sure that passes required by
696 /// P are run before P is run. Update analysis info maintained by
697 /// the manager. Remove dead passes. This is a recursive function.
698 void PMTopLevelManager::schedulePass(Pass
*P
) {
700 // TODO : Allocate function manager for this pass, other wise required set
701 // may be inserted into previous function manager
703 // Give pass a chance to prepare the stage.
704 P
->preparePassManager(activeStack
);
706 // If P is an analysis pass and it is available then do not
707 // generate the analysis again. Stale analysis info should not be
708 // available at this point.
709 const PassInfo
*PI
= findAnalysisPassInfo(P
->getPassID());
710 if (PI
&& PI
->isAnalysis() && findAnalysisPass(P
->getPassID())) {
711 // Remove any cached AnalysisUsage information.
717 AnalysisUsage
*AnUsage
= findAnalysisUsage(P
);
719 bool checkAnalysis
= true;
720 while (checkAnalysis
) {
721 checkAnalysis
= false;
723 const AnalysisUsage::VectorType
&RequiredSet
= AnUsage
->getRequiredSet();
724 for (const AnalysisID ID
: RequiredSet
) {
726 Pass
*AnalysisPass
= findAnalysisPass(ID
);
728 const PassInfo
*PI
= findAnalysisPassInfo(ID
);
731 // Pass P is not in the global PassRegistry
732 dbgs() << "Pass '" << P
->getPassName() << "' is not initialized." << "\n";
733 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
734 dbgs() << "Required Passes:" << "\n";
735 for (const AnalysisID ID2
: RequiredSet
) {
738 Pass
*AnalysisPass2
= findAnalysisPass(ID2
);
740 dbgs() << "\t" << AnalysisPass2
->getPassName() << "\n";
742 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
743 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
744 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
749 assert(PI
&& "Expected required passes to be initialized");
750 AnalysisPass
= PI
->createPass();
751 if (P
->getPotentialPassManagerType () ==
752 AnalysisPass
->getPotentialPassManagerType())
753 // Schedule analysis pass that is managed by the same pass manager.
754 schedulePass(AnalysisPass
);
755 else if (P
->getPotentialPassManagerType () >
756 AnalysisPass
->getPotentialPassManagerType()) {
757 // Schedule analysis pass that is managed by a new manager.
758 schedulePass(AnalysisPass
);
759 // Recheck analysis passes to ensure that required analyses that
760 // are already checked are still available.
761 checkAnalysis
= true;
763 // Do not schedule this analysis. Lower level analysis
764 // passes are run on the fly.
770 // Now all required passes are available.
771 if (ImmutablePass
*IP
= P
->getAsImmutablePass()) {
772 // P is a immutable pass and it will be managed by this
773 // top level manager. Set up analysis resolver to connect them.
774 PMDataManager
*DM
= getAsPMDataManager();
775 AnalysisResolver
*AR
= new AnalysisResolver(*DM
);
777 DM
->initializeAnalysisImpl(P
);
778 addImmutablePass(IP
);
779 DM
->recordAvailableAnalysis(IP
);
783 if (PI
&& !PI
->isAnalysis() && ShouldPrintBeforePass(PI
)) {
784 Pass
*PP
= P
->createPrinterPass(
785 dbgs(), ("*** IR Dump Before " + P
->getPassName() + " ***").str());
786 PP
->assignPassManager(activeStack
, getTopLevelPassManagerType());
789 // Add the requested pass to the best available pass manager.
790 P
->assignPassManager(activeStack
, getTopLevelPassManagerType());
792 if (PI
&& !PI
->isAnalysis() && ShouldPrintAfterPass(PI
)) {
793 Pass
*PP
= P
->createPrinterPass(
794 dbgs(), ("*** IR Dump After " + P
->getPassName() + " ***").str());
795 PP
->assignPassManager(activeStack
, getTopLevelPassManagerType());
799 /// Find the pass that implements Analysis AID. Search immutable
800 /// passes and all pass managers. If desired pass is not found
801 /// then return NULL.
802 Pass
*PMTopLevelManager::findAnalysisPass(AnalysisID AID
) {
803 // For immutable passes we have a direct mapping from ID to pass, so check
805 if (Pass
*P
= ImmutablePassMap
.lookup(AID
))
808 // Check pass managers
809 for (PMDataManager
*PassManager
: PassManagers
)
810 if (Pass
*P
= PassManager
->findAnalysisPass(AID
, false))
813 // Check other pass managers
814 for (PMDataManager
*IndirectPassManager
: IndirectPassManagers
)
815 if (Pass
*P
= IndirectPassManager
->findAnalysisPass(AID
, false))
821 const PassInfo
*PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID
) const {
822 const PassInfo
*&PI
= AnalysisPassInfos
[AID
];
824 PI
= PassRegistry::getPassRegistry()->getPassInfo(AID
);
826 assert(PI
== PassRegistry::getPassRegistry()->getPassInfo(AID
) &&
827 "The pass info pointer changed for an analysis ID!");
832 void PMTopLevelManager::addImmutablePass(ImmutablePass
*P
) {
834 ImmutablePasses
.push_back(P
);
836 // Add this pass to the map from its analysis ID. We clobber any prior runs
837 // of the pass in the map so that the last one added is the one found when
839 AnalysisID AID
= P
->getPassID();
840 ImmutablePassMap
[AID
] = P
;
842 // Also add any interfaces implemented by the immutable pass to the map for
844 const PassInfo
*PassInf
= findAnalysisPassInfo(AID
);
845 assert(PassInf
&& "Expected all immutable passes to be initialized");
846 for (const PassInfo
*ImmPI
: PassInf
->getInterfacesImplemented())
847 ImmutablePassMap
[ImmPI
->getTypeInfo()] = P
;
850 // Print passes managed by this top level manager.
851 void PMTopLevelManager::dumpPasses() const {
853 if (PassDebugging
< Structure
)
856 // Print out the immutable passes
857 for (unsigned i
= 0, e
= ImmutablePasses
.size(); i
!= e
; ++i
) {
858 ImmutablePasses
[i
]->dumpPassStructure(0);
861 // Every class that derives from PMDataManager also derives from Pass
862 // (sometimes indirectly), but there's no inheritance relationship
863 // between PMDataManager and Pass, so we have to getAsPass to get
864 // from a PMDataManager* to a Pass*.
865 for (PMDataManager
*Manager
: PassManagers
)
866 Manager
->getAsPass()->dumpPassStructure(1);
869 void PMTopLevelManager::dumpArguments() const {
871 if (PassDebugging
< Arguments
)
874 dbgs() << "Pass Arguments: ";
875 for (ImmutablePass
*P
: ImmutablePasses
)
876 if (const PassInfo
*PI
= findAnalysisPassInfo(P
->getPassID())) {
877 assert(PI
&& "Expected all immutable passes to be initialized");
878 if (!PI
->isAnalysisGroup())
879 dbgs() << " -" << PI
->getPassArgument();
881 for (PMDataManager
*PM
: PassManagers
)
882 PM
->dumpPassArguments();
886 void PMTopLevelManager::initializeAllAnalysisInfo() {
887 for (PMDataManager
*PM
: PassManagers
)
888 PM
->initializeAnalysisInfo();
890 // Initailize other pass managers
891 for (PMDataManager
*IPM
: IndirectPassManagers
)
892 IPM
->initializeAnalysisInfo();
894 for (auto LU
: LastUser
) {
895 SmallPtrSet
<Pass
*, 8> &L
= InversedLastUser
[LU
.second
];
901 PMTopLevelManager::~PMTopLevelManager() {
902 for (PMDataManager
*PM
: PassManagers
)
905 for (ImmutablePass
*P
: ImmutablePasses
)
909 //===----------------------------------------------------------------------===//
910 // PMDataManager implementation
912 /// Augement AvailableAnalysis by adding analysis made available by pass P.
913 void PMDataManager::recordAvailableAnalysis(Pass
*P
) {
914 AnalysisID PI
= P
->getPassID();
916 AvailableAnalysis
[PI
] = P
;
918 assert(!AvailableAnalysis
.empty());
920 // This pass is the current implementation of all of the interfaces it
921 // implements as well.
922 const PassInfo
*PInf
= TPM
->findAnalysisPassInfo(PI
);
924 const std::vector
<const PassInfo
*> &II
= PInf
->getInterfacesImplemented();
925 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
)
926 AvailableAnalysis
[II
[i
]->getTypeInfo()] = P
;
929 // Return true if P preserves high level analysis used by other
930 // passes managed by this manager
931 bool PMDataManager::preserveHigherLevelAnalysis(Pass
*P
) {
932 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
933 if (AnUsage
->getPreservesAll())
936 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
937 for (Pass
*P1
: HigherLevelAnalysis
) {
938 if (P1
->getAsImmutablePass() == nullptr &&
939 !is_contained(PreservedSet
, P1
->getPassID()))
946 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
947 void PMDataManager::verifyPreservedAnalysis(Pass
*P
) {
948 // Don't do this unless assertions are enabled.
952 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
953 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
955 // Verify preserved analysis
956 for (AnalysisID AID
: PreservedSet
) {
957 if (Pass
*AP
= findAnalysisPass(AID
, true)) {
958 TimeRegion
PassTimer(getPassTimer(AP
));
959 AP
->verifyAnalysis();
964 /// Remove Analysis not preserved by Pass P
965 void PMDataManager::removeNotPreservedAnalysis(Pass
*P
) {
966 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
967 if (AnUsage
->getPreservesAll())
970 const AnalysisUsage::VectorType
&PreservedSet
= AnUsage
->getPreservedSet();
971 for (DenseMap
<AnalysisID
, Pass
*>::iterator I
= AvailableAnalysis
.begin(),
972 E
= AvailableAnalysis
.end(); I
!= E
; ) {
973 DenseMap
<AnalysisID
, Pass
*>::iterator Info
= I
++;
974 if (Info
->second
->getAsImmutablePass() == nullptr &&
975 !is_contained(PreservedSet
, Info
->first
)) {
976 // Remove this analysis
977 if (PassDebugging
>= Details
) {
978 Pass
*S
= Info
->second
;
979 dbgs() << " -- '" << P
->getPassName() << "' is not preserving '";
980 dbgs() << S
->getPassName() << "'\n";
982 AvailableAnalysis
.erase(Info
);
986 // Check inherited analysis also. If P is not preserving analysis
987 // provided by parent manager then remove it here.
988 for (unsigned Index
= 0; Index
< PMT_Last
; ++Index
) {
990 if (!InheritedAnalysis
[Index
])
993 for (DenseMap
<AnalysisID
, Pass
*>::iterator
994 I
= InheritedAnalysis
[Index
]->begin(),
995 E
= InheritedAnalysis
[Index
]->end(); I
!= E
; ) {
996 DenseMap
<AnalysisID
, Pass
*>::iterator Info
= I
++;
997 if (Info
->second
->getAsImmutablePass() == nullptr &&
998 !is_contained(PreservedSet
, Info
->first
)) {
999 // Remove this analysis
1000 if (PassDebugging
>= Details
) {
1001 Pass
*S
= Info
->second
;
1002 dbgs() << " -- '" << P
->getPassName() << "' is not preserving '";
1003 dbgs() << S
->getPassName() << "'\n";
1005 InheritedAnalysis
[Index
]->erase(Info
);
1011 /// Remove analysis passes that are not used any longer
1012 void PMDataManager::removeDeadPasses(Pass
*P
, StringRef Msg
,
1013 enum PassDebuggingString DBG_STR
) {
1015 SmallVector
<Pass
*, 12> DeadPasses
;
1017 // If this is a on the fly manager then it does not have TPM.
1021 TPM
->collectLastUses(DeadPasses
, P
);
1023 if (PassDebugging
>= Details
&& !DeadPasses
.empty()) {
1024 dbgs() << " -*- '" << P
->getPassName();
1025 dbgs() << "' is the last user of following pass instances.";
1026 dbgs() << " Free these instances\n";
1029 for (Pass
*P
: DeadPasses
)
1030 freePass(P
, Msg
, DBG_STR
);
1033 void PMDataManager::freePass(Pass
*P
, StringRef Msg
,
1034 enum PassDebuggingString DBG_STR
) {
1035 dumpPassInfo(P
, FREEING_MSG
, DBG_STR
, Msg
);
1038 // If the pass crashes releasing memory, remember this.
1039 PassManagerPrettyStackEntry
X(P
);
1040 TimeRegion
PassTimer(getPassTimer(P
));
1045 AnalysisID PI
= P
->getPassID();
1046 if (const PassInfo
*PInf
= TPM
->findAnalysisPassInfo(PI
)) {
1047 // Remove the pass itself (if it is not already removed).
1048 AvailableAnalysis
.erase(PI
);
1050 // Remove all interfaces this pass implements, for which it is also
1051 // listed as the available implementation.
1052 const std::vector
<const PassInfo
*> &II
= PInf
->getInterfacesImplemented();
1053 for (unsigned i
= 0, e
= II
.size(); i
!= e
; ++i
) {
1054 DenseMap
<AnalysisID
, Pass
*>::iterator Pos
=
1055 AvailableAnalysis
.find(II
[i
]->getTypeInfo());
1056 if (Pos
!= AvailableAnalysis
.end() && Pos
->second
== P
)
1057 AvailableAnalysis
.erase(Pos
);
1062 /// Add pass P into the PassVector. Update
1063 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1064 void PMDataManager::add(Pass
*P
, bool ProcessAnalysis
) {
1065 // This manager is going to manage pass P. Set up analysis resolver
1067 AnalysisResolver
*AR
= new AnalysisResolver(*this);
1070 // If a FunctionPass F is the last user of ModulePass info M
1071 // then the F's manager, not F, records itself as a last user of M.
1072 SmallVector
<Pass
*, 12> TransferLastUses
;
1074 if (!ProcessAnalysis
) {
1076 PassVector
.push_back(P
);
1080 // At the moment, this pass is the last user of all required passes.
1081 SmallVector
<Pass
*, 12> LastUses
;
1082 SmallVector
<Pass
*, 8> UsedPasses
;
1083 SmallVector
<AnalysisID
, 8> ReqAnalysisNotAvailable
;
1085 unsigned PDepth
= this->getDepth();
1087 collectRequiredAndUsedAnalyses(UsedPasses
, ReqAnalysisNotAvailable
, P
);
1088 for (Pass
*PUsed
: UsedPasses
) {
1089 unsigned RDepth
= 0;
1091 assert(PUsed
->getResolver() && "Analysis Resolver is not set");
1092 PMDataManager
&DM
= PUsed
->getResolver()->getPMDataManager();
1093 RDepth
= DM
.getDepth();
1095 if (PDepth
== RDepth
)
1096 LastUses
.push_back(PUsed
);
1097 else if (PDepth
> RDepth
) {
1098 // Let the parent claim responsibility of last use
1099 TransferLastUses
.push_back(PUsed
);
1100 // Keep track of higher level analysis used by this manager.
1101 HigherLevelAnalysis
.push_back(PUsed
);
1103 llvm_unreachable("Unable to accommodate Used Pass");
1106 // Set P as P's last user until someone starts using P.
1107 // However, if P is a Pass Manager then it does not need
1108 // to record its last user.
1109 if (!P
->getAsPMDataManager())
1110 LastUses
.push_back(P
);
1111 TPM
->setLastUser(LastUses
, P
);
1113 if (!TransferLastUses
.empty()) {
1114 Pass
*My_PM
= getAsPass();
1115 TPM
->setLastUser(TransferLastUses
, My_PM
);
1116 TransferLastUses
.clear();
1119 // Now, take care of required analyses that are not available.
1120 for (AnalysisID ID
: ReqAnalysisNotAvailable
) {
1121 const PassInfo
*PI
= TPM
->findAnalysisPassInfo(ID
);
1122 Pass
*AnalysisPass
= PI
->createPass();
1123 this->addLowerLevelRequiredPass(P
, AnalysisPass
);
1126 // Take a note of analysis required and made available by this pass.
1127 // Remove the analysis not preserved by this pass
1128 removeNotPreservedAnalysis(P
);
1129 recordAvailableAnalysis(P
);
1132 PassVector
.push_back(P
);
1136 /// Populate UP with analysis pass that are used or required by
1137 /// pass P and are available. Populate RP_NotAvail with analysis
1138 /// pass that are required by pass P but are not available.
1139 void PMDataManager::collectRequiredAndUsedAnalyses(
1140 SmallVectorImpl
<Pass
*> &UP
, SmallVectorImpl
<AnalysisID
> &RP_NotAvail
,
1142 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
1144 for (const auto &UsedID
: AnUsage
->getUsedSet())
1145 if (Pass
*AnalysisPass
= findAnalysisPass(UsedID
, true))
1146 UP
.push_back(AnalysisPass
);
1148 for (const auto &RequiredID
: AnUsage
->getRequiredSet())
1149 if (Pass
*AnalysisPass
= findAnalysisPass(RequiredID
, true))
1150 UP
.push_back(AnalysisPass
);
1152 RP_NotAvail
.push_back(RequiredID
);
1154 for (const auto &RequiredID
: AnUsage
->getRequiredTransitiveSet())
1155 if (Pass
*AnalysisPass
= findAnalysisPass(RequiredID
, true))
1156 UP
.push_back(AnalysisPass
);
1158 RP_NotAvail
.push_back(RequiredID
);
1161 // All Required analyses should be available to the pass as it runs! Here
1162 // we fill in the AnalysisImpls member of the pass so that it can
1163 // successfully use the getAnalysis() method to retrieve the
1164 // implementations it needs.
1166 void PMDataManager::initializeAnalysisImpl(Pass
*P
) {
1167 AnalysisUsage
*AnUsage
= TPM
->findAnalysisUsage(P
);
1169 for (const AnalysisID ID
: AnUsage
->getRequiredSet()) {
1170 Pass
*Impl
= findAnalysisPass(ID
, true);
1172 // This may be analysis pass that is initialized on the fly.
1173 // If that is not the case then it will raise an assert when it is used.
1175 AnalysisResolver
*AR
= P
->getResolver();
1176 assert(AR
&& "Analysis Resolver is not set");
1177 AR
->addAnalysisImplsPair(ID
, Impl
);
1181 /// Find the pass that implements Analysis AID. If desired pass is not found
1182 /// then return NULL.
1183 Pass
*PMDataManager::findAnalysisPass(AnalysisID AID
, bool SearchParent
) {
1185 // Check if AvailableAnalysis map has one entry.
1186 DenseMap
<AnalysisID
, Pass
*>::const_iterator I
= AvailableAnalysis
.find(AID
);
1188 if (I
!= AvailableAnalysis
.end())
1191 // Search Parents through TopLevelManager
1193 return TPM
->findAnalysisPass(AID
);
1198 // Print list of passes that are last used by P.
1199 void PMDataManager::dumpLastUses(Pass
*P
, unsigned Offset
) const{
1201 SmallVector
<Pass
*, 12> LUses
;
1203 // If this is a on the fly manager then it does not have TPM.
1207 TPM
->collectLastUses(LUses
, P
);
1209 for (Pass
*P
: LUses
) {
1210 dbgs() << "--" << std::string(Offset
*2, ' ');
1211 P
->dumpPassStructure(0);
1215 void PMDataManager::dumpPassArguments() const {
1216 for (Pass
*P
: PassVector
) {
1217 if (PMDataManager
*PMD
= P
->getAsPMDataManager())
1218 PMD
->dumpPassArguments();
1220 if (const PassInfo
*PI
=
1221 TPM
->findAnalysisPassInfo(P
->getPassID()))
1222 if (!PI
->isAnalysisGroup())
1223 dbgs() << " -" << PI
->getPassArgument();
1227 void PMDataManager::dumpPassInfo(Pass
*P
, enum PassDebuggingString S1
,
1228 enum PassDebuggingString S2
,
1230 if (PassDebugging
< Executions
)
1232 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1233 << std::string(getDepth() * 2 + 1, ' ');
1236 dbgs() << "Executing Pass '" << P
->getPassName();
1238 case MODIFICATION_MSG
:
1239 dbgs() << "Made Modification '" << P
->getPassName();
1242 dbgs() << " Freeing Pass '" << P
->getPassName();
1248 case ON_BASICBLOCK_MSG
:
1249 dbgs() << "' on BasicBlock '" << Msg
<< "'...\n";
1251 case ON_FUNCTION_MSG
:
1252 dbgs() << "' on Function '" << Msg
<< "'...\n";
1255 dbgs() << "' on Module '" << Msg
<< "'...\n";
1258 dbgs() << "' on Region '" << Msg
<< "'...\n";
1261 dbgs() << "' on Loop '" << Msg
<< "'...\n";
1264 dbgs() << "' on Call Graph Nodes '" << Msg
<< "'...\n";
1271 void PMDataManager::dumpRequiredSet(const Pass
*P
) const {
1272 if (PassDebugging
< Details
)
1275 AnalysisUsage analysisUsage
;
1276 P
->getAnalysisUsage(analysisUsage
);
1277 dumpAnalysisUsage("Required", P
, analysisUsage
.getRequiredSet());
1280 void PMDataManager::dumpPreservedSet(const Pass
*P
) const {
1281 if (PassDebugging
< Details
)
1284 AnalysisUsage analysisUsage
;
1285 P
->getAnalysisUsage(analysisUsage
);
1286 dumpAnalysisUsage("Preserved", P
, analysisUsage
.getPreservedSet());
1289 void PMDataManager::dumpUsedSet(const Pass
*P
) const {
1290 if (PassDebugging
< Details
)
1293 AnalysisUsage analysisUsage
;
1294 P
->getAnalysisUsage(analysisUsage
);
1295 dumpAnalysisUsage("Used", P
, analysisUsage
.getUsedSet());
1298 void PMDataManager::dumpAnalysisUsage(StringRef Msg
, const Pass
*P
,
1299 const AnalysisUsage::VectorType
&Set
) const {
1300 assert(PassDebugging
>= Details
);
1303 dbgs() << (const void*)P
<< std::string(getDepth()*2+3, ' ') << Msg
<< " Analyses:";
1304 for (unsigned i
= 0; i
!= Set
.size(); ++i
) {
1305 if (i
) dbgs() << ',';
1306 const PassInfo
*PInf
= TPM
->findAnalysisPassInfo(Set
[i
]);
1308 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1310 dbgs() << " Uninitialized Pass";
1313 dbgs() << ' ' << PInf
->getPassName();
1318 /// Add RequiredPass into list of lower level passes required by pass P.
1319 /// RequiredPass is run on the fly by Pass Manager when P requests it
1320 /// through getAnalysis interface.
1321 /// This should be handled by specific pass manager.
1322 void PMDataManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1324 TPM
->dumpArguments();
1328 // Module Level pass may required Function Level analysis info
1329 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1330 // to provide this on demand. In that case, in Pass manager terminology,
1331 // module level pass is requiring lower level analysis info managed by
1332 // lower level pass manager.
1334 // When Pass manager is not able to order required analysis info, Pass manager
1335 // checks whether any lower level manager will be able to provide this
1336 // analysis info on demand or not.
1338 dbgs() << "Unable to schedule '" << RequiredPass
->getPassName();
1339 dbgs() << "' required by '" << P
->getPassName() << "'\n";
1341 llvm_unreachable("Unable to schedule pass");
1344 Pass
*PMDataManager::getOnTheFlyPass(Pass
*P
, AnalysisID PI
, Function
&F
) {
1345 llvm_unreachable("Unable to find on the fly pass");
1349 PMDataManager::~PMDataManager() {
1350 for (Pass
*P
: PassVector
)
1354 //===----------------------------------------------------------------------===//
1355 // NOTE: Is this the right place to define this method ?
1356 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1357 Pass
*AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID
, bool dir
) const {
1358 return PM
.findAnalysisPass(ID
, dir
);
1361 Pass
*AnalysisResolver::findImplPass(Pass
*P
, AnalysisID AnalysisPI
,
1363 return PM
.getOnTheFlyPass(P
, AnalysisPI
, F
);
1366 //===----------------------------------------------------------------------===//
1367 // BBPassManager implementation
1369 /// Execute all of the passes scheduled for execution by invoking
1370 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1371 /// the function, and if so, return true.
1372 bool BBPassManager::runOnFunction(Function
&F
) {
1373 if (F
.isDeclaration())
1376 bool Changed
= doInitialization(F
);
1377 Module
&M
= *F
.getParent();
1379 unsigned InstrCount
, BBSize
= 0;
1380 StringMap
<std::pair
<unsigned, unsigned>> FunctionToInstrCount
;
1381 bool EmitICRemark
= M
.shouldEmitInstrCountChangedRemark();
1383 InstrCount
= initSizeRemarkInfo(M
, FunctionToInstrCount
);
1385 for (BasicBlock
&BB
: F
) {
1386 // Collect the initial size of the basic block.
1389 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1390 BasicBlockPass
*BP
= getContainedPass(Index
);
1391 bool LocalChanged
= false;
1393 dumpPassInfo(BP
, EXECUTION_MSG
, ON_BASICBLOCK_MSG
, BB
.getName());
1394 dumpRequiredSet(BP
);
1396 initializeAnalysisImpl(BP
);
1399 // If the pass crashes, remember this.
1400 PassManagerPrettyStackEntry
X(BP
, BB
);
1401 TimeRegion
PassTimer(getPassTimer(BP
));
1402 LocalChanged
|= BP
->runOnBasicBlock(BB
);
1404 unsigned NewSize
= BB
.size();
1405 // Update the size of the basic block, emit a remark, and update the
1406 // size of the module.
1407 if (NewSize
!= BBSize
) {
1409 static_cast<int64_t>(NewSize
) - static_cast<int64_t>(BBSize
);
1410 emitInstrCountChangedRemark(BP
, M
, Delta
, InstrCount
,
1411 FunctionToInstrCount
, &F
);
1412 InstrCount
= static_cast<int64_t>(InstrCount
) + Delta
;
1418 Changed
|= LocalChanged
;
1420 dumpPassInfo(BP
, MODIFICATION_MSG
, ON_BASICBLOCK_MSG
,
1422 dumpPreservedSet(BP
);
1425 verifyPreservedAnalysis(BP
);
1426 removeNotPreservedAnalysis(BP
);
1427 recordAvailableAnalysis(BP
);
1428 removeDeadPasses(BP
, BB
.getName(), ON_BASICBLOCK_MSG
);
1432 return doFinalization(F
) || Changed
;
1435 // Implement doInitialization and doFinalization
1436 bool BBPassManager::doInitialization(Module
&M
) {
1437 bool Changed
= false;
1439 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1440 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1445 bool BBPassManager::doFinalization(Module
&M
) {
1446 bool Changed
= false;
1448 for (int Index
= getNumContainedPasses() - 1; Index
>= 0; --Index
)
1449 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1454 bool BBPassManager::doInitialization(Function
&F
) {
1455 bool Changed
= false;
1457 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1458 BasicBlockPass
*BP
= getContainedPass(Index
);
1459 Changed
|= BP
->doInitialization(F
);
1465 bool BBPassManager::doFinalization(Function
&F
) {
1466 bool Changed
= false;
1468 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1469 BasicBlockPass
*BP
= getContainedPass(Index
);
1470 Changed
|= BP
->doFinalization(F
);
1477 //===----------------------------------------------------------------------===//
1478 // FunctionPassManager implementation
1480 /// Create new Function pass manager
1481 FunctionPassManager::FunctionPassManager(Module
*m
) : M(m
) {
1482 FPM
= new FunctionPassManagerImpl();
1483 // FPM is the top level manager.
1484 FPM
->setTopLevelManager(FPM
);
1486 AnalysisResolver
*AR
= new AnalysisResolver(*FPM
);
1487 FPM
->setResolver(AR
);
1490 FunctionPassManager::~FunctionPassManager() {
1494 void FunctionPassManager::add(Pass
*P
) {
1498 /// run - Execute all of the passes scheduled for execution. Keep
1499 /// track of whether any of the passes modifies the function, and if
1500 /// so, return true.
1502 bool FunctionPassManager::run(Function
&F
) {
1503 handleAllErrors(F
.materialize(), [&](ErrorInfoBase
&EIB
) {
1504 report_fatal_error("Error reading bitcode file: " + EIB
.message());
1510 /// doInitialization - Run all of the initializers for the function passes.
1512 bool FunctionPassManager::doInitialization() {
1513 return FPM
->doInitialization(*M
);
1516 /// doFinalization - Run all of the finalizers for the function passes.
1518 bool FunctionPassManager::doFinalization() {
1519 return FPM
->doFinalization(*M
);
1522 //===----------------------------------------------------------------------===//
1523 // FunctionPassManagerImpl implementation
1525 bool FunctionPassManagerImpl::doInitialization(Module
&M
) {
1526 bool Changed
= false;
1531 for (ImmutablePass
*ImPass
: getImmutablePasses())
1532 Changed
|= ImPass
->doInitialization(M
);
1534 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1535 Changed
|= getContainedManager(Index
)->doInitialization(M
);
1540 bool FunctionPassManagerImpl::doFinalization(Module
&M
) {
1541 bool Changed
= false;
1543 for (int Index
= getNumContainedManagers() - 1; Index
>= 0; --Index
)
1544 Changed
|= getContainedManager(Index
)->doFinalization(M
);
1546 for (ImmutablePass
*ImPass
: getImmutablePasses())
1547 Changed
|= ImPass
->doFinalization(M
);
1552 /// cleanup - After running all passes, clean up pass manager cache.
1553 void FPPassManager::cleanup() {
1554 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1555 FunctionPass
*FP
= getContainedPass(Index
);
1556 AnalysisResolver
*AR
= FP
->getResolver();
1557 assert(AR
&& "Analysis Resolver is not set");
1558 AR
->clearAnalysisImpls();
1562 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1565 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
1566 FPPassManager
*FPPM
= getContainedManager(Index
);
1567 for (unsigned Index
= 0; Index
< FPPM
->getNumContainedPasses(); ++Index
) {
1568 FPPM
->getContainedPass(Index
)->releaseMemory();
1574 // Execute all the passes managed by this top level manager.
1575 // Return true if any function is modified by a pass.
1576 bool FunctionPassManagerImpl::run(Function
&F
) {
1577 bool Changed
= false;
1579 initializeAllAnalysisInfo();
1580 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
1581 Changed
|= getContainedManager(Index
)->runOnFunction(F
);
1582 F
.getContext().yield();
1585 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
)
1586 getContainedManager(Index
)->cleanup();
1592 //===----------------------------------------------------------------------===//
1593 // FPPassManager implementation
1595 char FPPassManager::ID
= 0;
1596 /// Print passes managed by this manager
1597 void FPPassManager::dumpPassStructure(unsigned Offset
) {
1598 dbgs().indent(Offset
*2) << "FunctionPass Manager\n";
1599 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1600 FunctionPass
*FP
= getContainedPass(Index
);
1601 FP
->dumpPassStructure(Offset
+ 1);
1602 dumpLastUses(FP
, Offset
+1);
1607 /// Execute all of the passes scheduled for execution by invoking
1608 /// runOnFunction method. Keep track of whether any of the passes modifies
1609 /// the function, and if so, return true.
1610 bool FPPassManager::runOnFunction(Function
&F
) {
1611 if (F
.isDeclaration())
1614 bool Changed
= false;
1615 Module
&M
= *F
.getParent();
1616 // Collect inherited analysis from Module level pass manager.
1617 populateInheritedAnalysis(TPM
->activeStack
);
1619 unsigned InstrCount
, FunctionSize
= 0;
1620 StringMap
<std::pair
<unsigned, unsigned>> FunctionToInstrCount
;
1621 bool EmitICRemark
= M
.shouldEmitInstrCountChangedRemark();
1622 // Collect the initial size of the module.
1624 InstrCount
= initSizeRemarkInfo(M
, FunctionToInstrCount
);
1625 FunctionSize
= F
.getInstructionCount();
1628 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1629 FunctionPass
*FP
= getContainedPass(Index
);
1630 bool LocalChanged
= false;
1632 dumpPassInfo(FP
, EXECUTION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1633 dumpRequiredSet(FP
);
1635 initializeAnalysisImpl(FP
);
1638 PassManagerPrettyStackEntry
X(FP
, F
);
1639 TimeRegion
PassTimer(getPassTimer(FP
));
1640 LocalChanged
|= FP
->runOnFunction(F
);
1642 unsigned NewSize
= F
.getInstructionCount();
1644 // Update the size of the function, emit a remark, and update the size
1646 if (NewSize
!= FunctionSize
) {
1647 int64_t Delta
= static_cast<int64_t>(NewSize
) -
1648 static_cast<int64_t>(FunctionSize
);
1649 emitInstrCountChangedRemark(FP
, M
, Delta
, InstrCount
,
1650 FunctionToInstrCount
, &F
);
1651 InstrCount
= static_cast<int64_t>(InstrCount
) + Delta
;
1652 FunctionSize
= NewSize
;
1657 Changed
|= LocalChanged
;
1659 dumpPassInfo(FP
, MODIFICATION_MSG
, ON_FUNCTION_MSG
, F
.getName());
1660 dumpPreservedSet(FP
);
1663 verifyPreservedAnalysis(FP
);
1664 removeNotPreservedAnalysis(FP
);
1665 recordAvailableAnalysis(FP
);
1666 removeDeadPasses(FP
, F
.getName(), ON_FUNCTION_MSG
);
1671 bool FPPassManager::runOnModule(Module
&M
) {
1672 bool Changed
= false;
1674 for (Function
&F
: M
)
1675 Changed
|= runOnFunction(F
);
1680 bool FPPassManager::doInitialization(Module
&M
) {
1681 bool Changed
= false;
1683 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1684 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1689 bool FPPassManager::doFinalization(Module
&M
) {
1690 bool Changed
= false;
1692 for (int Index
= getNumContainedPasses() - 1; Index
>= 0; --Index
)
1693 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1698 //===----------------------------------------------------------------------===//
1699 // MPPassManager implementation
1701 /// Execute all of the passes scheduled for execution by invoking
1702 /// runOnModule method. Keep track of whether any of the passes modifies
1703 /// the module, and if so, return true.
1705 MPPassManager::runOnModule(Module
&M
) {
1706 bool Changed
= false;
1708 // Initialize on-the-fly passes
1709 for (auto &OnTheFlyManager
: OnTheFlyManagers
) {
1710 FunctionPassManagerImpl
*FPP
= OnTheFlyManager
.second
;
1711 Changed
|= FPP
->doInitialization(M
);
1714 // Initialize module passes
1715 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
)
1716 Changed
|= getContainedPass(Index
)->doInitialization(M
);
1718 unsigned InstrCount
, ModuleCount
= 0;
1719 StringMap
<std::pair
<unsigned, unsigned>> FunctionToInstrCount
;
1720 bool EmitICRemark
= M
.shouldEmitInstrCountChangedRemark();
1721 // Collect the initial size of the module.
1723 InstrCount
= initSizeRemarkInfo(M
, FunctionToInstrCount
);
1724 ModuleCount
= InstrCount
;
1727 for (unsigned Index
= 0; Index
< getNumContainedPasses(); ++Index
) {
1728 ModulePass
*MP
= getContainedPass(Index
);
1729 bool LocalChanged
= false;
1731 dumpPassInfo(MP
, EXECUTION_MSG
, ON_MODULE_MSG
, M
.getModuleIdentifier());
1732 dumpRequiredSet(MP
);
1734 initializeAnalysisImpl(MP
);
1737 PassManagerPrettyStackEntry
X(MP
, M
);
1738 TimeRegion
PassTimer(getPassTimer(MP
));
1740 LocalChanged
|= MP
->runOnModule(M
);
1742 // Update the size of the module.
1743 ModuleCount
= M
.getInstructionCount();
1744 if (ModuleCount
!= InstrCount
) {
1745 int64_t Delta
= static_cast<int64_t>(ModuleCount
) -
1746 static_cast<int64_t>(InstrCount
);
1747 emitInstrCountChangedRemark(MP
, M
, Delta
, InstrCount
,
1748 FunctionToInstrCount
);
1749 InstrCount
= ModuleCount
;
1754 Changed
|= LocalChanged
;
1756 dumpPassInfo(MP
, MODIFICATION_MSG
, ON_MODULE_MSG
,
1757 M
.getModuleIdentifier());
1758 dumpPreservedSet(MP
);
1761 verifyPreservedAnalysis(MP
);
1762 removeNotPreservedAnalysis(MP
);
1763 recordAvailableAnalysis(MP
);
1764 removeDeadPasses(MP
, M
.getModuleIdentifier(), ON_MODULE_MSG
);
1767 // Finalize module passes
1768 for (int Index
= getNumContainedPasses() - 1; Index
>= 0; --Index
)
1769 Changed
|= getContainedPass(Index
)->doFinalization(M
);
1771 // Finalize on-the-fly passes
1772 for (auto &OnTheFlyManager
: OnTheFlyManagers
) {
1773 FunctionPassManagerImpl
*FPP
= OnTheFlyManager
.second
;
1774 // We don't know when is the last time an on-the-fly pass is run,
1775 // so we need to releaseMemory / finalize here
1776 FPP
->releaseMemoryOnTheFly();
1777 Changed
|= FPP
->doFinalization(M
);
1783 /// Add RequiredPass into list of lower level passes required by pass P.
1784 /// RequiredPass is run on the fly by Pass Manager when P requests it
1785 /// through getAnalysis interface.
1786 void MPPassManager::addLowerLevelRequiredPass(Pass
*P
, Pass
*RequiredPass
) {
1787 assert(P
->getPotentialPassManagerType() == PMT_ModulePassManager
&&
1788 "Unable to handle Pass that requires lower level Analysis pass");
1789 assert((P
->getPotentialPassManagerType() <
1790 RequiredPass
->getPotentialPassManagerType()) &&
1791 "Unable to handle Pass that requires lower level Analysis pass");
1795 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[P
];
1797 FPP
= new FunctionPassManagerImpl();
1798 // FPP is the top level manager.
1799 FPP
->setTopLevelManager(FPP
);
1801 OnTheFlyManagers
[P
] = FPP
;
1803 const PassInfo
*RequiredPassPI
=
1804 TPM
->findAnalysisPassInfo(RequiredPass
->getPassID());
1806 Pass
*FoundPass
= nullptr;
1807 if (RequiredPassPI
&& RequiredPassPI
->isAnalysis()) {
1809 ((PMTopLevelManager
*)FPP
)->findAnalysisPass(RequiredPass
->getPassID());
1812 FoundPass
= RequiredPass
;
1813 // This should be guaranteed to add RequiredPass to the passmanager given
1814 // that we checked for an available analysis above.
1815 FPP
->add(RequiredPass
);
1817 // Register P as the last user of FoundPass or RequiredPass.
1818 SmallVector
<Pass
*, 1> LU
;
1819 LU
.push_back(FoundPass
);
1820 FPP
->setLastUser(LU
, P
);
1823 /// Return function pass corresponding to PassInfo PI, that is
1824 /// required by module pass MP. Instantiate analysis pass, by using
1825 /// its runOnFunction() for function F.
1826 Pass
* MPPassManager::getOnTheFlyPass(Pass
*MP
, AnalysisID PI
, Function
&F
){
1827 FunctionPassManagerImpl
*FPP
= OnTheFlyManagers
[MP
];
1828 assert(FPP
&& "Unable to find on the fly pass");
1830 FPP
->releaseMemoryOnTheFly();
1832 return ((PMTopLevelManager
*)FPP
)->findAnalysisPass(PI
);
1836 //===----------------------------------------------------------------------===//
1837 // PassManagerImpl implementation
1840 /// run - Execute all of the passes scheduled for execution. Keep track of
1841 /// whether any of the passes modifies the module, and if so, return true.
1842 bool PassManagerImpl::run(Module
&M
) {
1843 bool Changed
= false;
1848 for (ImmutablePass
*ImPass
: getImmutablePasses())
1849 Changed
|= ImPass
->doInitialization(M
);
1851 initializeAllAnalysisInfo();
1852 for (unsigned Index
= 0; Index
< getNumContainedManagers(); ++Index
) {
1853 Changed
|= getContainedManager(Index
)->runOnModule(M
);
1854 M
.getContext().yield();
1857 for (ImmutablePass
*ImPass
: getImmutablePasses())
1858 Changed
|= ImPass
->doFinalization(M
);
1863 //===----------------------------------------------------------------------===//
1864 // PassManager implementation
1866 /// Create new pass manager
1867 PassManager::PassManager() {
1868 PM
= new PassManagerImpl();
1869 // PM is the top level manager
1870 PM
->setTopLevelManager(PM
);
1873 PassManager::~PassManager() {
1877 void PassManager::add(Pass
*P
) {
1881 /// run - Execute all of the passes scheduled for execution. Keep track of
1882 /// whether any of the passes modifies the module, and if so, return true.
1883 bool PassManager::run(Module
&M
) {
1887 //===----------------------------------------------------------------------===//
1888 // PMStack implementation
1891 // Pop Pass Manager from the stack and clear its analysis info.
1892 void PMStack::pop() {
1894 PMDataManager
*Top
= this->top();
1895 Top
->initializeAnalysisInfo();
1900 // Push PM on the stack and set its top level manager.
1901 void PMStack::push(PMDataManager
*PM
) {
1902 assert(PM
&& "Unable to push. Pass Manager expected");
1903 assert(PM
->getDepth()==0 && "Pass Manager depth set too early");
1905 if (!this->empty()) {
1906 assert(PM
->getPassManagerType() > this->top()->getPassManagerType()
1907 && "pushing bad pass manager to PMStack");
1908 PMTopLevelManager
*TPM
= this->top()->getTopLevelManager();
1910 assert(TPM
&& "Unable to find top level manager");
1911 TPM
->addIndirectPassManager(PM
);
1912 PM
->setTopLevelManager(TPM
);
1913 PM
->setDepth(this->top()->getDepth()+1);
1915 assert((PM
->getPassManagerType() == PMT_ModulePassManager
1916 || PM
->getPassManagerType() == PMT_FunctionPassManager
)
1917 && "pushing bad pass manager to PMStack");
1924 // Dump content of the pass manager stack.
1925 LLVM_DUMP_METHOD
void PMStack::dump() const {
1926 for (PMDataManager
*Manager
: S
)
1927 dbgs() << Manager
->getAsPass()->getPassName() << ' ';
1933 /// Find appropriate Module Pass Manager in the PM Stack and
1934 /// add self into that manager.
1935 void ModulePass::assignPassManager(PMStack
&PMS
,
1936 PassManagerType PreferredType
) {
1937 // Find Module Pass Manager
1938 while (!PMS
.empty()) {
1939 PassManagerType TopPMType
= PMS
.top()->getPassManagerType();
1940 if (TopPMType
== PreferredType
)
1941 break; // We found desired pass manager
1942 else if (TopPMType
> PMT_ModulePassManager
)
1943 PMS
.pop(); // Pop children pass managers
1947 assert(!PMS
.empty() && "Unable to find appropriate Pass Manager");
1948 PMS
.top()->add(this);
1951 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1952 /// in the PM Stack and add self into that manager.
1953 void FunctionPass::assignPassManager(PMStack
&PMS
,
1954 PassManagerType PreferredType
) {
1956 // Find Function Pass Manager
1957 while (!PMS
.empty()) {
1958 if (PMS
.top()->getPassManagerType() > PMT_FunctionPassManager
)
1964 // Create new Function Pass Manager if needed.
1966 if (PMS
.top()->getPassManagerType() == PMT_FunctionPassManager
) {
1967 FPP
= (FPPassManager
*)PMS
.top();
1969 assert(!PMS
.empty() && "Unable to create Function Pass Manager");
1970 PMDataManager
*PMD
= PMS
.top();
1972 // [1] Create new Function Pass Manager
1973 FPP
= new FPPassManager();
1974 FPP
->populateInheritedAnalysis(PMS
);
1976 // [2] Set up new manager's top level manager
1977 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
1978 TPM
->addIndirectPassManager(FPP
);
1980 // [3] Assign manager to manage this new manager. This may create
1981 // and push new managers into PMS
1982 FPP
->assignPassManager(PMS
, PMD
->getPassManagerType());
1984 // [4] Push new manager into PMS
1988 // Assign FPP as the manager of this pass.
1992 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1993 /// in the PM Stack and add self into that manager.
1994 void BasicBlockPass::assignPassManager(PMStack
&PMS
,
1995 PassManagerType PreferredType
) {
1998 // Basic Pass Manager is a leaf pass manager. It does not handle
1999 // any other pass manager.
2001 PMS
.top()->getPassManagerType() == PMT_BasicBlockPassManager
) {
2002 BBP
= (BBPassManager
*)PMS
.top();
2004 // If leaf manager is not Basic Block Pass manager then create new
2005 // basic Block Pass manager.
2006 assert(!PMS
.empty() && "Unable to create BasicBlock Pass Manager");
2007 PMDataManager
*PMD
= PMS
.top();
2009 // [1] Create new Basic Block Manager
2010 BBP
= new BBPassManager();
2012 // [2] Set up new manager's top level manager
2013 // Basic Block Pass Manager does not live by itself
2014 PMTopLevelManager
*TPM
= PMD
->getTopLevelManager();
2015 TPM
->addIndirectPassManager(BBP
);
2017 // [3] Assign manager to manage this new manager. This may create
2018 // and push new managers into PMS
2019 BBP
->assignPassManager(PMS
, PreferredType
);
2021 // [4] Push new manager into PMS
2025 // Assign BBP as the manager of this pass.
2029 PassManagerBase::~PassManagerBase() {}