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