127 changes: 127 additions & 0 deletions llvm/lib/Transforms/IPO/SyntheticCountsPropagation.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//=- SyntheticCountsPropagation.cpp - Propagate function counts --*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a transformation that synthesizes entry counts for
// functions and attaches !prof metadata to functions with the synthesized
// counts. The presence of !prof metadata with counter name set to
// 'synthesized_function_entry_count' indicate that the value of the counter is
// an estimation of the likely execution count of the function. This transform
// is applied only in non PGO mode as functions get 'real' profile-based
// function entry counts in the PGO mode.
//
// The transformation works by first assigning some initial values to the entry
// counts of all functions and then doing a top-down traversal of the
// callgraph-scc to propagate the counts. For each function the set of callsites
// and their relative block frequency is gathered. The relative block frequency
// multiplied by the entry count of the caller and added to the callee's entry
// count. For non-trivial SCCs, the new counts are computed from the previous
// counts and updated in one shot.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/SyntheticCountsUtils.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using Scaled64 = ScaledNumber<uint64_t>;

#define DEBUG_TYPE "synthetic-counts-propagation"

/// Initial synthetic count assigned to functions.
static cl::opt<int>
InitialSyntheticCount("initial-synthetic-count", cl::Hidden, cl::init(10),
cl::ZeroOrMore,
cl::desc("Initial value of synthetic entry count."));

/// Initial synthetic count assigned to inline functions.
static cl::opt<int> InlineSyntheticCount(
"inline-synthetic-count", cl::Hidden, cl::init(15), cl::ZeroOrMore,
cl::desc("Initial synthetic entry count for inline functions."));

/// Initial synthetic count assigned to cold functions.
static cl::opt<int> ColdSyntheticCount(
"cold-synthetic-count", cl::Hidden, cl::init(5), cl::ZeroOrMore,
cl::desc("Initial synthetic entry count for cold functions."));

// Assign initial synthetic entry counts to 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)) {
// Use a higher value for inline functions to account for the fact that
// these are usually beneficial to inline.
InitialCount = InlineSyntheticCount;
} else if (F.hasLocalLinkage() && !MayHaveIndirectCalls(F)) {
// Local functions without inline hints get counts only through
// propagation.
InitialCount = 0;
} else if (F.hasFnAttribute(Attribute::Cold) ||
F.hasFnAttribute(Attribute::NoInline)) {
// Use a lower value for noinline and cold functions.
InitialCount = ColdSyntheticCount;
}
SetCount(&F, InitialCount);
}
}

PreservedAnalyses SyntheticCountsPropagation::run(Module &M,
ModuleAnalysisManager &MAM) {
FunctionAnalysisManager &FAM =
MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
DenseMap<Function *, uint64_t> Counts;
// Set initial entry counts.
initializeCounts(M, [&](Function *F, uint64_t Count) { Counts[F] = Count; });

// Compute the relative block frequency for a callsite. Use scaled numbers
// and not integers since the relative block frequency could be less than 1.
auto GetCallSiteRelFreq = [&](CallSite CS) {
Function *Caller = CS.getCaller();
auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(*Caller);
BasicBlock *CSBB = CS.getInstruction()->getParent();
Scaled64 EntryFreq(BFI.getEntryFreq(), 0);
Scaled64 BBFreq(BFI.getBlockFreq(CSBB).getFrequency(), 0);
BBFreq /= EntryFreq;
return BBFreq;
};

CallGraph CG(M);
// Propgate the entry counts on the callgraph.
propagateSyntheticCounts(
CG, GetCallSiteRelFreq, [&](Function *F) { return Counts[F]; },
[&](Function *F, uint64_t New) { Counts[F] += New; });

// Set the counts as metadata.
for (auto Entry : Counts)
Entry.first->setEntryCount(Entry.second, true);

return PreservedAnalyses::all();
}
79 changes: 79 additions & 0 deletions llvm/test/Transforms/SyntheticCountsPropagation/initial.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
; RUN: opt -passes=synthetic-counts-propagation -S < %s | FileCheck %s

; CHECK-LABEL: define void @foo()
; CHECK: !prof ![[COUNT1:[0-9]+]]
define void @foo() {
ret void
}

; CHECK-LABEL: define void @foo_inline() #0
; CHECK: !prof ![[COUNT2:[0-9]+]]
define void @foo_inline() #0 {
ret void
}

; CHECK-LABEL: define void @foo_always_inline() #1
; CHECK: !prof ![[COUNT2]]
define void @foo_always_inline() #1 {
ret void
}

