106f32e7eSjoerg //=- SyntheticCountsPropagation.cpp - Propagate function counts --*- C++ -*-=//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file implements a transformation that synthesizes entry counts for
1006f32e7eSjoerg // functions and attaches !prof metadata to functions with the synthesized
1106f32e7eSjoerg // counts. The presence of !prof metadata with counter name set to
1206f32e7eSjoerg // 'synthesized_function_entry_count' indicate that the value of the counter is
1306f32e7eSjoerg // an estimation of the likely execution count of the function. This transform
1406f32e7eSjoerg // is applied only in non PGO mode as functions get 'real' profile-based
1506f32e7eSjoerg // function entry counts in the PGO mode.
1606f32e7eSjoerg //
1706f32e7eSjoerg // The transformation works by first assigning some initial values to the entry
1806f32e7eSjoerg // counts of all functions and then doing a top-down traversal of the
1906f32e7eSjoerg // callgraph-scc to propagate the counts. For each function the set of callsites
2006f32e7eSjoerg // and their relative block frequency is gathered. The relative block frequency
2106f32e7eSjoerg // multiplied by the entry count of the caller and added to the callee's entry
2206f32e7eSjoerg // count. For non-trivial SCCs, the new counts are computed from the previous
2306f32e7eSjoerg // counts and updated in one shot.
2406f32e7eSjoerg //
2506f32e7eSjoerg //===----------------------------------------------------------------------===//
2606f32e7eSjoerg 
2706f32e7eSjoerg #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
2806f32e7eSjoerg #include "llvm/ADT/DenseSet.h"
2906f32e7eSjoerg #include "llvm/ADT/STLExtras.h"
3006f32e7eSjoerg #include "llvm/Analysis/BlockFrequencyInfo.h"
3106f32e7eSjoerg #include "llvm/Analysis/CallGraph.h"
3206f32e7eSjoerg #include "llvm/Analysis/ProfileSummaryInfo.h"
3306f32e7eSjoerg #include "llvm/Analysis/SyntheticCountsUtils.h"
3406f32e7eSjoerg #include "llvm/IR/Function.h"
3506f32e7eSjoerg #include "llvm/IR/Instructions.h"
3606f32e7eSjoerg #include "llvm/IR/Module.h"
3706f32e7eSjoerg #include "llvm/Support/CommandLine.h"
3806f32e7eSjoerg #include "llvm/Support/Debug.h"
3906f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
4006f32e7eSjoerg 
4106f32e7eSjoerg using namespace llvm;
4206f32e7eSjoerg using Scaled64 = ScaledNumber<uint64_t>;
4306f32e7eSjoerg using ProfileCount = Function::ProfileCount;
4406f32e7eSjoerg 
4506f32e7eSjoerg #define DEBUG_TYPE "synthetic-counts-propagation"
4606f32e7eSjoerg 
47*da58b97aSjoerg namespace llvm {
4806f32e7eSjoerg cl::opt<int>
4906f32e7eSjoerg     InitialSyntheticCount("initial-synthetic-count", cl::Hidden, cl::init(10),
5006f32e7eSjoerg                           cl::ZeroOrMore,
51*da58b97aSjoerg                           cl::desc("Initial value of synthetic entry count"));
52*da58b97aSjoerg } // namespace llvm
5306f32e7eSjoerg 
5406f32e7eSjoerg /// Initial synthetic count assigned to inline functions.
5506f32e7eSjoerg static cl::opt<int> InlineSyntheticCount(
5606f32e7eSjoerg     "inline-synthetic-count", cl::Hidden, cl::init(15), cl::ZeroOrMore,
5706f32e7eSjoerg     cl::desc("Initial synthetic entry count for inline functions."));
5806f32e7eSjoerg 
5906f32e7eSjoerg /// Initial synthetic count assigned to cold functions.
6006f32e7eSjoerg static cl::opt<int> ColdSyntheticCount(
6106f32e7eSjoerg     "cold-synthetic-count", cl::Hidden, cl::init(5), cl::ZeroOrMore,
6206f32e7eSjoerg     cl::desc("Initial synthetic entry count for cold functions."));
6306f32e7eSjoerg 
6406f32e7eSjoerg // Assign initial synthetic entry counts to functions.
6506f32e7eSjoerg static void
initializeCounts(Module & M,function_ref<void (Function *,uint64_t)> SetCount)6606f32e7eSjoerg initializeCounts(Module &M, function_ref<void(Function *, uint64_t)> SetCount) {
6706f32e7eSjoerg   auto MayHaveIndirectCalls = [](Function &F) {
6806f32e7eSjoerg     for (auto *U : F.users()) {
6906f32e7eSjoerg       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
7006f32e7eSjoerg         return true;
7106f32e7eSjoerg     }
7206f32e7eSjoerg     return false;
7306f32e7eSjoerg   };
7406f32e7eSjoerg 
7506f32e7eSjoerg   for (Function &F : M) {
7606f32e7eSjoerg     uint64_t InitialCount = InitialSyntheticCount;
7706f32e7eSjoerg     if (F.isDeclaration())
7806f32e7eSjoerg       continue;
7906f32e7eSjoerg     if (F.hasFnAttribute(Attribute::AlwaysInline) ||
8006f32e7eSjoerg         F.hasFnAttribute(Attribute::InlineHint)) {
8106f32e7eSjoerg       // Use a higher value for inline functions to account for the fact that
8206f32e7eSjoerg       // these are usually beneficial to inline.
8306f32e7eSjoerg       InitialCount = InlineSyntheticCount;
8406f32e7eSjoerg     } else if (F.hasLocalLinkage() && !MayHaveIndirectCalls(F)) {
8506f32e7eSjoerg       // Local functions without inline hints get counts only through
8606f32e7eSjoerg       // propagation.
8706f32e7eSjoerg       InitialCount = 0;
8806f32e7eSjoerg     } else if (F.hasFnAttribute(Attribute::Cold) ||
8906f32e7eSjoerg                F.hasFnAttribute(Attribute::NoInline)) {
9006f32e7eSjoerg       // Use a lower value for noinline and cold functions.
9106f32e7eSjoerg       InitialCount = ColdSyntheticCount;
9206f32e7eSjoerg     }
9306f32e7eSjoerg     SetCount(&F, InitialCount);
9406f32e7eSjoerg   }
9506f32e7eSjoerg }
9606f32e7eSjoerg 
run(Module & M,ModuleAnalysisManager & MAM)9706f32e7eSjoerg PreservedAnalyses SyntheticCountsPropagation::run(Module &M,
9806f32e7eSjoerg                                                   ModuleAnalysisManager &MAM) {
9906f32e7eSjoerg   FunctionAnalysisManager &FAM =
10006f32e7eSjoerg       MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
10106f32e7eSjoerg   DenseMap<Function *, Scaled64> Counts;
10206f32e7eSjoerg   // Set initial entry counts.
10306f32e7eSjoerg   initializeCounts(
10406f32e7eSjoerg       M, [&](Function *F, uint64_t Count) { Counts[F] = Scaled64(Count, 0); });
10506f32e7eSjoerg 
10606f32e7eSjoerg   // Edge includes information about the source. Hence ignore the first
10706f32e7eSjoerg   // parameter.
10806f32e7eSjoerg   auto GetCallSiteProfCount = [&](const CallGraphNode *,
10906f32e7eSjoerg                                   const CallGraphNode::CallRecord &Edge) {
11006f32e7eSjoerg     Optional<Scaled64> Res = None;
11106f32e7eSjoerg     if (!Edge.first)
11206f32e7eSjoerg       return Res;
113*da58b97aSjoerg     CallBase &CB = *cast<CallBase>(*Edge.first);
114*da58b97aSjoerg     Function *Caller = CB.getCaller();
11506f32e7eSjoerg     auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(*Caller);
11606f32e7eSjoerg 
11706f32e7eSjoerg     // Now compute the callsite count from relative frequency and
11806f32e7eSjoerg     // entry count:
119*da58b97aSjoerg     BasicBlock *CSBB = CB.getParent();
12006f32e7eSjoerg     Scaled64 EntryFreq(BFI.getEntryFreq(), 0);
12106f32e7eSjoerg     Scaled64 BBCount(BFI.getBlockFreq(CSBB).getFrequency(), 0);
12206f32e7eSjoerg     BBCount /= EntryFreq;
12306f32e7eSjoerg     BBCount *= Counts[Caller];
12406f32e7eSjoerg     return Optional<Scaled64>(BBCount);
12506f32e7eSjoerg   };
12606f32e7eSjoerg 
12706f32e7eSjoerg   CallGraph CG(M);
12806f32e7eSjoerg   // Propgate the entry counts on the callgraph.
12906f32e7eSjoerg   SyntheticCountsUtils<const CallGraph *>::propagate(
13006f32e7eSjoerg       &CG, GetCallSiteProfCount, [&](const CallGraphNode *N, Scaled64 New) {
13106f32e7eSjoerg         auto F = N->getFunction();
13206f32e7eSjoerg         if (!F || F->isDeclaration())
13306f32e7eSjoerg           return;
13406f32e7eSjoerg 
13506f32e7eSjoerg         Counts[F] += New;
13606f32e7eSjoerg       });
13706f32e7eSjoerg 
13806f32e7eSjoerg   // Set the counts as metadata.
13906f32e7eSjoerg   for (auto Entry : Counts) {
14006f32e7eSjoerg     Entry.first->setEntryCount(ProfileCount(
14106f32e7eSjoerg         Entry.second.template toInt<uint64_t>(), Function::PCT_Synthetic));
14206f32e7eSjoerg   }
14306f32e7eSjoerg 
14406f32e7eSjoerg   return PreservedAnalyses::all();
14506f32e7eSjoerg }
146