Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / IR / LegacyPassManager.cpp
blob98b7d9b76aaaad9b3ee8281bc72b31ac1a18ba2c
1 //===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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/ADT/Statistic.h"
16 #include "llvm/IR/DiagnosticInfo.h"
17 #include "llvm/IR/IRPrintingPasses.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/LegacyPassManagers.h"
20 #include "llvm/IR/LegacyPassNameParser.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/PassTimingInfo.h"
23 #include "llvm/Support/Chrono.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/Mutex.h"
30 #include "llvm/Support/Timer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <unordered_set>
34 using namespace llvm;
35 using namespace llvm::legacy;
37 // See PassManagers.h for Pass Manager infrastructure overview.
39 //===----------------------------------------------------------------------===//
40 // Pass debugging information. Often it is useful to find out what pass is
41 // running when a crash occurs in a utility. When this library is compiled with
42 // debugging on, a command line option (--debug-pass) is enabled that causes the
43 // pass name to be printed before it executes.
46 namespace {
47 // Different debug levels that can be enabled...
48 enum PassDebugLevel {
49 Disabled, Arguments, Structure, Executions, Details
53 static cl::opt<enum PassDebugLevel>
54 PassDebugging("debug-pass", cl::Hidden,
55 cl::desc("Print PassManager debugging information"),
56 cl::values(
57 clEnumVal(Disabled , "disable debug output"),
58 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
59 clEnumVal(Structure , "print pass structure before run()"),
60 clEnumVal(Executions, "print pass name before it is executed"),
61 clEnumVal(Details , "print pass details when it is executed")));
63 namespace {
64 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
65 PassOptionList;
68 // Print IR out before/after specified passes.
69 static PassOptionList
70 PrintBefore("print-before",
71 llvm::cl::desc("Print IR before specified passes"),
72 cl::Hidden);
74 static PassOptionList
75 PrintAfter("print-after",
76 llvm::cl::desc("Print IR after specified passes"),
77 cl::Hidden);
79 static cl::opt<bool> PrintBeforeAll("print-before-all",
80 llvm::cl::desc("Print IR before each pass"),
81 cl::init(false), cl::Hidden);
82 static cl::opt<bool> PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
84 cl::init(false), cl::Hidden);
86 static cl::opt<bool>
87 PrintModuleScope("print-module-scope",
88 cl::desc("When printing IR for print-[before|after]{-all} "
89 "always print a module IR"),
90 cl::init(false), cl::Hidden);
92 static cl::list<std::string>
93 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
94 cl::desc("Only print IR for functions whose name "
95 "match this for all print-[before|after][-all] "
96 "options"),
97 cl::CommaSeparated, cl::Hidden);
99 /// This is a helper to determine whether to print IR before or
100 /// after a pass.
102 bool llvm::shouldPrintBeforePass() {
103 return PrintBeforeAll || !PrintBefore.empty();
106 bool llvm::shouldPrintAfterPass() {
107 return PrintAfterAll || !PrintAfter.empty();
110 static bool ShouldPrintBeforeOrAfterPass(StringRef PassID,
111 PassOptionList &PassesToPrint) {
112 for (auto *PassInf : PassesToPrint) {
113 if (PassInf)
114 if (PassInf->getPassArgument() == PassID) {
115 return true;
118 return false;
121 bool llvm::shouldPrintBeforePass(StringRef PassID) {
122 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
125 bool llvm::shouldPrintAfterPass(StringRef PassID) {
126 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
129 bool llvm::forcePrintModuleIR() { return PrintModuleScope; }
131 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
132 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
133 PrintFuncsList.end());
134 return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
136 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
137 /// or higher is specified.
138 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
139 return PassDebugging >= Executions;
142 unsigned PMDataManager::initSizeRemarkInfo(
143 Module &M, StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount) {
144 // Only calculate getInstructionCount if the size-info remark is requested.
145 unsigned InstrCount = 0;
147 // Collect instruction counts for every function. We'll use this to emit
148 // per-function size remarks later.
149 for (Function &F : M) {
150 unsigned FCount = F.getInstructionCount();
152 // Insert a record into FunctionToInstrCount keeping track of the current
153 // size of the function as the first member of a pair. Set the second
154 // member to 0; if the function is deleted by the pass, then when we get
155 // here, we'll be able to let the user know that F no longer contributes to
156 // the module.
157 FunctionToInstrCount[F.getName().str()] =
158 std::pair<unsigned, unsigned>(FCount, 0);
159 InstrCount += FCount;
161 return InstrCount;
164 void PMDataManager::emitInstrCountChangedRemark(
165 Pass *P, Module &M, int64_t Delta, unsigned CountBefore,
166 StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,
167 Function *F) {
168 // If it's a pass manager, don't emit a remark. (This hinges on the assumption
169 // that the only passes that return non-null with getAsPMDataManager are pass
170 // managers.) The reason we have to do this is to avoid emitting remarks for
171 // CGSCC passes.
172 if (P->getAsPMDataManager())
173 return;
175 // Set to true if this isn't a module pass or CGSCC pass.
176 bool CouldOnlyImpactOneFunction = (F != nullptr);
178 // Helper lambda that updates the changes to the size of some function.
179 auto UpdateFunctionChanges =
180 [&FunctionToInstrCount](Function &MaybeChangedFn) {
181 // Update the total module count.
182 unsigned FnSize = MaybeChangedFn.getInstructionCount();
183 auto It = FunctionToInstrCount.find(MaybeChangedFn.getName());
185 // If we created a new function, then we need to add it to the map and
186 // say that it changed from 0 instructions to FnSize.
187 if (It == FunctionToInstrCount.end()) {
188 FunctionToInstrCount[MaybeChangedFn.getName()] =
189 std::pair<unsigned, unsigned>(0, FnSize);
190 return;
192 // Insert the new function size into the second member of the pair. This
193 // tells us whether or not this function changed in size.
194 It->second.second = FnSize;
197 // We need to initially update all of the function sizes.
198 // If no function was passed in, then we're either a module pass or an
199 // CGSCC pass.
200 if (!CouldOnlyImpactOneFunction)
201 std::for_each(M.begin(), M.end(), UpdateFunctionChanges);
202 else
203 UpdateFunctionChanges(*F);
205 // Do we have a function we can use to emit a remark?
206 if (!CouldOnlyImpactOneFunction) {
207 // We need a function containing at least one basic block in order to output
208 // remarks. Since it's possible that the first function in the module
209 // doesn't actually contain a basic block, we have to go and find one that's
210 // suitable for emitting remarks.
211 auto It = std::find_if(M.begin(), M.end(),
212 [](const Function &Fn) { return !Fn.empty(); });
214 // Didn't find a function. Quit.
215 if (It == M.end())
216 return;
218 // We found a function containing at least one basic block.
219 F = &*It;
221 int64_t CountAfter = static_cast<int64_t>(CountBefore) + Delta;
222 BasicBlock &BB = *F->begin();
223 OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
224 DiagnosticLocation(), &BB);
225 // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
226 // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
227 R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())
228 << ": IR instruction count changed from "
229 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
230 << " to "
231 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
232 << "; Delta: "
233 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
234 F->getContext().diagnose(R); // Not using ORE for layering reasons.
236 // Emit per-function size change remarks separately.
237 std::string PassName = P->getPassName().str();
239 // Helper lambda that emits a remark when the size of a function has changed.
240 auto EmitFunctionSizeChangedRemark = [&FunctionToInstrCount, &F, &BB,
241 &PassName](const std::string &Fname) {
242 unsigned FnCountBefore, FnCountAfter;
243 std::pair<unsigned, unsigned> &Change = FunctionToInstrCount[Fname];
244 std::tie(FnCountBefore, FnCountAfter) = Change;
245 int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
246 static_cast<int64_t>(FnCountBefore);
248 if (FnDelta == 0)
249 return;
251 // FIXME: We shouldn't use BB for the location here. Unfortunately, because
252 // the function that we're looking at could have been deleted, we can't use
253 // it for the source location. We *want* remarks when a function is deleted
254 // though, so we're kind of stuck here as is. (This remark, along with the
255 // whole-module size change remarks really ought not to have source
256 // locations at all.)
257 OptimizationRemarkAnalysis FR("size-info", "FunctionIRSizeChange",
258 DiagnosticLocation(), &BB);
259 FR << DiagnosticInfoOptimizationBase::Argument("Pass", PassName)
260 << ": Function: "
261 << DiagnosticInfoOptimizationBase::Argument("Function", Fname)
262 << ": IR instruction count changed from "
263 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",
264 FnCountBefore)
265 << " to "
266 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",
267 FnCountAfter)
268 << "; Delta: "
269 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta);
270 F->getContext().diagnose(FR);
272 // Update the function size.
273 Change.first = FnCountAfter;
276 // Are we looking at more than one function? If so, emit remarks for all of
277 // the functions in the module. Otherwise, only emit one remark.
278 if (!CouldOnlyImpactOneFunction)
279 std::for_each(FunctionToInstrCount.keys().begin(),
280 FunctionToInstrCount.keys().end(),
281 EmitFunctionSizeChangedRemark);
282 else
283 EmitFunctionSizeChangedRemark(F->getName().str());
286 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
287 if (!V && !M)
288 OS << "Releasing pass '";
289 else
290 OS << "Running pass '";
292 OS << P->getPassName() << "'";
294 if (M) {
295 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
296 return;
298 if (!V) {
299 OS << '\n';
300 return;
303 OS << " on ";
304 if (isa<Function>(V))
305 OS << "function";
306 else if (isa<BasicBlock>(V))
307 OS << "basic block";
308 else
309 OS << "value";
311 OS << " '";
312 V->printAsOperand(OS, /*PrintTy=*/false, M);
313 OS << "'\n";
317 namespace {
318 //===----------------------------------------------------------------------===//
319 // BBPassManager
321 /// BBPassManager manages BasicBlockPass. It batches all the
322 /// pass together and sequence them to process one basic block before
323 /// processing next basic block.
324 class BBPassManager : public PMDataManager, public FunctionPass {
326 public:
327 static char ID;
328 explicit BBPassManager()
329 : PMDataManager(), FunctionPass(ID) {}
331 /// Execute all of the passes scheduled for execution. Keep track of
332 /// whether any of the passes modifies the function, and if so, return true.
333 bool runOnFunction(Function &F) override;
335 /// Pass Manager itself does not invalidate any analysis info.
336 void getAnalysisUsage(AnalysisUsage &Info) const override {
337 Info.setPreservesAll();
340 bool doInitialization(Module &M) override;
341 bool doInitialization(Function &F);
342 bool doFinalization(Module &M) override;
343 bool doFinalization(Function &F);
345 PMDataManager *getAsPMDataManager() override { return this; }
346 Pass *getAsPass() override { return this; }
348 StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
350 // Print passes managed by this manager
351 void dumpPassStructure(unsigned Offset) override {
352 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
353 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
354 BasicBlockPass *BP = getContainedPass(Index);
355 BP->dumpPassStructure(Offset + 1);
356 dumpLastUses(BP, Offset+1);
360 BasicBlockPass *getContainedPass(unsigned N) {
361 assert(N < PassVector.size() && "Pass number out of range!");
362 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
363 return BP;
366 PassManagerType getPassManagerType() const override {
367 return PMT_BasicBlockPassManager;
371 char BBPassManager::ID = 0;
372 } // End anonymous namespace
374 namespace llvm {
375 namespace legacy {
376 //===----------------------------------------------------------------------===//
377 // FunctionPassManagerImpl
379 /// FunctionPassManagerImpl manages FPPassManagers
380 class FunctionPassManagerImpl : public Pass,
381 public PMDataManager,
382 public PMTopLevelManager {
383 virtual void anchor();
384 private:
385 bool wasRun;
386 public:
387 static char ID;
388 explicit FunctionPassManagerImpl() :
389 Pass(PT_PassManager, ID), PMDataManager(),
390 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
392 /// \copydoc FunctionPassManager::add()
393 void add(Pass *P) {
394 schedulePass(P);
397 /// createPrinterPass - Get a function printer pass.
398 Pass *createPrinterPass(raw_ostream &O,
399 const std::string &Banner) const override {
400 return createPrintFunctionPass(O, Banner);
403 // Prepare for running an on the fly pass, freeing memory if needed
404 // from a previous run.
405 void releaseMemoryOnTheFly();
407 /// run - Execute all of the passes scheduled for execution. Keep track of
408 /// whether any of the passes modifies the module, and if so, return true.
409 bool run(Function &F);
411 /// doInitialization - Run all of the initializers for the function passes.
413 bool doInitialization(Module &M) override;
415 /// doFinalization - Run all of the finalizers for the function passes.
417 bool doFinalization(Module &M) override;
420 PMDataManager *getAsPMDataManager() override { return this; }
421 Pass *getAsPass() override { return this; }
422 PassManagerType getTopLevelPassManagerType() override {
423 return PMT_FunctionPassManager;
426 /// Pass Manager itself does not invalidate any analysis info.
427 void getAnalysisUsage(AnalysisUsage &Info) const override {
428 Info.setPreservesAll();
431 FPPassManager *getContainedManager(unsigned N) {
432 assert(N < PassManagers.size() && "Pass number out of range!");
433 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
434 return FP;
438 void FunctionPassManagerImpl::anchor() {}
440 char FunctionPassManagerImpl::ID = 0;
441 } // End of legacy namespace
442 } // End of llvm namespace
444 namespace {
445 //===----------------------------------------------------------------------===//
446 // MPPassManager
448 /// MPPassManager manages ModulePasses and function pass managers.
449 /// It batches all Module passes and function pass managers together and
450 /// sequences them to process one module.
451 class MPPassManager : public Pass, public PMDataManager {
452 public:
453 static char ID;
454 explicit MPPassManager() :
455 Pass(PT_PassManager, ID), PMDataManager() { }
457 // Delete on the fly managers.
458 ~MPPassManager() override {
459 for (auto &OnTheFlyManager : OnTheFlyManagers) {
460 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
461 delete FPP;
465 /// createPrinterPass - Get a module printer pass.
466 Pass *createPrinterPass(raw_ostream &O,
467 const std::string &Banner) const override {
468 return createPrintModulePass(O, Banner);
471 /// run - Execute all of the passes scheduled for execution. Keep track of
472 /// whether any of the passes modifies the module, and if so, return true.
473 bool runOnModule(Module &M);
475 using llvm::Pass::doInitialization;
476 using llvm::Pass::doFinalization;
478 /// Pass Manager itself does not invalidate any analysis info.
479 void getAnalysisUsage(AnalysisUsage &Info) const override {
480 Info.setPreservesAll();
483 /// Add RequiredPass into list of lower level passes required by pass P.
484 /// RequiredPass is run on the fly by Pass Manager when P requests it
485 /// through getAnalysis interface.
486 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
488 /// Return function pass corresponding to PassInfo PI, that is
489 /// required by module pass MP. Instantiate analysis pass, by using
490 /// its runOnFunction() for function F.
491 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
493 StringRef getPassName() const override { return "Module Pass Manager"; }
495 PMDataManager *getAsPMDataManager() override { return this; }
496 Pass *getAsPass() override { return this; }
498 // Print passes managed by this manager
499 void dumpPassStructure(unsigned Offset) override {
500 dbgs().indent(Offset*2) << "ModulePass Manager\n";
501 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
502 ModulePass *MP = getContainedPass(Index);
503 MP->dumpPassStructure(Offset + 1);
504 MapVector<Pass *, FunctionPassManagerImpl *>::const_iterator I =
505 OnTheFlyManagers.find(MP);
506 if (I != OnTheFlyManagers.end())
507 I->second->dumpPassStructure(Offset + 2);
508 dumpLastUses(MP, Offset+1);
512 ModulePass *getContainedPass(unsigned N) {
513 assert(N < PassVector.size() && "Pass number out of range!");
514 return static_cast<ModulePass *>(PassVector[N]);
517 PassManagerType getPassManagerType() const override {
518 return PMT_ModulePassManager;
521 private:
522 /// Collection of on the fly FPPassManagers. These managers manage
523 /// function passes that are required by module passes.
524 MapVector<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
527 char MPPassManager::ID = 0;
528 } // End anonymous namespace
530 namespace llvm {
531 namespace legacy {
532 //===----------------------------------------------------------------------===//
533 // PassManagerImpl
536 /// PassManagerImpl manages MPPassManagers
537 class PassManagerImpl : public Pass,
538 public PMDataManager,
539 public PMTopLevelManager {
540 virtual void anchor();
542 public:
543 static char ID;
544 explicit PassManagerImpl() :
545 Pass(PT_PassManager, ID), PMDataManager(),
546 PMTopLevelManager(new MPPassManager()) {}
548 /// \copydoc PassManager::add()
549 void add(Pass *P) {
550 schedulePass(P);
553 /// createPrinterPass - Get a module printer pass.
554 Pass *createPrinterPass(raw_ostream &O,
555 const std::string &Banner) const override {
556 return createPrintModulePass(O, Banner);
559 /// run - Execute all of the passes scheduled for execution. Keep track of
560 /// whether any of the passes modifies the module, and if so, return true.
561 bool run(Module &M);
563 using llvm::Pass::doInitialization;
564 using llvm::Pass::doFinalization;
566 /// Pass Manager itself does not invalidate any analysis info.
567 void getAnalysisUsage(AnalysisUsage &Info) const override {
568 Info.setPreservesAll();
571 PMDataManager *getAsPMDataManager() override { return this; }
572 Pass *getAsPass() override { return this; }
573 PassManagerType getTopLevelPassManagerType() override {
574 return PMT_ModulePassManager;
577 MPPassManager *getContainedManager(unsigned N) {
578 assert(N < PassManagers.size() && "Pass number out of range!");
579 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
580 return MP;
584 void PassManagerImpl::anchor() {}
586 char PassManagerImpl::ID = 0;
587 } // End of legacy namespace
588 } // End of llvm namespace
590 //===----------------------------------------------------------------------===//
591 // PMTopLevelManager implementation
593 /// Initialize top level manager. Create first pass manager.
594 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
595 PMDM->setTopLevelManager(this);
596 addPassManager(PMDM);
597 activeStack.push(PMDM);
600 /// Set pass P as the last user of the given analysis passes.
601 void
602 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
603 unsigned PDepth = 0;
604 if (P->getResolver())
605 PDepth = P->getResolver()->getPMDataManager().getDepth();
607 for (Pass *AP : AnalysisPasses) {
608 LastUser[AP] = P;
610 if (P == AP)
611 continue;
613 // Update the last users of passes that are required transitive by AP.
614 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
615 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
616 SmallVector<Pass *, 12> LastUses;
617 SmallVector<Pass *, 12> LastPMUses;
618 for (AnalysisID ID : IDs) {
619 Pass *AnalysisPass = findAnalysisPass(ID);
620 assert(AnalysisPass && "Expected analysis pass to exist.");
621 AnalysisResolver *AR = AnalysisPass->getResolver();
622 assert(AR && "Expected analysis resolver to exist.");
623 unsigned APDepth = AR->getPMDataManager().getDepth();
625 if (PDepth == APDepth)
626 LastUses.push_back(AnalysisPass);
627 else if (PDepth > APDepth)
628 LastPMUses.push_back(AnalysisPass);
631 setLastUser(LastUses, P);
633 // If this pass has a corresponding pass manager, push higher level
634 // analysis to this pass manager.
635 if (P->getResolver())
636 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
639 // If AP is the last user of other passes then make P last user of
640 // such passes.
641 for (auto LU : LastUser) {
642 if (LU.second == AP)
643 // DenseMap iterator is not invalidated here because
644 // this is just updating existing entries.
645 LastUser[LU.first] = P;
650 /// Collect passes whose last user is P
651 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
652 Pass *P) {
653 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
654 InversedLastUser.find(P);
655 if (DMI == InversedLastUser.end())
656 return;
658 SmallPtrSet<Pass *, 8> &LU = DMI->second;
659 for (Pass *LUP : LU) {
660 LastUses.push_back(LUP);
665 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
666 AnalysisUsage *AnUsage = nullptr;
667 auto DMI = AnUsageMap.find(P);
668 if (DMI != AnUsageMap.end())
669 AnUsage = DMI->second;
670 else {
671 // Look up the analysis usage from the pass instance (different instances
672 // of the same pass can produce different results), but unique the
673 // resulting object to reduce memory usage. This helps to greatly reduce
674 // memory usage when we have many instances of only a few pass types
675 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
676 // of dependencies.
677 AnalysisUsage AU;
678 P->getAnalysisUsage(AU);
680 AUFoldingSetNode* Node = nullptr;
681 FoldingSetNodeID ID;
682 AUFoldingSetNode::Profile(ID, AU);
683 void *IP = nullptr;
684 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
685 Node = N;
686 else {
687 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
688 UniqueAnalysisUsages.InsertNode(Node, IP);
690 assert(Node && "cached analysis usage must be non null");
692 AnUsageMap[P] = &Node->AU;
693 AnUsage = &Node->AU;
695 return AnUsage;
698 /// Schedule pass P for execution. Make sure that passes required by
699 /// P are run before P is run. Update analysis info maintained by
700 /// the manager. Remove dead passes. This is a recursive function.
701 void PMTopLevelManager::schedulePass(Pass *P) {
703 // TODO : Allocate function manager for this pass, other wise required set
704 // may be inserted into previous function manager
706 // Give pass a chance to prepare the stage.
707 P->preparePassManager(activeStack);
709 // If P is an analysis pass and it is available then do not
710 // generate the analysis again. Stale analysis info should not be
711 // available at this point.
712 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
713 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
714 // Remove any cached AnalysisUsage information.
715 AnUsageMap.erase(P);
716 delete P;
717 return;
720 AnalysisUsage *AnUsage = findAnalysisUsage(P);
722 bool checkAnalysis = true;
723 while (checkAnalysis) {
724 checkAnalysis = false;
726 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
727 for (const AnalysisID ID : RequiredSet) {
729 Pass *AnalysisPass = findAnalysisPass(ID);
730 if (!AnalysisPass) {
731 const PassInfo *PI = findAnalysisPassInfo(ID);
733 if (!PI) {
734 // Pass P is not in the global PassRegistry
735 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
736 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
737 dbgs() << "Required Passes:" << "\n";
738 for (const AnalysisID ID2 : RequiredSet) {
739 if (ID == ID2)
740 break;
741 Pass *AnalysisPass2 = findAnalysisPass(ID2);
742 if (AnalysisPass2) {
743 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
744 } else {
745 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
746 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
747 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
752 assert(PI && "Expected required passes to be initialized");
753 AnalysisPass = PI->createPass();
754 if (P->getPotentialPassManagerType () ==
755 AnalysisPass->getPotentialPassManagerType())
756 // Schedule analysis pass that is managed by the same pass manager.
757 schedulePass(AnalysisPass);
758 else if (P->getPotentialPassManagerType () >
759 AnalysisPass->getPotentialPassManagerType()) {
760 // Schedule analysis pass that is managed by a new manager.
761 schedulePass(AnalysisPass);
762 // Recheck analysis passes to ensure that required analyses that
763 // are already checked are still available.
764 checkAnalysis = true;
765 } else
766 // Do not schedule this analysis. Lower level analysis
767 // passes are run on the fly.
768 delete AnalysisPass;
773 // Now all required passes are available.
774 if (ImmutablePass *IP = P->getAsImmutablePass()) {
775 // P is a immutable pass and it will be managed by this
776 // top level manager. Set up analysis resolver to connect them.
777 PMDataManager *DM = getAsPMDataManager();
778 AnalysisResolver *AR = new AnalysisResolver(*DM);
779 P->setResolver(AR);
780 DM->initializeAnalysisImpl(P);
781 addImmutablePass(IP);
782 DM->recordAvailableAnalysis(IP);
783 return;
786 if (PI && !PI->isAnalysis() && shouldPrintBeforePass(PI->getPassArgument())) {
787 Pass *PP = P->createPrinterPass(
788 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
789 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
792 // Add the requested pass to the best available pass manager.
793 P->assignPassManager(activeStack, getTopLevelPassManagerType());
795 if (PI && !PI->isAnalysis() && shouldPrintAfterPass(PI->getPassArgument())) {
796 Pass *PP = P->createPrinterPass(
797 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
798 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
802 /// Find the pass that implements Analysis AID. Search immutable
803 /// passes and all pass managers. If desired pass is not found
804 /// then return NULL.
805 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
806 // For immutable passes we have a direct mapping from ID to pass, so check
807 // that first.
808 if (Pass *P = ImmutablePassMap.lookup(AID))
809 return P;
811 // Check pass managers
812 for (PMDataManager *PassManager : PassManagers)
813 if (Pass *P = PassManager->findAnalysisPass(AID, false))
814 return P;
816 // Check other pass managers
817 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
818 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
819 return P;
821 return nullptr;
824 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
825 const PassInfo *&PI = AnalysisPassInfos[AID];
826 if (!PI)
827 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
828 else
829 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
830 "The pass info pointer changed for an analysis ID!");
832 return PI;
835 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
836 P->initializePass();
837 ImmutablePasses.push_back(P);
839 // Add this pass to the map from its analysis ID. We clobber any prior runs
840 // of the pass in the map so that the last one added is the one found when
841 // doing lookups.
842 AnalysisID AID = P->getPassID();
843 ImmutablePassMap[AID] = P;
845 // Also add any interfaces implemented by the immutable pass to the map for
846 // fast lookup.
847 const PassInfo *PassInf = findAnalysisPassInfo(AID);
848 assert(PassInf && "Expected all immutable passes to be initialized");
849 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
850 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
853 // Print passes managed by this top level manager.
854 void PMTopLevelManager::dumpPasses() const {
856 if (PassDebugging < Structure)
857 return;
859 // Print out the immutable passes
860 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
861 ImmutablePasses[i]->dumpPassStructure(0);
864 // Every class that derives from PMDataManager also derives from Pass
865 // (sometimes indirectly), but there's no inheritance relationship
866 // between PMDataManager and Pass, so we have to getAsPass to get
867 // from a PMDataManager* to a Pass*.
868 for (PMDataManager *Manager : PassManagers)
869 Manager->getAsPass()->dumpPassStructure(1);
872 void PMTopLevelManager::dumpArguments() const {
874 if (PassDebugging < Arguments)
875 return;
877 dbgs() << "Pass Arguments: ";
878 for (ImmutablePass *P : ImmutablePasses)
879 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
880 assert(PI && "Expected all immutable passes to be initialized");
881 if (!PI->isAnalysisGroup())
882 dbgs() << " -" << PI->getPassArgument();
884 for (PMDataManager *PM : PassManagers)
885 PM->dumpPassArguments();
886 dbgs() << "\n";
889 void PMTopLevelManager::initializeAllAnalysisInfo() {
890 for (PMDataManager *PM : PassManagers)
891 PM->initializeAnalysisInfo();
893 // Initailize other pass managers
894 for (PMDataManager *IPM : IndirectPassManagers)
895 IPM->initializeAnalysisInfo();
897 for (auto LU : LastUser) {
898 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
899 L.insert(LU.first);
903 /// Destructor
904 PMTopLevelManager::~PMTopLevelManager() {
905 for (PMDataManager *PM : PassManagers)
906 delete PM;
908 for (ImmutablePass *P : ImmutablePasses)
909 delete P;
912 //===----------------------------------------------------------------------===//
913 // PMDataManager implementation
915 /// Augement AvailableAnalysis by adding analysis made available by pass P.
916 void PMDataManager::recordAvailableAnalysis(Pass *P) {
917 AnalysisID PI = P->getPassID();
919 AvailableAnalysis[PI] = P;
921 assert(!AvailableAnalysis.empty());
923 // This pass is the current implementation of all of the interfaces it
924 // implements as well.
925 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
926 if (!PInf) return;
927 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
928 for (unsigned i = 0, e = II.size(); i != e; ++i)
929 AvailableAnalysis[II[i]->getTypeInfo()] = P;
932 // Return true if P preserves high level analysis used by other
933 // passes managed by this manager
934 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
935 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
936 if (AnUsage->getPreservesAll())
937 return true;
939 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
940 for (Pass *P1 : HigherLevelAnalysis) {
941 if (P1->getAsImmutablePass() == nullptr &&
942 !is_contained(PreservedSet, P1->getPassID()))
943 return false;
946 return true;
949 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
950 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
951 // Don't do this unless assertions are enabled.
952 #ifdef NDEBUG
953 return;
954 #endif
955 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
956 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
958 // Verify preserved analysis
959 for (AnalysisID AID : PreservedSet) {
960 if (Pass *AP = findAnalysisPass(AID, true)) {
961 TimeRegion PassTimer(getPassTimer(AP));
962 AP->verifyAnalysis();
967 /// Remove Analysis not preserved by Pass P
968 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
969 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
970 if (AnUsage->getPreservesAll())
971 return;
973 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
974 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
975 E = AvailableAnalysis.end(); I != E; ) {
976 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
977 if (Info->second->getAsImmutablePass() == nullptr &&
978 !is_contained(PreservedSet, Info->first)) {
979 // Remove this analysis
980 if (PassDebugging >= Details) {
981 Pass *S = Info->second;
982 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
983 dbgs() << S->getPassName() << "'\n";
985 AvailableAnalysis.erase(Info);
989 // Check inherited analysis also. If P is not preserving analysis
990 // provided by parent manager then remove it here.
991 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
993 if (!InheritedAnalysis[Index])
994 continue;
996 for (DenseMap<AnalysisID, Pass*>::iterator
997 I = InheritedAnalysis[Index]->begin(),
998 E = InheritedAnalysis[Index]->end(); I != E; ) {
999 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
1000 if (Info->second->getAsImmutablePass() == nullptr &&
1001 !is_contained(PreservedSet, Info->first)) {
1002 // Remove this analysis
1003 if (PassDebugging >= Details) {
1004 Pass *S = Info->second;
1005 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
1006 dbgs() << S->getPassName() << "'\n";
1008 InheritedAnalysis[Index]->erase(Info);
1014 /// Remove analysis passes that are not used any longer
1015 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
1016 enum PassDebuggingString DBG_STR) {
1018 SmallVector<Pass *, 12> DeadPasses;
1020 // If this is a on the fly manager then it does not have TPM.
1021 if (!TPM)
1022 return;
1024 TPM->collectLastUses(DeadPasses, P);
1026 if (PassDebugging >= Details && !DeadPasses.empty()) {
1027 dbgs() << " -*- '" << P->getPassName();
1028 dbgs() << "' is the last user of following pass instances.";
1029 dbgs() << " Free these instances\n";
1032 for (Pass *P : DeadPasses)
1033 freePass(P, Msg, DBG_STR);
1036 void PMDataManager::freePass(Pass *P, StringRef Msg,
1037 enum PassDebuggingString DBG_STR) {
1038 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
1041 // If the pass crashes releasing memory, remember this.
1042 PassManagerPrettyStackEntry X(P);
1043 TimeRegion PassTimer(getPassTimer(P));
1045 P->releaseMemory();
1048 AnalysisID PI = P->getPassID();
1049 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
1050 // Remove the pass itself (if it is not already removed).
1051 AvailableAnalysis.erase(PI);
1053 // Remove all interfaces this pass implements, for which it is also
1054 // listed as the available implementation.
1055 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
1056 for (unsigned i = 0, e = II.size(); i != e; ++i) {
1057 DenseMap<AnalysisID, Pass*>::iterator Pos =
1058 AvailableAnalysis.find(II[i]->getTypeInfo());
1059 if (Pos != AvailableAnalysis.end() && Pos->second == P)
1060 AvailableAnalysis.erase(Pos);
1065 /// Add pass P into the PassVector. Update
1066 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1067 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
1068 // This manager is going to manage pass P. Set up analysis resolver
1069 // to connect them.
1070 AnalysisResolver *AR = new AnalysisResolver(*this);
1071 P->setResolver(AR);
1073 // If a FunctionPass F is the last user of ModulePass info M
1074 // then the F's manager, not F, records itself as a last user of M.
1075 SmallVector<Pass *, 12> TransferLastUses;
1077 if (!ProcessAnalysis) {
1078 // Add pass
1079 PassVector.push_back(P);
1080 return;
1083 // At the moment, this pass is the last user of all required passes.
1084 SmallVector<Pass *, 12> LastUses;
1085 SmallVector<Pass *, 8> UsedPasses;
1086 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1088 unsigned PDepth = this->getDepth();
1090 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1091 for (Pass *PUsed : UsedPasses) {
1092 unsigned RDepth = 0;
1094 assert(PUsed->getResolver() && "Analysis Resolver is not set");
1095 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1096 RDepth = DM.getDepth();
1098 if (PDepth == RDepth)
1099 LastUses.push_back(PUsed);
1100 else if (PDepth > RDepth) {
1101 // Let the parent claim responsibility of last use
1102 TransferLastUses.push_back(PUsed);
1103 // Keep track of higher level analysis used by this manager.
1104 HigherLevelAnalysis.push_back(PUsed);
1105 } else
1106 llvm_unreachable("Unable to accommodate Used Pass");
1109 // Set P as P's last user until someone starts using P.
1110 // However, if P is a Pass Manager then it does not need
1111 // to record its last user.
1112 if (!P->getAsPMDataManager())
1113 LastUses.push_back(P);
1114 TPM->setLastUser(LastUses, P);
1116 if (!TransferLastUses.empty()) {
1117 Pass *My_PM = getAsPass();
1118 TPM->setLastUser(TransferLastUses, My_PM);
1119 TransferLastUses.clear();
1122 // Now, take care of required analyses that are not available.
1123 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1124 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1125 Pass *AnalysisPass = PI->createPass();
1126 this->addLowerLevelRequiredPass(P, AnalysisPass);
1129 // Take a note of analysis required and made available by this pass.
1130 // Remove the analysis not preserved by this pass
1131 removeNotPreservedAnalysis(P);
1132 recordAvailableAnalysis(P);
1134 // Add pass
1135 PassVector.push_back(P);
1139 /// Populate UP with analysis pass that are used or required by
1140 /// pass P and are available. Populate RP_NotAvail with analysis
1141 /// pass that are required by pass P but are not available.
1142 void PMDataManager::collectRequiredAndUsedAnalyses(
1143 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1144 Pass *P) {
1145 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1147 for (const auto &UsedID : AnUsage->getUsedSet())
1148 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1149 UP.push_back(AnalysisPass);
1151 for (const auto &RequiredID : AnUsage->getRequiredSet())
1152 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1153 UP.push_back(AnalysisPass);
1154 else
1155 RP_NotAvail.push_back(RequiredID);
1157 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1158 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1159 UP.push_back(AnalysisPass);
1160 else
1161 RP_NotAvail.push_back(RequiredID);
1164 // All Required analyses should be available to the pass as it runs! Here
1165 // we fill in the AnalysisImpls member of the pass so that it can
1166 // successfully use the getAnalysis() method to retrieve the
1167 // implementations it needs.
1169 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1170 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1172 for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1173 Pass *Impl = findAnalysisPass(ID, true);
1174 if (!Impl)
1175 // This may be analysis pass that is initialized on the fly.
1176 // If that is not the case then it will raise an assert when it is used.
1177 continue;
1178 AnalysisResolver *AR = P->getResolver();
1179 assert(AR && "Analysis Resolver is not set");
1180 AR->addAnalysisImplsPair(ID, Impl);
1184 /// Find the pass that implements Analysis AID. If desired pass is not found
1185 /// then return NULL.
1186 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1188 // Check if AvailableAnalysis map has one entry.
1189 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1191 if (I != AvailableAnalysis.end())
1192 return I->second;
1194 // Search Parents through TopLevelManager
1195 if (SearchParent)
1196 return TPM->findAnalysisPass(AID);
1198 return nullptr;
1201 // Print list of passes that are last used by P.
1202 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1204 SmallVector<Pass *, 12> LUses;
1206 // If this is a on the fly manager then it does not have TPM.
1207 if (!TPM)
1208 return;
1210 TPM->collectLastUses(LUses, P);
1212 for (Pass *P : LUses) {
1213 dbgs() << "--" << std::string(Offset*2, ' ');
1214 P->dumpPassStructure(0);
1218 void PMDataManager::dumpPassArguments() const {
1219 for (Pass *P : PassVector) {
1220 if (PMDataManager *PMD = P->getAsPMDataManager())
1221 PMD->dumpPassArguments();
1222 else
1223 if (const PassInfo *PI =
1224 TPM->findAnalysisPassInfo(P->getPassID()))
1225 if (!PI->isAnalysisGroup())
1226 dbgs() << " -" << PI->getPassArgument();
1230 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1231 enum PassDebuggingString S2,
1232 StringRef Msg) {
1233 if (PassDebugging < Executions)
1234 return;
1235 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1236 << std::string(getDepth() * 2 + 1, ' ');
1237 switch (S1) {
1238 case EXECUTION_MSG:
1239 dbgs() << "Executing Pass '" << P->getPassName();
1240 break;
1241 case MODIFICATION_MSG:
1242 dbgs() << "Made Modification '" << P->getPassName();
1243 break;
1244 case FREEING_MSG:
1245 dbgs() << " Freeing Pass '" << P->getPassName();
1246 break;
1247 default:
1248 break;
1250 switch (S2) {
1251 case ON_BASICBLOCK_MSG:
1252 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1253 break;
1254 case ON_FUNCTION_MSG:
1255 dbgs() << "' on Function '" << Msg << "'...\n";
1256 break;
1257 case ON_MODULE_MSG:
1258 dbgs() << "' on Module '" << Msg << "'...\n";
1259 break;
1260 case ON_REGION_MSG:
1261 dbgs() << "' on Region '" << Msg << "'...\n";
1262 break;
1263 case ON_LOOP_MSG:
1264 dbgs() << "' on Loop '" << Msg << "'...\n";
1265 break;
1266 case ON_CG_MSG:
1267 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1268 break;
1269 default:
1270 break;
1274 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1275 if (PassDebugging < Details)
1276 return;
1278 AnalysisUsage analysisUsage;
1279 P->getAnalysisUsage(analysisUsage);
1280 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1283 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1284 if (PassDebugging < Details)
1285 return;
1287 AnalysisUsage analysisUsage;
1288 P->getAnalysisUsage(analysisUsage);
1289 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1292 void PMDataManager::dumpUsedSet(const Pass *P) const {
1293 if (PassDebugging < Details)
1294 return;
1296 AnalysisUsage analysisUsage;
1297 P->getAnalysisUsage(analysisUsage);
1298 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1301 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1302 const AnalysisUsage::VectorType &Set) const {
1303 assert(PassDebugging >= Details);
1304 if (Set.empty())
1305 return;
1306 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1307 for (unsigned i = 0; i != Set.size(); ++i) {
1308 if (i) dbgs() << ',';
1309 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1310 if (!PInf) {
1311 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1312 // all drivers.
1313 dbgs() << " Uninitialized Pass";
1314 continue;
1316 dbgs() << ' ' << PInf->getPassName();
1318 dbgs() << '\n';
1321 /// Add RequiredPass into list of lower level passes required by pass P.
1322 /// RequiredPass is run on the fly by Pass Manager when P requests it
1323 /// through getAnalysis interface.
1324 /// This should be handled by specific pass manager.
1325 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1326 if (TPM) {
1327 TPM->dumpArguments();
1328 TPM->dumpPasses();
1331 // Module Level pass may required Function Level analysis info
1332 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1333 // to provide this on demand. In that case, in Pass manager terminology,
1334 // module level pass is requiring lower level analysis info managed by
1335 // lower level pass manager.
1337 // When Pass manager is not able to order required analysis info, Pass manager
1338 // checks whether any lower level manager will be able to provide this
1339 // analysis info on demand or not.
1340 #ifndef NDEBUG
1341 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1342 dbgs() << "' required by '" << P->getPassName() << "'\n";
1343 #endif
1344 llvm_unreachable("Unable to schedule pass");
1347 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1348 llvm_unreachable("Unable to find on the fly pass");
1351 // Destructor
1352 PMDataManager::~PMDataManager() {
1353 for (Pass *P : PassVector)
1354 delete P;
1357 //===----------------------------------------------------------------------===//
1358 // NOTE: Is this the right place to define this method ?
1359 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1360 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1361 return PM.findAnalysisPass(ID, dir);
1364 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1365 Function &F) {
1366 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1369 //===----------------------------------------------------------------------===//
1370 // BBPassManager implementation
1372 /// Execute all of the passes scheduled for execution by invoking
1373 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1374 /// the function, and if so, return true.
1375 bool BBPassManager::runOnFunction(Function &F) {
1376 if (F.isDeclaration())
1377 return false;
1379 bool Changed = doInitialization(F);
1380 Module &M = *F.getParent();
1382 unsigned InstrCount, BBSize = 0;
1383 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1384 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1385 if (EmitICRemark)
1386 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1388 for (BasicBlock &BB : F) {
1389 // Collect the initial size of the basic block.
1390 if (EmitICRemark)
1391 BBSize = BB.size();
1392 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1393 BasicBlockPass *BP = getContainedPass(Index);
1394 bool LocalChanged = false;
1396 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, BB.getName());
1397 dumpRequiredSet(BP);
1399 initializeAnalysisImpl(BP);
1402 // If the pass crashes, remember this.
1403 PassManagerPrettyStackEntry X(BP, BB);
1404 TimeRegion PassTimer(getPassTimer(BP));
1405 LocalChanged |= BP->runOnBasicBlock(BB);
1406 if (EmitICRemark) {
1407 unsigned NewSize = BB.size();
1408 // Update the size of the basic block, emit a remark, and update the
1409 // size of the module.
1410 if (NewSize != BBSize) {
1411 int64_t Delta =
1412 static_cast<int64_t>(NewSize) - static_cast<int64_t>(BBSize);
1413 emitInstrCountChangedRemark(BP, M, Delta, InstrCount,
1414 FunctionToInstrCount, &F);
1415 InstrCount = static_cast<int64_t>(InstrCount) + Delta;
1416 BBSize = NewSize;
1421 Changed |= LocalChanged;
1422 if (LocalChanged)
1423 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1424 BB.getName());
1425 dumpPreservedSet(BP);
1426 dumpUsedSet(BP);
1428 verifyPreservedAnalysis(BP);
1429 removeNotPreservedAnalysis(BP);
1430 recordAvailableAnalysis(BP);
1431 removeDeadPasses(BP, BB.getName(), ON_BASICBLOCK_MSG);
1435 return doFinalization(F) || Changed;
1438 // Implement doInitialization and doFinalization
1439 bool BBPassManager::doInitialization(Module &M) {
1440 bool Changed = false;
1442 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1443 Changed |= getContainedPass(Index)->doInitialization(M);
1445 return Changed;
1448 bool BBPassManager::doFinalization(Module &M) {
1449 bool Changed = false;
1451 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1452 Changed |= getContainedPass(Index)->doFinalization(M);
1454 return Changed;
1457 bool BBPassManager::doInitialization(Function &F) {
1458 bool Changed = false;
1460 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1461 BasicBlockPass *BP = getContainedPass(Index);
1462 Changed |= BP->doInitialization(F);
1465 return Changed;
1468 bool BBPassManager::doFinalization(Function &F) {
1469 bool Changed = false;
1471 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1472 BasicBlockPass *BP = getContainedPass(Index);
1473 Changed |= BP->doFinalization(F);
1476 return Changed;
1480 //===----------------------------------------------------------------------===//
1481 // FunctionPassManager implementation
1483 /// Create new Function pass manager
1484 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1485 FPM = new FunctionPassManagerImpl();
1486 // FPM is the top level manager.
1487 FPM->setTopLevelManager(FPM);
1489 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1490 FPM->setResolver(AR);
1493 FunctionPassManager::~FunctionPassManager() {
1494 delete FPM;
1497 void FunctionPassManager::add(Pass *P) {
1498 FPM->add(P);
1501 /// run - Execute all of the passes scheduled for execution. Keep
1502 /// track of whether any of the passes modifies the function, and if
1503 /// so, return true.
1505 bool FunctionPassManager::run(Function &F) {
1506 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1507 report_fatal_error("Error reading bitcode file: " + EIB.message());
1509 return FPM->run(F);
1513 /// doInitialization - Run all of the initializers for the function passes.
1515 bool FunctionPassManager::doInitialization() {
1516 return FPM->doInitialization(*M);
1519 /// doFinalization - Run all of the finalizers for the function passes.
1521 bool FunctionPassManager::doFinalization() {
1522 return FPM->doFinalization(*M);
1525 //===----------------------------------------------------------------------===//
1526 // FunctionPassManagerImpl implementation
1528 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1529 bool Changed = false;
1531 dumpArguments();
1532 dumpPasses();
1534 for (ImmutablePass *ImPass : getImmutablePasses())
1535 Changed |= ImPass->doInitialization(M);
1537 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1538 Changed |= getContainedManager(Index)->doInitialization(M);
1540 return Changed;
1543 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1544 bool Changed = false;
1546 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1547 Changed |= getContainedManager(Index)->doFinalization(M);
1549 for (ImmutablePass *ImPass : getImmutablePasses())
1550 Changed |= ImPass->doFinalization(M);
1552 return Changed;
1555 /// cleanup - After running all passes, clean up pass manager cache.
1556 void FPPassManager::cleanup() {
1557 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1558 FunctionPass *FP = getContainedPass(Index);
1559 AnalysisResolver *AR = FP->getResolver();
1560 assert(AR && "Analysis Resolver is not set");
1561 AR->clearAnalysisImpls();
1565 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1566 if (!wasRun)
1567 return;
1568 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1569 FPPassManager *FPPM = getContainedManager(Index);
1570 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1571 FPPM->getContainedPass(Index)->releaseMemory();
1574 wasRun = false;
1577 // Execute all the passes managed by this top level manager.
1578 // Return true if any function is modified by a pass.
1579 bool FunctionPassManagerImpl::run(Function &F) {
1580 bool Changed = false;
1582 initializeAllAnalysisInfo();
1583 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1584 Changed |= getContainedManager(Index)->runOnFunction(F);
1585 F.getContext().yield();
1588 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1589 getContainedManager(Index)->cleanup();
1591 wasRun = true;
1592 return Changed;
1595 //===----------------------------------------------------------------------===//
1596 // FPPassManager implementation
1598 char FPPassManager::ID = 0;
1599 /// Print passes managed by this manager
1600 void FPPassManager::dumpPassStructure(unsigned Offset) {
1601 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1602 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1603 FunctionPass *FP = getContainedPass(Index);
1604 FP->dumpPassStructure(Offset + 1);
1605 dumpLastUses(FP, Offset+1);
1610 /// Execute all of the passes scheduled for execution by invoking
1611 /// runOnFunction method. Keep track of whether any of the passes modifies
1612 /// the function, and if so, return true.
1613 bool FPPassManager::runOnFunction(Function &F) {
1614 if (F.isDeclaration())
1615 return false;
1617 bool Changed = false;
1618 Module &M = *F.getParent();
1619 // Collect inherited analysis from Module level pass manager.
1620 populateInheritedAnalysis(TPM->activeStack);
1622 unsigned InstrCount, FunctionSize = 0;
1623 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1624 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1625 // Collect the initial size of the module.
1626 if (EmitICRemark) {
1627 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1628 FunctionSize = F.getInstructionCount();
1631 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1632 FunctionPass *FP = getContainedPass(Index);
1633 bool LocalChanged = false;
1635 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1636 dumpRequiredSet(FP);
1638 initializeAnalysisImpl(FP);
1641 PassManagerPrettyStackEntry X(FP, F);
1642 TimeRegion PassTimer(getPassTimer(FP));
1643 LocalChanged |= FP->runOnFunction(F);
1644 if (EmitICRemark) {
1645 unsigned NewSize = F.getInstructionCount();
1647 // Update the size of the function, emit a remark, and update the size
1648 // of the module.
1649 if (NewSize != FunctionSize) {
1650 int64_t Delta = static_cast<int64_t>(NewSize) -
1651 static_cast<int64_t>(FunctionSize);
1652 emitInstrCountChangedRemark(FP, M, Delta, InstrCount,
1653 FunctionToInstrCount, &F);
1654 InstrCount = static_cast<int64_t>(InstrCount) + Delta;
1655 FunctionSize = NewSize;
1660 Changed |= LocalChanged;
1661 if (LocalChanged)
1662 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1663 dumpPreservedSet(FP);
1664 dumpUsedSet(FP);
1666 verifyPreservedAnalysis(FP);
1667 removeNotPreservedAnalysis(FP);
1668 recordAvailableAnalysis(FP);
1669 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1671 return Changed;
1674 bool FPPassManager::runOnModule(Module &M) {
1675 bool Changed = false;
1677 for (Function &F : M)
1678 Changed |= runOnFunction(F);
1680 return Changed;
1683 bool FPPassManager::doInitialization(Module &M) {
1684 bool Changed = false;
1686 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1687 Changed |= getContainedPass(Index)->doInitialization(M);
1689 return Changed;
1692 bool FPPassManager::doFinalization(Module &M) {
1693 bool Changed = false;
1695 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1696 Changed |= getContainedPass(Index)->doFinalization(M);
1698 return Changed;
1701 //===----------------------------------------------------------------------===//
1702 // MPPassManager implementation
1704 /// Execute all of the passes scheduled for execution by invoking
1705 /// runOnModule method. Keep track of whether any of the passes modifies
1706 /// the module, and if so, return true.
1707 bool
1708 MPPassManager::runOnModule(Module &M) {
1709 bool Changed = false;
1711 // Initialize on-the-fly passes
1712 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1713 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1714 Changed |= FPP->doInitialization(M);
1717 // Initialize module passes
1718 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1719 Changed |= getContainedPass(Index)->doInitialization(M);
1721 unsigned InstrCount, ModuleCount = 0;
1722 StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;
1723 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1724 // Collect the initial size of the module.
1725 if (EmitICRemark) {
1726 InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);
1727 ModuleCount = InstrCount;
1730 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1731 ModulePass *MP = getContainedPass(Index);
1732 bool LocalChanged = false;
1734 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1735 dumpRequiredSet(MP);
1737 initializeAnalysisImpl(MP);
1740 PassManagerPrettyStackEntry X(MP, M);
1741 TimeRegion PassTimer(getPassTimer(MP));
1743 LocalChanged |= MP->runOnModule(M);
1744 if (EmitICRemark) {
1745 // Update the size of the module.
1746 ModuleCount = M.getInstructionCount();
1747 if (ModuleCount != InstrCount) {
1748 int64_t Delta = static_cast<int64_t>(ModuleCount) -
1749 static_cast<int64_t>(InstrCount);
1750 emitInstrCountChangedRemark(MP, M, Delta, InstrCount,
1751 FunctionToInstrCount);
1752 InstrCount = ModuleCount;
1757 Changed |= LocalChanged;
1758 if (LocalChanged)
1759 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1760 M.getModuleIdentifier());
1761 dumpPreservedSet(MP);
1762 dumpUsedSet(MP);
1764 verifyPreservedAnalysis(MP);
1765 removeNotPreservedAnalysis(MP);
1766 recordAvailableAnalysis(MP);
1767 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1770 // Finalize module passes
1771 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1772 Changed |= getContainedPass(Index)->doFinalization(M);
1774 // Finalize on-the-fly passes
1775 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1776 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1777 // We don't know when is the last time an on-the-fly pass is run,
1778 // so we need to releaseMemory / finalize here
1779 FPP->releaseMemoryOnTheFly();
1780 Changed |= FPP->doFinalization(M);
1783 return Changed;
1786 /// Add RequiredPass into list of lower level passes required by pass P.
1787 /// RequiredPass is run on the fly by Pass Manager when P requests it
1788 /// through getAnalysis interface.
1789 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1790 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1791 "Unable to handle Pass that requires lower level Analysis pass");
1792 assert((P->getPotentialPassManagerType() <
1793 RequiredPass->getPotentialPassManagerType()) &&
1794 "Unable to handle Pass that requires lower level Analysis pass");
1795 if (!RequiredPass)
1796 return;
1798 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1799 if (!FPP) {
1800 FPP = new FunctionPassManagerImpl();
1801 // FPP is the top level manager.
1802 FPP->setTopLevelManager(FPP);
1804 OnTheFlyManagers[P] = FPP;
1806 const PassInfo *RequiredPassPI =
1807 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1809 Pass *FoundPass = nullptr;
1810 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1811 FoundPass =
1812 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1814 if (!FoundPass) {
1815 FoundPass = RequiredPass;
1816 // This should be guaranteed to add RequiredPass to the passmanager given
1817 // that we checked for an available analysis above.
1818 FPP->add(RequiredPass);
1820 // Register P as the last user of FoundPass or RequiredPass.
1821 SmallVector<Pass *, 1> LU;
1822 LU.push_back(FoundPass);
1823 FPP->setLastUser(LU, P);
1826 /// Return function pass corresponding to PassInfo PI, that is
1827 /// required by module pass MP. Instantiate analysis pass, by using
1828 /// its runOnFunction() for function F.
1829 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1830 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1831 assert(FPP && "Unable to find on the fly pass");
1833 FPP->releaseMemoryOnTheFly();
1834 FPP->run(F);
1835 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1839 //===----------------------------------------------------------------------===//
1840 // PassManagerImpl implementation
1843 /// run - Execute all of the passes scheduled for execution. Keep track of
1844 /// whether any of the passes modifies the module, and if so, return true.
1845 bool PassManagerImpl::run(Module &M) {
1846 bool Changed = false;
1848 dumpArguments();
1849 dumpPasses();
1851 for (ImmutablePass *ImPass : getImmutablePasses())
1852 Changed |= ImPass->doInitialization(M);
1854 initializeAllAnalysisInfo();
1855 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1856 Changed |= getContainedManager(Index)->runOnModule(M);
1857 M.getContext().yield();
1860 for (ImmutablePass *ImPass : getImmutablePasses())
1861 Changed |= ImPass->doFinalization(M);
1863 return Changed;
1866 //===----------------------------------------------------------------------===//
1867 // PassManager implementation
1869 /// Create new pass manager
1870 PassManager::PassManager() {
1871 PM = new PassManagerImpl();
1872 // PM is the top level manager
1873 PM->setTopLevelManager(PM);
1876 PassManager::~PassManager() {
1877 delete PM;
1880 void PassManager::add(Pass *P) {
1881 PM->add(P);
1884 /// run - Execute all of the passes scheduled for execution. Keep track of
1885 /// whether any of the passes modifies the module, and if so, return true.
1886 bool PassManager::run(Module &M) {
1887 return PM->run(M);
1890 //===----------------------------------------------------------------------===//
1891 // PMStack implementation
1894 // Pop Pass Manager from the stack and clear its analysis info.
1895 void PMStack::pop() {
1897 PMDataManager *Top = this->top();
1898 Top->initializeAnalysisInfo();
1900 S.pop_back();
1903 // Push PM on the stack and set its top level manager.
1904 void PMStack::push(PMDataManager *PM) {
1905 assert(PM && "Unable to push. Pass Manager expected");
1906 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1908 if (!this->empty()) {
1909 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1910 && "pushing bad pass manager to PMStack");
1911 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1913 assert(TPM && "Unable to find top level manager");
1914 TPM->addIndirectPassManager(PM);
1915 PM->setTopLevelManager(TPM);
1916 PM->setDepth(this->top()->getDepth()+1);
1917 } else {
1918 assert((PM->getPassManagerType() == PMT_ModulePassManager
1919 || PM->getPassManagerType() == PMT_FunctionPassManager)
1920 && "pushing bad pass manager to PMStack");
1921 PM->setDepth(1);
1924 S.push_back(PM);
1927 // Dump content of the pass manager stack.
1928 LLVM_DUMP_METHOD void PMStack::dump() const {
1929 for (PMDataManager *Manager : S)
1930 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1932 if (!S.empty())
1933 dbgs() << '\n';
1936 /// Find appropriate Module Pass Manager in the PM Stack and
1937 /// add self into that manager.
1938 void ModulePass::assignPassManager(PMStack &PMS,
1939 PassManagerType PreferredType) {
1940 // Find Module Pass Manager
1941 while (!PMS.empty()) {
1942 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1943 if (TopPMType == PreferredType)
1944 break; // We found desired pass manager
1945 else if (TopPMType > PMT_ModulePassManager)
1946 PMS.pop(); // Pop children pass managers
1947 else
1948 break;
1950 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1951 PMS.top()->add(this);
1954 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1955 /// in the PM Stack and add self into that manager.
1956 void FunctionPass::assignPassManager(PMStack &PMS,
1957 PassManagerType PreferredType) {
1959 // Find Function Pass Manager
1960 while (!PMS.empty()) {
1961 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1962 PMS.pop();
1963 else
1964 break;
1967 // Create new Function Pass Manager if needed.
1968 FPPassManager *FPP;
1969 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1970 FPP = (FPPassManager *)PMS.top();
1971 } else {
1972 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1973 PMDataManager *PMD = PMS.top();
1975 // [1] Create new Function Pass Manager
1976 FPP = new FPPassManager();
1977 FPP->populateInheritedAnalysis(PMS);
1979 // [2] Set up new manager's top level manager
1980 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1981 TPM->addIndirectPassManager(FPP);
1983 // [3] Assign manager to manage this new manager. This may create
1984 // and push new managers into PMS
1985 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1987 // [4] Push new manager into PMS
1988 PMS.push(FPP);
1991 // Assign FPP as the manager of this pass.
1992 FPP->add(this);
1995 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1996 /// in the PM Stack and add self into that manager.
1997 void BasicBlockPass::assignPassManager(PMStack &PMS,
1998 PassManagerType PreferredType) {
1999 BBPassManager *BBP;
2001 // Basic Pass Manager is a leaf pass manager. It does not handle
2002 // any other pass manager.
2003 if (!PMS.empty() &&
2004 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
2005 BBP = (BBPassManager *)PMS.top();
2006 } else {
2007 // If leaf manager is not Basic Block Pass manager then create new
2008 // basic Block Pass manager.
2009 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
2010 PMDataManager *PMD = PMS.top();
2012 // [1] Create new Basic Block Manager
2013 BBP = new BBPassManager();
2015 // [2] Set up new manager's top level manager
2016 // Basic Block Pass Manager does not live by itself
2017 PMTopLevelManager *TPM = PMD->getTopLevelManager();
2018 TPM->addIndirectPassManager(BBP);
2020 // [3] Assign manager to manage this new manager. This may create
2021 // and push new managers into PMS
2022 BBP->assignPassManager(PMS, PreferredType);
2024 // [4] Push new manager into PMS
2025 PMS.push(BBP);
2028 // Assign BBP as the manager of this pass.
2029 BBP->add(this);
2032 PassManagerBase::~PassManagerBase() {}