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/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"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm-c/Core.h"
30 // See PassManagers.h for Pass Manager infrastructure overview.
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
41 // Different debug levels that can be enabled...
43 None, Arguments, Structure, Executions, Details
46 // Always verify dominfo if expensive checking is enabled.
48 bool VerifyDomInfo = true;
50 bool VerifyDomInfo = false;
52 static cl::opt<bool,true>
53 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
54 cl::desc("Verify dominator info (time consuming)"));
56 static cl::opt<enum PassDebugLevel>
57 PassDebugging("debug-pass", cl::Hidden,
58 cl::desc("Print PassManager debugging information"),
60 clEnumVal(None , "disable debug output"),
61 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
62 clEnumVal(Structure , "print pass structure before run()"),
63 clEnumVal(Executions, "print pass name before it is executed"),
64 clEnumVal(Details , "print pass details when it is executed"),
66 } // End of llvm namespace
68 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
70 OS << "Releasing pass '";
72 OS << "Running pass '";
74 OS << P->getPassName() << "'";
77 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
88 else if (isa<BasicBlock>(V))
94 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
101 //===----------------------------------------------------------------------===//
104 /// BBPassManager manages BasicBlockPass. It batches all the
105 /// pass together and sequence them to process one basic block before
106 /// processing next basic block.
107 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
108 public FunctionPass {
112 explicit BBPassManager(int Depth)
113 : PMDataManager(Depth), FunctionPass(&ID) {}
115 /// Execute all of the passes scheduled for execution. Keep track of
116 /// whether any of the passes modifies the function, and if so, return true.
117 bool runOnFunction(Function &F);
119 /// Pass Manager itself does not invalidate any analysis info.
120 void getAnalysisUsage(AnalysisUsage &Info) const {
121 Info.setPreservesAll();
124 bool doInitialization(Module &M);
125 bool doInitialization(Function &F);
126 bool doFinalization(Module &M);
127 bool doFinalization(Function &F);
129 virtual const char *getPassName() const {
130 return "BasicBlock Pass Manager";
133 // Print passes managed by this manager
134 void dumpPassStructure(unsigned Offset) {
135 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
136 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
137 BasicBlockPass *BP = getContainedPass(Index);
138 BP->dumpPassStructure(Offset + 1);
139 dumpLastUses(BP, Offset+1);
143 BasicBlockPass *getContainedPass(unsigned N) {
144 assert(N < PassVector.size() && "Pass number out of range!");
145 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
149 virtual PassManagerType getPassManagerType() const {
150 return PMT_BasicBlockPassManager;
154 char BBPassManager::ID = 0;
159 //===----------------------------------------------------------------------===//
160 // FunctionPassManagerImpl
162 /// FunctionPassManagerImpl manages FPPassManagers
163 class FunctionPassManagerImpl : public Pass,
164 public PMDataManager,
165 public PMTopLevelManager {
168 explicit FunctionPassManagerImpl(int Depth) :
169 Pass(&ID), PMDataManager(Depth),
170 PMTopLevelManager(TLM_Function) { }
172 /// add - Add a pass to the queue of passes to run. This passes ownership of
173 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
174 /// will be destroyed as well, so there is no need to delete the pass. This
175 /// implies that all passes MUST be allocated with 'new'.
180 /// run - Execute all of the passes scheduled for execution. Keep track of
181 /// whether any of the passes modifies the module, and if so, return true.
182 bool run(Function &F);
184 /// doInitialization - Run all of the initializers for the function passes.
186 bool doInitialization(Module &M);
188 /// doFinalization - Run all of the finalizers for the function passes.
190 bool doFinalization(Module &M);
192 /// Pass Manager itself does not invalidate any analysis info.
193 void getAnalysisUsage(AnalysisUsage &Info) const {
194 Info.setPreservesAll();
197 inline void addTopLevelPass(Pass *P) {
199 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
201 // P is a immutable pass and it will be managed by this
202 // top level manager. Set up analysis resolver to connect them.
203 AnalysisResolver *AR = new AnalysisResolver(*this);
205 initializeAnalysisImpl(P);
206 addImmutablePass(IP);
207 recordAvailableAnalysis(IP);
209 P->assignPassManager(activeStack);
214 FPPassManager *getContainedManager(unsigned N) {
215 assert(N < PassManagers.size() && "Pass number out of range!");
216 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
221 char FunctionPassManagerImpl::ID = 0;
222 //===----------------------------------------------------------------------===//
225 /// MPPassManager manages ModulePasses and function pass managers.
226 /// It batches all Module passes and function pass managers together and
227 /// sequences them to process one module.
228 class MPPassManager : public Pass, public PMDataManager {
231 explicit MPPassManager(int Depth) :
232 Pass(&ID), PMDataManager(Depth) { }
234 // Delete on the fly managers.
235 virtual ~MPPassManager() {
236 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
237 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
239 FunctionPassManagerImpl *FPP = I->second;
244 /// run - Execute all of the passes scheduled for execution. Keep track of
245 /// whether any of the passes modifies the module, and if so, return true.
246 bool runOnModule(Module &M);
248 /// Pass Manager itself does not invalidate any analysis info.
249 void getAnalysisUsage(AnalysisUsage &Info) const {
250 Info.setPreservesAll();
253 /// Add RequiredPass into list of lower level passes required by pass P.
254 /// RequiredPass is run on the fly by Pass Manager when P requests it
255 /// through getAnalysis interface.
256 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
258 /// Return function pass corresponding to PassInfo PI, that is
259 /// required by module pass MP. Instantiate analysis pass, by using
260 /// its runOnFunction() for function F.
261 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
263 virtual const char *getPassName() const {
264 return "Module Pass Manager";
267 // Print passes managed by this manager
268 void dumpPassStructure(unsigned Offset) {
269 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
270 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
271 ModulePass *MP = getContainedPass(Index);
272 MP->dumpPassStructure(Offset + 1);
273 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
274 FPP->dumpPassStructure(Offset + 2);
275 dumpLastUses(MP, Offset+1);
279 ModulePass *getContainedPass(unsigned N) {
280 assert(N < PassVector.size() && "Pass number out of range!");
281 return static_cast<ModulePass *>(PassVector[N]);
284 virtual PassManagerType getPassManagerType() const {
285 return PMT_ModulePassManager;
289 /// Collection of on the fly FPPassManagers. These managers manage
290 /// function passes that are required by module passes.
291 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
294 char MPPassManager::ID = 0;
295 //===----------------------------------------------------------------------===//
299 /// PassManagerImpl manages MPPassManagers
300 class PassManagerImpl : public Pass,
301 public PMDataManager,
302 public PMTopLevelManager {
306 explicit PassManagerImpl(int Depth) :
307 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
309 /// add - Add a pass to the queue of passes to run. This passes ownership of
310 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
311 /// will be destroyed as well, so there is no need to delete the pass. This
312 /// implies that all passes MUST be allocated with 'new'.
317 /// run - Execute all of the passes scheduled for execution. Keep track of
318 /// whether any of the passes modifies the module, and if so, return true.
321 /// Pass Manager itself does not invalidate any analysis info.
322 void getAnalysisUsage(AnalysisUsage &Info) const {
323 Info.setPreservesAll();
326 inline void addTopLevelPass(Pass *P) {
327 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
329 // P is a immutable pass and it will be managed by this
330 // top level manager. Set up analysis resolver to connect them.
331 AnalysisResolver *AR = new AnalysisResolver(*this);
333 initializeAnalysisImpl(P);
334 addImmutablePass(IP);
335 recordAvailableAnalysis(IP);
337 P->assignPassManager(activeStack);
341 MPPassManager *getContainedManager(unsigned N) {
342 assert(N < PassManagers.size() && "Pass number out of range!");
343 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
348 char PassManagerImpl::ID = 0;
349 } // End of llvm namespace
353 //===----------------------------------------------------------------------===//
354 /// TimingInfo Class - This class is used to calculate information about the
355 /// amount of time each pass takes to execute. This only happens when
356 /// -time-passes is enabled on the command line.
358 class VISIBILITY_HIDDEN TimingInfo {
359 std::map<Pass*, Timer> TimingData;
363 // Use 'create' member to get this.
364 TimingInfo() : TG("... Pass execution timing report ...") {}
366 // TimingDtor - Print out information about timing information
368 // Delete all of the timers...
370 // TimerGroup is deleted next, printing the report.
373 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
374 // to a non null value (if the -time-passes option is enabled) or it leaves it
375 // null. It may be called multiple times.
376 static void createTheTimeInfo();
378 void passStarted(Pass *P) {
379 if (dynamic_cast<PMDataManager *>(P))
382 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
383 if (I == TimingData.end())
384 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
385 I->second.startTimer();
387 void passEnded(Pass *P) {
388 if (dynamic_cast<PMDataManager *>(P))
391 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
392 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
393 I->second.stopTimer();
397 } // End of anon namespace
399 static TimingInfo *TheTimeInfo;
401 //===----------------------------------------------------------------------===//
402 // PMTopLevelManager implementation
404 /// Initialize top level manager. Create first pass manager.
405 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
407 MPPassManager *MPP = new MPPassManager(1);
408 MPP->setTopLevelManager(this);
410 activeStack.push(MPP);
411 } else if (t == TLM_Function) {
412 FPPassManager *FPP = new FPPassManager(1);
413 FPP->setTopLevelManager(this);
415 activeStack.push(FPP);
419 /// Set pass P as the last user of the given analysis passes.
420 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
422 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
423 E = AnalysisPasses.end(); I != E; ++I) {
430 // If AP is the last user of other passes then make P last user of
432 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
433 LUE = LastUser.end(); LUI != LUE; ++LUI) {
434 if (LUI->second == AP)
435 // DenseMap iterator is not invalidated here because
436 // this is just updating exisitng entry.
437 LastUser[LUI->first] = P;
442 /// Collect passes whose last user is P
443 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
445 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
446 InversedLastUser.find(P);
447 if (DMI == InversedLastUser.end())
450 SmallPtrSet<Pass *, 8> &LU = DMI->second;
451 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
452 E = LU.end(); I != E; ++I) {
453 LastUses.push_back(*I);
458 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
459 AnalysisUsage *AnUsage = NULL;
460 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
461 if (DMI != AnUsageMap.end())
462 AnUsage = DMI->second;
464 AnUsage = new AnalysisUsage();
465 P->getAnalysisUsage(*AnUsage);
466 AnUsageMap[P] = AnUsage;
471 /// Schedule pass P for execution. Make sure that passes required by
472 /// P are run before P is run. Update analysis info maintained by
473 /// the manager. Remove dead passes. This is a recursive function.
474 void PMTopLevelManager::schedulePass(Pass *P) {
476 // TODO : Allocate function manager for this pass, other wise required set
477 // may be inserted into previous function manager
479 // Give pass a chance to prepare the stage.
480 P->preparePassManager(activeStack);
482 // If P is an analysis pass and it is available then do not
483 // generate the analysis again. Stale analysis info should not be
484 // available at this point.
485 if (P->getPassInfo() &&
486 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
491 AnalysisUsage *AnUsage = findAnalysisUsage(P);
493 bool checkAnalysis = true;
494 while (checkAnalysis) {
495 checkAnalysis = false;
497 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
498 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
499 E = RequiredSet.end(); I != E; ++I) {
501 Pass *AnalysisPass = findAnalysisPass(*I);
503 AnalysisPass = (*I)->createPass();
504 if (P->getPotentialPassManagerType () ==
505 AnalysisPass->getPotentialPassManagerType())
506 // Schedule analysis pass that is managed by the same pass manager.
507 schedulePass(AnalysisPass);
508 else if (P->getPotentialPassManagerType () >
509 AnalysisPass->getPotentialPassManagerType()) {
510 // Schedule analysis pass that is managed by a new manager.
511 schedulePass(AnalysisPass);
512 // Recheck analysis passes to ensure that required analysises that
513 // are already checked are still available.
514 checkAnalysis = true;
517 // Do not schedule this analysis. Lower level analsyis
518 // passes are run on the fly.
524 // Now all required passes are available.
528 /// Find the pass that implements Analysis AID. Search immutable
529 /// passes and all pass managers. If desired pass is not found
530 /// then return NULL.
531 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
534 // Check pass managers
535 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
536 E = PassManagers.end(); P == NULL && I != E; ++I) {
537 PMDataManager *PMD = *I;
538 P = PMD->findAnalysisPass(AID, false);
541 // Check other pass managers
542 for (SmallVector<PMDataManager *, 8>::iterator
543 I = IndirectPassManagers.begin(),
544 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
545 P = (*I)->findAnalysisPass(AID, false);
547 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
548 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
549 const PassInfo *PI = (*I)->getPassInfo();
553 // If Pass not found then check the interfaces implemented by Immutable Pass
555 const std::vector<const PassInfo*> &ImmPI =
556 PI->getInterfacesImplemented();
557 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
565 // Print passes managed by this top level manager.
566 void PMTopLevelManager::dumpPasses() const {
568 if (PassDebugging < Structure)
571 // Print out the immutable passes
572 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
573 ImmutablePasses[i]->dumpPassStructure(0);
576 // Every class that derives from PMDataManager also derives from Pass
577 // (sometimes indirectly), but there's no inheritance relationship
578 // between PMDataManager and Pass, so we have to dynamic_cast to get
579 // from a PMDataManager* to a Pass*.
580 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
581 E = PassManagers.end(); I != E; ++I)
582 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
585 void PMTopLevelManager::dumpArguments() const {
587 if (PassDebugging < Arguments)
590 cerr << "Pass Arguments: ";
591 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
592 E = PassManagers.end(); I != E; ++I)
593 (*I)->dumpPassArguments();
597 void PMTopLevelManager::initializeAllAnalysisInfo() {
598 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
599 E = PassManagers.end(); I != E; ++I)
600 (*I)->initializeAnalysisInfo();
602 // Initailize other pass managers
603 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
604 E = IndirectPassManagers.end(); I != E; ++I)
605 (*I)->initializeAnalysisInfo();
607 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
608 DME = LastUser.end(); DMI != DME; ++DMI) {
609 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
610 InversedLastUser.find(DMI->second);
611 if (InvDMI != InversedLastUser.end()) {
612 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
613 L.insert(DMI->first);
615 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
616 InversedLastUser[DMI->second] = L;
622 PMTopLevelManager::~PMTopLevelManager() {
623 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
624 E = PassManagers.end(); I != E; ++I)
627 for (SmallVector<ImmutablePass *, 8>::iterator
628 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
631 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
632 DME = AnUsageMap.end(); DMI != DME; ++DMI)
636 //===----------------------------------------------------------------------===//
637 // PMDataManager implementation
639 /// Augement AvailableAnalysis by adding analysis made available by pass P.
640 void PMDataManager::recordAvailableAnalysis(Pass *P) {
641 const PassInfo *PI = P->getPassInfo();
644 AvailableAnalysis[PI] = P;
646 //This pass is the current implementation of all of the interfaces it
647 //implements as well.
648 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
649 for (unsigned i = 0, e = II.size(); i != e; ++i)
650 AvailableAnalysis[II[i]] = P;
653 // Return true if P preserves high level analysis used by other
654 // passes managed by this manager
655 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
656 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
657 if (AnUsage->getPreservesAll())
660 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
661 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
662 E = HigherLevelAnalysis.end(); I != E; ++I) {
664 if (!dynamic_cast<ImmutablePass*>(P1) &&
665 std::find(PreservedSet.begin(), PreservedSet.end(),
666 P1->getPassInfo()) ==
674 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
675 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
676 // Don't do this unless assertions are enabled.
680 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
681 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
683 // Verify preserved analysis
684 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
685 E = PreservedSet.end(); I != E; ++I) {
687 if (Pass *AP = findAnalysisPass(AID, true))
688 AP->verifyAnalysis();
692 /// verifyDomInfo - Verify dominator information if it is available.
693 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
694 if (!VerifyDomInfo || !P.getResolver())
697 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
701 DominatorTree OtherDT;
702 OtherDT.getBase().recalculate(F);
703 if (DT->compare(OtherDT)) {
704 cerr << "Dominator Information for " << F.getNameStart() << "\n";
705 cerr << "Pass '" << P.getPassName() << "'\n";
706 cerr << "----- Valid -----\n";
708 cerr << "----- Invalid -----\n";
710 assert(0 && "Invalid dominator info");
713 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
717 DominanceFrontier OtherDF;
718 std::vector<BasicBlock*> DTRoots = DT->getRoots();
719 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
720 if (DF->compare(OtherDF)) {
721 cerr << "Dominator Information for " << F.getNameStart() << "\n";
722 cerr << "Pass '" << P.getPassName() << "'\n";
723 cerr << "----- Valid -----\n";
725 cerr << "----- Invalid -----\n";
727 assert(0 && "Invalid dominator info");
731 /// Remove Analysis not preserved by Pass P
732 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
733 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
734 if (AnUsage->getPreservesAll())
737 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
738 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
739 E = AvailableAnalysis.end(); I != E; ) {
740 std::map<AnalysisID, Pass*>::iterator Info = I++;
741 if (!dynamic_cast<ImmutablePass*>(Info->second)
742 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
743 PreservedSet.end()) {
744 // Remove this analysis
745 if (PassDebugging >= Details) {
746 Pass *S = Info->second;
747 cerr << " -- '" << P->getPassName() << "' is not preserving '";
748 cerr << S->getPassName() << "'\n";
750 AvailableAnalysis.erase(Info);
754 // Check inherited analysis also. If P is not preserving analysis
755 // provided by parent manager then remove it here.
756 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
758 if (!InheritedAnalysis[Index])
761 for (std::map<AnalysisID, Pass*>::iterator
762 I = InheritedAnalysis[Index]->begin(),
763 E = InheritedAnalysis[Index]->end(); I != E; ) {
764 std::map<AnalysisID, Pass *>::iterator Info = I++;
765 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
766 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
768 // Remove this analysis
769 InheritedAnalysis[Index]->erase(Info);
774 /// Remove analysis passes that are not used any longer
775 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
776 enum PassDebuggingString DBG_STR) {
778 SmallVector<Pass *, 12> DeadPasses;
780 // If this is a on the fly manager then it does not have TPM.
784 TPM->collectLastUses(DeadPasses, P);
786 if (PassDebugging >= Details && !DeadPasses.empty()) {
787 cerr << " -*- '" << P->getPassName();
788 cerr << "' is the last user of following pass instances.";
789 cerr << " Free these instances\n";
792 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
793 E = DeadPasses.end(); I != E; ++I) {
795 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
798 // If the pass crashes releasing memory, remember this.
799 PassManagerPrettyStackEntry X(*I);
801 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
802 (*I)->releaseMemory();
803 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
805 if (const PassInfo *PI = (*I)->getPassInfo()) {
806 std::map<AnalysisID, Pass*>::iterator Pos =
807 AvailableAnalysis.find(PI);
809 // It is possible that pass is already removed from the AvailableAnalysis
810 if (Pos != AvailableAnalysis.end())
811 AvailableAnalysis.erase(Pos);
813 // Remove all interfaces this pass implements, for which it is also
814 // listed as the available implementation.
815 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
816 for (unsigned i = 0, e = II.size(); i != e; ++i) {
817 Pos = AvailableAnalysis.find(II[i]);
818 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
819 AvailableAnalysis.erase(Pos);
825 /// Add pass P into the PassVector. Update
826 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
827 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
828 // This manager is going to manage pass P. Set up analysis resolver
830 AnalysisResolver *AR = new AnalysisResolver(*this);
833 // If a FunctionPass F is the last user of ModulePass info M
834 // then the F's manager, not F, records itself as a last user of M.
835 SmallVector<Pass *, 12> TransferLastUses;
837 if (!ProcessAnalysis) {
839 PassVector.push_back(P);
843 // At the moment, this pass is the last user of all required passes.
844 SmallVector<Pass *, 12> LastUses;
845 SmallVector<Pass *, 8> RequiredPasses;
846 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
848 unsigned PDepth = this->getDepth();
850 collectRequiredAnalysis(RequiredPasses,
851 ReqAnalysisNotAvailable, P);
852 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
853 E = RequiredPasses.end(); I != E; ++I) {
854 Pass *PRequired = *I;
857 assert(PRequired->getResolver() && "Analysis Resolver is not set");
858 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
859 RDepth = DM.getDepth();
861 if (PDepth == RDepth)
862 LastUses.push_back(PRequired);
863 else if (PDepth > RDepth) {
864 // Let the parent claim responsibility of last use
865 TransferLastUses.push_back(PRequired);
866 // Keep track of higher level analysis used by this manager.
867 HigherLevelAnalysis.push_back(PRequired);
869 assert(0 && "Unable to accomodate Required Pass");
872 // Set P as P's last user until someone starts using P.
873 // However, if P is a Pass Manager then it does not need
874 // to record its last user.
875 if (!dynamic_cast<PMDataManager *>(P))
876 LastUses.push_back(P);
877 TPM->setLastUser(LastUses, P);
879 if (!TransferLastUses.empty()) {
880 Pass *My_PM = dynamic_cast<Pass *>(this);
881 TPM->setLastUser(TransferLastUses, My_PM);
882 TransferLastUses.clear();
885 // Now, take care of required analysises that are not available.
886 for (SmallVector<AnalysisID, 8>::iterator
887 I = ReqAnalysisNotAvailable.begin(),
888 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
889 Pass *AnalysisPass = (*I)->createPass();
890 this->addLowerLevelRequiredPass(P, AnalysisPass);
893 // Take a note of analysis required and made available by this pass.
894 // Remove the analysis not preserved by this pass
895 removeNotPreservedAnalysis(P);
896 recordAvailableAnalysis(P);
899 PassVector.push_back(P);
903 /// Populate RP with analysis pass that are required by
904 /// pass P and are available. Populate RP_NotAvail with analysis
905 /// pass that are required by pass P but are not available.
906 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
907 SmallVector<AnalysisID, 8> &RP_NotAvail,
909 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
910 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
911 for (AnalysisUsage::VectorType::const_iterator
912 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
913 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
914 RP.push_back(AnalysisPass);
916 RP_NotAvail.push_back(*I);
919 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
920 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
921 E = IDs.end(); I != E; ++I) {
922 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
923 RP.push_back(AnalysisPass);
925 RP_NotAvail.push_back(*I);
929 // All Required analyses should be available to the pass as it runs! Here
930 // we fill in the AnalysisImpls member of the pass so that it can
931 // successfully use the getAnalysis() method to retrieve the
932 // implementations it needs.
934 void PMDataManager::initializeAnalysisImpl(Pass *P) {
935 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
937 for (AnalysisUsage::VectorType::const_iterator
938 I = AnUsage->getRequiredSet().begin(),
939 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
940 Pass *Impl = findAnalysisPass(*I, true);
942 // This may be analysis pass that is initialized on the fly.
943 // If that is not the case then it will raise an assert when it is used.
945 AnalysisResolver *AR = P->getResolver();
946 assert(AR && "Analysis Resolver is not set");
947 AR->addAnalysisImplsPair(*I, Impl);
951 /// Find the pass that implements Analysis AID. If desired pass is not found
952 /// then return NULL.
953 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
955 // Check if AvailableAnalysis map has one entry.
956 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
958 if (I != AvailableAnalysis.end())
961 // Search Parents through TopLevelManager
963 return TPM->findAnalysisPass(AID);
968 // Print list of passes that are last used by P.
969 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
971 SmallVector<Pass *, 12> LUses;
973 // If this is a on the fly manager then it does not have TPM.
977 TPM->collectLastUses(LUses, P);
979 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
980 E = LUses.end(); I != E; ++I) {
981 llvm::cerr << "--" << std::string(Offset*2, ' ');
982 (*I)->dumpPassStructure(0);
986 void PMDataManager::dumpPassArguments() const {
987 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
988 E = PassVector.end(); I != E; ++I) {
989 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
990 PMD->dumpPassArguments();
992 if (const PassInfo *PI = (*I)->getPassInfo())
993 if (!PI->isAnalysisGroup())
994 cerr << " -" << PI->getPassArgument();
998 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
999 enum PassDebuggingString S2,
1001 if (PassDebugging < Executions)
1003 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
1006 cerr << "Executing Pass '" << P->getPassName();
1008 case MODIFICATION_MSG:
1009 cerr << "Made Modification '" << P->getPassName();
1012 cerr << " Freeing Pass '" << P->getPassName();
1018 case ON_BASICBLOCK_MSG:
1019 cerr << "' on BasicBlock '" << Msg << "'...\n";
1021 case ON_FUNCTION_MSG:
1022 cerr << "' on Function '" << Msg << "'...\n";
1025 cerr << "' on Module '" << Msg << "'...\n";
1028 cerr << "' on Loop " << Msg << "'...\n";
1031 cerr << "' on Call Graph " << Msg << "'...\n";
1038 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1039 if (PassDebugging < Details)
1042 AnalysisUsage analysisUsage;
1043 P->getAnalysisUsage(analysisUsage);
1044 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1047 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1048 if (PassDebugging < Details)
1051 AnalysisUsage analysisUsage;
1052 P->getAnalysisUsage(analysisUsage);
1053 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1056 void PMDataManager::dumpAnalysisUsage(const char *Msg, const Pass *P,
1057 const AnalysisUsage::VectorType &Set) const {
1058 assert(PassDebugging >= Details);
1061 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1062 for (unsigned i = 0; i != Set.size(); ++i) {
1064 cerr << " " << Set[i]->getPassName();
1069 /// Add RequiredPass into list of lower level passes required by pass P.
1070 /// RequiredPass is run on the fly by Pass Manager when P requests it
1071 /// through getAnalysis interface.
1072 /// This should be handled by specific pass manager.
1073 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1075 TPM->dumpArguments();
1079 // Module Level pass may required Function Level analysis info
1080 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1081 // to provide this on demand. In that case, in Pass manager terminology,
1082 // module level pass is requiring lower level analysis info managed by
1083 // lower level pass manager.
1085 // When Pass manager is not able to order required analysis info, Pass manager
1086 // checks whether any lower level manager will be able to provide this
1087 // analysis info on demand or not.
1089 cerr << "Unable to schedule '" << RequiredPass->getPassName();
1090 cerr << "' required by '" << P->getPassName() << "'\n";
1092 assert(0 && "Unable to schedule pass");
1096 PMDataManager::~PMDataManager() {
1097 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1098 E = PassVector.end(); I != E; ++I)
1102 //===----------------------------------------------------------------------===//
1103 // NOTE: Is this the right place to define this method ?
1104 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1105 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1106 return PM.findAnalysisPass(ID, dir);
1109 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1111 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1114 //===----------------------------------------------------------------------===//
1115 // BBPassManager implementation
1117 /// Execute all of the passes scheduled for execution by invoking
1118 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1119 /// the function, and if so, return true.
1120 bool BBPassManager::runOnFunction(Function &F) {
1121 if (F.isDeclaration())
1124 bool Changed = doInitialization(F);
1126 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1127 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1128 BasicBlockPass *BP = getContainedPass(Index);
1130 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
1131 dumpRequiredSet(BP);
1133 initializeAnalysisImpl(BP);
1136 // If the pass crashes, remember this.
1137 PassManagerPrettyStackEntry X(BP, *I);
1139 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1140 Changed |= BP->runOnBasicBlock(*I);
1141 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1145 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1147 dumpPreservedSet(BP);
1149 verifyPreservedAnalysis(BP);
1150 removeNotPreservedAnalysis(BP);
1151 recordAvailableAnalysis(BP);
1152 removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
1155 return Changed |= doFinalization(F);
1158 // Implement doInitialization and doFinalization
1159 bool BBPassManager::doInitialization(Module &M) {
1160 bool Changed = false;
1162 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1163 Changed |= getContainedPass(Index)->doInitialization(M);
1168 bool BBPassManager::doFinalization(Module &M) {
1169 bool Changed = false;
1171 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1172 Changed |= getContainedPass(Index)->doFinalization(M);
1177 bool BBPassManager::doInitialization(Function &F) {
1178 bool Changed = false;
1180 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1181 BasicBlockPass *BP = getContainedPass(Index);
1182 Changed |= BP->doInitialization(F);
1188 bool BBPassManager::doFinalization(Function &F) {
1189 bool Changed = false;
1191 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1192 BasicBlockPass *BP = getContainedPass(Index);
1193 Changed |= BP->doFinalization(F);
1200 //===----------------------------------------------------------------------===//
1201 // FunctionPassManager implementation
1203 /// Create new Function pass manager
1204 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1205 FPM = new FunctionPassManagerImpl(0);
1206 // FPM is the top level manager.
1207 FPM->setTopLevelManager(FPM);
1209 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1210 FPM->setResolver(AR);
1215 FunctionPassManager::~FunctionPassManager() {
1219 /// add - Add a pass to the queue of passes to run. This passes
1220 /// ownership of the Pass to the PassManager. When the
1221 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1222 /// there is no need to delete the pass. (TODO delete passes.)
1223 /// This implies that all passes MUST be allocated with 'new'.
1224 void FunctionPassManager::add(Pass *P) {
1228 /// run - Execute all of the passes scheduled for execution. Keep
1229 /// track of whether any of the passes modifies the function, and if
1230 /// so, return true.
1232 bool FunctionPassManager::run(Function &F) {
1234 if (MP->materializeFunction(&F, &errstr)) {
1235 cerr << "Error reading bitcode file: " << errstr << "\n";
1242 /// doInitialization - Run all of the initializers for the function passes.
1244 bool FunctionPassManager::doInitialization() {
1245 return FPM->doInitialization(*MP->getModule());
1248 /// doFinalization - Run all of the finalizers for the function passes.
1250 bool FunctionPassManager::doFinalization() {
1251 return FPM->doFinalization(*MP->getModule());
1254 //===----------------------------------------------------------------------===//
1255 // FunctionPassManagerImpl implementation
1257 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1258 bool Changed = false;
1260 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1261 Changed |= getContainedManager(Index)->doInitialization(M);
1266 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1267 bool Changed = false;
1269 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1270 Changed |= getContainedManager(Index)->doFinalization(M);
1275 /// cleanup - After running all passes, clean up pass manager cache.
1276 void FPPassManager::cleanup() {
1277 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1278 FunctionPass *FP = getContainedPass(Index);
1279 AnalysisResolver *AR = FP->getResolver();
1280 assert(AR && "Analysis Resolver is not set");
1281 AR->clearAnalysisImpls();
1285 // Execute all the passes managed by this top level manager.
1286 // Return true if any function is modified by a pass.
1287 bool FunctionPassManagerImpl::run(Function &F) {
1288 bool Changed = false;
1289 TimingInfo::createTheTimeInfo();
1294 initializeAllAnalysisInfo();
1295 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1296 Changed |= getContainedManager(Index)->runOnFunction(F);
1298 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1299 getContainedManager(Index)->cleanup();
1304 //===----------------------------------------------------------------------===//
1305 // FPPassManager implementation
1307 char FPPassManager::ID = 0;
1308 /// Print passes managed by this manager
1309 void FPPassManager::dumpPassStructure(unsigned Offset) {
1310 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1311 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1312 FunctionPass *FP = getContainedPass(Index);
1313 FP->dumpPassStructure(Offset + 1);
1314 dumpLastUses(FP, Offset+1);
1319 /// Execute all of the passes scheduled for execution by invoking
1320 /// runOnFunction method. Keep track of whether any of the passes modifies
1321 /// the function, and if so, return true.
1322 bool FPPassManager::runOnFunction(Function &F) {
1323 if (F.isDeclaration())
1326 bool Changed = false;
1328 // Collect inherited analysis from Module level pass manager.
1329 populateInheritedAnalysis(TPM->activeStack);
1331 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1332 FunctionPass *FP = getContainedPass(Index);
1334 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1335 dumpRequiredSet(FP);
1337 initializeAnalysisImpl(FP);
1340 PassManagerPrettyStackEntry X(FP, F);
1342 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1343 Changed |= FP->runOnFunction(F);
1344 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1348 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1349 dumpPreservedSet(FP);
1351 verifyPreservedAnalysis(FP);
1352 removeNotPreservedAnalysis(FP);
1353 recordAvailableAnalysis(FP);
1354 removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1356 // If dominator information is available then verify the info if requested.
1357 verifyDomInfo(*FP, F);
1362 bool FPPassManager::runOnModule(Module &M) {
1363 bool Changed = doInitialization(M);
1365 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1368 return Changed |= doFinalization(M);
1371 bool FPPassManager::doInitialization(Module &M) {
1372 bool Changed = false;
1374 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1375 Changed |= getContainedPass(Index)->doInitialization(M);
1380 bool FPPassManager::doFinalization(Module &M) {
1381 bool Changed = false;
1383 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1384 Changed |= getContainedPass(Index)->doFinalization(M);
1389 //===----------------------------------------------------------------------===//
1390 // MPPassManager implementation
1392 /// Execute all of the passes scheduled for execution by invoking
1393 /// runOnModule method. Keep track of whether any of the passes modifies
1394 /// the module, and if so, return true.
1396 MPPassManager::runOnModule(Module &M) {
1397 bool Changed = false;
1399 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1400 ModulePass *MP = getContainedPass(Index);
1402 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1403 M.getModuleIdentifier().c_str());
1404 dumpRequiredSet(MP);
1406 initializeAnalysisImpl(MP);
1409 PassManagerPrettyStackEntry X(MP, M);
1410 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1411 Changed |= MP->runOnModule(M);
1412 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1416 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1417 M.getModuleIdentifier().c_str());
1418 dumpPreservedSet(MP);
1420 verifyPreservedAnalysis(MP);
1421 removeNotPreservedAnalysis(MP);
1422 recordAvailableAnalysis(MP);
1423 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1428 /// Add RequiredPass into list of lower level passes required by pass P.
1429 /// RequiredPass is run on the fly by Pass Manager when P requests it
1430 /// through getAnalysis interface.
1431 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1432 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1433 "Unable to handle Pass that requires lower level Analysis pass");
1434 assert((P->getPotentialPassManagerType() <
1435 RequiredPass->getPotentialPassManagerType()) &&
1436 "Unable to handle Pass that requires lower level Analysis pass");
1438 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1440 FPP = new FunctionPassManagerImpl(0);
1441 // FPP is the top level manager.
1442 FPP->setTopLevelManager(FPP);
1444 OnTheFlyManagers[P] = FPP;
1446 FPP->add(RequiredPass);
1448 // Register P as the last user of RequiredPass.
1449 SmallVector<Pass *, 12> LU;
1450 LU.push_back(RequiredPass);
1451 FPP->setLastUser(LU, P);
1454 /// Return function pass corresponding to PassInfo PI, that is
1455 /// required by module pass MP. Instantiate analysis pass, by using
1456 /// its runOnFunction() for function F.
1457 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1458 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1459 assert(FPP && "Unable to find on the fly pass");
1462 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1466 //===----------------------------------------------------------------------===//
1467 // PassManagerImpl implementation
1469 /// run - Execute all of the passes scheduled for execution. Keep track of
1470 /// whether any of the passes modifies the module, and if so, return true.
1471 bool PassManagerImpl::run(Module &M) {
1472 bool Changed = false;
1473 TimingInfo::createTheTimeInfo();
1478 initializeAllAnalysisInfo();
1479 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1480 Changed |= getContainedManager(Index)->runOnModule(M);
1484 //===----------------------------------------------------------------------===//
1485 // PassManager implementation
1487 /// Create new pass manager
1488 PassManager::PassManager() {
1489 PM = new PassManagerImpl(0);
1490 // PM is the top level manager
1491 PM->setTopLevelManager(PM);
1494 PassManager::~PassManager() {
1498 /// add - Add a pass to the queue of passes to run. This passes ownership of
1499 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1500 /// will be destroyed as well, so there is no need to delete the pass. This
1501 /// implies that all passes MUST be allocated with 'new'.
1502 void PassManager::add(Pass *P) {
1506 /// run - Execute all of the passes scheduled for execution. Keep track of
1507 /// whether any of the passes modifies the module, and if so, return true.
1508 bool PassManager::run(Module &M) {
1512 //===----------------------------------------------------------------------===//
1513 // TimingInfo Class - This class is used to calculate information about the
1514 // amount of time each pass takes to execute. This only happens with
1515 // -time-passes is enabled on the command line.
1517 bool llvm::TimePassesIsEnabled = false;
1518 static cl::opt<bool,true>
1519 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1520 cl::desc("Time each pass, printing elapsed time for each on exit"));
1522 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1523 // a non null value (if the -time-passes option is enabled) or it leaves it
1524 // null. It may be called multiple times.
1525 void TimingInfo::createTheTimeInfo() {
1526 if (!TimePassesIsEnabled || TheTimeInfo) return;
1528 // Constructed the first time this is called, iff -time-passes is enabled.
1529 // This guarantees that the object will be constructed before static globals,
1530 // thus it will be destroyed before them.
1531 static ManagedStatic<TimingInfo> TTI;
1532 TheTimeInfo = &*TTI;
1535 /// If TimingInfo is enabled then start pass timer.
1536 void StartPassTimer(Pass *P) {
1538 TheTimeInfo->passStarted(P);
1541 /// If TimingInfo is enabled then stop pass timer.
1542 void StopPassTimer(Pass *P) {
1544 TheTimeInfo->passEnded(P);
1547 //===----------------------------------------------------------------------===//
1548 // PMStack implementation
1551 // Pop Pass Manager from the stack and clear its analysis info.
1552 void PMStack::pop() {
1554 PMDataManager *Top = this->top();
1555 Top->initializeAnalysisInfo();
1560 // Push PM on the stack and set its top level manager.
1561 void PMStack::push(PMDataManager *PM) {
1562 assert(PM && "Unable to push. Pass Manager expected");
1564 if (!this->empty()) {
1565 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1567 assert(TPM && "Unable to find top level manager");
1568 TPM->addIndirectPassManager(PM);
1569 PM->setTopLevelManager(TPM);
1575 // Dump content of the pass manager stack.
1576 void PMStack::dump() {
1577 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1578 E = S.end(); I != E; ++I)
1579 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1585 /// Find appropriate Module Pass Manager in the PM Stack and
1586 /// add self into that manager.
1587 void ModulePass::assignPassManager(PMStack &PMS,
1588 PassManagerType PreferredType) {
1589 // Find Module Pass Manager
1590 while(!PMS.empty()) {
1591 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1592 if (TopPMType == PreferredType)
1593 break; // We found desired pass manager
1594 else if (TopPMType > PMT_ModulePassManager)
1595 PMS.pop(); // Pop children pass managers
1599 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1600 PMS.top()->add(this);
1603 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1604 /// in the PM Stack and add self into that manager.
1605 void FunctionPass::assignPassManager(PMStack &PMS,
1606 PassManagerType PreferredType) {
1608 // Find Module Pass Manager
1609 while(!PMS.empty()) {
1610 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1615 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1617 // Create new Function Pass Manager
1619 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1620 PMDataManager *PMD = PMS.top();
1622 // [1] Create new Function Pass Manager
1623 FPP = new FPPassManager(PMD->getDepth() + 1);
1624 FPP->populateInheritedAnalysis(PMS);
1626 // [2] Set up new manager's top level manager
1627 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1628 TPM->addIndirectPassManager(FPP);
1630 // [3] Assign manager to manage this new manager. This may create
1631 // and push new managers into PMS
1632 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1634 // [4] Push new manager into PMS
1638 // Assign FPP as the manager of this pass.
1642 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1643 /// in the PM Stack and add self into that manager.
1644 void BasicBlockPass::assignPassManager(PMStack &PMS,
1645 PassManagerType PreferredType) {
1646 BBPassManager *BBP = NULL;
1648 // Basic Pass Manager is a leaf pass manager. It does not handle
1649 // any other pass manager.
1651 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1653 // If leaf manager is not Basic Block Pass manager then create new
1654 // basic Block Pass manager.
1657 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1658 PMDataManager *PMD = PMS.top();
1660 // [1] Create new Basic Block Manager
1661 BBP = new BBPassManager(PMD->getDepth() + 1);
1663 // [2] Set up new manager's top level manager
1664 // Basic Block Pass Manager does not live by itself
1665 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1666 TPM->addIndirectPassManager(BBP);
1668 // [3] Assign manager to manage this new manager. This may create
1669 // and push new managers into PMS
1670 BBP->assignPassManager(PMS);
1672 // [4] Push new manager into PMS
1676 // Assign BBP as the manager of this pass.
1680 PassManagerBase::~PassManagerBase() {}
1682 /*===-- C Bindings --------------------------------------------------------===*/
1684 LLVMPassManagerRef LLVMCreatePassManager() {
1685 return wrap(new PassManager());
1688 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1689 return wrap(new FunctionPassManager(unwrap(P)));
1692 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1693 return unwrap<PassManager>(PM)->run(*unwrap(M));
1696 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1697 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1700 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1701 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1704 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1705 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1708 void LLVMDisposePassManager(LLVMPassManagerRef PM) {