]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inlheur/analyze.go
cmd/compile/internal/inline: tweak "returns inlinable func" heuristic
[gostls13.git] / src / cmd / compile / internal / inline / inlheur / analyze.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/base"
9         "cmd/compile/internal/ir"
10         "cmd/compile/internal/types"
11         "encoding/json"
12         "fmt"
13         "internal/goexperiment"
14         "io"
15         "os"
16         "path/filepath"
17         "sort"
18         "strings"
19 )
20
21 const (
22         debugTraceFuncs = 1 << iota
23         debugTraceFuncFlags
24         debugTraceResults
25         debugTraceParams
26         debugTraceExprClassify
27         debugTraceCalls
28         debugTraceScoring
29 )
30
31 // propAnalyzer interface is used for defining one or more analyzer
32 // helper objects, each tasked with computing some specific subset of
33 // the properties we're interested in. The assumption is that
34 // properties are independent, so each new analyzer that implements
35 // this interface can operate entirely on its own. For a given analyzer
36 // there will be a sequence of calls to nodeVisitPre and nodeVisitPost
37 // as the nodes within a function are visited, then a followup call to
38 // setResults so that the analyzer can transfer its results into the
39 // final properties object.
40 type propAnalyzer interface {
41         nodeVisitPre(n ir.Node)
42         nodeVisitPost(n ir.Node)
43         setResults(fp *FuncProps)
44 }
45
46 // fnInlHeur contains inline heuristics state information about a
47 // specific Go function being analyzed/considered by the inliner. Note
48 // that in addition to constructing a fnInlHeur object by analyzing a
49 // specific *ir.Func, there is also code in the test harness
50 // (funcprops_test.go) that builds up fnInlHeur's by reading in and
51 // parsing a dump. This is the reason why we have file/fname/line
52 // fields below instead of just an *ir.Func field.
53 type fnInlHeur struct {
54         fname           string
55         file            string
56         line            uint
57         inlineMaxBudget int32
58         props           *FuncProps
59         cstab           CallSiteTab
60 }
61
62 var fpmap = map[*ir.Func]fnInlHeur{}
63
64 func AnalyzeFunc(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) *FuncProps {
65         if fih, ok := fpmap[fn]; ok {
66                 return fih.props
67         }
68         fp, fcstab := computeFuncProps(fn, canInline, inlineMaxBudget)
69         file, line := fnFileLine(fn)
70         entry := fnInlHeur{
71                 fname:           fn.Sym().Name,
72                 file:            file,
73                 line:            line,
74                 inlineMaxBudget: inlineMaxBudget,
75                 props:           fp,
76                 cstab:           fcstab,
77         }
78         // Merge this functions call sites into the package level table.
79         if err := cstab.merge(fcstab); err != nil {
80                 base.FatalfAt(fn.Pos(), "%v", err)
81         }
82         fn.SetNeverReturns(entry.props.Flags&FuncPropNeverReturns != 0)
83         fpmap[fn] = entry
84         if fn.Inl != nil && fn.Inl.Properties == "" {
85                 fn.Inl.Properties = entry.props.SerializeToString()
86         }
87         return fp
88 }
89
90 // computeFuncProps examines the Go function 'fn' and computes for it
91 // a function "properties" object, to be used to drive inlining
92 // heuristics. See comments on the FuncProps type for more info.
93 func computeFuncProps(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) (*FuncProps, CallSiteTab) {
94         enableDebugTraceIfEnv()
95         if debugTrace&debugTraceFuncs != 0 {
96                 fmt.Fprintf(os.Stderr, "=-= starting analysis of func %v:\n%+v\n",
97                         fn.Sym().Name, fn)
98         }
99         ra := makeResultsAnalyzer(fn, canInline, inlineMaxBudget)
100         pa := makeParamsAnalyzer(fn)
101         ffa := makeFuncFlagsAnalyzer(fn)
102         analyzers := []propAnalyzer{ffa, ra, pa}
103         fp := new(FuncProps)
104         runAnalyzersOnFunction(fn, analyzers)
105         for _, a := range analyzers {
106                 a.setResults(fp)
107         }
108         // Now build up a partial table of callsites for this func.
109         cstab := computeCallSiteTable(fn, ffa.panicPathTable())
110         disableDebugTrace()
111         return fp, cstab
112 }
113
114 func runAnalyzersOnFunction(fn *ir.Func, analyzers []propAnalyzer) {
115         var doNode func(ir.Node) bool
116         doNode = func(n ir.Node) bool {
117                 for _, a := range analyzers {
118                         a.nodeVisitPre(n)
119                 }
120                 ir.DoChildren(n, doNode)
121                 for _, a := range analyzers {
122                         a.nodeVisitPost(n)
123                 }
124                 return false
125         }
126         doNode(fn)
127 }
128
129 func propsForFunc(fn *ir.Func) *FuncProps {
130         if fih, ok := fpmap[fn]; ok {
131                 return fih.props
132         } else if fn.Inl != nil && fn.Inl.Properties != "" {
133                 // FIXME: considering adding some sort of cache or table
134                 // for deserialized properties of imported functions.
135                 return DeserializeFromString(fn.Inl.Properties)
136         }
137         return nil
138 }
139
140 func fnFileLine(fn *ir.Func) (string, uint) {
141         p := base.Ctxt.InnermostPos(fn.Pos())
142         return filepath.Base(p.Filename()), p.Line()
143 }
144
145 func UnitTesting() bool {
146         return base.Debug.DumpInlFuncProps != ""
147 }
148
149 // DumpFuncProps computes and caches function properties for the func
150 // 'fn' and any closures it contains, or if fn is nil, it writes out the
151 // cached set of properties to the file given in 'dumpfile'. Used for
152 // the "-d=dumpinlfuncprops=..." command line flag, intended for use
153 // primarily in unit testing.
154 func DumpFuncProps(fn *ir.Func, dumpfile string, canInline func(*ir.Func), inlineMaxBudget int32) {
155         if fn != nil {
156                 enableDebugTraceIfEnv()
157                 dmp := func(fn *ir.Func) {
158                         if !goexperiment.NewInliner {
159                                 ScoreCalls(fn)
160                         }
161                         captureFuncDumpEntry(fn, canInline, inlineMaxBudget)
162                 }
163                 dmp(fn)
164                 ir.Visit(fn, func(n ir.Node) {
165                         if clo, ok := n.(*ir.ClosureExpr); ok {
166                                 dmp(clo.Func)
167                         }
168                 })
169                 disableDebugTrace()
170         } else {
171                 emitDumpToFile(dumpfile)
172         }
173 }
174
175 // emitDumpToFile writes out the buffer function property dump entries
176 // to a file, for unit testing. Dump entries need to be sorted by
177 // definition line, and due to generics we need to account for the
178 // possibility that several ir.Func's will have the same def line.
179 func emitDumpToFile(dumpfile string) {
180         mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
181         if dumpfile[0] == '+' {
182                 dumpfile = dumpfile[1:]
183                 mode = os.O_WRONLY | os.O_APPEND | os.O_CREATE
184         }
185         if dumpfile[0] == '%' {
186                 dumpfile = dumpfile[1:]
187                 d, b := filepath.Dir(dumpfile), filepath.Base(dumpfile)
188                 ptag := strings.ReplaceAll(types.LocalPkg.Path, "/", ":")
189                 dumpfile = d + "/" + ptag + "." + b
190         }
191         outf, err := os.OpenFile(dumpfile, mode, 0644)
192         if err != nil {
193                 base.Fatalf("opening function props dump file %q: %v\n", dumpfile, err)
194         }
195         defer outf.Close()
196         dumpFilePreamble(outf)
197
198         atline := map[uint]uint{}
199         sl := make([]fnInlHeur, 0, len(dumpBuffer))
200         for _, e := range dumpBuffer {
201                 sl = append(sl, e)
202                 atline[e.line] = atline[e.line] + 1
203         }
204         sl = sortFnInlHeurSlice(sl)
205
206         prevline := uint(0)
207         for _, entry := range sl {
208                 idx := uint(0)
209                 if prevline == entry.line {
210                         idx++
211                 }
212                 prevline = entry.line
213                 atl := atline[entry.line]
214                 if err := dumpFnPreamble(outf, &entry, nil, idx, atl); err != nil {
215                         base.Fatalf("function props dump: %v\n", err)
216                 }
217         }
218         dumpBuffer = nil
219 }
220
221 // captureFuncDumpEntry grabs the function properties object for 'fn'
222 // and enqueues it for later dumping. Used for the
223 // "-d=dumpinlfuncprops=..." command line flag, intended for use
224 // primarily in unit testing.
225 func captureFuncDumpEntry(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) {
226         // avoid capturing compiler-generated equality funcs.
227         if strings.HasPrefix(fn.Sym().Name, ".eq.") {
228                 return
229         }
230         fih, ok := fpmap[fn]
231         // Props object should already be present, unless this is a
232         // directly recursive routine.
233         if !ok {
234                 AnalyzeFunc(fn, canInline, inlineMaxBudget)
235                 fih = fpmap[fn]
236                 if fn.Inl != nil && fn.Inl.Properties == "" {
237                         fn.Inl.Properties = fih.props.SerializeToString()
238                 }
239         }
240         if dumpBuffer == nil {
241                 dumpBuffer = make(map[*ir.Func]fnInlHeur)
242         }
243         if _, ok := dumpBuffer[fn]; ok {
244                 // we can wind up seeing closures multiple times here,
245                 // so don't add them more than once.
246                 return
247         }
248         if debugTrace&debugTraceFuncs != 0 {
249                 fmt.Fprintf(os.Stderr, "=-= capturing dump for %v:\n", fn)
250         }
251         dumpBuffer[fn] = fih
252 }
253
254 // dumpFilePreamble writes out a file-level preamble for a given
255 // Go function as part of a function properties dump.
256 func dumpFilePreamble(w io.Writer) {
257         fmt.Fprintf(w, "// DO NOT EDIT (use 'go test -v -update-expected' instead.)\n")
258         fmt.Fprintf(w, "// See cmd/compile/internal/inline/inlheur/testdata/props/README.txt\n")
259         fmt.Fprintf(w, "// for more information on the format of this file.\n")
260         fmt.Fprintf(w, "// %s\n", preambleDelimiter)
261 }
262
263 // dumpFnPreamble writes out a function-level preamble for a given
264 // Go function as part of a function properties dump. See the
265 // README.txt file in testdata/props for more on the format of
266 // this preamble.
267 func dumpFnPreamble(w io.Writer, fih *fnInlHeur, ecst encodedCallSiteTab, idx, atl uint) error {
268         fmt.Fprintf(w, "// %s %s %d %d %d\n",
269                 fih.file, fih.fname, fih.line, idx, atl)
270         // emit props as comments, followed by delimiter
271         fmt.Fprintf(w, "%s// %s\n", fih.props.ToString("// "), comDelimiter)
272         data, err := json.Marshal(fih.props)
273         if err != nil {
274                 return fmt.Errorf("marshall error %v\n", err)
275         }
276         fmt.Fprintf(w, "// %s\n", string(data))
277         dumpCallSiteComments(w, fih.cstab, ecst)
278         fmt.Fprintf(w, "// %s\n", fnDelimiter)
279         return nil
280 }
281
282 // sortFnInlHeurSlice sorts a slice of fnInlHeur based on
283 // the starting line of the function definition, then by name.
284 func sortFnInlHeurSlice(sl []fnInlHeur) []fnInlHeur {
285         sort.SliceStable(sl, func(i, j int) bool {
286                 if sl[i].line != sl[j].line {
287                         return sl[i].line < sl[j].line
288                 }
289                 return sl[i].fname < sl[j].fname
290         })
291         return sl
292 }
293
294 // delimiters written to various preambles to make parsing of
295 // dumps easier.
296 const preambleDelimiter = "<endfilepreamble>"
297 const fnDelimiter = "<endfuncpreamble>"
298 const comDelimiter = "<endpropsdump>"
299 const csDelimiter = "<endcallsites>"
300
301 // dumpBuffer stores up function properties dumps when
302 // "-d=dumpinlfuncprops=..." is in effect.
303 var dumpBuffer map[*ir.Func]fnInlHeur