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"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 None, Arguments, Structure, Executions, Details
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
52 clEnumVal(None , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
59 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
62 // Print IR out before/after specified passes.
64 PrintBefore("print-before",
65 llvm::cl::desc("Print IR before specified passes"),
69 PrintAfter("print-after",
70 llvm::cl::desc("Print IR after specified passes"),
74 PrintBeforeAll("print-before-all",
75 llvm::cl::desc("Print IR before each pass"),
78 PrintAfterAll("print-after-all",
79 llvm::cl::desc("Print IR after each pass"),
82 /// This is a helper to determine whether to print IR before or
85 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
86 PassOptionList &PassesToPrint) {
87 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88 const llvm::PassInfo *PassInf = PassesToPrint[i];
90 if (PassInf->getPassArgument() == PI->getPassArgument()) {
97 /// This is a utility to check whether a pass should have IR dumped
99 static bool ShouldPrintBeforePass(const PassInfo *PI) {
100 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
103 /// This is a utility to check whether a pass should have IR dumped
105 static bool ShouldPrintAfterPass(const PassInfo *PI) {
106 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
109 } // End of llvm namespace
111 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112 /// or higher is specified.
113 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114 return PassDebugging >= Executions;
120 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
121 if (V == 0 && M == 0)
122 OS << "Releasing pass '";
124 OS << "Running pass '";
126 OS << P->getPassName() << "'";
129 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
138 if (isa<Function>(V))
140 else if (isa<BasicBlock>(V))
146 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
153 //===----------------------------------------------------------------------===//
156 /// BBPassManager manages BasicBlockPass. It batches all the
157 /// pass together and sequence them to process one basic block before
158 /// processing next basic block.
159 class BBPassManager : public PMDataManager, public FunctionPass {
163 explicit BBPassManager()
164 : PMDataManager(), FunctionPass(ID) {}
166 /// Execute all of the passes scheduled for execution. Keep track of
167 /// whether any of the passes modifies the function, and if so, return true.
168 bool runOnFunction(Function &F);
170 /// Pass Manager itself does not invalidate any analysis info.
171 void getAnalysisUsage(AnalysisUsage &Info) const {
172 Info.setPreservesAll();
175 bool doInitialization(Module &M);
176 bool doInitialization(Function &F);
177 bool doFinalization(Module &M);
178 bool doFinalization(Function &F);
180 virtual PMDataManager *getAsPMDataManager() { return this; }
181 virtual Pass *getAsPass() { return this; }
183 virtual const char *getPassName() const {
184 return "BasicBlock Pass Manager";
187 // Print passes managed by this manager
188 void dumpPassStructure(unsigned Offset) {
189 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191 BasicBlockPass *BP = getContainedPass(Index);
192 BP->dumpPassStructure(Offset + 1);
193 dumpLastUses(BP, Offset+1);
197 BasicBlockPass *getContainedPass(unsigned N) {
198 assert(N < PassVector.size() && "Pass number out of range!");
199 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
203 virtual PassManagerType getPassManagerType() const {
204 return PMT_BasicBlockPassManager;
208 char BBPassManager::ID = 0;
213 //===----------------------------------------------------------------------===//
214 // FunctionPassManagerImpl
216 /// FunctionPassManagerImpl manages FPPassManagers
217 class FunctionPassManagerImpl : public Pass,
218 public PMDataManager,
219 public PMTopLevelManager {
220 virtual void anchor();
225 explicit FunctionPassManagerImpl() :
226 Pass(PT_PassManager, ID), PMDataManager(),
227 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
229 /// add - Add a pass to the queue of passes to run. This passes ownership of
230 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
231 /// will be destroyed as well, so there is no need to delete the pass. This
232 /// implies that all passes MUST be allocated with 'new'.
237 /// createPrinterPass - Get a function printer pass.
238 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
239 return createPrintFunctionPass(Banner, &O);
242 // Prepare for running an on the fly pass, freeing memory if needed
243 // from a previous run.
244 void releaseMemoryOnTheFly();
246 /// run - Execute all of the passes scheduled for execution. Keep track of
247 /// whether any of the passes modifies the module, and if so, return true.
248 bool run(Function &F);
250 /// doInitialization - Run all of the initializers for the function passes.
252 bool doInitialization(Module &M);
254 /// doFinalization - Run all of the finalizers for the function passes.
256 bool doFinalization(Module &M);
259 virtual PMDataManager *getAsPMDataManager() { return this; }
260 virtual Pass *getAsPass() { return this; }
261 virtual PassManagerType getTopLevelPassManagerType() {
262 return PMT_FunctionPassManager;
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const {
267 Info.setPreservesAll();
270 FPPassManager *getContainedManager(unsigned N) {
271 assert(N < PassManagers.size() && "Pass number out of range!");
272 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
277 void FunctionPassManagerImpl::anchor() {}
279 char FunctionPassManagerImpl::ID = 0;
281 //===----------------------------------------------------------------------===//
284 /// MPPassManager manages ModulePasses and function pass managers.
285 /// It batches all Module passes and function pass managers together and
286 /// sequences them to process one module.
287 class MPPassManager : public Pass, public PMDataManager {
290 explicit MPPassManager() :
291 Pass(PT_PassManager, ID), PMDataManager() { }
293 // Delete on the fly managers.
294 virtual ~MPPassManager() {
295 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
296 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
298 FunctionPassManagerImpl *FPP = I->second;
303 /// createPrinterPass - Get a module printer pass.
304 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
305 return createPrintModulePass(&O, false, Banner);
308 /// run - Execute all of the passes scheduled for execution. Keep track of
309 /// whether any of the passes modifies the module, and if so, return true.
310 bool runOnModule(Module &M);
312 /// Pass Manager itself does not invalidate any analysis info.
313 void getAnalysisUsage(AnalysisUsage &Info) const {
314 Info.setPreservesAll();
317 /// Add RequiredPass into list of lower level passes required by pass P.
318 /// RequiredPass is run on the fly by Pass Manager when P requests it
319 /// through getAnalysis interface.
320 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
322 /// Return function pass corresponding to PassInfo PI, that is
323 /// required by module pass MP. Instantiate analysis pass, by using
324 /// its runOnFunction() for function F.
325 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
327 virtual const char *getPassName() const {
328 return "Module Pass Manager";
331 virtual PMDataManager *getAsPMDataManager() { return this; }
332 virtual Pass *getAsPass() { return this; }
334 // Print passes managed by this manager
335 void dumpPassStructure(unsigned Offset) {
336 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
337 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
338 ModulePass *MP = getContainedPass(Index);
339 MP->dumpPassStructure(Offset + 1);
340 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
341 OnTheFlyManagers.find(MP);
342 if (I != OnTheFlyManagers.end())
343 I->second->dumpPassStructure(Offset + 2);
344 dumpLastUses(MP, Offset+1);
348 ModulePass *getContainedPass(unsigned N) {
349 assert(N < PassVector.size() && "Pass number out of range!");
350 return static_cast<ModulePass *>(PassVector[N]);
353 virtual PassManagerType getPassManagerType() const {
354 return PMT_ModulePassManager;
358 /// Collection of on the fly FPPassManagers. These managers manage
359 /// function passes that are required by module passes.
360 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
363 char MPPassManager::ID = 0;
364 //===----------------------------------------------------------------------===//
368 /// PassManagerImpl manages MPPassManagers
369 class PassManagerImpl : public Pass,
370 public PMDataManager,
371 public PMTopLevelManager {
372 virtual void anchor();
376 explicit PassManagerImpl() :
377 Pass(PT_PassManager, ID), PMDataManager(),
378 PMTopLevelManager(new MPPassManager()) {}
380 /// add - Add a pass to the queue of passes to run. This passes ownership of
381 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
382 /// will be destroyed as well, so there is no need to delete the pass. This
383 /// implies that all passes MUST be allocated with 'new'.
388 /// createPrinterPass - Get a module printer pass.
389 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
390 return createPrintModulePass(&O, false, Banner);
393 /// run - Execute all of the passes scheduled for execution. Keep track of
394 /// whether any of the passes modifies the module, and if so, return true.
397 /// Pass Manager itself does not invalidate any analysis info.
398 void getAnalysisUsage(AnalysisUsage &Info) const {
399 Info.setPreservesAll();
402 virtual PMDataManager *getAsPMDataManager() { return this; }
403 virtual Pass *getAsPass() { return this; }
404 virtual PassManagerType getTopLevelPassManagerType() {
405 return PMT_ModulePassManager;
408 MPPassManager *getContainedManager(unsigned N) {
409 assert(N < PassManagers.size() && "Pass number out of range!");
410 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
415 void PassManagerImpl::anchor() {}
417 char PassManagerImpl::ID = 0;
418 } // End of llvm namespace
422 //===----------------------------------------------------------------------===//
423 /// TimingInfo Class - This class is used to calculate information about the
424 /// amount of time each pass takes to execute. This only happens when
425 /// -time-passes is enabled on the command line.
428 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
431 DenseMap<Pass*, Timer*> TimingData;
434 // Use 'create' member to get this.
435 TimingInfo() : TG("... Pass execution timing report ...") {}
437 // TimingDtor - Print out information about timing information
439 // Delete all of the timers, which accumulate their info into the
441 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
442 E = TimingData.end(); I != E; ++I)
444 // TimerGroup is deleted next, printing the report.
447 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
448 // to a non null value (if the -time-passes option is enabled) or it leaves it
449 // null. It may be called multiple times.
450 static void createTheTimeInfo();
452 /// getPassTimer - Return the timer for the specified pass if it exists.
453 Timer *getPassTimer(Pass *P) {
454 if (P->getAsPMDataManager())
457 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
458 Timer *&T = TimingData[P];
460 T = new Timer(P->getPassName(), TG);
465 } // End of anon namespace
467 static TimingInfo *TheTimeInfo;
469 //===----------------------------------------------------------------------===//
470 // PMTopLevelManager implementation
472 /// Initialize top level manager. Create first pass manager.
473 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
474 PMDM->setTopLevelManager(this);
475 addPassManager(PMDM);
476 activeStack.push(PMDM);
479 /// Set pass P as the last user of the given analysis passes.
481 PMTopLevelManager::setLastUser(const SmallVectorImpl<Pass *> &AnalysisPasses,
484 if (P->getResolver())
485 PDepth = P->getResolver()->getPMDataManager().getDepth();
487 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
488 E = AnalysisPasses.end(); I != E; ++I) {
495 // Update the last users of passes that are required transitive by AP.
496 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
497 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
498 SmallVector<Pass *, 12> LastUses;
499 SmallVector<Pass *, 12> LastPMUses;
500 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
501 E = IDs.end(); I != E; ++I) {
502 Pass *AnalysisPass = findAnalysisPass(*I);
503 assert(AnalysisPass && "Expected analysis pass to exist.");
504 AnalysisResolver *AR = AnalysisPass->getResolver();
505 assert(AR && "Expected analysis resolver to exist.");
506 unsigned APDepth = AR->getPMDataManager().getDepth();
508 if (PDepth == APDepth)
509 LastUses.push_back(AnalysisPass);
510 else if (PDepth > APDepth)
511 LastPMUses.push_back(AnalysisPass);
514 setLastUser(LastUses, P);
516 // If this pass has a corresponding pass manager, push higher level
517 // analysis to this pass manager.
518 if (P->getResolver())
519 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
522 // If AP is the last user of other passes then make P last user of
524 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
525 LUE = LastUser.end(); LUI != LUE; ++LUI) {
526 if (LUI->second == AP)
527 // DenseMap iterator is not invalidated here because
528 // this is just updating existing entries.
529 LastUser[LUI->first] = P;
534 /// Collect passes whose last user is P
535 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
537 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
538 InversedLastUser.find(P);
539 if (DMI == InversedLastUser.end())
542 SmallPtrSet<Pass *, 8> &LU = DMI->second;
543 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
544 E = LU.end(); I != E; ++I) {
545 LastUses.push_back(*I);
550 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
551 AnalysisUsage *AnUsage = NULL;
552 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
553 if (DMI != AnUsageMap.end())
554 AnUsage = DMI->second;
556 AnUsage = new AnalysisUsage();
557 P->getAnalysisUsage(*AnUsage);
558 AnUsageMap[P] = AnUsage;
563 /// Schedule pass P for execution. Make sure that passes required by
564 /// P are run before P is run. Update analysis info maintained by
565 /// the manager. Remove dead passes. This is a recursive function.
566 void PMTopLevelManager::schedulePass(Pass *P) {
568 // TODO : Allocate function manager for this pass, other wise required set
569 // may be inserted into previous function manager
571 // Give pass a chance to prepare the stage.
572 P->preparePassManager(activeStack);
574 // If P is an analysis pass and it is available then do not
575 // generate the analysis again. Stale analysis info should not be
576 // available at this point.
578 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
579 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
584 AnalysisUsage *AnUsage = findAnalysisUsage(P);
586 bool checkAnalysis = true;
587 while (checkAnalysis) {
588 checkAnalysis = false;
590 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
591 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
592 E = RequiredSet.end(); I != E; ++I) {
594 Pass *AnalysisPass = findAnalysisPass(*I);
596 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
597 assert(PI && "Expected required passes to be initialized");
598 AnalysisPass = PI->createPass();
599 if (P->getPotentialPassManagerType () ==
600 AnalysisPass->getPotentialPassManagerType())
601 // Schedule analysis pass that is managed by the same pass manager.
602 schedulePass(AnalysisPass);
603 else if (P->getPotentialPassManagerType () >
604 AnalysisPass->getPotentialPassManagerType()) {
605 // Schedule analysis pass that is managed by a new manager.
606 schedulePass(AnalysisPass);
607 // Recheck analysis passes to ensure that required analyses that
608 // are already checked are still available.
609 checkAnalysis = true;
612 // Do not schedule this analysis. Lower level analsyis
613 // passes are run on the fly.
619 // Now all required passes are available.
620 if (ImmutablePass *IP = P->getAsImmutablePass()) {
621 // P is a immutable pass and it will be managed by this
622 // top level manager. Set up analysis resolver to connect them.
623 PMDataManager *DM = getAsPMDataManager();
624 AnalysisResolver *AR = new AnalysisResolver(*DM);
626 DM->initializeAnalysisImpl(P);
627 addImmutablePass(IP);
628 DM->recordAvailableAnalysis(IP);
632 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
633 Pass *PP = P->createPrinterPass(
634 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
635 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
638 // Add the requested pass to the best available pass manager.
639 P->assignPassManager(activeStack, getTopLevelPassManagerType());
641 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
642 Pass *PP = P->createPrinterPass(
643 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
644 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
648 /// Find the pass that implements Analysis AID. Search immutable
649 /// passes and all pass managers. If desired pass is not found
650 /// then return NULL.
651 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
653 // Check pass managers
654 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
655 E = PassManagers.end(); I != E; ++I)
656 if (Pass *P = (*I)->findAnalysisPass(AID, false))
659 // Check other pass managers
660 for (SmallVectorImpl<PMDataManager *>::iterator
661 I = IndirectPassManagers.begin(),
662 E = IndirectPassManagers.end(); I != E; ++I)
663 if (Pass *P = (*I)->findAnalysisPass(AID, false))
666 // Check the immutable passes. Iterate in reverse order so that we find
667 // the most recently registered passes first.
668 for (SmallVector<ImmutablePass *, 8>::reverse_iterator I =
669 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
670 AnalysisID PI = (*I)->getPassID();
674 // If Pass not found then check the interfaces implemented by Immutable Pass
675 const PassInfo *PassInf =
676 PassRegistry::getPassRegistry()->getPassInfo(PI);
677 assert(PassInf && "Expected all immutable passes to be initialized");
678 const std::vector<const PassInfo*> &ImmPI =
679 PassInf->getInterfacesImplemented();
680 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
681 EE = ImmPI.end(); II != EE; ++II) {
682 if ((*II)->getTypeInfo() == AID)
690 // Print passes managed by this top level manager.
691 void PMTopLevelManager::dumpPasses() const {
693 if (PassDebugging < Structure)
696 // Print out the immutable passes
697 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
698 ImmutablePasses[i]->dumpPassStructure(0);
701 // Every class that derives from PMDataManager also derives from Pass
702 // (sometimes indirectly), but there's no inheritance relationship
703 // between PMDataManager and Pass, so we have to getAsPass to get
704 // from a PMDataManager* to a Pass*.
705 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
706 E = PassManagers.end(); I != E; ++I)
707 (*I)->getAsPass()->dumpPassStructure(1);
710 void PMTopLevelManager::dumpArguments() const {
712 if (PassDebugging < Arguments)
715 dbgs() << "Pass Arguments: ";
716 for (SmallVector<ImmutablePass *, 8>::const_iterator I =
717 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
718 if (const PassInfo *PI =
719 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
720 assert(PI && "Expected all immutable passes to be initialized");
721 if (!PI->isAnalysisGroup())
722 dbgs() << " -" << PI->getPassArgument();
724 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
725 E = PassManagers.end(); I != E; ++I)
726 (*I)->dumpPassArguments();
730 void PMTopLevelManager::initializeAllAnalysisInfo() {
731 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
732 E = PassManagers.end(); I != E; ++I)
733 (*I)->initializeAnalysisInfo();
735 // Initailize other pass managers
736 for (SmallVectorImpl<PMDataManager *>::iterator
737 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
739 (*I)->initializeAnalysisInfo();
741 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
742 DME = LastUser.end(); DMI != DME; ++DMI) {
743 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
744 InversedLastUser.find(DMI->second);
745 if (InvDMI != InversedLastUser.end()) {
746 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
747 L.insert(DMI->first);
749 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
750 InversedLastUser[DMI->second] = L;
756 PMTopLevelManager::~PMTopLevelManager() {
757 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
758 E = PassManagers.end(); I != E; ++I)
761 for (SmallVectorImpl<ImmutablePass *>::iterator
762 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
765 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
766 DME = AnUsageMap.end(); DMI != DME; ++DMI)
770 //===----------------------------------------------------------------------===//
771 // PMDataManager implementation
773 /// Augement AvailableAnalysis by adding analysis made available by pass P.
774 void PMDataManager::recordAvailableAnalysis(Pass *P) {
775 AnalysisID PI = P->getPassID();
777 AvailableAnalysis[PI] = P;
779 assert(!AvailableAnalysis.empty());
781 // This pass is the current implementation of all of the interfaces it
782 // implements as well.
783 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
784 if (PInf == 0) return;
785 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
786 for (unsigned i = 0, e = II.size(); i != e; ++i)
787 AvailableAnalysis[II[i]->getTypeInfo()] = P;
790 // Return true if P preserves high level analysis used by other
791 // passes managed by this manager
792 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
793 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
794 if (AnUsage->getPreservesAll())
797 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
798 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
799 E = HigherLevelAnalysis.end(); I != E; ++I) {
801 if (P1->getAsImmutablePass() == 0 &&
802 std::find(PreservedSet.begin(), PreservedSet.end(),
811 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
812 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
813 // Don't do this unless assertions are enabled.
817 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
818 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
820 // Verify preserved analysis
821 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
822 E = PreservedSet.end(); I != E; ++I) {
824 if (Pass *AP = findAnalysisPass(AID, true)) {
825 TimeRegion PassTimer(getPassTimer(AP));
826 AP->verifyAnalysis();
831 /// Remove Analysis not preserved by Pass P
832 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
833 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
834 if (AnUsage->getPreservesAll())
837 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
838 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
839 E = AvailableAnalysis.end(); I != E; ) {
840 std::map<AnalysisID, Pass*>::iterator Info = I++;
841 if (Info->second->getAsImmutablePass() == 0 &&
842 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
843 PreservedSet.end()) {
844 // Remove this analysis
845 if (PassDebugging >= Details) {
846 Pass *S = Info->second;
847 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
848 dbgs() << S->getPassName() << "'\n";
850 AvailableAnalysis.erase(Info);
854 // Check inherited analysis also. If P is not preserving analysis
855 // provided by parent manager then remove it here.
856 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
858 if (!InheritedAnalysis[Index])
861 for (std::map<AnalysisID, Pass*>::iterator
862 I = InheritedAnalysis[Index]->begin(),
863 E = InheritedAnalysis[Index]->end(); I != E; ) {
864 std::map<AnalysisID, Pass *>::iterator Info = I++;
865 if (Info->second->getAsImmutablePass() == 0 &&
866 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
867 PreservedSet.end()) {
868 // Remove this analysis
869 if (PassDebugging >= Details) {
870 Pass *S = Info->second;
871 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
872 dbgs() << S->getPassName() << "'\n";
874 InheritedAnalysis[Index]->erase(Info);
880 /// Remove analysis passes that are not used any longer
881 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
882 enum PassDebuggingString DBG_STR) {
884 SmallVector<Pass *, 12> DeadPasses;
886 // If this is a on the fly manager then it does not have TPM.
890 TPM->collectLastUses(DeadPasses, P);
892 if (PassDebugging >= Details && !DeadPasses.empty()) {
893 dbgs() << " -*- '" << P->getPassName();
894 dbgs() << "' is the last user of following pass instances.";
895 dbgs() << " Free these instances\n";
898 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
899 E = DeadPasses.end(); I != E; ++I)
900 freePass(*I, Msg, DBG_STR);
903 void PMDataManager::freePass(Pass *P, StringRef Msg,
904 enum PassDebuggingString DBG_STR) {
905 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
908 // If the pass crashes releasing memory, remember this.
909 PassManagerPrettyStackEntry X(P);
910 TimeRegion PassTimer(getPassTimer(P));
915 AnalysisID PI = P->getPassID();
916 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
917 // Remove the pass itself (if it is not already removed).
918 AvailableAnalysis.erase(PI);
920 // Remove all interfaces this pass implements, for which it is also
921 // listed as the available implementation.
922 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
923 for (unsigned i = 0, e = II.size(); i != e; ++i) {
924 std::map<AnalysisID, Pass*>::iterator Pos =
925 AvailableAnalysis.find(II[i]->getTypeInfo());
926 if (Pos != AvailableAnalysis.end() && Pos->second == P)
927 AvailableAnalysis.erase(Pos);
932 /// Add pass P into the PassVector. Update
933 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
934 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
935 // This manager is going to manage pass P. Set up analysis resolver
937 AnalysisResolver *AR = new AnalysisResolver(*this);
940 // If a FunctionPass F is the last user of ModulePass info M
941 // then the F's manager, not F, records itself as a last user of M.
942 SmallVector<Pass *, 12> TransferLastUses;
944 if (!ProcessAnalysis) {
946 PassVector.push_back(P);
950 // At the moment, this pass is the last user of all required passes.
951 SmallVector<Pass *, 12> LastUses;
952 SmallVector<Pass *, 8> RequiredPasses;
953 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
955 unsigned PDepth = this->getDepth();
957 collectRequiredAnalysis(RequiredPasses,
958 ReqAnalysisNotAvailable, P);
959 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
960 E = RequiredPasses.end(); I != E; ++I) {
961 Pass *PRequired = *I;
964 assert(PRequired->getResolver() && "Analysis Resolver is not set");
965 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
966 RDepth = DM.getDepth();
968 if (PDepth == RDepth)
969 LastUses.push_back(PRequired);
970 else if (PDepth > RDepth) {
971 // Let the parent claim responsibility of last use
972 TransferLastUses.push_back(PRequired);
973 // Keep track of higher level analysis used by this manager.
974 HigherLevelAnalysis.push_back(PRequired);
976 llvm_unreachable("Unable to accommodate Required Pass");
979 // Set P as P's last user until someone starts using P.
980 // However, if P is a Pass Manager then it does not need
981 // to record its last user.
982 if (P->getAsPMDataManager() == 0)
983 LastUses.push_back(P);
984 TPM->setLastUser(LastUses, P);
986 if (!TransferLastUses.empty()) {
987 Pass *My_PM = getAsPass();
988 TPM->setLastUser(TransferLastUses, My_PM);
989 TransferLastUses.clear();
992 // Now, take care of required analyses that are not available.
993 for (SmallVectorImpl<AnalysisID>::iterator
994 I = ReqAnalysisNotAvailable.begin(),
995 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
996 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
997 Pass *AnalysisPass = PI->createPass();
998 this->addLowerLevelRequiredPass(P, AnalysisPass);
1001 // Take a note of analysis required and made available by this pass.
1002 // Remove the analysis not preserved by this pass
1003 removeNotPreservedAnalysis(P);
1004 recordAvailableAnalysis(P);
1007 PassVector.push_back(P);
1011 /// Populate RP with analysis pass that are required by
1012 /// pass P and are available. Populate RP_NotAvail with analysis
1013 /// pass that are required by pass P but are not available.
1014 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1015 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1017 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1018 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1019 for (AnalysisUsage::VectorType::const_iterator
1020 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1021 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1022 RP.push_back(AnalysisPass);
1024 RP_NotAvail.push_back(*I);
1027 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1028 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1029 E = IDs.end(); I != E; ++I) {
1030 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1031 RP.push_back(AnalysisPass);
1033 RP_NotAvail.push_back(*I);
1037 // All Required analyses should be available to the pass as it runs! Here
1038 // we fill in the AnalysisImpls member of the pass so that it can
1039 // successfully use the getAnalysis() method to retrieve the
1040 // implementations it needs.
1042 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1043 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1045 for (AnalysisUsage::VectorType::const_iterator
1046 I = AnUsage->getRequiredSet().begin(),
1047 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1048 Pass *Impl = findAnalysisPass(*I, true);
1050 // This may be analysis pass that is initialized on the fly.
1051 // If that is not the case then it will raise an assert when it is used.
1053 AnalysisResolver *AR = P->getResolver();
1054 assert(AR && "Analysis Resolver is not set");
1055 AR->addAnalysisImplsPair(*I, Impl);
1059 /// Find the pass that implements Analysis AID. If desired pass is not found
1060 /// then return NULL.
1061 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1063 // Check if AvailableAnalysis map has one entry.
1064 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1066 if (I != AvailableAnalysis.end())
1069 // Search Parents through TopLevelManager
1071 return TPM->findAnalysisPass(AID);
1076 // Print list of passes that are last used by P.
1077 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1079 SmallVector<Pass *, 12> LUses;
1081 // If this is a on the fly manager then it does not have TPM.
1085 TPM->collectLastUses(LUses, P);
1087 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1088 E = LUses.end(); I != E; ++I) {
1089 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1090 (*I)->dumpPassStructure(0);
1094 void PMDataManager::dumpPassArguments() const {
1095 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1096 E = PassVector.end(); I != E; ++I) {
1097 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1098 PMD->dumpPassArguments();
1100 if (const PassInfo *PI =
1101 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1102 if (!PI->isAnalysisGroup())
1103 dbgs() << " -" << PI->getPassArgument();
1107 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1108 enum PassDebuggingString S2,
1110 if (PassDebugging < Executions)
1112 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1115 dbgs() << "Executing Pass '" << P->getPassName();
1117 case MODIFICATION_MSG:
1118 dbgs() << "Made Modification '" << P->getPassName();
1121 dbgs() << " Freeing Pass '" << P->getPassName();
1127 case ON_BASICBLOCK_MSG:
1128 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1130 case ON_FUNCTION_MSG:
1131 dbgs() << "' on Function '" << Msg << "'...\n";
1134 dbgs() << "' on Module '" << Msg << "'...\n";
1137 dbgs() << "' on Region '" << Msg << "'...\n";
1140 dbgs() << "' on Loop '" << Msg << "'...\n";
1143 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1150 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1151 if (PassDebugging < Details)
1154 AnalysisUsage analysisUsage;
1155 P->getAnalysisUsage(analysisUsage);
1156 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1159 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1160 if (PassDebugging < Details)
1163 AnalysisUsage analysisUsage;
1164 P->getAnalysisUsage(analysisUsage);
1165 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1168 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1169 const AnalysisUsage::VectorType &Set) const {
1170 assert(PassDebugging >= Details);
1173 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1174 for (unsigned i = 0; i != Set.size(); ++i) {
1175 if (i) dbgs() << ',';
1176 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1178 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1180 dbgs() << " Uninitialized Pass";
1183 dbgs() << ' ' << PInf->getPassName();
1188 /// Add RequiredPass into list of lower level passes required by pass P.
1189 /// RequiredPass is run on the fly by Pass Manager when P requests it
1190 /// through getAnalysis interface.
1191 /// This should be handled by specific pass manager.
1192 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1194 TPM->dumpArguments();
1198 // Module Level pass may required Function Level analysis info
1199 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1200 // to provide this on demand. In that case, in Pass manager terminology,
1201 // module level pass is requiring lower level analysis info managed by
1202 // lower level pass manager.
1204 // When Pass manager is not able to order required analysis info, Pass manager
1205 // checks whether any lower level manager will be able to provide this
1206 // analysis info on demand or not.
1208 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1209 dbgs() << "' required by '" << P->getPassName() << "'\n";
1211 llvm_unreachable("Unable to schedule pass");
1214 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1215 llvm_unreachable("Unable to find on the fly pass");
1219 PMDataManager::~PMDataManager() {
1220 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1221 E = PassVector.end(); I != E; ++I)
1225 //===----------------------------------------------------------------------===//
1226 // NOTE: Is this the right place to define this method ?
1227 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1228 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1229 return PM.findAnalysisPass(ID, dir);
1232 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1234 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1237 //===----------------------------------------------------------------------===//
1238 // BBPassManager implementation
1240 /// Execute all of the passes scheduled for execution by invoking
1241 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1242 /// the function, and if so, return true.
1243 bool BBPassManager::runOnFunction(Function &F) {
1244 if (F.isDeclaration())
1247 bool Changed = doInitialization(F);
1249 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1250 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1251 BasicBlockPass *BP = getContainedPass(Index);
1252 bool LocalChanged = false;
1254 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1255 dumpRequiredSet(BP);
1257 initializeAnalysisImpl(BP);
1260 // If the pass crashes, remember this.
1261 PassManagerPrettyStackEntry X(BP, *I);
1262 TimeRegion PassTimer(getPassTimer(BP));
1264 LocalChanged |= BP->runOnBasicBlock(*I);
1267 Changed |= LocalChanged;
1269 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1271 dumpPreservedSet(BP);
1273 verifyPreservedAnalysis(BP);
1274 removeNotPreservedAnalysis(BP);
1275 recordAvailableAnalysis(BP);
1276 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1279 return doFinalization(F) || Changed;
1282 // Implement doInitialization and doFinalization
1283 bool BBPassManager::doInitialization(Module &M) {
1284 bool Changed = false;
1286 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1287 Changed |= getContainedPass(Index)->doInitialization(M);
1292 bool BBPassManager::doFinalization(Module &M) {
1293 bool Changed = false;
1295 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1296 Changed |= getContainedPass(Index)->doFinalization(M);
1301 bool BBPassManager::doInitialization(Function &F) {
1302 bool Changed = false;
1304 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1305 BasicBlockPass *BP = getContainedPass(Index);
1306 Changed |= BP->doInitialization(F);
1312 bool BBPassManager::doFinalization(Function &F) {
1313 bool Changed = false;
1315 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1316 BasicBlockPass *BP = getContainedPass(Index);
1317 Changed |= BP->doFinalization(F);
1324 //===----------------------------------------------------------------------===//
1325 // FunctionPassManager implementation
1327 /// Create new Function pass manager
1328 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1329 FPM = new FunctionPassManagerImpl();
1330 // FPM is the top level manager.
1331 FPM->setTopLevelManager(FPM);
1333 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1334 FPM->setResolver(AR);
1337 FunctionPassManager::~FunctionPassManager() {
1341 /// add - Add a pass to the queue of passes to run. This passes
1342 /// ownership of the Pass to the PassManager. When the
1343 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1344 /// there is no need to delete the pass. (TODO delete passes.)
1345 /// This implies that all passes MUST be allocated with 'new'.
1346 void FunctionPassManager::add(Pass *P) {
1350 /// run - Execute all of the passes scheduled for execution. Keep
1351 /// track of whether any of the passes modifies the function, and if
1352 /// so, return true.
1354 bool FunctionPassManager::run(Function &F) {
1355 if (F.isMaterializable()) {
1357 if (F.Materialize(&errstr))
1358 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1364 /// doInitialization - Run all of the initializers for the function passes.
1366 bool FunctionPassManager::doInitialization() {
1367 return FPM->doInitialization(*M);
1370 /// doFinalization - Run all of the finalizers for the function passes.
1372 bool FunctionPassManager::doFinalization() {
1373 return FPM->doFinalization(*M);
1376 //===----------------------------------------------------------------------===//
1377 // FunctionPassManagerImpl implementation
1379 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1380 bool Changed = false;
1385 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1386 Changed |= getContainedManager(Index)->doInitialization(M);
1391 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1392 bool Changed = false;
1394 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1395 Changed |= getContainedManager(Index)->doFinalization(M);
1400 /// cleanup - After running all passes, clean up pass manager cache.
1401 void FPPassManager::cleanup() {
1402 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1403 FunctionPass *FP = getContainedPass(Index);
1404 AnalysisResolver *AR = FP->getResolver();
1405 assert(AR && "Analysis Resolver is not set");
1406 AR->clearAnalysisImpls();
1410 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1413 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1414 FPPassManager *FPPM = getContainedManager(Index);
1415 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1416 FPPM->getContainedPass(Index)->releaseMemory();
1422 // Execute all the passes managed by this top level manager.
1423 // Return true if any function is modified by a pass.
1424 bool FunctionPassManagerImpl::run(Function &F) {
1425 bool Changed = false;
1426 TimingInfo::createTheTimeInfo();
1428 initializeAllAnalysisInfo();
1429 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1430 Changed |= getContainedManager(Index)->runOnFunction(F);
1432 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1433 getContainedManager(Index)->cleanup();
1439 //===----------------------------------------------------------------------===//
1440 // FPPassManager implementation
1442 char FPPassManager::ID = 0;
1443 /// Print passes managed by this manager
1444 void FPPassManager::dumpPassStructure(unsigned Offset) {
1445 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1446 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1447 FunctionPass *FP = getContainedPass(Index);
1448 FP->dumpPassStructure(Offset + 1);
1449 dumpLastUses(FP, Offset+1);
1454 /// Execute all of the passes scheduled for execution by invoking
1455 /// runOnFunction method. Keep track of whether any of the passes modifies
1456 /// the function, and if so, return true.
1457 bool FPPassManager::runOnFunction(Function &F) {
1458 if (F.isDeclaration())
1461 bool Changed = false;
1463 // Collect inherited analysis from Module level pass manager.
1464 populateInheritedAnalysis(TPM->activeStack);
1466 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1467 FunctionPass *FP = getContainedPass(Index);
1468 bool LocalChanged = false;
1470 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1471 dumpRequiredSet(FP);
1473 initializeAnalysisImpl(FP);
1476 PassManagerPrettyStackEntry X(FP, F);
1477 TimeRegion PassTimer(getPassTimer(FP));
1479 LocalChanged |= FP->runOnFunction(F);
1482 Changed |= LocalChanged;
1484 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1485 dumpPreservedSet(FP);
1487 verifyPreservedAnalysis(FP);
1488 removeNotPreservedAnalysis(FP);
1489 recordAvailableAnalysis(FP);
1490 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1495 bool FPPassManager::runOnModule(Module &M) {
1496 bool Changed = doInitialization(M);
1498 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1499 Changed |= runOnFunction(*I);
1501 return doFinalization(M) || Changed;
1504 bool FPPassManager::doInitialization(Module &M) {
1505 bool Changed = false;
1507 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1508 Changed |= getContainedPass(Index)->doInitialization(M);
1513 bool FPPassManager::doFinalization(Module &M) {
1514 bool Changed = false;
1516 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1517 Changed |= getContainedPass(Index)->doFinalization(M);
1522 //===----------------------------------------------------------------------===//
1523 // MPPassManager implementation
1525 /// Execute all of the passes scheduled for execution by invoking
1526 /// runOnModule method. Keep track of whether any of the passes modifies
1527 /// the module, and if so, return true.
1529 MPPassManager::runOnModule(Module &M) {
1530 bool Changed = false;
1532 // Initialize on-the-fly passes
1533 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1534 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1536 FunctionPassManagerImpl *FPP = I->second;
1537 Changed |= FPP->doInitialization(M);
1540 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1541 ModulePass *MP = getContainedPass(Index);
1542 bool LocalChanged = false;
1544 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1545 dumpRequiredSet(MP);
1547 initializeAnalysisImpl(MP);
1550 PassManagerPrettyStackEntry X(MP, M);
1551 TimeRegion PassTimer(getPassTimer(MP));
1553 LocalChanged |= MP->runOnModule(M);
1556 Changed |= LocalChanged;
1558 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1559 M.getModuleIdentifier());
1560 dumpPreservedSet(MP);
1562 verifyPreservedAnalysis(MP);
1563 removeNotPreservedAnalysis(MP);
1564 recordAvailableAnalysis(MP);
1565 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1568 // Finalize on-the-fly passes
1569 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1570 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1572 FunctionPassManagerImpl *FPP = I->second;
1573 // We don't know when is the last time an on-the-fly pass is run,
1574 // so we need to releaseMemory / finalize here
1575 FPP->releaseMemoryOnTheFly();
1576 Changed |= FPP->doFinalization(M);
1581 /// Add RequiredPass into list of lower level passes required by pass P.
1582 /// RequiredPass is run on the fly by Pass Manager when P requests it
1583 /// through getAnalysis interface.
1584 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1585 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1586 "Unable to handle Pass that requires lower level Analysis pass");
1587 assert((P->getPotentialPassManagerType() <
1588 RequiredPass->getPotentialPassManagerType()) &&
1589 "Unable to handle Pass that requires lower level Analysis pass");
1591 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1593 FPP = new FunctionPassManagerImpl();
1594 // FPP is the top level manager.
1595 FPP->setTopLevelManager(FPP);
1597 OnTheFlyManagers[P] = FPP;
1599 FPP->add(RequiredPass);
1601 // Register P as the last user of RequiredPass.
1603 SmallVector<Pass *, 1> LU;
1604 LU.push_back(RequiredPass);
1605 FPP->setLastUser(LU, P);
1609 /// Return function pass corresponding to PassInfo PI, that is
1610 /// required by module pass MP. Instantiate analysis pass, by using
1611 /// its runOnFunction() for function F.
1612 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1613 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1614 assert(FPP && "Unable to find on the fly pass");
1616 FPP->releaseMemoryOnTheFly();
1618 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1622 //===----------------------------------------------------------------------===//
1623 // PassManagerImpl implementation
1625 /// run - Execute all of the passes scheduled for execution. Keep track of
1626 /// whether any of the passes modifies the module, and if so, return true.
1627 bool PassManagerImpl::run(Module &M) {
1628 bool Changed = false;
1629 TimingInfo::createTheTimeInfo();
1634 initializeAllAnalysisInfo();
1635 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1636 Changed |= getContainedManager(Index)->runOnModule(M);
1640 //===----------------------------------------------------------------------===//
1641 // PassManager implementation
1643 /// Create new pass manager
1644 PassManager::PassManager() {
1645 PM = new PassManagerImpl();
1646 // PM is the top level manager
1647 PM->setTopLevelManager(PM);
1650 PassManager::~PassManager() {
1654 /// add - Add a pass to the queue of passes to run. This passes ownership of
1655 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1656 /// will be destroyed as well, so there is no need to delete the pass. This
1657 /// implies that all passes MUST be allocated with 'new'.
1658 void PassManager::add(Pass *P) {
1662 /// run - Execute all of the passes scheduled for execution. Keep track of
1663 /// whether any of the passes modifies the module, and if so, return true.
1664 bool PassManager::run(Module &M) {
1668 //===----------------------------------------------------------------------===//
1669 // TimingInfo Class - This class is used to calculate information about the
1670 // amount of time each pass takes to execute. This only happens with
1671 // -time-passes is enabled on the command line.
1673 bool llvm::TimePassesIsEnabled = false;
1674 static cl::opt<bool,true>
1675 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1676 cl::desc("Time each pass, printing elapsed time for each on exit"));
1678 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1679 // a non null value (if the -time-passes option is enabled) or it leaves it
1680 // null. It may be called multiple times.
1681 void TimingInfo::createTheTimeInfo() {
1682 if (!TimePassesIsEnabled || TheTimeInfo) return;
1684 // Constructed the first time this is called, iff -time-passes is enabled.
1685 // This guarantees that the object will be constructed before static globals,
1686 // thus it will be destroyed before them.
1687 static ManagedStatic<TimingInfo> TTI;
1688 TheTimeInfo = &*TTI;
1691 /// If TimingInfo is enabled then start pass timer.
1692 Timer *llvm::getPassTimer(Pass *P) {
1694 return TheTimeInfo->getPassTimer(P);
1698 //===----------------------------------------------------------------------===//
1699 // PMStack implementation
1702 // Pop Pass Manager from the stack and clear its analysis info.
1703 void PMStack::pop() {
1705 PMDataManager *Top = this->top();
1706 Top->initializeAnalysisInfo();
1711 // Push PM on the stack and set its top level manager.
1712 void PMStack::push(PMDataManager *PM) {
1713 assert(PM && "Unable to push. Pass Manager expected");
1714 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1716 if (!this->empty()) {
1717 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1718 && "pushing bad pass manager to PMStack");
1719 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1721 assert(TPM && "Unable to find top level manager");
1722 TPM->addIndirectPassManager(PM);
1723 PM->setTopLevelManager(TPM);
1724 PM->setDepth(this->top()->getDepth()+1);
1727 assert((PM->getPassManagerType() == PMT_ModulePassManager
1728 || PM->getPassManagerType() == PMT_FunctionPassManager)
1729 && "pushing bad pass manager to PMStack");
1736 // Dump content of the pass manager stack.
1737 void PMStack::dump() const {
1738 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1739 E = S.end(); I != E; ++I)
1740 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1746 /// Find appropriate Module Pass Manager in the PM Stack and
1747 /// add self into that manager.
1748 void ModulePass::assignPassManager(PMStack &PMS,
1749 PassManagerType PreferredType) {
1750 // Find Module Pass Manager
1751 while (!PMS.empty()) {
1752 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1753 if (TopPMType == PreferredType)
1754 break; // We found desired pass manager
1755 else if (TopPMType > PMT_ModulePassManager)
1756 PMS.pop(); // Pop children pass managers
1760 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1761 PMS.top()->add(this);
1764 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1765 /// in the PM Stack and add self into that manager.
1766 void FunctionPass::assignPassManager(PMStack &PMS,
1767 PassManagerType PreferredType) {
1769 // Find Function Pass Manager
1770 while (!PMS.empty()) {
1771 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1777 // Create new Function Pass Manager if needed.
1779 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1780 FPP = (FPPassManager *)PMS.top();
1782 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1783 PMDataManager *PMD = PMS.top();
1785 // [1] Create new Function Pass Manager
1786 FPP = new FPPassManager();
1787 FPP->populateInheritedAnalysis(PMS);
1789 // [2] Set up new manager's top level manager
1790 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1791 TPM->addIndirectPassManager(FPP);
1793 // [3] Assign manager to manage this new manager. This may create
1794 // and push new managers into PMS
1795 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1797 // [4] Push new manager into PMS
1801 // Assign FPP as the manager of this pass.
1805 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1806 /// in the PM Stack and add self into that manager.
1807 void BasicBlockPass::assignPassManager(PMStack &PMS,
1808 PassManagerType PreferredType) {
1811 // Basic Pass Manager is a leaf pass manager. It does not handle
1812 // any other pass manager.
1814 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1815 BBP = (BBPassManager *)PMS.top();
1817 // If leaf manager is not Basic Block Pass manager then create new
1818 // basic Block Pass manager.
1819 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1820 PMDataManager *PMD = PMS.top();
1822 // [1] Create new Basic Block Manager
1823 BBP = new BBPassManager();
1825 // [2] Set up new manager's top level manager
1826 // Basic Block Pass Manager does not live by itself
1827 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1828 TPM->addIndirectPassManager(BBP);
1830 // [3] Assign manager to manage this new manager. This may create
1831 // and push new managers into PMS
1832 BBP->assignPassManager(PMS, PreferredType);
1834 // [4] Push new manager into PMS
1838 // Assign BBP as the manager of this pass.
1842 PassManagerBase::~PassManagerBase() {}