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 (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
92 const llvm::PassInfo *PassInf = PassesToPrint[i];
94 if (PassInf->getPassArgument() == PI->getPassArgument()) {
101 /// This is a utility to check whether a pass should have IR dumped
103 static bool ShouldPrintBeforePass(const PassInfo *PI) {
104 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
107 /// This is a utility to check whether a pass should have IR dumped
109 static bool ShouldPrintAfterPass(const PassInfo *PI) {
110 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
113 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
114 /// or higher is specified.
115 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
116 return PassDebugging >= Executions;
122 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
124 OS << "Releasing pass '";
126 OS << "Running pass '";
128 OS << P->getPassName() << "'";
131 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
140 if (isa<Function>(V))
142 else if (isa<BasicBlock>(V))
148 V->printAsOperand(OS, /*PrintTy=*/false, M);
154 //===----------------------------------------------------------------------===//
157 /// BBPassManager manages BasicBlockPass. It batches all the
158 /// pass together and sequence them to process one basic block before
159 /// processing next basic block.
160 class BBPassManager : public PMDataManager, public FunctionPass {
164 explicit BBPassManager()
165 : PMDataManager(), FunctionPass(ID) {}
167 /// Execute all of the passes scheduled for execution. Keep track of
168 /// whether any of the passes modifies the function, and if so, return true.
169 bool runOnFunction(Function &F) override;
171 /// Pass Manager itself does not invalidate any analysis info.
172 void getAnalysisUsage(AnalysisUsage &Info) const override {
173 Info.setPreservesAll();
176 bool doInitialization(Module &M) override;
177 bool doInitialization(Function &F);
178 bool doFinalization(Module &M) override;
179 bool doFinalization(Function &F);
181 PMDataManager *getAsPMDataManager() override { return this; }
182 Pass *getAsPass() override { return this; }
184 const char *getPassName() const override {
185 return "BasicBlock Pass Manager";
188 // Print passes managed by this manager
189 void dumpPassStructure(unsigned Offset) override {
190 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
191 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
192 BasicBlockPass *BP = getContainedPass(Index);
193 BP->dumpPassStructure(Offset + 1);
194 dumpLastUses(BP, Offset+1);
198 BasicBlockPass *getContainedPass(unsigned N) {
199 assert(N < PassVector.size() && "Pass number out of range!");
200 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
204 PassManagerType getPassManagerType() const override {
205 return PMT_BasicBlockPassManager;
209 char BBPassManager::ID = 0;
210 } // End anonymous namespace
214 //===----------------------------------------------------------------------===//
215 // FunctionPassManagerImpl
217 /// FunctionPassManagerImpl manages FPPassManagers
218 class FunctionPassManagerImpl : public Pass,
219 public PMDataManager,
220 public PMTopLevelManager {
221 virtual void anchor();
226 explicit FunctionPassManagerImpl() :
227 Pass(PT_PassManager, ID), PMDataManager(),
228 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
230 /// \copydoc FunctionPassManager::add()
235 /// createPrinterPass - Get a function printer pass.
236 Pass *createPrinterPass(raw_ostream &O,
237 const std::string &Banner) const override {
238 return createPrintFunctionPass(O, Banner);
241 // Prepare for running an on the fly pass, freeing memory if needed
242 // from a previous run.
243 void releaseMemoryOnTheFly();
245 /// run - Execute all of the passes scheduled for execution. Keep track of
246 /// whether any of the passes modifies the module, and if so, return true.
247 bool run(Function &F);
249 /// doInitialization - Run all of the initializers for the function passes.
251 bool doInitialization(Module &M) override;
253 /// doFinalization - Run all of the finalizers for the function passes.
255 bool doFinalization(Module &M) override;
258 PMDataManager *getAsPMDataManager() override { return this; }
259 Pass *getAsPass() override { return this; }
260 PassManagerType getTopLevelPassManagerType() override {
261 return PMT_FunctionPassManager;
264 /// Pass Manager itself does not invalidate any analysis info.
265 void getAnalysisUsage(AnalysisUsage &Info) const override {
266 Info.setPreservesAll();
269 FPPassManager *getContainedManager(unsigned N) {
270 assert(N < PassManagers.size() && "Pass number out of range!");
271 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
276 void FunctionPassManagerImpl::anchor() {}
278 char FunctionPassManagerImpl::ID = 0;
279 } // End of legacy namespace
280 } // End of llvm namespace
283 //===----------------------------------------------------------------------===//
286 /// MPPassManager manages ModulePasses and function pass managers.
287 /// It batches all Module passes and function pass managers together and
288 /// sequences them to process one module.
289 class MPPassManager : public Pass, public PMDataManager {
292 explicit MPPassManager() :
293 Pass(PT_PassManager, ID), PMDataManager() { }
295 // Delete on the fly managers.
296 virtual ~MPPassManager() {
297 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
298 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
300 FunctionPassManagerImpl *FPP = I->second;
305 /// createPrinterPass - Get a module printer pass.
306 Pass *createPrinterPass(raw_ostream &O,
307 const std::string &Banner) const override {
308 return createPrintModulePass(O, Banner);
311 /// run - Execute all of the passes scheduled for execution. Keep track of
312 /// whether any of the passes modifies the module, and if so, return true.
313 bool runOnModule(Module &M);
315 using llvm::Pass::doInitialization;
316 using llvm::Pass::doFinalization;
318 /// doInitialization - Run all of the initializers for the module passes.
320 bool doInitialization();
322 /// doFinalization - Run all of the finalizers for the module passes.
324 bool doFinalization();
326 /// Pass Manager itself does not invalidate any analysis info.
327 void getAnalysisUsage(AnalysisUsage &Info) const override {
328 Info.setPreservesAll();
331 /// Add RequiredPass into list of lower level passes required by pass P.
332 /// RequiredPass is run on the fly by Pass Manager when P requests it
333 /// through getAnalysis interface.
334 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
336 /// Return function pass corresponding to PassInfo PI, that is
337 /// required by module pass MP. Instantiate analysis pass, by using
338 /// its runOnFunction() for function F.
339 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
341 const char *getPassName() const override {
342 return "Module Pass Manager";
345 PMDataManager *getAsPMDataManager() override { return this; }
346 Pass *getAsPass() override { return this; }
348 // Print passes managed by this manager
349 void dumpPassStructure(unsigned Offset) override {
350 dbgs().indent(Offset*2) << "ModulePass Manager\n";
351 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
352 ModulePass *MP = getContainedPass(Index);
353 MP->dumpPassStructure(Offset + 1);
354 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
355 OnTheFlyManagers.find(MP);
356 if (I != OnTheFlyManagers.end())
357 I->second->dumpPassStructure(Offset + 2);
358 dumpLastUses(MP, Offset+1);
362 ModulePass *getContainedPass(unsigned N) {
363 assert(N < PassVector.size() && "Pass number out of range!");
364 return static_cast<ModulePass *>(PassVector[N]);
367 PassManagerType getPassManagerType() const override {
368 return PMT_ModulePassManager;
372 /// Collection of on the fly FPPassManagers. These managers manage
373 /// function passes that are required by module passes.
374 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
377 char MPPassManager::ID = 0;
378 } // End anonymous namespace
382 //===----------------------------------------------------------------------===//
386 /// PassManagerImpl manages MPPassManagers
387 class PassManagerImpl : public Pass,
388 public PMDataManager,
389 public PMTopLevelManager {
390 virtual void anchor();
394 explicit PassManagerImpl() :
395 Pass(PT_PassManager, ID), PMDataManager(),
396 PMTopLevelManager(new MPPassManager()) {}
398 /// \copydoc PassManager::add()
403 /// createPrinterPass - Get a module printer pass.
404 Pass *createPrinterPass(raw_ostream &O,
405 const std::string &Banner) const override {
406 return createPrintModulePass(O, Banner);
409 /// run - Execute all of the passes scheduled for execution. Keep track of
410 /// whether any of the passes modifies the module, and if so, return true.
413 using llvm::Pass::doInitialization;
414 using llvm::Pass::doFinalization;
416 /// doInitialization - Run all of the initializers for the module passes.
418 bool doInitialization();
420 /// doFinalization - Run all of the finalizers for the module passes.
422 bool doFinalization();
424 /// Pass Manager itself does not invalidate any analysis info.
425 void getAnalysisUsage(AnalysisUsage &Info) const override {
426 Info.setPreservesAll();
429 PMDataManager *getAsPMDataManager() override { return this; }
430 Pass *getAsPass() override { return this; }
431 PassManagerType getTopLevelPassManagerType() override {
432 return PMT_ModulePassManager;
435 MPPassManager *getContainedManager(unsigned N) {
436 assert(N < PassManagers.size() && "Pass number out of range!");
437 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
442 void PassManagerImpl::anchor() {}
444 char PassManagerImpl::ID = 0;
445 } // End of legacy namespace
446 } // End of llvm namespace
450 //===----------------------------------------------------------------------===//
451 /// TimingInfo Class - This class is used to calculate information about the
452 /// amount of time each pass takes to execute. This only happens when
453 /// -time-passes is enabled on the command line.
456 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
459 DenseMap<Pass*, Timer*> TimingData;
462 // Use 'create' member to get this.
463 TimingInfo() : TG("... Pass execution timing report ...") {}
465 // TimingDtor - Print out information about timing information
467 // Delete all of the timers, which accumulate their info into the
469 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
470 E = TimingData.end(); I != E; ++I)
472 // TimerGroup is deleted next, printing the report.
475 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
476 // to a non-null value (if the -time-passes option is enabled) or it leaves it
477 // null. It may be called multiple times.
478 static void createTheTimeInfo();
480 /// getPassTimer - Return the timer for the specified pass if it exists.
481 Timer *getPassTimer(Pass *P) {
482 if (P->getAsPMDataManager())
485 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
486 Timer *&T = TimingData[P];
488 T = new Timer(P->getPassName(), TG);
493 } // End of anon namespace
495 static TimingInfo *TheTimeInfo;
497 //===----------------------------------------------------------------------===//
498 // PMTopLevelManager implementation
500 /// Initialize top level manager. Create first pass manager.
501 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
502 PMDM->setTopLevelManager(this);
503 addPassManager(PMDM);
504 activeStack.push(PMDM);
507 /// Set pass P as the last user of the given analysis passes.
509 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
511 if (P->getResolver())
512 PDepth = P->getResolver()->getPMDataManager().getDepth();
514 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
515 E = AnalysisPasses.end(); I != E; ++I) {
522 // Update the last users of passes that are required transitive by AP.
523 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
524 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
525 SmallVector<Pass *, 12> LastUses;
526 SmallVector<Pass *, 12> LastPMUses;
527 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
528 E = IDs.end(); I != E; ++I) {
529 Pass *AnalysisPass = findAnalysisPass(*I);
530 assert(AnalysisPass && "Expected analysis pass to exist.");
531 AnalysisResolver *AR = AnalysisPass->getResolver();
532 assert(AR && "Expected analysis resolver to exist.");
533 unsigned APDepth = AR->getPMDataManager().getDepth();
535 if (PDepth == APDepth)
536 LastUses.push_back(AnalysisPass);
537 else if (PDepth > APDepth)
538 LastPMUses.push_back(AnalysisPass);
541 setLastUser(LastUses, P);
543 // If this pass has a corresponding pass manager, push higher level
544 // analysis to this pass manager.
545 if (P->getResolver())
546 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
549 // If AP is the last user of other passes then make P last user of
551 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
552 LUE = LastUser.end(); LUI != LUE; ++LUI) {
553 if (LUI->second == AP)
554 // DenseMap iterator is not invalidated here because
555 // this is just updating existing entries.
556 LastUser[LUI->first] = P;
561 /// Collect passes whose last user is P
562 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
564 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
565 InversedLastUser.find(P);
566 if (DMI == InversedLastUser.end())
569 SmallPtrSet<Pass *, 8> &LU = DMI->second;
570 for (Pass *LUP : LU) {
571 LastUses.push_back(LUP);
576 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
577 AnalysisUsage *AnUsage = nullptr;
578 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
579 if (DMI != AnUsageMap.end())
580 AnUsage = DMI->second;
582 AnUsage = new AnalysisUsage();
583 P->getAnalysisUsage(*AnUsage);
584 AnUsageMap[P] = AnUsage;
589 /// Schedule pass P for execution. Make sure that passes required by
590 /// P are run before P is run. Update analysis info maintained by
591 /// the manager. Remove dead passes. This is a recursive function.
592 void PMTopLevelManager::schedulePass(Pass *P) {
594 // TODO : Allocate function manager for this pass, other wise required set
595 // may be inserted into previous function manager
597 // Give pass a chance to prepare the stage.
598 P->preparePassManager(activeStack);
600 // If P is an analysis pass and it is available then do not
601 // generate the analysis again. Stale analysis info should not be
602 // available at this point.
603 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
604 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
609 AnalysisUsage *AnUsage = findAnalysisUsage(P);
611 bool checkAnalysis = true;
612 while (checkAnalysis) {
613 checkAnalysis = false;
615 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
616 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
617 E = RequiredSet.end(); I != E; ++I) {
619 Pass *AnalysisPass = findAnalysisPass(*I);
621 const PassInfo *PI = findAnalysisPassInfo(*I);
624 // Pass P is not in the global PassRegistry
625 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
626 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
627 dbgs() << "Required Passes:" << "\n";
628 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
629 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
630 Pass *AnalysisPass2 = findAnalysisPass(*I2);
632 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
634 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
635 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
636 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
641 assert(PI && "Expected required passes to be initialized");
642 AnalysisPass = PI->createPass();
643 if (P->getPotentialPassManagerType () ==
644 AnalysisPass->getPotentialPassManagerType())
645 // Schedule analysis pass that is managed by the same pass manager.
646 schedulePass(AnalysisPass);
647 else if (P->getPotentialPassManagerType () >
648 AnalysisPass->getPotentialPassManagerType()) {
649 // Schedule analysis pass that is managed by a new manager.
650 schedulePass(AnalysisPass);
651 // Recheck analysis passes to ensure that required analyses that
652 // are already checked are still available.
653 checkAnalysis = true;
655 // Do not schedule this analysis. Lower level analsyis
656 // passes are run on the fly.
662 // Now all required passes are available.
663 if (ImmutablePass *IP = P->getAsImmutablePass()) {
664 // P is a immutable pass and it will be managed by this
665 // top level manager. Set up analysis resolver to connect them.
666 PMDataManager *DM = getAsPMDataManager();
667 AnalysisResolver *AR = new AnalysisResolver(*DM);
669 DM->initializeAnalysisImpl(P);
670 addImmutablePass(IP);
671 DM->recordAvailableAnalysis(IP);
675 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
676 Pass *PP = P->createPrinterPass(
677 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
678 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
681 // Add the requested pass to the best available pass manager.
682 P->assignPassManager(activeStack, getTopLevelPassManagerType());
684 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
685 Pass *PP = P->createPrinterPass(
686 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
687 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
691 /// Find the pass that implements Analysis AID. Search immutable
692 /// passes and all pass managers. If desired pass is not found
693 /// then return NULL.
694 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
696 // Check pass managers
697 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
698 E = PassManagers.end(); I != E; ++I)
699 if (Pass *P = (*I)->findAnalysisPass(AID, false))
702 // Check other pass managers
703 for (SmallVectorImpl<PMDataManager *>::iterator
704 I = IndirectPassManagers.begin(),
705 E = IndirectPassManagers.end(); I != E; ++I)
706 if (Pass *P = (*I)->findAnalysisPass(AID, false))
709 // Check the immutable passes. Iterate in reverse order so that we find
710 // the most recently registered passes first.
711 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
712 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
713 AnalysisID PI = (*I)->getPassID();
717 // If Pass not found then check the interfaces implemented by Immutable Pass
718 const PassInfo *PassInf = findAnalysisPassInfo(PI);
719 assert(PassInf && "Expected all immutable passes to be initialized");
720 const std::vector<const PassInfo*> &ImmPI =
721 PassInf->getInterfacesImplemented();
722 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
723 EE = ImmPI.end(); II != EE; ++II) {
724 if ((*II)->getTypeInfo() == AID)
732 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
733 const PassInfo *&PI = AnalysisPassInfos[AID];
735 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
737 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
738 "The pass info pointer changed for an analysis ID!");
743 // Print passes managed by this top level manager.
744 void PMTopLevelManager::dumpPasses() const {
746 if (PassDebugging < Structure)
749 // Print out the immutable passes
750 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
751 ImmutablePasses[i]->dumpPassStructure(0);
754 // Every class that derives from PMDataManager also derives from Pass
755 // (sometimes indirectly), but there's no inheritance relationship
756 // between PMDataManager and Pass, so we have to getAsPass to get
757 // from a PMDataManager* to a Pass*.
758 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
759 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
760 (*I)->getAsPass()->dumpPassStructure(1);
763 void PMTopLevelManager::dumpArguments() const {
765 if (PassDebugging < Arguments)
768 dbgs() << "Pass Arguments: ";
769 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
770 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
771 if (const PassInfo *PI = findAnalysisPassInfo((*I)->getPassID())) {
772 assert(PI && "Expected all immutable passes to be initialized");
773 if (!PI->isAnalysisGroup())
774 dbgs() << " -" << PI->getPassArgument();
776 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
777 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
778 (*I)->dumpPassArguments();
782 void PMTopLevelManager::initializeAllAnalysisInfo() {
783 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
784 E = PassManagers.end(); I != E; ++I)
785 (*I)->initializeAnalysisInfo();
787 // Initailize other pass managers
788 for (SmallVectorImpl<PMDataManager *>::iterator
789 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
791 (*I)->initializeAnalysisInfo();
793 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
794 DME = LastUser.end(); DMI != DME; ++DMI) {
795 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
796 InversedLastUser.find(DMI->second);
797 if (InvDMI != InversedLastUser.end()) {
798 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
799 L.insert(DMI->first);
801 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
802 InversedLastUser[DMI->second] = L;
808 PMTopLevelManager::~PMTopLevelManager() {
809 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
810 E = PassManagers.end(); I != E; ++I)
813 for (SmallVectorImpl<ImmutablePass *>::iterator
814 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
817 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
818 DME = AnUsageMap.end(); DMI != DME; ++DMI)
822 //===----------------------------------------------------------------------===//
823 // PMDataManager implementation
825 /// Augement AvailableAnalysis by adding analysis made available by pass P.
826 void PMDataManager::recordAvailableAnalysis(Pass *P) {
827 AnalysisID PI = P->getPassID();
829 AvailableAnalysis[PI] = P;
831 assert(!AvailableAnalysis.empty());
833 // This pass is the current implementation of all of the interfaces it
834 // implements as well.
835 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
837 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
838 for (unsigned i = 0, e = II.size(); i != e; ++i)
839 AvailableAnalysis[II[i]->getTypeInfo()] = P;
842 // Return true if P preserves high level analysis used by other
843 // passes managed by this manager
844 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
845 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
846 if (AnUsage->getPreservesAll())
849 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
850 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
851 E = HigherLevelAnalysis.end(); I != E; ++I) {
853 if (P1->getAsImmutablePass() == nullptr &&
854 std::find(PreservedSet.begin(), PreservedSet.end(),
863 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
864 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
865 // Don't do this unless assertions are enabled.
869 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
870 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
872 // Verify preserved analysis
873 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
874 E = PreservedSet.end(); I != E; ++I) {
876 if (Pass *AP = findAnalysisPass(AID, true)) {
877 TimeRegion PassTimer(getPassTimer(AP));
878 AP->verifyAnalysis();
883 /// Remove Analysis not preserved by Pass P
884 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
885 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
886 if (AnUsage->getPreservesAll())
889 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
890 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
891 E = AvailableAnalysis.end(); I != E; ) {
892 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
893 if (Info->second->getAsImmutablePass() == nullptr &&
894 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
895 PreservedSet.end()) {
896 // Remove this analysis
897 if (PassDebugging >= Details) {
898 Pass *S = Info->second;
899 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
900 dbgs() << S->getPassName() << "'\n";
902 AvailableAnalysis.erase(Info);
906 // Check inherited analysis also. If P is not preserving analysis
907 // provided by parent manager then remove it here.
908 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
910 if (!InheritedAnalysis[Index])
913 for (DenseMap<AnalysisID, Pass*>::iterator
914 I = InheritedAnalysis[Index]->begin(),
915 E = InheritedAnalysis[Index]->end(); I != E; ) {
916 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
917 if (Info->second->getAsImmutablePass() == nullptr &&
918 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
919 PreservedSet.end()) {
920 // Remove this analysis
921 if (PassDebugging >= Details) {
922 Pass *S = Info->second;
923 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
924 dbgs() << S->getPassName() << "'\n";
926 InheritedAnalysis[Index]->erase(Info);
932 /// Remove analysis passes that are not used any longer
933 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
934 enum PassDebuggingString DBG_STR) {
936 SmallVector<Pass *, 12> DeadPasses;
938 // If this is a on the fly manager then it does not have TPM.
942 TPM->collectLastUses(DeadPasses, P);
944 if (PassDebugging >= Details && !DeadPasses.empty()) {
945 dbgs() << " -*- '" << P->getPassName();
946 dbgs() << "' is the last user of following pass instances.";
947 dbgs() << " Free these instances\n";
950 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
951 E = DeadPasses.end(); I != E; ++I)
952 freePass(*I, Msg, DBG_STR);
955 void PMDataManager::freePass(Pass *P, StringRef Msg,
956 enum PassDebuggingString DBG_STR) {
957 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
960 // If the pass crashes releasing memory, remember this.
961 PassManagerPrettyStackEntry X(P);
962 TimeRegion PassTimer(getPassTimer(P));
967 AnalysisID PI = P->getPassID();
968 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
969 // Remove the pass itself (if it is not already removed).
970 AvailableAnalysis.erase(PI);
972 // Remove all interfaces this pass implements, for which it is also
973 // listed as the available implementation.
974 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
975 for (unsigned i = 0, e = II.size(); i != e; ++i) {
976 DenseMap<AnalysisID, Pass*>::iterator Pos =
977 AvailableAnalysis.find(II[i]->getTypeInfo());
978 if (Pos != AvailableAnalysis.end() && Pos->second == P)
979 AvailableAnalysis.erase(Pos);
984 /// Add pass P into the PassVector. Update
985 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
986 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
987 // This manager is going to manage pass P. Set up analysis resolver
989 AnalysisResolver *AR = new AnalysisResolver(*this);
992 // If a FunctionPass F is the last user of ModulePass info M
993 // then the F's manager, not F, records itself as a last user of M.
994 SmallVector<Pass *, 12> TransferLastUses;
996 if (!ProcessAnalysis) {
998 PassVector.push_back(P);
1002 // At the moment, this pass is the last user of all required passes.
1003 SmallVector<Pass *, 12> LastUses;
1004 SmallVector<Pass *, 8> RequiredPasses;
1005 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1007 unsigned PDepth = this->getDepth();
1009 collectRequiredAnalysis(RequiredPasses,
1010 ReqAnalysisNotAvailable, P);
1011 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1012 E = RequiredPasses.end(); I != E; ++I) {
1013 Pass *PRequired = *I;
1014 unsigned RDepth = 0;
1016 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1017 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1018 RDepth = DM.getDepth();
1020 if (PDepth == RDepth)
1021 LastUses.push_back(PRequired);
1022 else if (PDepth > RDepth) {
1023 // Let the parent claim responsibility of last use
1024 TransferLastUses.push_back(PRequired);
1025 // Keep track of higher level analysis used by this manager.
1026 HigherLevelAnalysis.push_back(PRequired);
1028 llvm_unreachable("Unable to accommodate Required Pass");
1031 // Set P as P's last user until someone starts using P.
1032 // However, if P is a Pass Manager then it does not need
1033 // to record its last user.
1034 if (!P->getAsPMDataManager())
1035 LastUses.push_back(P);
1036 TPM->setLastUser(LastUses, P);
1038 if (!TransferLastUses.empty()) {
1039 Pass *My_PM = getAsPass();
1040 TPM->setLastUser(TransferLastUses, My_PM);
1041 TransferLastUses.clear();
1044 // Now, take care of required analyses that are not available.
1045 for (SmallVectorImpl<AnalysisID>::iterator
1046 I = ReqAnalysisNotAvailable.begin(),
1047 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1048 const PassInfo *PI = TPM->findAnalysisPassInfo(*I);
1049 Pass *AnalysisPass = PI->createPass();
1050 this->addLowerLevelRequiredPass(P, AnalysisPass);
1053 // Take a note of analysis required and made available by this pass.
1054 // Remove the analysis not preserved by this pass
1055 removeNotPreservedAnalysis(P);
1056 recordAvailableAnalysis(P);
1059 PassVector.push_back(P);
1063 /// Populate RP with analysis pass that are required by
1064 /// pass P and are available. Populate RP_NotAvail with analysis
1065 /// pass that are required by pass P but are not available.
1066 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1067 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1069 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1070 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1071 for (AnalysisUsage::VectorType::const_iterator
1072 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1073 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1074 RP.push_back(AnalysisPass);
1076 RP_NotAvail.push_back(*I);
1079 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1080 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1081 E = IDs.end(); I != E; ++I) {
1082 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1083 RP.push_back(AnalysisPass);
1085 RP_NotAvail.push_back(*I);
1089 // All Required analyses should be available to the pass as it runs! Here
1090 // we fill in the AnalysisImpls member of the pass so that it can
1091 // successfully use the getAnalysis() method to retrieve the
1092 // implementations it needs.
1094 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1095 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1097 for (AnalysisUsage::VectorType::const_iterator
1098 I = AnUsage->getRequiredSet().begin(),
1099 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1100 Pass *Impl = findAnalysisPass(*I, true);
1102 // This may be analysis pass that is initialized on the fly.
1103 // If that is not the case then it will raise an assert when it is used.
1105 AnalysisResolver *AR = P->getResolver();
1106 assert(AR && "Analysis Resolver is not set");
1107 AR->addAnalysisImplsPair(*I, Impl);
1111 /// Find the pass that implements Analysis AID. If desired pass is not found
1112 /// then return NULL.
1113 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1115 // Check if AvailableAnalysis map has one entry.
1116 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1118 if (I != AvailableAnalysis.end())
1121 // Search Parents through TopLevelManager
1123 return TPM->findAnalysisPass(AID);
1128 // Print list of passes that are last used by P.
1129 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1131 SmallVector<Pass *, 12> LUses;
1133 // If this is a on the fly manager then it does not have TPM.
1137 TPM->collectLastUses(LUses, P);
1139 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1140 E = LUses.end(); I != E; ++I) {
1141 dbgs() << "--" << std::string(Offset*2, ' ');
1142 (*I)->dumpPassStructure(0);
1146 void PMDataManager::dumpPassArguments() const {
1147 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1148 E = PassVector.end(); I != E; ++I) {
1149 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1150 PMD->dumpPassArguments();
1152 if (const PassInfo *PI =
1153 TPM->findAnalysisPassInfo((*I)->getPassID()))
1154 if (!PI->isAnalysisGroup())
1155 dbgs() << " -" << PI->getPassArgument();
1159 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1160 enum PassDebuggingString S2,
1162 if (PassDebugging < Executions)
1164 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1165 << std::string(getDepth() * 2 + 1, ' ');
1168 dbgs() << "Executing Pass '" << P->getPassName();
1170 case MODIFICATION_MSG:
1171 dbgs() << "Made Modification '" << P->getPassName();
1174 dbgs() << " Freeing Pass '" << P->getPassName();
1180 case ON_BASICBLOCK_MSG:
1181 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1183 case ON_FUNCTION_MSG:
1184 dbgs() << "' on Function '" << Msg << "'...\n";
1187 dbgs() << "' on Module '" << Msg << "'...\n";
1190 dbgs() << "' on Region '" << Msg << "'...\n";
1193 dbgs() << "' on Loop '" << Msg << "'...\n";
1196 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1203 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1204 if (PassDebugging < Details)
1207 AnalysisUsage analysisUsage;
1208 P->getAnalysisUsage(analysisUsage);
1209 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1212 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1213 if (PassDebugging < Details)
1216 AnalysisUsage analysisUsage;
1217 P->getAnalysisUsage(analysisUsage);
1218 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1221 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1222 const AnalysisUsage::VectorType &Set) const {
1223 assert(PassDebugging >= Details);
1226 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1227 for (unsigned i = 0; i != Set.size(); ++i) {
1228 if (i) dbgs() << ',';
1229 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1231 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1233 dbgs() << " Uninitialized Pass";
1236 dbgs() << ' ' << PInf->getPassName();
1241 /// Add RequiredPass into list of lower level passes required by pass P.
1242 /// RequiredPass is run on the fly by Pass Manager when P requests it
1243 /// through getAnalysis interface.
1244 /// This should be handled by specific pass manager.
1245 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1247 TPM->dumpArguments();
1251 // Module Level pass may required Function Level analysis info
1252 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1253 // to provide this on demand. In that case, in Pass manager terminology,
1254 // module level pass is requiring lower level analysis info managed by
1255 // lower level pass manager.
1257 // When Pass manager is not able to order required analysis info, Pass manager
1258 // checks whether any lower level manager will be able to provide this
1259 // analysis info on demand or not.
1261 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1262 dbgs() << "' required by '" << P->getPassName() << "'\n";
1264 llvm_unreachable("Unable to schedule pass");
1267 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1268 llvm_unreachable("Unable to find on the fly pass");
1272 PMDataManager::~PMDataManager() {
1273 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1274 E = PassVector.end(); I != E; ++I)
1278 //===----------------------------------------------------------------------===//
1279 // NOTE: Is this the right place to define this method ?
1280 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1281 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1282 return PM.findAnalysisPass(ID, dir);
1285 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1287 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1290 //===----------------------------------------------------------------------===//
1291 // BBPassManager implementation
1293 /// Execute all of the passes scheduled for execution by invoking
1294 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1295 /// the function, and if so, return true.
1296 bool BBPassManager::runOnFunction(Function &F) {
1297 if (F.isDeclaration())
1300 bool Changed = doInitialization(F);
1302 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1303 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1304 BasicBlockPass *BP = getContainedPass(Index);
1305 bool LocalChanged = false;
1307 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1308 dumpRequiredSet(BP);
1310 initializeAnalysisImpl(BP);
1313 // If the pass crashes, remember this.
1314 PassManagerPrettyStackEntry X(BP, *I);
1315 TimeRegion PassTimer(getPassTimer(BP));
1317 LocalChanged |= BP->runOnBasicBlock(*I);
1320 Changed |= LocalChanged;
1322 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1324 dumpPreservedSet(BP);
1326 verifyPreservedAnalysis(BP);
1327 removeNotPreservedAnalysis(BP);
1328 recordAvailableAnalysis(BP);
1329 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1332 return doFinalization(F) || Changed;
1335 // Implement doInitialization and doFinalization
1336 bool BBPassManager::doInitialization(Module &M) {
1337 bool Changed = false;
1339 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1340 Changed |= getContainedPass(Index)->doInitialization(M);
1345 bool BBPassManager::doFinalization(Module &M) {
1346 bool Changed = false;
1348 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1349 Changed |= getContainedPass(Index)->doFinalization(M);
1354 bool BBPassManager::doInitialization(Function &F) {
1355 bool Changed = false;
1357 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1358 BasicBlockPass *BP = getContainedPass(Index);
1359 Changed |= BP->doInitialization(F);
1365 bool BBPassManager::doFinalization(Function &F) {
1366 bool Changed = false;
1368 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1369 BasicBlockPass *BP = getContainedPass(Index);
1370 Changed |= BP->doFinalization(F);
1377 //===----------------------------------------------------------------------===//
1378 // FunctionPassManager implementation
1380 /// Create new Function pass manager
1381 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1382 FPM = new FunctionPassManagerImpl();
1383 // FPM is the top level manager.
1384 FPM->setTopLevelManager(FPM);
1386 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1387 FPM->setResolver(AR);
1390 FunctionPassManager::~FunctionPassManager() {
1394 void FunctionPassManager::add(Pass *P) {
1398 /// run - Execute all of the passes scheduled for execution. Keep
1399 /// track of whether any of the passes modifies the function, and if
1400 /// so, return true.
1402 bool FunctionPassManager::run(Function &F) {
1403 if (std::error_code EC = F.materialize())
1404 report_fatal_error("Error reading bitcode file: " + EC.message());
1409 /// doInitialization - Run all of the initializers for the function passes.
1411 bool FunctionPassManager::doInitialization() {
1412 return FPM->doInitialization(*M);
1415 /// doFinalization - Run all of the finalizers for the function passes.
1417 bool FunctionPassManager::doFinalization() {
1418 return FPM->doFinalization(*M);
1421 //===----------------------------------------------------------------------===//
1422 // FunctionPassManagerImpl implementation
1424 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1425 bool Changed = false;
1430 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1431 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1432 E = IPV.end(); I != E; ++I) {
1433 Changed |= (*I)->doInitialization(M);
1436 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1437 Changed |= getContainedManager(Index)->doInitialization(M);
1442 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1443 bool Changed = false;
1445 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1446 Changed |= getContainedManager(Index)->doFinalization(M);
1448 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1449 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1450 E = IPV.end(); I != E; ++I) {
1451 Changed |= (*I)->doFinalization(M);
1457 /// cleanup - After running all passes, clean up pass manager cache.
1458 void FPPassManager::cleanup() {
1459 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1460 FunctionPass *FP = getContainedPass(Index);
1461 AnalysisResolver *AR = FP->getResolver();
1462 assert(AR && "Analysis Resolver is not set");
1463 AR->clearAnalysisImpls();
1467 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1470 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1471 FPPassManager *FPPM = getContainedManager(Index);
1472 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1473 FPPM->getContainedPass(Index)->releaseMemory();
1479 // Execute all the passes managed by this top level manager.
1480 // Return true if any function is modified by a pass.
1481 bool FunctionPassManagerImpl::run(Function &F) {
1482 bool Changed = false;
1483 TimingInfo::createTheTimeInfo();
1485 initializeAllAnalysisInfo();
1486 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1487 Changed |= getContainedManager(Index)->runOnFunction(F);
1488 F.getContext().yield();
1491 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1492 getContainedManager(Index)->cleanup();
1498 //===----------------------------------------------------------------------===//
1499 // FPPassManager implementation
1501 char FPPassManager::ID = 0;
1502 /// Print passes managed by this manager
1503 void FPPassManager::dumpPassStructure(unsigned Offset) {
1504 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1505 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1506 FunctionPass *FP = getContainedPass(Index);
1507 FP->dumpPassStructure(Offset + 1);
1508 dumpLastUses(FP, Offset+1);
1513 /// Execute all of the passes scheduled for execution by invoking
1514 /// runOnFunction method. Keep track of whether any of the passes modifies
1515 /// the function, and if so, return true.
1516 bool FPPassManager::runOnFunction(Function &F) {
1517 if (F.isDeclaration())
1520 bool Changed = false;
1522 // Collect inherited analysis from Module level pass manager.
1523 populateInheritedAnalysis(TPM->activeStack);
1525 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1526 FunctionPass *FP = getContainedPass(Index);
1527 bool LocalChanged = false;
1529 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1530 dumpRequiredSet(FP);
1532 initializeAnalysisImpl(FP);
1535 PassManagerPrettyStackEntry X(FP, F);
1536 TimeRegion PassTimer(getPassTimer(FP));
1538 LocalChanged |= FP->runOnFunction(F);
1541 Changed |= LocalChanged;
1543 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1544 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 (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1558 Changed |= runOnFunction(*I);
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 (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1593 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1595 FunctionPassManagerImpl *FPP = I->second;
1596 Changed |= FPP->doInitialization(M);
1599 // Initialize module passes
1600 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1601 Changed |= getContainedPass(Index)->doInitialization(M);
1603 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1604 ModulePass *MP = getContainedPass(Index);
1605 bool LocalChanged = false;
1607 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1608 dumpRequiredSet(MP);
1610 initializeAnalysisImpl(MP);
1613 PassManagerPrettyStackEntry X(MP, M);
1614 TimeRegion PassTimer(getPassTimer(MP));
1616 LocalChanged |= MP->runOnModule(M);
1619 Changed |= LocalChanged;
1621 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1622 M.getModuleIdentifier());
1623 dumpPreservedSet(MP);
1625 verifyPreservedAnalysis(MP);
1626 removeNotPreservedAnalysis(MP);
1627 recordAvailableAnalysis(MP);
1628 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1631 // Finalize module passes
1632 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1633 Changed |= getContainedPass(Index)->doFinalization(M);
1635 // Finalize on-the-fly passes
1636 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1637 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1639 FunctionPassManagerImpl *FPP = I->second;
1640 // We don't know when is the last time an on-the-fly pass is run,
1641 // so we need to releaseMemory / finalize here
1642 FPP->releaseMemoryOnTheFly();
1643 Changed |= FPP->doFinalization(M);
1649 /// Add RequiredPass into list of lower level passes required by pass P.
1650 /// RequiredPass is run on the fly by Pass Manager when P requests it
1651 /// through getAnalysis interface.
1652 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1653 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1654 "Unable to handle Pass that requires lower level Analysis pass");
1655 assert((P->getPotentialPassManagerType() <
1656 RequiredPass->getPotentialPassManagerType()) &&
1657 "Unable to handle Pass that requires lower level Analysis pass");
1661 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1663 FPP = new FunctionPassManagerImpl();
1664 // FPP is the top level manager.
1665 FPP->setTopLevelManager(FPP);
1667 OnTheFlyManagers[P] = FPP;
1669 const PassInfo *RequiredPassPI =
1670 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1672 Pass *FoundPass = nullptr;
1673 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1675 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1678 FoundPass = RequiredPass;
1679 // This should be guaranteed to add RequiredPass to the passmanager given
1680 // that we checked for an available analysis above.
1681 FPP->add(RequiredPass);
1683 // Register P as the last user of FoundPass or RequiredPass.
1684 SmallVector<Pass *, 1> LU;
1685 LU.push_back(FoundPass);
1686 FPP->setLastUser(LU, P);
1689 /// Return function pass corresponding to PassInfo PI, that is
1690 /// required by module pass MP. Instantiate analysis pass, by using
1691 /// its runOnFunction() for function F.
1692 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1693 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1694 assert(FPP && "Unable to find on the fly pass");
1696 FPP->releaseMemoryOnTheFly();
1698 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1702 //===----------------------------------------------------------------------===//
1703 // PassManagerImpl implementation
1706 /// run - Execute all of the passes scheduled for execution. Keep track of
1707 /// whether any of the passes modifies the module, and if so, return true.
1708 bool PassManagerImpl::run(Module &M) {
1709 bool Changed = false;
1710 TimingInfo::createTheTimeInfo();
1715 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1716 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1717 E = IPV.end(); I != E; ++I) {
1718 Changed |= (*I)->doInitialization(M);
1721 initializeAllAnalysisInfo();
1722 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1723 Changed |= getContainedManager(Index)->runOnModule(M);
1724 M.getContext().yield();
1727 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1728 E = IPV.end(); I != E; ++I) {
1729 Changed |= (*I)->doFinalization(M);
1735 //===----------------------------------------------------------------------===//
1736 // PassManager implementation
1738 /// Create new pass manager
1739 PassManager::PassManager() {
1740 PM = new PassManagerImpl();
1741 // PM is the top level manager
1742 PM->setTopLevelManager(PM);
1745 PassManager::~PassManager() {
1749 void PassManager::add(Pass *P) {
1753 /// run - Execute all of the passes scheduled for execution. Keep track of
1754 /// whether any of the passes modifies the module, and if so, return true.
1755 bool PassManager::run(Module &M) {
1759 //===----------------------------------------------------------------------===//
1760 // TimingInfo implementation
1762 bool llvm::TimePassesIsEnabled = false;
1763 static cl::opt<bool,true>
1764 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1765 cl::desc("Time each pass, printing elapsed time for each on exit"));
1767 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1768 // a non-null value (if the -time-passes option is enabled) or it leaves it
1769 // null. It may be called multiple times.
1770 void TimingInfo::createTheTimeInfo() {
1771 if (!TimePassesIsEnabled || TheTimeInfo) return;
1773 // Constructed the first time this is called, iff -time-passes is enabled.
1774 // This guarantees that the object will be constructed before static globals,
1775 // thus it will be destroyed before them.
1776 static ManagedStatic<TimingInfo> TTI;
1777 TheTimeInfo = &*TTI;
1780 /// If TimingInfo is enabled then start pass timer.
1781 Timer *llvm::getPassTimer(Pass *P) {
1783 return TheTimeInfo->getPassTimer(P);
1787 //===----------------------------------------------------------------------===//
1788 // PMStack implementation
1791 // Pop Pass Manager from the stack and clear its analysis info.
1792 void PMStack::pop() {
1794 PMDataManager *Top = this->top();
1795 Top->initializeAnalysisInfo();
1800 // Push PM on the stack and set its top level manager.
1801 void PMStack::push(PMDataManager *PM) {
1802 assert(PM && "Unable to push. Pass Manager expected");
1803 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1805 if (!this->empty()) {
1806 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1807 && "pushing bad pass manager to PMStack");
1808 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1810 assert(TPM && "Unable to find top level manager");
1811 TPM->addIndirectPassManager(PM);
1812 PM->setTopLevelManager(TPM);
1813 PM->setDepth(this->top()->getDepth()+1);
1815 assert((PM->getPassManagerType() == PMT_ModulePassManager
1816 || PM->getPassManagerType() == PMT_FunctionPassManager)
1817 && "pushing bad pass manager to PMStack");
1824 // Dump content of the pass manager stack.
1825 void PMStack::dump() const {
1826 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1827 E = S.end(); I != E; ++I)
1828 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1834 /// Find appropriate Module Pass Manager in the PM Stack and
1835 /// add self into that manager.
1836 void ModulePass::assignPassManager(PMStack &PMS,
1837 PassManagerType PreferredType) {
1838 // Find Module Pass Manager
1839 while (!PMS.empty()) {
1840 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1841 if (TopPMType == PreferredType)
1842 break; // We found desired pass manager
1843 else if (TopPMType > PMT_ModulePassManager)
1844 PMS.pop(); // Pop children pass managers
1848 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1849 PMS.top()->add(this);
1852 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1853 /// in the PM Stack and add self into that manager.
1854 void FunctionPass::assignPassManager(PMStack &PMS,
1855 PassManagerType PreferredType) {
1857 // Find Function Pass Manager
1858 while (!PMS.empty()) {
1859 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1865 // Create new Function Pass Manager if needed.
1867 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1868 FPP = (FPPassManager *)PMS.top();
1870 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1871 PMDataManager *PMD = PMS.top();
1873 // [1] Create new Function Pass Manager
1874 FPP = new FPPassManager();
1875 FPP->populateInheritedAnalysis(PMS);
1877 // [2] Set up new manager's top level manager
1878 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1879 TPM->addIndirectPassManager(FPP);
1881 // [3] Assign manager to manage this new manager. This may create
1882 // and push new managers into PMS
1883 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1885 // [4] Push new manager into PMS
1889 // Assign FPP as the manager of this pass.
1893 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1894 /// in the PM Stack and add self into that manager.
1895 void BasicBlockPass::assignPassManager(PMStack &PMS,
1896 PassManagerType PreferredType) {
1899 // Basic Pass Manager is a leaf pass manager. It does not handle
1900 // any other pass manager.
1902 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1903 BBP = (BBPassManager *)PMS.top();
1905 // If leaf manager is not Basic Block Pass manager then create new
1906 // basic Block Pass manager.
1907 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1908 PMDataManager *PMD = PMS.top();
1910 // [1] Create new Basic Block Manager
1911 BBP = new BBPassManager();
1913 // [2] Set up new manager's top level manager
1914 // Basic Block Pass Manager does not live by itself
1915 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1916 TPM->addIndirectPassManager(BBP);
1918 // [3] Assign manager to manage this new manager. This may create
1919 // and push new managers into PMS
1920 BBP->assignPassManager(PMS, PreferredType);
1922 // [4] Push new manager into PMS
1926 // Assign BBP as the manager of this pass.
1930 PassManagerBase::~PassManagerBase() {}