1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source 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"
26 // See PassManagers.h for Pass Manager infrastructure overview.
30 //===----------------------------------------------------------------------===//
31 // Pass debugging information. Often it is useful to find out what pass is
32 // running when a crash occurs in a utility. When this library is compiled with
33 // debugging on, a command line option (--debug-pass) is enabled that causes the
34 // pass name to be printed before it executes.
37 // Different debug levels that can be enabled...
39 None, Arguments, Structure, Executions, Details
42 static cl::opt<enum PassDebugLevel>
43 PassDebugging("debug-pass", cl::Hidden,
44 cl::desc("Print PassManager debugging information"),
46 clEnumVal(None , "disable debug output"),
47 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
48 clEnumVal(Structure , "print pass structure before run()"),
49 clEnumVal(Executions, "print pass name before it is executed"),
50 clEnumVal(Details , "print pass details when it is executed"),
52 } // End of llvm namespace
56 //===----------------------------------------------------------------------===//
59 /// BBPassManager manages BasicBlockPass. It batches all the
60 /// pass together and sequence them to process one basic block before
61 /// processing next basic block.
62 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
67 BBPassManager(int Depth)
68 : PMDataManager(Depth), FunctionPass((intptr_t)&ID) {}
70 /// Execute all of the passes scheduled for execution. Keep track of
71 /// whether any of the passes modifies the function, and if so, return true.
72 bool runOnFunction(Function &F);
74 /// Pass Manager itself does not invalidate any analysis info.
75 void getAnalysisUsage(AnalysisUsage &Info) const {
76 Info.setPreservesAll();
79 bool doInitialization(Module &M);
80 bool doInitialization(Function &F);
81 bool doFinalization(Module &M);
82 bool doFinalization(Function &F);
84 virtual const char *getPassName() const {
85 return "BasicBlock Pass Manager";
88 // Print passes managed by this manager
89 void dumpPassStructure(unsigned Offset) {
90 llvm::cerr << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
91 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
92 BasicBlockPass *BP = getContainedPass(Index);
93 BP->dumpPassStructure(Offset + 1);
94 dumpLastUses(BP, Offset+1);
98 BasicBlockPass *getContainedPass(unsigned N) {
99 assert ( N < PassVector.size() && "Pass number out of range!");
100 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
104 virtual PassManagerType getPassManagerType() const {
105 return PMT_BasicBlockPassManager;
109 const int BBPassManager::ID = 0;
114 //===----------------------------------------------------------------------===//
115 // FunctionPassManagerImpl
117 /// FunctionPassManagerImpl manages FPPassManagers
118 class FunctionPassManagerImpl : public Pass,
119 public PMDataManager,
120 public PMTopLevelManager {
123 FunctionPassManagerImpl(int Depth) :
124 Pass((intptr_t)&ID), PMDataManager(Depth),
125 PMTopLevelManager(TLM_Function) { }
127 /// add - Add a pass to the queue of passes to run. This passes ownership of
128 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
129 /// will be destroyed as well, so there is no need to delete the pass. This
130 /// implies that all passes MUST be allocated with 'new'.
135 /// run - Execute all of the passes scheduled for execution. Keep track of
136 /// whether any of the passes modifies the module, and if so, return true.
137 bool run(Function &F);
139 /// doInitialization - Run all of the initializers for the function passes.
141 bool doInitialization(Module &M);
143 /// doFinalization - Run all of the initializers for the function passes.
145 bool doFinalization(Module &M);
147 /// Pass Manager itself does not invalidate any analysis info.
148 void getAnalysisUsage(AnalysisUsage &Info) const {
149 Info.setPreservesAll();
152 inline void addTopLevelPass(Pass *P) {
154 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
156 // P is a immutable pass and it will be managed by this
157 // top level manager. Set up analysis resolver to connect them.
158 AnalysisResolver *AR = new AnalysisResolver(*this);
160 initializeAnalysisImpl(P);
161 addImmutablePass(IP);
162 recordAvailableAnalysis(IP);
164 P->assignPassManager(activeStack);
169 FPPassManager *getContainedManager(unsigned N) {
170 assert ( N < PassManagers.size() && "Pass number out of range!");
171 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
176 const int FunctionPassManagerImpl::ID = 0;
177 //===----------------------------------------------------------------------===//
180 /// MPPassManager manages ModulePasses and function pass managers.
181 /// It batches all Module passes passes and function pass managers together and
182 /// sequence them to process one module.
183 class MPPassManager : public Pass, public PMDataManager {
187 MPPassManager(int Depth) : Pass((intptr_t)&ID), PMDataManager(Depth) { }
189 // Delete on the fly managers.
190 virtual ~MPPassManager() {
191 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
192 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
194 FunctionPassManagerImpl *FPP = I->second;
199 /// run - Execute all of the passes scheduled for execution. Keep track of
200 /// whether any of the passes modifies the module, and if so, return true.
201 bool runOnModule(Module &M);
203 /// Pass Manager itself does not invalidate any analysis info.
204 void getAnalysisUsage(AnalysisUsage &Info) const {
205 Info.setPreservesAll();
208 /// Add RequiredPass into list of lower level passes required by pass P.
209 /// RequiredPass is run on the fly by Pass Manager when P requests it
210 /// through getAnalysis interface.
211 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
213 /// Return function pass corresponding to PassInfo PI, that is
214 /// required by module pass MP. Instantiate analysis pass, by using
215 /// its runOnFunction() for function F.
216 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
218 virtual const char *getPassName() const {
219 return "Module Pass Manager";
222 // Print passes managed by this manager
223 void dumpPassStructure(unsigned Offset) {
224 llvm::cerr << std::string(Offset*2, ' ') << "ModulePass Manager\n";
225 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
226 ModulePass *MP = getContainedPass(Index);
227 MP->dumpPassStructure(Offset + 1);
228 if (FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP])
229 FPP->dumpPassStructure(Offset + 2);
230 dumpLastUses(MP, Offset+1);
234 ModulePass *getContainedPass(unsigned N) {
235 assert ( N < PassVector.size() && "Pass number out of range!");
236 ModulePass *MP = static_cast<ModulePass *>(PassVector[N]);
240 virtual PassManagerType getPassManagerType() const {
241 return PMT_ModulePassManager;
245 /// Collection of on the fly FPPassManagers. These managers manage
246 /// function passes that are required by module passes.
247 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
250 const int MPPassManager::ID = 0;
251 //===----------------------------------------------------------------------===//
255 /// PassManagerImpl manages MPPassManagers
256 class PassManagerImpl : public Pass,
257 public PMDataManager,
258 public PMTopLevelManager {
262 PassManagerImpl(int Depth) : Pass((intptr_t)&ID), PMDataManager(Depth),
263 PMTopLevelManager(TLM_Pass) { }
265 /// add - Add a pass to the queue of passes to run. This passes ownership of
266 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
267 /// will be destroyed as well, so there is no need to delete the pass. This
268 /// implies that all passes MUST be allocated with 'new'.
273 /// run - Execute all of the passes scheduled for execution. Keep track of
274 /// whether any of the passes modifies the module, and if so, return true.
277 /// Pass Manager itself does not invalidate any analysis info.
278 void getAnalysisUsage(AnalysisUsage &Info) const {
279 Info.setPreservesAll();
282 inline void addTopLevelPass(Pass *P) {
284 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
286 // P is a immutable pass and it will be managed by this
287 // top level manager. Set up analysis resolver to connect them.
288 AnalysisResolver *AR = new AnalysisResolver(*this);
290 initializeAnalysisImpl(P);
291 addImmutablePass(IP);
292 recordAvailableAnalysis(IP);
294 P->assignPassManager(activeStack);
299 MPPassManager *getContainedManager(unsigned N) {
300 assert ( N < PassManagers.size() && "Pass number out of range!");
301 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
307 const int PassManagerImpl::ID = 0;
308 } // End of llvm namespace
312 //===----------------------------------------------------------------------===//
313 // TimingInfo Class - This class is used to calculate information about the
314 // amount of time each pass takes to execute. This only happens when
315 // -time-passes is enabled on the command line.
318 class VISIBILITY_HIDDEN TimingInfo {
319 std::map<Pass*, Timer> TimingData;
323 // Use 'create' member to get this.
324 TimingInfo() : TG("... Pass execution timing report ...") {}
326 // TimingDtor - Print out information about timing information
328 // Delete all of the timers...
330 // TimerGroup is deleted next, printing the report.
333 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
334 // to a non null value (if the -time-passes option is enabled) or it leaves it
335 // null. It may be called multiple times.
336 static void createTheTimeInfo();
338 void passStarted(Pass *P) {
340 if (dynamic_cast<PMDataManager *>(P))
343 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
344 if (I == TimingData.end())
345 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
346 I->second.startTimer();
348 void passEnded(Pass *P) {
350 if (dynamic_cast<PMDataManager *>(P))
353 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
354 assert (I != TimingData.end() && "passStarted/passEnded not nested right!");
355 I->second.stopTimer();
359 static TimingInfo *TheTimeInfo;
361 } // End of anon namespace
363 //===----------------------------------------------------------------------===//
364 // PMTopLevelManager implementation
366 /// Initialize top level manager. Create first pass manager.
367 PMTopLevelManager::PMTopLevelManager (enum TopLevelManagerType t) {
370 MPPassManager *MPP = new MPPassManager(1);
371 MPP->setTopLevelManager(this);
373 activeStack.push(MPP);
375 else if (t == TLM_Function) {
376 FPPassManager *FPP = new FPPassManager(1);
377 FPP->setTopLevelManager(this);
379 activeStack.push(FPP);
383 /// Set pass P as the last user of the given analysis passes.
384 void PMTopLevelManager::setLastUser(std::vector<Pass *> &AnalysisPasses,
387 for (std::vector<Pass *>::iterator I = AnalysisPasses.begin(),
388 E = AnalysisPasses.end(); I != E; ++I) {
395 // If AP is the last user of other passes then make P last user of
397 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
398 LUE = LastUser.end(); LUI != LUE; ++LUI) {
399 if (LUI->second == AP)
400 LastUser[LUI->first] = P;
405 /// Collect passes whose last user is P
406 void PMTopLevelManager::collectLastUses(std::vector<Pass *> &LastUses,
408 for (std::map<Pass *, Pass *>::iterator LUI = LastUser.begin(),
409 LUE = LastUser.end(); LUI != LUE; ++LUI)
410 if (LUI->second == P)
411 LastUses.push_back(LUI->first);
414 /// Schedule pass P for execution. Make sure that passes required by
415 /// P are run before P is run. Update analysis info maintained by
416 /// the manager. Remove dead passes. This is a recursive function.
417 void PMTopLevelManager::schedulePass(Pass *P) {
419 // TODO : Allocate function manager for this pass, other wise required set
420 // may be inserted into previous function manager
422 // If this Analysis is already requested by one of the previous pass
423 // and it is still available then do not insert new pass in the queue again.
424 if (findAnalysisPass(P->getPassInfo()))
427 // Give pass a chance to prepare the stage.
428 P->preparePassManager(activeStack);
430 AnalysisUsage AnUsage;
431 P->getAnalysisUsage(AnUsage);
432 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
433 for (std::vector<AnalysisID>::const_iterator I = RequiredSet.begin(),
434 E = RequiredSet.end(); I != E; ++I) {
436 Pass *AnalysisPass = findAnalysisPass(*I);
438 AnalysisPass = (*I)->createPass();
439 // Schedule this analysis run first only if it is not a lower level
440 // analysis pass. Lower level analsyis passes are run on the fly.
441 if (P->getPotentialPassManagerType () >=
442 AnalysisPass->getPotentialPassManagerType())
443 schedulePass(AnalysisPass);
449 // Now all required passes are available.
453 /// Find the pass that implements Analysis AID. Search immutable
454 /// passes and all pass managers. If desired pass is not found
455 /// then return NULL.
456 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
459 // Check pass managers
460 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
461 E = PassManagers.end(); P == NULL && I != E; ++I) {
462 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
463 assert(PMD && "This is not a PassManager");
464 P = PMD->findAnalysisPass(AID, false);
467 // Check other pass managers
468 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
469 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
470 P = (*I)->findAnalysisPass(AID, false);
472 for (std::vector<ImmutablePass *>::iterator I = ImmutablePasses.begin(),
473 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
474 const PassInfo *PI = (*I)->getPassInfo();
478 // If Pass not found then check the interfaces implemented by Immutable Pass
480 const std::vector<const PassInfo*> &ImmPI = PI->getInterfacesImplemented();
481 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
489 // Print passes managed by this top level manager.
490 void PMTopLevelManager::dumpPasses() const {
492 if (PassDebugging < Structure)
495 // Print out the immutable passes
496 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
497 ImmutablePasses[i]->dumpPassStructure(0);
500 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
501 E = PassManagers.end(); I != E; ++I)
502 (*I)->dumpPassStructure(1);
505 void PMTopLevelManager::dumpArguments() const {
507 if (PassDebugging < Arguments)
510 cerr << "Pass Arguments: ";
511 for (std::vector<Pass *>::const_iterator I = PassManagers.begin(),
512 E = PassManagers.end(); I != E; ++I) {
513 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
514 assert(PMD && "This is not a PassManager");
515 PMD->dumpPassArguments();
520 void PMTopLevelManager::initializeAllAnalysisInfo() {
522 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
523 E = PassManagers.end(); I != E; ++I) {
524 PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I);
525 assert(PMD && "This is not a PassManager");
526 PMD->initializeAnalysisInfo();
529 // Initailize other pass managers
530 for (std::vector<PMDataManager *>::iterator I = IndirectPassManagers.begin(),
531 E = IndirectPassManagers.end(); I != E; ++I)
532 (*I)->initializeAnalysisInfo();
536 PMTopLevelManager::~PMTopLevelManager() {
537 for (std::vector<Pass *>::iterator I = PassManagers.begin(),
538 E = PassManagers.end(); I != E; ++I)
541 for (std::vector<ImmutablePass *>::iterator
542 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
545 PassManagers.clear();
548 //===----------------------------------------------------------------------===//
549 // PMDataManager implementation
551 /// Return true IFF pass P's required analysis set does not required new
553 bool PMDataManager::manageablePass(Pass *P) {
556 // If this pass is not preserving information that is required by a
557 // pass maintained by higher level pass manager then do not insert
558 // this pass into current manager. Use new manager. For example,
559 // For example, If FunctionPass F is not preserving ModulePass Info M1
560 // that is used by another ModulePass M2 then do not insert F in
561 // current function pass manager.
565 /// Augement AvailableAnalysis by adding analysis made available by pass P.
566 void PMDataManager::recordAvailableAnalysis(Pass *P) {
568 if (const PassInfo *PI = P->getPassInfo()) {
569 AvailableAnalysis[PI] = P;
571 //This pass is the current implementation of all of the interfaces it
572 //implements as well.
573 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
574 for (unsigned i = 0, e = II.size(); i != e; ++i)
575 AvailableAnalysis[II[i]] = P;
579 // Return true if P preserves high level analysis used by other
580 // passes managed by this manager
581 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
583 AnalysisUsage AnUsage;
584 P->getAnalysisUsage(AnUsage);
586 if (AnUsage.getPreservesAll())
589 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
590 for (std::vector<Pass *>::iterator I = HigherLevelAnalysis.begin(),
591 E = HigherLevelAnalysis.end(); I != E; ++I) {
593 if (!dynamic_cast<ImmutablePass*>(P1)
594 && std::find(PreservedSet.begin(), PreservedSet.end(), P1->getPassInfo()) ==
602 /// Remove Analyss not preserved by Pass P
603 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
604 AnalysisUsage AnUsage;
605 P->getAnalysisUsage(AnUsage);
607 if (AnUsage.getPreservesAll())
610 const std::vector<AnalysisID> &PreservedSet = AnUsage.getPreservedSet();
611 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
612 E = AvailableAnalysis.end(); I != E; ) {
613 std::map<AnalysisID, Pass*>::iterator Info = I++;
614 if (!dynamic_cast<ImmutablePass*>(Info->second)
615 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
617 // Remove this analysis
618 AvailableAnalysis.erase(Info);
621 // Check inherited analysis also. If P is not preserving analysis
622 // provided by parent manager then remove it here.
623 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
625 if (!InheritedAnalysis[Index])
628 for (std::map<AnalysisID, Pass*>::iterator
629 I = InheritedAnalysis[Index]->begin(),
630 E = InheritedAnalysis[Index]->end(); I != E; ) {
631 std::map<AnalysisID, Pass *>::iterator Info = I++;
632 if (!dynamic_cast<ImmutablePass*>(Info->second)
633 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
635 // Remove this analysis
636 InheritedAnalysis[Index]->erase(Info);
642 /// Remove analysis passes that are not used any longer
643 void PMDataManager::removeDeadPasses(Pass *P, std::string Msg,
644 enum PassDebuggingString DBG_STR) {
646 std::vector<Pass *> DeadPasses;
648 // If this is a on the fly manager then it does not have TPM.
652 TPM->collectLastUses(DeadPasses, P);
654 for (std::vector<Pass *>::iterator I = DeadPasses.begin(),
655 E = DeadPasses.end(); I != E; ++I) {
657 dumpPassInfo(*I, FREEING_MSG, DBG_STR, Msg);
659 if (TheTimeInfo) TheTimeInfo->passStarted(*I);
660 (*I)->releaseMemory();
661 if (TheTimeInfo) TheTimeInfo->passEnded(*I);
663 std::map<AnalysisID, Pass*>::iterator Pos =
664 AvailableAnalysis.find((*I)->getPassInfo());
666 // It is possible that pass is already removed from the AvailableAnalysis
667 if (Pos != AvailableAnalysis.end())
668 AvailableAnalysis.erase(Pos);
672 /// Add pass P into the PassVector. Update
673 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
674 void PMDataManager::add(Pass *P,
675 bool ProcessAnalysis) {
677 // This manager is going to manage pass P. Set up analysis resolver
679 AnalysisResolver *AR = new AnalysisResolver(*this);
682 // If a FunctionPass F is the last user of ModulePass info M
683 // then the F's manager, not F, records itself as a last user of M.
684 std::vector<Pass *> TransferLastUses;
686 if (ProcessAnalysis) {
688 // At the moment, this pass is the last user of all required passes.
689 std::vector<Pass *> LastUses;
690 SmallVector<Pass *, 8> RequiredPasses;
691 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
693 unsigned PDepth = this->getDepth();
695 collectRequiredAnalysis(RequiredPasses,
696 ReqAnalysisNotAvailable, P);
697 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
698 E = RequiredPasses.end(); I != E; ++I) {
699 Pass *PRequired = *I;
702 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
703 RDepth = DM.getDepth();
705 if (PDepth == RDepth)
706 LastUses.push_back(PRequired);
707 else if (PDepth > RDepth) {
708 // Let the parent claim responsibility of last use
709 TransferLastUses.push_back(PRequired);
710 // Keep track of higher level analysis used by this manager.
711 HigherLevelAnalysis.push_back(PRequired);
713 assert (0 && "Unable to accomodate Required Pass");
716 // Set P as P's last user until someone starts using P.
717 // However, if P is a Pass Manager then it does not need
718 // to record its last user.
719 if (!dynamic_cast<PMDataManager *>(P))
720 LastUses.push_back(P);
721 TPM->setLastUser(LastUses, P);
723 if (!TransferLastUses.empty()) {
724 Pass *My_PM = dynamic_cast<Pass *>(this);
725 TPM->setLastUser(TransferLastUses, My_PM);
726 TransferLastUses.clear();
729 // Now, take care of required analysises that are not available.
730 for (SmallVector<AnalysisID, 8>::iterator
731 I = ReqAnalysisNotAvailable.begin(),
732 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
733 Pass *AnalysisPass = (*I)->createPass();
734 this->addLowerLevelRequiredPass(P, AnalysisPass);
737 // Take a note of analysis required and made available by this pass.
738 // Remove the analysis not preserved by this pass
739 removeNotPreservedAnalysis(P);
740 recordAvailableAnalysis(P);
744 PassVector.push_back(P);
748 /// Populate RP with analysis pass that are required by
749 /// pass P and are available. Populate RP_NotAvail with analysis
750 /// pass that are required by pass P but are not available.
751 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
752 SmallVector<AnalysisID, 8> &RP_NotAvail,
754 AnalysisUsage AnUsage;
755 P->getAnalysisUsage(AnUsage);
756 const std::vector<AnalysisID> &RequiredSet = AnUsage.getRequiredSet();
757 for (std::vector<AnalysisID>::const_iterator
758 I = RequiredSet.begin(), E = RequiredSet.end();
761 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
762 RP.push_back(AnalysisPass);
764 RP_NotAvail.push_back(AID);
767 const std::vector<AnalysisID> &IDs = AnUsage.getRequiredTransitiveSet();
768 for (std::vector<AnalysisID>::const_iterator I = IDs.begin(),
769 E = IDs.end(); I != E; ++I) {
771 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
772 RP.push_back(AnalysisPass);
774 RP_NotAvail.push_back(AID);
778 // All Required analyses should be available to the pass as it runs! Here
779 // we fill in the AnalysisImpls member of the pass so that it can
780 // successfully use the getAnalysis() method to retrieve the
781 // implementations it needs.
783 void PMDataManager::initializeAnalysisImpl(Pass *P) {
784 AnalysisUsage AnUsage;
785 P->getAnalysisUsage(AnUsage);
787 for (std::vector<const PassInfo *>::const_iterator
788 I = AnUsage.getRequiredSet().begin(),
789 E = AnUsage.getRequiredSet().end(); I != E; ++I) {
790 Pass *Impl = findAnalysisPass(*I, true);
792 // This may be analysis pass that is initialized on the fly.
793 // If that is not the case then it will raise an assert when it is used.
795 AnalysisResolver *AR = P->getResolver();
796 AR->addAnalysisImplsPair(*I, Impl);
800 /// Find the pass that implements Analysis AID. If desired pass is not found
801 /// then return NULL.
802 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
804 // Check if AvailableAnalysis map has one entry.
805 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
807 if (I != AvailableAnalysis.end())
810 // Search Parents through TopLevelManager
812 return TPM->findAnalysisPass(AID);
817 // Print list of passes that are last used by P.
818 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
820 std::vector<Pass *> LUses;
822 // If this is a on the fly manager then it does not have TPM.
826 TPM->collectLastUses(LUses, P);
828 for (std::vector<Pass *>::iterator I = LUses.begin(),
829 E = LUses.end(); I != E; ++I) {
830 llvm::cerr << "--" << std::string(Offset*2, ' ');
831 (*I)->dumpPassStructure(0);
835 void PMDataManager::dumpPassArguments() const {
836 for(std::vector<Pass *>::const_iterator I = PassVector.begin(),
837 E = PassVector.end(); I != E; ++I) {
838 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
839 PMD->dumpPassArguments();
841 if (const PassInfo *PI = (*I)->getPassInfo())
842 if (!PI->isAnalysisGroup())
843 cerr << " -" << PI->getPassArgument();
847 void PMDataManager:: dumpPassInfo(Pass *P, enum PassDebuggingString S1,
848 enum PassDebuggingString S2,
850 if (PassDebugging < Executions)
852 cerr << (void*)this << std::string(getDepth()*2+1, ' ');
855 cerr << "Executing Pass '" << P->getPassName();
857 case MODIFICATION_MSG:
858 cerr << "' Made Modification '" << P->getPassName();
861 cerr << " Freeing Pass '" << P->getPassName();
867 case ON_BASICBLOCK_MSG:
868 cerr << "' on BasicBlock '" << Msg << "...\n";
870 case ON_FUNCTION_MSG:
871 cerr << "' on Function '" << Msg << "...\n";
874 cerr << "' on Module '" << Msg << "...\n";
877 cerr << "' on Loop " << Msg << "...\n";
880 cerr << "' on Call Graph " << Msg << "...\n";
887 void PMDataManager::dumpAnalysisSetInfo(const char *Msg, Pass *P,
888 const std::vector<AnalysisID> &Set)
890 if (PassDebugging >= Details && !Set.empty()) {
891 cerr << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
892 for (unsigned i = 0; i != Set.size(); ++i) {
894 cerr << " " << Set[i]->getPassName();
901 PMDataManager::~PMDataManager() {
903 for (std::vector<Pass *>::iterator I = PassVector.begin(),
904 E = PassVector.end(); I != E; ++I)
910 //===----------------------------------------------------------------------===//
911 // NOTE: Is this the right place to define this method ?
912 // getAnalysisToUpdate - Return an analysis result or null if it doesn't exist
913 Pass *AnalysisResolver::getAnalysisToUpdate(AnalysisID ID, bool dir) const {
914 return PM.findAnalysisPass(ID, dir);
917 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
919 return PM.getOnTheFlyPass(P, AnalysisPI, F);
922 //===----------------------------------------------------------------------===//
923 // BBPassManager implementation
925 /// Execute all of the passes scheduled for execution by invoking
926 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
927 /// the function, and if so, return true.
929 BBPassManager::runOnFunction(Function &F) {
931 if (F.isDeclaration())
934 bool Changed = doInitialization(F);
936 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
937 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
938 BasicBlockPass *BP = getContainedPass(Index);
939 AnalysisUsage AnUsage;
940 BP->getAnalysisUsage(AnUsage);
942 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
943 dumpAnalysisSetInfo("Required", BP, AnUsage.getRequiredSet());
945 initializeAnalysisImpl(BP);
947 if (TheTimeInfo) TheTimeInfo->passStarted(BP);
948 Changed |= BP->runOnBasicBlock(*I);
949 if (TheTimeInfo) TheTimeInfo->passEnded(BP);
952 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG, (*I).getName());
953 dumpAnalysisSetInfo("Preserved", BP, AnUsage.getPreservedSet());
955 removeNotPreservedAnalysis(BP);
956 recordAvailableAnalysis(BP);
957 removeDeadPasses(BP, (*I).getName(), ON_BASICBLOCK_MSG);
960 return Changed |= doFinalization(F);
963 // Implement doInitialization and doFinalization
964 inline bool BBPassManager::doInitialization(Module &M) {
965 bool Changed = false;
967 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
968 BasicBlockPass *BP = getContainedPass(Index);
969 Changed |= BP->doInitialization(M);
975 inline bool BBPassManager::doFinalization(Module &M) {
976 bool Changed = false;
978 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
979 BasicBlockPass *BP = getContainedPass(Index);
980 Changed |= BP->doFinalization(M);
986 inline bool BBPassManager::doInitialization(Function &F) {
987 bool Changed = false;
989 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
990 BasicBlockPass *BP = getContainedPass(Index);
991 Changed |= BP->doInitialization(F);
997 inline bool BBPassManager::doFinalization(Function &F) {
998 bool Changed = false;
1000 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1001 BasicBlockPass *BP = getContainedPass(Index);
1002 Changed |= BP->doFinalization(F);
1009 //===----------------------------------------------------------------------===//
1010 // FunctionPassManager implementation
1012 /// Create new Function pass manager
1013 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1014 FPM = new FunctionPassManagerImpl(0);
1015 // FPM is the top level manager.
1016 FPM->setTopLevelManager(FPM);
1018 PMDataManager *PMD = dynamic_cast<PMDataManager *>(FPM);
1019 AnalysisResolver *AR = new AnalysisResolver(*PMD);
1020 FPM->setResolver(AR);
1025 FunctionPassManager::~FunctionPassManager() {
1029 /// add - Add a pass to the queue of passes to run. This passes
1030 /// ownership of the Pass to the PassManager. When the
1031 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1032 /// there is no need to delete the pass. (TODO delete passes.)
1033 /// This implies that all passes MUST be allocated with 'new'.
1034 void FunctionPassManager::add(Pass *P) {
1038 /// run - Execute all of the passes scheduled for execution. Keep
1039 /// track of whether any of the passes modifies the function, and if
1040 /// so, return true.
1042 bool FunctionPassManager::run(Function &F) {
1044 if (MP->materializeFunction(&F, &errstr)) {
1045 cerr << "Error reading bytecode file: " << errstr << "\n";
1052 /// doInitialization - Run all of the initializers for the function passes.
1054 bool FunctionPassManager::doInitialization() {
1055 return FPM->doInitialization(*MP->getModule());
1058 /// doFinalization - Run all of the initializers for the function passes.
1060 bool FunctionPassManager::doFinalization() {
1061 return FPM->doFinalization(*MP->getModule());
1064 //===----------------------------------------------------------------------===//
1065 // FunctionPassManagerImpl implementation
1067 inline bool FunctionPassManagerImpl::doInitialization(Module &M) {
1068 bool Changed = false;
1070 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1071 FPPassManager *FP = getContainedManager(Index);
1072 Changed |= FP->doInitialization(M);
1078 inline bool FunctionPassManagerImpl::doFinalization(Module &M) {
1079 bool Changed = false;
1081 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1082 FPPassManager *FP = getContainedManager(Index);
1083 Changed |= FP->doFinalization(M);
1089 // Execute all the passes managed by this top level manager.
1090 // Return true if any function is modified by a pass.
1091 bool FunctionPassManagerImpl::run(Function &F) {
1093 bool Changed = false;
1095 TimingInfo::createTheTimeInfo();
1100 initializeAllAnalysisInfo();
1101 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1102 FPPassManager *FP = getContainedManager(Index);
1103 Changed |= FP->runOnFunction(F);
1108 //===----------------------------------------------------------------------===//
1109 // FPPassManager implementation
1111 const int FPPassManager::ID = 0;
1112 /// Print passes managed by this manager
1113 void FPPassManager::dumpPassStructure(unsigned Offset) {
1114 llvm::cerr << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1115 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1116 FunctionPass *FP = getContainedPass(Index);
1117 FP->dumpPassStructure(Offset + 1);
1118 dumpLastUses(FP, Offset+1);
1123 /// Execute all of the passes scheduled for execution by invoking
1124 /// runOnFunction method. Keep track of whether any of the passes modifies
1125 /// the function, and if so, return true.
1126 bool FPPassManager::runOnFunction(Function &F) {
1128 bool Changed = false;
1130 if (F.isDeclaration())
1133 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1134 FunctionPass *FP = getContainedPass(Index);
1136 AnalysisUsage AnUsage;
1137 FP->getAnalysisUsage(AnUsage);
1139 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1140 dumpAnalysisSetInfo("Required", FP, AnUsage.getRequiredSet());
1142 initializeAnalysisImpl(FP);
1144 if (TheTimeInfo) TheTimeInfo->passStarted(FP);
1145 Changed |= FP->runOnFunction(F);
1146 if (TheTimeInfo) TheTimeInfo->passEnded(FP);
1149 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1150 dumpAnalysisSetInfo("Preserved", FP, AnUsage.getPreservedSet());
1152 removeNotPreservedAnalysis(FP);
1153 recordAvailableAnalysis(FP);
1154 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1159 bool FPPassManager::runOnModule(Module &M) {
1161 bool Changed = doInitialization(M);
1163 for(Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1164 this->runOnFunction(*I);
1166 return Changed |= doFinalization(M);
1169 inline bool FPPassManager::doInitialization(Module &M) {
1170 bool Changed = false;
1172 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1173 FunctionPass *FP = getContainedPass(Index);
1174 Changed |= FP->doInitialization(M);
1180 inline bool FPPassManager::doFinalization(Module &M) {
1181 bool Changed = false;
1183 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1184 FunctionPass *FP = getContainedPass(Index);
1185 Changed |= FP->doFinalization(M);
1191 //===----------------------------------------------------------------------===//
1192 // MPPassManager implementation
1194 /// Execute all of the passes scheduled for execution by invoking
1195 /// runOnModule method. Keep track of whether any of the passes modifies
1196 /// the module, and if so, return true.
1198 MPPassManager::runOnModule(Module &M) {
1199 bool Changed = false;
1201 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1202 ModulePass *MP = getContainedPass(Index);
1204 AnalysisUsage AnUsage;
1205 MP->getAnalysisUsage(AnUsage);
1207 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1208 dumpAnalysisSetInfo("Required", MP, AnUsage.getRequiredSet());
1210 initializeAnalysisImpl(MP);
1212 if (TheTimeInfo) TheTimeInfo->passStarted(MP);
1213 Changed |= MP->runOnModule(M);
1214 if (TheTimeInfo) TheTimeInfo->passEnded(MP);
1217 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1218 M.getModuleIdentifier());
1219 dumpAnalysisSetInfo("Preserved", MP, AnUsage.getPreservedSet());
1221 removeNotPreservedAnalysis(MP);
1222 recordAvailableAnalysis(MP);
1223 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1228 /// Add RequiredPass into list of lower level passes required by pass P.
1229 /// RequiredPass is run on the fly by Pass Manager when P requests it
1230 /// through getAnalysis interface.
1231 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1233 assert (P->getPotentialPassManagerType() == PMT_ModulePassManager
1234 && "Unable to handle Pass that requires lower level Analysis pass");
1235 assert ((P->getPotentialPassManagerType() <
1236 RequiredPass->getPotentialPassManagerType())
1237 && "Unable to handle Pass that requires lower level Analysis pass");
1239 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1241 FPP = new FunctionPassManagerImpl(0);
1242 // FPP is the top level manager.
1243 FPP->setTopLevelManager(FPP);
1245 OnTheFlyManagers[P] = FPP;
1247 FPP->add(RequiredPass);
1249 // Register P as the last user of RequiredPass.
1250 std::vector<Pass *> LU;
1251 LU.push_back(RequiredPass);
1252 FPP->setLastUser(LU, P);
1255 /// Return function pass corresponding to PassInfo PI, that is
1256 /// required by module pass MP. Instantiate analysis pass, by using
1257 /// its runOnFunction() for function F.
1258 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI,
1260 AnalysisID AID = PI;
1261 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1262 assert (FPP && "Unable to find on the fly pass");
1265 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(AID);
1269 //===----------------------------------------------------------------------===//
1270 // PassManagerImpl implementation
1272 /// run - Execute all of the passes scheduled for execution. Keep track of
1273 /// whether any of the passes modifies the module, and if so, return true.
1274 bool PassManagerImpl::run(Module &M) {
1276 bool Changed = false;
1278 TimingInfo::createTheTimeInfo();
1283 initializeAllAnalysisInfo();
1284 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1285 MPPassManager *MP = getContainedManager(Index);
1286 Changed |= MP->runOnModule(M);
1291 //===----------------------------------------------------------------------===//
1292 // PassManager implementation
1294 /// Create new pass manager
1295 PassManager::PassManager() {
1296 PM = new PassManagerImpl(0);
1297 // PM is the top level manager
1298 PM->setTopLevelManager(PM);
1301 PassManager::~PassManager() {
1305 /// add - Add a pass to the queue of passes to run. This passes ownership of
1306 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1307 /// will be destroyed as well, so there is no need to delete the pass. This
1308 /// implies that all passes MUST be allocated with 'new'.
1310 PassManager::add(Pass *P) {
1314 /// run - Execute all of the passes scheduled for execution. Keep track of
1315 /// whether any of the passes modifies the module, and if so, return true.
1317 PassManager::run(Module &M) {
1321 //===----------------------------------------------------------------------===//
1322 // TimingInfo Class - This class is used to calculate information about the
1323 // amount of time each pass takes to execute. This only happens with
1324 // -time-passes is enabled on the command line.
1326 bool llvm::TimePassesIsEnabled = false;
1327 static cl::opt<bool,true>
1328 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1329 cl::desc("Time each pass, printing elapsed time for each on exit"));
1331 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1332 // a non null value (if the -time-passes option is enabled) or it leaves it
1333 // null. It may be called multiple times.
1334 void TimingInfo::createTheTimeInfo() {
1335 if (!TimePassesIsEnabled || TheTimeInfo) return;
1337 // Constructed the first time this is called, iff -time-passes is enabled.
1338 // This guarantees that the object will be constructed before static globals,
1339 // thus it will be destroyed before them.
1340 static ManagedStatic<TimingInfo> TTI;
1341 TheTimeInfo = &*TTI;
1344 /// If TimingInfo is enabled then start pass timer.
1345 void StartPassTimer(Pass *P) {
1347 TheTimeInfo->passStarted(P);
1350 /// If TimingInfo is enabled then stop pass timer.
1351 void StopPassTimer(Pass *P) {
1353 TheTimeInfo->passEnded(P);
1356 //===----------------------------------------------------------------------===//
1357 // PMStack implementation
1360 // Pop Pass Manager from the stack and clear its analysis info.
1361 void PMStack::pop() {
1363 PMDataManager *Top = this->top();
1364 Top->initializeAnalysisInfo();
1369 // Push PM on the stack and set its top level manager.
1370 void PMStack::push(Pass *P) {
1372 PMDataManager *Top = NULL;
1373 PMDataManager *PM = dynamic_cast<PMDataManager *>(P);
1374 assert (PM && "Unable to push. Pass Manager expected");
1376 if (this->empty()) {
1381 PMTopLevelManager *TPM = Top->getTopLevelManager();
1383 assert (TPM && "Unable to find top level manager");
1384 TPM->addIndirectPassManager(PM);
1385 PM->setTopLevelManager(TPM);
1388 AnalysisResolver *AR = new AnalysisResolver(*Top);
1394 // Dump content of the pass manager stack.
1395 void PMStack::dump() {
1396 for(std::deque<PMDataManager *>::iterator I = S.begin(),
1397 E = S.end(); I != E; ++I) {
1398 Pass *P = dynamic_cast<Pass *>(*I);
1399 printf ("%s ", P->getPassName());
1405 /// Find appropriate Module Pass Manager in the PM Stack and
1406 /// add self into that manager.
1407 void ModulePass::assignPassManager(PMStack &PMS,
1408 PassManagerType PreferredType) {
1410 // Find Module Pass Manager
1411 while(!PMS.empty()) {
1412 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1413 if (TopPMType == PreferredType)
1414 break; // We found desired pass manager
1415 else if (TopPMType > PMT_ModulePassManager)
1416 PMS.pop(); // Pop children pass managers
1421 PMS.top()->add(this);
1424 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1425 /// in the PM Stack and add self into that manager.
1426 void FunctionPass::assignPassManager(PMStack &PMS,
1427 PassManagerType PreferredType) {
1429 // Find Module Pass Manager (TODO : Or Call Graph Pass Manager)
1430 while(!PMS.empty()) {
1431 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1436 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1438 // Create new Function Pass Manager
1440 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1441 PMDataManager *PMD = PMS.top();
1443 // [1] Create new Function Pass Manager
1444 FPP = new FPPassManager(PMD->getDepth() + 1);
1446 // [2] Set up new manager's top level manager
1447 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1448 TPM->addIndirectPassManager(FPP);
1450 // [3] Assign manager to manage this new manager. This may create
1451 // and push new managers into PMS
1452 Pass *P = dynamic_cast<Pass *>(FPP);
1454 // If Call Graph Pass Manager is active then use it to manage
1455 // this new Function Pass manager.
1456 if (PMD->getPassManagerType() == PMT_CallGraphPassManager)
1457 P->assignPassManager(PMS, PMT_CallGraphPassManager);
1459 P->assignPassManager(PMS);
1461 // [4] Push new manager into PMS
1465 // Assign FPP as the manager of this pass.
1469 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1470 /// in the PM Stack and add self into that manager.
1471 void BasicBlockPass::assignPassManager(PMStack &PMS,
1472 PassManagerType PreferredType) {
1474 BBPassManager *BBP = NULL;
1476 // Basic Pass Manager is a leaf pass manager. It does not handle
1477 // any other pass manager.
1479 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1482 // If leaf manager is not Basic Block Pass manager then create new
1483 // basic Block Pass manager.
1486 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1487 PMDataManager *PMD = PMS.top();
1489 // [1] Create new Basic Block Manager
1490 BBP = new BBPassManager(PMD->getDepth() + 1);
1492 // [2] Set up new manager's top level manager
1493 // Basic Block Pass Manager does not live by itself
1494 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1495 TPM->addIndirectPassManager(BBP);
1497 // [3] Assign manager to manage this new manager. This may create
1498 // and push new managers into PMS
1499 Pass *P = dynamic_cast<Pass *>(BBP);
1500 P->assignPassManager(PMS);
1502 // [4] Push new manager into PMS
1506 // Assign BBP as the manager of this pass.