blob: 4b6ac893c6009b57eb4ecb12f8e95427d5710371 [file]
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package pgo contains the compiler-agnostic portions of PGO profile handling.
// Notably, parsing pprof profiles and serializing/deserializing from a custom
// intermediate representation.
package pgo
import (
"errors"
"fmt"
"internal/profile"
"io"
"sort"
)
// FromPProf parses Profile from a pprof profile.
func FromPProf(r io.Reader) (*Profile, error) {
p, err := profile.Parse(r)
if errors.Is(err, profile.ErrNoData) {
// Treat a completely empty file the same as a profile with no
// samples: nothing to do.
return emptyProfile(), nil
} else if err != nil {
return nil, fmt.Errorf("error parsing profile: %w", err)
}
if len(p.Sample) == 0 {
// We accept empty profiles, but there is nothing to do.
return emptyProfile(), nil
}
valueIndex, err := sampleValueIndex(p)
if err != nil {
return nil, err
}
g := profile.NewGraph(p, &profile.Options{
SampleValue: func(v []int64) int64 { return v[valueIndex] },
})
if len(g.Nodes) == 0 {
// If all sample values are 0, the graph will have no nodes.
// In this case, treat it as an empty profile.
return emptyProfile(), nil
}
namedEdgeMap, totalWeight, err := createNamedEdgeMap(g)
if err != nil {
return nil, err
}
if totalWeight == 0 {
return emptyProfile(), nil // accept but ignore profile with no samples.
}
return &Profile{
TotalWeight: totalWeight,
NamedEdgeMap: namedEdgeMap,
}, nil
}
// sampleValueIndex returns the index of the sample value to use as the PGO
// weight. Non-Go CPU profiles (e.g., from Linux perf) use arbitrary sample
// types, so we accept the default sample type unless it indicates a Go
// non-CPU profile (heap, mutex, block, or goroutine) passed by mistake.
func sampleValueIndex(p *profile.Profile) (int, error) {
if len(p.SampleType) == 0 {
return 0, fmt.Errorf("profile has no sample types")
}
// Prefer runtime/pprof's CPU profile sample types.
for i, s := range p.SampleType {
if (s.Type == "samples" && s.Unit == "count") ||
(s.Type == "cpu" && s.Unit == "nanoseconds") {
return i, nil
}
}
// Use the default sample type, or the last sample type if there is no
// default, as pprof does.
index := len(p.SampleType) - 1
if d := p.DefaultSampleType; d != "" {
for i, s := range p.SampleType {
if s.Type == d {
index = i
break
}
}
}
switch t := p.SampleType[index].Type; t {
case "alloc_objects", "alloc_space", "inuse_objects", "inuse_space":
return 0, fmt.Errorf("profile must be a CPU profile (default sample type %q indicates that this is a Go heap profile)", t)
case "contentions", "delay":
return 0, fmt.Errorf("profile must be a CPU profile (default sample type %q indicates that this is a Go mutex or block profile)", t)
case "goroutine":
return 0, fmt.Errorf("profile must be a CPU profile (default sample type %q indicates that this is a Go goroutine profile)", t)
}
return index, nil
}
// createNamedEdgeMap builds a map of callsite-callee edge weights from the
// profile-graph.
//
// Caller should ignore the profile if totalWeight == 0.
func createNamedEdgeMap(g *profile.Graph) (edgeMap NamedEdgeMap, totalWeight int64, err error) {
seenStartLine := false
// Process graph and build various node and edge maps which will
// be consumed by AST walk.
weight := make(map[NamedCallEdge]int64)
for _, n := range g.Nodes {
seenStartLine = seenStartLine || n.Info.StartLine != 0
canonicalName := n.Info.Name
// Create the key to the nodeMapKey.
namedEdge := NamedCallEdge{
CallerName: canonicalName,
CallSiteOffset: n.Info.Lineno - n.Info.StartLine,
}
for _, e := range n.Out {
totalWeight += e.WeightValue()
namedEdge.CalleeName = e.Dest.Info.Name
// Create new entry or increment existing entry.
weight[namedEdge] += e.WeightValue()
}
}
if !seenStartLine {
// TODO(prattmic): If Function.start_line is missing we could
// fall back to using absolute line numbers, which is better
// than nothing.
return NamedEdgeMap{}, 0, fmt.Errorf("profile missing Function.start_line data (Go version of profiled application too old? Go 1.20+ automatically adds this to profiles)")
}
return postProcessNamedEdgeMap(weight, totalWeight)
}
func sortByWeight(edges []NamedCallEdge, weight map[NamedCallEdge]int64) {
sort.Slice(edges, func(i, j int) bool {
ei, ej := edges[i], edges[j]
if wi, wj := weight[ei], weight[ej]; wi != wj {
return wi > wj // want larger weight first
}
// same weight, order by name/line number
if ei.CallerName != ej.CallerName {
return ei.CallerName < ej.CallerName
}
if ei.CalleeName != ej.CalleeName {
return ei.CalleeName < ej.CalleeName
}
return ei.CallSiteOffset < ej.CallSiteOffset
})
}
func postProcessNamedEdgeMap(weight map[NamedCallEdge]int64, weightVal int64) (edgeMap NamedEdgeMap, totalWeight int64, err error) {
if weightVal == 0 {
return NamedEdgeMap{}, 0, nil // accept but ignore profile with no samples.
}
byWeight := make([]NamedCallEdge, 0, len(weight))
for namedEdge := range weight {
byWeight = append(byWeight, namedEdge)
}
sortByWeight(byWeight, weight)
edgeMap = NamedEdgeMap{
Weight: weight,
ByWeight: byWeight,
}
totalWeight = weightVal
return edgeMap, totalWeight, nil
}