]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inlheur/analyze_func_callsites.go
e59ee265312b1f2112caa655b98d057ce4a94af2
[gostls13.git] / src / cmd / compile / internal / inline / inlheur / analyze_func_callsites.go
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.
4
5 package inlheur
6
7 import (
8         "cmd/compile/internal/ir"
9         "cmd/compile/internal/pgo"
10         "fmt"
11         "os"
12         "strings"
13 )
14
15 type callSiteAnalyzer struct {
16         cstab    CallSiteTab
17         fn       *ir.Func
18         ptab     map[ir.Node]pstate
19         nstack   []ir.Node
20         loopNest int
21         isInit   bool
22 }
23
24 func makeCallSiteAnalyzer(fn *ir.Func, cstab CallSiteTab, ptab map[ir.Node]pstate, loopNestingLevel int) *callSiteAnalyzer {
25         isInit := fn.IsPackageInit() || strings.HasPrefix(fn.Sym().Name, "init.")
26         return &callSiteAnalyzer{
27                 fn:       fn,
28                 cstab:    cstab,
29                 ptab:     ptab,
30                 isInit:   isInit,
31                 loopNest: loopNestingLevel,
32                 nstack:   []ir.Node{fn},
33         }
34 }
35
36 // computeCallSiteTable builds and returns a table of call sites for
37 // the specified region in function fn. A region here corresponds to a
38 // specific subtree within the AST for a function. The main intended
39 // use cases are for 'region' to be either A) an entire function body,
40 // or B) an inlined call expression.
41 func computeCallSiteTable(fn *ir.Func, region ir.Nodes, cstab CallSiteTab, ptab map[ir.Node]pstate, loopNestingLevel int) CallSiteTab {
42         csa := makeCallSiteAnalyzer(fn, cstab, ptab, loopNestingLevel)
43         var doNode func(ir.Node) bool
44         doNode = func(n ir.Node) bool {
45                 csa.nodeVisitPre(n)
46                 ir.DoChildren(n, doNode)
47                 csa.nodeVisitPost(n)
48                 return false
49         }
50         for _, n := range region {
51                 doNode(n)
52         }
53         return csa.cstab
54 }
55
56 func (csa *callSiteAnalyzer) flagsForNode(call *ir.CallExpr) CSPropBits {
57         var r CSPropBits
58
59         if debugTrace&debugTraceCalls != 0 {
60                 fmt.Fprintf(os.Stderr, "=-= analyzing call at %s\n",
61                         fmtFullPos(call.Pos()))
62         }
63
64         // Set a bit if this call is within a loop.
65         if csa.loopNest > 0 {
66                 r |= CallSiteInLoop
67         }
68
69         // Set a bit if the call is within an init function (either
70         // compiler-generated or user-written).
71         if csa.isInit {
72                 r |= CallSiteInInitFunc
73         }
74
75         // Decide whether to apply the panic path heuristic. Hack: don't
76         // apply this heuristic in the function "main.main" (mostly just
77         // to avoid annoying users).
78         if !isMainMain(csa.fn) {
79                 r = csa.determinePanicPathBits(call, r)
80         }
81
82         return r
83 }
84
85 // determinePanicPathBits updates the CallSiteOnPanicPath bit within
86 // "r" if we think this call is on an unconditional path to
87 // panic/exit. Do this by walking back up the node stack to see if we
88 // can find either A) an enclosing panic, or B) a statement node that
89 // we've determined leads to a panic/exit.
90 func (csa *callSiteAnalyzer) determinePanicPathBits(call ir.Node, r CSPropBits) CSPropBits {
91         csa.nstack = append(csa.nstack, call)
92         defer func() {
93                 csa.nstack = csa.nstack[:len(csa.nstack)-1]
94         }()
95
96         for ri := range csa.nstack[:len(csa.nstack)-1] {
97                 i := len(csa.nstack) - ri - 1
98                 n := csa.nstack[i]
99                 _, isCallExpr := n.(*ir.CallExpr)
100                 _, isStmt := n.(ir.Stmt)
101                 if isCallExpr {
102                         isStmt = false
103                 }
104
105                 if debugTrace&debugTraceCalls != 0 {
106                         ps, inps := csa.ptab[n]
107                         fmt.Fprintf(os.Stderr, "=-= callpar %d op=%s ps=%s inptab=%v stmt=%v\n", i, n.Op().String(), ps.String(), inps, isStmt)
108                 }
109
110                 if n.Op() == ir.OPANIC {
111                         r |= CallSiteOnPanicPath
112                         break
113                 }
114                 if v, ok := csa.ptab[n]; ok {
115                         if v == psCallsPanic {
116                                 r |= CallSiteOnPanicPath
117                                 break
118                         }
119                         if isStmt {
120                                 break
121                         }
122                 }
123         }
124         return r
125 }
126
127 func (csa *callSiteAnalyzer) addCallSite(callee *ir.Func, call *ir.CallExpr) {
128         flags := csa.flagsForNode(call)
129         // FIXME: maybe bulk-allocate these?
130         cs := &CallSite{
131                 Call:   call,
132                 Callee: callee,
133                 Assign: csa.containingAssignment(call),
134                 Flags:  flags,
135                 ID:     uint(len(csa.cstab)),
136         }
137         if _, ok := csa.cstab[call]; ok {
138                 fmt.Fprintf(os.Stderr, "*** cstab duplicate entry at: %s\n",
139                         fmtFullPos(call.Pos()))
140                 fmt.Fprintf(os.Stderr, "*** call: %+v\n", call)
141                 panic("bad")
142         }
143         if callee.Inl != nil {
144                 // Set initial score for callsite to the cost computed
145                 // by CanInline; this score will be refined later based
146                 // on heuristics.
147                 cs.Score = int(callee.Inl.Cost)
148         }
149
150         if csa.cstab == nil {
151                 csa.cstab = make(CallSiteTab)
152         }
153         csa.cstab[call] = cs
154         if debugTrace&debugTraceCalls != 0 {
155                 fmt.Fprintf(os.Stderr, "=-= added callsite at %s: callee=%s call[%p]=%v\n", fmtFullPos(call.Pos()), callee.Sym().Name, call, call)
156         }
157 }
158
159 func (csa *callSiteAnalyzer) nodeVisitPre(n ir.Node) {
160         switch n.Op() {
161         case ir.ORANGE, ir.OFOR:
162                 if !hasTopLevelLoopBodyReturnOrBreak(loopBody(n)) {
163                         csa.loopNest++
164                 }
165         case ir.OCALLFUNC:
166                 ce := n.(*ir.CallExpr)
167                 callee := pgo.DirectCallee(ce.Fun)
168                 if callee != nil && callee.Inl != nil {
169                         csa.addCallSite(callee, ce)
170                 }
171         }
172         csa.nstack = append(csa.nstack, n)
173 }
174
175 func (csa *callSiteAnalyzer) nodeVisitPost(n ir.Node) {
176         csa.nstack = csa.nstack[:len(csa.nstack)-1]
177         switch n.Op() {
178         case ir.ORANGE, ir.OFOR:
179                 if !hasTopLevelLoopBodyReturnOrBreak(loopBody(n)) {
180                         csa.loopNest--
181                 }
182         }
183 }
184
185 func loopBody(n ir.Node) ir.Nodes {
186         if forst, ok := n.(*ir.ForStmt); ok {
187                 return forst.Body
188         }
189         if rst, ok := n.(*ir.RangeStmt); ok {
190                 return rst.Body
191         }
192         return nil
193 }
194
195 // hasTopLevelLoopBodyReturnOrBreak examines the body of a "for" or
196 // "range" loop to try to verify that it is a real loop, as opposed to
197 // a construct that is syntactically loopy but doesn't actually iterate
198 // multiple times, like:
199 //
200 //      for {
201 //        blah()
202 //        return 1
203 //      }
204 //
205 // [Remark: the pattern above crops up quite a bit in the source code
206 // for the compiler itself, e.g. the auto-generated rewrite code]
207 //
208 // Note that we don't look for GOTO statements here, so it's possible
209 // we'll get the wrong result for a loop with complicated control
210 // jumps via gotos.
211 func hasTopLevelLoopBodyReturnOrBreak(loopBody ir.Nodes) bool {
212         for _, n := range loopBody {
213                 if n.Op() == ir.ORETURN || n.Op() == ir.OBREAK {
214                         return true
215                 }
216         }
217         return false
218 }
219
220 // containingAssignment returns the top-level assignment statement
221 // for a statement level function call "n". Examples:
222 //
223 //      x := foo()
224 //      x, y := bar(z, baz())
225 //      if blah() { ...
226 //
227 // Here the top-level assignment statement for the foo() call is the
228 // statement assigning to "x"; the top-level assignment for "bar()"
229 // call is the assignment to x,y. For the baz() and blah() calls,
230 // there is no top level assignment statement.
231 //
232 // The unstated goal here is that we want to use the containing
233 // assignment to establish a connection between a given call and the
234 // variables to which its results/returns are being assigned.
235 //
236 // Note that for the "bar" command above, the front end sometimes
237 // decomposes this into two assignments, the first one assigning the
238 // call to a pair of auto-temps, then the second one assigning the
239 // auto-temps to the user-visible vars. This helper will return the
240 // second (outer) of these two.
241 func (csa *callSiteAnalyzer) containingAssignment(n ir.Node) ir.Node {
242         parent := csa.nstack[len(csa.nstack)-1]
243
244         // assignsOnlyAutoTemps returns TRUE of the specified OAS2FUNC
245         // node assigns only auto-temps.
246         assignsOnlyAutoTemps := func(x ir.Node) bool {
247                 alst := x.(*ir.AssignListStmt)
248                 oa2init := alst.Init()
249                 if len(oa2init) == 0 {
250                         return false
251                 }
252                 for _, v := range oa2init {
253                         d := v.(*ir.Decl)
254                         if !ir.IsAutoTmp(d.X) {
255                                 return false
256                         }
257                 }
258                 return true
259         }
260
261         // Simple case: x := foo()
262         if parent.Op() == ir.OAS {
263                 return parent
264         }
265
266         // Multi-return case: x, y := bar()
267         if parent.Op() == ir.OAS2FUNC {
268                 // Hack city: if the result vars are auto-temps, try looking
269                 // for an outer assignment in the tree. The code shape we're
270                 // looking for here is:
271                 //
272                 // OAS1({x,y},OCONVNOP(OAS2FUNC({auto1,auto2},OCALLFUNC(bar))))
273                 //
274                 if assignsOnlyAutoTemps(parent) {
275                         par2 := csa.nstack[len(csa.nstack)-2]
276                         if par2.Op() == ir.OAS2 {
277                                 return par2
278                         }
279                         if par2.Op() == ir.OCONVNOP {
280                                 par3 := csa.nstack[len(csa.nstack)-3]
281                                 if par3.Op() == ir.OAS2 {
282                                         return par3
283                                 }
284                         }
285                 }
286         }
287
288         return nil
289 }