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"
54 // IRGraph is the key data structure that is built from profile. It is
55 // essentially a call graph with nodes pointing to IRs of functions and edges
56 // carrying weights and callsite information. The graph is bidirectional that
57 // helps in removing nodes efficiently.
60 IRNodes map[string]*IRNode
65 // IRNode represents a node in the IRGraph.
67 // Pointer to the IR of the Function represented by this node.
69 // Flat weight of the IRNode, obtained from profile.
71 // Cumulative weight of the IRNode.
75 // IREdgeMap maps an IRNode to its successors.
76 type IREdgeMap map[*IRNode][]*IREdge
78 // IREdge represents a call edge in the IRGraph with source, destination,
79 // weight, callsite, and line number information.
81 // Source and destination of the edge in IRNode.
84 CallSiteOffset int // Line offset from function start line.
87 // NodeMapKey represents a hash key to identify unique call-edges in profile
88 // and in IR. Used for deduplication of call edges found in profile.
89 type NodeMapKey struct {
92 CallSiteOffset int // Line offset from function start line.
95 // Weights capture both node weight and edge weight.
102 // CallSiteInfo captures call-site information and its caller/callee.
103 type CallSiteInfo struct {
104 LineOffset int // Line offset from function start line.
109 // Profile contains the processed PGO profile and weighted call graph used for
110 // PGO optimizations.
111 type Profile struct {
112 // Aggregated NodeWeights and EdgeWeights across the profile. This
113 // helps us determine the percentage threshold for hot/cold
115 TotalNodeWeight int64
116 TotalEdgeWeight int64
118 // NodeMap contains all unique call-edges in the profile and their
119 // aggregated weight.
120 NodeMap map[NodeMapKey]*Weights
122 // WeightedCG represents the IRGraph built from profile, which we will
123 // update as part of inlining.
127 // New generates a profile-graph from the profile.
128 func New(profileFile string) (*Profile, error) {
129 f, err := os.Open(profileFile)
131 return nil, fmt.Errorf("error opening profile: %w", err)
134 profile, err := profile.Parse(f)
136 return nil, fmt.Errorf("error parsing profile: %w", err)
139 if len(profile.Sample) == 0 {
140 // We accept empty profiles, but there is nothing to do.
145 for i, s := range profile.SampleType {
146 // Samples count is the raw data collected, and CPU nanoseconds is just
147 // a scaled version of it, so either one we can find is fine.
148 if (s.Type == "samples" && s.Unit == "count") ||
149 (s.Type == "cpu" && s.Unit == "nanoseconds") {
155 if valueIndex == -1 {
156 return nil, fmt.Errorf(`profile does not contain a sample index with value/type "samples/count" or cpu/nanoseconds"`)
159 g := graph.NewGraph(profile, &graph.Options{
160 SampleValue: func(v []int64) int64 { return v[valueIndex] },
164 NodeMap: make(map[NodeMapKey]*Weights),
165 WeightedCG: &IRGraph{
166 IRNodes: make(map[string]*IRNode),
170 // Build the node map and totals from the profile graph.
171 if err := p.processprofileGraph(g); err != nil {
175 if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0 {
176 return nil, nil // accept but ignore profile with no samples.
179 // Create package-level call graph with weights from profile and IR.
180 p.initializeIRGraph()
185 // processprofileGraph builds various maps from the profile-graph.
187 // It initializes NodeMap and Total{Node,Edge}Weight based on the name and
188 // callsite to compute node and edge weights which will be used later on to
189 // create edges for WeightedCG.
191 // Caller should ignore the profile if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0.
192 func (p *Profile) processprofileGraph(g *graph.Graph) error {
193 nFlat := make(map[string]int64)
194 nCum := make(map[string]int64)
195 seenStartLine := false
197 // Accummulate weights for the same node.
198 for _, n := range g.Nodes {
199 canonicalName := n.Info.Name
200 nFlat[canonicalName] += n.FlatValue()
201 nCum[canonicalName] += n.CumValue()
204 // Process graph and build various node and edge maps which will
205 // be consumed by AST walk.
206 for _, n := range g.Nodes {
207 seenStartLine = seenStartLine || n.Info.StartLine != 0
209 p.TotalNodeWeight += n.FlatValue()
210 canonicalName := n.Info.Name
211 // Create the key to the nodeMapKey.
212 nodeinfo := NodeMapKey{
213 CallerName: canonicalName,
214 CallSiteOffset: n.Info.Lineno - n.Info.StartLine,
217 for _, e := range n.Out {
218 p.TotalEdgeWeight += e.WeightValue()
219 nodeinfo.CalleeName = e.Dest.Info.Name
220 if w, ok := p.NodeMap[nodeinfo]; ok {
221 w.EWeight += e.WeightValue()
223 weights := new(Weights)
224 weights.NFlat = nFlat[canonicalName]
225 weights.NCum = nCum[canonicalName]
226 weights.EWeight = e.WeightValue()
227 p.NodeMap[nodeinfo] = weights
232 if p.TotalNodeWeight == 0 || p.TotalEdgeWeight == 0 {
233 return nil // accept but ignore profile with no samples.
237 // TODO(prattmic): If Function.start_line is missing we could
238 // fall back to using absolute line numbers, which is better
240 return fmt.Errorf("profile missing Function.start_line data (Go version of profiled application too old? Go 1.20+ automatically adds this to profiles)")
246 // initializeIRGraph builds the IRGraph by visiting all the ir.Func in decl list
248 func (p *Profile) initializeIRGraph() {
249 // Bottomup walk over the function to create IRGraph.
250 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
251 for _, n := range list {
257 // VisitIR traverses the body of each ir.Func and use NodeMap to determine if
258 // we need to add an edge from ir.Func and any node in the ir.Func body.
259 func (p *Profile) VisitIR(fn *ir.Func) {
262 if g.IRNodes == nil {
263 g.IRNodes = make(map[string]*IRNode)
265 if g.OutEdges == nil {
266 g.OutEdges = make(map[*IRNode][]*IREdge)
268 if g.InEdges == nil {
269 g.InEdges = make(map[*IRNode][]*IREdge)
271 name := ir.LinkFuncName(fn)
274 if g.IRNodes[name] == nil {
275 g.IRNodes[name] = node
277 // Create the key for the NodeMapKey.
278 nodeinfo := NodeMapKey{
283 // If the node exists, then update its node weight.
284 if weights, ok := p.NodeMap[nodeinfo]; ok {
285 g.IRNodes[name].Flat = weights.NFlat
286 g.IRNodes[name].Cum = weights.NCum
289 // Recursively walk over the body of the function to create IRGraph edges.
290 p.createIRGraphEdge(fn, g.IRNodes[name], name)
293 // NodeLineOffset returns the line offset of n in fn.
294 func NodeLineOffset(n ir.Node, fn *ir.Func) int {
295 // See "A note on line numbers" at the top of the file.
296 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
297 startLine := int(base.Ctxt.InnermostPos(fn.Pos()).RelLine())
298 return line - startLine
301 // addIREdge adds an edge between caller and new node that points to `callee`
302 // based on the profile-graph and NodeMap.
303 func (p *Profile) addIREdge(caller *IRNode, callername string, call ir.Node, callee *ir.Func) {
306 // Create an IRNode for the callee.
307 calleenode := new(IRNode)
308 calleenode.AST = callee
309 calleename := ir.LinkFuncName(callee)
311 // Create key for NodeMapKey.
312 nodeinfo := NodeMapKey{
313 CallerName: callername,
314 CalleeName: calleename,
315 CallSiteOffset: NodeLineOffset(call, caller.AST),
318 // Create the callee node with node weight.
319 if g.IRNodes[calleename] == nil {
320 g.IRNodes[calleename] = calleenode
321 nodeinfo2 := NodeMapKey{
322 CallerName: calleename,
326 if weights, ok := p.NodeMap[nodeinfo2]; ok {
327 g.IRNodes[calleename].Flat = weights.NFlat
328 g.IRNodes[calleename].Cum = weights.NCum
332 if weights, ok := p.NodeMap[nodeinfo]; ok {
333 caller.Flat = weights.NFlat
334 caller.Cum = weights.NCum
336 // Add edge in the IRGraph from caller to callee.
337 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: weights.EWeight, CallSiteOffset: nodeinfo.CallSiteOffset}
338 g.OutEdges[caller] = append(g.OutEdges[caller], info)
339 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
341 nodeinfo.CalleeName = ""
342 nodeinfo.CallSiteOffset = 0
343 if weights, ok := p.NodeMap[nodeinfo]; ok {
344 caller.Flat = weights.NFlat
345 caller.Cum = weights.NCum
346 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSiteOffset: nodeinfo.CallSiteOffset}
347 g.OutEdges[caller] = append(g.OutEdges[caller], info)
348 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
350 info := &IREdge{Src: caller, Dst: g.IRNodes[calleename], Weight: 0, CallSiteOffset: nodeinfo.CallSiteOffset}
351 g.OutEdges[caller] = append(g.OutEdges[caller], info)
352 g.InEdges[g.IRNodes[calleename]] = append(g.InEdges[g.IRNodes[calleename]], info)
357 // 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.
358 func (p *Profile) createIRGraphEdge(fn *ir.Func, callernode *IRNode, name string) {
359 var doNode func(ir.Node) bool
360 doNode = func(n ir.Node) bool {
363 ir.DoChildren(n, doNode)
365 call := n.(*ir.CallExpr)
366 // Find the callee function from the call site and add the edge.
367 callee := inlCallee(call.X)
369 p.addIREdge(callernode, name, n, callee)
372 call := n.(*ir.CallExpr)
373 // Find the callee method from the call site and add the edge.
374 callee := ir.MethodExprName(call.X).Func
375 p.addIREdge(callernode, name, n, callee)
382 // WeightInPercentage converts profile weights to a percentage.
383 func WeightInPercentage(value int64, total int64) float64 {
384 return (float64(value) / float64(total)) * 100
387 // PrintWeightedCallGraphDOT prints IRGraph in DOT format.
388 func (p *Profile) PrintWeightedCallGraphDOT(edgeThreshold float64) {
389 fmt.Printf("\ndigraph G {\n")
390 fmt.Printf("forcelabels=true;\n")
392 // List of functions in this package.
393 funcs := make(map[string]struct{})
394 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
395 for _, f := range list {
396 name := ir.LinkFuncName(f)
397 funcs[name] = struct{}{}
401 // Determine nodes of DOT.
402 nodes := make(map[string]*ir.Func)
403 for name := range funcs {
404 if n, ok := p.WeightedCG.IRNodes[name]; ok {
405 for _, e := range p.WeightedCG.OutEdges[n] {
406 if _, ok := nodes[ir.LinkFuncName(e.Src.AST)]; !ok {
407 nodes[ir.LinkFuncName(e.Src.AST)] = e.Src.AST
409 if _, ok := nodes[ir.LinkFuncName(e.Dst.AST)]; !ok {
410 nodes[ir.LinkFuncName(e.Dst.AST)] = e.Dst.AST
413 if _, ok := nodes[ir.LinkFuncName(n.AST)]; !ok {
414 nodes[ir.LinkFuncName(n.AST)] = n.AST
420 for name, ast := range nodes {
421 if n, ok := p.WeightedCG.IRNodes[name]; ok {
422 nodeweight := WeightInPercentage(n.Flat, p.TotalNodeWeight)
425 fmt.Printf("\"%v\" [color=%v,label=\"%v,freq=%.2f,inl_cost=%d\"];\n", ir.LinkFuncName(ast), color, ir.LinkFuncName(ast), nodeweight, ast.Inl.Cost)
427 fmt.Printf("\"%v\" [color=%v, label=\"%v,freq=%.2f\"];\n", ir.LinkFuncName(ast), color, ir.LinkFuncName(ast), nodeweight)
432 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
433 for _, f := range list {
434 name := ir.LinkFuncName(f)
435 if n, ok := p.WeightedCG.IRNodes[name]; ok {
436 for _, e := range p.WeightedCG.OutEdges[n] {
437 edgepercent := WeightInPercentage(e.Weight, p.TotalEdgeWeight)
438 if edgepercent > edgeThreshold {
439 fmt.Printf("edge [color=red, style=solid];\n")
441 fmt.Printf("edge [color=black, style=solid];\n")
444 fmt.Printf("\"%v\" -> \"%v\" [label=\"%.2f\"];\n", ir.LinkFuncName(n.AST), ir.LinkFuncName(e.Dst.AST), edgepercent)
452 // RedirectEdges deletes and redirects out-edges from node cur based on
453 // inlining information via inlinedCallSites.
455 // CallSiteInfo.Callee must be nil.
456 func (p *Profile) RedirectEdges(cur *IRNode, inlinedCallSites map[CallSiteInfo]struct{}) {
460 outs := g.OutEdges[cur]
464 _, found := inlinedCallSites[CallSiteInfo{LineOffset: outEdge.CallSiteOffset, Caller: cur.AST}]
466 for _, InEdge := range g.InEdges[cur] {
467 if _, ok := inlinedCallSites[CallSiteInfo{LineOffset: InEdge.CallSiteOffset, Caller: InEdge.Src.AST}]; ok {
468 weight := g.calculateWeight(InEdge.Src, cur)
469 g.redirectEdge(InEdge.Src, outEdge, weight)
474 if found || redirected {
476 outs = g.OutEdges[cur]
483 // redirectEdge redirects a node's out-edge to one of its parent nodes, cloning is
484 // required as the node might be inlined in multiple call-sites.
485 // TODO: adjust the in-edges of outEdge.Dst if necessary
486 func (g *IRGraph) redirectEdge(parent *IRNode, outEdge *IREdge, weight int64) {
487 edge := &IREdge{Src: parent, Dst: outEdge.Dst, Weight: weight * outEdge.Weight, CallSiteOffset: outEdge.CallSiteOffset}
488 g.OutEdges[parent] = append(g.OutEdges[parent], edge)
491 // remove deletes the cur-node's out-edges at index idx.
492 func (g *IRGraph) remove(cur *IRNode, i int) {
493 if len(g.OutEdges[cur]) >= 2 {
494 g.OutEdges[cur][i] = g.OutEdges[cur][len(g.OutEdges[cur])-1]
495 g.OutEdges[cur] = g.OutEdges[cur][:len(g.OutEdges[cur])-1]
497 delete(g.OutEdges, cur)
501 // calculateWeight calculates the weight of the new redirected edge.
502 func (g *IRGraph) calculateWeight(parent *IRNode, cur *IRNode) int64 {
505 for _, InEdge := range g.InEdges[cur] {
507 if InEdge.Src == parent {
520 // inlCallee is same as the implementation for inl.go with one change. The change is that we do not invoke CanInline on a closure.
521 func inlCallee(fn ir.Node) *ir.Func {
522 fn = ir.StaticValue(fn)
525 fn := fn.(*ir.SelectorExpr)
526 n := ir.MethodExprName(fn)
527 // Check that receiver type matches fn.X.
528 // TODO(mdempsky): Handle implicit dereference
529 // of pointer receiver argument?
530 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
536 if fn.Class == ir.PFUNC {
540 fn := fn.(*ir.ClosureExpr)