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