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/PassManager.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Timer.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/Mutex.h"
33 // See PassManagers.h for Pass Manager infrastructure overview.
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information. Often it is useful to find out what pass is
39 // running when a crash occurs in a utility. When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
44 // Different debug levels that can be enabled...
46 None, Arguments, Structure, Executions, Details
49 static cl::opt<enum PassDebugLevel>
50 PassDebugging("debug-pass", cl::Hidden,
51 cl::desc("Print PassManager debugging information"),
53 clEnumVal(None , "disable debug output"),
54 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
55 clEnumVal(Structure , "print pass structure before run()"),
56 clEnumVal(Executions, "print pass name before it is executed"),
57 clEnumVal(Details , "print pass details when it is executed"),
60 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
63 // Print IR out before/after specified passes.
65 PrintBefore("print-before",
66 llvm::cl::desc("Print IR before specified passes"));
69 PrintAfter("print-after",
70 llvm::cl::desc("Print IR after specified passes"));
73 PrintBeforeAll("print-before-all",
74 llvm::cl::desc("Print IR before each pass"),
77 PrintAfterAll("print-after-all",
78 llvm::cl::desc("Print IR after each pass"),
81 /// This is a helper to determine whether to print IR before or
84 static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
85 PassOptionList &PassesToPrint) {
86 if (const llvm::PassInfo *PI =
87 PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
88 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
89 const llvm::PassInfo *PassInf = PassesToPrint[i];
91 if (PassInf->getPassArgument() == PI->getPassArgument()) {
100 /// This is a utility to check whether a pass should have IR dumped
102 static bool ShouldPrintBeforePass(const void *PassID) {
103 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
106 /// This is a utility to check whether a pass should have IR dumped
108 static bool ShouldPrintAfterPass(const void *PassID) {
109 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
112 } // End of llvm namespace
114 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
115 /// or higher is specified.
116 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
117 return PassDebugging >= Executions;
123 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
124 if (V == 0 && M == 0)
125 OS << "Releasing pass '";
127 OS << "Running pass '";
129 OS << P->getPassName() << "'";
132 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
141 if (isa<Function>(V))
143 else if (isa<BasicBlock>(V))
149 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
156 //===----------------------------------------------------------------------===//
159 /// BBPassManager manages BasicBlockPass. It batches all the
160 /// pass together and sequence them to process one basic block before
161 /// processing next basic block.
162 class BBPassManager : public PMDataManager, public FunctionPass {
166 explicit BBPassManager(int Depth)
167 : PMDataManager(Depth), FunctionPass(ID) {}
169 /// Execute all of the passes scheduled for execution. Keep track of
170 /// whether any of the passes modifies the function, and if so, return true.
171 bool runOnFunction(Function &F);
173 /// Pass Manager itself does not invalidate any analysis info.
174 void getAnalysisUsage(AnalysisUsage &Info) const {
175 Info.setPreservesAll();
178 bool doInitialization(Module &M);
179 bool doInitialization(Function &F);
180 bool doFinalization(Module &M);
181 bool doFinalization(Function &F);
183 virtual PMDataManager *getAsPMDataManager() { return this; }
184 virtual Pass *getAsPass() { return this; }
186 virtual const char *getPassName() const {
187 return "BasicBlock Pass Manager";
190 // Print passes managed by this manager
191 void dumpPassStructure(unsigned Offset) {
192 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
193 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
194 BasicBlockPass *BP = getContainedPass(Index);
195 BP->dumpPassStructure(Offset + 1);
196 dumpLastUses(BP, Offset+1);
200 BasicBlockPass *getContainedPass(unsigned N) {
201 assert(N < PassVector.size() && "Pass number out of range!");
202 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
206 virtual PassManagerType getPassManagerType() const {
207 return PMT_BasicBlockPassManager;
211 char BBPassManager::ID = 0;
216 //===----------------------------------------------------------------------===//
217 // FunctionPassManagerImpl
219 /// FunctionPassManagerImpl manages FPPassManagers
220 class FunctionPassManagerImpl : public Pass,
221 public PMDataManager,
222 public PMTopLevelManager {
227 explicit FunctionPassManagerImpl(int Depth) :
228 Pass(PT_PassManager, ID), PMDataManager(Depth),
229 PMTopLevelManager(new FPPassManager(1)), wasRun(false) {}
231 /// add - Add a pass to the queue of passes to run. This passes ownership of
232 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
233 /// will be destroyed as well, so there is no need to delete the pass. This
234 /// implies that all passes MUST be allocated with 'new'.
239 /// createPrinterPass - Get a function printer pass.
240 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
241 return createPrintFunctionPass(Banner, &O);
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);
256 /// doFinalization - Run all of the finalizers for the function passes.
258 bool doFinalization(Module &M);
261 virtual PMDataManager *getAsPMDataManager() { return this; }
262 virtual Pass *getAsPass() { return this; }
264 /// Pass Manager itself does not invalidate any analysis info.
265 void getAnalysisUsage(AnalysisUsage &Info) const {
266 Info.setPreservesAll();
269 void addTopLevelPass(Pass *P) {
270 if (ImmutablePass *IP = P->getAsImmutablePass()) {
271 // P is a immutable pass and it will be managed by this
272 // top level manager. Set up analysis resolver to connect them.
273 AnalysisResolver *AR = new AnalysisResolver(*this);
275 initializeAnalysisImpl(P);
276 addImmutablePass(IP);
277 recordAvailableAnalysis(IP);
279 P->assignPassManager(activeStack, PMT_FunctionPassManager);
284 FPPassManager *getContainedManager(unsigned N) {
285 assert(N < PassManagers.size() && "Pass number out of range!");
286 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
291 char FunctionPassManagerImpl::ID = 0;
293 //===----------------------------------------------------------------------===//
296 /// MPPassManager manages ModulePasses and function pass managers.
297 /// It batches all Module passes and function pass managers together and
298 /// sequences them to process one module.
299 class MPPassManager : public Pass, public PMDataManager {
302 explicit MPPassManager(int Depth) :
303 Pass(PT_PassManager, ID), PMDataManager(Depth) { }
305 // Delete on the fly managers.
306 virtual ~MPPassManager() {
307 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
308 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
310 FunctionPassManagerImpl *FPP = I->second;
315 /// createPrinterPass - Get a module printer pass.
316 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
317 return createPrintModulePass(&O, false, Banner);
320 /// run - Execute all of the passes scheduled for execution. Keep track of
321 /// whether any of the passes modifies the module, and if so, return true.
322 bool runOnModule(Module &M);
324 /// Pass Manager itself does not invalidate any analysis info.
325 void getAnalysisUsage(AnalysisUsage &Info) const {
326 Info.setPreservesAll();
329 /// Add RequiredPass into list of lower level passes required by pass P.
330 /// RequiredPass is run on the fly by Pass Manager when P requests it
331 /// through getAnalysis interface.
332 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
334 /// Return function pass corresponding to PassInfo PI, that is
335 /// required by module pass MP. Instantiate analysis pass, by using
336 /// its runOnFunction() for function F.
337 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
339 virtual const char *getPassName() const {
340 return "Module Pass Manager";
343 virtual PMDataManager *getAsPMDataManager() { return this; }
344 virtual Pass *getAsPass() { return this; }
346 // Print passes managed by this manager
347 void dumpPassStructure(unsigned Offset) {
348 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
350 ModulePass *MP = getContainedPass(Index);
351 MP->dumpPassStructure(Offset + 1);
352 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
353 OnTheFlyManagers.find(MP);
354 if (I != OnTheFlyManagers.end())
355 I->second->dumpPassStructure(Offset + 2);
356 dumpLastUses(MP, Offset+1);
360 ModulePass *getContainedPass(unsigned N) {
361 assert(N < PassVector.size() && "Pass number out of range!");
362 return static_cast<ModulePass *>(PassVector[N]);
365 virtual PassManagerType getPassManagerType() const {
366 return PMT_ModulePassManager;
370 /// Collection of on the fly FPPassManagers. These managers manage
371 /// function passes that are required by module passes.
372 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
375 char MPPassManager::ID = 0;
376 //===----------------------------------------------------------------------===//
380 /// PassManagerImpl manages MPPassManagers
381 class PassManagerImpl : public Pass,
382 public PMDataManager,
383 public PMTopLevelManager {
387 explicit PassManagerImpl(int Depth) :
388 Pass(PT_PassManager, ID), PMDataManager(Depth),
389 PMTopLevelManager(new MPPassManager(1)) {}
391 /// add - Add a pass to the queue of passes to run. This passes ownership of
392 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
393 /// will be destroyed as well, so there is no need to delete the pass. This
394 /// implies that all passes MUST be allocated with 'new'.
399 /// createPrinterPass - Get a module printer pass.
400 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401 return createPrintModulePass(&O, false, Banner);
404 /// run - Execute all of the passes scheduled for execution. Keep track of
405 /// whether any of the passes modifies the module, and if so, return true.
408 /// Pass Manager itself does not invalidate any analysis info.
409 void getAnalysisUsage(AnalysisUsage &Info) const {
410 Info.setPreservesAll();
413 void addTopLevelPass(Pass *P) {
414 if (ImmutablePass *IP = P->getAsImmutablePass()) {
415 // P is a immutable pass and it will be managed by this
416 // top level manager. Set up analysis resolver to connect them.
417 AnalysisResolver *AR = new AnalysisResolver(*this);
419 initializeAnalysisImpl(P);
420 addImmutablePass(IP);
421 recordAvailableAnalysis(IP);
423 P->assignPassManager(activeStack, PMT_ModulePassManager);
427 virtual PMDataManager *getAsPMDataManager() { return this; }
428 virtual Pass *getAsPass() { return this; }
430 MPPassManager *getContainedManager(unsigned N) {
431 assert(N < PassManagers.size() && "Pass number out of range!");
432 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
437 char PassManagerImpl::ID = 0;
438 } // End of llvm namespace
442 //===----------------------------------------------------------------------===//
443 /// TimingInfo Class - This class is used to calculate information about the
444 /// amount of time each pass takes to execute. This only happens when
445 /// -time-passes is enabled on the command line.
448 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
451 DenseMap<Pass*, Timer*> TimingData;
454 // Use 'create' member to get this.
455 TimingInfo() : TG("... Pass execution timing report ...") {}
457 // TimingDtor - Print out information about timing information
459 // Delete all of the timers, which accumulate their info into the
461 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
462 E = TimingData.end(); I != E; ++I)
464 // TimerGroup is deleted next, printing the report.
467 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
468 // to a non null value (if the -time-passes option is enabled) or it leaves it
469 // null. It may be called multiple times.
470 static void createTheTimeInfo();
472 /// getPassTimer - Return the timer for the specified pass if it exists.
473 Timer *getPassTimer(Pass *P) {
474 if (P->getAsPMDataManager())
477 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
478 Timer *&T = TimingData[P];
480 T = new Timer(P->getPassName(), TG);
485 } // End of anon namespace
487 static TimingInfo *TheTimeInfo;
489 //===----------------------------------------------------------------------===//
490 // PMTopLevelManager implementation
492 /// Initialize top level manager. Create first pass manager.
493 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
494 PMDM->setTopLevelManager(this);
495 addPassManager(PMDM);
496 activeStack.push(PMDM);
499 /// Set pass P as the last user of the given analysis passes.
501 PMTopLevelManager::setLastUser(const SmallVectorImpl<Pass *> &AnalysisPasses,
503 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
504 E = AnalysisPasses.end(); I != E; ++I) {
511 // If AP is the last user of other passes then make P last user of
513 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
514 LUE = LastUser.end(); LUI != LUE; ++LUI) {
515 if (LUI->second == AP)
516 // DenseMap iterator is not invalidated here because
517 // this is just updating exisitng entry.
518 LastUser[LUI->first] = P;
523 /// Collect passes whose last user is P
524 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
526 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
527 InversedLastUser.find(P);
528 if (DMI == InversedLastUser.end())
531 SmallPtrSet<Pass *, 8> &LU = DMI->second;
532 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
533 E = LU.end(); I != E; ++I) {
534 LastUses.push_back(*I);
539 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
540 AnalysisUsage *AnUsage = NULL;
541 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
542 if (DMI != AnUsageMap.end())
543 AnUsage = DMI->second;
545 AnUsage = new AnalysisUsage();
546 P->getAnalysisUsage(*AnUsage);
547 AnUsageMap[P] = AnUsage;
552 /// Schedule pass P for execution. Make sure that passes required by
553 /// P are run before P is run. Update analysis info maintained by
554 /// the manager. Remove dead passes. This is a recursive function.
555 void PMTopLevelManager::schedulePass(Pass *P) {
557 // TODO : Allocate function manager for this pass, other wise required set
558 // may be inserted into previous function manager
560 // Give pass a chance to prepare the stage.
561 P->preparePassManager(activeStack);
563 // If P is an analysis pass and it is available then do not
564 // generate the analysis again. Stale analysis info should not be
565 // available at this point.
567 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
568 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
573 AnalysisUsage *AnUsage = findAnalysisUsage(P);
575 bool checkAnalysis = true;
576 while (checkAnalysis) {
577 checkAnalysis = false;
579 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
580 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
581 E = RequiredSet.end(); I != E; ++I) {
583 Pass *AnalysisPass = findAnalysisPass(*I);
585 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
586 AnalysisPass = PI->createPass();
587 if (P->getPotentialPassManagerType () ==
588 AnalysisPass->getPotentialPassManagerType())
589 // Schedule analysis pass that is managed by the same pass manager.
590 schedulePass(AnalysisPass);
591 else if (P->getPotentialPassManagerType () >
592 AnalysisPass->getPotentialPassManagerType()) {
593 // Schedule analysis pass that is managed by a new manager.
594 schedulePass(AnalysisPass);
595 // Recheck analysis passes to ensure that required analyses that
596 // are already checked are still available.
597 checkAnalysis = true;
600 // Do not schedule this analysis. Lower level analsyis
601 // passes are run on the fly.
607 // Now all required passes are available.
611 /// Find the pass that implements Analysis AID. Search immutable
612 /// passes and all pass managers. If desired pass is not found
613 /// then return NULL.
614 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
616 // Check pass managers
617 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
618 E = PassManagers.end(); I != E; ++I)
619 if (Pass *P = (*I)->findAnalysisPass(AID, false))
622 // Check other pass managers
623 for (SmallVectorImpl<PMDataManager *>::iterator
624 I = IndirectPassManagers.begin(),
625 E = IndirectPassManagers.end(); I != E; ++I)
626 if (Pass *P = (*I)->findAnalysisPass(AID, false))
629 // Check the immutable passes. Iterate in reverse order so that we find
630 // the most recently registered passes first.
631 for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
632 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
633 AnalysisID PI = (*I)->getPassID();
637 // If Pass not found then check the interfaces implemented by Immutable Pass
638 const PassInfo *PassInf =
639 PassRegistry::getPassRegistry()->getPassInfo(PI);
640 const std::vector<const PassInfo*> &ImmPI =
641 PassInf->getInterfacesImplemented();
642 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
643 EE = ImmPI.end(); II != EE; ++II) {
644 if ((*II)->getTypeInfo() == AID)
652 // Print passes managed by this top level manager.
653 void PMTopLevelManager::dumpPasses() const {
655 if (PassDebugging < Structure)
658 // Print out the immutable passes
659 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
660 ImmutablePasses[i]->dumpPassStructure(0);
663 // Every class that derives from PMDataManager also derives from Pass
664 // (sometimes indirectly), but there's no inheritance relationship
665 // between PMDataManager and Pass, so we have to getAsPass to get
666 // from a PMDataManager* to a Pass*.
667 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
668 E = PassManagers.end(); I != E; ++I)
669 (*I)->getAsPass()->dumpPassStructure(1);
672 void PMTopLevelManager::dumpArguments() const {
674 if (PassDebugging < Arguments)
677 dbgs() << "Pass Arguments: ";
678 for (SmallVector<ImmutablePass *, 8>::const_iterator I =
679 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
680 if (const PassInfo *PI =
681 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
682 if (!PI->isAnalysisGroup())
683 dbgs() << " -" << PI->getPassArgument();
684 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
685 E = PassManagers.end(); I != E; ++I)
686 (*I)->dumpPassArguments();
690 void PMTopLevelManager::initializeAllAnalysisInfo() {
691 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
692 E = PassManagers.end(); I != E; ++I)
693 (*I)->initializeAnalysisInfo();
695 // Initailize other pass managers
696 for (SmallVectorImpl<PMDataManager *>::iterator
697 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
699 (*I)->initializeAnalysisInfo();
701 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
702 DME = LastUser.end(); DMI != DME; ++DMI) {
703 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
704 InversedLastUser.find(DMI->second);
705 if (InvDMI != InversedLastUser.end()) {
706 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
707 L.insert(DMI->first);
709 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
710 InversedLastUser[DMI->second] = L;
716 PMTopLevelManager::~PMTopLevelManager() {
717 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
718 E = PassManagers.end(); I != E; ++I)
721 for (SmallVectorImpl<ImmutablePass *>::iterator
722 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
725 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
726 DME = AnUsageMap.end(); DMI != DME; ++DMI)
730 //===----------------------------------------------------------------------===//
731 // PMDataManager implementation
733 /// Augement AvailableAnalysis by adding analysis made available by pass P.
734 void PMDataManager::recordAvailableAnalysis(Pass *P) {
735 AnalysisID PI = P->getPassID();
737 AvailableAnalysis[PI] = P;
739 assert(!AvailableAnalysis.empty());
741 // This pass is the current implementation of all of the interfaces it
742 // implements as well.
743 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
744 if (PInf == 0) return;
745 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
746 for (unsigned i = 0, e = II.size(); i != e; ++i)
747 AvailableAnalysis[II[i]->getTypeInfo()] = P;
750 // Return true if P preserves high level analysis used by other
751 // passes managed by this manager
752 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
753 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
754 if (AnUsage->getPreservesAll())
757 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
758 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
759 E = HigherLevelAnalysis.end(); I != E; ++I) {
761 if (P1->getAsImmutablePass() == 0 &&
762 std::find(PreservedSet.begin(), PreservedSet.end(),
771 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
772 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
773 // Don't do this unless assertions are enabled.
777 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
778 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
780 // Verify preserved analysis
781 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
782 E = PreservedSet.end(); I != E; ++I) {
784 if (Pass *AP = findAnalysisPass(AID, true)) {
785 TimeRegion PassTimer(getPassTimer(AP));
786 AP->verifyAnalysis();
791 /// Remove Analysis not preserved by Pass P
792 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
793 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
794 if (AnUsage->getPreservesAll())
797 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
798 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
799 E = AvailableAnalysis.end(); I != E; ) {
800 std::map<AnalysisID, Pass*>::iterator Info = I++;
801 if (Info->second->getAsImmutablePass() == 0 &&
802 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
803 PreservedSet.end()) {
804 // Remove this analysis
805 if (PassDebugging >= Details) {
806 Pass *S = Info->second;
807 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
808 dbgs() << S->getPassName() << "'\n";
810 AvailableAnalysis.erase(Info);
814 // Check inherited analysis also. If P is not preserving analysis
815 // provided by parent manager then remove it here.
816 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
818 if (!InheritedAnalysis[Index])
821 for (std::map<AnalysisID, Pass*>::iterator
822 I = InheritedAnalysis[Index]->begin(),
823 E = InheritedAnalysis[Index]->end(); I != E; ) {
824 std::map<AnalysisID, Pass *>::iterator Info = I++;
825 if (Info->second->getAsImmutablePass() == 0 &&
826 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
827 PreservedSet.end()) {
828 // Remove this analysis
829 if (PassDebugging >= Details) {
830 Pass *S = Info->second;
831 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
832 dbgs() << S->getPassName() << "'\n";
834 InheritedAnalysis[Index]->erase(Info);
840 /// Remove analysis passes that are not used any longer
841 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
842 enum PassDebuggingString DBG_STR) {
844 SmallVector<Pass *, 12> DeadPasses;
846 // If this is a on the fly manager then it does not have TPM.
850 TPM->collectLastUses(DeadPasses, P);
852 if (PassDebugging >= Details && !DeadPasses.empty()) {
853 dbgs() << " -*- '" << P->getPassName();
854 dbgs() << "' is the last user of following pass instances.";
855 dbgs() << " Free these instances\n";
858 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
859 E = DeadPasses.end(); I != E; ++I)
860 freePass(*I, Msg, DBG_STR);
863 void PMDataManager::freePass(Pass *P, StringRef Msg,
864 enum PassDebuggingString DBG_STR) {
865 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
868 // If the pass crashes releasing memory, remember this.
869 PassManagerPrettyStackEntry X(P);
870 TimeRegion PassTimer(getPassTimer(P));
875 AnalysisID PI = P->getPassID();
876 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
877 // Remove the pass itself (if it is not already removed).
878 AvailableAnalysis.erase(PI);
880 // Remove all interfaces this pass implements, for which it is also
881 // listed as the available implementation.
882 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
883 for (unsigned i = 0, e = II.size(); i != e; ++i) {
884 std::map<AnalysisID, Pass*>::iterator Pos =
885 AvailableAnalysis.find(II[i]->getTypeInfo());
886 if (Pos != AvailableAnalysis.end() && Pos->second == P)
887 AvailableAnalysis.erase(Pos);
892 /// Add pass P into the PassVector. Update
893 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
894 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
895 // This manager is going to manage pass P. Set up analysis resolver
897 AnalysisResolver *AR = new AnalysisResolver(*this);
900 // If a FunctionPass F is the last user of ModulePass info M
901 // then the F's manager, not F, records itself as a last user of M.
902 SmallVector<Pass *, 12> TransferLastUses;
904 if (!ProcessAnalysis) {
906 PassVector.push_back(P);
910 // At the moment, this pass is the last user of all required passes.
911 SmallVector<Pass *, 12> LastUses;
912 SmallVector<Pass *, 8> RequiredPasses;
913 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
915 unsigned PDepth = this->getDepth();
917 collectRequiredAnalysis(RequiredPasses,
918 ReqAnalysisNotAvailable, P);
919 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
920 E = RequiredPasses.end(); I != E; ++I) {
921 Pass *PRequired = *I;
924 assert(PRequired->getResolver() && "Analysis Resolver is not set");
925 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
926 RDepth = DM.getDepth();
928 if (PDepth == RDepth)
929 LastUses.push_back(PRequired);
930 else if (PDepth > RDepth) {
931 // Let the parent claim responsibility of last use
932 TransferLastUses.push_back(PRequired);
933 // Keep track of higher level analysis used by this manager.
934 HigherLevelAnalysis.push_back(PRequired);
936 llvm_unreachable("Unable to accomodate Required Pass");
939 // Set P as P's last user until someone starts using P.
940 // However, if P is a Pass Manager then it does not need
941 // to record its last user.
942 if (P->getAsPMDataManager() == 0)
943 LastUses.push_back(P);
944 TPM->setLastUser(LastUses, P);
946 if (!TransferLastUses.empty()) {
947 Pass *My_PM = getAsPass();
948 TPM->setLastUser(TransferLastUses, My_PM);
949 TransferLastUses.clear();
952 // Now, take care of required analyses that are not available.
953 for (SmallVectorImpl<AnalysisID>::iterator
954 I = ReqAnalysisNotAvailable.begin(),
955 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
956 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
957 Pass *AnalysisPass = PI->createPass();
958 this->addLowerLevelRequiredPass(P, AnalysisPass);
961 // Take a note of analysis required and made available by this pass.
962 // Remove the analysis not preserved by this pass
963 removeNotPreservedAnalysis(P);
964 recordAvailableAnalysis(P);
967 PassVector.push_back(P);
971 /// Populate RP with analysis pass that are required by
972 /// pass P and are available. Populate RP_NotAvail with analysis
973 /// pass that are required by pass P but are not available.
974 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
975 SmallVectorImpl<AnalysisID> &RP_NotAvail,
977 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
978 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
979 for (AnalysisUsage::VectorType::const_iterator
980 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
981 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
982 RP.push_back(AnalysisPass);
984 RP_NotAvail.push_back(*I);
987 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
988 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
989 E = IDs.end(); I != E; ++I) {
990 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
991 RP.push_back(AnalysisPass);
993 RP_NotAvail.push_back(*I);
997 // All Required analyses should be available to the pass as it runs! Here
998 // we fill in the AnalysisImpls member of the pass so that it can
999 // successfully use the getAnalysis() method to retrieve the
1000 // implementations it needs.
1002 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1003 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1005 for (AnalysisUsage::VectorType::const_iterator
1006 I = AnUsage->getRequiredSet().begin(),
1007 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1008 Pass *Impl = findAnalysisPass(*I, true);
1010 // This may be analysis pass that is initialized on the fly.
1011 // If that is not the case then it will raise an assert when it is used.
1013 AnalysisResolver *AR = P->getResolver();
1014 assert(AR && "Analysis Resolver is not set");
1015 AR->addAnalysisImplsPair(*I, Impl);
1019 /// Find the pass that implements Analysis AID. If desired pass is not found
1020 /// then return NULL.
1021 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1023 // Check if AvailableAnalysis map has one entry.
1024 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1026 if (I != AvailableAnalysis.end())
1029 // Search Parents through TopLevelManager
1031 return TPM->findAnalysisPass(AID);
1036 // Print list of passes that are last used by P.
1037 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1039 SmallVector<Pass *, 12> LUses;
1041 // If this is a on the fly manager then it does not have TPM.
1045 TPM->collectLastUses(LUses, P);
1047 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1048 E = LUses.end(); I != E; ++I) {
1049 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1050 (*I)->dumpPassStructure(0);
1054 void PMDataManager::dumpPassArguments() const {
1055 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1056 E = PassVector.end(); I != E; ++I) {
1057 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1058 PMD->dumpPassArguments();
1060 if (const PassInfo *PI =
1061 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1062 if (!PI->isAnalysisGroup())
1063 dbgs() << " -" << PI->getPassArgument();
1067 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1068 enum PassDebuggingString S2,
1070 if (PassDebugging < Executions)
1072 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1075 dbgs() << "Executing Pass '" << P->getPassName();
1077 case MODIFICATION_MSG:
1078 dbgs() << "Made Modification '" << P->getPassName();
1081 dbgs() << " Freeing Pass '" << P->getPassName();
1087 case ON_BASICBLOCK_MSG:
1088 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1090 case ON_FUNCTION_MSG:
1091 dbgs() << "' on Function '" << Msg << "'...\n";
1094 dbgs() << "' on Module '" << Msg << "'...\n";
1097 dbgs() << "' on Region '" << Msg << "'...\n";
1100 dbgs() << "' on Loop '" << Msg << "'...\n";
1103 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1110 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1111 if (PassDebugging < Details)
1114 AnalysisUsage analysisUsage;
1115 P->getAnalysisUsage(analysisUsage);
1116 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1119 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1120 if (PassDebugging < Details)
1123 AnalysisUsage analysisUsage;
1124 P->getAnalysisUsage(analysisUsage);
1125 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1128 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1129 const AnalysisUsage::VectorType &Set) const {
1130 assert(PassDebugging >= Details);
1133 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1134 for (unsigned i = 0; i != Set.size(); ++i) {
1135 if (i) dbgs() << ',';
1136 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1137 dbgs() << ' ' << PInf->getPassName();
1142 /// Add RequiredPass into list of lower level passes required by pass P.
1143 /// RequiredPass is run on the fly by Pass Manager when P requests it
1144 /// through getAnalysis interface.
1145 /// This should be handled by specific pass manager.
1146 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1148 TPM->dumpArguments();
1152 // Module Level pass may required Function Level analysis info
1153 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1154 // to provide this on demand. In that case, in Pass manager terminology,
1155 // module level pass is requiring lower level analysis info managed by
1156 // lower level pass manager.
1158 // When Pass manager is not able to order required analysis info, Pass manager
1159 // checks whether any lower level manager will be able to provide this
1160 // analysis info on demand or not.
1162 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1163 dbgs() << "' required by '" << P->getPassName() << "'\n";
1165 llvm_unreachable("Unable to schedule pass");
1168 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1169 assert(0 && "Unable to find on the fly pass");
1174 PMDataManager::~PMDataManager() {
1175 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1176 E = PassVector.end(); I != E; ++I)
1180 //===----------------------------------------------------------------------===//
1181 // NOTE: Is this the right place to define this method ?
1182 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1183 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1184 return PM.findAnalysisPass(ID, dir);
1187 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1189 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1192 //===----------------------------------------------------------------------===//
1193 // BBPassManager implementation
1195 /// Execute all of the passes scheduled for execution by invoking
1196 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1197 /// the function, and if so, return true.
1198 bool BBPassManager::runOnFunction(Function &F) {
1199 if (F.isDeclaration())
1202 bool Changed = doInitialization(F);
1204 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1205 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1206 BasicBlockPass *BP = getContainedPass(Index);
1207 bool LocalChanged = false;
1209 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1210 dumpRequiredSet(BP);
1212 initializeAnalysisImpl(BP);
1215 // If the pass crashes, remember this.
1216 PassManagerPrettyStackEntry X(BP, *I);
1217 TimeRegion PassTimer(getPassTimer(BP));
1219 LocalChanged |= BP->runOnBasicBlock(*I);
1222 Changed |= LocalChanged;
1224 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1226 dumpPreservedSet(BP);
1228 verifyPreservedAnalysis(BP);
1229 removeNotPreservedAnalysis(BP);
1230 recordAvailableAnalysis(BP);
1231 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1234 return doFinalization(F) || Changed;
1237 // Implement doInitialization and doFinalization
1238 bool BBPassManager::doInitialization(Module &M) {
1239 bool Changed = false;
1241 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1242 Changed |= getContainedPass(Index)->doInitialization(M);
1247 bool BBPassManager::doFinalization(Module &M) {
1248 bool Changed = false;
1250 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1251 Changed |= getContainedPass(Index)->doFinalization(M);
1256 bool BBPassManager::doInitialization(Function &F) {
1257 bool Changed = false;
1259 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1260 BasicBlockPass *BP = getContainedPass(Index);
1261 Changed |= BP->doInitialization(F);
1267 bool BBPassManager::doFinalization(Function &F) {
1268 bool Changed = false;
1270 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1271 BasicBlockPass *BP = getContainedPass(Index);
1272 Changed |= BP->doFinalization(F);
1279 //===----------------------------------------------------------------------===//
1280 // FunctionPassManager implementation
1282 /// Create new Function pass manager
1283 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1284 FPM = new FunctionPassManagerImpl(0);
1285 // FPM is the top level manager.
1286 FPM->setTopLevelManager(FPM);
1288 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1289 FPM->setResolver(AR);
1292 FunctionPassManager::~FunctionPassManager() {
1296 /// addImpl - Add a pass to the queue of passes to run, without
1297 /// checking whether to add a printer pass.
1298 void FunctionPassManager::addImpl(Pass *P) {
1302 /// add - Add a pass to the queue of passes to run. This passes
1303 /// ownership of the Pass to the PassManager. When the
1304 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1305 /// there is no need to delete the pass. (TODO delete passes.)
1306 /// This implies that all passes MUST be allocated with 'new'.
1307 void FunctionPassManager::add(Pass *P) {
1308 // If this is a not a function pass, don't add a printer for it.
1309 const void *PassID = P->getPassID();
1310 if (P->getPassKind() == PT_Function)
1311 if (ShouldPrintBeforePass(PassID))
1312 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1313 + P->getPassName() + " ***"));
1317 if (P->getPassKind() == PT_Function)
1318 if (ShouldPrintAfterPass(PassID))
1319 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1320 + P->getPassName() + " ***"));
1323 /// run - Execute all of the passes scheduled for execution. Keep
1324 /// track of whether any of the passes modifies the function, and if
1325 /// so, return true.
1327 bool FunctionPassManager::run(Function &F) {
1328 if (F.isMaterializable()) {
1330 if (F.Materialize(&errstr))
1331 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1337 /// doInitialization - Run all of the initializers for the function passes.
1339 bool FunctionPassManager::doInitialization() {
1340 return FPM->doInitialization(*M);
1343 /// doFinalization - Run all of the finalizers for the function passes.
1345 bool FunctionPassManager::doFinalization() {
1346 return FPM->doFinalization(*M);
1349 //===----------------------------------------------------------------------===//
1350 // FunctionPassManagerImpl implementation
1352 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1353 bool Changed = false;
1358 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1359 Changed |= getContainedManager(Index)->doInitialization(M);
1364 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1365 bool Changed = false;
1367 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1368 Changed |= getContainedManager(Index)->doFinalization(M);
1373 /// cleanup - After running all passes, clean up pass manager cache.
1374 void FPPassManager::cleanup() {
1375 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1376 FunctionPass *FP = getContainedPass(Index);
1377 AnalysisResolver *AR = FP->getResolver();
1378 assert(AR && "Analysis Resolver is not set");
1379 AR->clearAnalysisImpls();
1383 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1386 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1387 FPPassManager *FPPM = getContainedManager(Index);
1388 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1389 FPPM->getContainedPass(Index)->releaseMemory();
1395 // Execute all the passes managed by this top level manager.
1396 // Return true if any function is modified by a pass.
1397 bool FunctionPassManagerImpl::run(Function &F) {
1398 bool Changed = false;
1399 TimingInfo::createTheTimeInfo();
1401 initializeAllAnalysisInfo();
1402 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1403 Changed |= getContainedManager(Index)->runOnFunction(F);
1405 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1406 getContainedManager(Index)->cleanup();
1412 //===----------------------------------------------------------------------===//
1413 // FPPassManager implementation
1415 char FPPassManager::ID = 0;
1416 /// Print passes managed by this manager
1417 void FPPassManager::dumpPassStructure(unsigned Offset) {
1418 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1419 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1420 FunctionPass *FP = getContainedPass(Index);
1421 FP->dumpPassStructure(Offset + 1);
1422 dumpLastUses(FP, Offset+1);
1427 /// Execute all of the passes scheduled for execution by invoking
1428 /// runOnFunction method. Keep track of whether any of the passes modifies
1429 /// the function, and if so, return true.
1430 bool FPPassManager::runOnFunction(Function &F) {
1431 if (F.isDeclaration())
1434 bool Changed = false;
1436 // Collect inherited analysis from Module level pass manager.
1437 populateInheritedAnalysis(TPM->activeStack);
1439 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1440 FunctionPass *FP = getContainedPass(Index);
1441 bool LocalChanged = false;
1443 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1444 dumpRequiredSet(FP);
1446 initializeAnalysisImpl(FP);
1449 PassManagerPrettyStackEntry X(FP, F);
1450 TimeRegion PassTimer(getPassTimer(FP));
1452 LocalChanged |= FP->runOnFunction(F);
1455 Changed |= LocalChanged;
1457 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1458 dumpPreservedSet(FP);
1460 verifyPreservedAnalysis(FP);
1461 removeNotPreservedAnalysis(FP);
1462 recordAvailableAnalysis(FP);
1463 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1468 bool FPPassManager::runOnModule(Module &M) {
1469 bool Changed = doInitialization(M);
1471 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1474 return doFinalization(M) || Changed;
1477 bool FPPassManager::doInitialization(Module &M) {
1478 bool Changed = false;
1480 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1481 Changed |= getContainedPass(Index)->doInitialization(M);
1486 bool FPPassManager::doFinalization(Module &M) {
1487 bool Changed = false;
1489 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1490 Changed |= getContainedPass(Index)->doFinalization(M);
1495 //===----------------------------------------------------------------------===//
1496 // MPPassManager implementation
1498 /// Execute all of the passes scheduled for execution by invoking
1499 /// runOnModule method. Keep track of whether any of the passes modifies
1500 /// the module, and if so, return true.
1502 MPPassManager::runOnModule(Module &M) {
1503 bool Changed = false;
1505 // Initialize on-the-fly passes
1506 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1507 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1509 FunctionPassManagerImpl *FPP = I->second;
1510 Changed |= FPP->doInitialization(M);
1513 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1514 ModulePass *MP = getContainedPass(Index);
1515 bool LocalChanged = false;
1517 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1518 dumpRequiredSet(MP);
1520 initializeAnalysisImpl(MP);
1523 PassManagerPrettyStackEntry X(MP, M);
1524 TimeRegion PassTimer(getPassTimer(MP));
1526 LocalChanged |= MP->runOnModule(M);
1529 Changed |= LocalChanged;
1531 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1532 M.getModuleIdentifier());
1533 dumpPreservedSet(MP);
1535 verifyPreservedAnalysis(MP);
1536 removeNotPreservedAnalysis(MP);
1537 recordAvailableAnalysis(MP);
1538 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1541 // Finalize on-the-fly passes
1542 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1543 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1545 FunctionPassManagerImpl *FPP = I->second;
1546 // We don't know when is the last time an on-the-fly pass is run,
1547 // so we need to releaseMemory / finalize here
1548 FPP->releaseMemoryOnTheFly();
1549 Changed |= FPP->doFinalization(M);
1554 /// Add RequiredPass into list of lower level passes required by pass P.
1555 /// RequiredPass is run on the fly by Pass Manager when P requests it
1556 /// through getAnalysis interface.
1557 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1558 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1559 "Unable to handle Pass that requires lower level Analysis pass");
1560 assert((P->getPotentialPassManagerType() <
1561 RequiredPass->getPotentialPassManagerType()) &&
1562 "Unable to handle Pass that requires lower level Analysis pass");
1564 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1566 FPP = new FunctionPassManagerImpl(0);
1567 // FPP is the top level manager.
1568 FPP->setTopLevelManager(FPP);
1570 OnTheFlyManagers[P] = FPP;
1572 FPP->add(RequiredPass);
1574 // Register P as the last user of RequiredPass.
1575 SmallVector<Pass *, 1> LU;
1576 LU.push_back(RequiredPass);
1577 FPP->setLastUser(LU, P);
1580 /// Return function pass corresponding to PassInfo PI, that is
1581 /// required by module pass MP. Instantiate analysis pass, by using
1582 /// its runOnFunction() for function F.
1583 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1584 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1585 assert(FPP && "Unable to find on the fly pass");
1587 FPP->releaseMemoryOnTheFly();
1589 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1593 //===----------------------------------------------------------------------===//
1594 // PassManagerImpl implementation
1596 /// run - Execute all of the passes scheduled for execution. Keep track of
1597 /// whether any of the passes modifies the module, and if so, return true.
1598 bool PassManagerImpl::run(Module &M) {
1599 bool Changed = false;
1600 TimingInfo::createTheTimeInfo();
1605 initializeAllAnalysisInfo();
1606 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1607 Changed |= getContainedManager(Index)->runOnModule(M);
1611 //===----------------------------------------------------------------------===//
1612 // PassManager implementation
1614 /// Create new pass manager
1615 PassManager::PassManager() {
1616 PM = new PassManagerImpl(0);
1617 // PM is the top level manager
1618 PM->setTopLevelManager(PM);
1621 PassManager::~PassManager() {
1625 /// addImpl - Add a pass to the queue of passes to run, without
1626 /// checking whether to add a printer pass.
1627 void PassManager::addImpl(Pass *P) {
1631 /// add - Add a pass to the queue of passes to run. This passes ownership of
1632 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1633 /// will be destroyed as well, so there is no need to delete the pass. This
1634 /// implies that all passes MUST be allocated with 'new'.
1635 void PassManager::add(Pass *P) {
1636 const void* PassID = P->getPassID();
1637 if (ShouldPrintBeforePass(PassID))
1638 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1639 + P->getPassName() + " ***"));
1643 if (ShouldPrintAfterPass(PassID))
1644 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1645 + P->getPassName() + " ***"));
1648 /// run - Execute all of the passes scheduled for execution. Keep track of
1649 /// whether any of the passes modifies the module, and if so, return true.
1650 bool PassManager::run(Module &M) {
1654 //===----------------------------------------------------------------------===//
1655 // TimingInfo Class - This class is used to calculate information about the
1656 // amount of time each pass takes to execute. This only happens with
1657 // -time-passes is enabled on the command line.
1659 bool llvm::TimePassesIsEnabled = false;
1660 static cl::opt<bool,true>
1661 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1662 cl::desc("Time each pass, printing elapsed time for each on exit"));
1664 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1665 // a non null value (if the -time-passes option is enabled) or it leaves it
1666 // null. It may be called multiple times.
1667 void TimingInfo::createTheTimeInfo() {
1668 if (!TimePassesIsEnabled || TheTimeInfo) return;
1670 // Constructed the first time this is called, iff -time-passes is enabled.
1671 // This guarantees that the object will be constructed before static globals,
1672 // thus it will be destroyed before them.
1673 static ManagedStatic<TimingInfo> TTI;
1674 TheTimeInfo = &*TTI;
1677 /// If TimingInfo is enabled then start pass timer.
1678 Timer *llvm::getPassTimer(Pass *P) {
1680 return TheTimeInfo->getPassTimer(P);
1684 //===----------------------------------------------------------------------===//
1685 // PMStack implementation
1688 // Pop Pass Manager from the stack and clear its analysis info.
1689 void PMStack::pop() {
1691 PMDataManager *Top = this->top();
1692 Top->initializeAnalysisInfo();
1697 // Push PM on the stack and set its top level manager.
1698 void PMStack::push(PMDataManager *PM) {
1699 assert(PM && "Unable to push. Pass Manager expected");
1701 if (!this->empty()) {
1702 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1704 assert(TPM && "Unable to find top level manager");
1705 TPM->addIndirectPassManager(PM);
1706 PM->setTopLevelManager(TPM);
1712 // Dump content of the pass manager stack.
1713 void PMStack::dump() const {
1714 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1715 E = S.end(); I != E; ++I)
1716 printf("%s ", (*I)->getAsPass()->getPassName());
1722 /// Find appropriate Module Pass Manager in the PM Stack and
1723 /// add self into that manager.
1724 void ModulePass::assignPassManager(PMStack &PMS,
1725 PassManagerType PreferredType) {
1726 // Find Module Pass Manager
1727 while (!PMS.empty()) {
1728 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1729 if (TopPMType == PreferredType)
1730 break; // We found desired pass manager
1731 else if (TopPMType > PMT_ModulePassManager)
1732 PMS.pop(); // Pop children pass managers
1736 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1737 PMS.top()->add(this);
1740 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1741 /// in the PM Stack and add self into that manager.
1742 void FunctionPass::assignPassManager(PMStack &PMS,
1743 PassManagerType PreferredType) {
1745 // Find Module Pass Manager
1746 while (!PMS.empty()) {
1747 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1753 // Create new Function Pass Manager if needed.
1755 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1756 FPP = (FPPassManager *)PMS.top();
1758 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1759 PMDataManager *PMD = PMS.top();
1761 // [1] Create new Function Pass Manager
1762 FPP = new FPPassManager(PMD->getDepth() + 1);
1763 FPP->populateInheritedAnalysis(PMS);
1765 // [2] Set up new manager's top level manager
1766 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1767 TPM->addIndirectPassManager(FPP);
1769 // [3] Assign manager to manage this new manager. This may create
1770 // and push new managers into PMS
1771 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1773 // [4] Push new manager into PMS
1777 // Assign FPP as the manager of this pass.
1781 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1782 /// in the PM Stack and add self into that manager.
1783 void BasicBlockPass::assignPassManager(PMStack &PMS,
1784 PassManagerType PreferredType) {
1787 // Basic Pass Manager is a leaf pass manager. It does not handle
1788 // any other pass manager.
1790 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1791 BBP = (BBPassManager *)PMS.top();
1793 // If leaf manager is not Basic Block Pass manager then create new
1794 // basic Block Pass manager.
1795 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1796 PMDataManager *PMD = PMS.top();
1798 // [1] Create new Basic Block Manager
1799 BBP = new BBPassManager(PMD->getDepth() + 1);
1801 // [2] Set up new manager's top level manager
1802 // Basic Block Pass Manager does not live by itself
1803 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1804 TPM->addIndirectPassManager(BBP);
1806 // [3] Assign manager to manage this new manager. This may create
1807 // and push new managers into PMS
1808 BBP->assignPassManager(PMS, PreferredType);
1810 // [4] Push new manager into PMS
1814 // Assign BBP as the manager of this pass.
1818 PassManagerBase::~PassManagerBase() {}