1 //===- PassManager.cpp - LLVM Pass Infrastructure Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/PassManagers.h"
16 #include "llvm/Assembly/PrintModulePass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/Timer.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Mutex.h"
27 #include "llvm/System/Threading.h"
28 #include "llvm-c/Core.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(Pass *P,
86 PassOptionList &PassesToPrint) {
87 for (unsigned i = 0, ie = PassesToPrint.size(); i < ie; ++i) {
88 const llvm::PassInfo *PassInf = PassesToPrint[i];
89 if (PassInf && P->getPassInfo())
90 if (PassInf->getPassArgument() ==
91 P->getPassInfo()->getPassArgument()) {
99 /// This is a utility to check whether a pass should have IR dumped
101 static bool ShouldPrintBeforePass(Pass *P) {
102 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(P, PrintBefore);
105 /// This is a utility to check whether a pass should have IR dumped
107 static bool ShouldPrintAfterPass(Pass *P) {
108 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(P, PrintAfter);
111 } // End of llvm namespace
113 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
114 /// or higher is specified.
115 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
116 return PassDebugging >= Executions;
122 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
123 if (V == 0 && M == 0)
124 OS << "Releasing pass '";
126 OS << "Running pass '";
128 OS << P->getPassName() << "'";
131 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
140 if (isa<Function>(V))
142 else if (isa<BasicBlock>(V))
148 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
155 //===----------------------------------------------------------------------===//
158 /// BBPassManager manages BasicBlockPass. It batches all the
159 /// pass together and sequence them to process one basic block before
160 /// processing next basic block.
161 class BBPassManager : public PMDataManager, public FunctionPass {
165 explicit BBPassManager(int Depth)
166 : PMDataManager(Depth), FunctionPass(&ID) {}
168 /// Execute all of the passes scheduled for execution. Keep track of
169 /// whether any of the passes modifies the function, and if so, return true.
170 bool runOnFunction(Function &F);
172 /// Pass Manager itself does not invalidate any analysis info.
173 void getAnalysisUsage(AnalysisUsage &Info) const {
174 Info.setPreservesAll();
177 bool doInitialization(Module &M);
178 bool doInitialization(Function &F);
179 bool doFinalization(Module &M);
180 bool doFinalization(Function &F);
182 virtual PMDataManager *getAsPMDataManager() { return this; }
183 virtual Pass *getAsPass() { return this; }
185 virtual const char *getPassName() const {
186 return "BasicBlock Pass Manager";
189 // Print passes managed by this manager
190 void dumpPassStructure(unsigned Offset) {
191 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
192 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
193 BasicBlockPass *BP = getContainedPass(Index);
194 BP->dumpPassStructure(Offset + 1);
195 dumpLastUses(BP, Offset+1);
199 BasicBlockPass *getContainedPass(unsigned N) {
200 assert(N < PassVector.size() && "Pass number out of range!");
201 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
205 virtual PassManagerType getPassManagerType() const {
206 return PMT_BasicBlockPassManager;
210 char BBPassManager::ID = 0;
215 //===----------------------------------------------------------------------===//
216 // FunctionPassManagerImpl
218 /// FunctionPassManagerImpl manages FPPassManagers
219 class FunctionPassManagerImpl : public Pass,
220 public PMDataManager,
221 public PMTopLevelManager {
226 explicit FunctionPassManagerImpl(int Depth) :
227 Pass(PT_PassManager, &ID), PMDataManager(Depth),
228 PMTopLevelManager(TLM_Function), wasRun(false) { }
230 /// add - Add a pass to the queue of passes to run. This passes ownership of
231 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
232 /// will be destroyed as well, so there is no need to delete the pass. This
233 /// implies that all passes MUST be allocated with 'new'.
238 /// createPrinterPass - Get a function printer pass.
239 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
240 return createPrintFunctionPass(Banner, &O);
243 // Prepare for running an on the fly pass, freeing memory if needed
244 // from a previous run.
245 void releaseMemoryOnTheFly();
247 /// run - Execute all of the passes scheduled for execution. Keep track of
248 /// whether any of the passes modifies the module, and if so, return true.
249 bool run(Function &F);
251 /// doInitialization - Run all of the initializers for the function passes.
253 bool doInitialization(Module &M);
255 /// doFinalization - Run all of the finalizers for the function passes.
257 bool doFinalization(Module &M);
260 virtual PMDataManager *getAsPMDataManager() { return this; }
261 virtual Pass *getAsPass() { return this; }
263 /// Pass Manager itself does not invalidate any analysis info.
264 void getAnalysisUsage(AnalysisUsage &Info) const {
265 Info.setPreservesAll();
268 inline void addTopLevelPass(Pass *P) {
269 if (ImmutablePass *IP = P->getAsImmutablePass()) {
270 // P is a immutable pass and it will be managed by this
271 // top level manager. Set up analysis resolver to connect them.
272 AnalysisResolver *AR = new AnalysisResolver(*this);
274 initializeAnalysisImpl(P);
275 addImmutablePass(IP);
276 recordAvailableAnalysis(IP);
278 P->assignPassManager(activeStack, PMT_FunctionPassManager);
283 FPPassManager *getContainedManager(unsigned N) {
284 assert(N < PassManagers.size() && "Pass number out of range!");
285 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
290 char FunctionPassManagerImpl::ID = 0;
291 //===----------------------------------------------------------------------===//
294 /// MPPassManager manages ModulePasses and function pass managers.
295 /// It batches all Module passes and function pass managers together and
296 /// sequences them to process one module.
297 class MPPassManager : public Pass, public PMDataManager {
300 explicit MPPassManager(int Depth) :
301 Pass(PT_PassManager, &ID), PMDataManager(Depth) { }
303 // Delete on the fly managers.
304 virtual ~MPPassManager() {
305 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
306 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
308 FunctionPassManagerImpl *FPP = I->second;
313 /// createPrinterPass - Get a module printer pass.
314 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
315 return createPrintModulePass(&O, false, Banner);
318 /// run - Execute all of the passes scheduled for execution. Keep track of
319 /// whether any of the passes modifies the module, and if so, return true.
320 bool runOnModule(Module &M);
322 /// Pass Manager itself does not invalidate any analysis info.
323 void getAnalysisUsage(AnalysisUsage &Info) const {
324 Info.setPreservesAll();
327 /// Add RequiredPass into list of lower level passes required by pass P.
328 /// RequiredPass is run on the fly by Pass Manager when P requests it
329 /// through getAnalysis interface.
330 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
332 /// Return function pass corresponding to PassInfo PI, that is
333 /// required by module pass MP. Instantiate analysis pass, by using
334 /// its runOnFunction() for function F.
335 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
337 virtual const char *getPassName() const {
338 return "Module Pass Manager";
341 virtual PMDataManager *getAsPMDataManager() { return this; }
342 virtual Pass *getAsPass() { return this; }
344 // Print passes managed by this manager
345 void dumpPassStructure(unsigned Offset) {
346 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
347 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
348 ModulePass *MP = getContainedPass(Index);
349 MP->dumpPassStructure(Offset + 1);
350 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
351 OnTheFlyManagers.find(MP);
352 if (I != OnTheFlyManagers.end())
353 I->second->dumpPassStructure(Offset + 2);
354 dumpLastUses(MP, Offset+1);
358 ModulePass *getContainedPass(unsigned N) {
359 assert(N < PassVector.size() && "Pass number out of range!");
360 return static_cast<ModulePass *>(PassVector[N]);
363 virtual PassManagerType getPassManagerType() const {
364 return PMT_ModulePassManager;
368 /// Collection of on the fly FPPassManagers. These managers manage
369 /// function passes that are required by module passes.
370 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
373 char MPPassManager::ID = 0;
374 //===----------------------------------------------------------------------===//
378 /// PassManagerImpl manages MPPassManagers
379 class PassManagerImpl : public Pass,
380 public PMDataManager,
381 public PMTopLevelManager {
385 explicit PassManagerImpl(int Depth) :
386 Pass(PT_PassManager, &ID), PMDataManager(Depth),
387 PMTopLevelManager(TLM_Pass) { }
389 /// add - Add a pass to the queue of passes to run. This passes ownership of
390 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
391 /// will be destroyed as well, so there is no need to delete the pass. This
392 /// implies that all passes MUST be allocated with 'new'.
397 /// createPrinterPass - Get a module printer pass.
398 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
399 return createPrintModulePass(&O, false, Banner);
402 /// run - Execute all of the passes scheduled for execution. Keep track of
403 /// whether any of the passes modifies the module, and if so, return true.
406 /// Pass Manager itself does not invalidate any analysis info.
407 void getAnalysisUsage(AnalysisUsage &Info) const {
408 Info.setPreservesAll();
411 inline void addTopLevelPass(Pass *P) {
412 if (ImmutablePass *IP = P->getAsImmutablePass()) {
413 // P is a immutable pass and it will be managed by this
414 // top level manager. Set up analysis resolver to connect them.
415 AnalysisResolver *AR = new AnalysisResolver(*this);
417 initializeAnalysisImpl(P);
418 addImmutablePass(IP);
419 recordAvailableAnalysis(IP);
421 P->assignPassManager(activeStack, PMT_ModulePassManager);
425 virtual PMDataManager *getAsPMDataManager() { return this; }
426 virtual Pass *getAsPass() { return this; }
428 MPPassManager *getContainedManager(unsigned N) {
429 assert(N < PassManagers.size() && "Pass number out of range!");
430 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
435 char PassManagerImpl::ID = 0;
436 } // End of llvm namespace
440 //===----------------------------------------------------------------------===//
441 /// TimingInfo Class - This class is used to calculate information about the
442 /// amount of time each pass takes to execute. This only happens when
443 /// -time-passes is enabled on the command line.
446 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
449 DenseMap<Pass*, Timer*> TimingData;
452 // Use 'create' member to get this.
453 TimingInfo() : TG("... Pass execution timing report ...") {}
455 // TimingDtor - Print out information about timing information
457 // Delete all of the timers, which accumulate their info into the
459 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
460 E = TimingData.end(); I != E; ++I)
462 // TimerGroup is deleted next, printing the report.
465 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
466 // to a non null value (if the -time-passes option is enabled) or it leaves it
467 // null. It may be called multiple times.
468 static void createTheTimeInfo();
470 /// getPassTimer - Return the timer for the specified pass if it exists.
471 Timer *getPassTimer(Pass *P) {
472 if (P->getAsPMDataManager())
475 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
476 Timer *&T = TimingData[P];
478 T = new Timer(P->getPassName(), TG);
483 } // End of anon namespace
485 static TimingInfo *TheTimeInfo;
487 //===----------------------------------------------------------------------===//
488 // PMTopLevelManager implementation
490 /// Initialize top level manager. Create first pass manager.
491 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
493 MPPassManager *MPP = new MPPassManager(1);
494 MPP->setTopLevelManager(this);
496 activeStack.push(MPP);
497 } else if (t == TLM_Function) {
498 FPPassManager *FPP = new FPPassManager(1);
499 FPP->setTopLevelManager(this);
501 activeStack.push(FPP);
505 /// Set pass P as the last user of the given analysis passes.
506 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
508 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
509 E = AnalysisPasses.end(); I != E; ++I) {
516 // If AP is the last user of other passes then make P last user of
518 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
519 LUE = LastUser.end(); LUI != LUE; ++LUI) {
520 if (LUI->second == AP)
521 // DenseMap iterator is not invalidated here because
522 // this is just updating exisitng entry.
523 LastUser[LUI->first] = P;
528 /// Collect passes whose last user is P
529 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
531 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
532 InversedLastUser.find(P);
533 if (DMI == InversedLastUser.end())
536 SmallPtrSet<Pass *, 8> &LU = DMI->second;
537 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
538 E = LU.end(); I != E; ++I) {
539 LastUses.push_back(*I);
544 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
545 AnalysisUsage *AnUsage = NULL;
546 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
547 if (DMI != AnUsageMap.end())
548 AnUsage = DMI->second;
550 AnUsage = new AnalysisUsage();
551 P->getAnalysisUsage(*AnUsage);
552 AnUsageMap[P] = AnUsage;
557 /// Schedule pass P for execution. Make sure that passes required by
558 /// P are run before P is run. Update analysis info maintained by
559 /// the manager. Remove dead passes. This is a recursive function.
560 void PMTopLevelManager::schedulePass(Pass *P) {
562 // TODO : Allocate function manager for this pass, other wise required set
563 // may be inserted into previous function manager
565 // Give pass a chance to prepare the stage.
566 P->preparePassManager(activeStack);
568 // If P is an analysis pass and it is available then do not
569 // generate the analysis again. Stale analysis info should not be
570 // available at this point.
571 if (P->getPassInfo() &&
572 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
577 AnalysisUsage *AnUsage = findAnalysisUsage(P);
579 bool checkAnalysis = true;
580 while (checkAnalysis) {
581 checkAnalysis = false;
583 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
584 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
585 E = RequiredSet.end(); I != E; ++I) {
587 Pass *AnalysisPass = findAnalysisPass(*I);
589 AnalysisPass = (*I)->createPass();
590 if (P->getPotentialPassManagerType () ==
591 AnalysisPass->getPotentialPassManagerType())
592 // Schedule analysis pass that is managed by the same pass manager.
593 schedulePass(AnalysisPass);
594 else if (P->getPotentialPassManagerType () >
595 AnalysisPass->getPotentialPassManagerType()) {
596 // Schedule analysis pass that is managed by a new manager.
597 schedulePass(AnalysisPass);
598 // Recheck analysis passes to ensure that required analysises that
599 // are already checked are still available.
600 checkAnalysis = true;
603 // Do not schedule this analysis. Lower level analsyis
604 // passes are run on the fly.
610 // Now all required passes are available.
614 /// Find the pass that implements Analysis AID. Search immutable
615 /// passes and all pass managers. If desired pass is not found
616 /// then return NULL.
617 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
620 // Check pass managers
621 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
622 E = PassManagers.end(); P == NULL && I != E; ++I) {
623 PMDataManager *PMD = *I;
624 P = PMD->findAnalysisPass(AID, false);
627 // Check other pass managers
628 for (SmallVector<PMDataManager *, 8>::iterator
629 I = IndirectPassManagers.begin(),
630 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
631 P = (*I)->findAnalysisPass(AID, false);
633 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
634 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
635 const PassInfo *PI = (*I)->getPassInfo();
639 // If Pass not found then check the interfaces implemented by Immutable Pass
641 const PassInfo::InterfaceInfo *ImmPI = PI->getInterfacesImplemented();
643 if (ImmPI->interface == AID) {
655 // Print passes managed by this top level manager.
656 void PMTopLevelManager::dumpPasses() const {
658 if (PassDebugging < Structure)
661 // Print out the immutable passes
662 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
663 ImmutablePasses[i]->dumpPassStructure(0);
666 // Every class that derives from PMDataManager also derives from Pass
667 // (sometimes indirectly), but there's no inheritance relationship
668 // between PMDataManager and Pass, so we have to getAsPass to get
669 // from a PMDataManager* to a Pass*.
670 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
671 E = PassManagers.end(); I != E; ++I)
672 (*I)->getAsPass()->dumpPassStructure(1);
675 void PMTopLevelManager::dumpArguments() const {
677 if (PassDebugging < Arguments)
680 dbgs() << "Pass Arguments: ";
681 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
682 E = PassManagers.end(); I != E; ++I)
683 (*I)->dumpPassArguments();
687 void PMTopLevelManager::initializeAllAnalysisInfo() {
688 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
689 E = PassManagers.end(); I != E; ++I)
690 (*I)->initializeAnalysisInfo();
692 // Initailize other pass managers
693 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
694 E = IndirectPassManagers.end(); I != E; ++I)
695 (*I)->initializeAnalysisInfo();
697 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
698 DME = LastUser.end(); DMI != DME; ++DMI) {
699 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
700 InversedLastUser.find(DMI->second);
701 if (InvDMI != InversedLastUser.end()) {
702 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
703 L.insert(DMI->first);
705 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
706 InversedLastUser[DMI->second] = L;
712 PMTopLevelManager::~PMTopLevelManager() {
713 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
714 E = PassManagers.end(); I != E; ++I)
717 for (SmallVector<ImmutablePass *, 8>::iterator
718 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
721 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
722 DME = AnUsageMap.end(); DMI != DME; ++DMI)
726 //===----------------------------------------------------------------------===//
727 // PMDataManager implementation
729 /// Augement AvailableAnalysis by adding analysis made available by pass P.
730 void PMDataManager::recordAvailableAnalysis(Pass *P) {
731 const PassInfo *PI = P->getPassInfo();
734 AvailableAnalysis[PI] = P;
736 //This pass is the current implementation of all of the interfaces it
737 //implements as well.
738 const PassInfo::InterfaceInfo *II = PI->getInterfacesImplemented();
740 AvailableAnalysis[II->interface] = P;
745 // Return true if P preserves high level analysis used by other
746 // passes managed by this manager
747 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
748 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
749 if (AnUsage->getPreservesAll())
752 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
753 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
754 E = HigherLevelAnalysis.end(); I != E; ++I) {
756 if (P1->getAsImmutablePass() == 0 &&
757 std::find(PreservedSet.begin(), PreservedSet.end(),
758 P1->getPassInfo()) ==
766 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
767 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
768 // Don't do this unless assertions are enabled.
772 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
773 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
775 // Verify preserved analysis
776 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
777 E = PreservedSet.end(); I != E; ++I) {
779 if (Pass *AP = findAnalysisPass(AID, true)) {
780 TimeRegion PassTimer(getPassTimer(AP));
781 AP->verifyAnalysis();
786 /// Remove Analysis not preserved by Pass P
787 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
788 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
789 if (AnUsage->getPreservesAll())
792 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
793 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
794 E = AvailableAnalysis.end(); I != E; ) {
795 std::map<AnalysisID, Pass*>::iterator Info = I++;
796 if (Info->second->getAsImmutablePass() == 0 &&
797 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
798 PreservedSet.end()) {
799 // Remove this analysis
800 if (PassDebugging >= Details) {
801 Pass *S = Info->second;
802 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
803 dbgs() << S->getPassName() << "'\n";
805 AvailableAnalysis.erase(Info);
809 // Check inherited analysis also. If P is not preserving analysis
810 // provided by parent manager then remove it here.
811 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
813 if (!InheritedAnalysis[Index])
816 for (std::map<AnalysisID, Pass*>::iterator
817 I = InheritedAnalysis[Index]->begin(),
818 E = InheritedAnalysis[Index]->end(); I != E; ) {
819 std::map<AnalysisID, Pass *>::iterator Info = I++;
820 if (Info->second->getAsImmutablePass() == 0 &&
821 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
822 PreservedSet.end()) {
823 // Remove this analysis
824 if (PassDebugging >= Details) {
825 Pass *S = Info->second;
826 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
827 dbgs() << S->getPassName() << "'\n";
829 InheritedAnalysis[Index]->erase(Info);
835 /// Remove analysis passes that are not used any longer
836 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
837 enum PassDebuggingString DBG_STR) {
839 SmallVector<Pass *, 12> DeadPasses;
841 // If this is a on the fly manager then it does not have TPM.
845 TPM->collectLastUses(DeadPasses, P);
847 if (PassDebugging >= Details && !DeadPasses.empty()) {
848 dbgs() << " -*- '" << P->getPassName();
849 dbgs() << "' is the last user of following pass instances.";
850 dbgs() << " Free these instances\n";
853 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
854 E = DeadPasses.end(); I != E; ++I)
855 freePass(*I, Msg, DBG_STR);
858 void PMDataManager::freePass(Pass *P, StringRef Msg,
859 enum PassDebuggingString DBG_STR) {
860 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
863 // If the pass crashes releasing memory, remember this.
864 PassManagerPrettyStackEntry X(P);
865 TimeRegion PassTimer(getPassTimer(P));
870 if (const PassInfo *PI = P->getPassInfo()) {
871 // Remove the pass itself (if it is not already removed).
872 AvailableAnalysis.erase(PI);
874 // Remove all interfaces this pass implements, for which it is also
875 // listed as the available implementation.
876 const PassInfo::InterfaceInfo *II = PI->getInterfacesImplemented();
878 std::map<AnalysisID, Pass*>::iterator Pos =
879 AvailableAnalysis.find(II->interface);
880 if (Pos != AvailableAnalysis.end() && Pos->second == P)
881 AvailableAnalysis.erase(Pos);
887 /// Add pass P into the PassVector. Update
888 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
889 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
890 // This manager is going to manage pass P. Set up analysis resolver
892 AnalysisResolver *AR = new AnalysisResolver(*this);
895 // If a FunctionPass F is the last user of ModulePass info M
896 // then the F's manager, not F, records itself as a last user of M.
897 SmallVector<Pass *, 12> TransferLastUses;
899 if (!ProcessAnalysis) {
901 PassVector.push_back(P);
905 // At the moment, this pass is the last user of all required passes.
906 SmallVector<Pass *, 12> LastUses;
907 SmallVector<Pass *, 8> RequiredPasses;
908 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
910 unsigned PDepth = this->getDepth();
912 collectRequiredAnalysis(RequiredPasses,
913 ReqAnalysisNotAvailable, P);
914 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
915 E = RequiredPasses.end(); I != E; ++I) {
916 Pass *PRequired = *I;
919 assert(PRequired->getResolver() && "Analysis Resolver is not set");
920 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
921 RDepth = DM.getDepth();
923 if (PDepth == RDepth)
924 LastUses.push_back(PRequired);
925 else if (PDepth > RDepth) {
926 // Let the parent claim responsibility of last use
927 TransferLastUses.push_back(PRequired);
928 // Keep track of higher level analysis used by this manager.
929 HigherLevelAnalysis.push_back(PRequired);
931 llvm_unreachable("Unable to accomodate Required Pass");
934 // Set P as P's last user until someone starts using P.
935 // However, if P is a Pass Manager then it does not need
936 // to record its last user.
937 if (P->getAsPMDataManager() == 0)
938 LastUses.push_back(P);
939 TPM->setLastUser(LastUses, P);
941 if (!TransferLastUses.empty()) {
942 Pass *My_PM = getAsPass();
943 TPM->setLastUser(TransferLastUses, My_PM);
944 TransferLastUses.clear();
947 // Now, take care of required analysises that are not available.
948 for (SmallVector<AnalysisID, 8>::iterator
949 I = ReqAnalysisNotAvailable.begin(),
950 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
951 Pass *AnalysisPass = (*I)->createPass();
952 this->addLowerLevelRequiredPass(P, AnalysisPass);
955 // Take a note of analysis required and made available by this pass.
956 // Remove the analysis not preserved by this pass
957 removeNotPreservedAnalysis(P);
958 recordAvailableAnalysis(P);
961 PassVector.push_back(P);
965 /// Populate RP with analysis pass that are required by
966 /// pass P and are available. Populate RP_NotAvail with analysis
967 /// pass that are required by pass P but are not available.
968 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
969 SmallVector<AnalysisID, 8> &RP_NotAvail,
971 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
972 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
973 for (AnalysisUsage::VectorType::const_iterator
974 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
975 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
976 RP.push_back(AnalysisPass);
978 RP_NotAvail.push_back(*I);
981 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
982 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
983 E = IDs.end(); I != E; ++I) {
984 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
985 RP.push_back(AnalysisPass);
987 RP_NotAvail.push_back(*I);
991 // All Required analyses should be available to the pass as it runs! Here
992 // we fill in the AnalysisImpls member of the pass so that it can
993 // successfully use the getAnalysis() method to retrieve the
994 // implementations it needs.
996 void PMDataManager::initializeAnalysisImpl(Pass *P) {
997 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
999 for (AnalysisUsage::VectorType::const_iterator
1000 I = AnUsage->getRequiredSet().begin(),
1001 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1002 Pass *Impl = findAnalysisPass(*I, true);
1004 // This may be analysis pass that is initialized on the fly.
1005 // If that is not the case then it will raise an assert when it is used.
1007 AnalysisResolver *AR = P->getResolver();
1008 assert(AR && "Analysis Resolver is not set");
1009 AR->addAnalysisImplsPair(*I, Impl);
1013 /// Find the pass that implements Analysis AID. If desired pass is not found
1014 /// then return NULL.
1015 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1017 // Check if AvailableAnalysis map has one entry.
1018 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1020 if (I != AvailableAnalysis.end())
1023 // Search Parents through TopLevelManager
1025 return TPM->findAnalysisPass(AID);
1030 // Print list of passes that are last used by P.
1031 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1033 SmallVector<Pass *, 12> LUses;
1035 // If this is a on the fly manager then it does not have TPM.
1039 TPM->collectLastUses(LUses, P);
1041 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1042 E = LUses.end(); I != E; ++I) {
1043 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1044 (*I)->dumpPassStructure(0);
1048 void PMDataManager::dumpPassArguments() const {
1049 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1050 E = PassVector.end(); I != E; ++I) {
1051 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1052 PMD->dumpPassArguments();
1054 if (const PassInfo *PI = (*I)->getPassInfo())
1055 if (!PI->isAnalysisGroup())
1056 dbgs() << " -" << PI->getPassArgument();
1060 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1061 enum PassDebuggingString S2,
1063 if (PassDebugging < Executions)
1065 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1068 dbgs() << "Executing Pass '" << P->getPassName();
1070 case MODIFICATION_MSG:
1071 dbgs() << "Made Modification '" << P->getPassName();
1074 dbgs() << " Freeing Pass '" << P->getPassName();
1080 case ON_BASICBLOCK_MSG:
1081 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1083 case ON_FUNCTION_MSG:
1084 dbgs() << "' on Function '" << Msg << "'...\n";
1087 dbgs() << "' on Module '" << Msg << "'...\n";
1090 dbgs() << "' on Loop '" << Msg << "'...\n";
1093 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1100 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1101 if (PassDebugging < Details)
1104 AnalysisUsage analysisUsage;
1105 P->getAnalysisUsage(analysisUsage);
1106 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1109 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1110 if (PassDebugging < Details)
1113 AnalysisUsage analysisUsage;
1114 P->getAnalysisUsage(analysisUsage);
1115 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1118 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1119 const AnalysisUsage::VectorType &Set) const {
1120 assert(PassDebugging >= Details);
1123 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1124 for (unsigned i = 0; i != Set.size(); ++i) {
1125 if (i) dbgs() << ',';
1126 dbgs() << ' ' << Set[i]->getPassName();
1131 /// Add RequiredPass into list of lower level passes required by pass P.
1132 /// RequiredPass is run on the fly by Pass Manager when P requests it
1133 /// through getAnalysis interface.
1134 /// This should be handled by specific pass manager.
1135 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1137 TPM->dumpArguments();
1141 // Module Level pass may required Function Level analysis info
1142 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1143 // to provide this on demand. In that case, in Pass manager terminology,
1144 // module level pass is requiring lower level analysis info managed by
1145 // lower level pass manager.
1147 // When Pass manager is not able to order required analysis info, Pass manager
1148 // checks whether any lower level manager will be able to provide this
1149 // analysis info on demand or not.
1151 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1152 dbgs() << "' required by '" << P->getPassName() << "'\n";
1154 llvm_unreachable("Unable to schedule pass");
1157 Pass *PMDataManager::getOnTheFlyPass(Pass *P, const PassInfo *PI, Function &F) {
1158 assert(0 && "Unable to find on the fly pass");
1163 PMDataManager::~PMDataManager() {
1164 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1165 E = PassVector.end(); I != E; ++I)
1169 //===----------------------------------------------------------------------===//
1170 // NOTE: Is this the right place to define this method ?
1171 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1172 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1173 return PM.findAnalysisPass(ID, dir);
1176 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1178 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1181 //===----------------------------------------------------------------------===//
1182 // BBPassManager implementation
1184 /// Execute all of the passes scheduled for execution by invoking
1185 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1186 /// the function, and if so, return true.
1187 bool BBPassManager::runOnFunction(Function &F) {
1188 if (F.isDeclaration())
1191 bool Changed = doInitialization(F);
1193 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1194 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1195 BasicBlockPass *BP = getContainedPass(Index);
1196 bool LocalChanged = false;
1198 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1199 dumpRequiredSet(BP);
1201 initializeAnalysisImpl(BP);
1204 // If the pass crashes, remember this.
1205 PassManagerPrettyStackEntry X(BP, *I);
1206 TimeRegion PassTimer(getPassTimer(BP));
1208 LocalChanged |= BP->runOnBasicBlock(*I);
1211 Changed |= LocalChanged;
1213 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1215 dumpPreservedSet(BP);
1217 verifyPreservedAnalysis(BP);
1218 removeNotPreservedAnalysis(BP);
1219 recordAvailableAnalysis(BP);
1220 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1223 return doFinalization(F) || Changed;
1226 // Implement doInitialization and doFinalization
1227 bool BBPassManager::doInitialization(Module &M) {
1228 bool Changed = false;
1230 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1231 Changed |= getContainedPass(Index)->doInitialization(M);
1236 bool BBPassManager::doFinalization(Module &M) {
1237 bool Changed = false;
1239 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1240 Changed |= getContainedPass(Index)->doFinalization(M);
1245 bool BBPassManager::doInitialization(Function &F) {
1246 bool Changed = false;
1248 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1249 BasicBlockPass *BP = getContainedPass(Index);
1250 Changed |= BP->doInitialization(F);
1256 bool BBPassManager::doFinalization(Function &F) {
1257 bool Changed = false;
1259 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1260 BasicBlockPass *BP = getContainedPass(Index);
1261 Changed |= BP->doFinalization(F);
1268 //===----------------------------------------------------------------------===//
1269 // FunctionPassManager implementation
1271 /// Create new Function pass manager
1272 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1273 FPM = new FunctionPassManagerImpl(0);
1274 // FPM is the top level manager.
1275 FPM->setTopLevelManager(FPM);
1277 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1278 FPM->setResolver(AR);
1281 FunctionPassManager::~FunctionPassManager() {
1285 /// addImpl - Add a pass to the queue of passes to run, without
1286 /// checking whether to add a printer pass.
1287 void FunctionPassManager::addImpl(Pass *P) {
1291 /// add - Add a pass to the queue of passes to run. This passes
1292 /// ownership of the Pass to the PassManager. When the
1293 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1294 /// there is no need to delete the pass. (TODO delete passes.)
1295 /// This implies that all passes MUST be allocated with 'new'.
1296 void FunctionPassManager::add(Pass *P) {
1297 // If this is a not a function pass, don't add a printer for it.
1298 if (P->getPassKind() == PT_Function)
1299 if (ShouldPrintBeforePass(P))
1300 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1301 + P->getPassName() + " ***"));
1305 if (P->getPassKind() == PT_Function)
1306 if (ShouldPrintAfterPass(P))
1307 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1308 + P->getPassName() + " ***"));
1311 /// run - Execute all of the passes scheduled for execution. Keep
1312 /// track of whether any of the passes modifies the function, and if
1313 /// so, return true.
1315 bool FunctionPassManager::run(Function &F) {
1316 if (F.isMaterializable()) {
1318 if (F.Materialize(&errstr))
1319 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1325 /// doInitialization - Run all of the initializers for the function passes.
1327 bool FunctionPassManager::doInitialization() {
1328 return FPM->doInitialization(*M);
1331 /// doFinalization - Run all of the finalizers for the function passes.
1333 bool FunctionPassManager::doFinalization() {
1334 return FPM->doFinalization(*M);
1337 //===----------------------------------------------------------------------===//
1338 // FunctionPassManagerImpl implementation
1340 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1341 bool Changed = false;
1346 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1347 Changed |= getContainedManager(Index)->doInitialization(M);
1352 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1353 bool Changed = false;
1355 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1356 Changed |= getContainedManager(Index)->doFinalization(M);
1361 /// cleanup - After running all passes, clean up pass manager cache.
1362 void FPPassManager::cleanup() {
1363 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1364 FunctionPass *FP = getContainedPass(Index);
1365 AnalysisResolver *AR = FP->getResolver();
1366 assert(AR && "Analysis Resolver is not set");
1367 AR->clearAnalysisImpls();
1371 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1374 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1375 FPPassManager *FPPM = getContainedManager(Index);
1376 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1377 FPPM->getContainedPass(Index)->releaseMemory();
1383 // Execute all the passes managed by this top level manager.
1384 // Return true if any function is modified by a pass.
1385 bool FunctionPassManagerImpl::run(Function &F) {
1386 bool Changed = false;
1387 TimingInfo::createTheTimeInfo();
1389 initializeAllAnalysisInfo();
1390 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1391 Changed |= getContainedManager(Index)->runOnFunction(F);
1393 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1394 getContainedManager(Index)->cleanup();
1400 //===----------------------------------------------------------------------===//
1401 // FPPassManager implementation
1403 char FPPassManager::ID = 0;
1404 /// Print passes managed by this manager
1405 void FPPassManager::dumpPassStructure(unsigned Offset) {
1406 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1407 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1408 FunctionPass *FP = getContainedPass(Index);
1409 FP->dumpPassStructure(Offset + 1);
1410 dumpLastUses(FP, Offset+1);
1415 /// Execute all of the passes scheduled for execution by invoking
1416 /// runOnFunction method. Keep track of whether any of the passes modifies
1417 /// the function, and if so, return true.
1418 bool FPPassManager::runOnFunction(Function &F) {
1419 if (F.isDeclaration())
1422 bool Changed = false;
1424 // Collect inherited analysis from Module level pass manager.
1425 populateInheritedAnalysis(TPM->activeStack);
1427 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1428 FunctionPass *FP = getContainedPass(Index);
1429 bool LocalChanged = false;
1431 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1432 dumpRequiredSet(FP);
1434 initializeAnalysisImpl(FP);
1437 PassManagerPrettyStackEntry X(FP, F);
1438 TimeRegion PassTimer(getPassTimer(FP));
1440 LocalChanged |= FP->runOnFunction(F);
1443 Changed |= LocalChanged;
1445 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1446 dumpPreservedSet(FP);
1448 verifyPreservedAnalysis(FP);
1449 removeNotPreservedAnalysis(FP);
1450 recordAvailableAnalysis(FP);
1451 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1456 bool FPPassManager::runOnModule(Module &M) {
1457 bool Changed = doInitialization(M);
1459 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1462 return doFinalization(M) || Changed;
1465 bool FPPassManager::doInitialization(Module &M) {
1466 bool Changed = false;
1468 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1469 Changed |= getContainedPass(Index)->doInitialization(M);
1474 bool FPPassManager::doFinalization(Module &M) {
1475 bool Changed = false;
1477 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1478 Changed |= getContainedPass(Index)->doFinalization(M);
1483 //===----------------------------------------------------------------------===//
1484 // MPPassManager implementation
1486 /// Execute all of the passes scheduled for execution by invoking
1487 /// runOnModule method. Keep track of whether any of the passes modifies
1488 /// the module, and if so, return true.
1490 MPPassManager::runOnModule(Module &M) {
1491 bool Changed = false;
1493 // Initialize on-the-fly passes
1494 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1495 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1497 FunctionPassManagerImpl *FPP = I->second;
1498 Changed |= FPP->doInitialization(M);
1501 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1502 ModulePass *MP = getContainedPass(Index);
1503 bool LocalChanged = false;
1505 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1506 dumpRequiredSet(MP);
1508 initializeAnalysisImpl(MP);
1511 PassManagerPrettyStackEntry X(MP, M);
1512 TimeRegion PassTimer(getPassTimer(MP));
1514 LocalChanged |= MP->runOnModule(M);
1517 Changed |= LocalChanged;
1519 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1520 M.getModuleIdentifier());
1521 dumpPreservedSet(MP);
1523 verifyPreservedAnalysis(MP);
1524 removeNotPreservedAnalysis(MP);
1525 recordAvailableAnalysis(MP);
1526 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1529 // Finalize on-the-fly passes
1530 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1531 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1533 FunctionPassManagerImpl *FPP = I->second;
1534 // We don't know when is the last time an on-the-fly pass is run,
1535 // so we need to releaseMemory / finalize here
1536 FPP->releaseMemoryOnTheFly();
1537 Changed |= FPP->doFinalization(M);
1542 /// Add RequiredPass into list of lower level passes required by pass P.
1543 /// RequiredPass is run on the fly by Pass Manager when P requests it
1544 /// through getAnalysis interface.
1545 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1546 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1547 "Unable to handle Pass that requires lower level Analysis pass");
1548 assert((P->getPotentialPassManagerType() <
1549 RequiredPass->getPotentialPassManagerType()) &&
1550 "Unable to handle Pass that requires lower level Analysis pass");
1552 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1554 FPP = new FunctionPassManagerImpl(0);
1555 // FPP is the top level manager.
1556 FPP->setTopLevelManager(FPP);
1558 OnTheFlyManagers[P] = FPP;
1560 FPP->add(RequiredPass);
1562 // Register P as the last user of RequiredPass.
1563 SmallVector<Pass *, 12> LU;
1564 LU.push_back(RequiredPass);
1565 FPP->setLastUser(LU, P);
1568 /// Return function pass corresponding to PassInfo PI, that is
1569 /// required by module pass MP. Instantiate analysis pass, by using
1570 /// its runOnFunction() for function F.
1571 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1572 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1573 assert(FPP && "Unable to find on the fly pass");
1575 FPP->releaseMemoryOnTheFly();
1577 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1581 //===----------------------------------------------------------------------===//
1582 // PassManagerImpl implementation
1584 /// run - Execute all of the passes scheduled for execution. Keep track of
1585 /// whether any of the passes modifies the module, and if so, return true.
1586 bool PassManagerImpl::run(Module &M) {
1587 bool Changed = false;
1588 TimingInfo::createTheTimeInfo();
1593 initializeAllAnalysisInfo();
1594 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1595 Changed |= getContainedManager(Index)->runOnModule(M);
1599 //===----------------------------------------------------------------------===//
1600 // PassManager implementation
1602 /// Create new pass manager
1603 PassManager::PassManager() {
1604 PM = new PassManagerImpl(0);
1605 // PM is the top level manager
1606 PM->setTopLevelManager(PM);
1609 PassManager::~PassManager() {
1613 /// addImpl - Add a pass to the queue of passes to run, without
1614 /// checking whether to add a printer pass.
1615 void PassManager::addImpl(Pass *P) {
1619 /// add - Add a pass to the queue of passes to run. This passes ownership of
1620 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1621 /// will be destroyed as well, so there is no need to delete the pass. This
1622 /// implies that all passes MUST be allocated with 'new'.
1623 void PassManager::add(Pass *P) {
1624 if (ShouldPrintBeforePass(P))
1625 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1626 + P->getPassName() + " ***"));
1630 if (ShouldPrintAfterPass(P))
1631 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1632 + P->getPassName() + " ***"));
1635 /// run - Execute all of the passes scheduled for execution. Keep track of
1636 /// whether any of the passes modifies the module, and if so, return true.
1637 bool PassManager::run(Module &M) {
1641 //===----------------------------------------------------------------------===//
1642 // TimingInfo Class - This class is used to calculate information about the
1643 // amount of time each pass takes to execute. This only happens with
1644 // -time-passes is enabled on the command line.
1646 bool llvm::TimePassesIsEnabled = false;
1647 static cl::opt<bool,true>
1648 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1649 cl::desc("Time each pass, printing elapsed time for each on exit"));
1651 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1652 // a non null value (if the -time-passes option is enabled) or it leaves it
1653 // null. It may be called multiple times.
1654 void TimingInfo::createTheTimeInfo() {
1655 if (!TimePassesIsEnabled || TheTimeInfo) return;
1657 // Constructed the first time this is called, iff -time-passes is enabled.
1658 // This guarantees that the object will be constructed before static globals,
1659 // thus it will be destroyed before them.
1660 static ManagedStatic<TimingInfo> TTI;
1661 TheTimeInfo = &*TTI;
1664 /// If TimingInfo is enabled then start pass timer.
1665 Timer *llvm::getPassTimer(Pass *P) {
1667 return TheTimeInfo->getPassTimer(P);
1671 //===----------------------------------------------------------------------===//
1672 // PMStack implementation
1675 // Pop Pass Manager from the stack and clear its analysis info.
1676 void PMStack::pop() {
1678 PMDataManager *Top = this->top();
1679 Top->initializeAnalysisInfo();
1684 // Push PM on the stack and set its top level manager.
1685 void PMStack::push(PMDataManager *PM) {
1686 assert(PM && "Unable to push. Pass Manager expected");
1688 if (!this->empty()) {
1689 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1691 assert(TPM && "Unable to find top level manager");
1692 TPM->addIndirectPassManager(PM);
1693 PM->setTopLevelManager(TPM);
1699 // Dump content of the pass manager stack.
1700 void PMStack::dump() {
1701 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1702 E = S.end(); I != E; ++I)
1703 printf("%s ", (*I)->getAsPass()->getPassName());
1709 /// Find appropriate Module Pass Manager in the PM Stack and
1710 /// add self into that manager.
1711 void ModulePass::assignPassManager(PMStack &PMS,
1712 PassManagerType PreferredType) {
1713 // Find Module Pass Manager
1714 while(!PMS.empty()) {
1715 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1716 if (TopPMType == PreferredType)
1717 break; // We found desired pass manager
1718 else if (TopPMType > PMT_ModulePassManager)
1719 PMS.pop(); // Pop children pass managers
1723 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1724 PMS.top()->add(this);
1727 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1728 /// in the PM Stack and add self into that manager.
1729 void FunctionPass::assignPassManager(PMStack &PMS,
1730 PassManagerType PreferredType) {
1732 // Find Module Pass Manager
1733 while (!PMS.empty()) {
1734 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1740 // Create new Function Pass Manager if needed.
1742 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1743 FPP = (FPPassManager *)PMS.top();
1745 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1746 PMDataManager *PMD = PMS.top();
1748 // [1] Create new Function Pass Manager
1749 FPP = new FPPassManager(PMD->getDepth() + 1);
1750 FPP->populateInheritedAnalysis(PMS);
1752 // [2] Set up new manager's top level manager
1753 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1754 TPM->addIndirectPassManager(FPP);
1756 // [3] Assign manager to manage this new manager. This may create
1757 // and push new managers into PMS
1758 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1760 // [4] Push new manager into PMS
1764 // Assign FPP as the manager of this pass.
1768 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1769 /// in the PM Stack and add self into that manager.
1770 void BasicBlockPass::assignPassManager(PMStack &PMS,
1771 PassManagerType PreferredType) {
1774 // Basic Pass Manager is a leaf pass manager. It does not handle
1775 // any other pass manager.
1777 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1778 BBP = (BBPassManager *)PMS.top();
1780 // If leaf manager is not Basic Block Pass manager then create new
1781 // basic Block Pass manager.
1782 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1783 PMDataManager *PMD = PMS.top();
1785 // [1] Create new Basic Block Manager
1786 BBP = new BBPassManager(PMD->getDepth() + 1);
1788 // [2] Set up new manager's top level manager
1789 // Basic Block Pass Manager does not live by itself
1790 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1791 TPM->addIndirectPassManager(BBP);
1793 // [3] Assign manager to manage this new manager. This may create
1794 // and push new managers into PMS
1795 BBP->assignPassManager(PMS, PreferredType);
1797 // [4] Push new manager into PMS
1801 // Assign BBP as the manager of this pass.
1805 PassManagerBase::~PassManagerBase() {}
1807 /*===-- C Bindings --------------------------------------------------------===*/
1809 LLVMPassManagerRef LLVMCreatePassManager() {
1810 return wrap(new PassManager());
1813 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1814 return wrap(new FunctionPassManager(unwrap(M)));
1817 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1818 return LLVMCreateFunctionPassManagerForModule(
1819 reinterpret_cast<LLVMModuleRef>(P));
1822 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1823 return unwrap<PassManager>(PM)->run(*unwrap(M));
1826 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1827 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1830 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1831 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1834 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1835 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1838 void LLVMDisposePassManager(LLVMPassManagerRef PM) {