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 StaticPassInfo *PI,
338 virtual const char *getPassName() const {
339 return "Module Pass Manager";
342 virtual PMDataManager *getAsPMDataManager() { return this; }
343 virtual Pass *getAsPass() { return this; }
345 // Print passes managed by this manager
346 void dumpPassStructure(unsigned Offset) {
347 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
348 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
349 ModulePass *MP = getContainedPass(Index);
350 MP->dumpPassStructure(Offset + 1);
351 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
352 OnTheFlyManagers.find(MP);
353 if (I != OnTheFlyManagers.end())
354 I->second->dumpPassStructure(Offset + 2);
355 dumpLastUses(MP, Offset+1);
359 ModulePass *getContainedPass(unsigned N) {
360 assert(N < PassVector.size() && "Pass number out of range!");
361 return static_cast<ModulePass *>(PassVector[N]);
364 virtual PassManagerType getPassManagerType() const {
365 return PMT_ModulePassManager;
369 /// Collection of on the fly FPPassManagers. These managers manage
370 /// function passes that are required by module passes.
371 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
374 char MPPassManager::ID = 0;
375 //===----------------------------------------------------------------------===//
379 /// PassManagerImpl manages MPPassManagers
380 class PassManagerImpl : public Pass,
381 public PMDataManager,
382 public PMTopLevelManager {
386 explicit PassManagerImpl(int Depth) :
387 Pass(PT_PassManager, &ID), PMDataManager(Depth),
388 PMTopLevelManager(TLM_Pass) { }
390 /// add - Add a pass to the queue of passes to run. This passes ownership of
391 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
392 /// will be destroyed as well, so there is no need to delete the pass. This
393 /// implies that all passes MUST be allocated with 'new'.
398 /// createPrinterPass - Get a module printer pass.
399 Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const {
400 return createPrintModulePass(&O, false, Banner);
403 /// run - Execute all of the passes scheduled for execution. Keep track of
404 /// whether any of the passes modifies the module, and if so, return true.
407 /// Pass Manager itself does not invalidate any analysis info.
408 void getAnalysisUsage(AnalysisUsage &Info) const {
409 Info.setPreservesAll();
412 inline void addTopLevelPass(Pass *P) {
413 if (ImmutablePass *IP = P->getAsImmutablePass()) {
414 // P is a immutable pass and it will be managed by this
415 // top level manager. Set up analysis resolver to connect them.
416 AnalysisResolver *AR = new AnalysisResolver(*this);
418 initializeAnalysisImpl(P);
419 addImmutablePass(IP);
420 recordAvailableAnalysis(IP);
422 P->assignPassManager(activeStack, PMT_ModulePassManager);
426 virtual PMDataManager *getAsPMDataManager() { return this; }
427 virtual Pass *getAsPass() { return this; }
429 MPPassManager *getContainedManager(unsigned N) {
430 assert(N < PassManagers.size() && "Pass number out of range!");
431 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
436 char PassManagerImpl::ID = 0;
437 } // End of llvm namespace
441 //===----------------------------------------------------------------------===//
442 /// TimingInfo Class - This class is used to calculate information about the
443 /// amount of time each pass takes to execute. This only happens when
444 /// -time-passes is enabled on the command line.
447 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
450 DenseMap<Pass*, Timer*> TimingData;
453 // Use 'create' member to get this.
454 TimingInfo() : TG("... Pass execution timing report ...") {}
456 // TimingDtor - Print out information about timing information
458 // Delete all of the timers, which accumulate their info into the
460 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
461 E = TimingData.end(); I != E; ++I)
463 // TimerGroup is deleted next, printing the report.
466 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
467 // to a non null value (if the -time-passes option is enabled) or it leaves it
468 // null. It may be called multiple times.
469 static void createTheTimeInfo();
471 /// getPassTimer - Return the timer for the specified pass if it exists.
472 Timer *getPassTimer(Pass *P) {
473 if (P->getAsPMDataManager())
476 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
477 Timer *&T = TimingData[P];
479 T = new Timer(P->getPassName(), TG);
484 } // End of anon namespace
486 static TimingInfo *TheTimeInfo;
488 //===----------------------------------------------------------------------===//
489 // PMTopLevelManager implementation
491 /// Initialize top level manager. Create first pass manager.
492 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
494 MPPassManager *MPP = new MPPassManager(1);
495 MPP->setTopLevelManager(this);
497 activeStack.push(MPP);
498 } else if (t == TLM_Function) {
499 FPPassManager *FPP = new FPPassManager(1);
500 FPP->setTopLevelManager(this);
502 activeStack.push(FPP);
506 /// Set pass P as the last user of the given analysis passes.
507 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
509 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
510 E = AnalysisPasses.end(); I != E; ++I) {
517 // If AP is the last user of other passes then make P last user of
519 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
520 LUE = LastUser.end(); LUI != LUE; ++LUI) {
521 if (LUI->second == AP)
522 // DenseMap iterator is not invalidated here because
523 // this is just updating exisitng entry.
524 LastUser[LUI->first] = P;
529 /// Collect passes whose last user is P
530 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
532 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
533 InversedLastUser.find(P);
534 if (DMI == InversedLastUser.end())
537 SmallPtrSet<Pass *, 8> &LU = DMI->second;
538 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
539 E = LU.end(); I != E; ++I) {
540 LastUses.push_back(*I);
545 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
546 AnalysisUsage *AnUsage = NULL;
547 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
548 if (DMI != AnUsageMap.end())
549 AnUsage = DMI->second;
551 AnUsage = new AnalysisUsage();
552 P->getAnalysisUsage(*AnUsage);
553 AnUsageMap[P] = AnUsage;
558 /// Schedule pass P for execution. Make sure that passes required by
559 /// P are run before P is run. Update analysis info maintained by
560 /// the manager. Remove dead passes. This is a recursive function.
561 void PMTopLevelManager::schedulePass(Pass *P) {
563 // TODO : Allocate function manager for this pass, other wise required set
564 // may be inserted into previous function manager
566 // Give pass a chance to prepare the stage.
567 P->preparePassManager(activeStack);
569 // If P is an analysis pass and it is available then do not
570 // generate the analysis again. Stale analysis info should not be
571 // available at this point.
572 if (P->getPassInfo() &&
573 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
578 AnalysisUsage *AnUsage = findAnalysisUsage(P);
580 bool checkAnalysis = true;
581 while (checkAnalysis) {
582 checkAnalysis = false;
584 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
585 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
586 E = RequiredSet.end(); I != E; ++I) {
588 Pass *AnalysisPass = findAnalysisPass(*I);
590 AnalysisPass = (*I)->createPass();
591 if (P->getPotentialPassManagerType () ==
592 AnalysisPass->getPotentialPassManagerType())
593 // Schedule analysis pass that is managed by the same pass manager.
594 schedulePass(AnalysisPass);
595 else if (P->getPotentialPassManagerType () >
596 AnalysisPass->getPotentialPassManagerType()) {
597 // Schedule analysis pass that is managed by a new manager.
598 schedulePass(AnalysisPass);
599 // Recheck analysis passes to ensure that required analysises that
600 // are already checked are still available.
601 checkAnalysis = true;
604 // Do not schedule this analysis. Lower level analsyis
605 // passes are run on the fly.
611 // Now all required passes are available.
615 /// Find the pass that implements Analysis AID. Search immutable
616 /// passes and all pass managers. If desired pass is not found
617 /// then return NULL.
618 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
621 // Check pass managers
622 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
623 E = PassManagers.end(); P == NULL && I != E; ++I) {
624 PMDataManager *PMD = *I;
625 P = PMD->findAnalysisPass(AID, false);
628 // Check other pass managers
629 for (SmallVector<PMDataManager *, 8>::iterator
630 I = IndirectPassManagers.begin(),
631 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
632 P = (*I)->findAnalysisPass(AID, false);
634 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
635 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
636 const StaticPassInfo *PI = (*I)->getPassInfo();
640 // If Pass not found then check the interfaces implemented by Immutable Pass
642 const PassInfo::InterfaceInfo *ImmPI = PI->getInterfacesImplemented();
644 if (ImmPI->interface == AID) {
656 // Print passes managed by this top level manager.
657 void PMTopLevelManager::dumpPasses() const {
659 if (PassDebugging < Structure)
662 // Print out the immutable passes
663 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
664 ImmutablePasses[i]->dumpPassStructure(0);
667 // Every class that derives from PMDataManager also derives from Pass
668 // (sometimes indirectly), but there's no inheritance relationship
669 // between PMDataManager and Pass, so we have to getAsPass to get
670 // from a PMDataManager* to a Pass*.
671 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
672 E = PassManagers.end(); I != E; ++I)
673 (*I)->getAsPass()->dumpPassStructure(1);
676 void PMTopLevelManager::dumpArguments() const {
678 if (PassDebugging < Arguments)
681 dbgs() << "Pass Arguments: ";
682 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
683 E = PassManagers.end(); I != E; ++I)
684 (*I)->dumpPassArguments();
688 void PMTopLevelManager::initializeAllAnalysisInfo() {
689 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
690 E = PassManagers.end(); I != E; ++I)
691 (*I)->initializeAnalysisInfo();
693 // Initailize other pass managers
694 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
695 E = IndirectPassManagers.end(); I != E; ++I)
696 (*I)->initializeAnalysisInfo();
698 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
699 DME = LastUser.end(); DMI != DME; ++DMI) {
700 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
701 InversedLastUser.find(DMI->second);
702 if (InvDMI != InversedLastUser.end()) {
703 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
704 L.insert(DMI->first);
706 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
707 InversedLastUser[DMI->second] = L;
713 PMTopLevelManager::~PMTopLevelManager() {
714 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
715 E = PassManagers.end(); I != E; ++I)
718 for (SmallVector<ImmutablePass *, 8>::iterator
719 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
722 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
723 DME = AnUsageMap.end(); DMI != DME; ++DMI)
727 //===----------------------------------------------------------------------===//
728 // PMDataManager implementation
730 /// Augement AvailableAnalysis by adding analysis made available by pass P.
731 void PMDataManager::recordAvailableAnalysis(Pass *P) {
732 const StaticPassInfo *PI = P->getPassInfo();
735 AvailableAnalysis[PI] = P;
737 //This pass is the current implementation of all of the interfaces it
738 //implements as well.
739 const PassInfo::InterfaceInfo *II = PI->getInterfacesImplemented();
741 AvailableAnalysis[II->interface] = P;
746 // Return true if P preserves high level analysis used by other
747 // passes managed by this manager
748 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
749 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
750 if (AnUsage->getPreservesAll())
753 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
754 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
755 E = HigherLevelAnalysis.end(); I != E; ++I) {
757 if (P1->getAsImmutablePass() == 0 &&
758 std::find(PreservedSet.begin(), PreservedSet.end(),
759 P1->getPassInfo()) ==
767 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
768 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
769 // Don't do this unless assertions are enabled.
773 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
774 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
776 // Verify preserved analysis
777 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
778 E = PreservedSet.end(); I != E; ++I) {
780 if (Pass *AP = findAnalysisPass(AID, true)) {
781 TimeRegion PassTimer(getPassTimer(AP));
782 AP->verifyAnalysis();
787 /// Remove Analysis not preserved by Pass P
788 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
789 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
790 if (AnUsage->getPreservesAll())
793 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
794 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
795 E = AvailableAnalysis.end(); I != E; ) {
796 std::map<AnalysisID, Pass*>::iterator Info = I++;
797 if (Info->second->getAsImmutablePass() == 0 &&
798 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
799 PreservedSet.end()) {
800 // Remove this analysis
801 if (PassDebugging >= Details) {
802 Pass *S = Info->second;
803 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
804 dbgs() << S->getPassName() << "'\n";
806 AvailableAnalysis.erase(Info);
810 // Check inherited analysis also. If P is not preserving analysis
811 // provided by parent manager then remove it here.
812 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
814 if (!InheritedAnalysis[Index])
817 for (std::map<AnalysisID, Pass*>::iterator
818 I = InheritedAnalysis[Index]->begin(),
819 E = InheritedAnalysis[Index]->end(); I != E; ) {
820 std::map<AnalysisID, Pass *>::iterator Info = I++;
821 if (Info->second->getAsImmutablePass() == 0 &&
822 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
823 PreservedSet.end()) {
824 // Remove this analysis
825 if (PassDebugging >= Details) {
826 Pass *S = Info->second;
827 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
828 dbgs() << S->getPassName() << "'\n";
830 InheritedAnalysis[Index]->erase(Info);
836 /// Remove analysis passes that are not used any longer
837 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
838 enum PassDebuggingString DBG_STR) {
840 SmallVector<Pass *, 12> DeadPasses;
842 // If this is a on the fly manager then it does not have TPM.
846 TPM->collectLastUses(DeadPasses, P);
848 if (PassDebugging >= Details && !DeadPasses.empty()) {
849 dbgs() << " -*- '" << P->getPassName();
850 dbgs() << "' is the last user of following pass instances.";
851 dbgs() << " Free these instances\n";
854 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
855 E = DeadPasses.end(); I != E; ++I)
856 freePass(*I, Msg, DBG_STR);
859 void PMDataManager::freePass(Pass *P, StringRef Msg,
860 enum PassDebuggingString DBG_STR) {
861 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
864 // If the pass crashes releasing memory, remember this.
865 PassManagerPrettyStackEntry X(P);
866 TimeRegion PassTimer(getPassTimer(P));
871 if (const StaticPassInfo *PI = P->getPassInfo()) {
872 // Remove the pass itself (if it is not already removed).
873 AvailableAnalysis.erase(PI);
875 // Remove all interfaces this pass implements, for which it is also
876 // listed as the available implementation.
877 const PassInfo::InterfaceInfo *II = PI->getInterfacesImplemented();
879 std::map<AnalysisID, Pass*>::iterator Pos =
880 AvailableAnalysis.find(II->interface);
881 if (Pos != AvailableAnalysis.end() && Pos->second == P)
882 AvailableAnalysis.erase(Pos);
888 /// Add pass P into the PassVector. Update
889 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
890 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
891 // This manager is going to manage pass P. Set up analysis resolver
893 AnalysisResolver *AR = new AnalysisResolver(*this);
896 // If a FunctionPass F is the last user of ModulePass info M
897 // then the F's manager, not F, records itself as a last user of M.
898 SmallVector<Pass *, 12> TransferLastUses;
900 if (!ProcessAnalysis) {
902 PassVector.push_back(P);
906 // At the moment, this pass is the last user of all required passes.
907 SmallVector<Pass *, 12> LastUses;
908 SmallVector<Pass *, 8> RequiredPasses;
909 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
911 unsigned PDepth = this->getDepth();
913 collectRequiredAnalysis(RequiredPasses,
914 ReqAnalysisNotAvailable, P);
915 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
916 E = RequiredPasses.end(); I != E; ++I) {
917 Pass *PRequired = *I;
920 assert(PRequired->getResolver() && "Analysis Resolver is not set");
921 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
922 RDepth = DM.getDepth();
924 if (PDepth == RDepth)
925 LastUses.push_back(PRequired);
926 else if (PDepth > RDepth) {
927 // Let the parent claim responsibility of last use
928 TransferLastUses.push_back(PRequired);
929 // Keep track of higher level analysis used by this manager.
930 HigherLevelAnalysis.push_back(PRequired);
932 llvm_unreachable("Unable to accomodate Required Pass");
935 // Set P as P's last user until someone starts using P.
936 // However, if P is a Pass Manager then it does not need
937 // to record its last user.
938 if (P->getAsPMDataManager() == 0)
939 LastUses.push_back(P);
940 TPM->setLastUser(LastUses, P);
942 if (!TransferLastUses.empty()) {
943 Pass *My_PM = getAsPass();
944 TPM->setLastUser(TransferLastUses, My_PM);
945 TransferLastUses.clear();
948 // Now, take care of required analysises that are not available.
949 for (SmallVector<AnalysisID, 8>::iterator
950 I = ReqAnalysisNotAvailable.begin(),
951 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
952 Pass *AnalysisPass = (*I)->createPass();
953 this->addLowerLevelRequiredPass(P, AnalysisPass);
956 // Take a note of analysis required and made available by this pass.
957 // Remove the analysis not preserved by this pass
958 removeNotPreservedAnalysis(P);
959 recordAvailableAnalysis(P);
962 PassVector.push_back(P);
966 /// Populate RP with analysis pass that are required by
967 /// pass P and are available. Populate RP_NotAvail with analysis
968 /// pass that are required by pass P but are not available.
969 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
970 SmallVector<AnalysisID, 8> &RP_NotAvail,
972 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
973 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
974 for (AnalysisUsage::VectorType::const_iterator
975 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
976 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
977 RP.push_back(AnalysisPass);
979 RP_NotAvail.push_back(*I);
982 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
983 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
984 E = IDs.end(); I != E; ++I) {
985 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
986 RP.push_back(AnalysisPass);
988 RP_NotAvail.push_back(*I);
992 // All Required analyses should be available to the pass as it runs! Here
993 // we fill in the AnalysisImpls member of the pass so that it can
994 // successfully use the getAnalysis() method to retrieve the
995 // implementations it needs.
997 void PMDataManager::initializeAnalysisImpl(Pass *P) {
998 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1000 for (AnalysisUsage::VectorType::const_iterator
1001 I = AnUsage->getRequiredSet().begin(),
1002 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1003 Pass *Impl = findAnalysisPass(*I, true);
1005 // This may be analysis pass that is initialized on the fly.
1006 // If that is not the case then it will raise an assert when it is used.
1008 AnalysisResolver *AR = P->getResolver();
1009 assert(AR && "Analysis Resolver is not set");
1010 AR->addAnalysisImplsPair(*I, Impl);
1014 /// Find the pass that implements Analysis AID. If desired pass is not found
1015 /// then return NULL.
1016 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1018 // Check if AvailableAnalysis map has one entry.
1019 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1021 if (I != AvailableAnalysis.end())
1024 // Search Parents through TopLevelManager
1026 return TPM->findAnalysisPass(AID);
1031 // Print list of passes that are last used by P.
1032 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1034 SmallVector<Pass *, 12> LUses;
1036 // If this is a on the fly manager then it does not have TPM.
1040 TPM->collectLastUses(LUses, P);
1042 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
1043 E = LUses.end(); I != E; ++I) {
1044 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
1045 (*I)->dumpPassStructure(0);
1049 void PMDataManager::dumpPassArguments() const {
1050 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
1051 E = PassVector.end(); I != E; ++I) {
1052 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1053 PMD->dumpPassArguments();
1055 if (const StaticPassInfo *PI = (*I)->getPassInfo())
1056 if (!PI->isAnalysisGroup())
1057 dbgs() << " -" << PI->getPassArgument();
1061 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1062 enum PassDebuggingString S2,
1064 if (PassDebugging < Executions)
1066 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
1069 dbgs() << "Executing Pass '" << P->getPassName();
1071 case MODIFICATION_MSG:
1072 dbgs() << "Made Modification '" << P->getPassName();
1075 dbgs() << " Freeing Pass '" << P->getPassName();
1081 case ON_BASICBLOCK_MSG:
1082 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1084 case ON_FUNCTION_MSG:
1085 dbgs() << "' on Function '" << Msg << "'...\n";
1088 dbgs() << "' on Module '" << Msg << "'...\n";
1091 dbgs() << "' on Loop '" << Msg << "'...\n";
1094 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1101 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1102 if (PassDebugging < Details)
1105 AnalysisUsage analysisUsage;
1106 P->getAnalysisUsage(analysisUsage);
1107 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1110 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1111 if (PassDebugging < Details)
1114 AnalysisUsage analysisUsage;
1115 P->getAnalysisUsage(analysisUsage);
1116 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1119 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1120 const AnalysisUsage::VectorType &Set) const {
1121 assert(PassDebugging >= Details);
1124 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1125 for (unsigned i = 0; i != Set.size(); ++i) {
1126 if (i) dbgs() << ',';
1127 dbgs() << ' ' << Set[i]->getPassName();
1132 /// Add RequiredPass into list of lower level passes required by pass P.
1133 /// RequiredPass is run on the fly by Pass Manager when P requests it
1134 /// through getAnalysis interface.
1135 /// This should be handled by specific pass manager.
1136 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1138 TPM->dumpArguments();
1142 // Module Level pass may required Function Level analysis info
1143 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1144 // to provide this on demand. In that case, in Pass manager terminology,
1145 // module level pass is requiring lower level analysis info managed by
1146 // lower level pass manager.
1148 // When Pass manager is not able to order required analysis info, Pass manager
1149 // checks whether any lower level manager will be able to provide this
1150 // analysis info on demand or not.
1152 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1153 dbgs() << "' required by '" << P->getPassName() << "'\n";
1155 llvm_unreachable("Unable to schedule pass");
1158 Pass *PMDataManager::getOnTheFlyPass(Pass *P, const StaticPassInfo *PI,
1160 assert(0 && "Unable to find on the fly pass");
1165 PMDataManager::~PMDataManager() {
1166 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1167 E = PassVector.end(); I != E; ++I)
1171 //===----------------------------------------------------------------------===//
1172 // NOTE: Is this the right place to define this method ?
1173 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1174 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1175 return PM.findAnalysisPass(ID, dir);
1178 Pass *AnalysisResolver::findImplPass(Pass *P, const StaticPassInfo *AnalysisPI,
1180 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1183 //===----------------------------------------------------------------------===//
1184 // BBPassManager implementation
1186 /// Execute all of the passes scheduled for execution by invoking
1187 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1188 /// the function, and if so, return true.
1189 bool BBPassManager::runOnFunction(Function &F) {
1190 if (F.isDeclaration())
1193 bool Changed = doInitialization(F);
1195 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1196 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1197 BasicBlockPass *BP = getContainedPass(Index);
1198 bool LocalChanged = false;
1200 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1201 dumpRequiredSet(BP);
1203 initializeAnalysisImpl(BP);
1206 // If the pass crashes, remember this.
1207 PassManagerPrettyStackEntry X(BP, *I);
1208 TimeRegion PassTimer(getPassTimer(BP));
1210 LocalChanged |= BP->runOnBasicBlock(*I);
1213 Changed |= LocalChanged;
1215 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1217 dumpPreservedSet(BP);
1219 verifyPreservedAnalysis(BP);
1220 removeNotPreservedAnalysis(BP);
1221 recordAvailableAnalysis(BP);
1222 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1225 return doFinalization(F) || Changed;
1228 // Implement doInitialization and doFinalization
1229 bool BBPassManager::doInitialization(Module &M) {
1230 bool Changed = false;
1232 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1233 Changed |= getContainedPass(Index)->doInitialization(M);
1238 bool BBPassManager::doFinalization(Module &M) {
1239 bool Changed = false;
1241 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1242 Changed |= getContainedPass(Index)->doFinalization(M);
1247 bool BBPassManager::doInitialization(Function &F) {
1248 bool Changed = false;
1250 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1251 BasicBlockPass *BP = getContainedPass(Index);
1252 Changed |= BP->doInitialization(F);
1258 bool BBPassManager::doFinalization(Function &F) {
1259 bool Changed = false;
1261 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1262 BasicBlockPass *BP = getContainedPass(Index);
1263 Changed |= BP->doFinalization(F);
1270 //===----------------------------------------------------------------------===//
1271 // FunctionPassManager implementation
1273 /// Create new Function pass manager
1274 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1275 FPM = new FunctionPassManagerImpl(0);
1276 // FPM is the top level manager.
1277 FPM->setTopLevelManager(FPM);
1279 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1280 FPM->setResolver(AR);
1283 FunctionPassManager::~FunctionPassManager() {
1287 /// addImpl - Add a pass to the queue of passes to run, without
1288 /// checking whether to add a printer pass.
1289 void FunctionPassManager::addImpl(Pass *P) {
1293 /// add - Add a pass to the queue of passes to run. This passes
1294 /// ownership of the Pass to the PassManager. When the
1295 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1296 /// there is no need to delete the pass. (TODO delete passes.)
1297 /// This implies that all passes MUST be allocated with 'new'.
1298 void FunctionPassManager::add(Pass *P) {
1299 // If this is a not a function pass, don't add a printer for it.
1300 if (P->getPassKind() == PT_Function)
1301 if (ShouldPrintBeforePass(P))
1302 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1303 + P->getPassName() + " ***"));
1307 if (P->getPassKind() == PT_Function)
1308 if (ShouldPrintAfterPass(P))
1309 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1310 + P->getPassName() + " ***"));
1313 /// run - Execute all of the passes scheduled for execution. Keep
1314 /// track of whether any of the passes modifies the function, and if
1315 /// so, return true.
1317 bool FunctionPassManager::run(Function &F) {
1318 if (F.isMaterializable()) {
1320 if (F.Materialize(&errstr))
1321 report_fatal_error("Error reading bitcode file: " + Twine(errstr));
1327 /// doInitialization - Run all of the initializers for the function passes.
1329 bool FunctionPassManager::doInitialization() {
1330 return FPM->doInitialization(*M);
1333 /// doFinalization - Run all of the finalizers for the function passes.
1335 bool FunctionPassManager::doFinalization() {
1336 return FPM->doFinalization(*M);
1339 //===----------------------------------------------------------------------===//
1340 // FunctionPassManagerImpl implementation
1342 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1343 bool Changed = false;
1348 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1349 Changed |= getContainedManager(Index)->doInitialization(M);
1354 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1355 bool Changed = false;
1357 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1358 Changed |= getContainedManager(Index)->doFinalization(M);
1363 /// cleanup - After running all passes, clean up pass manager cache.
1364 void FPPassManager::cleanup() {
1365 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1366 FunctionPass *FP = getContainedPass(Index);
1367 AnalysisResolver *AR = FP->getResolver();
1368 assert(AR && "Analysis Resolver is not set");
1369 AR->clearAnalysisImpls();
1373 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1376 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1377 FPPassManager *FPPM = getContainedManager(Index);
1378 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1379 FPPM->getContainedPass(Index)->releaseMemory();
1385 // Execute all the passes managed by this top level manager.
1386 // Return true if any function is modified by a pass.
1387 bool FunctionPassManagerImpl::run(Function &F) {
1388 bool Changed = false;
1389 TimingInfo::createTheTimeInfo();
1391 initializeAllAnalysisInfo();
1392 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1393 Changed |= getContainedManager(Index)->runOnFunction(F);
1395 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1396 getContainedManager(Index)->cleanup();
1402 //===----------------------------------------------------------------------===//
1403 // FPPassManager implementation
1405 char FPPassManager::ID = 0;
1406 /// Print passes managed by this manager
1407 void FPPassManager::dumpPassStructure(unsigned Offset) {
1408 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1409 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1410 FunctionPass *FP = getContainedPass(Index);
1411 FP->dumpPassStructure(Offset + 1);
1412 dumpLastUses(FP, Offset+1);
1417 /// Execute all of the passes scheduled for execution by invoking
1418 /// runOnFunction method. Keep track of whether any of the passes modifies
1419 /// the function, and if so, return true.
1420 bool FPPassManager::runOnFunction(Function &F) {
1421 if (F.isDeclaration())
1424 bool Changed = false;
1426 // Collect inherited analysis from Module level pass manager.
1427 populateInheritedAnalysis(TPM->activeStack);
1429 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1430 FunctionPass *FP = getContainedPass(Index);
1431 bool LocalChanged = false;
1433 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1434 dumpRequiredSet(FP);
1436 initializeAnalysisImpl(FP);
1439 PassManagerPrettyStackEntry X(FP, F);
1440 TimeRegion PassTimer(getPassTimer(FP));
1442 LocalChanged |= FP->runOnFunction(F);
1445 Changed |= LocalChanged;
1447 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1448 dumpPreservedSet(FP);
1450 verifyPreservedAnalysis(FP);
1451 removeNotPreservedAnalysis(FP);
1452 recordAvailableAnalysis(FP);
1453 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1458 bool FPPassManager::runOnModule(Module &M) {
1459 bool Changed = doInitialization(M);
1461 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1464 return doFinalization(M) || Changed;
1467 bool FPPassManager::doInitialization(Module &M) {
1468 bool Changed = false;
1470 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1471 Changed |= getContainedPass(Index)->doInitialization(M);
1476 bool FPPassManager::doFinalization(Module &M) {
1477 bool Changed = false;
1479 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1480 Changed |= getContainedPass(Index)->doFinalization(M);
1485 //===----------------------------------------------------------------------===//
1486 // MPPassManager implementation
1488 /// Execute all of the passes scheduled for execution by invoking
1489 /// runOnModule method. Keep track of whether any of the passes modifies
1490 /// the module, and if so, return true.
1492 MPPassManager::runOnModule(Module &M) {
1493 bool Changed = false;
1495 // Initialize on-the-fly passes
1496 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1497 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1499 FunctionPassManagerImpl *FPP = I->second;
1500 Changed |= FPP->doInitialization(M);
1503 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1504 ModulePass *MP = getContainedPass(Index);
1505 bool LocalChanged = false;
1507 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1508 dumpRequiredSet(MP);
1510 initializeAnalysisImpl(MP);
1513 PassManagerPrettyStackEntry X(MP, M);
1514 TimeRegion PassTimer(getPassTimer(MP));
1516 LocalChanged |= MP->runOnModule(M);
1519 Changed |= LocalChanged;
1521 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1522 M.getModuleIdentifier());
1523 dumpPreservedSet(MP);
1525 verifyPreservedAnalysis(MP);
1526 removeNotPreservedAnalysis(MP);
1527 recordAvailableAnalysis(MP);
1528 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1531 // Finalize on-the-fly passes
1532 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1533 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1535 FunctionPassManagerImpl *FPP = I->second;
1536 // We don't know when is the last time an on-the-fly pass is run,
1537 // so we need to releaseMemory / finalize here
1538 FPP->releaseMemoryOnTheFly();
1539 Changed |= FPP->doFinalization(M);
1544 /// Add RequiredPass into list of lower level passes required by pass P.
1545 /// RequiredPass is run on the fly by Pass Manager when P requests it
1546 /// through getAnalysis interface.
1547 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1548 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1549 "Unable to handle Pass that requires lower level Analysis pass");
1550 assert((P->getPotentialPassManagerType() <
1551 RequiredPass->getPotentialPassManagerType()) &&
1552 "Unable to handle Pass that requires lower level Analysis pass");
1554 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1556 FPP = new FunctionPassManagerImpl(0);
1557 // FPP is the top level manager.
1558 FPP->setTopLevelManager(FPP);
1560 OnTheFlyManagers[P] = FPP;
1562 FPP->add(RequiredPass);
1564 // Register P as the last user of RequiredPass.
1565 SmallVector<Pass *, 12> LU;
1566 LU.push_back(RequiredPass);
1567 FPP->setLastUser(LU, P);
1570 /// Return function pass corresponding to PassInfo PI, that is
1571 /// required by module pass MP. Instantiate analysis pass, by using
1572 /// its runOnFunction() for function F.
1573 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const StaticPassInfo *PI,
1575 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1576 assert(FPP && "Unable to find on the fly pass");
1578 FPP->releaseMemoryOnTheFly();
1580 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1584 //===----------------------------------------------------------------------===//
1585 // PassManagerImpl implementation
1587 /// run - Execute all of the passes scheduled for execution. Keep track of
1588 /// whether any of the passes modifies the module, and if so, return true.
1589 bool PassManagerImpl::run(Module &M) {
1590 bool Changed = false;
1591 TimingInfo::createTheTimeInfo();
1596 initializeAllAnalysisInfo();
1597 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1598 Changed |= getContainedManager(Index)->runOnModule(M);
1602 //===----------------------------------------------------------------------===//
1603 // PassManager implementation
1605 /// Create new pass manager
1606 PassManager::PassManager() {
1607 PM = new PassManagerImpl(0);
1608 // PM is the top level manager
1609 PM->setTopLevelManager(PM);
1612 PassManager::~PassManager() {
1616 /// addImpl - Add a pass to the queue of passes to run, without
1617 /// checking whether to add a printer pass.
1618 void PassManager::addImpl(Pass *P) {
1622 /// add - Add a pass to the queue of passes to run. This passes ownership of
1623 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1624 /// will be destroyed as well, so there is no need to delete the pass. This
1625 /// implies that all passes MUST be allocated with 'new'.
1626 void PassManager::add(Pass *P) {
1627 if (ShouldPrintBeforePass(P))
1628 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
1629 + P->getPassName() + " ***"));
1633 if (ShouldPrintAfterPass(P))
1634 addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
1635 + P->getPassName() + " ***"));
1638 /// run - Execute all of the passes scheduled for execution. Keep track of
1639 /// whether any of the passes modifies the module, and if so, return true.
1640 bool PassManager::run(Module &M) {
1644 //===----------------------------------------------------------------------===//
1645 // TimingInfo Class - This class is used to calculate information about the
1646 // amount of time each pass takes to execute. This only happens with
1647 // -time-passes is enabled on the command line.
1649 bool llvm::TimePassesIsEnabled = false;
1650 static cl::opt<bool,true>
1651 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1652 cl::desc("Time each pass, printing elapsed time for each on exit"));
1654 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1655 // a non null value (if the -time-passes option is enabled) or it leaves it
1656 // null. It may be called multiple times.
1657 void TimingInfo::createTheTimeInfo() {
1658 if (!TimePassesIsEnabled || TheTimeInfo) return;
1660 // Constructed the first time this is called, iff -time-passes is enabled.
1661 // This guarantees that the object will be constructed before static globals,
1662 // thus it will be destroyed before them.
1663 static ManagedStatic<TimingInfo> TTI;
1664 TheTimeInfo = &*TTI;
1667 /// If TimingInfo is enabled then start pass timer.
1668 Timer *llvm::getPassTimer(Pass *P) {
1670 return TheTimeInfo->getPassTimer(P);
1674 //===----------------------------------------------------------------------===//
1675 // PMStack implementation
1678 // Pop Pass Manager from the stack and clear its analysis info.
1679 void PMStack::pop() {
1681 PMDataManager *Top = this->top();
1682 Top->initializeAnalysisInfo();
1687 // Push PM on the stack and set its top level manager.
1688 void PMStack::push(PMDataManager *PM) {
1689 assert(PM && "Unable to push. Pass Manager expected");
1691 if (!this->empty()) {
1692 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1694 assert(TPM && "Unable to find top level manager");
1695 TPM->addIndirectPassManager(PM);
1696 PM->setTopLevelManager(TPM);
1702 // Dump content of the pass manager stack.
1703 void PMStack::dump() {
1704 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1705 E = S.end(); I != E; ++I)
1706 printf("%s ", (*I)->getAsPass()->getPassName());
1712 /// Find appropriate Module Pass Manager in the PM Stack and
1713 /// add self into that manager.
1714 void ModulePass::assignPassManager(PMStack &PMS,
1715 PassManagerType PreferredType) {
1716 // Find Module Pass Manager
1717 while(!PMS.empty()) {
1718 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1719 if (TopPMType == PreferredType)
1720 break; // We found desired pass manager
1721 else if (TopPMType > PMT_ModulePassManager)
1722 PMS.pop(); // Pop children pass managers
1726 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1727 PMS.top()->add(this);
1730 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1731 /// in the PM Stack and add self into that manager.
1732 void FunctionPass::assignPassManager(PMStack &PMS,
1733 PassManagerType PreferredType) {
1735 // Find Module Pass Manager
1736 while (!PMS.empty()) {
1737 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1743 // Create new Function Pass Manager if needed.
1745 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1746 FPP = (FPPassManager *)PMS.top();
1748 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1749 PMDataManager *PMD = PMS.top();
1751 // [1] Create new Function Pass Manager
1752 FPP = new FPPassManager(PMD->getDepth() + 1);
1753 FPP->populateInheritedAnalysis(PMS);
1755 // [2] Set up new manager's top level manager
1756 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1757 TPM->addIndirectPassManager(FPP);
1759 // [3] Assign manager to manage this new manager. This may create
1760 // and push new managers into PMS
1761 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1763 // [4] Push new manager into PMS
1767 // Assign FPP as the manager of this pass.
1771 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1772 /// in the PM Stack and add self into that manager.
1773 void BasicBlockPass::assignPassManager(PMStack &PMS,
1774 PassManagerType PreferredType) {
1777 // Basic Pass Manager is a leaf pass manager. It does not handle
1778 // any other pass manager.
1780 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1781 BBP = (BBPassManager *)PMS.top();
1783 // If leaf manager is not Basic Block Pass manager then create new
1784 // basic Block Pass manager.
1785 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1786 PMDataManager *PMD = PMS.top();
1788 // [1] Create new Basic Block Manager
1789 BBP = new BBPassManager(PMD->getDepth() + 1);
1791 // [2] Set up new manager's top level manager
1792 // Basic Block Pass Manager does not live by itself
1793 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1794 TPM->addIndirectPassManager(BBP);
1796 // [3] Assign manager to manage this new manager. This may create
1797 // and push new managers into PMS
1798 BBP->assignPassManager(PMS, PreferredType);
1800 // [4] Push new manager into PMS
1804 // Assign BBP as the manager of this pass.
1808 PassManagerBase::~PassManagerBase() {}
1810 /*===-- C Bindings --------------------------------------------------------===*/
1812 LLVMPassManagerRef LLVMCreatePassManager() {
1813 return wrap(new PassManager());
1816 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1817 return wrap(new FunctionPassManager(unwrap(M)));
1820 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1821 return LLVMCreateFunctionPassManagerForModule(
1822 reinterpret_cast<LLVMModuleRef>(P));
1825 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1826 return unwrap<PassManager>(PM)->run(*unwrap(M));
1829 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1830 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1833 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1834 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1837 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1838 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1841 void LLVMDisposePassManager(LLVMPassManagerRef PM) {