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/Analysis/Dominators.h"
23 #include "llvm-c/Core.h"
29 // See PassManagers.h for Pass Manager infrastructure overview.
33 //===----------------------------------------------------------------------===//
34 // Pass debugging information. Often it is useful to find out what pass is
35 // running when a crash occurs in a utility. When this library is compiled with
36 // debugging on, a command line option (--debug-pass) is enabled that causes the
37 // pass name to be printed before it executes.
40 // Different debug levels that can be enabled...
42 None, Arguments, Structure, Executions, Details
45 bool VerifyDomInfo = false;
46 static cl::opt<bool,true>
47 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
48 cl::desc("Verify dominator info (time consuming)"));
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(None , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
60 } // End of llvm namespace
64 //===----------------------------------------------------------------------===//
67 /// BBPassManager manages BasicBlockPass. It batches all the
68 /// pass together and sequence them to process one basic block before
69 /// processing next basic block.
70 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
75 explicit BBPassManager(int Depth)
76 : PMDataManager(Depth), FunctionPass((intptr_t)&ID) {}
78 /// Execute all of the passes scheduled for execution. Keep track of
79 /// whether any of the passes modifies the function, and if so, return true.
80 bool runOnFunction(Function &F);
82 /// Pass Manager itself does not invalidate any analysis info.
83 void getAnalysisUsage(AnalysisUsage &Info) const {
84 Info.setPreservesAll();
87 bool doInitialization(Module &M);
88 bool doInitialization(Function &F);
89 bool doFinalization(Module &M);
90 bool doFinalization(Function &F);
92 virtual const char *getPassName() const {
93 return "BasicBlock Pass Manager";
96 // Print passes managed by this manager
97 void dumpPassStructure(unsigned Offset) {
98 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
99 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
100 BasicBlockPass *BP = getContainedPass(Index);
101 BP->dumpPassStructure(Offset + 1);
102 dumpLastUses(BP, Offset+1);
106 BasicBlockPass *getContainedPass(unsigned N) {
107 assert ( N < PassVector.size() && "Pass number out of range!");
108 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
112 virtual PassManagerType getPassManagerType() const {
113 return PMT_BasicBlockPassManager;
117 char BBPassManager::ID = 0;
122 //===----------------------------------------------------------------------===//
123 // FunctionPassManagerImpl
125 /// FunctionPassManagerImpl manages FPPassManagers
126 class FunctionPassManagerImpl : public Pass,
127 public PMDataManager,
128 public PMTopLevelManager {
131 explicit FunctionPassManagerImpl(int Depth) :
132 Pass((intptr_t)&ID), PMDataManager(Depth),
133 PMTopLevelManager(TLM_Function) { }
135 /// add - Add a pass to the queue of passes to run. This passes ownership of
136 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
137 /// will be destroyed as well, so there is no need to delete the pass. This
138 /// implies that all passes MUST be allocated with 'new'.
143 /// run - Execute all of the passes scheduled for execution. Keep track of
144 /// whether any of the passes modifies the module, and if so, return true.
145 bool run(Function &F);
147 /// doInitialization - Run all of the initializers for the function passes.
149 bool doInitialization(Module &M);
151 /// doFinalization - Run all of the finalizers for the function passes.
153 bool doFinalization(Module &M);
155 /// Pass Manager itself does not invalidate any analysis info.
156 void getAnalysisUsage(AnalysisUsage &Info) const {
157 Info.setPreservesAll();
160 inline void addTopLevelPass(Pass *P) {
162 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
164 // P is a immutable pass and it will be managed by this
165 // top level manager. Set up analysis resolver to connect them.
166 AnalysisResolver *AR = new AnalysisResolver(*this);
168 initializeAnalysisImpl(P);
169 addImmutablePass(IP);
170 recordAvailableAnalysis(IP);
172 P->assignPassManager(activeStack);
177 FPPassManager *getContainedManager(unsigned N) {
178 assert ( N < PassManagers.size() && "Pass number out of range!");
179 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
184 char FunctionPassManagerImpl::ID = 0;
185 //===----------------------------------------------------------------------===//
188 /// MPPassManager manages ModulePasses and function pass managers.
189 /// It batches all Module passes and function pass managers together and
190 /// sequences them to process one module.
191 class MPPassManager : public Pass, public PMDataManager {
195 explicit MPPassManager(int Depth) :
196 Pass((intptr_t)&ID), PMDataManager(Depth) { }
198 // Delete on the fly managers.
199 virtual ~MPPassManager() {
200 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
201 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
203 FunctionPassManagerImpl *FPP = I->second;
208 /// run - Execute all of the passes scheduled for execution. Keep track of
209 /// whether any of the passes modifies the module, and if so, return true.
210 bool runOnModule(Module &M);
212 /// Pass Manager itself does not invalidate any analysis info.
213 void getAnalysisUsage(AnalysisUsage &Info) const {
214 Info.setPreservesAll();
217 /// Add RequiredPass into list of lower level passes required by pass P.
218 /// RequiredPass is run on the fly by Pass Manager when P requests it
219 /// through getAnalysis interface.
220 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
222 /// Return function pass corresponding to PassInfo PI, that is
223 /// required by module pass MP. Instantiate analysis pass, by using
224 /// its runOnFunction() for function F.
225 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
227 virtual const char *getPassName() const {
228 return "Module Pass Manager";
231 // Print passes managed by this manager
232 void dumpPassStructure(unsigned Offset) {
233 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
234 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
235 ModulePass *MP = getContainedPass(Index);
236 MP->dumpPassStructure(Offset + 1);
237 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
238 FPP->dumpPassStructure(Offset + 2);
239 dumpLastUses(MP, Offset+1);
243 ModulePass *getContainedPass(unsigned N) {
244 assert ( N < PassVector.size() && "Pass number out of range!");
245 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
249 virtual PassManagerType getPassManagerType() const {
250 return PMT_ModulePassManager;
254 /// Collection of on the fly FPPassManagers. These managers manage
255 /// function passes that are required by module passes.
256 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
259 char MPPassManager::ID = 0;
260 //===----------------------------------------------------------------------===//
264 /// PassManagerImpl manages MPPassManagers
265 class PassManagerImpl : public Pass,
266 public PMDataManager,
267 public PMTopLevelManager {
271 explicit PassManagerImpl(int Depth) :
272 Pass((intptr_t)&ID), PMDataManager(Depth),
273 PMTopLevelManager(TLM_Pass) { }
275 /// add - Add a pass to the queue of passes to run. This passes ownership of
276 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
277 /// will be destroyed as well, so there is no need to delete the pass. This
278 /// implies that all passes MUST be allocated with 'new'.
283 /// run - Execute all of the passes scheduled for execution. Keep track of
284 /// whether any of the passes modifies the module, and if so, return true.
287 /// Pass Manager itself does not invalidate any analysis info.
288 void getAnalysisUsage(AnalysisUsage &Info) const {
289 Info.setPreservesAll();
292 inline void addTopLevelPass(Pass *P) {
294 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
296 // P is a immutable pass and it will be managed by this
297 // top level manager. Set up analysis resolver to connect them.
298 AnalysisResolver *AR = new AnalysisResolver(*this);
300 initializeAnalysisImpl(P);
301 addImmutablePass(IP);
302 recordAvailableAnalysis(IP);
304 P->assignPassManager(activeStack);
309 MPPassManager *getContainedManager(unsigned N) {
310 assert ( N < PassManagers.size() && "Pass number out of range!");
311 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
317 char PassManagerImpl::ID = 0;
318 } // End of llvm namespace
322 //===----------------------------------------------------------------------===//
323 // TimingInfo Class - This class is used to calculate information about the
324 // amount of time each pass takes to execute. This only happens when
325 // -time-passes is enabled on the command line.
328 class VISIBILITY_HIDDEN TimingInfo {
329 std::map<Pass*, Timer> TimingData;
333 // Use 'create' member to get this.
334 TimingInfo() : TG("... Pass execution timing report ...") {}
336 // TimingDtor - Print out information about timing information
338 // Delete all of the timers...
340 // TimerGroup is deleted next, printing the report.
343 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
344 // to a non null value (if the -time-passes option is enabled) or it leaves it
345 // null. It may be called multiple times.
346 static void createTheTimeInfo();
348 void passStarted(Pass *P) {
350 if (dynamic_cast<PMDataManager *>(P))
353 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
354 if (I == TimingData.end())
355 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
356 I->second.startTimer();
358 void passEnded(Pass *P) {
360 if (dynamic_cast<PMDataManager *>(P))
363 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
364 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
365 I->second.stopTimer();
369 } // End of anon namespace
371 static TimingInfo *TheTimeInfo;
373 //===----------------------------------------------------------------------===//
374 // PMTopLevelManager implementation
376 /// Initialize top level manager. Create first pass manager.
377 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
380 MPPassManager *MPP = new MPPassManager(1);
381 MPP->setTopLevelManager(this);
383 activeStack.push(MPP);
385 else if (t == TLM_Function) {
386 FPPassManager *FPP = new FPPassManager(1);
387 FPP->setTopLevelManager(this);
389 activeStack.push(FPP);
393 /// Set pass P as the last user of the given analysis passes.
394 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
397 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
398 E = AnalysisPasses.end(); I != E; ++I) {
405 // If AP is the last user of other passes then make P last user of
407 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
408 LUE = LastUser.end(); LUI != LUE; ++LUI) {
409 if (LUI->second == AP)
410 // DenseMap iterator is not invalidated here because
411 // this is just updating exisitng entry.
412 LastUser[LUI->first] = P;
417 /// Collect passes whose last user is P
418 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
420 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
421 InversedLastUser.find(P);
422 if (DMI == InversedLastUser.end())
425 SmallPtrSet<Pass *, 8> &LU = DMI->second;
426 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
427 E = LU.end(); I != E; ++I) {
428 LastUses.push_back(*I);
433 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
434 AnalysisUsage *AnUsage = NULL;
435 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
436 if (DMI != AnUsageMap.end())
437 AnUsage = DMI->second;
439 AnUsage = new AnalysisUsage();
440 P->getAnalysisUsage(*AnUsage);
441 AnUsageMap[P] = AnUsage;
446 /// Schedule pass P for execution. Make sure that passes required by
447 /// P are run before P is run. Update analysis info maintained by
448 /// the manager. Remove dead passes. This is a recursive function.
449 void PMTopLevelManager::schedulePass(Pass *P) {
451 // TODO : Allocate function manager for this pass, other wise required set
452 // may be inserted into previous function manager
454 // Give pass a chance to prepare the stage.
455 P->preparePassManager(activeStack);
457 // If P is an analysis pass and it is available then do not
458 // generate the analysis again. Stale analysis info should not be
459 // available at this point.
460 if (P->getPassInfo() &&
461 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo()))
464 AnalysisUsage *AnUsage = findAnalysisUsage(P);
466 bool checkAnalysis = true;
467 while (checkAnalysis) {
468 checkAnalysis = false;
470 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
471 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
472 E = RequiredSet.end(); I != E; ++I) {
474 Pass *AnalysisPass = findAnalysisPass(*I);
476 AnalysisPass = (*I)->createPass();
477 if (P->getPotentialPassManagerType () ==
478 AnalysisPass->getPotentialPassManagerType())
479 // Schedule analysis pass that is managed by the same pass manager.
480 schedulePass(AnalysisPass);
481 else if (P->getPotentialPassManagerType () >
482 AnalysisPass->getPotentialPassManagerType()) {
483 // Schedule analysis pass that is managed by a new manager.
484 schedulePass(AnalysisPass);
485 // Recheck analysis passes to ensure that required analysises that
486 // are already checked are still available.
487 checkAnalysis = true;
490 // Do not schedule this analysis. Lower level analsyis
491 // passes are run on the fly.
497 // Now all required passes are available.
501 /// Find the pass that implements Analysis AID. Search immutable
502 /// passes and all pass managers. If desired pass is not found
503 /// then return NULL.
504 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
507 // Check pass managers
508 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
509 E = PassManagers.end(); P == NULL && I != E; ++I) {
510 PMDataManager *PMD = *I;
511 P = PMD->findAnalysisPass(AID, false);
514 // Check other pass managers
515 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
516 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
517 P = (*I)->findAnalysisPass(AID, false);
519 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
520 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
521 const PassInfo *PI = (*I)->getPassInfo();
525 // If Pass not found then check the interfaces implemented by Immutable Pass
527 const std::vector<const PassInfo*> &ImmPI =
528 PI->getInterfacesImplemented();
529 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
537 // Print passes managed by this top level manager.
538 void PMTopLevelManager::dumpPasses() const {
540 if (PassDebugging < Structure)
543 // Print out the immutable passes
544 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
545 ImmutablePasses[i]->dumpPassStructure(0);
548 // Every class that derives from PMDataManager also derives from Pass
549 // (sometimes indirectly), but there's no inheritance relationship
550 // between PMDataManager and Pass, so we have to dynamic_cast to get
551 // from a PMDataManager* to a Pass*.
552 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
553 E = PassManagers.end(); I != E; ++I)
554 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
557 void PMTopLevelManager::dumpArguments() const {
559 if (PassDebugging < Arguments)
562 cerr << "Pass Arguments: ";
563 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
564 E = PassManagers.end(); I != E; ++I) {
565 PMDataManager *PMD = *I;
566 PMD->dumpPassArguments();
571 void PMTopLevelManager::initializeAllAnalysisInfo() {
573 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
574 E = PassManagers.end(); I != E; ++I) {
575 PMDataManager *PMD = *I;
576 PMD->initializeAnalysisInfo();
579 // Initailize other pass managers
580 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
581 E = IndirectPassManagers.end(); I != E; ++I)
582 (*I)->initializeAnalysisInfo();
584 for(DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
585 DME = LastUser.end(); DMI != DME; ++DMI) {
586 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
587 InversedLastUser.find(DMI->second);
588 if (InvDMI != InversedLastUser.end()) {
589 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
590 L.insert(DMI->first);
592 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
593 InversedLastUser[DMI->second] = L;
599 PMTopLevelManager::~PMTopLevelManager() {
600 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
601 E = PassManagers.end(); I != E; ++I)
604 for (SmallVector<ImmutablePass *, 8>::iterator
605 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
608 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
609 DME = AnUsageMap.end(); DMI != DME; ++DMI) {
610 AnalysisUsage *AU = DMI->second;
616 //===----------------------------------------------------------------------===//
617 // PMDataManager implementation
619 /// Augement AvailableAnalysis by adding analysis made available by pass P.
620 void PMDataManager::recordAvailableAnalysis(Pass *P) {
622 if (const PassInfo *PI = P->getPassInfo()) {
623 AvailableAnalysis[PI] = P;
625 //This pass is the current implementation of all of the interfaces it
626 //implements as well.
627 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
628 for (unsigned i = 0, e = II.size(); i != e; ++i)
629 AvailableAnalysis[II[i]] = P;
633 // Return true if P preserves high level analysis used by other
634 // passes managed by this manager
635 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
637 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
639 if (AnUsage->getPreservesAll())
642 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
643 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
644 E = HigherLevelAnalysis.end(); I != E; ++I) {
646 if (!dynamic_cast<ImmutablePass*>(P1) &&
647 std::find(PreservedSet.begin(), PreservedSet.end(),
648 P1->getPassInfo()) ==
656 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
657 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
658 // Don't do this unless assertions are enabled.
662 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
663 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
665 // Verify preserved analysis
666 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
667 E = PreservedSet.end(); I != E; ++I) {
669 if (Pass *AP = findAnalysisPass(AID, true))
670 AP->verifyAnalysis();
674 /// verifyDomInfo - Verify dominator information if it is available.
675 void PMDataManager::verifyDomInfo(Pass &P, Function &F) {
677 if (!VerifyDomInfo || !P.getResolver())
680 DominatorTree *DT = P.getAnalysisToUpdate<DominatorTree>();
684 DominatorTree OtherDT;
685 OtherDT.getBase().recalculate(F);
686 if (DT->compare(OtherDT)) {
687 cerr << "Dominator Information for " << F.getNameStart() << "\n";
688 cerr << "Pass '" << P.getPassName() << "'\n";
689 cerr << "----- Valid -----\n";
691 cerr << "----- Invalid -----\n";
693 assert (0 && "Invalid dominator info");
696 DominanceFrontier *DF = P.getAnalysisToUpdate<DominanceFrontier>();
700 DominanceFrontier OtherDF;
701 std::vector<BasicBlock*> DTRoots = DT->getRoots();
702 OtherDF.calculate(*DT, DT->getNode(DTRoots[0]));
703 if (DF->compare(OtherDF)) {
704 cerr << "Dominator Information for " << F.getNameStart() << "\n";
705 cerr << "Pass '" << P.getPassName() << "'\n";
706 cerr << "----- Valid -----\n";
708 cerr << "----- Invalid -----\n";
710 assert (0 && "Invalid dominator info");
714 /// Remove Analysis not preserved by Pass P
715 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
716 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
717 if (AnUsage->getPreservesAll())
720 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
721 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
722 E = AvailableAnalysis.end(); I != E; ) {
723 std::map<AnalysisID, Pass*>::iterator Info = I++;
724 if (!dynamic_cast<ImmutablePass*>(Info->second)
725 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
726 PreservedSet.end()) {
727 // Remove this analysis
728 AvailableAnalysis.erase(Info);
729 if (PassDebugging >= Details) {
730 Pass *S = Info->second;
731 cerr << " -- '" << P->getPassName() << "' is not preserving '";
732 cerr << S->getPassName() << "'\n";
737 // Check inherited analysis also. If P is not preserving analysis
738 // provided by parent manager then remove it here.
739 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
741 if (!InheritedAnalysis[Index])
744 for (std::map<AnalysisID, Pass*>::iterator
745 I = InheritedAnalysis[Index]->begin(),
746 E = InheritedAnalysis[Index]->end(); I != E; ) {
747 std::map<AnalysisID, Pass *>::iterator Info = I++;
748 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
749 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
751 // Remove this analysis
752 InheritedAnalysis[Index]->erase(Info);
757 /// Remove analysis passes that are not used any longer
758 void PMDataManager::removeDeadPasses(Pass *P, const char *Msg,
759 enum PassDebuggingString DBG_STR) {
761 SmallVector<Pass *, 12> DeadPasses;
763 // If this is a on the fly manager then it does not have TPM.
767 TPM->collectLastUses(DeadPasses, P);
769 if (PassDebugging >= Details && !DeadPasses.empty()) {
770 cerr << " -*- '" << P->getPassName();
771 cerr << "' is the last user of following pass instances.";
772 cerr << " Free these instances\n";
775 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
776 E = DeadPasses.end(); I != E; ++I) {
778 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
780 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
781 (*I)->releaseMemory();
782 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
784 std::map<AnalysisID, Pass*>::iterator Pos =
785 AvailableAnalysis.find((*I)->getPassInfo());
787 // It is possible that pass is already removed from the AvailableAnalysis
788 if (Pos != AvailableAnalysis.end())
789 AvailableAnalysis.erase(Pos);
793 /// Add pass P into the PassVector. Update
794 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
795 void PMDataManager::add(Pass *P,
796 bool ProcessAnalysis) {
798 // This manager is going to manage pass P. Set up analysis resolver
800 AnalysisResolver *AR = new AnalysisResolver(*this);
803 // If a FunctionPass F is the last user of ModulePass info M
804 // then the F's manager, not F, records itself as a last user of M.
805 SmallVector<Pass *, 12> TransferLastUses;
807 if (ProcessAnalysis) {
809 // At the moment, this pass is the last user of all required passes.
810 SmallVector<Pass *, 12> LastUses;
811 SmallVector<Pass *, 8> RequiredPasses;
812 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
814 unsigned PDepth = this->getDepth();
816 collectRequiredAnalysis(RequiredPasses,
817 ReqAnalysisNotAvailable, P);
818 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
819 E = RequiredPasses.end(); I != E; ++I) {
820 Pass *PRequired = *I;
823 assert (PRequired->getResolver() && "Analysis Resolver is not set");
824 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
825 RDepth = DM.getDepth();
827 if (PDepth == RDepth)
828 LastUses.push_back(PRequired);
829 else if (PDepth > RDepth) {
830 // Let the parent claim responsibility of last use
831 TransferLastUses.push_back(PRequired);
832 // Keep track of higher level analysis used by this manager.
833 HigherLevelAnalysis.push_back(PRequired);
835 assert (0 && "Unable to accomodate Required Pass");
838 // Set P as P's last user until someone starts using P.
839 // However, if P is a Pass Manager then it does not need
840 // to record its last user.
841 if (!dynamic_cast<PMDataManager *>(P))
842 LastUses.push_back(P);
843 TPM->setLastUser(LastUses, P);
845 if (!TransferLastUses.empty()) {
846 Pass *My_PM = dynamic_cast<Pass *>(this);
847 TPM->setLastUser(TransferLastUses, My_PM);
848 TransferLastUses.clear();
851 // Now, take care of required analysises that are not available.
852 for (SmallVector<AnalysisID, 8>::iterator
853 I = ReqAnalysisNotAvailable.begin(),
854 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
855 Pass *AnalysisPass = (*I)->createPass();
856 this->addLowerLevelRequiredPass(P, AnalysisPass);
859 // Take a note of analysis required and made available by this pass.
860 // Remove the analysis not preserved by this pass
861 removeNotPreservedAnalysis(P);
862 recordAvailableAnalysis(P);
866 PassVector.push_back(P);
870 /// Populate RP with analysis pass that are required by
871 /// pass P and are available. Populate RP_NotAvail with analysis
872 /// pass that are required by pass P but are not available.
873 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
874 SmallVector<AnalysisID, 8> &RP_NotAvail,
876 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
877 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
878 for (AnalysisUsage::VectorType::const_iterator
879 I = RequiredSet.begin(), E = RequiredSet.end();
882 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
883 RP.push_back(AnalysisPass);
885 RP_NotAvail.push_back(AID);
888 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
889 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
890 E = IDs.end(); I != E; ++I) {
892 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
893 RP.push_back(AnalysisPass);
895 RP_NotAvail.push_back(AID);
899 // All Required analyses should be available to the pass as it runs! Here
900 // we fill in the AnalysisImpls member of the pass so that it can
901 // successfully use the getAnalysis() method to retrieve the
902 // implementations it needs.
904 void PMDataManager::initializeAnalysisImpl(Pass *P) {
905 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
907 for (AnalysisUsage::VectorType::const_iterator
908 I = AnUsage->getRequiredSet().begin(),
909 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
910 Pass *Impl = findAnalysisPass(*I, true);
912 // This may be analysis pass that is initialized on the fly.
913 // If that is not the case then it will raise an assert when it is used.
915 AnalysisResolver *AR = P->getResolver();
916 assert (AR && "Analysis Resolver is not set");
917 AR->addAnalysisImplsPair(*I, Impl);
921 /// Find the pass that implements Analysis AID. If desired pass is not found
922 /// then return NULL.
923 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
925 // Check if AvailableAnalysis map has one entry.
926 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
928 if (I != AvailableAnalysis.end())
931 // Search Parents through TopLevelManager
933 return TPM->findAnalysisPass(AID);
938 // Print list of passes that are last used by P.
939 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
941 SmallVector<Pass *, 12> LUses;
943 // If this is a on the fly manager then it does not have TPM.
947 TPM->collectLastUses(LUses, P);
949 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
950 E = LUses.end(); I != E; ++I) {
951 llvm::cerr << "--" << std::string(Offset*2, ' ');
952 (*I)->dumpPassStructure(0);
956 void PMDataManager::dumpPassArguments() const {
957 for(SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
958 E = PassVector.end(); I != E; ++I) {
959 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
960 PMD->dumpPassArguments();
962 if (const PassInfo *PI = (*I)->getPassInfo())
963 if (!PI->isAnalysisGroup())
964 cerr << " -" << PI->getPassArgument();
968 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
969 enum PassDebuggingString S2,
971 if (PassDebugging < Executions)
973 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
976 cerr << "Executing Pass '" << P->getPassName();
978 case MODIFICATION_MSG:
979 cerr << "Made Modification '" << P->getPassName();
982 cerr << " Freeing Pass '" << P->getPassName();
988 case ON_BASICBLOCK_MSG:
989 cerr << "' on BasicBlock '" << Msg << "'...\n";
991 case ON_FUNCTION_MSG:
992 cerr << "' on Function '" << Msg << "'...\n";
995 cerr << "' on Module '" << Msg << "'...\n";
998 cerr << "' on Loop " << Msg << "'...\n";
1001 cerr << "' on Call Graph " << Msg << "'...\n";
1008 void PMDataManager::dumpRequiredSet(const Pass *P)
1010 if (PassDebugging < Details)
1013 AnalysisUsage analysisUsage;
1014 P->getAnalysisUsage(analysisUsage);
1015 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1018 void PMDataManager::dumpPreservedSet(const Pass *P)
1020 if (PassDebugging < Details)
1023 AnalysisUsage analysisUsage;
1024 P->getAnalysisUsage(analysisUsage);
1025 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1028 void PMDataManager::dumpAnalysisUsage(const char *Msg, const Pass *P,
1029 const AnalysisUsage::VectorType &Set)
1031 assert(PassDebugging >= Details);
1034 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1035 for (unsigned i = 0; i != Set.size(); ++i) {
1037 cerr << " " << Set[i]->getPassName();
1042 /// Add RequiredPass into list of lower level passes required by pass P.
1043 /// RequiredPass is run on the fly by Pass Manager when P requests it
1044 /// through getAnalysis interface.
1045 /// This should be handled by specific pass manager.
1046 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1048 TPM->dumpArguments();
1052 // Module Level pass may required Function Level analysis info
1053 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1054 // to provide this on demand. In that case, in Pass manager terminology,
1055 // module level pass is requiring lower level analysis info managed by
1056 // lower level pass manager.
1058 // When Pass manager is not able to order required analysis info, Pass manager
1059 // checks whether any lower level manager will be able to provide this
1060 // analysis info on demand or not.
1062 cerr << "Unable to schedule '" << RequiredPass->getPassName();
1063 cerr << "' required by '" << P->getPassName() << "'\n";
1065 assert (0 && "Unable to schedule pass");
1069 PMDataManager::~PMDataManager() {
1071 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1072 E = PassVector.end(); I != E; ++I)
1077 //===----------------------------------------------------------------------===//
1078 // NOTE: Is this the right place to define this method ?
1079 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
1080 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
1081 return PM.findAnalysisPass(ID, dir);
1084 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1086 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1089 //===----------------------------------------------------------------------===//
1090 // BBPassManager implementation
1092 /// Execute all of the passes scheduled for execution by invoking
1093 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1094 /// the function, and if so, return true.
1096 BBPassManager::runOnFunction(Function &F) {
1098 if (F.isDeclaration())
1101 bool Changed = doInitialization(F);
1103 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1104 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1105 BasicBlockPass *BP = getContainedPass(Index);
1107 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getNameStart());
1108 dumpRequiredSet(BP);
1110 initializeAnalysisImpl(BP);
1112 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
1113 Changed |= BP->runOnBasicBlock(*I);
1114 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
1117 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1119 dumpPreservedSet(BP);
1121 verifyPreservedAnalysis(BP);
1122 removeNotPreservedAnalysis(BP);
1123 recordAvailableAnalysis(BP);
1124 removeDeadPasses(BP, I->getNameStart(), ON_BASICBLOCK_MSG);
1127 return Changed |= doFinalization(F);
1130 // Implement doInitialization and doFinalization
1131 inline bool BBPassManager::doInitialization(Module &M) {
1132 bool Changed = false;
1134 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1135 BasicBlockPass *BP = getContainedPass(Index);
1136 Changed |= BP->doInitialization(M);
1142 inline bool BBPassManager::doFinalization(Module &M) {
1143 bool Changed = false;
1145 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1146 BasicBlockPass *BP = getContainedPass(Index);
1147 Changed |= BP->doFinalization(M);
1153 inline bool BBPassManager::doInitialization(Function &F) {
1154 bool Changed = false;
1156 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1157 BasicBlockPass *BP = getContainedPass(Index);
1158 Changed |= BP->doInitialization(F);
1164 inline bool BBPassManager::doFinalization(Function &F) {
1165 bool Changed = false;
1167 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1168 BasicBlockPass *BP = getContainedPass(Index);
1169 Changed |= BP->doFinalization(F);
1176 //===----------------------------------------------------------------------===//
1177 // FunctionPassManager implementation
1179 /// Create new Function pass manager
1180 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1181 FPM = new FunctionPassManagerImpl(0);
1182 // FPM is the top level manager.
1183 FPM->setTopLevelManager(FPM);
1185 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1186 FPM->setResolver(AR);
1191 FunctionPassManager::~FunctionPassManager() {
1195 /// add - Add a pass to the queue of passes to run. This passes
1196 /// ownership of the Pass to the PassManager. When the
1197 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1198 /// there is no need to delete the pass. (TODO delete passes.)
1199 /// This implies that all passes MUST be allocated with 'new'.
1200 void FunctionPassManager::add(Pass *P) {
1204 /// run - Execute all of the passes scheduled for execution. Keep
1205 /// track of whether any of the passes modifies the function, and if
1206 /// so, return true.
1208 bool FunctionPassManager::run(Function &F) {
1210 if (MP->materializeFunction(&F, &errstr)) {
1211 cerr << "Error reading bitcode file: " << errstr << "\n";
1218 /// doInitialization - Run all of the initializers for the function passes.
1220 bool FunctionPassManager::doInitialization() {
1221 return FPM->doInitialization(*MP->getModule());
1224 /// doFinalization - Run all of the finalizers for the function passes.
1226 bool FunctionPassManager::doFinalization() {
1227 return FPM->doFinalization(*MP->getModule());
1230 //===----------------------------------------------------------------------===//
1231 // FunctionPassManagerImpl implementation
1233 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1234 bool Changed = false;
1236 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1237 FPPassManager *FP = getContainedManager(Index);
1238 Changed |= FP->doInitialization(M);
1244 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1245 bool Changed = false;
1247 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1248 FPPassManager *FP = getContainedManager(Index);
1249 Changed |= FP->doFinalization(M);
1255 // Execute all the passes managed by this top level manager.
1256 // Return true if any function is modified by a pass.
1257 bool FunctionPassManagerImpl::run(Function &F) {
1259 bool Changed = false;
1261 TimingInfo::createTheTimeInfo();
1266 initializeAllAnalysisInfo();
1267 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1268 FPPassManager *FP = getContainedManager(Index);
1269 Changed |= FP->runOnFunction(F);
1274 //===----------------------------------------------------------------------===//
1275 // FPPassManager implementation
1277 char FPPassManager::ID = 0;
1278 /// Print passes managed by this manager
1279 void FPPassManager::dumpPassStructure(unsigned Offset) {
1280 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1281 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1282 FunctionPass *FP = getContainedPass(Index);
1283 FP->dumpPassStructure(Offset + 1);
1284 dumpLastUses(FP, Offset+1);
1289 /// Execute all of the passes scheduled for execution by invoking
1290 /// runOnFunction method. Keep track of whether any of the passes modifies
1291 /// the function, and if so, return true.
1292 bool FPPassManager::runOnFunction(Function &F) {
1294 bool Changed = false;
1296 if (F.isDeclaration())
1299 // Collect inherited analysis from Module level pass manager.
1300 populateInheritedAnalysis(TPM->activeStack);
1302 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1303 FunctionPass *FP = getContainedPass(Index);
1305 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1306 dumpRequiredSet(FP);
1308 initializeAnalysisImpl(FP);
1310 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1311 Changed |= FP->runOnFunction(F);
1312 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1315 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getNameStart());
1316 dumpPreservedSet(FP);
1318 verifyPreservedAnalysis(FP);
1319 removeNotPreservedAnalysis(FP);
1320 recordAvailableAnalysis(FP);
1321 removeDeadPasses(FP, F.getNameStart(), ON_FUNCTION_MSG);
1323 // If dominator information is available then verify the info if requested.
1324 verifyDomInfo(*FP, F);
1329 bool FPPassManager::runOnModule(Module &M) {
1331 bool Changed = doInitialization(M);
1333 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1334 this->runOnFunction(*I);
1336 return Changed |= doFinalization(M);
1339 inline bool FPPassManager::doInitialization(Module &M) {
1340 bool Changed = false;
1342 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1343 FunctionPass *FP = getContainedPass(Index);
1344 Changed |= FP->doInitialization(M);
1350 inline bool FPPassManager::doFinalization(Module &M) {
1351 bool Changed = false;
1353 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1354 FunctionPass *FP = getContainedPass(Index);
1355 Changed |= FP->doFinalization(M);
1361 //===----------------------------------------------------------------------===//
1362 // MPPassManager implementation
1364 /// Execute all of the passes scheduled for execution by invoking
1365 /// runOnModule method. Keep track of whether any of the passes modifies
1366 /// the module, and if so, return true.
1368 MPPassManager::runOnModule(Module &M) {
1369 bool Changed = false;
1371 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1372 ModulePass *MP = getContainedPass(Index);
1374 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1375 M.getModuleIdentifier().c_str());
1376 dumpRequiredSet(MP);
1378 initializeAnalysisImpl(MP);
1380 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1381 Changed |= MP->runOnModule(M);
1382 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1385 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1386 M.getModuleIdentifier().c_str());
1387 dumpPreservedSet(MP);
1389 verifyPreservedAnalysis(MP);
1390 removeNotPreservedAnalysis(MP);
1391 recordAvailableAnalysis(MP);
1392 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1397 /// Add RequiredPass into list of lower level passes required by pass P.
1398 /// RequiredPass is run on the fly by Pass Manager when P requests it
1399 /// through getAnalysis interface.
1400 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1402 assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1403 && "Unable to handle Pass that requires lower level Analysis pass");
1404 assert ((P->getPotentialPassManagerType() <
1405 RequiredPass->getPotentialPassManagerType())
1406 && "Unable to handle Pass that requires lower level Analysis pass");
1408 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1410 FPP = new FunctionPassManagerImpl(0);
1411 // FPP is the top level manager.
1412 FPP->setTopLevelManager(FPP);
1414 OnTheFlyManagers[P] = FPP;
1416 FPP->add(RequiredPass);
1418 // Register P as the last user of RequiredPass.
1419 SmallVector<Pass *, 12> LU;
1420 LU.push_back(RequiredPass);
1421 FPP->setLastUser(LU, P);
1424 /// Return function pass corresponding to PassInfo PI, that is
1425 /// required by module pass MP. Instantiate analysis pass, by using
1426 /// its runOnFunction() for function F.
1427 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI,
1429 AnalysisID AID = PI;
1430 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1431 assert (FPP && "Unable to find on the fly pass");
1434 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(AID);
1438 //===----------------------------------------------------------------------===//
1439 // PassManagerImpl implementation
1441 /// run - Execute all of the passes scheduled for execution. Keep track of
1442 /// whether any of the passes modifies the module, and if so, return true.
1443 bool PassManagerImpl::run(Module &M) {
1445 bool Changed = false;
1447 TimingInfo::createTheTimeInfo();
1452 initializeAllAnalysisInfo();
1453 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1454 MPPassManager *MP = getContainedManager(Index);
1455 Changed |= MP->runOnModule(M);
1460 //===----------------------------------------------------------------------===//
1461 // PassManager implementation
1463 /// Create new pass manager
1464 PassManager::PassManager() {
1465 PM = new PassManagerImpl(0);
1466 // PM is the top level manager
1467 PM->setTopLevelManager(PM);
1470 PassManager::~PassManager() {
1474 /// add - Add a pass to the queue of passes to run. This passes ownership of
1475 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1476 /// will be destroyed as well, so there is no need to delete the pass. This
1477 /// implies that all passes MUST be allocated with 'new'.
1479 PassManager::add(Pass *P) {
1483 /// run - Execute all of the passes scheduled for execution. Keep track of
1484 /// whether any of the passes modifies the module, and if so, return true.
1486 PassManager::run(Module &M) {
1490 //===----------------------------------------------------------------------===//
1491 // TimingInfo Class - This class is used to calculate information about the
1492 // amount of time each pass takes to execute. This only happens with
1493 // -time-passes is enabled on the command line.
1495 bool llvm::TimePassesIsEnabled = false;
1496 static cl::opt<bool,true>
1497 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1498 cl::desc("Time each pass, printing elapsed time for each on exit"));
1500 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1501 // a non null value (if the -time-passes option is enabled) or it leaves it
1502 // null. It may be called multiple times.
1503 void TimingInfo::createTheTimeInfo() {
1504 if (!TimePassesIsEnabled || TheTimeInfo) return;
1506 // Constructed the first time this is called, iff -time-passes is enabled.
1507 // This guarantees that the object will be constructed before static globals,
1508 // thus it will be destroyed before them.
1509 static ManagedStatic<TimingInfo> TTI;
1510 TheTimeInfo = &*TTI;
1513 /// If TimingInfo is enabled then start pass timer.
1514 void StartPassTimer(Pass *P) {
1516 TheTimeInfo->passStarted(P);
1519 /// If TimingInfo is enabled then stop pass timer.
1520 void StopPassTimer(Pass *P) {
1522 TheTimeInfo->passEnded(P);
1525 //===----------------------------------------------------------------------===//
1526 // PMStack implementation
1529 // Pop Pass Manager from the stack and clear its analysis info.
1530 void PMStack::pop() {
1532 PMDataManager *Top = this->top();
1533 Top->initializeAnalysisInfo();
1538 // Push PM on the stack and set its top level manager.
1539 void PMStack::push(PMDataManager *PM) {
1541 PMDataManager *Top = NULL;
1542 assert (PM && "Unable to push. Pass Manager expected");
1544 if (this->empty()) {
1549 PMTopLevelManager *TPM = 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 Pass *P = dynamic_cast<Pass *>(*I);
1564 printf("%s ", P->getPassName());
1570 /// Find appropriate Module Pass Manager in the PM Stack and
1571 /// add self into that manager.
1572 void ModulePass::assignPassManager(PMStack &PMS,
1573 PassManagerType PreferredType) {
1575 // Find Module Pass Manager
1576 while(!PMS.empty()) {
1577 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1578 if (TopPMType == PreferredType)
1579 break; // We found desired pass manager
1580 else if (TopPMType > PMT_ModulePassManager)
1581 PMS.pop(); // Pop children pass managers
1586 PMS.top()->add(this);
1589 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1590 /// in the PM Stack and add self into that manager.
1591 void FunctionPass::assignPassManager(PMStack &PMS,
1592 PassManagerType PreferredType) {
1594 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1595 while(!PMS.empty()) {
1596 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1601 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1603 // Create new Function Pass Manager
1605 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1606 PMDataManager *PMD = PMS.top();
1608 // [1] Create new Function Pass Manager
1609 FPP = new FPPassManager(PMD->getDepth() + 1);
1610 FPP->populateInheritedAnalysis(PMS);
1612 // [2] Set up new manager's top level manager
1613 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1614 TPM->addIndirectPassManager(FPP);
1616 // [3] Assign manager to manage this new manager. This may create
1617 // and push new managers into PMS
1619 // If Call Graph Pass Manager is active then use it to manage
1620 // this new Function Pass manager.
1621 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1622 FPP->assignPassManager(PMS, PMT_CallGraphPassManager);
1624 FPP->assignPassManager(PMS);
1626 // [4] Push new manager into PMS
1630 // Assign FPP as the manager of this pass.
1634 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1635 /// in the PM Stack and add self into that manager.
1636 void BasicBlockPass::assignPassManager(PMStack &PMS,
1637 PassManagerType PreferredType) {
1639 BBPassManager *BBP = NULL;
1641 // Basic Pass Manager is a leaf pass manager. It does not handle
1642 // any other pass manager.
1644 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1646 // If leaf manager is not Basic Block Pass manager then create new
1647 // basic Block Pass manager.
1650 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1651 PMDataManager *PMD = PMS.top();
1653 // [1] Create new Basic Block Manager
1654 BBP = new BBPassManager(PMD->getDepth() + 1);
1656 // [2] Set up new manager's top level manager
1657 // Basic Block Pass Manager does not live by itself
1658 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1659 TPM->addIndirectPassManager(BBP);
1661 // [3] Assign manager to manage this new manager. This may create
1662 // and push new managers into PMS
1663 BBP->assignPassManager(PMS);
1665 // [4] Push new manager into PMS
1669 // Assign BBP as the manager of this pass.
1673 PassManagerBase::~PassManagerBase() {}
1675 /*===-- C Bindings --------------------------------------------------------===*/
1677 LLVMPassManagerRef LLVMCreatePassManager() {
1678 return wrap(new PassManager());
1681 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1682 return wrap(new FunctionPassManager(unwrap(P)));
1685 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1686 return unwrap<PassManager>(PM)->run(*unwrap(M));
1689 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1690 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1693 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1694 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1697 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1698 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1701 void LLVMDisposePassManager(LLVMPassManagerRef PM) {