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/Assembly/Writer.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Timer.h"
19 #include "llvm/Module.h"
20 #include "llvm/ModuleProvider.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.h"
26 #include "llvm-c/Core.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"),
58 } // End of llvm namespace
60 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
61 /// or higher is specified.
62 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
63 return PassDebugging >= Executions;
69 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
71 OS << "Releasing pass '";
73 OS << "Running pass '";
75 OS << P->getPassName() << "'";
78 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
89 else if (isa<BasicBlock>(V))
95 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
102 //===----------------------------------------------------------------------===//
105 /// BBPassManager manages BasicBlockPass. It batches all the
106 /// pass together and sequence them to process one basic block before
107 /// processing next basic block.
108 class BBPassManager : public PMDataManager, 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::errs() << 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 {
170 explicit FunctionPassManagerImpl(int Depth) :
171 Pass(&ID), PMDataManager(Depth),
172 PMTopLevelManager(TLM_Function), wasRun(false) { }
174 /// add - Add a pass to the queue of passes to run. This passes ownership of
175 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
176 /// will be destroyed as well, so there is no need to delete the pass. This
177 /// implies that all passes MUST be allocated with 'new'.
182 // Prepare for running an on the fly pass, freeing memory if needed
183 // from a previous run.
184 void releaseMemoryOnTheFly();
186 /// run - Execute all of the passes scheduled for execution. Keep track of
187 /// whether any of the passes modifies the module, and if so, return true.
188 bool run(Function &F);
190 /// doInitialization - Run all of the initializers for the function passes.
192 bool doInitialization(Module &M);
194 /// doFinalization - Run all of the finalizers for the function passes.
196 bool doFinalization(Module &M);
198 /// Pass Manager itself does not invalidate any analysis info.
199 void getAnalysisUsage(AnalysisUsage &Info) const {
200 Info.setPreservesAll();
203 inline void addTopLevelPass(Pass *P) {
205 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
207 // P is a immutable pass and it will be managed by this
208 // top level manager. Set up analysis resolver to connect them.
209 AnalysisResolver *AR = new AnalysisResolver(*this);
211 initializeAnalysisImpl(P);
212 addImmutablePass(IP);
213 recordAvailableAnalysis(IP);
215 P->assignPassManager(activeStack);
220 FPPassManager *getContainedManager(unsigned N) {
221 assert(N < PassManagers.size() && "Pass number out of range!");
222 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
227 char FunctionPassManagerImpl::ID = 0;
228 //===----------------------------------------------------------------------===//
231 /// MPPassManager manages ModulePasses and function pass managers.
232 /// It batches all Module passes and function pass managers together and
233 /// sequences them to process one module.
234 class MPPassManager : public Pass, public PMDataManager {
237 explicit MPPassManager(int Depth) :
238 Pass(&ID), PMDataManager(Depth) { }
240 // Delete on the fly managers.
241 virtual ~MPPassManager() {
242 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
243 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
245 FunctionPassManagerImpl *FPP = I->second;
250 /// run - Execute all of the passes scheduled for execution. Keep track of
251 /// whether any of the passes modifies the module, and if so, return true.
252 bool runOnModule(Module &M);
254 /// Pass Manager itself does not invalidate any analysis info.
255 void getAnalysisUsage(AnalysisUsage &Info) const {
256 Info.setPreservesAll();
259 /// Add RequiredPass into list of lower level passes required by pass P.
260 /// RequiredPass is run on the fly by Pass Manager when P requests it
261 /// through getAnalysis interface.
262 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
264 /// Return function pass corresponding to PassInfo PI, that is
265 /// required by module pass MP. Instantiate analysis pass, by using
266 /// its runOnFunction() for function F.
267 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
269 virtual const char *getPassName() const {
270 return "Module Pass Manager";
273 // Print passes managed by this manager
274 void dumpPassStructure(unsigned Offset) {
275 llvm::errs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
276 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
277 ModulePass *MP = getContainedPass(Index);
278 MP->dumpPassStructure(Offset + 1);
279 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
280 OnTheFlyManagers.find(MP);
281 if (I != OnTheFlyManagers.end())
282 I->second->dumpPassStructure(Offset + 2);
283 dumpLastUses(MP, Offset+1);
287 ModulePass *getContainedPass(unsigned N) {
288 assert(N < PassVector.size() && "Pass number out of range!");
289 return static_cast<ModulePass *>(PassVector[N]);
292 virtual PassManagerType getPassManagerType() const {
293 return PMT_ModulePassManager;
297 /// Collection of on the fly FPPassManagers. These managers manage
298 /// function passes that are required by module passes.
299 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
302 char MPPassManager::ID = 0;
303 //===----------------------------------------------------------------------===//
307 /// PassManagerImpl manages MPPassManagers
308 class PassManagerImpl : public Pass,
309 public PMDataManager,
310 public PMTopLevelManager {
314 explicit PassManagerImpl(int Depth) :
315 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
317 /// add - Add a pass to the queue of passes to run. This passes ownership of
318 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
319 /// will be destroyed as well, so there is no need to delete the pass. This
320 /// implies that all passes MUST be allocated with 'new'.
325 /// run - Execute all of the passes scheduled for execution. Keep track of
326 /// whether any of the passes modifies the module, and if so, return true.
329 /// Pass Manager itself does not invalidate any analysis info.
330 void getAnalysisUsage(AnalysisUsage &Info) const {
331 Info.setPreservesAll();
334 inline void addTopLevelPass(Pass *P) {
335 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
337 // P is a immutable pass and it will be managed by this
338 // top level manager. Set up analysis resolver to connect them.
339 AnalysisResolver *AR = new AnalysisResolver(*this);
341 initializeAnalysisImpl(P);
342 addImmutablePass(IP);
343 recordAvailableAnalysis(IP);
345 P->assignPassManager(activeStack);
349 MPPassManager *getContainedManager(unsigned N) {
350 assert(N < PassManagers.size() && "Pass number out of range!");
351 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
356 char PassManagerImpl::ID = 0;
357 } // End of llvm namespace
361 //===----------------------------------------------------------------------===//
362 /// TimingInfo Class - This class is used to calculate information about the
363 /// amount of time each pass takes to execute. This only happens when
364 /// -time-passes is enabled on the command line.
367 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
370 std::map<Pass*, Timer> TimingData;
374 // Use 'create' member to get this.
375 TimingInfo() : TG("... Pass execution timing report ...") {}
377 // TimingDtor - Print out information about timing information
379 // Delete all of the timers...
381 // TimerGroup is deleted next, printing the report.
384 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
385 // to a non null value (if the -time-passes option is enabled) or it leaves it
386 // null. It may be called multiple times.
387 static void createTheTimeInfo();
389 /// passStarted - This method creates a timer for the given pass if it doesn't
390 /// already have one, and starts the timer.
391 Timer *passStarted(Pass *P) {
392 if (dynamic_cast<PMDataManager *>(P))
395 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
396 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
397 if (I == TimingData.end())
398 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
399 Timer *T = &I->second;
405 } // End of anon namespace
407 static TimingInfo *TheTimeInfo;
409 //===----------------------------------------------------------------------===//
410 // PMTopLevelManager implementation
412 /// Initialize top level manager. Create first pass manager.
413 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
415 MPPassManager *MPP = new MPPassManager(1);
416 MPP->setTopLevelManager(this);
418 activeStack.push(MPP);
419 } else if (t == TLM_Function) {
420 FPPassManager *FPP = new FPPassManager(1);
421 FPP->setTopLevelManager(this);
423 activeStack.push(FPP);
427 /// Set pass P as the last user of the given analysis passes.
428 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
430 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
431 E = AnalysisPasses.end(); I != E; ++I) {
438 // If AP is the last user of other passes then make P last user of
440 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
441 LUE = LastUser.end(); LUI != LUE; ++LUI) {
442 if (LUI->second == AP)
443 // DenseMap iterator is not invalidated here because
444 // this is just updating exisitng entry.
445 LastUser[LUI->first] = P;
450 /// Collect passes whose last user is P
451 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
453 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
454 InversedLastUser.find(P);
455 if (DMI == InversedLastUser.end())
458 SmallPtrSet<Pass *, 8> &LU = DMI->second;
459 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
460 E = LU.end(); I != E; ++I) {
461 LastUses.push_back(*I);
466 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
467 AnalysisUsage *AnUsage = NULL;
468 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
469 if (DMI != AnUsageMap.end())
470 AnUsage = DMI->second;
472 AnUsage = new AnalysisUsage();
473 P->getAnalysisUsage(*AnUsage);
474 AnUsageMap[P] = AnUsage;
479 /// Schedule pass P for execution. Make sure that passes required by
480 /// P are run before P is run. Update analysis info maintained by
481 /// the manager. Remove dead passes. This is a recursive function.
482 void PMTopLevelManager::schedulePass(Pass *P) {
484 // TODO : Allocate function manager for this pass, other wise required set
485 // may be inserted into previous function manager
487 // Give pass a chance to prepare the stage.
488 P->preparePassManager(activeStack);
490 // If P is an analysis pass and it is available then do not
491 // generate the analysis again. Stale analysis info should not be
492 // available at this point.
493 if (P->getPassInfo() &&
494 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
499 AnalysisUsage *AnUsage = findAnalysisUsage(P);
501 bool checkAnalysis = true;
502 while (checkAnalysis) {
503 checkAnalysis = false;
505 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
506 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
507 E = RequiredSet.end(); I != E; ++I) {
509 Pass *AnalysisPass = findAnalysisPass(*I);
511 AnalysisPass = (*I)->createPass();
512 if (P->getPotentialPassManagerType () ==
513 AnalysisPass->getPotentialPassManagerType())
514 // Schedule analysis pass that is managed by the same pass manager.
515 schedulePass(AnalysisPass);
516 else if (P->getPotentialPassManagerType () >
517 AnalysisPass->getPotentialPassManagerType()) {
518 // Schedule analysis pass that is managed by a new manager.
519 schedulePass(AnalysisPass);
520 // Recheck analysis passes to ensure that required analysises that
521 // are already checked are still available.
522 checkAnalysis = true;
525 // Do not schedule this analysis. Lower level analsyis
526 // passes are run on the fly.
532 // Now all required passes are available.
536 /// Find the pass that implements Analysis AID. Search immutable
537 /// passes and all pass managers. If desired pass is not found
538 /// then return NULL.
539 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
542 // Check pass managers
543 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
544 E = PassManagers.end(); P == NULL && I != E; ++I) {
545 PMDataManager *PMD = *I;
546 P = PMD->findAnalysisPass(AID, false);
549 // Check other pass managers
550 for (SmallVector<PMDataManager *, 8>::iterator
551 I = IndirectPassManagers.begin(),
552 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
553 P = (*I)->findAnalysisPass(AID, false);
555 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
556 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
557 const PassInfo *PI = (*I)->getPassInfo();
561 // If Pass not found then check the interfaces implemented by Immutable Pass
563 const std::vector<const PassInfo*> &ImmPI =
564 PI->getInterfacesImplemented();
565 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
573 // Print passes managed by this top level manager.
574 void PMTopLevelManager::dumpPasses() const {
576 if (PassDebugging < Structure)
579 // Print out the immutable passes
580 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
581 ImmutablePasses[i]->dumpPassStructure(0);
584 // Every class that derives from PMDataManager also derives from Pass
585 // (sometimes indirectly), but there's no inheritance relationship
586 // between PMDataManager and Pass, so we have to dynamic_cast to get
587 // from a PMDataManager* to a Pass*.
588 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
589 E = PassManagers.end(); I != E; ++I)
590 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
593 void PMTopLevelManager::dumpArguments() const {
595 if (PassDebugging < Arguments)
598 errs() << "Pass Arguments: ";
599 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
600 E = PassManagers.end(); I != E; ++I)
601 (*I)->dumpPassArguments();
605 void PMTopLevelManager::initializeAllAnalysisInfo() {
606 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
607 E = PassManagers.end(); I != E; ++I)
608 (*I)->initializeAnalysisInfo();
610 // Initailize other pass managers
611 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
612 E = IndirectPassManagers.end(); I != E; ++I)
613 (*I)->initializeAnalysisInfo();
615 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
616 DME = LastUser.end(); DMI != DME; ++DMI) {
617 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
618 InversedLastUser.find(DMI->second);
619 if (InvDMI != InversedLastUser.end()) {
620 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
621 L.insert(DMI->first);
623 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
624 InversedLastUser[DMI->second] = L;
630 PMTopLevelManager::~PMTopLevelManager() {
631 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
632 E = PassManagers.end(); I != E; ++I)
635 for (SmallVector<ImmutablePass *, 8>::iterator
636 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
639 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
640 DME = AnUsageMap.end(); DMI != DME; ++DMI)
644 //===----------------------------------------------------------------------===//
645 // PMDataManager implementation
647 /// Augement AvailableAnalysis by adding analysis made available by pass P.
648 void PMDataManager::recordAvailableAnalysis(Pass *P) {
649 const PassInfo *PI = P->getPassInfo();
652 AvailableAnalysis[PI] = P;
654 //This pass is the current implementation of all of the interfaces it
655 //implements as well.
656 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
657 for (unsigned i = 0, e = II.size(); i != e; ++i)
658 AvailableAnalysis[II[i]] = P;
661 // Return true if P preserves high level analysis used by other
662 // passes managed by this manager
663 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
664 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
665 if (AnUsage->getPreservesAll())
668 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
669 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
670 E = HigherLevelAnalysis.end(); I != E; ++I) {
672 if (!dynamic_cast<ImmutablePass*>(P1) &&
673 std::find(PreservedSet.begin(), PreservedSet.end(),
674 P1->getPassInfo()) ==
682 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
683 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
684 // Don't do this unless assertions are enabled.
688 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
689 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
691 // Verify preserved analysis
692 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
693 E = PreservedSet.end(); I != E; ++I) {
695 if (Pass *AP = findAnalysisPass(AID, true)) {
698 if (TheTimeInfo) T = TheTimeInfo->passStarted(AP);
699 AP->verifyAnalysis();
700 if (T) T->stopTimer();
705 /// Remove Analysis not preserved by Pass P
706 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
707 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
708 if (AnUsage->getPreservesAll())
711 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
712 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
713 E = AvailableAnalysis.end(); I != E; ) {
714 std::map<AnalysisID, Pass*>::iterator Info = I++;
715 if (!dynamic_cast<ImmutablePass*>(Info->second)
716 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
717 PreservedSet.end()) {
718 // Remove this analysis
719 if (PassDebugging >= Details) {
720 Pass *S = Info->second;
721 errs() << " -- '" << P->getPassName() << "' is not preserving '";
722 errs() << S->getPassName() << "'\n";
724 AvailableAnalysis.erase(Info);
728 // Check inherited analysis also. If P is not preserving analysis
729 // provided by parent manager then remove it here.
730 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
732 if (!InheritedAnalysis[Index])
735 for (std::map<AnalysisID, Pass*>::iterator
736 I = InheritedAnalysis[Index]->begin(),
737 E = InheritedAnalysis[Index]->end(); I != E; ) {
738 std::map<AnalysisID, Pass *>::iterator Info = I++;
739 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
740 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
741 PreservedSet.end()) {
742 // Remove this analysis
743 if (PassDebugging >= Details) {
744 Pass *S = Info->second;
745 errs() << " -- '" << P->getPassName() << "' is not preserving '";
746 errs() << S->getPassName() << "'\n";
748 InheritedAnalysis[Index]->erase(Info);
754 /// Remove analysis passes that are not used any longer
755 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
756 enum PassDebuggingString DBG_STR) {
758 SmallVector<Pass *, 12> DeadPasses;
760 // If this is a on the fly manager then it does not have TPM.
764 TPM->collectLastUses(DeadPasses, P);
766 if (PassDebugging >= Details && !DeadPasses.empty()) {
767 errs() << " -*- '" << P->getPassName();
768 errs() << "' is the last user of following pass instances.";
769 errs() << " Free these instances\n";
772 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
773 E = DeadPasses.end(); I != E; ++I)
774 freePass(*I, Msg, DBG_STR);
777 void PMDataManager::freePass(Pass *P, StringRef Msg,
778 enum PassDebuggingString DBG_STR) {
779 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
782 // If the pass crashes releasing memory, remember this.
783 PassManagerPrettyStackEntry X(P);
785 Timer *T = StartPassTimer(P);
790 if (const PassInfo *PI = P->getPassInfo()) {
791 // Remove the pass itself (if it is not already removed).
792 AvailableAnalysis.erase(PI);
794 // Remove all interfaces this pass implements, for which it is also
795 // listed as the available implementation.
796 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
797 for (unsigned i = 0, e = II.size(); i != e; ++i) {
798 std::map<AnalysisID, Pass*>::iterator Pos =
799 AvailableAnalysis.find(II[i]);
800 if (Pos != AvailableAnalysis.end() && Pos->second == P)
801 AvailableAnalysis.erase(Pos);
806 /// Add pass P into the PassVector. Update
807 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
808 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
809 // This manager is going to manage pass P. Set up analysis resolver
811 AnalysisResolver *AR = new AnalysisResolver(*this);
814 // If a FunctionPass F is the last user of ModulePass info M
815 // then the F's manager, not F, records itself as a last user of M.
816 SmallVector<Pass *, 12> TransferLastUses;
818 if (!ProcessAnalysis) {
820 PassVector.push_back(P);
824 // At the moment, this pass is the last user of all required passes.
825 SmallVector<Pass *, 12> LastUses;
826 SmallVector<Pass *, 8> RequiredPasses;
827 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
829 unsigned PDepth = this->getDepth();
831 collectRequiredAnalysis(RequiredPasses,
832 ReqAnalysisNotAvailable, P);
833 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
834 E = RequiredPasses.end(); I != E; ++I) {
835 Pass *PRequired = *I;
838 assert(PRequired->getResolver() && "Analysis Resolver is not set");
839 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
840 RDepth = DM.getDepth();
842 if (PDepth == RDepth)
843 LastUses.push_back(PRequired);
844 else if (PDepth > RDepth) {
845 // Let the parent claim responsibility of last use
846 TransferLastUses.push_back(PRequired);
847 // Keep track of higher level analysis used by this manager.
848 HigherLevelAnalysis.push_back(PRequired);
850 llvm_unreachable("Unable to accomodate Required Pass");
853 // Set P as P's last user until someone starts using P.
854 // However, if P is a Pass Manager then it does not need
855 // to record its last user.
856 if (!dynamic_cast<PMDataManager *>(P))
857 LastUses.push_back(P);
858 TPM->setLastUser(LastUses, P);
860 if (!TransferLastUses.empty()) {
861 Pass *My_PM = dynamic_cast<Pass *>(this);
862 TPM->setLastUser(TransferLastUses, My_PM);
863 TransferLastUses.clear();
866 // Now, take care of required analysises that are not available.
867 for (SmallVector<AnalysisID, 8>::iterator
868 I = ReqAnalysisNotAvailable.begin(),
869 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
870 Pass *AnalysisPass = (*I)->createPass();
871 this->addLowerLevelRequiredPass(P, AnalysisPass);
874 // Take a note of analysis required and made available by this pass.
875 // Remove the analysis not preserved by this pass
876 removeNotPreservedAnalysis(P);
877 recordAvailableAnalysis(P);
880 PassVector.push_back(P);
884 /// Populate RP with analysis pass that are required by
885 /// pass P and are available. Populate RP_NotAvail with analysis
886 /// pass that are required by pass P but are not available.
887 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
888 SmallVector<AnalysisID, 8> &RP_NotAvail,
890 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
891 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
892 for (AnalysisUsage::VectorType::const_iterator
893 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
894 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
895 RP.push_back(AnalysisPass);
897 RP_NotAvail.push_back(*I);
900 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
901 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
902 E = IDs.end(); I != E; ++I) {
903 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
904 RP.push_back(AnalysisPass);
906 RP_NotAvail.push_back(*I);
910 // All Required analyses should be available to the pass as it runs! Here
911 // we fill in the AnalysisImpls member of the pass so that it can
912 // successfully use the getAnalysis() method to retrieve the
913 // implementations it needs.
915 void PMDataManager::initializeAnalysisImpl(Pass *P) {
916 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
918 for (AnalysisUsage::VectorType::const_iterator
919 I = AnUsage->getRequiredSet().begin(),
920 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
921 Pass *Impl = findAnalysisPass(*I, true);
923 // This may be analysis pass that is initialized on the fly.
924 // If that is not the case then it will raise an assert when it is used.
926 AnalysisResolver *AR = P->getResolver();
927 assert(AR && "Analysis Resolver is not set");
928 AR->addAnalysisImplsPair(*I, Impl);
932 /// Find the pass that implements Analysis AID. If desired pass is not found
933 /// then return NULL.
934 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
936 // Check if AvailableAnalysis map has one entry.
937 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
939 if (I != AvailableAnalysis.end())
942 // Search Parents through TopLevelManager
944 return TPM->findAnalysisPass(AID);
949 // Print list of passes that are last used by P.
950 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
952 SmallVector<Pass *, 12> LUses;
954 // If this is a on the fly manager then it does not have TPM.
958 TPM->collectLastUses(LUses, P);
960 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
961 E = LUses.end(); I != E; ++I) {
962 llvm::errs() << "--" << std::string(Offset*2, ' ');
963 (*I)->dumpPassStructure(0);
967 void PMDataManager::dumpPassArguments() const {
968 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
969 E = PassVector.end(); I != E; ++I) {
970 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
971 PMD->dumpPassArguments();
973 if (const PassInfo *PI = (*I)->getPassInfo())
974 if (!PI->isAnalysisGroup())
975 errs() << " -" << PI->getPassArgument();
979 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
980 enum PassDebuggingString S2,
982 if (PassDebugging < Executions)
984 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
987 errs() << "Executing Pass '" << P->getPassName();
989 case MODIFICATION_MSG:
990 errs() << "Made Modification '" << P->getPassName();
993 errs() << " Freeing Pass '" << P->getPassName();
999 case ON_BASICBLOCK_MSG:
1000 errs() << "' on BasicBlock '" << Msg << "'...\n";
1002 case ON_FUNCTION_MSG:
1003 errs() << "' on Function '" << Msg << "'...\n";
1006 errs() << "' on Module '" << Msg << "'...\n";
1009 errs() << "' on Loop '" << Msg << "'...\n";
1012 errs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1019 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1020 if (PassDebugging < Details)
1023 AnalysisUsage analysisUsage;
1024 P->getAnalysisUsage(analysisUsage);
1025 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1028 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1029 if (PassDebugging < Details)
1032 AnalysisUsage analysisUsage;
1033 P->getAnalysisUsage(analysisUsage);
1034 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1037 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1038 const AnalysisUsage::VectorType &Set) const {
1039 assert(PassDebugging >= Details);
1042 errs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1043 for (unsigned i = 0; i != Set.size(); ++i) {
1044 if (i) errs() << ',';
1045 errs() << ' ' << Set[i]->getPassName();
1050 /// Add RequiredPass into list of lower level passes required by pass P.
1051 /// RequiredPass is run on the fly by Pass Manager when P requests it
1052 /// through getAnalysis interface.
1053 /// This should be handled by specific pass manager.
1054 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1056 TPM->dumpArguments();
1060 // Module Level pass may required Function Level analysis info
1061 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1062 // to provide this on demand. In that case, in Pass manager terminology,
1063 // module level pass is requiring lower level analysis info managed by
1064 // lower level pass manager.
1066 // When Pass manager is not able to order required analysis info, Pass manager
1067 // checks whether any lower level manager will be able to provide this
1068 // analysis info on demand or not.
1070 errs() << "Unable to schedule '" << RequiredPass->getPassName();
1071 errs() << "' required by '" << P->getPassName() << "'\n";
1073 llvm_unreachable("Unable to schedule pass");
1077 PMDataManager::~PMDataManager() {
1078 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1079 E = PassVector.end(); I != E; ++I)
1083 //===----------------------------------------------------------------------===//
1084 // NOTE: Is this the right place to define this method ?
1085 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1086 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1087 return PM.findAnalysisPass(ID, dir);
1090 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1092 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1095 //===----------------------------------------------------------------------===//
1096 // BBPassManager implementation
1098 /// Execute all of the passes scheduled for execution by invoking
1099 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1100 /// the function, and if so, return true.
1101 bool BBPassManager::runOnFunction(Function &F) {
1102 if (F.isDeclaration())
1105 bool Changed = doInitialization(F);
1107 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1108 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1109 BasicBlockPass *BP = getContainedPass(Index);
1111 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1112 dumpRequiredSet(BP);
1114 initializeAnalysisImpl(BP);
1117 // If the pass crashes, remember this.
1118 PassManagerPrettyStackEntry X(BP, *I);
1120 Timer *T = StartPassTimer(BP);
1121 Changed |= BP->runOnBasicBlock(*I);
1122 StopPassTimer(BP, T);
1126 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1128 dumpPreservedSet(BP);
1130 verifyPreservedAnalysis(BP);
1131 removeNotPreservedAnalysis(BP);
1132 recordAvailableAnalysis(BP);
1133 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1136 return doFinalization(F) || Changed;
1139 // Implement doInitialization and doFinalization
1140 bool BBPassManager::doInitialization(Module &M) {
1141 bool Changed = false;
1143 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1144 Changed |= getContainedPass(Index)->doInitialization(M);
1149 bool BBPassManager::doFinalization(Module &M) {
1150 bool Changed = false;
1152 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1153 Changed |= getContainedPass(Index)->doFinalization(M);
1158 bool BBPassManager::doInitialization(Function &F) {
1159 bool Changed = false;
1161 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1162 BasicBlockPass *BP = getContainedPass(Index);
1163 Changed |= BP->doInitialization(F);
1169 bool BBPassManager::doFinalization(Function &F) {
1170 bool Changed = false;
1172 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1173 BasicBlockPass *BP = getContainedPass(Index);
1174 Changed |= BP->doFinalization(F);
1181 //===----------------------------------------------------------------------===//
1182 // FunctionPassManager implementation
1184 /// Create new Function pass manager
1185 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1186 FPM = new FunctionPassManagerImpl(0);
1187 // FPM is the top level manager.
1188 FPM->setTopLevelManager(FPM);
1190 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1191 FPM->setResolver(AR);
1196 FunctionPassManager::~FunctionPassManager() {
1200 /// add - Add a pass to the queue of passes to run. This passes
1201 /// ownership of the Pass to the PassManager. When the
1202 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1203 /// there is no need to delete the pass. (TODO delete passes.)
1204 /// This implies that all passes MUST be allocated with 'new'.
1205 void FunctionPassManager::add(Pass *P) {
1209 /// run - Execute all of the passes scheduled for execution. Keep
1210 /// track of whether any of the passes modifies the function, and if
1211 /// so, return true.
1213 bool FunctionPassManager::run(Function &F) {
1215 if (MP->materializeFunction(&F, &errstr)) {
1216 llvm_report_error("Error reading bitcode file: " + errstr);
1222 /// doInitialization - Run all of the initializers for the function passes.
1224 bool FunctionPassManager::doInitialization() {
1225 return FPM->doInitialization(*MP->getModule());
1228 /// doFinalization - Run all of the finalizers for the function passes.
1230 bool FunctionPassManager::doFinalization() {
1231 return FPM->doFinalization(*MP->getModule());
1234 //===----------------------------------------------------------------------===//
1235 // FunctionPassManagerImpl implementation
1237 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1238 bool Changed = false;
1243 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1244 Changed |= getContainedManager(Index)->doInitialization(M);
1249 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1250 bool Changed = false;
1252 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1253 Changed |= getContainedManager(Index)->doFinalization(M);
1258 /// cleanup - After running all passes, clean up pass manager cache.
1259 void FPPassManager::cleanup() {
1260 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1261 FunctionPass *FP = getContainedPass(Index);
1262 AnalysisResolver *AR = FP->getResolver();
1263 assert(AR && "Analysis Resolver is not set");
1264 AR->clearAnalysisImpls();
1268 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1271 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1272 FPPassManager *FPPM = getContainedManager(Index);
1273 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1274 FPPM->getContainedPass(Index)->releaseMemory();
1280 // Execute all the passes managed by this top level manager.
1281 // Return true if any function is modified by a pass.
1282 bool FunctionPassManagerImpl::run(Function &F) {
1283 bool Changed = false;
1284 TimingInfo::createTheTimeInfo();
1286 initializeAllAnalysisInfo();
1287 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1288 Changed |= getContainedManager(Index)->runOnFunction(F);
1290 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1291 getContainedManager(Index)->cleanup();
1297 //===----------------------------------------------------------------------===//
1298 // FPPassManager implementation
1300 char FPPassManager::ID = 0;
1301 /// Print passes managed by this manager
1302 void FPPassManager::dumpPassStructure(unsigned Offset) {
1303 llvm::errs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1304 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1305 FunctionPass *FP = getContainedPass(Index);
1306 FP->dumpPassStructure(Offset + 1);
1307 dumpLastUses(FP, Offset+1);
1312 /// Execute all of the passes scheduled for execution by invoking
1313 /// runOnFunction method. Keep track of whether any of the passes modifies
1314 /// the function, and if so, return true.
1315 bool FPPassManager::runOnFunction(Function &F) {
1316 if (F.isDeclaration())
1319 bool Changed = false;
1321 // Collect inherited analysis from Module level pass manager.
1322 populateInheritedAnalysis(TPM->activeStack);
1324 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1325 FunctionPass *FP = getContainedPass(Index);
1327 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1328 dumpRequiredSet(FP);
1330 initializeAnalysisImpl(FP);
1333 PassManagerPrettyStackEntry X(FP, F);
1335 Timer *T = StartPassTimer(FP);
1336 Changed |= FP->runOnFunction(F);
1337 StopPassTimer(FP, T);
1341 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1342 dumpPreservedSet(FP);
1344 verifyPreservedAnalysis(FP);
1345 removeNotPreservedAnalysis(FP);
1346 recordAvailableAnalysis(FP);
1347 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1352 bool FPPassManager::runOnModule(Module &M) {
1353 bool Changed = doInitialization(M);
1355 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1358 return doFinalization(M) || Changed;
1361 bool FPPassManager::doInitialization(Module &M) {
1362 bool Changed = false;
1364 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1365 Changed |= getContainedPass(Index)->doInitialization(M);
1370 bool FPPassManager::doFinalization(Module &M) {
1371 bool Changed = false;
1373 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1374 Changed |= getContainedPass(Index)->doFinalization(M);
1379 //===----------------------------------------------------------------------===//
1380 // MPPassManager implementation
1382 /// Execute all of the passes scheduled for execution by invoking
1383 /// runOnModule method. Keep track of whether any of the passes modifies
1384 /// the module, and if so, return true.
1386 MPPassManager::runOnModule(Module &M) {
1387 bool Changed = false;
1389 // Initialize on-the-fly passes
1390 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1391 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1393 FunctionPassManagerImpl *FPP = I->second;
1394 Changed |= FPP->doInitialization(M);
1397 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1398 ModulePass *MP = getContainedPass(Index);
1400 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1401 dumpRequiredSet(MP);
1403 initializeAnalysisImpl(MP);
1406 PassManagerPrettyStackEntry X(MP, M);
1407 Timer *T = StartPassTimer(MP);
1408 Changed |= MP->runOnModule(M);
1409 StopPassTimer(MP, T);
1413 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1414 M.getModuleIdentifier());
1415 dumpPreservedSet(MP);
1417 verifyPreservedAnalysis(MP);
1418 removeNotPreservedAnalysis(MP);
1419 recordAvailableAnalysis(MP);
1420 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1423 // Finalize on-the-fly passes
1424 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1425 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1427 FunctionPassManagerImpl *FPP = I->second;
1428 // We don't know when is the last time an on-the-fly pass is run,
1429 // so we need to releaseMemory / finalize here
1430 FPP->releaseMemoryOnTheFly();
1431 Changed |= FPP->doFinalization(M);
1436 /// Add RequiredPass into list of lower level passes required by pass P.
1437 /// RequiredPass is run on the fly by Pass Manager when P requests it
1438 /// through getAnalysis interface.
1439 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1440 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1441 "Unable to handle Pass that requires lower level Analysis pass");
1442 assert((P->getPotentialPassManagerType() <
1443 RequiredPass->getPotentialPassManagerType()) &&
1444 "Unable to handle Pass that requires lower level Analysis pass");
1446 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1448 FPP = new FunctionPassManagerImpl(0);
1449 // FPP is the top level manager.
1450 FPP->setTopLevelManager(FPP);
1452 OnTheFlyManagers[P] = FPP;
1454 FPP->add(RequiredPass);
1456 // Register P as the last user of RequiredPass.
1457 SmallVector<Pass *, 12> LU;
1458 LU.push_back(RequiredPass);
1459 FPP->setLastUser(LU, P);
1462 /// Return function pass corresponding to PassInfo PI, that is
1463 /// required by module pass MP. Instantiate analysis pass, by using
1464 /// its runOnFunction() for function F.
1465 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1466 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1467 assert(FPP && "Unable to find on the fly pass");
1469 FPP->releaseMemoryOnTheFly();
1471 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1475 //===----------------------------------------------------------------------===//
1476 // PassManagerImpl implementation
1478 /// run - Execute all of the passes scheduled for execution. Keep track of
1479 /// whether any of the passes modifies the module, and if so, return true.
1480 bool PassManagerImpl::run(Module &M) {
1481 bool Changed = false;
1482 TimingInfo::createTheTimeInfo();
1487 initializeAllAnalysisInfo();
1488 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1489 Changed |= getContainedManager(Index)->runOnModule(M);
1493 //===----------------------------------------------------------------------===//
1494 // PassManager implementation
1496 /// Create new pass manager
1497 PassManager::PassManager() {
1498 PM = new PassManagerImpl(0);
1499 // PM is the top level manager
1500 PM->setTopLevelManager(PM);
1503 PassManager::~PassManager() {
1507 /// add - Add a pass to the queue of passes to run. This passes ownership of
1508 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1509 /// will be destroyed as well, so there is no need to delete the pass. This
1510 /// implies that all passes MUST be allocated with 'new'.
1511 void PassManager::add(Pass *P) {
1515 /// run - Execute all of the passes scheduled for execution. Keep track of
1516 /// whether any of the passes modifies the module, and if so, return true.
1517 bool PassManager::run(Module &M) {
1521 //===----------------------------------------------------------------------===//
1522 // TimingInfo Class - This class is used to calculate information about the
1523 // amount of time each pass takes to execute. This only happens with
1524 // -time-passes is enabled on the command line.
1526 bool llvm::TimePassesIsEnabled = false;
1527 static cl::opt<bool,true>
1528 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1529 cl::desc("Time each pass, printing elapsed time for each on exit"));
1531 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1532 // a non null value (if the -time-passes option is enabled) or it leaves it
1533 // null. It may be called multiple times.
1534 void TimingInfo::createTheTimeInfo() {
1535 if (!TimePassesIsEnabled || TheTimeInfo) return;
1537 // Constructed the first time this is called, iff -time-passes is enabled.
1538 // This guarantees that the object will be constructed before static globals,
1539 // thus it will be destroyed before them.
1540 static ManagedStatic<TimingInfo> TTI;
1541 TheTimeInfo = &*TTI;
1544 /// If TimingInfo is enabled then start pass timer.
1545 Timer *llvm::StartPassTimer(Pass *P) {
1547 return TheTimeInfo->passStarted(P);
1551 /// If TimingInfo is enabled then stop pass timer.
1552 void llvm::StopPassTimer(Pass *P, Timer *T) {
1553 if (T) T->stopTimer();
1556 //===----------------------------------------------------------------------===//
1557 // PMStack implementation
1560 // Pop Pass Manager from the stack and clear its analysis info.
1561 void PMStack::pop() {
1563 PMDataManager *Top = this->top();
1564 Top->initializeAnalysisInfo();
1569 // Push PM on the stack and set its top level manager.
1570 void PMStack::push(PMDataManager *PM) {
1571 assert(PM && "Unable to push. Pass Manager expected");
1573 if (!this->empty()) {
1574 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1576 assert(TPM && "Unable to find top level manager");
1577 TPM->addIndirectPassManager(PM);
1578 PM->setTopLevelManager(TPM);
1584 // Dump content of the pass manager stack.
1585 void PMStack::dump() {
1586 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1587 E = S.end(); I != E; ++I)
1588 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1594 /// Find appropriate Module Pass Manager in the PM Stack and
1595 /// add self into that manager.
1596 void ModulePass::assignPassManager(PMStack &PMS,
1597 PassManagerType PreferredType) {
1598 // Find Module Pass Manager
1599 while(!PMS.empty()) {
1600 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1601 if (TopPMType == PreferredType)
1602 break; // We found desired pass manager
1603 else if (TopPMType > PMT_ModulePassManager)
1604 PMS.pop(); // Pop children pass managers
1608 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1609 PMS.top()->add(this);
1612 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1613 /// in the PM Stack and add self into that manager.
1614 void FunctionPass::assignPassManager(PMStack &PMS,
1615 PassManagerType PreferredType) {
1617 // Find Module Pass Manager
1618 while(!PMS.empty()) {
1619 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1624 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1626 // Create new Function Pass Manager
1628 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1629 PMDataManager *PMD = PMS.top();
1631 // [1] Create new Function Pass Manager
1632 FPP = new FPPassManager(PMD->getDepth() + 1);
1633 FPP->populateInheritedAnalysis(PMS);
1635 // [2] Set up new manager's top level manager
1636 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1637 TPM->addIndirectPassManager(FPP);
1639 // [3] Assign manager to manage this new manager. This may create
1640 // and push new managers into PMS
1641 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1643 // [4] Push new manager into PMS
1647 // Assign FPP as the manager of this pass.
1651 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1652 /// in the PM Stack and add self into that manager.
1653 void BasicBlockPass::assignPassManager(PMStack &PMS,
1654 PassManagerType PreferredType) {
1655 BBPassManager *BBP = NULL;
1657 // Basic Pass Manager is a leaf pass manager. It does not handle
1658 // any other pass manager.
1660 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1662 // If leaf manager is not Basic Block Pass manager then create new
1663 // basic Block Pass manager.
1666 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1667 PMDataManager *PMD = PMS.top();
1669 // [1] Create new Basic Block Manager
1670 BBP = new BBPassManager(PMD->getDepth() + 1);
1672 // [2] Set up new manager's top level manager
1673 // Basic Block Pass Manager does not live by itself
1674 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1675 TPM->addIndirectPassManager(BBP);
1677 // [3] Assign manager to manage this new manager. This may create
1678 // and push new managers into PMS
1679 BBP->assignPassManager(PMS);
1681 // [4] Push new manager into PMS
1685 // Assign BBP as the manager of this pass.
1689 PassManagerBase::~PassManagerBase() {}
1691 /*===-- C Bindings --------------------------------------------------------===*/
1693 LLVMPassManagerRef LLVMCreatePassManager() {
1694 return wrap(new PassManager());
1697 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1698 return wrap(new FunctionPassManager(unwrap(P)));
1701 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1702 return unwrap<PassManager>(PM)->run(*unwrap(M));
1705 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1706 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1709 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1710 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1713 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1714 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1717 void LLVMDisposePassManager(LLVMPassManagerRef PM) {