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/types"
13 "internal/goexperiment"
22 debugTraceFuncs = 1 << iota
26 debugTraceExprClassify
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)
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 {
62 var fpmap = map[*ir.Func]fnInlHeur{}
64 func AnalyzeFunc(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) *FuncProps {
65 if funcInlHeur, ok := fpmap[fn]; ok {
66 return funcInlHeur.props
68 funcProps, fcstab := computeFuncProps(fn, canInline, inlineMaxBudget)
69 file, line := fnFileLine(fn)
74 inlineMaxBudget: inlineMaxBudget,
78 fn.SetNeverReturns(entry.props.Flags&FuncPropNeverReturns != 0)
80 if fn.Inl != nil && fn.Inl.Properties == "" {
81 fn.Inl.Properties = entry.props.SerializeToString()
86 // RevisitInlinability revisits the question of whether to continue to
87 // treat function 'fn' as an inline candidate based on the set of
88 // properties we've computed for it. If (for example) it has an
89 // initial size score of 150 and no interesting properties to speak
90 // of, then there isn't really any point to moving ahead with it as an
92 func RevisitInlinability(fn *ir.Func, budgetForFunc func(*ir.Func) int32) {
96 entry, ok := fpmap[fn]
101 mxAdjust := int32(largestScoreAdjustment(fn, entry.props))
102 budget := budgetForFunc(fn)
103 if fn.Inl.Cost+mxAdjust > budget {
108 // computeFuncProps examines the Go function 'fn' and computes for it
109 // a function "properties" object, to be used to drive inlining
110 // heuristics. See comments on the FuncProps type for more info.
111 func computeFuncProps(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) (*FuncProps, CallSiteTab) {
112 enableDebugTraceIfEnv()
113 if debugTrace&debugTraceFuncs != 0 {
114 fmt.Fprintf(os.Stderr, "=-= starting analysis of func %v:\n%+v\n",
117 ra := makeResultsAnalyzer(fn, canInline, inlineMaxBudget)
118 pa := makeParamsAnalyzer(fn)
119 ffa := makeFuncFlagsAnalyzer(fn)
120 analyzers := []propAnalyzer{ffa, ra, pa}
121 funcProps := new(FuncProps)
122 runAnalyzersOnFunction(fn, analyzers)
123 for _, a := range analyzers {
124 a.setResults(funcProps)
126 // Now build up a partial table of callsites for this func.
127 cstab := computeCallSiteTable(fn, ffa.panicPathTable())
129 return funcProps, cstab
132 func runAnalyzersOnFunction(fn *ir.Func, analyzers []propAnalyzer) {
133 var doNode func(ir.Node) bool
134 doNode = func(n ir.Node) bool {
135 for _, a := range analyzers {
138 ir.DoChildren(n, doNode)
139 for _, a := range analyzers {
147 func propsForFunc(fn *ir.Func) *FuncProps {
148 if funcInlHeur, ok := fpmap[fn]; ok {
149 return funcInlHeur.props
150 } else if fn.Inl != nil && fn.Inl.Properties != "" {
151 // FIXME: considering adding some sort of cache or table
152 // for deserialized properties of imported functions.
153 return DeserializeFromString(fn.Inl.Properties)
158 func fnFileLine(fn *ir.Func) (string, uint) {
159 p := base.Ctxt.InnermostPos(fn.Pos())
160 return filepath.Base(p.Filename()), p.Line()
163 func UnitTesting() bool {
164 return base.Debug.DumpInlFuncProps != ""
167 // DumpFuncProps computes and caches function properties for the func
168 // 'fn' and any closures it contains, or if fn is nil, it writes out the
169 // cached set of properties to the file given in 'dumpfile'. Used for
170 // the "-d=dumpinlfuncprops=..." command line flag, intended for use
171 // primarily in unit testing.
172 func DumpFuncProps(fn *ir.Func, dumpfile string, canInline func(*ir.Func), inlineMaxBudget int32) {
174 enableDebugTraceIfEnv()
175 dmp := func(fn *ir.Func) {
176 if !goexperiment.NewInliner {
179 captureFuncDumpEntry(fn, canInline, inlineMaxBudget)
182 ir.Visit(fn, func(n ir.Node) {
183 if clo, ok := n.(*ir.ClosureExpr); ok {
189 emitDumpToFile(dumpfile)
193 // emitDumpToFile writes out the buffer function property dump entries
194 // to a file, for unit testing. Dump entries need to be sorted by
195 // definition line, and due to generics we need to account for the
196 // possibility that several ir.Func's will have the same def line.
197 func emitDumpToFile(dumpfile string) {
198 mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
199 if dumpfile[0] == '+' {
200 dumpfile = dumpfile[1:]
201 mode = os.O_WRONLY | os.O_APPEND | os.O_CREATE
203 if dumpfile[0] == '%' {
204 dumpfile = dumpfile[1:]
205 d, b := filepath.Dir(dumpfile), filepath.Base(dumpfile)
206 ptag := strings.ReplaceAll(types.LocalPkg.Path, "/", ":")
207 dumpfile = d + "/" + ptag + "." + b
209 outf, err := os.OpenFile(dumpfile, mode, 0644)
211 base.Fatalf("opening function props dump file %q: %v\n", dumpfile, err)
214 dumpFilePreamble(outf)
216 atline := map[uint]uint{}
217 sl := make([]fnInlHeur, 0, len(dumpBuffer))
218 for _, e := range dumpBuffer {
220 atline[e.line] = atline[e.line] + 1
222 sl = sortFnInlHeurSlice(sl)
225 for _, entry := range sl {
227 if prevline == entry.line {
230 prevline = entry.line
231 atl := atline[entry.line]
232 if err := dumpFnPreamble(outf, &entry, nil, idx, atl); err != nil {
233 base.Fatalf("function props dump: %v\n", err)
239 // captureFuncDumpEntry grabs the function properties object for 'fn'
240 // and enqueues it for later dumping. Used for the
241 // "-d=dumpinlfuncprops=..." command line flag, intended for use
242 // primarily in unit testing.
243 func captureFuncDumpEntry(fn *ir.Func, canInline func(*ir.Func), inlineMaxBudget int32) {
244 // avoid capturing compiler-generated equality funcs.
245 if strings.HasPrefix(fn.Sym().Name, ".eq.") {
248 funcInlHeur, ok := fpmap[fn]
249 // Props object should already be present, unless this is a
250 // directly recursive routine.
252 AnalyzeFunc(fn, canInline, inlineMaxBudget)
253 funcInlHeur = fpmap[fn]
254 if fn.Inl != nil && fn.Inl.Properties == "" {
255 fn.Inl.Properties = funcInlHeur.props.SerializeToString()
258 if dumpBuffer == nil {
259 dumpBuffer = make(map[*ir.Func]fnInlHeur)
261 if _, ok := dumpBuffer[fn]; ok {
262 // we can wind up seeing closures multiple times here,
263 // so don't add them more than once.
266 if debugTrace&debugTraceFuncs != 0 {
267 fmt.Fprintf(os.Stderr, "=-= capturing dump for %v:\n", fn)
269 dumpBuffer[fn] = funcInlHeur
272 // dumpFilePreamble writes out a file-level preamble for a given
273 // Go function as part of a function properties dump.
274 func dumpFilePreamble(w io.Writer) {
275 fmt.Fprintf(w, "// DO NOT EDIT (use 'go test -v -update-expected' instead.)\n")
276 fmt.Fprintf(w, "// See cmd/compile/internal/inline/inlheur/testdata/props/README.txt\n")
277 fmt.Fprintf(w, "// for more information on the format of this file.\n")
278 fmt.Fprintf(w, "// %s\n", preambleDelimiter)
281 // dumpFnPreamble writes out a function-level preamble for a given
282 // Go function as part of a function properties dump. See the
283 // README.txt file in testdata/props for more on the format of
285 func dumpFnPreamble(w io.Writer, funcInlHeur *fnInlHeur, ecst encodedCallSiteTab, idx, atl uint) error {
286 fmt.Fprintf(w, "// %s %s %d %d %d\n",
287 funcInlHeur.file, funcInlHeur.fname, funcInlHeur.line, idx, atl)
288 // emit props as comments, followed by delimiter
289 fmt.Fprintf(w, "%s// %s\n", funcInlHeur.props.ToString("// "), comDelimiter)
290 data, err := json.Marshal(funcInlHeur.props)
292 return fmt.Errorf("marshall error %v\n", err)
294 fmt.Fprintf(w, "// %s\n", string(data))
295 dumpCallSiteComments(w, funcInlHeur.cstab, ecst)
296 fmt.Fprintf(w, "// %s\n", fnDelimiter)
300 // sortFnInlHeurSlice sorts a slice of fnInlHeur based on
301 // the starting line of the function definition, then by name.
302 func sortFnInlHeurSlice(sl []fnInlHeur) []fnInlHeur {
303 sort.SliceStable(sl, func(i, j int) bool {
304 if sl[i].line != sl[j].line {
305 return sl[i].line < sl[j].line
307 return sl[i].fname < sl[j].fname
312 // delimiters written to various preambles to make parsing of
314 const preambleDelimiter = "<endfilepreamble>"
315 const fnDelimiter = "<endfuncpreamble>"
316 const comDelimiter = "<endpropsdump>"
317 const csDelimiter = "<endcallsites>"
319 // dumpBuffer stores up function properties dumps when
320 // "-d=dumpinlfuncprops=..." is in effect.
321 var dumpBuffer map[*ir.Func]fnInlHeur