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);
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);
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 std::vector<const PassInfo*> &ImmPI =
642 PI->getInterfacesImplemented();
643 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
651 // Print passes managed by this top level manager.
652 void PMTopLevelManager::dumpPasses() const {
654 if (PassDebugging < Structure)
657 // Print out the immutable passes
658 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
659 ImmutablePasses[i]->dumpPassStructure(0);
662 // Every class that derives from PMDataManager also derives from Pass
663 // (sometimes indirectly), but there's no inheritance relationship
664 // between PMDataManager and Pass, so we have to getAsPass to get
665 // from a PMDataManager* to a Pass*.
666 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
667 E = PassManagers.end(); I != E; ++I)
668 (*I)->getAsPass()->dumpPassStructure(1);
671 void PMTopLevelManager::dumpArguments() const {
673 if (PassDebugging < Arguments)
676 dbgs() << "Pass Arguments: ";
677 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
678 E = PassManagers.end(); I != E; ++I)
679 (*I)->dumpPassArguments();
683 void PMTopLevelManager::initializeAllAnalysisInfo() {
684 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
685 E = PassManagers.end(); I != E; ++I)
686 (*I)->initializeAnalysisInfo();
688 // Initailize other pass managers
689 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
690 E = IndirectPassManagers.end(); I != E; ++I)
691 (*I)->initializeAnalysisInfo();
693 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
694 DME = LastUser.end(); DMI != DME; ++DMI) {
695 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
696 InversedLastUser.find(DMI->second);
697 if (InvDMI != InversedLastUser.end()) {
698 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
699 L.insert(DMI->first);
701 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
702 InversedLastUser[DMI->second] = L;
708 PMTopLevelManager::~PMTopLevelManager() {
709 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
710 E = PassManagers.end(); I != E; ++I)
713 for (SmallVector<ImmutablePass *, 8>::iterator
714 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
717 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
718 DME = AnUsageMap.end(); DMI != DME; ++DMI)
722 //===----------------------------------------------------------------------===//
723 // PMDataManager implementation
725 /// Augement AvailableAnalysis by adding analysis made available by pass P.
726 void PMDataManager::recordAvailableAnalysis(Pass *P) {
727 const PassInfo *PI = P->getPassInfo();
730 AvailableAnalysis[PI] = P;
732 //This pass is the current implementation of all of the interfaces it
733 //implements as well.
734 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
735 for (unsigned i = 0, e = II.size(); i != e; ++i)
736 AvailableAnalysis[II[i]] = P;
739 // Return true if P preserves high level analysis used by other
740 // passes managed by this manager
741 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
742 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
743 if (AnUsage->getPreservesAll())
746 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
747 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
748 E = HigherLevelAnalysis.end(); I != E; ++I) {
750 if (P1->getAsImmutablePass() == 0 &&
751 std::find(PreservedSet.begin(), PreservedSet.end(),
752 P1->getPassInfo()) ==
760 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
761 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
762 // Don't do this unless assertions are enabled.
766 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
767 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
769 // Verify preserved analysis
770 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
771 E = PreservedSet.end(); I != E; ++I) {
773 if (Pass *AP = findAnalysisPass(AID, true)) {
774 TimeRegion PassTimer(getPassTimer(AP));
775 AP->verifyAnalysis();
780 /// Remove Analysis not preserved by Pass P
781 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
782 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
783 if (AnUsage->getPreservesAll())
786 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
787 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
788 E = AvailableAnalysis.end(); I != E; ) {
789 std::map<AnalysisID, Pass*>::iterator Info = I++;
790 if (Info->second->getAsImmutablePass() == 0 &&
791 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
792 PreservedSet.end()) {
793 // Remove this analysis
794 if (PassDebugging >= Details) {
795 Pass *S = Info->second;
796 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
797 dbgs() << S->getPassName() << "'\n";
799 AvailableAnalysis.erase(Info);
803 // Check inherited analysis also. If P is not preserving analysis
804 // provided by parent manager then remove it here.
805 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
807 if (!InheritedAnalysis[Index])
810 for (std::map<AnalysisID, Pass*>::iterator
811 I = InheritedAnalysis[Index]->begin(),
812 E = InheritedAnalysis[Index]->end(); I != E; ) {
813 std::map<AnalysisID, Pass *>::iterator Info = I++;
814 if (Info->second->getAsImmutablePass() == 0 &&
815 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
816 PreservedSet.end()) {
817 // Remove this analysis
818 if (PassDebugging >= Details) {
819 Pass *S = Info->second;
820 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
821 dbgs() << S->getPassName() << "'\n";
823 InheritedAnalysis[Index]->erase(Info);
829 /// Remove analysis passes that are not used any longer
830 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
831 enum PassDebuggingString DBG_STR) {
833 SmallVector<Pass *, 12> DeadPasses;
835 // If this is a on the fly manager then it does not have TPM.
839 TPM->collectLastUses(DeadPasses, P);
841 if (PassDebugging >= Details && !DeadPasses.empty()) {
842 dbgs() << " -*- '" << P->getPassName();
843 dbgs() << "' is the last user of following pass instances.";
844 dbgs() << " Free these instances\n";
847 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
848 E = DeadPasses.end(); I != E; ++I)
849 freePass(*I, Msg, DBG_STR);
852 void PMDataManager::freePass(Pass *P, StringRef Msg,
853 enum PassDebuggingString DBG_STR) {
854 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
857 // If the pass crashes releasing memory, remember this.
858 PassManagerPrettyStackEntry X(P);
859 TimeRegion PassTimer(getPassTimer(P));
864 if (const PassInfo *PI = P->getPassInfo()) {
865 // Remove the pass itself (if it is not already removed).
866 AvailableAnalysis.erase(PI);
868 // Remove all interfaces this pass implements, for which it is also
869 // listed as the available implementation.
870 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
871 for (unsigned i = 0, e = II.size(); i != e; ++i) {
872 std::map<AnalysisID, Pass*>::iterator Pos =
873 AvailableAnalysis.find(II[i]);
874 if (Pos != AvailableAnalysis.end() && Pos->second == P)
875 AvailableAnalysis.erase(Pos);
880 /// Add pass P into the PassVector. Update
881 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
882 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
883 // This manager is going to manage pass P. Set up analysis resolver
885 AnalysisResolver *AR = new AnalysisResolver(*this);
888 // If a FunctionPass F is the last user of ModulePass info M
889 // then the F's manager, not F, records itself as a last user of M.
890 SmallVector<Pass *, 12> TransferLastUses;
892 if (!ProcessAnalysis) {
894 PassVector.push_back(P);
898 // At the moment, this pass is the last user of all required passes.
899 SmallVector<Pass *, 12> LastUses;
900 SmallVector<Pass *, 8> RequiredPasses;
901 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
903 unsigned PDepth = this->getDepth();
905 collectRequiredAnalysis(RequiredPasses,
906 ReqAnalysisNotAvailable, P);
907 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
908 E = RequiredPasses.end(); I != E; ++I) {
909 Pass *PRequired = *I;
912 assert(PRequired->getResolver() && "Analysis Resolver is not set");
913 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
914 RDepth = DM.getDepth();
916 if (PDepth == RDepth)
917 LastUses.push_back(PRequired);
918 else if (PDepth > RDepth) {
919 // Let the parent claim responsibility of last use
920 TransferLastUses.push_back(PRequired);
921 // Keep track of higher level analysis used by this manager.
922 HigherLevelAnalysis.push_back(PRequired);
924 llvm_unreachable("Unable to accomodate Required Pass");
927 // Set P as P's last user until someone starts using P.
928 // However, if P is a Pass Manager then it does not need
929 // to record its last user.
930 if (P->getAsPMDataManager() == 0)
931 LastUses.push_back(P);
932 TPM->setLastUser(LastUses, P);
934 if (!TransferLastUses.empty()) {
935 Pass *My_PM = getAsPass();
936 TPM->setLastUser(TransferLastUses, My_PM);
937 TransferLastUses.clear();
940 // Now, take care of required analysises that are not available.
941 for (SmallVector<AnalysisID, 8>::iterator
942 I = ReqAnalysisNotAvailable.begin(),
943 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
944 Pass *AnalysisPass = (*I)->createPass();
945 this->addLowerLevelRequiredPass(P, AnalysisPass);
948 // Take a note of analysis required and made available by this pass.
949 // Remove the analysis not preserved by this pass
950 removeNotPreservedAnalysis(P);
951 recordAvailableAnalysis(P);
954 PassVector.push_back(P);
958 /// Populate RP with analysis pass that are required by
959 /// pass P and are available. Populate RP_NotAvail with analysis
960 /// pass that are required by pass P but are not available.
961 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
962 SmallVector<AnalysisID, 8> &RP_NotAvail,
964 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
965 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
966 for (AnalysisUsage::VectorType::const_iterator
967 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
968 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
969 RP.push_back(AnalysisPass);
971 RP_NotAvail.push_back(*I);
974 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
975 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
976 E = IDs.end(); I != E; ++I) {
977 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
978 RP.push_back(AnalysisPass);
980 RP_NotAvail.push_back(*I);
984 // All Required analyses should be available to the pass as it runs! Here
985 // we fill in the AnalysisImpls member of the pass so that it can
986 // successfully use the getAnalysis() method to retrieve the
987 // implementations it needs.
989 void PMDataManager::initializeAnalysisImpl(Pass *P) {
990 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
992 for (AnalysisUsage::VectorType::const_iterator
993 I = AnUsage->getRequiredSet().begin(),
994 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
995 Pass *Impl = findAnalysisPass(*I, true);
997 // This may be analysis pass that is initialized on the fly.
998 // If that is not the case then it will raise an assert when it is used.
1000 AnalysisResolver *AR = P->getResolver();
1001 assert(AR && "Analysis Resolver is not set");
1002 AR->addAnalysisImplsPair(*I, Impl);
1006 /// Find the pass that implements Analysis AID. If desired pass is not found
1007 /// then return NULL.
1008 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1010 // Check if AvailableAnalysis map has one entry.
1011 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1013 if (I != AvailableAnalysis.end())
1016 // Search Parents through TopLevelManager
1018 return TPM->findAnalysisPass(AID);
1023 // Print list of passes that are last used by P.
1024 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1026 SmallVector<Pass *, 12> LUses;
1028 // If this is a on the fly manager then it does not have TPM.
1032 TPM->collectLastUses(LUses, P);
1034 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1035 E = LUses.end(); I != E; ++I) {
1036 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1037 (*I)->dumpPassStructure(0);
1041 void PMDataManager::dumpPassArguments() const {
1042 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1043 E = PassVector.end(); I != E; ++I) {
1044 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1045 PMD->dumpPassArguments();
1047 if (const PassInfo *PI = (*I)->getPassInfo())
1048 if (!PI->isAnalysisGroup())
1049 dbgs() << " -" << PI->getPassArgument();
1053 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1054 enum PassDebuggingString S2,
1056 if (PassDebugging < Executions)
1058 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1061 dbgs() << "Executing Pass '" << P->getPassName();
1063 case MODIFICATION_MSG:
1064 dbgs() << "Made Modification '" << P->getPassName();
1067 dbgs() << " Freeing Pass '" << P->getPassName();
1073 case ON_BASICBLOCK_MSG:
1074 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1076 case ON_FUNCTION_MSG:
1077 dbgs() << "' on Function '" << Msg << "'...\n";
1080 dbgs() << "' on Module '" << Msg << "'...\n";
1083 dbgs() << "' on Loop '" << Msg << "'...\n";
1086 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1093 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1094 if (PassDebugging < Details)
1097 AnalysisUsage analysisUsage;
1098 P->getAnalysisUsage(analysisUsage);
1099 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1102 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1103 if (PassDebugging < Details)
1106 AnalysisUsage analysisUsage;
1107 P->getAnalysisUsage(analysisUsage);
1108 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1111 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1112 const AnalysisUsage::VectorType &Set) const {
1113 assert(PassDebugging >= Details);
1116 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1117 for (unsigned i = 0; i != Set.size(); ++i) {
1118 if (i) dbgs() << ',';
1119 dbgs() << ' ' << Set[i]->getPassName();
1124 /// Add RequiredPass into list of lower level passes required by pass P.
1125 /// RequiredPass is run on the fly by Pass Manager when P requests it
1126 /// through getAnalysis interface.
1127 /// This should be handled by specific pass manager.
1128 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1130 TPM->dumpArguments();
1134 // Module Level pass may required Function Level analysis info
1135 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1136 // to provide this on demand. In that case, in Pass manager terminology,
1137 // module level pass is requiring lower level analysis info managed by
1138 // lower level pass manager.
1140 // When Pass manager is not able to order required analysis info, Pass manager
1141 // checks whether any lower level manager will be able to provide this
1142 // analysis info on demand or not.
1144 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1145 dbgs() << "' required by '" << P->getPassName() << "'\n";
1147 llvm_unreachable("Unable to schedule pass");
1151 PMDataManager::~PMDataManager() {
1152 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1153 E = PassVector.end(); I != E; ++I)
1157 //===----------------------------------------------------------------------===//
1158 // NOTE: Is this the right place to define this method ?
1159 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1160 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1161 return PM.findAnalysisPass(ID, dir);
1164 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1166 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1169 //===----------------------------------------------------------------------===//
1170 // BBPassManager implementation
1172 /// Execute all of the passes scheduled for execution by invoking
1173 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1174 /// the function, and if so, return true.
1175 bool BBPassManager::runOnFunction(Function &F) {
1176 if (F.isDeclaration())
1179 bool Changed = doInitialization(F);
1181 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1182 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1183 BasicBlockPass *BP = getContainedPass(Index);
1184 bool LocalChanged = false;
1186 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1187 dumpRequiredSet(BP);
1189 initializeAnalysisImpl(BP);
1192 // If the pass crashes, remember this.
1193 PassManagerPrettyStackEntry X(BP, *I);
1194 TimeRegion PassTimer(getPassTimer(BP));
1196 LocalChanged |= BP->runOnBasicBlock(*I);
1199 Changed |= LocalChanged;
1201 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1203 dumpPreservedSet(BP);
1205 verifyPreservedAnalysis(BP);
1206 removeNotPreservedAnalysis(BP);
1207 recordAvailableAnalysis(BP);
1208 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1211 return doFinalization(F) || Changed;
1214 // Implement doInitialization and doFinalization
1215 bool BBPassManager::doInitialization(Module &M) {
1216 bool Changed = false;
1218 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1219 Changed |= getContainedPass(Index)->doInitialization(M);
1224 bool BBPassManager::doFinalization(Module &M) {
1225 bool Changed = false;
1227 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1228 Changed |= getContainedPass(Index)->doFinalization(M);
1233 bool BBPassManager::doInitialization(Function &F) {
1234 bool Changed = false;
1236 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1237 BasicBlockPass *BP = getContainedPass(Index);
1238 Changed |= BP->doInitialization(F);
1244 bool BBPassManager::doFinalization(Function &F) {
1245 bool Changed = false;
1247 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1248 BasicBlockPass *BP = getContainedPass(Index);
1249 Changed |= BP->doFinalization(F);
1256 //===----------------------------------------------------------------------===//
1257 // FunctionPassManager implementation
1259 /// Create new Function pass manager
1260 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1261 FPM = new FunctionPassManagerImpl(0);
1262 // FPM is the top level manager.
1263 FPM->setTopLevelManager(FPM);
1265 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1266 FPM->setResolver(AR);
1269 FunctionPassManager::~FunctionPassManager() {
1273 /// add - Add a pass to the queue of passes to run. This passes
1274 /// ownership of the Pass to the PassManager. When the
1275 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1276 /// there is no need to delete the pass. (TODO delete passes.)
1277 /// This implies that all passes MUST be allocated with 'new'.
1278 void FunctionPassManager::add(Pass *P) {
1279 if (ShouldPrintBeforePass(P))
1280 add(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1281 + P->getPassName() + " ***"));
1284 if (ShouldPrintAfterPass(P))
1285 add(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1286 + P->getPassName() + " ***"));
1289 /// run - Execute all of the passes scheduled for execution. Keep
1290 /// track of whether any of the passes modifies the function, and if
1291 /// so, return true.
1293 bool FunctionPassManager::run(Function &F) {
1294 if (F.isMaterializable()) {
1296 if (F.Materialize(&errstr)) {
1297 llvm_report_error("Error reading bitcode file: " + errstr);
1304 /// doInitialization - Run all of the initializers for the function passes.
1306 bool FunctionPassManager::doInitialization() {
1307 return FPM->doInitialization(*M);
1310 /// doFinalization - Run all of the finalizers for the function passes.
1312 bool FunctionPassManager::doFinalization() {
1313 return FPM->doFinalization(*M);
1316 //===----------------------------------------------------------------------===//
1317 // FunctionPassManagerImpl implementation
1319 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1320 bool Changed = false;
1325 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1326 Changed |= getContainedManager(Index)->doInitialization(M);
1331 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1332 bool Changed = false;
1334 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1335 Changed |= getContainedManager(Index)->doFinalization(M);
1340 /// cleanup - After running all passes, clean up pass manager cache.
1341 void FPPassManager::cleanup() {
1342 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1343 FunctionPass *FP = getContainedPass(Index);
1344 AnalysisResolver *AR = FP->getResolver();
1345 assert(AR && "Analysis Resolver is not set");
1346 AR->clearAnalysisImpls();
1350 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1353 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1354 FPPassManager *FPPM = getContainedManager(Index);
1355 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1356 FPPM->getContainedPass(Index)->releaseMemory();
1362 // Execute all the passes managed by this top level manager.
1363 // Return true if any function is modified by a pass.
1364 bool FunctionPassManagerImpl::run(Function &F) {
1365 bool Changed = false;
1366 TimingInfo::createTheTimeInfo();
1368 initializeAllAnalysisInfo();
1369 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1370 Changed |= getContainedManager(Index)->runOnFunction(F);
1372 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1373 getContainedManager(Index)->cleanup();
1379 //===----------------------------------------------------------------------===//
1380 // FPPassManager implementation
1382 char FPPassManager::ID = 0;
1383 /// Print passes managed by this manager
1384 void FPPassManager::dumpPassStructure(unsigned Offset) {
1385 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1386 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1387 FunctionPass *FP = getContainedPass(Index);
1388 FP->dumpPassStructure(Offset + 1);
1389 dumpLastUses(FP, Offset+1);
1394 /// Execute all of the passes scheduled for execution by invoking
1395 /// runOnFunction method. Keep track of whether any of the passes modifies
1396 /// the function, and if so, return true.
1397 bool FPPassManager::runOnFunction(Function &F) {
1398 if (F.isDeclaration())
1401 bool Changed = false;
1403 // Collect inherited analysis from Module level pass manager.
1404 populateInheritedAnalysis(TPM->activeStack);
1406 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1407 FunctionPass *FP = getContainedPass(Index);
1408 bool LocalChanged = false;
1410 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1411 dumpRequiredSet(FP);
1413 initializeAnalysisImpl(FP);
1416 PassManagerPrettyStackEntry X(FP, F);
1417 TimeRegion PassTimer(getPassTimer(FP));
1419 LocalChanged |= FP->runOnFunction(F);
1422 Changed |= LocalChanged;
1424 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1425 dumpPreservedSet(FP);
1427 verifyPreservedAnalysis(FP);
1428 removeNotPreservedAnalysis(FP);
1429 recordAvailableAnalysis(FP);
1430 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1435 bool FPPassManager::runOnModule(Module &M) {
1436 bool Changed = doInitialization(M);
1438 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1441 return doFinalization(M) || Changed;
1444 bool FPPassManager::doInitialization(Module &M) {
1445 bool Changed = false;
1447 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1448 Changed |= getContainedPass(Index)->doInitialization(M);
1453 bool FPPassManager::doFinalization(Module &M) {
1454 bool Changed = false;
1456 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1457 Changed |= getContainedPass(Index)->doFinalization(M);
1462 //===----------------------------------------------------------------------===//
1463 // MPPassManager implementation
1465 /// Execute all of the passes scheduled for execution by invoking
1466 /// runOnModule method. Keep track of whether any of the passes modifies
1467 /// the module, and if so, return true.
1469 MPPassManager::runOnModule(Module &M) {
1470 bool Changed = false;
1472 // Initialize on-the-fly passes
1473 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1474 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1476 FunctionPassManagerImpl *FPP = I->second;
1477 Changed |= FPP->doInitialization(M);
1480 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1481 ModulePass *MP = getContainedPass(Index);
1482 bool LocalChanged = false;
1484 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1485 dumpRequiredSet(MP);
1487 initializeAnalysisImpl(MP);
1490 PassManagerPrettyStackEntry X(MP, M);
1491 TimeRegion PassTimer(getPassTimer(MP));
1493 LocalChanged |= MP->runOnModule(M);
1496 Changed |= LocalChanged;
1498 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1499 M.getModuleIdentifier());
1500 dumpPreservedSet(MP);
1502 verifyPreservedAnalysis(MP);
1503 removeNotPreservedAnalysis(MP);
1504 recordAvailableAnalysis(MP);
1505 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1508 // Finalize on-the-fly passes
1509 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1510 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1512 FunctionPassManagerImpl *FPP = I->second;
1513 // We don't know when is the last time an on-the-fly pass is run,
1514 // so we need to releaseMemory / finalize here
1515 FPP->releaseMemoryOnTheFly();
1516 Changed |= FPP->doFinalization(M);
1521 /// Add RequiredPass into list of lower level passes required by pass P.
1522 /// RequiredPass is run on the fly by Pass Manager when P requests it
1523 /// through getAnalysis interface.
1524 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1525 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1526 "Unable to handle Pass that requires lower level Analysis pass");
1527 assert((P->getPotentialPassManagerType() <
1528 RequiredPass->getPotentialPassManagerType()) &&
1529 "Unable to handle Pass that requires lower level Analysis pass");
1531 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1533 FPP = new FunctionPassManagerImpl(0);
1534 // FPP is the top level manager.
1535 FPP->setTopLevelManager(FPP);
1537 OnTheFlyManagers[P] = FPP;
1539 FPP->add(RequiredPass);
1541 // Register P as the last user of RequiredPass.
1542 SmallVector<Pass *, 12> LU;
1543 LU.push_back(RequiredPass);
1544 FPP->setLastUser(LU, P);
1547 /// Return function pass corresponding to PassInfo PI, that is
1548 /// required by module pass MP. Instantiate analysis pass, by using
1549 /// its runOnFunction() for function F.
1550 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1551 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1552 assert(FPP && "Unable to find on the fly pass");
1554 FPP->releaseMemoryOnTheFly();
1556 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1560 //===----------------------------------------------------------------------===//
1561 // PassManagerImpl implementation
1563 /// run - Execute all of the passes scheduled for execution. Keep track of
1564 /// whether any of the passes modifies the module, and if so, return true.
1565 bool PassManagerImpl::run(Module &M) {
1566 bool Changed = false;
1567 TimingInfo::createTheTimeInfo();
1572 initializeAllAnalysisInfo();
1573 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1574 Changed |= getContainedManager(Index)->runOnModule(M);
1578 //===----------------------------------------------------------------------===//
1579 // PassManager implementation
1581 /// Create new pass manager
1582 PassManager::PassManager() {
1583 PM = new PassManagerImpl(0);
1584 // PM is the top level manager
1585 PM->setTopLevelManager(PM);
1588 PassManager::~PassManager() {
1592 /// add - Add a pass to the queue of passes to run. This passes ownership of
1593 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1594 /// will be destroyed as well, so there is no need to delete the pass. This
1595 /// implies that all passes MUST be allocated with 'new'.
1596 void PassManager::add(Pass *P) {
1597 if (ShouldPrintBeforePass(P))
1598 add(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1599 + P->getPassName() + " ***"));
1603 if (ShouldPrintAfterPass(P))
1604 add(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1605 + P->getPassName() + " ***"));
1608 /// run - Execute all of the passes scheduled for execution. Keep track of
1609 /// whether any of the passes modifies the module, and if so, return true.
1610 bool PassManager::run(Module &M) {
1614 //===----------------------------------------------------------------------===//
1615 // TimingInfo Class - This class is used to calculate information about the
1616 // amount of time each pass takes to execute. This only happens with
1617 // -time-passes is enabled on the command line.
1619 bool llvm::TimePassesIsEnabled = false;
1620 static cl::opt<bool,true>
1621 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1622 cl::desc("Time each pass, printing elapsed time for each on exit"));
1624 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1625 // a non null value (if the -time-passes option is enabled) or it leaves it
1626 // null. It may be called multiple times.
1627 void TimingInfo::createTheTimeInfo() {
1628 if (!TimePassesIsEnabled || TheTimeInfo) return;
1630 // Constructed the first time this is called, iff -time-passes is enabled.
1631 // This guarantees that the object will be constructed before static globals,
1632 // thus it will be destroyed before them.
1633 static ManagedStatic<TimingInfo> TTI;
1634 TheTimeInfo = &*TTI;
1637 /// If TimingInfo is enabled then start pass timer.
1638 Timer *llvm::getPassTimer(Pass *P) {
1640 return TheTimeInfo->getPassTimer(P);
1644 //===----------------------------------------------------------------------===//
1645 // PMStack implementation
1648 // Pop Pass Manager from the stack and clear its analysis info.
1649 void PMStack::pop() {
1651 PMDataManager *Top = this->top();
1652 Top->initializeAnalysisInfo();
1657 // Push PM on the stack and set its top level manager.
1658 void PMStack::push(PMDataManager *PM) {
1659 assert(PM && "Unable to push. Pass Manager expected");
1661 if (!this->empty()) {
1662 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1664 assert(TPM && "Unable to find top level manager");
1665 TPM->addIndirectPassManager(PM);
1666 PM->setTopLevelManager(TPM);
1672 // Dump content of the pass manager stack.
1673 void PMStack::dump() {
1674 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1675 E = S.end(); I != E; ++I)
1676 printf("%s ", (*I)->getAsPass()->getPassName());
1682 /// Find appropriate Module Pass Manager in the PM Stack and
1683 /// add self into that manager.
1684 void ModulePass::assignPassManager(PMStack &PMS,
1685 PassManagerType PreferredType) {
1686 // Find Module Pass Manager
1687 while(!PMS.empty()) {
1688 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1689 if (TopPMType == PreferredType)
1690 break; // We found desired pass manager
1691 else if (TopPMType > PMT_ModulePassManager)
1692 PMS.pop(); // Pop children pass managers
1696 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1697 PMS.top()->add(this);
1700 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1701 /// in the PM Stack and add self into that manager.
1702 void FunctionPass::assignPassManager(PMStack &PMS,
1703 PassManagerType PreferredType) {
1705 // Find Module Pass Manager
1706 while (!PMS.empty()) {
1707 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1713 // Create new Function Pass Manager if needed.
1715 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1716 FPP = (FPPassManager *)PMS.top();
1718 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1719 PMDataManager *PMD = PMS.top();
1721 // [1] Create new Function Pass Manager
1722 FPP = new FPPassManager(PMD->getDepth() + 1);
1723 FPP->populateInheritedAnalysis(PMS);
1725 // [2] Set up new manager's top level manager
1726 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1727 TPM->addIndirectPassManager(FPP);
1729 // [3] Assign manager to manage this new manager. This may create
1730 // and push new managers into PMS
1731 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1733 // [4] Push new manager into PMS
1737 // Assign FPP as the manager of this pass.
1741 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1742 /// in the PM Stack and add self into that manager.
1743 void BasicBlockPass::assignPassManager(PMStack &PMS,
1744 PassManagerType PreferredType) {
1747 // Basic Pass Manager is a leaf pass manager. It does not handle
1748 // any other pass manager.
1750 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1751 BBP = (BBPassManager *)PMS.top();
1753 // If leaf manager is not Basic Block Pass manager then create new
1754 // basic Block Pass manager.
1755 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1756 PMDataManager *PMD = PMS.top();
1758 // [1] Create new Basic Block Manager
1759 BBP = new BBPassManager(PMD->getDepth() + 1);
1761 // [2] Set up new manager's top level manager
1762 // Basic Block Pass Manager does not live by itself
1763 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1764 TPM->addIndirectPassManager(BBP);
1766 // [3] Assign manager to manage this new manager. This may create
1767 // and push new managers into PMS
1768 BBP->assignPassManager(PMS);
1770 // [4] Push new manager into PMS
1774 // Assign BBP as the manager of this pass.
1778 PassManagerBase::~PassManagerBase() {}
1780 /*===-- C Bindings --------------------------------------------------------===*/
1782 LLVMPassManagerRef LLVMCreatePassManager() {
1783 return wrap(new PassManager());
1786 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1787 return wrap(new FunctionPassManager(unwrap(M)));
1790 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1791 return LLVMCreateFunctionPassManagerForModule(
1792 reinterpret_cast<LLVMModuleRef>(P));
1795 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1796 return unwrap<PassManager>(PM)->run(*unwrap(M));
1799 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1800 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1803 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1804 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1807 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1808 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1811 void LLVMDisposePassManager(LLVMPassManagerRef PM) {