1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
25 // See PassManagers.h for Pass Manager infrastructure overview.
29 //===----------------------------------------------------------------------===//
30 // Pass debugging information. Often it is useful to find out what pass is
31 // running when a crash occurs in a utility. When this library is compiled with
32 // debugging on, a command line option (--debug-pass) is enabled that causes the
33 // pass name to be printed before it executes.
36 // Different debug levels that can be enabled...
38 None, Arguments, Structure, Executions, Details
41 static cl::opt<enum PassDebugLevel>
42 PassDebugging("debug-pass", cl::Hidden,
43 cl::desc("Print PassManager debugging information"),
45 clEnumVal(None , "disable debug output"),
46 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
47 clEnumVal(Structure , "print pass structure before run()"),
48 clEnumVal(Executions, "print pass name before it is executed"),
49 clEnumVal(Details , "print pass details when it is executed"),
51 } // End of llvm namespace
55 //===----------------------------------------------------------------------===//
58 /// BBPassManager manages BasicBlockPass. It batches all the
59 /// pass together and sequence them to process one basic block before
60 /// processing next basic block.
61 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
65 BBPassManager(int Depth) : PMDataManager(Depth) { }
67 /// Execute all of the passes scheduled for execution. Keep track of
68 /// whether any of the passes modifies the function, and if so, return true.
69 bool runOnFunction(Function &F);
71 /// Pass Manager itself does not invalidate any analysis info.
72 void getAnalysisUsage(AnalysisUsage &Info) const {
73 Info.setPreservesAll();
76 bool doInitialization(Module &M);
77 bool doInitialization(Function &F);
78 bool doFinalization(Module &M);
79 bool doFinalization(Function &F);
81 virtual const char *getPassName() const {
82 return "BasicBlock Pass Manager";
85 // Print passes managed by this manager
86 void dumpPassStructure(unsigned Offset) {
87 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
88 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
89 BasicBlockPass *BP = getContainedPass(Index);
90 BP->dumpPassStructure(Offset + 1);
91 dumpLastUses(BP, Offset+1);
95 BasicBlockPass *getContainedPass(unsigned N) {
96 assert ( N < PassVector.size() && "Pass number out of range!");
97 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
101 virtual PassManagerType getPassManagerType() {
102 return PMT_BasicBlockPassManager;
110 //===----------------------------------------------------------------------===//
111 // FunctionPassManagerImpl
113 /// FunctionPassManagerImpl manages FPPassManagers
114 class FunctionPassManagerImpl : public Pass,
115 public PMDataManager,
116 public PMTopLevelManager {
119 FunctionPassManagerImpl(int Depth) : PMDataManager(Depth),
120 PMTopLevelManager(TLM_Function) { }
122 /// add - Add a pass to the queue of passes to run. This passes ownership of
123 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
124 /// will be destroyed as well, so there is no need to delete the pass. This
125 /// implies that all passes MUST be allocated with 'new'.
130 /// run - Execute all of the passes scheduled for execution. Keep track of
131 /// whether any of the passes modifies the module, and if so, return true.
132 bool run(Function &F);
134 /// doInitialization - Run all of the initializers for the function passes.
136 bool doInitialization(Module &M);
138 /// doFinalization - Run all of the initializers for the function passes.
140 bool doFinalization(Module &M);
142 /// Pass Manager itself does not invalidate any analysis info.
143 void getAnalysisUsage(AnalysisUsage &Info) const {
144 Info.setPreservesAll();
147 inline void addTopLevelPass(Pass *P) {
149 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
151 // P is a immutable pass and it will be managed by this
152 // top level manager. Set up analysis resolver to connect them.
153 AnalysisResolver *AR = new AnalysisResolver(*this);
155 initializeAnalysisImpl(P);
156 addImmutablePass(IP);
157 recordAvailableAnalysis(IP);
159 P->assignPassManager(activeStack);
160 activeStack.handleLastUserOverflow();
165 FPPassManager *getContainedManager(unsigned N) {
166 assert ( N < PassManagers.size() && "Pass number out of range!");
167 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
173 //===----------------------------------------------------------------------===//
176 /// MPPassManager manages ModulePasses and function pass managers.
177 /// It batches all Module passes passes and function pass managers together and
178 /// sequence them to process one module.
179 class MPPassManager : public Pass, public PMDataManager {
182 MPPassManager(int Depth) : PMDataManager(Depth) { }
184 /// run - Execute all of the passes scheduled for execution. Keep track of
185 /// whether any of the passes modifies the module, and if so, return true.
186 bool runOnModule(Module &M);
188 /// Pass Manager itself does not invalidate any analysis info.
189 void getAnalysisUsage(AnalysisUsage &Info) const {
190 Info.setPreservesAll();
193 virtual const char *getPassName() const {
194 return "Module Pass Manager";
197 // Print passes managed by this manager
198 void dumpPassStructure(unsigned Offset) {
199 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
200 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
201 ModulePass *MP = getContainedPass(Index);
202 MP->dumpPassStructure(Offset + 1);
203 dumpLastUses(MP, Offset+1);
207 ModulePass *getContainedPass(unsigned N) {
208 assert ( N < PassVector.size() && "Pass number out of range!");
209 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
213 virtual PassManagerType getPassManagerType() { return PMT_ModulePassManager; }
216 //===----------------------------------------------------------------------===//
219 /// PassManagerImpl manages MPPassManagers
220 class PassManagerImpl : public Pass,
221 public PMDataManager,
222 public PMTopLevelManager {
226 PassManagerImpl(int Depth) : PMDataManager(Depth),
227 PMTopLevelManager(TLM_Pass) { }
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 /// run - Execute all of the passes scheduled for execution. Keep track of
238 /// whether any of the passes modifies the module, and if so, return true.
241 /// Pass Manager itself does not invalidate any analysis info.
242 void getAnalysisUsage(AnalysisUsage &Info) const {
243 Info.setPreservesAll();
246 inline void addTopLevelPass(Pass *P) {
248 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
250 // P is a immutable pass and it will be managed by this
251 // top level manager. Set up analysis resolver to connect them.
252 AnalysisResolver *AR = new AnalysisResolver(*this);
254 initializeAnalysisImpl(P);
255 addImmutablePass(IP);
256 recordAvailableAnalysis(IP);
258 P->assignPassManager(activeStack);
259 activeStack.handleLastUserOverflow();
264 MPPassManager *getContainedManager(unsigned N) {
265 assert ( N < PassManagers.size() && "Pass number out of range!");
266 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
272 } // End of llvm namespace
276 //===----------------------------------------------------------------------===//
277 // TimingInfo Class - This class is used to calculate information about the
278 // amount of time each pass takes to execute. This only happens when
279 // -time-passes is enabled on the command line.
282 class VISIBILITY_HIDDEN TimingInfo {
283 std::map<Pass*, Timer> TimingData;
287 // Use 'create' member to get this.
288 TimingInfo() : TG("... Pass execution timing report ...") {}
290 // TimingDtor - Print out information about timing information
292 // Delete all of the timers...
294 // TimerGroup is deleted next, printing the report.
297 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
298 // to a non null value (if the -time-passes option is enabled) or it leaves it
299 // null. It may be called multiple times.
300 static void createTheTimeInfo();
302 void passStarted(Pass *P) {
304 if (dynamic_cast<PMDataManager *>(P))
307 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
308 if (I == TimingData.end())
309 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
310 I->second.startTimer();
312 void passEnded(Pass *P) {
314 if (dynamic_cast<PMDataManager *>(P))
317 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
318 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
319 I->second.stopTimer();
323 static TimingInfo *TheTimeInfo;
325 } // End of anon namespace
327 //===----------------------------------------------------------------------===//
328 // PMTopLevelManager implementation
330 /// Initialize top level manager. Create first pass manager.
331 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
334 MPPassManager *MPP = new MPPassManager(1);
335 MPP->setTopLevelManager(this);
337 activeStack.push(MPP);
339 else if (t == TLM_Function) {
340 FPPassManager *FPP = new FPPassManager(1);
341 FPP->setTopLevelManager(this);
343 activeStack.push(FPP);
347 /// Set pass P as the last user of the given analysis passes.
348 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
351 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
352 E = AnalysisPasses.end(); I != E; ++I) {
355 // If AP is the last user of other passes then make P last user of
357 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
358 LUE = LastUser.end(); LUI != LUE; ++LUI) {
359 if (LUI->second == AP)
360 LastUser[LUI->first] = P;
365 // Walk LastUser map and create inverted map. This should be done
366 // after all passes are added and before running first pass.
367 void PMTopLevelManager::collectInvertedLU() {
368 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
369 LUE = LastUser.end(); LUI != LUE; ++LUI)
370 InvertedLU[LUI->second].push_back(LUI->first);
373 /// Collect passes whose last user is P
374 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
376 std::vector<Pass *>&LU = InvertedLU[P];
377 LastUses.insert(LastUses.end(), LU.begin(), LU.end());
380 /// Schedule pass P for execution. Make sure that passes required by
381 /// P are run before P is run. Update analysis info maintained by
382 /// the manager. Remove dead passes. This is a recursive function.
383 void PMTopLevelManager::schedulePass(Pass *P) {
385 // TODO : Allocate function manager for this pass, other wise required set
386 // may be inserted into previous function manager
388 // If this Analysis is already requested by one of the previous pass
389 // and it is still available then do not insert new pass in the queue again.
390 if (findAnalysisPass(P->getPassInfo()))
393 AnalysisUsage AnUsage;
394 P->getAnalysisUsage(AnUsage);
395 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
396 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
397 E = RequiredSet.end(); I != E; ++I) {
399 Pass *AnalysisPass = findAnalysisPass(*I);
401 // Schedule this analysis run first.
402 AnalysisPass = (*I)->createPass();
403 schedulePass(AnalysisPass);
407 // Now all required passes are available.
411 /// Find the pass that implements Analysis AID. Search immutable
412 /// passes and all pass managers. If desired pass is not found
413 /// then return NULL.
414 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
417 // Check pass managers
418 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
419 E = PassManagers.end(); P == NULL && I != E; ++I) {
420 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
421 assert(PMD && "This is not a PassManager");
422 P = PMD->findAnalysisPass(AID, false);
425 // Check other pass managers
426 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
427 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
428 P = (*I)->findAnalysisPass(AID, false);
430 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
431 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
432 const PassInfo *PI = (*I)->getPassInfo();
436 // If Pass not found then check the interfaces implemented by Immutable Pass
438 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
439 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
447 // Print passes managed by this top level manager.
448 void PMTopLevelManager::dumpPasses() const {
450 if (PassDebugging < Structure)
453 // Print out the immutable passes
454 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
455 ImmutablePasses[i]->dumpPassStructure(0);
458 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
459 E = PassManagers.end(); I != E; ++I)
460 (*I)->dumpPassStructure(1);
463 void PMTopLevelManager::dumpArguments() const {
465 if (PassDebugging < Arguments)
468 cerr << "Pass Arguments: ";
469 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
470 E = PassManagers.end(); I != E; ++I) {
471 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
472 assert(PMD && "This is not a PassManager");
473 PMD->dumpPassArguments();
478 void PMTopLevelManager::initializeAllAnalysisInfo() {
480 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
481 E = PassManagers.end(); I != E; ++I) {
482 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
483 assert(PMD && "This is not a PassManager");
484 PMD->initializeAnalysisInfo();
487 // Initailize other pass managers
488 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
489 E = IndirectPassManagers.end(); I != E; ++I)
490 (*I)->initializeAnalysisInfo();
494 PMTopLevelManager::~PMTopLevelManager() {
495 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
496 E = PassManagers.end(); I != E; ++I)
499 for (std::vector<ImmutablePass *>::iterator
500 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
503 PassManagers.clear();
506 //===----------------------------------------------------------------------===//
507 // PMDataManager implementation
509 /// Return true IFF pass P's required analysis set does not required new
511 bool PMDataManager::manageablePass(Pass *P) {
514 // If this pass is not preserving information that is required by a
515 // pass maintained by higher level pass manager then do not insert
516 // this pass into current manager. Use new manager. For example,
517 // For example, If FunctionPass F is not preserving ModulePass Info M1
518 // that is used by another ModulePass M2 then do not insert F in
519 // current function pass manager.
523 /// Augement AvailableAnalysis by adding analysis made available by pass P.
524 void PMDataManager::recordAvailableAnalysis(Pass *P) {
526 if (const PassInfo *PI = P->getPassInfo()) {
527 AvailableAnalysis[PI] = P;
529 //This pass is the current implementation of all of the interfaces it
530 //implements as well.
531 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
532 for (unsigned i = 0, e = II.size(); i != e; ++i)
533 AvailableAnalysis[II[i]] = P;
537 /// Remove Analyss not preserved by Pass P
538 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
539 AnalysisUsage AnUsage;
540 P->getAnalysisUsage(AnUsage);
542 if (AnUsage.getPreservesAll())
545 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
546 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
547 E = AvailableAnalysis.end(); I != E; ) {
548 std::map<AnalysisID, Pass*>::iterator Info = I++;
549 if (std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
550 PreservedSet.end()) {
551 // Remove this analysis
552 if (!dynamic_cast<ImmutablePass*>(Info->second))
553 AvailableAnalysis.erase(Info);
558 /// Remove analysis passes that are not used any longer
559 void PMDataManager::removeDeadPasses(Pass *P, std::string &Msg) {
561 std::vector<Pass *> DeadPasses;
562 TPM->collectLastUses(DeadPasses, P);
564 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
565 E = DeadPasses.end(); I != E; ++I) {
567 std::string Msg1 = " Freeing Pass '";
568 dumpPassInfo(*I, Msg1, Msg);
570 if (TheTimeInfo) TheTimeInfo->passStarted(P);
571 (*I)->releaseMemory();
572 if (TheTimeInfo) TheTimeInfo->passEnded(P);
574 std::map<AnalysisID, Pass*>::iterator Pos =
575 AvailableAnalysis.find((*I)->getPassInfo());
577 // It is possible that pass is already removed from the AvailableAnalysis
578 if (Pos != AvailableAnalysis.end())
579 AvailableAnalysis.erase(Pos);
583 /// Add pass P into the PassVector. Update
584 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
585 void PMDataManager::add(Pass *P,
586 bool ProcessAnalysis) {
588 // This manager is going to manage pass P. Set up analysis resolver
590 AnalysisResolver *AR = new AnalysisResolver(*this);
593 if (ProcessAnalysis) {
595 // At the moment, this pass is the last user of all required passes.
596 std::vector<Pass *> LastUses;
597 std::vector<Pass *> RequiredPasses;
598 unsigned PDepth = this->getDepth();
600 collectRequiredAnalysisPasses(RequiredPasses, P);
601 for (std::vector<Pass *>::iterator I = RequiredPasses.begin(),
602 E = RequiredPasses.end(); I != E; ++I) {
603 Pass *PRequired = *I;
606 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
607 RDepth = DM.getDepth();
609 if (PDepth == RDepth)
610 LastUses.push_back(PRequired);
611 else if (PDepth > RDepth) {
612 // Let the parent claim responsibility of last use
613 TransferLastUses.push_back(PRequired);
615 // Note : This feature is not yet implemented
617 "Unable to handle Pass that requires lower level Analysis pass");
621 // Set P as P's last user until someone starts using P.
622 // However, if P is a Pass Manager then it does not need
623 // to record its last user.
624 if (!dynamic_cast<PMDataManager *>(P))
625 LastUses.push_back(P);
626 TPM->setLastUser(LastUses, P);
628 // Take a note of analysis required and made available by this pass.
629 // Remove the analysis not preserved by this pass
630 removeNotPreservedAnalysis(P);
631 recordAvailableAnalysis(P);
635 PassVector.push_back(P);
638 /// Populate RequiredPasses with the analysis pass that are required by
640 void PMDataManager::collectRequiredAnalysisPasses(std::vector<Pass *> &RP,
642 AnalysisUsage AnUsage;
643 P->getAnalysisUsage(AnUsage);
644 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
645 for (std::vector<AnalysisID>::const_iterator
646 I = RequiredSet.begin(), E = RequiredSet.end();
648 Pass *AnalysisPass = findAnalysisPass(*I, true);
649 assert (AnalysisPass && "Analysis pass is not available");
650 RP.push_back(AnalysisPass);
653 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
654 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
655 E = IDs.end(); I != E; ++I) {
656 Pass *AnalysisPass = findAnalysisPass(*I, true);
657 assert (AnalysisPass && "Analysis pass is not available");
658 RP.push_back(AnalysisPass);
662 // All Required analyses should be available to the pass as it runs! Here
663 // we fill in the AnalysisImpls member of the pass so that it can
664 // successfully use the getAnalysis() method to retrieve the
665 // implementations it needs.
667 void PMDataManager::initializeAnalysisImpl(Pass *P) {
668 AnalysisUsage AnUsage;
669 P->getAnalysisUsage(AnUsage);
671 for (std::vector<const PassInfo *>::const_iterator
672 I = AnUsage.getRequiredSet().begin(),
673 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
674 Pass *Impl = findAnalysisPass(*I, true);
676 assert(0 && "Analysis used but not available!");
677 AnalysisResolver *AR = P->getResolver();
678 AR->addAnalysisImplsPair(*I, Impl);
682 /// Find the pass that implements Analysis AID. If desired pass is not found
683 /// then return NULL.
684 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
686 // Check if AvailableAnalysis map has one entry.
687 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
689 if (I != AvailableAnalysis.end())
692 // Search Parents through TopLevelManager
694 return TPM->findAnalysisPass(AID);
699 // Print list of passes that are last used by P.
700 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
702 std::vector<Pass *> LUses;
704 assert (TPM && "Top Level Manager is missing");
705 TPM->collectLastUses(LUses, P);
707 for (std::vector<Pass *>::iterator I = LUses.begin(),
708 E = LUses.end(); I != E; ++I) {
709 llvm::cerr << "--" << std::string(Offset*2, ' ');
710 (*I)->dumpPassStructure(0);
714 void PMDataManager::dumpPassArguments() const {
715 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
716 E = PassVector.end(); I != E; ++I) {
717 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
718 PMD->dumpPassArguments();
720 if (const PassInfo *PI = (*I)->getPassInfo())
721 if (!PI->isAnalysisGroup())
722 cerr << " -" << PI->getPassArgument();
726 void PMDataManager:: dumpPassInfo(Pass *P, std::string &Msg1,
727 std::string &Msg2) const {
728 if (PassDebugging < Executions)
730 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
732 cerr << P->getPassName();
736 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
737 const std::vector<AnalysisID> &Set)
739 if (PassDebugging >= Details && !Set.empty()) {
740 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
741 for (unsigned i = 0; i != Set.size(); ++i) {
743 cerr << " " << Set[i]->getPassName();
750 PMDataManager::~PMDataManager() {
752 for (std::vector<Pass *>::iterator I = PassVector.begin(),
753 E = PassVector.end(); I != E; ++I)
759 //===----------------------------------------------------------------------===//
760 // NOTE: Is this the right place to define this method ?
761 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
762 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
763 return PM.findAnalysisPass(ID, dir);
766 //===----------------------------------------------------------------------===//
767 // BBPassManager implementation
769 /// Execute all of the passes scheduled for execution by invoking
770 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
771 /// the function, and if so, return true.
773 BBPassManager::runOnFunction(Function &F) {
775 if (F.isDeclaration())
778 bool Changed = doInitialization(F);
780 std::string Msg1 = "Executing Pass '";
781 std::string Msg3 = "' Made Modification '";
783 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
784 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
785 BasicBlockPass *BP = getContainedPass(Index);
786 AnalysisUsage AnUsage;
787 BP->getAnalysisUsage(AnUsage);
789 std::string Msg2 = "' on BasicBlock '" + (*I).getName() + "'...\n";
790 dumpPassInfo(BP, Msg1, Msg2);
791 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
793 initializeAnalysisImpl(BP);
795 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
796 Changed |= BP->runOnBasicBlock(*I);
797 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
800 dumpPassInfo(BP, Msg3, Msg2);
801 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
803 removeNotPreservedAnalysis(BP);
804 recordAvailableAnalysis(BP);
805 removeDeadPasses(BP, Msg2);
807 return Changed |= doFinalization(F);
810 // Implement doInitialization and doFinalization
811 inline bool BBPassManager::doInitialization(Module &M) {
812 bool Changed = false;
814 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
815 BasicBlockPass *BP = getContainedPass(Index);
816 Changed |= BP->doInitialization(M);
822 inline bool BBPassManager::doFinalization(Module &M) {
823 bool Changed = false;
825 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
826 BasicBlockPass *BP = getContainedPass(Index);
827 Changed |= BP->doFinalization(M);
833 inline bool BBPassManager::doInitialization(Function &F) {
834 bool Changed = false;
836 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
837 BasicBlockPass *BP = getContainedPass(Index);
838 Changed |= BP->doInitialization(F);
844 inline bool BBPassManager::doFinalization(Function &F) {
845 bool Changed = false;
847 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
848 BasicBlockPass *BP = getContainedPass(Index);
849 Changed |= BP->doFinalization(F);
856 //===----------------------------------------------------------------------===//
857 // FunctionPassManager implementation
859 /// Create new Function pass manager
860 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
861 FPM = new FunctionPassManagerImpl(0);
862 // FPM is the top level manager.
863 FPM->setTopLevelManager(FPM);
865 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
866 AnalysisResolver *AR = new AnalysisResolver(*PMD);
867 FPM->setResolver(AR);
872 FunctionPassManager::~FunctionPassManager() {
876 /// add - Add a pass to the queue of passes to run. This passes
877 /// ownership of the Pass to the PassManager. When the
878 /// PassManager_X is destroyed, the pass will be destroyed as well, so
879 /// there is no need to delete the pass. (TODO delete passes.)
880 /// This implies that all passes MUST be allocated with 'new'.
881 void FunctionPassManager::add(Pass *P) {
885 /// run - Execute all of the passes scheduled for execution. Keep
886 /// track of whether any of the passes modifies the function, and if
889 bool FunctionPassManager::run(Function &F) {
891 if (MP->materializeFunction(&F, &errstr)) {
892 cerr << "Error reading bytecode file: " << errstr << "\n";
899 /// doInitialization - Run all of the initializers for the function passes.
901 bool FunctionPassManager::doInitialization() {
902 return FPM->doInitialization(*MP->getModule());
905 /// doFinalization - Run all of the initializers for the function passes.
907 bool FunctionPassManager::doFinalization() {
908 return FPM->doFinalization(*MP->getModule());
911 //===----------------------------------------------------------------------===//
912 // FunctionPassManagerImpl implementation
914 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
915 bool Changed = false;
917 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
918 FPPassManager *FP = getContainedManager(Index);
919 Changed |= FP->doInitialization(M);
925 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
926 bool Changed = false;
928 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
929 FPPassManager *FP = getContainedManager(Index);
930 Changed |= FP->doFinalization(M);
936 // Execute all the passes managed by this top level manager.
937 // Return true if any function is modified by a pass.
938 bool FunctionPassManagerImpl::run(Function &F) {
940 bool Changed = false;
942 TimingInfo::createTheTimeInfo();
947 // Collect inverted map of LastUsers. This improves speed of
948 // collectLastUses().
949 TPM->collectInvertedLU();
950 initializeAllAnalysisInfo();
951 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
952 FPPassManager *FP = getContainedManager(Index);
953 Changed |= FP->runOnFunction(F);
958 //===----------------------------------------------------------------------===//
959 // FPPassManager implementation
961 /// Print passes managed by this manager
962 void FPPassManager::dumpPassStructure(unsigned Offset) {
963 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
964 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
965 FunctionPass *FP = getContainedPass(Index);
966 FP->dumpPassStructure(Offset + 1);
967 dumpLastUses(FP, Offset+1);
972 /// Execute all of the passes scheduled for execution by invoking
973 /// runOnFunction method. Keep track of whether any of the passes modifies
974 /// the function, and if so, return true.
975 bool FPPassManager::runOnFunction(Function &F) {
977 bool Changed = false;
979 if (F.isDeclaration())
982 std::string Msg1 = "Executing Pass '";
983 std::string Msg3 = "' Made Modification '";
985 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
986 FunctionPass *FP = getContainedPass(Index);
988 AnalysisUsage AnUsage;
989 FP->getAnalysisUsage(AnUsage);
991 std::string Msg2 = "' on Function '" + F.getName() + "'...\n";
992 dumpPassInfo(FP, Msg1, Msg2);
993 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
995 initializeAnalysisImpl(FP);
997 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
998 Changed |= FP->runOnFunction(F);
999 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1002 dumpPassInfo(FP, Msg3, Msg2);
1003 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1005 removeNotPreservedAnalysis(FP);
1006 recordAvailableAnalysis(FP);
1007 removeDeadPasses(FP, Msg2);
1012 bool FPPassManager::runOnModule(Module &M) {
1014 bool Changed = doInitialization(M);
1016 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1017 this->runOnFunction(*I);
1019 return Changed |= doFinalization(M);
1022 inline bool FPPassManager::doInitialization(Module &M) {
1023 bool Changed = false;
1025 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1026 FunctionPass *FP = getContainedPass(Index);
1027 Changed |= FP->doInitialization(M);
1033 inline bool FPPassManager::doFinalization(Module &M) {
1034 bool Changed = false;
1036 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1037 FunctionPass *FP = getContainedPass(Index);
1038 Changed |= FP->doFinalization(M);
1044 //===----------------------------------------------------------------------===//
1045 // MPPassManager implementation
1047 /// Execute all of the passes scheduled for execution by invoking
1048 /// runOnModule method. Keep track of whether any of the passes modifies
1049 /// the module, and if so, return true.
1051 MPPassManager::runOnModule(Module &M) {
1052 bool Changed = false;
1054 std::string Msg1 = "Executing Pass '";
1055 std::string Msg3 = "' Made Modification '";
1057 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1058 ModulePass *MP = getContainedPass(Index);
1060 AnalysisUsage AnUsage;
1061 MP->getAnalysisUsage(AnUsage);
1063 std::string Msg2 = "' on Module '" + M.getModuleIdentifier() + "'...\n";
1064 dumpPassInfo(MP, Msg1, Msg2);
1065 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1067 initializeAnalysisImpl(MP);
1069 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1070 Changed |= MP->runOnModule(M);
1071 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1074 dumpPassInfo(MP, Msg3, Msg2);
1075 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1077 removeNotPreservedAnalysis(MP);
1078 recordAvailableAnalysis(MP);
1079 removeDeadPasses(MP, Msg2);
1084 //===----------------------------------------------------------------------===//
1085 // PassManagerImpl implementation
1087 /// run - Execute all of the passes scheduled for execution. Keep track of
1088 /// whether any of the passes modifies the module, and if so, return true.
1089 bool PassManagerImpl::run(Module &M) {
1091 bool Changed = false;
1093 TimingInfo::createTheTimeInfo();
1098 // Collect inverted map of LastUsers. This improves speed of
1099 // collectLastUses().
1100 TPM->collectInvertedLU();
1101 initializeAllAnalysisInfo();
1102 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1103 MPPassManager *MP = getContainedManager(Index);
1104 Changed |= MP->runOnModule(M);
1109 //===----------------------------------------------------------------------===//
1110 // PassManager implementation
1112 /// Create new pass manager
1113 PassManager::PassManager() {
1114 PM = new PassManagerImpl(0);
1115 // PM is the top level manager
1116 PM->setTopLevelManager(PM);
1119 PassManager::~PassManager() {
1123 /// add - Add a pass to the queue of passes to run. This passes ownership of
1124 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1125 /// will be destroyed as well, so there is no need to delete the pass. This
1126 /// implies that all passes MUST be allocated with 'new'.
1128 PassManager::add(Pass *P) {
1132 /// run - Execute all of the passes scheduled for execution. Keep track of
1133 /// whether any of the passes modifies the module, and if so, return true.
1135 PassManager::run(Module &M) {
1139 //===----------------------------------------------------------------------===//
1140 // TimingInfo Class - This class is used to calculate information about the
1141 // amount of time each pass takes to execute. This only happens with
1142 // -time-passes is enabled on the command line.
1144 bool llvm::TimePassesIsEnabled = false;
1145 static cl::opt<bool,true>
1146 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1147 cl::desc("Time each pass, printing elapsed time for each on exit"));
1149 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1150 // a non null value (if the -time-passes option is enabled) or it leaves it
1151 // null. It may be called multiple times.
1152 void TimingInfo::createTheTimeInfo() {
1153 if (!TimePassesIsEnabled || TheTimeInfo) return;
1155 // Constructed the first time this is called, iff -time-passes is enabled.
1156 // This guarantees that the object will be constructed before static globals,
1157 // thus it will be destroyed before them.
1158 static ManagedStatic<TimingInfo> TTI;
1159 TheTimeInfo = &*TTI;
1162 /// If TimingInfo is enabled then start pass timer.
1163 void StartPassTimer(Pass *P) {
1165 TheTimeInfo->passStarted(P);
1168 /// If TimingInfo is enabled then stop pass timer.
1169 void StopPassTimer(Pass *P) {
1171 TheTimeInfo->passEnded(P);
1174 //===----------------------------------------------------------------------===//
1175 // PMStack implementation
1178 // Pop Pass Manager from the stack and clear its analysis info.
1179 void PMStack::pop() {
1181 PMDataManager *Top = this->top();
1182 Top->initializeAnalysisInfo();
1187 // Push PM on the stack and set its top level manager.
1188 void PMStack::push(Pass *P) {
1190 PMDataManager *Top = NULL;
1191 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1192 assert (PM && "Unable to push. Pass Manager expected");
1194 if (this->empty()) {
1199 PMTopLevelManager *TPM = Top->getTopLevelManager();
1201 assert (TPM && "Unable to find top level manager");
1202 TPM->addIndirectPassManager(PM);
1203 PM->setTopLevelManager(TPM);
1206 AnalysisResolver *AR = new AnalysisResolver(*Top);
1212 // Dump content of the pass manager stack.
1213 void PMStack::dump() {
1214 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1215 E = S.end(); I != E; ++I) {
1216 Pass *P = dynamic_cast<Pass *>(*I);
1217 printf ("%s ", P->getPassName());
1223 // Walk Pass Manager stack and set LastUse markers if any
1224 // manager is transfering this priviledge to its parent manager
1225 void PMStack::handleLastUserOverflow() {
1227 for(PMStack::iterator I = this->begin(), E = this->end(); I != E;) {
1229 PMDataManager *Child = *I++;
1231 PMDataManager *Parent = *I++;
1232 PMTopLevelManager *TPM = Parent->getTopLevelManager();
1233 std::vector<Pass *> &TLU = Child->getTransferredLastUses();
1235 Pass *P = dynamic_cast<Pass *>(Parent);
1236 TPM->setLastUser(TLU, P);
1243 /// Find appropriate Module Pass Manager in the PM Stack and
1244 /// add self into that manager.
1245 void ModulePass::assignPassManager(PMStack &PMS,
1246 PassManagerType PreferredType) {
1248 // Find Module Pass Manager
1249 while(!PMS.empty()) {
1250 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1251 if (TopPMType == PreferredType)
1252 break; // We found desired pass manager
1253 else if (TopPMType > PMT_ModulePassManager)
1254 PMS.pop(); // Pop children pass managers
1259 PMS.top()->add(this);
1262 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1263 /// in the PM Stack and add self into that manager.
1264 void FunctionPass::assignPassManager(PMStack &PMS,
1265 PassManagerType PreferredType) {
1267 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1268 while(!PMS.empty()) {
1269 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1274 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1276 // Create new Function Pass Manager
1278 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1279 PMDataManager *PMD = PMS.top();
1281 // [1] Create new Function Pass Manager
1282 FPP = new FPPassManager(PMD->getDepth() + 1);
1284 // [2] Set up new manager's top level manager
1285 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1286 TPM->addIndirectPassManager(FPP);
1288 // [3] Assign manager to manage this new manager. This may create
1289 // and push new managers into PMS
1290 Pass *P = dynamic_cast<Pass *>(FPP);
1292 // If Call Graph Pass Manager is active then use it to manage
1293 // this new Function Pass manager.
1294 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1295 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1297 P->assignPassManager(PMS);
1299 // [4] Push new manager into PMS
1303 // Assign FPP as the manager of this pass.
1307 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1308 /// in the PM Stack and add self into that manager.
1309 void BasicBlockPass::assignPassManager(PMStack &PMS,
1310 PassManagerType PreferredType) {
1312 BBPassManager *BBP = NULL;
1314 // Basic Pass Manager is a leaf pass manager. It does not handle
1315 // any other pass manager.
1317 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1320 // If leaf manager is not Basic Block Pass manager then create new
1321 // basic Block Pass manager.
1324 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1325 PMDataManager *PMD = PMS.top();
1327 // [1] Create new Basic Block Manager
1328 BBP = new BBPassManager(PMD->getDepth() + 1);
1330 // [2] Set up new manager's top level manager
1331 // Basic Block Pass Manager does not live by itself
1332 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1333 TPM->addIndirectPassManager(BBP);
1335 // [3] Assign manager to manage this new manager. This may create
1336 // and push new managers into PMS
1337 Pass *P = dynamic_cast<Pass *>(BBP);
1338 P->assignPassManager(PMS);
1340 // [4] Push new manager into PMS
1344 // Assign BBP as the manager of this pass.