1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Timer.h"
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm-c/Core.h"
30 // See PassManagers.h for Pass Manager infrastructure overview.
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
41 // Different debug levels that can be enabled...
43 None, Arguments, Structure, Executions, Details
46 bool VerifyDomInfo = false;
47 static cl::opt<bool,true>
48 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
49 cl::desc("Verify dominator info (time consuming)"));
51 static cl::opt<enum PassDebugLevel>
52 PassDebugging("debug-pass", cl::Hidden,
53 cl::desc("Print PassManager debugging information"),
55 clEnumVal(None , "disable debug output"),
56 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
57 clEnumVal(Structure , "print pass structure before run()"),
58 clEnumVal(Executions, "print pass name before it is executed"),
59 clEnumVal(Details , "print pass details when it is executed"),
61 } // End of llvm namespace
63 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
65 OS << "Releasing pass '";
67 OS << "Running pass '";
69 OS << P->getPassName() << "'";
72 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
80 std::string Name = V->getNameStr();
83 else if (isa<GlobalValue>(V))
89 OS << " on function '" << Name << "'\n";
90 else if (isa<BasicBlock>(V))
91 OS << " on basic block '" << Name << "'\n";
93 OS << " on value '" << Name << "'\n";
99 //===----------------------------------------------------------------------===//
102 /// BBPassManager manages BasicBlockPass. It batches all the
103 /// pass together and sequence them to process one basic block before
104 /// processing next basic block.
105 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
106 public FunctionPass {
110 explicit BBPassManager(int Depth)
111 : PMDataManager(Depth), FunctionPass(&ID) {}
113 /// Execute all of the passes scheduled for execution. Keep track of
114 /// whether any of the passes modifies the function, and if so, return true.
115 bool runOnFunction(Function &F);
117 /// Pass Manager itself does not invalidate any analysis info.
118 void getAnalysisUsage(AnalysisUsage &Info) const {
119 Info.setPreservesAll();
122 bool doInitialization(Module &M);
123 bool doInitialization(Function &F);
124 bool doFinalization(Module &M);
125 bool doFinalization(Function &F);
127 virtual const char *getPassName() const {
128 return "BasicBlock Pass Manager";
131 // Print passes managed by this manager
132 void dumpPassStructure(unsigned Offset) {
133 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
134 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
135 BasicBlockPass *BP = getContainedPass(Index);
136 BP->dumpPassStructure(Offset + 1);
137 dumpLastUses(BP, Offset+1);
141 BasicBlockPass *getContainedPass(unsigned N) {
142 assert(N < PassVector.size() && "Pass number out of range!");
143 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
147 virtual PassManagerType getPassManagerType() const {
148 return PMT_BasicBlockPassManager;
152 char BBPassManager::ID = 0;
157 //===----------------------------------------------------------------------===//
158 // FunctionPassManagerImpl
160 /// FunctionPassManagerImpl manages FPPassManagers
161 class FunctionPassManagerImpl : public Pass,
162 public PMDataManager,
163 public PMTopLevelManager {
166 explicit FunctionPassManagerImpl(int Depth) :
167 Pass(&ID), PMDataManager(Depth),
168 PMTopLevelManager(TLM_Function) { }
170 /// add - Add a pass to the queue of passes to run. This passes ownership of
171 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
172 /// will be destroyed as well, so there is no need to delete the pass. This
173 /// implies that all passes MUST be allocated with 'new'.
178 /// run - Execute all of the passes scheduled for execution. Keep track of
179 /// whether any of the passes modifies the module, and if so, return true.
180 bool run(Function &F);
182 /// doInitialization - Run all of the initializers for the function passes.
184 bool doInitialization(Module &M);
186 /// doFinalization - Run all of the finalizers for the function passes.
188 bool doFinalization(Module &M);
190 /// Pass Manager itself does not invalidate any analysis info.
191 void getAnalysisUsage(AnalysisUsage &Info) const {
192 Info.setPreservesAll();
195 inline void addTopLevelPass(Pass *P) {
197 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
199 // P is a immutable pass and it will be managed by this
200 // top level manager. Set up analysis resolver to connect them.
201 AnalysisResolver *AR = new AnalysisResolver(*this);
203 initializeAnalysisImpl(P);
204 addImmutablePass(IP);
205 recordAvailableAnalysis(IP);
207 P->assignPassManager(activeStack);
212 FPPassManager *getContainedManager(unsigned N) {
213 assert(N < PassManagers.size() && "Pass number out of range!");
214 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
219 char FunctionPassManagerImpl::ID = 0;
220 //===----------------------------------------------------------------------===//
223 /// MPPassManager manages ModulePasses and function pass managers.
224 /// It batches all Module passes and function pass managers together and
225 /// sequences them to process one module.
226 class MPPassManager : public Pass, public PMDataManager {
229 explicit MPPassManager(int Depth) :
230 Pass(&ID), PMDataManager(Depth) { }
232 // Delete on the fly managers.
233 virtual ~MPPassManager() {
234 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
235 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
237 FunctionPassManagerImpl *FPP = I->second;
242 /// run - Execute all of the passes scheduled for execution. Keep track of
243 /// whether any of the passes modifies the module, and if so, return true.
244 bool runOnModule(Module &M);
246 /// Pass Manager itself does not invalidate any analysis info.
247 void getAnalysisUsage(AnalysisUsage &Info) const {
248 Info.setPreservesAll();
251 /// Add RequiredPass into list of lower level passes required by pass P.
252 /// RequiredPass is run on the fly by Pass Manager when P requests it
253 /// through getAnalysis interface.
254 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
256 /// Return function pass corresponding to PassInfo PI, that is
257 /// required by module pass MP. Instantiate analysis pass, by using
258 /// its runOnFunction() for function F.
259 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
261 virtual const char *getPassName() const {
262 return "Module Pass Manager";
265 // Print passes managed by this manager
266 void dumpPassStructure(unsigned Offset) {
267 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
268 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
269 ModulePass *MP = getContainedPass(Index);
270 MP->dumpPassStructure(Offset + 1);
271 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
272 FPP->dumpPassStructure(Offset + 2);
273 dumpLastUses(MP, Offset+1);
277 ModulePass *getContainedPass(unsigned N) {
278 assert(N < PassVector.size() && "Pass number out of range!");
279 return static_cast<ModulePass *>(PassVector[N]);
282 virtual PassManagerType getPassManagerType() const {
283 return PMT_ModulePassManager;
287 /// Collection of on the fly FPPassManagers. These managers manage
288 /// function passes that are required by module passes.
289 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
292 char MPPassManager::ID = 0;
293 //===----------------------------------------------------------------------===//
297 /// PassManagerImpl manages MPPassManagers
298 class PassManagerImpl : public Pass,
299 public PMDataManager,
300 public PMTopLevelManager {
304 explicit PassManagerImpl(int Depth) :
305 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
307 /// add - Add a pass to the queue of passes to run. This passes ownership of
308 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
309 /// will be destroyed as well, so there is no need to delete the pass. This
310 /// implies that all passes MUST be allocated with 'new'.
315 /// run - Execute all of the passes scheduled for execution. Keep track of
316 /// whether any of the passes modifies the module, and if so, return true.
319 /// Pass Manager itself does not invalidate any analysis info.
320 void getAnalysisUsage(AnalysisUsage &Info) const {
321 Info.setPreservesAll();
324 inline void addTopLevelPass(Pass *P) {
325 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
327 // P is a immutable pass and it will be managed by this
328 // top level manager. Set up analysis resolver to connect them.
329 AnalysisResolver *AR = new AnalysisResolver(*this);
331 initializeAnalysisImpl(P);
332 addImmutablePass(IP);
333 recordAvailableAnalysis(IP);
335 P->assignPassManager(activeStack);
339 MPPassManager *getContainedManager(unsigned N) {
340 assert(N < PassManagers.size() && "Pass number out of range!");
341 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
346 char PassManagerImpl::ID = 0;
347 } // End of llvm namespace
351 //===----------------------------------------------------------------------===//
352 /// TimingInfo Class - This class is used to calculate information about the
353 /// amount of time each pass takes to execute. This only happens when
354 /// -time-passes is enabled on the command line.
356 class VISIBILITY_HIDDEN TimingInfo {
357 std::map<Pass*, Timer> TimingData;
361 // Use 'create' member to get this.
362 TimingInfo() : TG("... Pass execution timing report ...") {}
364 // TimingDtor - Print out information about timing information
366 // Delete all of the timers...
368 // TimerGroup is deleted next, printing the report.
371 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
372 // to a non null value (if the -time-passes option is enabled) or it leaves it
373 // null. It may be called multiple times.
374 static void createTheTimeInfo();
376 void passStarted(Pass *P) {
377 if (dynamic_cast<PMDataManager *>(P))
380 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
381 if (I == TimingData.end())
382 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
383 I->second.startTimer();
385 void passEnded(Pass *P) {
386 if (dynamic_cast<PMDataManager *>(P))
389 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
390 assert(I != TimingData.end() && "passStarted/passEnded not nested right!");
391 I->second.stopTimer();
395 } // End of anon namespace
397 static TimingInfo *TheTimeInfo;
399 //===----------------------------------------------------------------------===//
400 // PMTopLevelManager implementation
402 /// Initialize top level manager. Create first pass manager.
403 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
405 MPPassManager *MPP = new MPPassManager(1);
406 MPP->setTopLevelManager(this);
408 activeStack.push(MPP);
409 } else if (t == TLM_Function) {
410 FPPassManager *FPP = new FPPassManager(1);
411 FPP->setTopLevelManager(this);
413 activeStack.push(FPP);
417 /// Set pass P as the last user of the given analysis passes.
418 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
420 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
421 E = AnalysisPasses.end(); I != E; ++I) {
428 // If AP is the last user of other passes then make P last user of
430 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
431 LUE = LastUser.end(); LUI != LUE; ++LUI) {
432 if (LUI->second == AP)
433 // DenseMap iterator is not invalidated here because
434 // this is just updating exisitng entry.
435 LastUser[LUI->first] = P;
440 /// Collect passes whose last user is P
441 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
443 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
444 InversedLastUser.find(P);
445 if (DMI == InversedLastUser.end())
448 SmallPtrSet<Pass *, 8> &LU = DMI->second;
449 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
450 E = LU.end(); I != E; ++I) {
451 LastUses.push_back(*I);
456 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
457 AnalysisUsage *AnUsage = NULL;
458 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
459 if (DMI != AnUsageMap.end())
460 AnUsage = DMI->second;
462 AnUsage = new AnalysisUsage();
463 P->getAnalysisUsage(*AnUsage);
464 AnUsageMap[P] = AnUsage;
469 /// Schedule pass P for execution. Make sure that passes required by
470 /// P are run before P is run. Update analysis info maintained by
471 /// the manager. Remove dead passes. This is a recursive function.
472 void PMTopLevelManager::schedulePass(Pass *P) {
474 // TODO : Allocate function manager for this pass, other wise required set
475 // may be inserted into previous function manager
477 // Give pass a chance to prepare the stage.
478 P->preparePassManager(activeStack);
480 // If P is an analysis pass and it is available then do not
481 // generate the analysis again. Stale analysis info should not be
482 // available at this point.
483 if (P->getPassInfo() &&
484 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
489 AnalysisUsage *AnUsage = findAnalysisUsage(P);
491 bool checkAnalysis = true;
492 while (checkAnalysis) {
493 checkAnalysis = false;
495 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
496 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
497 E = RequiredSet.end(); I != E; ++I) {
499 Pass *AnalysisPass = findAnalysisPass(*I);
501 AnalysisPass = (*I)->createPass();
502 if (P->getPotentialPassManagerType () ==
503 AnalysisPass->getPotentialPassManagerType())
504 // Schedule analysis pass that is managed by the same pass manager.
505 schedulePass(AnalysisPass);
506 else if (P->getPotentialPassManagerType () >
507 AnalysisPass->getPotentialPassManagerType()) {
508 // Schedule analysis pass that is managed by a new manager.
509 schedulePass(AnalysisPass);
510 // Recheck analysis passes to ensure that required analysises that
511 // are already checked are still available.
512 checkAnalysis = true;
515 // Do not schedule this analysis. Lower level analsyis
516 // passes are run on the fly.
522 // Now all required passes are available.
526 /// Find the pass that implements Analysis AID. Search immutable
527 /// passes and all pass managers. If desired pass is not found
528 /// then return NULL.
529 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
532 // Check pass managers
533 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
534 E = PassManagers.end(); P == NULL && I != E; ++I) {
535 PMDataManager *PMD = *I;
536 P = PMD->findAnalysisPass(AID, false);
539 // Check other pass managers
540 for (SmallVector<PMDataManager *, 8>::iterator
541 I = IndirectPassManagers.begin(),
542 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
543 P = (*I)->findAnalysisPass(AID, false);
545 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
546 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
547 const PassInfo *PI = (*I)->getPassInfo();
551 // If Pass not found then check the interfaces implemented by Immutable Pass
553 const std::vector<const PassInfo*> &ImmPI =
554 PI->getInterfacesImplemented();
555 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
563 // Print passes managed by this top level manager.
564 void PMTopLevelManager::dumpPasses() const {
566 if (PassDebugging < Structure)
569 // Print out the immutable passes
570 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
571 ImmutablePasses[i]->dumpPassStructure(0);
574 // Every class that derives from PMDataManager also derives from Pass
575 // (sometimes indirectly), but there's no inheritance relationship
576 // between PMDataManager and Pass, so we have to dynamic_cast to get
577 // from a PMDataManager* to a Pass*.
578 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
579 E = PassManagers.end(); I != E; ++I)
580 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
583 void PMTopLevelManager::dumpArguments() const {
585 if (PassDebugging < Arguments)
588 cerr << "Pass Arguments: ";
589 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
590 E = PassManagers.end(); I != E; ++I)
591 (*I)->dumpPassArguments();
595 void PMTopLevelManager::initializeAllAnalysisInfo() {
596 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
597 E = PassManagers.end(); I != E; ++I)
598 (*I)->initializeAnalysisInfo();
600 // Initailize other pass managers
601 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
602 E = IndirectPassManagers.end(); I != E; ++I)
603 (*I)->initializeAnalysisInfo();
605 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
606 DME = LastUser.end(); DMI != DME; ++DMI) {
607 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
608 InversedLastUser.find(DMI->second);
609 if (InvDMI != InversedLastUser.end()) {
610 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
611 L.insert(DMI->first);
613 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
614 InversedLastUser[DMI->second] = L;
620 PMTopLevelManager::~PMTopLevelManager() {
621 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
622 E = PassManagers.end(); I != E; ++I)
625 for (SmallVector<ImmutablePass *, 8>::iterator
626 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
629 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
630 DME = AnUsageMap.end(); DMI != DME; ++DMI)
634 //===----------------------------------------------------------------------===//
635 // PMDataManager implementation
637 /// Augement AvailableAnalysis by adding analysis made available by pass P.
638 void PMDataManager::recordAvailableAnalysis(Pass *P) {
639 const PassInfo *PI = P->getPassInfo();
642 AvailableAnalysis[PI] = P;
644 //This pass is the current implementation of all of the interfaces it
645 //implements as well.
646 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
647 for (unsigned i = 0, e = II.size(); i != e; ++i)
648 AvailableAnalysis[II[i]] = P;
651 // Return true if P preserves high level analysis used by other
652 // passes managed by this manager
653 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
654 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
655 if (AnUsage->getPreservesAll())
658 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
659 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
660 E = HigherLevelAnalysis.end(); I != E; ++I) {
662 if (!dynamic_cast<ImmutablePass*>(P1) &&
663 std::find(PreservedSet.begin(), PreservedSet.end(),
664 P1->getPassInfo()) ==
672 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
673 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
674 // Don't do this unless assertions are enabled.
678 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
679 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
681 // Verify preserved analysis
682 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
683 E = PreservedSet.end(); I != E; ++I) {
685 if (Pass *AP = findAnalysisPass(AID, true))
686 AP->verifyAnalysis();
690 /// verifyDomInfo - Verify dominator information if it is available.
691 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
692 if (!VerifyDomInfo || !P.getResolver())
695 DominatorTree *DT = P.getAnalysisIfAvailable<DominatorTree>();
699 DominatorTree OtherDT;
700 OtherDT.getBase().recalculate(F);
701 if (DT->compare(OtherDT)) {
702 cerr << "Dominator Information for " << F.getNameStart() << "\n";
703 cerr << "Pass '" << P.getPassName() << "'\n";
704 cerr << "----- Valid -----\n";
706 cerr << "----- Invalid -----\n";
708 assert(0 && "Invalid dominator info");
711 DominanceFrontier *DF = P.getAnalysisIfAvailable<DominanceFrontier>();
715 DominanceFrontier OtherDF;
716 std::vector<BasicBlock*> DTRoots = DT->getRoots();
717 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
718 if (DF->compare(OtherDF)) {
719 cerr << "Dominator Information for " << F.getNameStart() << "\n";
720 cerr << "Pass '" << P.getPassName() << "'\n";
721 cerr << "----- Valid -----\n";
723 cerr << "----- Invalid -----\n";
725 assert(0 && "Invalid dominator info");
729 /// Remove Analysis not preserved by Pass P
730 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
731 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
732 if (AnUsage->getPreservesAll())
735 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
736 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
737 E = AvailableAnalysis.end(); I != E; ) {
738 std::map<AnalysisID, Pass*>::iterator Info = I++;
739 if (!dynamic_cast<ImmutablePass*>(Info->second)
740 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
741 PreservedSet.end()) {
742 // Remove this analysis
743 if (PassDebugging >= Details) {
744 Pass *S = Info->second;
745 cerr << " -- '" << P->getPassName() << "' is not preserving '";
746 cerr << S->getPassName() << "'\n";
748 AvailableAnalysis.erase(Info);
752 // Check inherited analysis also. If P is not preserving analysis
753 // provided by parent manager then remove it here.
754 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
756 if (!InheritedAnalysis[Index])
759 for (std::map<AnalysisID, Pass*>::iterator
760 I = InheritedAnalysis[Index]->begin(),
761 E = InheritedAnalysis[Index]->end(); I != E; ) {
762 std::map<AnalysisID, Pass *>::iterator Info = I++;
763 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
764 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
766 // Remove this analysis
767 InheritedAnalysis[Index]->erase(Info);
772 /// Remove analysis passes that are not used any longer
773 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
774 enum PassDebuggingString DBG_STR) {
776 SmallVector<Pass *, 12> DeadPasses;
778 // If this is a on the fly manager then it does not have TPM.
782 TPM->collectLastUses(DeadPasses, P);
784 if (PassDebugging >= Details && !DeadPasses.empty()) {
785 cerr << " -*- '" << P->getPassName();
786 cerr << "' is the last user of following pass instances.";
787 cerr << " Free these instances\n";
790 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
791 E = DeadPasses.end(); I != E; ++I) {
793 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
796 // If the pass crashes releasing memory, remember this.
797 PassManagerPrettyStackEntry X(*I);
799 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
800 (*I)->releaseMemory();
801 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
803 if (const PassInfo *PI = (*I)->getPassInfo()) {
804 std::map<AnalysisID, Pass*>::iterator Pos =
805 AvailableAnalysis.find(PI);
807 // It is possible that pass is already removed from the AvailableAnalysis
808 if (Pos != AvailableAnalysis.end())
809 AvailableAnalysis.erase(Pos);
811 // Remove all interfaces this pass implements, for which it is also
812 // listed as the available implementation.
813 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
814 for (unsigned i = 0, e = II.size(); i != e; ++i) {
815 Pos = AvailableAnalysis.find(II[i]);
816 if (Pos != AvailableAnalysis.end() && Pos->second == *I)
817 AvailableAnalysis.erase(Pos);
823 /// Add pass P into the PassVector. Update
824 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
825 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
826 // This manager is going to manage pass P. Set up analysis resolver
828 AnalysisResolver *AR = new AnalysisResolver(*this);
831 // If a FunctionPass F is the last user of ModulePass info M
832 // then the F's manager, not F, records itself as a last user of M.
833 SmallVector<Pass *, 12> TransferLastUses;
835 if (!ProcessAnalysis) {
837 PassVector.push_back(P);
841 // At the moment, this pass is the last user of all required passes.
842 SmallVector<Pass *, 12> LastUses;
843 SmallVector<Pass *, 8> RequiredPasses;
844 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
846 unsigned PDepth = this->getDepth();
848 collectRequiredAnalysis(RequiredPasses,
849 ReqAnalysisNotAvailable, P);
850 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
851 E = RequiredPasses.end(); I != E; ++I) {
852 Pass *PRequired = *I;
855 assert(PRequired->getResolver() && "Analysis Resolver is not set");
856 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
857 RDepth = DM.getDepth();
859 if (PDepth == RDepth)
860 LastUses.push_back(PRequired);
861 else if (PDepth > RDepth) {
862 // Let the parent claim responsibility of last use
863 TransferLastUses.push_back(PRequired);
864 // Keep track of higher level analysis used by this manager.
865 HigherLevelAnalysis.push_back(PRequired);
867 assert(0 && "Unable to accomodate Required Pass");
870 // Set P as P's last user until someone starts using P.
871 // However, if P is a Pass Manager then it does not need
872 // to record its last user.
873 if (!dynamic_cast<PMDataManager *>(P))
874 LastUses.push_back(P);
875 TPM->setLastUser(LastUses, P);
877 if (!TransferLastUses.empty()) {
878 Pass *My_PM = dynamic_cast<Pass *>(this);
879 TPM->setLastUser(TransferLastUses, My_PM);
880 TransferLastUses.clear();
883 // Now, take care of required analysises that are not available.
884 for (SmallVector<AnalysisID, 8>::iterator
885 I = ReqAnalysisNotAvailable.begin(),
886 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
887 Pass *AnalysisPass = (*I)->createPass();
888 this->addLowerLevelRequiredPass(P, AnalysisPass);
891 // Take a note of analysis required and made available by this pass.
892 // Remove the analysis not preserved by this pass
893 removeNotPreservedAnalysis(P);
894 recordAvailableAnalysis(P);
897 PassVector.push_back(P);
901 /// Populate RP with analysis pass that are required by
902 /// pass P and are available. Populate RP_NotAvail with analysis
903 /// pass that are required by pass P but are not available.
904 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
905 SmallVector<AnalysisID, 8> &RP_NotAvail,
907 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
908 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
909 for (AnalysisUsage::VectorType::const_iterator
910 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
911 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
912 RP.push_back(AnalysisPass);
914 RP_NotAvail.push_back(*I);
917 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
918 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
919 E = IDs.end(); I != E; ++I) {
920 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
921 RP.push_back(AnalysisPass);
923 RP_NotAvail.push_back(*I);
927 // All Required analyses should be available to the pass as it runs! Here
928 // we fill in the AnalysisImpls member of the pass so that it can
929 // successfully use the getAnalysis() method to retrieve the
930 // implementations it needs.
932 void PMDataManager::initializeAnalysisImpl(Pass *P) {
933 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
935 for (AnalysisUsage::VectorType::const_iterator
936 I = AnUsage->getRequiredSet().begin(),
937 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
938 Pass *Impl = findAnalysisPass(*I, true);
940 // This may be analysis pass that is initialized on the fly.
941 // If that is not the case then it will raise an assert when it is used.
943 AnalysisResolver *AR = P->getResolver();
944 assert(AR && "Analysis Resolver is not set");
945 AR->addAnalysisImplsPair(*I, Impl);
949 /// Find the pass that implements Analysis AID. If desired pass is not found
950 /// then return NULL.
951 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
953 // Check if AvailableAnalysis map has one entry.
954 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
956 if (I != AvailableAnalysis.end())
959 // Search Parents through TopLevelManager
961 return TPM->findAnalysisPass(AID);
966 // Print list of passes that are last used by P.
967 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
969 SmallVector<Pass *, 12> LUses;
971 // If this is a on the fly manager then it does not have TPM.
975 TPM->collectLastUses(LUses, P);
977 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
978 E = LUses.end(); I != E; ++I) {
979 llvm::cerr << "--" << std::string(Offset*2, ' ');
980 (*I)->dumpPassStructure(0);
984 void PMDataManager::dumpPassArguments() const {
985 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
986 E = PassVector.end(); I != E; ++I) {
987 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
988 PMD->dumpPassArguments();
990 if (const PassInfo *PI = (*I)->getPassInfo())
991 if (!PI->isAnalysisGroup())
992 cerr << " -" << PI->getPassArgument();
996 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
997 enum PassDebuggingString S2,
999 if (PassDebugging < Executions)
1001 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
1004 cerr << "Executing Pass '" << P->getPassName();
1006 case MODIFICATION_MSG:
1007 cerr << "Made Modification '" << P->getPassName();
1010 cerr << " Freeing Pass '" << P->getPassName();
1016 case ON_BASICBLOCK_MSG:
1017 cerr << "' on BasicBlock '" << Msg << "'...\n";
1019 case ON_FUNCTION_MSG:
1020 cerr << "' on Function '" << Msg << "'...\n";
1023 cerr << "' on Module '" << Msg << "'...\n";
1026 cerr << "' on Loop " << Msg << "'...\n";
1029 cerr << "' on Call Graph " << Msg << "'...\n";
1036 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1037 if (PassDebugging < Details)
1040 AnalysisUsage analysisUsage;
1041 P->getAnalysisUsage(analysisUsage);
1042 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1045 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1046 if (PassDebugging < Details)
1049 AnalysisUsage analysisUsage;
1050 P->getAnalysisUsage(analysisUsage);
1051 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1054 void PMDataManager::dumpAnalysisUsage(const char *Msg, const Pass *P,
1055 const AnalysisUsage::VectorType &Set) const {
1056 assert(PassDebugging >= Details);
1059 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1060 for (unsigned i = 0; i != Set.size(); ++i) {
1062 cerr << " " << Set[i]->getPassName();
1067 /// Add RequiredPass into list of lower level passes required by pass P.
1068 /// RequiredPass is run on the fly by Pass Manager when P requests it
1069 /// through getAnalysis interface.
1070 /// This should be handled by specific pass manager.
1071 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1073 TPM->dumpArguments();
1077 // Module Level pass may required Function Level analysis info
1078 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1079 // to provide this on demand. In that case, in Pass manager terminology,
1080 // module level pass is requiring lower level analysis info managed by
1081 // lower level pass manager.
1083 // When Pass manager is not able to order required analysis info, Pass manager
1084 // checks whether any lower level manager will be able to provide this
1085 // analysis info on demand or not.
1087 cerr << "Unable to schedule '" << RequiredPass->getPassName();
1088 cerr << "' required by '" << P->getPassName() << "'\n";
1090 assert(0 && "Unable to schedule pass");
1094 PMDataManager::~PMDataManager() {
1095 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1096 E = PassVector.end(); I != E; ++I)
1100 //===----------------------------------------------------------------------===//
1101 // NOTE: Is this the right place to define this method ?
1102 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1103 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1104 return PM.findAnalysisPass(ID, dir);
1107 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1109 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1112 //===----------------------------------------------------------------------===//
1113 // BBPassManager implementation
1115 /// Execute all of the passes scheduled for execution by invoking
1116 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1117 /// the function, and if so, return true.
1118 bool BBPassManager::runOnFunction(Function &F) {
1119 if (F.isDeclaration())
1122 bool Changed = doInitialization(F);
1124 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1125 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1126 BasicBlockPass *BP = getContainedPass(Index);
1128 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
1129 dumpRequiredSet(BP);
1131 initializeAnalysisImpl(BP);
1134 // If the pass crashes, remember this.
1135 PassManagerPrettyStackEntry X(BP, *I);
1137 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1138 Changed |= BP->runOnBasicBlock(*I);
1139 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1143 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1145 dumpPreservedSet(BP);
1147 verifyPreservedAnalysis(BP);
1148 removeNotPreservedAnalysis(BP);
1149 recordAvailableAnalysis(BP);
1150 removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
1153 return Changed |= doFinalization(F);
1156 // Implement doInitialization and doFinalization
1157 bool BBPassManager::doInitialization(Module &M) {
1158 bool Changed = false;
1160 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1161 Changed |= getContainedPass(Index)->doInitialization(M);
1166 bool BBPassManager::doFinalization(Module &M) {
1167 bool Changed = false;
1169 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1170 Changed |= getContainedPass(Index)->doFinalization(M);
1175 bool BBPassManager::doInitialization(Function &F) {
1176 bool Changed = false;
1178 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1179 BasicBlockPass *BP = getContainedPass(Index);
1180 Changed |= BP->doInitialization(F);
1186 bool BBPassManager::doFinalization(Function &F) {
1187 bool Changed = false;
1189 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1190 BasicBlockPass *BP = getContainedPass(Index);
1191 Changed |= BP->doFinalization(F);
1198 //===----------------------------------------------------------------------===//
1199 // FunctionPassManager implementation
1201 /// Create new Function pass manager
1202 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1203 FPM = new FunctionPassManagerImpl(0);
1204 // FPM is the top level manager.
1205 FPM->setTopLevelManager(FPM);
1207 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1208 FPM->setResolver(AR);
1213 FunctionPassManager::~FunctionPassManager() {
1217 /// add - Add a pass to the queue of passes to run. This passes
1218 /// ownership of the Pass to the PassManager. When the
1219 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1220 /// there is no need to delete the pass. (TODO delete passes.)
1221 /// This implies that all passes MUST be allocated with 'new'.
1222 void FunctionPassManager::add(Pass *P) {
1226 /// run - Execute all of the passes scheduled for execution. Keep
1227 /// track of whether any of the passes modifies the function, and if
1228 /// so, return true.
1230 bool FunctionPassManager::run(Function &F) {
1232 if (MP->materializeFunction(&F, &errstr)) {
1233 cerr << "Error reading bitcode file: " << errstr << "\n";
1240 /// doInitialization - Run all of the initializers for the function passes.
1242 bool FunctionPassManager::doInitialization() {
1243 return FPM->doInitialization(*MP->getModule());
1246 /// doFinalization - Run all of the finalizers for the function passes.
1248 bool FunctionPassManager::doFinalization() {
1249 return FPM->doFinalization(*MP->getModule());
1252 //===----------------------------------------------------------------------===//
1253 // FunctionPassManagerImpl implementation
1255 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1256 bool Changed = false;
1258 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1259 Changed |= getContainedManager(Index)->doInitialization(M);
1264 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1265 bool Changed = false;
1267 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1268 Changed |= getContainedManager(Index)->doFinalization(M);
1273 // Execute all the passes managed by this top level manager.
1274 // Return true if any function is modified by a pass.
1275 bool FunctionPassManagerImpl::run(Function &F) {
1276 bool Changed = false;
1277 TimingInfo::createTheTimeInfo();
1282 initializeAllAnalysisInfo();
1283 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1284 Changed |= getContainedManager(Index)->runOnFunction(F);
1288 //===----------------------------------------------------------------------===//
1289 // FPPassManager implementation
1291 char FPPassManager::ID = 0;
1292 /// Print passes managed by this manager
1293 void FPPassManager::dumpPassStructure(unsigned Offset) {
1294 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1295 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1296 FunctionPass *FP = getContainedPass(Index);
1297 FP->dumpPassStructure(Offset + 1);
1298 dumpLastUses(FP, Offset+1);
1303 /// Execute all of the passes scheduled for execution by invoking
1304 /// runOnFunction method. Keep track of whether any of the passes modifies
1305 /// the function, and if so, return true.
1306 bool FPPassManager::runOnFunction(Function &F) {
1307 if (F.isDeclaration())
1310 bool Changed = false;
1312 // Collect inherited analysis from Module level pass manager.
1313 populateInheritedAnalysis(TPM->activeStack);
1315 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1316 FunctionPass *FP = getContainedPass(Index);
1318 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1319 dumpRequiredSet(FP);
1321 initializeAnalysisImpl(FP);
1324 PassManagerPrettyStackEntry X(FP, F);
1326 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1327 Changed |= FP->runOnFunction(F);
1328 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1332 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1333 dumpPreservedSet(FP);
1335 verifyPreservedAnalysis(FP);
1336 removeNotPreservedAnalysis(FP);
1337 recordAvailableAnalysis(FP);
1338 removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1340 // If dominator information is available then verify the info if requested.
1341 verifyDomInfo(*FP, F);
1346 bool FPPassManager::runOnModule(Module &M) {
1347 bool Changed = doInitialization(M);
1349 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1352 return Changed |= doFinalization(M);
1355 bool FPPassManager::doInitialization(Module &M) {
1356 bool Changed = false;
1358 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1359 Changed |= getContainedPass(Index)->doInitialization(M);
1364 bool FPPassManager::doFinalization(Module &M) {
1365 bool Changed = false;
1367 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1368 Changed |= getContainedPass(Index)->doFinalization(M);
1373 //===----------------------------------------------------------------------===//
1374 // MPPassManager implementation
1376 /// Execute all of the passes scheduled for execution by invoking
1377 /// runOnModule method. Keep track of whether any of the passes modifies
1378 /// the module, and if so, return true.
1380 MPPassManager::runOnModule(Module &M) {
1381 bool Changed = false;
1383 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1384 ModulePass *MP = getContainedPass(Index);
1386 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1387 M.getModuleIdentifier().c_str());
1388 dumpRequiredSet(MP);
1390 initializeAnalysisImpl(MP);
1393 PassManagerPrettyStackEntry X(MP, M);
1394 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1395 Changed |= MP->runOnModule(M);
1396 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1400 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1401 M.getModuleIdentifier().c_str());
1402 dumpPreservedSet(MP);
1404 verifyPreservedAnalysis(MP);
1405 removeNotPreservedAnalysis(MP);
1406 recordAvailableAnalysis(MP);
1407 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1412 /// Add RequiredPass into list of lower level passes required by pass P.
1413 /// RequiredPass is run on the fly by Pass Manager when P requests it
1414 /// through getAnalysis interface.
1415 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1416 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1417 "Unable to handle Pass that requires lower level Analysis pass");
1418 assert((P->getPotentialPassManagerType() <
1419 RequiredPass->getPotentialPassManagerType()) &&
1420 "Unable to handle Pass that requires lower level Analysis pass");
1422 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1424 FPP = new FunctionPassManagerImpl(0);
1425 // FPP is the top level manager.
1426 FPP->setTopLevelManager(FPP);
1428 OnTheFlyManagers[P] = FPP;
1430 FPP->add(RequiredPass);
1432 // Register P as the last user of RequiredPass.
1433 SmallVector<Pass *, 12> LU;
1434 LU.push_back(RequiredPass);
1435 FPP->setLastUser(LU, P);
1438 /// Return function pass corresponding to PassInfo PI, that is
1439 /// required by module pass MP. Instantiate analysis pass, by using
1440 /// its runOnFunction() for function F.
1441 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1442 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1443 assert(FPP && "Unable to find on the fly pass");
1446 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1450 //===----------------------------------------------------------------------===//
1451 // PassManagerImpl implementation
1453 /// run - Execute all of the passes scheduled for execution. Keep track of
1454 /// whether any of the passes modifies the module, and if so, return true.
1455 bool PassManagerImpl::run(Module &M) {
1456 bool Changed = false;
1457 TimingInfo::createTheTimeInfo();
1462 initializeAllAnalysisInfo();
1463 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1464 Changed |= getContainedManager(Index)->runOnModule(M);
1468 //===----------------------------------------------------------------------===//
1469 // PassManager implementation
1471 /// Create new pass manager
1472 PassManager::PassManager() {
1473 PM = new PassManagerImpl(0);
1474 // PM is the top level manager
1475 PM->setTopLevelManager(PM);
1478 PassManager::~PassManager() {
1482 /// add - Add a pass to the queue of passes to run. This passes ownership of
1483 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1484 /// will be destroyed as well, so there is no need to delete the pass. This
1485 /// implies that all passes MUST be allocated with 'new'.
1486 void PassManager::add(Pass *P) {
1490 /// run - Execute all of the passes scheduled for execution. Keep track of
1491 /// whether any of the passes modifies the module, and if so, return true.
1492 bool PassManager::run(Module &M) {
1496 //===----------------------------------------------------------------------===//
1497 // TimingInfo Class - This class is used to calculate information about the
1498 // amount of time each pass takes to execute. This only happens with
1499 // -time-passes is enabled on the command line.
1501 bool llvm::TimePassesIsEnabled = false;
1502 static cl::opt<bool,true>
1503 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1504 cl::desc("Time each pass, printing elapsed time for each on exit"));
1506 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1507 // a non null value (if the -time-passes option is enabled) or it leaves it
1508 // null. It may be called multiple times.
1509 void TimingInfo::createTheTimeInfo() {
1510 if (!TimePassesIsEnabled || TheTimeInfo) return;
1512 // Constructed the first time this is called, iff -time-passes is enabled.
1513 // This guarantees that the object will be constructed before static globals,
1514 // thus it will be destroyed before them.
1515 static ManagedStatic<TimingInfo> TTI;
1516 TheTimeInfo = &*TTI;
1519 /// If TimingInfo is enabled then start pass timer.
1520 void StartPassTimer(Pass *P) {
1522 TheTimeInfo->passStarted(P);
1525 /// If TimingInfo is enabled then stop pass timer.
1526 void StopPassTimer(Pass *P) {
1528 TheTimeInfo->passEnded(P);
1531 //===----------------------------------------------------------------------===//
1532 // PMStack implementation
1535 // Pop Pass Manager from the stack and clear its analysis info.
1536 void PMStack::pop() {
1538 PMDataManager *Top = this->top();
1539 Top->initializeAnalysisInfo();
1544 // Push PM on the stack and set its top level manager.
1545 void PMStack::push(PMDataManager *PM) {
1546 assert(PM && "Unable to push. Pass Manager expected");
1548 if (!this->empty()) {
1549 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1551 assert(TPM && "Unable to find top level manager");
1552 TPM->addIndirectPassManager(PM);
1553 PM->setTopLevelManager(TPM);
1559 // Dump content of the pass manager stack.
1560 void PMStack::dump() {
1561 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1562 E = S.end(); I != E; ++I)
1563 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1569 /// Find appropriate Module Pass Manager in the PM Stack and
1570 /// add self into that manager.
1571 void ModulePass::assignPassManager(PMStack &PMS,
1572 PassManagerType PreferredType) {
1573 // Find Module Pass Manager
1574 while(!PMS.empty()) {
1575 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1576 if (TopPMType == PreferredType)
1577 break; // We found desired pass manager
1578 else if (TopPMType > PMT_ModulePassManager)
1579 PMS.pop(); // Pop children pass managers
1583 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1584 PMS.top()->add(this);
1587 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1588 /// in the PM Stack and add self into that manager.
1589 void FunctionPass::assignPassManager(PMStack &PMS,
1590 PassManagerType PreferredType) {
1592 // Find Module Pass Manager
1593 while(!PMS.empty()) {
1594 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1599 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1601 // Create new Function Pass Manager
1603 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1604 PMDataManager *PMD = PMS.top();
1606 // [1] Create new Function Pass Manager
1607 FPP = new FPPassManager(PMD->getDepth() + 1);
1608 FPP->populateInheritedAnalysis(PMS);
1610 // [2] Set up new manager's top level manager
1611 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1612 TPM->addIndirectPassManager(FPP);
1614 // [3] Assign manager to manage this new manager. This may create
1615 // and push new managers into PMS
1616 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1618 // [4] Push new manager into PMS
1622 // Assign FPP as the manager of this pass.
1626 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1627 /// in the PM Stack and add self into that manager.
1628 void BasicBlockPass::assignPassManager(PMStack &PMS,
1629 PassManagerType PreferredType) {
1630 BBPassManager *BBP = NULL;
1632 // Basic Pass Manager is a leaf pass manager. It does not handle
1633 // any other pass manager.
1635 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1637 // If leaf manager is not Basic Block Pass manager then create new
1638 // basic Block Pass manager.
1641 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1642 PMDataManager *PMD = PMS.top();
1644 // [1] Create new Basic Block Manager
1645 BBP = new BBPassManager(PMD->getDepth() + 1);
1647 // [2] Set up new manager's top level manager
1648 // Basic Block Pass Manager does not live by itself
1649 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1650 TPM->addIndirectPassManager(BBP);
1652 // [3] Assign manager to manage this new manager. This may create
1653 // and push new managers into PMS
1654 BBP->assignPassManager(PMS);
1656 // [4] Push new manager into PMS
1660 // Assign BBP as the manager of this pass.
1664 PassManagerBase::~PassManagerBase() {}
1666 /*===-- C Bindings --------------------------------------------------------===*/
1668 LLVMPassManagerRef LLVMCreatePassManager() {
1669 return wrap(new PassManager());
1672 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1673 return wrap(new FunctionPassManager(unwrap(P)));
1676 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1677 return unwrap<PassManager>(PM)->run(*unwrap(M));
1680 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1681 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1684 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1685 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1688 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1689 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1692 void LLVMDisposePassManager(LLVMPassManagerRef PM) {