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/PassManager.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Timer.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PassNameParser.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/Threading.h"
34 // See PassManagers.h for Pass Manager infrastructure overview.
38 //===----------------------------------------------------------------------===//
39 // Pass debugging information. Often it is useful to find out what pass is
40 // running when a crash occurs in a utility. When this library is compiled with
41 // debugging on, a command line option (--debug-pass) is enabled that causes the
42 // pass name to be printed before it executes.
45 // Different debug levels that can be enabled...
47 None, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(None , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
61 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
64 // Print IR out before/after specified passes.
66 PrintBefore("print-before",
67 llvm::cl::desc("Print IR before specified passes"));
70 PrintAfter("print-after",
71 llvm::cl::desc("Print IR after specified passes"));
74 PrintBeforeAll("print-before-all",
75 llvm::cl::desc("Print IR before each pass"),
78 PrintAfterAll("print-after-all",
79 llvm::cl::desc("Print IR after each pass"),
82 /// This is a helper to determine whether to print IR before or
85 static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
86 PassOptionList &PassesToPrint) {
87 if (const llvm::PassInfo *PI =
88 PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
89 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
90 const llvm::PassInfo *PassInf = PassesToPrint[i];
92 if (PassInf->getPassArgument() == PI->getPassArgument()) {
101 /// This is a utility to check whether a pass should have IR dumped
103 static bool ShouldPrintBeforePass(const void *PassID) {
104 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefore);
107 /// This is a utility to check whether a pass should have IR dumped
109 static bool ShouldPrintAfterPass(const void *PassID) {
110 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
113 } // End of llvm namespace
115 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
116 /// or higher is specified.
117 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
118 return PassDebugging >= Executions;
124 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
125 if (V == 0 && M == 0)
126 OS << "Releasing pass '";
128 OS << "Running pass '";
130 OS << P->getPassName() << "'";
133 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
142 if (isa<Function>(V))
144 else if (isa<BasicBlock>(V))
150 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
157 //===----------------------------------------------------------------------===//
160 /// BBPassManager manages BasicBlockPass. It batches all the
161 /// pass together and sequence them to process one basic block before
162 /// processing next basic block.
163 class BBPassManager : public PMDataManager, public FunctionPass {
167 explicit BBPassManager(int Depth)
168 : PMDataManager(Depth), FunctionPass(ID) {}
170 /// Execute all of the passes scheduled for execution. Keep track of
171 /// whether any of the passes modifies the function, and if so, return true.
172 bool runOnFunction(Function &F);
174 /// Pass Manager itself does not invalidate any analysis info.
175 void getAnalysisUsage(AnalysisUsage &Info) const {
176 Info.setPreservesAll();
179 bool doInitialization(Module &M);
180 bool doInitialization(Function &F);
181 bool doFinalization(Module &M);
182 bool doFinalization(Function &F);
184 virtual PMDataManager *getAsPMDataManager() { return this; }
185 virtual Pass *getAsPass() { return this; }
187 virtual const char *getPassName() const {
188 return "BasicBlock Pass Manager";
191 // Print passes managed by this manager
192 void dumpPassStructure(unsigned Offset) {
193 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
194 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
195 BasicBlockPass *BP = getContainedPass(Index);
196 BP->dumpPassStructure(Offset + 1);
197 dumpLastUses(BP, Offset+1);
201 BasicBlockPass *getContainedPass(unsigned N) {
202 assert(N < PassVector.size() && "Pass number out of range!");
203 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
207 virtual PassManagerType getPassManagerType() const {
208 return PMT_BasicBlockPassManager;
212 char BBPassManager::ID = 0;
217 //===----------------------------------------------------------------------===//
218 // FunctionPassManagerImpl
220 /// FunctionPassManagerImpl manages FPPassManagers
221 class FunctionPassManagerImpl : public Pass,
222 public PMDataManager,
223 public PMTopLevelManager {
228 explicit FunctionPassManagerImpl(int Depth) :
229 Pass(PT_PassManager, ID), PMDataManager(Depth),
230 PMTopLevelManager(TLM_Function), wasRun(false) { }
232 /// add - Add a pass to the queue of passes to run. This passes ownership of
233 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
234 /// will be destroyed as well, so there is no need to delete the pass. This
235 /// implies that all passes MUST be allocated with 'new'.
240 /// createPrinterPass - Get a function printer pass.
241 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
242 return createPrintFunctionPass(Banner, &O);
245 // Prepare for running an on the fly pass, freeing memory if needed
246 // from a previous run.
247 void releaseMemoryOnTheFly();
249 /// run - Execute all of the passes scheduled for execution. Keep track of
250 /// whether any of the passes modifies the module, and if so, return true.
251 bool run(Function &F);
253 /// doInitialization - Run all of the initializers for the function passes.
255 bool doInitialization(Module &M);
257 /// doFinalization - Run all of the finalizers for the function passes.
259 bool doFinalization(Module &M);
262 virtual PMDataManager *getAsPMDataManager() { return this; }
263 virtual Pass *getAsPass() { return this; }
265 /// Pass Manager itself does not invalidate any analysis info.
266 void getAnalysisUsage(AnalysisUsage &Info) const {
267 Info.setPreservesAll();
270 inline void addTopLevelPass(Pass *P) {
271 if (ImmutablePass *IP = P->getAsImmutablePass()) {
272 // P is a immutable pass and it will be managed by this
273 // top level manager. Set up analysis resolver to connect them.
274 AnalysisResolver *AR = new AnalysisResolver(*this);
276 initializeAnalysisImpl(P);
277 addImmutablePass(IP);
278 recordAvailableAnalysis(IP);
280 P->assignPassManager(activeStack, PMT_FunctionPassManager);
285 FPPassManager *getContainedManager(unsigned N) {
286 assert(N < PassManagers.size() && "Pass number out of range!");
287 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
292 char FunctionPassManagerImpl::ID = 0;
293 //===----------------------------------------------------------------------===//
296 /// MPPassManager manages ModulePasses and function pass managers.
297 /// It batches all Module passes and function pass managers together and
298 /// sequences them to process one module.
299 class MPPassManager : public Pass, public PMDataManager {
302 explicit MPPassManager(int Depth) :
303 Pass(PT_PassManager, ID), PMDataManager(Depth) { }
305 // Delete on the fly managers.
306 virtual ~MPPassManager() {
307 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
308 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
310 FunctionPassManagerImpl *FPP = I->second;
315 /// createPrinterPass - Get a module printer pass.
316 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
317 return createPrintModulePass(&O, false, Banner);
320 /// run - Execute all of the passes scheduled for execution. Keep track of
321 /// whether any of the passes modifies the module, and if so, return true.
322 bool runOnModule(Module &M);
324 /// Pass Manager itself does not invalidate any analysis info.
325 void getAnalysisUsage(AnalysisUsage &Info) const {
326 Info.setPreservesAll();
329 /// Add RequiredPass into list of lower level passes required by pass P.
330 /// RequiredPass is run on the fly by Pass Manager when P requests it
331 /// through getAnalysis interface.
332 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
334 /// Return function pass corresponding to PassInfo PI, that is
335 /// required by module pass MP. Instantiate analysis pass, by using
336 /// its runOnFunction() for function F.
337 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
339 virtual const char *getPassName() const {
340 return "Module Pass Manager";
343 virtual PMDataManager *getAsPMDataManager() { return this; }
344 virtual Pass *getAsPass() { return this; }
346 // Print passes managed by this manager
347 void dumpPassStructure(unsigned Offset) {
348 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
350 ModulePass *MP = getContainedPass(Index);
351 MP->dumpPassStructure(Offset + 1);
352 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
353 OnTheFlyManagers.find(MP);
354 if (I != OnTheFlyManagers.end())
355 I->second->dumpPassStructure(Offset + 2);
356 dumpLastUses(MP, Offset+1);
360 ModulePass *getContainedPass(unsigned N) {
361 assert(N < PassVector.size() && "Pass number out of range!");
362 return static_cast<ModulePass *>(PassVector[N]);
365 virtual PassManagerType getPassManagerType() const {
366 return PMT_ModulePassManager;
370 /// Collection of on the fly FPPassManagers. These managers manage
371 /// function passes that are required by module passes.
372 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
375 char MPPassManager::ID = 0;
376 //===----------------------------------------------------------------------===//
380 /// PassManagerImpl manages MPPassManagers
381 class PassManagerImpl : public Pass,
382 public PMDataManager,
383 public PMTopLevelManager {
387 explicit PassManagerImpl(int Depth) :
388 Pass(PT_PassManager, ID), PMDataManager(Depth),
389 PMTopLevelManager(TLM_Pass) { }
391 /// add - Add a pass to the queue of passes to run. This passes ownership of
392 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
393 /// will be destroyed as well, so there is no need to delete the pass. This
394 /// implies that all passes MUST be allocated with 'new'.
399 /// createPrinterPass - Get a module printer pass.
400 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
401 return createPrintModulePass(&O, false, Banner);
404 /// run - Execute all of the passes scheduled for execution. Keep track of
405 /// whether any of the passes modifies the module, and if so, return true.
408 /// Pass Manager itself does not invalidate any analysis info.
409 void getAnalysisUsage(AnalysisUsage &Info) const {
410 Info.setPreservesAll();
413 inline void addTopLevelPass(Pass *P) {
414 if (ImmutablePass *IP = P->getAsImmutablePass()) {
415 // P is a immutable pass and it will be managed by this
416 // top level manager. Set up analysis resolver to connect them.
417 AnalysisResolver *AR = new AnalysisResolver(*this);
419 initializeAnalysisImpl(P);
420 addImmutablePass(IP);
421 recordAvailableAnalysis(IP);
423 P->assignPassManager(activeStack, PMT_ModulePassManager);
427 virtual PMDataManager *getAsPMDataManager() { return this; }
428 virtual Pass *getAsPass() { return this; }
430 MPPassManager *getContainedManager(unsigned N) {
431 assert(N < PassManagers.size() && "Pass number out of range!");
432 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
437 char PassManagerImpl::ID = 0;
438 } // End of llvm namespace
442 //===----------------------------------------------------------------------===//
443 /// TimingInfo Class - This class is used to calculate information about the
444 /// amount of time each pass takes to execute. This only happens when
445 /// -time-passes is enabled on the command line.
448 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
451 DenseMap<Pass*, Timer*> TimingData;
454 // Use 'create' member to get this.
455 TimingInfo() : TG("... Pass execution timing report ...") {}
457 // TimingDtor - Print out information about timing information
459 // Delete all of the timers, which accumulate their info into the
461 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
462 E = TimingData.end(); I != E; ++I)
464 // TimerGroup is deleted next, printing the report.
467 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
468 // to a non null value (if the -time-passes option is enabled) or it leaves it
469 // null. It may be called multiple times.
470 static void createTheTimeInfo();
472 /// getPassTimer - Return the timer for the specified pass if it exists.
473 Timer *getPassTimer(Pass *P) {
474 if (P->getAsPMDataManager())
477 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
478 Timer *&T = TimingData[P];
480 T = new Timer(P->getPassName(), TG);
485 } // End of anon namespace
487 static TimingInfo *TheTimeInfo;
489 //===----------------------------------------------------------------------===//
490 // PMTopLevelManager implementation
492 /// Initialize top level manager. Create first pass manager.
493 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
495 MPPassManager *MPP = new MPPassManager(1);
496 MPP->setTopLevelManager(this);
498 activeStack.push(MPP);
499 } else if (t == TLM_Function) {
500 FPPassManager *FPP = new FPPassManager(1);
501 FPP->setTopLevelManager(this);
503 activeStack.push(FPP);
507 /// Set pass P as the last user of the given analysis passes.
508 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
510 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
511 E = AnalysisPasses.end(); I != E; ++I) {
518 // If AP is the last user of other passes then make P last user of
520 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
521 LUE = LastUser.end(); LUI != LUE; ++LUI) {
522 if (LUI->second == AP)
523 // DenseMap iterator is not invalidated here because
524 // this is just updating exisitng entry.
525 LastUser[LUI->first] = P;
530 /// Collect passes whose last user is P
531 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
533 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
534 InversedLastUser.find(P);
535 if (DMI == InversedLastUser.end())
538 SmallPtrSet<Pass *, 8> &LU = DMI->second;
539 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
540 E = LU.end(); I != E; ++I) {
541 LastUses.push_back(*I);
546 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
547 AnalysisUsage *AnUsage = NULL;
548 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
549 if (DMI != AnUsageMap.end())
550 AnUsage = DMI->second;
552 AnUsage = new AnalysisUsage();
553 P->getAnalysisUsage(*AnUsage);
554 AnUsageMap[P] = AnUsage;
559 /// Schedule pass P for execution. Make sure that passes required by
560 /// P are run before P is run. Update analysis info maintained by
561 /// the manager. Remove dead passes. This is a recursive function.
562 void PMTopLevelManager::schedulePass(Pass *P) {
564 // TODO : Allocate function manager for this pass, other wise required set
565 // may be inserted into previous function manager
567 // Give pass a chance to prepare the stage.
568 P->preparePassManager(activeStack);
570 // If P is an analysis pass and it is available then do not
571 // generate the analysis again. Stale analysis info should not be
572 // available at this point.
574 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
575 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
580 AnalysisUsage *AnUsage = findAnalysisUsage(P);
582 bool checkAnalysis = true;
583 while (checkAnalysis) {
584 checkAnalysis = false;
586 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
587 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
588 E = RequiredSet.end(); I != E; ++I) {
590 Pass *AnalysisPass = findAnalysisPass(*I);
592 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
593 AnalysisPass = PI->createPass();
594 if (P->getPotentialPassManagerType () ==
595 AnalysisPass->getPotentialPassManagerType())
596 // Schedule analysis pass that is managed by the same pass manager.
597 schedulePass(AnalysisPass);
598 else if (P->getPotentialPassManagerType () >
599 AnalysisPass->getPotentialPassManagerType()) {
600 // Schedule analysis pass that is managed by a new manager.
601 schedulePass(AnalysisPass);
602 // Recheck analysis passes to ensure that required analysises that
603 // are already checked are still available.
604 checkAnalysis = true;
607 // Do not schedule this analysis. Lower level analsyis
608 // passes are run on the fly.
614 // Now all required passes are available.
618 /// Find the pass that implements Analysis AID. Search immutable
619 /// passes and all pass managers. If desired pass is not found
620 /// then return NULL.
621 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
624 // Check pass managers
625 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
626 E = PassManagers.end(); P == NULL && I != E; ++I) {
627 PMDataManager *PMD = *I;
628 P = PMD->findAnalysisPass(AID, false);
631 // Check other pass managers
632 for (SmallVector<PMDataManager *, 8>::iterator
633 I = IndirectPassManagers.begin(),
634 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
635 P = (*I)->findAnalysisPass(AID, false);
637 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
638 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
639 AnalysisID PI = (*I)->getPassID();
643 // If Pass not found then check the interfaces implemented by Immutable Pass
645 const PassInfo *PassInf =
646 PassRegistry::getPassRegistry()->getPassInfo(PI);
647 const std::vector<const PassInfo*> &ImmPI =
648 PassInf->getInterfacesImplemented();
649 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
650 EE = ImmPI.end(); II != EE; ++II) {
651 if ((*II)->getTypeInfo() == AID)
660 // Print passes managed by this top level manager.
661 void PMTopLevelManager::dumpPasses() const {
663 if (PassDebugging < Structure)
666 // Print out the immutable passes
667 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
668 ImmutablePasses[i]->dumpPassStructure(0);
671 // Every class that derives from PMDataManager also derives from Pass
672 // (sometimes indirectly), but there's no inheritance relationship
673 // between PMDataManager and Pass, so we have to getAsPass to get
674 // from a PMDataManager* to a Pass*.
675 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
676 E = PassManagers.end(); I != E; ++I)
677 (*I)->getAsPass()->dumpPassStructure(1);
680 void PMTopLevelManager::dumpArguments() const {
682 if (PassDebugging < Arguments)
685 dbgs() << "Pass Arguments: ";
686 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
687 E = PassManagers.end(); I != E; ++I)
688 (*I)->dumpPassArguments();
692 void PMTopLevelManager::initializeAllAnalysisInfo() {
693 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
694 E = PassManagers.end(); I != E; ++I)
695 (*I)->initializeAnalysisInfo();
697 // Initailize other pass managers
698 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
699 E = IndirectPassManagers.end(); I != E; ++I)
700 (*I)->initializeAnalysisInfo();
702 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
703 DME = LastUser.end(); DMI != DME; ++DMI) {
704 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
705 InversedLastUser.find(DMI->second);
706 if (InvDMI != InversedLastUser.end()) {
707 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
708 L.insert(DMI->first);
710 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
711 InversedLastUser[DMI->second] = L;
717 PMTopLevelManager::~PMTopLevelManager() {
718 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
719 E = PassManagers.end(); I != E; ++I)
722 for (SmallVector<ImmutablePass *, 8>::iterator
723 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
726 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
727 DME = AnUsageMap.end(); DMI != DME; ++DMI)
731 //===----------------------------------------------------------------------===//
732 // PMDataManager implementation
734 /// Augement AvailableAnalysis by adding analysis made available by pass P.
735 void PMDataManager::recordAvailableAnalysis(Pass *P) {
736 AnalysisID PI = P->getPassID();
738 AvailableAnalysis[PI] = P;
740 assert(AvailableAnalysis.size());
742 //This pass is the current implementation of all of the interfaces it
743 //implements as well.
744 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
745 if (PInf == 0) return;
746 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
747 for (unsigned i = 0, e = II.size(); i != e; ++i)
748 AvailableAnalysis[II[i]->getTypeInfo()] = P;
751 // Return true if P preserves high level analysis used by other
752 // passes managed by this manager
753 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
754 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
755 if (AnUsage->getPreservesAll())
758 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
759 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
760 E = HigherLevelAnalysis.end(); I != E; ++I) {
762 if (P1->getAsImmutablePass() == 0 &&
763 std::find(PreservedSet.begin(), PreservedSet.end(),
772 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
773 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
774 // Don't do this unless assertions are enabled.
778 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
779 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
781 // Verify preserved analysis
782 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
783 E = PreservedSet.end(); I != E; ++I) {
785 if (Pass *AP = findAnalysisPass(AID, true)) {
786 TimeRegion PassTimer(getPassTimer(AP));
787 AP->verifyAnalysis();
792 /// Remove Analysis not preserved by Pass P
793 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
794 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
795 if (AnUsage->getPreservesAll())
798 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
799 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
800 E = AvailableAnalysis.end(); I != E; ) {
801 std::map<AnalysisID, Pass*>::iterator Info = I++;
802 if (Info->second->getAsImmutablePass() == 0 &&
803 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
804 PreservedSet.end()) {
805 // Remove this analysis
806 if (PassDebugging >= Details) {
807 Pass *S = Info->second;
808 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
809 dbgs() << S->getPassName() << "'\n";
811 AvailableAnalysis.erase(Info);
815 // Check inherited analysis also. If P is not preserving analysis
816 // provided by parent manager then remove it here.
817 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
819 if (!InheritedAnalysis[Index])
822 for (std::map<AnalysisID, Pass*>::iterator
823 I = InheritedAnalysis[Index]->begin(),
824 E = InheritedAnalysis[Index]->end(); I != E; ) {
825 std::map<AnalysisID, Pass *>::iterator Info = I++;
826 if (Info->second->getAsImmutablePass() == 0 &&
827 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
828 PreservedSet.end()) {
829 // Remove this analysis
830 if (PassDebugging >= Details) {
831 Pass *S = Info->second;
832 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
833 dbgs() << S->getPassName() << "'\n";
835 InheritedAnalysis[Index]->erase(Info);
841 /// Remove analysis passes that are not used any longer
842 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
843 enum PassDebuggingString DBG_STR) {
845 SmallVector<Pass *, 12> DeadPasses;
847 // If this is a on the fly manager then it does not have TPM.
851 TPM->collectLastUses(DeadPasses, P);
853 if (PassDebugging >= Details && !DeadPasses.empty()) {
854 dbgs() << " -*- '" << P->getPassName();
855 dbgs() << "' is the last user of following pass instances.";
856 dbgs() << " Free these instances\n";
859 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
860 E = DeadPasses.end(); I != E; ++I)
861 freePass(*I, Msg, DBG_STR);
864 void PMDataManager::freePass(Pass *P, StringRef Msg,
865 enum PassDebuggingString DBG_STR) {
866 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
869 // If the pass crashes releasing memory, remember this.
870 PassManagerPrettyStackEntry X(P);
871 TimeRegion PassTimer(getPassTimer(P));
876 AnalysisID PI = P->getPassID();
877 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
878 // Remove the pass itself (if it is not already removed).
879 AvailableAnalysis.erase(PI);
881 // Remove all interfaces this pass implements, for which it is also
882 // listed as the available implementation.
883 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
884 for (unsigned i = 0, e = II.size(); i != e; ++i) {
885 std::map<AnalysisID, Pass*>::iterator Pos =
886 AvailableAnalysis.find(II[i]->getTypeInfo());
887 if (Pos != AvailableAnalysis.end() && Pos->second == P)
888 AvailableAnalysis.erase(Pos);
893 /// Add pass P into the PassVector. Update
894 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
895 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
896 // This manager is going to manage pass P. Set up analysis resolver
898 AnalysisResolver *AR = new AnalysisResolver(*this);
901 // If a FunctionPass F is the last user of ModulePass info M
902 // then the F's manager, not F, records itself as a last user of M.
903 SmallVector<Pass *, 12> TransferLastUses;
905 if (!ProcessAnalysis) {
907 PassVector.push_back(P);
911 // At the moment, this pass is the last user of all required passes.
912 SmallVector<Pass *, 12> LastUses;
913 SmallVector<Pass *, 8> RequiredPasses;
914 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
916 unsigned PDepth = this->getDepth();
918 collectRequiredAnalysis(RequiredPasses,
919 ReqAnalysisNotAvailable, P);
920 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
921 E = RequiredPasses.end(); I != E; ++I) {
922 Pass *PRequired = *I;
925 assert(PRequired->getResolver() && "Analysis Resolver is not set");
926 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
927 RDepth = DM.getDepth();
929 if (PDepth == RDepth)
930 LastUses.push_back(PRequired);
931 else if (PDepth > RDepth) {
932 // Let the parent claim responsibility of last use
933 TransferLastUses.push_back(PRequired);
934 // Keep track of higher level analysis used by this manager.
935 HigherLevelAnalysis.push_back(PRequired);
937 llvm_unreachable("Unable to accomodate Required Pass");
940 // Set P as P's last user until someone starts using P.
941 // However, if P is a Pass Manager then it does not need
942 // to record its last user.
943 if (P->getAsPMDataManager() == 0)
944 LastUses.push_back(P);
945 TPM->setLastUser(LastUses, P);
947 if (!TransferLastUses.empty()) {
948 Pass *My_PM = getAsPass();
949 TPM->setLastUser(TransferLastUses, My_PM);
950 TransferLastUses.clear();
953 // Now, take care of required analysises that are not available.
954 for (SmallVector<AnalysisID, 8>::iterator
955 I = ReqAnalysisNotAvailable.begin(),
956 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
957 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
958 Pass *AnalysisPass = PI->createPass();
959 this->addLowerLevelRequiredPass(P, AnalysisPass);
962 // Take a note of analysis required and made available by this pass.
963 // Remove the analysis not preserved by this pass
964 removeNotPreservedAnalysis(P);
965 recordAvailableAnalysis(P);
968 PassVector.push_back(P);
972 /// Populate RP with analysis pass that are required by
973 /// pass P and are available. Populate RP_NotAvail with analysis
974 /// pass that are required by pass P but are not available.
975 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
976 SmallVector<AnalysisID, 8> &RP_NotAvail,
978 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
979 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
980 for (AnalysisUsage::VectorType::const_iterator
981 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
982 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
983 RP.push_back(AnalysisPass);
985 RP_NotAvail.push_back(*I);
988 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
989 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
990 E = IDs.end(); I != E; ++I) {
991 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
992 RP.push_back(AnalysisPass);
994 RP_NotAvail.push_back(*I);
998 // All Required analyses should be available to the pass as it runs! Here
999 // we fill in the AnalysisImpls member of the pass so that it can
1000 // successfully use the getAnalysis() method to retrieve the
1001 // implementations it needs.
1003 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1004 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1006 for (AnalysisUsage::VectorType::const_iterator
1007 I = AnUsage->getRequiredSet().begin(),
1008 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1009 Pass *Impl = findAnalysisPass(*I, true);
1011 // This may be analysis pass that is initialized on the fly.
1012 // If that is not the case then it will raise an assert when it is used.
1014 AnalysisResolver *AR = P->getResolver();
1015 assert(AR && "Analysis Resolver is not set");
1016 AR->addAnalysisImplsPair(*I, Impl);
1020 /// Find the pass that implements Analysis AID. If desired pass is not found
1021 /// then return NULL.
1022 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1024 // Check if AvailableAnalysis map has one entry.
1025 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1027 if (I != AvailableAnalysis.end())
1030 // Search Parents through TopLevelManager
1032 return TPM->findAnalysisPass(AID);
1037 // Print list of passes that are last used by P.
1038 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1040 SmallVector<Pass *, 12> LUses;
1042 // If this is a on the fly manager then it does not have TPM.
1046 TPM->collectLastUses(LUses, P);
1048 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1049 E = LUses.end(); I != E; ++I) {
1050 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1051 (*I)->dumpPassStructure(0);
1055 void PMDataManager::dumpPassArguments() const {
1056 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1057 E = PassVector.end(); I != E; ++I) {
1058 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1059 PMD->dumpPassArguments();
1061 if (const PassInfo *PI =
1062 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1063 if (!PI->isAnalysisGroup())
1064 dbgs() << " -" << PI->getPassArgument();
1068 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1069 enum PassDebuggingString S2,
1071 if (PassDebugging < Executions)
1073 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1076 dbgs() << "Executing Pass '" << P->getPassName();
1078 case MODIFICATION_MSG:
1079 dbgs() << "Made Modification '" << P->getPassName();
1082 dbgs() << " Freeing Pass '" << P->getPassName();
1088 case ON_BASICBLOCK_MSG:
1089 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1091 case ON_FUNCTION_MSG:
1092 dbgs() << "' on Function '" << Msg << "'...\n";
1095 dbgs() << "' on Module '" << Msg << "'...\n";
1098 dbgs() << "' on Loop '" << Msg << "'...\n";
1101 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1108 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1109 if (PassDebugging < Details)
1112 AnalysisUsage analysisUsage;
1113 P->getAnalysisUsage(analysisUsage);
1114 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1117 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1118 if (PassDebugging < Details)
1121 AnalysisUsage analysisUsage;
1122 P->getAnalysisUsage(analysisUsage);
1123 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1126 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1127 const AnalysisUsage::VectorType &Set) const {
1128 assert(PassDebugging >= Details);
1131 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1132 for (unsigned i = 0; i != Set.size(); ++i) {
1133 if (i) dbgs() << ',';
1134 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1135 dbgs() << ' ' << PInf->getPassName();
1140 /// Add RequiredPass into list of lower level passes required by pass P.
1141 /// RequiredPass is run on the fly by Pass Manager when P requests it
1142 /// through getAnalysis interface.
1143 /// This should be handled by specific pass manager.
1144 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1146 TPM->dumpArguments();
1150 // Module Level pass may required Function Level analysis info
1151 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1152 // to provide this on demand. In that case, in Pass manager terminology,
1153 // module level pass is requiring lower level analysis info managed by
1154 // lower level pass manager.
1156 // When Pass manager is not able to order required analysis info, Pass manager
1157 // checks whether any lower level manager will be able to provide this
1158 // analysis info on demand or not.
1160 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1161 dbgs() << "' required by '" << P->getPassName() << "'\n";
1163 llvm_unreachable("Unable to schedule pass");
1166 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1167 assert(0 && "Unable to find on the fly pass");
1172 PMDataManager::~PMDataManager() {
1173 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1174 E = PassVector.end(); I != E; ++I)
1178 //===----------------------------------------------------------------------===//
1179 // NOTE: Is this the right place to define this method ?
1180 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1181 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1182 return PM.findAnalysisPass(ID, dir);
1185 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1187 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1190 //===----------------------------------------------------------------------===//
1191 // BBPassManager implementation
1193 /// Execute all of the passes scheduled for execution by invoking
1194 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1195 /// the function, and if so, return true.
1196 bool BBPassManager::runOnFunction(Function &F) {
1197 if (F.isDeclaration())
1200 bool Changed = doInitialization(F);
1202 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1203 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1204 BasicBlockPass *BP = getContainedPass(Index);
1205 bool LocalChanged = false;
1207 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1208 dumpRequiredSet(BP);
1210 initializeAnalysisImpl(BP);
1213 // If the pass crashes, remember this.
1214 PassManagerPrettyStackEntry X(BP, *I);
1215 TimeRegion PassTimer(getPassTimer(BP));
1217 LocalChanged |= BP->runOnBasicBlock(*I);
1220 Changed |= LocalChanged;
1222 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1224 dumpPreservedSet(BP);
1226 verifyPreservedAnalysis(BP);
1227 removeNotPreservedAnalysis(BP);
1228 recordAvailableAnalysis(BP);
1229 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1232 return doFinalization(F) || Changed;
1235 // Implement doInitialization and doFinalization
1236 bool BBPassManager::doInitialization(Module &M) {
1237 bool Changed = false;
1239 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1240 Changed |= getContainedPass(Index)->doInitialization(M);
1245 bool BBPassManager::doFinalization(Module &M) {
1246 bool Changed = false;
1248 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1249 Changed |= getContainedPass(Index)->doFinalization(M);
1254 bool BBPassManager::doInitialization(Function &F) {
1255 bool Changed = false;
1257 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1258 BasicBlockPass *BP = getContainedPass(Index);
1259 Changed |= BP->doInitialization(F);
1265 bool BBPassManager::doFinalization(Function &F) {
1266 bool Changed = false;
1268 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1269 BasicBlockPass *BP = getContainedPass(Index);
1270 Changed |= BP->doFinalization(F);
1277 //===----------------------------------------------------------------------===//
1278 // FunctionPassManager implementation
1280 /// Create new Function pass manager
1281 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1282 FPM = new FunctionPassManagerImpl(0);
1283 // FPM is the top level manager.
1284 FPM->setTopLevelManager(FPM);
1286 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1287 FPM->setResolver(AR);
1290 FunctionPassManager::~FunctionPassManager() {
1294 /// addImpl - Add a pass to the queue of passes to run, without
1295 /// checking whether to add a printer pass.
1296 void FunctionPassManager::addImpl(Pass *P) {
1300 /// add - Add a pass to the queue of passes to run. This passes
1301 /// ownership of the Pass to the PassManager. When the
1302 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1303 /// there is no need to delete the pass. (TODO delete passes.)
1304 /// This implies that all passes MUST be allocated with 'new'.
1305 void FunctionPassManager::add(Pass *P) {
1306 // If this is a not a function pass, don't add a printer for it.
1307 const void *PassID = P->getPassID();
1308 if (P->getPassKind() == PT_Function)
1309 if (ShouldPrintBeforePass(PassID))
1310 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1311 + P->getPassName() + " ***"));
1315 if (P->getPassKind() == PT_Function)
1316 if (ShouldPrintAfterPass(PassID))
1317 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1318 + P->getPassName() + " ***"));
1321 /// run - Execute all of the passes scheduled for execution. Keep
1322 /// track of whether any of the passes modifies the function, and if
1323 /// so, return true.
1325 bool FunctionPassManager::run(Function &F) {
1326 if (F.isMaterializable()) {
1328 if (F.Materialize(&errstr))
1329 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1335 /// doInitialization - Run all of the initializers for the function passes.
1337 bool FunctionPassManager::doInitialization() {
1338 return FPM->doInitialization(*M);
1341 /// doFinalization - Run all of the finalizers for the function passes.
1343 bool FunctionPassManager::doFinalization() {
1344 return FPM->doFinalization(*M);
1347 //===----------------------------------------------------------------------===//
1348 // FunctionPassManagerImpl implementation
1350 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1351 bool Changed = false;
1356 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1357 Changed |= getContainedManager(Index)->doInitialization(M);
1362 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1363 bool Changed = false;
1365 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1366 Changed |= getContainedManager(Index)->doFinalization(M);
1371 /// cleanup - After running all passes, clean up pass manager cache.
1372 void FPPassManager::cleanup() {
1373 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1374 FunctionPass *FP = getContainedPass(Index);
1375 AnalysisResolver *AR = FP->getResolver();
1376 assert(AR && "Analysis Resolver is not set");
1377 AR->clearAnalysisImpls();
1381 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1384 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1385 FPPassManager *FPPM = getContainedManager(Index);
1386 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1387 FPPM->getContainedPass(Index)->releaseMemory();
1393 // Execute all the passes managed by this top level manager.
1394 // Return true if any function is modified by a pass.
1395 bool FunctionPassManagerImpl::run(Function &F) {
1396 bool Changed = false;
1397 TimingInfo::createTheTimeInfo();
1399 initializeAllAnalysisInfo();
1400 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1401 Changed |= getContainedManager(Index)->runOnFunction(F);
1403 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1404 getContainedManager(Index)->cleanup();
1410 //===----------------------------------------------------------------------===//
1411 // FPPassManager implementation
1413 char FPPassManager::ID = 0;
1414 /// Print passes managed by this manager
1415 void FPPassManager::dumpPassStructure(unsigned Offset) {
1416 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1417 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1418 FunctionPass *FP = getContainedPass(Index);
1419 FP->dumpPassStructure(Offset + 1);
1420 dumpLastUses(FP, Offset+1);
1425 /// Execute all of the passes scheduled for execution by invoking
1426 /// runOnFunction method. Keep track of whether any of the passes modifies
1427 /// the function, and if so, return true.
1428 bool FPPassManager::runOnFunction(Function &F) {
1429 if (F.isDeclaration())
1432 bool Changed = false;
1434 // Collect inherited analysis from Module level pass manager.
1435 populateInheritedAnalysis(TPM->activeStack);
1437 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1438 FunctionPass *FP = getContainedPass(Index);
1439 bool LocalChanged = false;
1441 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1442 dumpRequiredSet(FP);
1444 initializeAnalysisImpl(FP);
1447 PassManagerPrettyStackEntry X(FP, F);
1448 TimeRegion PassTimer(getPassTimer(FP));
1450 LocalChanged |= FP->runOnFunction(F);
1453 Changed |= LocalChanged;
1455 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1456 dumpPreservedSet(FP);
1458 verifyPreservedAnalysis(FP);
1459 removeNotPreservedAnalysis(FP);
1460 recordAvailableAnalysis(FP);
1461 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1466 bool FPPassManager::runOnModule(Module &M) {
1467 bool Changed = doInitialization(M);
1469 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1472 return doFinalization(M) || Changed;
1475 bool FPPassManager::doInitialization(Module &M) {
1476 bool Changed = false;
1478 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1479 Changed |= getContainedPass(Index)->doInitialization(M);
1484 bool FPPassManager::doFinalization(Module &M) {
1485 bool Changed = false;
1487 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1488 Changed |= getContainedPass(Index)->doFinalization(M);
1493 //===----------------------------------------------------------------------===//
1494 // MPPassManager implementation
1496 /// Execute all of the passes scheduled for execution by invoking
1497 /// runOnModule method. Keep track of whether any of the passes modifies
1498 /// the module, and if so, return true.
1500 MPPassManager::runOnModule(Module &M) {
1501 bool Changed = false;
1503 // Initialize on-the-fly passes
1504 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1505 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1507 FunctionPassManagerImpl *FPP = I->second;
1508 Changed |= FPP->doInitialization(M);
1511 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1512 ModulePass *MP = getContainedPass(Index);
1513 bool LocalChanged = false;
1515 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1516 dumpRequiredSet(MP);
1518 initializeAnalysisImpl(MP);
1521 PassManagerPrettyStackEntry X(MP, M);
1522 TimeRegion PassTimer(getPassTimer(MP));
1524 LocalChanged |= MP->runOnModule(M);
1527 Changed |= LocalChanged;
1529 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1530 M.getModuleIdentifier());
1531 dumpPreservedSet(MP);
1533 verifyPreservedAnalysis(MP);
1534 removeNotPreservedAnalysis(MP);
1535 recordAvailableAnalysis(MP);
1536 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1539 // Finalize on-the-fly passes
1540 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1541 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1543 FunctionPassManagerImpl *FPP = I->second;
1544 // We don't know when is the last time an on-the-fly pass is run,
1545 // so we need to releaseMemory / finalize here
1546 FPP->releaseMemoryOnTheFly();
1547 Changed |= FPP->doFinalization(M);
1552 /// Add RequiredPass into list of lower level passes required by pass P.
1553 /// RequiredPass is run on the fly by Pass Manager when P requests it
1554 /// through getAnalysis interface.
1555 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1556 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1557 "Unable to handle Pass that requires lower level Analysis pass");
1558 assert((P->getPotentialPassManagerType() <
1559 RequiredPass->getPotentialPassManagerType()) &&
1560 "Unable to handle Pass that requires lower level Analysis pass");
1562 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1564 FPP = new FunctionPassManagerImpl(0);
1565 // FPP is the top level manager.
1566 FPP->setTopLevelManager(FPP);
1568 OnTheFlyManagers[P] = FPP;
1570 FPP->add(RequiredPass);
1572 // Register P as the last user of RequiredPass.
1573 SmallVector<Pass *, 12> LU;
1574 LU.push_back(RequiredPass);
1575 FPP->setLastUser(LU, P);
1578 /// Return function pass corresponding to PassInfo PI, that is
1579 /// required by module pass MP. Instantiate analysis pass, by using
1580 /// its runOnFunction() for function F.
1581 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1582 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1583 assert(FPP && "Unable to find on the fly pass");
1585 FPP->releaseMemoryOnTheFly();
1587 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1591 //===----------------------------------------------------------------------===//
1592 // PassManagerImpl implementation
1594 /// run - Execute all of the passes scheduled for execution. Keep track of
1595 /// whether any of the passes modifies the module, and if so, return true.
1596 bool PassManagerImpl::run(Module &M) {
1597 bool Changed = false;
1598 TimingInfo::createTheTimeInfo();
1603 initializeAllAnalysisInfo();
1604 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1605 Changed |= getContainedManager(Index)->runOnModule(M);
1609 //===----------------------------------------------------------------------===//
1610 // PassManager implementation
1612 /// Create new pass manager
1613 PassManager::PassManager() {
1614 PM = new PassManagerImpl(0);
1615 // PM is the top level manager
1616 PM->setTopLevelManager(PM);
1619 PassManager::~PassManager() {
1623 /// addImpl - Add a pass to the queue of passes to run, without
1624 /// checking whether to add a printer pass.
1625 void PassManager::addImpl(Pass *P) {
1629 /// add - Add a pass to the queue of passes to run. This passes ownership of
1630 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1631 /// will be destroyed as well, so there is no need to delete the pass. This
1632 /// implies that all passes MUST be allocated with 'new'.
1633 void PassManager::add(Pass *P) {
1634 const void* PassID = P->getPassID();
1635 if (ShouldPrintBeforePass(PassID))
1636 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1637 + P->getPassName() + " ***"));
1641 if (ShouldPrintAfterPass(PassID))
1642 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1643 + P->getPassName() + " ***"));
1646 /// run - Execute all of the passes scheduled for execution. Keep track of
1647 /// whether any of the passes modifies the module, and if so, return true.
1648 bool PassManager::run(Module &M) {
1652 //===----------------------------------------------------------------------===//
1653 // TimingInfo Class - This class is used to calculate information about the
1654 // amount of time each pass takes to execute. This only happens with
1655 // -time-passes is enabled on the command line.
1657 bool llvm::TimePassesIsEnabled = false;
1658 static cl::opt<bool,true>
1659 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1660 cl::desc("Time each pass, printing elapsed time for each on exit"));
1662 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1663 // a non null value (if the -time-passes option is enabled) or it leaves it
1664 // null. It may be called multiple times.
1665 void TimingInfo::createTheTimeInfo() {
1666 if (!TimePassesIsEnabled || TheTimeInfo) return;
1668 // Constructed the first time this is called, iff -time-passes is enabled.
1669 // This guarantees that the object will be constructed before static globals,
1670 // thus it will be destroyed before them.
1671 static ManagedStatic<TimingInfo> TTI;
1672 TheTimeInfo = &*TTI;
1675 /// If TimingInfo is enabled then start pass timer.
1676 Timer *llvm::getPassTimer(Pass *P) {
1678 return TheTimeInfo->getPassTimer(P);
1682 //===----------------------------------------------------------------------===//
1683 // PMStack implementation
1686 // Pop Pass Manager from the stack and clear its analysis info.
1687 void PMStack::pop() {
1689 PMDataManager *Top = this->top();
1690 Top->initializeAnalysisInfo();
1695 // Push PM on the stack and set its top level manager.
1696 void PMStack::push(PMDataManager *PM) {
1697 assert(PM && "Unable to push. Pass Manager expected");
1699 if (!this->empty()) {
1700 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1702 assert(TPM && "Unable to find top level manager");
1703 TPM->addIndirectPassManager(PM);
1704 PM->setTopLevelManager(TPM);
1710 // Dump content of the pass manager stack.
1711 void PMStack::dump() const {
1712 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1713 E = S.end(); I != E; ++I)
1714 printf("%s ", (*I)->getAsPass()->getPassName());
1720 /// Find appropriate Module Pass Manager in the PM Stack and
1721 /// add self into that manager.
1722 void ModulePass::assignPassManager(PMStack &PMS,
1723 PassManagerType PreferredType) {
1724 // Find Module Pass Manager
1725 while(!PMS.empty()) {
1726 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1727 if (TopPMType == PreferredType)
1728 break; // We found desired pass manager
1729 else if (TopPMType > PMT_ModulePassManager)
1730 PMS.pop(); // Pop children pass managers
1734 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1735 PMS.top()->add(this);
1738 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1739 /// in the PM Stack and add self into that manager.
1740 void FunctionPass::assignPassManager(PMStack &PMS,
1741 PassManagerType PreferredType) {
1743 // Find Module Pass Manager
1744 while (!PMS.empty()) {
1745 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1751 // Create new Function Pass Manager if needed.
1753 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1754 FPP = (FPPassManager *)PMS.top();
1756 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1757 PMDataManager *PMD = PMS.top();
1759 // [1] Create new Function Pass Manager
1760 FPP = new FPPassManager(PMD->getDepth() + 1);
1761 FPP->populateInheritedAnalysis(PMS);
1763 // [2] Set up new manager's top level manager
1764 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1765 TPM->addIndirectPassManager(FPP);
1767 // [3] Assign manager to manage this new manager. This may create
1768 // and push new managers into PMS
1769 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1771 // [4] Push new manager into PMS
1775 // Assign FPP as the manager of this pass.
1779 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1780 /// in the PM Stack and add self into that manager.
1781 void BasicBlockPass::assignPassManager(PMStack &PMS,
1782 PassManagerType PreferredType) {
1785 // Basic Pass Manager is a leaf pass manager. It does not handle
1786 // any other pass manager.
1788 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1789 BBP = (BBPassManager *)PMS.top();
1791 // If leaf manager is not Basic Block Pass manager then create new
1792 // basic Block Pass manager.
1793 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1794 PMDataManager *PMD = PMS.top();
1796 // [1] Create new Basic Block Manager
1797 BBP = new BBPassManager(PMD->getDepth() + 1);
1799 // [2] Set up new manager's top level manager
1800 // Basic Block Pass Manager does not live by itself
1801 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1802 TPM->addIndirectPassManager(BBP);
1804 // [3] Assign manager to manage this new manager. This may create
1805 // and push new managers into PMS
1806 BBP->assignPassManager(PMS, PreferredType);
1808 // [4] Push new manager into PMS
1812 // Assign BBP as the manager of this pass.
1816 PassManagerBase::~PassManagerBase() {}