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/Statistic.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Chrono.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/Mutex.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/Support/raw_ostream.h"
32 #include <unordered_set>
34 using namespace llvm::legacy;
36 // See PassManagers.h for Pass Manager infrastructure overview.
38 //===----------------------------------------------------------------------===//
39 // Pass debugging information. Often it is useful to find out what pass is
40 // running when a crash occurs in a utility. When this library is compiled with
41 // debugging on, a command line option (--debug-pass) is enabled that causes the
42 // pass name to be printed before it executes.
46 // Different debug levels that can be enabled...
48 Disabled, Arguments, Structure, Executions, Details
52 static cl::opt<enum PassDebugLevel>
53 PassDebugging("debug-pass", cl::Hidden,
54 cl::desc("Print PassManager debugging information"),
56 clEnumVal(Disabled , "disable debug output"),
57 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
58 clEnumVal(Structure , "print pass structure before run()"),
59 clEnumVal(Executions, "print pass name before it is executed"),
60 clEnumVal(Details , "print pass details when it is executed")));
63 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
67 // Print IR out before/after specified passes.
69 PrintBefore("print-before",
70 llvm::cl::desc("Print IR before specified passes"),
74 PrintAfter("print-after",
75 llvm::cl::desc("Print IR after specified passes"),
79 PrintBeforeAll("print-before-all",
80 llvm::cl::desc("Print IR before each pass"),
83 PrintAfterAll("print-after-all",
84 llvm::cl::desc("Print IR after each pass"),
87 static cl::list<std::string>
88 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
89 cl::desc("Only print IR for functions whose name "
90 "match this for all print-[before|after][-all] "
94 /// This is a helper to determine whether to print IR before or
97 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
98 PassOptionList &PassesToPrint) {
99 for (auto *PassInf : PassesToPrint) {
101 if (PassInf->getPassArgument() == PI->getPassArgument()) {
108 /// This is a utility to check whether a pass should have IR dumped
110 static bool ShouldPrintBeforePass(const PassInfo *PI) {
111 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
114 /// This is a utility to check whether a pass should have IR dumped
116 static bool ShouldPrintAfterPass(const PassInfo *PI) {
117 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
120 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
121 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
122 PrintFuncsList.end());
123 return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
125 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
126 /// or higher is specified.
127 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
128 return PassDebugging >= Executions;
134 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
136 OS << "Releasing pass '";
138 OS << "Running pass '";
140 OS << P->getPassName() << "'";
143 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
152 if (isa<Function>(V))
154 else if (isa<BasicBlock>(V))
160 V->printAsOperand(OS, /*PrintTy=*/false, M);
166 //===----------------------------------------------------------------------===//
169 /// BBPassManager manages BasicBlockPass. It batches all the
170 /// pass together and sequence them to process one basic block before
171 /// processing next basic block.
172 class BBPassManager : public PMDataManager, public FunctionPass {
176 explicit BBPassManager()
177 : PMDataManager(), FunctionPass(ID) {}
179 /// Execute all of the passes scheduled for execution. Keep track of
180 /// whether any of the passes modifies the function, and if so, return true.
181 bool runOnFunction(Function &F) override;
183 /// Pass Manager itself does not invalidate any analysis info.
184 void getAnalysisUsage(AnalysisUsage &Info) const override {
185 Info.setPreservesAll();
188 bool doInitialization(Module &M) override;
189 bool doInitialization(Function &F);
190 bool doFinalization(Module &M) override;
191 bool doFinalization(Function &F);
193 PMDataManager *getAsPMDataManager() override { return this; }
194 Pass *getAsPass() override { return this; }
196 StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
198 // Print passes managed by this manager
199 void dumpPassStructure(unsigned Offset) override {
200 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
201 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
202 BasicBlockPass *BP = getContainedPass(Index);
203 BP->dumpPassStructure(Offset + 1);
204 dumpLastUses(BP, Offset+1);
208 BasicBlockPass *getContainedPass(unsigned N) {
209 assert(N < PassVector.size() && "Pass number out of range!");
210 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
214 PassManagerType getPassManagerType() const override {
215 return PMT_BasicBlockPassManager;
219 char BBPassManager::ID = 0;
220 } // End anonymous namespace
224 //===----------------------------------------------------------------------===//
225 // FunctionPassManagerImpl
227 /// FunctionPassManagerImpl manages FPPassManagers
228 class FunctionPassManagerImpl : public Pass,
229 public PMDataManager,
230 public PMTopLevelManager {
231 virtual void anchor();
236 explicit FunctionPassManagerImpl() :
237 Pass(PT_PassManager, ID), PMDataManager(),
238 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
240 /// \copydoc FunctionPassManager::add()
245 /// createPrinterPass - Get a function printer pass.
246 Pass *createPrinterPass(raw_ostream &O,
247 const std::string &Banner) const override {
248 return createPrintFunctionPass(O, Banner);
251 // Prepare for running an on the fly pass, freeing memory if needed
252 // from a previous run.
253 void releaseMemoryOnTheFly();
255 /// run - Execute all of the passes scheduled for execution. Keep track of
256 /// whether any of the passes modifies the module, and if so, return true.
257 bool run(Function &F);
259 /// doInitialization - Run all of the initializers for the function passes.
261 bool doInitialization(Module &M) override;
263 /// doFinalization - Run all of the finalizers for the function passes.
265 bool doFinalization(Module &M) override;
268 PMDataManager *getAsPMDataManager() override { return this; }
269 Pass *getAsPass() override { return this; }
270 PassManagerType getTopLevelPassManagerType() override {
271 return PMT_FunctionPassManager;
274 /// Pass Manager itself does not invalidate any analysis info.
275 void getAnalysisUsage(AnalysisUsage &Info) const override {
276 Info.setPreservesAll();
279 FPPassManager *getContainedManager(unsigned N) {
280 assert(N < PassManagers.size() && "Pass number out of range!");
281 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
286 void FunctionPassManagerImpl::anchor() {}
288 char FunctionPassManagerImpl::ID = 0;
289 } // End of legacy namespace
290 } // End of llvm namespace
293 //===----------------------------------------------------------------------===//
296 /// MPPassManager manages ModulePasses and function pass managers.
297 /// It batches all Module passes and function pass managers together and
298 /// sequences them to process one module.
299 class MPPassManager : public Pass, public PMDataManager {
302 explicit MPPassManager() :
303 Pass(PT_PassManager, ID), PMDataManager() { }
305 // Delete on the fly managers.
306 ~MPPassManager() override {
307 for (auto &OnTheFlyManager : OnTheFlyManagers) {
308 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
313 /// createPrinterPass - Get a module printer pass.
314 Pass *createPrinterPass(raw_ostream &O,
315 const std::string &Banner) const override {
316 return createPrintModulePass(O, Banner);
319 /// run - Execute all of the passes scheduled for execution. Keep track of
320 /// whether any of the passes modifies the module, and if so, return true.
321 bool runOnModule(Module &M);
323 using llvm::Pass::doInitialization;
324 using llvm::Pass::doFinalization;
326 /// Pass Manager itself does not invalidate any analysis info.
327 void getAnalysisUsage(AnalysisUsage &Info) const override {
328 Info.setPreservesAll();
331 /// Add RequiredPass into list of lower level passes required by pass P.
332 /// RequiredPass is run on the fly by Pass Manager when P requests it
333 /// through getAnalysis interface.
334 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
336 /// Return function pass corresponding to PassInfo PI, that is
337 /// required by module pass MP. Instantiate analysis pass, by using
338 /// its runOnFunction() for function F.
339 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
341 StringRef getPassName() const override { return "Module Pass Manager"; }
343 PMDataManager *getAsPMDataManager() override { return this; }
344 Pass *getAsPass() override { return this; }
346 // Print passes managed by this manager
347 void dumpPassStructure(unsigned Offset) override {
348 dbgs().indent(Offset*2) << "ModulePass Manager\n";
349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
350 ModulePass *MP = getContainedPass(Index);
351 MP->dumpPassStructure(Offset + 1);
352 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
353 OnTheFlyManagers.find(MP);
354 if (I != OnTheFlyManagers.end())
355 I->second->dumpPassStructure(Offset + 2);
356 dumpLastUses(MP, Offset+1);
360 ModulePass *getContainedPass(unsigned N) {
361 assert(N < PassVector.size() && "Pass number out of range!");
362 return static_cast<ModulePass *>(PassVector[N]);
365 PassManagerType getPassManagerType() const override {
366 return PMT_ModulePassManager;
370 /// Collection of on the fly FPPassManagers. These managers manage
371 /// function passes that are required by module passes.
372 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
375 char MPPassManager::ID = 0;
376 } // End anonymous namespace
380 //===----------------------------------------------------------------------===//
384 /// PassManagerImpl manages MPPassManagers
385 class PassManagerImpl : public Pass,
386 public PMDataManager,
387 public PMTopLevelManager {
388 virtual void anchor();
392 explicit PassManagerImpl() :
393 Pass(PT_PassManager, ID), PMDataManager(),
394 PMTopLevelManager(new MPPassManager()) {}
396 /// \copydoc PassManager::add()
401 /// createPrinterPass - Get a module printer pass.
402 Pass *createPrinterPass(raw_ostream &O,
403 const std::string &Banner) const override {
404 return createPrintModulePass(O, Banner);
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.
411 using llvm::Pass::doInitialization;
412 using llvm::Pass::doFinalization;
414 /// Pass Manager itself does not invalidate any analysis info.
415 void getAnalysisUsage(AnalysisUsage &Info) const override {
416 Info.setPreservesAll();
419 PMDataManager *getAsPMDataManager() override { return this; }
420 Pass *getAsPass() override { return this; }
421 PassManagerType getTopLevelPassManagerType() override {
422 return PMT_ModulePassManager;
425 MPPassManager *getContainedManager(unsigned N) {
426 assert(N < PassManagers.size() && "Pass number out of range!");
427 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
432 void PassManagerImpl::anchor() {}
434 char PassManagerImpl::ID = 0;
435 } // End of legacy namespace
436 } // End of llvm namespace
440 //===----------------------------------------------------------------------===//
441 /// TimingInfo Class - This class is used to calculate information about the
442 /// amount of time each pass takes to execute. This only happens when
443 /// -time-passes is enabled on the command line.
446 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
449 DenseMap<Pass*, Timer*> TimingData;
452 // Use 'create' member to get this.
453 TimingInfo() : TG("pass", "... Pass execution timing report ...") {}
455 // TimingDtor - Print out information about timing information
457 // Delete all of the timers, which accumulate their info into the
459 for (auto &I : TimingData)
461 // TimerGroup is deleted next, printing the report.
464 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
465 // to a non-null value (if the -time-passes option is enabled) or it leaves it
466 // null. It may be called multiple times.
467 static void createTheTimeInfo();
469 // print - Prints out timing information and then resets the timers.
471 TG.print(*CreateInfoOutputFile());
474 /// getPassTimer - Return the timer for the specified pass if it exists.
475 Timer *getPassTimer(Pass *P) {
476 if (P->getAsPMDataManager())
479 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
480 Timer *&T = TimingData[P];
482 StringRef PassName = P->getPassName();
483 T = new Timer(PassName, PassName, TG);
489 } // End of anon namespace
491 static TimingInfo *TheTimeInfo;
493 //===----------------------------------------------------------------------===//
494 // PMTopLevelManager implementation
496 /// Initialize top level manager. Create first pass manager.
497 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
498 PMDM->setTopLevelManager(this);
499 addPassManager(PMDM);
500 activeStack.push(PMDM);
503 /// Set pass P as the last user of the given analysis passes.
505 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
507 if (P->getResolver())
508 PDepth = P->getResolver()->getPMDataManager().getDepth();
510 for (Pass *AP : AnalysisPasses) {
516 // Update the last users of passes that are required transitive by AP.
517 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
518 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
519 SmallVector<Pass *, 12> LastUses;
520 SmallVector<Pass *, 12> LastPMUses;
521 for (AnalysisID ID : IDs) {
522 Pass *AnalysisPass = findAnalysisPass(ID);
523 assert(AnalysisPass && "Expected analysis pass to exist.");
524 AnalysisResolver *AR = AnalysisPass->getResolver();
525 assert(AR && "Expected analysis resolver to exist.");
526 unsigned APDepth = AR->getPMDataManager().getDepth();
528 if (PDepth == APDepth)
529 LastUses.push_back(AnalysisPass);
530 else if (PDepth > APDepth)
531 LastPMUses.push_back(AnalysisPass);
534 setLastUser(LastUses, P);
536 // If this pass has a corresponding pass manager, push higher level
537 // analysis to this pass manager.
538 if (P->getResolver())
539 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
542 // If AP is the last user of other passes then make P last user of
544 for (auto LU : LastUser) {
546 // DenseMap iterator is not invalidated here because
547 // this is just updating existing entries.
548 LastUser[LU.first] = P;
553 /// Collect passes whose last user is P
554 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
556 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
557 InversedLastUser.find(P);
558 if (DMI == InversedLastUser.end())
561 SmallPtrSet<Pass *, 8> &LU = DMI->second;
562 for (Pass *LUP : LU) {
563 LastUses.push_back(LUP);
568 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
569 AnalysisUsage *AnUsage = nullptr;
570 auto DMI = AnUsageMap.find(P);
571 if (DMI != AnUsageMap.end())
572 AnUsage = DMI->second;
574 // Look up the analysis usage from the pass instance (different instances
575 // of the same pass can produce different results), but unique the
576 // resulting object to reduce memory usage. This helps to greatly reduce
577 // memory usage when we have many instances of only a few pass types
578 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
581 P->getAnalysisUsage(AU);
583 AUFoldingSetNode* Node = nullptr;
585 AUFoldingSetNode::Profile(ID, AU);
587 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
590 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
591 UniqueAnalysisUsages.InsertNode(Node, IP);
593 assert(Node && "cached analysis usage must be non null");
595 AnUsageMap[P] = &Node->AU;
601 /// Schedule pass P for execution. Make sure that passes required by
602 /// P are run before P is run. Update analysis info maintained by
603 /// the manager. Remove dead passes. This is a recursive function.
604 void PMTopLevelManager::schedulePass(Pass *P) {
606 // TODO : Allocate function manager for this pass, other wise required set
607 // may be inserted into previous function manager
609 // Give pass a chance to prepare the stage.
610 P->preparePassManager(activeStack);
612 // If P is an analysis pass and it is available then do not
613 // generate the analysis again. Stale analysis info should not be
614 // available at this point.
615 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
616 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
621 AnalysisUsage *AnUsage = findAnalysisUsage(P);
623 bool checkAnalysis = true;
624 while (checkAnalysis) {
625 checkAnalysis = false;
627 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
628 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
629 E = RequiredSet.end(); I != E; ++I) {
631 Pass *AnalysisPass = findAnalysisPass(*I);
633 const PassInfo *PI = findAnalysisPassInfo(*I);
636 // Pass P is not in the global PassRegistry
637 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
638 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
639 dbgs() << "Required Passes:" << "\n";
640 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
641 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
642 Pass *AnalysisPass2 = findAnalysisPass(*I2);
644 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
646 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
647 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
648 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
653 assert(PI && "Expected required passes to be initialized");
654 AnalysisPass = PI->createPass();
655 if (P->getPotentialPassManagerType () ==
656 AnalysisPass->getPotentialPassManagerType())
657 // Schedule analysis pass that is managed by the same pass manager.
658 schedulePass(AnalysisPass);
659 else if (P->getPotentialPassManagerType () >
660 AnalysisPass->getPotentialPassManagerType()) {
661 // Schedule analysis pass that is managed by a new manager.
662 schedulePass(AnalysisPass);
663 // Recheck analysis passes to ensure that required analyses that
664 // are already checked are still available.
665 checkAnalysis = true;
667 // Do not schedule this analysis. Lower level analysis
668 // passes are run on the fly.
674 // Now all required passes are available.
675 if (ImmutablePass *IP = P->getAsImmutablePass()) {
676 // P is a immutable pass and it will be managed by this
677 // top level manager. Set up analysis resolver to connect them.
678 PMDataManager *DM = getAsPMDataManager();
679 AnalysisResolver *AR = new AnalysisResolver(*DM);
681 DM->initializeAnalysisImpl(P);
682 addImmutablePass(IP);
683 DM->recordAvailableAnalysis(IP);
687 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
688 Pass *PP = P->createPrinterPass(
689 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
690 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
693 // Add the requested pass to the best available pass manager.
694 P->assignPassManager(activeStack, getTopLevelPassManagerType());
696 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
697 Pass *PP = P->createPrinterPass(
698 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
699 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
703 /// Find the pass that implements Analysis AID. Search immutable
704 /// passes and all pass managers. If desired pass is not found
705 /// then return NULL.
706 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
707 // For immutable passes we have a direct mapping from ID to pass, so check
709 if (Pass *P = ImmutablePassMap.lookup(AID))
712 // Check pass managers
713 for (PMDataManager *PassManager : PassManagers)
714 if (Pass *P = PassManager->findAnalysisPass(AID, false))
717 // Check other pass managers
718 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
719 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
725 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
726 const PassInfo *&PI = AnalysisPassInfos[AID];
728 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
730 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
731 "The pass info pointer changed for an analysis ID!");
736 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
738 ImmutablePasses.push_back(P);
740 // Add this pass to the map from its analysis ID. We clobber any prior runs
741 // of the pass in the map so that the last one added is the one found when
743 AnalysisID AID = P->getPassID();
744 ImmutablePassMap[AID] = P;
746 // Also add any interfaces implemented by the immutable pass to the map for
748 const PassInfo *PassInf = findAnalysisPassInfo(AID);
749 assert(PassInf && "Expected all immutable passes to be initialized");
750 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
751 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
754 // Print passes managed by this top level manager.
755 void PMTopLevelManager::dumpPasses() const {
757 if (PassDebugging < Structure)
760 // Print out the immutable passes
761 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
762 ImmutablePasses[i]->dumpPassStructure(0);
765 // Every class that derives from PMDataManager also derives from Pass
766 // (sometimes indirectly), but there's no inheritance relationship
767 // between PMDataManager and Pass, so we have to getAsPass to get
768 // from a PMDataManager* to a Pass*.
769 for (PMDataManager *Manager : PassManagers)
770 Manager->getAsPass()->dumpPassStructure(1);
773 void PMTopLevelManager::dumpArguments() const {
775 if (PassDebugging < Arguments)
778 dbgs() << "Pass Arguments: ";
779 for (ImmutablePass *P : ImmutablePasses)
780 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
781 assert(PI && "Expected all immutable passes to be initialized");
782 if (!PI->isAnalysisGroup())
783 dbgs() << " -" << PI->getPassArgument();
785 for (PMDataManager *PM : PassManagers)
786 PM->dumpPassArguments();
790 void PMTopLevelManager::initializeAllAnalysisInfo() {
791 for (PMDataManager *PM : PassManagers)
792 PM->initializeAnalysisInfo();
794 // Initailize other pass managers
795 for (PMDataManager *IPM : IndirectPassManagers)
796 IPM->initializeAnalysisInfo();
798 for (auto LU : LastUser) {
799 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
805 PMTopLevelManager::~PMTopLevelManager() {
806 for (PMDataManager *PM : PassManagers)
809 for (ImmutablePass *P : ImmutablePasses)
813 //===----------------------------------------------------------------------===//
814 // PMDataManager implementation
816 /// Augement AvailableAnalysis by adding analysis made available by pass P.
817 void PMDataManager::recordAvailableAnalysis(Pass *P) {
818 AnalysisID PI = P->getPassID();
820 AvailableAnalysis[PI] = P;
822 assert(!AvailableAnalysis.empty());
824 // This pass is the current implementation of all of the interfaces it
825 // implements as well.
826 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
828 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
829 for (unsigned i = 0, e = II.size(); i != e; ++i)
830 AvailableAnalysis[II[i]->getTypeInfo()] = P;
833 // Return true if P preserves high level analysis used by other
834 // passes managed by this manager
835 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
836 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
837 if (AnUsage->getPreservesAll())
840 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
841 for (Pass *P1 : HigherLevelAnalysis) {
842 if (P1->getAsImmutablePass() == nullptr &&
843 !is_contained(PreservedSet, P1->getPassID()))
850 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
851 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
852 // Don't do this unless assertions are enabled.
856 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
857 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
859 // Verify preserved analysis
860 for (AnalysisID AID : PreservedSet) {
861 if (Pass *AP = findAnalysisPass(AID, true)) {
862 TimeRegion PassTimer(getPassTimer(AP));
863 AP->verifyAnalysis();
868 /// Remove Analysis not preserved by Pass P
869 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
870 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
871 if (AnUsage->getPreservesAll())
874 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
875 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
876 E = AvailableAnalysis.end(); I != E; ) {
877 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
878 if (Info->second->getAsImmutablePass() == nullptr &&
879 !is_contained(PreservedSet, Info->first)) {
880 // Remove this analysis
881 if (PassDebugging >= Details) {
882 Pass *S = Info->second;
883 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
884 dbgs() << S->getPassName() << "'\n";
886 AvailableAnalysis.erase(Info);
890 // Check inherited analysis also. If P is not preserving analysis
891 // provided by parent manager then remove it here.
892 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
894 if (!InheritedAnalysis[Index])
897 for (DenseMap<AnalysisID, Pass*>::iterator
898 I = InheritedAnalysis[Index]->begin(),
899 E = InheritedAnalysis[Index]->end(); I != E; ) {
900 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
901 if (Info->second->getAsImmutablePass() == nullptr &&
902 !is_contained(PreservedSet, Info->first)) {
903 // Remove this analysis
904 if (PassDebugging >= Details) {
905 Pass *S = Info->second;
906 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
907 dbgs() << S->getPassName() << "'\n";
909 InheritedAnalysis[Index]->erase(Info);
915 /// Remove analysis passes that are not used any longer
916 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
917 enum PassDebuggingString DBG_STR) {
919 SmallVector<Pass *, 12> DeadPasses;
921 // If this is a on the fly manager then it does not have TPM.
925 TPM->collectLastUses(DeadPasses, P);
927 if (PassDebugging >= Details && !DeadPasses.empty()) {
928 dbgs() << " -*- '" << P->getPassName();
929 dbgs() << "' is the last user of following pass instances.";
930 dbgs() << " Free these instances\n";
933 for (Pass *P : DeadPasses)
934 freePass(P, Msg, DBG_STR);
937 void PMDataManager::freePass(Pass *P, StringRef Msg,
938 enum PassDebuggingString DBG_STR) {
939 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
942 // If the pass crashes releasing memory, remember this.
943 PassManagerPrettyStackEntry X(P);
944 TimeRegion PassTimer(getPassTimer(P));
949 AnalysisID PI = P->getPassID();
950 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
951 // Remove the pass itself (if it is not already removed).
952 AvailableAnalysis.erase(PI);
954 // Remove all interfaces this pass implements, for which it is also
955 // listed as the available implementation.
956 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
957 for (unsigned i = 0, e = II.size(); i != e; ++i) {
958 DenseMap<AnalysisID, Pass*>::iterator Pos =
959 AvailableAnalysis.find(II[i]->getTypeInfo());
960 if (Pos != AvailableAnalysis.end() && Pos->second == P)
961 AvailableAnalysis.erase(Pos);
966 /// Add pass P into the PassVector. Update
967 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
968 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
969 // This manager is going to manage pass P. Set up analysis resolver
971 AnalysisResolver *AR = new AnalysisResolver(*this);
974 // If a FunctionPass F is the last user of ModulePass info M
975 // then the F's manager, not F, records itself as a last user of M.
976 SmallVector<Pass *, 12> TransferLastUses;
978 if (!ProcessAnalysis) {
980 PassVector.push_back(P);
984 // At the moment, this pass is the last user of all required passes.
985 SmallVector<Pass *, 12> LastUses;
986 SmallVector<Pass *, 8> UsedPasses;
987 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
989 unsigned PDepth = this->getDepth();
991 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
992 for (Pass *PUsed : UsedPasses) {
995 assert(PUsed->getResolver() && "Analysis Resolver is not set");
996 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
997 RDepth = DM.getDepth();
999 if (PDepth == RDepth)
1000 LastUses.push_back(PUsed);
1001 else if (PDepth > RDepth) {
1002 // Let the parent claim responsibility of last use
1003 TransferLastUses.push_back(PUsed);
1004 // Keep track of higher level analysis used by this manager.
1005 HigherLevelAnalysis.push_back(PUsed);
1007 llvm_unreachable("Unable to accommodate Used Pass");
1010 // Set P as P's last user until someone starts using P.
1011 // However, if P is a Pass Manager then it does not need
1012 // to record its last user.
1013 if (!P->getAsPMDataManager())
1014 LastUses.push_back(P);
1015 TPM->setLastUser(LastUses, P);
1017 if (!TransferLastUses.empty()) {
1018 Pass *My_PM = getAsPass();
1019 TPM->setLastUser(TransferLastUses, My_PM);
1020 TransferLastUses.clear();
1023 // Now, take care of required analyses that are not available.
1024 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1025 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1026 Pass *AnalysisPass = PI->createPass();
1027 this->addLowerLevelRequiredPass(P, AnalysisPass);
1030 // Take a note of analysis required and made available by this pass.
1031 // Remove the analysis not preserved by this pass
1032 removeNotPreservedAnalysis(P);
1033 recordAvailableAnalysis(P);
1036 PassVector.push_back(P);
1040 /// Populate UP with analysis pass that are used or required by
1041 /// pass P and are available. Populate RP_NotAvail with analysis
1042 /// pass that are required by pass P but are not available.
1043 void PMDataManager::collectRequiredAndUsedAnalyses(
1044 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1046 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1048 for (const auto &UsedID : AnUsage->getUsedSet())
1049 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1050 UP.push_back(AnalysisPass);
1052 for (const auto &RequiredID : AnUsage->getRequiredSet())
1053 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1054 UP.push_back(AnalysisPass);
1056 RP_NotAvail.push_back(RequiredID);
1058 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1059 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1060 UP.push_back(AnalysisPass);
1062 RP_NotAvail.push_back(RequiredID);
1065 // All Required analyses should be available to the pass as it runs! Here
1066 // we fill in the AnalysisImpls member of the pass so that it can
1067 // successfully use the getAnalysis() method to retrieve the
1068 // implementations it needs.
1070 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1071 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1073 for (AnalysisUsage::VectorType::const_iterator
1074 I = AnUsage->getRequiredSet().begin(),
1075 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1076 Pass *Impl = findAnalysisPass(*I, true);
1078 // This may be analysis pass that is initialized on the fly.
1079 // If that is not the case then it will raise an assert when it is used.
1081 AnalysisResolver *AR = P->getResolver();
1082 assert(AR && "Analysis Resolver is not set");
1083 AR->addAnalysisImplsPair(*I, Impl);
1087 /// Find the pass that implements Analysis AID. If desired pass is not found
1088 /// then return NULL.
1089 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1091 // Check if AvailableAnalysis map has one entry.
1092 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1094 if (I != AvailableAnalysis.end())
1097 // Search Parents through TopLevelManager
1099 return TPM->findAnalysisPass(AID);
1104 // Print list of passes that are last used by P.
1105 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1107 SmallVector<Pass *, 12> LUses;
1109 // If this is a on the fly manager then it does not have TPM.
1113 TPM->collectLastUses(LUses, P);
1115 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1116 E = LUses.end(); I != E; ++I) {
1117 dbgs() << "--" << std::string(Offset*2, ' ');
1118 (*I)->dumpPassStructure(0);
1122 void PMDataManager::dumpPassArguments() const {
1123 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1124 E = PassVector.end(); I != E; ++I) {
1125 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1126 PMD->dumpPassArguments();
1128 if (const PassInfo *PI =
1129 TPM->findAnalysisPassInfo((*I)->getPassID()))
1130 if (!PI->isAnalysisGroup())
1131 dbgs() << " -" << PI->getPassArgument();
1135 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1136 enum PassDebuggingString S2,
1138 if (PassDebugging < Executions)
1140 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1141 << std::string(getDepth() * 2 + 1, ' ');
1144 dbgs() << "Executing Pass '" << P->getPassName();
1146 case MODIFICATION_MSG:
1147 dbgs() << "Made Modification '" << P->getPassName();
1150 dbgs() << " Freeing Pass '" << P->getPassName();
1156 case ON_BASICBLOCK_MSG:
1157 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1159 case ON_FUNCTION_MSG:
1160 dbgs() << "' on Function '" << Msg << "'...\n";
1163 dbgs() << "' on Module '" << Msg << "'...\n";
1166 dbgs() << "' on Region '" << Msg << "'...\n";
1169 dbgs() << "' on Loop '" << Msg << "'...\n";
1172 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1179 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1180 if (PassDebugging < Details)
1183 AnalysisUsage analysisUsage;
1184 P->getAnalysisUsage(analysisUsage);
1185 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1188 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1189 if (PassDebugging < Details)
1192 AnalysisUsage analysisUsage;
1193 P->getAnalysisUsage(analysisUsage);
1194 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1197 void PMDataManager::dumpUsedSet(const Pass *P) const {
1198 if (PassDebugging < Details)
1201 AnalysisUsage analysisUsage;
1202 P->getAnalysisUsage(analysisUsage);
1203 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1206 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1207 const AnalysisUsage::VectorType &Set) const {
1208 assert(PassDebugging >= Details);
1211 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1212 for (unsigned i = 0; i != Set.size(); ++i) {
1213 if (i) dbgs() << ',';
1214 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1216 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1218 dbgs() << " Uninitialized Pass";
1221 dbgs() << ' ' << PInf->getPassName();
1226 /// Add RequiredPass into list of lower level passes required by pass P.
1227 /// RequiredPass is run on the fly by Pass Manager when P requests it
1228 /// through getAnalysis interface.
1229 /// This should be handled by specific pass manager.
1230 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1232 TPM->dumpArguments();
1236 // Module Level pass may required Function Level analysis info
1237 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1238 // to provide this on demand. In that case, in Pass manager terminology,
1239 // module level pass is requiring lower level analysis info managed by
1240 // lower level pass manager.
1242 // When Pass manager is not able to order required analysis info, Pass manager
1243 // checks whether any lower level manager will be able to provide this
1244 // analysis info on demand or not.
1246 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1247 dbgs() << "' required by '" << P->getPassName() << "'\n";
1249 llvm_unreachable("Unable to schedule pass");
1252 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1253 llvm_unreachable("Unable to find on the fly pass");
1257 PMDataManager::~PMDataManager() {
1258 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1259 E = PassVector.end(); I != E; ++I)
1263 //===----------------------------------------------------------------------===//
1264 // NOTE: Is this the right place to define this method ?
1265 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1266 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1267 return PM.findAnalysisPass(ID, dir);
1270 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1272 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1275 //===----------------------------------------------------------------------===//
1276 // BBPassManager implementation
1278 /// Execute all of the passes scheduled for execution by invoking
1279 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1280 /// the function, and if so, return true.
1281 bool BBPassManager::runOnFunction(Function &F) {
1282 if (F.isDeclaration())
1285 bool Changed = doInitialization(F);
1287 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1288 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1289 BasicBlockPass *BP = getContainedPass(Index);
1290 bool LocalChanged = false;
1292 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1293 dumpRequiredSet(BP);
1295 initializeAnalysisImpl(BP);
1298 // If the pass crashes, remember this.
1299 PassManagerPrettyStackEntry X(BP, *I);
1300 TimeRegion PassTimer(getPassTimer(BP));
1302 LocalChanged |= BP->runOnBasicBlock(*I);
1305 Changed |= LocalChanged;
1307 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1309 dumpPreservedSet(BP);
1312 verifyPreservedAnalysis(BP);
1313 removeNotPreservedAnalysis(BP);
1314 recordAvailableAnalysis(BP);
1315 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1318 return doFinalization(F) || Changed;
1321 // Implement doInitialization and doFinalization
1322 bool BBPassManager::doInitialization(Module &M) {
1323 bool Changed = false;
1325 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1326 Changed |= getContainedPass(Index)->doInitialization(M);
1331 bool BBPassManager::doFinalization(Module &M) {
1332 bool Changed = false;
1334 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1335 Changed |= getContainedPass(Index)->doFinalization(M);
1340 bool BBPassManager::doInitialization(Function &F) {
1341 bool Changed = false;
1343 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1344 BasicBlockPass *BP = getContainedPass(Index);
1345 Changed |= BP->doInitialization(F);
1351 bool BBPassManager::doFinalization(Function &F) {
1352 bool Changed = false;
1354 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1355 BasicBlockPass *BP = getContainedPass(Index);
1356 Changed |= BP->doFinalization(F);
1363 //===----------------------------------------------------------------------===//
1364 // FunctionPassManager implementation
1366 /// Create new Function pass manager
1367 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1368 FPM = new FunctionPassManagerImpl();
1369 // FPM is the top level manager.
1370 FPM->setTopLevelManager(FPM);
1372 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1373 FPM->setResolver(AR);
1376 FunctionPassManager::~FunctionPassManager() {
1380 void FunctionPassManager::add(Pass *P) {
1384 /// run - Execute all of the passes scheduled for execution. Keep
1385 /// track of whether any of the passes modifies the function, and if
1386 /// so, return true.
1388 bool FunctionPassManager::run(Function &F) {
1389 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1390 report_fatal_error("Error reading bitcode file: " + EIB.message());
1396 /// doInitialization - Run all of the initializers for the function passes.
1398 bool FunctionPassManager::doInitialization() {
1399 return FPM->doInitialization(*M);
1402 /// doFinalization - Run all of the finalizers for the function passes.
1404 bool FunctionPassManager::doFinalization() {
1405 return FPM->doFinalization(*M);
1408 //===----------------------------------------------------------------------===//
1409 // FunctionPassManagerImpl implementation
1411 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1412 bool Changed = false;
1417 for (ImmutablePass *ImPass : getImmutablePasses())
1418 Changed |= ImPass->doInitialization(M);
1420 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1421 Changed |= getContainedManager(Index)->doInitialization(M);
1426 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1427 bool Changed = false;
1429 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1430 Changed |= getContainedManager(Index)->doFinalization(M);
1432 for (ImmutablePass *ImPass : getImmutablePasses())
1433 Changed |= ImPass->doFinalization(M);
1438 /// cleanup - After running all passes, clean up pass manager cache.
1439 void FPPassManager::cleanup() {
1440 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1441 FunctionPass *FP = getContainedPass(Index);
1442 AnalysisResolver *AR = FP->getResolver();
1443 assert(AR && "Analysis Resolver is not set");
1444 AR->clearAnalysisImpls();
1448 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1451 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1452 FPPassManager *FPPM = getContainedManager(Index);
1453 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1454 FPPM->getContainedPass(Index)->releaseMemory();
1460 // Execute all the passes managed by this top level manager.
1461 // Return true if any function is modified by a pass.
1462 bool FunctionPassManagerImpl::run(Function &F) {
1463 bool Changed = false;
1464 TimingInfo::createTheTimeInfo();
1466 initializeAllAnalysisInfo();
1467 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1468 Changed |= getContainedManager(Index)->runOnFunction(F);
1469 F.getContext().yield();
1472 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1473 getContainedManager(Index)->cleanup();
1479 //===----------------------------------------------------------------------===//
1480 // FPPassManager implementation
1482 char FPPassManager::ID = 0;
1483 /// Print passes managed by this manager
1484 void FPPassManager::dumpPassStructure(unsigned Offset) {
1485 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1486 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1487 FunctionPass *FP = getContainedPass(Index);
1488 FP->dumpPassStructure(Offset + 1);
1489 dumpLastUses(FP, Offset+1);
1494 /// Execute all of the passes scheduled for execution by invoking
1495 /// runOnFunction method. Keep track of whether any of the passes modifies
1496 /// the function, and if so, return true.
1497 bool FPPassManager::runOnFunction(Function &F) {
1498 if (F.isDeclaration())
1501 bool Changed = false;
1503 // Collect inherited analysis from Module level pass manager.
1504 populateInheritedAnalysis(TPM->activeStack);
1506 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1507 FunctionPass *FP = getContainedPass(Index);
1508 bool LocalChanged = false;
1510 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1511 dumpRequiredSet(FP);
1513 initializeAnalysisImpl(FP);
1516 PassManagerPrettyStackEntry X(FP, F);
1517 TimeRegion PassTimer(getPassTimer(FP));
1519 LocalChanged |= FP->runOnFunction(F);
1522 Changed |= LocalChanged;
1524 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1525 dumpPreservedSet(FP);
1528 verifyPreservedAnalysis(FP);
1529 removeNotPreservedAnalysis(FP);
1530 recordAvailableAnalysis(FP);
1531 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1536 bool FPPassManager::runOnModule(Module &M) {
1537 bool Changed = false;
1539 for (Function &F : M)
1540 Changed |= runOnFunction(F);
1545 bool FPPassManager::doInitialization(Module &M) {
1546 bool Changed = false;
1548 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1549 Changed |= getContainedPass(Index)->doInitialization(M);
1554 bool FPPassManager::doFinalization(Module &M) {
1555 bool Changed = false;
1557 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1558 Changed |= getContainedPass(Index)->doFinalization(M);
1563 //===----------------------------------------------------------------------===//
1564 // MPPassManager implementation
1566 /// Execute all of the passes scheduled for execution by invoking
1567 /// runOnModule method. Keep track of whether any of the passes modifies
1568 /// the module, and if so, return true.
1570 MPPassManager::runOnModule(Module &M) {
1571 bool Changed = false;
1573 // Initialize on-the-fly passes
1574 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1575 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1576 Changed |= FPP->doInitialization(M);
1579 // Initialize module passes
1580 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1581 Changed |= getContainedPass(Index)->doInitialization(M);
1583 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1584 ModulePass *MP = getContainedPass(Index);
1585 bool LocalChanged = false;
1587 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1588 dumpRequiredSet(MP);
1590 initializeAnalysisImpl(MP);
1593 PassManagerPrettyStackEntry X(MP, M);
1594 TimeRegion PassTimer(getPassTimer(MP));
1596 LocalChanged |= MP->runOnModule(M);
1599 Changed |= LocalChanged;
1601 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1602 M.getModuleIdentifier());
1603 dumpPreservedSet(MP);
1606 verifyPreservedAnalysis(MP);
1607 removeNotPreservedAnalysis(MP);
1608 recordAvailableAnalysis(MP);
1609 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1612 // Finalize module passes
1613 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1614 Changed |= getContainedPass(Index)->doFinalization(M);
1616 // Finalize on-the-fly passes
1617 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1618 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1619 // We don't know when is the last time an on-the-fly pass is run,
1620 // so we need to releaseMemory / finalize here
1621 FPP->releaseMemoryOnTheFly();
1622 Changed |= FPP->doFinalization(M);
1628 /// Add RequiredPass into list of lower level passes required by pass P.
1629 /// RequiredPass is run on the fly by Pass Manager when P requests it
1630 /// through getAnalysis interface.
1631 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1632 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1633 "Unable to handle Pass that requires lower level Analysis pass");
1634 assert((P->getPotentialPassManagerType() <
1635 RequiredPass->getPotentialPassManagerType()) &&
1636 "Unable to handle Pass that requires lower level Analysis pass");
1640 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1642 FPP = new FunctionPassManagerImpl();
1643 // FPP is the top level manager.
1644 FPP->setTopLevelManager(FPP);
1646 OnTheFlyManagers[P] = FPP;
1648 const PassInfo *RequiredPassPI =
1649 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1651 Pass *FoundPass = nullptr;
1652 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1654 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1657 FoundPass = RequiredPass;
1658 // This should be guaranteed to add RequiredPass to the passmanager given
1659 // that we checked for an available analysis above.
1660 FPP->add(RequiredPass);
1662 // Register P as the last user of FoundPass or RequiredPass.
1663 SmallVector<Pass *, 1> LU;
1664 LU.push_back(FoundPass);
1665 FPP->setLastUser(LU, P);
1668 /// Return function pass corresponding to PassInfo PI, that is
1669 /// required by module pass MP. Instantiate analysis pass, by using
1670 /// its runOnFunction() for function F.
1671 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1672 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1673 assert(FPP && "Unable to find on the fly pass");
1675 FPP->releaseMemoryOnTheFly();
1677 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1681 //===----------------------------------------------------------------------===//
1682 // PassManagerImpl implementation
1685 /// run - Execute all of the passes scheduled for execution. Keep track of
1686 /// whether any of the passes modifies the module, and if so, return true.
1687 bool PassManagerImpl::run(Module &M) {
1688 bool Changed = false;
1689 TimingInfo::createTheTimeInfo();
1694 for (ImmutablePass *ImPass : getImmutablePasses())
1695 Changed |= ImPass->doInitialization(M);
1697 initializeAllAnalysisInfo();
1698 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1699 Changed |= getContainedManager(Index)->runOnModule(M);
1700 M.getContext().yield();
1703 for (ImmutablePass *ImPass : getImmutablePasses())
1704 Changed |= ImPass->doFinalization(M);
1709 //===----------------------------------------------------------------------===//
1710 // PassManager implementation
1712 /// Create new pass manager
1713 PassManager::PassManager() {
1714 PM = new PassManagerImpl();
1715 // PM is the top level manager
1716 PM->setTopLevelManager(PM);
1719 PassManager::~PassManager() {
1723 void PassManager::add(Pass *P) {
1727 /// run - Execute all of the passes scheduled for execution. Keep track of
1728 /// whether any of the passes modifies the module, and if so, return true.
1729 bool PassManager::run(Module &M) {
1733 //===----------------------------------------------------------------------===//
1734 // TimingInfo implementation
1736 bool llvm::TimePassesIsEnabled = false;
1737 static cl::opt<bool,true>
1738 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1739 cl::desc("Time each pass, printing elapsed time for each on exit"));
1741 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1742 // a non-null value (if the -time-passes option is enabled) or it leaves it
1743 // null. It may be called multiple times.
1744 void TimingInfo::createTheTimeInfo() {
1745 if (!TimePassesIsEnabled || TheTimeInfo) return;
1747 // Constructed the first time this is called, iff -time-passes is enabled.
1748 // This guarantees that the object will be constructed before static globals,
1749 // thus it will be destroyed before them.
1750 static ManagedStatic<TimingInfo> TTI;
1751 TheTimeInfo = &*TTI;
1754 /// If TimingInfo is enabled then start pass timer.
1755 Timer *llvm::getPassTimer(Pass *P) {
1757 return TheTimeInfo->getPassTimer(P);
1761 /// If timing is enabled, report the times collected up to now and then reset
1763 void llvm::reportAndResetTimings() {
1765 TheTimeInfo->print();
1768 //===----------------------------------------------------------------------===//
1769 // PMStack implementation
1772 // Pop Pass Manager from the stack and clear its analysis info.
1773 void PMStack::pop() {
1775 PMDataManager *Top = this->top();
1776 Top->initializeAnalysisInfo();
1781 // Push PM on the stack and set its top level manager.
1782 void PMStack::push(PMDataManager *PM) {
1783 assert(PM && "Unable to push. Pass Manager expected");
1784 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1786 if (!this->empty()) {
1787 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1788 && "pushing bad pass manager to PMStack");
1789 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1791 assert(TPM && "Unable to find top level manager");
1792 TPM->addIndirectPassManager(PM);
1793 PM->setTopLevelManager(TPM);
1794 PM->setDepth(this->top()->getDepth()+1);
1796 assert((PM->getPassManagerType() == PMT_ModulePassManager
1797 || PM->getPassManagerType() == PMT_FunctionPassManager)
1798 && "pushing bad pass manager to PMStack");
1805 // Dump content of the pass manager stack.
1806 LLVM_DUMP_METHOD void PMStack::dump() const {
1807 for (PMDataManager *Manager : S)
1808 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1814 /// Find appropriate Module Pass Manager in the PM Stack and
1815 /// add self into that manager.
1816 void ModulePass::assignPassManager(PMStack &PMS,
1817 PassManagerType PreferredType) {
1818 // Find Module Pass Manager
1819 while (!PMS.empty()) {
1820 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1821 if (TopPMType == PreferredType)
1822 break; // We found desired pass manager
1823 else if (TopPMType > PMT_ModulePassManager)
1824 PMS.pop(); // Pop children pass managers
1828 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1829 PMS.top()->add(this);
1832 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1833 /// in the PM Stack and add self into that manager.
1834 void FunctionPass::assignPassManager(PMStack &PMS,
1835 PassManagerType PreferredType) {
1837 // Find Function Pass Manager
1838 while (!PMS.empty()) {
1839 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1845 // Create new Function Pass Manager if needed.
1847 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1848 FPP = (FPPassManager *)PMS.top();
1850 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1851 PMDataManager *PMD = PMS.top();
1853 // [1] Create new Function Pass Manager
1854 FPP = new FPPassManager();
1855 FPP->populateInheritedAnalysis(PMS);
1857 // [2] Set up new manager's top level manager
1858 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1859 TPM->addIndirectPassManager(FPP);
1861 // [3] Assign manager to manage this new manager. This may create
1862 // and push new managers into PMS
1863 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1865 // [4] Push new manager into PMS
1869 // Assign FPP as the manager of this pass.
1873 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1874 /// in the PM Stack and add self into that manager.
1875 void BasicBlockPass::assignPassManager(PMStack &PMS,
1876 PassManagerType PreferredType) {
1879 // Basic Pass Manager is a leaf pass manager. It does not handle
1880 // any other pass manager.
1882 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1883 BBP = (BBPassManager *)PMS.top();
1885 // If leaf manager is not Basic Block Pass manager then create new
1886 // basic Block Pass manager.
1887 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1888 PMDataManager *PMD = PMS.top();
1890 // [1] Create new Basic Block Manager
1891 BBP = new BBPassManager();
1893 // [2] Set up new manager's top level manager
1894 // Basic Block Pass Manager does not live by itself
1895 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1896 TPM->addIndirectPassManager(BBP);
1898 // [3] Assign manager to manage this new manager. This may create
1899 // and push new managers into PMS
1900 BBP->assignPassManager(PMS, PreferredType);
1902 // [4] Push new manager into PMS
1906 // Assign BBP as the manager of this pass.
1910 PassManagerBase::~PassManagerBase() {}