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