Path: blob/main/contrib/llvm-project/llvm/lib/IR/LegacyPassManager.cpp
35234 views
//===- LegacyPassManager.cpp - LLVM Pass Infrastructure Implementation ----===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the legacy LLVM Pass Manager infrastructure.9//10//===----------------------------------------------------------------------===//1112#include "llvm/IR/LegacyPassManager.h"13#include "llvm/ADT/MapVector.h"14#include "llvm/IR/DiagnosticInfo.h"15#include "llvm/IR/IRPrintingPasses.h"16#include "llvm/IR/LLVMContext.h"17#include "llvm/IR/LegacyPassManagers.h"18#include "llvm/IR/Module.h"19#include "llvm/IR/PassTimingInfo.h"20#include "llvm/IR/PrintPasses.h"21#include "llvm/Support/Chrono.h"22#include "llvm/Support/CommandLine.h"23#include "llvm/Support/Debug.h"24#include "llvm/Support/Error.h"25#include "llvm/Support/ErrorHandling.h"26#include "llvm/Support/TimeProfiler.h"27#include "llvm/Support/Timer.h"28#include "llvm/Support/raw_ostream.h"29#include <algorithm>3031using namespace llvm;3233extern cl::opt<bool> UseNewDbgInfoFormat;34// See PassManagers.h for Pass Manager infrastructure overview.3536//===----------------------------------------------------------------------===//37// Pass debugging information. Often it is useful to find out what pass is38// running when a crash occurs in a utility. When this library is compiled with39// debugging on, a command line option (--debug-pass) is enabled that causes the40// pass name to be printed before it executes.41//4243namespace {44// Different debug levels that can be enabled...45enum PassDebugLevel {46Disabled, Arguments, Structure, Executions, Details47};48} // namespace4950static cl::opt<enum PassDebugLevel> PassDebugging(51"debug-pass", cl::Hidden,52cl::desc("Print legacy PassManager debugging information"),53cl::values(clEnumVal(Disabled, "disable debug output"),54clEnumVal(Arguments, "print pass arguments to pass to 'opt'"),55clEnumVal(Structure, "print pass structure before run()"),56clEnumVal(Executions, "print pass name before it is executed"),57clEnumVal(Details, "print pass details when it is executed")));5859/// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=Executions60/// or higher is specified.61bool PMDataManager::isPassDebuggingExecutionsOrMore() const {62return PassDebugging >= Executions;63}6465unsigned PMDataManager::initSizeRemarkInfo(66Module &M, StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount) {67// Only calculate getInstructionCount if the size-info remark is requested.68unsigned InstrCount = 0;6970// Collect instruction counts for every function. We'll use this to emit71// per-function size remarks later.72for (Function &F : M) {73unsigned FCount = F.getInstructionCount();7475// Insert a record into FunctionToInstrCount keeping track of the current76// size of the function as the first member of a pair. Set the second77// member to 0; if the function is deleted by the pass, then when we get78// here, we'll be able to let the user know that F no longer contributes to79// the module.80FunctionToInstrCount[F.getName().str()] =81std::pair<unsigned, unsigned>(FCount, 0);82InstrCount += FCount;83}84return InstrCount;85}8687void PMDataManager::emitInstrCountChangedRemark(88Pass *P, Module &M, int64_t Delta, unsigned CountBefore,89StringMap<std::pair<unsigned, unsigned>> &FunctionToInstrCount,90Function *F) {91// If it's a pass manager, don't emit a remark. (This hinges on the assumption92// that the only passes that return non-null with getAsPMDataManager are pass93// managers.) The reason we have to do this is to avoid emitting remarks for94// CGSCC passes.95if (P->getAsPMDataManager())96return;9798// Set to true if this isn't a module pass or CGSCC pass.99bool CouldOnlyImpactOneFunction = (F != nullptr);100101// Helper lambda that updates the changes to the size of some function.102auto UpdateFunctionChanges =103[&FunctionToInstrCount](Function &MaybeChangedFn) {104// Update the total module count.105unsigned FnSize = MaybeChangedFn.getInstructionCount();106auto It = FunctionToInstrCount.find(MaybeChangedFn.getName());107108// If we created a new function, then we need to add it to the map and109// say that it changed from 0 instructions to FnSize.110if (It == FunctionToInstrCount.end()) {111FunctionToInstrCount[MaybeChangedFn.getName()] =112std::pair<unsigned, unsigned>(0, FnSize);113return;114}115// Insert the new function size into the second member of the pair. This116// tells us whether or not this function changed in size.117It->second.second = FnSize;118};119120// We need to initially update all of the function sizes.121// If no function was passed in, then we're either a module pass or an122// CGSCC pass.123if (!CouldOnlyImpactOneFunction)124std::for_each(M.begin(), M.end(), UpdateFunctionChanges);125else126UpdateFunctionChanges(*F);127128// Do we have a function we can use to emit a remark?129if (!CouldOnlyImpactOneFunction) {130// We need a function containing at least one basic block in order to output131// remarks. Since it's possible that the first function in the module132// doesn't actually contain a basic block, we have to go and find one that's133// suitable for emitting remarks.134auto It = llvm::find_if(M, [](const Function &Fn) { return !Fn.empty(); });135136// Didn't find a function. Quit.137if (It == M.end())138return;139140// We found a function containing at least one basic block.141F = &*It;142}143int64_t CountAfter = static_cast<int64_t>(CountBefore) + Delta;144BasicBlock &BB = *F->begin();145OptimizationRemarkAnalysis R("size-info", "IRSizeChange",146DiagnosticLocation(), &BB);147// FIXME: Move ore namespace to DiagnosticInfo so that we can use it. This148// would let us use NV instead of DiagnosticInfoOptimizationBase::Argument.149R << DiagnosticInfoOptimizationBase::Argument("Pass", P->getPassName())150<< ": IR instruction count changed from "151<< DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore", CountBefore)152<< " to "153<< DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter", CountAfter)154<< "; Delta: "155<< DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", Delta);156F->getContext().diagnose(R); // Not using ORE for layering reasons.157158// Emit per-function size change remarks separately.159std::string PassName = P->getPassName().str();160161// Helper lambda that emits a remark when the size of a function has changed.162auto EmitFunctionSizeChangedRemark = [&FunctionToInstrCount, &F, &BB,163&PassName](StringRef Fname) {164unsigned FnCountBefore, FnCountAfter;165std::pair<unsigned, unsigned> &Change = FunctionToInstrCount[Fname];166std::tie(FnCountBefore, FnCountAfter) = Change;167int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -168static_cast<int64_t>(FnCountBefore);169170if (FnDelta == 0)171return;172173// FIXME: We shouldn't use BB for the location here. Unfortunately, because174// the function that we're looking at could have been deleted, we can't use175// it for the source location. We *want* remarks when a function is deleted176// though, so we're kind of stuck here as is. (This remark, along with the177// whole-module size change remarks really ought not to have source178// locations at all.)179OptimizationRemarkAnalysis FR("size-info", "FunctionIRSizeChange",180DiagnosticLocation(), &BB);181FR << DiagnosticInfoOptimizationBase::Argument("Pass", PassName)182<< ": Function: "183<< DiagnosticInfoOptimizationBase::Argument("Function", Fname)184<< ": IR instruction count changed from "185<< DiagnosticInfoOptimizationBase::Argument("IRInstrsBefore",186FnCountBefore)187<< " to "188<< DiagnosticInfoOptimizationBase::Argument("IRInstrsAfter",189FnCountAfter)190<< "; Delta: "191<< DiagnosticInfoOptimizationBase::Argument("DeltaInstrCount", FnDelta);192F->getContext().diagnose(FR);193194// Update the function size.195Change.first = FnCountAfter;196};197198// Are we looking at more than one function? If so, emit remarks for all of199// the functions in the module. Otherwise, only emit one remark.200if (!CouldOnlyImpactOneFunction)201std::for_each(FunctionToInstrCount.keys().begin(),202FunctionToInstrCount.keys().end(),203EmitFunctionSizeChangedRemark);204else205EmitFunctionSizeChangedRemark(F->getName().str());206}207208void PassManagerPrettyStackEntry::print(raw_ostream &OS) const {209if (!V && !M)210OS << "Releasing pass '";211else212OS << "Running pass '";213214OS << P->getPassName() << "'";215216if (M) {217OS << " on module '" << M->getModuleIdentifier() << "'.\n";218return;219}220if (!V) {221OS << '\n';222return;223}224225OS << " on ";226if (isa<Function>(V))227OS << "function";228else if (isa<BasicBlock>(V))229OS << "basic block";230else231OS << "value";232233OS << " '";234V->printAsOperand(OS, /*PrintType=*/false, M);235OS << "'\n";236}237238namespace llvm {239namespace legacy {240bool debugPassSpecified() { return PassDebugging != Disabled; }241242//===----------------------------------------------------------------------===//243// FunctionPassManagerImpl244//245/// FunctionPassManagerImpl manages FPPassManagers246class FunctionPassManagerImpl : public Pass,247public PMDataManager,248public PMTopLevelManager {249virtual void anchor();250private:251bool wasRun;252public:253static char ID;254explicit FunctionPassManagerImpl()255: Pass(PT_PassManager, ID), PMTopLevelManager(new FPPassManager()),256wasRun(false) {}257258/// \copydoc FunctionPassManager::add()259void add(Pass *P) {260schedulePass(P);261}262263/// createPrinterPass - Get a function printer pass.264Pass *createPrinterPass(raw_ostream &O,265const std::string &Banner) const override {266return createPrintFunctionPass(O, Banner);267}268269// Prepare for running an on the fly pass, freeing memory if needed270// from a previous run.271void releaseMemoryOnTheFly();272273/// run - Execute all of the passes scheduled for execution. Keep track of274/// whether any of the passes modifies the module, and if so, return true.275bool run(Function &F);276277/// doInitialization - Run all of the initializers for the function passes.278///279bool doInitialization(Module &M) override;280281/// doFinalization - Run all of the finalizers for the function passes.282///283bool doFinalization(Module &M) override;284285286PMDataManager *getAsPMDataManager() override { return this; }287Pass *getAsPass() override { return this; }288PassManagerType getTopLevelPassManagerType() override {289return PMT_FunctionPassManager;290}291292/// Pass Manager itself does not invalidate any analysis info.293void getAnalysisUsage(AnalysisUsage &Info) const override {294Info.setPreservesAll();295}296297FPPassManager *getContainedManager(unsigned N) {298assert(N < PassManagers.size() && "Pass number out of range!");299FPPassManager *FP = static_cast<FPPassManager *>(PassManagers[N]);300return FP;301}302303void dumpPassStructure(unsigned Offset) override {304for (unsigned I = 0; I < getNumContainedManagers(); ++I)305getContainedManager(I)->dumpPassStructure(Offset);306}307};308309void FunctionPassManagerImpl::anchor() {}310311char FunctionPassManagerImpl::ID = 0;312313//===----------------------------------------------------------------------===//314// FunctionPassManagerImpl implementation315//316bool FunctionPassManagerImpl::doInitialization(Module &M) {317bool Changed = false;318319dumpArguments();320dumpPasses();321322for (ImmutablePass *ImPass : getImmutablePasses())323Changed |= ImPass->doInitialization(M);324325for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)326Changed |= getContainedManager(Index)->doInitialization(M);327328return Changed;329}330331bool FunctionPassManagerImpl::doFinalization(Module &M) {332bool Changed = false;333334for (int Index = getNumContainedManagers() - 1; Index >= 0; --Index)335Changed |= getContainedManager(Index)->doFinalization(M);336337for (ImmutablePass *ImPass : getImmutablePasses())338Changed |= ImPass->doFinalization(M);339340return Changed;341}342343void FunctionPassManagerImpl::releaseMemoryOnTheFly() {344if (!wasRun)345return;346for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {347FPPassManager *FPPM = getContainedManager(Index);348for (unsigned Index = 0; Index < FPPM->getNumContainedPasses(); ++Index) {349FPPM->getContainedPass(Index)->releaseMemory();350}351}352wasRun = false;353}354355// Execute all the passes managed by this top level manager.356// Return true if any function is modified by a pass.357bool FunctionPassManagerImpl::run(Function &F) {358bool Changed = false;359360initializeAllAnalysisInfo();361for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {362Changed |= getContainedManager(Index)->runOnFunction(F);363F.getContext().yield();364}365366for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index)367getContainedManager(Index)->cleanup();368369wasRun = true;370return Changed;371}372} // namespace legacy373} // namespace llvm374375namespace {376//===----------------------------------------------------------------------===//377// MPPassManager378//379/// MPPassManager manages ModulePasses and function pass managers.380/// It batches all Module passes and function pass managers together and381/// sequences them to process one module.382class MPPassManager : public Pass, public PMDataManager {383public:384static char ID;385explicit MPPassManager() : Pass(PT_PassManager, ID) {}386387// Delete on the fly managers.388~MPPassManager() override {389for (auto &OnTheFlyManager : OnTheFlyManagers) {390legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;391delete FPP;392}393}394395/// createPrinterPass - Get a module printer pass.396Pass *createPrinterPass(raw_ostream &O,397const std::string &Banner) const override {398return createPrintModulePass(O, Banner);399}400401/// run - Execute all of the passes scheduled for execution. Keep track of402/// whether any of the passes modifies the module, and if so, return true.403bool runOnModule(Module &M);404405using llvm::Pass::doInitialization;406using llvm::Pass::doFinalization;407408/// Pass Manager itself does not invalidate any analysis info.409void getAnalysisUsage(AnalysisUsage &Info) const override {410Info.setPreservesAll();411}412413/// Add RequiredPass into list of lower level passes required by pass P.414/// RequiredPass is run on the fly by Pass Manager when P requests it415/// through getAnalysis interface.416void addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) override;417418/// Return function pass corresponding to PassInfo PI, that is419/// required by module pass MP. Instantiate analysis pass, by using420/// its runOnFunction() for function F.421std::tuple<Pass *, bool> getOnTheFlyPass(Pass *MP, AnalysisID PI,422Function &F) override;423424StringRef getPassName() const override { return "Module Pass Manager"; }425426PMDataManager *getAsPMDataManager() override { return this; }427Pass *getAsPass() override { return this; }428429// Print passes managed by this manager430void dumpPassStructure(unsigned Offset) override {431dbgs().indent(Offset*2) << "ModulePass Manager\n";432for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {433ModulePass *MP = getContainedPass(Index);434MP->dumpPassStructure(Offset + 1);435MapVector<Pass *, legacy::FunctionPassManagerImpl *>::const_iterator I =436OnTheFlyManagers.find(MP);437if (I != OnTheFlyManagers.end())438I->second->dumpPassStructure(Offset + 2);439dumpLastUses(MP, Offset+1);440}441}442443ModulePass *getContainedPass(unsigned N) {444assert(N < PassVector.size() && "Pass number out of range!");445return static_cast<ModulePass *>(PassVector[N]);446}447448PassManagerType getPassManagerType() const override {449return PMT_ModulePassManager;450}451452private:453/// Collection of on the fly FPPassManagers. These managers manage454/// function passes that are required by module passes.455MapVector<Pass *, legacy::FunctionPassManagerImpl *> OnTheFlyManagers;456};457458char MPPassManager::ID = 0;459} // End anonymous namespace460461namespace llvm {462namespace legacy {463//===----------------------------------------------------------------------===//464// PassManagerImpl465//466467/// PassManagerImpl manages MPPassManagers468class PassManagerImpl : public Pass,469public PMDataManager,470public PMTopLevelManager {471virtual void anchor();472473public:474static char ID;475explicit PassManagerImpl()476: Pass(PT_PassManager, ID), PMTopLevelManager(new MPPassManager()) {}477478/// \copydoc PassManager::add()479void add(Pass *P) {480schedulePass(P);481}482483/// createPrinterPass - Get a module printer pass.484Pass *createPrinterPass(raw_ostream &O,485const std::string &Banner) const override {486return createPrintModulePass(O, Banner);487}488489/// run - Execute all of the passes scheduled for execution. Keep track of490/// whether any of the passes modifies the module, and if so, return true.491bool run(Module &M);492493using llvm::Pass::doInitialization;494using llvm::Pass::doFinalization;495496/// Pass Manager itself does not invalidate any analysis info.497void getAnalysisUsage(AnalysisUsage &Info) const override {498Info.setPreservesAll();499}500501PMDataManager *getAsPMDataManager() override { return this; }502Pass *getAsPass() override { return this; }503PassManagerType getTopLevelPassManagerType() override {504return PMT_ModulePassManager;505}506507MPPassManager *getContainedManager(unsigned N) {508assert(N < PassManagers.size() && "Pass number out of range!");509MPPassManager *MP = static_cast<MPPassManager *>(PassManagers[N]);510return MP;511}512};513514void PassManagerImpl::anchor() {}515516char PassManagerImpl::ID = 0;517518//===----------------------------------------------------------------------===//519// PassManagerImpl implementation520521//522/// run - Execute all of the passes scheduled for execution. Keep track of523/// whether any of the passes modifies the module, and if so, return true.524bool PassManagerImpl::run(Module &M) {525bool Changed = false;526527dumpArguments();528dumpPasses();529530// RemoveDIs: if a command line flag is given, convert to the531// DbgVariableRecord representation of debug-info for the duration of these532// passes.533ScopedDbgInfoFormatSetter FormatSetter(M, UseNewDbgInfoFormat);534535for (ImmutablePass *ImPass : getImmutablePasses())536Changed |= ImPass->doInitialization(M);537538initializeAllAnalysisInfo();539for (unsigned Index = 0; Index < getNumContainedManagers(); ++Index) {540Changed |= getContainedManager(Index)->runOnModule(M);541M.getContext().yield();542}543544for (ImmutablePass *ImPass : getImmutablePasses())545Changed |= ImPass->doFinalization(M);546547return Changed;548}549} // namespace legacy550} // namespace llvm551552//===----------------------------------------------------------------------===//553// PMTopLevelManager implementation554555/// Initialize top level manager. Create first pass manager.556PMTopLevelManager::PMTopLevelManager(PMDataManager *PMDM) {557PMDM->setTopLevelManager(this);558addPassManager(PMDM);559activeStack.push(PMDM);560}561562/// Set pass P as the last user of the given analysis passes.563void564PMTopLevelManager::setLastUser(ArrayRef<Pass*> AnalysisPasses, Pass *P) {565unsigned PDepth = 0;566if (P->getResolver())567PDepth = P->getResolver()->getPMDataManager().getDepth();568569for (Pass *AP : AnalysisPasses) {570// Record P as the new last user of AP.571auto &LastUserOfAP = LastUser[AP];572if (LastUserOfAP)573InversedLastUser[LastUserOfAP].erase(AP);574LastUserOfAP = P;575InversedLastUser[P].insert(AP);576577if (P == AP)578continue;579580// Update the last users of passes that are required transitive by AP.581AnalysisUsage *AnUsage = findAnalysisUsage(AP);582const AnalysisUsage::VectorType &IDs = AnUsage->getRequiredTransitiveSet();583SmallVector<Pass *, 12> LastUses;584SmallVector<Pass *, 12> LastPMUses;585for (AnalysisID ID : IDs) {586Pass *AnalysisPass = findAnalysisPass(ID);587assert(AnalysisPass && "Expected analysis pass to exist.");588AnalysisResolver *AR = AnalysisPass->getResolver();589assert(AR && "Expected analysis resolver to exist.");590unsigned APDepth = AR->getPMDataManager().getDepth();591592if (PDepth == APDepth)593LastUses.push_back(AnalysisPass);594else if (PDepth > APDepth)595LastPMUses.push_back(AnalysisPass);596}597598setLastUser(LastUses, P);599600// If this pass has a corresponding pass manager, push higher level601// analysis to this pass manager.602if (P->getResolver())603setLastUser(LastPMUses, P->getResolver()->getPMDataManager().getAsPass());604605// If AP is the last user of other passes then make P last user of606// such passes.607auto &LastUsedByAP = InversedLastUser[AP];608for (Pass *L : LastUsedByAP)609LastUser[L] = P;610InversedLastUser[P].insert(LastUsedByAP.begin(), LastUsedByAP.end());611LastUsedByAP.clear();612}613}614615/// Collect passes whose last user is P616void PMTopLevelManager::collectLastUses(SmallVectorImpl<Pass *> &LastUses,617Pass *P) {618auto DMI = InversedLastUser.find(P);619if (DMI == InversedLastUser.end())620return;621622auto &LU = DMI->second;623LastUses.append(LU.begin(), LU.end());624}625626AnalysisUsage *PMTopLevelManager::findAnalysisUsage(Pass *P) {627AnalysisUsage *AnUsage = nullptr;628auto DMI = AnUsageMap.find(P);629if (DMI != AnUsageMap.end())630AnUsage = DMI->second;631else {632// Look up the analysis usage from the pass instance (different instances633// of the same pass can produce different results), but unique the634// resulting object to reduce memory usage. This helps to greatly reduce635// memory usage when we have many instances of only a few pass types636// (e.g. instcombine, simplifycfg, etc...) which tend to share a fixed set637// of dependencies.638AnalysisUsage AU;639P->getAnalysisUsage(AU);640641AUFoldingSetNode* Node = nullptr;642FoldingSetNodeID ID;643AUFoldingSetNode::Profile(ID, AU);644void *IP = nullptr;645if (auto *N = UniqueAnalysisUsages.FindNodeOrInsertPos(ID, IP))646Node = N;647else {648Node = new (AUFoldingSetNodeAllocator.Allocate()) AUFoldingSetNode(AU);649UniqueAnalysisUsages.InsertNode(Node, IP);650}651assert(Node && "cached analysis usage must be non null");652653AnUsageMap[P] = &Node->AU;654AnUsage = &Node->AU;655}656return AnUsage;657}658659/// Schedule pass P for execution. Make sure that passes required by660/// P are run before P is run. Update analysis info maintained by661/// the manager. Remove dead passes. This is a recursive function.662void PMTopLevelManager::schedulePass(Pass *P) {663664// TODO : Allocate function manager for this pass, other wise required set665// may be inserted into previous function manager666667// Give pass a chance to prepare the stage.668P->preparePassManager(activeStack);669670// If P is an analysis pass and it is available then do not671// generate the analysis again. Stale analysis info should not be672// available at this point.673const PassInfo *PI = findAnalysisPassInfo(P->getPassID());674if (PI && PI->isAnalysis() && findAnalysisPass(P->getPassID())) {675// Remove any cached AnalysisUsage information.676AnUsageMap.erase(P);677delete P;678return;679}680681AnalysisUsage *AnUsage = findAnalysisUsage(P);682683bool checkAnalysis = true;684while (checkAnalysis) {685checkAnalysis = false;686687const AnalysisUsage::VectorType &RequiredSet = AnUsage->getRequiredSet();688for (const AnalysisID ID : RequiredSet) {689690Pass *AnalysisPass = findAnalysisPass(ID);691if (!AnalysisPass) {692const PassInfo *PI = findAnalysisPassInfo(ID);693694if (!PI) {695// Pass P is not in the global PassRegistry696dbgs() << "Pass '" << P->getPassName() << "' is not initialized." << "\n";697dbgs() << "Verify if there is a pass dependency cycle." << "\n";698dbgs() << "Required Passes:" << "\n";699for (const AnalysisID ID2 : RequiredSet) {700if (ID == ID2)701break;702Pass *AnalysisPass2 = findAnalysisPass(ID2);703if (AnalysisPass2) {704dbgs() << "\t" << AnalysisPass2->getPassName() << "\n";705} else {706dbgs() << "\t" << "Error: Required pass not found! Possible causes:" << "\n";707dbgs() << "\t\t" << "- Pass misconfiguration (e.g.: missing macros)" << "\n";708dbgs() << "\t\t" << "- Corruption of the global PassRegistry" << "\n";709}710}711}712713assert(PI && "Expected required passes to be initialized");714AnalysisPass = PI->createPass();715if (P->getPotentialPassManagerType () ==716AnalysisPass->getPotentialPassManagerType())717// Schedule analysis pass that is managed by the same pass manager.718schedulePass(AnalysisPass);719else if (P->getPotentialPassManagerType () >720AnalysisPass->getPotentialPassManagerType()) {721// Schedule analysis pass that is managed by a new manager.722schedulePass(AnalysisPass);723// Recheck analysis passes to ensure that required analyses that724// are already checked are still available.725checkAnalysis = true;726} else727// Do not schedule this analysis. Lower level analysis728// passes are run on the fly.729delete AnalysisPass;730}731}732}733734// Now all required passes are available.735if (ImmutablePass *IP = P->getAsImmutablePass()) {736// P is a immutable pass and it will be managed by this737// top level manager. Set up analysis resolver to connect them.738PMDataManager *DM = getAsPMDataManager();739AnalysisResolver *AR = new AnalysisResolver(*DM);740P->setResolver(AR);741DM->initializeAnalysisImpl(P);742addImmutablePass(IP);743DM->recordAvailableAnalysis(IP);744return;745}746747if (PI && !PI->isAnalysis() && shouldPrintBeforePass(PI->getPassArgument())) {748Pass *PP =749P->createPrinterPass(dbgs(), ("*** IR Dump Before " + P->getPassName() +750" (" + PI->getPassArgument() + ") ***")751.str());752PP->assignPassManager(activeStack, getTopLevelPassManagerType());753}754755// Add the requested pass to the best available pass manager.756P->assignPassManager(activeStack, getTopLevelPassManagerType());757758if (PI && !PI->isAnalysis() && shouldPrintAfterPass(PI->getPassArgument())) {759Pass *PP =760P->createPrinterPass(dbgs(), ("*** IR Dump After " + P->getPassName() +761" (" + PI->getPassArgument() + ") ***")762.str());763PP->assignPassManager(activeStack, getTopLevelPassManagerType());764}765}766767/// Find the pass that implements Analysis AID. Search immutable768/// passes and all pass managers. If desired pass is not found769/// then return NULL.770Pass *PMTopLevelManager::findAnalysisPass(AnalysisID AID) {771// For immutable passes we have a direct mapping from ID to pass, so check772// that first.773if (Pass *P = ImmutablePassMap.lookup(AID))774return P;775776// Check pass managers777for (PMDataManager *PassManager : PassManagers)778if (Pass *P = PassManager->findAnalysisPass(AID, false))779return P;780781// Check other pass managers782for (PMDataManager *IndirectPassManager : IndirectPassManagers)783if (Pass *P = IndirectPassManager->findAnalysisPass(AID, false))784return P;785786return nullptr;787}788789const PassInfo *PMTopLevelManager::findAnalysisPassInfo(AnalysisID AID) const {790const PassInfo *&PI = AnalysisPassInfos[AID];791if (!PI)792PI = PassRegistry::getPassRegistry()->getPassInfo(AID);793else794assert(PI == PassRegistry::getPassRegistry()->getPassInfo(AID) &&795"The pass info pointer changed for an analysis ID!");796797return PI;798}799800void PMTopLevelManager::addImmutablePass(ImmutablePass *P) {801P->initializePass();802ImmutablePasses.push_back(P);803804// Add this pass to the map from its analysis ID. We clobber any prior runs805// of the pass in the map so that the last one added is the one found when806// doing lookups.807AnalysisID AID = P->getPassID();808ImmutablePassMap[AID] = P;809810// Also add any interfaces implemented by the immutable pass to the map for811// fast lookup.812const PassInfo *PassInf = findAnalysisPassInfo(AID);813assert(PassInf && "Expected all immutable passes to be initialized");814for (const PassInfo *ImmPI : PassInf->getInterfacesImplemented())815ImmutablePassMap[ImmPI->getTypeInfo()] = P;816}817818// Print passes managed by this top level manager.819void PMTopLevelManager::dumpPasses() const {820821if (PassDebugging < Structure)822return;823824// Print out the immutable passes825for (ImmutablePass *Pass : ImmutablePasses)826Pass->dumpPassStructure(0);827828// Every class that derives from PMDataManager also derives from Pass829// (sometimes indirectly), but there's no inheritance relationship830// between PMDataManager and Pass, so we have to getAsPass to get831// from a PMDataManager* to a Pass*.832for (PMDataManager *Manager : PassManagers)833Manager->getAsPass()->dumpPassStructure(1);834}835836void PMTopLevelManager::dumpArguments() const {837838if (PassDebugging < Arguments)839return;840841dbgs() << "Pass Arguments: ";842for (ImmutablePass *P : ImmutablePasses)843if (const PassInfo *PI = findAnalysisPassInfo(P->getPassID())) {844assert(PI && "Expected all immutable passes to be initialized");845if (!PI->isAnalysisGroup())846dbgs() << " -" << PI->getPassArgument();847}848for (PMDataManager *PM : PassManagers)849PM->dumpPassArguments();850dbgs() << "\n";851}852853void PMTopLevelManager::initializeAllAnalysisInfo() {854for (PMDataManager *PM : PassManagers)855PM->initializeAnalysisInfo();856857// Initailize other pass managers858for (PMDataManager *IPM : IndirectPassManagers)859IPM->initializeAnalysisInfo();860}861862/// Destructor863PMTopLevelManager::~PMTopLevelManager() {864for (PMDataManager *PM : PassManagers)865delete PM;866867for (ImmutablePass *P : ImmutablePasses)868delete P;869}870871//===----------------------------------------------------------------------===//872// PMDataManager implementation873874/// Augement AvailableAnalysis by adding analysis made available by pass P.875void PMDataManager::recordAvailableAnalysis(Pass *P) {876AnalysisID PI = P->getPassID();877878AvailableAnalysis[PI] = P;879880assert(!AvailableAnalysis.empty());881882// This pass is the current implementation of all of the interfaces it883// implements as well.884const PassInfo *PInf = TPM->findAnalysisPassInfo(PI);885if (!PInf) return;886for (const PassInfo *PI : PInf->getInterfacesImplemented())887AvailableAnalysis[PI->getTypeInfo()] = P;888}889890// Return true if P preserves high level analysis used by other891// passes managed by this manager892bool PMDataManager::preserveHigherLevelAnalysis(Pass *P) {893AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);894if (AnUsage->getPreservesAll())895return true;896897const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();898for (Pass *P1 : HigherLevelAnalysis) {899if (P1->getAsImmutablePass() == nullptr &&900!is_contained(PreservedSet, P1->getPassID()))901return false;902}903904return true;905}906907/// verifyPreservedAnalysis -- Verify analysis preserved by pass P.908void PMDataManager::verifyPreservedAnalysis(Pass *P) {909// Don't do this unless assertions are enabled.910#ifdef NDEBUG911return;912#endif913AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);914const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();915916// Verify preserved analysis917for (AnalysisID AID : PreservedSet) {918if (Pass *AP = findAnalysisPass(AID, true)) {919TimeRegion PassTimer(getPassTimer(AP));920AP->verifyAnalysis();921}922}923}924925/// Remove Analysis not preserved by Pass P926void PMDataManager::removeNotPreservedAnalysis(Pass *P) {927AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);928if (AnUsage->getPreservesAll())929return;930931const AnalysisUsage::VectorType &PreservedSet = AnUsage->getPreservedSet();932for (DenseMap<AnalysisID, Pass*>::iterator I = AvailableAnalysis.begin(),933E = AvailableAnalysis.end(); I != E; ) {934DenseMap<AnalysisID, Pass*>::iterator Info = I++;935if (Info->second->getAsImmutablePass() == nullptr &&936!is_contained(PreservedSet, Info->first)) {937// Remove this analysis938if (PassDebugging >= Details) {939Pass *S = Info->second;940dbgs() << " -- '" << P->getPassName() << "' is not preserving '";941dbgs() << S->getPassName() << "'\n";942}943AvailableAnalysis.erase(Info);944}945}946947// Check inherited analysis also. If P is not preserving analysis948// provided by parent manager then remove it here.949for (DenseMap<AnalysisID, Pass *> *IA : InheritedAnalysis) {950if (!IA)951continue;952953for (DenseMap<AnalysisID, Pass *>::iterator I = IA->begin(),954E = IA->end();955I != E;) {956DenseMap<AnalysisID, Pass *>::iterator Info = I++;957if (Info->second->getAsImmutablePass() == nullptr &&958!is_contained(PreservedSet, Info->first)) {959// Remove this analysis960if (PassDebugging >= Details) {961Pass *S = Info->second;962dbgs() << " -- '" << P->getPassName() << "' is not preserving '";963dbgs() << S->getPassName() << "'\n";964}965IA->erase(Info);966}967}968}969}970971/// Remove analysis passes that are not used any longer972void PMDataManager::removeDeadPasses(Pass *P, StringRef Msg,973enum PassDebuggingString DBG_STR) {974975SmallVector<Pass *, 12> DeadPasses;976977// If this is a on the fly manager then it does not have TPM.978if (!TPM)979return;980981TPM->collectLastUses(DeadPasses, P);982983if (PassDebugging >= Details && !DeadPasses.empty()) {984dbgs() << " -*- '" << P->getPassName();985dbgs() << "' is the last user of following pass instances.";986dbgs() << " Free these instances\n";987}988989for (Pass *P : DeadPasses)990freePass(P, Msg, DBG_STR);991}992993void PMDataManager::freePass(Pass *P, StringRef Msg,994enum PassDebuggingString DBG_STR) {995dumpPassInfo(P, FREEING_MSG, DBG_STR, Msg);996997{998// If the pass crashes releasing memory, remember this.999PassManagerPrettyStackEntry X(P);1000TimeRegion PassTimer(getPassTimer(P));10011002P->releaseMemory();1003}10041005AnalysisID PI = P->getPassID();1006if (const PassInfo *PInf = TPM->findAnalysisPassInfo(PI)) {1007// Remove the pass itself (if it is not already removed).1008AvailableAnalysis.erase(PI);10091010// Remove all interfaces this pass implements, for which it is also1011// listed as the available implementation.1012for (const PassInfo *PI : PInf->getInterfacesImplemented()) {1013DenseMap<AnalysisID, Pass *>::iterator Pos =1014AvailableAnalysis.find(PI->getTypeInfo());1015if (Pos != AvailableAnalysis.end() && Pos->second == P)1016AvailableAnalysis.erase(Pos);1017}1018}1019}10201021/// Add pass P into the PassVector. Update1022/// AvailableAnalysis appropriately if ProcessAnalysis is true.1023void PMDataManager::add(Pass *P, bool ProcessAnalysis) {1024// This manager is going to manage pass P. Set up analysis resolver1025// to connect them.1026AnalysisResolver *AR = new AnalysisResolver(*this);1027P->setResolver(AR);10281029// If a FunctionPass F is the last user of ModulePass info M1030// then the F's manager, not F, records itself as a last user of M.1031SmallVector<Pass *, 12> TransferLastUses;10321033if (!ProcessAnalysis) {1034// Add pass1035PassVector.push_back(P);1036return;1037}10381039// At the moment, this pass is the last user of all required passes.1040SmallVector<Pass *, 12> LastUses;1041SmallVector<Pass *, 8> UsedPasses;1042SmallVector<AnalysisID, 8> ReqAnalysisNotAvailable;10431044unsigned PDepth = this->getDepth();10451046collectRequiredAndUsedAnalyses(UsedPasses, ReqAnalysisNotAvailable, P);1047for (Pass *PUsed : UsedPasses) {1048unsigned RDepth = 0;10491050assert(PUsed->getResolver() && "Analysis Resolver is not set");1051PMDataManager &DM = PUsed->getResolver()->getPMDataManager();1052RDepth = DM.getDepth();10531054if (PDepth == RDepth)1055LastUses.push_back(PUsed);1056else if (PDepth > RDepth) {1057// Let the parent claim responsibility of last use1058TransferLastUses.push_back(PUsed);1059// Keep track of higher level analysis used by this manager.1060HigherLevelAnalysis.push_back(PUsed);1061} else1062llvm_unreachable("Unable to accommodate Used Pass");1063}10641065// Set P as P's last user until someone starts using P.1066// However, if P is a Pass Manager then it does not need1067// to record its last user.1068if (!P->getAsPMDataManager())1069LastUses.push_back(P);1070TPM->setLastUser(LastUses, P);10711072if (!TransferLastUses.empty()) {1073Pass *My_PM = getAsPass();1074TPM->setLastUser(TransferLastUses, My_PM);1075TransferLastUses.clear();1076}10771078// Now, take care of required analyses that are not available.1079for (AnalysisID ID : ReqAnalysisNotAvailable) {1080const PassInfo *PI = TPM->findAnalysisPassInfo(ID);1081Pass *AnalysisPass = PI->createPass();1082this->addLowerLevelRequiredPass(P, AnalysisPass);1083}10841085// Take a note of analysis required and made available by this pass.1086// Remove the analysis not preserved by this pass1087removeNotPreservedAnalysis(P);1088recordAvailableAnalysis(P);10891090// Add pass1091PassVector.push_back(P);1092}109310941095/// Populate UP with analysis pass that are used or required by1096/// pass P and are available. Populate RP_NotAvail with analysis1097/// pass that are required by pass P but are not available.1098void PMDataManager::collectRequiredAndUsedAnalyses(1099SmallVectorImpl<Pass *> &UP, SmallVectorImpl<AnalysisID> &RP_NotAvail,1100Pass *P) {1101AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);11021103for (const auto &UsedID : AnUsage->getUsedSet())1104if (Pass *AnalysisPass = findAnalysisPass(UsedID, true))1105UP.push_back(AnalysisPass);11061107for (const auto &RequiredID : AnUsage->getRequiredSet())1108if (Pass *AnalysisPass = findAnalysisPass(RequiredID, true))1109UP.push_back(AnalysisPass);1110else1111RP_NotAvail.push_back(RequiredID);1112}11131114// All Required analyses should be available to the pass as it runs! Here1115// we fill in the AnalysisImpls member of the pass so that it can1116// successfully use the getAnalysis() method to retrieve the1117// implementations it needs.1118//1119void PMDataManager::initializeAnalysisImpl(Pass *P) {1120AnalysisUsage *AnUsage = TPM->findAnalysisUsage(P);11211122for (const AnalysisID ID : AnUsage->getRequiredSet()) {1123Pass *Impl = findAnalysisPass(ID, true);1124if (!Impl)1125// This may be analysis pass that is initialized on the fly.1126// If that is not the case then it will raise an assert when it is used.1127continue;1128AnalysisResolver *AR = P->getResolver();1129assert(AR && "Analysis Resolver is not set");1130AR->addAnalysisImplsPair(ID, Impl);1131}1132}11331134/// Find the pass that implements Analysis AID. If desired pass is not found1135/// then return NULL.1136Pass *PMDataManager::findAnalysisPass(AnalysisID AID, bool SearchParent) {11371138// Check if AvailableAnalysis map has one entry.1139DenseMap<AnalysisID, Pass*>::const_iterator I = AvailableAnalysis.find(AID);11401141if (I != AvailableAnalysis.end())1142return I->second;11431144// Search Parents through TopLevelManager1145if (SearchParent)1146return TPM->findAnalysisPass(AID);11471148return nullptr;1149}11501151// Print list of passes that are last used by P.1152void PMDataManager::dumpLastUses(Pass *P, unsigned Offset) const{1153if (PassDebugging < Details)1154return;11551156SmallVector<Pass *, 12> LUses;11571158// If this is a on the fly manager then it does not have TPM.1159if (!TPM)1160return;11611162TPM->collectLastUses(LUses, P);11631164for (Pass *P : LUses) {1165dbgs() << "--" << std::string(Offset*2, ' ');1166P->dumpPassStructure(0);1167}1168}11691170void PMDataManager::dumpPassArguments() const {1171for (Pass *P : PassVector) {1172if (PMDataManager *PMD = P->getAsPMDataManager())1173PMD->dumpPassArguments();1174else1175if (const PassInfo *PI =1176TPM->findAnalysisPassInfo(P->getPassID()))1177if (!PI->isAnalysisGroup())1178dbgs() << " -" << PI->getPassArgument();1179}1180}11811182void PMDataManager::dumpPassInfo(Pass *P, enum PassDebuggingString S1,1183enum PassDebuggingString S2,1184StringRef Msg) {1185if (PassDebugging < Executions)1186return;1187dbgs() << "[" << std::chrono::system_clock::now() << "] " << (void *)this1188<< std::string(getDepth() * 2 + 1, ' ');1189switch (S1) {1190case EXECUTION_MSG:1191dbgs() << "Executing Pass '" << P->getPassName();1192break;1193case MODIFICATION_MSG:1194dbgs() << "Made Modification '" << P->getPassName();1195break;1196case FREEING_MSG:1197dbgs() << " Freeing Pass '" << P->getPassName();1198break;1199default:1200break;1201}1202switch (S2) {1203case ON_FUNCTION_MSG:1204dbgs() << "' on Function '" << Msg << "'...\n";1205break;1206case ON_MODULE_MSG:1207dbgs() << "' on Module '" << Msg << "'...\n";1208break;1209case ON_REGION_MSG:1210dbgs() << "' on Region '" << Msg << "'...\n";1211break;1212case ON_LOOP_MSG:1213dbgs() << "' on Loop '" << Msg << "'...\n";1214break;1215case ON_CG_MSG:1216dbgs() << "' on Call Graph Nodes '" << Msg << "'...\n";1217break;1218default:1219break;1220}1221}12221223void PMDataManager::dumpRequiredSet(const Pass *P) const {1224if (PassDebugging < Details)1225return;12261227AnalysisUsage analysisUsage;1228P->getAnalysisUsage(analysisUsage);1229dumpAnalysisUsage("Required", P, analysisUsage.getRequiredSet());1230}12311232void PMDataManager::dumpPreservedSet(const Pass *P) const {1233if (PassDebugging < Details)1234return;12351236AnalysisUsage analysisUsage;1237P->getAnalysisUsage(analysisUsage);1238dumpAnalysisUsage("Preserved", P, analysisUsage.getPreservedSet());1239}12401241void PMDataManager::dumpUsedSet(const Pass *P) const {1242if (PassDebugging < Details)1243return;12441245AnalysisUsage analysisUsage;1246P->getAnalysisUsage(analysisUsage);1247dumpAnalysisUsage("Used", P, analysisUsage.getUsedSet());1248}12491250void PMDataManager::dumpAnalysisUsage(StringRef Msg, const Pass *P,1251const AnalysisUsage::VectorType &Set) const {1252assert(PassDebugging >= Details);1253if (Set.empty())1254return;1255dbgs() << (const void*)P << std::string(getDepth()*2+3, ' ') << Msg << " Analyses:";1256for (unsigned i = 0; i != Set.size(); ++i) {1257if (i) dbgs() << ',';1258const PassInfo *PInf = TPM->findAnalysisPassInfo(Set[i]);1259if (!PInf) {1260// Some preserved passes, such as AliasAnalysis, may not be initialized by1261// all drivers.1262dbgs() << " Uninitialized Pass";1263continue;1264}1265dbgs() << ' ' << PInf->getPassName();1266}1267dbgs() << '\n';1268}12691270/// Add RequiredPass into list of lower level passes required by pass P.1271/// RequiredPass is run on the fly by Pass Manager when P requests it1272/// through getAnalysis interface.1273/// This should be handled by specific pass manager.1274void PMDataManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {1275if (TPM) {1276TPM->dumpArguments();1277TPM->dumpPasses();1278}12791280// Module Level pass may required Function Level analysis info1281// (e.g. dominator info). Pass manager uses on the fly function pass manager1282// to provide this on demand. In that case, in Pass manager terminology,1283// module level pass is requiring lower level analysis info managed by1284// lower level pass manager.12851286// When Pass manager is not able to order required analysis info, Pass manager1287// checks whether any lower level manager will be able to provide this1288// analysis info on demand or not.1289#ifndef NDEBUG1290dbgs() << "Unable to schedule '" << RequiredPass->getPassName();1291dbgs() << "' required by '" << P->getPassName() << "'\n";1292#endif1293llvm_unreachable("Unable to schedule pass");1294}12951296std::tuple<Pass *, bool> PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI,1297Function &F) {1298llvm_unreachable("Unable to find on the fly pass");1299}13001301// Destructor1302PMDataManager::~PMDataManager() {1303for (Pass *P : PassVector)1304delete P;1305}13061307//===----------------------------------------------------------------------===//1308// NOTE: Is this the right place to define this method ?1309// getAnalysisIfAvailable - Return analysis result or null if it doesn't exist.1310Pass *AnalysisResolver::getAnalysisIfAvailable(AnalysisID ID) const {1311return PM.findAnalysisPass(ID, true);1312}13131314std::tuple<Pass *, bool>1315AnalysisResolver::findImplPass(Pass *P, AnalysisID AnalysisPI, Function &F) {1316return PM.getOnTheFlyPass(P, AnalysisPI, F);1317}13181319namespace llvm {1320namespace legacy {13211322//===----------------------------------------------------------------------===//1323// FunctionPassManager implementation13241325/// Create new Function pass manager1326FunctionPassManager::FunctionPassManager(Module *m) : M(m) {1327FPM = new legacy::FunctionPassManagerImpl();1328// FPM is the top level manager.1329FPM->setTopLevelManager(FPM);13301331AnalysisResolver *AR = new AnalysisResolver(*FPM);1332FPM->setResolver(AR);1333}13341335FunctionPassManager::~FunctionPassManager() {1336delete FPM;1337}13381339void FunctionPassManager::add(Pass *P) {1340FPM->add(P);1341}13421343/// run - Execute all of the passes scheduled for execution. Keep1344/// track of whether any of the passes modifies the function, and if1345/// so, return true.1346///1347bool FunctionPassManager::run(Function &F) {1348handleAllErrors(F.materialize(), [&](ErrorInfoBase &EIB) {1349report_fatal_error(Twine("Error reading bitcode file: ") + EIB.message());1350});1351return FPM->run(F);1352}135313541355/// doInitialization - Run all of the initializers for the function passes.1356///1357bool FunctionPassManager::doInitialization() {1358return FPM->doInitialization(*M);1359}13601361/// doFinalization - Run all of the finalizers for the function passes.1362///1363bool FunctionPassManager::doFinalization() {1364return FPM->doFinalization(*M);1365}1366} // namespace legacy1367} // namespace llvm13681369/// cleanup - After running all passes, clean up pass manager cache.1370void FPPassManager::cleanup() {1371for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {1372FunctionPass *FP = getContainedPass(Index);1373AnalysisResolver *AR = FP->getResolver();1374assert(AR && "Analysis Resolver is not set");1375AR->clearAnalysisImpls();1376}1377}137813791380//===----------------------------------------------------------------------===//1381// FPPassManager implementation13821383char FPPassManager::ID = 0;1384/// Print passes managed by this manager1385void FPPassManager::dumpPassStructure(unsigned Offset) {1386dbgs().indent(Offset*2) << "FunctionPass Manager\n";1387for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {1388FunctionPass *FP = getContainedPass(Index);1389FP->dumpPassStructure(Offset + 1);1390dumpLastUses(FP, Offset+1);1391}1392}13931394/// Execute all of the passes scheduled for execution by invoking1395/// runOnFunction method. Keep track of whether any of the passes modifies1396/// the function, and if so, return true.1397bool FPPassManager::runOnFunction(Function &F) {1398if (F.isDeclaration())1399return false;14001401bool Changed = false;1402Module &M = *F.getParent();1403// Collect inherited analysis from Module level pass manager.1404populateInheritedAnalysis(TPM->activeStack);14051406unsigned InstrCount, FunctionSize = 0;1407StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;1408bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();1409// Collect the initial size of the module.1410if (EmitICRemark) {1411InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);1412FunctionSize = F.getInstructionCount();1413}14141415// Store name outside of loop to avoid redundant calls.1416const StringRef Name = F.getName();1417llvm::TimeTraceScope FunctionScope("OptFunction", Name);14181419for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {1420FunctionPass *FP = getContainedPass(Index);1421bool LocalChanged = false;14221423// Call getPassName only when required. The call itself is fairly cheap, but1424// still virtual and repeated calling adds unnecessary overhead.1425llvm::TimeTraceScope PassScope(1426"RunPass", [FP]() { return std::string(FP->getPassName()); });14271428dumpPassInfo(FP, EXECUTION_MSG, ON_FUNCTION_MSG, Name);1429dumpRequiredSet(FP);14301431initializeAnalysisImpl(FP);14321433{1434PassManagerPrettyStackEntry X(FP, F);1435TimeRegion PassTimer(getPassTimer(FP));1436#ifdef EXPENSIVE_CHECKS1437uint64_t RefHash = FP->structuralHash(F);1438#endif1439LocalChanged |= FP->runOnFunction(F);14401441#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)1442if (!LocalChanged && (RefHash != FP->structuralHash(F))) {1443llvm::errs() << "Pass modifies its input and doesn't report it: "1444<< FP->getPassName() << "\n";1445llvm_unreachable("Pass modifies its input and doesn't report it");1446}1447#endif14481449if (EmitICRemark) {1450unsigned NewSize = F.getInstructionCount();14511452// Update the size of the function, emit a remark, and update the size1453// of the module.1454if (NewSize != FunctionSize) {1455int64_t Delta = static_cast<int64_t>(NewSize) -1456static_cast<int64_t>(FunctionSize);1457emitInstrCountChangedRemark(FP, M, Delta, InstrCount,1458FunctionToInstrCount, &F);1459InstrCount = static_cast<int64_t>(InstrCount) + Delta;1460FunctionSize = NewSize;1461}1462}1463}14641465Changed |= LocalChanged;1466if (LocalChanged)1467dumpPassInfo(FP, MODIFICATION_MSG, ON_FUNCTION_MSG, Name);1468dumpPreservedSet(FP);1469dumpUsedSet(FP);14701471verifyPreservedAnalysis(FP);1472if (LocalChanged)1473removeNotPreservedAnalysis(FP);1474recordAvailableAnalysis(FP);1475removeDeadPasses(FP, Name, ON_FUNCTION_MSG);1476}14771478return Changed;1479}14801481bool FPPassManager::runOnModule(Module &M) {1482bool Changed = false;14831484for (Function &F : M)1485Changed |= runOnFunction(F);14861487return Changed;1488}14891490bool FPPassManager::doInitialization(Module &M) {1491bool Changed = false;14921493for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)1494Changed |= getContainedPass(Index)->doInitialization(M);14951496return Changed;1497}14981499bool FPPassManager::doFinalization(Module &M) {1500bool Changed = false;15011502for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)1503Changed |= getContainedPass(Index)->doFinalization(M);15041505return Changed;1506}15071508//===----------------------------------------------------------------------===//1509// MPPassManager implementation15101511/// Execute all of the passes scheduled for execution by invoking1512/// runOnModule method. Keep track of whether any of the passes modifies1513/// the module, and if so, return true.1514bool1515MPPassManager::runOnModule(Module &M) {1516llvm::TimeTraceScope TimeScope("OptModule", M.getName());15171518bool Changed = false;15191520// Initialize on-the-fly passes1521for (auto &OnTheFlyManager : OnTheFlyManagers) {1522legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;1523Changed |= FPP->doInitialization(M);1524}15251526// Initialize module passes1527for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index)1528Changed |= getContainedPass(Index)->doInitialization(M);15291530unsigned InstrCount;1531StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount;1532bool EmitICRemark = M.shouldEmitInstrCountChangedRemark();1533// Collect the initial size of the module.1534if (EmitICRemark)1535InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount);15361537for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {1538ModulePass *MP = getContainedPass(Index);1539bool LocalChanged = false;15401541dumpPassInfo(MP, EXECUTION_MSG, ON_MODULE_MSG, M.getModuleIdentifier());1542dumpRequiredSet(MP);15431544initializeAnalysisImpl(MP);15451546{1547PassManagerPrettyStackEntry X(MP, M);1548TimeRegion PassTimer(getPassTimer(MP));15491550#ifdef EXPENSIVE_CHECKS1551uint64_t RefHash = MP->structuralHash(M);1552#endif15531554LocalChanged |= MP->runOnModule(M);15551556#ifdef EXPENSIVE_CHECKS1557assert((LocalChanged || (RefHash == MP->structuralHash(M))) &&1558"Pass modifies its input and doesn't report it.");1559#endif15601561if (EmitICRemark) {1562// Update the size of the module.1563unsigned ModuleCount = M.getInstructionCount();1564if (ModuleCount != InstrCount) {1565int64_t Delta = static_cast<int64_t>(ModuleCount) -1566static_cast<int64_t>(InstrCount);1567emitInstrCountChangedRemark(MP, M, Delta, InstrCount,1568FunctionToInstrCount);1569InstrCount = ModuleCount;1570}1571}1572}15731574Changed |= LocalChanged;1575if (LocalChanged)1576dumpPassInfo(MP, MODIFICATION_MSG, ON_MODULE_MSG,1577M.getModuleIdentifier());1578dumpPreservedSet(MP);1579dumpUsedSet(MP);15801581verifyPreservedAnalysis(MP);1582if (LocalChanged)1583removeNotPreservedAnalysis(MP);1584recordAvailableAnalysis(MP);1585removeDeadPasses(MP, M.getModuleIdentifier(), ON_MODULE_MSG);1586}15871588// Finalize module passes1589for (int Index = getNumContainedPasses() - 1; Index >= 0; --Index)1590Changed |= getContainedPass(Index)->doFinalization(M);15911592// Finalize on-the-fly passes1593for (auto &OnTheFlyManager : OnTheFlyManagers) {1594legacy::FunctionPassManagerImpl *FPP = OnTheFlyManager.second;1595// We don't know when is the last time an on-the-fly pass is run,1596// so we need to releaseMemory / finalize here1597FPP->releaseMemoryOnTheFly();1598Changed |= FPP->doFinalization(M);1599}16001601return Changed;1602}16031604/// Add RequiredPass into list of lower level passes required by pass P.1605/// RequiredPass is run on the fly by Pass Manager when P requests it1606/// through getAnalysis interface.1607void MPPassManager::addLowerLevelRequiredPass(Pass *P, Pass *RequiredPass) {1608assert(RequiredPass && "No required pass?");1609assert(P->getPotentialPassManagerType() == PMT_ModulePassManager &&1610"Unable to handle Pass that requires lower level Analysis pass");1611assert((P->getPotentialPassManagerType() <1612RequiredPass->getPotentialPassManagerType()) &&1613"Unable to handle Pass that requires lower level Analysis pass");16141615legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[P];1616if (!FPP) {1617FPP = new legacy::FunctionPassManagerImpl();1618// FPP is the top level manager.1619FPP->setTopLevelManager(FPP);16201621OnTheFlyManagers[P] = FPP;1622}1623const PassInfo *RequiredPassPI =1624TPM->findAnalysisPassInfo(RequiredPass->getPassID());16251626Pass *FoundPass = nullptr;1627if (RequiredPassPI && RequiredPassPI->isAnalysis()) {1628FoundPass =1629((PMTopLevelManager*)FPP)->findAnalysisPass(RequiredPass->getPassID());1630}1631if (!FoundPass) {1632FoundPass = RequiredPass;1633// This should be guaranteed to add RequiredPass to the passmanager given1634// that we checked for an available analysis above.1635FPP->add(RequiredPass);1636}1637// Register P as the last user of FoundPass or RequiredPass.1638SmallVector<Pass *, 1> LU;1639LU.push_back(FoundPass);1640FPP->setLastUser(LU, P);1641}16421643/// Return function pass corresponding to PassInfo PI, that is1644/// required by module pass MP. Instantiate analysis pass, by using1645/// its runOnFunction() for function F.1646std::tuple<Pass *, bool> MPPassManager::getOnTheFlyPass(Pass *MP, AnalysisID PI,1647Function &F) {1648legacy::FunctionPassManagerImpl *FPP = OnTheFlyManagers[MP];1649assert(FPP && "Unable to find on the fly pass");16501651FPP->releaseMemoryOnTheFly();1652bool Changed = FPP->run(F);1653return std::make_tuple(((PMTopLevelManager *)FPP)->findAnalysisPass(PI),1654Changed);1655}16561657namespace llvm {1658namespace legacy {16591660//===----------------------------------------------------------------------===//1661// PassManager implementation16621663/// Create new pass manager1664PassManager::PassManager() {1665PM = new PassManagerImpl();1666// PM is the top level manager1667PM->setTopLevelManager(PM);1668}16691670PassManager::~PassManager() {1671delete PM;1672}16731674void PassManager::add(Pass *P) {1675PM->add(P);1676}16771678/// run - Execute all of the passes scheduled for execution. Keep track of1679/// whether any of the passes modifies the module, and if so, return true.1680bool PassManager::run(Module &M) {1681return PM->run(M);1682}1683} // namespace legacy1684} // namespace llvm16851686//===----------------------------------------------------------------------===//1687// PMStack implementation1688//16891690// Pop Pass Manager from the stack and clear its analysis info.1691void PMStack::pop() {16921693PMDataManager *Top = this->top();1694Top->initializeAnalysisInfo();16951696S.pop_back();1697}16981699// Push PM on the stack and set its top level manager.1700void PMStack::push(PMDataManager *PM) {1701assert(PM && "Unable to push. Pass Manager expected");1702assert(PM->getDepth()==0 && "Pass Manager depth set too early");17031704if (!this->empty()) {1705assert(PM->getPassManagerType() > this->top()->getPassManagerType()1706&& "pushing bad pass manager to PMStack");1707PMTopLevelManager *TPM = this->top()->getTopLevelManager();17081709assert(TPM && "Unable to find top level manager");1710TPM->addIndirectPassManager(PM);1711PM->setTopLevelManager(TPM);1712PM->setDepth(this->top()->getDepth()+1);1713} else {1714assert((PM->getPassManagerType() == PMT_ModulePassManager1715|| PM->getPassManagerType() == PMT_FunctionPassManager)1716&& "pushing bad pass manager to PMStack");1717PM->setDepth(1);1718}17191720S.push_back(PM);1721}17221723// Dump content of the pass manager stack.1724LLVM_DUMP_METHOD void PMStack::dump() const {1725for (PMDataManager *Manager : S)1726dbgs() << Manager->getAsPass()->getPassName() << ' ';17271728if (!S.empty())1729dbgs() << '\n';1730}17311732/// Find appropriate Module Pass Manager in the PM Stack and1733/// add self into that manager.1734void ModulePass::assignPassManager(PMStack &PMS,1735PassManagerType PreferredType) {1736// Find Module Pass Manager1737PassManagerType T;1738while ((T = PMS.top()->getPassManagerType()) > PMT_ModulePassManager &&1739T != PreferredType)1740PMS.pop();1741PMS.top()->add(this);1742}17431744/// Find appropriate Function Pass Manager or Call Graph Pass Manager1745/// in the PM Stack and add self into that manager.1746void FunctionPass::assignPassManager(PMStack &PMS,1747PassManagerType /*PreferredType*/) {1748// Find Function Pass Manager1749PMDataManager *PM;1750while (PM = PMS.top(), PM->getPassManagerType() > PMT_FunctionPassManager)1751PMS.pop();17521753// Create new Function Pass Manager if needed.1754if (PM->getPassManagerType() != PMT_FunctionPassManager) {1755// [1] Create new Function Pass Manager1756auto *FPP = new FPPassManager;1757FPP->populateInheritedAnalysis(PMS);17581759// [2] Set up new manager's top level manager1760PM->getTopLevelManager()->addIndirectPassManager(FPP);17611762// [3] Assign manager to manage this new manager. This may create1763// and push new managers into PMS1764FPP->assignPassManager(PMS, PM->getPassManagerType());17651766// [4] Push new manager into PMS1767PMS.push(FPP);1768PM = FPP;1769}17701771// Assign FPP as the manager of this pass.1772PM->add(this);1773}17741775legacy::PassManagerBase::~PassManagerBase() = default;177617771778