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"
10 "cmd/compile/internal/pgo"
17 type callSiteAnalyzer struct {
20 ptab map[ir.Node]pstate
26 func makeCallSiteAnalyzer(fn *ir.Func, ptab map[ir.Node]pstate) *callSiteAnalyzer {
27 isInit := fn.IsPackageInit() || strings.HasPrefix(fn.Sym().Name, "init.")
28 return &callSiteAnalyzer{
30 cstab: make(CallSiteTab),
36 func computeCallSiteTable(fn *ir.Func, ptab map[ir.Node]pstate) CallSiteTab {
38 fmt.Fprintf(os.Stderr, "=-= making callsite table for func %v:\n",
41 csa := makeCallSiteAnalyzer(fn, ptab)
42 var doNode func(ir.Node) bool
43 doNode = func(n ir.Node) bool {
45 ir.DoChildren(n, doNode)
53 func (csa *callSiteAnalyzer) flagsForNode(call *ir.CallExpr) CSPropBits {
56 if debugTrace&debugTraceCalls != 0 {
57 fmt.Fprintf(os.Stderr, "=-= analyzing call at %s\n",
58 fmtFullPos(call.Pos()))
61 // Set a bit if this call is within a loop.
66 // Set a bit if the call is within an init function (either
67 // compiler-generated or user-written).
69 r |= CallSiteInInitFunc
72 // Decide whether to apply the panic path heuristic. Hack: don't
73 // apply this heuristic in the function "main.main" (mostly just
74 // to avoid annoying users).
75 if !isMainMain(csa.fn) {
76 r = csa.determinePanicPathBits(call, r)
82 // determinePanicPathBits updates the CallSiteOnPanicPath bit within
83 // "r" if we think this call is on an unconditional path to
84 // panic/exit. Do this by walking back up the node stack to see if we
85 // can find either A) an enclosing panic, or B) a statement node that
86 // we've determined leads to a panic/exit.
87 func (csa *callSiteAnalyzer) determinePanicPathBits(call ir.Node, r CSPropBits) CSPropBits {
88 csa.nstack = append(csa.nstack, call)
90 csa.nstack = csa.nstack[:len(csa.nstack)-1]
93 for ri := range csa.nstack[:len(csa.nstack)-1] {
94 i := len(csa.nstack) - ri - 1
96 _, isCallExpr := n.(*ir.CallExpr)
97 _, isStmt := n.(ir.Stmt)
102 if debugTrace&debugTraceCalls != 0 {
103 ps, inps := csa.ptab[n]
104 fmt.Fprintf(os.Stderr, "=-= callpar %d op=%s ps=%s inptab=%v stmt=%v\n", i, n.Op().String(), ps.String(), inps, isStmt)
107 if n.Op() == ir.OPANIC {
108 r |= CallSiteOnPanicPath
111 if v, ok := csa.ptab[n]; ok {
112 if v == psCallsPanic {
113 r |= CallSiteOnPanicPath
124 func (csa *callSiteAnalyzer) addCallSite(callee *ir.Func, call *ir.CallExpr) {
125 flags := csa.flagsForNode(call)
126 // FIXME: maybe bulk-allocate these?
130 Assign: csa.containingAssignment(call),
132 ID: uint(len(csa.cstab)),
134 if _, ok := csa.cstab[call]; ok {
135 fmt.Fprintf(os.Stderr, "*** cstab duplicate entry at: %s\n",
136 fmtFullPos(call.Pos()))
137 fmt.Fprintf(os.Stderr, "*** call: %+v\n", call)
140 if callee.Inl != nil {
141 // Set initial score for callsite to the cost computed
142 // by CanInline; this score will be refined later based
144 cs.Score = int(callee.Inl.Cost)
148 if debugTrace&debugTraceCalls != 0 {
149 fmt.Fprintf(os.Stderr, "=-= added callsite: callee=%s call=%v\n",
150 callee.Sym().Name, callee)
154 // ScoreCalls assigns numeric scores to each of the callsites in
155 // function 'fn'; the lower the score, the more helpful we think it
156 // will be to inline.
158 // Unlike a lot of the other inline heuristics machinery, callsite
159 // scoring can't be done as part of the CanInline call for a function,
160 // due to fact that we may be working on a non-trivial SCC. So for
161 // example with this SCC:
163 // func foo(x int) { func bar(x int, f func()) {
165 // bar(x, func(){}) foo(x-1)
169 // We don't want to perform scoring for the 'foo' call in "bar" until
170 // after foo has been analyzed, but it's conceivable that CanInline
171 // might visit bar before foo for this SCC.
172 func ScoreCalls(fn *ir.Func) {
173 enableDebugTraceIfEnv()
174 defer disableDebugTrace()
175 if debugTrace&debugTraceScoring != 0 {
176 fmt.Fprintf(os.Stderr, "=-= ScoreCalls(%v)\n", ir.FuncName(fn))
181 // TODO: add an assert/panic here.
185 // Sort callsites to avoid any surprises with non deterministic
186 // map iteration order (this is probably not needed, but here just
188 csl := make([]*CallSite, 0, len(fih.cstab))
189 for _, cs := range fih.cstab {
190 csl = append(csl, cs)
192 sort.Slice(csl, func(i, j int) bool {
193 return csl[i].ID < csl[j].ID
196 // Score each call site.
197 for _, cs := range csl {
198 var cprops *FuncProps
201 if fih, ok := fpmap[cs.Callee]; ok {
204 } else if cs.Callee.Inl != nil {
205 cprops = DeserializeFromString(cs.Callee.Inl.Properties)
208 if base.Debug.DumpInlFuncProps != "" {
209 fmt.Fprintf(os.Stderr, "=-= *** unable to score call to %s from %s\n", cs.Callee.Sym().Name, fmtFullPos(cs.Call.Pos()))
210 panic("should never happen")
215 cs.Score, cs.ScoreMask = computeCallSiteScore(cs.Callee, cprops, cs.Call, cs.Flags)
217 if debugTrace&debugTraceScoring != 0 {
218 fmt.Fprintf(os.Stderr, "=-= scoring call at %s: flags=%d score=%d fih=%v deser=%v\n", fmtFullPos(cs.Call.Pos()), cs.Flags, cs.Score, fihcprops, desercprops)
223 func (csa *callSiteAnalyzer) nodeVisitPre(n ir.Node) {
225 case ir.ORANGE, ir.OFOR:
226 if !hasTopLevelLoopBodyReturnOrBreak(loopBody(n)) {
230 ce := n.(*ir.CallExpr)
231 callee := pgo.DirectCallee(ce.X)
232 if callee != nil && callee.Inl != nil {
233 csa.addCallSite(callee, ce)
236 csa.nstack = append(csa.nstack, n)
239 func (csa *callSiteAnalyzer) nodeVisitPost(n ir.Node) {
240 csa.nstack = csa.nstack[:len(csa.nstack)-1]
242 case ir.ORANGE, ir.OFOR:
243 if !hasTopLevelLoopBodyReturnOrBreak(loopBody(n)) {
249 func loopBody(n ir.Node) ir.Nodes {
250 if forst, ok := n.(*ir.ForStmt); ok {
253 if rst, ok := n.(*ir.RangeStmt); ok {
259 // hasTopLevelLoopBodyReturnOrBreak examines the body of a "for" or
260 // "range" loop to try to verify that it is a real loop, as opposed to
261 // a construct that is syntactically loopy but doesn't actually iterate
262 // multiple times, like:
269 // [Remark: the pattern above crops up quite a bit in the source code
270 // for the compiler itself, e.g. the auto-generated rewrite code]
272 // Note that we don't look for GOTO statements here, so it's possible
273 // we'll get the wrong result for a loop with complicated control
275 func hasTopLevelLoopBodyReturnOrBreak(loopBody ir.Nodes) bool {
276 for _, n := range loopBody {
277 if n.Op() == ir.ORETURN || n.Op() == ir.OBREAK {
284 // containingAssignment returns the top-level assignment statement
285 // for a statement level function call "n". Examples:
288 // x, y := bar(z, baz())
291 // Here the top-level assignment statement for the foo() call is the
292 // statement assigning to "x"; the top-level assignment for "bar()"
293 // call is the assignment to x,y. For the baz() and blah() calls,
294 // there is no top level assignment statement.
296 // The unstated goal here is that we want to use the containing assignment
297 // to establish a connection between a given call and the variables
298 // to which its results/returns are being assigned.
300 // Note that for the "bar" command above, the front end sometimes
301 // decomposes this into two assignments, the first one assigning the
302 // call to a pair of auto-temps, then the second one assigning the
303 // auto-temps to the user-visible vars. This helper will return the
304 // second (outer) of these two.
305 func (csa *callSiteAnalyzer) containingAssignment(n ir.Node) ir.Node {
306 parent := csa.nstack[len(csa.nstack)-1]
308 // assignsOnlyAutoTemps returns TRUE of the specified OAS2FUNC
309 // node assigns only auto-temps.
310 assignsOnlyAutoTemps := func(x ir.Node) bool {
311 alst := x.(*ir.AssignListStmt)
312 oa2init := alst.Init()
313 if len(oa2init) == 0 {
316 for _, v := range oa2init {
318 if !ir.IsAutoTmp(d.X) {
325 // Simple case: x := foo()
326 if parent.Op() == ir.OAS {
330 // Multi-return case: x, y := bar()
331 if parent.Op() == ir.OAS2FUNC {
332 // Hack city: if the result vars are auto-temps, try looking
333 // for an outer assignment in the tree. The code shape we're
334 // looking for here is:
336 // OAS1({x,y},OCONVNOP(OAS2FUNC({auto1,auto2},OCALLFUNC(bar))))
338 if assignsOnlyAutoTemps(parent) {
339 par2 := csa.nstack[len(csa.nstack)-2]
340 if par2.Op() == ir.OAS2 {
343 if par2.Op() == ir.OCONVNOP {
344 par3 := csa.nstack[len(csa.nstack)-3]
345 if par3.Op() == ir.OAS2 {