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 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/TimeValue.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm::legacy;
34 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
44 // Different debug levels that can be enabled...
46 Disabled, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(Disabled , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
66 // Print IR out before/after specified passes.
68 PrintBefore("print-before",
69 llvm::cl::desc("Print IR before specified passes"),
73 PrintAfter("print-after",
74 llvm::cl::desc("Print IR after specified passes"),
78 PrintBeforeAll("print-before-all",
79 llvm::cl::desc("Print IR before each pass"),
82 PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
86 /// This is a helper to determine whether to print IR before or
89 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
90 PassOptionList &PassesToPrint) {
91 for (auto *PassInf : PassesToPrint) {
93 if (PassInf->getPassArgument() == PI->getPassArgument()) {
100 /// This is a utility to check whether a pass should have IR dumped
102 static bool ShouldPrintBeforePass(const PassInfo *PI) {
103 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
106 /// This is a utility to check whether a pass should have IR dumped
108 static bool ShouldPrintAfterPass(const PassInfo *PI) {
109 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
112 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
113 /// or higher is specified.
114 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
115 return PassDebugging >= Executions;
121 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
123 OS << "Releasing pass '";
125 OS << "Running pass '";
127 OS << P->getPassName() << "'";
130 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
139 if (isa<Function>(V))
141 else if (isa<BasicBlock>(V))
147 V->printAsOperand(OS, /*PrintTy=*/false, M);
153 //===----------------------------------------------------------------------===//
156 /// BBPassManager manages BasicBlockPass. It batches all the
157 /// pass together and sequence them to process one basic block before
158 /// processing next basic block.
159 class BBPassManager : public PMDataManager, public FunctionPass {
163 explicit BBPassManager()
164 : PMDataManager(), FunctionPass(ID) {}
166 /// Execute all of the passes scheduled for execution. Keep track of
167 /// whether any of the passes modifies the function, and if so, return true.
168 bool runOnFunction(Function &F) override;
170 /// Pass Manager itself does not invalidate any analysis info.
171 void getAnalysisUsage(AnalysisUsage &Info) const override {
172 Info.setPreservesAll();
175 bool doInitialization(Module &M) override;
176 bool doInitialization(Function &F);
177 bool doFinalization(Module &M) override;
178 bool doFinalization(Function &F);
180 PMDataManager *getAsPMDataManager() override { return this; }
181 Pass *getAsPass() override { return this; }
183 const char *getPassName() const override {
184 return "BasicBlock Pass Manager";
187 // Print passes managed by this manager
188 void dumpPassStructure(unsigned Offset) override {
189 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191 BasicBlockPass *BP = getContainedPass(Index);
192 BP->dumpPassStructure(Offset + 1);
193 dumpLastUses(BP, Offset+1);
197 BasicBlockPass *getContainedPass(unsigned N) {
198 assert(N < PassVector.size() && "Pass number out of range!");
199 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
203 PassManagerType getPassManagerType() const override {
204 return PMT_BasicBlockPassManager;
208 char BBPassManager::ID = 0;
209 } // End anonymous namespace
213 //===----------------------------------------------------------------------===//
214 // FunctionPassManagerImpl
216 /// FunctionPassManagerImpl manages FPPassManagers
217 class FunctionPassManagerImpl : public Pass,
218 public PMDataManager,
219 public PMTopLevelManager {
220 virtual void anchor();
225 explicit FunctionPassManagerImpl() :
226 Pass(PT_PassManager, ID), PMDataManager(),
227 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
229 /// \copydoc FunctionPassManager::add()
234 /// createPrinterPass - Get a function printer pass.
235 Pass *createPrinterPass(raw_ostream &O,
236 const std::string &Banner) const override {
237 return createPrintFunctionPass(O, Banner);
240 // Prepare for running an on the fly pass, freeing memory if needed
241 // from a previous run.
242 void releaseMemoryOnTheFly();
244 /// run - Execute all of the passes scheduled for execution. Keep track of
245 /// whether any of the passes modifies the module, and if so, return true.
246 bool run(Function &F);
248 /// doInitialization - Run all of the initializers for the function passes.
250 bool doInitialization(Module &M) override;
252 /// doFinalization - Run all of the finalizers for the function passes.
254 bool doFinalization(Module &M) override;
257 PMDataManager *getAsPMDataManager() override { return this; }
258 Pass *getAsPass() override { return this; }
259 PassManagerType getTopLevelPassManagerType() override {
260 return PMT_FunctionPassManager;
263 /// Pass Manager itself does not invalidate any analysis info.
264 void getAnalysisUsage(AnalysisUsage &Info) const override {
265 Info.setPreservesAll();
268 FPPassManager *getContainedManager(unsigned N) {
269 assert(N < PassManagers.size() && "Pass number out of range!");
270 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
275 void FunctionPassManagerImpl::anchor() {}
277 char FunctionPassManagerImpl::ID = 0;
278 } // End of legacy namespace
279 } // End of llvm namespace
282 //===----------------------------------------------------------------------===//
285 /// MPPassManager manages ModulePasses and function pass managers.
286 /// It batches all Module passes and function pass managers together and
287 /// sequences them to process one module.
288 class MPPassManager : public Pass, public PMDataManager {
291 explicit MPPassManager() :
292 Pass(PT_PassManager, ID), PMDataManager() { }
294 // Delete on the fly managers.
295 ~MPPassManager() override {
296 for (auto &OnTheFlyManager : OnTheFlyManagers) {
297 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
302 /// createPrinterPass - Get a module printer pass.
303 Pass *createPrinterPass(raw_ostream &O,
304 const std::string &Banner) const override {
305 return createPrintModulePass(O, Banner);
308 /// run - Execute all of the passes scheduled for execution. Keep track of
309 /// whether any of the passes modifies the module, and if so, return true.
310 bool runOnModule(Module &M);
312 using llvm::Pass::doInitialization;
313 using llvm::Pass::doFinalization;
315 /// doInitialization - Run all of the initializers for the module passes.
317 bool doInitialization();
319 /// doFinalization - Run all of the finalizers for the module passes.
321 bool doFinalization();
323 /// Pass Manager itself does not invalidate any analysis info.
324 void getAnalysisUsage(AnalysisUsage &Info) const override {
325 Info.setPreservesAll();
328 /// Add RequiredPass into list of lower level passes required by pass P.
329 /// RequiredPass is run on the fly by Pass Manager when P requests it
330 /// through getAnalysis interface.
331 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
333 /// Return function pass corresponding to PassInfo PI, that is
334 /// required by module pass MP. Instantiate analysis pass, by using
335 /// its runOnFunction() for function F.
336 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
338 const char *getPassName() const override {
339 return "Module Pass Manager";
342 PMDataManager *getAsPMDataManager() override { return this; }
343 Pass *getAsPass() override { return this; }
345 // Print passes managed by this manager
346 void dumpPassStructure(unsigned Offset) override {
347 dbgs().indent(Offset*2) << "ModulePass Manager\n";
348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349 ModulePass *MP = getContainedPass(Index);
350 MP->dumpPassStructure(Offset + 1);
351 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352 OnTheFlyManagers.find(MP);
353 if (I != OnTheFlyManagers.end())
354 I->second->dumpPassStructure(Offset + 2);
355 dumpLastUses(MP, Offset+1);
359 ModulePass *getContainedPass(unsigned N) {
360 assert(N < PassVector.size() && "Pass number out of range!");
361 return static_cast<ModulePass *>(PassVector[N]);
364 PassManagerType getPassManagerType() const override {
365 return PMT_ModulePassManager;
369 /// Collection of on the fly FPPassManagers. These managers manage
370 /// function passes that are required by module passes.
371 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
374 char MPPassManager::ID = 0;
375 } // End anonymous namespace
379 //===----------------------------------------------------------------------===//
383 /// PassManagerImpl manages MPPassManagers
384 class PassManagerImpl : public Pass,
385 public PMDataManager,
386 public PMTopLevelManager {
387 virtual void anchor();
391 explicit PassManagerImpl() :
392 Pass(PT_PassManager, ID), PMDataManager(),
393 PMTopLevelManager(new MPPassManager()) {}
395 /// \copydoc PassManager::add()
400 /// createPrinterPass - Get a module printer pass.
401 Pass *createPrinterPass(raw_ostream &O,
402 const std::string &Banner) const override {
403 return createPrintModulePass(O, Banner);
406 /// run - Execute all of the passes scheduled for execution. Keep track of
407 /// whether any of the passes modifies the module, and if so, return true.
410 using llvm::Pass::doInitialization;
411 using llvm::Pass::doFinalization;
413 /// doInitialization - Run all of the initializers for the module passes.
415 bool doInitialization();
417 /// doFinalization - Run all of the finalizers for the module passes.
419 bool doFinalization();
421 /// Pass Manager itself does not invalidate any analysis info.
422 void getAnalysisUsage(AnalysisUsage &Info) const override {
423 Info.setPreservesAll();
426 PMDataManager *getAsPMDataManager() override { return this; }
427 Pass *getAsPass() override { return this; }
428 PassManagerType getTopLevelPassManagerType() override {
429 return PMT_ModulePassManager;
432 MPPassManager *getContainedManager(unsigned N) {
433 assert(N < PassManagers.size() && "Pass number out of range!");
434 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
439 void PassManagerImpl::anchor() {}
441 char PassManagerImpl::ID = 0;
442 } // End of legacy namespace
443 } // End of llvm namespace
447 //===----------------------------------------------------------------------===//
448 /// TimingInfo Class - This class is used to calculate information about the
449 /// amount of time each pass takes to execute. This only happens when
450 /// -time-passes is enabled on the command line.
453 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
456 DenseMap<Pass*, Timer*> TimingData;
459 // Use 'create' member to get this.
460 TimingInfo() : TG("... Pass execution timing report ...") {}
462 // TimingDtor - Print out information about timing information
464 // Delete all of the timers, which accumulate their info into the
466 for (auto &I : TimingData)
468 // TimerGroup is deleted next, printing the report.
471 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
472 // to a non-null value (if the -time-passes option is enabled) or it leaves it
473 // null. It may be called multiple times.
474 static void createTheTimeInfo();
476 /// getPassTimer - Return the timer for the specified pass if it exists.
477 Timer *getPassTimer(Pass *P) {
478 if (P->getAsPMDataManager())
481 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
482 Timer *&T = TimingData[P];
484 T = new Timer(P->getPassName(), 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 (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
522 E = IDs.end(); I != E; ++I) {
523 Pass *AnalysisPass = findAnalysisPass(*I);
524 assert(AnalysisPass && "Expected analysis pass to exist.");
525 AnalysisResolver *AR = AnalysisPass->getResolver();
526 assert(AR && "Expected analysis resolver to exist.");
527 unsigned APDepth = AR->getPMDataManager().getDepth();
529 if (PDepth == APDepth)
530 LastUses.push_back(AnalysisPass);
531 else if (PDepth > APDepth)
532 LastPMUses.push_back(AnalysisPass);
535 setLastUser(LastUses, P);
537 // If this pass has a corresponding pass manager, push higher level
538 // analysis to this pass manager.
539 if (P->getResolver())
540 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
543 // If AP is the last user of other passes then make P last user of
545 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
546 LUE = LastUser.end(); LUI != LUE; ++LUI) {
547 if (LUI->second == AP)
548 // DenseMap iterator is not invalidated here because
549 // this is just updating existing entries.
550 LastUser[LUI->first] = P;
555 /// Collect passes whose last user is P
556 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
558 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
559 InversedLastUser.find(P);
560 if (DMI == InversedLastUser.end())
563 SmallPtrSet<Pass *, 8> &LU = DMI->second;
564 for (Pass *LUP : LU) {
565 LastUses.push_back(LUP);
570 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
571 AnalysisUsage *AnUsage = nullptr;
572 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
573 if (DMI != AnUsageMap.end())
574 AnUsage = DMI->second;
576 AnUsage = new AnalysisUsage();
577 P->getAnalysisUsage(*AnUsage);
578 AnUsageMap[P] = AnUsage;
583 /// Schedule pass P for execution. Make sure that passes required by
584 /// P are run before P is run. Update analysis info maintained by
585 /// the manager. Remove dead passes. This is a recursive function.
586 void PMTopLevelManager::schedulePass(Pass *P) {
588 // TODO : Allocate function manager for this pass, other wise required set
589 // may be inserted into previous function manager
591 // Give pass a chance to prepare the stage.
592 P->preparePassManager(activeStack);
594 // If P is an analysis pass and it is available then do not
595 // generate the analysis again. Stale analysis info should not be
596 // available at this point.
597 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
598 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
603 AnalysisUsage *AnUsage = findAnalysisUsage(P);
605 bool checkAnalysis = true;
606 while (checkAnalysis) {
607 checkAnalysis = false;
609 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
610 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
611 E = RequiredSet.end(); I != E; ++I) {
613 Pass *AnalysisPass = findAnalysisPass(*I);
615 const PassInfo *PI = findAnalysisPassInfo(*I);
618 // Pass P is not in the global PassRegistry
619 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
620 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
621 dbgs() << "Required Passes:" << "\n";
622 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
623 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
624 Pass *AnalysisPass2 = findAnalysisPass(*I2);
626 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
628 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
629 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
630 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
635 assert(PI && "Expected required passes to be initialized");
636 AnalysisPass = PI->createPass();
637 if (P->getPotentialPassManagerType () ==
638 AnalysisPass->getPotentialPassManagerType())
639 // Schedule analysis pass that is managed by the same pass manager.
640 schedulePass(AnalysisPass);
641 else if (P->getPotentialPassManagerType () >
642 AnalysisPass->getPotentialPassManagerType()) {
643 // Schedule analysis pass that is managed by a new manager.
644 schedulePass(AnalysisPass);
645 // Recheck analysis passes to ensure that required analyses that
646 // are already checked are still available.
647 checkAnalysis = true;
649 // Do not schedule this analysis. Lower level analysis
650 // passes are run on the fly.
656 // Now all required passes are available.
657 if (ImmutablePass *IP = P->getAsImmutablePass()) {
658 // P is a immutable pass and it will be managed by this
659 // top level manager. Set up analysis resolver to connect them.
660 PMDataManager *DM = getAsPMDataManager();
661 AnalysisResolver *AR = new AnalysisResolver(*DM);
663 DM->initializeAnalysisImpl(P);
664 addImmutablePass(IP);
665 DM->recordAvailableAnalysis(IP);
669 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
670 Pass *PP = P->createPrinterPass(
671 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
672 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
675 // Add the requested pass to the best available pass manager.
676 P->assignPassManager(activeStack, getTopLevelPassManagerType());
678 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
679 Pass *PP = P->createPrinterPass(
680 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
681 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
685 /// Find the pass that implements Analysis AID. Search immutable
686 /// passes and all pass managers. If desired pass is not found
687 /// then return NULL.
688 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
690 // Check pass managers
691 for (PMDataManager *PassManager : PassManagers)
692 if (Pass *P = PassManager->findAnalysisPass(AID, false))
695 // Check other pass managers
696 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
697 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
700 // Check the immutable passes. Iterate in reverse order so that we find
701 // the most recently registered passes first.
702 for (auto I = ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E;
704 AnalysisID PI = (*I)->getPassID();
708 // If Pass not found then check the interfaces implemented by Immutable Pass
709 const PassInfo *PassInf = findAnalysisPassInfo(PI);
710 assert(PassInf && "Expected all immutable passes to be initialized");
711 const std::vector<const PassInfo*> &ImmPI =
712 PassInf->getInterfacesImplemented();
713 for (const PassInfo *PI : ImmPI)
714 if (PI->getTypeInfo() == AID)
721 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
722 const PassInfo *&PI = AnalysisPassInfos[AID];
724 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
726 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
727 "The pass info pointer changed for an analysis ID!");
732 // Print passes managed by this top level manager.
733 void PMTopLevelManager::dumpPasses() const {
735 if (PassDebugging < Structure)
738 // Print out the immutable passes
739 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
740 ImmutablePasses[i]->dumpPassStructure(0);
743 // Every class that derives from PMDataManager also derives from Pass
744 // (sometimes indirectly), but there's no inheritance relationship
745 // between PMDataManager and Pass, so we have to getAsPass to get
746 // from a PMDataManager* to a Pass*.
747 for (PMDataManager *Manager : PassManagers)
748 Manager->getAsPass()->dumpPassStructure(1);
751 void PMTopLevelManager::dumpArguments() const {
753 if (PassDebugging < Arguments)
756 dbgs() << "Pass Arguments: ";
757 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
758 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
759 if (const PassInfo *PI = findAnalysisPassInfo((*I)->getPassID())) {
760 assert(PI && "Expected all immutable passes to be initialized");
761 if (!PI->isAnalysisGroup())
762 dbgs() << " -" << PI->getPassArgument();
764 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
765 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
766 (*I)->dumpPassArguments();
770 void PMTopLevelManager::initializeAllAnalysisInfo() {
771 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
772 E = PassManagers.end(); I != E; ++I)
773 (*I)->initializeAnalysisInfo();
775 // Initailize other pass managers
776 for (SmallVectorImpl<PMDataManager *>::iterator
777 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
779 (*I)->initializeAnalysisInfo();
781 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
782 DME = LastUser.end(); DMI != DME; ++DMI) {
783 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
784 InversedLastUser.find(DMI->second);
785 if (InvDMI != InversedLastUser.end()) {
786 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
787 L.insert(DMI->first);
789 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
790 InversedLastUser[DMI->second] = L;
796 PMTopLevelManager::~PMTopLevelManager() {
797 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
798 E = PassManagers.end(); I != E; ++I)
801 for (SmallVectorImpl<ImmutablePass *>::iterator
802 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
805 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
806 DME = AnUsageMap.end(); DMI != DME; ++DMI)
810 //===----------------------------------------------------------------------===//
811 // PMDataManager implementation
813 /// Augement AvailableAnalysis by adding analysis made available by pass P.
814 void PMDataManager::recordAvailableAnalysis(Pass *P) {
815 AnalysisID PI = P->getPassID();
817 AvailableAnalysis[PI] = P;
819 assert(!AvailableAnalysis.empty());
821 // This pass is the current implementation of all of the interfaces it
822 // implements as well.
823 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
825 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
826 for (unsigned i = 0, e = II.size(); i != e; ++i)
827 AvailableAnalysis[II[i]->getTypeInfo()] = P;
830 // Return true if P preserves high level analysis used by other
831 // passes managed by this manager
832 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
833 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
834 if (AnUsage->getPreservesAll())
837 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
838 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
839 E = HigherLevelAnalysis.end(); I != E; ++I) {
841 if (P1->getAsImmutablePass() == nullptr &&
842 std::find(PreservedSet.begin(), PreservedSet.end(),
851 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
852 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
853 // Don't do this unless assertions are enabled.
857 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
858 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
860 // Verify preserved analysis
861 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
862 E = PreservedSet.end(); I != E; ++I) {
864 if (Pass *AP = findAnalysisPass(AID, true)) {
865 TimeRegion PassTimer(getPassTimer(AP));
866 AP->verifyAnalysis();
871 /// Remove Analysis not preserved by Pass P
872 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
873 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
874 if (AnUsage->getPreservesAll())
877 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
878 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
879 E = AvailableAnalysis.end(); I != E; ) {
880 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
881 if (Info->second->getAsImmutablePass() == nullptr &&
882 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
883 PreservedSet.end()) {
884 // Remove this analysis
885 if (PassDebugging >= Details) {
886 Pass *S = Info->second;
887 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
888 dbgs() << S->getPassName() << "'\n";
890 AvailableAnalysis.erase(Info);
894 // Check inherited analysis also. If P is not preserving analysis
895 // provided by parent manager then remove it here.
896 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
898 if (!InheritedAnalysis[Index])
901 for (DenseMap<AnalysisID, Pass*>::iterator
902 I = InheritedAnalysis[Index]->begin(),
903 E = InheritedAnalysis[Index]->end(); I != E; ) {
904 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
905 if (Info->second->getAsImmutablePass() == nullptr &&
906 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
907 PreservedSet.end()) {
908 // Remove this analysis
909 if (PassDebugging >= Details) {
910 Pass *S = Info->second;
911 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
912 dbgs() << S->getPassName() << "'\n";
914 InheritedAnalysis[Index]->erase(Info);
920 /// Remove analysis passes that are not used any longer
921 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
922 enum PassDebuggingString DBG_STR) {
924 SmallVector<Pass *, 12> DeadPasses;
926 // If this is a on the fly manager then it does not have TPM.
930 TPM->collectLastUses(DeadPasses, P);
932 if (PassDebugging >= Details && !DeadPasses.empty()) {
933 dbgs() << " -*- '" << P->getPassName();
934 dbgs() << "' is the last user of following pass instances.";
935 dbgs() << " Free these instances\n";
938 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
939 E = DeadPasses.end(); I != E; ++I)
940 freePass(*I, Msg, DBG_STR);
943 void PMDataManager::freePass(Pass *P, StringRef Msg,
944 enum PassDebuggingString DBG_STR) {
945 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
948 // If the pass crashes releasing memory, remember this.
949 PassManagerPrettyStackEntry X(P);
950 TimeRegion PassTimer(getPassTimer(P));
955 AnalysisID PI = P->getPassID();
956 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
957 // Remove the pass itself (if it is not already removed).
958 AvailableAnalysis.erase(PI);
960 // Remove all interfaces this pass implements, for which it is also
961 // listed as the available implementation.
962 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
963 for (unsigned i = 0, e = II.size(); i != e; ++i) {
964 DenseMap<AnalysisID, Pass*>::iterator Pos =
965 AvailableAnalysis.find(II[i]->getTypeInfo());
966 if (Pos != AvailableAnalysis.end() && Pos->second == P)
967 AvailableAnalysis.erase(Pos);
972 /// Add pass P into the PassVector. Update
973 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
974 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
975 // This manager is going to manage pass P. Set up analysis resolver
977 AnalysisResolver *AR = new AnalysisResolver(*this);
980 // If a FunctionPass F is the last user of ModulePass info M
981 // then the F's manager, not F, records itself as a last user of M.
982 SmallVector<Pass *, 12> TransferLastUses;
984 if (!ProcessAnalysis) {
986 PassVector.push_back(P);
990 // At the moment, this pass is the last user of all required passes.
991 SmallVector<Pass *, 12> LastUses;
992 SmallVector<Pass *, 8> RequiredPasses;
993 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
995 unsigned PDepth = this->getDepth();
997 collectRequiredAnalysis(RequiredPasses,
998 ReqAnalysisNotAvailable, P);
999 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1000 E = RequiredPasses.end(); I != E; ++I) {
1001 Pass *PRequired = *I;
1002 unsigned RDepth = 0;
1004 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1005 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1006 RDepth = DM.getDepth();
1008 if (PDepth == RDepth)
1009 LastUses.push_back(PRequired);
1010 else if (PDepth > RDepth) {
1011 // Let the parent claim responsibility of last use
1012 TransferLastUses.push_back(PRequired);
1013 // Keep track of higher level analysis used by this manager.
1014 HigherLevelAnalysis.push_back(PRequired);
1016 llvm_unreachable("Unable to accommodate Required Pass");
1019 // Set P as P's last user until someone starts using P.
1020 // However, if P is a Pass Manager then it does not need
1021 // to record its last user.
1022 if (!P->getAsPMDataManager())
1023 LastUses.push_back(P);
1024 TPM->setLastUser(LastUses, P);
1026 if (!TransferLastUses.empty()) {
1027 Pass *My_PM = getAsPass();
1028 TPM->setLastUser(TransferLastUses, My_PM);
1029 TransferLastUses.clear();
1032 // Now, take care of required analyses that are not available.
1033 for (SmallVectorImpl<AnalysisID>::iterator
1034 I = ReqAnalysisNotAvailable.begin(),
1035 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1036 const PassInfo *PI = TPM->findAnalysisPassInfo(*I);
1037 Pass *AnalysisPass = PI->createPass();
1038 this->addLowerLevelRequiredPass(P, AnalysisPass);
1041 // Take a note of analysis required and made available by this pass.
1042 // Remove the analysis not preserved by this pass
1043 removeNotPreservedAnalysis(P);
1044 recordAvailableAnalysis(P);
1047 PassVector.push_back(P);
1051 /// Populate RP with analysis pass that are required by
1052 /// pass P and are available. Populate RP_NotAvail with analysis
1053 /// pass that are required by pass P but are not available.
1054 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1055 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1057 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1058 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1059 for (AnalysisUsage::VectorType::const_iterator
1060 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1061 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1062 RP.push_back(AnalysisPass);
1064 RP_NotAvail.push_back(*I);
1067 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1068 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1069 E = IDs.end(); I != E; ++I) {
1070 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1071 RP.push_back(AnalysisPass);
1073 RP_NotAvail.push_back(*I);
1077 // All Required analyses should be available to the pass as it runs! Here
1078 // we fill in the AnalysisImpls member of the pass so that it can
1079 // successfully use the getAnalysis() method to retrieve the
1080 // implementations it needs.
1082 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1083 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1085 for (AnalysisUsage::VectorType::const_iterator
1086 I = AnUsage->getRequiredSet().begin(),
1087 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1088 Pass *Impl = findAnalysisPass(*I, true);
1090 // This may be analysis pass that is initialized on the fly.
1091 // If that is not the case then it will raise an assert when it is used.
1093 AnalysisResolver *AR = P->getResolver();
1094 assert(AR && "Analysis Resolver is not set");
1095 AR->addAnalysisImplsPair(*I, Impl);
1099 /// Find the pass that implements Analysis AID. If desired pass is not found
1100 /// then return NULL.
1101 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1103 // Check if AvailableAnalysis map has one entry.
1104 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1106 if (I != AvailableAnalysis.end())
1109 // Search Parents through TopLevelManager
1111 return TPM->findAnalysisPass(AID);
1116 // Print list of passes that are last used by P.
1117 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1119 SmallVector<Pass *, 12> LUses;
1121 // If this is a on the fly manager then it does not have TPM.
1125 TPM->collectLastUses(LUses, P);
1127 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1128 E = LUses.end(); I != E; ++I) {
1129 dbgs() << "--" << std::string(Offset*2, ' ');
1130 (*I)->dumpPassStructure(0);
1134 void PMDataManager::dumpPassArguments() const {
1135 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1136 E = PassVector.end(); I != E; ++I) {
1137 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1138 PMD->dumpPassArguments();
1140 if (const PassInfo *PI =
1141 TPM->findAnalysisPassInfo((*I)->getPassID()))
1142 if (!PI->isAnalysisGroup())
1143 dbgs() << " -" << PI->getPassArgument();
1147 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1148 enum PassDebuggingString S2,
1150 if (PassDebugging < Executions)
1152 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1153 << std::string(getDepth() * 2 + 1, ' ');
1156 dbgs() << "Executing Pass '" << P->getPassName();
1158 case MODIFICATION_MSG:
1159 dbgs() << "Made Modification '" << P->getPassName();
1162 dbgs() << " Freeing Pass '" << P->getPassName();
1168 case ON_BASICBLOCK_MSG:
1169 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1171 case ON_FUNCTION_MSG:
1172 dbgs() << "' on Function '" << Msg << "'...\n";
1175 dbgs() << "' on Module '" << Msg << "'...\n";
1178 dbgs() << "' on Region '" << Msg << "'...\n";
1181 dbgs() << "' on Loop '" << Msg << "'...\n";
1184 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1191 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1192 if (PassDebugging < Details)
1195 AnalysisUsage analysisUsage;
1196 P->getAnalysisUsage(analysisUsage);
1197 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1200 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1201 if (PassDebugging < Details)
1204 AnalysisUsage analysisUsage;
1205 P->getAnalysisUsage(analysisUsage);
1206 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1209 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1210 const AnalysisUsage::VectorType &Set) const {
1211 assert(PassDebugging >= Details);
1214 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1215 for (unsigned i = 0; i != Set.size(); ++i) {
1216 if (i) dbgs() << ',';
1217 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1219 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1221 dbgs() << " Uninitialized Pass";
1224 dbgs() << ' ' << PInf->getPassName();
1229 /// Add RequiredPass into list of lower level passes required by pass P.
1230 /// RequiredPass is run on the fly by Pass Manager when P requests it
1231 /// through getAnalysis interface.
1232 /// This should be handled by specific pass manager.
1233 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1235 TPM->dumpArguments();
1239 // Module Level pass may required Function Level analysis info
1240 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1241 // to provide this on demand. In that case, in Pass manager terminology,
1242 // module level pass is requiring lower level analysis info managed by
1243 // lower level pass manager.
1245 // When Pass manager is not able to order required analysis info, Pass manager
1246 // checks whether any lower level manager will be able to provide this
1247 // analysis info on demand or not.
1249 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1250 dbgs() << "' required by '" << P->getPassName() << "'\n";
1252 llvm_unreachable("Unable to schedule pass");
1255 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1256 llvm_unreachable("Unable to find on the fly pass");
1260 PMDataManager::~PMDataManager() {
1261 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1262 E = PassVector.end(); I != E; ++I)
1266 //===----------------------------------------------------------------------===//
1267 // NOTE: Is this the right place to define this method ?
1268 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1269 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1270 return PM.findAnalysisPass(ID, dir);
1273 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1275 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1278 //===----------------------------------------------------------------------===//
1279 // BBPassManager implementation
1281 /// Execute all of the passes scheduled for execution by invoking
1282 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1283 /// the function, and if so, return true.
1284 bool BBPassManager::runOnFunction(Function &F) {
1285 if (F.isDeclaration())
1288 bool Changed = doInitialization(F);
1290 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1291 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1292 BasicBlockPass *BP = getContainedPass(Index);
1293 bool LocalChanged = false;
1295 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1296 dumpRequiredSet(BP);
1298 initializeAnalysisImpl(BP);
1301 // If the pass crashes, remember this.
1302 PassManagerPrettyStackEntry X(BP, *I);
1303 TimeRegion PassTimer(getPassTimer(BP));
1305 LocalChanged |= BP->runOnBasicBlock(*I);
1308 Changed |= LocalChanged;
1310 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1312 dumpPreservedSet(BP);
1314 verifyPreservedAnalysis(BP);
1315 removeNotPreservedAnalysis(BP);
1316 recordAvailableAnalysis(BP);
1317 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1320 return doFinalization(F) || Changed;
1323 // Implement doInitialization and doFinalization
1324 bool BBPassManager::doInitialization(Module &M) {
1325 bool Changed = false;
1327 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1328 Changed |= getContainedPass(Index)->doInitialization(M);
1333 bool BBPassManager::doFinalization(Module &M) {
1334 bool Changed = false;
1336 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1337 Changed |= getContainedPass(Index)->doFinalization(M);
1342 bool BBPassManager::doInitialization(Function &F) {
1343 bool Changed = false;
1345 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1346 BasicBlockPass *BP = getContainedPass(Index);
1347 Changed |= BP->doInitialization(F);
1353 bool BBPassManager::doFinalization(Function &F) {
1354 bool Changed = false;
1356 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1357 BasicBlockPass *BP = getContainedPass(Index);
1358 Changed |= BP->doFinalization(F);
1365 //===----------------------------------------------------------------------===//
1366 // FunctionPassManager implementation
1368 /// Create new Function pass manager
1369 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1370 FPM = new FunctionPassManagerImpl();
1371 // FPM is the top level manager.
1372 FPM->setTopLevelManager(FPM);
1374 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1375 FPM->setResolver(AR);
1378 FunctionPassManager::~FunctionPassManager() {
1382 void FunctionPassManager::add(Pass *P) {
1386 /// run - Execute all of the passes scheduled for execution. Keep
1387 /// track of whether any of the passes modifies the function, and if
1388 /// so, return true.
1390 bool FunctionPassManager::run(Function &F) {
1391 if (std::error_code EC = F.materialize())
1392 report_fatal_error("Error reading bitcode file: " + EC.message());
1397 /// doInitialization - Run all of the initializers for the function passes.
1399 bool FunctionPassManager::doInitialization() {
1400 return FPM->doInitialization(*M);
1403 /// doFinalization - Run all of the finalizers for the function passes.
1405 bool FunctionPassManager::doFinalization() {
1406 return FPM->doFinalization(*M);
1409 //===----------------------------------------------------------------------===//
1410 // FunctionPassManagerImpl implementation
1412 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1413 bool Changed = false;
1418 for (ImmutablePass *ImPass : getImmutablePasses())
1419 Changed |= ImPass->doInitialization(M);
1421 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1422 Changed |= getContainedManager(Index)->doInitialization(M);
1427 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1428 bool Changed = false;
1430 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1431 Changed |= getContainedManager(Index)->doFinalization(M);
1433 for (ImmutablePass *ImPass : getImmutablePasses())
1434 Changed |= ImPass->doFinalization(M);
1439 /// cleanup - After running all passes, clean up pass manager cache.
1440 void FPPassManager::cleanup() {
1441 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1442 FunctionPass *FP = getContainedPass(Index);
1443 AnalysisResolver *AR = FP->getResolver();
1444 assert(AR && "Analysis Resolver is not set");
1445 AR->clearAnalysisImpls();
1449 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1452 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1453 FPPassManager *FPPM = getContainedManager(Index);
1454 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1455 FPPM->getContainedPass(Index)->releaseMemory();
1461 // Execute all the passes managed by this top level manager.
1462 // Return true if any function is modified by a pass.
1463 bool FunctionPassManagerImpl::run(Function &F) {
1464 bool Changed = false;
1465 TimingInfo::createTheTimeInfo();
1467 initializeAllAnalysisInfo();
1468 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1469 Changed |= getContainedManager(Index)->runOnFunction(F);
1470 F.getContext().yield();
1473 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1474 getContainedManager(Index)->cleanup();
1480 //===----------------------------------------------------------------------===//
1481 // FPPassManager implementation
1483 char FPPassManager::ID = 0;
1484 /// Print passes managed by this manager
1485 void FPPassManager::dumpPassStructure(unsigned Offset) {
1486 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1487 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1488 FunctionPass *FP = getContainedPass(Index);
1489 FP->dumpPassStructure(Offset + 1);
1490 dumpLastUses(FP, Offset+1);
1495 /// Execute all of the passes scheduled for execution by invoking
1496 /// runOnFunction method. Keep track of whether any of the passes modifies
1497 /// the function, and if so, return true.
1498 bool FPPassManager::runOnFunction(Function &F) {
1499 if (F.isDeclaration())
1502 bool Changed = false;
1504 // Collect inherited analysis from Module level pass manager.
1505 populateInheritedAnalysis(TPM->activeStack);
1507 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1508 FunctionPass *FP = getContainedPass(Index);
1509 bool LocalChanged = false;
1511 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1512 dumpRequiredSet(FP);
1514 initializeAnalysisImpl(FP);
1517 PassManagerPrettyStackEntry X(FP, F);
1518 TimeRegion PassTimer(getPassTimer(FP));
1520 LocalChanged |= FP->runOnFunction(F);
1523 Changed |= LocalChanged;
1525 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1526 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);
1605 verifyPreservedAnalysis(MP);
1606 removeNotPreservedAnalysis(MP);
1607 recordAvailableAnalysis(MP);
1608 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1611 // Finalize module passes
1612 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1613 Changed |= getContainedPass(Index)->doFinalization(M);
1615 // Finalize on-the-fly passes
1616 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1617 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1618 // We don't know when is the last time an on-the-fly pass is run,
1619 // so we need to releaseMemory / finalize here
1620 FPP->releaseMemoryOnTheFly();
1621 Changed |= FPP->doFinalization(M);
1627 /// Add RequiredPass into list of lower level passes required by pass P.
1628 /// RequiredPass is run on the fly by Pass Manager when P requests it
1629 /// through getAnalysis interface.
1630 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1631 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1632 "Unable to handle Pass that requires lower level Analysis pass");
1633 assert((P->getPotentialPassManagerType() <
1634 RequiredPass->getPotentialPassManagerType()) &&
1635 "Unable to handle Pass that requires lower level Analysis pass");
1639 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1641 FPP = new FunctionPassManagerImpl();
1642 // FPP is the top level manager.
1643 FPP->setTopLevelManager(FPP);
1645 OnTheFlyManagers[P] = FPP;
1647 const PassInfo *RequiredPassPI =
1648 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1650 Pass *FoundPass = nullptr;
1651 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1653 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1656 FoundPass = RequiredPass;
1657 // This should be guaranteed to add RequiredPass to the passmanager given
1658 // that we checked for an available analysis above.
1659 FPP->add(RequiredPass);
1661 // Register P as the last user of FoundPass or RequiredPass.
1662 SmallVector<Pass *, 1> LU;
1663 LU.push_back(FoundPass);
1664 FPP->setLastUser(LU, P);
1667 /// Return function pass corresponding to PassInfo PI, that is
1668 /// required by module pass MP. Instantiate analysis pass, by using
1669 /// its runOnFunction() for function F.
1670 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1671 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1672 assert(FPP && "Unable to find on the fly pass");
1674 FPP->releaseMemoryOnTheFly();
1676 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1680 //===----------------------------------------------------------------------===//
1681 // PassManagerImpl implementation
1684 /// run - Execute all of the passes scheduled for execution. Keep track of
1685 /// whether any of the passes modifies the module, and if so, return true.
1686 bool PassManagerImpl::run(Module &M) {
1687 bool Changed = false;
1688 TimingInfo::createTheTimeInfo();
1693 for (ImmutablePass *ImPass : getImmutablePasses())
1694 Changed |= ImPass->doInitialization(M);
1696 initializeAllAnalysisInfo();
1697 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1698 Changed |= getContainedManager(Index)->runOnModule(M);
1699 M.getContext().yield();
1702 for (ImmutablePass *ImPass : getImmutablePasses())
1703 Changed |= ImPass->doFinalization(M);
1708 //===----------------------------------------------------------------------===//
1709 // PassManager implementation
1711 /// Create new pass manager
1712 PassManager::PassManager() {
1713 PM = new PassManagerImpl();
1714 // PM is the top level manager
1715 PM->setTopLevelManager(PM);
1718 PassManager::~PassManager() {
1722 void PassManager::add(Pass *P) {
1726 /// run - Execute all of the passes scheduled for execution. Keep track of
1727 /// whether any of the passes modifies the module, and if so, return true.
1728 bool PassManager::run(Module &M) {
1732 //===----------------------------------------------------------------------===//
1733 // TimingInfo implementation
1735 bool llvm::TimePassesIsEnabled = false;
1736 static cl::opt<bool,true>
1737 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1738 cl::desc("Time each pass, printing elapsed time for each on exit"));
1740 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1741 // a non-null value (if the -time-passes option is enabled) or it leaves it
1742 // null. It may be called multiple times.
1743 void TimingInfo::createTheTimeInfo() {
1744 if (!TimePassesIsEnabled || TheTimeInfo) return;
1746 // Constructed the first time this is called, iff -time-passes is enabled.
1747 // This guarantees that the object will be constructed before static globals,
1748 // thus it will be destroyed before them.
1749 static ManagedStatic<TimingInfo> TTI;
1750 TheTimeInfo = &*TTI;
1753 /// If TimingInfo is enabled then start pass timer.
1754 Timer *llvm::getPassTimer(Pass *P) {
1756 return TheTimeInfo->getPassTimer(P);
1760 //===----------------------------------------------------------------------===//
1761 // PMStack implementation
1764 // Pop Pass Manager from the stack and clear its analysis info.
1765 void PMStack::pop() {
1767 PMDataManager *Top = this->top();
1768 Top->initializeAnalysisInfo();
1773 // Push PM on the stack and set its top level manager.
1774 void PMStack::push(PMDataManager *PM) {
1775 assert(PM && "Unable to push. Pass Manager expected");
1776 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1778 if (!this->empty()) {
1779 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1780 && "pushing bad pass manager to PMStack");
1781 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1783 assert(TPM && "Unable to find top level manager");
1784 TPM->addIndirectPassManager(PM);
1785 PM->setTopLevelManager(TPM);
1786 PM->setDepth(this->top()->getDepth()+1);
1788 assert((PM->getPassManagerType() == PMT_ModulePassManager
1789 || PM->getPassManagerType() == PMT_FunctionPassManager)
1790 && "pushing bad pass manager to PMStack");
1797 // Dump content of the pass manager stack.
1798 void PMStack::dump() const {
1799 for (PMDataManager *Manager : S)
1800 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1806 /// Find appropriate Module Pass Manager in the PM Stack and
1807 /// add self into that manager.
1808 void ModulePass::assignPassManager(PMStack &PMS,
1809 PassManagerType PreferredType) {
1810 // Find Module Pass Manager
1811 while (!PMS.empty()) {
1812 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1813 if (TopPMType == PreferredType)
1814 break; // We found desired pass manager
1815 else if (TopPMType > PMT_ModulePassManager)
1816 PMS.pop(); // Pop children pass managers
1820 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1821 PMS.top()->add(this);
1824 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1825 /// in the PM Stack and add self into that manager.
1826 void FunctionPass::assignPassManager(PMStack &PMS,
1827 PassManagerType PreferredType) {
1829 // Find Function Pass Manager
1830 while (!PMS.empty()) {
1831 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1837 // Create new Function Pass Manager if needed.
1839 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1840 FPP = (FPPassManager *)PMS.top();
1842 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1843 PMDataManager *PMD = PMS.top();
1845 // [1] Create new Function Pass Manager
1846 FPP = new FPPassManager();
1847 FPP->populateInheritedAnalysis(PMS);
1849 // [2] Set up new manager's top level manager
1850 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1851 TPM->addIndirectPassManager(FPP);
1853 // [3] Assign manager to manage this new manager. This may create
1854 // and push new managers into PMS
1855 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1857 // [4] Push new manager into PMS
1861 // Assign FPP as the manager of this pass.
1865 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1866 /// in the PM Stack and add self into that manager.
1867 void BasicBlockPass::assignPassManager(PMStack &PMS,
1868 PassManagerType PreferredType) {
1871 // Basic Pass Manager is a leaf pass manager. It does not handle
1872 // any other pass manager.
1874 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1875 BBP = (BBPassManager *)PMS.top();
1877 // If leaf manager is not Basic Block Pass manager then create new
1878 // basic Block Pass manager.
1879 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1880 PMDataManager *PMD = PMS.top();
1882 // [1] Create new Basic Block Manager
1883 BBP = new BBPassManager();
1885 // [2] Set up new manager's top level manager
1886 // Basic Block Pass Manager does not live by itself
1887 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1888 TPM->addIndirectPassManager(BBP);
1890 // [3] Assign manager to manage this new manager. This may create
1891 // and push new managers into PMS
1892 BBP->assignPassManager(PMS, PreferredType);
1894 // [4] Push new manager into PMS
1898 // Assign BBP as the manager of this pass.
1902 PassManagerBase::~PassManagerBase() {}