]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
cmd/compile/inline/inleur: use "largest possible score" to revise inlinability
[gostls13.git] / src / cmd / compile / internal / inline / inl.go
1 // Copyright 2011 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 // The inlining facility makes 2 passes: first CanInline determines which
6 // functions are suitable for inlining, and for those that are it
7 // saves a copy of the body. Then InlineCalls walks each function body to
8 // expand calls to inlinable functions.
9 //
10 // The Debug.l flag controls the aggressiveness. Note that main() swaps level 0 and 1,
11 // making 1 the default and -l disable. Additional levels (beyond -l) may be buggy and
12 // are not supported.
13 //      0: disabled
14 //      1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
15 //      2: (unassigned)
16 //      3: (unassigned)
17 //      4: allow non-leaf functions
18 //
19 // At some point this may get another default and become switch-offable with -N.
20 //
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
23 //
24 // The Debug.m flag enables diagnostic output.  a single -m is useful for verifying
25 // which calls get inlined or not, more is for debugging, and may go away at any point.
26
27 package inline
28
29 import (
30         "fmt"
31         "go/constant"
32         "internal/goexperiment"
33         "strconv"
34
35         "cmd/compile/internal/base"
36         "cmd/compile/internal/inline/inlheur"
37         "cmd/compile/internal/ir"
38         "cmd/compile/internal/logopt"
39         "cmd/compile/internal/pgo"
40         "cmd/compile/internal/typecheck"
41         "cmd/compile/internal/types"
42         "cmd/internal/obj"
43 )
44
45 // Inlining budget parameters, gathered in one place
46 const (
47         inlineMaxBudget       = 80
48         inlineExtraAppendCost = 0
49         // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50         inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51         inlineExtraPanicCost = 1               // do not penalize inlining panics.
52         inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53
54         inlineBigFunctionNodes   = 5000 // Functions with this many nodes are considered "big".
55         inlineBigFunctionMaxCost = 20   // Max cost of inlinee when inlining into a "big" function.
56 )
57
58 var (
59         // List of all hot callee nodes.
60         // TODO(prattmic): Make this non-global.
61         candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62
63         // List of all hot call sites. CallSiteInfo.Callee is always nil.
64         // TODO(prattmic): Make this non-global.
65         candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66
67         // Threshold in percentage for hot callsite inlining.
68         inlineHotCallSiteThresholdPercent float64
69
70         // Threshold in CDF percentage for hot callsite inlining,
71         // that is, for a threshold of X the hottest callsites that
72         // make up the top X% of total edge weight will be
73         // considered hot for inlining candidates.
74         inlineCDFHotCallSiteThresholdPercent = float64(99)
75
76         // Budget increased due to hotness.
77         inlineHotMaxBudget int32 = 2000
78 )
79
80 // pgoInlinePrologue records the hot callsites from ir-graph.
81 func pgoInlinePrologue(p *pgo.Profile, funcs []*ir.Func) {
82         if base.Debug.PGOInlineCDFThreshold != "" {
83                 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
84                         inlineCDFHotCallSiteThresholdPercent = s
85                 } else {
86                         base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
87                 }
88         }
89         var hotCallsites []pgo.NamedCallEdge
90         inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
91         if base.Debug.PGODebug > 0 {
92                 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
93         }
94
95         if x := base.Debug.PGOInlineBudget; x != 0 {
96                 inlineHotMaxBudget = int32(x)
97         }
98
99         for _, n := range hotCallsites {
100                 // mark inlineable callees from hot edges
101                 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
102                         candHotCalleeMap[callee] = struct{}{}
103                 }
104                 // mark hot call sites
105                 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
106                         csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
107                         candHotEdgeMap[csi] = struct{}{}
108                 }
109         }
110
111         if base.Debug.PGODebug >= 3 {
112                 fmt.Printf("hot-cg before inline in dot format:")
113                 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
114         }
115 }
116
117 // hotNodesFromCDF computes an edge weight threshold and the list of hot
118 // nodes that make up the given percentage of the CDF. The threshold, as
119 // a percent, is the lower bound of weight for nodes to be considered hot
120 // (currently only used in debug prints) (in case of equal weights,
121 // comparing with the threshold may not accurately reflect which nodes are
122 // considiered hot).
123 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NamedCallEdge) {
124         cum := int64(0)
125         for i, n := range p.NamedEdgeMap.ByWeight {
126                 w := p.NamedEdgeMap.Weight[n]
127                 cum += w
128                 if pgo.WeightInPercentage(cum, p.TotalWeight) > inlineCDFHotCallSiteThresholdPercent {
129                         // nodes[:i+1] to include the very last node that makes it to go over the threshold.
130                         // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
131                         // include that node instead of excluding it.)
132                         return pgo.WeightInPercentage(w, p.TotalWeight), p.NamedEdgeMap.ByWeight[:i+1]
133                 }
134         }
135         return 0, p.NamedEdgeMap.ByWeight
136 }
137
138 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
139 func InlinePackage(p *pgo.Profile) {
140         if base.Debug.PGOInline == 0 {
141                 p = nil
142         }
143
144         InlineDecls(p, typecheck.Target.Funcs, true)
145
146         // Perform a garbage collection of hidden closures functions that
147         // are no longer reachable from top-level functions following
148         // inlining. See #59404 and #59638 for more context.
149         garbageCollectUnreferencedHiddenClosures()
150
151         if base.Debug.DumpInlFuncProps != "" {
152                 inlheur.DumpFuncProps(nil, base.Debug.DumpInlFuncProps, nil, inlineMaxBudget)
153         }
154         if goexperiment.NewInliner {
155                 postProcessCallSites(p)
156         }
157 }
158
159 // InlineDecls applies inlining to the given batch of declarations.
160 func InlineDecls(p *pgo.Profile, funcs []*ir.Func, doInline bool) {
161         if p != nil {
162                 pgoInlinePrologue(p, funcs)
163         }
164
165         doCanInline := func(n *ir.Func, recursive bool, numfns int) {
166                 if !recursive || numfns > 1 {
167                         // We allow inlining if there is no
168                         // recursion, or the recursion cycle is
169                         // across more than one function.
170                         CanInline(n, p)
171                 } else {
172                         if base.Flag.LowerM > 1 && n.OClosure == nil {
173                                 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
174                         }
175                 }
176         }
177
178         ir.VisitFuncsBottomUp(funcs, func(list []*ir.Func, recursive bool) {
179                 numfns := numNonClosures(list)
180                 // We visit functions within an SCC in fairly arbitrary order,
181                 // so by computing inlinability for all functions in the SCC
182                 // before performing any inlining, the results are less
183                 // sensitive to the order within the SCC (see #58905 for an
184                 // example).
185
186                 // First compute inlinability for all functions in the SCC ...
187                 for _, n := range list {
188                         doCanInline(n, recursive, numfns)
189                 }
190                 // ... then make a second pass to do inlining of calls.
191                 if doInline {
192                         for _, n := range list {
193                                 InlineCalls(n, p)
194                         }
195                 }
196         })
197 }
198
199 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
200 // top-level (non-hidden-closure) functions looking for nested closure
201 // functions that are reachable, then sweeps through the Target.Decls
202 // list and marks any non-reachable hidden closure function as dead.
203 // See issues #59404 and #59638 for more context.
204 func garbageCollectUnreferencedHiddenClosures() {
205
206         liveFuncs := make(map[*ir.Func]bool)
207
208         var markLiveFuncs func(fn *ir.Func)
209         markLiveFuncs = func(fn *ir.Func) {
210                 if liveFuncs[fn] {
211                         return
212                 }
213                 liveFuncs[fn] = true
214                 ir.Visit(fn, func(n ir.Node) {
215                         if clo, ok := n.(*ir.ClosureExpr); ok {
216                                 markLiveFuncs(clo.Func)
217                         }
218                 })
219         }
220
221         for i := 0; i < len(typecheck.Target.Funcs); i++ {
222                 fn := typecheck.Target.Funcs[i]
223                 if fn.IsHiddenClosure() {
224                         continue
225                 }
226                 markLiveFuncs(fn)
227         }
228
229         for i := 0; i < len(typecheck.Target.Funcs); i++ {
230                 fn := typecheck.Target.Funcs[i]
231                 if !fn.IsHiddenClosure() {
232                         continue
233                 }
234                 if fn.IsDeadcodeClosure() {
235                         continue
236                 }
237                 if liveFuncs[fn] {
238                         continue
239                 }
240                 fn.SetIsDeadcodeClosure(true)
241                 if base.Flag.LowerM > 2 {
242                         fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
243                 }
244                 if fn.Inl != nil && fn.LSym == nil {
245                         ir.InitLSym(fn, true)
246                 }
247         }
248 }
249
250 // inlineBudget determines the max budget for function 'fn' prior to
251 // analyzing the hairyness of the body of 'fn'. We pass in the pgo
252 // profile if available (which can change the budget), also a
253 // 'relaxed' flag, which expands the budget slightly to allow for the
254 // possibility that a call to the function might have its score
255 // adjusted downwards. If 'verbose' is set, then print a remark where
256 // we boost the budget due to PGO.
257 func inlineBudget(fn *ir.Func, profile *pgo.Profile, relaxed bool, verbose bool) int32 {
258         // Update the budget for profile-guided inlining.
259         budget := int32(inlineMaxBudget)
260         if profile != nil {
261                 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
262                         if _, ok := candHotCalleeMap[n]; ok {
263                                 budget = int32(inlineHotMaxBudget)
264                                 if verbose {
265                                         fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
266                                 }
267                         }
268                 }
269         }
270         if relaxed {
271                 budget += inlineMaxBudget
272         }
273         return budget
274 }
275
276 // CanInline determines whether fn is inlineable.
277 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
278 // fn and fn.Body will already have been typechecked.
279 func CanInline(fn *ir.Func, profile *pgo.Profile) {
280         if fn.Nname == nil {
281                 base.Fatalf("CanInline no nname %+v", fn)
282         }
283
284         var funcProps *inlheur.FuncProps
285         if goexperiment.NewInliner || inlheur.UnitTesting() {
286                 callCanInline := func(fn *ir.Func) { CanInline(fn, profile) }
287                 funcProps = inlheur.AnalyzeFunc(fn, callCanInline, inlineMaxBudget)
288                 budgetForFunc := func(fn *ir.Func) int32 {
289                         return inlineBudget(fn, profile, true, false)
290                 }
291                 defer func() { inlheur.RevisitInlinability(fn, budgetForFunc) }()
292         }
293
294         var reason string // reason, if any, that the function was not inlined
295         if base.Flag.LowerM > 1 || logopt.Enabled() {
296                 defer func() {
297                         if reason != "" {
298                                 if base.Flag.LowerM > 1 {
299                                         fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
300                                 }
301                                 if logopt.Enabled() {
302                                         logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
303                                 }
304                         }
305                 }()
306         }
307
308         reason = InlineImpossible(fn)
309         if reason != "" {
310                 return
311         }
312         if fn.Typecheck() == 0 {
313                 base.Fatalf("CanInline on non-typechecked function %v", fn)
314         }
315
316         n := fn.Nname
317         if n.Func.InlinabilityChecked() {
318                 return
319         }
320         defer n.Func.SetInlinabilityChecked(true)
321
322         cc := int32(inlineExtraCallCost)
323         if base.Flag.LowerL == 4 {
324                 cc = 1 // this appears to yield better performance than 0.
325         }
326
327         // Used a "relaxed" inline budget if goexperiment.NewInliner is in
328         // effect, or if we're producing a debugging dump.
329         relaxed := goexperiment.NewInliner ||
330                 (base.Debug.DumpInlFuncProps != "" ||
331                         base.Debug.DumpInlCallSiteScores != 0)
332
333         // Compute the inline budget for this func.
334         budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
335
336         // At this point in the game the function we're looking at may
337         // have "stale" autos, vars that still appear in the Dcl list, but
338         // which no longer have any uses in the function body (due to
339         // elimination by deadcode). We'd like to exclude these dead vars
340         // when creating the "Inline.Dcl" field below; to accomplish this,
341         // the hairyVisitor below builds up a map of used/referenced
342         // locals, and we use this map to produce a pruned Inline.Dcl
343         // list. See issue 25459 for more context.
344
345         visitor := hairyVisitor{
346                 curFunc:       fn,
347                 isBigFunc:     isBigFunc(fn),
348                 budget:        budget,
349                 maxBudget:     budget,
350                 extraCallCost: cc,
351                 profile:       profile,
352         }
353         if visitor.tooHairy(fn) {
354                 reason = visitor.reason
355                 return
356         }
357
358         n.Func.Inl = &ir.Inline{
359                 Cost:    budget - visitor.budget,
360                 Dcl:     pruneUnusedAutos(n.Func.Dcl, &visitor),
361                 HaveDcl: true,
362
363                 CanDelayResults: canDelayResults(fn),
364         }
365         if goexperiment.NewInliner {
366                 n.Func.Inl.Properties = funcProps.SerializeToString()
367         }
368
369         if base.Flag.LowerM > 1 {
370                 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(fn.Body))
371         } else if base.Flag.LowerM != 0 {
372                 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
373         }
374         if logopt.Enabled() {
375                 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
376         }
377 }
378
379 // InlineImpossible returns a non-empty reason string if fn is impossible to
380 // inline regardless of cost or contents.
381 func InlineImpossible(fn *ir.Func) string {
382         var reason string // reason, if any, that the function can not be inlined.
383         if fn.Nname == nil {
384                 reason = "no name"
385                 return reason
386         }
387
388         // If marked "go:noinline", don't inline.
389         if fn.Pragma&ir.Noinline != 0 {
390                 reason = "marked go:noinline"
391                 return reason
392         }
393
394         // If marked "go:norace" and -race compilation, don't inline.
395         if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
396                 reason = "marked go:norace with -race compilation"
397                 return reason
398         }
399
400         // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
401         if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
402                 reason = "marked go:nocheckptr"
403                 return reason
404         }
405
406         // If marked "go:cgo_unsafe_args", don't inline, since the function
407         // makes assumptions about its argument frame layout.
408         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
409                 reason = "marked go:cgo_unsafe_args"
410                 return reason
411         }
412
413         // If marked as "go:uintptrkeepalive", don't inline, since the keep
414         // alive information is lost during inlining.
415         //
416         // TODO(prattmic): This is handled on calls during escape analysis,
417         // which is after inlining. Move prior to inlining so the keep-alive is
418         // maintained after inlining.
419         if fn.Pragma&ir.UintptrKeepAlive != 0 {
420                 reason = "marked as having a keep-alive uintptr argument"
421                 return reason
422         }
423
424         // If marked as "go:uintptrescapes", don't inline, since the escape
425         // information is lost during inlining.
426         if fn.Pragma&ir.UintptrEscapes != 0 {
427                 reason = "marked as having an escaping uintptr argument"
428                 return reason
429         }
430
431         // The nowritebarrierrec checker currently works at function
432         // granularity, so inlining yeswritebarrierrec functions can confuse it
433         // (#22342). As a workaround, disallow inlining them for now.
434         if fn.Pragma&ir.Yeswritebarrierrec != 0 {
435                 reason = "marked go:yeswritebarrierrec"
436                 return reason
437         }
438
439         // If a local function has no fn.Body (is defined outside of Go), cannot inline it.
440         // Imported functions don't have fn.Body but might have inline body in fn.Inl.
441         if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
442                 reason = "no function body"
443                 return reason
444         }
445
446         return ""
447 }
448
449 // canDelayResults reports whether inlined calls to fn can delay
450 // declaring the result parameter until the "return" statement.
451 func canDelayResults(fn *ir.Func) bool {
452         // We can delay declaring+initializing result parameters if:
453         // (1) there's exactly one "return" statement in the inlined function;
454         // (2) it's not an empty return statement (#44355); and
455         // (3) the result parameters aren't named.
456
457         nreturns := 0
458         ir.VisitList(fn.Body, func(n ir.Node) {
459                 if n, ok := n.(*ir.ReturnStmt); ok {
460                         nreturns++
461                         if len(n.Results) == 0 {
462                                 nreturns++ // empty return statement (case 2)
463                         }
464                 }
465         })
466
467         if nreturns != 1 {
468                 return false // not exactly one return statement (case 1)
469         }
470
471         // temporaries for return values.
472         for _, param := range fn.Type().Results() {
473                 if sym := param.Sym; sym != nil && !sym.IsBlank() {
474                         return false // found a named result parameter (case 3)
475                 }
476         }
477
478         return true
479 }
480
481 // hairyVisitor visits a function body to determine its inlining
482 // hairiness and whether or not it can be inlined.
483 type hairyVisitor struct {
484         // This is needed to access the current caller in the doNode function.
485         curFunc       *ir.Func
486         isBigFunc     bool
487         budget        int32
488         maxBudget     int32
489         reason        string
490         extraCallCost int32
491         usedLocals    ir.NameSet
492         do            func(ir.Node) bool
493         profile       *pgo.Profile
494 }
495
496 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
497         v.do = v.doNode // cache closure
498         if ir.DoChildren(fn, v.do) {
499                 return true
500         }
501         if v.budget < 0 {
502                 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
503                 return true
504         }
505         return false
506 }
507
508 // doNode visits n and its children, updates the state in v, and returns true if
509 // n makes the current function too hairy for inlining.
510 func (v *hairyVisitor) doNode(n ir.Node) bool {
511         if n == nil {
512                 return false
513         }
514 opSwitch:
515         switch n.Op() {
516         // Call is okay if inlinable and we have the budget for the body.
517         case ir.OCALLFUNC:
518                 n := n.(*ir.CallExpr)
519                 // Functions that call runtime.getcaller{pc,sp} can not be inlined
520                 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
521                 //
522                 // runtime.throw is a "cheap call" like panic in normal code.
523                 var cheap bool
524                 if n.Fun.Op() == ir.ONAME {
525                         name := n.Fun.(*ir.Name)
526                         if name.Class == ir.PFUNC {
527                                 switch fn := types.RuntimeSymName(name.Sym()); fn {
528                                 case "getcallerpc", "getcallersp":
529                                         v.reason = "call to " + fn
530                                         return true
531                                 case "throw":
532                                         v.budget -= inlineExtraThrowCost
533                                         break opSwitch
534                                 }
535                                 // Special case for reflect.noescape. It does just type
536                                 // conversions to appease the escape analysis, and doesn't
537                                 // generate code.
538                                 if types.ReflectSymName(name.Sym()) == "noescape" {
539                                         cheap = true
540                                 }
541                         }
542                         // Special case for coverage counter updates; although
543                         // these correspond to real operations, we treat them as
544                         // zero cost for the moment. This is due to the existence
545                         // of tests that are sensitive to inlining-- if the
546                         // insertion of coverage instrumentation happens to tip a
547                         // given function over the threshold and move it from
548                         // "inlinable" to "not-inlinable", this can cause changes
549                         // in allocation behavior, which can then result in test
550                         // failures (a good example is the TestAllocations in
551                         // crypto/ed25519).
552                         if isAtomicCoverageCounterUpdate(n) {
553                                 return false
554                         }
555                 }
556                 if n.Fun.Op() == ir.OMETHEXPR {
557                         if meth := ir.MethodExprName(n.Fun); meth != nil {
558                                 if fn := meth.Func; fn != nil {
559                                         s := fn.Sym()
560                                         if types.RuntimeSymName(s) == "heapBits.nextArena" {
561                                                 // Special case: explicitly allow mid-stack inlining of
562                                                 // runtime.heapBits.next even though it calls slow-path
563                                                 // runtime.heapBits.nextArena.
564                                                 cheap = true
565                                         }
566                                         // Special case: on architectures that can do unaligned loads,
567                                         // explicitly mark encoding/binary methods as cheap,
568                                         // because in practice they are, even though our inlining
569                                         // budgeting system does not see that. See issue 42958.
570                                         if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
571                                                 switch s.Name {
572                                                 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
573                                                         "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
574                                                         "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
575                                                         "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
576                                                         "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
577                                                         "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
578                                                         cheap = true
579                                                 }
580                                         }
581                                 }
582                         }
583                 }
584                 if cheap {
585                         break // treat like any other node, that is, cost of 1
586                 }
587
588                 if ir.IsIntrinsicCall(n) {
589                         // Treat like any other node.
590                         break
591                 }
592
593                 if callee := inlCallee(v.curFunc, n.Fun, v.profile); callee != nil && typecheck.HaveInlineBody(callee) {
594                         // Check whether we'd actually inline this call. Set
595                         // log == false since we aren't actually doing inlining
596                         // yet.
597                         if canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false) {
598                                 // mkinlcall would inline this call [1], so use
599                                 // the cost of the inline body as the cost of
600                                 // the call, as that is what will actually
601                                 // appear in the code.
602                                 //
603                                 // [1] This is almost a perfect match to the
604                                 // mkinlcall logic, except that
605                                 // canInlineCallExpr considers inlining cycles
606                                 // by looking at what has already been inlined.
607                                 // Since we haven't done any inlining yet we
608                                 // will miss those.
609                                 v.budget -= callee.Inl.Cost
610                                 break
611                         }
612                 }
613
614                 // Call cost for non-leaf inlining.
615                 v.budget -= v.extraCallCost
616
617         case ir.OCALLMETH:
618                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
619
620         // Things that are too hairy, irrespective of the budget
621         case ir.OCALL, ir.OCALLINTER:
622                 // Call cost for non-leaf inlining.
623                 v.budget -= v.extraCallCost
624
625         case ir.OPANIC:
626                 n := n.(*ir.UnaryExpr)
627                 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
628                         // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
629                         // Before CL 284412, these conversions were introduced later in the
630                         // compiler, so they didn't count against inlining budget.
631                         v.budget++
632                 }
633                 v.budget -= inlineExtraPanicCost
634
635         case ir.ORECOVER:
636                 base.FatalfAt(n.Pos(), "ORECOVER missed typecheck")
637         case ir.ORECOVERFP:
638                 // recover matches the argument frame pointer to find
639                 // the right panic value, so it needs an argument frame.
640                 v.reason = "call to recover"
641                 return true
642
643         case ir.OCLOSURE:
644                 if base.Debug.InlFuncsWithClosures == 0 {
645                         v.reason = "not inlining functions with closures"
646                         return true
647                 }
648
649                 // TODO(danscales): Maybe make budget proportional to number of closure
650                 // variables, e.g.:
651                 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
652                 // TODO(austin): However, if we're able to inline this closure into
653                 // v.curFunc, then we actually pay nothing for the closure captures. We
654                 // should try to account for that if we're going to account for captures.
655                 v.budget -= 15
656
657         case ir.OGO, ir.ODEFER, ir.OTAILCALL:
658                 v.reason = "unhandled op " + n.Op().String()
659                 return true
660
661         case ir.OAPPEND:
662                 v.budget -= inlineExtraAppendCost
663
664         case ir.OADDR:
665                 n := n.(*ir.AddrExpr)
666                 // Make "&s.f" cost 0 when f's offset is zero.
667                 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
668                         if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
669                                 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
670                         }
671                 }
672
673         case ir.ODEREF:
674                 // *(*X)(unsafe.Pointer(&x)) is low-cost
675                 n := n.(*ir.StarExpr)
676
677                 ptr := n.X
678                 for ptr.Op() == ir.OCONVNOP {
679                         ptr = ptr.(*ir.ConvExpr).X
680                 }
681                 if ptr.Op() == ir.OADDR {
682                         v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
683                 }
684
685         case ir.OCONVNOP:
686                 // This doesn't produce code, but the children might.
687                 v.budget++ // undo default cost
688
689         case ir.OFALL, ir.OTYPE:
690                 // These nodes don't produce code; omit from inlining budget.
691                 return false
692
693         case ir.OIF:
694                 n := n.(*ir.IfStmt)
695                 if ir.IsConst(n.Cond, constant.Bool) {
696                         // This if and the condition cost nothing.
697                         if doList(n.Init(), v.do) {
698                                 return true
699                         }
700                         if ir.BoolVal(n.Cond) {
701                                 return doList(n.Body, v.do)
702                         } else {
703                                 return doList(n.Else, v.do)
704                         }
705                 }
706
707         case ir.ONAME:
708                 n := n.(*ir.Name)
709                 if n.Class == ir.PAUTO {
710                         v.usedLocals.Add(n)
711                 }
712
713         case ir.OBLOCK:
714                 // The only OBLOCK we should see at this point is an empty one.
715                 // In any event, let the visitList(n.List()) below take care of the statements,
716                 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
717                 v.budget++
718
719         case ir.OMETHVALUE, ir.OSLICELIT:
720                 v.budget-- // Hack for toolstash -cmp.
721
722         case ir.OMETHEXPR:
723                 v.budget++ // Hack for toolstash -cmp.
724
725         case ir.OAS2:
726                 n := n.(*ir.AssignListStmt)
727
728                 // Unified IR unconditionally rewrites:
729                 //
730                 //      a, b = f()
731                 //
732                 // into:
733                 //
734                 //      DCL tmp1
735                 //      DCL tmp2
736                 //      tmp1, tmp2 = f()
737                 //      a, b = tmp1, tmp2
738                 //
739                 // so that it can insert implicit conversions as necessary. To
740                 // minimize impact to the existing inlining heuristics (in
741                 // particular, to avoid breaking the existing inlinability regress
742                 // tests), we need to compensate for this here.
743                 //
744                 // See also identical logic in isBigFunc.
745                 if init := n.Rhs[0].Init(); len(init) == 1 {
746                         if _, ok := init[0].(*ir.AssignListStmt); ok {
747                                 // 4 for each value, because each temporary variable now
748                                 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
749                                 //
750                                 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
751                                 v.budget += 4*int32(len(n.Lhs)) + 1
752                         }
753                 }
754
755         case ir.OAS:
756                 // Special case for coverage counter updates and coverage
757                 // function registrations. Although these correspond to real
758                 // operations, we treat them as zero cost for the moment. This
759                 // is primarily due to the existence of tests that are
760                 // sensitive to inlining-- if the insertion of coverage
761                 // instrumentation happens to tip a given function over the
762                 // threshold and move it from "inlinable" to "not-inlinable",
763                 // this can cause changes in allocation behavior, which can
764                 // then result in test failures (a good example is the
765                 // TestAllocations in crypto/ed25519).
766                 n := n.(*ir.AssignStmt)
767                 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
768                         return false
769                 }
770         }
771
772         v.budget--
773
774         // When debugging, don't stop early, to get full cost of inlining this function
775         if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
776                 v.reason = "too expensive"
777                 return true
778         }
779
780         return ir.DoChildren(n, v.do)
781 }
782
783 func isBigFunc(fn *ir.Func) bool {
784         budget := inlineBigFunctionNodes
785         return ir.Any(fn, func(n ir.Node) bool {
786                 // See logic in hairyVisitor.doNode, explaining unified IR's
787                 // handling of "a, b = f()" assignments.
788                 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
789                         if init := n.Rhs[0].Init(); len(init) == 1 {
790                                 if _, ok := init[0].(*ir.AssignListStmt); ok {
791                                         budget += 4*len(n.Lhs) + 1
792                                 }
793                         }
794                 }
795
796                 budget--
797                 return budget <= 0
798         })
799 }
800
801 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
802 // calls made to inlineable functions. This is the external entry point.
803 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
804         if goexperiment.NewInliner && !fn.Wrapper() {
805                 inlheur.ScoreCalls(fn)
806         }
807         if base.Debug.DumpInlFuncProps != "" && !fn.Wrapper() {
808                 inlheur.DumpFuncProps(fn, base.Debug.DumpInlFuncProps,
809                         func(fn *ir.Func) { CanInline(fn, profile) }, inlineMaxBudget)
810         }
811         savefn := ir.CurFunc
812         ir.CurFunc = fn
813         bigCaller := isBigFunc(fn)
814         if bigCaller && base.Flag.LowerM > 1 {
815                 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
816         }
817         var inlCalls []*ir.InlinedCallExpr
818         var edit func(ir.Node) ir.Node
819         edit = func(n ir.Node) ir.Node {
820                 return inlnode(fn, n, bigCaller, &inlCalls, edit, profile)
821         }
822         ir.EditChildren(fn, edit)
823
824         // If we inlined any calls, we want to recursively visit their
825         // bodies for further inlining. However, we need to wait until
826         // *after* the original function body has been expanded, or else
827         // inlCallee can have false positives (e.g., #54632).
828         for len(inlCalls) > 0 {
829                 call := inlCalls[0]
830                 inlCalls = inlCalls[1:]
831                 ir.EditChildren(call, edit)
832         }
833
834         ir.CurFunc = savefn
835 }
836
837 // inlnode recurses over the tree to find inlineable calls, which will
838 // be turned into OINLCALLs by mkinlcall. When the recursion comes
839 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
840 // nbody and nelse and use one of the 4 inlconv/glue functions above
841 // to turn the OINLCALL into an expression, a statement, or patch it
842 // in to this nodes list or rlist as appropriate.
843 // NOTE it makes no sense to pass the glue functions down the
844 // recursion to the level where the OINLCALL gets created because they
845 // have to edit /this/ n, so you'd have to push that one down as well,
846 // but then you may as well do it here.  so this is cleaner and
847 // shorter and less complicated.
848 // The result of inlnode MUST be assigned back to n, e.g.
849 //
850 //      n.Left = inlnode(n.Left)
851 func inlnode(callerfn *ir.Func, n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
852         if n == nil {
853                 return n
854         }
855
856         switch n.Op() {
857         case ir.ODEFER, ir.OGO:
858                 n := n.(*ir.GoDeferStmt)
859                 switch call := n.Call; call.Op() {
860                 case ir.OCALLMETH:
861                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
862                 case ir.OCALLFUNC:
863                         call := call.(*ir.CallExpr)
864                         call.NoInline = true
865                 }
866         case ir.OTAILCALL:
867                 n := n.(*ir.TailCallStmt)
868                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
869
870         // TODO do them here (or earlier),
871         // so escape analysis can avoid more heapmoves.
872         case ir.OCLOSURE:
873                 return n
874         case ir.OCALLMETH:
875                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
876         case ir.OCALLFUNC:
877                 n := n.(*ir.CallExpr)
878                 if n.Fun.Op() == ir.OMETHEXPR {
879                         // Prevent inlining some reflect.Value methods when using checkptr,
880                         // even when package reflect was compiled without it (#35073).
881                         if meth := ir.MethodExprName(n.Fun); meth != nil {
882                                 s := meth.Sym()
883                                 if base.Debug.Checkptr != 0 {
884                                         switch types.ReflectSymName(s) {
885                                         case "Value.UnsafeAddr", "Value.Pointer":
886                                                 return n
887                                         }
888                                 }
889                         }
890                 }
891         }
892
893         lno := ir.SetPos(n)
894
895         ir.EditChildren(n, edit)
896
897         // with all the branches out of the way, it is now time to
898         // transmogrify this node itself unless inhibited by the
899         // switch at the top of this function.
900         switch n.Op() {
901         case ir.OCALLMETH:
902                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
903
904         case ir.OCALLFUNC:
905                 call := n.(*ir.CallExpr)
906                 if call.NoInline {
907                         break
908                 }
909                 if base.Flag.LowerM > 3 {
910                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.Fun)
911                 }
912                 if ir.IsIntrinsicCall(call) {
913                         break
914                 }
915                 if fn := inlCallee(callerfn, call.Fun, profile); fn != nil && typecheck.HaveInlineBody(fn) {
916                         n = mkinlcall(callerfn, call, fn, bigCaller, inlCalls)
917                 }
918         }
919
920         base.Pos = lno
921
922         return n
923 }
924
925 // inlCallee takes a function-typed expression and returns the underlying function ONAME
926 // that it refers to if statically known. Otherwise, it returns nil.
927 func inlCallee(caller *ir.Func, fn ir.Node, profile *pgo.Profile) (res *ir.Func) {
928         fn = ir.StaticValue(fn)
929         switch fn.Op() {
930         case ir.OMETHEXPR:
931                 fn := fn.(*ir.SelectorExpr)
932                 n := ir.MethodExprName(fn)
933                 // Check that receiver type matches fn.X.
934                 // TODO(mdempsky): Handle implicit dereference
935                 // of pointer receiver argument?
936                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
937                         return nil
938                 }
939                 return n.Func
940         case ir.ONAME:
941                 fn := fn.(*ir.Name)
942                 if fn.Class == ir.PFUNC {
943                         return fn.Func
944                 }
945         case ir.OCLOSURE:
946                 fn := fn.(*ir.ClosureExpr)
947                 c := fn.Func
948                 if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
949                         return nil // inliner doesn't support inlining across closure frames
950                 }
951                 CanInline(c, profile)
952                 return c
953         }
954         return nil
955 }
956
957 var inlgen int
958
959 // SSADumpInline gives the SSA back end a chance to dump the function
960 // when producing output for debugging the compiler itself.
961 var SSADumpInline = func(*ir.Func) {}
962
963 // InlineCall allows the inliner implementation to be overridden.
964 // If it returns nil, the function will not be inlined.
965 var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
966         base.Fatalf("inline.InlineCall not overridden")
967         panic("unreachable")
968 }
969
970 // inlineCostOK returns true if call n from caller to callee is cheap enough to
971 // inline. bigCaller indicates that caller is a big function.
972 //
973 // If inlineCostOK returns false, it also returns the max cost that the callee
974 // exceeded.
975 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
976         maxCost := int32(inlineMaxBudget)
977         if bigCaller {
978                 // We use this to restrict inlining into very big functions.
979                 // See issue 26546 and 17566.
980                 maxCost = inlineBigFunctionMaxCost
981         }
982
983         metric := callee.Inl.Cost
984         if goexperiment.NewInliner {
985                 score, ok := inlheur.GetCallSiteScore(caller, n)
986                 if ok {
987                         metric = int32(score)
988                 }
989
990         }
991
992         if metric <= maxCost {
993                 // Simple case. Function is already cheap enough.
994                 return true, 0
995         }
996
997         // We'll also allow inlining of hot functions below inlineHotMaxBudget,
998         // but only in small functions.
999
1000         lineOffset := pgo.NodeLineOffset(n, caller)
1001         csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
1002         if _, ok := candHotEdgeMap[csi]; !ok {
1003                 // Cold
1004                 return false, maxCost
1005         }
1006
1007         // Hot
1008
1009         if bigCaller {
1010                 if base.Debug.PGODebug > 0 {
1011                         fmt.Printf("hot-big check disallows inlining for call %s (cost %d) at %v in big function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1012                 }
1013                 return false, maxCost
1014         }
1015
1016         if metric > inlineHotMaxBudget {
1017                 return false, inlineHotMaxBudget
1018         }
1019
1020         if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
1021                 // De-selected by PGO Hash.
1022                 return false, maxCost
1023         }
1024
1025         if base.Debug.PGODebug > 0 {
1026                 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1027         }
1028
1029         return true, 0
1030 }
1031
1032 // canInlineCallsite returns true if the call n from caller to callee can be
1033 // inlined. bigCaller indicates that caller is a big function. log indicates
1034 // that the 'cannot inline' reason should be logged.
1035 //
1036 // Preconditions: CanInline(callee) has already been called.
1037 func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller bool, log bool) bool {
1038         if callee.Inl == nil {
1039                 // callee is never inlinable.
1040                 if log && logopt.Enabled() {
1041                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1042                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
1043                 }
1044                 return false
1045         }
1046
1047         if ok, maxCost := inlineCostOK(n, callerfn, callee, bigCaller); !ok {
1048                 // callee cost too high for this call site.
1049                 if log && logopt.Enabled() {
1050                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1051                                 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
1052                 }
1053                 return false
1054         }
1055
1056         if callee == callerfn {
1057                 // Can't recursively inline a function into itself.
1058                 if log && logopt.Enabled() {
1059                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
1060                 }
1061                 return false
1062         }
1063
1064         if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
1065                 // Runtime package must not be instrumented.
1066                 // Instrument skips runtime package. However, some runtime code can be
1067                 // inlined into other packages and instrumented there. To avoid this,
1068                 // we disable inlining of runtime functions when instrumenting.
1069                 // The example that we observed is inlining of LockOSThread,
1070                 // which lead to false race reports on m contents.
1071                 if log && logopt.Enabled() {
1072                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1073                                 fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
1074                 }
1075                 return false
1076         }
1077
1078         if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
1079                 if log && logopt.Enabled() {
1080                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1081                                 fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
1082                 }
1083                 return false
1084         }
1085
1086         // Check if we've already inlined this function at this particular
1087         // call site, in order to stop inlining when we reach the beginning
1088         // of a recursion cycle again. We don't inline immediately recursive
1089         // functions, but allow inlining if there is a recursion cycle of
1090         // many functions. Most likely, the inlining will stop before we
1091         // even hit the beginning of the cycle again, but this catches the
1092         // unusual case.
1093         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1094         sym := callee.Linksym()
1095         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1096                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1097                         if log {
1098                                 if base.Flag.LowerM > 1 {
1099                                         fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
1100                                 }
1101                                 if logopt.Enabled() {
1102                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1103                                                 fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
1104                                 }
1105                         }
1106                         return false
1107                 }
1108         }
1109
1110         return true
1111 }
1112
1113 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1114 // function with an inlinable body, return an OINLCALL node that can replace n.
1115 // The returned node's Ninit has the parameter assignments, the Nbody is the
1116 // inlined function body, and (List, Rlist) contain the (input, output)
1117 // parameters.
1118 // The result of mkinlcall MUST be assigned back to n, e.g.
1119 //
1120 //      n.Left = mkinlcall(n.Left, fn, isddd)
1121 func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1122         if !canInlineCallExpr(callerfn, n, fn, bigCaller, true) {
1123                 return n
1124         }
1125         typecheck.AssertFixedCall(n)
1126
1127         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1128         sym := fn.Linksym()
1129         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1130
1131         closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1132                 // The linker needs FuncInfo metadata for all inlined
1133                 // functions. This is typically handled by gc.enqueueFunc
1134                 // calling ir.InitLSym for all function declarations in
1135                 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1136                 // Decls).
1137                 //
1138                 // However, non-trivial closures in Decls are ignored, and are
1139                 // insteaded enqueued when walk of the calling function
1140                 // discovers them.
1141                 //
1142                 // This presents a problem for direct calls to closures.
1143                 // Inlining will replace the entire closure definition with its
1144                 // body, which hides the closure from walk and thus suppresses
1145                 // symbol creation.
1146                 //
1147                 // Explicitly create a symbol early in this edge case to ensure
1148                 // we keep this metadata.
1149                 //
1150                 // TODO: Refactor to keep a reference so this can all be done
1151                 // by enqueueFunc.
1152
1153                 if n.Op() != ir.OCALLFUNC {
1154                         // Not a standard call.
1155                         return
1156                 }
1157                 if n.Fun.Op() != ir.OCLOSURE {
1158                         // Not a direct closure call.
1159                         return
1160                 }
1161
1162                 clo := n.Fun.(*ir.ClosureExpr)
1163                 if ir.IsTrivialClosure(clo) {
1164                         // enqueueFunc will handle trivial closures anyways.
1165                         return
1166                 }
1167
1168                 ir.InitLSym(fn, true)
1169         }
1170
1171         closureInitLSym(n, fn)
1172
1173         if base.Flag.GenDwarfInl > 0 {
1174                 if !sym.WasInlined() {
1175                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1176                         sym.Set(obj.AttrWasInlined, true)
1177                 }
1178         }
1179
1180         if base.Flag.LowerM != 0 {
1181                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1182         }
1183         if base.Flag.LowerM > 2 {
1184                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1185         }
1186
1187         res := InlineCall(callerfn, n, fn, inlIndex)
1188
1189         if res == nil {
1190                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1191         }
1192
1193         if base.Flag.LowerM > 2 {
1194                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1195         }
1196
1197         *inlCalls = append(*inlCalls, res)
1198
1199         return res
1200 }
1201
1202 // CalleeEffects appends any side effects from evaluating callee to init.
1203 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1204         for {
1205                 init.Append(ir.TakeInit(callee)...)
1206
1207                 switch callee.Op() {
1208                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1209                         return // done
1210
1211                 case ir.OCONVNOP:
1212                         conv := callee.(*ir.ConvExpr)
1213                         callee = conv.X
1214
1215                 case ir.OINLCALL:
1216                         ic := callee.(*ir.InlinedCallExpr)
1217                         init.Append(ic.Body.Take()...)
1218                         callee = ic.SingleResult()
1219
1220                 default:
1221                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1222                 }
1223         }
1224 }
1225
1226 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1227         s := make([]*ir.Name, 0, len(ll))
1228         for _, n := range ll {
1229                 if n.Class == ir.PAUTO {
1230                         if !vis.usedLocals.Has(n) {
1231                                 // TODO(mdempsky): Simplify code after confident that this
1232                                 // never happens anymore.
1233                                 base.FatalfAt(n.Pos(), "unused auto: %v", n)
1234                                 continue
1235                         }
1236                 }
1237                 s = append(s, n)
1238         }
1239         return s
1240 }
1241
1242 // numNonClosures returns the number of functions in list which are not closures.
1243 func numNonClosures(list []*ir.Func) int {
1244         count := 0
1245         for _, fn := range list {
1246                 if fn.OClosure == nil {
1247                         count++
1248                 }
1249         }
1250         return count
1251 }
1252
1253 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1254         for _, x := range list {
1255                 if x != nil {
1256                         if do(x) {
1257                                 return true
1258                         }
1259                 }
1260         }
1261         return false
1262 }
1263
1264 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1265 // into a coverage counter array.
1266 func isIndexingCoverageCounter(n ir.Node) bool {
1267         if n.Op() != ir.OINDEX {
1268                 return false
1269         }
1270         ixn := n.(*ir.IndexExpr)
1271         if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1272                 return false
1273         }
1274         nn := ixn.X.(*ir.Name)
1275         return nn.CoverageCounter()
1276 }
1277
1278 // isAtomicCoverageCounterUpdate examines the specified node to
1279 // determine whether it represents a call to sync/atomic.AddUint32 to
1280 // increment a coverage counter.
1281 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1282         if cn.Fun.Op() != ir.ONAME {
1283                 return false
1284         }
1285         name := cn.Fun.(*ir.Name)
1286         if name.Class != ir.PFUNC {
1287                 return false
1288         }
1289         fn := name.Sym().Name
1290         if name.Sym().Pkg.Path != "sync/atomic" ||
1291                 (fn != "AddUint32" && fn != "StoreUint32") {
1292                 return false
1293         }
1294         if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1295                 return false
1296         }
1297         adn := cn.Args[0].(*ir.AddrExpr)
1298         v := isIndexingCoverageCounter(adn.X)
1299         return v
1300 }
1301
1302 func postProcessCallSites(profile *pgo.Profile) {
1303         if base.Debug.DumpInlCallSiteScores != 0 {
1304                 budgetCallback := func(fn *ir.Func, prof *pgo.Profile) (int32, bool) {
1305                         v := inlineBudget(fn, prof, false, false)
1306                         return v, v == inlineHotMaxBudget
1307                 }
1308                 inlheur.DumpInlCallSiteScores(profile, budgetCallback)
1309         }
1310 }