Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/Inliner.cpp
35269 views
//===- Inliner.cpp - Code common to all inliners --------------------------===//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 mechanics required to implement inlining without9// missing any calls and updating the call graph. The decisions of which calls10// are profitable to inline are implemented elsewhere.11//12//===----------------------------------------------------------------------===//1314#include "llvm/Transforms/IPO/Inliner.h"15#include "llvm/ADT/PriorityWorklist.h"16#include "llvm/ADT/STLExtras.h"17#include "llvm/ADT/ScopeExit.h"18#include "llvm/ADT/SetVector.h"19#include "llvm/ADT/SmallPtrSet.h"20#include "llvm/ADT/SmallVector.h"21#include "llvm/ADT/Statistic.h"22#include "llvm/ADT/StringExtras.h"23#include "llvm/ADT/StringRef.h"24#include "llvm/Analysis/AssumptionCache.h"25#include "llvm/Analysis/BasicAliasAnalysis.h"26#include "llvm/Analysis/BlockFrequencyInfo.h"27#include "llvm/Analysis/CGSCCPassManager.h"28#include "llvm/Analysis/InlineAdvisor.h"29#include "llvm/Analysis/InlineCost.h"30#include "llvm/Analysis/LazyCallGraph.h"31#include "llvm/Analysis/OptimizationRemarkEmitter.h"32#include "llvm/Analysis/ProfileSummaryInfo.h"33#include "llvm/Analysis/ReplayInlineAdvisor.h"34#include "llvm/Analysis/TargetLibraryInfo.h"35#include "llvm/Analysis/Utils/ImportedFunctionsInliningStatistics.h"36#include "llvm/IR/Attributes.h"37#include "llvm/IR/BasicBlock.h"38#include "llvm/IR/DebugLoc.h"39#include "llvm/IR/DerivedTypes.h"40#include "llvm/IR/DiagnosticInfo.h"41#include "llvm/IR/Function.h"42#include "llvm/IR/InstIterator.h"43#include "llvm/IR/Instruction.h"44#include "llvm/IR/Instructions.h"45#include "llvm/IR/IntrinsicInst.h"46#include "llvm/IR/Metadata.h"47#include "llvm/IR/Module.h"48#include "llvm/IR/PassManager.h"49#include "llvm/IR/User.h"50#include "llvm/IR/Value.h"51#include "llvm/Pass.h"52#include "llvm/Support/Casting.h"53#include "llvm/Support/CommandLine.h"54#include "llvm/Support/Debug.h"55#include "llvm/Support/raw_ostream.h"56#include "llvm/Transforms/Utils/CallPromotionUtils.h"57#include "llvm/Transforms/Utils/Cloning.h"58#include "llvm/Transforms/Utils/Local.h"59#include "llvm/Transforms/Utils/ModuleUtils.h"60#include <algorithm>61#include <cassert>62#include <functional>63#include <utility>6465using namespace llvm;6667#define DEBUG_TYPE "inline"6869STATISTIC(NumInlined, "Number of functions inlined");70STATISTIC(NumDeleted, "Number of functions deleted because all callers found");7172static cl::opt<int> IntraSCCCostMultiplier(73"intra-scc-cost-multiplier", cl::init(2), cl::Hidden,74cl::desc(75"Cost multiplier to multiply onto inlined call sites where the "76"new call was previously an intra-SCC call (not relevant when the "77"original call was already intra-SCC). This can accumulate over "78"multiple inlinings (e.g. if a call site already had a cost "79"multiplier and one of its inlined calls was also subject to "80"this, the inlined call would have the original multiplier "81"multiplied by intra-scc-cost-multiplier). This is to prevent tons of "82"inlining through a child SCC which can cause terrible compile times"));8384/// A flag for test, so we can print the content of the advisor when running it85/// as part of the default (e.g. -O3) pipeline.86static cl::opt<bool> KeepAdvisorForPrinting("keep-inline-advisor-for-printing",87cl::init(false), cl::Hidden);8889/// Allows printing the contents of the advisor after each SCC inliner pass.90static cl::opt<bool>91EnablePostSCCAdvisorPrinting("enable-scc-inline-advisor-printing",92cl::init(false), cl::Hidden);939495static cl::opt<std::string> CGSCCInlineReplayFile(96"cgscc-inline-replay", cl::init(""), cl::value_desc("filename"),97cl::desc(98"Optimization remarks file containing inline remarks to be replayed "99"by cgscc inlining."),100cl::Hidden);101102static cl::opt<ReplayInlinerSettings::Scope> CGSCCInlineReplayScope(103"cgscc-inline-replay-scope",104cl::init(ReplayInlinerSettings::Scope::Function),105cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function",106"Replay on functions that have remarks associated "107"with them (default)"),108clEnumValN(ReplayInlinerSettings::Scope::Module, "Module",109"Replay on the entire module")),110cl::desc("Whether inline replay should be applied to the entire "111"Module or just the Functions (default) that are present as "112"callers in remarks during cgscc inlining."),113cl::Hidden);114115static cl::opt<ReplayInlinerSettings::Fallback> CGSCCInlineReplayFallback(116"cgscc-inline-replay-fallback",117cl::init(ReplayInlinerSettings::Fallback::Original),118cl::values(119clEnumValN(120ReplayInlinerSettings::Fallback::Original, "Original",121"All decisions not in replay send to original advisor (default)"),122clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline,123"AlwaysInline", "All decisions not in replay are inlined"),124clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline",125"All decisions not in replay are not inlined")),126cl::desc(127"How cgscc inline replay treats sites that don't come from the replay. "128"Original: defers to original advisor, AlwaysInline: inline all sites "129"not in replay, NeverInline: inline no sites not in replay"),130cl::Hidden);131132static cl::opt<CallSiteFormat::Format> CGSCCInlineReplayFormat(133"cgscc-inline-replay-format",134cl::init(CallSiteFormat::Format::LineColumnDiscriminator),135cl::values(136clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"),137clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn",138"<Line Number>:<Column Number>"),139clEnumValN(CallSiteFormat::Format::LineDiscriminator,140"LineDiscriminator", "<Line Number>.<Discriminator>"),141clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator,142"LineColumnDiscriminator",143"<Line Number>:<Column Number>.<Discriminator> (default)")),144cl::desc("How cgscc inline replay file is formatted"), cl::Hidden);145146/// Return true if the specified inline history ID147/// indicates an inline history that includes the specified function.148static bool inlineHistoryIncludes(149Function *F, int InlineHistoryID,150const SmallVectorImpl<std::pair<Function *, int>> &InlineHistory) {151while (InlineHistoryID != -1) {152assert(unsigned(InlineHistoryID) < InlineHistory.size() &&153"Invalid inline history ID");154if (InlineHistory[InlineHistoryID].first == F)155return true;156InlineHistoryID = InlineHistory[InlineHistoryID].second;157}158return false;159}160161InlineAdvisor &162InlinerPass::getAdvisor(const ModuleAnalysisManagerCGSCCProxy::Result &MAM,163FunctionAnalysisManager &FAM, Module &M) {164if (OwnedAdvisor)165return *OwnedAdvisor;166167auto *IAA = MAM.getCachedResult<InlineAdvisorAnalysis>(M);168if (!IAA) {169// It should still be possible to run the inliner as a stand-alone SCC pass,170// for test scenarios. In that case, we default to the171// DefaultInlineAdvisor, which doesn't need to keep state between SCC pass172// runs. It also uses just the default InlineParams.173// In this case, we need to use the provided FAM, which is valid for the174// duration of the inliner pass, and thus the lifetime of the owned advisor.175// The one we would get from the MAM can be invalidated as a result of the176// inliner's activity.177OwnedAdvisor = std::make_unique<DefaultInlineAdvisor>(178M, FAM, getInlineParams(),179InlineContext{LTOPhase, InlinePass::CGSCCInliner});180181if (!CGSCCInlineReplayFile.empty())182OwnedAdvisor = getReplayInlineAdvisor(183M, FAM, M.getContext(), std::move(OwnedAdvisor),184ReplayInlinerSettings{CGSCCInlineReplayFile,185CGSCCInlineReplayScope,186CGSCCInlineReplayFallback,187{CGSCCInlineReplayFormat}},188/*EmitRemarks=*/true,189InlineContext{LTOPhase, InlinePass::ReplayCGSCCInliner});190191return *OwnedAdvisor;192}193assert(IAA->getAdvisor() &&194"Expected a present InlineAdvisorAnalysis also have an "195"InlineAdvisor initialized");196return *IAA->getAdvisor();197}198199void makeFunctionBodyUnreachable(Function &F) {200F.dropAllReferences();201for (BasicBlock &BB : make_early_inc_range(F))202BB.eraseFromParent();203BasicBlock *BB = BasicBlock::Create(F.getContext(), "", &F);204new UnreachableInst(F.getContext(), BB);205}206207PreservedAnalyses InlinerPass::run(LazyCallGraph::SCC &InitialC,208CGSCCAnalysisManager &AM, LazyCallGraph &CG,209CGSCCUpdateResult &UR) {210const auto &MAMProxy =211AM.getResult<ModuleAnalysisManagerCGSCCProxy>(InitialC, CG);212bool Changed = false;213214assert(InitialC.size() > 0 && "Cannot handle an empty SCC!");215Module &M = *InitialC.begin()->getFunction().getParent();216ProfileSummaryInfo *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(M);217218FunctionAnalysisManager &FAM =219AM.getResult<FunctionAnalysisManagerCGSCCProxy>(InitialC, CG)220.getManager();221222InlineAdvisor &Advisor = getAdvisor(MAMProxy, FAM, M);223Advisor.onPassEntry(&InitialC);224225// We use a single common worklist for calls across the entire SCC. We226// process these in-order and append new calls introduced during inlining to227// the end. The PriorityInlineOrder is optional here, in which the smaller228// callee would have a higher priority to inline.229//230// Note that this particular order of processing is actually critical to231// avoid very bad behaviors. Consider *highly connected* call graphs where232// each function contains a small amount of code and a couple of calls to233// other functions. Because the LLVM inliner is fundamentally a bottom-up234// inliner, it can handle gracefully the fact that these all appear to be235// reasonable inlining candidates as it will flatten things until they become236// too big to inline, and then move on and flatten another batch.237//238// However, when processing call edges *within* an SCC we cannot rely on this239// bottom-up behavior. As a consequence, with heavily connected *SCCs* of240// functions we can end up incrementally inlining N calls into each of241// N functions because each incremental inlining decision looks good and we242// don't have a topological ordering to prevent explosions.243//244// To compensate for this, we don't process transitive edges made immediate245// by inlining until we've done one pass of inlining across the entire SCC.246// Large, highly connected SCCs still lead to some amount of code bloat in247// this model, but it is uniformly spread across all the functions in the SCC248// and eventually they all become too large to inline, rather than249// incrementally maknig a single function grow in a super linear fashion.250SmallVector<std::pair<CallBase *, int>, 16> Calls;251252// Populate the initial list of calls in this SCC.253for (auto &N : InitialC) {254auto &ORE =255FAM.getResult<OptimizationRemarkEmitterAnalysis>(N.getFunction());256// We want to generally process call sites top-down in order for257// simplifications stemming from replacing the call with the returned value258// after inlining to be visible to subsequent inlining decisions.259// FIXME: Using instructions sequence is a really bad way to do this.260// Instead we should do an actual RPO walk of the function body.261for (Instruction &I : instructions(N.getFunction()))262if (auto *CB = dyn_cast<CallBase>(&I))263if (Function *Callee = CB->getCalledFunction()) {264if (!Callee->isDeclaration())265Calls.push_back({CB, -1});266else if (!isa<IntrinsicInst>(I)) {267using namespace ore;268setInlineRemark(*CB, "unavailable definition");269ORE.emit([&]() {270return OptimizationRemarkMissed(DEBUG_TYPE, "NoDefinition", &I)271<< NV("Callee", Callee) << " will not be inlined into "272<< NV("Caller", CB->getCaller())273<< " because its definition is unavailable"274<< setIsVerbose();275});276}277}278}279280// Capture updatable variable for the current SCC.281auto *C = &InitialC;282283auto AdvisorOnExit = make_scope_exit([&] { Advisor.onPassExit(C); });284285if (Calls.empty())286return PreservedAnalyses::all();287288// When inlining a callee produces new call sites, we want to keep track of289// the fact that they were inlined from the callee. This allows us to avoid290// infinite inlining in some obscure cases. To represent this, we use an291// index into the InlineHistory vector.292SmallVector<std::pair<Function *, int>, 16> InlineHistory;293294// Track a set vector of inlined callees so that we can augment the caller295// with all of their edges in the call graph before pruning out the ones that296// got simplified away.297SmallSetVector<Function *, 4> InlinedCallees;298299// Track the dead functions to delete once finished with inlining calls. We300// defer deleting these to make it easier to handle the call graph updates.301SmallVector<Function *, 4> DeadFunctions;302303// Track potentially dead non-local functions with comdats to see if they can304// be deleted as a batch after inlining.305SmallVector<Function *, 4> DeadFunctionsInComdats;306307// Loop forward over all of the calls. Note that we cannot cache the size as308// inlining can introduce new calls that need to be processed.309for (int I = 0; I < (int)Calls.size(); ++I) {310// We expect the calls to typically be batched with sequences of calls that311// have the same caller, so we first set up some shared infrastructure for312// this caller. We also do any pruning we can at this layer on the caller313// alone.314Function &F = *Calls[I].first->getCaller();315LazyCallGraph::Node &N = *CG.lookup(F);316if (CG.lookupSCC(N) != C)317continue;318319LLVM_DEBUG(dbgs() << "Inlining calls in: " << F.getName() << "\n"320<< " Function size: " << F.getInstructionCount()321<< "\n");322323auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {324return FAM.getResult<AssumptionAnalysis>(F);325};326327// Now process as many calls as we have within this caller in the sequence.328// We bail out as soon as the caller has to change so we can update the329// call graph and prepare the context of that new caller.330bool DidInline = false;331for (; I < (int)Calls.size() && Calls[I].first->getCaller() == &F; ++I) {332auto &P = Calls[I];333CallBase *CB = P.first;334const int InlineHistoryID = P.second;335Function &Callee = *CB->getCalledFunction();336337if (InlineHistoryID != -1 &&338inlineHistoryIncludes(&Callee, InlineHistoryID, InlineHistory)) {339LLVM_DEBUG(dbgs() << "Skipping inlining due to history: " << F.getName()340<< " -> " << Callee.getName() << "\n");341setInlineRemark(*CB, "recursive");342// Set noinline so that we don't forget this decision across CGSCC343// iterations.344CB->setIsNoInline();345continue;346}347348// Check if this inlining may repeat breaking an SCC apart that has349// already been split once before. In that case, inlining here may350// trigger infinite inlining, much like is prevented within the inliner351// itself by the InlineHistory above, but spread across CGSCC iterations352// and thus hidden from the full inline history.353LazyCallGraph::SCC *CalleeSCC = CG.lookupSCC(*CG.lookup(Callee));354if (CalleeSCC == C && UR.InlinedInternalEdges.count({&N, C})) {355LLVM_DEBUG(dbgs() << "Skipping inlining internal SCC edge from a node "356"previously split out of this SCC by inlining: "357<< F.getName() << " -> " << Callee.getName() << "\n");358setInlineRemark(*CB, "recursive SCC split");359continue;360}361362std::unique_ptr<InlineAdvice> Advice =363Advisor.getAdvice(*CB, OnlyMandatory);364365// Check whether we want to inline this callsite.366if (!Advice)367continue;368369if (!Advice->isInliningRecommended()) {370Advice->recordUnattemptedInlining();371continue;372}373374int CBCostMult =375getStringFnAttrAsInt(376*CB, InlineConstants::FunctionInlineCostMultiplierAttributeName)377.value_or(1);378379// Setup the data structure used to plumb customization into the380// `InlineFunction` routine.381InlineFunctionInfo IFI(382GetAssumptionCache, PSI,383&FAM.getResult<BlockFrequencyAnalysis>(*(CB->getCaller())),384&FAM.getResult<BlockFrequencyAnalysis>(Callee));385386InlineResult IR =387InlineFunction(*CB, IFI, /*MergeAttributes=*/true,388&FAM.getResult<AAManager>(*CB->getCaller()));389if (!IR.isSuccess()) {390Advice->recordUnsuccessfulInlining(IR);391continue;392}393394DidInline = true;395InlinedCallees.insert(&Callee);396++NumInlined;397398LLVM_DEBUG(dbgs() << " Size after inlining: "399<< F.getInstructionCount() << "\n");400401// Add any new callsites to defined functions to the worklist.402if (!IFI.InlinedCallSites.empty()) {403int NewHistoryID = InlineHistory.size();404InlineHistory.push_back({&Callee, InlineHistoryID});405406for (CallBase *ICB : reverse(IFI.InlinedCallSites)) {407Function *NewCallee = ICB->getCalledFunction();408assert(!(NewCallee && NewCallee->isIntrinsic()) &&409"Intrinsic calls should not be tracked.");410if (!NewCallee) {411// Try to promote an indirect (virtual) call without waiting for412// the post-inline cleanup and the next DevirtSCCRepeatedPass413// iteration because the next iteration may not happen and we may414// miss inlining it.415if (tryPromoteCall(*ICB))416NewCallee = ICB->getCalledFunction();417}418if (NewCallee) {419if (!NewCallee->isDeclaration()) {420Calls.push_back({ICB, NewHistoryID});421// Continually inlining through an SCC can result in huge compile422// times and bloated code since we arbitrarily stop at some point423// when the inliner decides it's not profitable to inline anymore.424// We attempt to mitigate this by making these calls exponentially425// more expensive.426// This doesn't apply to calls in the same SCC since if we do427// inline through the SCC the function will end up being428// self-recursive which the inliner bails out on, and inlining429// within an SCC is necessary for performance.430if (CalleeSCC != C &&431CalleeSCC == CG.lookupSCC(CG.get(*NewCallee))) {432Attribute NewCBCostMult = Attribute::get(433M.getContext(),434InlineConstants::FunctionInlineCostMultiplierAttributeName,435itostr(CBCostMult * IntraSCCCostMultiplier));436ICB->addFnAttr(NewCBCostMult);437}438}439}440}441}442443// For local functions or discardable functions without comdats, check444// whether this makes the callee trivially dead. In that case, we can drop445// the body of the function eagerly which may reduce the number of callers446// of other functions to one, changing inline cost thresholds. Non-local447// discardable functions with comdats are checked later on.448bool CalleeWasDeleted = false;449if (Callee.isDiscardableIfUnused() && Callee.hasZeroLiveUses() &&450!CG.isLibFunction(Callee)) {451if (Callee.hasLocalLinkage() || !Callee.hasComdat()) {452Calls.erase(453std::remove_if(Calls.begin() + I + 1, Calls.end(),454[&](const std::pair<CallBase *, int> &Call) {455return Call.first->getCaller() == &Callee;456}),457Calls.end());458459// Clear the body and queue the function itself for call graph460// updating when we finish inlining.461makeFunctionBodyUnreachable(Callee);462assert(!is_contained(DeadFunctions, &Callee) &&463"Cannot put cause a function to become dead twice!");464DeadFunctions.push_back(&Callee);465CalleeWasDeleted = true;466} else {467DeadFunctionsInComdats.push_back(&Callee);468}469}470if (CalleeWasDeleted)471Advice->recordInliningWithCalleeDeleted();472else473Advice->recordInlining();474}475476// Back the call index up by one to put us in a good position to go around477// the outer loop.478--I;479480if (!DidInline)481continue;482Changed = true;483484// At this point, since we have made changes we have at least removed485// a call instruction. However, in the process we do some incremental486// simplification of the surrounding code. This simplification can487// essentially do all of the same things as a function pass and we can488// re-use the exact same logic for updating the call graph to reflect the489// change.490491// Inside the update, we also update the FunctionAnalysisManager in the492// proxy for this particular SCC. We do this as the SCC may have changed and493// as we're going to mutate this particular function we want to make sure494// the proxy is in place to forward any invalidation events.495LazyCallGraph::SCC *OldC = C;496C = &updateCGAndAnalysisManagerForCGSCCPass(CG, *C, N, AM, UR, FAM);497LLVM_DEBUG(dbgs() << "Updated inlining SCC: " << *C << "\n");498499// If this causes an SCC to split apart into multiple smaller SCCs, there500// is a subtle risk we need to prepare for. Other transformations may501// expose an "infinite inlining" opportunity later, and because of the SCC502// mutation, we will revisit this function and potentially re-inline. If we503// do, and that re-inlining also has the potentially to mutate the SCC504// structure, the infinite inlining problem can manifest through infinite505// SCC splits and merges. To avoid this, we capture the originating caller506// node and the SCC containing the call edge. This is a slight over507// approximation of the possible inlining decisions that must be avoided,508// but is relatively efficient to store. We use C != OldC to know when509// a new SCC is generated and the original SCC may be generated via merge510// in later iterations.511//512// It is also possible that even if no new SCC is generated513// (i.e., C == OldC), the original SCC could be split and then merged514// into the same one as itself. and the original SCC will be added into515// UR.CWorklist again, we want to catch such cases too.516//517// FIXME: This seems like a very heavyweight way of retaining the inline518// history, we should look for a more efficient way of tracking it.519if ((C != OldC || UR.CWorklist.count(OldC)) &&520llvm::any_of(InlinedCallees, [&](Function *Callee) {521return CG.lookupSCC(*CG.lookup(*Callee)) == OldC;522})) {523LLVM_DEBUG(dbgs() << "Inlined an internal call edge and split an SCC, "524"retaining this to avoid infinite inlining.\n");525UR.InlinedInternalEdges.insert({&N, OldC});526}527InlinedCallees.clear();528529// Invalidate analyses for this function now so that we don't have to530// invalidate analyses for all functions in this SCC later.531FAM.invalidate(F, PreservedAnalyses::none());532}533534// We must ensure that we only delete functions with comdats if every function535// in the comdat is going to be deleted.536if (!DeadFunctionsInComdats.empty()) {537filterDeadComdatFunctions(DeadFunctionsInComdats);538for (auto *Callee : DeadFunctionsInComdats)539makeFunctionBodyUnreachable(*Callee);540DeadFunctions.append(DeadFunctionsInComdats);541}542543// Now that we've finished inlining all of the calls across this SCC, delete544// all of the trivially dead functions, updating the call graph and the CGSCC545// pass manager in the process.546//547// Note that this walks a pointer set which has non-deterministic order but548// that is OK as all we do is delete things and add pointers to unordered549// sets.550for (Function *DeadF : DeadFunctions) {551CG.markDeadFunction(*DeadF);552// Get the necessary information out of the call graph and nuke the553// function there. Also, clear out any cached analyses.554auto &DeadC = *CG.lookupSCC(*CG.lookup(*DeadF));555FAM.clear(*DeadF, DeadF->getName());556AM.clear(DeadC, DeadC.getName());557558// Mark the relevant parts of the call graph as invalid so we don't visit559// them.560UR.InvalidatedSCCs.insert(&DeadC);561562UR.DeadFunctions.push_back(DeadF);563564++NumDeleted;565}566567if (!Changed)568return PreservedAnalyses::all();569570PreservedAnalyses PA;571// Even if we change the IR, we update the core CGSCC data structures and so572// can preserve the proxy to the function analysis manager.573PA.preserve<FunctionAnalysisManagerCGSCCProxy>();574// We have already invalidated all analyses on modified functions.575PA.preserveSet<AllAnalysesOn<Function>>();576return PA;577}578579ModuleInlinerWrapperPass::ModuleInlinerWrapperPass(InlineParams Params,580bool MandatoryFirst,581InlineContext IC,582InliningAdvisorMode Mode,583unsigned MaxDevirtIterations)584: Params(Params), IC(IC), Mode(Mode),585MaxDevirtIterations(MaxDevirtIterations) {586// Run the inliner first. The theory is that we are walking bottom-up and so587// the callees have already been fully optimized, and we want to inline them588// into the callers so that our optimizations can reflect that.589// For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO590// because it makes profile annotation in the backend inaccurate.591if (MandatoryFirst) {592PM.addPass(InlinerPass(/*OnlyMandatory*/ true));593if (EnablePostSCCAdvisorPrinting)594PM.addPass(InlineAdvisorAnalysisPrinterPass(dbgs()));595}596PM.addPass(InlinerPass());597if (EnablePostSCCAdvisorPrinting)598PM.addPass(InlineAdvisorAnalysisPrinterPass(dbgs()));599}600601PreservedAnalyses ModuleInlinerWrapperPass::run(Module &M,602ModuleAnalysisManager &MAM) {603auto &IAA = MAM.getResult<InlineAdvisorAnalysis>(M);604if (!IAA.tryCreate(Params, Mode,605{CGSCCInlineReplayFile,606CGSCCInlineReplayScope,607CGSCCInlineReplayFallback,608{CGSCCInlineReplayFormat}},609IC)) {610M.getContext().emitError(611"Could not setup Inlining Advisor for the requested "612"mode and/or options");613return PreservedAnalyses::all();614}615616// We wrap the CGSCC pipeline in a devirtualization repeater. This will try617// to detect when we devirtualize indirect calls and iterate the SCC passes618// in that case to try and catch knock-on inlining or function attrs619// opportunities. Then we add it to the module pipeline by walking the SCCs620// in postorder (or bottom-up).621// If MaxDevirtIterations is 0, we just don't use the devirtualization622// wrapper.623if (MaxDevirtIterations == 0)624MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(PM)));625else626MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(627createDevirtSCCRepeatedPass(std::move(PM), MaxDevirtIterations)));628629MPM.addPass(std::move(AfterCGMPM));630MPM.run(M, MAM);631632// Discard the InlineAdvisor, a subsequent inlining session should construct633// its own.634auto PA = PreservedAnalyses::all();635if (!KeepAdvisorForPrinting)636PA.abandon<InlineAdvisorAnalysis>();637return PA;638}639640void InlinerPass::printPipeline(641raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {642static_cast<PassInfoMixin<InlinerPass> *>(this)->printPipeline(643OS, MapClassName2PassName);644if (OnlyMandatory)645OS << "<only-mandatory>";646}647648void ModuleInlinerWrapperPass::printPipeline(649raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {650// Print some info about passes added to the wrapper. This is however651// incomplete as InlineAdvisorAnalysis part isn't included (which also depends652// on Params and Mode).653if (!MPM.isEmpty()) {654MPM.printPipeline(OS, MapClassName2PassName);655OS << ',';656}657OS << "cgscc(";658if (MaxDevirtIterations != 0)659OS << "devirt<" << MaxDevirtIterations << ">(";660PM.printPipeline(OS, MapClassName2PassName);661if (MaxDevirtIterations != 0)662OS << ')';663OS << ')';664}665666667