]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/pgo/irgraph.go
cmd/compile: report profile open/parse errors
[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 // WORK IN PROGRESS
6
7 // A note on line numbers: when working with line numbers, we always use the
8 // binary-visible relative line number. i.e., the line number as adjusted by
9 // //line directives (ctxt.InnermostPos(ir.Node.Pos()).RelLine()). Use
10 // NodeLineOffset to compute line offsets.
11 //
12 // If you are thinking, "wait, doesn't that just make things more complex than
13 // using the real line number?", then you are 100% correct. Unfortunately,
14 // pprof profiles generated by the runtime always contain line numbers as
15 // adjusted by //line directives (because that is what we put in pclntab). Thus
16 // for the best behavior when attempting to match the source with the profile
17 // it makes sense to use the same line number space.
18 //
19 // Some of the effects of this to keep in mind:
20 //
21 //  - For files without //line directives there is no impact, as RelLine() ==
22 //    Line().
23 //  - For functions entirely covered by the same //line directive (i.e., a
24 //    directive before the function definition and no directives within the
25 //    function), there should also be no impact, as line offsets within the
26 //    function should be the same as the real line offsets.
27 //  - Functions containing //line directives may be impacted. As fake line
28 //    numbers need not be monotonic, we may compute negative line offsets. We
29 //    should accept these and attempt to use them for best-effort matching, as
30 //    these offsets should still match if the source is unchanged, and may
31 //    continue to match with changed source depending on the impact of the
32 //    changes on fake line numbers.
33 //  - Functions containing //line directives may also contain duplicate lines,
34 //    making it ambiguous which call the profile is referencing. This is a
35 //    similar problem to multiple calls on a single real line, as we don't
36 //    currently track column numbers.
37 //
38 // Long term it would be best to extend pprof profiles to include real line
39 // numbers. Until then, we have to live with these complexities. Luckily,
40 // //line directives that change line numbers in strange ways should be rare,
41 // and failing PGO matching on these files is not too big of a loss.
42
43 package pgo
44
45 import (
46         "cmd/compile/internal/base"
47         "cmd/compile/internal/ir"
48         "cmd/compile/internal/typecheck"
49         "cmd/compile/internal/types"
50         "fmt"
51         "internal/profile"
52         "os"
53 )
54
55 // IRGraph is the key data structure that is built from profile. It is
56 // essentially a call graph with nodes pointing to IRs of functions and edges
57 // carrying weights and callsite information. The graph is bidirectional that
58 // helps in removing nodes efficiently.
59 type IRGraph struct {
60         // Nodes of the graph
61         IRNodes  map[string]*IRNode
62         OutEdges IREdgeMap
63         InEdges  IREdgeMap
64 }
65
66 // IRNode represents a node in the IRGraph.
67 type IRNode struct {
68         // Pointer to the IR of the Function represented by this node.
69         AST *ir.Func
70         // Flat weight of the IRNode, obtained from profile.
71         Flat int64
72         // Cumulative weight of the IRNode.
73         Cum int64
74 }
75
76 // IREdgeMap maps an IRNode to its successors.
77 type IREdgeMap map[*IRNode][]*IREdge
78
79 // IREdge represents a call edge in the IRGraph with source, destination,
80 // weight, callsite, and line number information.
81 type IREdge struct {
82         // Source and destination of the edge in IRNode.
83         Src, Dst       *IRNode
84         Weight         int64
85         CallSiteOffset int // Line offset from function start line.
86 }
87
88 // NodeMapKey represents a hash key to identify unique call-edges in profile
89 // and in IR. Used for deduplication of call edges found in profile.
90 type NodeMapKey struct {
91         CallerName     string
92         CalleeName     string
93         CallSiteOffset int // Line offset from function start line.
94 }
95
96 // Weights capture both node weight and edge weight.
97 type Weights struct {
98         NFlat   int64
99         NCum    int64
100         EWeight int64
101 }
102
103 // CallSiteInfo captures call-site information and its caller/callee.
104 type CallSiteInfo struct {
105         LineOffset int // Line offset from function start line.
106         Caller     *ir.Func
107         Callee     *ir.Func
108 }
109
110 // Profile contains the processed PGO profile and weighted call graph used for
111 // PGO optimizations.
112 type Profile struct {
113         // Aggregated NodeWeights and EdgeWeights across the profile. This
114         // helps us determine the percentage threshold for hot/cold
115         // partitioning.
116         TotalNodeWeight int64
117         TotalEdgeWeight int64
118
119         // NodeMap contains all unique call-edges in the profile and their
120         // aggregated weight.
121         NodeMap map[NodeMapKey]*Weights
122
123         // WeightedCG represents the IRGraph built from profile, which we will
124         // update as part of inlining.
125         WeightedCG *IRGraph
126 }
127
128 // New generates a profile-graph from the profile.
129 func New(profileFile string) (*Profile, error) {
130         f, err := os.Open(profileFile)
131         if err != nil {
132                 return nil, fmt.Errorf("error opening profile: %w", err)
133         }
134         defer f.Close()
135         profile, err := profile.Parse(f)
136         if err != nil {
137                 return nil, fmt.Errorf("error parsing profile: %w", err)
138         }
139
140         if len(profile.Sample) == 0 {
141                 // We accept empty profiles, but there is nothing to do.
142                 return nil, nil
143         }
144
145         valueIndex := -1
146         for i, s := range profile.SampleType {
147                 // Samples count is the raw data collected, and CPU nanoseconds is just
148                 // a scaled version of it, so either one we can find is fine.
149                 if (s.Type == "samples" && s.Unit == "count") ||
150                         (s.Type == "cpu" && s.Unit == "nanoseconds") {
151                         valueIndex = i
152                         break
153                 }
154         }
155
156         if valueIndex == -1 {
157                 return nil, fmt.Errorf(`profile does not contain a sample index with value/type "samples/count" or cpu/nanoseconds"`)
158         }
159
160         g := newGraph(profile, &Options{
161                 CallTree:    false,
162                 SampleValue: func(v []int64) int64 { return v[valueIndex] },
163         })
164
165         p := &Profile{
166                 NodeMap: make(map[NodeMapKey]*Weights),
167                 WeightedCG: &IRGraph{
168                         IRNodes: make(map[string]*IRNode),
169                 },
170         }
171
172         // Build the node map and totals from the profile graph.
173         if err := p.processprofileGraph(g); err != nil {
174                 return nil, err
175         }
176
177         if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0 {
178                 return nil, nil // accept but ignore profile with no samples.
179         }
180
181         // Create package-level call graph with weights from profile and IR.
182         p.initializeIRGraph()
183
184         return p, nil
185 }
186
187 // processprofileGraph builds various maps from the profile-graph.
188 //
189 // It initializes NodeMap and Total{Node,Edge}Weight based on the name and
190 // callsite to compute node and edge weights which will be used later on to
191 // create edges for WeightedCG.
192 //
193 // Caller should ignore the profile if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0.
194 func (p *Profile) processprofileGraph(g *Graph) error {
195         nFlat := make(map[string]int64)
196         nCum := make(map[string]int64)
197         seenStartLine := false
198
199         // Accummulate weights for the same node.
200         for _, n := range g.Nodes {
201                 canonicalName := n.Info.Name
202                 nFlat[canonicalName] += n.FlatValue()
203                 nCum[canonicalName] += n.CumValue()
204         }
205
206         // Process graph and build various node and edge maps which will
207         // be consumed by AST walk.
208         for _, n := range g.Nodes {
209                 seenStartLine = seenStartLine || n.Info.StartLine != 0
210
211                 p.TotalNodeWeight += n.FlatValue()
212                 canonicalName := n.Info.Name
213                 // Create the key to the nodeMapKey.
214                 nodeinfo := NodeMapKey{
215                         CallerName:     canonicalName,
216                         CallSiteOffset: n.Info.Lineno - n.Info.StartLine,
217                 }
218
219                 for _, e := range n.Out {
220                         p.TotalEdgeWeight += e.WeightValue()
221                         nodeinfo.CalleeName = e.Dest.Info.Name
222                         if w, ok := p.NodeMap[nodeinfo]; ok {
223                                 w.EWeight += e.WeightValue()
224                         } else {
225                                 weights := new(Weights)
226                                 weights.NFlat = nFlat[canonicalName]
227                                 weights.NCum = nCum[canonicalName]
228                                 weights.EWeight = e.WeightValue()
229                                 p.NodeMap[nodeinfo] = weights
230                         }
231                 }
232         }
233
234         if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0 {
235                 return nil // accept but ignore profile with no samples.
236         }
237
238         if !seenStartLine {
239                 // TODO(prattmic): If Function.start_line is missing we could
240                 // fall back to using absolute line numbers, which is better
241                 // than nothing.
242                 return fmt.Errorf("profile missing Function.start_line data (Go version of profiled application too old? Go 1.20+ automatically adds this to profiles)")
243         }
244
245         return nil
246 }
247
248 // initializeIRGraph builds the IRGraph by visiting all the ir.Func in decl list
249 // of a package.
250 func (p *Profile) initializeIRGraph() {
251         // Bottomup walk over the function to create IRGraph.
252         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
253                 for _, n := range list {
254                         p.VisitIR(n)
255                 }
256         })
257 }
258
259 // VisitIR traverses the body of each ir.Func and use NodeMap to determine if
260 // we need to add an edge from ir.Func and any node in the ir.Func body.
261 func (p *Profile) VisitIR(fn *ir.Func) {
262         g := p.WeightedCG
263
264         if g.IRNodes == nil {
265                 g.IRNodes = make(map[string]*IRNode)
266         }
267         if g.OutEdges == nil {
268                 g.OutEdges = make(map[*IRNode][]*IREdge)
269         }
270         if g.InEdges == nil {
271                 g.InEdges = make(map[*IRNode][]*IREdge)
272         }
273         name := ir.PkgFuncName(fn)
274         node := new(IRNode)
275         node.AST = fn
276         if g.IRNodes[name] == nil {
277                 g.IRNodes[name] = node
278         }
279         // Create the key for the NodeMapKey.
280         nodeinfo := NodeMapKey{
281                 CallerName:     name,
282                 CalleeName:     "",
283                 CallSiteOffset: 0,
284         }
285         // If the node exists, then update its node weight.
286         if weights, ok := p.NodeMap[nodeinfo]; ok {
287                 g.IRNodes[name].Flat = weights.NFlat
288                 g.IRNodes[name].Cum = weights.NCum
289         }
290
291         // Recursively walk over the body of the function to create IRGraph edges.
292         p.createIRGraphEdge(fn, g.IRNodes[name], name)
293 }
294
295 // NodeLineOffset returns the line offset of n in fn.
296 func NodeLineOffset(n ir.Node, fn *ir.Func) int {
297         // See "A note on line numbers" at the top of the file.
298         line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
299         startLine := int(base.Ctxt.InnermostPos(fn.Pos()).RelLine())
300         return line - startLine
301 }
302
303 // addIREdge adds an edge between caller and new node that points to `callee`
304 // based on the profile-graph and NodeMap.
305 func (p *Profile) addIREdge(caller *IRNode, callername string, call ir.Node, callee *ir.Func) {
306         g := p.WeightedCG
307
308         // Create an IRNode for the callee.
309         calleenode := new(IRNode)
310         calleenode.AST = callee
311         calleename := ir.PkgFuncName(callee)
312
313         // Create key for NodeMapKey.
314         nodeinfo := NodeMapKey{
315                 CallerName:     callername,
316                 CalleeName:     calleename,
317                 CallSiteOffset: NodeLineOffset(call, caller.AST),
318         }
319
320         // Create the callee node with node weight.
321         if g.IRNodes[calleename] == nil {
322                 g.IRNodes[calleename] = calleenode
323                 nodeinfo2 := NodeMapKey{
324                         CallerName:     calleename,
325                         CalleeName:     "",
326                         CallSiteOffset: 0,
327                 }
328                 if weights, ok := p.NodeMap[nodeinfo2]; ok {
329                         g.IRNodes[calleename].Flat = weights.NFlat
330                         g.IRNodes[calleename].Cum = weights.NCum
331                 }
332         }
333
334         if weights, ok := p.NodeMap[nodeinfo]; ok {
335                 caller.Flat = weights.NFlat
336                 caller.Cum = weights.NCum
337
338                 // Add edge in the IRGraph from caller to callee.
339                 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: weights.EWeight, CallSiteOffset: nodeinfo.CallSiteOffset}
340                 g.OutEdges[caller] = append(g.OutEdges[caller], info)
341                 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
342         } else {
343                 nodeinfo.CalleeName = ""
344                 nodeinfo.CallSiteOffset = 0
345                 if weights, ok := p.NodeMap[nodeinfo]; ok {
346                         caller.Flat = weights.NFlat
347                         caller.Cum = weights.NCum
348                         info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSiteOffset: nodeinfo.CallSiteOffset}
349                         g.OutEdges[caller] = append(g.OutEdges[caller], info)
350                         g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
351                 } else {
352                         info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSiteOffset: nodeinfo.CallSiteOffset}
353                         g.OutEdges[caller] = append(g.OutEdges[caller], info)
354                         g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
355                 }
356         }
357 }
358
359 // createIRGraphEdge traverses the nodes in the body of ir.Func and add edges between callernode which points to the ir.Func and the nodes in the body.
360 func (p *Profile) createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string) {
361         var doNode func(ir.Node) bool
362         doNode = func(n ir.Node) bool {
363                 switch n.Op() {
364                 default:
365                         ir.DoChildren(n, doNode)
366                 case ir.OCALLFUNC:
367                         call := n.(*ir.CallExpr)
368                         // Find the callee function from the call site and add the edge.
369                         callee := inlCallee(call.X)
370                         if callee != nil {
371                                 p.addIREdge(callernode, name, n, callee)
372                         }
373                 case ir.OCALLMETH:
374                         call := n.(*ir.CallExpr)
375                         // Find the callee method from the call site and add the edge.
376                         callee := ir.MethodExprName(call.X).Func
377                         p.addIREdge(callernode, name, n, callee)
378                 }
379                 return false
380         }
381         doNode(fn)
382 }
383
384 // WeightInPercentage converts profile weights to a percentage.
385 func WeightInPercentage(value int64, total int64) float64 {
386         return (float64(value) / float64(total)) * 100
387 }
388
389 // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
390 func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
391         fmt.Printf("\ndigraph G {\n")
392         fmt.Printf("forcelabels=true;\n")
393
394         // List of functions in this package.
395         funcs := make(map[string]struct{})
396         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
397                 for _, f := range list {
398                         name := ir.PkgFuncName(f)
399                         funcs[name] = struct{}{}
400                 }
401         })
402
403         // Determine nodes of DOT.
404         nodes := make(map[string]*ir.Func)
405         for name := range funcs {
406                 if n, ok := p.WeightedCG.IRNodes[name]; ok {
407                         for _, e := range p.WeightedCG.OutEdges[n] {
408                                 if _, ok := nodes[ir.PkgFuncName(e.Src.AST)]; !ok {
409                                         nodes[ir.PkgFuncName(e.Src.AST)] = e.Src.AST
410                                 }
411                                 if _, ok := nodes[ir.PkgFuncName(e.Dst.AST)]; !ok {
412                                         nodes[ir.PkgFuncName(e.Dst.AST)] = e.Dst.AST
413                                 }
414                         }
415                         if _, ok := nodes[ir.PkgFuncName(n.AST)]; !ok {
416                                 nodes[ir.PkgFuncName(n.AST)] = n.AST
417                         }
418                 }
419         }
420
421         // Print nodes.
422         for name, ast := range nodes {
423                 if n, ok := p.WeightedCG.IRNodes[name]; ok {
424                         nodeweight := WeightInPercentage(n.Flat, p.TotalNodeWeight)
425                         color := "black"
426                         if ast.Inl != nil {
427                                 fmt.Printf("\"%v\" [color=%v,label=\"%v,freq=%.2f,inl_cost=%d\"];\n", ir.PkgFuncName(ast), color, ir.PkgFuncName(ast), nodeweight, ast.Inl.Cost)
428                         } else {
429                                 fmt.Printf("\"%v\" [color=%v, label=\"%v,freq=%.2f\"];\n", ir.PkgFuncName(ast), color, ir.PkgFuncName(ast), nodeweight)
430                         }
431                 }
432         }
433         // Print edges.
434         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
435                 for _, f := range list {
436                         name := ir.PkgFuncName(f)
437                         if n, ok := p.WeightedCG.IRNodes[name]; ok {
438                                 for _, e := range p.WeightedCG.OutEdges[n] {
439                                         edgepercent := WeightInPercentage(e.Weight, p.TotalEdgeWeight)
440                                         if edgepercent > edgeThreshold {
441                                                 fmt.Printf("edge [color=red, style=solid];\n")
442                                         } else {
443                                                 fmt.Printf("edge [color=black, style=solid];\n")
444                                         }
445
446                                         fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", ir.PkgFuncName(n.AST), ir.PkgFuncName(e.Dst.AST), edgepercent)
447                                 }
448                         }
449                 }
450         })
451         fmt.Printf("}\n")
452 }
453
454 // RedirectEdges deletes and redirects out-edges from node cur based on
455 // inlining information via inlinedCallSites.
456 //
457 // CallSiteInfo.Callee must be nil.
458 func (p *Profile) RedirectEdges(cur *IRNode, inlinedCallSites map[CallSiteInfo]struct{}) {
459         g := p.WeightedCG
460
461         i := 0
462         outs := g.OutEdges[cur]
463         for i < len(outs) {
464                 outEdge := outs[i]
465                 redirected := false
466                 _, found := inlinedCallSites[CallSiteInfo{LineOffset: outEdge.CallSiteOffset, Caller: cur.AST}]
467                 if !found {
468                         for _, InEdge := range g.InEdges[cur] {
469                                 if _, ok := inlinedCallSites[CallSiteInfo{LineOffset: InEdge.CallSiteOffset, Caller: InEdge.Src.AST}]; ok {
470                                         weight := g.calculateWeight(InEdge.Src, cur)
471                                         g.redirectEdge(InEdge.Src, outEdge, weight)
472                                         redirected = true
473                                 }
474                         }
475                 }
476                 if found || redirected {
477                         g.remove(cur, i)
478                         outs = g.OutEdges[cur]
479                         continue
480                 }
481                 i++
482         }
483 }
484
485 // redirectEdge redirects a node's out-edge to one of its parent nodes, cloning is
486 // required as the node might be inlined in multiple call-sites.
487 // TODO: adjust the in-edges of outEdge.Dst if necessary
488 func (g *IRGraph) redirectEdge(parent *IRNode, outEdge *IREdge, weight int64) {
489         edge := &IREdge{Src: parent, Dst: outEdge.Dst, Weight: weight * outEdge.Weight, CallSiteOffset: outEdge.CallSiteOffset}
490         g.OutEdges[parent] = append(g.OutEdges[parent], edge)
491 }
492
493 // remove deletes the cur-node's out-edges at index idx.
494 func (g *IRGraph) remove(cur *IRNode, i int) {
495         if len(g.OutEdges[cur]) >= 2 {
496                 g.OutEdges[cur][i] = g.OutEdges[cur][len(g.OutEdges[cur])-1]
497                 g.OutEdges[cur] = g.OutEdges[cur][:len(g.OutEdges[cur])-1]
498         } else {
499                 delete(g.OutEdges, cur)
500         }
501 }
502
503 // calculateWeight calculates the weight of the new redirected edge.
504 func (g *IRGraph) calculateWeight(parent *IRNode, cur *IRNode) int64 {
505         sum := int64(0)
506         pw := int64(0)
507         for _, InEdge := range g.InEdges[cur] {
508                 sum += InEdge.Weight
509                 if InEdge.Src == parent {
510                         pw = InEdge.Weight
511                 }
512         }
513         weight := int64(0)
514         if sum != 0 {
515                 weight = pw / sum
516         } else {
517                 weight = pw
518         }
519         return weight
520 }
521
522 // inlCallee is same as the implementation for inl.go with one change. The change is that we do not invoke CanInline on a closure.
523 func inlCallee(fn ir.Node) *ir.Func {
524         fn = ir.StaticValue(fn)
525         switch fn.Op() {
526         case ir.OMETHEXPR:
527                 fn := fn.(*ir.SelectorExpr)
528                 n := ir.MethodExprName(fn)
529                 // Check that receiver type matches fn.X.
530                 // TODO(mdempsky): Handle implicit dereference
531                 // of pointer receiver argument?
532                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
533                         return nil
534                 }
535                 return n.Func
536         case ir.ONAME:
537                 fn := fn.(*ir.Name)
538                 if fn.Class == ir.PFUNC {
539                         return fn.Func
540                 }
541         case ir.OCLOSURE:
542                 fn := fn.(*ir.ClosureExpr)
543                 c := fn.Func
544                 return c
545         }
546         return nil
547 }