1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/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 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
72 OS << "Releasing pass '";
74 OS << "Running pass '";
76 OS << P->getPassName() << "'";
79 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
90 else if (isa<BasicBlock>(V))
96 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
103 //===----------------------------------------------------------------------===//
106 /// BBPassManager manages BasicBlockPass. It batches all the
107 /// pass together and sequence them to process one basic block before
108 /// processing next basic block.
109 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
110 public FunctionPass {
114 explicit BBPassManager(int Depth)
115 : PMDataManager(Depth), FunctionPass(&ID) {}
117 /// Execute all of the passes scheduled for execution. Keep track of
118 /// whether any of the passes modifies the function, and if so, return true.
119 bool runOnFunction(Function &F);
121 /// Pass Manager itself does not invalidate any analysis info.
122 void getAnalysisUsage(AnalysisUsage &Info) const {
123 Info.setPreservesAll();
126 bool doInitialization(Module &M);
127 bool doInitialization(Function &F);
128 bool doFinalization(Module &M);
129 bool doFinalization(Function &F);
131 virtual const char *getPassName() const {
132 return "BasicBlock Pass Manager";
135 // Print passes managed by this manager
136 void dumpPassStructure(unsigned Offset) {
137 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
138 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
139 BasicBlockPass *BP = getContainedPass(Index);
140 BP->dumpPassStructure(Offset + 1);
141 dumpLastUses(BP, Offset+1);
145 BasicBlockPass *getContainedPass(unsigned N) {
146 assert(N < PassVector.size() && "Pass number out of range!");
147 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
151 virtual PassManagerType getPassManagerType() const {
152 return PMT_BasicBlockPassManager;
156 char BBPassManager::ID = 0;
161 //===----------------------------------------------------------------------===//
162 // FunctionPassManagerImpl
164 /// FunctionPassManagerImpl manages FPPassManagers
165 class FunctionPassManagerImpl : public Pass,
166 public PMDataManager,
167 public PMTopLevelManager {
170 explicit FunctionPassManagerImpl(int Depth) :
171 Pass(&ID), PMDataManager(Depth),
172 PMTopLevelManager(TLM_Function) { }
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 /// run - Execute all of the passes scheduled for execution. Keep track of
183 /// whether any of the passes modifies the module, and if so, return true.
184 bool run(Function &F);
186 /// doInitialization - Run all of the initializers for the function passes.
188 bool doInitialization(Module &M);
190 /// doFinalization - Run all of the finalizers for the function passes.
192 bool doFinalization(Module &M);
194 /// Pass Manager itself does not invalidate any analysis info.
195 void getAnalysisUsage(AnalysisUsage &Info) const {
196 Info.setPreservesAll();
199 inline void addTopLevelPass(Pass *P) {
201 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
203 // P is a immutable pass and it will be managed by this
204 // top level manager. Set up analysis resolver to connect them.
205 AnalysisResolver *AR = new AnalysisResolver(*this);
207 initializeAnalysisImpl(P);
208 addImmutablePass(IP);
209 recordAvailableAnalysis(IP);
211 P->assignPassManager(activeStack);
216 FPPassManager *getContainedManager(unsigned N) {
217 assert(N < PassManagers.size() && "Pass number out of range!");
218 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
223 char FunctionPassManagerImpl::ID = 0;
224 //===----------------------------------------------------------------------===//
227 /// MPPassManager manages ModulePasses and function pass managers.
228 /// It batches all Module passes and function pass managers together and
229 /// sequences them to process one module.
230 class MPPassManager : public Pass, public PMDataManager {
233 explicit MPPassManager(int Depth) :
234 Pass(&ID), PMDataManager(Depth) { }
236 // Delete on the fly managers.
237 virtual ~MPPassManager() {
238 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
239 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
241 FunctionPassManagerImpl *FPP = I->second;
246 /// run - Execute all of the passes scheduled for execution. Keep track of
247 /// whether any of the passes modifies the module, and if so, return true.
248 bool runOnModule(Module &M);
250 /// Pass Manager itself does not invalidate any analysis info.
251 void getAnalysisUsage(AnalysisUsage &Info) const {
252 Info.setPreservesAll();
255 /// Add RequiredPass into list of lower level passes required by pass P.
256 /// RequiredPass is run on the fly by Pass Manager when P requests it
257 /// through getAnalysis interface.
258 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
260 /// Return function pass corresponding to PassInfo PI, that is
261 /// required by module pass MP. Instantiate analysis pass, by using
262 /// its runOnFunction() for function F.
263 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
265 virtual const char *getPassName() const {
266 return "Module Pass Manager";
269 // Print passes managed by this manager
270 void dumpPassStructure(unsigned Offset) {
271 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
272 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
273 ModulePass *MP = getContainedPass(Index);
274 MP->dumpPassStructure(Offset + 1);
275 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
276 FPP->dumpPassStructure(Offset + 2);
277 dumpLastUses(MP, Offset+1);
281 ModulePass *getContainedPass(unsigned N) {
282 assert(N < PassVector.size() && "Pass number out of range!");
283 return static_cast<ModulePass *>(PassVector[N]);
286 virtual PassManagerType getPassManagerType() const {
287 return PMT_ModulePassManager;
291 /// Collection of on the fly FPPassManagers. These managers manage
292 /// function passes that are required by module passes.
293 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
296 char MPPassManager::ID = 0;
297 //===----------------------------------------------------------------------===//
301 /// PassManagerImpl manages MPPassManagers
302 class PassManagerImpl : public Pass,
303 public PMDataManager,
304 public PMTopLevelManager {
308 explicit PassManagerImpl(int Depth) :
309 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
311 /// add - Add a pass to the queue of passes to run. This passes ownership of
312 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
313 /// will be destroyed as well, so there is no need to delete the pass. This
314 /// implies that all passes MUST be allocated with 'new'.
319 /// run - Execute all of the passes scheduled for execution. Keep track of
320 /// whether any of the passes modifies the module, and if so, return true.
323 /// Pass Manager itself does not invalidate any analysis info.
324 void getAnalysisUsage(AnalysisUsage &Info) const {
325 Info.setPreservesAll();
328 inline void addTopLevelPass(Pass *P) {
329 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
331 // P is a immutable pass and it will be managed by this
332 // top level manager. Set up analysis resolver to connect them.
333 AnalysisResolver *AR = new AnalysisResolver(*this);
335 initializeAnalysisImpl(P);
336 addImmutablePass(IP);
337 recordAvailableAnalysis(IP);
339 P->assignPassManager(activeStack);
343 MPPassManager *getContainedManager(unsigned N) {
344 assert(N < PassManagers.size() && "Pass number out of range!");
345 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
350 char PassManagerImpl::ID = 0;
351 } // End of llvm namespace
355 //===----------------------------------------------------------------------===//
356 /// TimingInfo Class - This class is used to calculate information about the
357 /// amount of time each pass takes to execute. This only happens when
358 /// -time-passes is enabled on the command line.
361 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
363 class VISIBILITY_HIDDEN TimingInfo {
364 std::map<Pass*, Timer> TimingData;
368 // Use 'create' member to get this.
369 TimingInfo() : TG("... Pass execution timing report ...") {}
371 // TimingDtor - Print out information about timing information
373 // Delete all of the timers...
375 // TimerGroup is deleted next, printing the report.
378 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
379 // to a non null value (if the -time-passes option is enabled) or it leaves it
380 // null. It may be called multiple times.
381 static void createTheTimeInfo();
383 void passStarted(Pass *P) {
384 if (dynamic_cast<PMDataManager *>(P))
387 sys::SmartScopedLock<true> Lock(&*TimingInfoMutex);
388 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
389 if (I == TimingData.end())
390 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
391 I->second.startTimer();
394 void passEnded(Pass *P) {
395 if (dynamic_cast<PMDataManager *>(P))
398 sys::SmartScopedLock<true> Lock(&*TimingInfoMutex);
399 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
400 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
401 I->second.stopTimer();
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 cerr << "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))
696 AP->verifyAnalysis();
700 /// verifyDomInfo - Verify dominator information if it is available.
701 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
702 if (!VerifyDomInfo || !P.getResolver())
705 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
709 DominatorTree OtherDT;
710 OtherDT.getBase().recalculate(F);
711 if (DT->compare(OtherDT)) {
712 cerr << "Dominator Information for " << F.getNameStart() << "\n";
713 cerr << "Pass '" << P.getPassName() << "'\n";
714 cerr << "----- Valid -----\n";
716 cerr << "----- Invalid -----\n";
718 assert(0 && "Invalid dominator info");
721 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
725 DominanceFrontier OtherDF;
726 std::vector<BasicBlock*> DTRoots = DT->getRoots();
727 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
728 if (DF->compare(OtherDF)) {
729 cerr << "Dominator Information for " << F.getNameStart() << "\n";
730 cerr << "Pass '" << P.getPassName() << "'\n";
731 cerr << "----- Valid -----\n";
733 cerr << "----- Invalid -----\n";
735 assert(0 && "Invalid dominator info");
739 /// Remove Analysis not preserved by Pass P
740 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
741 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
742 if (AnUsage->getPreservesAll())
745 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
746 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
747 E = AvailableAnalysis.end(); I != E; ) {
748 std::map<AnalysisID, Pass*>::iterator Info = I++;
749 if (!dynamic_cast<ImmutablePass*>(Info->second)
750 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
751 PreservedSet.end()) {
752 // Remove this analysis
753 if (PassDebugging >= Details) {
754 Pass *S = Info->second;
755 cerr << " -- '" << P->getPassName() << "' is not preserving '";
756 cerr << S->getPassName() << "'\n";
758 AvailableAnalysis.erase(Info);
762 // Check inherited analysis also. If P is not preserving analysis
763 // provided by parent manager then remove it here.
764 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
766 if (!InheritedAnalysis[Index])
769 for (std::map<AnalysisID, Pass*>::iterator
770 I = InheritedAnalysis[Index]->begin(),
771 E = InheritedAnalysis[Index]->end(); I != E; ) {
772 std::map<AnalysisID, Pass *>::iterator Info = I++;
773 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
774 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
776 // Remove this analysis
777 InheritedAnalysis[Index]->erase(Info);
782 /// Remove analysis passes that are not used any longer
783 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
784 enum PassDebuggingString DBG_STR) {
786 SmallVector<Pass *, 12> DeadPasses;
788 // If this is a on the fly manager then it does not have TPM.
792 TPM->collectLastUses(DeadPasses, P);
794 if (PassDebugging >= Details && !DeadPasses.empty()) {
795 cerr << " -*- '" << P->getPassName();
796 cerr << "' is the last user of following pass instances.";
797 cerr << " Free these instances\n";
800 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
801 E = DeadPasses.end(); I != E; ++I) {
803 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
806 // If the pass crashes releasing memory, remember this.
807 PassManagerPrettyStackEntry X(*I);
809 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
810 (*I)->releaseMemory();
811 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
813 if (const PassInfo *PI = (*I)->getPassInfo()) {
814 std::map<AnalysisID, Pass*>::iterator Pos =
815 AvailableAnalysis.find(PI);
817 // It is possible that pass is already removed from the AvailableAnalysis
818 if (Pos != AvailableAnalysis.end())
819 AvailableAnalysis.erase(Pos);
821 // Remove all interfaces this pass implements, for which it is also
822 // listed as the available implementation.
823 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
824 for (unsigned i = 0, e = II.size(); i != e; ++i) {
825 Pos = AvailableAnalysis.find(II[i]);
826 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
827 AvailableAnalysis.erase(Pos);
833 /// Add pass P into the PassVector. Update
834 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
835 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
836 // This manager is going to manage pass P. Set up analysis resolver
838 AnalysisResolver *AR = new AnalysisResolver(*this);
841 // If a FunctionPass F is the last user of ModulePass info M
842 // then the F's manager, not F, records itself as a last user of M.
843 SmallVector<Pass *, 12> TransferLastUses;
845 if (!ProcessAnalysis) {
847 PassVector.push_back(P);
851 // At the moment, this pass is the last user of all required passes.
852 SmallVector<Pass *, 12> LastUses;
853 SmallVector<Pass *, 8> RequiredPasses;
854 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
856 unsigned PDepth = this->getDepth();
858 collectRequiredAnalysis(RequiredPasses,
859 ReqAnalysisNotAvailable, P);
860 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
861 E = RequiredPasses.end(); I != E; ++I) {
862 Pass *PRequired = *I;
865 assert(PRequired->getResolver() && "Analysis Resolver is not set");
866 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
867 RDepth = DM.getDepth();
869 if (PDepth == RDepth)
870 LastUses.push_back(PRequired);
871 else if (PDepth > RDepth) {
872 // Let the parent claim responsibility of last use
873 TransferLastUses.push_back(PRequired);
874 // Keep track of higher level analysis used by this manager.
875 HigherLevelAnalysis.push_back(PRequired);
877 assert(0 && "Unable to accomodate Required Pass");
880 // Set P as P's last user until someone starts using P.
881 // However, if P is a Pass Manager then it does not need
882 // to record its last user.
883 if (!dynamic_cast<PMDataManager *>(P))
884 LastUses.push_back(P);
885 TPM->setLastUser(LastUses, P);
887 if (!TransferLastUses.empty()) {
888 Pass *My_PM = dynamic_cast<Pass *>(this);
889 TPM->setLastUser(TransferLastUses, My_PM);
890 TransferLastUses.clear();
893 // Now, take care of required analysises that are not available.
894 for (SmallVector<AnalysisID, 8>::iterator
895 I = ReqAnalysisNotAvailable.begin(),
896 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
897 Pass *AnalysisPass = (*I)->createPass();
898 this->addLowerLevelRequiredPass(P, AnalysisPass);
901 // Take a note of analysis required and made available by this pass.
902 // Remove the analysis not preserved by this pass
903 removeNotPreservedAnalysis(P);
904 recordAvailableAnalysis(P);
907 PassVector.push_back(P);
911 /// Populate RP with analysis pass that are required by
912 /// pass P and are available. Populate RP_NotAvail with analysis
913 /// pass that are required by pass P but are not available.
914 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
915 SmallVector<AnalysisID, 8> &RP_NotAvail,
917 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
918 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
919 for (AnalysisUsage::VectorType::const_iterator
920 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
921 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
922 RP.push_back(AnalysisPass);
924 RP_NotAvail.push_back(*I);
927 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
928 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
929 E = IDs.end(); I != E; ++I) {
930 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
931 RP.push_back(AnalysisPass);
933 RP_NotAvail.push_back(*I);
937 // All Required analyses should be available to the pass as it runs! Here
938 // we fill in the AnalysisImpls member of the pass so that it can
939 // successfully use the getAnalysis() method to retrieve the
940 // implementations it needs.
942 void PMDataManager::initializeAnalysisImpl(Pass *P) {
943 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
945 for (AnalysisUsage::VectorType::const_iterator
946 I = AnUsage->getRequiredSet().begin(),
947 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
948 Pass *Impl = findAnalysisPass(*I, true);
950 // This may be analysis pass that is initialized on the fly.
951 // If that is not the case then it will raise an assert when it is used.
953 AnalysisResolver *AR = P->getResolver();
954 assert(AR && "Analysis Resolver is not set");
955 AR->addAnalysisImplsPair(*I, Impl);
959 /// Find the pass that implements Analysis AID. If desired pass is not found
960 /// then return NULL.
961 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
963 // Check if AvailableAnalysis map has one entry.
964 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
966 if (I != AvailableAnalysis.end())
969 // Search Parents through TopLevelManager
971 return TPM->findAnalysisPass(AID);
976 // Print list of passes that are last used by P.
977 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
979 SmallVector<Pass *, 12> LUses;
981 // If this is a on the fly manager then it does not have TPM.
985 TPM->collectLastUses(LUses, P);
987 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
988 E = LUses.end(); I != E; ++I) {
989 llvm::cerr << "--" << std::string(Offset*2, ' ');
990 (*I)->dumpPassStructure(0);
994 void PMDataManager::dumpPassArguments() const {
995 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
996 E = PassVector.end(); I != E; ++I) {
997 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
998 PMD->dumpPassArguments();
1000 if (const PassInfo *PI = (*I)->getPassInfo())
1001 if (!PI->isAnalysisGroup())
1002 cerr << " -" << PI->getPassArgument();
1006 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1007 enum PassDebuggingString S2,
1009 if (PassDebugging < Executions)
1011 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
1014 cerr << "Executing Pass '" << P->getPassName();
1016 case MODIFICATION_MSG:
1017 cerr << "Made Modification '" << P->getPassName();
1020 cerr << " Freeing Pass '" << P->getPassName();
1026 case ON_BASICBLOCK_MSG:
1027 cerr << "' on BasicBlock '" << Msg << "'...\n";
1029 case ON_FUNCTION_MSG:
1030 cerr << "' on Function '" << Msg << "'...\n";
1033 cerr << "' on Module '" << Msg << "'...\n";
1036 cerr << "' on Loop " << Msg << "'...\n";
1039 cerr << "' on Call Graph " << Msg << "'...\n";
1046 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1047 if (PassDebugging < Details)
1050 AnalysisUsage analysisUsage;
1051 P->getAnalysisUsage(analysisUsage);
1052 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1055 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1056 if (PassDebugging < Details)
1059 AnalysisUsage analysisUsage;
1060 P->getAnalysisUsage(analysisUsage);
1061 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1064 void PMDataManager::dumpAnalysisUsage(const char *Msg, const Pass *P,
1065 const AnalysisUsage::VectorType &Set) const {
1066 assert(PassDebugging >= Details);
1069 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1070 for (unsigned i = 0; i != Set.size(); ++i) {
1072 cerr << " " << Set[i]->getPassName();
1077 /// Add RequiredPass into list of lower level passes required by pass P.
1078 /// RequiredPass is run on the fly by Pass Manager when P requests it
1079 /// through getAnalysis interface.
1080 /// This should be handled by specific pass manager.
1081 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1083 TPM->dumpArguments();
1087 // Module Level pass may required Function Level analysis info
1088 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1089 // to provide this on demand. In that case, in Pass manager terminology,
1090 // module level pass is requiring lower level analysis info managed by
1091 // lower level pass manager.
1093 // When Pass manager is not able to order required analysis info, Pass manager
1094 // checks whether any lower level manager will be able to provide this
1095 // analysis info on demand or not.
1097 cerr << "Unable to schedule '" << RequiredPass->getPassName();
1098 cerr << "' required by '" << P->getPassName() << "'\n";
1100 assert(0 && "Unable to schedule pass");
1104 PMDataManager::~PMDataManager() {
1105 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1106 E = PassVector.end(); I != E; ++I)
1110 //===----------------------------------------------------------------------===//
1111 // NOTE: Is this the right place to define this method ?
1112 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1113 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1114 return PM.findAnalysisPass(ID, dir);
1117 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1119 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1122 //===----------------------------------------------------------------------===//
1123 // BBPassManager implementation
1125 /// Execute all of the passes scheduled for execution by invoking
1126 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1127 /// the function, and if so, return true.
1128 bool BBPassManager::runOnFunction(Function &F) {
1129 if (F.isDeclaration())
1132 bool Changed = doInitialization(F);
1134 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1135 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1136 BasicBlockPass *BP = getContainedPass(Index);
1138 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
1139 dumpRequiredSet(BP);
1141 initializeAnalysisImpl(BP);
1144 // If the pass crashes, remember this.
1145 PassManagerPrettyStackEntry X(BP, *I);
1147 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1148 Changed |= BP->runOnBasicBlock(*I);
1149 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1153 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1155 dumpPreservedSet(BP);
1157 verifyPreservedAnalysis(BP);
1158 removeNotPreservedAnalysis(BP);
1159 recordAvailableAnalysis(BP);
1160 removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
1163 return Changed |= doFinalization(F);
1166 // Implement doInitialization and doFinalization
1167 bool BBPassManager::doInitialization(Module &M) {
1168 bool Changed = false;
1170 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1171 Changed |= getContainedPass(Index)->doInitialization(M);
1176 bool BBPassManager::doFinalization(Module &M) {
1177 bool Changed = false;
1179 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1180 Changed |= getContainedPass(Index)->doFinalization(M);
1185 bool BBPassManager::doInitialization(Function &F) {
1186 bool Changed = false;
1188 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1189 BasicBlockPass *BP = getContainedPass(Index);
1190 Changed |= BP->doInitialization(F);
1196 bool BBPassManager::doFinalization(Function &F) {
1197 bool Changed = false;
1199 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1200 BasicBlockPass *BP = getContainedPass(Index);
1201 Changed |= BP->doFinalization(F);
1208 //===----------------------------------------------------------------------===//
1209 // FunctionPassManager implementation
1211 /// Create new Function pass manager
1212 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1213 FPM = new FunctionPassManagerImpl(0);
1214 // FPM is the top level manager.
1215 FPM->setTopLevelManager(FPM);
1217 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1218 FPM->setResolver(AR);
1223 FunctionPassManager::~FunctionPassManager() {
1227 /// add - Add a pass to the queue of passes to run. This passes
1228 /// ownership of the Pass to the PassManager. When the
1229 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1230 /// there is no need to delete the pass. (TODO delete passes.)
1231 /// This implies that all passes MUST be allocated with 'new'.
1232 void FunctionPassManager::add(Pass *P) {
1236 /// run - Execute all of the passes scheduled for execution. Keep
1237 /// track of whether any of the passes modifies the function, and if
1238 /// so, return true.
1240 bool FunctionPassManager::run(Function &F) {
1242 if (MP->materializeFunction(&F, &errstr)) {
1243 cerr << "Error reading bitcode file: " << errstr << "\n";
1250 /// doInitialization - Run all of the initializers for the function passes.
1252 bool FunctionPassManager::doInitialization() {
1253 return FPM->doInitialization(*MP->getModule());
1256 /// doFinalization - Run all of the finalizers for the function passes.
1258 bool FunctionPassManager::doFinalization() {
1259 return FPM->doFinalization(*MP->getModule());
1262 //===----------------------------------------------------------------------===//
1263 // FunctionPassManagerImpl implementation
1265 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1266 bool Changed = false;
1268 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1269 Changed |= getContainedManager(Index)->doInitialization(M);
1274 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1275 bool Changed = false;
1277 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1278 Changed |= getContainedManager(Index)->doFinalization(M);
1283 /// cleanup - After running all passes, clean up pass manager cache.
1284 void FPPassManager::cleanup() {
1285 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1286 FunctionPass *FP = getContainedPass(Index);
1287 AnalysisResolver *AR = FP->getResolver();
1288 assert(AR && "Analysis Resolver is not set");
1289 AR->clearAnalysisImpls();
1293 // Execute all the passes managed by this top level manager.
1294 // Return true if any function is modified by a pass.
1295 bool FunctionPassManagerImpl::run(Function &F) {
1296 bool Changed = false;
1297 TimingInfo::createTheTimeInfo();
1302 initializeAllAnalysisInfo();
1303 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1304 Changed |= getContainedManager(Index)->runOnFunction(F);
1306 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1307 getContainedManager(Index)->cleanup();
1312 //===----------------------------------------------------------------------===//
1313 // FPPassManager implementation
1315 char FPPassManager::ID = 0;
1316 /// Print passes managed by this manager
1317 void FPPassManager::dumpPassStructure(unsigned Offset) {
1318 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1319 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1320 FunctionPass *FP = getContainedPass(Index);
1321 FP->dumpPassStructure(Offset + 1);
1322 dumpLastUses(FP, Offset+1);
1327 /// Execute all of the passes scheduled for execution by invoking
1328 /// runOnFunction method. Keep track of whether any of the passes modifies
1329 /// the function, and if so, return true.
1330 bool FPPassManager::runOnFunction(Function &F) {
1331 if (F.isDeclaration())
1334 bool Changed = false;
1336 // Collect inherited analysis from Module level pass manager.
1337 populateInheritedAnalysis(TPM->activeStack);
1339 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1340 FunctionPass *FP = getContainedPass(Index);
1342 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1343 dumpRequiredSet(FP);
1345 initializeAnalysisImpl(FP);
1348 PassManagerPrettyStackEntry X(FP, F);
1350 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1351 Changed |= FP->runOnFunction(F);
1352 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1356 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1357 dumpPreservedSet(FP);
1359 verifyPreservedAnalysis(FP);
1360 removeNotPreservedAnalysis(FP);
1361 recordAvailableAnalysis(FP);
1362 removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1364 // If dominator information is available then verify the info if requested.
1365 verifyDomInfo(*FP, F);
1370 bool FPPassManager::runOnModule(Module &M) {
1371 bool Changed = doInitialization(M);
1373 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1376 return Changed |= doFinalization(M);
1379 bool FPPassManager::doInitialization(Module &M) {
1380 bool Changed = false;
1382 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1383 Changed |= getContainedPass(Index)->doInitialization(M);
1388 bool FPPassManager::doFinalization(Module &M) {
1389 bool Changed = false;
1391 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1392 Changed |= getContainedPass(Index)->doFinalization(M);
1397 //===----------------------------------------------------------------------===//
1398 // MPPassManager implementation
1400 /// Execute all of the passes scheduled for execution by invoking
1401 /// runOnModule method. Keep track of whether any of the passes modifies
1402 /// the module, and if so, return true.
1404 MPPassManager::runOnModule(Module &M) {
1405 bool Changed = false;
1407 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1408 ModulePass *MP = getContainedPass(Index);
1410 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1411 M.getModuleIdentifier().c_str());
1412 dumpRequiredSet(MP);
1414 initializeAnalysisImpl(MP);
1417 PassManagerPrettyStackEntry X(MP, M);
1418 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1419 Changed |= MP->runOnModule(M);
1420 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1424 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1425 M.getModuleIdentifier().c_str());
1426 dumpPreservedSet(MP);
1428 verifyPreservedAnalysis(MP);
1429 removeNotPreservedAnalysis(MP);
1430 recordAvailableAnalysis(MP);
1431 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
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");
1470 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1474 //===----------------------------------------------------------------------===//
1475 // PassManagerImpl implementation
1477 /// run - Execute all of the passes scheduled for execution. Keep track of
1478 /// whether any of the passes modifies the module, and if so, return true.
1479 bool PassManagerImpl::run(Module &M) {
1480 bool Changed = false;
1481 TimingInfo::createTheTimeInfo();
1486 initializeAllAnalysisInfo();
1487 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1488 Changed |= getContainedManager(Index)->runOnModule(M);
1492 //===----------------------------------------------------------------------===//
1493 // PassManager implementation
1495 /// Create new pass manager
1496 PassManager::PassManager() {
1497 PM = new PassManagerImpl(0);
1498 // PM is the top level manager
1499 PM->setTopLevelManager(PM);
1502 PassManager::~PassManager() {
1506 /// add - Add a pass to the queue of passes to run. This passes ownership of
1507 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1508 /// will be destroyed as well, so there is no need to delete the pass. This
1509 /// implies that all passes MUST be allocated with 'new'.
1510 void PassManager::add(Pass *P) {
1514 /// run - Execute all of the passes scheduled for execution. Keep track of
1515 /// whether any of the passes modifies the module, and if so, return true.
1516 bool PassManager::run(Module &M) {
1520 //===----------------------------------------------------------------------===//
1521 // TimingInfo Class - This class is used to calculate information about the
1522 // amount of time each pass takes to execute. This only happens with
1523 // -time-passes is enabled on the command line.
1525 bool llvm::TimePassesIsEnabled = false;
1526 static cl::opt<bool,true>
1527 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1528 cl::desc("Time each pass, printing elapsed time for each on exit"));
1530 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1531 // a non null value (if the -time-passes option is enabled) or it leaves it
1532 // null. It may be called multiple times.
1533 void TimingInfo::createTheTimeInfo() {
1534 if (!TimePassesIsEnabled || TheTimeInfo) return;
1536 // Constructed the first time this is called, iff -time-passes is enabled.
1537 // This guarantees that the object will be constructed before static globals,
1538 // thus it will be destroyed before them.
1539 static ManagedStatic<TimingInfo> TTI;
1540 TheTimeInfo = &*TTI;
1543 /// If TimingInfo is enabled then start pass timer.
1544 void StartPassTimer(Pass *P) {
1546 TheTimeInfo->passStarted(P);
1549 /// If TimingInfo is enabled then stop pass timer.
1550 void StopPassTimer(Pass *P) {
1552 TheTimeInfo->passEnded(P);
1555 //===----------------------------------------------------------------------===//
1556 // PMStack implementation
1559 // Pop Pass Manager from the stack and clear its analysis info.
1560 void PMStack::pop() {
1562 PMDataManager *Top = this->top();
1563 Top->initializeAnalysisInfo();
1568 // Push PM on the stack and set its top level manager.
1569 void PMStack::push(PMDataManager *PM) {
1570 assert(PM && "Unable to push. Pass Manager expected");
1572 if (!this->empty()) {
1573 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1575 assert(TPM && "Unable to find top level manager");
1576 TPM->addIndirectPassManager(PM);
1577 PM->setTopLevelManager(TPM);
1583 // Dump content of the pass manager stack.
1584 void PMStack::dump() {
1585 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1586 E = S.end(); I != E; ++I)
1587 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1593 /// Find appropriate Module Pass Manager in the PM Stack and
1594 /// add self into that manager.
1595 void ModulePass::assignPassManager(PMStack &PMS,
1596 PassManagerType PreferredType) {
1597 // Find Module Pass Manager
1598 while(!PMS.empty()) {
1599 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1600 if (TopPMType == PreferredType)
1601 break; // We found desired pass manager
1602 else if (TopPMType > PMT_ModulePassManager)
1603 PMS.pop(); // Pop children pass managers
1607 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1608 PMS.top()->add(this);
1611 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1612 /// in the PM Stack and add self into that manager.
1613 void FunctionPass::assignPassManager(PMStack &PMS,
1614 PassManagerType PreferredType) {
1616 // Find Module Pass Manager
1617 while(!PMS.empty()) {
1618 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1623 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1625 // Create new Function Pass Manager
1627 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1628 PMDataManager *PMD = PMS.top();
1630 // [1] Create new Function Pass Manager
1631 FPP = new FPPassManager(PMD->getDepth() + 1);
1632 FPP->populateInheritedAnalysis(PMS);
1634 // [2] Set up new manager's top level manager
1635 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1636 TPM->addIndirectPassManager(FPP);
1638 // [3] Assign manager to manage this new manager. This may create
1639 // and push new managers into PMS
1640 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1642 // [4] Push new manager into PMS
1646 // Assign FPP as the manager of this pass.
1650 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1651 /// in the PM Stack and add self into that manager.
1652 void BasicBlockPass::assignPassManager(PMStack &PMS,
1653 PassManagerType PreferredType) {
1654 BBPassManager *BBP = NULL;
1656 // Basic Pass Manager is a leaf pass manager. It does not handle
1657 // any other pass manager.
1659 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1661 // If leaf manager is not Basic Block Pass manager then create new
1662 // basic Block Pass manager.
1665 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1666 PMDataManager *PMD = PMS.top();
1668 // [1] Create new Basic Block Manager
1669 BBP = new BBPassManager(PMD->getDepth() + 1);
1671 // [2] Set up new manager's top level manager
1672 // Basic Block Pass Manager does not live by itself
1673 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1674 TPM->addIndirectPassManager(BBP);
1676 // [3] Assign manager to manage this new manager. This may create
1677 // and push new managers into PMS
1678 BBP->assignPassManager(PMS);
1680 // [4] Push new manager into PMS
1684 // Assign BBP as the manager of this pass.
1688 PassManagerBase::~PassManagerBase() {}
1690 /*===-- C Bindings --------------------------------------------------------===*/
1692 LLVMPassManagerRef LLVMCreatePassManager() {
1693 return wrap(new PassManager());
1696 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1697 return wrap(new FunctionPassManager(unwrap(P)));
1700 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1701 return unwrap<PassManager>(PM)->run(*unwrap(M));
1704 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1705 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1708 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1709 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1712 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1713 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1716 void LLVMDisposePassManager(LLVMPassManagerRef PM) {