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/Assembly/Writer.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Timer.h"
19 #include "llvm/Module.h"
20 #include "llvm/ModuleProvider.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.h"
26 #include "llvm-c/Core.h"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 None, Arguments, Structure, Executions, Details
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
52 clEnumVal(None , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
58 } // End of llvm namespace
60 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
61 /// or higher is specified.
62 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
63 return PassDebugging >= Executions;
69 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
71 OS << "Releasing pass '";
73 OS << "Running pass '";
75 OS << P->getPassName() << "'";
78 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
89 else if (isa<BasicBlock>(V))
95 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
102 //===----------------------------------------------------------------------===//
105 /// BBPassManager manages BasicBlockPass. It batches all the
106 /// pass together and sequence them to process one basic block before
107 /// processing next basic block.
108 class VISIBILITY_HIDDEN BBPassManager : public PMDataManager,
109 public FunctionPass {
113 explicit BBPassManager(int Depth)
114 : PMDataManager(Depth), FunctionPass(&ID) {}
116 /// Execute all of the passes scheduled for execution. Keep track of
117 /// whether any of the passes modifies the function, and if so, return true.
118 bool runOnFunction(Function &F);
120 /// Pass Manager itself does not invalidate any analysis info.
121 void getAnalysisUsage(AnalysisUsage &Info) const {
122 Info.setPreservesAll();
125 bool doInitialization(Module &M);
126 bool doInitialization(Function &F);
127 bool doFinalization(Module &M);
128 bool doFinalization(Function &F);
130 virtual const char *getPassName() const {
131 return "BasicBlock Pass Manager";
134 // Print passes managed by this manager
135 void dumpPassStructure(unsigned Offset) {
136 llvm::errs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
137 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
138 BasicBlockPass *BP = getContainedPass(Index);
139 BP->dumpPassStructure(Offset + 1);
140 dumpLastUses(BP, Offset+1);
144 BasicBlockPass *getContainedPass(unsigned N) {
145 assert(N < PassVector.size() && "Pass number out of range!");
146 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
150 virtual PassManagerType getPassManagerType() const {
151 return PMT_BasicBlockPassManager;
155 char BBPassManager::ID = 0;
160 //===----------------------------------------------------------------------===//
161 // FunctionPassManagerImpl
163 /// FunctionPassManagerImpl manages FPPassManagers
164 class FunctionPassManagerImpl : public Pass,
165 public PMDataManager,
166 public PMTopLevelManager {
171 explicit FunctionPassManagerImpl(int Depth) :
172 Pass(&ID), PMDataManager(Depth),
173 PMTopLevelManager(TLM_Function), wasRun(false) { }
175 /// add - Add a pass to the queue of passes to run. This passes ownership of
176 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
177 /// will be destroyed as well, so there is no need to delete the pass. This
178 /// implies that all passes MUST be allocated with 'new'.
183 // Prepare for running an on the fly pass, freeing memory if needed
184 // from a previous run.
185 void releaseMemoryOnTheFly();
187 /// run - Execute all of the passes scheduled for execution. Keep track of
188 /// whether any of the passes modifies the module, and if so, return true.
189 bool run(Function &F);
191 /// doInitialization - Run all of the initializers for the function passes.
193 bool doInitialization(Module &M);
195 /// doFinalization - Run all of the finalizers for the function passes.
197 bool doFinalization(Module &M);
199 /// Pass Manager itself does not invalidate any analysis info.
200 void getAnalysisUsage(AnalysisUsage &Info) const {
201 Info.setPreservesAll();
204 inline void addTopLevelPass(Pass *P) {
206 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
208 // P is a immutable pass and it will be managed by this
209 // top level manager. Set up analysis resolver to connect them.
210 AnalysisResolver *AR = new AnalysisResolver(*this);
212 initializeAnalysisImpl(P);
213 addImmutablePass(IP);
214 recordAvailableAnalysis(IP);
216 P->assignPassManager(activeStack);
221 FPPassManager *getContainedManager(unsigned N) {
222 assert(N < PassManagers.size() && "Pass number out of range!");
223 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
228 char FunctionPassManagerImpl::ID = 0;
229 //===----------------------------------------------------------------------===//
232 /// MPPassManager manages ModulePasses and function pass managers.
233 /// It batches all Module passes and function pass managers together and
234 /// sequences them to process one module.
235 class MPPassManager : public Pass, public PMDataManager {
238 explicit MPPassManager(int Depth) :
239 Pass(&ID), PMDataManager(Depth) { }
241 // Delete on the fly managers.
242 virtual ~MPPassManager() {
243 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
244 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
246 FunctionPassManagerImpl *FPP = I->second;
251 /// run - Execute all of the passes scheduled for execution. Keep track of
252 /// whether any of the passes modifies the module, and if so, return true.
253 bool runOnModule(Module &M);
255 /// Pass Manager itself does not invalidate any analysis info.
256 void getAnalysisUsage(AnalysisUsage &Info) const {
257 Info.setPreservesAll();
260 /// Add RequiredPass into list of lower level passes required by pass P.
261 /// RequiredPass is run on the fly by Pass Manager when P requests it
262 /// through getAnalysis interface.
263 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
265 /// Return function pass corresponding to PassInfo PI, that is
266 /// required by module pass MP. Instantiate analysis pass, by using
267 /// its runOnFunction() for function F.
268 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
270 virtual const char *getPassName() const {
271 return "Module Pass Manager";
274 // Print passes managed by this manager
275 void dumpPassStructure(unsigned Offset) {
276 llvm::errs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
277 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
278 ModulePass *MP = getContainedPass(Index);
279 MP->dumpPassStructure(Offset + 1);
280 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
281 OnTheFlyManagers.find(MP);
282 if (I != OnTheFlyManagers.end())
283 I->second->dumpPassStructure(Offset + 2);
284 dumpLastUses(MP, Offset+1);
288 ModulePass *getContainedPass(unsigned N) {
289 assert(N < PassVector.size() && "Pass number out of range!");
290 return static_cast<ModulePass *>(PassVector[N]);
293 virtual PassManagerType getPassManagerType() const {
294 return PMT_ModulePassManager;
298 /// Collection of on the fly FPPassManagers. These managers manage
299 /// function passes that are required by module passes.
300 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
303 char MPPassManager::ID = 0;
304 //===----------------------------------------------------------------------===//
308 /// PassManagerImpl manages MPPassManagers
309 class PassManagerImpl : public Pass,
310 public PMDataManager,
311 public PMTopLevelManager {
315 explicit PassManagerImpl(int Depth) :
316 Pass(&ID), PMDataManager(Depth), PMTopLevelManager(TLM_Pass) { }
318 /// add - Add a pass to the queue of passes to run. This passes ownership of
319 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
320 /// will be destroyed as well, so there is no need to delete the pass. This
321 /// implies that all passes MUST be allocated with 'new'.
326 /// run - Execute all of the passes scheduled for execution. Keep track of
327 /// whether any of the passes modifies the module, and if so, return true.
330 /// Pass Manager itself does not invalidate any analysis info.
331 void getAnalysisUsage(AnalysisUsage &Info) const {
332 Info.setPreservesAll();
335 inline void addTopLevelPass(Pass *P) {
336 if (ImmutablePass *IP = dynamic_cast<ImmutablePass *> (P)) {
338 // P is a immutable pass and it will be managed by this
339 // top level manager. Set up analysis resolver to connect them.
340 AnalysisResolver *AR = new AnalysisResolver(*this);
342 initializeAnalysisImpl(P);
343 addImmutablePass(IP);
344 recordAvailableAnalysis(IP);
346 P->assignPassManager(activeStack);
350 MPPassManager *getContainedManager(unsigned N) {
351 assert(N < PassManagers.size() && "Pass number out of range!");
352 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
357 char PassManagerImpl::ID = 0;
358 } // End of llvm namespace
362 //===----------------------------------------------------------------------===//
363 /// TimingInfo Class - This class is used to calculate information about the
364 /// amount of time each pass takes to execute. This only happens when
365 /// -time-passes is enabled on the command line.
368 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
370 class VISIBILITY_HIDDEN TimingInfo {
371 std::map<Pass*, Timer> TimingData;
375 // Use 'create' member to get this.
376 TimingInfo() : TG("... Pass execution timing report ...") {}
378 // TimingDtor - Print out information about timing information
380 // Delete all of the timers...
382 // TimerGroup is deleted next, printing the report.
385 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
386 // to a non null value (if the -time-passes option is enabled) or it leaves it
387 // null. It may be called multiple times.
388 static void createTheTimeInfo();
390 /// passStarted - This method creates a timer for the given pass if it doesn't
391 /// already have one, and starts the timer.
392 Timer *passStarted(Pass *P) {
393 if (dynamic_cast<PMDataManager *>(P))
396 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
397 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
398 if (I == TimingData.end())
399 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
400 Timer *T = &I->second;
406 } // End of anon namespace
408 static TimingInfo *TheTimeInfo;
410 //===----------------------------------------------------------------------===//
411 // PMTopLevelManager implementation
413 /// Initialize top level manager. Create first pass manager.
414 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
416 MPPassManager *MPP = new MPPassManager(1);
417 MPP->setTopLevelManager(this);
419 activeStack.push(MPP);
420 } else if (t == TLM_Function) {
421 FPPassManager *FPP = new FPPassManager(1);
422 FPP->setTopLevelManager(this);
424 activeStack.push(FPP);
428 /// Set pass P as the last user of the given analysis passes.
429 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
431 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
432 E = AnalysisPasses.end(); I != E; ++I) {
439 // If AP is the last user of other passes then make P last user of
441 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
442 LUE = LastUser.end(); LUI != LUE; ++LUI) {
443 if (LUI->second == AP)
444 // DenseMap iterator is not invalidated here because
445 // this is just updating exisitng entry.
446 LastUser[LUI->first] = P;
451 /// Collect passes whose last user is P
452 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
454 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
455 InversedLastUser.find(P);
456 if (DMI == InversedLastUser.end())
459 SmallPtrSet<Pass *, 8> &LU = DMI->second;
460 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
461 E = LU.end(); I != E; ++I) {
462 LastUses.push_back(*I);
467 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
468 AnalysisUsage *AnUsage = NULL;
469 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
470 if (DMI != AnUsageMap.end())
471 AnUsage = DMI->second;
473 AnUsage = new AnalysisUsage();
474 P->getAnalysisUsage(*AnUsage);
475 AnUsageMap[P] = AnUsage;
480 /// Schedule pass P for execution. Make sure that passes required by
481 /// P are run before P is run. Update analysis info maintained by
482 /// the manager. Remove dead passes. This is a recursive function.
483 void PMTopLevelManager::schedulePass(Pass *P) {
485 // TODO : Allocate function manager for this pass, other wise required set
486 // may be inserted into previous function manager
488 // Give pass a chance to prepare the stage.
489 P->preparePassManager(activeStack);
491 // If P is an analysis pass and it is available then do not
492 // generate the analysis again. Stale analysis info should not be
493 // available at this point.
494 if (P->getPassInfo() &&
495 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
500 AnalysisUsage *AnUsage = findAnalysisUsage(P);
502 bool checkAnalysis = true;
503 while (checkAnalysis) {
504 checkAnalysis = false;
506 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
507 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
508 E = RequiredSet.end(); I != E; ++I) {
510 Pass *AnalysisPass = findAnalysisPass(*I);
512 AnalysisPass = (*I)->createPass();
513 if (P->getPotentialPassManagerType () ==
514 AnalysisPass->getPotentialPassManagerType())
515 // Schedule analysis pass that is managed by the same pass manager.
516 schedulePass(AnalysisPass);
517 else if (P->getPotentialPassManagerType () >
518 AnalysisPass->getPotentialPassManagerType()) {
519 // Schedule analysis pass that is managed by a new manager.
520 schedulePass(AnalysisPass);
521 // Recheck analysis passes to ensure that required analysises that
522 // are already checked are still available.
523 checkAnalysis = true;
526 // Do not schedule this analysis. Lower level analsyis
527 // passes are run on the fly.
533 // Now all required passes are available.
537 /// Find the pass that implements Analysis AID. Search immutable
538 /// passes and all pass managers. If desired pass is not found
539 /// then return NULL.
540 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
543 // Check pass managers
544 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
545 E = PassManagers.end(); P == NULL && I != E; ++I) {
546 PMDataManager *PMD = *I;
547 P = PMD->findAnalysisPass(AID, false);
550 // Check other pass managers
551 for (SmallVector<PMDataManager *, 8>::iterator
552 I = IndirectPassManagers.begin(),
553 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
554 P = (*I)->findAnalysisPass(AID, false);
556 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
557 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
558 const PassInfo *PI = (*I)->getPassInfo();
562 // If Pass not found then check the interfaces implemented by Immutable Pass
564 const std::vector<const PassInfo*> &ImmPI =
565 PI->getInterfacesImplemented();
566 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
574 // Print passes managed by this top level manager.
575 void PMTopLevelManager::dumpPasses() const {
577 if (PassDebugging < Structure)
580 // Print out the immutable passes
581 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
582 ImmutablePasses[i]->dumpPassStructure(0);
585 // Every class that derives from PMDataManager also derives from Pass
586 // (sometimes indirectly), but there's no inheritance relationship
587 // between PMDataManager and Pass, so we have to dynamic_cast to get
588 // from a PMDataManager* to a Pass*.
589 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
590 E = PassManagers.end(); I != E; ++I)
591 dynamic_cast<Pass *>(*I)->dumpPassStructure(1);
594 void PMTopLevelManager::dumpArguments() const {
596 if (PassDebugging < Arguments)
599 errs() << "Pass Arguments: ";
600 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
601 E = PassManagers.end(); I != E; ++I)
602 (*I)->dumpPassArguments();
606 void PMTopLevelManager::initializeAllAnalysisInfo() {
607 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
608 E = PassManagers.end(); I != E; ++I)
609 (*I)->initializeAnalysisInfo();
611 // Initailize other pass managers
612 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
613 E = IndirectPassManagers.end(); I != E; ++I)
614 (*I)->initializeAnalysisInfo();
616 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
617 DME = LastUser.end(); DMI != DME; ++DMI) {
618 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
619 InversedLastUser.find(DMI->second);
620 if (InvDMI != InversedLastUser.end()) {
621 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
622 L.insert(DMI->first);
624 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
625 InversedLastUser[DMI->second] = L;
631 PMTopLevelManager::~PMTopLevelManager() {
632 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
633 E = PassManagers.end(); I != E; ++I)
636 for (SmallVector<ImmutablePass *, 8>::iterator
637 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
640 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
641 DME = AnUsageMap.end(); DMI != DME; ++DMI)
645 //===----------------------------------------------------------------------===//
646 // PMDataManager implementation
648 /// Augement AvailableAnalysis by adding analysis made available by pass P.
649 void PMDataManager::recordAvailableAnalysis(Pass *P) {
650 const PassInfo *PI = P->getPassInfo();
653 AvailableAnalysis[PI] = P;
655 //This pass is the current implementation of all of the interfaces it
656 //implements as well.
657 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
658 for (unsigned i = 0, e = II.size(); i != e; ++i)
659 AvailableAnalysis[II[i]] = P;
662 // Return true if P preserves high level analysis used by other
663 // passes managed by this manager
664 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
665 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
666 if (AnUsage->getPreservesAll())
669 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
670 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
671 E = HigherLevelAnalysis.end(); I != E; ++I) {
673 if (!dynamic_cast<ImmutablePass*>(P1) &&
674 std::find(PreservedSet.begin(), PreservedSet.end(),
675 P1->getPassInfo()) ==
683 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
684 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
685 // Don't do this unless assertions are enabled.
689 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
690 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
692 // Verify preserved analysis
693 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
694 E = PreservedSet.end(); I != E; ++I) {
696 if (Pass *AP = findAnalysisPass(AID, true)) {
699 if (TheTimeInfo) T = TheTimeInfo->passStarted(AP);
700 AP->verifyAnalysis();
701 if (T) T->stopTimer();
706 /// Remove Analysis not preserved by Pass P
707 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
708 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
709 if (AnUsage->getPreservesAll())
712 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
713 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
714 E = AvailableAnalysis.end(); I != E; ) {
715 std::map<AnalysisID, Pass*>::iterator Info = I++;
716 if (!dynamic_cast<ImmutablePass*>(Info->second)
717 && std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
718 PreservedSet.end()) {
719 // Remove this analysis
720 if (PassDebugging >= Details) {
721 Pass *S = Info->second;
722 errs() << " -- '" << P->getPassName() << "' is not preserving '";
723 errs() << S->getPassName() << "'\n";
725 AvailableAnalysis.erase(Info);
729 // Check inherited analysis also. If P is not preserving analysis
730 // provided by parent manager then remove it here.
731 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
733 if (!InheritedAnalysis[Index])
736 for (std::map<AnalysisID, Pass*>::iterator
737 I = InheritedAnalysis[Index]->begin(),
738 E = InheritedAnalysis[Index]->end(); I != E; ) {
739 std::map<AnalysisID, Pass *>::iterator Info = I++;
740 if (!dynamic_cast<ImmutablePass*>(Info->second) &&
741 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
743 // Remove this analysis
744 InheritedAnalysis[Index]->erase(Info);
749 /// Remove analysis passes that are not used any longer
750 void PMDataManager::removeDeadPasses(Pass *P, const StringRef &Msg,
751 enum PassDebuggingString DBG_STR) {
753 SmallVector<Pass *, 12> DeadPasses;
755 // If this is a on the fly manager then it does not have TPM.
759 TPM->collectLastUses(DeadPasses, P);
761 if (PassDebugging >= Details && !DeadPasses.empty()) {
762 errs() << " -*- '" << P->getPassName();
763 errs() << "' is the last user of following pass instances.";
764 errs() << " Free these instances\n";
767 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
768 E = DeadPasses.end(); I != E; ++I)
769 freePass(*I, Msg, DBG_STR);
772 void PMDataManager::freePass(Pass *P, const StringRef &Msg,
773 enum PassDebuggingString DBG_STR) {
774 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
777 // If the pass crashes releasing memory, remember this.
778 PassManagerPrettyStackEntry X(P);
780 Timer *T = StartPassTimer(P);
785 if (const PassInfo *PI = P->getPassInfo()) {
786 // Remove the pass itself (if it is not already removed).
787 AvailableAnalysis.erase(PI);
789 // Remove all interfaces this pass implements, for which it is also
790 // listed as the available implementation.
791 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
792 for (unsigned i = 0, e = II.size(); i != e; ++i) {
793 std::map<AnalysisID, Pass*>::iterator Pos =
794 AvailableAnalysis.find(II[i]);
795 if (Pos != AvailableAnalysis.end() && Pos->second == P)
796 AvailableAnalysis.erase(Pos);
801 /// Add pass P into the PassVector. Update
802 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
803 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
804 // This manager is going to manage pass P. Set up analysis resolver
806 AnalysisResolver *AR = new AnalysisResolver(*this);
809 // If a FunctionPass F is the last user of ModulePass info M
810 // then the F's manager, not F, records itself as a last user of M.
811 SmallVector<Pass *, 12> TransferLastUses;
813 if (!ProcessAnalysis) {
815 PassVector.push_back(P);
819 // At the moment, this pass is the last user of all required passes.
820 SmallVector<Pass *, 12> LastUses;
821 SmallVector<Pass *, 8> RequiredPasses;
822 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
824 unsigned PDepth = this->getDepth();
826 collectRequiredAnalysis(RequiredPasses,
827 ReqAnalysisNotAvailable, P);
828 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
829 E = RequiredPasses.end(); I != E; ++I) {
830 Pass *PRequired = *I;
833 assert(PRequired->getResolver() && "Analysis Resolver is not set");
834 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
835 RDepth = DM.getDepth();
837 if (PDepth == RDepth)
838 LastUses.push_back(PRequired);
839 else if (PDepth > RDepth) {
840 // Let the parent claim responsibility of last use
841 TransferLastUses.push_back(PRequired);
842 // Keep track of higher level analysis used by this manager.
843 HigherLevelAnalysis.push_back(PRequired);
845 llvm_unreachable("Unable to accomodate Required Pass");
848 // Set P as P's last user until someone starts using P.
849 // However, if P is a Pass Manager then it does not need
850 // to record its last user.
851 if (!dynamic_cast<PMDataManager *>(P))
852 LastUses.push_back(P);
853 TPM->setLastUser(LastUses, P);
855 if (!TransferLastUses.empty()) {
856 Pass *My_PM = dynamic_cast<Pass *>(this);
857 TPM->setLastUser(TransferLastUses, My_PM);
858 TransferLastUses.clear();
861 // Now, take care of required analysises that are not available.
862 for (SmallVector<AnalysisID, 8>::iterator
863 I = ReqAnalysisNotAvailable.begin(),
864 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
865 Pass *AnalysisPass = (*I)->createPass();
866 this->addLowerLevelRequiredPass(P, AnalysisPass);
869 // Take a note of analysis required and made available by this pass.
870 // Remove the analysis not preserved by this pass
871 removeNotPreservedAnalysis(P);
872 recordAvailableAnalysis(P);
875 PassVector.push_back(P);
879 /// Populate RP with analysis pass that are required by
880 /// pass P and are available. Populate RP_NotAvail with analysis
881 /// pass that are required by pass P but are not available.
882 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
883 SmallVector<AnalysisID, 8> &RP_NotAvail,
885 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
886 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
887 for (AnalysisUsage::VectorType::const_iterator
888 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
889 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
890 RP.push_back(AnalysisPass);
892 RP_NotAvail.push_back(*I);
895 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
896 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
897 E = IDs.end(); I != E; ++I) {
898 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
899 RP.push_back(AnalysisPass);
901 RP_NotAvail.push_back(*I);
905 // All Required analyses should be available to the pass as it runs! Here
906 // we fill in the AnalysisImpls member of the pass so that it can
907 // successfully use the getAnalysis() method to retrieve the
908 // implementations it needs.
910 void PMDataManager::initializeAnalysisImpl(Pass *P) {
911 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
913 for (AnalysisUsage::VectorType::const_iterator
914 I = AnUsage->getRequiredSet().begin(),
915 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
916 Pass *Impl = findAnalysisPass(*I, true);
918 // This may be analysis pass that is initialized on the fly.
919 // If that is not the case then it will raise an assert when it is used.
921 AnalysisResolver *AR = P->getResolver();
922 assert(AR && "Analysis Resolver is not set");
923 AR->addAnalysisImplsPair(*I, Impl);
927 /// Find the pass that implements Analysis AID. If desired pass is not found
928 /// then return NULL.
929 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
931 // Check if AvailableAnalysis map has one entry.
932 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
934 if (I != AvailableAnalysis.end())
937 // Search Parents through TopLevelManager
939 return TPM->findAnalysisPass(AID);
944 // Print list of passes that are last used by P.
945 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
947 SmallVector<Pass *, 12> LUses;
949 // If this is a on the fly manager then it does not have TPM.
953 TPM->collectLastUses(LUses, P);
955 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
956 E = LUses.end(); I != E; ++I) {
957 llvm::errs() << "--" << std::string(Offset*2, ' ');
958 (*I)->dumpPassStructure(0);
962 void PMDataManager::dumpPassArguments() const {
963 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
964 E = PassVector.end(); I != E; ++I) {
965 if (PMDataManager *PMD = dynamic_cast<PMDataManager *>(*I))
966 PMD->dumpPassArguments();
968 if (const PassInfo *PI = (*I)->getPassInfo())
969 if (!PI->isAnalysisGroup())
970 errs() << " -" << PI->getPassArgument();
974 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
975 enum PassDebuggingString S2,
976 const StringRef &Msg) {
977 if (PassDebugging < Executions)
979 errs() << (void*)this << std::string(getDepth()*2+1, ' ');
982 errs() << "Executing Pass '" << P->getPassName();
984 case MODIFICATION_MSG:
985 errs() << "Made Modification '" << P->getPassName();
988 errs() << " Freeing Pass '" << P->getPassName();
994 case ON_BASICBLOCK_MSG:
995 errs() << "' on BasicBlock '" << Msg << "'...\n";
997 case ON_FUNCTION_MSG:
998 errs() << "' on Function '" << Msg << "'...\n";
1001 errs() << "' on Module '" << Msg << "'...\n";
1004 errs() << "' on Loop '" << Msg << "'...\n";
1007 errs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1014 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1015 if (PassDebugging < Details)
1018 AnalysisUsage analysisUsage;
1019 P->getAnalysisUsage(analysisUsage);
1020 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1023 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1024 if (PassDebugging < Details)
1027 AnalysisUsage analysisUsage;
1028 P->getAnalysisUsage(analysisUsage);
1029 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1032 void PMDataManager::dumpAnalysisUsage(const StringRef &Msg, const Pass *P,
1033 const AnalysisUsage::VectorType &Set) const {
1034 assert(PassDebugging >= Details);
1037 errs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1038 for (unsigned i = 0; i != Set.size(); ++i) {
1039 if (i) errs() << ',';
1040 errs() << ' ' << Set[i]->getPassName();
1045 /// Add RequiredPass into list of lower level passes required by pass P.
1046 /// RequiredPass is run on the fly by Pass Manager when P requests it
1047 /// through getAnalysis interface.
1048 /// This should be handled by specific pass manager.
1049 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1051 TPM->dumpArguments();
1055 // Module Level pass may required Function Level analysis info
1056 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1057 // to provide this on demand. In that case, in Pass manager terminology,
1058 // module level pass is requiring lower level analysis info managed by
1059 // lower level pass manager.
1061 // When Pass manager is not able to order required analysis info, Pass manager
1062 // checks whether any lower level manager will be able to provide this
1063 // analysis info on demand or not.
1065 errs() << "Unable to schedule '" << RequiredPass->getPassName();
1066 errs() << "' required by '" << P->getPassName() << "'\n";
1068 llvm_unreachable("Unable to schedule pass");
1072 PMDataManager::~PMDataManager() {
1073 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1074 E = PassVector.end(); I != E; ++I)
1078 //===----------------------------------------------------------------------===//
1079 // NOTE: Is this the right place to define this method ?
1080 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1081 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1082 return PM.findAnalysisPass(ID, dir);
1085 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1087 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1090 //===----------------------------------------------------------------------===//
1091 // BBPassManager implementation
1093 /// Execute all of the passes scheduled for execution by invoking
1094 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1095 /// the function, and if so, return true.
1096 bool BBPassManager::runOnFunction(Function &F) {
1097 if (F.isDeclaration())
1100 bool Changed = doInitialization(F);
1102 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1103 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1104 BasicBlockPass *BP = getContainedPass(Index);
1106 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1107 dumpRequiredSet(BP);
1109 initializeAnalysisImpl(BP);
1112 // If the pass crashes, remember this.
1113 PassManagerPrettyStackEntry X(BP, *I);
1115 Timer *T = StartPassTimer(BP);
1116 Changed |= BP->runOnBasicBlock(*I);
1117 StopPassTimer(BP, T);
1121 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1123 dumpPreservedSet(BP);
1125 verifyPreservedAnalysis(BP);
1126 removeNotPreservedAnalysis(BP);
1127 recordAvailableAnalysis(BP);
1128 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1131 return Changed |= doFinalization(F);
1134 // Implement doInitialization and doFinalization
1135 bool BBPassManager::doInitialization(Module &M) {
1136 bool Changed = false;
1138 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1139 Changed |= getContainedPass(Index)->doInitialization(M);
1144 bool BBPassManager::doFinalization(Module &M) {
1145 bool Changed = false;
1147 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1148 Changed |= getContainedPass(Index)->doFinalization(M);
1153 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 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 llvm_report_error("Error reading bitcode file: " + errstr);
1217 /// doInitialization - Run all of the initializers for the function passes.
1219 bool FunctionPassManager::doInitialization() {
1220 return FPM->doInitialization(*MP->getModule());
1223 /// doFinalization - Run all of the finalizers for the function passes.
1225 bool FunctionPassManager::doFinalization() {
1226 return FPM->doFinalization(*MP->getModule());
1229 //===----------------------------------------------------------------------===//
1230 // FunctionPassManagerImpl implementation
1232 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1233 bool Changed = false;
1235 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1236 Changed |= getContainedManager(Index)->doInitialization(M);
1241 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1242 bool Changed = false;
1244 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1245 Changed |= getContainedManager(Index)->doFinalization(M);
1250 /// cleanup - After running all passes, clean up pass manager cache.
1251 void FPPassManager::cleanup() {
1252 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1253 FunctionPass *FP = getContainedPass(Index);
1254 AnalysisResolver *AR = FP->getResolver();
1255 assert(AR && "Analysis Resolver is not set");
1256 AR->clearAnalysisImpls();
1260 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1263 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1264 FPPassManager *FPPM = getContainedManager(Index);
1265 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1266 FPPM->getContainedPass(Index)->releaseMemory();
1272 // Execute all the passes managed by this top level manager.
1273 // Return true if any function is modified by a pass.
1274 bool FunctionPassManagerImpl::run(Function &F) {
1275 bool Changed = false;
1276 TimingInfo::createTheTimeInfo();
1281 initializeAllAnalysisInfo();
1282 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1283 Changed |= getContainedManager(Index)->runOnFunction(F);
1285 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1286 getContainedManager(Index)->cleanup();
1292 //===----------------------------------------------------------------------===//
1293 // FPPassManager implementation
1295 char FPPassManager::ID = 0;
1296 /// Print passes managed by this manager
1297 void FPPassManager::dumpPassStructure(unsigned Offset) {
1298 llvm::errs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1299 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1300 FunctionPass *FP = getContainedPass(Index);
1301 FP->dumpPassStructure(Offset + 1);
1302 dumpLastUses(FP, Offset+1);
1307 /// Execute all of the passes scheduled for execution by invoking
1308 /// runOnFunction method. Keep track of whether any of the passes modifies
1309 /// the function, and if so, return true.
1310 bool FPPassManager::runOnFunction(Function &F) {
1311 if (F.isDeclaration())
1314 bool Changed = false;
1316 // Collect inherited analysis from Module level pass manager.
1317 populateInheritedAnalysis(TPM->activeStack);
1319 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1320 FunctionPass *FP = getContainedPass(Index);
1322 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1323 dumpRequiredSet(FP);
1325 initializeAnalysisImpl(FP);
1328 PassManagerPrettyStackEntry X(FP, F);
1330 Timer *T = StartPassTimer(FP);
1331 Changed |= FP->runOnFunction(F);
1332 StopPassTimer(FP, T);
1336 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1337 dumpPreservedSet(FP);
1339 verifyPreservedAnalysis(FP);
1340 removeNotPreservedAnalysis(FP);
1341 recordAvailableAnalysis(FP);
1342 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1347 bool FPPassManager::runOnModule(Module &M) {
1348 bool Changed = doInitialization(M);
1350 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1353 return Changed |= doFinalization(M);
1356 bool FPPassManager::doInitialization(Module &M) {
1357 bool Changed = false;
1359 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1360 Changed |= getContainedPass(Index)->doInitialization(M);
1365 bool FPPassManager::doFinalization(Module &M) {
1366 bool Changed = false;
1368 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1369 Changed |= getContainedPass(Index)->doFinalization(M);
1374 //===----------------------------------------------------------------------===//
1375 // MPPassManager implementation
1377 /// Execute all of the passes scheduled for execution by invoking
1378 /// runOnModule method. Keep track of whether any of the passes modifies
1379 /// the module, and if so, return true.
1381 MPPassManager::runOnModule(Module &M) {
1382 bool Changed = false;
1384 // Initialize on-the-fly passes
1385 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1386 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1388 FunctionPassManagerImpl *FPP = I->second;
1389 Changed |= FPP->doInitialization(M);
1392 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1393 ModulePass *MP = getContainedPass(Index);
1395 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG,
1396 M.getModuleIdentifier().c_str());
1397 dumpRequiredSet(MP);
1399 initializeAnalysisImpl(MP);
1402 PassManagerPrettyStackEntry X(MP, M);
1403 Timer *T = StartPassTimer(MP);
1404 Changed |= MP->runOnModule(M);
1405 StopPassTimer(MP, T);
1409 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1410 M.getModuleIdentifier().c_str());
1411 dumpPreservedSet(MP);
1413 verifyPreservedAnalysis(MP);
1414 removeNotPreservedAnalysis(MP);
1415 recordAvailableAnalysis(MP);
1416 removeDeadPasses(MP, M.getModuleIdentifier().c_str(), ON_MODULE_MSG);
1419 // Finalize on-the-fly passes
1420 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1421 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1423 FunctionPassManagerImpl *FPP = I->second;
1424 // We don't know when is the last time an on-the-fly pass is run,
1425 // so we need to releaseMemory / finalize here
1426 FPP->releaseMemoryOnTheFly();
1427 Changed |= FPP->doFinalization(M);
1432 /// Add RequiredPass into list of lower level passes required by pass P.
1433 /// RequiredPass is run on the fly by Pass Manager when P requests it
1434 /// through getAnalysis interface.
1435 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1436 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1437 "Unable to handle Pass that requires lower level Analysis pass");
1438 assert((P->getPotentialPassManagerType() <
1439 RequiredPass->getPotentialPassManagerType()) &&
1440 "Unable to handle Pass that requires lower level Analysis pass");
1442 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1444 FPP = new FunctionPassManagerImpl(0);
1445 // FPP is the top level manager.
1446 FPP->setTopLevelManager(FPP);
1448 OnTheFlyManagers[P] = FPP;
1450 FPP->add(RequiredPass);
1452 // Register P as the last user of RequiredPass.
1453 SmallVector<Pass *, 12> LU;
1454 LU.push_back(RequiredPass);
1455 FPP->setLastUser(LU, P);
1458 /// Return function pass corresponding to PassInfo PI, that is
1459 /// required by module pass MP. Instantiate analysis pass, by using
1460 /// its runOnFunction() for function F.
1461 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1462 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1463 assert(FPP && "Unable to find on the fly pass");
1465 FPP->releaseMemoryOnTheFly();
1467 return (dynamic_cast<PMTopLevelManager *>(FPP))->findAnalysisPass(PI);
1471 //===----------------------------------------------------------------------===//
1472 // PassManagerImpl implementation
1474 /// run - Execute all of the passes scheduled for execution. Keep track of
1475 /// whether any of the passes modifies the module, and if so, return true.
1476 bool PassManagerImpl::run(Module &M) {
1477 bool Changed = false;
1478 TimingInfo::createTheTimeInfo();
1483 initializeAllAnalysisInfo();
1484 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1485 Changed |= getContainedManager(Index)->runOnModule(M);
1489 //===----------------------------------------------------------------------===//
1490 // PassManager implementation
1492 /// Create new pass manager
1493 PassManager::PassManager() {
1494 PM = new PassManagerImpl(0);
1495 // PM is the top level manager
1496 PM->setTopLevelManager(PM);
1499 PassManager::~PassManager() {
1503 /// add - Add a pass to the queue of passes to run. This passes ownership of
1504 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1505 /// will be destroyed as well, so there is no need to delete the pass. This
1506 /// implies that all passes MUST be allocated with 'new'.
1507 void PassManager::add(Pass *P) {
1511 /// run - Execute all of the passes scheduled for execution. Keep track of
1512 /// whether any of the passes modifies the module, and if so, return true.
1513 bool PassManager::run(Module &M) {
1517 //===----------------------------------------------------------------------===//
1518 // TimingInfo Class - This class is used to calculate information about the
1519 // amount of time each pass takes to execute. This only happens with
1520 // -time-passes is enabled on the command line.
1522 bool llvm::TimePassesIsEnabled = false;
1523 static cl::opt<bool,true>
1524 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1525 cl::desc("Time each pass, printing elapsed time for each on exit"));
1527 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1528 // a non null value (if the -time-passes option is enabled) or it leaves it
1529 // null. It may be called multiple times.
1530 void TimingInfo::createTheTimeInfo() {
1531 if (!TimePassesIsEnabled || TheTimeInfo) return;
1533 // Constructed the first time this is called, iff -time-passes is enabled.
1534 // This guarantees that the object will be constructed before static globals,
1535 // thus it will be destroyed before them.
1536 static ManagedStatic<TimingInfo> TTI;
1537 TheTimeInfo = &*TTI;
1540 /// If TimingInfo is enabled then start pass timer.
1541 Timer *llvm::StartPassTimer(Pass *P) {
1543 return TheTimeInfo->passStarted(P);
1547 /// If TimingInfo is enabled then stop pass timer.
1548 void llvm::StopPassTimer(Pass *P, Timer *T) {
1549 if (T) T->stopTimer();
1552 //===----------------------------------------------------------------------===//
1553 // PMStack implementation
1556 // Pop Pass Manager from the stack and clear its analysis info.
1557 void PMStack::pop() {
1559 PMDataManager *Top = this->top();
1560 Top->initializeAnalysisInfo();
1565 // Push PM on the stack and set its top level manager.
1566 void PMStack::push(PMDataManager *PM) {
1567 assert(PM && "Unable to push. Pass Manager expected");
1569 if (!this->empty()) {
1570 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1572 assert(TPM && "Unable to find top level manager");
1573 TPM->addIndirectPassManager(PM);
1574 PM->setTopLevelManager(TPM);
1580 // Dump content of the pass manager stack.
1581 void PMStack::dump() {
1582 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1583 E = S.end(); I != E; ++I)
1584 printf("%s ", dynamic_cast<Pass *>(*I)->getPassName());
1590 /// Find appropriate Module Pass Manager in the PM Stack and
1591 /// add self into that manager.
1592 void ModulePass::assignPassManager(PMStack &PMS,
1593 PassManagerType PreferredType) {
1594 // Find Module Pass Manager
1595 while(!PMS.empty()) {
1596 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1597 if (TopPMType == PreferredType)
1598 break; // We found desired pass manager
1599 else if (TopPMType > PMT_ModulePassManager)
1600 PMS.pop(); // Pop children pass managers
1604 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1605 PMS.top()->add(this);
1608 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1609 /// in the PM Stack and add self into that manager.
1610 void FunctionPass::assignPassManager(PMStack &PMS,
1611 PassManagerType PreferredType) {
1613 // Find Module Pass Manager
1614 while(!PMS.empty()) {
1615 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1620 FPPassManager *FPP = dynamic_cast<FPPassManager *>(PMS.top());
1622 // Create new Function Pass Manager
1624 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1625 PMDataManager *PMD = PMS.top();
1627 // [1] Create new Function Pass Manager
1628 FPP = new FPPassManager(PMD->getDepth() + 1);
1629 FPP->populateInheritedAnalysis(PMS);
1631 // [2] Set up new manager's top level manager
1632 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1633 TPM->addIndirectPassManager(FPP);
1635 // [3] Assign manager to manage this new manager. This may create
1636 // and push new managers into PMS
1637 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1639 // [4] Push new manager into PMS
1643 // Assign FPP as the manager of this pass.
1647 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1648 /// in the PM Stack and add self into that manager.
1649 void BasicBlockPass::assignPassManager(PMStack &PMS,
1650 PassManagerType PreferredType) {
1651 BBPassManager *BBP = NULL;
1653 // Basic Pass Manager is a leaf pass manager. It does not handle
1654 // any other pass manager.
1656 BBP = dynamic_cast<BBPassManager *>(PMS.top());
1658 // If leaf manager is not Basic Block Pass manager then create new
1659 // basic Block Pass manager.
1662 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1663 PMDataManager *PMD = PMS.top();
1665 // [1] Create new Basic Block Manager
1666 BBP = new BBPassManager(PMD->getDepth() + 1);
1668 // [2] Set up new manager's top level manager
1669 // Basic Block Pass Manager does not live by itself
1670 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1671 TPM->addIndirectPassManager(BBP);
1673 // [3] Assign manager to manage this new manager. This may create
1674 // and push new managers into PMS
1675 BBP->assignPassManager(PMS);
1677 // [4] Push new manager into PMS
1681 // Assign BBP as the manager of this pass.
1685 PassManagerBase::~PassManagerBase() {}
1687 /*===-- C Bindings --------------------------------------------------------===*/
1689 LLVMPassManagerRef LLVMCreatePassManager() {
1690 return wrap(new PassManager());
1693 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1694 return wrap(new FunctionPassManager(unwrap(P)));
1697 int LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1698 return unwrap<PassManager>(PM)->run(*unwrap(M));
1701 int LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1702 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1705 int LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1706 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1709 int LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1710 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1713 void LLVMDisposePassManager(LLVMPassManagerRef PM) {