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