1 //===- LegacyPassManager.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 legacy LLVM Pass Manager infrastructure.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/IRPrintingPasses.h"
17 #include "llvm/IR/LegacyPassManager.h"
18 #include "llvm/IR/LegacyPassManagers.h"
19 #include "llvm/IR/LegacyPassNameParser.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/Mutex.h"
26 #include "llvm/Support/TimeValue.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm::legacy;
34 // 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.
44 // Different debug levels that can be enabled...
46 Disabled, Arguments, Structure, Executions, Details
50 static cl::opt<enum PassDebugLevel>
51 PassDebugging("debug-pass", cl::Hidden,
52 cl::desc("Print PassManager debugging information"),
54 clEnumVal(Disabled , "disable debug output"),
55 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
56 clEnumVal(Structure , "print pass structure before run()"),
57 clEnumVal(Executions, "print pass name before it is executed"),
58 clEnumVal(Details , "print pass details when it is executed"),
62 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
66 // Print IR out before/after specified passes.
68 PrintBefore("print-before",
69 llvm::cl::desc("Print IR before specified passes"),
73 PrintAfter("print-after",
74 llvm::cl::desc("Print IR after specified passes"),
78 PrintBeforeAll("print-before-all",
79 llvm::cl::desc("Print IR before each pass"),
82 PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
86 /// This is a helper to determine whether to print IR before or
89 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
90 PassOptionList &PassesToPrint) {
91 for (auto *PassInf : PassesToPrint) {
93 if (PassInf->getPassArgument() == PI->getPassArgument()) {
100 /// This is a utility to check whether a pass should have IR dumped
102 static bool ShouldPrintBeforePass(const PassInfo *PI) {
103 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
106 /// This is a utility to check whether a pass should have IR dumped
108 static bool ShouldPrintAfterPass(const PassInfo *PI) {
109 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
112 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
113 /// or higher is specified.
114 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
115 return PassDebugging >= Executions;
121 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
123 OS << "Releasing pass '";
125 OS << "Running pass '";
127 OS << P->getPassName() << "'";
130 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
139 if (isa<Function>(V))
141 else if (isa<BasicBlock>(V))
147 V->printAsOperand(OS, /*PrintTy=*/false, M);
153 //===----------------------------------------------------------------------===//
156 /// BBPassManager manages BasicBlockPass. It batches all the
157 /// pass together and sequence them to process one basic block before
158 /// processing next basic block.
159 class BBPassManager : public PMDataManager, public FunctionPass {
163 explicit BBPassManager()
164 : PMDataManager(), FunctionPass(ID) {}
166 /// Execute all of the passes scheduled for execution. Keep track of
167 /// whether any of the passes modifies the function, and if so, return true.
168 bool runOnFunction(Function &F) override;
170 /// Pass Manager itself does not invalidate any analysis info.
171 void getAnalysisUsage(AnalysisUsage &Info) const override {
172 Info.setPreservesAll();
175 bool doInitialization(Module &M) override;
176 bool doInitialization(Function &F);
177 bool doFinalization(Module &M) override;
178 bool doFinalization(Function &F);
180 PMDataManager *getAsPMDataManager() override { return this; }
181 Pass *getAsPass() override { return this; }
183 const char *getPassName() const override {
184 return "BasicBlock Pass Manager";
187 // Print passes managed by this manager
188 void dumpPassStructure(unsigned Offset) override {
189 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
190 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
191 BasicBlockPass *BP = getContainedPass(Index);
192 BP->dumpPassStructure(Offset + 1);
193 dumpLastUses(BP, Offset+1);
197 BasicBlockPass *getContainedPass(unsigned N) {
198 assert(N < PassVector.size() && "Pass number out of range!");
199 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
203 PassManagerType getPassManagerType() const override {
204 return PMT_BasicBlockPassManager;
208 char BBPassManager::ID = 0;
209 } // End anonymous namespace
213 //===----------------------------------------------------------------------===//
214 // FunctionPassManagerImpl
216 /// FunctionPassManagerImpl manages FPPassManagers
217 class FunctionPassManagerImpl : public Pass,
218 public PMDataManager,
219 public PMTopLevelManager {
220 virtual void anchor();
225 explicit FunctionPassManagerImpl() :
226 Pass(PT_PassManager, ID), PMDataManager(),
227 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
229 /// \copydoc FunctionPassManager::add()
234 /// createPrinterPass - Get a function printer pass.
235 Pass *createPrinterPass(raw_ostream &O,
236 const std::string &Banner) const override {
237 return createPrintFunctionPass(O, Banner);
240 // Prepare for running an on the fly pass, freeing memory if needed
241 // from a previous run.
242 void releaseMemoryOnTheFly();
244 /// run - Execute all of the passes scheduled for execution. Keep track of
245 /// whether any of the passes modifies the module, and if so, return true.
246 bool run(Function &F);
248 /// doInitialization - Run all of the initializers for the function passes.
250 bool doInitialization(Module &M) override;
252 /// doFinalization - Run all of the finalizers for the function passes.
254 bool doFinalization(Module &M) override;
257 PMDataManager *getAsPMDataManager() override { return this; }
258 Pass *getAsPass() override { return this; }
259 PassManagerType getTopLevelPassManagerType() override {
260 return PMT_FunctionPassManager;
263 /// Pass Manager itself does not invalidate any analysis info.
264 void getAnalysisUsage(AnalysisUsage &Info) const override {
265 Info.setPreservesAll();
268 FPPassManager *getContainedManager(unsigned N) {
269 assert(N < PassManagers.size() && "Pass number out of range!");
270 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
275 void FunctionPassManagerImpl::anchor() {}
277 char FunctionPassManagerImpl::ID = 0;
278 } // End of legacy namespace
279 } // End of llvm namespace
282 //===----------------------------------------------------------------------===//
285 /// MPPassManager manages ModulePasses and function pass managers.
286 /// It batches all Module passes and function pass managers together and
287 /// sequences them to process one module.
288 class MPPassManager : public Pass, public PMDataManager {
291 explicit MPPassManager() :
292 Pass(PT_PassManager, ID), PMDataManager() { }
294 // Delete on the fly managers.
295 ~MPPassManager() override {
296 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
297 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
299 FunctionPassManagerImpl *FPP = I->second;
304 /// createPrinterPass - Get a module printer pass.
305 Pass *createPrinterPass(raw_ostream &O,
306 const std::string &Banner) const override {
307 return createPrintModulePass(O, Banner);
310 /// run - Execute all of the passes scheduled for execution. Keep track of
311 /// whether any of the passes modifies the module, and if so, return true.
312 bool runOnModule(Module &M);
314 using llvm::Pass::doInitialization;
315 using llvm::Pass::doFinalization;
317 /// doInitialization - Run all of the initializers for the module passes.
319 bool doInitialization();
321 /// doFinalization - Run all of the finalizers for the module passes.
323 bool doFinalization();
325 /// Pass Manager itself does not invalidate any analysis info.
326 void getAnalysisUsage(AnalysisUsage &Info) const override {
327 Info.setPreservesAll();
330 /// Add RequiredPass into list of lower level passes required by pass P.
331 /// RequiredPass is run on the fly by Pass Manager when P requests it
332 /// through getAnalysis interface.
333 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
335 /// Return function pass corresponding to PassInfo PI, that is
336 /// required by module pass MP. Instantiate analysis pass, by using
337 /// its runOnFunction() for function F.
338 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
340 const char *getPassName() const override {
341 return "Module Pass Manager";
344 PMDataManager *getAsPMDataManager() override { return this; }
345 Pass *getAsPass() override { return this; }
347 // Print passes managed by this manager
348 void dumpPassStructure(unsigned Offset) override {
349 dbgs().indent(Offset*2) << "ModulePass Manager\n";
350 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
351 ModulePass *MP = getContainedPass(Index);
352 MP->dumpPassStructure(Offset + 1);
353 std::map<Pass *, FunctionPassManagerImpl *>::const_iterator I =
354 OnTheFlyManagers.find(MP);
355 if (I != OnTheFlyManagers.end())
356 I->second->dumpPassStructure(Offset + 2);
357 dumpLastUses(MP, Offset+1);
361 ModulePass *getContainedPass(unsigned N) {
362 assert(N < PassVector.size() && "Pass number out of range!");
363 return static_cast<ModulePass *>(PassVector[N]);
366 PassManagerType getPassManagerType() const override {
367 return PMT_ModulePassManager;
371 /// Collection of on the fly FPPassManagers. These managers manage
372 /// function passes that are required by module passes.
373 std::map<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
376 char MPPassManager::ID = 0;
377 } // End anonymous namespace
381 //===----------------------------------------------------------------------===//
385 /// PassManagerImpl manages MPPassManagers
386 class PassManagerImpl : public Pass,
387 public PMDataManager,
388 public PMTopLevelManager {
389 virtual void anchor();
393 explicit PassManagerImpl() :
394 Pass(PT_PassManager, ID), PMDataManager(),
395 PMTopLevelManager(new MPPassManager()) {}
397 /// \copydoc PassManager::add()
402 /// createPrinterPass - Get a module printer pass.
403 Pass *createPrinterPass(raw_ostream &O,
404 const std::string &Banner) const override {
405 return createPrintModulePass(O, Banner);
408 /// run - Execute all of the passes scheduled for execution. Keep track of
409 /// whether any of the passes modifies the module, and if so, return true.
412 using llvm::Pass::doInitialization;
413 using llvm::Pass::doFinalization;
415 /// doInitialization - Run all of the initializers for the module passes.
417 bool doInitialization();
419 /// doFinalization - Run all of the finalizers for the module passes.
421 bool doFinalization();
423 /// Pass Manager itself does not invalidate any analysis info.
424 void getAnalysisUsage(AnalysisUsage &Info) const override {
425 Info.setPreservesAll();
428 PMDataManager *getAsPMDataManager() override { return this; }
429 Pass *getAsPass() override { return this; }
430 PassManagerType getTopLevelPassManagerType() override {
431 return PMT_ModulePassManager;
434 MPPassManager *getContainedManager(unsigned N) {
435 assert(N < PassManagers.size() && "Pass number out of range!");
436 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
441 void PassManagerImpl::anchor() {}
443 char PassManagerImpl::ID = 0;
444 } // End of legacy namespace
445 } // End of llvm namespace
449 //===----------------------------------------------------------------------===//
450 /// TimingInfo Class - This class is used to calculate information about the
451 /// amount of time each pass takes to execute. This only happens when
452 /// -time-passes is enabled on the command line.
455 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
458 DenseMap<Pass*, Timer*> TimingData;
461 // Use 'create' member to get this.
462 TimingInfo() : TG("... Pass execution timing report ...") {}
464 // TimingDtor - Print out information about timing information
466 // Delete all of the timers, which accumulate their info into the
468 for (DenseMap<Pass*, Timer*>::iterator I = TimingData.begin(),
469 E = TimingData.end(); I != E; ++I)
471 // TimerGroup is deleted next, printing the report.
474 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
475 // to a non-null value (if the -time-passes option is enabled) or it leaves it
476 // null. It may be called multiple times.
477 static void createTheTimeInfo();
479 /// getPassTimer - Return the timer for the specified pass if it exists.
480 Timer *getPassTimer(Pass *P) {
481 if (P->getAsPMDataManager())
484 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
485 Timer *&T = TimingData[P];
487 T = new Timer(P->getPassName(), TG);
492 } // End of anon namespace
494 static TimingInfo *TheTimeInfo;
496 //===----------------------------------------------------------------------===//
497 // PMTopLevelManager implementation
499 /// Initialize top level manager. Create first pass manager.
500 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
501 PMDM->setTopLevelManager(this);
502 addPassManager(PMDM);
503 activeStack.push(PMDM);
506 /// Set pass P as the last user of the given analysis passes.
508 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
510 if (P->getResolver())
511 PDepth = P->getResolver()->getPMDataManager().getDepth();
513 for (SmallVectorImpl<Pass *>::const_iterator I = AnalysisPasses.begin(),
514 E = AnalysisPasses.end(); I != E; ++I) {
521 // Update the last users of passes that are required transitive by AP.
522 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
523 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
524 SmallVector<Pass *, 12> LastUses;
525 SmallVector<Pass *, 12> LastPMUses;
526 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
527 E = IDs.end(); I != E; ++I) {
528 Pass *AnalysisPass = findAnalysisPass(*I);
529 assert(AnalysisPass && "Expected analysis pass to exist.");
530 AnalysisResolver *AR = AnalysisPass->getResolver();
531 assert(AR && "Expected analysis resolver to exist.");
532 unsigned APDepth = AR->getPMDataManager().getDepth();
534 if (PDepth == APDepth)
535 LastUses.push_back(AnalysisPass);
536 else if (PDepth > APDepth)
537 LastPMUses.push_back(AnalysisPass);
540 setLastUser(LastUses, P);
542 // If this pass has a corresponding pass manager, push higher level
543 // analysis to this pass manager.
544 if (P->getResolver())
545 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
548 // If AP is the last user of other passes then make P last user of
550 for (DenseMap<Pass *, Pass *>::iterator LUI = LastUser.begin(),
551 LUE = LastUser.end(); LUI != LUE; ++LUI) {
552 if (LUI->second == AP)
553 // DenseMap iterator is not invalidated here because
554 // this is just updating existing entries.
555 LastUser[LUI->first] = P;
560 /// Collect passes whose last user is P
561 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
563 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
564 InversedLastUser.find(P);
565 if (DMI == InversedLastUser.end())
568 SmallPtrSet<Pass *, 8> &LU = DMI->second;
569 for (Pass *LUP : LU) {
570 LastUses.push_back(LUP);
575 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
576 AnalysisUsage *AnUsage = nullptr;
577 DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.find(P);
578 if (DMI != AnUsageMap.end())
579 AnUsage = DMI->second;
581 AnUsage = new AnalysisUsage();
582 P->getAnalysisUsage(*AnUsage);
583 AnUsageMap[P] = AnUsage;
588 /// Schedule pass P for execution. Make sure that passes required by
589 /// P are run before P is run. Update analysis info maintained by
590 /// the manager. Remove dead passes. This is a recursive function.
591 void PMTopLevelManager::schedulePass(Pass *P) {
593 // TODO : Allocate function manager for this pass, other wise required set
594 // may be inserted into previous function manager
596 // Give pass a chance to prepare the stage.
597 P->preparePassManager(activeStack);
599 // If P is an analysis pass and it is available then do not
600 // generate the analysis again. Stale analysis info should not be
601 // available at this point.
602 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
603 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
608 AnalysisUsage *AnUsage = findAnalysisUsage(P);
610 bool checkAnalysis = true;
611 while (checkAnalysis) {
612 checkAnalysis = false;
614 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
615 for (AnalysisUsage::VectorType::const_iterator I = RequiredSet.begin(),
616 E = RequiredSet.end(); I != E; ++I) {
618 Pass *AnalysisPass = findAnalysisPass(*I);
620 const PassInfo *PI = findAnalysisPassInfo(*I);
623 // Pass P is not in the global PassRegistry
624 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
625 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
626 dbgs() << "Required Passes:" << "\n";
627 for (AnalysisUsage::VectorType::const_iterator I2 = RequiredSet.begin(),
628 E = RequiredSet.end(); I2 != E && I2 != I; ++I2) {
629 Pass *AnalysisPass2 = findAnalysisPass(*I2);
631 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
633 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
634 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
635 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
640 assert(PI && "Expected required passes to be initialized");
641 AnalysisPass = PI->createPass();
642 if (P->getPotentialPassManagerType () ==
643 AnalysisPass->getPotentialPassManagerType())
644 // Schedule analysis pass that is managed by the same pass manager.
645 schedulePass(AnalysisPass);
646 else if (P->getPotentialPassManagerType () >
647 AnalysisPass->getPotentialPassManagerType()) {
648 // Schedule analysis pass that is managed by a new manager.
649 schedulePass(AnalysisPass);
650 // Recheck analysis passes to ensure that required analyses that
651 // are already checked are still available.
652 checkAnalysis = true;
654 // Do not schedule this analysis. Lower level analysis
655 // passes are run on the fly.
661 // Now all required passes are available.
662 if (ImmutablePass *IP = P->getAsImmutablePass()) {
663 // P is a immutable pass and it will be managed by this
664 // top level manager. Set up analysis resolver to connect them.
665 PMDataManager *DM = getAsPMDataManager();
666 AnalysisResolver *AR = new AnalysisResolver(*DM);
668 DM->initializeAnalysisImpl(P);
669 addImmutablePass(IP);
670 DM->recordAvailableAnalysis(IP);
674 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
675 Pass *PP = P->createPrinterPass(
676 dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " ***");
677 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
680 // Add the requested pass to the best available pass manager.
681 P->assignPassManager(activeStack, getTopLevelPassManagerType());
683 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
684 Pass *PP = P->createPrinterPass(
685 dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***");
686 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
690 /// Find the pass that implements Analysis AID. Search immutable
691 /// passes and all pass managers. If desired pass is not found
692 /// then return NULL.
693 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
695 // Check pass managers
696 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
697 E = PassManagers.end(); I != E; ++I)
698 if (Pass *P = (*I)->findAnalysisPass(AID, false))
701 // Check other pass managers
702 for (SmallVectorImpl<PMDataManager *>::iterator
703 I = IndirectPassManagers.begin(),
704 E = IndirectPassManagers.end(); I != E; ++I)
705 if (Pass *P = (*I)->findAnalysisPass(AID, false))
708 // Check the immutable passes. Iterate in reverse order so that we find
709 // the most recently registered passes first.
710 for (SmallVectorImpl<ImmutablePass *>::reverse_iterator I =
711 ImmutablePasses.rbegin(), E = ImmutablePasses.rend(); I != E; ++I) {
712 AnalysisID PI = (*I)->getPassID();
716 // If Pass not found then check the interfaces implemented by Immutable Pass
717 const PassInfo *PassInf = findAnalysisPassInfo(PI);
718 assert(PassInf && "Expected all immutable passes to be initialized");
719 const std::vector<const PassInfo*> &ImmPI =
720 PassInf->getInterfacesImplemented();
721 for (std::vector<const PassInfo*>::const_iterator II = ImmPI.begin(),
722 EE = ImmPI.end(); II != EE; ++II) {
723 if ((*II)->getTypeInfo() == AID)
731 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
732 const PassInfo *&PI = AnalysisPassInfos[AID];
734 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
736 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
737 "The pass info pointer changed for an analysis ID!");
742 // Print passes managed by this top level manager.
743 void PMTopLevelManager::dumpPasses() const {
745 if (PassDebugging < Structure)
748 // Print out the immutable passes
749 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
750 ImmutablePasses[i]->dumpPassStructure(0);
753 // Every class that derives from PMDataManager also derives from Pass
754 // (sometimes indirectly), but there's no inheritance relationship
755 // between PMDataManager and Pass, so we have to getAsPass to get
756 // from a PMDataManager* to a Pass*.
757 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
758 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
759 (*I)->getAsPass()->dumpPassStructure(1);
762 void PMTopLevelManager::dumpArguments() const {
764 if (PassDebugging < Arguments)
767 dbgs() << "Pass Arguments: ";
768 for (SmallVectorImpl<ImmutablePass *>::const_iterator I =
769 ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
770 if (const PassInfo *PI = findAnalysisPassInfo((*I)->getPassID())) {
771 assert(PI && "Expected all immutable passes to be initialized");
772 if (!PI->isAnalysisGroup())
773 dbgs() << " -" << PI->getPassArgument();
775 for (SmallVectorImpl<PMDataManager *>::const_iterator I =
776 PassManagers.begin(), E = PassManagers.end(); I != E; ++I)
777 (*I)->dumpPassArguments();
781 void PMTopLevelManager::initializeAllAnalysisInfo() {
782 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
783 E = PassManagers.end(); I != E; ++I)
784 (*I)->initializeAnalysisInfo();
786 // Initailize other pass managers
787 for (SmallVectorImpl<PMDataManager *>::iterator
788 I = IndirectPassManagers.begin(), E = IndirectPassManagers.end();
790 (*I)->initializeAnalysisInfo();
792 for (DenseMap<Pass *, Pass *>::iterator DMI = LastUser.begin(),
793 DME = LastUser.end(); DMI != DME; ++DMI) {
794 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator InvDMI =
795 InversedLastUser.find(DMI->second);
796 if (InvDMI != InversedLastUser.end()) {
797 SmallPtrSet<Pass *, 8> &L = InvDMI->second;
798 L.insert(DMI->first);
800 SmallPtrSet<Pass *, 8> L; L.insert(DMI->first);
801 InversedLastUser[DMI->second] = L;
807 PMTopLevelManager::~PMTopLevelManager() {
808 for (SmallVectorImpl<PMDataManager *>::iterator I = PassManagers.begin(),
809 E = PassManagers.end(); I != E; ++I)
812 for (SmallVectorImpl<ImmutablePass *>::iterator
813 I = ImmutablePasses.begin(), E = ImmutablePasses.end(); I != E; ++I)
816 for (DenseMap<Pass *, AnalysisUsage *>::iterator DMI = AnUsageMap.begin(),
817 DME = AnUsageMap.end(); DMI != DME; ++DMI)
821 //===----------------------------------------------------------------------===//
822 // PMDataManager implementation
824 /// Augement AvailableAnalysis by adding analysis made available by pass P.
825 void PMDataManager::recordAvailableAnalysis(Pass *P) {
826 AnalysisID PI = P->getPassID();
828 AvailableAnalysis[PI] = P;
830 assert(!AvailableAnalysis.empty());
832 // This pass is the current implementation of all of the interfaces it
833 // implements as well.
834 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
836 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
837 for (unsigned i = 0, e = II.size(); i != e; ++i)
838 AvailableAnalysis[II[i]->getTypeInfo()] = P;
841 // Return true if P preserves high level analysis used by other
842 // passes managed by this manager
843 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
844 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
845 if (AnUsage->getPreservesAll())
848 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
849 for (SmallVectorImpl<Pass *>::iterator I = HigherLevelAnalysis.begin(),
850 E = HigherLevelAnalysis.end(); I != E; ++I) {
852 if (P1->getAsImmutablePass() == nullptr &&
853 std::find(PreservedSet.begin(), PreservedSet.end(),
862 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
863 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
864 // Don't do this unless assertions are enabled.
868 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
869 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
871 // Verify preserved analysis
872 for (AnalysisUsage::VectorType::const_iterator I = PreservedSet.begin(),
873 E = PreservedSet.end(); I != E; ++I) {
875 if (Pass *AP = findAnalysisPass(AID, true)) {
876 TimeRegion PassTimer(getPassTimer(AP));
877 AP->verifyAnalysis();
882 /// Remove Analysis not preserved by Pass P
883 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
884 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
885 if (AnUsage->getPreservesAll())
888 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
889 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
890 E = AvailableAnalysis.end(); I != E; ) {
891 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
892 if (Info->second->getAsImmutablePass() == nullptr &&
893 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
894 PreservedSet.end()) {
895 // Remove this analysis
896 if (PassDebugging >= Details) {
897 Pass *S = Info->second;
898 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
899 dbgs() << S->getPassName() << "'\n";
901 AvailableAnalysis.erase(Info);
905 // Check inherited analysis also. If P is not preserving analysis
906 // provided by parent manager then remove it here.
907 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
909 if (!InheritedAnalysis[Index])
912 for (DenseMap<AnalysisID, Pass*>::iterator
913 I = InheritedAnalysis[Index]->begin(),
914 E = InheritedAnalysis[Index]->end(); I != E; ) {
915 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
916 if (Info->second->getAsImmutablePass() == nullptr &&
917 std::find(PreservedSet.begin(), PreservedSet.end(), Info->first) ==
918 PreservedSet.end()) {
919 // Remove this analysis
920 if (PassDebugging >= Details) {
921 Pass *S = Info->second;
922 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
923 dbgs() << S->getPassName() << "'\n";
925 InheritedAnalysis[Index]->erase(Info);
931 /// Remove analysis passes that are not used any longer
932 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
933 enum PassDebuggingString DBG_STR) {
935 SmallVector<Pass *, 12> DeadPasses;
937 // If this is a on the fly manager then it does not have TPM.
941 TPM->collectLastUses(DeadPasses, P);
943 if (PassDebugging >= Details && !DeadPasses.empty()) {
944 dbgs() << " -*- '" << P->getPassName();
945 dbgs() << "' is the last user of following pass instances.";
946 dbgs() << " Free these instances\n";
949 for (SmallVectorImpl<Pass *>::iterator I = DeadPasses.begin(),
950 E = DeadPasses.end(); I != E; ++I)
951 freePass(*I, Msg, DBG_STR);
954 void PMDataManager::freePass(Pass *P, StringRef Msg,
955 enum PassDebuggingString DBG_STR) {
956 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
959 // If the pass crashes releasing memory, remember this.
960 PassManagerPrettyStackEntry X(P);
961 TimeRegion PassTimer(getPassTimer(P));
966 AnalysisID PI = P->getPassID();
967 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
968 // Remove the pass itself (if it is not already removed).
969 AvailableAnalysis.erase(PI);
971 // Remove all interfaces this pass implements, for which it is also
972 // listed as the available implementation.
973 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
974 for (unsigned i = 0, e = II.size(); i != e; ++i) {
975 DenseMap<AnalysisID, Pass*>::iterator Pos =
976 AvailableAnalysis.find(II[i]->getTypeInfo());
977 if (Pos != AvailableAnalysis.end() && Pos->second == P)
978 AvailableAnalysis.erase(Pos);
983 /// Add pass P into the PassVector. Update
984 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
985 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
986 // This manager is going to manage pass P. Set up analysis resolver
988 AnalysisResolver *AR = new AnalysisResolver(*this);
991 // If a FunctionPass F is the last user of ModulePass info M
992 // then the F's manager, not F, records itself as a last user of M.
993 SmallVector<Pass *, 12> TransferLastUses;
995 if (!ProcessAnalysis) {
997 PassVector.push_back(P);
1001 // At the moment, this pass is the last user of all required passes.
1002 SmallVector<Pass *, 12> LastUses;
1003 SmallVector<Pass *, 8> RequiredPasses;
1004 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1006 unsigned PDepth = this->getDepth();
1008 collectRequiredAnalysis(RequiredPasses,
1009 ReqAnalysisNotAvailable, P);
1010 for (SmallVectorImpl<Pass *>::iterator I = RequiredPasses.begin(),
1011 E = RequiredPasses.end(); I != E; ++I) {
1012 Pass *PRequired = *I;
1013 unsigned RDepth = 0;
1015 assert(PRequired->getResolver() && "Analysis Resolver is not set");
1016 PMDataManager &DM = PRequired->getResolver()->getPMDataManager();
1017 RDepth = DM.getDepth();
1019 if (PDepth == RDepth)
1020 LastUses.push_back(PRequired);
1021 else if (PDepth > RDepth) {
1022 // Let the parent claim responsibility of last use
1023 TransferLastUses.push_back(PRequired);
1024 // Keep track of higher level analysis used by this manager.
1025 HigherLevelAnalysis.push_back(PRequired);
1027 llvm_unreachable("Unable to accommodate Required Pass");
1030 // Set P as P's last user until someone starts using P.
1031 // However, if P is a Pass Manager then it does not need
1032 // to record its last user.
1033 if (!P->getAsPMDataManager())
1034 LastUses.push_back(P);
1035 TPM->setLastUser(LastUses, P);
1037 if (!TransferLastUses.empty()) {
1038 Pass *My_PM = getAsPass();
1039 TPM->setLastUser(TransferLastUses, My_PM);
1040 TransferLastUses.clear();
1043 // Now, take care of required analyses that are not available.
1044 for (SmallVectorImpl<AnalysisID>::iterator
1045 I = ReqAnalysisNotAvailable.begin(),
1046 E = ReqAnalysisNotAvailable.end() ;I != E; ++I) {
1047 const PassInfo *PI = TPM->findAnalysisPassInfo(*I);
1048 Pass *AnalysisPass = PI->createPass();
1049 this->addLowerLevelRequiredPass(P, AnalysisPass);
1052 // Take a note of analysis required and made available by this pass.
1053 // Remove the analysis not preserved by this pass
1054 removeNotPreservedAnalysis(P);
1055 recordAvailableAnalysis(P);
1058 PassVector.push_back(P);
1062 /// Populate RP with analysis pass that are required by
1063 /// pass P and are available. Populate RP_NotAvail with analysis
1064 /// pass that are required by pass P but are not available.
1065 void PMDataManager::collectRequiredAnalysis(SmallVectorImpl<Pass *> &RP,
1066 SmallVectorImpl<AnalysisID> &RP_NotAvail,
1068 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1069 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
1070 for (AnalysisUsage::VectorType::const_iterator
1071 I = RequiredSet.begin(), E = RequiredSet.end(); I != E; ++I) {
1072 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1073 RP.push_back(AnalysisPass);
1075 RP_NotAvail.push_back(*I);
1078 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
1079 for (AnalysisUsage::VectorType::const_iterator I = IDs.begin(),
1080 E = IDs.end(); I != E; ++I) {
1081 if (Pass *AnalysisPass = findAnalysisPass(*I, true))
1082 RP.push_back(AnalysisPass);
1084 RP_NotAvail.push_back(*I);
1088 // All Required analyses should be available to the pass as it runs! Here
1089 // we fill in the AnalysisImpls member of the pass so that it can
1090 // successfully use the getAnalysis() method to retrieve the
1091 // implementations it needs.
1093 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1094 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1096 for (AnalysisUsage::VectorType::const_iterator
1097 I = AnUsage->getRequiredSet().begin(),
1098 E = AnUsage->getRequiredSet().end(); I != E; ++I) {
1099 Pass *Impl = findAnalysisPass(*I, true);
1101 // This may be analysis pass that is initialized on the fly.
1102 // If that is not the case then it will raise an assert when it is used.
1104 AnalysisResolver *AR = P->getResolver();
1105 assert(AR && "Analysis Resolver is not set");
1106 AR->addAnalysisImplsPair(*I, Impl);
1110 /// Find the pass that implements Analysis AID. If desired pass is not found
1111 /// then return NULL.
1112 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1114 // Check if AvailableAnalysis map has one entry.
1115 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1117 if (I != AvailableAnalysis.end())
1120 // Search Parents through TopLevelManager
1122 return TPM->findAnalysisPass(AID);
1127 // Print list of passes that are last used by P.
1128 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1130 SmallVector<Pass *, 12> LUses;
1132 // If this is a on the fly manager then it does not have TPM.
1136 TPM->collectLastUses(LUses, P);
1138 for (SmallVectorImpl<Pass *>::iterator I = LUses.begin(),
1139 E = LUses.end(); I != E; ++I) {
1140 dbgs() << "--" << std::string(Offset*2, ' ');
1141 (*I)->dumpPassStructure(0);
1145 void PMDataManager::dumpPassArguments() const {
1146 for (SmallVectorImpl<Pass *>::const_iterator I = PassVector.begin(),
1147 E = PassVector.end(); I != E; ++I) {
1148 if (PMDataManager *PMD = (*I)->getAsPMDataManager())
1149 PMD->dumpPassArguments();
1151 if (const PassInfo *PI =
1152 TPM->findAnalysisPassInfo((*I)->getPassID()))
1153 if (!PI->isAnalysisGroup())
1154 dbgs() << " -" << PI->getPassArgument();
1158 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1159 enum PassDebuggingString S2,
1161 if (PassDebugging < Executions)
1163 dbgs() << "[" << sys::TimeValue::now().str() << "] " << (void *)this
1164 << std::string(getDepth() * 2 + 1, ' ');
1167 dbgs() << "Executing Pass '" << P->getPassName();
1169 case MODIFICATION_MSG:
1170 dbgs() << "Made Modification '" << P->getPassName();
1173 dbgs() << " Freeing Pass '" << P->getPassName();
1179 case ON_BASICBLOCK_MSG:
1180 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1182 case ON_FUNCTION_MSG:
1183 dbgs() << "' on Function '" << Msg << "'...\n";
1186 dbgs() << "' on Module '" << Msg << "'...\n";
1189 dbgs() << "' on Region '" << Msg << "'...\n";
1192 dbgs() << "' on Loop '" << Msg << "'...\n";
1195 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1202 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1203 if (PassDebugging < Details)
1206 AnalysisUsage analysisUsage;
1207 P->getAnalysisUsage(analysisUsage);
1208 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1211 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1212 if (PassDebugging < Details)
1215 AnalysisUsage analysisUsage;
1216 P->getAnalysisUsage(analysisUsage);
1217 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1220 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1221 const AnalysisUsage::VectorType &Set) const {
1222 assert(PassDebugging >= Details);
1225 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1226 for (unsigned i = 0; i != Set.size(); ++i) {
1227 if (i) dbgs() << ',';
1228 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1230 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1232 dbgs() << " Uninitialized Pass";
1235 dbgs() << ' ' << PInf->getPassName();
1240 /// Add RequiredPass into list of lower level passes required by pass P.
1241 /// RequiredPass is run on the fly by Pass Manager when P requests it
1242 /// through getAnalysis interface.
1243 /// This should be handled by specific pass manager.
1244 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1246 TPM->dumpArguments();
1250 // Module Level pass may required Function Level analysis info
1251 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1252 // to provide this on demand. In that case, in Pass manager terminology,
1253 // module level pass is requiring lower level analysis info managed by
1254 // lower level pass manager.
1256 // When Pass manager is not able to order required analysis info, Pass manager
1257 // checks whether any lower level manager will be able to provide this
1258 // analysis info on demand or not.
1260 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1261 dbgs() << "' required by '" << P->getPassName() << "'\n";
1263 llvm_unreachable("Unable to schedule pass");
1266 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1267 llvm_unreachable("Unable to find on the fly pass");
1271 PMDataManager::~PMDataManager() {
1272 for (SmallVectorImpl<Pass *>::iterator I = PassVector.begin(),
1273 E = PassVector.end(); I != E; ++I)
1277 //===----------------------------------------------------------------------===//
1278 // NOTE: Is this the right place to define this method ?
1279 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1280 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1281 return PM.findAnalysisPass(ID, dir);
1284 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1286 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1289 //===----------------------------------------------------------------------===//
1290 // BBPassManager implementation
1292 /// Execute all of the passes scheduled for execution by invoking
1293 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1294 /// the function, and if so, return true.
1295 bool BBPassManager::runOnFunction(Function &F) {
1296 if (F.isDeclaration())
1299 bool Changed = doInitialization(F);
1301 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
1302 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1303 BasicBlockPass *BP = getContainedPass(Index);
1304 bool LocalChanged = false;
1306 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, I->getName());
1307 dumpRequiredSet(BP);
1309 initializeAnalysisImpl(BP);
1312 // If the pass crashes, remember this.
1313 PassManagerPrettyStackEntry X(BP, *I);
1314 TimeRegion PassTimer(getPassTimer(BP));
1316 LocalChanged |= BP->runOnBasicBlock(*I);
1319 Changed |= LocalChanged;
1321 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1323 dumpPreservedSet(BP);
1325 verifyPreservedAnalysis(BP);
1326 removeNotPreservedAnalysis(BP);
1327 recordAvailableAnalysis(BP);
1328 removeDeadPasses(BP, I->getName(), ON_BASICBLOCK_MSG);
1331 return doFinalization(F) || Changed;
1334 // Implement doInitialization and doFinalization
1335 bool BBPassManager::doInitialization(Module &M) {
1336 bool Changed = false;
1338 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1339 Changed |= getContainedPass(Index)->doInitialization(M);
1344 bool BBPassManager::doFinalization(Module &M) {
1345 bool Changed = false;
1347 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1348 Changed |= getContainedPass(Index)->doFinalization(M);
1353 bool BBPassManager::doInitialization(Function &F) {
1354 bool Changed = false;
1356 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1357 BasicBlockPass *BP = getContainedPass(Index);
1358 Changed |= BP->doInitialization(F);
1364 bool BBPassManager::doFinalization(Function &F) {
1365 bool Changed = false;
1367 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1368 BasicBlockPass *BP = getContainedPass(Index);
1369 Changed |= BP->doFinalization(F);
1376 //===----------------------------------------------------------------------===//
1377 // FunctionPassManager implementation
1379 /// Create new Function pass manager
1380 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1381 FPM = new FunctionPassManagerImpl();
1382 // FPM is the top level manager.
1383 FPM->setTopLevelManager(FPM);
1385 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1386 FPM->setResolver(AR);
1389 FunctionPassManager::~FunctionPassManager() {
1393 void FunctionPassManager::add(Pass *P) {
1397 /// run - Execute all of the passes scheduled for execution. Keep
1398 /// track of whether any of the passes modifies the function, and if
1399 /// so, return true.
1401 bool FunctionPassManager::run(Function &F) {
1402 if (std::error_code EC = F.materialize())
1403 report_fatal_error("Error reading bitcode file: " + EC.message());
1408 /// doInitialization - Run all of the initializers for the function passes.
1410 bool FunctionPassManager::doInitialization() {
1411 return FPM->doInitialization(*M);
1414 /// doFinalization - Run all of the finalizers for the function passes.
1416 bool FunctionPassManager::doFinalization() {
1417 return FPM->doFinalization(*M);
1420 //===----------------------------------------------------------------------===//
1421 // FunctionPassManagerImpl implementation
1423 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1424 bool Changed = false;
1429 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1430 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1431 E = IPV.end(); I != E; ++I) {
1432 Changed |= (*I)->doInitialization(M);
1435 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1436 Changed |= getContainedManager(Index)->doInitialization(M);
1441 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1442 bool Changed = false;
1444 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1445 Changed |= getContainedManager(Index)->doFinalization(M);
1447 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1448 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1449 E = IPV.end(); I != E; ++I) {
1450 Changed |= (*I)->doFinalization(M);
1456 /// cleanup - After running all passes, clean up pass manager cache.
1457 void FPPassManager::cleanup() {
1458 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1459 FunctionPass *FP = getContainedPass(Index);
1460 AnalysisResolver *AR = FP->getResolver();
1461 assert(AR && "Analysis Resolver is not set");
1462 AR->clearAnalysisImpls();
1466 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1469 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1470 FPPassManager *FPPM = getContainedManager(Index);
1471 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1472 FPPM->getContainedPass(Index)->releaseMemory();
1478 // Execute all the passes managed by this top level manager.
1479 // Return true if any function is modified by a pass.
1480 bool FunctionPassManagerImpl::run(Function &F) {
1481 bool Changed = false;
1482 TimingInfo::createTheTimeInfo();
1484 initializeAllAnalysisInfo();
1485 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1486 Changed |= getContainedManager(Index)->runOnFunction(F);
1487 F.getContext().yield();
1490 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1491 getContainedManager(Index)->cleanup();
1497 //===----------------------------------------------------------------------===//
1498 // FPPassManager implementation
1500 char FPPassManager::ID = 0;
1501 /// Print passes managed by this manager
1502 void FPPassManager::dumpPassStructure(unsigned Offset) {
1503 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1504 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1505 FunctionPass *FP = getContainedPass(Index);
1506 FP->dumpPassStructure(Offset + 1);
1507 dumpLastUses(FP, Offset+1);
1512 /// Execute all of the passes scheduled for execution by invoking
1513 /// runOnFunction method. Keep track of whether any of the passes modifies
1514 /// the function, and if so, return true.
1515 bool FPPassManager::runOnFunction(Function &F) {
1516 if (F.isDeclaration())
1519 bool Changed = false;
1521 // Collect inherited analysis from Module level pass manager.
1522 populateInheritedAnalysis(TPM->activeStack);
1524 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1525 FunctionPass *FP = getContainedPass(Index);
1526 bool LocalChanged = false;
1528 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1529 dumpRequiredSet(FP);
1531 initializeAnalysisImpl(FP);
1534 PassManagerPrettyStackEntry X(FP, F);
1535 TimeRegion PassTimer(getPassTimer(FP));
1537 LocalChanged |= FP->runOnFunction(F);
1540 Changed |= LocalChanged;
1542 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1543 dumpPreservedSet(FP);
1545 verifyPreservedAnalysis(FP);
1546 removeNotPreservedAnalysis(FP);
1547 recordAvailableAnalysis(FP);
1548 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1553 bool FPPassManager::runOnModule(Module &M) {
1554 bool Changed = false;
1556 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1557 Changed |= runOnFunction(*I);
1562 bool FPPassManager::doInitialization(Module &M) {
1563 bool Changed = false;
1565 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1566 Changed |= getContainedPass(Index)->doInitialization(M);
1571 bool FPPassManager::doFinalization(Module &M) {
1572 bool Changed = false;
1574 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1575 Changed |= getContainedPass(Index)->doFinalization(M);
1580 //===----------------------------------------------------------------------===//
1581 // MPPassManager implementation
1583 /// Execute all of the passes scheduled for execution by invoking
1584 /// runOnModule method. Keep track of whether any of the passes modifies
1585 /// the module, and if so, return true.
1587 MPPassManager::runOnModule(Module &M) {
1588 bool Changed = false;
1590 // Initialize on-the-fly passes
1591 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1592 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1594 FunctionPassManagerImpl *FPP = I->second;
1595 Changed |= FPP->doInitialization(M);
1598 // Initialize module passes
1599 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1600 Changed |= getContainedPass(Index)->doInitialization(M);
1602 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1603 ModulePass *MP = getContainedPass(Index);
1604 bool LocalChanged = false;
1606 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1607 dumpRequiredSet(MP);
1609 initializeAnalysisImpl(MP);
1612 PassManagerPrettyStackEntry X(MP, M);
1613 TimeRegion PassTimer(getPassTimer(MP));
1615 LocalChanged |= MP->runOnModule(M);
1618 Changed |= LocalChanged;
1620 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1621 M.getModuleIdentifier());
1622 dumpPreservedSet(MP);
1624 verifyPreservedAnalysis(MP);
1625 removeNotPreservedAnalysis(MP);
1626 recordAvailableAnalysis(MP);
1627 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1630 // Finalize module passes
1631 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1632 Changed |= getContainedPass(Index)->doFinalization(M);
1634 // Finalize on-the-fly passes
1635 for (std::map<Pass *, FunctionPassManagerImpl *>::iterator
1636 I = OnTheFlyManagers.begin(), E = OnTheFlyManagers.end();
1638 FunctionPassManagerImpl *FPP = I->second;
1639 // We don't know when is the last time an on-the-fly pass is run,
1640 // so we need to releaseMemory / finalize here
1641 FPP->releaseMemoryOnTheFly();
1642 Changed |= FPP->doFinalization(M);
1648 /// Add RequiredPass into list of lower level passes required by pass P.
1649 /// RequiredPass is run on the fly by Pass Manager when P requests it
1650 /// through getAnalysis interface.
1651 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1652 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1653 "Unable to handle Pass that requires lower level Analysis pass");
1654 assert((P->getPotentialPassManagerType() <
1655 RequiredPass->getPotentialPassManagerType()) &&
1656 "Unable to handle Pass that requires lower level Analysis pass");
1660 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1662 FPP = new FunctionPassManagerImpl();
1663 // FPP is the top level manager.
1664 FPP->setTopLevelManager(FPP);
1666 OnTheFlyManagers[P] = FPP;
1668 const PassInfo *RequiredPassPI =
1669 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1671 Pass *FoundPass = nullptr;
1672 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1674 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1677 FoundPass = RequiredPass;
1678 // This should be guaranteed to add RequiredPass to the passmanager given
1679 // that we checked for an available analysis above.
1680 FPP->add(RequiredPass);
1682 // Register P as the last user of FoundPass or RequiredPass.
1683 SmallVector<Pass *, 1> LU;
1684 LU.push_back(FoundPass);
1685 FPP->setLastUser(LU, P);
1688 /// Return function pass corresponding to PassInfo PI, that is
1689 /// required by module pass MP. Instantiate analysis pass, by using
1690 /// its runOnFunction() for function F.
1691 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1692 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1693 assert(FPP && "Unable to find on the fly pass");
1695 FPP->releaseMemoryOnTheFly();
1697 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1701 //===----------------------------------------------------------------------===//
1702 // PassManagerImpl implementation
1705 /// run - Execute all of the passes scheduled for execution. Keep track of
1706 /// whether any of the passes modifies the module, and if so, return true.
1707 bool PassManagerImpl::run(Module &M) {
1708 bool Changed = false;
1709 TimingInfo::createTheTimeInfo();
1714 SmallVectorImpl<ImmutablePass *>& IPV = getImmutablePasses();
1715 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1716 E = IPV.end(); I != E; ++I) {
1717 Changed |= (*I)->doInitialization(M);
1720 initializeAllAnalysisInfo();
1721 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1722 Changed |= getContainedManager(Index)->runOnModule(M);
1723 M.getContext().yield();
1726 for (SmallVectorImpl<ImmutablePass *>::const_iterator I = IPV.begin(),
1727 E = IPV.end(); I != E; ++I) {
1728 Changed |= (*I)->doFinalization(M);
1734 //===----------------------------------------------------------------------===//
1735 // PassManager implementation
1737 /// Create new pass manager
1738 PassManager::PassManager() {
1739 PM = new PassManagerImpl();
1740 // PM is the top level manager
1741 PM->setTopLevelManager(PM);
1744 PassManager::~PassManager() {
1748 void PassManager::add(Pass *P) {
1752 /// run - Execute all of the passes scheduled for execution. Keep track of
1753 /// whether any of the passes modifies the module, and if so, return true.
1754 bool PassManager::run(Module &M) {
1758 //===----------------------------------------------------------------------===//
1759 // TimingInfo implementation
1761 bool llvm::TimePassesIsEnabled = false;
1762 static cl::opt<bool,true>
1763 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
1764 cl::desc("Time each pass, printing elapsed time for each on exit"));
1766 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1767 // a non-null value (if the -time-passes option is enabled) or it leaves it
1768 // null. It may be called multiple times.
1769 void TimingInfo::createTheTimeInfo() {
1770 if (!TimePassesIsEnabled || TheTimeInfo) return;
1772 // Constructed the first time this is called, iff -time-passes is enabled.
1773 // This guarantees that the object will be constructed before static globals,
1774 // thus it will be destroyed before them.
1775 static ManagedStatic<TimingInfo> TTI;
1776 TheTimeInfo = &*TTI;
1779 /// If TimingInfo is enabled then start pass timer.
1780 Timer *llvm::getPassTimer(Pass *P) {
1782 return TheTimeInfo->getPassTimer(P);
1786 //===----------------------------------------------------------------------===//
1787 // PMStack implementation
1790 // Pop Pass Manager from the stack and clear its analysis info.
1791 void PMStack::pop() {
1793 PMDataManager *Top = this->top();
1794 Top->initializeAnalysisInfo();
1799 // Push PM on the stack and set its top level manager.
1800 void PMStack::push(PMDataManager *PM) {
1801 assert(PM && "Unable to push. Pass Manager expected");
1802 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1804 if (!this->empty()) {
1805 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1806 && "pushing bad pass manager to PMStack");
1807 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1809 assert(TPM && "Unable to find top level manager");
1810 TPM->addIndirectPassManager(PM);
1811 PM->setTopLevelManager(TPM);
1812 PM->setDepth(this->top()->getDepth()+1);
1814 assert((PM->getPassManagerType() == PMT_ModulePassManager
1815 || PM->getPassManagerType() == PMT_FunctionPassManager)
1816 && "pushing bad pass manager to PMStack");
1823 // Dump content of the pass manager stack.
1824 void PMStack::dump() const {
1825 for (std::vector<PMDataManager *>::const_iterator I = S.begin(),
1826 E = S.end(); I != E; ++I)
1827 dbgs() << (*I)->getAsPass()->getPassName() << ' ';
1833 /// Find appropriate Module Pass Manager in the PM Stack and
1834 /// add self into that manager.
1835 void ModulePass::assignPassManager(PMStack &PMS,
1836 PassManagerType PreferredType) {
1837 // Find Module Pass Manager
1838 while (!PMS.empty()) {
1839 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1840 if (TopPMType == PreferredType)
1841 break; // We found desired pass manager
1842 else if (TopPMType > PMT_ModulePassManager)
1843 PMS.pop(); // Pop children pass managers
1847 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1848 PMS.top()->add(this);
1851 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1852 /// in the PM Stack and add self into that manager.
1853 void FunctionPass::assignPassManager(PMStack &PMS,
1854 PassManagerType PreferredType) {
1856 // Find Function Pass Manager
1857 while (!PMS.empty()) {
1858 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1864 // Create new Function Pass Manager if needed.
1866 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1867 FPP = (FPPassManager *)PMS.top();
1869 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1870 PMDataManager *PMD = PMS.top();
1872 // [1] Create new Function Pass Manager
1873 FPP = new FPPassManager();
1874 FPP->populateInheritedAnalysis(PMS);
1876 // [2] Set up new manager's top level manager
1877 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1878 TPM->addIndirectPassManager(FPP);
1880 // [3] Assign manager to manage this new manager. This may create
1881 // and push new managers into PMS
1882 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1884 // [4] Push new manager into PMS
1888 // Assign FPP as the manager of this pass.
1892 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1893 /// in the PM Stack and add self into that manager.
1894 void BasicBlockPass::assignPassManager(PMStack &PMS,
1895 PassManagerType PreferredType) {
1898 // Basic Pass Manager is a leaf pass manager. It does not handle
1899 // any other pass manager.
1901 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1902 BBP = (BBPassManager *)PMS.top();
1904 // If leaf manager is not Basic Block Pass manager then create new
1905 // basic Block Pass manager.
1906 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1907 PMDataManager *PMD = PMS.top();
1909 // [1] Create new Basic Block Manager
1910 BBP = new BBPassManager();
1912 // [2] Set up new manager's top level manager
1913 // Basic Block Pass Manager does not live by itself
1914 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1915 TPM->addIndirectPassManager(BBP);
1917 // [3] Assign manager to manage this new manager. This may create
1918 // and push new managers into PMS
1919 BBP->assignPassManager(PMS, PreferredType);
1921 // [4] Push new manager into PMS
1925 // Assign BBP as the manager of this pass.
1929 PassManagerBase::~PassManagerBase() {}