]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inlheur/analyze.go
9af7e1207d9f1b8a3089529d61b194b869ad247b
[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(funcProps *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 funcInlHeur, ok := fpmap[fn]; ok {
66                 return funcInlHeur.props
67         }
68         funcProps, 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:           funcProps,
76                 cstab:           fcstab,
77         }
78         fn.SetNeverReturns(entry.props.Flags&FuncPropNeverReturns != 0)
79         fpmap[fn] = entry
80         if fn.Inl != nil && fn.Inl.Properties == "" {
81                 fn.Inl.Properties = entry.props.SerializeToString()
82         }
83         return funcProps
84 }
85
86 // computeFuncProps examines the Go function 'fn' and computes for it
87 // a function "properties" object, to be used to drive inlining
88 // heuristics. See comments on the FuncProps type for more info.
89 func computeFuncProps(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) (*FuncProps, CallSiteTab) {
90         enableDebugTraceIfEnv()
91         if debugTrace&debugTraceFuncs != 0 {
92                 fmt.Fprintf(os.Stderr, "=-= starting analysis of func %v:\n%+v\n",
93                         fn.Sym().Name, fn)
94         }
95         ra := makeResultsAnalyzer(fn, canInline, inlineMaxBudget)
96         pa := makeParamsAnalyzer(fn)
97         ffa := makeFuncFlagsAnalyzer(fn)
98         analyzers := []propAnalyzer{ffa, ra, pa}
99         funcProps := new(FuncProps)
100         runAnalyzersOnFunction(fn, analyzers)
101         for _, a := range analyzers {
102                 a.setResults(funcProps)
103         }
104         // Now build up a partial table of callsites for this func.
105         cstab := computeCallSiteTable(fn, ffa.panicPathTable())
106         disableDebugTrace()
107         return funcProps, cstab
108 }
109
110 func runAnalyzersOnFunction(fn *ir.Func, analyzers []propAnalyzer) {
111         var doNode func(ir.Node) bool
112         doNode = func(n ir.Node) bool {
113                 for _, a := range analyzers {
114                         a.nodeVisitPre(n)
115                 }
116                 ir.DoChildren(n, doNode)
117                 for _, a := range analyzers {
118                         a.nodeVisitPost(n)
119                 }
120                 return false
121         }
122         doNode(fn)
123 }
124
125 func propsForFunc(fn *ir.Func) *FuncProps {
126         if funcInlHeur, ok := fpmap[fn]; ok {
127                 return funcInlHeur.props
128         } else if fn.Inl != nil && fn.Inl.Properties != "" {
129                 // FIXME: considering adding some sort of cache or table
130                 // for deserialized properties of imported functions.
131                 return DeserializeFromString(fn.Inl.Properties)
132         }
133         return nil
134 }
135
136 func fnFileLine(fn *ir.Func) (string, uint) {
137         p := base.Ctxt.InnermostPos(fn.Pos())
138         return filepath.Base(p.Filename()), p.Line()
139 }
140
141 func UnitTesting() bool {
142         return base.Debug.DumpInlFuncProps != ""
143 }
144
145 // DumpFuncProps computes and caches function properties for the func
146 // 'fn' and any closures it contains, or if fn is nil, it writes out the
147 // cached set of properties to the file given in 'dumpfile'. Used for
148 // the "-d=dumpinlfuncprops=..." command line flag, intended for use
149 // primarily in unit testing.
150 func DumpFuncProps(fn *ir.Func, dumpfile string, canInline func(*ir.Func), inlineMaxBudget int32) {
151         if fn != nil {
152                 enableDebugTraceIfEnv()
153                 dmp := func(fn *ir.Func) {
154                         if !goexperiment.NewInliner {
155                                 ScoreCalls(fn)
156                         }
157                         captureFuncDumpEntry(fn, canInline, inlineMaxBudget)
158                 }
159                 dmp(fn)
160                 ir.Visit(fn, func(n ir.Node) {
161                         if clo, ok := n.(*ir.ClosureExpr); ok {
162                                 dmp(clo.Func)
163                         }
164                 })
165                 disableDebugTrace()
166         } else {
167                 emitDumpToFile(dumpfile)
168         }
169 }
170
171 // emitDumpToFile writes out the buffer function property dump entries
172 // to a file, for unit testing. Dump entries need to be sorted by
173 // definition line, and due to generics we need to account for the
174 // possibility that several ir.Func's will have the same def line.
175 func emitDumpToFile(dumpfile string) {
176         mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
177         if dumpfile[0] == '+' {
178                 dumpfile = dumpfile[1:]
179                 mode = os.O_WRONLY | os.O_APPEND | os.O_CREATE
180         }
181         if dumpfile[0] == '%' {
182                 dumpfile = dumpfile[1:]
183                 d, b := filepath.Dir(dumpfile), filepath.Base(dumpfile)
184                 ptag := strings.ReplaceAll(types.LocalPkg.Path, "/", ":")
185                 dumpfile = d + "/" + ptag + "." + b
186         }
187         outf, err := os.OpenFile(dumpfile, mode, 0644)
188         if err != nil {
189                 base.Fatalf("opening function props dump file %q: %v\n", dumpfile, err)
190         }
191         defer outf.Close()
192         dumpFilePreamble(outf)
193
194         atline := map[uint]uint{}
195         sl := make([]fnInlHeur, 0, len(dumpBuffer))
196         for _, e := range dumpBuffer {
197                 sl = append(sl, e)
198                 atline[e.line] = atline[e.line] + 1
199         }
200         sl = sortFnInlHeurSlice(sl)
201
202         prevline := uint(0)
203         for _, entry := range sl {
204                 idx := uint(0)
205                 if prevline == entry.line {
206                         idx++
207                 }
208                 prevline = entry.line
209                 atl := atline[entry.line]
210                 if err := dumpFnPreamble(outf, &entry, nil, idx, atl); err != nil {
211                         base.Fatalf("function props dump: %v\n", err)
212                 }
213         }
214         dumpBuffer = nil
215 }
216
217 // captureFuncDumpEntry grabs the function properties object for 'fn'
218 // and enqueues it for later dumping. Used for the
219 // "-d=dumpinlfuncprops=..." command line flag, intended for use
220 // primarily in unit testing.
221 func captureFuncDumpEntry(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) {
222         // avoid capturing compiler-generated equality funcs.
223         if strings.HasPrefix(fn.Sym().Name, ".eq.") {
224                 return
225         }
226         funcInlHeur, ok := fpmap[fn]
227         // Props object should already be present, unless this is a
228         // directly recursive routine.
229         if !ok {
230                 AnalyzeFunc(fn, canInline, inlineMaxBudget)
231                 funcInlHeur = fpmap[fn]
232                 if fn.Inl != nil && fn.Inl.Properties == "" {
233                         fn.Inl.Properties = funcInlHeur.props.SerializeToString()
234                 }
235         }
236         if dumpBuffer == nil {
237                 dumpBuffer = make(map[*ir.Func]fnInlHeur)
238         }
239         if _, ok := dumpBuffer[fn]; ok {
240                 // we can wind up seeing closures multiple times here,
241                 // so don't add them more than once.
242                 return
243         }
244         if debugTrace&debugTraceFuncs != 0 {
245                 fmt.Fprintf(os.Stderr, "=-= capturing dump for %v:\n", fn)
246         }
247         dumpBuffer[fn] = funcInlHeur
248 }
249
250 // dumpFilePreamble writes out a file-level preamble for a given
251 // Go function as part of a function properties dump.
252 func dumpFilePreamble(w io.Writer) {
253         fmt.Fprintf(w, "// DO NOT EDIT (use 'go test -v -update-expected' instead.)\n")
254         fmt.Fprintf(w, "// See cmd/compile/internal/inline/inlheur/testdata/props/README.txt\n")
255         fmt.Fprintf(w, "// for more information on the format of this file.\n")
256         fmt.Fprintf(w, "// %s\n", preambleDelimiter)
257 }
258
259 // dumpFnPreamble writes out a function-level preamble for a given
260 // Go function as part of a function properties dump. See the
261 // README.txt file in testdata/props for more on the format of
262 // this preamble.
263 func dumpFnPreamble(w io.Writer, funcInlHeur *fnInlHeur, ecst encodedCallSiteTab, idx, atl uint) error {
264         fmt.Fprintf(w, "// %s %s %d %d %d\n",
265                 funcInlHeur.file, funcInlHeur.fname, funcInlHeur.line, idx, atl)
266         // emit props as comments, followed by delimiter
267         fmt.Fprintf(w, "%s// %s\n", funcInlHeur.props.ToString("// "), comDelimiter)
268         data, err := json.Marshal(funcInlHeur.props)
269         if err != nil {
270                 return fmt.Errorf("marshall error %v\n", err)
271         }
272         fmt.Fprintf(w, "// %s\n", string(data))
273         dumpCallSiteComments(w, funcInlHeur.cstab, ecst)
274         fmt.Fprintf(w, "// %s\n", fnDelimiter)
275         return nil
276 }
277
278 // sortFnInlHeurSlice sorts a slice of fnInlHeur based on
279 // the starting line of the function definition, then by name.
280 func sortFnInlHeurSlice(sl []fnInlHeur) []fnInlHeur {
281         sort.SliceStable(sl, func(i, j int) bool {
282                 if sl[i].line != sl[j].line {
283                         return sl[i].line < sl[j].line
284                 }
285                 return sl[i].fname < sl[j].fname
286         })
287         return sl
288 }
289
290 // delimiters written to various preambles to make parsing of
291 // dumps easier.
292 const preambleDelimiter = "<endfilepreamble>"
293 const fnDelimiter = "<endfuncpreamble>"
294 const comDelimiter = "<endpropsdump>"
295 const csDelimiter = "<endcallsites>"
296
297 // dumpBuffer stores up function properties dumps when
298 // "-d=dumpinlfuncprops=..." is in effect.
299 var dumpBuffer map[*ir.Func]fnInlHeur