1 //===- LegacyPassManager.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 legacy LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/IRPrintingPasses.h"
16 #include "llvm/IR/LegacyPassManager.h"
17 #include "llvm/IR/LegacyPassManagers.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Mutex.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm::legacy;
32 // See PassManagers.h for Pass Manager infrastructure overview.
34 //===----------------------------------------------------------------------===//
35 // Pass debugging information. Often it is useful to find out what pass is
36 // running when a crash occurs in a utility. When this library is compiled with
37 // debugging on, a command line option (--debug-pass) is enabled that causes the
38 // pass name to be printed before it executes.
42 // Different debug levels that can be enabled...
44 Disabled, 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(Disabled , "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"),
60 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"),
71 PrintAfter("print-after",
72 llvm::cl::desc("Print IR after specified passes"),
76 PrintBeforeAll("print-before-all",
77 llvm::cl::desc("Print IR before each pass"),
80 PrintAfterAll("print-after-all",
81 llvm::cl::desc("Print IR after each pass"),
84 /// This is a helper to determine whether to print IR before or
87 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
88 PassOptionList &PassesToPrint) {
89 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
90 const llvm::PassInfo *PassInf = PassesToPrint[i];
92 if (PassInf->getPassArgument() == PI->getPassArgument()) {
99 /// This is a utility to check whether a pass should have IR dumped
101 static bool ShouldPrintBeforePass(const PassInfo *PI) {
102 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
105 /// This is a utility to check whether a pass should have IR dumped
107 static bool ShouldPrintAfterPass(const PassInfo *PI) {
108 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
111 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
112 /// or higher is specified.
113 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
114 return PassDebugging >= Executions;
120 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
121 if (V == 0 && M == 0)
122 OS << "Releasing pass '";
124 OS << "Running pass '";
126 OS << P->getPassName() << "'";
129 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
138 if (isa<Function>(V))
140 else if (isa<BasicBlock>(V))
146 V->printAsOperand(OS, /*PrintTy=*/false, M);
152 //===----------------------------------------------------------------------===//
155 /// BBPassManager manages BasicBlockPass. It batches all the
156 /// pass together and sequence them to process one basic block before
157 /// processing next basic block.
158 class BBPassManager : public PMDataManager, public FunctionPass {
162 explicit BBPassManager()
163 : PMDataManager(), FunctionPass(ID) {}
165 /// Execute all of the passes scheduled for execution. Keep track of
166 /// whether any of the passes modifies the function, and if so, return true.
167 bool runOnFunction(Function &F);
169 /// Pass Manager itself does not invalidate any analysis info.
170 void getAnalysisUsage(AnalysisUsage &Info) const {
171 Info.setPreservesAll();
174 bool doInitialization(Module &M);
175 bool doInitialization(Function &F);
176 bool doFinalization(Module &M);
177 bool doFinalization(Function &F);
179 virtual PMDataManager *getAsPMDataManager() { return this; }
180 virtual Pass *getAsPass() { return this; }
182 virtual const char *getPassName() const {
183 return "BasicBlock Pass Manager";
186 // Print passes managed by this manager
187 void dumpPassStructure(unsigned Offset) {
188 llvm::dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
189 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
190 BasicBlockPass *BP = getContainedPass(Index);
191 BP->dumpPassStructure(Offset + 1);
192 dumpLastUses(BP, Offset+1);
196 BasicBlockPass *getContainedPass(unsigned N) {
197 assert(N < PassVector.size() && "Pass number out of range!");
198 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
202 virtual PassManagerType getPassManagerType() const {
203 return PMT_BasicBlockPassManager;
207 char BBPassManager::ID = 0;
208 } // End anonymous namespace
212 //===----------------------------------------------------------------------===//
213 // FunctionPassManagerImpl
215 /// FunctionPassManagerImpl manages FPPassManagers
216 class FunctionPassManagerImpl : public Pass,
217 public PMDataManager,
218 public PMTopLevelManager {
219 virtual void anchor();
224 explicit FunctionPassManagerImpl() :
225 Pass(PT_PassManager, ID), PMDataManager(),
226 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
228 /// add - Add a pass to the queue of passes to run. This passes ownership of
229 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
230 /// will be destroyed as well, so there is no need to delete the pass. This
231 /// implies that all passes MUST be allocated with 'new'.
236 /// createPrinterPass - Get a function printer pass.
237 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
238 return createPrintFunctionPass(Banner, &O);
241 // Prepare for running an on the fly pass, freeing memory if needed
242 // from a previous run.
243 void releaseMemoryOnTheFly();
245 /// run - Execute all of the passes scheduled for execution. Keep track of
246 /// whether any of the passes modifies the module, and if so, return true.
247 bool run(Function &F);
249 /// doInitialization - Run all of the initializers for the function passes.
251 bool doInitialization(Module &M);
253 /// doFinalization - Run all of the finalizers for the function passes.
255 bool doFinalization(Module &M);
258 virtual PMDataManager *getAsPMDataManager() { return this; }
259 virtual Pass *getAsPass() { return this; }
260 virtual PassManagerType getTopLevelPassManagerType() {
261 return PMT_FunctionPassManager;
264 /// Pass Manager itself does not invalidate any analysis info.
265 void getAnalysisUsage(AnalysisUsage &Info) const {
266 Info.setPreservesAll();
269 FPPassManager *getContainedManager(unsigned N) {
270 assert(N < PassManagers.size() && "Pass number out of range!");
271 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
276 void FunctionPassManagerImpl::anchor() {}
278 char FunctionPassManagerImpl::ID = 0;
279 } // End of legacy namespace
280 } // End of llvm namespace
283 //===----------------------------------------------------------------------===//
286 /// MPPassManager manages ModulePasses and function pass managers.
287 /// It batches all Module passes and function pass managers together and
288 /// sequences them to process one module.
289 class MPPassManager : public Pass, public PMDataManager {
292 explicit MPPassManager() :
293 Pass(PT_PassManager, ID), PMDataManager() { }
295 // Delete on the fly managers.
296 virtual ~MPPassManager() {
297 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
298 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
300 FunctionPassManagerImpl *FPP = I->second;
305 /// createPrinterPass - Get a module printer pass.
306 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
307 return createPrintModulePass(&O, false, Banner);
310 /// run - Execute all of the passes scheduled for execution. Keep track of
311 /// whether any of the passes modifies the module, and if so, return true.
312 bool runOnModule(Module &M);
314 using llvm::Pass::doInitialization;
315 using llvm::Pass::doFinalization;
317 /// doInitialization - Run all of the initializers for the module passes.
319 bool doInitialization();
321 /// doFinalization - Run all of the finalizers for the module passes.
323 bool doFinalization();
325 /// Pass Manager itself does not invalidate any analysis info.
326 void getAnalysisUsage(AnalysisUsage &Info) const {
327 Info.setPreservesAll();
330 /// Add RequiredPass into list of lower level passes required by pass P.
331 /// RequiredPass is run on the fly by Pass Manager when P requests it
332 /// through getAnalysis interface.
333 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
335 /// Return function pass corresponding to PassInfo PI, that is
336 /// required by module pass MP. Instantiate analysis pass, by using
337 /// its runOnFunction() for function F.
338 virtual Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F);
340 virtual const char *getPassName() const {
341 return "Module Pass Manager";
344 virtual PMDataManager *getAsPMDataManager() { return this; }
345 virtual Pass *getAsPass() { return this; }
347 // Print passes managed by this manager
348 void dumpPassStructure(unsigned Offset) {
349 llvm::dbgs().indent(Offset*2) << "ModulePass Manager\n";
350 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
351 ModulePass *MP = getContainedPass(Index);
352 MP->dumpPassStructure(Offset + 1);
353 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
354 OnTheFlyManagers.find(MP);
355 if (I != OnTheFlyManagers.end())
356 I->second->dumpPassStructure(Offset + 2);
357 dumpLastUses(MP, Offset+1);
361 ModulePass *getContainedPass(unsigned N) {
362 assert(N < PassVector.size() && "Pass number out of range!");
363 return static_cast<ModulePass *>(PassVector[N]);
366 virtual PassManagerType getPassManagerType() const {
367 return PMT_ModulePassManager;
371 /// Collection of on the fly FPPassManagers. These managers manage
372 /// function passes that are required by module passes.
373 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
376 char MPPassManager::ID = 0;
377 } // End anonymous namespace
381 //===----------------------------------------------------------------------===//
385 /// PassManagerImpl manages MPPassManagers
386 class PassManagerImpl : public Pass,
387 public PMDataManager,
388 public PMTopLevelManager {
389 virtual void anchor();
393 explicit PassManagerImpl() :
394 Pass(PT_PassManager, ID), PMDataManager(),
395 PMTopLevelManager(new MPPassManager()) {}
397 /// add - Add a pass to the queue of passes to run. This passes ownership of
398 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
399 /// will be destroyed as well, so there is no need to delete the pass. This
400 /// implies that all passes MUST be allocated with 'new'.
405 /// createPrinterPass - Get a module printer pass.
406 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
407 return createPrintModulePass(&O, false, Banner);
410 /// run - Execute all of the passes scheduled for execution. Keep track of
411 /// whether any of the passes modifies the module, and if so, return true.
414 using llvm::Pass::doInitialization;
415 using llvm::Pass::doFinalization;
417 /// doInitialization - Run all of the initializers for the module passes.
419 bool doInitialization();
421 /// doFinalization - Run all of the finalizers for the module passes.
423 bool doFinalization();
425 /// Pass Manager itself does not invalidate any analysis info.
426 void getAnalysisUsage(AnalysisUsage &Info) const {
427 Info.setPreservesAll();
430 virtual PMDataManager *getAsPMDataManager() { return this; }
431 virtual Pass *getAsPass() { return this; }
432 virtual PassManagerType getTopLevelPassManagerType() {
433 return PMT_ModulePassManager;
436 MPPassManager *getContainedManager(unsigned N) {
437 assert(N < PassManagers.size() && "Pass number out of range!");
438 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
443 void PassManagerImpl::anchor() {}
445 char PassManagerImpl::ID = 0;
446 } // End of legacy namespace
447 } // End of llvm namespace
451 //===----------------------------------------------------------------------===//
452 /// TimingInfo Class - This class is used to calculate information about the
453 /// amount of time each pass takes to execute. This only happens when
454 /// -time-passes is enabled on the command line.
457 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
460 DenseMap<Pass*, Timer*> TimingData;
463 // Use 'create' member to get this.
464 TimingInfo() : TG("... Pass execution timing report ...") {}
466 // TimingDtor - Print out information about timing information
468 // Delete all of the timers, which accumulate their info into the
470 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
471 E = TimingData.end(); I != E; ++I)
473 // TimerGroup is deleted next, printing the report.
476 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
477 // to a non-null value (if the -time-passes option is enabled) or it leaves it
478 // null. It may be called multiple times.
479 static void createTheTimeInfo();
481 /// getPassTimer - Return the timer for the specified pass if it exists.
482 Timer *getPassTimer(Pass *P) {
483 if (P->getAsPMDataManager())
486 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
487 Timer *&T = TimingData[P];
489 T = new Timer(P->getPassName(), TG);
494 } // End of anon namespace
496 static TimingInfo *TheTimeInfo;
498 //===----------------------------------------------------------------------===//
499 // PMTopLevelManager implementation
501 /// Initialize top level manager. Create first pass manager.
502 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
503 PMDM->setTopLevelManager(this);
504 addPassManager(PMDM);
505 activeStack.push(PMDM);
508 /// Set pass P as the last user of the given analysis passes.
510 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
512 if (P->getResolver())
513 PDepth = P->getResolver()->getPMDataManager().getDepth();
515 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
516 E = AnalysisPasses.end(); I != E; ++I) {
523 // Update the last users of passes that are required transitive by AP.
524 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
525 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
526 SmallVector<Pass *, 12> LastUses;
527 SmallVector<Pass *, 12> LastPMUses;
528 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
529 E = IDs.end(); I != E; ++I) {
530 Pass *AnalysisPass = findAnalysisPass(*I);
531 assert(AnalysisPass && "Expected analysis pass to exist.");
532 AnalysisResolver *AR = AnalysisPass->getResolver();
533 assert(AR && "Expected analysis resolver to exist.");
534 unsigned APDepth = AR->getPMDataManager().getDepth();
536 if (PDepth == APDepth)
537 LastUses.push_back(AnalysisPass);
538 else if (PDepth > APDepth)
539 LastPMUses.push_back(AnalysisPass);
542 setLastUser(LastUses, P);
544 // If this pass has a corresponding pass manager, push higher level
545 // analysis to this pass manager.
546 if (P->getResolver())
547 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
550 // If AP is the last user of other passes then make P last user of
552 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
553 LUE = LastUser.end(); LUI != LUE; ++LUI) {
554 if (LUI->second == AP)
555 // DenseMap iterator is not invalidated here because
556 // this is just updating existing entries.
557 LastUser[LUI->first] = P;
562 /// Collect passes whose last user is P
563 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
565 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
566 InversedLastUser.find(P);
567 if (DMI == InversedLastUser.end())
570 SmallPtrSet<Pass *, 8> &LU = DMI->second;
571 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
572 E = LU.end(); I != E; ++I) {
573 LastUses.push_back(*I);
578 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
579 AnalysisUsage *AnUsage = NULL;
580 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
581 if (DMI != AnUsageMap.end())
582 AnUsage = DMI->second;
584 AnUsage = new AnalysisUsage();
585 P->getAnalysisUsage(*AnUsage);
586 AnUsageMap[P] = AnUsage;
591 /// Schedule pass P for execution. Make sure that passes required by
592 /// P are run before P is run. Update analysis info maintained by
593 /// the manager. Remove dead passes. This is a recursive function.
594 void PMTopLevelManager::schedulePass(Pass *P) {
596 // TODO : Allocate function manager for this pass, other wise required set
597 // may be inserted into previous function manager
599 // Give pass a chance to prepare the stage.
600 P->preparePassManager(activeStack);
602 // If P is an analysis pass and it is available then do not
603 // generate the analysis again. Stale analysis info should not be
604 // available at this point.
606 PassRegistry::getPassRegistry()->getPassInfo(P->getPassID());
607 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
612 AnalysisUsage *AnUsage = findAnalysisUsage(P);
614 bool checkAnalysis = true;
615 while (checkAnalysis) {
616 checkAnalysis = false;
618 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
619 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
620 E = RequiredSet.end(); I != E; ++I) {
622 Pass *AnalysisPass = findAnalysisPass(*I);
624 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
627 // Pass P is not in the global PassRegistry
628 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
629 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
630 dbgs() << "Required Passes:" << "\n";
631 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
632 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
633 Pass *AnalysisPass2 = findAnalysisPass(*I2);
635 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
637 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
638 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
639 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
644 assert(PI && "Expected required passes to be initialized");
645 AnalysisPass = PI->createPass();
646 if (P->getPotentialPassManagerType () ==
647 AnalysisPass->getPotentialPassManagerType())
648 // Schedule analysis pass that is managed by the same pass manager.
649 schedulePass(AnalysisPass);
650 else if (P->getPotentialPassManagerType () >
651 AnalysisPass->getPotentialPassManagerType()) {
652 // Schedule analysis pass that is managed by a new manager.
653 schedulePass(AnalysisPass);
654 // Recheck analysis passes to ensure that required analyses that
655 // are already checked are still available.
656 checkAnalysis = true;
658 // Do not schedule this analysis. Lower level analsyis
659 // passes are run on the fly.
665 // Now all required passes are available.
666 if (ImmutablePass *IP = P->getAsImmutablePass()) {
667 // P is a immutable pass and it will be managed by this
668 // top level manager. Set up analysis resolver to connect them.
669 PMDataManager *DM = getAsPMDataManager();
670 AnalysisResolver *AR = new AnalysisResolver(*DM);
672 DM->initializeAnalysisImpl(P);
673 addImmutablePass(IP);
674 DM->recordAvailableAnalysis(IP);
678 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
679 Pass *PP = P->createPrinterPass(
680 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
681 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
684 // Add the requested pass to the best available pass manager.
685 P->assignPassManager(activeStack, getTopLevelPassManagerType());
687 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
688 Pass *PP = P->createPrinterPass(
689 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
690 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
694 /// Find the pass that implements Analysis AID. Search immutable
695 /// passes and all pass managers. If desired pass is not found
696 /// then return NULL.
697 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
699 // Check pass managers
700 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
701 E = PassManagers.end(); I != E; ++I)
702 if (Pass *P = (*I)->findAnalysisPass(AID, false))
705 // Check other pass managers
706 for (SmallVectorImpl<PMDataManager *>::iterator
707 I = IndirectPassManagers.begin(),
708 E = IndirectPassManagers.end(); I != E; ++I)
709 if (Pass *P = (*I)->findAnalysisPass(AID, false))
712 // Check the immutable passes. Iterate in reverse order so that we find
713 // the most recently registered passes first.
714 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
715 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
716 AnalysisID PI = (*I)->getPassID();
720 // If Pass not found then check the interfaces implemented by Immutable Pass
721 const PassInfo *PassInf =
722 PassRegistry::getPassRegistry()->getPassInfo(PI);
723 assert(PassInf && "Expected all immutable passes to be initialized");
724 const std::vector<const PassInfo*> &ImmPI =
725 PassInf->getInterfacesImplemented();
726 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
727 EE = ImmPI.end(); II != EE; ++II) {
728 if ((*II)->getTypeInfo() == AID)
736 // Print passes managed by this top level manager.
737 void PMTopLevelManager::dumpPasses() const {
739 if (PassDebugging < Structure)
742 // Print out the immutable passes
743 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
744 ImmutablePasses[i]->dumpPassStructure(0);
747 // Every class that derives from PMDataManager also derives from Pass
748 // (sometimes indirectly), but there's no inheritance relationship
749 // between PMDataManager and Pass, so we have to getAsPass to get
750 // from a PMDataManager* to a Pass*.
751 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
752 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
753 (*I)->getAsPass()->dumpPassStructure(1);
756 void PMTopLevelManager::dumpArguments() const {
758 if (PassDebugging < Arguments)
761 dbgs() << "Pass Arguments: ";
762 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
763 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
764 if (const PassInfo *PI =
765 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID())) {
766 assert(PI && "Expected all immutable passes to be initialized");
767 if (!PI->isAnalysisGroup())
768 dbgs() << " -" << PI->getPassArgument();
770 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
771 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
772 (*I)->dumpPassArguments();
776 void PMTopLevelManager::initializeAllAnalysisInfo() {
777 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
778 E = PassManagers.end(); I != E; ++I)
779 (*I)->initializeAnalysisInfo();
781 // Initailize other pass managers
782 for (SmallVectorImpl<PMDataManager *>::iterator
783 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
785 (*I)->initializeAnalysisInfo();
787 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
788 DME = LastUser.end(); DMI != DME; ++DMI) {
789 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
790 InversedLastUser.find(DMI->second);
791 if (InvDMI != InversedLastUser.end()) {
792 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
793 L.insert(DMI->first);
795 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
796 InversedLastUser[DMI->second] = L;
802 PMTopLevelManager::~PMTopLevelManager() {
803 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
804 E = PassManagers.end(); I != E; ++I)
807 for (SmallVectorImpl<ImmutablePass *>::iterator
808 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
811 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
812 DME = AnUsageMap.end(); DMI != DME; ++DMI)
816 //===----------------------------------------------------------------------===//
817 // PMDataManager implementation
819 /// Augement AvailableAnalysis by adding analysis made available by pass P.
820 void PMDataManager::recordAvailableAnalysis(Pass *P) {
821 AnalysisID PI = P->getPassID();
823 AvailableAnalysis[PI] = P;
825 assert(!AvailableAnalysis.empty());
827 // This pass is the current implementation of all of the interfaces it
828 // implements as well.
829 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI);
830 if (PInf == 0) return;
831 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
832 for (unsigned i = 0, e = II.size(); i != e; ++i)
833 AvailableAnalysis[II[i]->getTypeInfo()] = P;
836 // Return true if P preserves high level analysis used by other
837 // passes managed by this manager
838 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
839 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
840 if (AnUsage->getPreservesAll())
843 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
844 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
845 E = HigherLevelAnalysis.end(); I != E; ++I) {
847 if (P1->getAsImmutablePass() == 0 &&
848 std::find(PreservedSet.begin(), PreservedSet.end(),
857 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
858 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
859 // Don't do this unless assertions are enabled.
863 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
864 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
866 // Verify preserved analysis
867 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
868 E = PreservedSet.end(); I != E; ++I) {
870 if (Pass *AP = findAnalysisPass(AID, true)) {
871 TimeRegion PassTimer(getPassTimer(AP));
872 AP->verifyAnalysis();
877 /// Remove Analysis not preserved by Pass P
878 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
879 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
880 if (AnUsage->getPreservesAll())
883 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
884 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
885 E = AvailableAnalysis.end(); I != E; ) {
886 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
887 if (Info->second->getAsImmutablePass() == 0 &&
888 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
889 PreservedSet.end()) {
890 // Remove this analysis
891 if (PassDebugging >= Details) {
892 Pass *S = Info->second;
893 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
894 dbgs() << S->getPassName() << "'\n";
896 AvailableAnalysis.erase(Info);
900 // Check inherited analysis also. If P is not preserving analysis
901 // provided by parent manager then remove it here.
902 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
904 if (!InheritedAnalysis[Index])
907 for (DenseMap<AnalysisID, Pass*>::iterator
908 I = InheritedAnalysis[Index]->begin(),
909 E = InheritedAnalysis[Index]->end(); I != E; ) {
910 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
911 if (Info->second->getAsImmutablePass() == 0 &&
912 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
913 PreservedSet.end()) {
914 // Remove this analysis
915 if (PassDebugging >= Details) {
916 Pass *S = Info->second;
917 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
918 dbgs() << S->getPassName() << "'\n";
920 InheritedAnalysis[Index]->erase(Info);
926 /// Remove analysis passes that are not used any longer
927 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
928 enum PassDebuggingString DBG_STR) {
930 SmallVector<Pass *, 12> DeadPasses;
932 // If this is a on the fly manager then it does not have TPM.
936 TPM->collectLastUses(DeadPasses, P);
938 if (PassDebugging >= Details && !DeadPasses.empty()) {
939 dbgs() << " -*- '" << P->getPassName();
940 dbgs() << "' is the last user of following pass instances.";
941 dbgs() << " Free these instances\n";
944 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
945 E = DeadPasses.end(); I != E; ++I)
946 freePass(*I, Msg, DBG_STR);
949 void PMDataManager::freePass(Pass *P, StringRef Msg,
950 enum PassDebuggingString DBG_STR) {
951 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
954 // If the pass crashes releasing memory, remember this.
955 PassManagerPrettyStackEntry X(P);
956 TimeRegion PassTimer(getPassTimer(P));
961 AnalysisID PI = P->getPassID();
962 if (const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(PI)) {
963 // Remove the pass itself (if it is not already removed).
964 AvailableAnalysis.erase(PI);
966 // Remove all interfaces this pass implements, for which it is also
967 // listed as the available implementation.
968 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
969 for (unsigned i = 0, e = II.size(); i != e; ++i) {
970 DenseMap<AnalysisID, Pass*>::iterator Pos =
971 AvailableAnalysis.find(II[i]->getTypeInfo());
972 if (Pos != AvailableAnalysis.end() && Pos->second == P)
973 AvailableAnalysis.erase(Pos);
978 /// Add pass P into the PassVector. Update
979 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
980 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
981 // This manager is going to manage pass P. Set up analysis resolver
983 AnalysisResolver *AR = new AnalysisResolver(*this);
986 // If a FunctionPass F is the last user of ModulePass info M
987 // then the F's manager, not F, records itself as a last user of M.
988 SmallVector<Pass *, 12> TransferLastUses;
990 if (!ProcessAnalysis) {
992 PassVector.push_back(P);
996 // At the moment, this pass is the last user of all required passes.
997 SmallVector<Pass *, 12> LastUses;
998 SmallVector<Pass *, 8> RequiredPasses;
999 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1001 unsigned PDepth = this->getDepth();
1003 collectRequiredAnalysis(RequiredPasses,
1004 ReqAnalysisNotAvailable, P);
1005 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1006 E = RequiredPasses.end(); I != E; ++I) {
1007 Pass *PRequired = *I;
1008 unsigned RDepth = 0;
1010 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1011 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1012 RDepth = DM.getDepth();
1014 if (PDepth == RDepth)
1015 LastUses.push_back(PRequired);
1016 else if (PDepth > RDepth) {
1017 // Let the parent claim responsibility of last use
1018 TransferLastUses.push_back(PRequired);
1019 // Keep track of higher level analysis used by this manager.
1020 HigherLevelAnalysis.push_back(PRequired);
1022 llvm_unreachable("Unable to accommodate Required Pass");
1025 // Set P as P's last user until someone starts using P.
1026 // However, if P is a Pass Manager then it does not need
1027 // to record its last user.
1028 if (P->getAsPMDataManager() == 0)
1029 LastUses.push_back(P);
1030 TPM->setLastUser(LastUses, P);
1032 if (!TransferLastUses.empty()) {
1033 Pass *My_PM = getAsPass();
1034 TPM->setLastUser(TransferLastUses, My_PM);
1035 TransferLastUses.clear();
1038 // Now, take care of required analyses that are not available.
1039 for (SmallVectorImpl<AnalysisID>::iterator
1040 I = ReqAnalysisNotAvailable.begin(),
1041 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1042 const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(*I);
1043 Pass *AnalysisPass = PI->createPass();
1044 this->addLowerLevelRequiredPass(P, AnalysisPass);
1047 // Take a note of analysis required and made available by this pass.
1048 // Remove the analysis not preserved by this pass
1049 removeNotPreservedAnalysis(P);
1050 recordAvailableAnalysis(P);
1053 PassVector.push_back(P);
1057 /// Populate RP with analysis pass that are required by
1058 /// pass P and are available. Populate RP_NotAvail with analysis
1059 /// pass that are required by pass P but are not available.
1060 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1061 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1063 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1064 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1065 for (AnalysisUsage::VectorType::const_iterator
1066 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1067 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1068 RP.push_back(AnalysisPass);
1070 RP_NotAvail.push_back(*I);
1073 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1074 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1075 E = IDs.end(); I != E; ++I) {
1076 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1077 RP.push_back(AnalysisPass);
1079 RP_NotAvail.push_back(*I);
1083 // All Required analyses should be available to the pass as it runs! Here
1084 // we fill in the AnalysisImpls member of the pass so that it can
1085 // successfully use the getAnalysis() method to retrieve the
1086 // implementations it needs.
1088 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1089 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1091 for (AnalysisUsage::VectorType::const_iterator
1092 I = AnUsage->getRequiredSet().begin(),
1093 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1094 Pass *Impl = findAnalysisPass(*I, true);
1096 // This may be analysis pass that is initialized on the fly.
1097 // If that is not the case then it will raise an assert when it is used.
1099 AnalysisResolver *AR = P->getResolver();
1100 assert(AR && "Analysis Resolver is not set");
1101 AR->addAnalysisImplsPair(*I, Impl);
1105 /// Find the pass that implements Analysis AID. If desired pass is not found
1106 /// then return NULL.
1107 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1109 // Check if AvailableAnalysis map has one entry.
1110 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1112 if (I != AvailableAnalysis.end())
1115 // Search Parents through TopLevelManager
1117 return TPM->findAnalysisPass(AID);
1122 // Print list of passes that are last used by P.
1123 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1125 SmallVector<Pass *, 12> LUses;
1127 // If this is a on the fly manager then it does not have TPM.
1131 TPM->collectLastUses(LUses, P);
1133 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1134 E = LUses.end(); I != E; ++I) {
1135 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1136 (*I)->dumpPassStructure(0);
1140 void PMDataManager::dumpPassArguments() const {
1141 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1142 E = PassVector.end(); I != E; ++I) {
1143 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1144 PMD->dumpPassArguments();
1146 if (const PassInfo *PI =
1147 PassRegistry::getPassRegistry()->getPassInfo((*I)->getPassID()))
1148 if (!PI->isAnalysisGroup())
1149 dbgs() << " -" << PI->getPassArgument();
1153 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1154 enum PassDebuggingString S2,
1156 if (PassDebugging < Executions)
1158 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1161 dbgs() << "Executing Pass '" << P->getPassName();
1163 case MODIFICATION_MSG:
1164 dbgs() << "Made Modification '" << P->getPassName();
1167 dbgs() << " Freeing Pass '" << P->getPassName();
1173 case ON_BASICBLOCK_MSG:
1174 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1176 case ON_FUNCTION_MSG:
1177 dbgs() << "' on Function '" << Msg << "'...\n";
1180 dbgs() << "' on Module '" << Msg << "'...\n";
1183 dbgs() << "' on Region '" << Msg << "'...\n";
1186 dbgs() << "' on Loop '" << Msg << "'...\n";
1189 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1196 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1197 if (PassDebugging < Details)
1200 AnalysisUsage analysisUsage;
1201 P->getAnalysisUsage(analysisUsage);
1202 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1205 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1206 if (PassDebugging < Details)
1209 AnalysisUsage analysisUsage;
1210 P->getAnalysisUsage(analysisUsage);
1211 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1214 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1215 const AnalysisUsage::VectorType &Set) const {
1216 assert(PassDebugging >= Details);
1219 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1220 for (unsigned i = 0; i != Set.size(); ++i) {
1221 if (i) dbgs() << ',';
1222 const PassInfo *PInf = PassRegistry::getPassRegistry()->getPassInfo(Set[i]);
1224 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1226 dbgs() << " Uninitialized Pass";
1229 dbgs() << ' ' << PInf->getPassName();
1234 /// Add RequiredPass into list of lower level passes required by pass P.
1235 /// RequiredPass is run on the fly by Pass Manager when P requests it
1236 /// through getAnalysis interface.
1237 /// This should be handled by specific pass manager.
1238 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1240 TPM->dumpArguments();
1244 // Module Level pass may required Function Level analysis info
1245 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1246 // to provide this on demand. In that case, in Pass manager terminology,
1247 // module level pass is requiring lower level analysis info managed by
1248 // lower level pass manager.
1250 // When Pass manager is not able to order required analysis info, Pass manager
1251 // checks whether any lower level manager will be able to provide this
1252 // analysis info on demand or not.
1254 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1255 dbgs() << "' required by '" << P->getPassName() << "'\n";
1257 llvm_unreachable("Unable to schedule pass");
1260 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1261 llvm_unreachable("Unable to find on the fly pass");
1265 PMDataManager::~PMDataManager() {
1266 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1267 E = PassVector.end(); I != E; ++I)
1271 //===----------------------------------------------------------------------===//
1272 // NOTE: Is this the right place to define this method ?
1273 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1274 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1275 return PM.findAnalysisPass(ID, dir);
1278 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1280 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1283 //===----------------------------------------------------------------------===//
1284 // BBPassManager implementation
1286 /// Execute all of the passes scheduled for execution by invoking
1287 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1288 /// the function, and if so, return true.
1289 bool BBPassManager::runOnFunction(Function &F) {
1290 if (F.isDeclaration())
1293 bool Changed = doInitialization(F);
1295 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1296 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1297 BasicBlockPass *BP = getContainedPass(Index);
1298 bool LocalChanged = false;
1300 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1301 dumpRequiredSet(BP);
1303 initializeAnalysisImpl(BP);
1306 // If the pass crashes, remember this.
1307 PassManagerPrettyStackEntry X(BP, *I);
1308 TimeRegion PassTimer(getPassTimer(BP));
1310 LocalChanged |= BP->runOnBasicBlock(*I);
1313 Changed |= LocalChanged;
1315 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1317 dumpPreservedSet(BP);
1319 verifyPreservedAnalysis(BP);
1320 removeNotPreservedAnalysis(BP);
1321 recordAvailableAnalysis(BP);
1322 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1325 return doFinalization(F) || Changed;
1328 // Implement doInitialization and doFinalization
1329 bool BBPassManager::doInitialization(Module &M) {
1330 bool Changed = false;
1332 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1333 Changed |= getContainedPass(Index)->doInitialization(M);
1338 bool BBPassManager::doFinalization(Module &M) {
1339 bool Changed = false;
1341 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1342 Changed |= getContainedPass(Index)->doFinalization(M);
1347 bool BBPassManager::doInitialization(Function &F) {
1348 bool Changed = false;
1350 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1351 BasicBlockPass *BP = getContainedPass(Index);
1352 Changed |= BP->doInitialization(F);
1358 bool BBPassManager::doFinalization(Function &F) {
1359 bool Changed = false;
1361 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1362 BasicBlockPass *BP = getContainedPass(Index);
1363 Changed |= BP->doFinalization(F);
1370 //===----------------------------------------------------------------------===//
1371 // FunctionPassManager implementation
1373 /// Create new Function pass manager
1374 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1375 FPM = new FunctionPassManagerImpl();
1376 // FPM is the top level manager.
1377 FPM->setTopLevelManager(FPM);
1379 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1380 FPM->setResolver(AR);
1383 FunctionPassManager::~FunctionPassManager() {
1387 /// add - Add a pass to the queue of passes to run. This passes
1388 /// ownership of the Pass to the PassManager. When the
1389 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1390 /// there is no need to delete the pass. (TODO delete passes.)
1391 /// This implies that all passes MUST be allocated with 'new'.
1392 void FunctionPassManager::add(Pass *P) {
1396 /// run - Execute all of the passes scheduled for execution. Keep
1397 /// track of whether any of the passes modifies the function, and if
1398 /// so, return true.
1400 bool FunctionPassManager::run(Function &F) {
1401 if (F.isMaterializable()) {
1403 if (F.Materialize(&errstr))
1404 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1410 /// doInitialization - Run all of the initializers for the function passes.
1412 bool FunctionPassManager::doInitialization() {
1413 return FPM->doInitialization(*M);
1416 /// doFinalization - Run all of the finalizers for the function passes.
1418 bool FunctionPassManager::doFinalization() {
1419 return FPM->doFinalization(*M);
1422 //===----------------------------------------------------------------------===//
1423 // FunctionPassManagerImpl implementation
1425 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1426 bool Changed = false;
1431 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1432 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1433 E = IPV.end(); I != E; ++I) {
1434 Changed |= (*I)->doInitialization(M);
1437 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1438 Changed |= getContainedManager(Index)->doInitialization(M);
1443 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1444 bool Changed = false;
1446 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1447 Changed |= getContainedManager(Index)->doFinalization(M);
1449 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1450 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1451 E = IPV.end(); I != E; ++I) {
1452 Changed |= (*I)->doFinalization(M);
1458 /// cleanup - After running all passes, clean up pass manager cache.
1459 void FPPassManager::cleanup() {
1460 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1461 FunctionPass *FP = getContainedPass(Index);
1462 AnalysisResolver *AR = FP->getResolver();
1463 assert(AR && "Analysis Resolver is not set");
1464 AR->clearAnalysisImpls();
1468 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1471 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1472 FPPassManager *FPPM = getContainedManager(Index);
1473 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1474 FPPM->getContainedPass(Index)->releaseMemory();
1480 // Execute all the passes managed by this top level manager.
1481 // Return true if any function is modified by a pass.
1482 bool FunctionPassManagerImpl::run(Function &F) {
1483 bool Changed = false;
1484 TimingInfo::createTheTimeInfo();
1486 initializeAllAnalysisInfo();
1487 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1488 Changed |= getContainedManager(Index)->runOnFunction(F);
1490 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1491 getContainedManager(Index)->cleanup();
1497 //===----------------------------------------------------------------------===//
1498 // FPPassManager implementation
1500 char FPPassManager::ID = 0;
1501 /// Print passes managed by this manager
1502 void FPPassManager::dumpPassStructure(unsigned Offset) {
1503 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1504 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1505 FunctionPass *FP = getContainedPass(Index);
1506 FP->dumpPassStructure(Offset + 1);
1507 dumpLastUses(FP, Offset+1);
1512 /// Execute all of the passes scheduled for execution by invoking
1513 /// runOnFunction method. Keep track of whether any of the passes modifies
1514 /// the function, and if so, return true.
1515 bool FPPassManager::runOnFunction(Function &F) {
1516 if (F.isDeclaration())
1519 bool Changed = false;
1521 // Collect inherited analysis from Module level pass manager.
1522 populateInheritedAnalysis(TPM->activeStack);
1524 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1525 FunctionPass *FP = getContainedPass(Index);
1526 bool LocalChanged = false;
1528 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1529 dumpRequiredSet(FP);
1531 initializeAnalysisImpl(FP);
1534 PassManagerPrettyStackEntry X(FP, F);
1535 TimeRegion PassTimer(getPassTimer(FP));
1537 LocalChanged |= FP->runOnFunction(F);
1540 Changed |= LocalChanged;
1542 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1543 dumpPreservedSet(FP);
1545 verifyPreservedAnalysis(FP);
1546 removeNotPreservedAnalysis(FP);
1547 recordAvailableAnalysis(FP);
1548 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1553 bool FPPassManager::runOnModule(Module &M) {
1554 bool Changed = false;
1556 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1557 Changed |= runOnFunction(*I);
1562 bool FPPassManager::doInitialization(Module &M) {
1563 bool Changed = false;
1565 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1566 Changed |= getContainedPass(Index)->doInitialization(M);
1571 bool FPPassManager::doFinalization(Module &M) {
1572 bool Changed = false;
1574 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1575 Changed |= getContainedPass(Index)->doFinalization(M);
1580 //===----------------------------------------------------------------------===//
1581 // MPPassManager implementation
1583 /// Execute all of the passes scheduled for execution by invoking
1584 /// runOnModule method. Keep track of whether any of the passes modifies
1585 /// the module, and if so, return true.
1587 MPPassManager::runOnModule(Module &M) {
1588 bool Changed = false;
1590 // Initialize on-the-fly passes
1591 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1592 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1594 FunctionPassManagerImpl *FPP = I->second;
1595 Changed |= FPP->doInitialization(M);
1598 // Initialize module passes
1599 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1600 Changed |= getContainedPass(Index)->doInitialization(M);
1602 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1603 ModulePass *MP = getContainedPass(Index);
1604 bool LocalChanged = false;
1606 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1607 dumpRequiredSet(MP);
1609 initializeAnalysisImpl(MP);
1612 PassManagerPrettyStackEntry X(MP, M);
1613 TimeRegion PassTimer(getPassTimer(MP));
1615 LocalChanged |= MP->runOnModule(M);
1618 Changed |= LocalChanged;
1620 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1621 M.getModuleIdentifier());
1622 dumpPreservedSet(MP);
1624 verifyPreservedAnalysis(MP);
1625 removeNotPreservedAnalysis(MP);
1626 recordAvailableAnalysis(MP);
1627 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1630 // Finalize module passes
1631 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1632 Changed |= getContainedPass(Index)->doFinalization(M);
1634 // Finalize on-the-fly passes
1635 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1636 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1638 FunctionPassManagerImpl *FPP = I->second;
1639 // We don't know when is the last time an on-the-fly pass is run,
1640 // so we need to releaseMemory / finalize here
1641 FPP->releaseMemoryOnTheFly();
1642 Changed |= FPP->doFinalization(M);
1648 /// Add RequiredPass into list of lower level passes required by pass P.
1649 /// RequiredPass is run on the fly by Pass Manager when P requests it
1650 /// through getAnalysis interface.
1651 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1652 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1653 "Unable to handle Pass that requires lower level Analysis pass");
1654 assert((P->getPotentialPassManagerType() <
1655 RequiredPass->getPotentialPassManagerType()) &&
1656 "Unable to handle Pass that requires lower level Analysis pass");
1658 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1660 FPP = new FunctionPassManagerImpl();
1661 // FPP is the top level manager.
1662 FPP->setTopLevelManager(FPP);
1664 OnTheFlyManagers[P] = FPP;
1666 FPP->add(RequiredPass);
1668 // Register P as the last user of RequiredPass.
1670 SmallVector<Pass *, 1> LU;
1671 LU.push_back(RequiredPass);
1672 FPP->setLastUser(LU, P);
1676 /// Return function pass corresponding to PassInfo PI, that is
1677 /// required by module pass MP. Instantiate analysis pass, by using
1678 /// its runOnFunction() for function F.
1679 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1680 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1681 assert(FPP && "Unable to find on the fly pass");
1683 FPP->releaseMemoryOnTheFly();
1685 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1689 //===----------------------------------------------------------------------===//
1690 // PassManagerImpl implementation
1693 /// run - Execute all of the passes scheduled for execution. Keep track of
1694 /// whether any of the passes modifies the module, and if so, return true.
1695 bool PassManagerImpl::run(Module &M) {
1696 bool Changed = false;
1697 TimingInfo::createTheTimeInfo();
1702 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1703 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1704 E = IPV.end(); I != E; ++I) {
1705 Changed |= (*I)->doInitialization(M);
1708 initializeAllAnalysisInfo();
1709 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1710 Changed |= getContainedManager(Index)->runOnModule(M);
1712 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1713 E = IPV.end(); I != E; ++I) {
1714 Changed |= (*I)->doFinalization(M);
1720 //===----------------------------------------------------------------------===//
1721 // PassManager implementation
1723 /// Create new pass manager
1724 PassManager::PassManager() {
1725 PM = new PassManagerImpl();
1726 // PM is the top level manager
1727 PM->setTopLevelManager(PM);
1730 PassManager::~PassManager() {
1734 /// add - Add a pass to the queue of passes to run. This passes ownership of
1735 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1736 /// will be destroyed as well, so there is no need to delete the pass. This
1737 /// implies that all passes MUST be allocated with 'new'.
1738 void PassManager::add(Pass *P) {
1742 /// run - Execute all of the passes scheduled for execution. Keep track of
1743 /// whether any of the passes modifies the module, and if so, return true.
1744 bool PassManager::run(Module &M) {
1748 //===----------------------------------------------------------------------===//
1749 // TimingInfo implementation
1751 bool llvm::TimePassesIsEnabled = false;
1752 static cl::opt<bool,true>
1753 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1754 cl::desc("Time each pass, printing elapsed time for each on exit"));
1756 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1757 // a non-null value (if the -time-passes option is enabled) or it leaves it
1758 // null. It may be called multiple times.
1759 void TimingInfo::createTheTimeInfo() {
1760 if (!TimePassesIsEnabled || TheTimeInfo) return;
1762 // Constructed the first time this is called, iff -time-passes is enabled.
1763 // This guarantees that the object will be constructed before static globals,
1764 // thus it will be destroyed before them.
1765 static ManagedStatic<TimingInfo> TTI;
1766 TheTimeInfo = &*TTI;
1769 /// If TimingInfo is enabled then start pass timer.
1770 Timer *llvm::getPassTimer(Pass *P) {
1772 return TheTimeInfo->getPassTimer(P);
1776 //===----------------------------------------------------------------------===//
1777 // PMStack implementation
1780 // Pop Pass Manager from the stack and clear its analysis info.
1781 void PMStack::pop() {
1783 PMDataManager *Top = this->top();
1784 Top->initializeAnalysisInfo();
1789 // Push PM on the stack and set its top level manager.
1790 void PMStack::push(PMDataManager *PM) {
1791 assert(PM && "Unable to push. Pass Manager expected");
1792 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1794 if (!this->empty()) {
1795 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1796 && "pushing bad pass manager to PMStack");
1797 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1799 assert(TPM && "Unable to find top level manager");
1800 TPM->addIndirectPassManager(PM);
1801 PM->setTopLevelManager(TPM);
1802 PM->setDepth(this->top()->getDepth()+1);
1804 assert((PM->getPassManagerType() == PMT_ModulePassManager
1805 || PM->getPassManagerType() == PMT_FunctionPassManager)
1806 && "pushing bad pass manager to PMStack");
1813 // Dump content of the pass manager stack.
1814 void PMStack::dump() const {
1815 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1816 E = S.end(); I != E; ++I)
1817 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1823 /// Find appropriate Module Pass Manager in the PM Stack and
1824 /// add self into that manager.
1825 void ModulePass::assignPassManager(PMStack &PMS,
1826 PassManagerType PreferredType) {
1827 // Find Module Pass Manager
1828 while (!PMS.empty()) {
1829 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1830 if (TopPMType == PreferredType)
1831 break; // We found desired pass manager
1832 else if (TopPMType > PMT_ModulePassManager)
1833 PMS.pop(); // Pop children pass managers
1837 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1838 PMS.top()->add(this);
1841 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1842 /// in the PM Stack and add self into that manager.
1843 void FunctionPass::assignPassManager(PMStack &PMS,
1844 PassManagerType PreferredType) {
1846 // Find Function Pass Manager
1847 while (!PMS.empty()) {
1848 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1854 // Create new Function Pass Manager if needed.
1856 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1857 FPP = (FPPassManager *)PMS.top();
1859 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1860 PMDataManager *PMD = PMS.top();
1862 // [1] Create new Function Pass Manager
1863 FPP = new FPPassManager();
1864 FPP->populateInheritedAnalysis(PMS);
1866 // [2] Set up new manager's top level manager
1867 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1868 TPM->addIndirectPassManager(FPP);
1870 // [3] Assign manager to manage this new manager. This may create
1871 // and push new managers into PMS
1872 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1874 // [4] Push new manager into PMS
1878 // Assign FPP as the manager of this pass.
1882 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1883 /// in the PM Stack and add self into that manager.
1884 void BasicBlockPass::assignPassManager(PMStack &PMS,
1885 PassManagerType PreferredType) {
1888 // Basic Pass Manager is a leaf pass manager. It does not handle
1889 // any other pass manager.
1891 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1892 BBP = (BBPassManager *)PMS.top();
1894 // If leaf manager is not Basic Block Pass manager then create new
1895 // basic Block Pass manager.
1896 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1897 PMDataManager *PMD = PMS.top();
1899 // [1] Create new Basic Block Manager
1900 BBP = new BBPassManager();
1902 // [2] Set up new manager's top level manager
1903 // Basic Block Pass Manager does not live by itself
1904 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1905 TPM->addIndirectPassManager(BBP);
1907 // [3] Assign manager to manage this new manager. This may create
1908 // and push new managers into PMS
1909 BBP->assignPassManager(PMS, PreferredType);
1911 // [4] Push new manager into PMS
1915 // Assign BBP as the manager of this pass.
1919 PassManagerBase::~PassManagerBase() {}