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/DebugInfoProbe.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Timer.h"
23 #include "llvm/Module.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/ADT/StringMap.h"
34 // See PassManagers.h for Pass Manager infrastructure overview.
38 //===----------------------------------------------------------------------===//
39 // Pass debugging information. Often it is useful to find out what pass is
40 // running when a crash occurs in a utility. When this library is compiled with
41 // debugging on, a command line option (--debug-pass) is enabled that causes the
42 // pass name to be printed before it executes.
45 // Different debug levels that can be enabled...
47 None, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(None , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
61 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
64 // Print IR out before/after specified passes.
66 PrintBefore("print-before",
67 llvm::cl::desc("Print IR before specified passes"),
71 PrintAfter("print-after",
72 llvm::cl::desc("Print IR after specified passes"),
76 PrintBeforeAll("print-before-all",
77 llvm::cl::desc("Print IR before each pass"),
80 PrintAfterAll("print-after-all",
81 llvm::cl::desc("Print IR after each pass"),
84 /// This is a helper to determine whether to print IR before or
87 static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
88 PassOptionList &PassesToPrint) {
89 if (const llvm::PassInfo *PI =
90 PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
91 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
92 const llvm::PassInfo *PassInf = PassesToPrint[i];
94 if (PassInf->getPassArgument() == PI->getPassArgument()) {
103 /// This is a utility to check whether a pass should have IR dumped
105 static bool ShouldPrintBeforePass(const void *PassID) {
106 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
109 /// This is a utility to check whether a pass should have IR dumped
111 static bool ShouldPrintAfterPass(const void *PassID) {
112 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
115 } // End of llvm namespace
117 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
118 /// or higher is specified.
119 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
120 return PassDebugging >= Executions;
126 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
127 if (V == 0 && M == 0)
128 OS << "Releasing pass '";
130 OS << "Running pass '";
132 OS << P->getPassName() << "'";
135 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
144 if (isa<Function>(V))
146 else if (isa<BasicBlock>(V))
152 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
159 //===----------------------------------------------------------------------===//
162 /// BBPassManager manages BasicBlockPass. It batches all the
163 /// pass together and sequence them to process one basic block before
164 /// processing next basic block.
165 class BBPassManager : public PMDataManager, public FunctionPass {
169 explicit BBPassManager()
170 : PMDataManager(), FunctionPass(ID) {}
172 /// Execute all of the passes scheduled for execution. Keep track of
173 /// whether any of the passes modifies the function, and if so, return true.
174 bool runOnFunction(Function &F);
176 /// Pass Manager itself does not invalidate any analysis info.
177 void getAnalysisUsage(AnalysisUsage &Info) const {
178 Info.setPreservesAll();
181 bool doInitialization(Module &M);
182 bool doInitialization(Function &F);
183 bool doFinalization(Module &M);
184 bool doFinalization(Function &F);
186 virtual PMDataManager *getAsPMDataManager() { return this; }
187 virtual Pass *getAsPass() { return this; }
189 virtual const char *getPassName() const {
190 return "BasicBlock Pass Manager";
193 // Print passes managed by this manager
194 void dumpPassStructure(unsigned Offset) {
195 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
196 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
197 BasicBlockPass *BP = getContainedPass(Index);
198 BP->dumpPassStructure(Offset + 1);
199 dumpLastUses(BP, Offset+1);
203 BasicBlockPass *getContainedPass(unsigned N) {
204 assert(N < PassVector.size() && "Pass number out of range!");
205 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
209 virtual PassManagerType getPassManagerType() const {
210 return PMT_BasicBlockPassManager;
214 char BBPassManager::ID = 0;
219 //===----------------------------------------------------------------------===//
220 // FunctionPassManagerImpl
222 /// FunctionPassManagerImpl manages FPPassManagers
223 class FunctionPassManagerImpl : public Pass,
224 public PMDataManager,
225 public PMTopLevelManager {
230 explicit FunctionPassManagerImpl() :
231 Pass(PT_PassManager, ID), PMDataManager(),
232 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
234 /// add - Add a pass to the queue of passes to run. This passes ownership of
235 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
236 /// will be destroyed as well, so there is no need to delete the pass. This
237 /// implies that all passes MUST be allocated with 'new'.
242 /// createPrinterPass - Get a function printer pass.
243 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
244 return createPrintFunctionPass(Banner, &O);
247 // Prepare for running an on the fly pass, freeing memory if needed
248 // from a previous run.
249 void releaseMemoryOnTheFly();
251 /// run - Execute all of the passes scheduled for execution. Keep track of
252 /// whether any of the passes modifies the module, and if so, return true.
253 bool run(Function &F);
255 /// doInitialization - Run all of the initializers for the function passes.
257 bool doInitialization(Module &M);
259 /// doFinalization - Run all of the finalizers for the function passes.
261 bool doFinalization(Module &M);
264 virtual PMDataManager *getAsPMDataManager() { return this; }
265 virtual Pass *getAsPass() { return this; }
267 /// Pass Manager itself does not invalidate any analysis info.
268 void getAnalysisUsage(AnalysisUsage &Info) const {
269 Info.setPreservesAll();
272 void addTopLevelPass(Pass *P) {
273 if (ImmutablePass *IP = P->getAsImmutablePass()) {
274 // P is a immutable pass and it will be managed by this
275 // top level manager. Set up analysis resolver to connect them.
276 AnalysisResolver *AR = new AnalysisResolver(*this);
278 initializeAnalysisImpl(P);
279 addImmutablePass(IP);
280 recordAvailableAnalysis(IP);
282 P->assignPassManager(activeStack, PMT_FunctionPassManager);
287 FPPassManager *getContainedManager(unsigned N) {
288 assert(N < PassManagers.size() && "Pass number out of range!");
289 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
294 char FunctionPassManagerImpl::ID = 0;
296 //===----------------------------------------------------------------------===//
299 /// MPPassManager manages ModulePasses and function pass managers.
300 /// It batches all Module passes and function pass managers together and
301 /// sequences them to process one module.
302 class MPPassManager : public Pass, public PMDataManager {
305 explicit MPPassManager() :
306 Pass(PT_PassManager, ID), PMDataManager() { }
308 // Delete on the fly managers.
309 virtual ~MPPassManager() {
310 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
311 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
313 FunctionPassManagerImpl *FPP = I->second;
318 /// createPrinterPass - Get a module printer pass.
319 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
320 return createPrintModulePass(&O, false, Banner);
323 /// run - Execute all of the passes scheduled for execution. Keep track of
324 /// whether any of the passes modifies the module, and if so, return true.
325 bool runOnModule(Module &M);
327 /// Pass Manager itself does not invalidate any analysis info.
328 void getAnalysisUsage(AnalysisUsage &Info) const {
329 Info.setPreservesAll();
332 /// Add RequiredPass into list of lower level passes required by pass P.
333 /// RequiredPass is run on the fly by Pass Manager when P requests it
334 /// through getAnalysis interface.
335 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
337 /// Return function pass corresponding to PassInfo PI, that is
338 /// required by module pass MP. Instantiate analysis pass, by using
339 /// its runOnFunction() for function F.
340 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
342 virtual const char *getPassName() const {
343 return "Module Pass Manager";
346 virtual PMDataManager *getAsPMDataManager() { return this; }
347 virtual Pass *getAsPass() { return this; }
349 // Print passes managed by this manager
350 void dumpPassStructure(unsigned Offset) {
351 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
352 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
353 ModulePass *MP = getContainedPass(Index);
354 MP->dumpPassStructure(Offset + 1);
355 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
356 OnTheFlyManagers.find(MP);
357 if (I != OnTheFlyManagers.end())
358 I->second->dumpPassStructure(Offset + 2);
359 dumpLastUses(MP, Offset+1);
363 ModulePass *getContainedPass(unsigned N) {
364 assert(N < PassVector.size() && "Pass number out of range!");
365 return static_cast<ModulePass *>(PassVector[N]);
368 virtual PassManagerType getPassManagerType() const {
369 return PMT_ModulePassManager;
373 /// Collection of on the fly FPPassManagers. These managers manage
374 /// function passes that are required by module passes.
375 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
378 char MPPassManager::ID = 0;
379 //===----------------------------------------------------------------------===//
383 /// PassManagerImpl manages MPPassManagers
384 class PassManagerImpl : public Pass,
385 public PMDataManager,
386 public PMTopLevelManager {
390 explicit PassManagerImpl() :
391 Pass(PT_PassManager, ID), PMDataManager(),
392 PMTopLevelManager(new MPPassManager()) {}
394 /// add - Add a pass to the queue of passes to run. This passes ownership of
395 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
396 /// will be destroyed as well, so there is no need to delete the pass. This
397 /// implies that all passes MUST be allocated with 'new'.
402 /// createPrinterPass - Get a module printer pass.
403 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
404 return createPrintModulePass(&O, false, Banner);
407 /// run - Execute all of the passes scheduled for execution. Keep track of
408 /// whether any of the passes modifies the module, and if so, return true.
411 /// Pass Manager itself does not invalidate any analysis info.
412 void getAnalysisUsage(AnalysisUsage &Info) const {
413 Info.setPreservesAll();
416 void addTopLevelPass(Pass *P) {
417 if (ImmutablePass *IP = P->getAsImmutablePass()) {
418 // P is a immutable pass and it will be managed by this
419 // top level manager. Set up analysis resolver to connect them.
420 AnalysisResolver *AR = new AnalysisResolver(*this);
422 initializeAnalysisImpl(P);
423 addImmutablePass(IP);
424 recordAvailableAnalysis(IP);
426 P->assignPassManager(activeStack, PMT_ModulePassManager);
430 virtual PMDataManager *getAsPMDataManager() { return this; }
431 virtual Pass *getAsPass() { return this; }
433 MPPassManager *getContainedManager(unsigned N) {
434 assert(N < PassManagers.size() && "Pass number out of range!");
435 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
440 char PassManagerImpl::ID = 0;
441 } // End of llvm namespace
445 //===----------------------------------------------------------------------===//
448 static DebugInfoProbeInfo *TheDebugProbe;
449 static void createDebugInfoProbe() {
450 if (TheDebugProbe) return;
452 // Constructed the first time this is called. This guarantees that the
453 // object will be constructed, if -enable-debug-info-probe is set,
454 // before static globals, thus it will be destroyed before them.
455 static ManagedStatic<DebugInfoProbeInfo> DIP;
456 TheDebugProbe = &*DIP;
459 //===----------------------------------------------------------------------===//
460 /// TimingInfo Class - This class is used to calculate information about the
461 /// amount of time each pass takes to execute. This only happens when
462 /// -time-passes is enabled on the command line.
465 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
468 DenseMap<Pass*, Timer*> TimingData;
471 // Use 'create' member to get this.
472 TimingInfo() : TG("... Pass execution timing report ...") {}
474 // TimingDtor - Print out information about timing information
476 // Delete all of the timers, which accumulate their info into the
478 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
479 E = TimingData.end(); I != E; ++I)
481 // TimerGroup is deleted next, printing the report.
484 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
485 // to a non null value (if the -time-passes option is enabled) or it leaves it
486 // null. It may be called multiple times.
487 static void createTheTimeInfo();
489 /// getPassTimer - Return the timer for the specified pass if it exists.
490 Timer *getPassTimer(Pass *P) {
491 if (P->getAsPMDataManager())
494 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
495 Timer *&T = TimingData[P];
497 T = new Timer(P->getPassName(), TG);
502 } // End of anon namespace
504 static TimingInfo *TheTimeInfo;
506 //===----------------------------------------------------------------------===//
507 // PMTopLevelManager implementation
509 /// Initialize top level manager. Create first pass manager.
510 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
511 PMDM->setTopLevelManager(this);
512 addPassManager(PMDM);
513 activeStack.push(PMDM);
516 /// Set pass P as the last user of the given analysis passes.
518 PMTopLevelManager::setLastUser(const SmallVectorImpl<Pass *> &AnalysisPasses,
521 if (P->getResolver())
522 PDepth = P->getResolver()->getPMDataManager().getDepth();
524 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
525 E = AnalysisPasses.end(); I != E; ++I) {
532 // Update the last users of passes that are required transitive by AP.
533 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
534 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
535 SmallVector<Pass *, 12> LastUses;
536 SmallVector<Pass *, 12> LastPMUses;
537 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
538 E = IDs.end(); I != E; ++I) {
539 Pass *AnalysisPass = findAnalysisPass(*I);
540 assert(AnalysisPass && "Expected analysis pass to exist.");
541 AnalysisResolver *AR = AnalysisPass->getResolver();
542 assert(AR && "Expected analysis resolver to exist.");
543 unsigned APDepth = AR->getPMDataManager().getDepth();
545 if (PDepth == APDepth)
546 LastUses.push_back(AnalysisPass);
547 else if (PDepth > APDepth)
548 LastPMUses.push_back(AnalysisPass);
551 setLastUser(LastUses, P);
553 // If this pass has a corresponding pass manager, push higher level
554 // analysis to this pass manager.
555 if (P->getResolver())
556 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
559 // If AP is the last user of other passes then make P last user of
561 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
562 LUE = LastUser.end(); LUI != LUE; ++LUI) {
563 if (LUI->second == AP)
564 // DenseMap iterator is not invalidated here because
565 // this is just updating existing entries.
566 LastUser[LUI->first] = P;
571 /// Collect passes whose last user is P
572 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
574 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
575 InversedLastUser.find(P);
576 if (DMI == InversedLastUser.end())
579 SmallPtrSet<Pass *, 8> &LU = DMI->second;
580 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
581 E = LU.end(); I != E; ++I) {
582 LastUses.push_back(*I);
587 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
588 AnalysisUsage *AnUsage = NULL;
589 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
590 if (DMI != AnUsageMap.end())
591 AnUsage = DMI->second;
593 AnUsage = new AnalysisUsage();
594 P->getAnalysisUsage(*AnUsage);
595 AnUsageMap[P] = AnUsage;
600 /// Schedule pass P for execution. Make sure that passes required by
601 /// P are run before P is run. Update analysis info maintained by
602 /// the manager. Remove dead passes. This is a recursive function.
603 void PMTopLevelManager::schedulePass(Pass *P) {
605 // TODO : Allocate function manager for this pass, other wise required set
606 // may be inserted into previous function manager
608 // Give pass a chance to prepare the stage.
609 P->preparePassManager(activeStack);
611 // If P is an analysis pass and it is available then do not
612 // generate the analysis again. Stale analysis info should not be
613 // available at this point.
615 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
616 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
621 AnalysisUsage *AnUsage = findAnalysisUsage(P);
623 bool checkAnalysis = true;
624 while (checkAnalysis) {
625 checkAnalysis = false;
627 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
628 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
629 E = RequiredSet.end(); I != E; ++I) {
631 Pass *AnalysisPass = findAnalysisPass(*I);
633 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
634 assert(PI && "Expected required passes to be initialized");
635 AnalysisPass = PI->createPass();
636 if (P->getPotentialPassManagerType () ==
637 AnalysisPass->getPotentialPassManagerType())
638 // Schedule analysis pass that is managed by the same pass manager.
639 schedulePass(AnalysisPass);
640 else if (P->getPotentialPassManagerType () >
641 AnalysisPass->getPotentialPassManagerType()) {
642 // Schedule analysis pass that is managed by a new manager.
643 schedulePass(AnalysisPass);
644 // Recheck analysis passes to ensure that required analyses that
645 // are already checked are still available.
646 checkAnalysis = true;
649 // Do not schedule this analysis. Lower level analsyis
650 // passes are run on the fly.
656 // Now all required passes are available.
660 /// Find the pass that implements Analysis AID. Search immutable
661 /// passes and all pass managers. If desired pass is not found
662 /// then return NULL.
663 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
665 // Check pass managers
666 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
667 E = PassManagers.end(); I != E; ++I)
668 if (Pass *P = (*I)->findAnalysisPass(AID, false))
671 // Check other pass managers
672 for (SmallVectorImpl<PMDataManager *>::iterator
673 I = IndirectPassManagers.begin(),
674 E = IndirectPassManagers.end(); I != E; ++I)
675 if (Pass *P = (*I)->findAnalysisPass(AID, false))
678 // Check the immutable passes. Iterate in reverse order so that we find
679 // the most recently registered passes first.
680 for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
681 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
682 AnalysisID PI = (*I)->getPassID();
686 // If Pass not found then check the interfaces implemented by Immutable Pass
687 const PassInfo *PassInf =
688 PassRegistry::getPassRegistry()->getPassInfo(PI);
689 assert(PassInf && "Expected all immutable passes to be initialized");
690 const std::vector<const PassInfo*> &ImmPI =
691 PassInf->getInterfacesImplemented();
692 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
693 EE = ImmPI.end(); II != EE; ++II) {
694 if ((*II)->getTypeInfo() == AID)
702 // Print passes managed by this top level manager.
703 void PMTopLevelManager::dumpPasses() const {
705 if (PassDebugging < Structure)
708 // Print out the immutable passes
709 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
710 ImmutablePasses[i]->dumpPassStructure(0);
713 // Every class that derives from PMDataManager also derives from Pass
714 // (sometimes indirectly), but there's no inheritance relationship
715 // between PMDataManager and Pass, so we have to getAsPass to get
716 // from a PMDataManager* to a Pass*.
717 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
718 E = PassManagers.end(); I != E; ++I)
719 (*I)->getAsPass()->dumpPassStructure(1);
722 void PMTopLevelManager::dumpArguments() const {
724 if (PassDebugging < Arguments)
727 dbgs() << "Pass Arguments: ";
728 for (SmallVector<ImmutablePass *, 8>::const_iterator I =
729 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
730 if (const PassInfo *PI =
731 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
732 assert(PI && "Expected all immutable passes to be initialized");
733 if (!PI->isAnalysisGroup())
734 dbgs() << " -" << PI->getPassArgument();
736 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
737 E = PassManagers.end(); I != E; ++I)
738 (*I)->dumpPassArguments();
742 void PMTopLevelManager::initializeAllAnalysisInfo() {
743 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
744 E = PassManagers.end(); I != E; ++I)
745 (*I)->initializeAnalysisInfo();
747 // Initailize other pass managers
748 for (SmallVectorImpl<PMDataManager *>::iterator
749 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
751 (*I)->initializeAnalysisInfo();
753 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
754 DME = LastUser.end(); DMI != DME; ++DMI) {
755 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
756 InversedLastUser.find(DMI->second);
757 if (InvDMI != InversedLastUser.end()) {
758 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
759 L.insert(DMI->first);
761 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
762 InversedLastUser[DMI->second] = L;
768 PMTopLevelManager::~PMTopLevelManager() {
769 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
770 E = PassManagers.end(); I != E; ++I)
773 for (SmallVectorImpl<ImmutablePass *>::iterator
774 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
777 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
778 DME = AnUsageMap.end(); DMI != DME; ++DMI)
782 //===----------------------------------------------------------------------===//
783 // PMDataManager implementation
785 /// Augement AvailableAnalysis by adding analysis made available by pass P.
786 void PMDataManager::recordAvailableAnalysis(Pass *P) {
787 AnalysisID PI = P->getPassID();
789 AvailableAnalysis[PI] = P;
791 assert(!AvailableAnalysis.empty());
793 // This pass is the current implementation of all of the interfaces it
794 // implements as well.
795 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
796 if (PInf == 0) return;
797 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
798 for (unsigned i = 0, e = II.size(); i != e; ++i)
799 AvailableAnalysis[II[i]->getTypeInfo()] = P;
802 // Return true if P preserves high level analysis used by other
803 // passes managed by this manager
804 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
805 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
806 if (AnUsage->getPreservesAll())
809 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
810 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
811 E = HigherLevelAnalysis.end(); I != E; ++I) {
813 if (P1->getAsImmutablePass() == 0 &&
814 std::find(PreservedSet.begin(), PreservedSet.end(),
823 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
824 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
825 // Don't do this unless assertions are enabled.
829 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
830 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
832 // Verify preserved analysis
833 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
834 E = PreservedSet.end(); I != E; ++I) {
836 if (Pass *AP = findAnalysisPass(AID, true)) {
837 TimeRegion PassTimer(getPassTimer(AP));
838 AP->verifyAnalysis();
843 /// Remove Analysis not preserved by Pass P
844 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
845 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
846 if (AnUsage->getPreservesAll())
849 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
850 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
851 E = AvailableAnalysis.end(); I != E; ) {
852 std::map<AnalysisID, Pass*>::iterator Info = I++;
853 if (Info->second->getAsImmutablePass() == 0 &&
854 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
855 PreservedSet.end()) {
856 // Remove this analysis
857 if (PassDebugging >= Details) {
858 Pass *S = Info->second;
859 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
860 dbgs() << S->getPassName() << "'\n";
862 AvailableAnalysis.erase(Info);
866 // Check inherited analysis also. If P is not preserving analysis
867 // provided by parent manager then remove it here.
868 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
870 if (!InheritedAnalysis[Index])
873 for (std::map<AnalysisID, Pass*>::iterator
874 I = InheritedAnalysis[Index]->begin(),
875 E = InheritedAnalysis[Index]->end(); I != E; ) {
876 std::map<AnalysisID, Pass *>::iterator Info = I++;
877 if (Info->second->getAsImmutablePass() == 0 &&
878 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
879 PreservedSet.end()) {
880 // Remove this analysis
881 if (PassDebugging >= Details) {
882 Pass *S = Info->second;
883 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
884 dbgs() << S->getPassName() << "'\n";
886 InheritedAnalysis[Index]->erase(Info);
892 /// Remove analysis passes that are not used any longer
893 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
894 enum PassDebuggingString DBG_STR) {
896 SmallVector<Pass *, 12> DeadPasses;
898 // If this is a on the fly manager then it does not have TPM.
902 TPM->collectLastUses(DeadPasses, P);
904 if (PassDebugging >= Details && !DeadPasses.empty()) {
905 dbgs() << " -*- '" << P->getPassName();
906 dbgs() << "' is the last user of following pass instances.";
907 dbgs() << " Free these instances\n";
910 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
911 E = DeadPasses.end(); I != E; ++I)
912 freePass(*I, Msg, DBG_STR);
915 void PMDataManager::freePass(Pass *P, StringRef Msg,
916 enum PassDebuggingString DBG_STR) {
917 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
920 // If the pass crashes releasing memory, remember this.
921 PassManagerPrettyStackEntry X(P);
922 TimeRegion PassTimer(getPassTimer(P));
927 AnalysisID PI = P->getPassID();
928 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
929 // Remove the pass itself (if it is not already removed).
930 AvailableAnalysis.erase(PI);
932 // Remove all interfaces this pass implements, for which it is also
933 // listed as the available implementation.
934 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
935 for (unsigned i = 0, e = II.size(); i != e; ++i) {
936 std::map<AnalysisID, Pass*>::iterator Pos =
937 AvailableAnalysis.find(II[i]->getTypeInfo());
938 if (Pos != AvailableAnalysis.end() && Pos->second == P)
939 AvailableAnalysis.erase(Pos);
944 /// Add pass P into the PassVector. Update
945 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
946 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
947 // This manager is going to manage pass P. Set up analysis resolver
949 AnalysisResolver *AR = new AnalysisResolver(*this);
952 // If a FunctionPass F is the last user of ModulePass info M
953 // then the F's manager, not F, records itself as a last user of M.
954 SmallVector<Pass *, 12> TransferLastUses;
956 if (!ProcessAnalysis) {
958 PassVector.push_back(P);
962 // At the moment, this pass is the last user of all required passes.
963 SmallVector<Pass *, 12> LastUses;
964 SmallVector<Pass *, 8> RequiredPasses;
965 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
967 unsigned PDepth = this->getDepth();
969 collectRequiredAnalysis(RequiredPasses,
970 ReqAnalysisNotAvailable, P);
971 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
972 E = RequiredPasses.end(); I != E; ++I) {
973 Pass *PRequired = *I;
976 assert(PRequired->getResolver() && "Analysis Resolver is not set");
977 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
978 RDepth = DM.getDepth();
980 if (PDepth == RDepth)
981 LastUses.push_back(PRequired);
982 else if (PDepth > RDepth) {
983 // Let the parent claim responsibility of last use
984 TransferLastUses.push_back(PRequired);
985 // Keep track of higher level analysis used by this manager.
986 HigherLevelAnalysis.push_back(PRequired);
988 llvm_unreachable("Unable to accommodate Required Pass");
991 // Set P as P's last user until someone starts using P.
992 // However, if P is a Pass Manager then it does not need
993 // to record its last user.
994 if (P->getAsPMDataManager() == 0)
995 LastUses.push_back(P);
996 TPM->setLastUser(LastUses, P);
998 if (!TransferLastUses.empty()) {
999 Pass *My_PM = getAsPass();
1000 TPM->setLastUser(TransferLastUses, My_PM);
1001 TransferLastUses.clear();
1004 // Now, take care of required analyses that are not available.
1005 for (SmallVectorImpl<AnalysisID>::iterator
1006 I = ReqAnalysisNotAvailable.begin(),
1007 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1008 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1009 Pass *AnalysisPass = PI->createPass();
1010 this->addLowerLevelRequiredPass(P, AnalysisPass);
1013 // Take a note of analysis required and made available by this pass.
1014 // Remove the analysis not preserved by this pass
1015 removeNotPreservedAnalysis(P);
1016 recordAvailableAnalysis(P);
1019 PassVector.push_back(P);
1023 /// Populate RP with analysis pass that are required by
1024 /// pass P and are available. Populate RP_NotAvail with analysis
1025 /// pass that are required by pass P but are not available.
1026 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1027 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1029 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1030 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1031 for (AnalysisUsage::VectorType::const_iterator
1032 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1033 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1034 RP.push_back(AnalysisPass);
1036 RP_NotAvail.push_back(*I);
1039 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1040 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1041 E = IDs.end(); I != E; ++I) {
1042 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1043 RP.push_back(AnalysisPass);
1045 RP_NotAvail.push_back(*I);
1049 // All Required analyses should be available to the pass as it runs! Here
1050 // we fill in the AnalysisImpls member of the pass so that it can
1051 // successfully use the getAnalysis() method to retrieve the
1052 // implementations it needs.
1054 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1055 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1057 for (AnalysisUsage::VectorType::const_iterator
1058 I = AnUsage->getRequiredSet().begin(),
1059 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1060 Pass *Impl = findAnalysisPass(*I, true);
1062 // This may be analysis pass that is initialized on the fly.
1063 // If that is not the case then it will raise an assert when it is used.
1065 AnalysisResolver *AR = P->getResolver();
1066 assert(AR && "Analysis Resolver is not set");
1067 AR->addAnalysisImplsPair(*I, Impl);
1071 /// Find the pass that implements Analysis AID. If desired pass is not found
1072 /// then return NULL.
1073 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1075 // Check if AvailableAnalysis map has one entry.
1076 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1078 if (I != AvailableAnalysis.end())
1081 // Search Parents through TopLevelManager
1083 return TPM->findAnalysisPass(AID);
1088 // Print list of passes that are last used by P.
1089 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1091 SmallVector<Pass *, 12> LUses;
1093 // If this is a on the fly manager then it does not have TPM.
1097 TPM->collectLastUses(LUses, P);
1099 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1100 E = LUses.end(); I != E; ++I) {
1101 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1102 (*I)->dumpPassStructure(0);
1106 void PMDataManager::dumpPassArguments() const {
1107 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1108 E = PassVector.end(); I != E; ++I) {
1109 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1110 PMD->dumpPassArguments();
1112 if (const PassInfo *PI =
1113 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1114 if (!PI->isAnalysisGroup())
1115 dbgs() << " -" << PI->getPassArgument();
1119 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1120 enum PassDebuggingString S2,
1122 if (PassDebugging < Executions)
1124 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1127 dbgs() << "Executing Pass '" << P->getPassName();
1129 case MODIFICATION_MSG:
1130 dbgs() << "Made Modification '" << P->getPassName();
1133 dbgs() << " Freeing Pass '" << P->getPassName();
1139 case ON_BASICBLOCK_MSG:
1140 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1142 case ON_FUNCTION_MSG:
1143 dbgs() << "' on Function '" << Msg << "'...\n";
1146 dbgs() << "' on Module '" << Msg << "'...\n";
1149 dbgs() << "' on Region '" << Msg << "'...\n";
1152 dbgs() << "' on Loop '" << Msg << "'...\n";
1155 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1162 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1163 if (PassDebugging < Details)
1166 AnalysisUsage analysisUsage;
1167 P->getAnalysisUsage(analysisUsage);
1168 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1171 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1172 if (PassDebugging < Details)
1175 AnalysisUsage analysisUsage;
1176 P->getAnalysisUsage(analysisUsage);
1177 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1180 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1181 const AnalysisUsage::VectorType &Set) const {
1182 assert(PassDebugging >= Details);
1185 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1186 for (unsigned i = 0; i != Set.size(); ++i) {
1187 if (i) dbgs() << ',';
1188 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1190 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1192 dbgs() << " Uninitialized Pass";
1195 dbgs() << ' ' << PInf->getPassName();
1200 /// Add RequiredPass into list of lower level passes required by pass P.
1201 /// RequiredPass is run on the fly by Pass Manager when P requests it
1202 /// through getAnalysis interface.
1203 /// This should be handled by specific pass manager.
1204 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1206 TPM->dumpArguments();
1210 // Module Level pass may required Function Level analysis info
1211 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1212 // to provide this on demand. In that case, in Pass manager terminology,
1213 // module level pass is requiring lower level analysis info managed by
1214 // lower level pass manager.
1216 // When Pass manager is not able to order required analysis info, Pass manager
1217 // checks whether any lower level manager will be able to provide this
1218 // analysis info on demand or not.
1220 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1221 dbgs() << "' required by '" << P->getPassName() << "'\n";
1223 llvm_unreachable("Unable to schedule pass");
1226 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1227 assert(0 && "Unable to find on the fly pass");
1232 PMDataManager::~PMDataManager() {
1233 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1234 E = PassVector.end(); I != E; ++I)
1238 //===----------------------------------------------------------------------===//
1239 // NOTE: Is this the right place to define this method ?
1240 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1241 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1242 return PM.findAnalysisPass(ID, dir);
1245 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1247 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1250 //===----------------------------------------------------------------------===//
1251 // BBPassManager implementation
1253 /// Execute all of the passes scheduled for execution by invoking
1254 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1255 /// the function, and if so, return true.
1256 bool BBPassManager::runOnFunction(Function &F) {
1257 if (F.isDeclaration())
1260 bool Changed = doInitialization(F);
1262 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1263 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1264 BasicBlockPass *BP = getContainedPass(Index);
1265 bool LocalChanged = false;
1267 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1268 dumpRequiredSet(BP);
1270 initializeAnalysisImpl(BP);
1273 // If the pass crashes, remember this.
1274 PassManagerPrettyStackEntry X(BP, *I);
1275 TimeRegion PassTimer(getPassTimer(BP));
1277 LocalChanged |= BP->runOnBasicBlock(*I);
1280 Changed |= LocalChanged;
1282 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1284 dumpPreservedSet(BP);
1286 verifyPreservedAnalysis(BP);
1287 removeNotPreservedAnalysis(BP);
1288 recordAvailableAnalysis(BP);
1289 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1292 return doFinalization(F) || Changed;
1295 // Implement doInitialization and doFinalization
1296 bool BBPassManager::doInitialization(Module &M) {
1297 bool Changed = false;
1299 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1300 Changed |= getContainedPass(Index)->doInitialization(M);
1305 bool BBPassManager::doFinalization(Module &M) {
1306 bool Changed = false;
1308 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1309 Changed |= getContainedPass(Index)->doFinalization(M);
1314 bool BBPassManager::doInitialization(Function &F) {
1315 bool Changed = false;
1317 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1318 BasicBlockPass *BP = getContainedPass(Index);
1319 Changed |= BP->doInitialization(F);
1325 bool BBPassManager::doFinalization(Function &F) {
1326 bool Changed = false;
1328 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1329 BasicBlockPass *BP = getContainedPass(Index);
1330 Changed |= BP->doFinalization(F);
1337 //===----------------------------------------------------------------------===//
1338 // FunctionPassManager implementation
1340 /// Create new Function pass manager
1341 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1342 FPM = new FunctionPassManagerImpl();
1343 // FPM is the top level manager.
1344 FPM->setTopLevelManager(FPM);
1346 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1347 FPM->setResolver(AR);
1350 FunctionPassManager::~FunctionPassManager() {
1354 /// addImpl - Add a pass to the queue of passes to run, without
1355 /// checking whether to add a printer pass.
1356 void FunctionPassManager::addImpl(Pass *P) {
1360 /// add - Add a pass to the queue of passes to run. This passes
1361 /// ownership of the Pass to the PassManager. When the
1362 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1363 /// there is no need to delete the pass. (TODO delete passes.)
1364 /// This implies that all passes MUST be allocated with 'new'.
1365 void FunctionPassManager::add(Pass *P) {
1366 // If this is a not a function pass, don't add a printer for it.
1367 const void *PassID = P->getPassID();
1368 if (P->getPassKind() == PT_Function)
1369 if (ShouldPrintBeforePass(PassID))
1370 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1371 + P->getPassName() + " ***"));
1375 if (P->getPassKind() == PT_Function)
1376 if (ShouldPrintAfterPass(PassID))
1377 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1378 + P->getPassName() + " ***"));
1381 /// run - Execute all of the passes scheduled for execution. Keep
1382 /// track of whether any of the passes modifies the function, and if
1383 /// so, return true.
1385 bool FunctionPassManager::run(Function &F) {
1386 if (F.isMaterializable()) {
1388 if (F.Materialize(&errstr))
1389 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1395 /// doInitialization - Run all of the initializers for the function passes.
1397 bool FunctionPassManager::doInitialization() {
1398 return FPM->doInitialization(*M);
1401 /// doFinalization - Run all of the finalizers for the function passes.
1403 bool FunctionPassManager::doFinalization() {
1404 return FPM->doFinalization(*M);
1407 //===----------------------------------------------------------------------===//
1408 // FunctionPassManagerImpl implementation
1410 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1411 bool Changed = false;
1416 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1417 Changed |= getContainedManager(Index)->doInitialization(M);
1422 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1423 bool Changed = false;
1425 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1426 Changed |= getContainedManager(Index)->doFinalization(M);
1431 /// cleanup - After running all passes, clean up pass manager cache.
1432 void FPPassManager::cleanup() {
1433 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1434 FunctionPass *FP = getContainedPass(Index);
1435 AnalysisResolver *AR = FP->getResolver();
1436 assert(AR && "Analysis Resolver is not set");
1437 AR->clearAnalysisImpls();
1441 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1444 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1445 FPPassManager *FPPM = getContainedManager(Index);
1446 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1447 FPPM->getContainedPass(Index)->releaseMemory();
1453 // Execute all the passes managed by this top level manager.
1454 // Return true if any function is modified by a pass.
1455 bool FunctionPassManagerImpl::run(Function &F) {
1456 bool Changed = false;
1457 TimingInfo::createTheTimeInfo();
1458 createDebugInfoProbe();
1460 initializeAllAnalysisInfo();
1461 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1462 Changed |= getContainedManager(Index)->runOnFunction(F);
1464 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1465 getContainedManager(Index)->cleanup();
1471 //===----------------------------------------------------------------------===//
1472 // FPPassManager implementation
1474 char FPPassManager::ID = 0;
1475 /// Print passes managed by this manager
1476 void FPPassManager::dumpPassStructure(unsigned Offset) {
1477 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1478 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1479 FunctionPass *FP = getContainedPass(Index);
1480 FP->dumpPassStructure(Offset + 1);
1481 dumpLastUses(FP, Offset+1);
1486 /// Execute all of the passes scheduled for execution by invoking
1487 /// runOnFunction method. Keep track of whether any of the passes modifies
1488 /// the function, and if so, return true.
1489 bool FPPassManager::runOnFunction(Function &F) {
1490 if (F.isDeclaration())
1493 bool Changed = false;
1495 // Collect inherited analysis from Module level pass manager.
1496 populateInheritedAnalysis(TPM->activeStack);
1498 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1499 FunctionPass *FP = getContainedPass(Index);
1500 bool LocalChanged = false;
1502 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1503 dumpRequiredSet(FP);
1505 initializeAnalysisImpl(FP);
1507 TheDebugProbe->initialize(FP, F);
1509 PassManagerPrettyStackEntry X(FP, F);
1510 TimeRegion PassTimer(getPassTimer(FP));
1512 LocalChanged |= FP->runOnFunction(F);
1515 TheDebugProbe->finalize(FP, F);
1517 Changed |= LocalChanged;
1519 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1520 dumpPreservedSet(FP);
1522 verifyPreservedAnalysis(FP);
1523 removeNotPreservedAnalysis(FP);
1524 recordAvailableAnalysis(FP);
1525 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1530 bool FPPassManager::runOnModule(Module &M) {
1531 bool Changed = doInitialization(M);
1533 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1534 Changed |= runOnFunction(*I);
1536 return doFinalization(M) || Changed;
1539 bool FPPassManager::doInitialization(Module &M) {
1540 bool Changed = false;
1542 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1543 Changed |= getContainedPass(Index)->doInitialization(M);
1548 bool FPPassManager::doFinalization(Module &M) {
1549 bool Changed = false;
1551 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1552 Changed |= getContainedPass(Index)->doFinalization(M);
1557 //===----------------------------------------------------------------------===//
1558 // MPPassManager implementation
1560 /// Execute all of the passes scheduled for execution by invoking
1561 /// runOnModule method. Keep track of whether any of the passes modifies
1562 /// the module, and if so, return true.
1564 MPPassManager::runOnModule(Module &M) {
1565 bool Changed = false;
1567 // Initialize on-the-fly passes
1568 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1569 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1571 FunctionPassManagerImpl *FPP = I->second;
1572 Changed |= FPP->doInitialization(M);
1575 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1576 ModulePass *MP = getContainedPass(Index);
1577 bool LocalChanged = false;
1579 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1580 dumpRequiredSet(MP);
1582 initializeAnalysisImpl(MP);
1585 PassManagerPrettyStackEntry X(MP, M);
1586 TimeRegion PassTimer(getPassTimer(MP));
1588 LocalChanged |= MP->runOnModule(M);
1591 Changed |= LocalChanged;
1593 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1594 M.getModuleIdentifier());
1595 dumpPreservedSet(MP);
1597 verifyPreservedAnalysis(MP);
1598 removeNotPreservedAnalysis(MP);
1599 recordAvailableAnalysis(MP);
1600 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1603 // Finalize on-the-fly passes
1604 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1605 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1607 FunctionPassManagerImpl *FPP = I->second;
1608 // We don't know when is the last time an on-the-fly pass is run,
1609 // so we need to releaseMemory / finalize here
1610 FPP->releaseMemoryOnTheFly();
1611 Changed |= FPP->doFinalization(M);
1616 /// Add RequiredPass into list of lower level passes required by pass P.
1617 /// RequiredPass is run on the fly by Pass Manager when P requests it
1618 /// through getAnalysis interface.
1619 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1620 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1621 "Unable to handle Pass that requires lower level Analysis pass");
1622 assert((P->getPotentialPassManagerType() <
1623 RequiredPass->getPotentialPassManagerType()) &&
1624 "Unable to handle Pass that requires lower level Analysis pass");
1626 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1628 FPP = new FunctionPassManagerImpl();
1629 // FPP is the top level manager.
1630 FPP->setTopLevelManager(FPP);
1632 OnTheFlyManagers[P] = FPP;
1634 FPP->add(RequiredPass);
1636 // Register P as the last user of RequiredPass.
1638 SmallVector<Pass *, 1> LU;
1639 LU.push_back(RequiredPass);
1640 FPP->setLastUser(LU, P);
1644 /// Return function pass corresponding to PassInfo PI, that is
1645 /// required by module pass MP. Instantiate analysis pass, by using
1646 /// its runOnFunction() for function F.
1647 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1648 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1649 assert(FPP && "Unable to find on the fly pass");
1651 FPP->releaseMemoryOnTheFly();
1653 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1657 //===----------------------------------------------------------------------===//
1658 // PassManagerImpl implementation
1660 /// run - Execute all of the passes scheduled for execution. Keep track of
1661 /// whether any of the passes modifies the module, and if so, return true.
1662 bool PassManagerImpl::run(Module &M) {
1663 bool Changed = false;
1664 TimingInfo::createTheTimeInfo();
1665 createDebugInfoProbe();
1670 initializeAllAnalysisInfo();
1671 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1672 Changed |= getContainedManager(Index)->runOnModule(M);
1676 //===----------------------------------------------------------------------===//
1677 // PassManager implementation
1679 /// Create new pass manager
1680 PassManager::PassManager() {
1681 PM = new PassManagerImpl();
1682 // PM is the top level manager
1683 PM->setTopLevelManager(PM);
1686 PassManager::~PassManager() {
1690 /// addImpl - Add a pass to the queue of passes to run, without
1691 /// checking whether to add a printer pass.
1692 void PassManager::addImpl(Pass *P) {
1696 /// add - Add a pass to the queue of passes to run. This passes ownership of
1697 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1698 /// will be destroyed as well, so there is no need to delete the pass. This
1699 /// implies that all passes MUST be allocated with 'new'.
1700 void PassManager::add(Pass *P) {
1701 const void* PassID = P->getPassID();
1702 if (ShouldPrintBeforePass(PassID))
1703 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1704 + P->getPassName() + " ***"));
1708 if (ShouldPrintAfterPass(PassID))
1709 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1710 + P->getPassName() + " ***"));
1713 /// run - Execute all of the passes scheduled for execution. Keep track of
1714 /// whether any of the passes modifies the module, and if so, return true.
1715 bool PassManager::run(Module &M) {
1719 //===----------------------------------------------------------------------===//
1720 // TimingInfo Class - This class is used to calculate information about the
1721 // amount of time each pass takes to execute. This only happens with
1722 // -time-passes is enabled on the command line.
1724 bool llvm::TimePassesIsEnabled = false;
1725 static cl::opt<bool,true>
1726 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1727 cl::desc("Time each pass, printing elapsed time for each on exit"));
1729 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1730 // a non null value (if the -time-passes option is enabled) or it leaves it
1731 // null. It may be called multiple times.
1732 void TimingInfo::createTheTimeInfo() {
1733 if (!TimePassesIsEnabled || TheTimeInfo) return;
1735 // Constructed the first time this is called, iff -time-passes is enabled.
1736 // This guarantees that the object will be constructed before static globals,
1737 // thus it will be destroyed before them.
1738 static ManagedStatic<TimingInfo> TTI;
1739 TheTimeInfo = &*TTI;
1742 /// If TimingInfo is enabled then start pass timer.
1743 Timer *llvm::getPassTimer(Pass *P) {
1745 return TheTimeInfo->getPassTimer(P);
1749 //===----------------------------------------------------------------------===//
1750 // PMStack implementation
1753 // Pop Pass Manager from the stack and clear its analysis info.
1754 void PMStack::pop() {
1756 PMDataManager *Top = this->top();
1757 Top->initializeAnalysisInfo();
1762 // Push PM on the stack and set its top level manager.
1763 void PMStack::push(PMDataManager *PM) {
1764 assert(PM && "Unable to push. Pass Manager expected");
1765 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1767 if (!this->empty()) {
1768 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1769 && "pushing bad pass manager to PMStack");
1770 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1772 assert(TPM && "Unable to find top level manager");
1773 TPM->addIndirectPassManager(PM);
1774 PM->setTopLevelManager(TPM);
1775 PM->setDepth(this->top()->getDepth()+1);
1778 assert((PM->getPassManagerType() == PMT_ModulePassManager
1779 || PM->getPassManagerType() == PMT_FunctionPassManager)
1780 && "pushing bad pass manager to PMStack");
1787 // Dump content of the pass manager stack.
1788 void PMStack::dump() const {
1789 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1790 E = S.end(); I != E; ++I)
1791 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1797 /// Find appropriate Module Pass Manager in the PM Stack and
1798 /// add self into that manager.
1799 void ModulePass::assignPassManager(PMStack &PMS,
1800 PassManagerType PreferredType) {
1801 // Find Module Pass Manager
1802 while (!PMS.empty()) {
1803 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1804 if (TopPMType == PreferredType)
1805 break; // We found desired pass manager
1806 else if (TopPMType > PMT_ModulePassManager)
1807 PMS.pop(); // Pop children pass managers
1811 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1812 PMS.top()->add(this);
1815 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1816 /// in the PM Stack and add self into that manager.
1817 void FunctionPass::assignPassManager(PMStack &PMS,
1818 PassManagerType PreferredType) {
1820 // Find Module Pass Manager
1821 while (!PMS.empty()) {
1822 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1828 // Create new Function Pass Manager if needed.
1830 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1831 FPP = (FPPassManager *)PMS.top();
1833 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1834 PMDataManager *PMD = PMS.top();
1836 // [1] Create new Function Pass Manager
1837 FPP = new FPPassManager();
1838 FPP->populateInheritedAnalysis(PMS);
1840 // [2] Set up new manager's top level manager
1841 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1842 TPM->addIndirectPassManager(FPP);
1844 // [3] Assign manager to manage this new manager. This may create
1845 // and push new managers into PMS
1846 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1848 // [4] Push new manager into PMS
1852 // Assign FPP as the manager of this pass.
1856 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1857 /// in the PM Stack and add self into that manager.
1858 void BasicBlockPass::assignPassManager(PMStack &PMS,
1859 PassManagerType PreferredType) {
1862 // Basic Pass Manager is a leaf pass manager. It does not handle
1863 // any other pass manager.
1865 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1866 BBP = (BBPassManager *)PMS.top();
1868 // If leaf manager is not Basic Block Pass manager then create new
1869 // basic Block Pass manager.
1870 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1871 PMDataManager *PMD = PMS.top();
1873 // [1] Create new Basic Block Manager
1874 BBP = new BBPassManager();
1876 // [2] Set up new manager's top level manager
1877 // Basic Block Pass Manager does not live by itself
1878 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1879 TPM->addIndirectPassManager(BBP);
1881 // [3] Assign manager to manage this new manager. This may create
1882 // and push new managers into PMS
1883 BBP->assignPassManager(PMS, PreferredType);
1885 // [4] Push new manager into PMS
1889 // Assign BBP as the manager of this pass.
1893 PassManagerBase::~PassManagerBase() {}