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/ErrorHandling.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/System/Threading.h"
25 #include "llvm/Analysis/Dominators.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 // Always verify dominfo if expensive checking is enabled.
50 bool VerifyDomInfo = true;
52 bool VerifyDomInfo = false;
54 static cl::opt<bool,true>
55 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
56 cl::desc("Verify dominator info (time consuming)"));
58 static cl::opt<enum PassDebugLevel>
59 PassDebugging("debug-pass", cl::Hidden,
60 cl::desc("Print PassManager debugging information"),
62 clEnumVal(None , "disable debug output"),
63 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
64 clEnumVal(Structure , "print pass structure before run()"),
65 clEnumVal(Executions, "print pass name before it is executed"),
66 clEnumVal(Details , "print pass details when it is executed"),
68 } // End of llvm namespace
70 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
71 /// or higher is specified.
72 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
73 return PassDebugging >= Executions;
79 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
81 OS << "Releasing pass '";
83 OS << "Running pass '";
85 OS << P->getPassName() << "'";
88 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
99 else if (isa<BasicBlock>(V))
105 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
112 //===----------------------------------------------------------------------===//
115 /// BBPassManager manages BasicBlockPass. It batches all the
116 /// pass together and sequence them to process one basic block before
117 /// processing next basic block.
118 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
119 public FunctionPass {
123 explicit BBPassManager(int Depth)
124 : PMDataManager(Depth), FunctionPass(&ID) {}
126 /// Execute all of the passes scheduled for execution. Keep track of
127 /// whether any of the passes modifies the function, and if so, return true.
128 bool runOnFunction(Function &F);
130 /// Pass Manager itself does not invalidate any analysis info.
131 void getAnalysisUsage(AnalysisUsage &Info) const {
132 Info.setPreservesAll();
135 bool doInitialization(Module &M);
136 bool doInitialization(Function &F);
137 bool doFinalization(Module &M);
138 bool doFinalization(Function &F);
140 virtual const char *getPassName() const {
141 return "BasicBlock Pass Manager";
144 // Print passes managed by this manager
145 void dumpPassStructure(unsigned Offset) {
146 llvm::errs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
147 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
148 BasicBlockPass *BP = getContainedPass(Index);
149 BP->dumpPassStructure(Offset + 1);
150 dumpLastUses(BP, Offset+1);
154 BasicBlockPass *getContainedPass(unsigned N) {
155 assert(N < PassVector.size() && "Pass number out of range!");
156 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
160 virtual PassManagerType getPassManagerType() const {
161 return PMT_BasicBlockPassManager;
165 char BBPassManager::ID = 0;
170 //===----------------------------------------------------------------------===//
171 // FunctionPassManagerImpl
173 /// FunctionPassManagerImpl manages FPPassManagers
174 class FunctionPassManagerImpl : public Pass,
175 public PMDataManager,
176 public PMTopLevelManager {
181 explicit FunctionPassManagerImpl(int Depth) :
182 Pass(&ID), PMDataManager(Depth),
183 PMTopLevelManager(TLM_Function), wasRun(false) { }
185 /// add - Add a pass to the queue of passes to run. This passes ownership of
186 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
187 /// will be destroyed as well, so there is no need to delete the pass. This
188 /// implies that all passes MUST be allocated with 'new'.
193 // Prepare for running an on the fly pass, freeing memory if needed
194 // from a previous run.
195 void releaseMemoryOnTheFly();
197 /// run - Execute all of the passes scheduled for execution. Keep track of
198 /// whether any of the passes modifies the module, and if so, return true.
199 bool run(Function &F);
201 /// doInitialization - Run all of the initializers for the function passes.
203 bool doInitialization(Module &M);
205 /// doFinalization - Run all of the finalizers for the function passes.
207 bool doFinalization(Module &M);
209 /// Pass Manager itself does not invalidate any analysis info.
210 void getAnalysisUsage(AnalysisUsage &Info) const {
211 Info.setPreservesAll();
214 inline void addTopLevelPass(Pass *P) {
216 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
218 // P is a immutable pass and it will be managed by this
219 // top level manager. Set up analysis resolver to connect them.
220 AnalysisResolver *AR = new AnalysisResolver(*this);
222 initializeAnalysisImpl(P);
223 addImmutablePass(IP);
224 recordAvailableAnalysis(IP);
226 P->assignPassManager(activeStack);
231 FPPassManager *getContainedManager(unsigned N) {
232 assert(N < PassManagers.size() && "Pass number out of range!");
233 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
238 char FunctionPassManagerImpl::ID = 0;
239 //===----------------------------------------------------------------------===//
242 /// MPPassManager manages ModulePasses and function pass managers.
243 /// It batches all Module passes and function pass managers together and
244 /// sequences them to process one module.
245 class MPPassManager : public Pass, public PMDataManager {
248 explicit MPPassManager(int Depth) :
249 Pass(&ID), PMDataManager(Depth) { }
251 // Delete on the fly managers.
252 virtual ~MPPassManager() {
253 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
254 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
256 FunctionPassManagerImpl *FPP = I->second;
261 /// run - Execute all of the passes scheduled for execution. Keep track of
262 /// whether any of the passes modifies the module, and if so, return true.
263 bool runOnModule(Module &M);
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const {
267 Info.setPreservesAll();
270 /// Add RequiredPass into list of lower level passes required by pass P.
271 /// RequiredPass is run on the fly by Pass Manager when P requests it
272 /// through getAnalysis interface.
273 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
275 /// Return function pass corresponding to PassInfo PI, that is
276 /// required by module pass MP. Instantiate analysis pass, by using
277 /// its runOnFunction() for function F.
278 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
280 virtual const char *getPassName() const {
281 return "Module Pass Manager";
284 // Print passes managed by this manager
285 void dumpPassStructure(unsigned Offset) {
286 llvm::errs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
287 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
288 ModulePass *MP = getContainedPass(Index);
289 MP->dumpPassStructure(Offset + 1);
290 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
291 OnTheFlyManagers.find(MP);
292 if (I != OnTheFlyManagers.end())
293 I->second->dumpPassStructure(Offset + 2);
294 dumpLastUses(MP, Offset+1);
298 ModulePass *getContainedPass(unsigned N) {
299 assert(N < PassVector.size() && "Pass number out of range!");
300 return static_cast<ModulePass *>(PassVector[N]);
303 virtual PassManagerType getPassManagerType() const {
304 return PMT_ModulePassManager;
308 /// Collection of on the fly FPPassManagers. These managers manage
309 /// function passes that are required by module passes.
310 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
313 char MPPassManager::ID = 0;
314 //===----------------------------------------------------------------------===//
318 /// PassManagerImpl manages MPPassManagers
319 class PassManagerImpl : public Pass,
320 public PMDataManager,
321 public PMTopLevelManager {
325 explicit PassManagerImpl(int Depth) :
326 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
328 /// add - Add a pass to the queue of passes to run. This passes ownership of
329 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
330 /// will be destroyed as well, so there is no need to delete the pass. This
331 /// implies that all passes MUST be allocated with 'new'.
336 /// run - Execute all of the passes scheduled for execution. Keep track of
337 /// whether any of the passes modifies the module, and if so, return true.
340 /// Pass Manager itself does not invalidate any analysis info.
341 void getAnalysisUsage(AnalysisUsage &Info) const {
342 Info.setPreservesAll();
345 inline void addTopLevelPass(Pass *P) {
346 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
348 // P is a immutable pass and it will be managed by this
349 // top level manager. Set up analysis resolver to connect them.
350 AnalysisResolver *AR = new AnalysisResolver(*this);
352 initializeAnalysisImpl(P);
353 addImmutablePass(IP);
354 recordAvailableAnalysis(IP);
356 P->assignPassManager(activeStack);
360 MPPassManager *getContainedManager(unsigned N) {
361 assert(N < PassManagers.size() && "Pass number out of range!");
362 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
367 char PassManagerImpl::ID = 0;
368 } // End of llvm namespace
372 //===----------------------------------------------------------------------===//
373 /// TimingInfo Class - This class is used to calculate information about the
374 /// amount of time each pass takes to execute. This only happens when
375 /// -time-passes is enabled on the command line.
378 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
380 class VISIBILITY_HIDDEN TimingInfo {
381 std::map<Pass*, Timer> TimingData;
385 // Use 'create' member to get this.
386 TimingInfo() : TG("... Pass execution timing report ...") {}
388 // TimingDtor - Print out information about timing information
390 // Delete all of the timers...
392 // TimerGroup is deleted next, printing the report.
395 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
396 // to a non null value (if the -time-passes option is enabled) or it leaves it
397 // null. It may be called multiple times.
398 static void createTheTimeInfo();
400 void passStarted(Pass *P) {
401 if (dynamic_cast<PMDataManager *>(P))
404 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
405 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
406 if (I == TimingData.end())
407 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
408 I->second.startTimer();
411 void passEnded(Pass *P) {
412 if (dynamic_cast<PMDataManager *>(P))
415 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
416 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
417 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
418 I->second.stopTimer();
422 } // End of anon namespace
424 static TimingInfo *TheTimeInfo;
426 //===----------------------------------------------------------------------===//
427 // PMTopLevelManager implementation
429 /// Initialize top level manager. Create first pass manager.
430 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
432 MPPassManager *MPP = new MPPassManager(1);
433 MPP->setTopLevelManager(this);
435 activeStack.push(MPP);
436 } else if (t == TLM_Function) {
437 FPPassManager *FPP = new FPPassManager(1);
438 FPP->setTopLevelManager(this);
440 activeStack.push(FPP);
444 /// Set pass P as the last user of the given analysis passes.
445 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
447 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
448 E = AnalysisPasses.end(); I != E; ++I) {
455 // If AP is the last user of other passes then make P last user of
457 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
458 LUE = LastUser.end(); LUI != LUE; ++LUI) {
459 if (LUI->second == AP)
460 // DenseMap iterator is not invalidated here because
461 // this is just updating exisitng entry.
462 LastUser[LUI->first] = P;
467 /// Collect passes whose last user is P
468 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
470 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
471 InversedLastUser.find(P);
472 if (DMI == InversedLastUser.end())
475 SmallPtrSet<Pass *, 8> &LU = DMI->second;
476 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
477 E = LU.end(); I != E; ++I) {
478 LastUses.push_back(*I);
483 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
484 AnalysisUsage *AnUsage = NULL;
485 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
486 if (DMI != AnUsageMap.end())
487 AnUsage = DMI->second;
489 AnUsage = new AnalysisUsage();
490 P->getAnalysisUsage(*AnUsage);
491 AnUsageMap[P] = AnUsage;
496 /// Schedule pass P for execution. Make sure that passes required by
497 /// P are run before P is run. Update analysis info maintained by
498 /// the manager. Remove dead passes. This is a recursive function.
499 void PMTopLevelManager::schedulePass(Pass *P) {
501 // TODO : Allocate function manager for this pass, other wise required set
502 // may be inserted into previous function manager
504 // Give pass a chance to prepare the stage.
505 P->preparePassManager(activeStack);
507 // If P is an analysis pass and it is available then do not
508 // generate the analysis again. Stale analysis info should not be
509 // available at this point.
510 if (P->getPassInfo() &&
511 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
516 AnalysisUsage *AnUsage = findAnalysisUsage(P);
518 bool checkAnalysis = true;
519 while (checkAnalysis) {
520 checkAnalysis = false;
522 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
523 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
524 E = RequiredSet.end(); I != E; ++I) {
526 Pass *AnalysisPass = findAnalysisPass(*I);
528 AnalysisPass = (*I)->createPass();
529 if (P->getPotentialPassManagerType () ==
530 AnalysisPass->getPotentialPassManagerType())
531 // Schedule analysis pass that is managed by the same pass manager.
532 schedulePass(AnalysisPass);
533 else if (P->getPotentialPassManagerType () >
534 AnalysisPass->getPotentialPassManagerType()) {
535 // Schedule analysis pass that is managed by a new manager.
536 schedulePass(AnalysisPass);
537 // Recheck analysis passes to ensure that required analysises that
538 // are already checked are still available.
539 checkAnalysis = true;
542 // Do not schedule this analysis. Lower level analsyis
543 // passes are run on the fly.
549 // Now all required passes are available.
553 /// Find the pass that implements Analysis AID. Search immutable
554 /// passes and all pass managers. If desired pass is not found
555 /// then return NULL.
556 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
559 // Check pass managers
560 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
561 E = PassManagers.end(); P == NULL && I != E; ++I) {
562 PMDataManager *PMD = *I;
563 P = PMD->findAnalysisPass(AID, false);
566 // Check other pass managers
567 for (SmallVector<PMDataManager *, 8>::iterator
568 I = IndirectPassManagers.begin(),
569 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
570 P = (*I)->findAnalysisPass(AID, false);
572 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
573 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
574 const PassInfo *PI = (*I)->getPassInfo();
578 // If Pass not found then check the interfaces implemented by Immutable Pass
580 const std::vector<const PassInfo*> &ImmPI =
581 PI->getInterfacesImplemented();
582 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
590 // Print passes managed by this top level manager.
591 void PMTopLevelManager::dumpPasses() const {
593 if (PassDebugging < Structure)
596 // Print out the immutable passes
597 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
598 ImmutablePasses[i]->dumpPassStructure(0);
601 // Every class that derives from PMDataManager also derives from Pass
602 // (sometimes indirectly), but there's no inheritance relationship
603 // between PMDataManager and Pass, so we have to dynamic_cast to get
604 // from a PMDataManager* to a Pass*.
605 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
606 E = PassManagers.end(); I != E; ++I)
607 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
610 void PMTopLevelManager::dumpArguments() const {
612 if (PassDebugging < Arguments)
615 errs() << "Pass Arguments: ";
616 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
617 E = PassManagers.end(); I != E; ++I)
618 (*I)->dumpPassArguments();
622 void PMTopLevelManager::initializeAllAnalysisInfo() {
623 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
624 E = PassManagers.end(); I != E; ++I)
625 (*I)->initializeAnalysisInfo();
627 // Initailize other pass managers
628 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
629 E = IndirectPassManagers.end(); I != E; ++I)
630 (*I)->initializeAnalysisInfo();
632 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
633 DME = LastUser.end(); DMI != DME; ++DMI) {
634 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
635 InversedLastUser.find(DMI->second);
636 if (InvDMI != InversedLastUser.end()) {
637 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
638 L.insert(DMI->first);
640 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
641 InversedLastUser[DMI->second] = L;
647 PMTopLevelManager::~PMTopLevelManager() {
648 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
649 E = PassManagers.end(); I != E; ++I)
652 for (SmallVector<ImmutablePass *, 8>::iterator
653 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
656 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
657 DME = AnUsageMap.end(); DMI != DME; ++DMI)
661 //===----------------------------------------------------------------------===//
662 // PMDataManager implementation
664 /// Augement AvailableAnalysis by adding analysis made available by pass P.
665 void PMDataManager::recordAvailableAnalysis(Pass *P) {
666 const PassInfo *PI = P->getPassInfo();
669 AvailableAnalysis[PI] = P;
671 //This pass is the current implementation of all of the interfaces it
672 //implements as well.
673 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
674 for (unsigned i = 0, e = II.size(); i != e; ++i)
675 AvailableAnalysis[II[i]] = P;
678 // Return true if P preserves high level analysis used by other
679 // passes managed by this manager
680 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
681 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
682 if (AnUsage->getPreservesAll())
685 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
686 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
687 E = HigherLevelAnalysis.end(); I != E; ++I) {
689 if (!dynamic_cast<ImmutablePass*>(P1) &&
690 std::find(PreservedSet.begin(), PreservedSet.end(),
691 P1->getPassInfo()) ==
699 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
700 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
701 // Don't do this unless assertions are enabled.
705 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
706 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
708 // Verify preserved analysis
709 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
710 E = PreservedSet.end(); I != E; ++I) {
712 if (Pass *AP = findAnalysisPass(AID, true))
713 AP->verifyAnalysis();
717 /// verifyDomInfo - Verify dominator information if it is available.
718 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
719 if (!VerifyDomInfo || !P.getResolver())
722 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
726 DominatorTree OtherDT;
727 OtherDT.getBase().recalculate(F);
728 if (DT->compare(OtherDT)) {
729 errs() << "Dominator Information for " << F.getName() << "\n";
730 errs() << "Pass '" << P.getPassName() << "'\n";
731 errs() << "----- Valid -----\n";
733 errs() << "----- Invalid -----\n";
735 llvm_unreachable("Invalid dominator info");
738 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
742 DominanceFrontier OtherDF;
743 std::vector<BasicBlock*> DTRoots = DT->getRoots();
744 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
745 if (DF->compare(OtherDF)) {
746 errs() << "Dominator Information for " << F.getName() << "\n";
747 errs() << "Pass '" << P.getPassName() << "'\n";
748 errs() << "----- Valid -----\n";
750 errs() << "----- Invalid -----\n";
752 llvm_unreachable("Invalid dominator info");
756 /// Remove Analysis not preserved by Pass P
757 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
758 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
759 if (AnUsage->getPreservesAll())
762 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
763 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
764 E = AvailableAnalysis.end(); I != E; ) {
765 std::map<AnalysisID, Pass*>::iterator Info = I++;
766 if (!dynamic_cast<ImmutablePass*>(Info->second)
767 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
768 PreservedSet.end()) {
769 // Remove this analysis
770 if (PassDebugging >= Details) {
771 Pass *S = Info->second;
772 errs() << " -- '" << P->getPassName() << "' is not preserving '";
773 errs() << S->getPassName() << "'\n";
775 AvailableAnalysis.erase(Info);
779 // Check inherited analysis also. If P is not preserving analysis
780 // provided by parent manager then remove it here.
781 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
783 if (!InheritedAnalysis[Index])
786 for (std::map<AnalysisID, Pass*>::iterator
787 I = InheritedAnalysis[Index]->begin(),
788 E = InheritedAnalysis[Index]->end(); I != E; ) {
789 std::map<AnalysisID, Pass *>::iterator Info = I++;
790 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
791 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
793 // Remove this analysis
794 InheritedAnalysis[Index]->erase(Info);
799 /// Remove analysis passes that are not used any longer
800 void PMDataManager::removeDeadPasses(Pass *P, const StringRef &Msg,
801 enum PassDebuggingString DBG_STR) {
803 SmallVector<Pass *, 12> DeadPasses;
805 // If this is a on the fly manager then it does not have TPM.
809 TPM->collectLastUses(DeadPasses, P);
811 if (PassDebugging >= Details && !DeadPasses.empty()) {
812 errs() << " -*- '" << P->getPassName();
813 errs() << "' is the last user of following pass instances.";
814 errs() << " Free these instances\n";
817 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
818 E = DeadPasses.end(); I != E; ++I)
819 freePass(*I, Msg, DBG_STR);
822 void PMDataManager::freePass(Pass *P, const StringRef &Msg,
823 enum PassDebuggingString DBG_STR) {
824 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
827 // If the pass crashes releasing memory, remember this.
828 PassManagerPrettyStackEntry X(P);
830 if (TheTimeInfo) TheTimeInfo->passStarted(P);
832 if (TheTimeInfo) TheTimeInfo->passEnded(P);
835 if (const PassInfo *PI = P->getPassInfo()) {
836 // Remove the pass itself (if it is not already removed).
837 AvailableAnalysis.erase(PI);
839 // Remove all interfaces this pass implements, for which it is also
840 // listed as the available implementation.
841 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
842 for (unsigned i = 0, e = II.size(); i != e; ++i) {
843 std::map<AnalysisID, Pass*>::iterator Pos =
844 AvailableAnalysis.find(II[i]);
845 if (Pos != AvailableAnalysis.end() && Pos->second == P)
846 AvailableAnalysis.erase(Pos);
851 /// Add pass P into the PassVector. Update
852 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
853 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
854 // This manager is going to manage pass P. Set up analysis resolver
856 AnalysisResolver *AR = new AnalysisResolver(*this);
859 // If a FunctionPass F is the last user of ModulePass info M
860 // then the F's manager, not F, records itself as a last user of M.
861 SmallVector<Pass *, 12> TransferLastUses;
863 if (!ProcessAnalysis) {
865 PassVector.push_back(P);
869 // At the moment, this pass is the last user of all required passes.
870 SmallVector<Pass *, 12> LastUses;
871 SmallVector<Pass *, 8> RequiredPasses;
872 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
874 unsigned PDepth = this->getDepth();
876 collectRequiredAnalysis(RequiredPasses,
877 ReqAnalysisNotAvailable, P);
878 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
879 E = RequiredPasses.end(); I != E; ++I) {
880 Pass *PRequired = *I;
883 assert(PRequired->getResolver() && "Analysis Resolver is not set");
884 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
885 RDepth = DM.getDepth();
887 if (PDepth == RDepth)
888 LastUses.push_back(PRequired);
889 else if (PDepth > RDepth) {
890 // Let the parent claim responsibility of last use
891 TransferLastUses.push_back(PRequired);
892 // Keep track of higher level analysis used by this manager.
893 HigherLevelAnalysis.push_back(PRequired);
895 llvm_unreachable("Unable to accomodate Required Pass");
898 // Set P as P's last user until someone starts using P.
899 // However, if P is a Pass Manager then it does not need
900 // to record its last user.
901 if (!dynamic_cast<PMDataManager *>(P))
902 LastUses.push_back(P);
903 TPM->setLastUser(LastUses, P);
905 if (!TransferLastUses.empty()) {
906 Pass *My_PM = dynamic_cast<Pass *>(this);
907 TPM->setLastUser(TransferLastUses, My_PM);
908 TransferLastUses.clear();
911 // Now, take care of required analysises that are not available.
912 for (SmallVector<AnalysisID, 8>::iterator
913 I = ReqAnalysisNotAvailable.begin(),
914 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
915 Pass *AnalysisPass = (*I)->createPass();
916 this->addLowerLevelRequiredPass(P, AnalysisPass);
919 // Take a note of analysis required and made available by this pass.
920 // Remove the analysis not preserved by this pass
921 removeNotPreservedAnalysis(P);
922 recordAvailableAnalysis(P);
925 PassVector.push_back(P);
929 /// Populate RP with analysis pass that are required by
930 /// pass P and are available. Populate RP_NotAvail with analysis
931 /// pass that are required by pass P but are not available.
932 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
933 SmallVector<AnalysisID, 8> &RP_NotAvail,
935 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
936 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
937 for (AnalysisUsage::VectorType::const_iterator
938 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
939 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
940 RP.push_back(AnalysisPass);
942 RP_NotAvail.push_back(*I);
945 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
946 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
947 E = IDs.end(); I != E; ++I) {
948 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
949 RP.push_back(AnalysisPass);
951 RP_NotAvail.push_back(*I);
955 // All Required analyses should be available to the pass as it runs! Here
956 // we fill in the AnalysisImpls member of the pass so that it can
957 // successfully use the getAnalysis() method to retrieve the
958 // implementations it needs.
960 void PMDataManager::initializeAnalysisImpl(Pass *P) {
961 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
963 for (AnalysisUsage::VectorType::const_iterator
964 I = AnUsage->getRequiredSet().begin(),
965 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
966 Pass *Impl = findAnalysisPass(*I, true);
968 // This may be analysis pass that is initialized on the fly.
969 // If that is not the case then it will raise an assert when it is used.
971 AnalysisResolver *AR = P->getResolver();
972 assert(AR && "Analysis Resolver is not set");
973 AR->addAnalysisImplsPair(*I, Impl);
977 /// Find the pass that implements Analysis AID. If desired pass is not found
978 /// then return NULL.
979 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
981 // Check if AvailableAnalysis map has one entry.
982 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
984 if (I != AvailableAnalysis.end())
987 // Search Parents through TopLevelManager
989 return TPM->findAnalysisPass(AID);
994 // Print list of passes that are last used by P.
995 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
997 SmallVector<Pass *, 12> LUses;
999 // If this is a on the fly manager then it does not have TPM.
1003 TPM->collectLastUses(LUses, P);
1005 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1006 E = LUses.end(); I != E; ++I) {
1007 llvm::errs() << "--" << std::string(Offset*2, ' ');
1008 (*I)->dumpPassStructure(0);
1012 void PMDataManager::dumpPassArguments() const {
1013 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1014 E = PassVector.end(); I != E; ++I) {
1015 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
1016 PMD->dumpPassArguments();
1018 if (const PassInfo *PI = (*I)->getPassInfo())
1019 if (!PI->isAnalysisGroup())
1020 errs() << " -" << PI->getPassArgument();
1024 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1025 enum PassDebuggingString S2,
1026 const StringRef &Msg) {
1027 if (PassDebugging < Executions)
1029 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
1032 errs() << "Executing Pass '" << P->getPassName();
1034 case MODIFICATION_MSG:
1035 errs() << "Made Modification '" << P->getPassName();
1038 errs() << " Freeing Pass '" << P->getPassName();
1044 case ON_BASICBLOCK_MSG:
1045 errs() << "' on BasicBlock '" << Msg << "'...\n";
1047 case ON_FUNCTION_MSG:
1048 errs() << "' on Function '" << Msg << "'...\n";
1051 errs() << "' on Module '" << Msg << "'...\n";
1054 errs() << "' on Loop '" << Msg << "'...\n";
1057 errs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1064 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1065 if (PassDebugging < Details)
1068 AnalysisUsage analysisUsage;
1069 P->getAnalysisUsage(analysisUsage);
1070 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1073 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1074 if (PassDebugging < Details)
1077 AnalysisUsage analysisUsage;
1078 P->getAnalysisUsage(analysisUsage);
1079 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1082 void PMDataManager::dumpAnalysisUsage(const StringRef &Msg, const Pass *P,
1083 const AnalysisUsage::VectorType &Set) const {
1084 assert(PassDebugging >= Details);
1087 errs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1088 for (unsigned i = 0; i != Set.size(); ++i) {
1089 if (i) errs() << ',';
1090 errs() << ' ' << Set[i]->getPassName();
1095 /// Add RequiredPass into list of lower level passes required by pass P.
1096 /// RequiredPass is run on the fly by Pass Manager when P requests it
1097 /// through getAnalysis interface.
1098 /// This should be handled by specific pass manager.
1099 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1101 TPM->dumpArguments();
1105 // Module Level pass may required Function Level analysis info
1106 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1107 // to provide this on demand. In that case, in Pass manager terminology,
1108 // module level pass is requiring lower level analysis info managed by
1109 // lower level pass manager.
1111 // When Pass manager is not able to order required analysis info, Pass manager
1112 // checks whether any lower level manager will be able to provide this
1113 // analysis info on demand or not.
1115 errs() << "Unable to schedule '" << RequiredPass->getPassName();
1116 errs() << "' required by '" << P->getPassName() << "'\n";
1118 llvm_unreachable("Unable to schedule pass");
1122 PMDataManager::~PMDataManager() {
1123 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1124 E = PassVector.end(); I != E; ++I)
1128 //===----------------------------------------------------------------------===//
1129 // NOTE: Is this the right place to define this method ?
1130 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1131 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1132 return PM.findAnalysisPass(ID, dir);
1135 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1137 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1140 //===----------------------------------------------------------------------===//
1141 // BBPassManager implementation
1143 /// Execute all of the passes scheduled for execution by invoking
1144 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1145 /// the function, and if so, return true.
1146 bool BBPassManager::runOnFunction(Function &F) {
1147 if (F.isDeclaration())
1150 bool Changed = doInitialization(F);
1152 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1153 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1154 BasicBlockPass *BP = getContainedPass(Index);
1156 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1157 dumpRequiredSet(BP);
1159 initializeAnalysisImpl(BP);
1162 // If the pass crashes, remember this.
1163 PassManagerPrettyStackEntry X(BP, *I);
1165 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1166 Changed |= BP->runOnBasicBlock(*I);
1167 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1171 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1173 dumpPreservedSet(BP);
1175 verifyPreservedAnalysis(BP);
1176 removeNotPreservedAnalysis(BP);
1177 recordAvailableAnalysis(BP);
1178 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1181 return Changed |= doFinalization(F);
1184 // Implement doInitialization and doFinalization
1185 bool BBPassManager::doInitialization(Module &M) {
1186 bool Changed = false;
1188 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1189 Changed |= getContainedPass(Index)->doInitialization(M);
1194 bool BBPassManager::doFinalization(Module &M) {
1195 bool Changed = false;
1197 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1198 Changed |= getContainedPass(Index)->doFinalization(M);
1203 bool BBPassManager::doInitialization(Function &F) {
1204 bool Changed = false;
1206 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1207 BasicBlockPass *BP = getContainedPass(Index);
1208 Changed |= BP->doInitialization(F);
1214 bool BBPassManager::doFinalization(Function &F) {
1215 bool Changed = false;
1217 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1218 BasicBlockPass *BP = getContainedPass(Index);
1219 Changed |= BP->doFinalization(F);
1226 //===----------------------------------------------------------------------===//
1227 // FunctionPassManager implementation
1229 /// Create new Function pass manager
1230 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1231 FPM = new FunctionPassManagerImpl(0);
1232 // FPM is the top level manager.
1233 FPM->setTopLevelManager(FPM);
1235 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1236 FPM->setResolver(AR);
1241 FunctionPassManager::~FunctionPassManager() {
1245 /// add - Add a pass to the queue of passes to run. This passes
1246 /// ownership of the Pass to the PassManager. When the
1247 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1248 /// there is no need to delete the pass. (TODO delete passes.)
1249 /// This implies that all passes MUST be allocated with 'new'.
1250 void FunctionPassManager::add(Pass *P) {
1254 /// run - Execute all of the passes scheduled for execution. Keep
1255 /// track of whether any of the passes modifies the function, and if
1256 /// so, return true.
1258 bool FunctionPassManager::run(Function &F) {
1260 if (MP->materializeFunction(&F, &errstr)) {
1261 llvm_report_error("Error reading bitcode file: " + errstr);
1267 /// doInitialization - Run all of the initializers for the function passes.
1269 bool FunctionPassManager::doInitialization() {
1270 return FPM->doInitialization(*MP->getModule());
1273 /// doFinalization - Run all of the finalizers for the function passes.
1275 bool FunctionPassManager::doFinalization() {
1276 return FPM->doFinalization(*MP->getModule());
1279 //===----------------------------------------------------------------------===//
1280 // FunctionPassManagerImpl implementation
1282 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1283 bool Changed = false;
1285 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1286 Changed |= getContainedManager(Index)->doInitialization(M);
1291 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1292 bool Changed = false;
1294 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1295 Changed |= getContainedManager(Index)->doFinalization(M);
1300 /// cleanup - After running all passes, clean up pass manager cache.
1301 void FPPassManager::cleanup() {
1302 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1303 FunctionPass *FP = getContainedPass(Index);
1304 AnalysisResolver *AR = FP->getResolver();
1305 assert(AR && "Analysis Resolver is not set");
1306 AR->clearAnalysisImpls();
1310 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1313 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1314 FPPassManager *FPPM = getContainedManager(Index);
1315 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1316 FPPM->getContainedPass(Index)->releaseMemory();
1322 // Execute all the passes managed by this top level manager.
1323 // Return true if any function is modified by a pass.
1324 bool FunctionPassManagerImpl::run(Function &F) {
1325 bool Changed = false;
1326 TimingInfo::createTheTimeInfo();
1331 initializeAllAnalysisInfo();
1332 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1333 Changed |= getContainedManager(Index)->runOnFunction(F);
1335 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1336 getContainedManager(Index)->cleanup();
1342 //===----------------------------------------------------------------------===//
1343 // FPPassManager implementation
1345 char FPPassManager::ID = 0;
1346 /// Print passes managed by this manager
1347 void FPPassManager::dumpPassStructure(unsigned Offset) {
1348 llvm::errs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1350 FunctionPass *FP = getContainedPass(Index);
1351 FP->dumpPassStructure(Offset + 1);
1352 dumpLastUses(FP, Offset+1);
1357 /// Execute all of the passes scheduled for execution by invoking
1358 /// runOnFunction method. Keep track of whether any of the passes modifies
1359 /// the function, and if so, return true.
1360 bool FPPassManager::runOnFunction(Function &F) {
1361 if (F.isDeclaration())
1364 bool Changed = false;
1366 // Collect inherited analysis from Module level pass manager.
1367 populateInheritedAnalysis(TPM->activeStack);
1369 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1370 FunctionPass *FP = getContainedPass(Index);
1372 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1373 dumpRequiredSet(FP);
1375 initializeAnalysisImpl(FP);
1378 PassManagerPrettyStackEntry X(FP, F);
1380 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1381 Changed |= FP->runOnFunction(F);
1382 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1386 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1387 dumpPreservedSet(FP);
1389 verifyPreservedAnalysis(FP);
1390 removeNotPreservedAnalysis(FP);
1391 recordAvailableAnalysis(FP);
1392 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1394 // If dominator information is available then verify the info if requested.
1395 verifyDomInfo(*FP, F);
1400 bool FPPassManager::runOnModule(Module &M) {
1401 bool Changed = doInitialization(M);
1403 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1406 return Changed |= doFinalization(M);
1409 bool FPPassManager::doInitialization(Module &M) {
1410 bool Changed = false;
1412 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1413 Changed |= getContainedPass(Index)->doInitialization(M);
1418 bool FPPassManager::doFinalization(Module &M) {
1419 bool Changed = false;
1421 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1422 Changed |= getContainedPass(Index)->doFinalization(M);
1427 //===----------------------------------------------------------------------===//
1428 // MPPassManager implementation
1430 /// Execute all of the passes scheduled for execution by invoking
1431 /// runOnModule method. Keep track of whether any of the passes modifies
1432 /// the module, and if so, return true.
1434 MPPassManager::runOnModule(Module &M) {
1435 bool Changed = false;
1437 // Initialize on-the-fly passes
1438 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1439 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1441 FunctionPassManagerImpl *FPP = I->second;
1442 Changed |= FPP->doInitialization(M);
1445 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1446 ModulePass *MP = getContainedPass(Index);
1448 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1449 M.getModuleIdentifier().c_str());
1450 dumpRequiredSet(MP);
1452 initializeAnalysisImpl(MP);
1455 PassManagerPrettyStackEntry X(MP, M);
1456 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1457 Changed |= MP->runOnModule(M);
1458 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1462 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1463 M.getModuleIdentifier().c_str());
1464 dumpPreservedSet(MP);
1466 verifyPreservedAnalysis(MP);
1467 removeNotPreservedAnalysis(MP);
1468 recordAvailableAnalysis(MP);
1469 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1472 // Finalize on-the-fly passes
1473 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1474 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1476 FunctionPassManagerImpl *FPP = I->second;
1477 // We don't know when is the last time an on-the-fly pass is run,
1478 // so we need to releaseMemory / finalize here
1479 FPP->releaseMemoryOnTheFly();
1480 Changed |= FPP->doFinalization(M);
1485 /// Add RequiredPass into list of lower level passes required by pass P.
1486 /// RequiredPass is run on the fly by Pass Manager when P requests it
1487 /// through getAnalysis interface.
1488 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1489 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1490 "Unable to handle Pass that requires lower level Analysis pass");
1491 assert((P->getPotentialPassManagerType() <
1492 RequiredPass->getPotentialPassManagerType()) &&
1493 "Unable to handle Pass that requires lower level Analysis pass");
1495 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1497 FPP = new FunctionPassManagerImpl(0);
1498 // FPP is the top level manager.
1499 FPP->setTopLevelManager(FPP);
1501 OnTheFlyManagers[P] = FPP;
1503 FPP->add(RequiredPass);
1505 // Register P as the last user of RequiredPass.
1506 SmallVector<Pass *, 12> LU;
1507 LU.push_back(RequiredPass);
1508 FPP->setLastUser(LU, P);
1511 /// Return function pass corresponding to PassInfo PI, that is
1512 /// required by module pass MP. Instantiate analysis pass, by using
1513 /// its runOnFunction() for function F.
1514 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1515 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1516 assert(FPP && "Unable to find on the fly pass");
1518 FPP->releaseMemoryOnTheFly();
1520 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1524 //===----------------------------------------------------------------------===//
1525 // PassManagerImpl implementation
1527 /// run - Execute all of the passes scheduled for execution. Keep track of
1528 /// whether any of the passes modifies the module, and if so, return true.
1529 bool PassManagerImpl::run(Module &M) {
1530 bool Changed = false;
1531 TimingInfo::createTheTimeInfo();
1536 initializeAllAnalysisInfo();
1537 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1538 Changed |= getContainedManager(Index)->runOnModule(M);
1542 //===----------------------------------------------------------------------===//
1543 // PassManager implementation
1545 /// Create new pass manager
1546 PassManager::PassManager() {
1547 PM = new PassManagerImpl(0);
1548 // PM is the top level manager
1549 PM->setTopLevelManager(PM);
1552 PassManager::~PassManager() {
1556 /// add - Add a pass to the queue of passes to run. This passes ownership of
1557 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1558 /// will be destroyed as well, so there is no need to delete the pass. This
1559 /// implies that all passes MUST be allocated with 'new'.
1560 void PassManager::add(Pass *P) {
1564 /// run - Execute all of the passes scheduled for execution. Keep track of
1565 /// whether any of the passes modifies the module, and if so, return true.
1566 bool PassManager::run(Module &M) {
1570 //===----------------------------------------------------------------------===//
1571 // TimingInfo Class - This class is used to calculate information about the
1572 // amount of time each pass takes to execute. This only happens with
1573 // -time-passes is enabled on the command line.
1575 bool llvm::TimePassesIsEnabled = false;
1576 static cl::opt<bool,true>
1577 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1578 cl::desc("Time each pass, printing elapsed time for each on exit"));
1580 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1581 // a non null value (if the -time-passes option is enabled) or it leaves it
1582 // null. It may be called multiple times.
1583 void TimingInfo::createTheTimeInfo() {
1584 if (!TimePassesIsEnabled || TheTimeInfo) return;
1586 // Constructed the first time this is called, iff -time-passes is enabled.
1587 // This guarantees that the object will be constructed before static globals,
1588 // thus it will be destroyed before them.
1589 static ManagedStatic<TimingInfo> TTI;
1590 TheTimeInfo = &*TTI;
1593 /// If TimingInfo is enabled then start pass timer.
1594 void llvm::StartPassTimer(Pass *P) {
1596 TheTimeInfo->passStarted(P);
1599 /// If TimingInfo is enabled then stop pass timer.
1600 void llvm::StopPassTimer(Pass *P) {
1602 TheTimeInfo->passEnded(P);
1605 //===----------------------------------------------------------------------===//
1606 // PMStack implementation
1609 // Pop Pass Manager from the stack and clear its analysis info.
1610 void PMStack::pop() {
1612 PMDataManager *Top = this->top();
1613 Top->initializeAnalysisInfo();
1618 // Push PM on the stack and set its top level manager.
1619 void PMStack::push(PMDataManager *PM) {
1620 assert(PM && "Unable to push. Pass Manager expected");
1622 if (!this->empty()) {
1623 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1625 assert(TPM && "Unable to find top level manager");
1626 TPM->addIndirectPassManager(PM);
1627 PM->setTopLevelManager(TPM);
1633 // Dump content of the pass manager stack.
1634 void PMStack::dump() {
1635 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1636 E = S.end(); I != E; ++I)
1637 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1643 /// Find appropriate Module Pass Manager in the PM Stack and
1644 /// add self into that manager.
1645 void ModulePass::assignPassManager(PMStack &PMS,
1646 PassManagerType PreferredType) {
1647 // Find Module Pass Manager
1648 while(!PMS.empty()) {
1649 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1650 if (TopPMType == PreferredType)
1651 break; // We found desired pass manager
1652 else if (TopPMType > PMT_ModulePassManager)
1653 PMS.pop(); // Pop children pass managers
1657 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1658 PMS.top()->add(this);
1661 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1662 /// in the PM Stack and add self into that manager.
1663 void FunctionPass::assignPassManager(PMStack &PMS,
1664 PassManagerType PreferredType) {
1666 // Find Module Pass Manager
1667 while(!PMS.empty()) {
1668 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1673 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1675 // Create new Function Pass Manager
1677 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1678 PMDataManager *PMD = PMS.top();
1680 // [1] Create new Function Pass Manager
1681 FPP = new FPPassManager(PMD->getDepth() + 1);
1682 FPP->populateInheritedAnalysis(PMS);
1684 // [2] Set up new manager's top level manager
1685 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1686 TPM->addIndirectPassManager(FPP);
1688 // [3] Assign manager to manage this new manager. This may create
1689 // and push new managers into PMS
1690 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1692 // [4] Push new manager into PMS
1696 // Assign FPP as the manager of this pass.
1700 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1701 /// in the PM Stack and add self into that manager.
1702 void BasicBlockPass::assignPassManager(PMStack &PMS,
1703 PassManagerType PreferredType) {
1704 BBPassManager *BBP = NULL;
1706 // Basic Pass Manager is a leaf pass manager. It does not handle
1707 // any other pass manager.
1709 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1711 // If leaf manager is not Basic Block Pass manager then create new
1712 // basic Block Pass manager.
1715 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1716 PMDataManager *PMD = PMS.top();
1718 // [1] Create new Basic Block Manager
1719 BBP = new BBPassManager(PMD->getDepth() + 1);
1721 // [2] Set up new manager's top level manager
1722 // Basic Block Pass Manager does not live by itself
1723 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1724 TPM->addIndirectPassManager(BBP);
1726 // [3] Assign manager to manage this new manager. This may create
1727 // and push new managers into PMS
1728 BBP->assignPassManager(PMS);
1730 // [4] Push new manager into PMS
1734 // Assign BBP as the manager of this pass.
1738 PassManagerBase::~PassManagerBase() {}
1740 /*===-- C Bindings --------------------------------------------------------===*/
1742 LLVMPassManagerRef LLVMCreatePassManager() {
1743 return wrap(new PassManager());
1746 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1747 return wrap(new FunctionPassManager(unwrap(P)));
1750 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1751 return unwrap<PassManager>(PM)->run(*unwrap(M));
1754 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1755 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1758 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1759 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1762 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1763 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1766 void LLVMDisposePassManager(LLVMPassManagerRef PM) {