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/Writer.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Timer.h"
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/System/Mutex.h"
26 #include "llvm/System/Threading.h"
27 #include "llvm-c/Core.h"
33 // See PassManagers.h for Pass Manager infrastructure overview.
37 //===----------------------------------------------------------------------===//
38 // Pass debugging information. Often it is useful to find out what pass is
39 // running when a crash occurs in a utility. When this library is compiled with
40 // debugging on, a command line option (--debug-pass) is enabled that causes the
41 // pass name to be printed before it executes.
44 // Different debug levels that can be enabled...
46 None, Arguments, Structure, Executions, Details
49 static cl::opt<enum PassDebugLevel>
50 PassDebugging("debug-pass", cl::Hidden,
51 cl::desc("Print PassManager debugging information"),
53 clEnumVal(None , "disable debug output"),
54 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
55 clEnumVal(Structure , "print pass structure before run()"),
56 clEnumVal(Executions, "print pass name before it is executed"),
57 clEnumVal(Details , "print pass details when it is executed"),
59 } // End of llvm namespace
61 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
62 /// or higher is specified.
63 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
64 return PassDebugging >= Executions;
70 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
72 OS << "Releasing pass '";
74 OS << "Running pass '";
76 OS << P->getPassName() << "'";
79 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
90 else if (isa<BasicBlock>(V))
96 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
103 //===----------------------------------------------------------------------===//
106 /// BBPassManager manages BasicBlockPass. It batches all the
107 /// pass together and sequence them to process one basic block before
108 /// processing next basic block.
109 class BBPassManager : public PMDataManager, public FunctionPass {
113 explicit BBPassManager(int Depth)
114 : PMDataManager(Depth), FunctionPass(&ID) {}
116 /// Execute all of the passes scheduled for execution. Keep track of
117 /// whether any of the passes modifies the function, and if so, return true.
118 bool runOnFunction(Function &F);
120 /// Pass Manager itself does not invalidate any analysis info.
121 void getAnalysisUsage(AnalysisUsage &Info) const {
122 Info.setPreservesAll();
125 bool doInitialization(Module &M);
126 bool doInitialization(Function &F);
127 bool doFinalization(Module &M);
128 bool doFinalization(Function &F);
130 virtual PMDataManager *getAsPMDataManager() { return this; }
131 virtual Pass *getAsPass() { return this; }
133 virtual const char *getPassName() const {
134 return "BasicBlock Pass Manager";
137 // Print passes managed by this manager
138 void dumpPassStructure(unsigned Offset) {
139 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
140 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
141 BasicBlockPass *BP = getContainedPass(Index);
142 BP->dumpPassStructure(Offset + 1);
143 dumpLastUses(BP, Offset+1);
147 BasicBlockPass *getContainedPass(unsigned N) {
148 assert(N < PassVector.size() && "Pass number out of range!");
149 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
153 virtual PassManagerType getPassManagerType() const {
154 return PMT_BasicBlockPassManager;
158 char BBPassManager::ID = 0;
163 //===----------------------------------------------------------------------===//
164 // FunctionPassManagerImpl
166 /// FunctionPassManagerImpl manages FPPassManagers
167 class FunctionPassManagerImpl : public Pass,
168 public PMDataManager,
169 public PMTopLevelManager {
174 explicit FunctionPassManagerImpl(int Depth) :
175 Pass(PT_PassManager, &ID), PMDataManager(Depth),
176 PMTopLevelManager(TLM_Function), wasRun(false) { }
178 /// add - Add a pass to the queue of passes to run. This passes ownership of
179 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
180 /// will be destroyed as well, so there is no need to delete the pass. This
181 /// implies that all passes MUST be allocated with 'new'.
186 // Prepare for running an on the fly pass, freeing memory if needed
187 // from a previous run.
188 void releaseMemoryOnTheFly();
190 /// run - Execute all of the passes scheduled for execution. Keep track of
191 /// whether any of the passes modifies the module, and if so, return true.
192 bool run(Function &F);
194 /// doInitialization - Run all of the initializers for the function passes.
196 bool doInitialization(Module &M);
198 /// doFinalization - Run all of the finalizers for the function passes.
200 bool doFinalization(Module &M);
203 virtual PMDataManager *getAsPMDataManager() { return this; }
204 virtual Pass *getAsPass() { return this; }
206 /// Pass Manager itself does not invalidate any analysis info.
207 void getAnalysisUsage(AnalysisUsage &Info) const {
208 Info.setPreservesAll();
211 inline void addTopLevelPass(Pass *P) {
212 if (ImmutablePass *IP = P->getAsImmutablePass()) {
213 // P is a immutable pass and it will be managed by this
214 // top level manager. Set up analysis resolver to connect them.
215 AnalysisResolver *AR = new AnalysisResolver(*this);
217 initializeAnalysisImpl(P);
218 addImmutablePass(IP);
219 recordAvailableAnalysis(IP);
221 P->assignPassManager(activeStack);
226 FPPassManager *getContainedManager(unsigned N) {
227 assert(N < PassManagers.size() && "Pass number out of range!");
228 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
233 char FunctionPassManagerImpl::ID = 0;
234 //===----------------------------------------------------------------------===//
237 /// MPPassManager manages ModulePasses and function pass managers.
238 /// It batches all Module passes and function pass managers together and
239 /// sequences them to process one module.
240 class MPPassManager : public Pass, public PMDataManager {
243 explicit MPPassManager(int Depth) :
244 Pass(PT_PassManager, &ID), PMDataManager(Depth) { }
246 // Delete on the fly managers.
247 virtual ~MPPassManager() {
248 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
249 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
251 FunctionPassManagerImpl *FPP = I->second;
256 /// run - Execute all of the passes scheduled for execution. Keep track of
257 /// whether any of the passes modifies the module, and if so, return true.
258 bool runOnModule(Module &M);
260 /// Pass Manager itself does not invalidate any analysis info.
261 void getAnalysisUsage(AnalysisUsage &Info) const {
262 Info.setPreservesAll();
265 /// Add RequiredPass into list of lower level passes required by pass P.
266 /// RequiredPass is run on the fly by Pass Manager when P requests it
267 /// through getAnalysis interface.
268 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
270 /// Return function pass corresponding to PassInfo PI, that is
271 /// required by module pass MP. Instantiate analysis pass, by using
272 /// its runOnFunction() for function F.
273 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
275 virtual const char *getPassName() const {
276 return "Module Pass Manager";
279 virtual PMDataManager *getAsPMDataManager() { return this; }
280 virtual Pass *getAsPass() { return this; }
282 // Print passes managed by this manager
283 void dumpPassStructure(unsigned Offset) {
284 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
285 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
286 ModulePass *MP = getContainedPass(Index);
287 MP->dumpPassStructure(Offset + 1);
288 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
289 OnTheFlyManagers.find(MP);
290 if (I != OnTheFlyManagers.end())
291 I->second->dumpPassStructure(Offset + 2);
292 dumpLastUses(MP, Offset+1);
296 ModulePass *getContainedPass(unsigned N) {
297 assert(N < PassVector.size() && "Pass number out of range!");
298 return static_cast<ModulePass *>(PassVector[N]);
301 virtual PassManagerType getPassManagerType() const {
302 return PMT_ModulePassManager;
306 /// Collection of on the fly FPPassManagers. These managers manage
307 /// function passes that are required by module passes.
308 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
311 char MPPassManager::ID = 0;
312 //===----------------------------------------------------------------------===//
316 /// PassManagerImpl manages MPPassManagers
317 class PassManagerImpl : public Pass,
318 public PMDataManager,
319 public PMTopLevelManager {
323 explicit PassManagerImpl(int Depth) :
324 Pass(PT_PassManager, &ID), PMDataManager(Depth),
325 PMTopLevelManager(TLM_Pass) { }
327 /// add - Add a pass to the queue of passes to run. This passes ownership of
328 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
329 /// will be destroyed as well, so there is no need to delete the pass. This
330 /// implies that all passes MUST be allocated with 'new'.
335 /// run - Execute all of the passes scheduled for execution. Keep track of
336 /// whether any of the passes modifies the module, and if so, return true.
339 /// Pass Manager itself does not invalidate any analysis info.
340 void getAnalysisUsage(AnalysisUsage &Info) const {
341 Info.setPreservesAll();
344 inline void addTopLevelPass(Pass *P) {
345 if (ImmutablePass *IP = P->getAsImmutablePass()) {
346 // P is a immutable pass and it will be managed by this
347 // top level manager. Set up analysis resolver to connect them.
348 AnalysisResolver *AR = new AnalysisResolver(*this);
350 initializeAnalysisImpl(P);
351 addImmutablePass(IP);
352 recordAvailableAnalysis(IP);
354 P->assignPassManager(activeStack);
358 virtual PMDataManager *getAsPMDataManager() { return this; }
359 virtual Pass *getAsPass() { return this; }
361 MPPassManager *getContainedManager(unsigned N) {
362 assert(N < PassManagers.size() && "Pass number out of range!");
363 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
368 char PassManagerImpl::ID = 0;
369 } // End of llvm namespace
373 //===----------------------------------------------------------------------===//
374 /// TimingInfo Class - This class is used to calculate information about the
375 /// amount of time each pass takes to execute. This only happens when
376 /// -time-passes is enabled on the command line.
379 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
382 std::map<Pass*, Timer> TimingData;
386 // Use 'create' member to get this.
387 TimingInfo() : TG("... Pass execution timing report ...") {}
389 // TimingDtor - Print out information about timing information
391 // Delete all of the timers...
393 // TimerGroup is deleted next, printing the report.
396 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
397 // to a non null value (if the -time-passes option is enabled) or it leaves it
398 // null. It may be called multiple times.
399 static void createTheTimeInfo();
401 /// passStarted - This method creates a timer for the given pass if it doesn't
402 /// already have one, and starts the timer.
403 Timer *passStarted(Pass *P) {
404 if (P->getAsPMDataManager())
407 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
408 std::map<Pass*, Timer>::iterator I = TimingData.find(P);
409 if (I == TimingData.end())
410 I=TimingData.insert(std::make_pair(P, Timer(P->getPassName(), TG))).first;
411 Timer *T = &I->second;
417 } // End of anon namespace
419 static TimingInfo *TheTimeInfo;
421 //===----------------------------------------------------------------------===//
422 // PMTopLevelManager implementation
424 /// Initialize top level manager. Create first pass manager.
425 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
427 MPPassManager *MPP = new MPPassManager(1);
428 MPP->setTopLevelManager(this);
430 activeStack.push(MPP);
431 } else if (t == TLM_Function) {
432 FPPassManager *FPP = new FPPassManager(1);
433 FPP->setTopLevelManager(this);
435 activeStack.push(FPP);
439 /// Set pass P as the last user of the given analysis passes.
440 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
442 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
443 E = AnalysisPasses.end(); I != E; ++I) {
450 // If AP is the last user of other passes then make P last user of
452 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
453 LUE = LastUser.end(); LUI != LUE; ++LUI) {
454 if (LUI->second == AP)
455 // DenseMap iterator is not invalidated here because
456 // this is just updating exisitng entry.
457 LastUser[LUI->first] = P;
462 /// Collect passes whose last user is P
463 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
465 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
466 InversedLastUser.find(P);
467 if (DMI == InversedLastUser.end())
470 SmallPtrSet<Pass *, 8> &LU = DMI->second;
471 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
472 E = LU.end(); I != E; ++I) {
473 LastUses.push_back(*I);
478 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
479 AnalysisUsage *AnUsage = NULL;
480 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
481 if (DMI != AnUsageMap.end())
482 AnUsage = DMI->second;
484 AnUsage = new AnalysisUsage();
485 P->getAnalysisUsage(*AnUsage);
486 AnUsageMap[P] = AnUsage;
491 /// Schedule pass P for execution. Make sure that passes required by
492 /// P are run before P is run. Update analysis info maintained by
493 /// the manager. Remove dead passes. This is a recursive function.
494 void PMTopLevelManager::schedulePass(Pass *P) {
496 // TODO : Allocate function manager for this pass, other wise required set
497 // may be inserted into previous function manager
499 // Give pass a chance to prepare the stage.
500 P->preparePassManager(activeStack);
502 // If P is an analysis pass and it is available then do not
503 // generate the analysis again. Stale analysis info should not be
504 // available at this point.
505 if (P->getPassInfo() &&
506 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
511 AnalysisUsage *AnUsage = findAnalysisUsage(P);
513 bool checkAnalysis = true;
514 while (checkAnalysis) {
515 checkAnalysis = false;
517 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
518 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
519 E = RequiredSet.end(); I != E; ++I) {
521 Pass *AnalysisPass = findAnalysisPass(*I);
523 AnalysisPass = (*I)->createPass();
524 if (P->getPotentialPassManagerType () ==
525 AnalysisPass->getPotentialPassManagerType())
526 // Schedule analysis pass that is managed by the same pass manager.
527 schedulePass(AnalysisPass);
528 else if (P->getPotentialPassManagerType () >
529 AnalysisPass->getPotentialPassManagerType()) {
530 // Schedule analysis pass that is managed by a new manager.
531 schedulePass(AnalysisPass);
532 // Recheck analysis passes to ensure that required analysises that
533 // are already checked are still available.
534 checkAnalysis = true;
537 // Do not schedule this analysis. Lower level analsyis
538 // passes are run on the fly.
544 // Now all required passes are available.
548 /// Find the pass that implements Analysis AID. Search immutable
549 /// passes and all pass managers. If desired pass is not found
550 /// then return NULL.
551 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
554 // Check pass managers
555 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
556 E = PassManagers.end(); P == NULL && I != E; ++I) {
557 PMDataManager *PMD = *I;
558 P = PMD->findAnalysisPass(AID, false);
561 // Check other pass managers
562 for (SmallVector<PMDataManager *, 8>::iterator
563 I = IndirectPassManagers.begin(),
564 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
565 P = (*I)->findAnalysisPass(AID, false);
567 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
568 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
569 const PassInfo *PI = (*I)->getPassInfo();
573 // If Pass not found then check the interfaces implemented by Immutable Pass
575 const std::vector<const PassInfo*> &ImmPI =
576 PI->getInterfacesImplemented();
577 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
585 // Print passes managed by this top level manager.
586 void PMTopLevelManager::dumpPasses() const {
588 if (PassDebugging < Structure)
591 // Print out the immutable passes
592 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
593 ImmutablePasses[i]->dumpPassStructure(0);
596 // Every class that derives from PMDataManager also derives from Pass
597 // (sometimes indirectly), but there's no inheritance relationship
598 // between PMDataManager and Pass, so we have to getAsPass to get
599 // from a PMDataManager* to a Pass*.
600 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
601 E = PassManagers.end(); I != E; ++I)
602 (*I)->getAsPass()->dumpPassStructure(1);
605 void PMTopLevelManager::dumpArguments() const {
607 if (PassDebugging < Arguments)
610 dbgs() << "Pass Arguments: ";
611 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
612 E = PassManagers.end(); I != E; ++I)
613 (*I)->dumpPassArguments();
617 void PMTopLevelManager::initializeAllAnalysisInfo() {
618 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
619 E = PassManagers.end(); I != E; ++I)
620 (*I)->initializeAnalysisInfo();
622 // Initailize other pass managers
623 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
624 E = IndirectPassManagers.end(); I != E; ++I)
625 (*I)->initializeAnalysisInfo();
627 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
628 DME = LastUser.end(); DMI != DME; ++DMI) {
629 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
630 InversedLastUser.find(DMI->second);
631 if (InvDMI != InversedLastUser.end()) {
632 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
633 L.insert(DMI->first);
635 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
636 InversedLastUser[DMI->second] = L;
642 PMTopLevelManager::~PMTopLevelManager() {
643 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
644 E = PassManagers.end(); I != E; ++I)
647 for (SmallVector<ImmutablePass *, 8>::iterator
648 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
651 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
652 DME = AnUsageMap.end(); DMI != DME; ++DMI)
656 //===----------------------------------------------------------------------===//
657 // PMDataManager implementation
659 /// Augement AvailableAnalysis by adding analysis made available by pass P.
660 void PMDataManager::recordAvailableAnalysis(Pass *P) {
661 const PassInfo *PI = P->getPassInfo();
664 AvailableAnalysis[PI] = P;
666 //This pass is the current implementation of all of the interfaces it
667 //implements as well.
668 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
669 for (unsigned i = 0, e = II.size(); i != e; ++i)
670 AvailableAnalysis[II[i]] = P;
673 // Return true if P preserves high level analysis used by other
674 // passes managed by this manager
675 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
676 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
677 if (AnUsage->getPreservesAll())
680 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
681 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
682 E = HigherLevelAnalysis.end(); I != E; ++I) {
684 if (P1->getAsImmutablePass() == 0 &&
685 std::find(PreservedSet.begin(), PreservedSet.end(),
686 P1->getPassInfo()) ==
694 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
695 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
696 // Don't do this unless assertions are enabled.
700 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
701 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
703 // Verify preserved analysis
704 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
705 E = PreservedSet.end(); I != E; ++I) {
707 if (Pass *AP = findAnalysisPass(AID, true)) {
710 if (TheTimeInfo) T = TheTimeInfo->passStarted(AP);
711 AP->verifyAnalysis();
712 if (T) T->stopTimer();
717 /// Remove Analysis not preserved by Pass P
718 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
719 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
720 if (AnUsage->getPreservesAll())
723 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
724 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
725 E = AvailableAnalysis.end(); I != E; ) {
726 std::map<AnalysisID, Pass*>::iterator Info = I++;
727 if (Info->second->getAsImmutablePass() == 0 &&
728 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
729 PreservedSet.end()) {
730 // Remove this analysis
731 if (PassDebugging >= Details) {
732 Pass *S = Info->second;
733 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
734 dbgs() << S->getPassName() << "'\n";
736 AvailableAnalysis.erase(Info);
740 // Check inherited analysis also. If P is not preserving analysis
741 // provided by parent manager then remove it here.
742 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
744 if (!InheritedAnalysis[Index])
747 for (std::map<AnalysisID, Pass*>::iterator
748 I = InheritedAnalysis[Index]->begin(),
749 E = InheritedAnalysis[Index]->end(); I != E; ) {
750 std::map<AnalysisID, Pass *>::iterator Info = I++;
751 if (Info->second->getAsImmutablePass() == 0 &&
752 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
753 PreservedSet.end()) {
754 // Remove this analysis
755 if (PassDebugging >= Details) {
756 Pass *S = Info->second;
757 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
758 dbgs() << S->getPassName() << "'\n";
760 InheritedAnalysis[Index]->erase(Info);
766 /// Remove analysis passes that are not used any longer
767 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
768 enum PassDebuggingString DBG_STR) {
770 SmallVector<Pass *, 12> DeadPasses;
772 // If this is a on the fly manager then it does not have TPM.
776 TPM->collectLastUses(DeadPasses, P);
778 if (PassDebugging >= Details && !DeadPasses.empty()) {
779 dbgs() << " -*- '" << P->getPassName();
780 dbgs() << "' is the last user of following pass instances.";
781 dbgs() << " Free these instances\n";
784 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
785 E = DeadPasses.end(); I != E; ++I)
786 freePass(*I, Msg, DBG_STR);
789 void PMDataManager::freePass(Pass *P, StringRef Msg,
790 enum PassDebuggingString DBG_STR) {
791 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
794 // If the pass crashes releasing memory, remember this.
795 PassManagerPrettyStackEntry X(P);
797 Timer *T = StartPassTimer(P);
802 if (const PassInfo *PI = P->getPassInfo()) {
803 // Remove the pass itself (if it is not already removed).
804 AvailableAnalysis.erase(PI);
806 // Remove all interfaces this pass implements, for which it is also
807 // listed as the available implementation.
808 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
809 for (unsigned i = 0, e = II.size(); i != e; ++i) {
810 std::map<AnalysisID, Pass*>::iterator Pos =
811 AvailableAnalysis.find(II[i]);
812 if (Pos != AvailableAnalysis.end() && Pos->second == P)
813 AvailableAnalysis.erase(Pos);
818 /// Add pass P into the PassVector. Update
819 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
820 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
821 // This manager is going to manage pass P. Set up analysis resolver
823 AnalysisResolver *AR = new AnalysisResolver(*this);
826 // If a FunctionPass F is the last user of ModulePass info M
827 // then the F's manager, not F, records itself as a last user of M.
828 SmallVector<Pass *, 12> TransferLastUses;
830 if (!ProcessAnalysis) {
832 PassVector.push_back(P);
836 // At the moment, this pass is the last user of all required passes.
837 SmallVector<Pass *, 12> LastUses;
838 SmallVector<Pass *, 8> RequiredPasses;
839 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
841 unsigned PDepth = this->getDepth();
843 collectRequiredAnalysis(RequiredPasses,
844 ReqAnalysisNotAvailable, P);
845 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
846 E = RequiredPasses.end(); I != E; ++I) {
847 Pass *PRequired = *I;
850 assert(PRequired->getResolver() && "Analysis Resolver is not set");
851 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
852 RDepth = DM.getDepth();
854 if (PDepth == RDepth)
855 LastUses.push_back(PRequired);
856 else if (PDepth > RDepth) {
857 // Let the parent claim responsibility of last use
858 TransferLastUses.push_back(PRequired);
859 // Keep track of higher level analysis used by this manager.
860 HigherLevelAnalysis.push_back(PRequired);
862 llvm_unreachable("Unable to accomodate Required Pass");
865 // Set P as P's last user until someone starts using P.
866 // However, if P is a Pass Manager then it does not need
867 // to record its last user.
868 if (P->getAsPMDataManager() == 0)
869 LastUses.push_back(P);
870 TPM->setLastUser(LastUses, P);
872 if (!TransferLastUses.empty()) {
873 Pass *My_PM = getAsPass();
874 TPM->setLastUser(TransferLastUses, My_PM);
875 TransferLastUses.clear();
878 // Now, take care of required analysises that are not available.
879 for (SmallVector<AnalysisID, 8>::iterator
880 I = ReqAnalysisNotAvailable.begin(),
881 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
882 Pass *AnalysisPass = (*I)->createPass();
883 this->addLowerLevelRequiredPass(P, AnalysisPass);
886 // Take a note of analysis required and made available by this pass.
887 // Remove the analysis not preserved by this pass
888 removeNotPreservedAnalysis(P);
889 recordAvailableAnalysis(P);
892 PassVector.push_back(P);
896 /// Populate RP with analysis pass that are required by
897 /// pass P and are available. Populate RP_NotAvail with analysis
898 /// pass that are required by pass P but are not available.
899 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
900 SmallVector<AnalysisID, 8> &RP_NotAvail,
902 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
903 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
904 for (AnalysisUsage::VectorType::const_iterator
905 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
906 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
907 RP.push_back(AnalysisPass);
909 RP_NotAvail.push_back(*I);
912 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
913 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
914 E = IDs.end(); I != E; ++I) {
915 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
916 RP.push_back(AnalysisPass);
918 RP_NotAvail.push_back(*I);
922 // All Required analyses should be available to the pass as it runs! Here
923 // we fill in the AnalysisImpls member of the pass so that it can
924 // successfully use the getAnalysis() method to retrieve the
925 // implementations it needs.
927 void PMDataManager::initializeAnalysisImpl(Pass *P) {
928 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
930 for (AnalysisUsage::VectorType::const_iterator
931 I = AnUsage->getRequiredSet().begin(),
932 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
933 Pass *Impl = findAnalysisPass(*I, true);
935 // This may be analysis pass that is initialized on the fly.
936 // If that is not the case then it will raise an assert when it is used.
938 AnalysisResolver *AR = P->getResolver();
939 assert(AR && "Analysis Resolver is not set");
940 AR->addAnalysisImplsPair(*I, Impl);
944 /// Find the pass that implements Analysis AID. If desired pass is not found
945 /// then return NULL.
946 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
948 // Check if AvailableAnalysis map has one entry.
949 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
951 if (I != AvailableAnalysis.end())
954 // Search Parents through TopLevelManager
956 return TPM->findAnalysisPass(AID);
961 // Print list of passes that are last used by P.
962 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
964 SmallVector<Pass *, 12> LUses;
966 // If this is a on the fly manager then it does not have TPM.
970 TPM->collectLastUses(LUses, P);
972 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
973 E = LUses.end(); I != E; ++I) {
974 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
975 (*I)->dumpPassStructure(0);
979 void PMDataManager::dumpPassArguments() const {
980 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
981 E = PassVector.end(); I != E; ++I) {
982 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
983 PMD->dumpPassArguments();
985 if (const PassInfo *PI = (*I)->getPassInfo())
986 if (!PI->isAnalysisGroup())
987 dbgs() << " -" << PI->getPassArgument();
991 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
992 enum PassDebuggingString S2,
994 if (PassDebugging < Executions)
996 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
999 dbgs() << "Executing Pass '" << P->getPassName();
1001 case MODIFICATION_MSG:
1002 dbgs() << "Made Modification '" << P->getPassName();
1005 dbgs() << " Freeing Pass '" << P->getPassName();
1011 case ON_BASICBLOCK_MSG:
1012 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1014 case ON_FUNCTION_MSG:
1015 dbgs() << "' on Function '" << Msg << "'...\n";
1018 dbgs() << "' on Module '" << Msg << "'...\n";
1021 dbgs() << "' on Loop '" << Msg << "'...\n";
1024 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1031 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1032 if (PassDebugging < Details)
1035 AnalysisUsage analysisUsage;
1036 P->getAnalysisUsage(analysisUsage);
1037 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1040 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1041 if (PassDebugging < Details)
1044 AnalysisUsage analysisUsage;
1045 P->getAnalysisUsage(analysisUsage);
1046 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1049 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1050 const AnalysisUsage::VectorType &Set) const {
1051 assert(PassDebugging >= Details);
1054 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1055 for (unsigned i = 0; i != Set.size(); ++i) {
1056 if (i) dbgs() << ',';
1057 dbgs() << ' ' << Set[i]->getPassName();
1062 /// Add RequiredPass into list of lower level passes required by pass P.
1063 /// RequiredPass is run on the fly by Pass Manager when P requests it
1064 /// through getAnalysis interface.
1065 /// This should be handled by specific pass manager.
1066 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1068 TPM->dumpArguments();
1072 // Module Level pass may required Function Level analysis info
1073 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1074 // to provide this on demand. In that case, in Pass manager terminology,
1075 // module level pass is requiring lower level analysis info managed by
1076 // lower level pass manager.
1078 // When Pass manager is not able to order required analysis info, Pass manager
1079 // checks whether any lower level manager will be able to provide this
1080 // analysis info on demand or not.
1082 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1083 dbgs() << "' required by '" << P->getPassName() << "'\n";
1085 llvm_unreachable("Unable to schedule pass");
1089 PMDataManager::~PMDataManager() {
1090 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1091 E = PassVector.end(); I != E; ++I)
1095 //===----------------------------------------------------------------------===//
1096 // NOTE: Is this the right place to define this method ?
1097 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1098 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1099 return PM.findAnalysisPass(ID, dir);
1102 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1104 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1107 //===----------------------------------------------------------------------===//
1108 // BBPassManager implementation
1110 /// Execute all of the passes scheduled for execution by invoking
1111 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1112 /// the function, and if so, return true.
1113 bool BBPassManager::runOnFunction(Function &F) {
1114 if (F.isDeclaration())
1117 bool Changed = doInitialization(F);
1119 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1120 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1121 BasicBlockPass *BP = getContainedPass(Index);
1123 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1124 dumpRequiredSet(BP);
1126 initializeAnalysisImpl(BP);
1129 // If the pass crashes, remember this.
1130 PassManagerPrettyStackEntry X(BP, *I);
1132 Timer *T = StartPassTimer(BP);
1133 Changed |= BP->runOnBasicBlock(*I);
1134 StopPassTimer(BP, T);
1138 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1140 dumpPreservedSet(BP);
1142 verifyPreservedAnalysis(BP);
1143 removeNotPreservedAnalysis(BP);
1144 recordAvailableAnalysis(BP);
1145 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1148 return doFinalization(F) || Changed;
1151 // Implement doInitialization and doFinalization
1152 bool BBPassManager::doInitialization(Module &M) {
1153 bool Changed = false;
1155 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1156 Changed |= getContainedPass(Index)->doInitialization(M);
1161 bool BBPassManager::doFinalization(Module &M) {
1162 bool Changed = false;
1164 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1165 Changed |= getContainedPass(Index)->doFinalization(M);
1170 bool BBPassManager::doInitialization(Function &F) {
1171 bool Changed = false;
1173 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1174 BasicBlockPass *BP = getContainedPass(Index);
1175 Changed |= BP->doInitialization(F);
1181 bool BBPassManager::doFinalization(Function &F) {
1182 bool Changed = false;
1184 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1185 BasicBlockPass *BP = getContainedPass(Index);
1186 Changed |= BP->doFinalization(F);
1193 //===----------------------------------------------------------------------===//
1194 // FunctionPassManager implementation
1196 /// Create new Function pass manager
1197 FunctionPassManager::FunctionPassManager(ModuleProvider *P) {
1198 FPM = new FunctionPassManagerImpl(0);
1199 // FPM is the top level manager.
1200 FPM->setTopLevelManager(FPM);
1202 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1203 FPM->setResolver(AR);
1208 FunctionPassManager::~FunctionPassManager() {
1212 /// add - Add a pass to the queue of passes to run. This passes
1213 /// ownership of the Pass to the PassManager. When the
1214 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1215 /// there is no need to delete the pass. (TODO delete passes.)
1216 /// This implies that all passes MUST be allocated with 'new'.
1217 void FunctionPassManager::add(Pass *P) {
1221 /// run - Execute all of the passes scheduled for execution. Keep
1222 /// track of whether any of the passes modifies the function, and if
1223 /// so, return true.
1225 bool FunctionPassManager::run(Function &F) {
1227 if (MP->materializeFunction(&F, &errstr)) {
1228 llvm_report_error("Error reading bitcode file: " + errstr);
1234 /// doInitialization - Run all of the initializers for the function passes.
1236 bool FunctionPassManager::doInitialization() {
1237 return FPM->doInitialization(*MP->getModule());
1240 /// doFinalization - Run all of the finalizers for the function passes.
1242 bool FunctionPassManager::doFinalization() {
1243 return FPM->doFinalization(*MP->getModule());
1246 //===----------------------------------------------------------------------===//
1247 // FunctionPassManagerImpl implementation
1249 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1250 bool Changed = false;
1255 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1256 Changed |= getContainedManager(Index)->doInitialization(M);
1261 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1262 bool Changed = false;
1264 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1265 Changed |= getContainedManager(Index)->doFinalization(M);
1270 /// cleanup - After running all passes, clean up pass manager cache.
1271 void FPPassManager::cleanup() {
1272 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1273 FunctionPass *FP = getContainedPass(Index);
1274 AnalysisResolver *AR = FP->getResolver();
1275 assert(AR && "Analysis Resolver is not set");
1276 AR->clearAnalysisImpls();
1280 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1283 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1284 FPPassManager *FPPM = getContainedManager(Index);
1285 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1286 FPPM->getContainedPass(Index)->releaseMemory();
1292 // Execute all the passes managed by this top level manager.
1293 // Return true if any function is modified by a pass.
1294 bool FunctionPassManagerImpl::run(Function &F) {
1295 bool Changed = false;
1296 TimingInfo::createTheTimeInfo();
1298 initializeAllAnalysisInfo();
1299 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1300 Changed |= getContainedManager(Index)->runOnFunction(F);
1302 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1303 getContainedManager(Index)->cleanup();
1309 //===----------------------------------------------------------------------===//
1310 // FPPassManager implementation
1312 char FPPassManager::ID = 0;
1313 /// Print passes managed by this manager
1314 void FPPassManager::dumpPassStructure(unsigned Offset) {
1315 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1316 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1317 FunctionPass *FP = getContainedPass(Index);
1318 FP->dumpPassStructure(Offset + 1);
1319 dumpLastUses(FP, Offset+1);
1324 /// Execute all of the passes scheduled for execution by invoking
1325 /// runOnFunction method. Keep track of whether any of the passes modifies
1326 /// the function, and if so, return true.
1327 bool FPPassManager::runOnFunction(Function &F) {
1328 if (F.isDeclaration())
1331 bool Changed = false;
1333 // Collect inherited analysis from Module level pass manager.
1334 populateInheritedAnalysis(TPM->activeStack);
1336 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1337 FunctionPass *FP = getContainedPass(Index);
1339 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1340 dumpRequiredSet(FP);
1342 initializeAnalysisImpl(FP);
1345 PassManagerPrettyStackEntry X(FP, F);
1347 Timer *T = StartPassTimer(FP);
1348 Changed |= FP->runOnFunction(F);
1349 StopPassTimer(FP, T);
1353 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1354 dumpPreservedSet(FP);
1356 verifyPreservedAnalysis(FP);
1357 removeNotPreservedAnalysis(FP);
1358 recordAvailableAnalysis(FP);
1359 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1364 bool FPPassManager::runOnModule(Module &M) {
1365 bool Changed = doInitialization(M);
1367 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1370 return doFinalization(M) || Changed;
1373 bool FPPassManager::doInitialization(Module &M) {
1374 bool Changed = false;
1376 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1377 Changed |= getContainedPass(Index)->doInitialization(M);
1382 bool FPPassManager::doFinalization(Module &M) {
1383 bool Changed = false;
1385 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1386 Changed |= getContainedPass(Index)->doFinalization(M);
1391 //===----------------------------------------------------------------------===//
1392 // MPPassManager implementation
1394 /// Execute all of the passes scheduled for execution by invoking
1395 /// runOnModule method. Keep track of whether any of the passes modifies
1396 /// the module, and if so, return true.
1398 MPPassManager::runOnModule(Module &M) {
1399 bool Changed = false;
1401 // Initialize on-the-fly passes
1402 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1403 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1405 FunctionPassManagerImpl *FPP = I->second;
1406 Changed |= FPP->doInitialization(M);
1409 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1410 ModulePass *MP = getContainedPass(Index);
1412 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1413 dumpRequiredSet(MP);
1415 initializeAnalysisImpl(MP);
1418 PassManagerPrettyStackEntry X(MP, M);
1419 Timer *T = StartPassTimer(MP);
1420 Changed |= MP->runOnModule(M);
1421 StopPassTimer(MP, T);
1425 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1426 M.getModuleIdentifier());
1427 dumpPreservedSet(MP);
1429 verifyPreservedAnalysis(MP);
1430 removeNotPreservedAnalysis(MP);
1431 recordAvailableAnalysis(MP);
1432 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1435 // Finalize on-the-fly passes
1436 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1437 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1439 FunctionPassManagerImpl *FPP = I->second;
1440 // We don't know when is the last time an on-the-fly pass is run,
1441 // so we need to releaseMemory / finalize here
1442 FPP->releaseMemoryOnTheFly();
1443 Changed |= FPP->doFinalization(M);
1448 /// Add RequiredPass into list of lower level passes required by pass P.
1449 /// RequiredPass is run on the fly by Pass Manager when P requests it
1450 /// through getAnalysis interface.
1451 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1452 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1453 "Unable to handle Pass that requires lower level Analysis pass");
1454 assert((P->getPotentialPassManagerType() <
1455 RequiredPass->getPotentialPassManagerType()) &&
1456 "Unable to handle Pass that requires lower level Analysis pass");
1458 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1460 FPP = new FunctionPassManagerImpl(0);
1461 // FPP is the top level manager.
1462 FPP->setTopLevelManager(FPP);
1464 OnTheFlyManagers[P] = FPP;
1466 FPP->add(RequiredPass);
1468 // Register P as the last user of RequiredPass.
1469 SmallVector<Pass *, 12> LU;
1470 LU.push_back(RequiredPass);
1471 FPP->setLastUser(LU, P);
1474 /// Return function pass corresponding to PassInfo PI, that is
1475 /// required by module pass MP. Instantiate analysis pass, by using
1476 /// its runOnFunction() for function F.
1477 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1478 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1479 assert(FPP && "Unable to find on the fly pass");
1481 FPP->releaseMemoryOnTheFly();
1483 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1487 //===----------------------------------------------------------------------===//
1488 // PassManagerImpl implementation
1490 /// run - Execute all of the passes scheduled for execution. Keep track of
1491 /// whether any of the passes modifies the module, and if so, return true.
1492 bool PassManagerImpl::run(Module &M) {
1493 bool Changed = false;
1494 TimingInfo::createTheTimeInfo();
1499 initializeAllAnalysisInfo();
1500 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1501 Changed |= getContainedManager(Index)->runOnModule(M);
1505 //===----------------------------------------------------------------------===//
1506 // PassManager implementation
1508 /// Create new pass manager
1509 PassManager::PassManager() {
1510 PM = new PassManagerImpl(0);
1511 // PM is the top level manager
1512 PM->setTopLevelManager(PM);
1515 PassManager::~PassManager() {
1519 /// add - Add a pass to the queue of passes to run. This passes ownership of
1520 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1521 /// will be destroyed as well, so there is no need to delete the pass. This
1522 /// implies that all passes MUST be allocated with 'new'.
1523 void PassManager::add(Pass *P) {
1527 /// run - Execute all of the passes scheduled for execution. Keep track of
1528 /// whether any of the passes modifies the module, and if so, return true.
1529 bool PassManager::run(Module &M) {
1533 //===----------------------------------------------------------------------===//
1534 // TimingInfo Class - This class is used to calculate information about the
1535 // amount of time each pass takes to execute. This only happens with
1536 // -time-passes is enabled on the command line.
1538 bool llvm::TimePassesIsEnabled = false;
1539 static cl::opt<bool,true>
1540 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1541 cl::desc("Time each pass, printing elapsed time for each on exit"));
1543 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1544 // a non null value (if the -time-passes option is enabled) or it leaves it
1545 // null. It may be called multiple times.
1546 void TimingInfo::createTheTimeInfo() {
1547 if (!TimePassesIsEnabled || TheTimeInfo) return;
1549 // Constructed the first time this is called, iff -time-passes is enabled.
1550 // This guarantees that the object will be constructed before static globals,
1551 // thus it will be destroyed before them.
1552 static ManagedStatic<TimingInfo> TTI;
1553 TheTimeInfo = &*TTI;
1556 /// If TimingInfo is enabled then start pass timer.
1557 Timer *llvm::StartPassTimer(Pass *P) {
1559 return TheTimeInfo->passStarted(P);
1563 /// If TimingInfo is enabled then stop pass timer.
1564 void llvm::StopPassTimer(Pass *P, Timer *T) {
1565 if (T) T->stopTimer();
1568 //===----------------------------------------------------------------------===//
1569 // PMStack implementation
1572 // Pop Pass Manager from the stack and clear its analysis info.
1573 void PMStack::pop() {
1575 PMDataManager *Top = this->top();
1576 Top->initializeAnalysisInfo();
1581 // Push PM on the stack and set its top level manager.
1582 void PMStack::push(PMDataManager *PM) {
1583 assert(PM && "Unable to push. Pass Manager expected");
1585 if (!this->empty()) {
1586 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1588 assert(TPM && "Unable to find top level manager");
1589 TPM->addIndirectPassManager(PM);
1590 PM->setTopLevelManager(TPM);
1596 // Dump content of the pass manager stack.
1597 void PMStack::dump() {
1598 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1599 E = S.end(); I != E; ++I)
1600 printf("%s ", (*I)->getAsPass()->getPassName());
1606 /// Find appropriate Module Pass Manager in the PM Stack and
1607 /// add self into that manager.
1608 void ModulePass::assignPassManager(PMStack &PMS,
1609 PassManagerType PreferredType) {
1610 // Find Module Pass Manager
1611 while(!PMS.empty()) {
1612 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1613 if (TopPMType == PreferredType)
1614 break; // We found desired pass manager
1615 else if (TopPMType > PMT_ModulePassManager)
1616 PMS.pop(); // Pop children pass managers
1620 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1621 PMS.top()->add(this);
1624 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1625 /// in the PM Stack and add self into that manager.
1626 void FunctionPass::assignPassManager(PMStack &PMS,
1627 PassManagerType PreferredType) {
1629 // Find Module Pass Manager
1630 while (!PMS.empty()) {
1631 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1637 // Create new Function Pass Manager if needed.
1639 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1640 FPP = (FPPassManager *)PMS.top();
1642 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1643 PMDataManager *PMD = PMS.top();
1645 // [1] Create new Function Pass Manager
1646 FPP = new FPPassManager(PMD->getDepth() + 1);
1647 FPP->populateInheritedAnalysis(PMS);
1649 // [2] Set up new manager's top level manager
1650 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1651 TPM->addIndirectPassManager(FPP);
1653 // [3] Assign manager to manage this new manager. This may create
1654 // and push new managers into PMS
1655 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1657 // [4] Push new manager into PMS
1661 // Assign FPP as the manager of this pass.
1665 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1666 /// in the PM Stack and add self into that manager.
1667 void BasicBlockPass::assignPassManager(PMStack &PMS,
1668 PassManagerType PreferredType) {
1671 // Basic Pass Manager is a leaf pass manager. It does not handle
1672 // any other pass manager.
1674 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1675 BBP = (BBPassManager *)PMS.top();
1677 // If leaf manager is not Basic Block Pass manager then create new
1678 // basic Block Pass manager.
1679 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1680 PMDataManager *PMD = PMS.top();
1682 // [1] Create new Basic Block Manager
1683 BBP = new BBPassManager(PMD->getDepth() + 1);
1685 // [2] Set up new manager's top level manager
1686 // Basic Block Pass Manager does not live by itself
1687 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1688 TPM->addIndirectPassManager(BBP);
1690 // [3] Assign manager to manage this new manager. This may create
1691 // and push new managers into PMS
1692 BBP->assignPassManager(PMS);
1694 // [4] Push new manager into PMS
1698 // Assign BBP as the manager of this pass.
1702 PassManagerBase::~PassManagerBase() {}
1704 /*===-- C Bindings --------------------------------------------------------===*/
1706 LLVMPassManagerRef LLVMCreatePassManager() {
1707 return wrap(new PassManager());
1710 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1711 return wrap(new FunctionPassManager(unwrap(P)));
1714 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1715 return unwrap<PassManager>(PM)->run(*unwrap(M));
1718 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1719 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1722 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1723 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1726 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1727 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1730 void LLVMDisposePassManager(LLVMPassManagerRef PM) {