1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // A note on line numbers: when working with line numbers, we always use the
6 // binary-visible relative line number. i.e., the line number as adjusted by
7 // //line directives (ctxt.InnermostPos(ir.Node.Pos()).RelLine()). Use
8 // NodeLineOffset to compute line offsets.
10 // If you are thinking, "wait, doesn't that just make things more complex than
11 // using the real line number?", then you are 100% correct. Unfortunately,
12 // pprof profiles generated by the runtime always contain line numbers as
13 // adjusted by //line directives (because that is what we put in pclntab). Thus
14 // for the best behavior when attempting to match the source with the profile
15 // it makes sense to use the same line number space.
17 // Some of the effects of this to keep in mind:
19 // - For files without //line directives there is no impact, as RelLine() ==
21 // - For functions entirely covered by the same //line directive (i.e., a
22 // directive before the function definition and no directives within the
23 // function), there should also be no impact, as line offsets within the
24 // function should be the same as the real line offsets.
25 // - Functions containing //line directives may be impacted. As fake line
26 // numbers need not be monotonic, we may compute negative line offsets. We
27 // should accept these and attempt to use them for best-effort matching, as
28 // these offsets should still match if the source is unchanged, and may
29 // continue to match with changed source depending on the impact of the
30 // changes on fake line numbers.
31 // - Functions containing //line directives may also contain duplicate lines,
32 // making it ambiguous which call the profile is referencing. This is a
33 // similar problem to multiple calls on a single real line, as we don't
34 // currently track column numbers.
36 // Long term it would be best to extend pprof profiles to include real line
37 // numbers. Until then, we have to live with these complexities. Luckily,
38 // //line directives that change line numbers in strange ways should be rare,
39 // and failing PGO matching on these files is not too big of a loss.
44 "cmd/compile/internal/base"
45 "cmd/compile/internal/ir"
46 "cmd/compile/internal/pgo/internal/graph"
47 "cmd/compile/internal/typecheck"
48 "cmd/compile/internal/types"
55 // IRGraph is a call graph with nodes pointing to IRs of functions and edges
56 // carrying weights and callsite information.
58 // Nodes for indirect calls may have missing IR (IRNode.AST == nil) if the node
59 // is not visible from this package (e.g., not in the transitive deps). Keeping
60 // these nodes allows determining the hottest edge from a call even if that
61 // callee is not available.
63 // TODO(prattmic): Consider merging this data structure with Graph. This is
64 // effectively a copy of Graph aggregated to line number and pointing to IR.
66 // Nodes of the graph. Each node represents a function, keyed by linker
68 IRNodes map[string]*IRNode
71 // IRNode represents a node (function) in the IRGraph.
73 // Pointer to the IR of the Function represented by this node.
75 // Linker symbol name of the Function represented by this node.
76 // Populated only if AST == nil.
77 LinkerSymbolName string
79 // Set of out-edges in the callgraph. The map uniquely identifies each
80 // edge based on the callsite and callee, for fast lookup.
81 OutEdges map[NamedCallEdge]*IREdge
84 // Name returns the symbol name of this function.
85 func (i *IRNode) Name() string {
87 return ir.LinkFuncName(i.AST)
89 return i.LinkerSymbolName
92 // IREdge represents a call edge in the IRGraph with source, destination,
93 // weight, callsite, and line number information.
95 // Source and destination of the edge in IRNode.
98 CallSiteOffset int // Line offset from function start line.
101 // NamedCallEdge identifies a call edge by linker symbol names and call site
103 type NamedCallEdge struct {
106 CallSiteOffset int // Line offset from function start line.
109 // NamedEdgeMap contains all unique call edges in the profile and their
111 type NamedEdgeMap struct {
112 Weight map[NamedCallEdge]int64
114 // ByWeight lists all keys in Weight, sorted by edge weight.
115 ByWeight []NamedCallEdge
118 // CallSiteInfo captures call-site information and its caller/callee.
119 type CallSiteInfo struct {
120 LineOffset int // Line offset from function start line.
125 // Profile contains the processed PGO profile and weighted call graph used for
126 // PGO optimizations.
127 type Profile struct {
128 // Aggregated edge weights across the profile. This helps us determine
129 // the percentage threshold for hot/cold partitioning.
132 // EdgeMap contains all unique call edges in the profile and their
134 NamedEdgeMap NamedEdgeMap
136 // WeightedCG represents the IRGraph built from profile, which we will
137 // update as part of inlining.
141 // New generates a profile-graph from the profile.
142 func New(profileFile string) (*Profile, error) {
143 f, err := os.Open(profileFile)
145 return nil, fmt.Errorf("error opening profile: %w", err)
148 profile, err := profile.Parse(f)
150 return nil, fmt.Errorf("error parsing profile: %w", err)
153 if len(profile.Sample) == 0 {
154 // We accept empty profiles, but there is nothing to do.
159 for i, s := range profile.SampleType {
160 // Samples count is the raw data collected, and CPU nanoseconds is just
161 // a scaled version of it, so either one we can find is fine.
162 if (s.Type == "samples" && s.Unit == "count") ||
163 (s.Type == "cpu" && s.Unit == "nanoseconds") {
169 if valueIndex == -1 {
170 return nil, fmt.Errorf(`profile does not contain a sample index with value/type "samples/count" or cpu/nanoseconds"`)
173 g := graph.NewGraph(profile, &graph.Options{
174 SampleValue: func(v []int64) int64 { return v[valueIndex] },
177 namedEdgeMap, totalWeight, err := createNamedEdgeMap(g)
182 if totalWeight == 0 {
183 return nil, nil // accept but ignore profile with no samples.
186 // Create package-level call graph with weights from profile and IR.
187 wg := createIRGraph(namedEdgeMap)
190 TotalWeight: totalWeight,
191 NamedEdgeMap: namedEdgeMap,
196 // createNamedEdgeMap builds a map of callsite-callee edge weights from the
199 // Caller should ignore the profile if totalWeight == 0.
200 func createNamedEdgeMap(g *graph.Graph) (edgeMap NamedEdgeMap, totalWeight int64, err error) {
201 seenStartLine := false
203 // Process graph and build various node and edge maps which will
204 // be consumed by AST walk.
205 weight := make(map[NamedCallEdge]int64)
206 for _, n := range g.Nodes {
207 seenStartLine = seenStartLine || n.Info.StartLine != 0
209 canonicalName := n.Info.Name
210 // Create the key to the nodeMapKey.
211 namedEdge := NamedCallEdge{
212 CallerName: canonicalName,
213 CallSiteOffset: n.Info.Lineno - n.Info.StartLine,
216 for _, e := range n.Out {
217 totalWeight += e.WeightValue()
218 namedEdge.CalleeName = e.Dest.Info.Name
219 // Create new entry or increment existing entry.
220 weight[namedEdge] += e.WeightValue()
224 if totalWeight == 0 {
225 return NamedEdgeMap{}, 0, nil // accept but ignore profile with no samples.
229 // TODO(prattmic): If Function.start_line is missing we could
230 // fall back to using absolute line numbers, which is better
232 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)")
235 byWeight := make([]NamedCallEdge, 0, len(weight))
236 for namedEdge := range weight {
237 byWeight = append(byWeight, namedEdge)
239 sort.Slice(byWeight, func(i, j int) bool {
240 ei, ej := byWeight[i], byWeight[j]
241 if wi, wj := weight[ei], weight[ej]; wi != wj {
242 return wi > wj // want larger weight first
244 // same weight, order by name/line number
245 if ei.CallerName != ej.CallerName {
246 return ei.CallerName < ej.CallerName
248 if ei.CalleeName != ej.CalleeName {
249 return ei.CalleeName < ej.CalleeName
251 return ei.CallSiteOffset < ej.CallSiteOffset
254 edgeMap = NamedEdgeMap{
259 return edgeMap, totalWeight, nil
262 // initializeIRGraph builds the IRGraph by visiting all the ir.Func in decl list
264 func createIRGraph(namedEdgeMap NamedEdgeMap) *IRGraph {
266 IRNodes: make(map[string]*IRNode),
269 // Bottomup walk over the function to create IRGraph.
270 ir.VisitFuncsBottomUp(typecheck.Target.Funcs, func(list []*ir.Func, recursive bool) {
271 for _, fn := range list {
272 visitIR(fn, namedEdgeMap, g)
276 // Add additional edges for indirect calls. This must be done second so
277 // that IRNodes is fully populated (see the dummy node TODO in
278 // addIndirectEdges).
280 // TODO(prattmic): visitIR above populates the graph via direct calls
281 // discovered via the IR. addIndirectEdges populates the graph via
282 // calls discovered via the profile. This combination of opposite
283 // approaches is a bit awkward, particularly because direct calls are
284 // discoverable via the profile as well. Unify these into a single
286 addIndirectEdges(g, namedEdgeMap)
291 // visitIR traverses the body of each ir.Func adds edges to g from ir.Func to
292 // any called function in the body.
293 func visitIR(fn *ir.Func, namedEdgeMap NamedEdgeMap, g *IRGraph) {
294 name := ir.LinkFuncName(fn)
295 node, ok := g.IRNodes[name]
300 g.IRNodes[name] = node
303 // Recursively walk over the body of the function to create IRGraph edges.
304 createIRGraphEdge(fn, node, name, namedEdgeMap, g)
307 // createIRGraphEdge traverses the nodes in the body of ir.Func and adds edges
308 // between the callernode which points to the ir.Func and the nodes in the
310 func createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string, namedEdgeMap NamedEdgeMap, g *IRGraph) {
311 ir.VisitList(fn.Body, func(n ir.Node) {
314 call := n.(*ir.CallExpr)
315 // Find the callee function from the call site and add the edge.
316 callee := DirectCallee(call.Fun)
318 addIREdge(callernode, name, n, callee, namedEdgeMap, g)
321 call := n.(*ir.CallExpr)
322 // Find the callee method from the call site and add the edge.
323 callee := ir.MethodExprName(call.Fun).Func
324 addIREdge(callernode, name, n, callee, namedEdgeMap, g)
329 // NodeLineOffset returns the line offset of n in fn.
330 func NodeLineOffset(n ir.Node, fn *ir.Func) int {
331 // See "A note on line numbers" at the top of the file.
332 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
333 startLine := int(base.Ctxt.InnermostPos(fn.Pos()).RelLine())
334 return line - startLine
337 // addIREdge adds an edge between caller and new node that points to `callee`
338 // based on the profile-graph and NodeMap.
339 func addIREdge(callerNode *IRNode, callerName string, call ir.Node, callee *ir.Func, namedEdgeMap NamedEdgeMap, g *IRGraph) {
340 calleeName := ir.LinkFuncName(callee)
341 calleeNode, ok := g.IRNodes[calleeName]
343 calleeNode = &IRNode{
346 g.IRNodes[calleeName] = calleeNode
349 namedEdge := NamedCallEdge{
350 CallerName: callerName,
351 CalleeName: calleeName,
352 CallSiteOffset: NodeLineOffset(call, callerNode.AST),
355 // Add edge in the IRGraph from caller to callee.
359 Weight: namedEdgeMap.Weight[namedEdge],
360 CallSiteOffset: namedEdge.CallSiteOffset,
363 if callerNode.OutEdges == nil {
364 callerNode.OutEdges = make(map[NamedCallEdge]*IREdge)
366 callerNode.OutEdges[namedEdge] = edge
369 // LookupMethodFunc looks up a method in export data. It is expected to be
370 // overridden by package noder, to break a dependency cycle.
371 var LookupMethodFunc = func(fullName string) (*ir.Func, error) {
372 base.Fatalf("pgo.LookupMethodFunc not overridden")
376 // addIndirectEdges adds indirect call edges found in the profile to the graph,
377 // to be used for devirtualization.
379 // N.B. despite the name, addIndirectEdges will add any edges discovered via
380 // the profile. We don't know for sure that they are indirect, but assume they
381 // are since direct calls would already be added. (e.g., direct calls that have
382 // been deleted from source since the profile was taken would be added here).
384 // TODO(prattmic): Devirtualization runs before inlining, so we can't devirtualize
385 // calls inside inlined call bodies. If we did add that, we'd need edges from
386 // inlined bodies as well.
387 func addIndirectEdges(g *IRGraph, namedEdgeMap NamedEdgeMap) {
388 // g.IRNodes is populated with the set of functions in the local
389 // package build by VisitIR. We want to filter for local functions
390 // below, but we also add unknown callees to IRNodes as we go. So make
391 // an initial copy of IRNodes to recall just the local functions.
392 localNodes := make(map[string]*IRNode, len(g.IRNodes))
393 for k, v := range g.IRNodes {
397 // N.B. We must consider edges in a stable order because export data
398 // lookup order (LookupMethodFunc, below) can impact the export data of
399 // this package, which must be stable across different invocations for
402 // The weight ordering of ByWeight is irrelevant, it just happens to be
403 // an ordered list of edges that is already available.
404 for _, key := range namedEdgeMap.ByWeight {
405 weight := namedEdgeMap.Weight[key]
406 // All callers in the local package build were added to IRNodes
407 // in VisitIR. If a caller isn't in the local package build we
408 // can skip adding edges, since we won't be devirtualizing in
409 // them anyway. This keeps the graph smaller.
410 callerNode, ok := localNodes[key.CallerName]
415 // Already handled this edge?
416 if _, ok := callerNode.OutEdges[key]; ok {
420 calleeNode, ok := g.IRNodes[key.CalleeName]
422 // IR is missing for this callee. VisitIR populates
423 // IRNodes with all functions discovered via local
424 // package function declarations and calls. This
425 // function may still be available from export data of
426 // a transitive dependency.
428 // TODO(prattmic): Currently we only attempt to lookup
429 // methods because we can only devirtualize interface
430 // calls, not any function pointer. Generic types are
433 // TODO(prattmic): This eager lookup during graph load
434 // is simple, but wasteful. We are likely to load many
435 // functions that we never need. We could delay load
436 // until we actually need the method in
437 // devirtualization. Instantiation of generic functions
438 // will likely need to be done at the devirtualization
440 fn, err := LookupMethodFunc(key.CalleeName)
442 if base.Debug.PGODebug >= 3 {
443 fmt.Printf("addIndirectEdges: %s found in export data\n", key.CalleeName)
445 calleeNode = &IRNode{AST: fn}
447 // N.B. we could call createIRGraphEdge to add
448 // direct calls in this newly-imported
449 // function's body to the graph. Similarly, we
450 // could add to this function's queue to add
451 // indirect calls. However, those would be
452 // useless given the visit order of inlining,
453 // and the ordering of PGO devirtualization and
454 // inlining. This function can only be used as
455 // an inlined body. We will never do PGO
456 // devirtualization inside an inlined call. Nor
457 // will we perform inlining inside an inlined
460 // Still not found. Most likely this is because
461 // the callee isn't in the transitive deps of
464 // Record this call anyway. If this is the hottest,
465 // then we want to skip devirtualization rather than
466 // devirtualizing to the second most common callee.
467 if base.Debug.PGODebug >= 3 {
468 fmt.Printf("addIndirectEdges: %s not found in export data: %v\n", key.CalleeName, err)
470 calleeNode = &IRNode{LinkerSymbolName: key.CalleeName}
473 // Add dummy node back to IRNodes. We don't need this
474 // directly, but PrintWeightedCallGraphDOT uses these
476 g.IRNodes[key.CalleeName] = calleeNode
482 CallSiteOffset: key.CallSiteOffset,
485 if callerNode.OutEdges == nil {
486 callerNode.OutEdges = make(map[NamedCallEdge]*IREdge)
488 callerNode.OutEdges[key] = edge
492 // WeightInPercentage converts profile weights to a percentage.
493 func WeightInPercentage(value int64, total int64) float64 {
494 return (float64(value) / float64(total)) * 100
497 // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
498 func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
499 fmt.Printf("\ndigraph G {\n")
500 fmt.Printf("forcelabels=true;\n")
502 // List of functions in this package.
503 funcs := make(map[string]struct{})
504 ir.VisitFuncsBottomUp(typecheck.Target.Funcs, func(list []*ir.Func, recursive bool) {
505 for _, f := range list {
506 name := ir.LinkFuncName(f)
507 funcs[name] = struct{}{}
511 // Determine nodes of DOT.
513 // Note that ir.Func may be nil for functions not visible from this
515 nodes := make(map[string]*ir.Func)
516 for name := range funcs {
517 if n, ok := p.WeightedCG.IRNodes[name]; ok {
518 for _, e := range n.OutEdges {
519 if _, ok := nodes[e.Src.Name()]; !ok {
520 nodes[e.Src.Name()] = e.Src.AST
522 if _, ok := nodes[e.Dst.Name()]; !ok {
523 nodes[e.Dst.Name()] = e.Dst.AST
526 if _, ok := nodes[n.Name()]; !ok {
527 nodes[n.Name()] = n.AST
533 for name, ast := range nodes {
534 if _, ok := p.WeightedCG.IRNodes[name]; ok {
540 if ast != nil && ast.Inl != nil {
541 fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v,inl_cost=%d\"];\n", name, style, name, ast.Inl.Cost)
543 fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v\"];\n", name, style, name)
548 ir.VisitFuncsBottomUp(typecheck.Target.Funcs, func(list []*ir.Func, recursive bool) {
549 for _, f := range list {
550 name := ir.LinkFuncName(f)
551 if n, ok := p.WeightedCG.IRNodes[name]; ok {
552 for _, e := range n.OutEdges {
554 if e.Dst.AST == nil {
558 edgepercent := WeightInPercentage(e.Weight, p.TotalWeight)
559 if edgepercent > edgeThreshold {
563 fmt.Printf("edge [color=%s, style=%s];\n", color, style)
564 fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", n.Name(), e.Dst.Name(), edgepercent)
572 // DirectCallee takes a function-typed expression and returns the underlying
573 // function that it refers to if statically known. Otherwise, it returns nil.
575 // Equivalent to inline.inlCallee without calling CanInline on closures.
576 func DirectCallee(fn ir.Node) *ir.Func {
577 fn = ir.StaticValue(fn)
580 fn := fn.(*ir.SelectorExpr)
581 n := ir.MethodExprName(fn)
582 // Check that receiver type matches fn.X.
583 // TODO(mdempsky): Handle implicit dereference
584 // of pointer receiver argument?
585 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
591 if fn.Class == ir.PFUNC {
595 fn := fn.(*ir.ClosureExpr)