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 auto DMI = AnUsageMap.find(P);
573 if (DMI != AnUsageMap.end())
574 AnUsage = DMI->second;
576 // Look up the analysis usage from the pass instance (different instances
577 // of the same pass can produce different results), but unique the
578 // resulting object to reduce memory usage. This helps to greatly reduce
579 // memory usage when we have many instances of only a few pass types
580 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
583 P->getAnalysisUsage(AU);
585 AUFoldingSetNode* Node = nullptr;
587 AUFoldingSetNode::Profile(ID, AU);
589 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
592 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
593 UniqueAnalysisUsages.InsertNode(Node, IP);
595 assert(Node && "cached analysis usage must be non null");
597 AnUsageMap[P] = &Node->AU;
598 AnUsage = &Node->AU;;
603 /// Schedule pass P for execution. Make sure that passes required by
604 /// P are run before P is run. Update analysis info maintained by
605 /// the manager. Remove dead passes. This is a recursive function.
606 void PMTopLevelManager::schedulePass(Pass *P) {
608 // TODO : Allocate function manager for this pass, other wise required set
609 // may be inserted into previous function manager
611 // Give pass a chance to prepare the stage.
612 P->preparePassManager(activeStack);
614 // If P is an analysis pass and it is available then do not
615 // generate the analysis again. Stale analysis info should not be
616 // available at this point.
617 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
618 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
623 AnalysisUsage *AnUsage = findAnalysisUsage(P);
625 bool checkAnalysis = true;
626 while (checkAnalysis) {
627 checkAnalysis = false;
629 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
630 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
631 E = RequiredSet.end(); I != E; ++I) {
633 Pass *AnalysisPass = findAnalysisPass(*I);
635 const PassInfo *PI = findAnalysisPassInfo(*I);
638 // Pass P is not in the global PassRegistry
639 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
640 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
641 dbgs() << "Required Passes:" << "\n";
642 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
643 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
644 Pass *AnalysisPass2 = findAnalysisPass(*I2);
646 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
648 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
649 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
650 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
655 assert(PI && "Expected required passes to be initialized");
656 AnalysisPass = PI->createPass();
657 if (P->getPotentialPassManagerType () ==
658 AnalysisPass->getPotentialPassManagerType())
659 // Schedule analysis pass that is managed by the same pass manager.
660 schedulePass(AnalysisPass);
661 else if (P->getPotentialPassManagerType () >
662 AnalysisPass->getPotentialPassManagerType()) {
663 // Schedule analysis pass that is managed by a new manager.
664 schedulePass(AnalysisPass);
665 // Recheck analysis passes to ensure that required analyses that
666 // are already checked are still available.
667 checkAnalysis = true;
669 // Do not schedule this analysis. Lower level analysis
670 // passes are run on the fly.
676 // Now all required passes are available.
677 if (ImmutablePass *IP = P->getAsImmutablePass()) {
678 // P is a immutable pass and it will be managed by this
679 // top level manager. Set up analysis resolver to connect them.
680 PMDataManager *DM = getAsPMDataManager();
681 AnalysisResolver *AR = new AnalysisResolver(*DM);
683 DM->initializeAnalysisImpl(P);
684 addImmutablePass(IP);
685 DM->recordAvailableAnalysis(IP);
689 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
690 Pass *PP = P->createPrinterPass(
691 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
692 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
695 // Add the requested pass to the best available pass manager.
696 P->assignPassManager(activeStack, getTopLevelPassManagerType());
698 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
699 Pass *PP = P->createPrinterPass(
700 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
701 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
705 /// Find the pass that implements Analysis AID. Search immutable
706 /// passes and all pass managers. If desired pass is not found
707 /// then return NULL.
708 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
709 // For immutable passes we have a direct mapping from ID to pass, so check
711 if (Pass *P = ImmutablePassMap.lookup(AID))
714 // Check pass managers
715 for (PMDataManager *PassManager : PassManagers)
716 if (Pass *P = PassManager->findAnalysisPass(AID, false))
719 // Check other pass managers
720 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
721 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
727 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
728 const PassInfo *&PI = AnalysisPassInfos[AID];
730 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
732 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
733 "The pass info pointer changed for an analysis ID!");
738 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
740 ImmutablePasses.push_back(P);
742 // Add this pass to the map from its analysis ID. We clobber any prior runs
743 // of the pass in the map so that the last one added is the one found when
745 AnalysisID AID = P->getPassID();
746 ImmutablePassMap[AID] = P;
748 // Also add any interfaces implemented by the immutable pass to the map for
750 const PassInfo *PassInf = findAnalysisPassInfo(AID);
751 assert(PassInf && "Expected all immutable passes to be initialized");
752 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
753 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
756 // Print passes managed by this top level manager.
757 void PMTopLevelManager::dumpPasses() const {
759 if (PassDebugging < Structure)
762 // Print out the immutable passes
763 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
764 ImmutablePasses[i]->dumpPassStructure(0);
767 // Every class that derives from PMDataManager also derives from Pass
768 // (sometimes indirectly), but there's no inheritance relationship
769 // between PMDataManager and Pass, so we have to getAsPass to get
770 // from a PMDataManager* to a Pass*.
771 for (PMDataManager *Manager : PassManagers)
772 Manager->getAsPass()->dumpPassStructure(1);
775 void PMTopLevelManager::dumpArguments() const {
777 if (PassDebugging < Arguments)
780 dbgs() << "Pass Arguments: ";
781 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
782 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
783 if (const PassInfo *PI = findAnalysisPassInfo((*I)->getPassID())) {
784 assert(PI && "Expected all immutable passes to be initialized");
785 if (!PI->isAnalysisGroup())
786 dbgs() << " -" << PI->getPassArgument();
788 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
789 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
790 (*I)->dumpPassArguments();
794 void PMTopLevelManager::initializeAllAnalysisInfo() {
795 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
796 E = PassManagers.end(); I != E; ++I)
797 (*I)->initializeAnalysisInfo();
799 // Initailize other pass managers
800 for (SmallVectorImpl<PMDataManager *>::iterator
801 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
803 (*I)->initializeAnalysisInfo();
805 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
806 DME = LastUser.end(); DMI != DME; ++DMI) {
807 SmallPtrSet<Pass *, 8> &L = InversedLastUser[DMI->second];
808 L.insert(DMI->first);
813 PMTopLevelManager::~PMTopLevelManager() {
814 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
815 E = PassManagers.end(); I != E; ++I)
818 for (SmallVectorImpl<ImmutablePass *>::iterator
819 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
823 //===----------------------------------------------------------------------===//
824 // PMDataManager implementation
826 /// Augement AvailableAnalysis by adding analysis made available by pass P.
827 void PMDataManager::recordAvailableAnalysis(Pass *P) {
828 AnalysisID PI = P->getPassID();
830 AvailableAnalysis[PI] = P;
832 assert(!AvailableAnalysis.empty());
834 // This pass is the current implementation of all of the interfaces it
835 // implements as well.
836 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
838 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
839 for (unsigned i = 0, e = II.size(); i != e; ++i)
840 AvailableAnalysis[II[i]->getTypeInfo()] = P;
843 // Return true if P preserves high level analysis used by other
844 // passes managed by this manager
845 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
846 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
847 if (AnUsage->getPreservesAll())
850 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
851 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
852 E = HigherLevelAnalysis.end(); I != E; ++I) {
854 if (P1->getAsImmutablePass() == nullptr &&
855 std::find(PreservedSet.begin(), PreservedSet.end(),
864 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
865 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
866 // Don't do this unless assertions are enabled.
870 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
871 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
873 // Verify preserved analysis
874 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
875 E = PreservedSet.end(); I != E; ++I) {
877 if (Pass *AP = findAnalysisPass(AID, true)) {
878 TimeRegion PassTimer(getPassTimer(AP));
879 AP->verifyAnalysis();
884 /// Remove Analysis not preserved by Pass P
885 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
886 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
887 if (AnUsage->getPreservesAll())
890 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
891 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
892 E = AvailableAnalysis.end(); I != E; ) {
893 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
894 if (Info->second->getAsImmutablePass() == nullptr &&
895 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
896 PreservedSet.end()) {
897 // Remove this analysis
898 if (PassDebugging >= Details) {
899 Pass *S = Info->second;
900 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
901 dbgs() << S->getPassName() << "'\n";
903 AvailableAnalysis.erase(Info);
907 // Check inherited analysis also. If P is not preserving analysis
908 // provided by parent manager then remove it here.
909 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
911 if (!InheritedAnalysis[Index])
914 for (DenseMap<AnalysisID, Pass*>::iterator
915 I = InheritedAnalysis[Index]->begin(),
916 E = InheritedAnalysis[Index]->end(); I != E; ) {
917 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
918 if (Info->second->getAsImmutablePass() == nullptr &&
919 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
920 PreservedSet.end()) {
921 // Remove this analysis
922 if (PassDebugging >= Details) {
923 Pass *S = Info->second;
924 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
925 dbgs() << S->getPassName() << "'\n";
927 InheritedAnalysis[Index]->erase(Info);
933 /// Remove analysis passes that are not used any longer
934 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
935 enum PassDebuggingString DBG_STR) {
937 SmallVector<Pass *, 12> DeadPasses;
939 // If this is a on the fly manager then it does not have TPM.
943 TPM->collectLastUses(DeadPasses, P);
945 if (PassDebugging >= Details && !DeadPasses.empty()) {
946 dbgs() << " -*- '" << P->getPassName();
947 dbgs() << "' is the last user of following pass instances.";
948 dbgs() << " Free these instances\n";
951 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
952 E = DeadPasses.end(); I != E; ++I)
953 freePass(*I, Msg, DBG_STR);
956 void PMDataManager::freePass(Pass *P, StringRef Msg,
957 enum PassDebuggingString DBG_STR) {
958 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
961 // If the pass crashes releasing memory, remember this.
962 PassManagerPrettyStackEntry X(P);
963 TimeRegion PassTimer(getPassTimer(P));
968 AnalysisID PI = P->getPassID();
969 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
970 // Remove the pass itself (if it is not already removed).
971 AvailableAnalysis.erase(PI);
973 // Remove all interfaces this pass implements, for which it is also
974 // listed as the available implementation.
975 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
976 for (unsigned i = 0, e = II.size(); i != e; ++i) {
977 DenseMap<AnalysisID, Pass*>::iterator Pos =
978 AvailableAnalysis.find(II[i]->getTypeInfo());
979 if (Pos != AvailableAnalysis.end() && Pos->second == P)
980 AvailableAnalysis.erase(Pos);
985 /// Add pass P into the PassVector. Update
986 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
987 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
988 // This manager is going to manage pass P. Set up analysis resolver
990 AnalysisResolver *AR = new AnalysisResolver(*this);
993 // If a FunctionPass F is the last user of ModulePass info M
994 // then the F's manager, not F, records itself as a last user of M.
995 SmallVector<Pass *, 12> TransferLastUses;
997 if (!ProcessAnalysis) {
999 PassVector.push_back(P);
1003 // At the moment, this pass is the last user of all required passes.
1004 SmallVector<Pass *, 12> LastUses;
1005 SmallVector<Pass *, 8> UsedPasses;
1006 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1008 unsigned PDepth = this->getDepth();
1010 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1011 for (Pass *PUsed : UsedPasses) {
1012 unsigned RDepth = 0;
1014 assert(PUsed->getResolver() && "Analysis Resolver is not set");
1015 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1016 RDepth = DM.getDepth();
1018 if (PDepth == RDepth)
1019 LastUses.push_back(PUsed);
1020 else if (PDepth > RDepth) {
1021 // Let the parent claim responsibility of last use
1022 TransferLastUses.push_back(PUsed);
1023 // Keep track of higher level analysis used by this manager.
1024 HigherLevelAnalysis.push_back(PUsed);
1026 llvm_unreachable("Unable to accommodate Used Pass");
1029 // Set P as P's last user until someone starts using P.
1030 // However, if P is a Pass Manager then it does not need
1031 // to record its last user.
1032 if (!P->getAsPMDataManager())
1033 LastUses.push_back(P);
1034 TPM->setLastUser(LastUses, P);
1036 if (!TransferLastUses.empty()) {
1037 Pass *My_PM = getAsPass();
1038 TPM->setLastUser(TransferLastUses, My_PM);
1039 TransferLastUses.clear();
1042 // Now, take care of required analyses that are not available.
1043 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1044 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1045 Pass *AnalysisPass = PI->createPass();
1046 this->addLowerLevelRequiredPass(P, AnalysisPass);
1049 // Take a note of analysis required and made available by this pass.
1050 // Remove the analysis not preserved by this pass
1051 removeNotPreservedAnalysis(P);
1052 recordAvailableAnalysis(P);
1055 PassVector.push_back(P);
1059 /// Populate UP with analysis pass that are used or required by
1060 /// pass P and are available. Populate RP_NotAvail with analysis
1061 /// pass that are required by pass P but are not available.
1062 void PMDataManager::collectRequiredAndUsedAnalyses(
1063 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1065 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1067 for (const auto &UsedID : AnUsage->getUsedSet())
1068 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1069 UP.push_back(AnalysisPass);
1071 for (const auto &RequiredID : AnUsage->getRequiredSet())
1072 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1073 UP.push_back(AnalysisPass);
1075 RP_NotAvail.push_back(RequiredID);
1077 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1078 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1079 UP.push_back(AnalysisPass);
1081 RP_NotAvail.push_back(RequiredID);
1084 // All Required analyses should be available to the pass as it runs! Here
1085 // we fill in the AnalysisImpls member of the pass so that it can
1086 // successfully use the getAnalysis() method to retrieve the
1087 // implementations it needs.
1089 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1090 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1092 for (AnalysisUsage::VectorType::const_iterator
1093 I = AnUsage->getRequiredSet().begin(),
1094 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1095 Pass *Impl = findAnalysisPass(*I, true);
1097 // This may be analysis pass that is initialized on the fly.
1098 // If that is not the case then it will raise an assert when it is used.
1100 AnalysisResolver *AR = P->getResolver();
1101 assert(AR && "Analysis Resolver is not set");
1102 AR->addAnalysisImplsPair(*I, Impl);
1106 /// Find the pass that implements Analysis AID. If desired pass is not found
1107 /// then return NULL.
1108 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1110 // Check if AvailableAnalysis map has one entry.
1111 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1113 if (I != AvailableAnalysis.end())
1116 // Search Parents through TopLevelManager
1118 return TPM->findAnalysisPass(AID);
1123 // Print list of passes that are last used by P.
1124 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1126 SmallVector<Pass *, 12> LUses;
1128 // If this is a on the fly manager then it does not have TPM.
1132 TPM->collectLastUses(LUses, P);
1134 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1135 E = LUses.end(); I != E; ++I) {
1136 dbgs() << "--" << std::string(Offset*2, ' ');
1137 (*I)->dumpPassStructure(0);
1141 void PMDataManager::dumpPassArguments() const {
1142 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1143 E = PassVector.end(); I != E; ++I) {
1144 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1145 PMD->dumpPassArguments();
1147 if (const PassInfo *PI =
1148 TPM->findAnalysisPassInfo((*I)->getPassID()))
1149 if (!PI->isAnalysisGroup())
1150 dbgs() << " -" << PI->getPassArgument();
1154 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1155 enum PassDebuggingString S2,
1157 if (PassDebugging < Executions)
1159 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1160 << std::string(getDepth() * 2 + 1, ' ');
1163 dbgs() << "Executing Pass '" << P->getPassName();
1165 case MODIFICATION_MSG:
1166 dbgs() << "Made Modification '" << P->getPassName();
1169 dbgs() << " Freeing Pass '" << P->getPassName();
1175 case ON_BASICBLOCK_MSG:
1176 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1178 case ON_FUNCTION_MSG:
1179 dbgs() << "' on Function '" << Msg << "'...\n";
1182 dbgs() << "' on Module '" << Msg << "'...\n";
1185 dbgs() << "' on Region '" << Msg << "'...\n";
1188 dbgs() << "' on Loop '" << Msg << "'...\n";
1191 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1198 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1199 if (PassDebugging < Details)
1202 AnalysisUsage analysisUsage;
1203 P->getAnalysisUsage(analysisUsage);
1204 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1207 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1208 if (PassDebugging < Details)
1211 AnalysisUsage analysisUsage;
1212 P->getAnalysisUsage(analysisUsage);
1213 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1216 void PMDataManager::dumpUsedSet(const Pass *P) const {
1217 if (PassDebugging < Details)
1220 AnalysisUsage analysisUsage;
1221 P->getAnalysisUsage(analysisUsage);
1222 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1225 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1226 const AnalysisUsage::VectorType &Set) const {
1227 assert(PassDebugging >= Details);
1230 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1231 for (unsigned i = 0; i != Set.size(); ++i) {
1232 if (i) dbgs() << ',';
1233 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1235 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1237 dbgs() << " Uninitialized Pass";
1240 dbgs() << ' ' << PInf->getPassName();
1245 /// Add RequiredPass into list of lower level passes required by pass P.
1246 /// RequiredPass is run on the fly by Pass Manager when P requests it
1247 /// through getAnalysis interface.
1248 /// This should be handled by specific pass manager.
1249 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1251 TPM->dumpArguments();
1255 // Module Level pass may required Function Level analysis info
1256 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1257 // to provide this on demand. In that case, in Pass manager terminology,
1258 // module level pass is requiring lower level analysis info managed by
1259 // lower level pass manager.
1261 // When Pass manager is not able to order required analysis info, Pass manager
1262 // checks whether any lower level manager will be able to provide this
1263 // analysis info on demand or not.
1265 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1266 dbgs() << "' required by '" << P->getPassName() << "'\n";
1268 llvm_unreachable("Unable to schedule pass");
1271 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1272 llvm_unreachable("Unable to find on the fly pass");
1276 PMDataManager::~PMDataManager() {
1277 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1278 E = PassVector.end(); I != E; ++I)
1282 //===----------------------------------------------------------------------===//
1283 // NOTE: Is this the right place to define this method ?
1284 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1285 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1286 return PM.findAnalysisPass(ID, dir);
1289 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1291 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1294 //===----------------------------------------------------------------------===//
1295 // BBPassManager implementation
1297 /// Execute all of the passes scheduled for execution by invoking
1298 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1299 /// the function, and if so, return true.
1300 bool BBPassManager::runOnFunction(Function &F) {
1301 if (F.isDeclaration())
1304 bool Changed = doInitialization(F);
1306 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1307 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1308 BasicBlockPass *BP = getContainedPass(Index);
1309 bool LocalChanged = false;
1311 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1312 dumpRequiredSet(BP);
1314 initializeAnalysisImpl(BP);
1317 // If the pass crashes, remember this.
1318 PassManagerPrettyStackEntry X(BP, *I);
1319 TimeRegion PassTimer(getPassTimer(BP));
1321 LocalChanged |= BP->runOnBasicBlock(*I);
1324 Changed |= LocalChanged;
1326 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1328 dumpPreservedSet(BP);
1331 verifyPreservedAnalysis(BP);
1332 removeNotPreservedAnalysis(BP);
1333 recordAvailableAnalysis(BP);
1334 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1337 return doFinalization(F) || Changed;
1340 // Implement doInitialization and doFinalization
1341 bool BBPassManager::doInitialization(Module &M) {
1342 bool Changed = false;
1344 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1345 Changed |= getContainedPass(Index)->doInitialization(M);
1350 bool BBPassManager::doFinalization(Module &M) {
1351 bool Changed = false;
1353 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1354 Changed |= getContainedPass(Index)->doFinalization(M);
1359 bool BBPassManager::doInitialization(Function &F) {
1360 bool Changed = false;
1362 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1363 BasicBlockPass *BP = getContainedPass(Index);
1364 Changed |= BP->doInitialization(F);
1370 bool BBPassManager::doFinalization(Function &F) {
1371 bool Changed = false;
1373 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1374 BasicBlockPass *BP = getContainedPass(Index);
1375 Changed |= BP->doFinalization(F);
1382 //===----------------------------------------------------------------------===//
1383 // FunctionPassManager implementation
1385 /// Create new Function pass manager
1386 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1387 FPM = new FunctionPassManagerImpl();
1388 // FPM is the top level manager.
1389 FPM->setTopLevelManager(FPM);
1391 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1392 FPM->setResolver(AR);
1395 FunctionPassManager::~FunctionPassManager() {
1399 void FunctionPassManager::add(Pass *P) {
1403 /// run - Execute all of the passes scheduled for execution. Keep
1404 /// track of whether any of the passes modifies the function, and if
1405 /// so, return true.
1407 bool FunctionPassManager::run(Function &F) {
1408 if (std::error_code EC = F.materialize())
1409 report_fatal_error("Error reading bitcode file: " + EC.message());
1414 /// doInitialization - Run all of the initializers for the function passes.
1416 bool FunctionPassManager::doInitialization() {
1417 return FPM->doInitialization(*M);
1420 /// doFinalization - Run all of the finalizers for the function passes.
1422 bool FunctionPassManager::doFinalization() {
1423 return FPM->doFinalization(*M);
1426 //===----------------------------------------------------------------------===//
1427 // FunctionPassManagerImpl implementation
1429 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1430 bool Changed = false;
1435 for (ImmutablePass *ImPass : getImmutablePasses())
1436 Changed |= ImPass->doInitialization(M);
1438 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1439 Changed |= getContainedManager(Index)->doInitialization(M);
1444 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1445 bool Changed = false;
1447 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1448 Changed |= getContainedManager(Index)->doFinalization(M);
1450 for (ImmutablePass *ImPass : getImmutablePasses())
1451 Changed |= ImPass->doFinalization(M);
1456 /// cleanup - After running all passes, clean up pass manager cache.
1457 void FPPassManager::cleanup() {
1458 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1459 FunctionPass *FP = getContainedPass(Index);
1460 AnalysisResolver *AR = FP->getResolver();
1461 assert(AR && "Analysis Resolver is not set");
1462 AR->clearAnalysisImpls();
1466 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1469 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1470 FPPassManager *FPPM = getContainedManager(Index);
1471 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1472 FPPM->getContainedPass(Index)->releaseMemory();
1478 // Execute all the passes managed by this top level manager.
1479 // Return true if any function is modified by a pass.
1480 bool FunctionPassManagerImpl::run(Function &F) {
1481 bool Changed = false;
1482 TimingInfo::createTheTimeInfo();
1484 initializeAllAnalysisInfo();
1485 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1486 Changed |= getContainedManager(Index)->runOnFunction(F);
1487 F.getContext().yield();
1490 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1491 getContainedManager(Index)->cleanup();
1497 //===----------------------------------------------------------------------===//
1498 // FPPassManager implementation
1500 char FPPassManager::ID = 0;
1501 /// Print passes managed by this manager
1502 void FPPassManager::dumpPassStructure(unsigned Offset) {
1503 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1504 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1505 FunctionPass *FP = getContainedPass(Index);
1506 FP->dumpPassStructure(Offset + 1);
1507 dumpLastUses(FP, Offset+1);
1512 /// Execute all of the passes scheduled for execution by invoking
1513 /// runOnFunction method. Keep track of whether any of the passes modifies
1514 /// the function, and if so, return true.
1515 bool FPPassManager::runOnFunction(Function &F) {
1516 if (F.isDeclaration())
1519 bool Changed = false;
1521 // Collect inherited analysis from Module level pass manager.
1522 populateInheritedAnalysis(TPM->activeStack);
1524 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1525 FunctionPass *FP = getContainedPass(Index);
1526 bool LocalChanged = false;
1528 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1529 dumpRequiredSet(FP);
1531 initializeAnalysisImpl(FP);
1534 PassManagerPrettyStackEntry X(FP, F);
1535 TimeRegion PassTimer(getPassTimer(FP));
1537 LocalChanged |= FP->runOnFunction(F);
1540 Changed |= LocalChanged;
1542 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1543 dumpPreservedSet(FP);
1546 verifyPreservedAnalysis(FP);
1547 removeNotPreservedAnalysis(FP);
1548 recordAvailableAnalysis(FP);
1549 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1554 bool FPPassManager::runOnModule(Module &M) {
1555 bool Changed = false;
1557 for (Function &F : M)
1558 Changed |= runOnFunction(F);
1563 bool FPPassManager::doInitialization(Module &M) {
1564 bool Changed = false;
1566 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1567 Changed |= getContainedPass(Index)->doInitialization(M);
1572 bool FPPassManager::doFinalization(Module &M) {
1573 bool Changed = false;
1575 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1576 Changed |= getContainedPass(Index)->doFinalization(M);
1581 //===----------------------------------------------------------------------===//
1582 // MPPassManager implementation
1584 /// Execute all of the passes scheduled for execution by invoking
1585 /// runOnModule method. Keep track of whether any of the passes modifies
1586 /// the module, and if so, return true.
1588 MPPassManager::runOnModule(Module &M) {
1589 bool Changed = false;
1591 // Initialize on-the-fly passes
1592 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1593 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1594 Changed |= FPP->doInitialization(M);
1597 // Initialize module passes
1598 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1599 Changed |= getContainedPass(Index)->doInitialization(M);
1601 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1602 ModulePass *MP = getContainedPass(Index);
1603 bool LocalChanged = false;
1605 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1606 dumpRequiredSet(MP);
1608 initializeAnalysisImpl(MP);
1611 PassManagerPrettyStackEntry X(MP, M);
1612 TimeRegion PassTimer(getPassTimer(MP));
1614 LocalChanged |= MP->runOnModule(M);
1617 Changed |= LocalChanged;
1619 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1620 M.getModuleIdentifier());
1621 dumpPreservedSet(MP);
1624 verifyPreservedAnalysis(MP);
1625 removeNotPreservedAnalysis(MP);
1626 recordAvailableAnalysis(MP);
1627 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1630 // Finalize module passes
1631 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1632 Changed |= getContainedPass(Index)->doFinalization(M);
1634 // Finalize on-the-fly passes
1635 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1636 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1637 // We don't know when is the last time an on-the-fly pass is run,
1638 // so we need to releaseMemory / finalize here
1639 FPP->releaseMemoryOnTheFly();
1640 Changed |= FPP->doFinalization(M);
1646 /// Add RequiredPass into list of lower level passes required by pass P.
1647 /// RequiredPass is run on the fly by Pass Manager when P requests it
1648 /// through getAnalysis interface.
1649 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1650 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1651 "Unable to handle Pass that requires lower level Analysis pass");
1652 assert((P->getPotentialPassManagerType() <
1653 RequiredPass->getPotentialPassManagerType()) &&
1654 "Unable to handle Pass that requires lower level Analysis pass");
1658 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1660 FPP = new FunctionPassManagerImpl();
1661 // FPP is the top level manager.
1662 FPP->setTopLevelManager(FPP);
1664 OnTheFlyManagers[P] = FPP;
1666 const PassInfo *RequiredPassPI =
1667 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1669 Pass *FoundPass = nullptr;
1670 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1672 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1675 FoundPass = RequiredPass;
1676 // This should be guaranteed to add RequiredPass to the passmanager given
1677 // that we checked for an available analysis above.
1678 FPP->add(RequiredPass);
1680 // Register P as the last user of FoundPass or RequiredPass.
1681 SmallVector<Pass *, 1> LU;
1682 LU.push_back(FoundPass);
1683 FPP->setLastUser(LU, P);
1686 /// Return function pass corresponding to PassInfo PI, that is
1687 /// required by module pass MP. Instantiate analysis pass, by using
1688 /// its runOnFunction() for function F.
1689 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1690 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1691 assert(FPP && "Unable to find on the fly pass");
1693 FPP->releaseMemoryOnTheFly();
1695 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1699 //===----------------------------------------------------------------------===//
1700 // PassManagerImpl implementation
1703 /// run - Execute all of the passes scheduled for execution. Keep track of
1704 /// whether any of the passes modifies the module, and if so, return true.
1705 bool PassManagerImpl::run(Module &M) {
1706 bool Changed = false;
1707 TimingInfo::createTheTimeInfo();
1712 for (ImmutablePass *ImPass : getImmutablePasses())
1713 Changed |= ImPass->doInitialization(M);
1715 initializeAllAnalysisInfo();
1716 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1717 Changed |= getContainedManager(Index)->runOnModule(M);
1718 M.getContext().yield();
1721 for (ImmutablePass *ImPass : getImmutablePasses())
1722 Changed |= ImPass->doFinalization(M);
1727 //===----------------------------------------------------------------------===//
1728 // PassManager implementation
1730 /// Create new pass manager
1731 PassManager::PassManager() {
1732 PM = new PassManagerImpl();
1733 // PM is the top level manager
1734 PM->setTopLevelManager(PM);
1737 PassManager::~PassManager() {
1741 void PassManager::add(Pass *P) {
1745 /// run - Execute all of the passes scheduled for execution. Keep track of
1746 /// whether any of the passes modifies the module, and if so, return true.
1747 bool PassManager::run(Module &M) {
1751 //===----------------------------------------------------------------------===//
1752 // TimingInfo implementation
1754 bool llvm::TimePassesIsEnabled = false;
1755 static cl::opt<bool,true>
1756 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1757 cl::desc("Time each pass, printing elapsed time for each on exit"));
1759 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1760 // a non-null value (if the -time-passes option is enabled) or it leaves it
1761 // null. It may be called multiple times.
1762 void TimingInfo::createTheTimeInfo() {
1763 if (!TimePassesIsEnabled || TheTimeInfo) return;
1765 // Constructed the first time this is called, iff -time-passes is enabled.
1766 // This guarantees that the object will be constructed before static globals,
1767 // thus it will be destroyed before them.
1768 static ManagedStatic<TimingInfo> TTI;
1769 TheTimeInfo = &*TTI;
1772 /// If TimingInfo is enabled then start pass timer.
1773 Timer *llvm::getPassTimer(Pass *P) {
1775 return TheTimeInfo->getPassTimer(P);
1779 //===----------------------------------------------------------------------===//
1780 // PMStack implementation
1783 // Pop Pass Manager from the stack and clear its analysis info.
1784 void PMStack::pop() {
1786 PMDataManager *Top = this->top();
1787 Top->initializeAnalysisInfo();
1792 // Push PM on the stack and set its top level manager.
1793 void PMStack::push(PMDataManager *PM) {
1794 assert(PM && "Unable to push. Pass Manager expected");
1795 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1797 if (!this->empty()) {
1798 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1799 && "pushing bad pass manager to PMStack");
1800 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1802 assert(TPM && "Unable to find top level manager");
1803 TPM->addIndirectPassManager(PM);
1804 PM->setTopLevelManager(TPM);
1805 PM->setDepth(this->top()->getDepth()+1);
1807 assert((PM->getPassManagerType() == PMT_ModulePassManager
1808 || PM->getPassManagerType() == PMT_FunctionPassManager)
1809 && "pushing bad pass manager to PMStack");
1816 // Dump content of the pass manager stack.
1817 void PMStack::dump() const {
1818 for (PMDataManager *Manager : S)
1819 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1825 /// Find appropriate Module Pass Manager in the PM Stack and
1826 /// add self into that manager.
1827 void ModulePass::assignPassManager(PMStack &PMS,
1828 PassManagerType PreferredType) {
1829 // Find Module Pass Manager
1830 while (!PMS.empty()) {
1831 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1832 if (TopPMType == PreferredType)
1833 break; // We found desired pass manager
1834 else if (TopPMType > PMT_ModulePassManager)
1835 PMS.pop(); // Pop children pass managers
1839 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1840 PMS.top()->add(this);
1843 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1844 /// in the PM Stack and add self into that manager.
1845 void FunctionPass::assignPassManager(PMStack &PMS,
1846 PassManagerType PreferredType) {
1848 // Find Function Pass Manager
1849 while (!PMS.empty()) {
1850 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1856 // Create new Function Pass Manager if needed.
1858 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1859 FPP = (FPPassManager *)PMS.top();
1861 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1862 PMDataManager *PMD = PMS.top();
1864 // [1] Create new Function Pass Manager
1865 FPP = new FPPassManager();
1866 FPP->populateInheritedAnalysis(PMS);
1868 // [2] Set up new manager's top level manager
1869 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1870 TPM->addIndirectPassManager(FPP);
1872 // [3] Assign manager to manage this new manager. This may create
1873 // and push new managers into PMS
1874 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1876 // [4] Push new manager into PMS
1880 // Assign FPP as the manager of this pass.
1884 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1885 /// in the PM Stack and add self into that manager.
1886 void BasicBlockPass::assignPassManager(PMStack &PMS,
1887 PassManagerType PreferredType) {
1890 // Basic Pass Manager is a leaf pass manager. It does not handle
1891 // any other pass manager.
1893 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1894 BBP = (BBPassManager *)PMS.top();
1896 // If leaf manager is not Basic Block Pass manager then create new
1897 // basic Block Pass manager.
1898 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1899 PMDataManager *PMD = PMS.top();
1901 // [1] Create new Basic Block Manager
1902 BBP = new BBPassManager();
1904 // [2] Set up new manager's top level manager
1905 // Basic Block Pass Manager does not live by itself
1906 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1907 TPM->addIndirectPassManager(BBP);
1909 // [3] Assign manager to manage this new manager. This may create
1910 // and push new managers into PMS
1911 BBP->assignPassManager(PMS, PreferredType);
1913 // [4] Push new manager into PMS
1917 // Assign BBP as the manager of this pass.
1921 PassManagerBase::~PassManagerBase() {}