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/Support/ErrorHandling.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Mutex.h"
25 #include "llvm/System/Threading.h"
26 #include "llvm-c/Core.h"
32 // See PassManagers.h for Pass Manager infrastructure overview.
36 //===----------------------------------------------------------------------===//
37 // Pass debugging information. Often it is useful to find out what pass is
38 // running when a crash occurs in a utility. When this library is compiled with
39 // debugging on, a command line option (--debug-pass) is enabled that causes the
40 // pass name to be printed before it executes.
43 // Different debug levels that can be enabled...
45 None, Arguments, Structure, Executions, Details
48 static cl::opt<enum PassDebugLevel>
49 PassDebugging("debug-pass", cl::Hidden,
50 cl::desc("Print PassManager debugging information"),
52 clEnumVal(None , "disable debug output"),
53 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
54 clEnumVal(Structure , "print pass structure before run()"),
55 clEnumVal(Executions, "print pass name before it is executed"),
56 clEnumVal(Details , "print pass details when it is executed"),
58 } // End of llvm namespace
60 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
61 /// or higher is specified.
62 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
63 return PassDebugging >= Executions;
69 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
71 OS << "Releasing pass '";
73 OS << "Running pass '";
75 OS << P->getPassName() << "'";
78 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
89 else if (isa<BasicBlock>(V))
95 WriteAsOperand(OS, V, /*PrintTy=*/false, M);
102 //===----------------------------------------------------------------------===//
105 /// BBPassManager manages BasicBlockPass. It batches all the
106 /// pass together and sequence them to process one basic block before
107 /// processing next basic block.
108 class BBPassManager : public PMDataManager, public FunctionPass {
112 explicit BBPassManager(int Depth)
113 : PMDataManager(Depth), FunctionPass(&ID) {}
115 /// Execute all of the passes scheduled for execution. Keep track of
116 /// whether any of the passes modifies the function, and if so, return true.
117 bool runOnFunction(Function &F);
119 /// Pass Manager itself does not invalidate any analysis info.
120 void getAnalysisUsage(AnalysisUsage &Info) const {
121 Info.setPreservesAll();
124 bool doInitialization(Module &M);
125 bool doInitialization(Function &F);
126 bool doFinalization(Module &M);
127 bool doFinalization(Function &F);
129 virtual PMDataManager *getAsPMDataManager() { return this; }
130 virtual Pass *getAsPass() { return this; }
132 virtual const char *getPassName() const {
133 return "BasicBlock Pass Manager";
136 // Print passes managed by this manager
137 void dumpPassStructure(unsigned Offset) {
138 llvm::dbgs() << std::string(Offset*2, ' ') << "BasicBlockPass Manager\n";
139 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
140 BasicBlockPass *BP = getContainedPass(Index);
141 BP->dumpPassStructure(Offset + 1);
142 dumpLastUses(BP, Offset+1);
146 BasicBlockPass *getContainedPass(unsigned N) {
147 assert(N < PassVector.size() && "Pass number out of range!");
148 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
152 virtual PassManagerType getPassManagerType() const {
153 return PMT_BasicBlockPassManager;
157 char BBPassManager::ID = 0;
162 //===----------------------------------------------------------------------===//
163 // FunctionPassManagerImpl
165 /// FunctionPassManagerImpl manages FPPassManagers
166 class FunctionPassManagerImpl : public Pass,
167 public PMDataManager,
168 public PMTopLevelManager {
173 explicit FunctionPassManagerImpl(int Depth) :
174 Pass(PT_PassManager, &ID), PMDataManager(Depth),
175 PMTopLevelManager(TLM_Function), wasRun(false) { }
177 /// add - Add a pass to the queue of passes to run. This passes ownership of
178 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
179 /// will be destroyed as well, so there is no need to delete the pass. This
180 /// implies that all passes MUST be allocated with 'new'.
185 // Prepare for running an on the fly pass, freeing memory if needed
186 // from a previous run.
187 void releaseMemoryOnTheFly();
189 /// run - Execute all of the passes scheduled for execution. Keep track of
190 /// whether any of the passes modifies the module, and if so, return true.
191 bool run(Function &F);
193 /// doInitialization - Run all of the initializers for the function passes.
195 bool doInitialization(Module &M);
197 /// doFinalization - Run all of the finalizers for the function passes.
199 bool doFinalization(Module &M);
202 virtual PMDataManager *getAsPMDataManager() { return this; }
203 virtual Pass *getAsPass() { return this; }
205 /// Pass Manager itself does not invalidate any analysis info.
206 void getAnalysisUsage(AnalysisUsage &Info) const {
207 Info.setPreservesAll();
210 inline void addTopLevelPass(Pass *P) {
211 if (ImmutablePass *IP = P->getAsImmutablePass()) {
212 // P is a immutable pass and it will be managed by this
213 // top level manager. Set up analysis resolver to connect them.
214 AnalysisResolver *AR = new AnalysisResolver(*this);
216 initializeAnalysisImpl(P);
217 addImmutablePass(IP);
218 recordAvailableAnalysis(IP);
220 P->assignPassManager(activeStack);
225 FPPassManager *getContainedManager(unsigned N) {
226 assert(N < PassManagers.size() && "Pass number out of range!");
227 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
232 char FunctionPassManagerImpl::ID = 0;
233 //===----------------------------------------------------------------------===//
236 /// MPPassManager manages ModulePasses and function pass managers.
237 /// It batches all Module passes and function pass managers together and
238 /// sequences them to process one module.
239 class MPPassManager : public Pass, public PMDataManager {
242 explicit MPPassManager(int Depth) :
243 Pass(PT_PassManager, &ID), PMDataManager(Depth) { }
245 // Delete on the fly managers.
246 virtual ~MPPassManager() {
247 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
248 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
250 FunctionPassManagerImpl *FPP = I->second;
255 /// run - Execute all of the passes scheduled for execution. Keep track of
256 /// whether any of the passes modifies the module, and if so, return true.
257 bool runOnModule(Module &M);
259 /// Pass Manager itself does not invalidate any analysis info.
260 void getAnalysisUsage(AnalysisUsage &Info) const {
261 Info.setPreservesAll();
264 /// Add RequiredPass into list of lower level passes required by pass P.
265 /// RequiredPass is run on the fly by Pass Manager when P requests it
266 /// through getAnalysis interface.
267 virtual void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass);
269 /// Return function pass corresponding to PassInfo PI, that is
270 /// required by module pass MP. Instantiate analysis pass, by using
271 /// its runOnFunction() for function F.
272 virtual Pass* getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F);
274 virtual const char *getPassName() const {
275 return "Module Pass Manager";
278 virtual PMDataManager *getAsPMDataManager() { return this; }
279 virtual Pass *getAsPass() { return this; }
281 // Print passes managed by this manager
282 void dumpPassStructure(unsigned Offset) {
283 llvm::dbgs() << std::string(Offset*2, ' ') << "ModulePass Manager\n";
284 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
285 ModulePass *MP = getContainedPass(Index);
286 MP->dumpPassStructure(Offset + 1);
287 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
288 OnTheFlyManagers.find(MP);
289 if (I != OnTheFlyManagers.end())
290 I->second->dumpPassStructure(Offset + 2);
291 dumpLastUses(MP, Offset+1);
295 ModulePass *getContainedPass(unsigned N) {
296 assert(N < PassVector.size() && "Pass number out of range!");
297 return static_cast<ModulePass *>(PassVector[N]);
300 virtual PassManagerType getPassManagerType() const {
301 return PMT_ModulePassManager;
305 /// Collection of on the fly FPPassManagers. These managers manage
306 /// function passes that are required by module passes.
307 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
310 char MPPassManager::ID = 0;
311 //===----------------------------------------------------------------------===//
315 /// PassManagerImpl manages MPPassManagers
316 class PassManagerImpl : public Pass,
317 public PMDataManager,
318 public PMTopLevelManager {
322 explicit PassManagerImpl(int Depth) :
323 Pass(PT_PassManager, &ID), PMDataManager(Depth),
324 PMTopLevelManager(TLM_Pass) { }
326 /// add - Add a pass to the queue of passes to run. This passes ownership of
327 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
328 /// will be destroyed as well, so there is no need to delete the pass. This
329 /// implies that all passes MUST be allocated with 'new'.
334 /// run - Execute all of the passes scheduled for execution. Keep track of
335 /// whether any of the passes modifies the module, and if so, return true.
338 /// Pass Manager itself does not invalidate any analysis info.
339 void getAnalysisUsage(AnalysisUsage &Info) const {
340 Info.setPreservesAll();
343 inline void addTopLevelPass(Pass *P) {
344 if (ImmutablePass *IP = P->getAsImmutablePass()) {
345 // P is a immutable pass and it will be managed by this
346 // top level manager. Set up analysis resolver to connect them.
347 AnalysisResolver *AR = new AnalysisResolver(*this);
349 initializeAnalysisImpl(P);
350 addImmutablePass(IP);
351 recordAvailableAnalysis(IP);
353 P->assignPassManager(activeStack);
357 virtual PMDataManager *getAsPMDataManager() { return this; }
358 virtual Pass *getAsPass() { return this; }
360 MPPassManager *getContainedManager(unsigned N) {
361 assert(N < PassManagers.size() && "Pass number out of range!");
362 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
367 char PassManagerImpl::ID = 0;
368 } // End of llvm namespace
372 //===----------------------------------------------------------------------===//
373 /// TimingInfo Class - This class is used to calculate information about the
374 /// amount of time each pass takes to execute. This only happens when
375 /// -time-passes is enabled on the command line.
378 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
381 DenseMap<Pass*, Timer> TimingData;
385 // Use 'create' member to get this.
386 TimingInfo() : TG("... Pass execution timing report ...") {}
388 // TimingDtor - Print out information about timing information
390 // Delete all of the timers...
392 // TimerGroup is deleted next, printing the report.
395 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
396 // to a non null value (if the -time-passes option is enabled) or it leaves it
397 // null. It may be called multiple times.
398 static void createTheTimeInfo();
400 /// getPassTimer - Return the timer for the specified pass if it exists.
401 Timer *getPassTimer(Pass *P) {
402 if (P->getAsPMDataManager())
405 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
406 Timer &T = TimingData[P];
407 if (!T.isInitialized())
408 T.init(P->getPassName(), TG);
413 } // End of anon namespace
415 static TimingInfo *TheTimeInfo;
417 //===----------------------------------------------------------------------===//
418 // PMTopLevelManager implementation
420 /// Initialize top level manager. Create first pass manager.
421 PMTopLevelManager::PMTopLevelManager(enum TopLevelManagerType t) {
423 MPPassManager *MPP = new MPPassManager(1);
424 MPP->setTopLevelManager(this);
426 activeStack.push(MPP);
427 } else if (t == TLM_Function) {
428 FPPassManager *FPP = new FPPassManager(1);
429 FPP->setTopLevelManager(this);
431 activeStack.push(FPP);
435 /// Set pass P as the last user of the given analysis passes.
436 void PMTopLevelManager::setLastUser(SmallVector<Pass *, 12> &AnalysisPasses,
438 for (SmallVector<Pass *, 12>::iterator I = AnalysisPasses.begin(),
439 E = AnalysisPasses.end(); I != E; ++I) {
446 // If AP is the last user of other passes then make P last user of
448 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
449 LUE = LastUser.end(); LUI != LUE; ++LUI) {
450 if (LUI->second == AP)
451 // DenseMap iterator is not invalidated here because
452 // this is just updating exisitng entry.
453 LastUser[LUI->first] = P;
458 /// Collect passes whose last user is P
459 void PMTopLevelManager::collectLastUses(SmallVector<Pass *, 12> &LastUses,
461 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
462 InversedLastUser.find(P);
463 if (DMI == InversedLastUser.end())
466 SmallPtrSet<Pass *, 8> &LU = DMI->second;
467 for (SmallPtrSet<Pass *, 8>::iterator I = LU.begin(),
468 E = LU.end(); I != E; ++I) {
469 LastUses.push_back(*I);
474 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
475 AnalysisUsage *AnUsage = NULL;
476 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
477 if (DMI != AnUsageMap.end())
478 AnUsage = DMI->second;
480 AnUsage = new AnalysisUsage();
481 P->getAnalysisUsage(*AnUsage);
482 AnUsageMap[P] = AnUsage;
487 /// Schedule pass P for execution. Make sure that passes required by
488 /// P are run before P is run. Update analysis info maintained by
489 /// the manager. Remove dead passes. This is a recursive function.
490 void PMTopLevelManager::schedulePass(Pass *P) {
492 // TODO : Allocate function manager for this pass, other wise required set
493 // may be inserted into previous function manager
495 // Give pass a chance to prepare the stage.
496 P->preparePassManager(activeStack);
498 // If P is an analysis pass and it is available then do not
499 // generate the analysis again. Stale analysis info should not be
500 // available at this point.
501 if (P->getPassInfo() &&
502 P->getPassInfo()->isAnalysis() && findAnalysisPass(P->getPassInfo())) {
507 AnalysisUsage *AnUsage = findAnalysisUsage(P);
509 bool checkAnalysis = true;
510 while (checkAnalysis) {
511 checkAnalysis = false;
513 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
514 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
515 E = RequiredSet.end(); I != E; ++I) {
517 Pass *AnalysisPass = findAnalysisPass(*I);
519 AnalysisPass = (*I)->createPass();
520 if (P->getPotentialPassManagerType () ==
521 AnalysisPass->getPotentialPassManagerType())
522 // Schedule analysis pass that is managed by the same pass manager.
523 schedulePass(AnalysisPass);
524 else if (P->getPotentialPassManagerType () >
525 AnalysisPass->getPotentialPassManagerType()) {
526 // Schedule analysis pass that is managed by a new manager.
527 schedulePass(AnalysisPass);
528 // Recheck analysis passes to ensure that required analysises that
529 // are already checked are still available.
530 checkAnalysis = true;
533 // Do not schedule this analysis. Lower level analsyis
534 // passes are run on the fly.
540 // Now all required passes are available.
544 /// Find the pass that implements Analysis AID. Search immutable
545 /// passes and all pass managers. If desired pass is not found
546 /// then return NULL.
547 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
550 // Check pass managers
551 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
552 E = PassManagers.end(); P == NULL && I != E; ++I) {
553 PMDataManager *PMD = *I;
554 P = PMD->findAnalysisPass(AID, false);
557 // Check other pass managers
558 for (SmallVector<PMDataManager *, 8>::iterator
559 I = IndirectPassManagers.begin(),
560 E = IndirectPassManagers.end(); P == NULL && I != E; ++I)
561 P = (*I)->findAnalysisPass(AID, false);
563 for (SmallVector<ImmutablePass *, 8>::iterator I = ImmutablePasses.begin(),
564 E = ImmutablePasses.end(); P == NULL && I != E; ++I) {
565 const PassInfo *PI = (*I)->getPassInfo();
569 // If Pass not found then check the interfaces implemented by Immutable Pass
571 const std::vector<const PassInfo*> &ImmPI =
572 PI->getInterfacesImplemented();
573 if (std::find(ImmPI.begin(), ImmPI.end(), AID) != ImmPI.end())
581 // Print passes managed by this top level manager.
582 void PMTopLevelManager::dumpPasses() const {
584 if (PassDebugging < Structure)
587 // Print out the immutable passes
588 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
589 ImmutablePasses[i]->dumpPassStructure(0);
592 // Every class that derives from PMDataManager also derives from Pass
593 // (sometimes indirectly), but there's no inheritance relationship
594 // between PMDataManager and Pass, so we have to getAsPass to get
595 // from a PMDataManager* to a Pass*.
596 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
597 E = PassManagers.end(); I != E; ++I)
598 (*I)->getAsPass()->dumpPassStructure(1);
601 void PMTopLevelManager::dumpArguments() const {
603 if (PassDebugging < Arguments)
606 dbgs() << "Pass Arguments: ";
607 for (SmallVector<PMDataManager *, 8>::const_iterator I = PassManagers.begin(),
608 E = PassManagers.end(); I != E; ++I)
609 (*I)->dumpPassArguments();
613 void PMTopLevelManager::initializeAllAnalysisInfo() {
614 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
615 E = PassManagers.end(); I != E; ++I)
616 (*I)->initializeAnalysisInfo();
618 // Initailize other pass managers
619 for (SmallVector<PMDataManager *, 8>::iterator I = IndirectPassManagers.begin(),
620 E = IndirectPassManagers.end(); I != E; ++I)
621 (*I)->initializeAnalysisInfo();
623 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
624 DME = LastUser.end(); DMI != DME; ++DMI) {
625 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
626 InversedLastUser.find(DMI->second);
627 if (InvDMI != InversedLastUser.end()) {
628 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
629 L.insert(DMI->first);
631 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
632 InversedLastUser[DMI->second] = L;
638 PMTopLevelManager::~PMTopLevelManager() {
639 for (SmallVector<PMDataManager *, 8>::iterator I = PassManagers.begin(),
640 E = PassManagers.end(); I != E; ++I)
643 for (SmallVector<ImmutablePass *, 8>::iterator
644 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
647 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
648 DME = AnUsageMap.end(); DMI != DME; ++DMI)
652 //===----------------------------------------------------------------------===//
653 // PMDataManager implementation
655 /// Augement AvailableAnalysis by adding analysis made available by pass P.
656 void PMDataManager::recordAvailableAnalysis(Pass *P) {
657 const PassInfo *PI = P->getPassInfo();
660 AvailableAnalysis[PI] = P;
662 //This pass is the current implementation of all of the interfaces it
663 //implements as well.
664 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
665 for (unsigned i = 0, e = II.size(); i != e; ++i)
666 AvailableAnalysis[II[i]] = P;
669 // Return true if P preserves high level analysis used by other
670 // passes managed by this manager
671 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
672 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
673 if (AnUsage->getPreservesAll())
676 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
677 for (SmallVector<Pass *, 8>::iterator I = HigherLevelAnalysis.begin(),
678 E = HigherLevelAnalysis.end(); I != E; ++I) {
680 if (P1->getAsImmutablePass() == 0 &&
681 std::find(PreservedSet.begin(), PreservedSet.end(),
682 P1->getPassInfo()) ==
690 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
691 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
692 // Don't do this unless assertions are enabled.
696 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
697 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
699 // Verify preserved analysis
700 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
701 E = PreservedSet.end(); I != E; ++I) {
703 if (Pass *AP = findAnalysisPass(AID, true)) {
704 TimeRegion PassTimer(getPassTimer(AP));
705 AP->verifyAnalysis();
710 /// Remove Analysis not preserved by Pass P
711 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
712 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
713 if (AnUsage->getPreservesAll())
716 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
717 for (std::map<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
718 E = AvailableAnalysis.end(); I != E; ) {
719 std::map<AnalysisID, Pass*>::iterator Info = I++;
720 if (Info->second->getAsImmutablePass() == 0 &&
721 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
722 PreservedSet.end()) {
723 // Remove this analysis
724 if (PassDebugging >= Details) {
725 Pass *S = Info->second;
726 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
727 dbgs() << S->getPassName() << "'\n";
729 AvailableAnalysis.erase(Info);
733 // Check inherited analysis also. If P is not preserving analysis
734 // provided by parent manager then remove it here.
735 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
737 if (!InheritedAnalysis[Index])
740 for (std::map<AnalysisID, Pass*>::iterator
741 I = InheritedAnalysis[Index]->begin(),
742 E = InheritedAnalysis[Index]->end(); I != E; ) {
743 std::map<AnalysisID, Pass *>::iterator Info = I++;
744 if (Info->second->getAsImmutablePass() == 0 &&
745 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
746 PreservedSet.end()) {
747 // Remove this analysis
748 if (PassDebugging >= Details) {
749 Pass *S = Info->second;
750 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
751 dbgs() << S->getPassName() << "'\n";
753 InheritedAnalysis[Index]->erase(Info);
759 /// Remove analysis passes that are not used any longer
760 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
761 enum PassDebuggingString DBG_STR) {
763 SmallVector<Pass *, 12> DeadPasses;
765 // If this is a on the fly manager then it does not have TPM.
769 TPM->collectLastUses(DeadPasses, P);
771 if (PassDebugging >= Details && !DeadPasses.empty()) {
772 dbgs() << " -*- '" << P->getPassName();
773 dbgs() << "' is the last user of following pass instances.";
774 dbgs() << " Free these instances\n";
777 for (SmallVector<Pass *, 12>::iterator I = DeadPasses.begin(),
778 E = DeadPasses.end(); I != E; ++I)
779 freePass(*I, Msg, DBG_STR);
782 void PMDataManager::freePass(Pass *P, StringRef Msg,
783 enum PassDebuggingString DBG_STR) {
784 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
787 // If the pass crashes releasing memory, remember this.
788 PassManagerPrettyStackEntry X(P);
789 TimeRegion PassTimer(getPassTimer(P));
794 if (const PassInfo *PI = P->getPassInfo()) {
795 // Remove the pass itself (if it is not already removed).
796 AvailableAnalysis.erase(PI);
798 // Remove all interfaces this pass implements, for which it is also
799 // listed as the available implementation.
800 const std::vector<const PassInfo*> &II = PI->getInterfacesImplemented();
801 for (unsigned i = 0, e = II.size(); i != e; ++i) {
802 std::map<AnalysisID, Pass*>::iterator Pos =
803 AvailableAnalysis.find(II[i]);
804 if (Pos != AvailableAnalysis.end() && Pos->second == P)
805 AvailableAnalysis.erase(Pos);
810 /// Add pass P into the PassVector. Update
811 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
812 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
813 // This manager is going to manage pass P. Set up analysis resolver
815 AnalysisResolver *AR = new AnalysisResolver(*this);
818 // If a FunctionPass F is the last user of ModulePass info M
819 // then the F's manager, not F, records itself as a last user of M.
820 SmallVector<Pass *, 12> TransferLastUses;
822 if (!ProcessAnalysis) {
824 PassVector.push_back(P);
828 // At the moment, this pass is the last user of all required passes.
829 SmallVector<Pass *, 12> LastUses;
830 SmallVector<Pass *, 8> RequiredPasses;
831 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
833 unsigned PDepth = this->getDepth();
835 collectRequiredAnalysis(RequiredPasses,
836 ReqAnalysisNotAvailable, P);
837 for (SmallVector<Pass *, 8>::iterator I = RequiredPasses.begin(),
838 E = RequiredPasses.end(); I != E; ++I) {
839 Pass *PRequired = *I;
842 assert(PRequired->getResolver() && "Analysis Resolver is not set");
843 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
844 RDepth = DM.getDepth();
846 if (PDepth == RDepth)
847 LastUses.push_back(PRequired);
848 else if (PDepth > RDepth) {
849 // Let the parent claim responsibility of last use
850 TransferLastUses.push_back(PRequired);
851 // Keep track of higher level analysis used by this manager.
852 HigherLevelAnalysis.push_back(PRequired);
854 llvm_unreachable("Unable to accomodate Required Pass");
857 // Set P as P's last user until someone starts using P.
858 // However, if P is a Pass Manager then it does not need
859 // to record its last user.
860 if (P->getAsPMDataManager() == 0)
861 LastUses.push_back(P);
862 TPM->setLastUser(LastUses, P);
864 if (!TransferLastUses.empty()) {
865 Pass *My_PM = getAsPass();
866 TPM->setLastUser(TransferLastUses, My_PM);
867 TransferLastUses.clear();
870 // Now, take care of required analysises that are not available.
871 for (SmallVector<AnalysisID, 8>::iterator
872 I = ReqAnalysisNotAvailable.begin(),
873 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
874 Pass *AnalysisPass = (*I)->createPass();
875 this->addLowerLevelRequiredPass(P, AnalysisPass);
878 // Take a note of analysis required and made available by this pass.
879 // Remove the analysis not preserved by this pass
880 removeNotPreservedAnalysis(P);
881 recordAvailableAnalysis(P);
884 PassVector.push_back(P);
888 /// Populate RP with analysis pass that are required by
889 /// pass P and are available. Populate RP_NotAvail with analysis
890 /// pass that are required by pass P but are not available.
891 void PMDataManager::collectRequiredAnalysis(SmallVector<Pass *, 8>&RP,
892 SmallVector<AnalysisID, 8> &RP_NotAvail,
894 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
895 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
896 for (AnalysisUsage::VectorType::const_iterator
897 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
898 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
899 RP.push_back(AnalysisPass);
901 RP_NotAvail.push_back(*I);
904 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
905 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
906 E = IDs.end(); I != E; ++I) {
907 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
908 RP.push_back(AnalysisPass);
910 RP_NotAvail.push_back(*I);
914 // All Required analyses should be available to the pass as it runs! Here
915 // we fill in the AnalysisImpls member of the pass so that it can
916 // successfully use the getAnalysis() method to retrieve the
917 // implementations it needs.
919 void PMDataManager::initializeAnalysisImpl(Pass *P) {
920 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
922 for (AnalysisUsage::VectorType::const_iterator
923 I = AnUsage->getRequiredSet().begin(),
924 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
925 Pass *Impl = findAnalysisPass(*I, true);
927 // This may be analysis pass that is initialized on the fly.
928 // If that is not the case then it will raise an assert when it is used.
930 AnalysisResolver *AR = P->getResolver();
931 assert(AR && "Analysis Resolver is not set");
932 AR->addAnalysisImplsPair(*I, Impl);
936 /// Find the pass that implements Analysis AID. If desired pass is not found
937 /// then return NULL.
938 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
940 // Check if AvailableAnalysis map has one entry.
941 std::map<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
943 if (I != AvailableAnalysis.end())
946 // Search Parents through TopLevelManager
948 return TPM->findAnalysisPass(AID);
953 // Print list of passes that are last used by P.
954 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
956 SmallVector<Pass *, 12> LUses;
958 // If this is a on the fly manager then it does not have TPM.
962 TPM->collectLastUses(LUses, P);
964 for (SmallVector<Pass *, 12>::iterator I = LUses.begin(),
965 E = LUses.end(); I != E; ++I) {
966 llvm::dbgs() << "--" << std::string(Offset*2, ' ');
967 (*I)->dumpPassStructure(0);
971 void PMDataManager::dumpPassArguments() const {
972 for (SmallVector<Pass *, 8>::const_iterator I = PassVector.begin(),
973 E = PassVector.end(); I != E; ++I) {
974 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
975 PMD->dumpPassArguments();
977 if (const PassInfo *PI = (*I)->getPassInfo())
978 if (!PI->isAnalysisGroup())
979 dbgs() << " -" << PI->getPassArgument();
983 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
984 enum PassDebuggingString S2,
986 if (PassDebugging < Executions)
988 dbgs() << (void*)this << std::string(getDepth()*2+1, ' ');
991 dbgs() << "Executing Pass '" << P->getPassName();
993 case MODIFICATION_MSG:
994 dbgs() << "Made Modification '" << P->getPassName();
997 dbgs() << " Freeing Pass '" << P->getPassName();
1003 case ON_BASICBLOCK_MSG:
1004 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1006 case ON_FUNCTION_MSG:
1007 dbgs() << "' on Function '" << Msg << "'...\n";
1010 dbgs() << "' on Module '" << Msg << "'...\n";
1013 dbgs() << "' on Loop '" << Msg << "'...\n";
1016 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1023 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1024 if (PassDebugging < Details)
1027 AnalysisUsage analysisUsage;
1028 P->getAnalysisUsage(analysisUsage);
1029 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1032 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1033 if (PassDebugging < Details)
1036 AnalysisUsage analysisUsage;
1037 P->getAnalysisUsage(analysisUsage);
1038 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1041 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1042 const AnalysisUsage::VectorType &Set) const {
1043 assert(PassDebugging >= Details);
1046 dbgs() << (void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1047 for (unsigned i = 0; i != Set.size(); ++i) {
1048 if (i) dbgs() << ',';
1049 dbgs() << ' ' << Set[i]->getPassName();
1054 /// Add RequiredPass into list of lower level passes required by pass P.
1055 /// RequiredPass is run on the fly by Pass Manager when P requests it
1056 /// through getAnalysis interface.
1057 /// This should be handled by specific pass manager.
1058 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1060 TPM->dumpArguments();
1064 // Module Level pass may required Function Level analysis info
1065 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1066 // to provide this on demand. In that case, in Pass manager terminology,
1067 // module level pass is requiring lower level analysis info managed by
1068 // lower level pass manager.
1070 // When Pass manager is not able to order required analysis info, Pass manager
1071 // checks whether any lower level manager will be able to provide this
1072 // analysis info on demand or not.
1074 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1075 dbgs() << "' required by '" << P->getPassName() << "'\n";
1077 llvm_unreachable("Unable to schedule pass");
1081 PMDataManager::~PMDataManager() {
1082 for (SmallVector<Pass *, 8>::iterator I = PassVector.begin(),
1083 E = PassVector.end(); I != E; ++I)
1087 //===----------------------------------------------------------------------===//
1088 // NOTE: Is this the right place to define this method ?
1089 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1090 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1091 return PM.findAnalysisPass(ID, dir);
1094 Pass *AnalysisResolver::findImplPass(Pass *P, const PassInfo *AnalysisPI,
1096 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1099 //===----------------------------------------------------------------------===//
1100 // BBPassManager implementation
1102 /// Execute all of the passes scheduled for execution by invoking
1103 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1104 /// the function, and if so, return true.
1105 bool BBPassManager::runOnFunction(Function &F) {
1106 if (F.isDeclaration())
1109 bool Changed = doInitialization(F);
1111 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1112 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1113 BasicBlockPass *BP = getContainedPass(Index);
1114 bool LocalChanged = false;
1116 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1117 dumpRequiredSet(BP);
1119 initializeAnalysisImpl(BP);
1122 // If the pass crashes, remember this.
1123 PassManagerPrettyStackEntry X(BP, *I);
1124 TimeRegion PassTimer(getPassTimer(BP));
1126 LocalChanged |= BP->runOnBasicBlock(*I);
1129 Changed |= LocalChanged;
1131 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1133 dumpPreservedSet(BP);
1135 verifyPreservedAnalysis(BP);
1136 removeNotPreservedAnalysis(BP);
1137 recordAvailableAnalysis(BP);
1138 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1141 return doFinalization(F) || Changed;
1144 // Implement doInitialization and doFinalization
1145 bool BBPassManager::doInitialization(Module &M) {
1146 bool Changed = false;
1148 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1149 Changed |= getContainedPass(Index)->doInitialization(M);
1154 bool BBPassManager::doFinalization(Module &M) {
1155 bool Changed = false;
1157 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1158 Changed |= getContainedPass(Index)->doFinalization(M);
1163 bool BBPassManager::doInitialization(Function &F) {
1164 bool Changed = false;
1166 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1167 BasicBlockPass *BP = getContainedPass(Index);
1168 Changed |= BP->doInitialization(F);
1174 bool BBPassManager::doFinalization(Function &F) {
1175 bool Changed = false;
1177 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1178 BasicBlockPass *BP = getContainedPass(Index);
1179 Changed |= BP->doFinalization(F);
1186 //===----------------------------------------------------------------------===//
1187 // FunctionPassManager implementation
1189 /// Create new Function pass manager
1190 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1191 FPM = new FunctionPassManagerImpl(0);
1192 // FPM is the top level manager.
1193 FPM->setTopLevelManager(FPM);
1195 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1196 FPM->setResolver(AR);
1199 FunctionPassManager::~FunctionPassManager() {
1203 /// add - Add a pass to the queue of passes to run. This passes
1204 /// ownership of the Pass to the PassManager. When the
1205 /// PassManager_X is destroyed, the pass will be destroyed as well, so
1206 /// there is no need to delete the pass. (TODO delete passes.)
1207 /// This implies that all passes MUST be allocated with 'new'.
1208 void FunctionPassManager::add(Pass *P) {
1212 /// run - Execute all of the passes scheduled for execution. Keep
1213 /// track of whether any of the passes modifies the function, and if
1214 /// so, return true.
1216 bool FunctionPassManager::run(Function &F) {
1217 if (F.isMaterializable()) {
1219 if (F.Materialize(&errstr)) {
1220 llvm_report_error("Error reading bitcode file: " + errstr);
1227 /// doInitialization - Run all of the initializers for the function passes.
1229 bool FunctionPassManager::doInitialization() {
1230 return FPM->doInitialization(*M);
1233 /// doFinalization - Run all of the finalizers for the function passes.
1235 bool FunctionPassManager::doFinalization() {
1236 return FPM->doFinalization(*M);
1239 //===----------------------------------------------------------------------===//
1240 // FunctionPassManagerImpl implementation
1242 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1243 bool Changed = false;
1248 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1249 Changed |= getContainedManager(Index)->doInitialization(M);
1254 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1255 bool Changed = false;
1257 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1258 Changed |= getContainedManager(Index)->doFinalization(M);
1263 /// cleanup - After running all passes, clean up pass manager cache.
1264 void FPPassManager::cleanup() {
1265 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1266 FunctionPass *FP = getContainedPass(Index);
1267 AnalysisResolver *AR = FP->getResolver();
1268 assert(AR && "Analysis Resolver is not set");
1269 AR->clearAnalysisImpls();
1273 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1276 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1277 FPPassManager *FPPM = getContainedManager(Index);
1278 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1279 FPPM->getContainedPass(Index)->releaseMemory();
1285 // Execute all the passes managed by this top level manager.
1286 // Return true if any function is modified by a pass.
1287 bool FunctionPassManagerImpl::run(Function &F) {
1288 bool Changed = false;
1289 TimingInfo::createTheTimeInfo();
1291 initializeAllAnalysisInfo();
1292 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1293 Changed |= getContainedManager(Index)->runOnFunction(F);
1295 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1296 getContainedManager(Index)->cleanup();
1302 //===----------------------------------------------------------------------===//
1303 // FPPassManager implementation
1305 char FPPassManager::ID = 0;
1306 /// Print passes managed by this manager
1307 void FPPassManager::dumpPassStructure(unsigned Offset) {
1308 llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
1309 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1310 FunctionPass *FP = getContainedPass(Index);
1311 FP->dumpPassStructure(Offset + 1);
1312 dumpLastUses(FP, Offset+1);
1317 /// Execute all of the passes scheduled for execution by invoking
1318 /// runOnFunction method. Keep track of whether any of the passes modifies
1319 /// the function, and if so, return true.
1320 bool FPPassManager::runOnFunction(Function &F) {
1321 if (F.isDeclaration())
1324 bool Changed = false;
1326 // Collect inherited analysis from Module level pass manager.
1327 populateInheritedAnalysis(TPM->activeStack);
1329 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1330 FunctionPass *FP = getContainedPass(Index);
1331 bool LocalChanged = false;
1333 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1334 dumpRequiredSet(FP);
1336 initializeAnalysisImpl(FP);
1339 PassManagerPrettyStackEntry X(FP, F);
1340 TimeRegion PassTimer(getPassTimer(FP));
1342 LocalChanged |= FP->runOnFunction(F);
1345 Changed |= LocalChanged;
1347 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1348 dumpPreservedSet(FP);
1350 verifyPreservedAnalysis(FP);
1351 removeNotPreservedAnalysis(FP);
1352 recordAvailableAnalysis(FP);
1353 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1358 bool FPPassManager::runOnModule(Module &M) {
1359 bool Changed = doInitialization(M);
1361 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1364 return doFinalization(M) || Changed;
1367 bool FPPassManager::doInitialization(Module &M) {
1368 bool Changed = false;
1370 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1371 Changed |= getContainedPass(Index)->doInitialization(M);
1376 bool FPPassManager::doFinalization(Module &M) {
1377 bool Changed = false;
1379 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1380 Changed |= getContainedPass(Index)->doFinalization(M);
1385 //===----------------------------------------------------------------------===//
1386 // MPPassManager implementation
1388 /// Execute all of the passes scheduled for execution by invoking
1389 /// runOnModule method. Keep track of whether any of the passes modifies
1390 /// the module, and if so, return true.
1392 MPPassManager::runOnModule(Module &M) {
1393 bool Changed = false;
1395 // Initialize on-the-fly passes
1396 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1397 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1399 FunctionPassManagerImpl *FPP = I->second;
1400 Changed |= FPP->doInitialization(M);
1403 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1404 ModulePass *MP = getContainedPass(Index);
1405 bool LocalChanged = false;
1407 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1408 dumpRequiredSet(MP);
1410 initializeAnalysisImpl(MP);
1413 PassManagerPrettyStackEntry X(MP, M);
1414 TimeRegion PassTimer(getPassTimer(MP));
1416 LocalChanged |= MP->runOnModule(M);
1419 Changed |= LocalChanged;
1421 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1422 M.getModuleIdentifier());
1423 dumpPreservedSet(MP);
1425 verifyPreservedAnalysis(MP);
1426 removeNotPreservedAnalysis(MP);
1427 recordAvailableAnalysis(MP);
1428 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1431 // Finalize on-the-fly passes
1432 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1433 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1435 FunctionPassManagerImpl *FPP = I->second;
1436 // We don't know when is the last time an on-the-fly pass is run,
1437 // so we need to releaseMemory / finalize here
1438 FPP->releaseMemoryOnTheFly();
1439 Changed |= FPP->doFinalization(M);
1444 /// Add RequiredPass into list of lower level passes required by pass P.
1445 /// RequiredPass is run on the fly by Pass Manager when P requests it
1446 /// through getAnalysis interface.
1447 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1448 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1449 "Unable to handle Pass that requires lower level Analysis pass");
1450 assert((P->getPotentialPassManagerType() <
1451 RequiredPass->getPotentialPassManagerType()) &&
1452 "Unable to handle Pass that requires lower level Analysis pass");
1454 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1456 FPP = new FunctionPassManagerImpl(0);
1457 // FPP is the top level manager.
1458 FPP->setTopLevelManager(FPP);
1460 OnTheFlyManagers[P] = FPP;
1462 FPP->add(RequiredPass);
1464 // Register P as the last user of RequiredPass.
1465 SmallVector<Pass *, 12> LU;
1466 LU.push_back(RequiredPass);
1467 FPP->setLastUser(LU, P);
1470 /// Return function pass corresponding to PassInfo PI, that is
1471 /// required by module pass MP. Instantiate analysis pass, by using
1472 /// its runOnFunction() for function F.
1473 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, const PassInfo *PI, Function &F){
1474 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1475 assert(FPP && "Unable to find on the fly pass");
1477 FPP->releaseMemoryOnTheFly();
1479 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1483 //===----------------------------------------------------------------------===//
1484 // PassManagerImpl implementation
1486 /// run - Execute all of the passes scheduled for execution. Keep track of
1487 /// whether any of the passes modifies the module, and if so, return true.
1488 bool PassManagerImpl::run(Module &M) {
1489 bool Changed = false;
1490 TimingInfo::createTheTimeInfo();
1495 initializeAllAnalysisInfo();
1496 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1497 Changed |= getContainedManager(Index)->runOnModule(M);
1501 //===----------------------------------------------------------------------===//
1502 // PassManager implementation
1504 /// Create new pass manager
1505 PassManager::PassManager() {
1506 PM = new PassManagerImpl(0);
1507 // PM is the top level manager
1508 PM->setTopLevelManager(PM);
1511 PassManager::~PassManager() {
1515 /// add - Add a pass to the queue of passes to run. This passes ownership of
1516 /// the Pass to the PassManager. When the PassManager is destroyed, the pass
1517 /// will be destroyed as well, so there is no need to delete the pass. This
1518 /// implies that all passes MUST be allocated with 'new'.
1519 void PassManager::add(Pass *P) {
1523 /// run - Execute all of the passes scheduled for execution. Keep track of
1524 /// whether any of the passes modifies the module, and if so, return true.
1525 bool PassManager::run(Module &M) {
1529 //===----------------------------------------------------------------------===//
1530 // TimingInfo Class - This class is used to calculate information about the
1531 // amount of time each pass takes to execute. This only happens with
1532 // -time-passes is enabled on the command line.
1534 bool llvm::TimePassesIsEnabled = false;
1535 static cl::opt<bool,true>
1536 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1537 cl::desc("Time each pass, printing elapsed time for each on exit"));
1539 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1540 // a non null value (if the -time-passes option is enabled) or it leaves it
1541 // null. It may be called multiple times.
1542 void TimingInfo::createTheTimeInfo() {
1543 if (!TimePassesIsEnabled || TheTimeInfo) return;
1545 // Constructed the first time this is called, iff -time-passes is enabled.
1546 // This guarantees that the object will be constructed before static globals,
1547 // thus it will be destroyed before them.
1548 static ManagedStatic<TimingInfo> TTI;
1549 TheTimeInfo = &*TTI;
1552 /// If TimingInfo is enabled then start pass timer.
1553 Timer *llvm::getPassTimer(Pass *P) {
1555 return TheTimeInfo->getPassTimer(P);
1559 //===----------------------------------------------------------------------===//
1560 // PMStack implementation
1563 // Pop Pass Manager from the stack and clear its analysis info.
1564 void PMStack::pop() {
1566 PMDataManager *Top = this->top();
1567 Top->initializeAnalysisInfo();
1572 // Push PM on the stack and set its top level manager.
1573 void PMStack::push(PMDataManager *PM) {
1574 assert(PM && "Unable to push. Pass Manager expected");
1576 if (!this->empty()) {
1577 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1579 assert(TPM && "Unable to find top level manager");
1580 TPM->addIndirectPassManager(PM);
1581 PM->setTopLevelManager(TPM);
1587 // Dump content of the pass manager stack.
1588 void PMStack::dump() {
1589 for (std::deque<PMDataManager *>::iterator I = S.begin(),
1590 E = S.end(); I != E; ++I)
1591 printf("%s ", (*I)->getAsPass()->getPassName());
1597 /// Find appropriate Module Pass Manager in the PM Stack and
1598 /// add self into that manager.
1599 void ModulePass::assignPassManager(PMStack &PMS,
1600 PassManagerType PreferredType) {
1601 // Find Module Pass Manager
1602 while(!PMS.empty()) {
1603 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1604 if (TopPMType == PreferredType)
1605 break; // We found desired pass manager
1606 else if (TopPMType > PMT_ModulePassManager)
1607 PMS.pop(); // Pop children pass managers
1611 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1612 PMS.top()->add(this);
1615 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1616 /// in the PM Stack and add self into that manager.
1617 void FunctionPass::assignPassManager(PMStack &PMS,
1618 PassManagerType PreferredType) {
1620 // Find Module Pass Manager
1621 while (!PMS.empty()) {
1622 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1628 // Create new Function Pass Manager if needed.
1630 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1631 FPP = (FPPassManager *)PMS.top();
1633 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1634 PMDataManager *PMD = PMS.top();
1636 // [1] Create new Function Pass Manager
1637 FPP = new FPPassManager(PMD->getDepth() + 1);
1638 FPP->populateInheritedAnalysis(PMS);
1640 // [2] Set up new manager's top level manager
1641 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1642 TPM->addIndirectPassManager(FPP);
1644 // [3] Assign manager to manage this new manager. This may create
1645 // and push new managers into PMS
1646 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1648 // [4] Push new manager into PMS
1652 // Assign FPP as the manager of this pass.
1656 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1657 /// in the PM Stack and add self into that manager.
1658 void BasicBlockPass::assignPassManager(PMStack &PMS,
1659 PassManagerType PreferredType) {
1662 // Basic Pass Manager is a leaf pass manager. It does not handle
1663 // any other pass manager.
1665 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1666 BBP = (BBPassManager *)PMS.top();
1668 // If leaf manager is not Basic Block Pass manager then create new
1669 // basic Block Pass manager.
1670 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1671 PMDataManager *PMD = PMS.top();
1673 // [1] Create new Basic Block Manager
1674 BBP = new BBPassManager(PMD->getDepth() + 1);
1676 // [2] Set up new manager's top level manager
1677 // Basic Block Pass Manager does not live by itself
1678 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1679 TPM->addIndirectPassManager(BBP);
1681 // [3] Assign manager to manage this new manager. This may create
1682 // and push new managers into PMS
1683 BBP->assignPassManager(PMS);
1685 // [4] Push new manager into PMS
1689 // Assign BBP as the manager of this pass.
1693 PassManagerBase::~PassManagerBase() {}
1695 /*===-- C Bindings --------------------------------------------------------===*/
1697 LLVMPassManagerRef LLVMCreatePassManager() {
1698 return wrap(new PassManager());
1701 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M) {
1702 return wrap(new FunctionPassManager(unwrap(M)));
1705 LLVMPassManagerRef LLVMCreateFunctionPassManager(LLVMModuleProviderRef P) {
1706 return LLVMCreateFunctionPassManagerForModule(
1707 reinterpret_cast<LLVMModuleRef>(P));
1710 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) {
1711 return unwrap<PassManager>(PM)->run(*unwrap(M));
1714 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM) {
1715 return unwrap<FunctionPassManager>(FPM)->doInitialization();
1718 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F) {
1719 return unwrap<FunctionPassManager>(FPM)->run(*unwrap<Function>(F));
1722 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM) {
1723 return unwrap<FunctionPassManager>(FPM)->doFinalization();
1726 void LLVMDisposePassManager(LLVMPassManagerRef PM) {