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 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/LegacyPassManager.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/DiagnosticInfo.h"
18 #include "llvm/IR/IRPrintingPasses.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/LegacyPassManagers.h"
21 #include "llvm/IR/LegacyPassNameParser.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/Chrono.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/Mutex.h"
30 #include "llvm/Support/Timer.h"
31 #include "llvm/Support/raw_ostream.h"
33 #include <unordered_set>
35 using namespace llvm::legacy;
37 // See PassManagers.h for Pass Manager infrastructure overview.
39 //===----------------------------------------------------------------------===//
40 // Pass debugging information. Often it is useful to find out what pass is
41 // running when a crash occurs in a utility. When this library is compiled with
42 // debugging on, a command line option (--debug-pass) is enabled that causes the
43 // pass name to be printed before it executes.
47 // Different debug levels that can be enabled...
49 Disabled, Arguments, Structure, Executions, Details
53 static cl::opt<enum PassDebugLevel>
54 PassDebugging("debug-pass", cl::Hidden,
55 cl::desc("Print PassManager debugging information"),
57 clEnumVal(Disabled , "disable debug output"),
58 clEnumVal(Arguments , "print pass arguments to pass to 'opt'"),
59 clEnumVal(Structure , "print pass structure before run()"),
60 clEnumVal(Executions, "print pass name before it is executed"),
61 clEnumVal(Details , "print pass details when it is executed")));
64 typedef llvm::cl::list<const llvm::PassInfo *, bool, PassNameParser>
68 // Print IR out before/after specified passes.
70 PrintBefore("print-before",
71 llvm::cl::desc("Print IR before specified passes"),
75 PrintAfter("print-after",
76 llvm::cl::desc("Print IR after specified passes"),
79 static cl::opt<bool> PrintBeforeAll("print-before-all",
80 llvm::cl::desc("Print IR before each pass"),
81 cl::init(false), cl::Hidden);
82 static cl::opt<bool> PrintAfterAll("print-after-all",
83 llvm::cl::desc("Print IR after each pass"),
84 cl::init(false), cl::Hidden);
87 PrintModuleScope("print-module-scope",
88 cl::desc("When printing IR for print-[before|after]{-all} "
89 "always print a module IR"),
90 cl::init(false), cl::Hidden);
92 static cl::list<std::string>
93 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
94 cl::desc("Only print IR for functions whose name "
95 "match this for all print-[before|after][-all] "
97 cl::CommaSeparated, cl::Hidden);
99 /// This is a helper to determine whether to print IR before or
102 static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
103 PassOptionList &PassesToPrint) {
104 for (auto *PassInf : PassesToPrint) {
106 if (PassInf->getPassArgument() == PI->getPassArgument()) {
113 /// This is a utility to check whether a pass should have IR dumped
115 static bool ShouldPrintBeforePass(const PassInfo *PI) {
116 return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
119 /// This is a utility to check whether a pass should have IR dumped
121 static bool ShouldPrintAfterPass(const PassInfo *PI) {
122 return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
125 bool llvm::forcePrintModuleIR() { return PrintModuleScope; }
127 bool llvm::isFunctionInPrintList(StringRef FunctionName) {
128 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
129 PrintFuncsList.end());
130 return PrintFuncNames.empty() || PrintFuncNames.count(FunctionName);
132 /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions
133 /// or higher is specified.
134 bool PMDataManager::isPassDebuggingExecutionsOrMore() const {
135 return PassDebugging >= Executions;
138 unsigned PMDataManager::initSizeRemarkInfo(Module &M) {
139 // Only calculate getInstructionCount if the size-info remark is requested.
140 return M.getInstructionCount();
143 void PMDataManager::emitInstrCountChangedRemark(Pass *P, Module &M,
144 unsigned CountBefore) {
145 // We need a function containing at least one basic block in order to output
146 // remarks. Since it's possible that the first function in the module doesn't
147 // actually contain a basic block, we have to go and find one that's suitable
148 // for emitting remarks.
149 auto It = std::find_if(M.begin(), M.end(),
150 [](const Function &Fn) { return !Fn.empty(); });
152 // Didn't find a function. Quit.
156 // We found a function containing at least one basic block.
159 // How many instructions are in the module now?
160 unsigned CountAfter = M.getInstructionCount();
162 // If there was no change, don't emit a remark.
163 if (CountBefore == CountAfter)
166 // If it's a pass manager, don't emit a remark. (This hinges on the assumption
167 // that the only passes that return non-null with getAsPMDataManager are pass
168 // managers.) The reason we have to do this is to avoid emitting remarks for
170 if (P->getAsPMDataManager())
173 // Compute a possibly negative delta between the instruction count before
174 // running P, and after running P.
176 static_cast<int64_t>(CountAfter) - static_cast<int64_t>(CountBefore);
178 BasicBlock &BB = *F->begin();
179 OptimizationRemarkAnalysis R("size-info", "IRSizeChange",
180 DiagnosticLocation(), &BB);
181 // FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This
182 // would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.
183 R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())
184 << ": IR instruction count changed from "
185 << DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)
187 << DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)
189 << DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);
190 F->getContext().diagnose(R); // Not using ORE for layering reasons.
193 void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {
195 OS << "Releasing pass '";
197 OS << "Running pass '";
199 OS << P->getPassName() << "'";
202 OS << " on module '" << M->getModuleIdentifier() << "'.\n";
211 if (isa<Function>(V))
213 else if (isa<BasicBlock>(V))
219 V->printAsOperand(OS, /*PrintTy=*/false, M);
225 //===----------------------------------------------------------------------===//
228 /// BBPassManager manages BasicBlockPass. It batches all the
229 /// pass together and sequence them to process one basic block before
230 /// processing next basic block.
231 class BBPassManager : public PMDataManager, public FunctionPass {
235 explicit BBPassManager()
236 : PMDataManager(), FunctionPass(ID) {}
238 /// Execute all of the passes scheduled for execution. Keep track of
239 /// whether any of the passes modifies the function, and if so, return true.
240 bool runOnFunction(Function &F) override;
242 /// Pass Manager itself does not invalidate any analysis info.
243 void getAnalysisUsage(AnalysisUsage &Info) const override {
244 Info.setPreservesAll();
247 bool doInitialization(Module &M) override;
248 bool doInitialization(Function &F);
249 bool doFinalization(Module &M) override;
250 bool doFinalization(Function &F);
252 PMDataManager *getAsPMDataManager() override { return this; }
253 Pass *getAsPass() override { return this; }
255 StringRef getPassName() const override { return "BasicBlock Pass Manager"; }
257 // Print passes managed by this manager
258 void dumpPassStructure(unsigned Offset) override {
259 dbgs().indent(Offset*2) << "BasicBlockPass Manager\n";
260 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
261 BasicBlockPass *BP = getContainedPass(Index);
262 BP->dumpPassStructure(Offset + 1);
263 dumpLastUses(BP, Offset+1);
267 BasicBlockPass *getContainedPass(unsigned N) {
268 assert(N < PassVector.size() && "Pass number out of range!");
269 BasicBlockPass *BP = static_cast<BasicBlockPass *>(PassVector[N]);
273 PassManagerType getPassManagerType() const override {
274 return PMT_BasicBlockPassManager;
278 char BBPassManager::ID = 0;
279 } // End anonymous namespace
283 //===----------------------------------------------------------------------===//
284 // FunctionPassManagerImpl
286 /// FunctionPassManagerImpl manages FPPassManagers
287 class FunctionPassManagerImpl : public Pass,
288 public PMDataManager,
289 public PMTopLevelManager {
290 virtual void anchor();
295 explicit FunctionPassManagerImpl() :
296 Pass(PT_PassManager, ID), PMDataManager(),
297 PMTopLevelManager(new FPPassManager()), wasRun(false) {}
299 /// \copydoc FunctionPassManager::add()
304 /// createPrinterPass - Get a function printer pass.
305 Pass *createPrinterPass(raw_ostream &O,
306 const std::string &Banner) const override {
307 return createPrintFunctionPass(O, Banner);
310 // Prepare for running an on the fly pass, freeing memory if needed
311 // from a previous run.
312 void releaseMemoryOnTheFly();
314 /// run - Execute all of the passes scheduled for execution. Keep track of
315 /// whether any of the passes modifies the module, and if so, return true.
316 bool run(Function &F);
318 /// doInitialization - Run all of the initializers for the function passes.
320 bool doInitialization(Module &M) override;
322 /// doFinalization - Run all of the finalizers for the function passes.
324 bool doFinalization(Module &M) override;
327 PMDataManager *getAsPMDataManager() override { return this; }
328 Pass *getAsPass() override { return this; }
329 PassManagerType getTopLevelPassManagerType() override {
330 return PMT_FunctionPassManager;
333 /// Pass Manager itself does not invalidate any analysis info.
334 void getAnalysisUsage(AnalysisUsage &Info) const override {
335 Info.setPreservesAll();
338 FPPassManager *getContainedManager(unsigned N) {
339 assert(N < PassManagers.size() && "Pass number out of range!");
340 FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);
345 void FunctionPassManagerImpl::anchor() {}
347 char FunctionPassManagerImpl::ID = 0;
348 } // End of legacy namespace
349 } // End of llvm namespace
352 //===----------------------------------------------------------------------===//
355 /// MPPassManager manages ModulePasses and function pass managers.
356 /// It batches all Module passes and function pass managers together and
357 /// sequences them to process one module.
358 class MPPassManager : public Pass, public PMDataManager {
361 explicit MPPassManager() :
362 Pass(PT_PassManager, ID), PMDataManager() { }
364 // Delete on the fly managers.
365 ~MPPassManager() override {
366 for (auto &OnTheFlyManager : OnTheFlyManagers) {
367 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
372 /// createPrinterPass - Get a module printer pass.
373 Pass *createPrinterPass(raw_ostream &O,
374 const std::string &Banner) const override {
375 return createPrintModulePass(O, Banner);
378 /// run - Execute all of the passes scheduled for execution. Keep track of
379 /// whether any of the passes modifies the module, and if so, return true.
380 bool runOnModule(Module &M);
382 using llvm::Pass::doInitialization;
383 using llvm::Pass::doFinalization;
385 /// Pass Manager itself does not invalidate any analysis info.
386 void getAnalysisUsage(AnalysisUsage &Info) const override {
387 Info.setPreservesAll();
390 /// Add RequiredPass into list of lower level passes required by pass P.
391 /// RequiredPass is run on the fly by Pass Manager when P requests it
392 /// through getAnalysis interface.
393 void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;
395 /// Return function pass corresponding to PassInfo PI, that is
396 /// required by module pass MP. Instantiate analysis pass, by using
397 /// its runOnFunction() for function F.
398 Pass* getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F) override;
400 StringRef getPassName() const override { return "Module Pass Manager"; }
402 PMDataManager *getAsPMDataManager() override { return this; }
403 Pass *getAsPass() override { return this; }
405 // Print passes managed by this manager
406 void dumpPassStructure(unsigned Offset) override {
407 dbgs().indent(Offset*2) << "ModulePass Manager\n";
408 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
409 ModulePass *MP = getContainedPass(Index);
410 MP->dumpPassStructure(Offset + 1);
411 MapVector<Pass *, FunctionPassManagerImpl *>::const_iterator I =
412 OnTheFlyManagers.find(MP);
413 if (I != OnTheFlyManagers.end())
414 I->second->dumpPassStructure(Offset + 2);
415 dumpLastUses(MP, Offset+1);
419 ModulePass *getContainedPass(unsigned N) {
420 assert(N < PassVector.size() && "Pass number out of range!");
421 return static_cast<ModulePass *>(PassVector[N]);
424 PassManagerType getPassManagerType() const override {
425 return PMT_ModulePassManager;
429 /// Collection of on the fly FPPassManagers. These managers manage
430 /// function passes that are required by module passes.
431 MapVector<Pass *, FunctionPassManagerImpl *> OnTheFlyManagers;
434 char MPPassManager::ID = 0;
435 } // End anonymous namespace
439 //===----------------------------------------------------------------------===//
443 /// PassManagerImpl manages MPPassManagers
444 class PassManagerImpl : public Pass,
445 public PMDataManager,
446 public PMTopLevelManager {
447 virtual void anchor();
451 explicit PassManagerImpl() :
452 Pass(PT_PassManager, ID), PMDataManager(),
453 PMTopLevelManager(new MPPassManager()) {}
455 /// \copydoc PassManager::add()
460 /// createPrinterPass - Get a module printer pass.
461 Pass *createPrinterPass(raw_ostream &O,
462 const std::string &Banner) const override {
463 return createPrintModulePass(O, Banner);
466 /// run - Execute all of the passes scheduled for execution. Keep track of
467 /// whether any of the passes modifies the module, and if so, return true.
470 using llvm::Pass::doInitialization;
471 using llvm::Pass::doFinalization;
473 /// Pass Manager itself does not invalidate any analysis info.
474 void getAnalysisUsage(AnalysisUsage &Info) const override {
475 Info.setPreservesAll();
478 PMDataManager *getAsPMDataManager() override { return this; }
479 Pass *getAsPass() override { return this; }
480 PassManagerType getTopLevelPassManagerType() override {
481 return PMT_ModulePassManager;
484 MPPassManager *getContainedManager(unsigned N) {
485 assert(N < PassManagers.size() && "Pass number out of range!");
486 MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);
491 void PassManagerImpl::anchor() {}
493 char PassManagerImpl::ID = 0;
494 } // End of legacy namespace
495 } // End of llvm namespace
499 //===----------------------------------------------------------------------===//
500 /// TimingInfo Class - This class is used to calculate information about the
501 /// amount of time each pass takes to execute. This only happens when
502 /// -time-passes is enabled on the command line.
505 static ManagedStatic<sys::SmartMutex<true> > TimingInfoMutex;
508 DenseMap<Pass*, Timer*> TimingData;
511 // Use 'create' member to get this.
512 TimingInfo() : TG("pass", "... Pass execution timing report ...") {}
514 // TimingDtor - Print out information about timing information
516 // Delete all of the timers, which accumulate their info into the
518 for (auto &I : TimingData)
520 // TimerGroup is deleted next, printing the report.
523 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer
524 // to a non-null value (if the -time-passes option is enabled) or it leaves it
525 // null. It may be called multiple times.
526 static void createTheTimeInfo();
528 // print - Prints out timing information and then resets the timers.
530 TG.print(*CreateInfoOutputFile());
533 /// getPassTimer - Return the timer for the specified pass if it exists.
534 Timer *getPassTimer(Pass *P) {
535 if (P->getAsPMDataManager())
538 sys::SmartScopedLock<true> Lock(*TimingInfoMutex);
539 Timer *&T = TimingData[P];
541 StringRef PassName = P->getPassName();
542 StringRef PassArgument;
543 if (const PassInfo *PI = Pass::lookupPassInfo(P->getPassID()))
544 PassArgument = PI->getPassArgument();
545 T = new Timer(PassArgument.empty() ? PassName : PassArgument, PassName,
552 } // End of anon namespace
554 static TimingInfo *TheTimeInfo;
556 //===----------------------------------------------------------------------===//
557 // PMTopLevelManager implementation
559 /// Initialize top level manager. Create first pass manager.
560 PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {
561 PMDM->setTopLevelManager(this);
562 addPassManager(PMDM);
563 activeStack.push(PMDM);
566 /// Set pass P as the last user of the given analysis passes.
568 PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {
570 if (P->getResolver())
571 PDepth = P->getResolver()->getPMDataManager().getDepth();
573 for (Pass *AP : AnalysisPasses) {
579 // Update the last users of passes that are required transitive by AP.
580 AnalysisUsage *AnUsage = findAnalysisUsage(AP);
581 const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();
582 SmallVector<Pass *, 12> LastUses;
583 SmallVector<Pass *, 12> LastPMUses;
584 for (AnalysisID ID : IDs) {
585 Pass *AnalysisPass = findAnalysisPass(ID);
586 assert(AnalysisPass && "Expected analysis pass to exist.");
587 AnalysisResolver *AR = AnalysisPass->getResolver();
588 assert(AR && "Expected analysis resolver to exist.");
589 unsigned APDepth = AR->getPMDataManager().getDepth();
591 if (PDepth == APDepth)
592 LastUses.push_back(AnalysisPass);
593 else if (PDepth > APDepth)
594 LastPMUses.push_back(AnalysisPass);
597 setLastUser(LastUses, P);
599 // If this pass has a corresponding pass manager, push higher level
600 // analysis to this pass manager.
601 if (P->getResolver())
602 setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());
605 // If AP is the last user of other passes then make P last user of
607 for (auto LU : LastUser) {
609 // DenseMap iterator is not invalidated here because
610 // this is just updating existing entries.
611 LastUser[LU.first] = P;
616 /// Collect passes whose last user is P
617 void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,
619 DenseMap<Pass *, SmallPtrSet<Pass *, 8> >::iterator DMI =
620 InversedLastUser.find(P);
621 if (DMI == InversedLastUser.end())
624 SmallPtrSet<Pass *, 8> &LU = DMI->second;
625 for (Pass *LUP : LU) {
626 LastUses.push_back(LUP);
631 AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {
632 AnalysisUsage *AnUsage = nullptr;
633 auto DMI = AnUsageMap.find(P);
634 if (DMI != AnUsageMap.end())
635 AnUsage = DMI->second;
637 // Look up the analysis usage from the pass instance (different instances
638 // of the same pass can produce different results), but unique the
639 // resulting object to reduce memory usage. This helps to greatly reduce
640 // memory usage when we have many instances of only a few pass types
641 // (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set
644 P->getAnalysisUsage(AU);
646 AUFoldingSetNode* Node = nullptr;
648 AUFoldingSetNode::Profile(ID, AU);
650 if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))
653 Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);
654 UniqueAnalysisUsages.InsertNode(Node, IP);
656 assert(Node && "cached analysis usage must be non null");
658 AnUsageMap[P] = &Node->AU;
664 /// Schedule pass P for execution. Make sure that passes required by
665 /// P are run before P is run. Update analysis info maintained by
666 /// the manager. Remove dead passes. This is a recursive function.
667 void PMTopLevelManager::schedulePass(Pass *P) {
669 // TODO : Allocate function manager for this pass, other wise required set
670 // may be inserted into previous function manager
672 // Give pass a chance to prepare the stage.
673 P->preparePassManager(activeStack);
675 // If P is an analysis pass and it is available then do not
676 // generate the analysis again. Stale analysis info should not be
677 // available at this point.
678 const PassInfo *PI = findAnalysisPassInfo(P->getPassID());
679 if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {
684 AnalysisUsage *AnUsage = findAnalysisUsage(P);
686 bool checkAnalysis = true;
687 while (checkAnalysis) {
688 checkAnalysis = false;
690 const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();
691 for (const AnalysisID ID : RequiredSet) {
693 Pass *AnalysisPass = findAnalysisPass(ID);
695 const PassInfo *PI = findAnalysisPassInfo(ID);
698 // Pass P is not in the global PassRegistry
699 dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";
700 dbgs() << "Verify if there is a pass dependency cycle." << "\n";
701 dbgs() << "Required Passes:" << "\n";
702 for (const AnalysisID ID2 : RequiredSet) {
705 Pass *AnalysisPass2 = findAnalysisPass(ID2);
707 dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";
709 dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";
710 dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";
711 dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";
716 assert(PI && "Expected required passes to be initialized");
717 AnalysisPass = PI->createPass();
718 if (P->getPotentialPassManagerType () ==
719 AnalysisPass->getPotentialPassManagerType())
720 // Schedule analysis pass that is managed by the same pass manager.
721 schedulePass(AnalysisPass);
722 else if (P->getPotentialPassManagerType () >
723 AnalysisPass->getPotentialPassManagerType()) {
724 // Schedule analysis pass that is managed by a new manager.
725 schedulePass(AnalysisPass);
726 // Recheck analysis passes to ensure that required analyses that
727 // are already checked are still available.
728 checkAnalysis = true;
730 // Do not schedule this analysis. Lower level analysis
731 // passes are run on the fly.
737 // Now all required passes are available.
738 if (ImmutablePass *IP = P->getAsImmutablePass()) {
739 // P is a immutable pass and it will be managed by this
740 // top level manager. Set up analysis resolver to connect them.
741 PMDataManager *DM = getAsPMDataManager();
742 AnalysisResolver *AR = new AnalysisResolver(*DM);
744 DM->initializeAnalysisImpl(P);
745 addImmutablePass(IP);
746 DM->recordAvailableAnalysis(IP);
750 if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
751 Pass *PP = P->createPrinterPass(
752 dbgs(), ("*** IR Dump Before " + P->getPassName() + " ***").str());
753 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
756 // Add the requested pass to the best available pass manager.
757 P->assignPassManager(activeStack, getTopLevelPassManagerType());
759 if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
760 Pass *PP = P->createPrinterPass(
761 dbgs(), ("*** IR Dump After " + P->getPassName() + " ***").str());
762 PP->assignPassManager(activeStack, getTopLevelPassManagerType());
766 /// Find the pass that implements Analysis AID. Search immutable
767 /// passes and all pass managers. If desired pass is not found
768 /// then return NULL.
769 Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {
770 // For immutable passes we have a direct mapping from ID to pass, so check
772 if (Pass *P = ImmutablePassMap.lookup(AID))
775 // Check pass managers
776 for (PMDataManager *PassManager : PassManagers)
777 if (Pass *P = PassManager->findAnalysisPass(AID, false))
780 // Check other pass managers
781 for (PMDataManager *IndirectPassManager : IndirectPassManagers)
782 if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))
788 const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {
789 const PassInfo *&PI = AnalysisPassInfos[AID];
791 PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
793 assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&
794 "The pass info pointer changed for an analysis ID!");
799 void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {
801 ImmutablePasses.push_back(P);
803 // Add this pass to the map from its analysis ID. We clobber any prior runs
804 // of the pass in the map so that the last one added is the one found when
806 AnalysisID AID = P->getPassID();
807 ImmutablePassMap[AID] = P;
809 // Also add any interfaces implemented by the immutable pass to the map for
811 const PassInfo *PassInf = findAnalysisPassInfo(AID);
812 assert(PassInf && "Expected all immutable passes to be initialized");
813 for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())
814 ImmutablePassMap[ImmPI->getTypeInfo()] = P;
817 // Print passes managed by this top level manager.
818 void PMTopLevelManager::dumpPasses() const {
820 if (PassDebugging < Structure)
823 // Print out the immutable passes
824 for (unsigned i = 0, e = ImmutablePasses.size(); i != e; ++i) {
825 ImmutablePasses[i]->dumpPassStructure(0);
828 // Every class that derives from PMDataManager also derives from Pass
829 // (sometimes indirectly), but there's no inheritance relationship
830 // between PMDataManager and Pass, so we have to getAsPass to get
831 // from a PMDataManager* to a Pass*.
832 for (PMDataManager *Manager : PassManagers)
833 Manager->getAsPass()->dumpPassStructure(1);
836 void PMTopLevelManager::dumpArguments() const {
838 if (PassDebugging < Arguments)
841 dbgs() << "Pass Arguments: ";
842 for (ImmutablePass *P : ImmutablePasses)
843 if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {
844 assert(PI && "Expected all immutable passes to be initialized");
845 if (!PI->isAnalysisGroup())
846 dbgs() << " -" << PI->getPassArgument();
848 for (PMDataManager *PM : PassManagers)
849 PM->dumpPassArguments();
853 void PMTopLevelManager::initializeAllAnalysisInfo() {
854 for (PMDataManager *PM : PassManagers)
855 PM->initializeAnalysisInfo();
857 // Initailize other pass managers
858 for (PMDataManager *IPM : IndirectPassManagers)
859 IPM->initializeAnalysisInfo();
861 for (auto LU : LastUser) {
862 SmallPtrSet<Pass *, 8> &L = InversedLastUser[LU.second];
868 PMTopLevelManager::~PMTopLevelManager() {
869 for (PMDataManager *PM : PassManagers)
872 for (ImmutablePass *P : ImmutablePasses)
876 //===----------------------------------------------------------------------===//
877 // PMDataManager implementation
879 /// Augement AvailableAnalysis by adding analysis made available by pass P.
880 void PMDataManager::recordAvailableAnalysis(Pass *P) {
881 AnalysisID PI = P->getPassID();
883 AvailableAnalysis[PI] = P;
885 assert(!AvailableAnalysis.empty());
887 // This pass is the current implementation of all of the interfaces it
888 // implements as well.
889 const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);
891 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
892 for (unsigned i = 0, e = II.size(); i != e; ++i)
893 AvailableAnalysis[II[i]->getTypeInfo()] = P;
896 // Return true if P preserves high level analysis used by other
897 // passes managed by this manager
898 bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {
899 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
900 if (AnUsage->getPreservesAll())
903 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
904 for (Pass *P1 : HigherLevelAnalysis) {
905 if (P1->getAsImmutablePass() == nullptr &&
906 !is_contained(PreservedSet, P1->getPassID()))
913 /// verifyPreservedAnalysis -- Verify analysis preserved by pass P.
914 void PMDataManager::verifyPreservedAnalysis(Pass *P) {
915 // Don't do this unless assertions are enabled.
919 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
920 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
922 // Verify preserved analysis
923 for (AnalysisID AID : PreservedSet) {
924 if (Pass *AP = findAnalysisPass(AID, true)) {
925 TimeRegion PassTimer(getPassTimer(AP));
926 AP->verifyAnalysis();
931 /// Remove Analysis not preserved by Pass P
932 void PMDataManager::removeNotPreservedAnalysis(Pass *P) {
933 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
934 if (AnUsage->getPreservesAll())
937 const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();
938 for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),
939 E = AvailableAnalysis.end(); I != E; ) {
940 DenseMap<AnalysisID, Pass*>::iterator Info = I++;
941 if (Info->second->getAsImmutablePass() == nullptr &&
942 !is_contained(PreservedSet, Info->first)) {
943 // Remove this analysis
944 if (PassDebugging >= Details) {
945 Pass *S = Info->second;
946 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
947 dbgs() << S->getPassName() << "'\n";
949 AvailableAnalysis.erase(Info);
953 // Check inherited analysis also. If P is not preserving analysis
954 // provided by parent manager then remove it here.
955 for (unsigned Index = 0; Index < PMT_Last; ++Index) {
957 if (!InheritedAnalysis[Index])
960 for (DenseMap<AnalysisID, Pass*>::iterator
961 I = InheritedAnalysis[Index]->begin(),
962 E = InheritedAnalysis[Index]->end(); I != E; ) {
963 DenseMap<AnalysisID, Pass *>::iterator Info = I++;
964 if (Info->second->getAsImmutablePass() == nullptr &&
965 !is_contained(PreservedSet, Info->first)) {
966 // Remove this analysis
967 if (PassDebugging >= Details) {
968 Pass *S = Info->second;
969 dbgs() << " -- '" << P->getPassName() << "' is not preserving '";
970 dbgs() << S->getPassName() << "'\n";
972 InheritedAnalysis[Index]->erase(Info);
978 /// Remove analysis passes that are not used any longer
979 void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,
980 enum PassDebuggingString DBG_STR) {
982 SmallVector<Pass *, 12> DeadPasses;
984 // If this is a on the fly manager then it does not have TPM.
988 TPM->collectLastUses(DeadPasses, P);
990 if (PassDebugging >= Details && !DeadPasses.empty()) {
991 dbgs() << " -*- '" << P->getPassName();
992 dbgs() << "' is the last user of following pass instances.";
993 dbgs() << " Free these instances\n";
996 for (Pass *P : DeadPasses)
997 freePass(P, Msg, DBG_STR);
1000 void PMDataManager::freePass(Pass *P, StringRef Msg,
1001 enum PassDebuggingString DBG_STR) {
1002 dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);
1005 // If the pass crashes releasing memory, remember this.
1006 PassManagerPrettyStackEntry X(P);
1007 TimeRegion PassTimer(getPassTimer(P));
1012 AnalysisID PI = P->getPassID();
1013 if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {
1014 // Remove the pass itself (if it is not already removed).
1015 AvailableAnalysis.erase(PI);
1017 // Remove all interfaces this pass implements, for which it is also
1018 // listed as the available implementation.
1019 const std::vector<const PassInfo*> &II = PInf->getInterfacesImplemented();
1020 for (unsigned i = 0, e = II.size(); i != e; ++i) {
1021 DenseMap<AnalysisID, Pass*>::iterator Pos =
1022 AvailableAnalysis.find(II[i]->getTypeInfo());
1023 if (Pos != AvailableAnalysis.end() && Pos->second == P)
1024 AvailableAnalysis.erase(Pos);
1029 /// Add pass P into the PassVector. Update
1030 /// AvailableAnalysis appropriately if ProcessAnalysis is true.
1031 void PMDataManager::add(Pass *P, bool ProcessAnalysis) {
1032 // This manager is going to manage pass P. Set up analysis resolver
1034 AnalysisResolver *AR = new AnalysisResolver(*this);
1037 // If a FunctionPass F is the last user of ModulePass info M
1038 // then the F's manager, not F, records itself as a last user of M.
1039 SmallVector<Pass *, 12> TransferLastUses;
1041 if (!ProcessAnalysis) {
1043 PassVector.push_back(P);
1047 // At the moment, this pass is the last user of all required passes.
1048 SmallVector<Pass *, 12> LastUses;
1049 SmallVector<Pass *, 8> UsedPasses;
1050 SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;
1052 unsigned PDepth = this->getDepth();
1054 collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);
1055 for (Pass *PUsed : UsedPasses) {
1056 unsigned RDepth = 0;
1058 assert(PUsed->getResolver() && "Analysis Resolver is not set");
1059 PMDataManager &DM = PUsed->getResolver()->getPMDataManager();
1060 RDepth = DM.getDepth();
1062 if (PDepth == RDepth)
1063 LastUses.push_back(PUsed);
1064 else if (PDepth > RDepth) {
1065 // Let the parent claim responsibility of last use
1066 TransferLastUses.push_back(PUsed);
1067 // Keep track of higher level analysis used by this manager.
1068 HigherLevelAnalysis.push_back(PUsed);
1070 llvm_unreachable("Unable to accommodate Used Pass");
1073 // Set P as P's last user until someone starts using P.
1074 // However, if P is a Pass Manager then it does not need
1075 // to record its last user.
1076 if (!P->getAsPMDataManager())
1077 LastUses.push_back(P);
1078 TPM->setLastUser(LastUses, P);
1080 if (!TransferLastUses.empty()) {
1081 Pass *My_PM = getAsPass();
1082 TPM->setLastUser(TransferLastUses, My_PM);
1083 TransferLastUses.clear();
1086 // Now, take care of required analyses that are not available.
1087 for (AnalysisID ID : ReqAnalysisNotAvailable) {
1088 const PassInfo *PI = TPM->findAnalysisPassInfo(ID);
1089 Pass *AnalysisPass = PI->createPass();
1090 this->addLowerLevelRequiredPass(P, AnalysisPass);
1093 // Take a note of analysis required and made available by this pass.
1094 // Remove the analysis not preserved by this pass
1095 removeNotPreservedAnalysis(P);
1096 recordAvailableAnalysis(P);
1099 PassVector.push_back(P);
1103 /// Populate UP with analysis pass that are used or required by
1104 /// pass P and are available. Populate RP_NotAvail with analysis
1105 /// pass that are required by pass P but are not available.
1106 void PMDataManager::collectRequiredAndUsedAnalyses(
1107 SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,
1109 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1111 for (const auto &UsedID : AnUsage->getUsedSet())
1112 if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))
1113 UP.push_back(AnalysisPass);
1115 for (const auto &RequiredID : AnUsage->getRequiredSet())
1116 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1117 UP.push_back(AnalysisPass);
1119 RP_NotAvail.push_back(RequiredID);
1121 for (const auto &RequiredID : AnUsage->getRequiredTransitiveSet())
1122 if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))
1123 UP.push_back(AnalysisPass);
1125 RP_NotAvail.push_back(RequiredID);
1128 // All Required analyses should be available to the pass as it runs! Here
1129 // we fill in the AnalysisImpls member of the pass so that it can
1130 // successfully use the getAnalysis() method to retrieve the
1131 // implementations it needs.
1133 void PMDataManager::initializeAnalysisImpl(Pass *P) {
1134 AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);
1136 for (const AnalysisID ID : AnUsage->getRequiredSet()) {
1137 Pass *Impl = findAnalysisPass(ID, true);
1139 // This may be analysis pass that is initialized on the fly.
1140 // If that is not the case then it will raise an assert when it is used.
1142 AnalysisResolver *AR = P->getResolver();
1143 assert(AR && "Analysis Resolver is not set");
1144 AR->addAnalysisImplsPair(ID, Impl);
1148 /// Find the pass that implements Analysis AID. If desired pass is not found
1149 /// then return NULL.
1150 Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {
1152 // Check if AvailableAnalysis map has one entry.
1153 DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);
1155 if (I != AvailableAnalysis.end())
1158 // Search Parents through TopLevelManager
1160 return TPM->findAnalysisPass(AID);
1165 // Print list of passes that are last used by P.
1166 void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{
1168 SmallVector<Pass *, 12> LUses;
1170 // If this is a on the fly manager then it does not have TPM.
1174 TPM->collectLastUses(LUses, P);
1176 for (Pass *P : LUses) {
1177 dbgs() << "--" << std::string(Offset*2, ' ');
1178 P->dumpPassStructure(0);
1182 void PMDataManager::dumpPassArguments() const {
1183 for (Pass *P : PassVector) {
1184 if (PMDataManager *PMD = P->getAsPMDataManager())
1185 PMD->dumpPassArguments();
1187 if (const PassInfo *PI =
1188 TPM->findAnalysisPassInfo(P->getPassID()))
1189 if (!PI->isAnalysisGroup())
1190 dbgs() << " -" << PI->getPassArgument();
1194 void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,
1195 enum PassDebuggingString S2,
1197 if (PassDebugging < Executions)
1199 dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this
1200 << std::string(getDepth() * 2 + 1, ' ');
1203 dbgs() << "Executing Pass '" << P->getPassName();
1205 case MODIFICATION_MSG:
1206 dbgs() << "Made Modification '" << P->getPassName();
1209 dbgs() << " Freeing Pass '" << P->getPassName();
1215 case ON_BASICBLOCK_MSG:
1216 dbgs() << "' on BasicBlock '" << Msg << "'...\n";
1218 case ON_FUNCTION_MSG:
1219 dbgs() << "' on Function '" << Msg << "'...\n";
1222 dbgs() << "' on Module '" << Msg << "'...\n";
1225 dbgs() << "' on Region '" << Msg << "'...\n";
1228 dbgs() << "' on Loop '" << Msg << "'...\n";
1231 dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";
1238 void PMDataManager::dumpRequiredSet(const Pass *P) const {
1239 if (PassDebugging < Details)
1242 AnalysisUsage analysisUsage;
1243 P->getAnalysisUsage(analysisUsage);
1244 dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());
1247 void PMDataManager::dumpPreservedSet(const Pass *P) const {
1248 if (PassDebugging < Details)
1251 AnalysisUsage analysisUsage;
1252 P->getAnalysisUsage(analysisUsage);
1253 dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());
1256 void PMDataManager::dumpUsedSet(const Pass *P) const {
1257 if (PassDebugging < Details)
1260 AnalysisUsage analysisUsage;
1261 P->getAnalysisUsage(analysisUsage);
1262 dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());
1265 void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,
1266 const AnalysisUsage::VectorType &Set) const {
1267 assert(PassDebugging >= Details);
1270 dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";
1271 for (unsigned i = 0; i != Set.size(); ++i) {
1272 if (i) dbgs() << ',';
1273 const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);
1275 // Some preserved passes, such as AliasAnalysis, may not be initialized by
1277 dbgs() << " Uninitialized Pass";
1280 dbgs() << ' ' << PInf->getPassName();
1285 /// Add RequiredPass into list of lower level passes required by pass P.
1286 /// RequiredPass is run on the fly by Pass Manager when P requests it
1287 /// through getAnalysis interface.
1288 /// This should be handled by specific pass manager.
1289 void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1291 TPM->dumpArguments();
1295 // Module Level pass may required Function Level analysis info
1296 // (e.g. dominator info). Pass manager uses on the fly function pass manager
1297 // to provide this on demand. In that case, in Pass manager terminology,
1298 // module level pass is requiring lower level analysis info managed by
1299 // lower level pass manager.
1301 // When Pass manager is not able to order required analysis info, Pass manager
1302 // checks whether any lower level manager will be able to provide this
1303 // analysis info on demand or not.
1305 dbgs() << "Unable to schedule '" << RequiredPass->getPassName();
1306 dbgs() << "' required by '" << P->getPassName() << "'\n";
1308 llvm_unreachable("Unable to schedule pass");
1311 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
1312 llvm_unreachable("Unable to find on the fly pass");
1316 PMDataManager::~PMDataManager() {
1317 for (Pass *P : PassVector)
1321 //===----------------------------------------------------------------------===//
1322 // NOTE: Is this the right place to define this method ?
1323 // getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.
1324 Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID, bool dir) const {
1325 return PM.findAnalysisPass(ID, dir);
1328 Pass *AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI,
1330 return PM.getOnTheFlyPass(P, AnalysisPI, F);
1333 //===----------------------------------------------------------------------===//
1334 // BBPassManager implementation
1336 /// Execute all of the passes scheduled for execution by invoking
1337 /// runOnBasicBlock method. Keep track of whether any of the passes modifies
1338 /// the function, and if so, return true.
1339 bool BBPassManager::runOnFunction(Function &F) {
1340 if (F.isDeclaration())
1343 bool Changed = doInitialization(F);
1344 Module &M = *F.getParent();
1346 unsigned InstrCount = 0;
1347 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1348 for (BasicBlock &BB : F)
1349 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1350 BasicBlockPass *BP = getContainedPass(Index);
1351 bool LocalChanged = false;
1353 dumpPassInfo(BP, EXECUTION_MSG, ON_BASICBLOCK_MSG, BB.getName());
1354 dumpRequiredSet(BP);
1356 initializeAnalysisImpl(BP);
1359 // If the pass crashes, remember this.
1360 PassManagerPrettyStackEntry X(BP, BB);
1361 TimeRegion PassTimer(getPassTimer(BP));
1363 InstrCount = initSizeRemarkInfo(M);
1364 LocalChanged |= BP->runOnBasicBlock(BB);
1366 emitInstrCountChangedRemark(BP, M, InstrCount);
1369 Changed |= LocalChanged;
1371 dumpPassInfo(BP, MODIFICATION_MSG, ON_BASICBLOCK_MSG,
1373 dumpPreservedSet(BP);
1376 verifyPreservedAnalysis(BP);
1377 removeNotPreservedAnalysis(BP);
1378 recordAvailableAnalysis(BP);
1379 removeDeadPasses(BP, BB.getName(), ON_BASICBLOCK_MSG);
1382 return doFinalization(F) || Changed;
1385 // Implement doInitialization and doFinalization
1386 bool BBPassManager::doInitialization(Module &M) {
1387 bool Changed = false;
1389 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1390 Changed |= getContainedPass(Index)->doInitialization(M);
1395 bool BBPassManager::doFinalization(Module &M) {
1396 bool Changed = false;
1398 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1399 Changed |= getContainedPass(Index)->doFinalization(M);
1404 bool BBPassManager::doInitialization(Function &F) {
1405 bool Changed = false;
1407 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1408 BasicBlockPass *BP = getContainedPass(Index);
1409 Changed |= BP->doInitialization(F);
1415 bool BBPassManager::doFinalization(Function &F) {
1416 bool Changed = false;
1418 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1419 BasicBlockPass *BP = getContainedPass(Index);
1420 Changed |= BP->doFinalization(F);
1427 //===----------------------------------------------------------------------===//
1428 // FunctionPassManager implementation
1430 /// Create new Function pass manager
1431 FunctionPassManager::FunctionPassManager(Module *m) : M(m) {
1432 FPM = new FunctionPassManagerImpl();
1433 // FPM is the top level manager.
1434 FPM->setTopLevelManager(FPM);
1436 AnalysisResolver *AR = new AnalysisResolver(*FPM);
1437 FPM->setResolver(AR);
1440 FunctionPassManager::~FunctionPassManager() {
1444 void FunctionPassManager::add(Pass *P) {
1448 /// run - Execute all of the passes scheduled for execution. Keep
1449 /// track of whether any of the passes modifies the function, and if
1450 /// so, return true.
1452 bool FunctionPassManager::run(Function &F) {
1453 handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {
1454 report_fatal_error("Error reading bitcode file: " + EIB.message());
1460 /// doInitialization - Run all of the initializers for the function passes.
1462 bool FunctionPassManager::doInitialization() {
1463 return FPM->doInitialization(*M);
1466 /// doFinalization - Run all of the finalizers for the function passes.
1468 bool FunctionPassManager::doFinalization() {
1469 return FPM->doFinalization(*M);
1472 //===----------------------------------------------------------------------===//
1473 // FunctionPassManagerImpl implementation
1475 bool FunctionPassManagerImpl::doInitialization(Module &M) {
1476 bool Changed = false;
1481 for (ImmutablePass *ImPass : getImmutablePasses())
1482 Changed |= ImPass->doInitialization(M);
1484 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1485 Changed |= getContainedManager(Index)->doInitialization(M);
1490 bool FunctionPassManagerImpl::doFinalization(Module &M) {
1491 bool Changed = false;
1493 for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)
1494 Changed |= getContainedManager(Index)->doFinalization(M);
1496 for (ImmutablePass *ImPass : getImmutablePasses())
1497 Changed |= ImPass->doFinalization(M);
1502 /// cleanup - After running all passes, clean up pass manager cache.
1503 void FPPassManager::cleanup() {
1504 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1505 FunctionPass *FP = getContainedPass(Index);
1506 AnalysisResolver *AR = FP->getResolver();
1507 assert(AR && "Analysis Resolver is not set");
1508 AR->clearAnalysisImpls();
1512 void FunctionPassManagerImpl::releaseMemoryOnTheFly() {
1515 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1516 FPPassManager *FPPM = getContainedManager(Index);
1517 for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {
1518 FPPM->getContainedPass(Index)->releaseMemory();
1524 // Execute all the passes managed by this top level manager.
1525 // Return true if any function is modified by a pass.
1526 bool FunctionPassManagerImpl::run(Function &F) {
1527 bool Changed = false;
1528 TimingInfo::createTheTimeInfo();
1530 initializeAllAnalysisInfo();
1531 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1532 Changed |= getContainedManager(Index)->runOnFunction(F);
1533 F.getContext().yield();
1536 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)
1537 getContainedManager(Index)->cleanup();
1543 //===----------------------------------------------------------------------===//
1544 // FPPassManager implementation
1546 char FPPassManager::ID = 0;
1547 /// Print passes managed by this manager
1548 void FPPassManager::dumpPassStructure(unsigned Offset) {
1549 dbgs().indent(Offset*2) << "FunctionPass Manager\n";
1550 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1551 FunctionPass *FP = getContainedPass(Index);
1552 FP->dumpPassStructure(Offset + 1);
1553 dumpLastUses(FP, Offset+1);
1558 /// Execute all of the passes scheduled for execution by invoking
1559 /// runOnFunction method. Keep track of whether any of the passes modifies
1560 /// the function, and if so, return true.
1561 bool FPPassManager::runOnFunction(Function &F) {
1562 if (F.isDeclaration())
1565 bool Changed = false;
1566 Module &M = *F.getParent();
1567 // Collect inherited analysis from Module level pass manager.
1568 populateInheritedAnalysis(TPM->activeStack);
1570 unsigned InstrCount = 0;
1571 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1572 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1573 FunctionPass *FP = getContainedPass(Index);
1574 bool LocalChanged = false;
1576 dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, F.getName());
1577 dumpRequiredSet(FP);
1579 initializeAnalysisImpl(FP);
1582 PassManagerPrettyStackEntry X(FP, F);
1583 TimeRegion PassTimer(getPassTimer(FP));
1585 InstrCount = initSizeRemarkInfo(M);
1586 LocalChanged |= FP->runOnFunction(F);
1588 emitInstrCountChangedRemark(FP, M, InstrCount);
1591 Changed |= LocalChanged;
1593 dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, F.getName());
1594 dumpPreservedSet(FP);
1597 verifyPreservedAnalysis(FP);
1598 removeNotPreservedAnalysis(FP);
1599 recordAvailableAnalysis(FP);
1600 removeDeadPasses(FP, F.getName(), ON_FUNCTION_MSG);
1605 bool FPPassManager::runOnModule(Module &M) {
1606 bool Changed = false;
1608 for (Function &F : M)
1609 Changed |= runOnFunction(F);
1614 bool FPPassManager::doInitialization(Module &M) {
1615 bool Changed = false;
1617 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1618 Changed |= getContainedPass(Index)->doInitialization(M);
1623 bool FPPassManager::doFinalization(Module &M) {
1624 bool Changed = false;
1626 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1627 Changed |= getContainedPass(Index)->doFinalization(M);
1632 //===----------------------------------------------------------------------===//
1633 // MPPassManager implementation
1635 /// Execute all of the passes scheduled for execution by invoking
1636 /// runOnModule method. Keep track of whether any of the passes modifies
1637 /// the module, and if so, return true.
1639 MPPassManager::runOnModule(Module &M) {
1640 bool Changed = false;
1642 // Initialize on-the-fly passes
1643 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1644 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1645 Changed |= FPP->doInitialization(M);
1648 // Initialize module passes
1649 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)
1650 Changed |= getContainedPass(Index)->doInitialization(M);
1652 unsigned InstrCount = 0;
1653 bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();
1654 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
1655 ModulePass *MP = getContainedPass(Index);
1656 bool LocalChanged = false;
1658 dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());
1659 dumpRequiredSet(MP);
1661 initializeAnalysisImpl(MP);
1664 PassManagerPrettyStackEntry X(MP, M);
1665 TimeRegion PassTimer(getPassTimer(MP));
1668 InstrCount = initSizeRemarkInfo(M);
1669 LocalChanged |= MP->runOnModule(M);
1671 emitInstrCountChangedRemark(MP, M, InstrCount);
1674 Changed |= LocalChanged;
1676 dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,
1677 M.getModuleIdentifier());
1678 dumpPreservedSet(MP);
1681 verifyPreservedAnalysis(MP);
1682 removeNotPreservedAnalysis(MP);
1683 recordAvailableAnalysis(MP);
1684 removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);
1687 // Finalize module passes
1688 for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)
1689 Changed |= getContainedPass(Index)->doFinalization(M);
1691 // Finalize on-the-fly passes
1692 for (auto &OnTheFlyManager : OnTheFlyManagers) {
1693 FunctionPassManagerImpl *FPP = OnTheFlyManager.second;
1694 // We don't know when is the last time an on-the-fly pass is run,
1695 // so we need to releaseMemory / finalize here
1696 FPP->releaseMemoryOnTheFly();
1697 Changed |= FPP->doFinalization(M);
1703 /// Add RequiredPass into list of lower level passes required by pass P.
1704 /// RequiredPass is run on the fly by Pass Manager when P requests it
1705 /// through getAnalysis interface.
1706 void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {
1707 assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&
1708 "Unable to handle Pass that requires lower level Analysis pass");
1709 assert((P->getPotentialPassManagerType() <
1710 RequiredPass->getPotentialPassManagerType()) &&
1711 "Unable to handle Pass that requires lower level Analysis pass");
1715 FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];
1717 FPP = new FunctionPassManagerImpl();
1718 // FPP is the top level manager.
1719 FPP->setTopLevelManager(FPP);
1721 OnTheFlyManagers[P] = FPP;
1723 const PassInfo *RequiredPassPI =
1724 TPM->findAnalysisPassInfo(RequiredPass->getPassID());
1726 Pass *FoundPass = nullptr;
1727 if (RequiredPassPI && RequiredPassPI->isAnalysis()) {
1729 ((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());
1732 FoundPass = RequiredPass;
1733 // This should be guaranteed to add RequiredPass to the passmanager given
1734 // that we checked for an available analysis above.
1735 FPP->add(RequiredPass);
1737 // Register P as the last user of FoundPass or RequiredPass.
1738 SmallVector<Pass *, 1> LU;
1739 LU.push_back(FoundPass);
1740 FPP->setLastUser(LU, P);
1743 /// Return function pass corresponding to PassInfo PI, that is
1744 /// required by module pass MP. Instantiate analysis pass, by using
1745 /// its runOnFunction() for function F.
1746 Pass* MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI, Function &F){
1747 FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];
1748 assert(FPP && "Unable to find on the fly pass");
1750 FPP->releaseMemoryOnTheFly();
1752 return ((PMTopLevelManager*)FPP)->findAnalysisPass(PI);
1756 //===----------------------------------------------------------------------===//
1757 // PassManagerImpl implementation
1760 /// run - Execute all of the passes scheduled for execution. Keep track of
1761 /// whether any of the passes modifies the module, and if so, return true.
1762 bool PassManagerImpl::run(Module &M) {
1763 bool Changed = false;
1764 TimingInfo::createTheTimeInfo();
1769 for (ImmutablePass *ImPass : getImmutablePasses())
1770 Changed |= ImPass->doInitialization(M);
1772 initializeAllAnalysisInfo();
1773 for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {
1774 Changed |= getContainedManager(Index)->runOnModule(M);
1775 M.getContext().yield();
1778 for (ImmutablePass *ImPass : getImmutablePasses())
1779 Changed |= ImPass->doFinalization(M);
1784 //===----------------------------------------------------------------------===//
1785 // PassManager implementation
1787 /// Create new pass manager
1788 PassManager::PassManager() {
1789 PM = new PassManagerImpl();
1790 // PM is the top level manager
1791 PM->setTopLevelManager(PM);
1794 PassManager::~PassManager() {
1798 void PassManager::add(Pass *P) {
1802 /// run - Execute all of the passes scheduled for execution. Keep track of
1803 /// whether any of the passes modifies the module, and if so, return true.
1804 bool PassManager::run(Module &M) {
1808 //===----------------------------------------------------------------------===//
1809 // TimingInfo implementation
1811 bool llvm::TimePassesIsEnabled = false;
1812 static cl::opt<bool, true> EnableTiming(
1813 "time-passes", cl::location(TimePassesIsEnabled), cl::Hidden,
1814 cl::desc("Time each pass, printing elapsed time for each on exit"));
1816 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
1817 // a non-null value (if the -time-passes option is enabled) or it leaves it
1818 // null. It may be called multiple times.
1819 void TimingInfo::createTheTimeInfo() {
1820 if (!TimePassesIsEnabled || TheTimeInfo) return;
1822 // Constructed the first time this is called, iff -time-passes is enabled.
1823 // This guarantees that the object will be constructed before static globals,
1824 // thus it will be destroyed before them.
1825 static ManagedStatic<TimingInfo> TTI;
1826 TheTimeInfo = &*TTI;
1829 /// If TimingInfo is enabled then start pass timer.
1830 Timer *llvm::getPassTimer(Pass *P) {
1832 return TheTimeInfo->getPassTimer(P);
1836 /// If timing is enabled, report the times collected up to now and then reset
1838 void llvm::reportAndResetTimings() {
1840 TheTimeInfo->print();
1843 //===----------------------------------------------------------------------===//
1844 // PMStack implementation
1847 // Pop Pass Manager from the stack and clear its analysis info.
1848 void PMStack::pop() {
1850 PMDataManager *Top = this->top();
1851 Top->initializeAnalysisInfo();
1856 // Push PM on the stack and set its top level manager.
1857 void PMStack::push(PMDataManager *PM) {
1858 assert(PM && "Unable to push. Pass Manager expected");
1859 assert(PM->getDepth()==0 && "Pass Manager depth set too early");
1861 if (!this->empty()) {
1862 assert(PM->getPassManagerType() > this->top()->getPassManagerType()
1863 && "pushing bad pass manager to PMStack");
1864 PMTopLevelManager *TPM = this->top()->getTopLevelManager();
1866 assert(TPM && "Unable to find top level manager");
1867 TPM->addIndirectPassManager(PM);
1868 PM->setTopLevelManager(TPM);
1869 PM->setDepth(this->top()->getDepth()+1);
1871 assert((PM->getPassManagerType() == PMT_ModulePassManager
1872 || PM->getPassManagerType() == PMT_FunctionPassManager)
1873 && "pushing bad pass manager to PMStack");
1880 // Dump content of the pass manager stack.
1881 LLVM_DUMP_METHOD void PMStack::dump() const {
1882 for (PMDataManager *Manager : S)
1883 dbgs() << Manager->getAsPass()->getPassName() << ' ';
1889 /// Find appropriate Module Pass Manager in the PM Stack and
1890 /// add self into that manager.
1891 void ModulePass::assignPassManager(PMStack &PMS,
1892 PassManagerType PreferredType) {
1893 // Find Module Pass Manager
1894 while (!PMS.empty()) {
1895 PassManagerType TopPMType = PMS.top()->getPassManagerType();
1896 if (TopPMType == PreferredType)
1897 break; // We found desired pass manager
1898 else if (TopPMType > PMT_ModulePassManager)
1899 PMS.pop(); // Pop children pass managers
1903 assert(!PMS.empty() && "Unable to find appropriate Pass Manager");
1904 PMS.top()->add(this);
1907 /// Find appropriate Function Pass Manager or Call Graph Pass Manager
1908 /// in the PM Stack and add self into that manager.
1909 void FunctionPass::assignPassManager(PMStack &PMS,
1910 PassManagerType PreferredType) {
1912 // Find Function Pass Manager
1913 while (!PMS.empty()) {
1914 if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
1920 // Create new Function Pass Manager if needed.
1922 if (PMS.top()->getPassManagerType() == PMT_FunctionPassManager) {
1923 FPP = (FPPassManager *)PMS.top();
1925 assert(!PMS.empty() && "Unable to create Function Pass Manager");
1926 PMDataManager *PMD = PMS.top();
1928 // [1] Create new Function Pass Manager
1929 FPP = new FPPassManager();
1930 FPP->populateInheritedAnalysis(PMS);
1932 // [2] Set up new manager's top level manager
1933 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1934 TPM->addIndirectPassManager(FPP);
1936 // [3] Assign manager to manage this new manager. This may create
1937 // and push new managers into PMS
1938 FPP->assignPassManager(PMS, PMD->getPassManagerType());
1940 // [4] Push new manager into PMS
1944 // Assign FPP as the manager of this pass.
1948 /// Find appropriate Basic Pass Manager or Call Graph Pass Manager
1949 /// in the PM Stack and add self into that manager.
1950 void BasicBlockPass::assignPassManager(PMStack &PMS,
1951 PassManagerType PreferredType) {
1954 // Basic Pass Manager is a leaf pass manager. It does not handle
1955 // any other pass manager.
1957 PMS.top()->getPassManagerType() == PMT_BasicBlockPassManager) {
1958 BBP = (BBPassManager *)PMS.top();
1960 // If leaf manager is not Basic Block Pass manager then create new
1961 // basic Block Pass manager.
1962 assert(!PMS.empty() && "Unable to create BasicBlock Pass Manager");
1963 PMDataManager *PMD = PMS.top();
1965 // [1] Create new Basic Block Manager
1966 BBP = new BBPassManager();
1968 // [2] Set up new manager's top level manager
1969 // Basic Block Pass Manager does not live by itself
1970 PMTopLevelManager *TPM = PMD->getTopLevelManager();
1971 TPM->addIndirectPassManager(BBP);
1973 // [3] Assign manager to manage this new manager. This may create
1974 // and push new managers into PMS
1975 BBP->assignPassManager(PMS, PreferredType);
1977 // [4] Push new manager into PMS
1981 // Assign BBP as the manager of this pass.
1985 PassManagerBase::~PassManagerBase() {}