1 //===- PassManager.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 LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/Assembly/PrintModulePass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/Timer.h"
27 #include "llvm/Support/raw_ostream.h"
32 // 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.
43 // Different debug levels that can be enabled...
45 Disabled, Arguments, Structure, Executions, Details
48 bool TimePassesIsEnabled = false;
50 /// Encapsulate PassManager debug options. These are convenient options that
51 /// should be available to any LLVM-based tool. They exist purely as
52 /// command-line debug options, therefore don't need to be local to an LLVM
53 /// context or captured by a formal API. In all respects they are handled like
54 /// global variables, but being defined in the LLVMCore library cannot have
55 /// static initializers and must be destroyed only at llvm_shutdown.
56 struct PassDebugOpts {
57 cl::opt<enum PassDebugLevel> PassDebugging;
59 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
62 // Print IR out before/after specified passes.
63 PassOptionList PrintBefore;
65 PassOptionList PrintAfter;
67 cl::opt<bool> PrintBeforeAll;
68 cl::opt<bool> PrintAfterAll;
70 cl::opt<bool,true> EnableTiming;
73 PassDebugging("debug-pass", cl::Hidden,
74 cl::desc("Print PassManager debugging information"),
76 clEnumVal(Disabled , "disable debug output"),
78 "print pass arguments to pass to 'opt'"),
79 clEnumVal(Structure, "print pass structure before run()"),
81 "print pass name before it is executed"),
83 "print pass details when it is executed"),
85 PrintBefore("print-before",
86 llvm::cl::desc("Print IR before specified passes"),
88 PrintAfter("print-after",
89 llvm::cl::desc("Print IR after specified passes"),
91 PrintBeforeAll("print-before-all",
92 llvm::cl::desc("Print IR before each pass"),
94 PrintAfterAll("print-after-all",
95 llvm::cl::desc("Print IR after each pass"),
97 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
99 "Time each pass, printing elapsed time for each on exit"))
102 /// This is a helper to determine whether to print IR before or
104 bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
105 PassOptionList &PassesToPrint) {
106 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
107 const llvm::PassInfo *PassInf = PassesToPrint[i];
109 if (PassInf->getPassArgument() == PI->getPassArgument()) {
116 /// This is a utility to check whether a pass should have IR dumped
118 bool ShouldPrintBeforePass(const PassInfo *PI) {
119 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
122 /// This is a utility to check whether a pass should have IR dumped
124 bool ShouldPrintAfterPass(const PassInfo *PI) {
125 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
129 static ManagedStatic<PassDebugOpts> GlobalPassDebugOpts;
131 /// This is called by tools to force registration of debugging options and
132 /// ensure they appear in the tool's -help usage.
133 void initializePassManager() {
134 // Force instantiation of PassDebugOpts.
135 *GlobalPassDebugOpts;
138 } // End of llvm namespace
140 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
141 /// or higher is specified.
142 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
143 return GlobalPassDebugOpts->PassDebugging >= Executions;
146 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
147 if (V == 0 && M == 0)
148 OS << "Releasing pass '";
150 OS << "Running pass '";
152 OS << P->getPassName() << "'";
155 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
164 if (isa<Function>(V))
166 else if (isa<BasicBlock>(V))
172 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
179 //===----------------------------------------------------------------------===//
182 /// BBPassManager manages BasicBlockPass. It batches all the
183 /// pass together and sequence them to process one basic block before
184 /// processing next basic block.
185 class BBPassManager : public PMDataManager, public FunctionPass {
189 explicit BBPassManager()
190 : PMDataManager(), FunctionPass(ID) {}
192 /// Execute all of the passes scheduled for execution. Keep track of
193 /// whether any of the passes modifies the function, and if so, return true.
194 bool runOnFunction(Function &F);
196 /// Pass Manager itself does not invalidate any analysis info.
197 void getAnalysisUsage(AnalysisUsage &Info) const {
198 Info.setPreservesAll();
201 bool doInitialization(Module &M);
202 bool doInitialization(Function &F);
203 bool doFinalization(Module &M);
204 bool doFinalization(Function &F);
206 virtual PMDataManager *getAsPMDataManager() { return this; }
207 virtual Pass *getAsPass() { return this; }
209 virtual const char *getPassName() const {
210 return "BasicBlock Pass Manager";
213 // Print passes managed by this manager
214 void dumpPassStructure(unsigned Offset) {
215 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
216 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
217 BasicBlockPass *BP = getContainedPass(Index);
218 BP->dumpPassStructure(Offset + 1);
219 dumpLastUses(BP, Offset+1);
223 BasicBlockPass *getContainedPass(unsigned N) {
224 assert(N < PassVector.size() && "Pass number out of range!");
225 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
229 virtual PassManagerType getPassManagerType() const {
230 return PMT_BasicBlockPassManager;
234 char BBPassManager::ID = 0;
239 //===----------------------------------------------------------------------===//
240 // FunctionPassManagerImpl
242 /// FunctionPassManagerImpl manages FPPassManagers
243 class FunctionPassManagerImpl : public Pass,
244 public PMDataManager,
245 public PMTopLevelManager {
246 virtual void anchor();
251 explicit FunctionPassManagerImpl() :
252 Pass(PT_PassManager, ID), PMDataManager(),
253 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
255 /// add - Add a pass to the queue of passes to run. This passes ownership of
256 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
257 /// will be destroyed as well, so there is no need to delete the pass. This
258 /// implies that all passes MUST be allocated with 'new'.
263 /// createPrinterPass - Get a function printer pass.
264 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
265 return createPrintFunctionPass(Banner, &O);
268 // Prepare for running an on the fly pass, freeing memory if needed
269 // from a previous run.
270 void releaseMemoryOnTheFly();
272 /// run - Execute all of the passes scheduled for execution. Keep track of
273 /// whether any of the passes modifies the module, and if so, return true.
274 bool run(Function &F);
276 /// doInitialization - Run all of the initializers for the function passes.
278 bool doInitialization(Module &M);
280 /// doFinalization - Run all of the finalizers for the function passes.
282 bool doFinalization(Module &M);
285 virtual PMDataManager *getAsPMDataManager() { return this; }
286 virtual Pass *getAsPass() { return this; }
287 virtual PassManagerType getTopLevelPassManagerType() {
288 return PMT_FunctionPassManager;
291 /// Pass Manager itself does not invalidate any analysis info.
292 void getAnalysisUsage(AnalysisUsage &Info) const {
293 Info.setPreservesAll();
296 FPPassManager *getContainedManager(unsigned N) {
297 assert(N < PassManagers.size() && "Pass number out of range!");
298 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
303 void FunctionPassManagerImpl::anchor() {}
305 char FunctionPassManagerImpl::ID = 0;
307 //===----------------------------------------------------------------------===//
310 /// MPPassManager manages ModulePasses and function pass managers.
311 /// It batches all Module passes and function pass managers together and
312 /// sequences them to process one module.
313 class MPPassManager : public Pass, public PMDataManager {
316 explicit MPPassManager() :
317 Pass(PT_PassManager, ID), PMDataManager() { }
319 // Delete on the fly managers.
320 virtual ~MPPassManager() {
321 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
322 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
324 FunctionPassManagerImpl *FPP = I->second;
329 /// createPrinterPass - Get a module printer pass.
330 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
331 return createPrintModulePass(&O, false, Banner);
334 /// run - Execute all of the passes scheduled for execution. Keep track of
335 /// whether any of the passes modifies the module, and if so, return true.
336 bool runOnModule(Module &M);
338 using llvm::Pass::doInitialization;
339 using llvm::Pass::doFinalization;
341 /// doInitialization - Run all of the initializers for the module passes.
343 bool doInitialization();
345 /// doFinalization - Run all of the finalizers for the module passes.
347 bool doFinalization();
349 /// Pass Manager itself does not invalidate any analysis info.
350 void getAnalysisUsage(AnalysisUsage &Info) const {
351 Info.setPreservesAll();
354 /// Add RequiredPass into list of lower level passes required by pass P.
355 /// RequiredPass is run on the fly by Pass Manager when P requests it
356 /// through getAnalysis interface.
357 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
359 /// Return function pass corresponding to PassInfo PI, that is
360 /// required by module pass MP. Instantiate analysis pass, by using
361 /// its runOnFunction() for function F.
362 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
364 virtual const char *getPassName() const {
365 return "Module Pass Manager";
368 virtual PMDataManager *getAsPMDataManager() { return this; }
369 virtual Pass *getAsPass() { return this; }
371 // Print passes managed by this manager
372 void dumpPassStructure(unsigned Offset) {
373 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
374 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
375 ModulePass *MP = getContainedPass(Index);
376 MP->dumpPassStructure(Offset + 1);
377 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
378 OnTheFlyManagers.find(MP);
379 if (I != OnTheFlyManagers.end())
380 I->second->dumpPassStructure(Offset + 2);
381 dumpLastUses(MP, Offset+1);
385 ModulePass *getContainedPass(unsigned N) {
386 assert(N < PassVector.size() && "Pass number out of range!");
387 return static_cast<ModulePass *>(PassVector[N]);
390 virtual PassManagerType getPassManagerType() const {
391 return PMT_ModulePassManager;
395 /// Collection of on the fly FPPassManagers. These managers manage
396 /// function passes that are required by module passes.
397 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
400 char MPPassManager::ID = 0;
401 //===----------------------------------------------------------------------===//
405 /// PassManagerImpl manages MPPassManagers
406 class PassManagerImpl : public Pass,
407 public PMDataManager,
408 public PMTopLevelManager {
409 virtual void anchor();
413 explicit PassManagerImpl() :
414 Pass(PT_PassManager, ID), PMDataManager(),
415 PMTopLevelManager(new MPPassManager()) {}
417 /// add - Add a pass to the queue of passes to run. This passes ownership of
418 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
419 /// will be destroyed as well, so there is no need to delete the pass. This
420 /// implies that all passes MUST be allocated with 'new'.
425 /// createPrinterPass - Get a module printer pass.
426 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
427 return createPrintModulePass(&O, false, Banner);
430 /// run - Execute all of the passes scheduled for execution. Keep track of
431 /// whether any of the passes modifies the module, and if so, return true.
434 using llvm::Pass::doInitialization;
435 using llvm::Pass::doFinalization;
437 /// doInitialization - Run all of the initializers for the module passes.
439 bool doInitialization();
441 /// doFinalization - Run all of the finalizers for the module passes.
443 bool doFinalization();
445 /// Pass Manager itself does not invalidate any analysis info.
446 void getAnalysisUsage(AnalysisUsage &Info) const {
447 Info.setPreservesAll();
450 virtual PMDataManager *getAsPMDataManager() { return this; }
451 virtual Pass *getAsPass() { return this; }
452 virtual PassManagerType getTopLevelPassManagerType() {
453 return PMT_ModulePassManager;
456 MPPassManager *getContainedManager(unsigned N) {
457 assert(N < PassManagers.size() && "Pass number out of range!");
458 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
463 void PassManagerImpl::anchor() {}
465 char PassManagerImpl::ID = 0;
466 } // End of llvm namespace
470 //===----------------------------------------------------------------------===//
471 /// TimingInfo Class - This class is used to calculate information about the
472 /// amount of time each pass takes to execute. This only happens when
473 /// -time-passes is enabled on the command line.
476 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
479 DenseMap<Pass*, Timer*> TimingData;
482 // Use 'create' member to get this.
483 TimingInfo() : TG("... Pass execution timing report ...") {}
485 // TimingDtor - Print out information about timing information
487 // Delete all of the timers, which accumulate their info into the
489 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
490 E = TimingData.end(); I != E; ++I)
492 // TimerGroup is deleted next, printing the report.
495 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
496 // to a non null value (if the -time-passes option is enabled) or it leaves it
497 // null. It may be called multiple times.
498 static void createTheTimeInfo();
500 /// getPassTimer - Return the timer for the specified pass if it exists.
501 Timer *getPassTimer(Pass *P) {
502 if (P->getAsPMDataManager())
505 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
506 Timer *&T = TimingData[P];
508 T = new Timer(P->getPassName(), TG);
513 } // End of anon namespace
515 static TimingInfo *TheTimeInfo;
517 //===----------------------------------------------------------------------===//
518 // PMTopLevelManager implementation
520 /// Initialize top level manager. Create first pass manager.
521 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
522 PMDM->setTopLevelManager(this);
523 addPassManager(PMDM);
524 activeStack.push(PMDM);
527 /// Set pass P as the last user of the given analysis passes.
529 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
531 if (P->getResolver())
532 PDepth = P->getResolver()->getPMDataManager().getDepth();
534 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
535 E = AnalysisPasses.end(); I != E; ++I) {
542 // Update the last users of passes that are required transitive by AP.
543 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
544 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
545 SmallVector<Pass *, 12> LastUses;
546 SmallVector<Pass *, 12> LastPMUses;
547 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
548 E = IDs.end(); I != E; ++I) {
549 Pass *AnalysisPass = findAnalysisPass(*I);
550 assert(AnalysisPass && "Expected analysis pass to exist.");
551 AnalysisResolver *AR = AnalysisPass->getResolver();
552 assert(AR && "Expected analysis resolver to exist.");
553 unsigned APDepth = AR->getPMDataManager().getDepth();
555 if (PDepth == APDepth)
556 LastUses.push_back(AnalysisPass);
557 else if (PDepth > APDepth)
558 LastPMUses.push_back(AnalysisPass);
561 setLastUser(LastUses, P);
563 // If this pass has a corresponding pass manager, push higher level
564 // analysis to this pass manager.
565 if (P->getResolver())
566 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
569 // If AP is the last user of other passes then make P last user of
571 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
572 LUE = LastUser.end(); LUI != LUE; ++LUI) {
573 if (LUI->second == AP)
574 // DenseMap iterator is not invalidated here because
575 // this is just updating existing entries.
576 LastUser[LUI->first] = P;
581 /// Collect passes whose last user is P
582 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
584 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
585 InversedLastUser.find(P);
586 if (DMI == InversedLastUser.end())
589 SmallPtrSet<Pass *, 8> &LU = DMI->second;
590 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
591 E = LU.end(); I != E; ++I) {
592 LastUses.push_back(*I);
597 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
598 AnalysisUsage *AnUsage = NULL;
599 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
600 if (DMI != AnUsageMap.end())
601 AnUsage = DMI->second;
603 AnUsage = new AnalysisUsage();
604 P->getAnalysisUsage(*AnUsage);
605 AnUsageMap[P] = AnUsage;
610 /// Schedule pass P for execution. Make sure that passes required by
611 /// P are run before P is run. Update analysis info maintained by
612 /// the manager. Remove dead passes. This is a recursive function.
613 void PMTopLevelManager::schedulePass(Pass *P) {
615 // TODO : Allocate function manager for this pass, other wise required set
616 // may be inserted into previous function manager
618 // Give pass a chance to prepare the stage.
619 P->preparePassManager(activeStack);
621 // If P is an analysis pass and it is available then do not
622 // generate the analysis again. Stale analysis info should not be
623 // available at this point.
625 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
626 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
631 AnalysisUsage *AnUsage = findAnalysisUsage(P);
633 bool checkAnalysis = true;
634 while (checkAnalysis) {
635 checkAnalysis = false;
637 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
638 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
639 E = RequiredSet.end(); I != E; ++I) {
641 Pass *AnalysisPass = findAnalysisPass(*I);
643 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
646 // Pass P is not in the global PassRegistry
647 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
648 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
649 dbgs() << "Required Passes:" << "\n";
650 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
651 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
652 Pass *AnalysisPass2 = findAnalysisPass(*I2);
654 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
656 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
657 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
658 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
663 assert(PI && "Expected required passes to be initialized");
664 AnalysisPass = PI->createPass();
665 if (P->getPotentialPassManagerType () ==
666 AnalysisPass->getPotentialPassManagerType())
667 // Schedule analysis pass that is managed by the same pass manager.
668 schedulePass(AnalysisPass);
669 else if (P->getPotentialPassManagerType () >
670 AnalysisPass->getPotentialPassManagerType()) {
671 // Schedule analysis pass that is managed by a new manager.
672 schedulePass(AnalysisPass);
673 // Recheck analysis passes to ensure that required analyses that
674 // are already checked are still available.
675 checkAnalysis = true;
677 // Do not schedule this analysis. Lower level analsyis
678 // passes are run on the fly.
684 // Now all required passes are available.
685 if (ImmutablePass *IP = P->getAsImmutablePass()) {
686 // P is a immutable pass and it will be managed by this
687 // top level manager. Set up analysis resolver to connect them.
688 PMDataManager *DM = getAsPMDataManager();
689 AnalysisResolver *AR = new AnalysisResolver(*DM);
691 DM->initializeAnalysisImpl(P);
692 addImmutablePass(IP);
693 DM->recordAvailableAnalysis(IP);
697 if (PI && !PI->isAnalysis() &&
698 GlobalPassDebugOpts->ShouldPrintBeforePass(PI)) {
699 Pass *PP = P->createPrinterPass(
700 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
701 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
704 // Add the requested pass to the best available pass manager.
705 P->assignPassManager(activeStack, getTopLevelPassManagerType());
707 if (PI && !PI->isAnalysis() &&
708 GlobalPassDebugOpts->ShouldPrintAfterPass(PI)) {
709 Pass *PP = P->createPrinterPass(
710 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
711 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
715 /// Find the pass that implements Analysis AID. Search immutable
716 /// passes and all pass managers. If desired pass is not found
717 /// then return NULL.
718 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
720 // Check pass managers
721 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
722 E = PassManagers.end(); I != E; ++I)
723 if (Pass *P = (*I)->findAnalysisPass(AID, false))
726 // Check other pass managers
727 for (SmallVectorImpl<PMDataManager *>::iterator
728 I = IndirectPassManagers.begin(),
729 E = IndirectPassManagers.end(); I != E; ++I)
730 if (Pass *P = (*I)->findAnalysisPass(AID, false))
733 // Check the immutable passes. Iterate in reverse order so that we find
734 // the most recently registered passes first.
735 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
736 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
737 AnalysisID PI = (*I)->getPassID();
741 // If Pass not found then check the interfaces implemented by Immutable Pass
742 const PassInfo *PassInf =
743 PassRegistry::getPassRegistry()->getPassInfo(PI);
744 assert(PassInf && "Expected all immutable passes to be initialized");
745 const std::vector<const PassInfo*> &ImmPI =
746 PassInf->getInterfacesImplemented();
747 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
748 EE = ImmPI.end(); II != EE; ++II) {
749 if ((*II)->getTypeInfo() == AID)
757 // Print passes managed by this top level manager.
758 void PMTopLevelManager::dumpPasses() const {
760 if (GlobalPassDebugOpts->PassDebugging < Structure)
763 // Print out the immutable passes
764 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
765 ImmutablePasses[i]->dumpPassStructure(0);
768 // Every class that derives from PMDataManager also derives from Pass
769 // (sometimes indirectly), but there's no inheritance relationship
770 // between PMDataManager and Pass, so we have to getAsPass to get
771 // from a PMDataManager* to a Pass*.
772 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
773 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
774 (*I)->getAsPass()->dumpPassStructure(1);
777 void PMTopLevelManager::dumpArguments() const {
779 if (GlobalPassDebugOpts->PassDebugging < Arguments)
782 dbgs() << "Pass Arguments: ";
783 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
784 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
785 if (const PassInfo *PI =
786 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
787 assert(PI && "Expected all immutable passes to be initialized");
788 if (!PI->isAnalysisGroup())
789 dbgs() << " -" << PI->getPassArgument();
791 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
792 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
793 (*I)->dumpPassArguments();
797 void PMTopLevelManager::initializeAllAnalysisInfo() {
798 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
799 E = PassManagers.end(); I != E; ++I)
800 (*I)->initializeAnalysisInfo();
802 // Initailize other pass managers
803 for (SmallVectorImpl<PMDataManager *>::iterator
804 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
806 (*I)->initializeAnalysisInfo();
808 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
809 DME = LastUser.end(); DMI != DME; ++DMI) {
810 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
811 InversedLastUser.find(DMI->second);
812 if (InvDMI != InversedLastUser.end()) {
813 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
814 L.insert(DMI->first);
816 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
817 InversedLastUser[DMI->second] = L;
823 PMTopLevelManager::~PMTopLevelManager() {
824 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
825 E = PassManagers.end(); I != E; ++I)
828 for (SmallVectorImpl<ImmutablePass *>::iterator
829 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
832 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
833 DME = AnUsageMap.end(); DMI != DME; ++DMI)
837 //===----------------------------------------------------------------------===//
838 // PMDataManager implementation
840 /// Augement AvailableAnalysis by adding analysis made available by pass P.
841 void PMDataManager::recordAvailableAnalysis(Pass *P) {
842 AnalysisID PI = P->getPassID();
844 AvailableAnalysis[PI] = P;
846 assert(!AvailableAnalysis.empty());
848 // This pass is the current implementation of all of the interfaces it
849 // implements as well.
850 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
851 if (PInf == 0) return;
852 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
853 for (unsigned i = 0, e = II.size(); i != e; ++i)
854 AvailableAnalysis[II[i]->getTypeInfo()] = P;
857 // Return true if P preserves high level analysis used by other
858 // passes managed by this manager
859 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
860 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
861 if (AnUsage->getPreservesAll())
864 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
865 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
866 E = HigherLevelAnalysis.end(); I != E; ++I) {
868 if (P1->getAsImmutablePass() == 0 &&
869 std::find(PreservedSet.begin(), PreservedSet.end(),
878 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
879 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
880 // Don't do this unless assertions are enabled.
884 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
885 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
887 // Verify preserved analysis
888 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
889 E = PreservedSet.end(); I != E; ++I) {
891 if (Pass *AP = findAnalysisPass(AID, true)) {
892 TimeRegion PassTimer(getPassTimer(AP));
893 AP->verifyAnalysis();
898 /// Remove Analysis not preserved by Pass P
899 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
900 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
901 if (AnUsage->getPreservesAll())
904 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
905 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
906 E = AvailableAnalysis.end(); I != E; ) {
907 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
908 if (Info->second->getAsImmutablePass() == 0 &&
909 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
910 PreservedSet.end()) {
911 // Remove this analysis
912 if (GlobalPassDebugOpts->PassDebugging >= Details) {
913 Pass *S = Info->second;
914 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
915 dbgs() << S->getPassName() << "'\n";
917 AvailableAnalysis.erase(Info);
921 // Check inherited analysis also. If P is not preserving analysis
922 // provided by parent manager then remove it here.
923 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
925 if (!InheritedAnalysis[Index])
928 for (DenseMap<AnalysisID, Pass*>::iterator
929 I = InheritedAnalysis[Index]->begin(),
930 E = InheritedAnalysis[Index]->end(); I != E; ) {
931 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
932 if (Info->second->getAsImmutablePass() == 0 &&
933 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
934 PreservedSet.end()) {
935 // Remove this analysis
936 if (GlobalPassDebugOpts->PassDebugging >= Details) {
937 Pass *S = Info->second;
938 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
939 dbgs() << S->getPassName() << "'\n";
941 InheritedAnalysis[Index]->erase(Info);
947 /// Remove analysis passes that are not used any longer
948 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
949 enum PassDebuggingString DBG_STR) {
951 SmallVector<Pass *, 12> DeadPasses;
953 // If this is a on the fly manager then it does not have TPM.
957 TPM->collectLastUses(DeadPasses, P);
959 if (GlobalPassDebugOpts->PassDebugging >= Details && !DeadPasses.empty()) {
960 dbgs() << " -*- '" << P->getPassName();
961 dbgs() << "' is the last user of following pass instances.";
962 dbgs() << " Free these instances\n";
965 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
966 E = DeadPasses.end(); I != E; ++I)
967 freePass(*I, Msg, DBG_STR);
970 void PMDataManager::freePass(Pass *P, StringRef Msg,
971 enum PassDebuggingString DBG_STR) {
972 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
975 // If the pass crashes releasing memory, remember this.
976 PassManagerPrettyStackEntry X(P);
977 TimeRegion PassTimer(getPassTimer(P));
982 AnalysisID PI = P->getPassID();
983 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
984 // Remove the pass itself (if it is not already removed).
985 AvailableAnalysis.erase(PI);
987 // Remove all interfaces this pass implements, for which it is also
988 // listed as the available implementation.
989 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
990 for (unsigned i = 0, e = II.size(); i != e; ++i) {
991 DenseMap<AnalysisID, Pass*>::iterator Pos =
992 AvailableAnalysis.find(II[i]->getTypeInfo());
993 if (Pos != AvailableAnalysis.end() && Pos->second == P)
994 AvailableAnalysis.erase(Pos);
999 /// Add pass P into the PassVector. Update
1000 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1001 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
1002 // This manager is going to manage pass P. Set up analysis resolver
1004 AnalysisResolver *AR = new AnalysisResolver(*this);
1007 // If a FunctionPass F is the last user of ModulePass info M
1008 // then the F's manager, not F, records itself as a last user of M.
1009 SmallVector<Pass *, 12> TransferLastUses;
1011 if (!ProcessAnalysis) {
1013 PassVector.push_back(P);
1017 // At the moment, this pass is the last user of all required passes.
1018 SmallVector<Pass *, 12> LastUses;
1019 SmallVector<Pass *, 8> RequiredPasses;
1020 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1022 unsigned PDepth = this->getDepth();
1024 collectRequiredAnalysis(RequiredPasses,
1025 ReqAnalysisNotAvailable, P);
1026 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1027 E = RequiredPasses.end(); I != E; ++I) {
1028 Pass *PRequired = *I;
1029 unsigned RDepth = 0;
1031 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1032 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1033 RDepth = DM.getDepth();
1035 if (PDepth == RDepth)
1036 LastUses.push_back(PRequired);
1037 else if (PDepth > RDepth) {
1038 // Let the parent claim responsibility of last use
1039 TransferLastUses.push_back(PRequired);
1040 // Keep track of higher level analysis used by this manager.
1041 HigherLevelAnalysis.push_back(PRequired);
1043 llvm_unreachable("Unable to accommodate Required Pass");
1046 // Set P as P's last user until someone starts using P.
1047 // However, if P is a Pass Manager then it does not need
1048 // to record its last user.
1049 if (P->getAsPMDataManager() == 0)
1050 LastUses.push_back(P);
1051 TPM->setLastUser(LastUses, P);
1053 if (!TransferLastUses.empty()) {
1054 Pass *My_PM = getAsPass();
1055 TPM->setLastUser(TransferLastUses, My_PM);
1056 TransferLastUses.clear();
1059 // Now, take care of required analyses that are not available.
1060 for (SmallVectorImpl<AnalysisID>::iterator
1061 I = ReqAnalysisNotAvailable.begin(),
1062 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1063 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1064 Pass *AnalysisPass = PI->createPass();
1065 this->addLowerLevelRequiredPass(P, AnalysisPass);
1068 // Take a note of analysis required and made available by this pass.
1069 // Remove the analysis not preserved by this pass
1070 removeNotPreservedAnalysis(P);
1071 recordAvailableAnalysis(P);
1074 PassVector.push_back(P);
1078 /// Populate RP with analysis pass that are required by
1079 /// pass P and are available. Populate RP_NotAvail with analysis
1080 /// pass that are required by pass P but are not available.
1081 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1082 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1084 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1085 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1086 for (AnalysisUsage::VectorType::const_iterator
1087 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1088 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1089 RP.push_back(AnalysisPass);
1091 RP_NotAvail.push_back(*I);
1094 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1095 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1096 E = IDs.end(); I != E; ++I) {
1097 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1098 RP.push_back(AnalysisPass);
1100 RP_NotAvail.push_back(*I);
1104 // All Required analyses should be available to the pass as it runs! Here
1105 // we fill in the AnalysisImpls member of the pass so that it can
1106 // successfully use the getAnalysis() method to retrieve the
1107 // implementations it needs.
1109 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1110 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1112 for (AnalysisUsage::VectorType::const_iterator
1113 I = AnUsage->getRequiredSet().begin(),
1114 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1115 Pass *Impl = findAnalysisPass(*I, true);
1117 // This may be analysis pass that is initialized on the fly.
1118 // If that is not the case then it will raise an assert when it is used.
1120 AnalysisResolver *AR = P->getResolver();
1121 assert(AR && "Analysis Resolver is not set");
1122 AR->addAnalysisImplsPair(*I, Impl);
1126 /// Find the pass that implements Analysis AID. If desired pass is not found
1127 /// then return NULL.
1128 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1130 // Check if AvailableAnalysis map has one entry.
1131 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1133 if (I != AvailableAnalysis.end())
1136 // Search Parents through TopLevelManager
1138 return TPM->findAnalysisPass(AID);
1143 // Print list of passes that are last used by P.
1144 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1146 SmallVector<Pass *, 12> LUses;
1148 // If this is a on the fly manager then it does not have TPM.
1152 TPM->collectLastUses(LUses, P);
1154 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1155 E = LUses.end(); I != E; ++I) {
1156 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1157 (*I)->dumpPassStructure(0);
1161 void PMDataManager::dumpPassArguments() const {
1162 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1163 E = PassVector.end(); I != E; ++I) {
1164 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1165 PMD->dumpPassArguments();
1167 if (const PassInfo *PI =
1168 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1169 if (!PI->isAnalysisGroup())
1170 dbgs() << " -" << PI->getPassArgument();
1174 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1175 enum PassDebuggingString S2,
1177 if (GlobalPassDebugOpts->PassDebugging < Executions)
1179 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1182 dbgs() << "Executing Pass '" << P->getPassName();
1184 case MODIFICATION_MSG:
1185 dbgs() << "Made Modification '" << P->getPassName();
1188 dbgs() << " Freeing Pass '" << P->getPassName();
1194 case ON_BASICBLOCK_MSG:
1195 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1197 case ON_FUNCTION_MSG:
1198 dbgs() << "' on Function '" << Msg << "'...\n";
1201 dbgs() << "' on Module '" << Msg << "'...\n";
1204 dbgs() << "' on Region '" << Msg << "'...\n";
1207 dbgs() << "' on Loop '" << Msg << "'...\n";
1210 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1217 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1218 if (GlobalPassDebugOpts->PassDebugging < Details)
1221 AnalysisUsage analysisUsage;
1222 P->getAnalysisUsage(analysisUsage);
1223 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1226 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1227 if (GlobalPassDebugOpts->PassDebugging < Details)
1230 AnalysisUsage analysisUsage;
1231 P->getAnalysisUsage(analysisUsage);
1232 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1235 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1236 const AnalysisUsage::VectorType &Set) const {
1237 assert(GlobalPassDebugOpts->PassDebugging >= Details);
1240 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1241 for (unsigned i = 0; i != Set.size(); ++i) {
1242 if (i) dbgs() << ',';
1243 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1245 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1247 dbgs() << " Uninitialized Pass";
1250 dbgs() << ' ' << PInf->getPassName();
1255 /// Add RequiredPass into list of lower level passes required by pass P.
1256 /// RequiredPass is run on the fly by Pass Manager when P requests it
1257 /// through getAnalysis interface.
1258 /// This should be handled by specific pass manager.
1259 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1261 TPM->dumpArguments();
1265 // Module Level pass may required Function Level analysis info
1266 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1267 // to provide this on demand. In that case, in Pass manager terminology,
1268 // module level pass is requiring lower level analysis info managed by
1269 // lower level pass manager.
1271 // When Pass manager is not able to order required analysis info, Pass manager
1272 // checks whether any lower level manager will be able to provide this
1273 // analysis info on demand or not.
1275 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1276 dbgs() << "' required by '" << P->getPassName() << "'\n";
1278 llvm_unreachable("Unable to schedule pass");
1281 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1282 llvm_unreachable("Unable to find on the fly pass");
1286 PMDataManager::~PMDataManager() {
1287 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1288 E = PassVector.end(); I != E; ++I)
1292 //===----------------------------------------------------------------------===//
1293 // NOTE: Is this the right place to define this method ?
1294 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1295 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1296 return PM.findAnalysisPass(ID, dir);
1299 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1301 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1304 //===----------------------------------------------------------------------===//
1305 // BBPassManager implementation
1307 /// Execute all of the passes scheduled for execution by invoking
1308 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1309 /// the function, and if so, return true.
1310 bool BBPassManager::runOnFunction(Function &F) {
1311 if (F.isDeclaration())
1314 bool Changed = doInitialization(F);
1316 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1317 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1318 BasicBlockPass *BP = getContainedPass(Index);
1319 bool LocalChanged = false;
1321 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1322 dumpRequiredSet(BP);
1324 initializeAnalysisImpl(BP);
1327 // If the pass crashes, remember this.
1328 PassManagerPrettyStackEntry X(BP, *I);
1329 TimeRegion PassTimer(getPassTimer(BP));
1331 LocalChanged |= BP->runOnBasicBlock(*I);
1334 Changed |= LocalChanged;
1336 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1338 dumpPreservedSet(BP);
1340 verifyPreservedAnalysis(BP);
1341 removeNotPreservedAnalysis(BP);
1342 recordAvailableAnalysis(BP);
1343 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1346 return doFinalization(F) || Changed;
1349 // Implement doInitialization and doFinalization
1350 bool BBPassManager::doInitialization(Module &M) {
1351 bool Changed = false;
1353 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1354 Changed |= getContainedPass(Index)->doInitialization(M);
1359 bool BBPassManager::doFinalization(Module &M) {
1360 bool Changed = false;
1362 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1363 Changed |= getContainedPass(Index)->doFinalization(M);
1368 bool BBPassManager::doInitialization(Function &F) {
1369 bool Changed = false;
1371 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1372 BasicBlockPass *BP = getContainedPass(Index);
1373 Changed |= BP->doInitialization(F);
1379 bool BBPassManager::doFinalization(Function &F) {
1380 bool Changed = false;
1382 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1383 BasicBlockPass *BP = getContainedPass(Index);
1384 Changed |= BP->doFinalization(F);
1391 //===----------------------------------------------------------------------===//
1392 // FunctionPassManager implementation
1394 /// Create new Function pass manager
1395 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1396 FPM = new FunctionPassManagerImpl();
1397 // FPM is the top level manager.
1398 FPM->setTopLevelManager(FPM);
1400 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1401 FPM->setResolver(AR);
1404 FunctionPassManager::~FunctionPassManager() {
1408 /// add - Add a pass to the queue of passes to run. This passes
1409 /// ownership of the Pass to the PassManager. When the
1410 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1411 /// there is no need to delete the pass. (TODO delete passes.)
1412 /// This implies that all passes MUST be allocated with 'new'.
1413 void FunctionPassManager::add(Pass *P) {
1417 /// run - Execute all of the passes scheduled for execution. Keep
1418 /// track of whether any of the passes modifies the function, and if
1419 /// so, return true.
1421 bool FunctionPassManager::run(Function &F) {
1422 if (F.isMaterializable()) {
1424 if (F.Materialize(&errstr))
1425 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1431 /// doInitialization - Run all of the initializers for the function passes.
1433 bool FunctionPassManager::doInitialization() {
1434 return FPM->doInitialization(*M);
1437 /// doFinalization - Run all of the finalizers for the function passes.
1439 bool FunctionPassManager::doFinalization() {
1440 return FPM->doFinalization(*M);
1443 //===----------------------------------------------------------------------===//
1444 // FunctionPassManagerImpl implementation
1446 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1447 bool Changed = false;
1452 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1453 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1454 E = IPV.end(); I != E; ++I) {
1455 Changed |= (*I)->doInitialization(M);
1458 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1459 Changed |= getContainedManager(Index)->doInitialization(M);
1464 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1465 bool Changed = false;
1467 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1468 Changed |= getContainedManager(Index)->doFinalization(M);
1470 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1471 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1472 E = IPV.end(); I != E; ++I) {
1473 Changed |= (*I)->doFinalization(M);
1479 /// cleanup - After running all passes, clean up pass manager cache.
1480 void FPPassManager::cleanup() {
1481 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1482 FunctionPass *FP = getContainedPass(Index);
1483 AnalysisResolver *AR = FP->getResolver();
1484 assert(AR && "Analysis Resolver is not set");
1485 AR->clearAnalysisImpls();
1489 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1492 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1493 FPPassManager *FPPM = getContainedManager(Index);
1494 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1495 FPPM->getContainedPass(Index)->releaseMemory();
1501 // Execute all the passes managed by this top level manager.
1502 // Return true if any function is modified by a pass.
1503 bool FunctionPassManagerImpl::run(Function &F) {
1504 bool Changed = false;
1505 TimingInfo::createTheTimeInfo();
1507 initializeAllAnalysisInfo();
1508 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1509 Changed |= getContainedManager(Index)->runOnFunction(F);
1511 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1512 getContainedManager(Index)->cleanup();
1518 //===----------------------------------------------------------------------===//
1519 // FPPassManager implementation
1521 char FPPassManager::ID = 0;
1522 /// Print passes managed by this manager
1523 void FPPassManager::dumpPassStructure(unsigned Offset) {
1524 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1525 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1526 FunctionPass *FP = getContainedPass(Index);
1527 FP->dumpPassStructure(Offset + 1);
1528 dumpLastUses(FP, Offset+1);
1533 /// Execute all of the passes scheduled for execution by invoking
1534 /// runOnFunction method. Keep track of whether any of the passes modifies
1535 /// the function, and if so, return true.
1536 bool FPPassManager::runOnFunction(Function &F) {
1537 if (F.isDeclaration())
1540 bool Changed = false;
1542 // Collect inherited analysis from Module level pass manager.
1543 populateInheritedAnalysis(TPM->activeStack);
1545 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1546 FunctionPass *FP = getContainedPass(Index);
1547 bool LocalChanged = false;
1549 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1550 dumpRequiredSet(FP);
1552 initializeAnalysisImpl(FP);
1555 PassManagerPrettyStackEntry X(FP, F);
1556 TimeRegion PassTimer(getPassTimer(FP));
1558 LocalChanged |= FP->runOnFunction(F);
1561 Changed |= LocalChanged;
1563 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1564 dumpPreservedSet(FP);
1566 verifyPreservedAnalysis(FP);
1567 removeNotPreservedAnalysis(FP);
1568 recordAvailableAnalysis(FP);
1569 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1574 bool FPPassManager::runOnModule(Module &M) {
1575 bool Changed = false;
1577 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1578 Changed |= runOnFunction(*I);
1583 bool FPPassManager::doInitialization(Module &M) {
1584 bool Changed = false;
1586 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1587 Changed |= getContainedPass(Index)->doInitialization(M);
1592 bool FPPassManager::doFinalization(Module &M) {
1593 bool Changed = false;
1595 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1596 Changed |= getContainedPass(Index)->doFinalization(M);
1601 //===----------------------------------------------------------------------===//
1602 // MPPassManager implementation
1604 /// Execute all of the passes scheduled for execution by invoking
1605 /// runOnModule method. Keep track of whether any of the passes modifies
1606 /// the module, and if so, return true.
1608 MPPassManager::runOnModule(Module &M) {
1609 bool Changed = false;
1611 // Initialize on-the-fly passes
1612 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1613 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1615 FunctionPassManagerImpl *FPP = I->second;
1616 Changed |= FPP->doInitialization(M);
1619 // Initialize module passes
1620 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1621 Changed |= getContainedPass(Index)->doInitialization(M);
1623 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1624 ModulePass *MP = getContainedPass(Index);
1625 bool LocalChanged = false;
1627 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1628 dumpRequiredSet(MP);
1630 initializeAnalysisImpl(MP);
1633 PassManagerPrettyStackEntry X(MP, M);
1634 TimeRegion PassTimer(getPassTimer(MP));
1636 LocalChanged |= MP->runOnModule(M);
1639 Changed |= LocalChanged;
1641 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1642 M.getModuleIdentifier());
1643 dumpPreservedSet(MP);
1645 verifyPreservedAnalysis(MP);
1646 removeNotPreservedAnalysis(MP);
1647 recordAvailableAnalysis(MP);
1648 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1651 // Finalize module passes
1652 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1653 Changed |= getContainedPass(Index)->doFinalization(M);
1655 // Finalize on-the-fly passes
1656 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1657 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1659 FunctionPassManagerImpl *FPP = I->second;
1660 // We don't know when is the last time an on-the-fly pass is run,
1661 // so we need to releaseMemory / finalize here
1662 FPP->releaseMemoryOnTheFly();
1663 Changed |= FPP->doFinalization(M);
1669 /// Add RequiredPass into list of lower level passes required by pass P.
1670 /// RequiredPass is run on the fly by Pass Manager when P requests it
1671 /// through getAnalysis interface.
1672 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1673 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1674 "Unable to handle Pass that requires lower level Analysis pass");
1675 assert((P->getPotentialPassManagerType() <
1676 RequiredPass->getPotentialPassManagerType()) &&
1677 "Unable to handle Pass that requires lower level Analysis pass");
1679 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1681 FPP = new FunctionPassManagerImpl();
1682 // FPP is the top level manager.
1683 FPP->setTopLevelManager(FPP);
1685 OnTheFlyManagers[P] = FPP;
1687 FPP->add(RequiredPass);
1689 // Register P as the last user of RequiredPass.
1691 SmallVector<Pass *, 1> LU;
1692 LU.push_back(RequiredPass);
1693 FPP->setLastUser(LU, P);
1697 /// Return function pass corresponding to PassInfo PI, that is
1698 /// required by module pass MP. Instantiate analysis pass, by using
1699 /// its runOnFunction() for function F.
1700 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1701 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1702 assert(FPP && "Unable to find on the fly pass");
1704 FPP->releaseMemoryOnTheFly();
1706 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1710 //===----------------------------------------------------------------------===//
1711 // PassManagerImpl implementation
1714 /// run - Execute all of the passes scheduled for execution. Keep track of
1715 /// whether any of the passes modifies the module, and if so, return true.
1716 bool PassManagerImpl::run(Module &M) {
1717 bool Changed = false;
1718 TimingInfo::createTheTimeInfo();
1723 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1724 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1725 E = IPV.end(); I != E; ++I) {
1726 Changed |= (*I)->doInitialization(M);
1729 initializeAllAnalysisInfo();
1730 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1731 Changed |= getContainedManager(Index)->runOnModule(M);
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 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1773 // a non null value (if the -time-passes option is enabled) or it leaves it
1774 // null. It may be called multiple times.
1775 void TimingInfo::createTheTimeInfo() {
1776 if (!TimePassesIsEnabled || TheTimeInfo) return;
1778 // Constructed the first time this is called, iff -time-passes is enabled.
1779 // This guarantees that the object will be constructed before static globals,
1780 // thus it will be destroyed before them.
1781 static ManagedStatic<TimingInfo> TTI;
1782 TheTimeInfo = &*TTI;
1785 /// If TimingInfo is enabled then start pass timer.
1786 Timer *llvm::getPassTimer(Pass *P) {
1788 return TheTimeInfo->getPassTimer(P);
1792 //===----------------------------------------------------------------------===//
1793 // PMStack implementation
1796 // Pop Pass Manager from the stack and clear its analysis info.
1797 void PMStack::pop() {
1799 PMDataManager *Top = this->top();
1800 Top->initializeAnalysisInfo();
1805 // Push PM on the stack and set its top level manager.
1806 void PMStack::push(PMDataManager *PM) {
1807 assert(PM && "Unable to push. Pass Manager expected");
1808 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1810 if (!this->empty()) {
1811 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1812 && "pushing bad pass manager to PMStack");
1813 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1815 assert(TPM && "Unable to find top level manager");
1816 TPM->addIndirectPassManager(PM);
1817 PM->setTopLevelManager(TPM);
1818 PM->setDepth(this->top()->getDepth()+1);
1820 assert((PM->getPassManagerType() == PMT_ModulePassManager
1821 || PM->getPassManagerType() == PMT_FunctionPassManager)
1822 && "pushing bad pass manager to PMStack");
1829 // Dump content of the pass manager stack.
1830 void PMStack::dump() const {
1831 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1832 E = S.end(); I != E; ++I)
1833 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1839 /// Find appropriate Module Pass Manager in the PM Stack and
1840 /// add self into that manager.
1841 void ModulePass::assignPassManager(PMStack &PMS,
1842 PassManagerType PreferredType) {
1843 // Find Module Pass Manager
1844 while (!PMS.empty()) {
1845 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1846 if (TopPMType == PreferredType)
1847 break; // We found desired pass manager
1848 else if (TopPMType > PMT_ModulePassManager)
1849 PMS.pop(); // Pop children pass managers
1853 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1854 PMS.top()->add(this);
1857 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1858 /// in the PM Stack and add self into that manager.
1859 void FunctionPass::assignPassManager(PMStack &PMS,
1860 PassManagerType PreferredType) {
1862 // Find Function Pass Manager
1863 while (!PMS.empty()) {
1864 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1870 // Create new Function Pass Manager if needed.
1872 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1873 FPP = (FPPassManager *)PMS.top();
1875 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1876 PMDataManager *PMD = PMS.top();
1878 // [1] Create new Function Pass Manager
1879 FPP = new FPPassManager();
1880 FPP->populateInheritedAnalysis(PMS);
1882 // [2] Set up new manager's top level manager
1883 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1884 TPM->addIndirectPassManager(FPP);
1886 // [3] Assign manager to manage this new manager. This may create
1887 // and push new managers into PMS
1888 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1890 // [4] Push new manager into PMS
1894 // Assign FPP as the manager of this pass.
1898 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1899 /// in the PM Stack and add self into that manager.
1900 void BasicBlockPass::assignPassManager(PMStack &PMS,
1901 PassManagerType PreferredType) {
1904 // Basic Pass Manager is a leaf pass manager. It does not handle
1905 // any other pass manager.
1907 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1908 BBP = (BBPassManager *)PMS.top();
1910 // If leaf manager is not Basic Block Pass manager then create new
1911 // basic Block Pass manager.
1912 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1913 PMDataManager *PMD = PMS.top();
1915 // [1] Create new Basic Block Manager
1916 BBP = new BBPassManager();
1918 // [2] Set up new manager's top level manager
1919 // Basic Block Pass Manager does not live by itself
1920 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1921 TPM->addIndirectPassManager(BBP);
1923 // [3] Assign manager to manage this new manager. This may create
1924 // and push new managers into PMS
1925 BBP->assignPassManager(PMS, PreferredType);
1927 // [4] Push new manager into PMS
1931 // Assign BBP as the manager of this pass.
1935 PassManagerBase::~PassManagerBase() {}