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 /// add - Add a pass to the queue of passes to run. This passes ownership of
231 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
232 /// will be destroyed as well, so there is no need to delete the pass. This
233 /// implies that all passes MUST be allocated with 'new'.
238 /// createPrinterPass - Get a function printer pass.
239 Pass *createPrinterPass(raw_ostream &O,
240 const std::string &Banner) const override {
241 return createPrintFunctionPass(O, Banner);
244 // Prepare for running an on the fly pass, freeing memory if needed
245 // from a previous run.
246 void releaseMemoryOnTheFly();
248 /// run - Execute all of the passes scheduled for execution. Keep track of
249 /// whether any of the passes modifies the module, and if so, return true.
250 bool run(Function &F);
252 /// doInitialization - Run all of the initializers for the function passes.
254 bool doInitialization(Module &M) override;
256 /// doFinalization - Run all of the finalizers for the function passes.
258 bool doFinalization(Module &M) override;
261 PMDataManager *getAsPMDataManager() override { return this; }
262 Pass *getAsPass() override { return this; }
263 PassManagerType getTopLevelPassManagerType() override {
264 return PMT_FunctionPassManager;
267 /// Pass Manager itself does not invalidate any analysis info.
268 void getAnalysisUsage(AnalysisUsage &Info) const override {
269 Info.setPreservesAll();
272 FPPassManager *getContainedManager(unsigned N) {
273 assert(N < PassManagers.size() && "Pass number out of range!");
274 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
279 void FunctionPassManagerImpl::anchor() {}
281 char FunctionPassManagerImpl::ID = 0;
282 } // End of legacy namespace
283 } // End of llvm namespace
286 //===----------------------------------------------------------------------===//
289 /// MPPassManager manages ModulePasses and function pass managers.
290 /// It batches all Module passes and function pass managers together and
291 /// sequences them to process one module.
292 class MPPassManager : public Pass, public PMDataManager {
295 explicit MPPassManager() :
296 Pass(PT_PassManager, ID), PMDataManager() { }
298 // Delete on the fly managers.
299 virtual ~MPPassManager() {
300 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
301 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
303 FunctionPassManagerImpl *FPP = I->second;
308 /// createPrinterPass - Get a module printer pass.
309 Pass *createPrinterPass(raw_ostream &O,
310 const std::string &Banner) const override {
311 return createPrintModulePass(O, Banner);
314 /// run - Execute all of the passes scheduled for execution. Keep track of
315 /// whether any of the passes modifies the module, and if so, return true.
316 bool runOnModule(Module &M);
318 using llvm::Pass::doInitialization;
319 using llvm::Pass::doFinalization;
321 /// doInitialization - Run all of the initializers for the module passes.
323 bool doInitialization();
325 /// doFinalization - Run all of the finalizers for the module passes.
327 bool doFinalization();
329 /// Pass Manager itself does not invalidate any analysis info.
330 void getAnalysisUsage(AnalysisUsage &Info) const override {
331 Info.setPreservesAll();
334 /// Add RequiredPass into list of lower level passes required by pass P.
335 /// RequiredPass is run on the fly by Pass Manager when P requests it
336 /// through getAnalysis interface.
337 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
339 /// Return function pass corresponding to PassInfo PI, that is
340 /// required by module pass MP. Instantiate analysis pass, by using
341 /// its runOnFunction() for function F.
342 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
344 const char *getPassName() const override {
345 return "Module Pass Manager";
348 PMDataManager *getAsPMDataManager() override { return this; }
349 Pass *getAsPass() override { return this; }
351 // Print passes managed by this manager
352 void dumpPassStructure(unsigned Offset) override {
353 dbgs().indent(Offset*2) << "ModulePass Manager\n";
354 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
355 ModulePass *MP = getContainedPass(Index);
356 MP->dumpPassStructure(Offset + 1);
357 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
358 OnTheFlyManagers.find(MP);
359 if (I != OnTheFlyManagers.end())
360 I->second->dumpPassStructure(Offset + 2);
361 dumpLastUses(MP, Offset+1);
365 ModulePass *getContainedPass(unsigned N) {
366 assert(N < PassVector.size() && "Pass number out of range!");
367 return static_cast<ModulePass *>(PassVector[N]);
370 PassManagerType getPassManagerType() const override {
371 return PMT_ModulePassManager;
375 /// Collection of on the fly FPPassManagers. These managers manage
376 /// function passes that are required by module passes.
377 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
380 char MPPassManager::ID = 0;
381 } // End anonymous namespace
385 //===----------------------------------------------------------------------===//
389 /// PassManagerImpl manages MPPassManagers
390 class PassManagerImpl : public Pass,
391 public PMDataManager,
392 public PMTopLevelManager {
393 virtual void anchor();
397 explicit PassManagerImpl() :
398 Pass(PT_PassManager, ID), PMDataManager(),
399 PMTopLevelManager(new MPPassManager()) {}
401 /// add - Add a pass to the queue of passes to run. This passes ownership of
402 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
403 /// will be destroyed as well, so there is no need to delete the pass. This
404 /// implies that all passes MUST be allocated with 'new'.
409 /// createPrinterPass - Get a module printer pass.
410 Pass *createPrinterPass(raw_ostream &O,
411 const std::string &Banner) const override {
412 return createPrintModulePass(O, Banner);
415 /// run - Execute all of the passes scheduled for execution. Keep track of
416 /// whether any of the passes modifies the module, and if so, return true.
419 using llvm::Pass::doInitialization;
420 using llvm::Pass::doFinalization;
422 /// doInitialization - Run all of the initializers for the module passes.
424 bool doInitialization();
426 /// doFinalization - Run all of the finalizers for the module passes.
428 bool doFinalization();
430 /// Pass Manager itself does not invalidate any analysis info.
431 void getAnalysisUsage(AnalysisUsage &Info) const override {
432 Info.setPreservesAll();
435 PMDataManager *getAsPMDataManager() override { return this; }
436 Pass *getAsPass() override { return this; }
437 PassManagerType getTopLevelPassManagerType() override {
438 return PMT_ModulePassManager;
441 MPPassManager *getContainedManager(unsigned N) {
442 assert(N < PassManagers.size() && "Pass number out of range!");
443 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
448 void PassManagerImpl::anchor() {}
450 char PassManagerImpl::ID = 0;
451 } // End of legacy namespace
452 } // End of llvm namespace
456 //===----------------------------------------------------------------------===//
457 /// TimingInfo Class - This class is used to calculate information about the
458 /// amount of time each pass takes to execute. This only happens when
459 /// -time-passes is enabled on the command line.
462 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
465 DenseMap<Pass*, Timer*> TimingData;
468 // Use 'create' member to get this.
469 TimingInfo() : TG("... Pass execution timing report ...") {}
471 // TimingDtor - Print out information about timing information
473 // Delete all of the timers, which accumulate their info into the
475 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
476 E = TimingData.end(); I != E; ++I)
478 // TimerGroup is deleted next, printing the report.
481 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
482 // to a non-null value (if the -time-passes option is enabled) or it leaves it
483 // null. It may be called multiple times.
484 static void createTheTimeInfo();
486 /// getPassTimer - Return the timer for the specified pass if it exists.
487 Timer *getPassTimer(Pass *P) {
488 if (P->getAsPMDataManager())
491 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
492 Timer *&T = TimingData[P];
494 T = new Timer(P->getPassName(), TG);
499 } // End of anon namespace
501 static TimingInfo *TheTimeInfo;
503 //===----------------------------------------------------------------------===//
504 // PMTopLevelManager implementation
506 /// Initialize top level manager. Create first pass manager.
507 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
508 PMDM->setTopLevelManager(this);
509 addPassManager(PMDM);
510 activeStack.push(PMDM);
513 /// Set pass P as the last user of the given analysis passes.
515 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
517 if (P->getResolver())
518 PDepth = P->getResolver()->getPMDataManager().getDepth();
520 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
521 E = AnalysisPasses.end(); I != E; ++I) {
528 // Update the last users of passes that are required transitive by AP.
529 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
530 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
531 SmallVector<Pass *, 12> LastUses;
532 SmallVector<Pass *, 12> LastPMUses;
533 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
534 E = IDs.end(); I != E; ++I) {
535 Pass *AnalysisPass = findAnalysisPass(*I);
536 assert(AnalysisPass && "Expected analysis pass to exist.");
537 AnalysisResolver *AR = AnalysisPass->getResolver();
538 assert(AR && "Expected analysis resolver to exist.");
539 unsigned APDepth = AR->getPMDataManager().getDepth();
541 if (PDepth == APDepth)
542 LastUses.push_back(AnalysisPass);
543 else if (PDepth > APDepth)
544 LastPMUses.push_back(AnalysisPass);
547 setLastUser(LastUses, P);
549 // If this pass has a corresponding pass manager, push higher level
550 // analysis to this pass manager.
551 if (P->getResolver())
552 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
555 // If AP is the last user of other passes then make P last user of
557 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
558 LUE = LastUser.end(); LUI != LUE; ++LUI) {
559 if (LUI->second == AP)
560 // DenseMap iterator is not invalidated here because
561 // this is just updating existing entries.
562 LastUser[LUI->first] = P;
567 /// Collect passes whose last user is P
568 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
570 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
571 InversedLastUser.find(P);
572 if (DMI == InversedLastUser.end())
575 SmallPtrSet<Pass *, 8> &LU = DMI->second;
576 for (Pass *LUP : LU) {
577 LastUses.push_back(LUP);
582 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
583 AnalysisUsage *AnUsage = nullptr;
584 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
585 if (DMI != AnUsageMap.end())
586 AnUsage = DMI->second;
588 AnUsage = new AnalysisUsage();
589 P->getAnalysisUsage(*AnUsage);
590 AnUsageMap[P] = AnUsage;
595 /// Schedule pass P for execution. Make sure that passes required by
596 /// P are run before P is run. Update analysis info maintained by
597 /// the manager. Remove dead passes. This is a recursive function.
598 void PMTopLevelManager::schedulePass(Pass *P) {
600 // TODO : Allocate function manager for this pass, other wise required set
601 // may be inserted into previous function manager
603 // Give pass a chance to prepare the stage.
604 P->preparePassManager(activeStack);
606 // If P is an analysis pass and it is available then do not
607 // generate the analysis again. Stale analysis info should not be
608 // available at this point.
610 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
611 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
616 AnalysisUsage *AnUsage = findAnalysisUsage(P);
618 bool checkAnalysis = true;
619 while (checkAnalysis) {
620 checkAnalysis = false;
622 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
623 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
624 E = RequiredSet.end(); I != E; ++I) {
626 Pass *AnalysisPass = findAnalysisPass(*I);
628 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
631 // Pass P is not in the global PassRegistry
632 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
633 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
634 dbgs() << "Required Passes:" << "\n";
635 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
636 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
637 Pass *AnalysisPass2 = findAnalysisPass(*I2);
639 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
641 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
642 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
643 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
648 assert(PI && "Expected required passes to be initialized");
649 AnalysisPass = PI->createPass();
650 if (P->getPotentialPassManagerType () ==
651 AnalysisPass->getPotentialPassManagerType())
652 // Schedule analysis pass that is managed by the same pass manager.
653 schedulePass(AnalysisPass);
654 else if (P->getPotentialPassManagerType () >
655 AnalysisPass->getPotentialPassManagerType()) {
656 // Schedule analysis pass that is managed by a new manager.
657 schedulePass(AnalysisPass);
658 // Recheck analysis passes to ensure that required analyses that
659 // are already checked are still available.
660 checkAnalysis = true;
662 // Do not schedule this analysis. Lower level analsyis
663 // passes are run on the fly.
669 // Now all required passes are available.
670 if (ImmutablePass *IP = P->getAsImmutablePass()) {
671 // P is a immutable pass and it will be managed by this
672 // top level manager. Set up analysis resolver to connect them.
673 PMDataManager *DM = getAsPMDataManager();
674 AnalysisResolver *AR = new AnalysisResolver(*DM);
676 DM->initializeAnalysisImpl(P);
677 addImmutablePass(IP);
678 DM->recordAvailableAnalysis(IP);
682 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
683 Pass *PP = P->createPrinterPass(
684 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
685 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
688 // Add the requested pass to the best available pass manager.
689 P->assignPassManager(activeStack, getTopLevelPassManagerType());
691 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
692 Pass *PP = P->createPrinterPass(
693 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
694 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
698 /// Find the pass that implements Analysis AID. Search immutable
699 /// passes and all pass managers. If desired pass is not found
700 /// then return NULL.
701 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
703 // Check pass managers
704 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
705 E = PassManagers.end(); I != E; ++I)
706 if (Pass *P = (*I)->findAnalysisPass(AID, false))
709 // Check other pass managers
710 for (SmallVectorImpl<PMDataManager *>::iterator
711 I = IndirectPassManagers.begin(),
712 E = IndirectPassManagers.end(); I != E; ++I)
713 if (Pass *P = (*I)->findAnalysisPass(AID, false))
716 // Check the immutable passes. Iterate in reverse order so that we find
717 // the most recently registered passes first.
718 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
719 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
720 AnalysisID PI = (*I)->getPassID();
724 // If Pass not found then check the interfaces implemented by Immutable Pass
725 const PassInfo *PassInf =
726 PassRegistry::getPassRegistry()->getPassInfo(PI);
727 assert(PassInf && "Expected all immutable passes to be initialized");
728 const std::vector<const PassInfo*> &ImmPI =
729 PassInf->getInterfacesImplemented();
730 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
731 EE = ImmPI.end(); II != EE; ++II) {
732 if ((*II)->getTypeInfo() == AID)
740 // Print passes managed by this top level manager.
741 void PMTopLevelManager::dumpPasses() const {
743 if (PassDebugging < Structure)
746 // Print out the immutable passes
747 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
748 ImmutablePasses[i]->dumpPassStructure(0);
751 // Every class that derives from PMDataManager also derives from Pass
752 // (sometimes indirectly), but there's no inheritance relationship
753 // between PMDataManager and Pass, so we have to getAsPass to get
754 // from a PMDataManager* to a Pass*.
755 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
756 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
757 (*I)->getAsPass()->dumpPassStructure(1);
760 void PMTopLevelManager::dumpArguments() const {
762 if (PassDebugging < Arguments)
765 dbgs() << "Pass Arguments: ";
766 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
767 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
768 if (const PassInfo *PI =
769 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
770 assert(PI && "Expected all immutable passes to be initialized");
771 if (!PI->isAnalysisGroup())
772 dbgs() << " -" << PI->getPassArgument();
774 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
775 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
776 (*I)->dumpPassArguments();
780 void PMTopLevelManager::initializeAllAnalysisInfo() {
781 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
782 E = PassManagers.end(); I != E; ++I)
783 (*I)->initializeAnalysisInfo();
785 // Initailize other pass managers
786 for (SmallVectorImpl<PMDataManager *>::iterator
787 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
789 (*I)->initializeAnalysisInfo();
791 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
792 DME = LastUser.end(); DMI != DME; ++DMI) {
793 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
794 InversedLastUser.find(DMI->second);
795 if (InvDMI != InversedLastUser.end()) {
796 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
797 L.insert(DMI->first);
799 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
800 InversedLastUser[DMI->second] = L;
806 PMTopLevelManager::~PMTopLevelManager() {
807 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
808 E = PassManagers.end(); I != E; ++I)
811 for (SmallVectorImpl<ImmutablePass *>::iterator
812 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
815 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
816 DME = AnUsageMap.end(); DMI != DME; ++DMI)
820 //===----------------------------------------------------------------------===//
821 // PMDataManager implementation
823 /// Augement AvailableAnalysis by adding analysis made available by pass P.
824 void PMDataManager::recordAvailableAnalysis(Pass *P) {
825 AnalysisID PI = P->getPassID();
827 AvailableAnalysis[PI] = P;
829 assert(!AvailableAnalysis.empty());
831 // This pass is the current implementation of all of the interfaces it
832 // implements as well.
833 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
835 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
836 for (unsigned i = 0, e = II.size(); i != e; ++i)
837 AvailableAnalysis[II[i]->getTypeInfo()] = P;
840 // Return true if P preserves high level analysis used by other
841 // passes managed by this manager
842 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
843 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
844 if (AnUsage->getPreservesAll())
847 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
848 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
849 E = HigherLevelAnalysis.end(); I != E; ++I) {
851 if (P1->getAsImmutablePass() == nullptr &&
852 std::find(PreservedSet.begin(), PreservedSet.end(),
861 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
862 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
863 // Don't do this unless assertions are enabled.
867 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
868 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
870 // Verify preserved analysis
871 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
872 E = PreservedSet.end(); I != E; ++I) {
874 if (Pass *AP = findAnalysisPass(AID, true)) {
875 TimeRegion PassTimer(getPassTimer(AP));
876 AP->verifyAnalysis();
881 /// Remove Analysis not preserved by Pass P
882 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
883 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
884 if (AnUsage->getPreservesAll())
887 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
888 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
889 E = AvailableAnalysis.end(); I != E; ) {
890 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
891 if (Info->second->getAsImmutablePass() == nullptr &&
892 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
893 PreservedSet.end()) {
894 // Remove this analysis
895 if (PassDebugging >= Details) {
896 Pass *S = Info->second;
897 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
898 dbgs() << S->getPassName() << "'\n";
900 AvailableAnalysis.erase(Info);
904 // Check inherited analysis also. If P is not preserving analysis
905 // provided by parent manager then remove it here.
906 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
908 if (!InheritedAnalysis[Index])
911 for (DenseMap<AnalysisID, Pass*>::iterator
912 I = InheritedAnalysis[Index]->begin(),
913 E = InheritedAnalysis[Index]->end(); I != E; ) {
914 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
915 if (Info->second->getAsImmutablePass() == nullptr &&
916 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
917 PreservedSet.end()) {
918 // Remove this analysis
919 if (PassDebugging >= Details) {
920 Pass *S = Info->second;
921 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
922 dbgs() << S->getPassName() << "'\n";
924 InheritedAnalysis[Index]->erase(Info);
930 /// Remove analysis passes that are not used any longer
931 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
932 enum PassDebuggingString DBG_STR) {
934 SmallVector<Pass *, 12> DeadPasses;
936 // If this is a on the fly manager then it does not have TPM.
940 TPM->collectLastUses(DeadPasses, P);
942 if (PassDebugging >= Details && !DeadPasses.empty()) {
943 dbgs() << " -*- '" << P->getPassName();
944 dbgs() << "' is the last user of following pass instances.";
945 dbgs() << " Free these instances\n";
948 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
949 E = DeadPasses.end(); I != E; ++I)
950 freePass(*I, Msg, DBG_STR);
953 void PMDataManager::freePass(Pass *P, StringRef Msg,
954 enum PassDebuggingString DBG_STR) {
955 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
958 // If the pass crashes releasing memory, remember this.
959 PassManagerPrettyStackEntry X(P);
960 TimeRegion PassTimer(getPassTimer(P));
965 AnalysisID PI = P->getPassID();
966 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
967 // Remove the pass itself (if it is not already removed).
968 AvailableAnalysis.erase(PI);
970 // Remove all interfaces this pass implements, for which it is also
971 // listed as the available implementation.
972 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
973 for (unsigned i = 0, e = II.size(); i != e; ++i) {
974 DenseMap<AnalysisID, Pass*>::iterator Pos =
975 AvailableAnalysis.find(II[i]->getTypeInfo());
976 if (Pos != AvailableAnalysis.end() && Pos->second == P)
977 AvailableAnalysis.erase(Pos);
982 /// Add pass P into the PassVector. Update
983 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
984 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
985 // This manager is going to manage pass P. Set up analysis resolver
987 AnalysisResolver *AR = new AnalysisResolver(*this);
990 // If a FunctionPass F is the last user of ModulePass info M
991 // then the F's manager, not F, records itself as a last user of M.
992 SmallVector<Pass *, 12> TransferLastUses;
994 if (!ProcessAnalysis) {
996 PassVector.push_back(P);
1000 // At the moment, this pass is the last user of all required passes.
1001 SmallVector<Pass *, 12> LastUses;
1002 SmallVector<Pass *, 8> RequiredPasses;
1003 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1005 unsigned PDepth = this->getDepth();
1007 collectRequiredAnalysis(RequiredPasses,
1008 ReqAnalysisNotAvailable, P);
1009 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1010 E = RequiredPasses.end(); I != E; ++I) {
1011 Pass *PRequired = *I;
1012 unsigned RDepth = 0;
1014 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1015 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1016 RDepth = DM.getDepth();
1018 if (PDepth == RDepth)
1019 LastUses.push_back(PRequired);
1020 else if (PDepth > RDepth) {
1021 // Let the parent claim responsibility of last use
1022 TransferLastUses.push_back(PRequired);
1023 // Keep track of higher level analysis used by this manager.
1024 HigherLevelAnalysis.push_back(PRequired);
1026 llvm_unreachable("Unable to accommodate Required 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 (SmallVectorImpl<AnalysisID>::iterator
1044 I = ReqAnalysisNotAvailable.begin(),
1045 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1046 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1047 Pass *AnalysisPass = PI->createPass();
1048 this->addLowerLevelRequiredPass(P, AnalysisPass);
1051 // Take a note of analysis required and made available by this pass.
1052 // Remove the analysis not preserved by this pass
1053 removeNotPreservedAnalysis(P);
1054 recordAvailableAnalysis(P);
1057 PassVector.push_back(P);
1061 /// Populate RP with analysis pass that are required by
1062 /// pass P and are available. Populate RP_NotAvail with analysis
1063 /// pass that are required by pass P but are not available.
1064 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1065 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1067 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1068 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1069 for (AnalysisUsage::VectorType::const_iterator
1070 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1071 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1072 RP.push_back(AnalysisPass);
1074 RP_NotAvail.push_back(*I);
1077 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1078 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1079 E = IDs.end(); I != E; ++I) {
1080 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1081 RP.push_back(AnalysisPass);
1083 RP_NotAvail.push_back(*I);
1087 // All Required analyses should be available to the pass as it runs! Here
1088 // we fill in the AnalysisImpls member of the pass so that it can
1089 // successfully use the getAnalysis() method to retrieve the
1090 // implementations it needs.
1092 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1093 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1095 for (AnalysisUsage::VectorType::const_iterator
1096 I = AnUsage->getRequiredSet().begin(),
1097 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1098 Pass *Impl = findAnalysisPass(*I, true);
1100 // This may be analysis pass that is initialized on the fly.
1101 // If that is not the case then it will raise an assert when it is used.
1103 AnalysisResolver *AR = P->getResolver();
1104 assert(AR && "Analysis Resolver is not set");
1105 AR->addAnalysisImplsPair(*I, Impl);
1109 /// Find the pass that implements Analysis AID. If desired pass is not found
1110 /// then return NULL.
1111 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1113 // Check if AvailableAnalysis map has one entry.
1114 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1116 if (I != AvailableAnalysis.end())
1119 // Search Parents through TopLevelManager
1121 return TPM->findAnalysisPass(AID);
1126 // Print list of passes that are last used by P.
1127 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1129 SmallVector<Pass *, 12> LUses;
1131 // If this is a on the fly manager then it does not have TPM.
1135 TPM->collectLastUses(LUses, P);
1137 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1138 E = LUses.end(); I != E; ++I) {
1139 dbgs() << "--" << std::string(Offset*2, ' ');
1140 (*I)->dumpPassStructure(0);
1144 void PMDataManager::dumpPassArguments() const {
1145 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1146 E = PassVector.end(); I != E; ++I) {
1147 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1148 PMD->dumpPassArguments();
1150 if (const PassInfo *PI =
1151 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1152 if (!PI->isAnalysisGroup())
1153 dbgs() << " -" << PI->getPassArgument();
1157 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1158 enum PassDebuggingString S2,
1160 if (PassDebugging < Executions)
1162 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1163 << std::string(getDepth() * 2 + 1, ' ');
1166 dbgs() << "Executing Pass '" << P->getPassName();
1168 case MODIFICATION_MSG:
1169 dbgs() << "Made Modification '" << P->getPassName();
1172 dbgs() << " Freeing Pass '" << P->getPassName();
1178 case ON_BASICBLOCK_MSG:
1179 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1181 case ON_FUNCTION_MSG:
1182 dbgs() << "' on Function '" << Msg << "'...\n";
1185 dbgs() << "' on Module '" << Msg << "'...\n";
1188 dbgs() << "' on Region '" << Msg << "'...\n";
1191 dbgs() << "' on Loop '" << Msg << "'...\n";
1194 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1201 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1202 if (PassDebugging < Details)
1205 AnalysisUsage analysisUsage;
1206 P->getAnalysisUsage(analysisUsage);
1207 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1210 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1211 if (PassDebugging < Details)
1214 AnalysisUsage analysisUsage;
1215 P->getAnalysisUsage(analysisUsage);
1216 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1219 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1220 const AnalysisUsage::VectorType &Set) const {
1221 assert(PassDebugging >= Details);
1224 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1225 for (unsigned i = 0; i != Set.size(); ++i) {
1226 if (i) dbgs() << ',';
1227 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1229 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1231 dbgs() << " Uninitialized Pass";
1234 dbgs() << ' ' << PInf->getPassName();
1239 /// Add RequiredPass into list of lower level passes required by pass P.
1240 /// RequiredPass is run on the fly by Pass Manager when P requests it
1241 /// through getAnalysis interface.
1242 /// This should be handled by specific pass manager.
1243 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1245 TPM->dumpArguments();
1249 // Module Level pass may required Function Level analysis info
1250 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1251 // to provide this on demand. In that case, in Pass manager terminology,
1252 // module level pass is requiring lower level analysis info managed by
1253 // lower level pass manager.
1255 // When Pass manager is not able to order required analysis info, Pass manager
1256 // checks whether any lower level manager will be able to provide this
1257 // analysis info on demand or not.
1259 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1260 dbgs() << "' required by '" << P->getPassName() << "'\n";
1262 llvm_unreachable("Unable to schedule pass");
1265 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1266 llvm_unreachable("Unable to find on the fly pass");
1270 PMDataManager::~PMDataManager() {
1271 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1272 E = PassVector.end(); I != E; ++I)
1276 //===----------------------------------------------------------------------===//
1277 // NOTE: Is this the right place to define this method ?
1278 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1279 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1280 return PM.findAnalysisPass(ID, dir);
1283 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1285 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1288 //===----------------------------------------------------------------------===//
1289 // BBPassManager implementation
1291 /// Execute all of the passes scheduled for execution by invoking
1292 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1293 /// the function, and if so, return true.
1294 bool BBPassManager::runOnFunction(Function &F) {
1295 if (F.isDeclaration())
1298 bool Changed = doInitialization(F);
1300 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1301 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1302 BasicBlockPass *BP = getContainedPass(Index);
1303 bool LocalChanged = false;
1305 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1306 dumpRequiredSet(BP);
1308 initializeAnalysisImpl(BP);
1311 // If the pass crashes, remember this.
1312 PassManagerPrettyStackEntry X(BP, *I);
1313 TimeRegion PassTimer(getPassTimer(BP));
1315 LocalChanged |= BP->runOnBasicBlock(*I);
1318 Changed |= LocalChanged;
1320 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1322 dumpPreservedSet(BP);
1324 verifyPreservedAnalysis(BP);
1325 removeNotPreservedAnalysis(BP);
1326 recordAvailableAnalysis(BP);
1327 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1330 return doFinalization(F) || Changed;
1333 // Implement doInitialization and doFinalization
1334 bool BBPassManager::doInitialization(Module &M) {
1335 bool Changed = false;
1337 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1338 Changed |= getContainedPass(Index)->doInitialization(M);
1343 bool BBPassManager::doFinalization(Module &M) {
1344 bool Changed = false;
1346 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1347 Changed |= getContainedPass(Index)->doFinalization(M);
1352 bool BBPassManager::doInitialization(Function &F) {
1353 bool Changed = false;
1355 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1356 BasicBlockPass *BP = getContainedPass(Index);
1357 Changed |= BP->doInitialization(F);
1363 bool BBPassManager::doFinalization(Function &F) {
1364 bool Changed = false;
1366 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1367 BasicBlockPass *BP = getContainedPass(Index);
1368 Changed |= BP->doFinalization(F);
1375 //===----------------------------------------------------------------------===//
1376 // FunctionPassManager implementation
1378 /// Create new Function pass manager
1379 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1380 FPM = new FunctionPassManagerImpl();
1381 // FPM is the top level manager.
1382 FPM->setTopLevelManager(FPM);
1384 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1385 FPM->setResolver(AR);
1388 FunctionPassManager::~FunctionPassManager() {
1392 /// add - Add a pass to the queue of passes to run. This passes
1393 /// ownership of the Pass to the PassManager. When the
1394 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1395 /// there is no need to delete the pass. (TODO delete passes.)
1396 /// This implies that all passes MUST be allocated with 'new'.
1397 void FunctionPassManager::add(Pass *P) {
1401 /// run - Execute all of the passes scheduled for execution. Keep
1402 /// track of whether any of the passes modifies the function, and if
1403 /// so, return true.
1405 bool FunctionPassManager::run(Function &F) {
1406 if (F.isMaterializable()) {
1408 if (F.Materialize(&errstr))
1409 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1415 /// doInitialization - Run all of the initializers for the function passes.
1417 bool FunctionPassManager::doInitialization() {
1418 return FPM->doInitialization(*M);
1421 /// doFinalization - Run all of the finalizers for the function passes.
1423 bool FunctionPassManager::doFinalization() {
1424 return FPM->doFinalization(*M);
1427 //===----------------------------------------------------------------------===//
1428 // FunctionPassManagerImpl implementation
1430 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1431 bool Changed = false;
1436 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1437 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1438 E = IPV.end(); I != E; ++I) {
1439 Changed |= (*I)->doInitialization(M);
1442 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1443 Changed |= getContainedManager(Index)->doInitialization(M);
1448 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1449 bool Changed = false;
1451 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1452 Changed |= getContainedManager(Index)->doFinalization(M);
1454 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1455 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1456 E = IPV.end(); I != E; ++I) {
1457 Changed |= (*I)->doFinalization(M);
1463 /// cleanup - After running all passes, clean up pass manager cache.
1464 void FPPassManager::cleanup() {
1465 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1466 FunctionPass *FP = getContainedPass(Index);
1467 AnalysisResolver *AR = FP->getResolver();
1468 assert(AR && "Analysis Resolver is not set");
1469 AR->clearAnalysisImpls();
1473 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1476 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1477 FPPassManager *FPPM = getContainedManager(Index);
1478 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1479 FPPM->getContainedPass(Index)->releaseMemory();
1485 // Execute all the passes managed by this top level manager.
1486 // Return true if any function is modified by a pass.
1487 bool FunctionPassManagerImpl::run(Function &F) {
1488 bool Changed = false;
1489 TimingInfo::createTheTimeInfo();
1491 initializeAllAnalysisInfo();
1492 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1493 Changed |= getContainedManager(Index)->runOnFunction(F);
1494 F.getContext().yield();
1497 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1498 getContainedManager(Index)->cleanup();
1504 //===----------------------------------------------------------------------===//
1505 // FPPassManager implementation
1507 char FPPassManager::ID = 0;
1508 /// Print passes managed by this manager
1509 void FPPassManager::dumpPassStructure(unsigned Offset) {
1510 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1511 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1512 FunctionPass *FP = getContainedPass(Index);
1513 FP->dumpPassStructure(Offset + 1);
1514 dumpLastUses(FP, Offset+1);
1519 /// Execute all of the passes scheduled for execution by invoking
1520 /// runOnFunction method. Keep track of whether any of the passes modifies
1521 /// the function, and if so, return true.
1522 bool FPPassManager::runOnFunction(Function &F) {
1523 if (F.isDeclaration())
1526 bool Changed = false;
1528 // Collect inherited analysis from Module level pass manager.
1529 populateInheritedAnalysis(TPM->activeStack);
1531 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1532 FunctionPass *FP = getContainedPass(Index);
1533 bool LocalChanged = false;
1535 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1536 dumpRequiredSet(FP);
1538 initializeAnalysisImpl(FP);
1541 PassManagerPrettyStackEntry X(FP, F);
1542 TimeRegion PassTimer(getPassTimer(FP));
1544 LocalChanged |= FP->runOnFunction(F);
1547 Changed |= LocalChanged;
1549 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1550 dumpPreservedSet(FP);
1552 verifyPreservedAnalysis(FP);
1553 removeNotPreservedAnalysis(FP);
1554 recordAvailableAnalysis(FP);
1555 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1560 bool FPPassManager::runOnModule(Module &M) {
1561 bool Changed = false;
1563 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1564 Changed |= runOnFunction(*I);
1569 bool FPPassManager::doInitialization(Module &M) {
1570 bool Changed = false;
1572 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1573 Changed |= getContainedPass(Index)->doInitialization(M);
1578 bool FPPassManager::doFinalization(Module &M) {
1579 bool Changed = false;
1581 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1582 Changed |= getContainedPass(Index)->doFinalization(M);
1587 //===----------------------------------------------------------------------===//
1588 // MPPassManager implementation
1590 /// Execute all of the passes scheduled for execution by invoking
1591 /// runOnModule method. Keep track of whether any of the passes modifies
1592 /// the module, and if so, return true.
1594 MPPassManager::runOnModule(Module &M) {
1595 bool Changed = false;
1597 // Initialize on-the-fly passes
1598 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1599 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1601 FunctionPassManagerImpl *FPP = I->second;
1602 Changed |= FPP->doInitialization(M);
1605 // Initialize module passes
1606 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1607 Changed |= getContainedPass(Index)->doInitialization(M);
1609 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1610 ModulePass *MP = getContainedPass(Index);
1611 bool LocalChanged = false;
1613 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1614 dumpRequiredSet(MP);
1616 initializeAnalysisImpl(MP);
1619 PassManagerPrettyStackEntry X(MP, M);
1620 TimeRegion PassTimer(getPassTimer(MP));
1622 LocalChanged |= MP->runOnModule(M);
1625 Changed |= LocalChanged;
1627 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1628 M.getModuleIdentifier());
1629 dumpPreservedSet(MP);
1631 verifyPreservedAnalysis(MP);
1632 removeNotPreservedAnalysis(MP);
1633 recordAvailableAnalysis(MP);
1634 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1637 // Finalize module passes
1638 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1639 Changed |= getContainedPass(Index)->doFinalization(M);
1641 // Finalize on-the-fly passes
1642 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1643 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1645 FunctionPassManagerImpl *FPP = I->second;
1646 // We don't know when is the last time an on-the-fly pass is run,
1647 // so we need to releaseMemory / finalize here
1648 FPP->releaseMemoryOnTheFly();
1649 Changed |= FPP->doFinalization(M);
1655 /// Add RequiredPass into list of lower level passes required by pass P.
1656 /// RequiredPass is run on the fly by Pass Manager when P requests it
1657 /// through getAnalysis interface.
1658 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1659 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1660 "Unable to handle Pass that requires lower level Analysis pass");
1661 assert((P->getPotentialPassManagerType() <
1662 RequiredPass->getPotentialPassManagerType()) &&
1663 "Unable to handle Pass that requires lower level Analysis pass");
1667 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1669 FPP = new FunctionPassManagerImpl();
1670 // FPP is the top level manager.
1671 FPP->setTopLevelManager(FPP);
1673 OnTheFlyManagers[P] = FPP;
1675 const PassInfo * RequiredPassPI =
1676 PassRegistry::getPassRegistry()->getPassInfo(RequiredPass->getPassID());
1678 Pass *FoundPass = nullptr;
1679 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1681 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1684 FoundPass = RequiredPass;
1685 // This should be guaranteed to add RequiredPass to the passmanager given
1686 // that we checked for an available analysis above.
1687 FPP->add(RequiredPass);
1689 // Register P as the last user of FoundPass or RequiredPass.
1690 SmallVector<Pass *, 1> LU;
1691 LU.push_back(FoundPass);
1692 FPP->setLastUser(LU, P);
1695 /// Return function pass corresponding to PassInfo PI, that is
1696 /// required by module pass MP. Instantiate analysis pass, by using
1697 /// its runOnFunction() for function F.
1698 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1699 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1700 assert(FPP && "Unable to find on the fly pass");
1702 FPP->releaseMemoryOnTheFly();
1704 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1708 //===----------------------------------------------------------------------===//
1709 // PassManagerImpl implementation
1712 /// run - Execute all of the passes scheduled for execution. Keep track of
1713 /// whether any of the passes modifies the module, and if so, return true.
1714 bool PassManagerImpl::run(Module &M) {
1715 bool Changed = false;
1716 TimingInfo::createTheTimeInfo();
1721 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1722 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1723 E = IPV.end(); I != E; ++I) {
1724 Changed |= (*I)->doInitialization(M);
1727 initializeAllAnalysisInfo();
1728 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1729 Changed |= getContainedManager(Index)->runOnModule(M);
1730 M.getContext().yield();
1733 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1734 E = IPV.end(); I != E; ++I) {
1735 Changed |= (*I)->doFinalization(M);
1741 //===----------------------------------------------------------------------===//
1742 // PassManager implementation
1744 /// Create new pass manager
1745 PassManager::PassManager() {
1746 PM = new PassManagerImpl();
1747 // PM is the top level manager
1748 PM->setTopLevelManager(PM);
1751 PassManager::~PassManager() {
1755 /// add - Add a pass to the queue of passes to run. This passes ownership of
1756 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1757 /// will be destroyed as well, so there is no need to delete the pass. This
1758 /// implies that all passes MUST be allocated with 'new'.
1759 void PassManager::add(Pass *P) {
1763 /// run - Execute all of the passes scheduled for execution. Keep track of
1764 /// whether any of the passes modifies the module, and if so, return true.
1765 bool PassManager::run(Module &M) {
1769 //===----------------------------------------------------------------------===//
1770 // TimingInfo implementation
1772 bool llvm::TimePassesIsEnabled = false;
1773 static cl::opt<bool,true>
1774 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1775 cl::desc("Time each pass, printing elapsed time for each on exit"));
1777 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1778 // a non-null value (if the -time-passes option is enabled) or it leaves it
1779 // null. It may be called multiple times.
1780 void TimingInfo::createTheTimeInfo() {
1781 if (!TimePassesIsEnabled || TheTimeInfo) return;
1783 // Constructed the first time this is called, iff -time-passes is enabled.
1784 // This guarantees that the object will be constructed before static globals,
1785 // thus it will be destroyed before them.
1786 static ManagedStatic<TimingInfo> TTI;
1787 TheTimeInfo = &*TTI;
1790 /// If TimingInfo is enabled then start pass timer.
1791 Timer *llvm::getPassTimer(Pass *P) {
1793 return TheTimeInfo->getPassTimer(P);
1797 //===----------------------------------------------------------------------===//
1798 // PMStack implementation
1801 // Pop Pass Manager from the stack and clear its analysis info.
1802 void PMStack::pop() {
1804 PMDataManager *Top = this->top();
1805 Top->initializeAnalysisInfo();
1810 // Push PM on the stack and set its top level manager.
1811 void PMStack::push(PMDataManager *PM) {
1812 assert(PM && "Unable to push. Pass Manager expected");
1813 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1815 if (!this->empty()) {
1816 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1817 && "pushing bad pass manager to PMStack");
1818 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1820 assert(TPM && "Unable to find top level manager");
1821 TPM->addIndirectPassManager(PM);
1822 PM->setTopLevelManager(TPM);
1823 PM->setDepth(this->top()->getDepth()+1);
1825 assert((PM->getPassManagerType() == PMT_ModulePassManager
1826 || PM->getPassManagerType() == PMT_FunctionPassManager)
1827 && "pushing bad pass manager to PMStack");
1834 // Dump content of the pass manager stack.
1835 void PMStack::dump() const {
1836 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1837 E = S.end(); I != E; ++I)
1838 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1844 /// Find appropriate Module Pass Manager in the PM Stack and
1845 /// add self into that manager.
1846 void ModulePass::assignPassManager(PMStack &PMS,
1847 PassManagerType PreferredType) {
1848 // Find Module Pass Manager
1849 while (!PMS.empty()) {
1850 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1851 if (TopPMType == PreferredType)
1852 break; // We found desired pass manager
1853 else if (TopPMType > PMT_ModulePassManager)
1854 PMS.pop(); // Pop children pass managers
1858 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1859 PMS.top()->add(this);
1862 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1863 /// in the PM Stack and add self into that manager.
1864 void FunctionPass::assignPassManager(PMStack &PMS,
1865 PassManagerType PreferredType) {
1867 // Find Function Pass Manager
1868 while (!PMS.empty()) {
1869 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1875 // Create new Function Pass Manager if needed.
1877 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1878 FPP = (FPPassManager *)PMS.top();
1880 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1881 PMDataManager *PMD = PMS.top();
1883 // [1] Create new Function Pass Manager
1884 FPP = new FPPassManager();
1885 FPP->populateInheritedAnalysis(PMS);
1887 // [2] Set up new manager's top level manager
1888 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1889 TPM->addIndirectPassManager(FPP);
1891 // [3] Assign manager to manage this new manager. This may create
1892 // and push new managers into PMS
1893 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1895 // [4] Push new manager into PMS
1899 // Assign FPP as the manager of this pass.
1903 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1904 /// in the PM Stack and add self into that manager.
1905 void BasicBlockPass::assignPassManager(PMStack &PMS,
1906 PassManagerType PreferredType) {
1909 // Basic Pass Manager is a leaf pass manager. It does not handle
1910 // any other pass manager.
1912 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1913 BBP = (BBPassManager *)PMS.top();
1915 // If leaf manager is not Basic Block Pass manager then create new
1916 // basic Block Pass manager.
1917 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1918 PMDataManager *PMD = PMS.top();
1920 // [1] Create new Basic Block Manager
1921 BBP = new BBPassManager();
1923 // [2] Set up new manager's top level manager
1924 // Basic Block Pass Manager does not live by itself
1925 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1926 TPM->addIndirectPassManager(BBP);
1928 // [3] Assign manager to manage this new manager. This may create
1929 // and push new managers into PMS
1930 BBP->assignPassManager(PMS, PreferredType);
1932 // [4] Push new manager into PMS
1936 // Assign BBP as the manager of this pass.
1940 PassManagerBase::~PassManagerBase() {}