]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/pgo/irgraph.go
be802dabc8d1ad4f298b294c2708b8be956da089
[gostls13.git] / src / cmd / compile / internal / pgo / irgraph.go
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.
4
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.
9 //
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.
16 //
17 // Some of the effects of this to keep in mind:
18 //
19 //  - For files without //line directives there is no impact, as RelLine() ==
20 //    Line().
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.
35 //
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.
40
41 package pgo
42
43 import (
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"
49         "fmt"
50         "internal/profile"
51         "os"
52         "sort"
53 )
54
55 // IRGraph is a call graph with nodes pointing to IRs of functions and edges
56 // carrying weights and callsite information.
57 //
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.
62 //
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.
65 type IRGraph struct {
66         // Nodes of the graph. Each node represents a function, keyed by linker
67         // symbol name.
68         IRNodes map[string]*IRNode
69 }
70
71 // IRNode represents a node (function) in the IRGraph.
72 type IRNode struct {
73         // Pointer to the IR of the Function represented by this node.
74         AST *ir.Func
75         // Linker symbol name of the Function represented by this node.
76         // Populated only if AST == nil.
77         LinkerSymbolName string
78
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
82 }
83
84 // Name returns the symbol name of this function.
85 func (i *IRNode) Name() string {
86         if i.AST != nil {
87                 return ir.LinkFuncName(i.AST)
88         }
89         return i.LinkerSymbolName
90 }
91
92 // IREdge represents a call edge in the IRGraph with source, destination,
93 // weight, callsite, and line number information.
94 type IREdge struct {
95         // Source and destination of the edge in IRNode.
96         Src, Dst       *IRNode
97         Weight         int64
98         CallSiteOffset int // Line offset from function start line.
99 }
100
101 // NamedCallEdge identifies a call edge by linker symbol names and call site
102 // offset.
103 type NamedCallEdge struct {
104         CallerName     string
105         CalleeName     string
106         CallSiteOffset int // Line offset from function start line.
107 }
108
109 // NamedEdgeMap contains all unique call edges in the profile and their
110 // edge weight.
111 type NamedEdgeMap struct {
112         Weight map[NamedCallEdge]int64
113
114         // ByWeight lists all keys in Weight, sorted by edge weight.
115         ByWeight []NamedCallEdge
116 }
117
118 // CallSiteInfo captures call-site information and its caller/callee.
119 type CallSiteInfo struct {
120         LineOffset int // Line offset from function start line.
121         Caller     *ir.Func
122         Callee     *ir.Func
123 }
124
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.
130         TotalWeight int64
131
132         // EdgeMap contains all unique call edges in the profile and their
133         // edge weight.
134         NamedEdgeMap NamedEdgeMap
135
136         // WeightedCG represents the IRGraph built from profile, which we will
137         // update as part of inlining.
138         WeightedCG *IRGraph
139 }
140
141 // New generates a profile-graph from the profile.
142 func New(profileFile string) (*Profile, error) {
143         f, err := os.Open(profileFile)
144         if err != nil {
145                 return nil, fmt.Errorf("error opening profile: %w", err)
146         }
147         defer f.Close()
148         profile, err := profile.Parse(f)
149         if err != nil {
150                 return nil, fmt.Errorf("error parsing profile: %w", err)
151         }
152
153         if len(profile.Sample) == 0 {
154                 // We accept empty profiles, but there is nothing to do.
155                 return nil, nil
156         }
157
158         valueIndex := -1
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") {
164                         valueIndex = i
165                         break
166                 }
167         }
168
169         if valueIndex == -1 {
170                 return nil, fmt.Errorf(`profile does not contain a sample index with value/type "samples/count" or cpu/nanoseconds"`)
171         }
172
173         g := graph.NewGraph(profile, &graph.Options{
174                 SampleValue: func(v []int64) int64 { return v[valueIndex] },
175         })
176
177         namedEdgeMap, totalWeight, err := createNamedEdgeMap(g)
178         if err != nil {
179                 return nil, err
180         }
181
182         if totalWeight == 0 {
183                 return nil, nil // accept but ignore profile with no samples.
184         }
185
186         // Create package-level call graph with weights from profile and IR.
187         wg := createIRGraph(namedEdgeMap)
188
189         return &Profile{
190                 TotalWeight:  totalWeight,
191                 NamedEdgeMap: namedEdgeMap,
192                 WeightedCG:   wg,
193         }, nil
194 }
195
196 // createNamedEdgeMap builds a map of callsite-callee edge weights from the
197 // profile-graph.
198 //
199 // Caller should ignore the profile if totalWeight == 0.
200 func createNamedEdgeMap(g *graph.Graph) (edgeMap NamedEdgeMap, totalWeight int64, err error) {
201         seenStartLine := false
202
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
208
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,
214                 }
215
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()
221                 }
222         }
223
224         if totalWeight == 0 {
225                 return NamedEdgeMap{}, 0, nil // accept but ignore profile with no samples.
226         }
227
228         if !seenStartLine {
229                 // TODO(prattmic): If Function.start_line is missing we could
230                 // fall back to using absolute line numbers, which is better
231                 // than nothing.
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)")
233         }
234
235         byWeight := make([]NamedCallEdge, 0, len(weight))
236         for namedEdge := range weight {
237                 byWeight = append(byWeight, namedEdge)
238         }
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
243                 }
244                 // same weight, order by name/line number
245                 if ei.CallerName != ej.CallerName {
246                         return ei.CallerName < ej.CallerName
247                 }
248                 if ei.CalleeName != ej.CalleeName {
249                         return ei.CalleeName < ej.CalleeName
250                 }
251                 return ei.CallSiteOffset < ej.CallSiteOffset
252         })
253
254         edgeMap = NamedEdgeMap{
255                 Weight:   weight,
256                 ByWeight: byWeight,
257         }
258
259         return edgeMap, totalWeight, nil
260 }
261
262 // initializeIRGraph builds the IRGraph by visiting all the ir.Func in decl list
263 // of a package.
264 func createIRGraph(namedEdgeMap NamedEdgeMap) *IRGraph {
265         g := &IRGraph{
266                 IRNodes: make(map[string]*IRNode),
267         }
268
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)
273                 }
274         })
275
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).
279         //
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
285         // approach.
286         addIndirectEdges(g, namedEdgeMap)
287
288         return g
289 }
290
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]
296         if !ok {
297                 node = &IRNode{
298                         AST: fn,
299                 }
300                 g.IRNodes[name] = node
301         }
302
303         // Recursively walk over the body of the function to create IRGraph edges.
304         createIRGraphEdge(fn, node, name, namedEdgeMap, g)
305 }
306
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
309 // body.
310 func createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string, namedEdgeMap NamedEdgeMap, g *IRGraph) {
311         ir.VisitList(fn.Body, func(n ir.Node) {
312                 switch n.Op() {
313                 case ir.OCALLFUNC:
314                         call := n.(*ir.CallExpr)
315                         // Find the callee function from the call site and add the edge.
316                         callee := DirectCallee(call.Fun)
317                         if callee != nil {
318                                 addIREdge(callernode, name, n, callee, namedEdgeMap, g)
319                         }
320                 case ir.OCALLMETH:
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)
325                 }
326         })
327 }
328
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
335 }
336
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]
342         if !ok {
343                 calleeNode = &IRNode{
344                         AST: callee,
345                 }
346                 g.IRNodes[calleeName] = calleeNode
347         }
348
349         namedEdge := NamedCallEdge{
350                 CallerName:     callerName,
351                 CalleeName:     calleeName,
352                 CallSiteOffset: NodeLineOffset(call, callerNode.AST),
353         }
354
355         // Add edge in the IRGraph from caller to callee.
356         edge := &IREdge{
357                 Src:            callerNode,
358                 Dst:            calleeNode,
359                 Weight:         namedEdgeMap.Weight[namedEdge],
360                 CallSiteOffset: namedEdge.CallSiteOffset,
361         }
362
363         if callerNode.OutEdges == nil {
364                 callerNode.OutEdges = make(map[NamedCallEdge]*IREdge)
365         }
366         callerNode.OutEdges[namedEdge] = edge
367 }
368
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")
373         panic("unreachable")
374 }
375
376 // addIndirectEdges adds indirect call edges found in the profile to the graph,
377 // to be used for devirtualization.
378 //
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).
383 //
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 {
394                 localNodes[k] = v
395         }
396
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
400         // reproducibility.
401         //
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]
411                 if !ok {
412                         continue
413                 }
414
415                 // Already handled this edge?
416                 if _, ok := callerNode.OutEdges[key]; ok {
417                         continue
418                 }
419
420                 calleeNode, ok := g.IRNodes[key.CalleeName]
421                 if !ok {
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.
427                         //
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
431                         // not supported.
432                         //
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
439                         // site, if at all.
440                         fn, err := LookupMethodFunc(key.CalleeName)
441                         if err == nil {
442                                 if base.Debug.PGODebug >= 3 {
443                                         fmt.Printf("addIndirectEdges: %s found in export data\n", key.CalleeName)
444                                 }
445                                 calleeNode = &IRNode{AST: fn}
446
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
458                                 // call.
459                         } else {
460                                 // Still not found. Most likely this is because
461                                 // the callee isn't in the transitive deps of
462                                 // this package.
463                                 //
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)
469                                 }
470                                 calleeNode = &IRNode{LinkerSymbolName: key.CalleeName}
471                         }
472
473                         // Add dummy node back to IRNodes. We don't need this
474                         // directly, but PrintWeightedCallGraphDOT uses these
475                         // to print nodes.
476                         g.IRNodes[key.CalleeName] = calleeNode
477                 }
478                 edge := &IREdge{
479                         Src:            callerNode,
480                         Dst:            calleeNode,
481                         Weight:         weight,
482                         CallSiteOffset: key.CallSiteOffset,
483                 }
484
485                 if callerNode.OutEdges == nil {
486                         callerNode.OutEdges = make(map[NamedCallEdge]*IREdge)
487                 }
488                 callerNode.OutEdges[key] = edge
489         }
490 }
491
492 // WeightInPercentage converts profile weights to a percentage.
493 func WeightInPercentage(value int64, total int64) float64 {
494         return (float64(value) / float64(total)) * 100
495 }
496
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")
501
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{}{}
508                 }
509         })
510
511         // Determine nodes of DOT.
512         //
513         // Note that ir.Func may be nil for functions not visible from this
514         // package.
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
521                                 }
522                                 if _, ok := nodes[e.Dst.Name()]; !ok {
523                                         nodes[e.Dst.Name()] = e.Dst.AST
524                                 }
525                         }
526                         if _, ok := nodes[n.Name()]; !ok {
527                                 nodes[n.Name()] = n.AST
528                         }
529                 }
530         }
531
532         // Print nodes.
533         for name, ast := range nodes {
534                 if _, ok := p.WeightedCG.IRNodes[name]; ok {
535                         style := "solid"
536                         if ast == nil {
537                                 style = "dashed"
538                         }
539
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)
542                         } else {
543                                 fmt.Printf("\"%v\" [color=black, style=%s, label=\"%v\"];\n", name, style, name)
544                         }
545                 }
546         }
547         // Print edges.
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 {
553                                         style := "solid"
554                                         if e.Dst.AST == nil {
555                                                 style = "dashed"
556                                         }
557                                         color := "black"
558                                         edgepercent := WeightInPercentage(e.Weight, p.TotalWeight)
559                                         if edgepercent > edgeThreshold {
560                                                 color = "red"
561                                         }
562
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)
565                                 }
566                         }
567                 }
568         })
569         fmt.Printf("}\n")
570 }
571
572 // DirectCallee takes a function-typed expression and returns the underlying
573 // function that it refers to if statically known. Otherwise, it returns nil.
574 //
575 // Equivalent to inline.inlCallee without calling CanInline on closures.
576 func DirectCallee(fn ir.Node) *ir.Func {
577         fn = ir.StaticValue(fn)
578         switch fn.Op() {
579         case ir.OMETHEXPR:
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()) {
586                         return nil
587                 }
588                 return n.Func
589         case ir.ONAME:
590                 fn := fn.(*ir.Name)
591                 if fn.Class == ir.PFUNC {
592                         return fn.Func
593                 }
594         case ir.OCLOSURE:
595                 fn := fn.(*ir.ClosureExpr)
596                 c := fn.Func
597                 return c
598         }
599         return nil
600 }