#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/SyntheticCountsUtils.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
using Scaled64 = ScaledNumber<uint64_t>;
using ProfileCount = Function::ProfileCount;
#define DEBUG_TYPE "synthetic-counts-propagation"
namespace llvm {
cl::opt<int>
InitialSyntheticCount("initial-synthetic-count", cl::Hidden, cl::init(10),
cl::desc("Initial value of synthetic entry count"));
}
static cl::opt<int> InlineSyntheticCount(
"inline-synthetic-count", cl::Hidden, cl::init(15),
cl::desc("Initial synthetic entry count for inline functions."));
static cl::opt<int> ColdSyntheticCount(
"cold-synthetic-count", cl::Hidden, cl::init(5),
cl::desc("Initial synthetic entry count for cold functions."));
static void
initializeCounts(Module &M, function_ref<void(Function *, uint64_t)> SetCount) {
auto MayHaveIndirectCalls = [](Function &F) {
for (auto *U : F.users()) {
if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
return true;
}
return false;
};
for (Function &F : M) {
uint64_t InitialCount = InitialSyntheticCount;
if (F.isDeclaration())
continue;
if (F.hasFnAttribute(Attribute::AlwaysInline) ||
F.hasFnAttribute(Attribute::InlineHint)) {
InitialCount = InlineSyntheticCount;
} else if (F.hasLocalLinkage() && !MayHaveIndirectCalls(F)) {
InitialCount = 0;
} else if (F.hasFnAttribute(Attribute::Cold) ||
F.hasFnAttribute(Attribute::NoInline)) {
InitialCount = ColdSyntheticCount;
}
SetCount(&F, InitialCount);
}
}
PreservedAnalyses SyntheticCountsPropagation::run(Module &M,
ModuleAnalysisManager &MAM) {
FunctionAnalysisManager &FAM =
MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
DenseMap<Function *, Scaled64> Counts;
initializeCounts(
M, [&](Function *F, uint64_t Count) { Counts[F] = Scaled64(Count, 0); });
auto GetCallSiteProfCount = [&](const CallGraphNode *,
const CallGraphNode::CallRecord &Edge) {
Optional<Scaled64> Res = None;
if (!Edge.first)
return Res;
CallBase &CB = *cast<CallBase>(*Edge.first);
Function *Caller = CB.getCaller();
auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(*Caller);
BasicBlock *CSBB = CB.getParent();
Scaled64 EntryFreq(BFI.getEntryFreq(), 0);
Scaled64 BBCount(BFI.getBlockFreq(CSBB).getFrequency(), 0);
BBCount /= EntryFreq;
BBCount *= Counts[Caller];
return Optional<Scaled64>(BBCount);
};
CallGraph CG(M);
SyntheticCountsUtils<const CallGraph *>::propagate(
&CG, GetCallSiteProfCount, [&](const CallGraphNode *N, Scaled64 New) {
auto F = N->getFunction();
if (!F || F->isDeclaration())
return;
Counts[F] += New;
});
for (auto Entry : Counts) {
Entry.first->setEntryCount(ProfileCount(
Entry.second.template toInt<uint64_t>(), Function::PCT_Synthetic));
}
return PreservedAnalyses::all();
}