; CHECK-LABEL: define void @foo_cold() #2
; CHECK: !prof ![[COUNT3:[0-9]+]]
define void @foo_cold() #2 {
ret void
}

; CHECK-LABEL: define void @foo_noinline() #3
; CHECK: !prof ![[COUNT3]]
define void @foo_noinline() #3 {
ret void
}

; CHECK-LABEL: define internal void @foo_local()
; CHECK: !prof ![[COUNT4:[0-9]+]]
define internal void @foo_local() {
ret void
}

; CHECK-LABEL: define internal void @foo_local_escaped()
; CHECK: !prof ![[COUNT1]]
define internal void @foo_local_escaped() {
ret void
}

declare void @ext(void ()*)

define void @bar() {
call void @ext(void ()* nonnull @foo_local_escaped)
ret void
}

; CHECK-LABEL: define internal void @foo_local_inline() #0
; CHECK: !prof ![[COUNT2]]
define internal void @foo_local_inline() #0 {
ret void
}

; CHECK-LABEL: define internal void @foo_local_cold() #2
; CHECK: !prof ![[COUNT4]]
define internal void @foo_local_cold() #2 {
ret void
}

; CHECK-LABEL: define linkonce void @foo_linkonce()
; CHECK: !prof ![[COUNT1]]
define linkonce void @foo_linkonce() {
ret void
}

; CHECK: ![[COUNT1]] = !{!"synthetic_function_entry_count", i64 10}
; CHECK: ![[COUNT2]] = !{!"synthetic_function_entry_count", i64 15}
; CHECK: ![[COUNT3]] = !{!"synthetic_function_entry_count", i64 5}
; CHECK: ![[COUNT4]] = !{!"synthetic_function_entry_count", i64 0}

attributes #0 = {inlinehint}
attributes #1 = {alwaysinline}
attributes #2 = {cold}
attributes #3 = {noinline}

50 changes: 50 additions & 0 deletions llvm/test/Transforms/SyntheticCountsPropagation/prop.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
; RUN: opt -passes=synthetic-counts-propagation -S < %s | FileCheck %s

; CHECK-LABEL: define void @level1a(i32 %n)
; CHECK: !prof ![[COUNT1:[0-9]+]]
define void @level1a(i32 %n) {
entry:
%cmp = icmp sgt i32 %n, 10
br i1 %cmp, label %exit, label %loop
loop:
%i = phi i32 [%n, %entry], [%i1, %loop]
call void @level2a(i32 %n)
%i1 = sub i32 %i, 1
%cmp2 = icmp eq i32 %i1, 0
br i1 %cmp2, label %exit, label %loop, !prof !1
exit:
ret void
}

; CHECK-LABEL: define void @level2a(i32 %n)
; CHECK: !prof ![[COUNT2:[0-9]+]]
define void @level2a(i32 %n) {
call void @level2b(i32 %n)
ret void
}

; CHECK-LABEL: define void @level2b(i32 %n)
; CHECK: !prof ![[COUNT2]]
define void @level2b(i32 %n) {
entry:
call void @level2a(i32 %n)
%cmp = icmp eq i32 %n, 0
br i1 %cmp, label %then, label %else, !prof !2
then:
call void @level3a(i32 %n)
br label %else
else:
ret void
}

; CHECK-LABEL: define internal void @level3a(i32 %n)
; CHECK: !prof ![[COUNT3:[0-9]+]]
define internal void @level3a(i32 %n) {
ret void
}

!1 = !{!"branch_weights", i32 1, i32 99}
!2 = !{!"branch_weights", i32 1, i32 1}
; CHECK: ![[COUNT1]] = !{!"synthetic_function_entry_count", i64 10}
; CHECK: ![[COUNT2]] = !{!"synthetic_function_entry_count", i64 520}
; CHECK: ![[COUNT3]] = !{!"synthetic_function_entry_count", i64 260}
19 changes: 19 additions & 0 deletions llvm/test/Transforms/SyntheticCountsPropagation/scc.ll
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
; RUN: opt -passes=synthetic-counts-propagation -S < %s | FileCheck %s

; CHECK-LABEL: define void @foo()
; CHECK: !prof ![[COUNT1:[0-9]+]]
define void @foo() {
call void @bar()
ret void
}

; CHECK-LABEL: define void @bar() #0
; CHECK: !prof ![[COUNT1]]
define void @bar() #0 {
call void @foo()
ret void
}

attributes #0 = {inlinehint}

; CHECK: ![[COUNT1]] = !{!"synthetic_function_entry_count", i64 25}