1 // Copyright 2023 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.
8 "cmd/compile/internal/base"
9 "cmd/compile/internal/ir"
18 // CallSite records useful information about a potentially inlinable
19 // (direct) function call. "Callee" is the target of the call, "Call"
20 // is the ir node corresponding to the call itself, "Assign" is
21 // the top-level assignment statement containing the call (if the call
22 // appears in the form of a top-level statement, e.g. "x := foo()"),
23 // "Flags" contains properties of the call that might be useful for
24 // making inlining decisions, "Score" is the final score assigned to
25 // the site, and "Id" is a numeric ID for the site within its
26 // containing function.
27 type CallSite struct {
36 // CallSiteTab is a table of call sites, keyed by call expr.
37 // Ideally it would be nice to key the table by src.XPos, but
38 // this results in collisions for calls on very long lines (the
39 // front end saturates column numbers at 255). We also wind up
40 // with many calls that share the same auto-generated pos.
41 type CallSiteTab map[*ir.CallExpr]*CallSite
43 // Package-level table of callsites.
44 var cstab = CallSiteTab{}
46 type CSPropBits uint32
49 CallSiteInLoop CSPropBits = 1 << iota
54 // encodedCallSiteTab is a table keyed by "encoded" callsite
55 // (stringified src.XPos plus call site ID) mapping to a value of call
57 type encodedCallSiteTab map[string]CSPropBits
59 func (cst CallSiteTab) merge(other CallSiteTab) error {
60 for k, v := range other {
61 if prev, ok := cst[k]; ok {
62 return fmt.Errorf("internal error: collision during call site table merge, fn=%s callsite=%s", prev.Callee.Sym().Name, fmtFullPos(prev.Call.Pos()))
69 func fmtFullPos(p src.XPos) string {
70 var sb strings.Builder
72 base.Ctxt.AllPos(p, func(pos src.Pos) {
75 file := filepath.Base(pos.Filename())
76 fmt.Fprintf(&sb, "%s:%d:%d", file, pos.Line(), pos.Col())
81 func encodeCallSiteKey(cs *CallSite) string {
82 var sb strings.Builder
83 // FIXME: rewrite line offsets relative to function start
84 sb.WriteString(fmtFullPos(cs.Call.Pos()))
85 fmt.Fprintf(&sb, "|%d", cs.Id)
89 func buildEncodedCallSiteTab(tab CallSiteTab) encodedCallSiteTab {
90 r := make(encodedCallSiteTab)
91 for _, cs := range tab {
92 k := encodeCallSiteKey(cs)
98 // dumpCallSiteComments emits comments into the dump file for the
99 // callsites in the function of interest. If "ecst" is non-nil, we use
100 // that, otherwise generated a fresh encodedCallSiteTab from "tab".
101 func dumpCallSiteComments(w io.Writer, tab CallSiteTab, ecst encodedCallSiteTab) {
103 ecst = buildEncodedCallSiteTab(tab)
105 tags := make([]string, 0, len(ecst))
106 for k := range ecst {
107 tags = append(tags, k)
110 for _, s := range tags {
112 fmt.Fprintf(w, "// callsite: %s flagstr %q flagval %d\n", s, v.String(), v)
114 fmt.Fprintf(w, "// %s\n", csDelimiter)