]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
cmd/compile: use edge weights to decide inlineability in PGO
[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         "strconv"
33         "strings"
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         "cmd/internal/src"
43 )
44
45 // Inlining budget parameters, gathered in one place
46 const (
47         inlineMaxBudget       = 80
48         inlineExtraAppendCost = 0
49         // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50         inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51         inlineExtraPanicCost = 1               // do not penalize inlining panics.
52         inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53
54         inlineBigFunctionNodes   = 5000 // Functions with this many nodes are considered "big".
55         inlineBigFunctionMaxCost = 20   // Max cost of inlinee when inlining into a "big" function.
56 )
57
58 var (
59         // List of all hot callee nodes.
60         // TODO(prattmic): Make this non-global.
61         candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62
63         // List of all hot call sites. CallSiteInfo.Callee is always nil.
64         // TODO(prattmic): Make this non-global.
65         candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66
67         // List of inlined call sites. CallSiteInfo.Callee is always nil.
68         // TODO(prattmic): Make this non-global.
69         inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
70
71         // Threshold in percentage for hot callsite inlining.
72         inlineHotCallSiteThresholdPercent = float64(0.1)
73
74         // Budget increased due to hotness.
75         inlineHotMaxBudget int32 = 160
76 )
77
78 // pgoInlinePrologue records the hot callsites from ir-graph.
79 func pgoInlinePrologue(p *pgo.Profile) {
80         if s, err := strconv.ParseFloat(base.Debug.InlineHotCallSiteThreshold, 64); err == nil {
81                 inlineHotCallSiteThresholdPercent = s
82                 if base.Debug.PGOInline > 0 {
83                         fmt.Printf("hot-callsite-thres=%v\n", inlineHotCallSiteThresholdPercent)
84                 }
85         }
86
87         if base.Debug.InlineHotBudget != 0 {
88                 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
89         }
90
91         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
92                 for _, f := range list {
93                         name := ir.PkgFuncName(f)
94                         if n, ok := p.WeightedCG.IRNodes[name]; ok {
95                                 for _, e := range p.WeightedCG.OutEdges[n] {
96                                         if e.Weight != 0 {
97                                                 edgeweightpercent := pgo.WeightInPercentage(e.Weight, p.TotalEdgeWeight)
98                                                 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
99                                                         csi := pgo.CallSiteInfo{Line: e.CallSite, Caller: n.AST}
100                                                         if _, ok := candHotEdgeMap[csi]; !ok {
101                                                                 candHotEdgeMap[csi] = struct{}{}
102                                                                 candHotCalleeMap[e.Dst] = struct{}{}
103                                                         }
104                                                 }
105                                         }
106                                 }
107                         }
108                 }
109         })
110         if base.Debug.PGOInline > 0 {
111                 fmt.Printf("hot-cg before inline in dot format:")
112                 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
113         }
114 }
115
116 // pgoInlineEpilogue updates IRGraph after inlining.
117 func pgoInlineEpilogue(p *pgo.Profile) {
118         if base.Debug.PGOInline > 0 {
119                 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
120                         for _, f := range list {
121                                 name := ir.PkgFuncName(f)
122                                 if n, ok := p.WeightedCG.IRNodes[name]; ok {
123                                         p.RedirectEdges(n, inlinedCallSites)
124                                 }
125                         }
126                 })
127                 // Print the call-graph after inlining. This is a debugging feature.
128                 fmt.Printf("hot-cg after inline in dot:")
129                 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
130         }
131 }
132
133 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
134 func InlinePackage(p *pgo.Profile) {
135         if p != nil {
136                 pgoInlinePrologue(p)
137         }
138
139         ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
140                 numfns := numNonClosures(list)
141                 for _, n := range list {
142                         if !recursive || numfns > 1 {
143                                 // We allow inlining if there is no
144                                 // recursion, or the recursion cycle is
145                                 // across more than one function.
146                                 CanInline(n, p)
147                         } else {
148                                 if base.Flag.LowerM > 1 {
149                                         fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
150                                 }
151                         }
152                         InlineCalls(n, p)
153                 }
154         })
155
156         if p != nil {
157                 pgoInlineEpilogue(p)
158         }
159 }
160
161 // CanInline determines whether fn is inlineable.
162 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
163 // fn and fn.Body will already have been typechecked.
164 func CanInline(fn *ir.Func, profile *pgo.Profile) {
165         if fn.Nname == nil {
166                 base.Fatalf("CanInline no nname %+v", fn)
167         }
168
169         var reason string // reason, if any, that the function was not inlined
170         if base.Flag.LowerM > 1 || logopt.Enabled() {
171                 defer func() {
172                         if reason != "" {
173                                 if base.Flag.LowerM > 1 {
174                                         fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
175                                 }
176                                 if logopt.Enabled() {
177                                         logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
178                                 }
179                         }
180                 }()
181         }
182
183         // If marked "go:noinline", don't inline
184         if fn.Pragma&ir.Noinline != 0 {
185                 reason = "marked go:noinline"
186                 return
187         }
188
189         // If marked "go:norace" and -race compilation, don't inline.
190         if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
191                 reason = "marked go:norace with -race compilation"
192                 return
193         }
194
195         // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
196         if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
197                 reason = "marked go:nocheckptr"
198                 return
199         }
200
201         // If marked "go:cgo_unsafe_args", don't inline, since the
202         // function makes assumptions about its argument frame layout.
203         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
204                 reason = "marked go:cgo_unsafe_args"
205                 return
206         }
207
208         // If marked as "go:uintptrkeepalive", don't inline, since the
209         // keep alive information is lost during inlining.
210         //
211         // TODO(prattmic): This is handled on calls during escape analysis,
212         // which is after inlining. Move prior to inlining so the keep-alive is
213         // maintained after inlining.
214         if fn.Pragma&ir.UintptrKeepAlive != 0 {
215                 reason = "marked as having a keep-alive uintptr argument"
216                 return
217         }
218
219         // If marked as "go:uintptrescapes", don't inline, since the
220         // escape information is lost during inlining.
221         if fn.Pragma&ir.UintptrEscapes != 0 {
222                 reason = "marked as having an escaping uintptr argument"
223                 return
224         }
225
226         // The nowritebarrierrec checker currently works at function
227         // granularity, so inlining yeswritebarrierrec functions can
228         // confuse it (#22342). As a workaround, disallow inlining
229         // them for now.
230         if fn.Pragma&ir.Yeswritebarrierrec != 0 {
231                 reason = "marked go:yeswritebarrierrec"
232                 return
233         }
234
235         // If fn has no body (is defined outside of Go), cannot inline it.
236         if len(fn.Body) == 0 {
237                 reason = "no function body"
238                 return
239         }
240
241         if fn.Typecheck() == 0 {
242                 base.Fatalf("CanInline on non-typechecked function %v", fn)
243         }
244
245         n := fn.Nname
246         if n.Func.InlinabilityChecked() {
247                 return
248         }
249         defer n.Func.SetInlinabilityChecked(true)
250
251         cc := int32(inlineExtraCallCost)
252         if base.Flag.LowerL == 4 {
253                 cc = 1 // this appears to yield better performance than 0.
254         }
255
256         // Update the budget for profile-guided inlining.
257         budget := int32(inlineMaxBudget)
258         if profile != nil {
259                 if n, ok := profile.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
260                         if _, ok := candHotCalleeMap[n]; ok {
261                                 budget = int32(inlineHotMaxBudget)
262                                 if base.Debug.PGOInline > 0 {
263                                         fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
264                                 }
265                         }
266                 }
267         }
268
269         // At this point in the game the function we're looking at may
270         // have "stale" autos, vars that still appear in the Dcl list, but
271         // which no longer have any uses in the function body (due to
272         // elimination by deadcode). We'd like to exclude these dead vars
273         // when creating the "Inline.Dcl" field below; to accomplish this,
274         // the hairyVisitor below builds up a map of used/referenced
275         // locals, and we use this map to produce a pruned Inline.Dcl
276         // list. See issue 25249 for more context.
277
278         visitor := hairyVisitor{
279                 curFunc:       fn,
280                 budget:        budget,
281                 maxBudget:     budget,
282                 extraCallCost: cc,
283                 profile:       profile,
284         }
285         if visitor.tooHairy(fn) {
286                 reason = visitor.reason
287                 return
288         }
289
290         n.Func.Inl = &ir.Inline{
291                 Cost: budget - visitor.budget,
292                 Dcl:  pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
293                 Body: inlcopylist(fn.Body),
294
295                 CanDelayResults: canDelayResults(fn),
296         }
297
298         if base.Flag.LowerM > 1 {
299                 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))
300         } else if base.Flag.LowerM != 0 {
301                 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
302         }
303         if logopt.Enabled() {
304                 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
305         }
306 }
307
308 // canDelayResults reports whether inlined calls to fn can delay
309 // declaring the result parameter until the "return" statement.
310 func canDelayResults(fn *ir.Func) bool {
311         // We can delay declaring+initializing result parameters if:
312         // (1) there's exactly one "return" statement in the inlined function;
313         // (2) it's not an empty return statement (#44355); and
314         // (3) the result parameters aren't named.
315
316         nreturns := 0
317         ir.VisitList(fn.Body, func(n ir.Node) {
318                 if n, ok := n.(*ir.ReturnStmt); ok {
319                         nreturns++
320                         if len(n.Results) == 0 {
321                                 nreturns++ // empty return statement (case 2)
322                         }
323                 }
324         })
325
326         if nreturns != 1 {
327                 return false // not exactly one return statement (case 1)
328         }
329
330         // temporaries for return values.
331         for _, param := range fn.Type().Results().FieldSlice() {
332                 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
333                         return false // found a named result parameter (case 3)
334                 }
335         }
336
337         return true
338 }
339
340 // hairyVisitor visits a function body to determine its inlining
341 // hairiness and whether or not it can be inlined.
342 type hairyVisitor struct {
343         // This is needed to access the current caller in the doNode function.
344         curFunc       *ir.Func
345         budget        int32
346         maxBudget     int32
347         reason        string
348         extraCallCost int32
349         usedLocals    ir.NameSet
350         do            func(ir.Node) bool
351         profile       *pgo.Profile
352 }
353
354 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
355         v.do = v.doNode // cache closure
356         if ir.DoChildren(fn, v.do) {
357                 return true
358         }
359         if v.budget < 0 {
360                 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
361                 return true
362         }
363         return false
364 }
365
366 func (v *hairyVisitor) doNode(n ir.Node) bool {
367         if n == nil {
368                 return false
369         }
370         switch n.Op() {
371         // Call is okay if inlinable and we have the budget for the body.
372         case ir.OCALLFUNC:
373                 n := n.(*ir.CallExpr)
374                 // Functions that call runtime.getcaller{pc,sp} can not be inlined
375                 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
376                 //
377                 // runtime.throw is a "cheap call" like panic in normal code.
378                 if n.X.Op() == ir.ONAME {
379                         name := n.X.(*ir.Name)
380                         if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
381                                 fn := name.Sym().Name
382                                 if fn == "getcallerpc" || fn == "getcallersp" {
383                                         v.reason = "call to " + fn
384                                         return true
385                                 }
386                                 if fn == "throw" {
387                                         v.budget -= inlineExtraThrowCost
388                                         break
389                                 }
390                         }
391                         // Special case for coverage counter updates; although
392                         // these correspond to real operations, we treat them as
393                         // zero cost for the moment. This is due to the existence
394                         // of tests that are sensitive to inlining-- if the
395                         // insertion of coverage instrumentation happens to tip a
396                         // given function over the threshold and move it from
397                         // "inlinable" to "not-inlinable", this can cause changes
398                         // in allocation behavior, which can then result in test
399                         // failures (a good example is the TestAllocations in
400                         // crypto/ed25519).
401                         if isAtomicCoverageCounterUpdate(n) {
402                                 return false
403                         }
404                 }
405                 if n.X.Op() == ir.OMETHEXPR {
406                         if meth := ir.MethodExprName(n.X); meth != nil {
407                                 if fn := meth.Func; fn != nil {
408                                         s := fn.Sym()
409                                         var cheap bool
410                                         if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
411                                                 // Special case: explicitly allow mid-stack inlining of
412                                                 // runtime.heapBits.next even though it calls slow-path
413                                                 // runtime.heapBits.nextArena.
414                                                 cheap = true
415                                         }
416                                         // Special case: on architectures that can do unaligned loads,
417                                         // explicitly mark encoding/binary methods as cheap,
418                                         // because in practice they are, even though our inlining
419                                         // budgeting system does not see that. See issue 42958.
420                                         if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
421                                                 switch s.Name {
422                                                 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
423                                                         "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
424                                                         "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
425                                                         "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
426                                                         "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
427                                                         "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
428                                                         cheap = true
429                                                 }
430                                         }
431                                         if cheap {
432                                                 break // treat like any other node, that is, cost of 1
433                                         }
434                                 }
435                         }
436                 }
437
438                 // Determine if the callee edge is for an inlinable hot callee or not.
439                 if v.profile != nil && v.curFunc != nil {
440                         if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
441                                 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
442                                 csi := pgo.CallSiteInfo{Line: line, Caller: v.curFunc}
443                                 if _, o := candHotEdgeMap[csi]; o {
444                                         if base.Debug.PGOInline > 0 {
445                                                 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
446                                         }
447                                 }
448                         }
449                 }
450
451                 if ir.IsIntrinsicCall(n) {
452                         // Treat like any other node.
453                         break
454                 }
455
456                 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
457                         v.budget -= fn.Inl.Cost
458                         break
459                 }
460
461                 // Call cost for non-leaf inlining.
462                 v.budget -= v.extraCallCost
463
464         case ir.OCALLMETH:
465                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
466
467         // Things that are too hairy, irrespective of the budget
468         case ir.OCALL, ir.OCALLINTER:
469                 // Call cost for non-leaf inlining.
470                 v.budget -= v.extraCallCost
471
472         case ir.OPANIC:
473                 n := n.(*ir.UnaryExpr)
474                 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
475                         // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
476                         // Before CL 284412, these conversions were introduced later in the
477                         // compiler, so they didn't count against inlining budget.
478                         v.budget++
479                 }
480                 v.budget -= inlineExtraPanicCost
481
482         case ir.ORECOVER:
483                 // recover matches the argument frame pointer to find
484                 // the right panic value, so it needs an argument frame.
485                 v.reason = "call to recover"
486                 return true
487
488         case ir.OCLOSURE:
489                 if base.Debug.InlFuncsWithClosures == 0 {
490                         v.reason = "not inlining functions with closures"
491                         return true
492                 }
493
494                 // TODO(danscales): Maybe make budget proportional to number of closure
495                 // variables, e.g.:
496                 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
497                 v.budget -= 15
498                 // Scan body of closure (which DoChildren doesn't automatically
499                 // do) to check for disallowed ops in the body and include the
500                 // body in the budget.
501                 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
502                         return true
503                 }
504
505         case ir.OGO,
506                 ir.ODEFER,
507                 ir.ODCLTYPE, // can't print yet
508                 ir.OTAILCALL:
509                 v.reason = "unhandled op " + n.Op().String()
510                 return true
511
512         case ir.OAPPEND:
513                 v.budget -= inlineExtraAppendCost
514
515         case ir.OADDR:
516                 n := n.(*ir.AddrExpr)
517                 // Make "&s.f" cost 0 when f's offset is zero.
518                 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
519                         if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
520                                 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
521                         }
522                 }
523
524         case ir.ODEREF:
525                 // *(*X)(unsafe.Pointer(&x)) is low-cost
526                 n := n.(*ir.StarExpr)
527
528                 ptr := n.X
529                 for ptr.Op() == ir.OCONVNOP {
530                         ptr = ptr.(*ir.ConvExpr).X
531                 }
532                 if ptr.Op() == ir.OADDR {
533                         v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
534                 }
535
536         case ir.OCONVNOP:
537                 // This doesn't produce code, but the children might.
538                 v.budget++ // undo default cost
539
540         case ir.ODCLCONST, ir.OFALL:
541                 // These nodes don't produce code; omit from inlining budget.
542                 return false
543
544         case ir.OIF:
545                 n := n.(*ir.IfStmt)
546                 if ir.IsConst(n.Cond, constant.Bool) {
547                         // This if and the condition cost nothing.
548                         if doList(n.Init(), v.do) {
549                                 return true
550                         }
551                         if ir.BoolVal(n.Cond) {
552                                 return doList(n.Body, v.do)
553                         } else {
554                                 return doList(n.Else, v.do)
555                         }
556                 }
557
558         case ir.ONAME:
559                 n := n.(*ir.Name)
560                 if n.Class == ir.PAUTO {
561                         v.usedLocals.Add(n)
562                 }
563
564         case ir.OBLOCK:
565                 // The only OBLOCK we should see at this point is an empty one.
566                 // In any event, let the visitList(n.List()) below take care of the statements,
567                 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
568                 v.budget++
569
570         case ir.OMETHVALUE, ir.OSLICELIT:
571                 v.budget-- // Hack for toolstash -cmp.
572
573         case ir.OMETHEXPR:
574                 v.budget++ // Hack for toolstash -cmp.
575
576         case ir.OAS2:
577                 n := n.(*ir.AssignListStmt)
578
579                 // Unified IR unconditionally rewrites:
580                 //
581                 //      a, b = f()
582                 //
583                 // into:
584                 //
585                 //      DCL tmp1
586                 //      DCL tmp2
587                 //      tmp1, tmp2 = f()
588                 //      a, b = tmp1, tmp2
589                 //
590                 // so that it can insert implicit conversions as necessary. To
591                 // minimize impact to the existing inlining heuristics (in
592                 // particular, to avoid breaking the existing inlinability regress
593                 // tests), we need to compensate for this here.
594                 if base.Debug.Unified != 0 {
595                         if init := n.Rhs[0].Init(); len(init) == 1 {
596                                 if _, ok := init[0].(*ir.AssignListStmt); ok {
597                                         // 4 for each value, because each temporary variable now
598                                         // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
599                                         //
600                                         // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
601                                         v.budget += 4*int32(len(n.Lhs)) + 1
602                                 }
603                         }
604                 }
605
606         case ir.OAS:
607                 // Special case for coverage counter updates and coverage
608                 // function registrations. Although these correspond to real
609                 // operations, we treat them as zero cost for the moment. This
610                 // is primarily due to the existence of tests that are
611                 // sensitive to inlining-- if the insertion of coverage
612                 // instrumentation happens to tip a given function over the
613                 // threshold and move it from "inlinable" to "not-inlinable",
614                 // this can cause changes in allocation behavior, which can
615                 // then result in test failures (a good example is the
616                 // TestAllocations in crypto/ed25519).
617                 n := n.(*ir.AssignStmt)
618                 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
619                         return false
620                 }
621         }
622
623         v.budget--
624
625         // When debugging, don't stop early, to get full cost of inlining this function
626         if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
627                 v.reason = "too expensive"
628                 return true
629         }
630
631         return ir.DoChildren(n, v.do)
632 }
633
634 func isBigFunc(fn *ir.Func) bool {
635         budget := inlineBigFunctionNodes
636         return ir.Any(fn, func(n ir.Node) bool {
637                 budget--
638                 return budget <= 0
639         })
640 }
641
642 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
643 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
644 // the body and dcls of an inlineable function.
645 func inlcopylist(ll []ir.Node) []ir.Node {
646         s := make([]ir.Node, len(ll))
647         for i, n := range ll {
648                 s[i] = inlcopy(n)
649         }
650         return s
651 }
652
653 // inlcopy is like DeepCopy(), but does extra work to copy closures.
654 func inlcopy(n ir.Node) ir.Node {
655         var edit func(ir.Node) ir.Node
656         edit = func(x ir.Node) ir.Node {
657                 switch x.Op() {
658                 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
659                         return x
660                 }
661                 m := ir.Copy(x)
662                 ir.EditChildren(m, edit)
663                 if x.Op() == ir.OCLOSURE {
664                         x := x.(*ir.ClosureExpr)
665                         // Need to save/duplicate x.Func.Nname,
666                         // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
667                         // x.Func.Body for iexport and local inlining.
668                         oldfn := x.Func
669                         newfn := ir.NewFunc(oldfn.Pos())
670                         m.(*ir.ClosureExpr).Func = newfn
671                         newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
672                         // XXX OK to share fn.Type() ??
673                         newfn.Nname.SetType(oldfn.Nname.Type())
674                         newfn.Body = inlcopylist(oldfn.Body)
675                         // Make shallow copy of the Dcl and ClosureVar slices
676                         newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
677                         newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
678                 }
679                 return m
680         }
681         return edit(n)
682 }
683
684 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
685 // calls made to inlineable functions. This is the external entry point.
686 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
687         savefn := ir.CurFunc
688         ir.CurFunc = fn
689         maxCost := int32(inlineMaxBudget)
690         if isBigFunc(fn) {
691                 maxCost = inlineBigFunctionMaxCost
692         }
693         var inlCalls []*ir.InlinedCallExpr
694         var edit func(ir.Node) ir.Node
695         edit = func(n ir.Node) ir.Node {
696                 return inlnode(n, maxCost, &inlCalls, edit, profile)
697         }
698         ir.EditChildren(fn, edit)
699
700         // If we inlined any calls, we want to recursively visit their
701         // bodies for further inlining. However, we need to wait until
702         // *after* the original function body has been expanded, or else
703         // inlCallee can have false positives (e.g., #54632).
704         for len(inlCalls) > 0 {
705                 call := inlCalls[0]
706                 inlCalls = inlCalls[1:]
707                 ir.EditChildren(call, edit)
708         }
709
710         ir.CurFunc = savefn
711 }
712
713 // inlnode recurses over the tree to find inlineable calls, which will
714 // be turned into OINLCALLs by mkinlcall. When the recursion comes
715 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
716 // nbody and nelse and use one of the 4 inlconv/glue functions above
717 // to turn the OINLCALL into an expression, a statement, or patch it
718 // in to this nodes list or rlist as appropriate.
719 // NOTE it makes no sense to pass the glue functions down the
720 // recursion to the level where the OINLCALL gets created because they
721 // have to edit /this/ n, so you'd have to push that one down as well,
722 // but then you may as well do it here.  so this is cleaner and
723 // shorter and less complicated.
724 // The result of inlnode MUST be assigned back to n, e.g.
725 //
726 //      n.Left = inlnode(n.Left)
727 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
728         if n == nil {
729                 return n
730         }
731
732         switch n.Op() {
733         case ir.ODEFER, ir.OGO:
734                 n := n.(*ir.GoDeferStmt)
735                 switch call := n.Call; call.Op() {
736                 case ir.OCALLMETH:
737                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
738                 case ir.OCALLFUNC:
739                         call := call.(*ir.CallExpr)
740                         call.NoInline = true
741                 }
742         case ir.OTAILCALL:
743                 n := n.(*ir.TailCallStmt)
744                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
745
746         // TODO do them here (or earlier),
747         // so escape analysis can avoid more heapmoves.
748         case ir.OCLOSURE:
749                 return n
750         case ir.OCALLMETH:
751                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
752         case ir.OCALLFUNC:
753                 n := n.(*ir.CallExpr)
754                 if n.X.Op() == ir.OMETHEXPR {
755                         // Prevent inlining some reflect.Value methods when using checkptr,
756                         // even when package reflect was compiled without it (#35073).
757                         if meth := ir.MethodExprName(n.X); meth != nil {
758                                 s := meth.Sym()
759                                 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
760                                         return n
761                                 }
762                         }
763                 }
764         }
765
766         lno := ir.SetPos(n)
767
768         ir.EditChildren(n, edit)
769
770         // with all the branches out of the way, it is now time to
771         // transmogrify this node itself unless inhibited by the
772         // switch at the top of this function.
773         switch n.Op() {
774         case ir.OCALLMETH:
775                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
776
777         case ir.OCALLFUNC:
778                 call := n.(*ir.CallExpr)
779                 if call.NoInline {
780                         break
781                 }
782                 if base.Flag.LowerM > 3 {
783                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
784                 }
785                 if ir.IsIntrinsicCall(call) {
786                         break
787                 }
788                 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
789                         n = mkinlcall(call, fn, maxCost, inlCalls, edit)
790                 }
791         }
792
793         base.Pos = lno
794
795         return n
796 }
797
798 // inlCallee takes a function-typed expression and returns the underlying function ONAME
799 // that it refers to if statically known. Otherwise, it returns nil.
800 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
801         fn = ir.StaticValue(fn)
802         switch fn.Op() {
803         case ir.OMETHEXPR:
804                 fn := fn.(*ir.SelectorExpr)
805                 n := ir.MethodExprName(fn)
806                 // Check that receiver type matches fn.X.
807                 // TODO(mdempsky): Handle implicit dereference
808                 // of pointer receiver argument?
809                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
810                         return nil
811                 }
812                 return n.Func
813         case ir.ONAME:
814                 fn := fn.(*ir.Name)
815                 if fn.Class == ir.PFUNC {
816                         return fn.Func
817                 }
818         case ir.OCLOSURE:
819                 fn := fn.(*ir.ClosureExpr)
820                 c := fn.Func
821                 CanInline(c, profile)
822                 return c
823         }
824         return nil
825 }
826
827 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
828         if t.Nname == nil {
829                 return ir.BlankNode
830         }
831         n := t.Nname.(*ir.Name)
832         if ir.IsBlank(n) {
833                 return ir.BlankNode
834         }
835         inlvar := inlvars[n]
836         if inlvar == nil {
837                 base.Fatalf("missing inlvar for %v", n)
838         }
839         as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
840         inlvar.Name().Defn = as
841         return inlvar
842 }
843
844 var inlgen int
845
846 // SSADumpInline gives the SSA back end a chance to dump the function
847 // when producing output for debugging the compiler itself.
848 var SSADumpInline = func(*ir.Func) {}
849
850 // InlineCall allows the inliner implementation to be overridden.
851 // If it returns nil, the function will not be inlined.
852 var InlineCall = oldInlineCall
853
854 // If n is a OCALLFUNC node, and fn is an ONAME node for a
855 // function with an inlinable body, return an OINLCALL node that can replace n.
856 // The returned node's Ninit has the parameter assignments, the Nbody is the
857 // inlined function body, and (List, Rlist) contain the (input, output)
858 // parameters.
859 // The result of mkinlcall MUST be assigned back to n, e.g.
860 //
861 //      n.Left = mkinlcall(n.Left, fn, isddd)
862 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
863         if fn.Inl == nil {
864                 if logopt.Enabled() {
865                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
866                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
867                 }
868                 return n
869         }
870         if fn.Inl.Cost > maxCost {
871                 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
872                 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
873                 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
874                 if _, ok := candHotEdgeMap[csi]; ok {
875                         if fn.Inl.Cost > inlineHotMaxBudget {
876                                 if logopt.Enabled() {
877                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
878                                                 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
879                                 }
880                                 return n
881                         }
882                         if base.Debug.PGOInline > 0 {
883                                 fmt.Printf("hot-budget check allows inlining for callsite at %v\n", ir.Line(n))
884                         }
885                 } else {
886                         // The inlined function body is too big. Typically we use this check to restrict
887                         // inlining into very big functions.  See issue 26546 and 17566.
888                         if logopt.Enabled() {
889                                 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
890                                         fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
891                         }
892                         return n
893                 }
894         }
895
896         if fn == ir.CurFunc {
897                 // Can't recursively inline a function into itself.
898                 if logopt.Enabled() {
899                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
900                 }
901                 return n
902         }
903
904         // The non-unified frontend has issues with inlining and shape parameters.
905         if base.Debug.Unified == 0 {
906                 // Don't inline a function fn that has no shape parameters, but is passed at
907                 // least one shape arg. This means we must be inlining a non-generic function
908                 // fn that was passed into a generic function, and can be called with a shape
909                 // arg because it matches an appropriate type parameters. But fn may include
910                 // an interface conversion (that may be applied to a shape arg) that was not
911                 // apparent when we first created the instantiation of the generic function.
912                 // We can't handle this if we actually do the inlining, since we want to know
913                 // all interface conversions immediately after stenciling. So, we avoid
914                 // inlining in this case, see issue #49309. (1)
915                 //
916                 // See discussion on go.dev/cl/406475 for more background.
917                 if !fn.Type().Params().HasShape() {
918                         for _, arg := range n.Args {
919                                 if arg.Type().HasShape() {
920                                         if logopt.Enabled() {
921                                                 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
922                                                         fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
923                                         }
924                                         return n
925                                 }
926                         }
927                 } else {
928                         // Don't inline a function fn that has shape parameters, but is passed no shape arg.
929                         // See comments (1) above, and issue #51909.
930                         inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
931                         for _, arg := range n.Args {
932                                 if arg.Type().HasShape() {
933                                         inlineable = true
934                                         break
935                                 }
936                         }
937                         if !inlineable {
938                                 if logopt.Enabled() {
939                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
940                                                 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
941                                 }
942                                 return n
943                         }
944                 }
945         }
946
947         if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
948                 // Runtime package must not be instrumented.
949                 // Instrument skips runtime package. However, some runtime code can be
950                 // inlined into other packages and instrumented there. To avoid this,
951                 // we disable inlining of runtime functions when instrumenting.
952                 // The example that we observed is inlining of LockOSThread,
953                 // which lead to false race reports on m contents.
954                 return n
955         }
956
957         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
958         sym := fn.Linksym()
959
960         // Check if we've already inlined this function at this particular
961         // call site, in order to stop inlining when we reach the beginning
962         // of a recursion cycle again. We don't inline immediately recursive
963         // functions, but allow inlining if there is a recursion cycle of
964         // many functions. Most likely, the inlining will stop before we
965         // even hit the beginning of the cycle again, but this catches the
966         // unusual case.
967         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
968                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
969                         if base.Flag.LowerM > 1 {
970                                 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
971                         }
972                         return n
973                 }
974         }
975
976         typecheck.FixVariadicCall(n)
977
978         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
979
980         closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
981                 // The linker needs FuncInfo metadata for all inlined
982                 // functions. This is typically handled by gc.enqueueFunc
983                 // calling ir.InitLSym for all function declarations in
984                 // typecheck.Target.Decls (ir.UseClosure adds all closures to
985                 // Decls).
986                 //
987                 // However, non-trivial closures in Decls are ignored, and are
988                 // insteaded enqueued when walk of the calling function
989                 // discovers them.
990                 //
991                 // This presents a problem for direct calls to closures.
992                 // Inlining will replace the entire closure definition with its
993                 // body, which hides the closure from walk and thus suppresses
994                 // symbol creation.
995                 //
996                 // Explicitly create a symbol early in this edge case to ensure
997                 // we keep this metadata.
998                 //
999                 // TODO: Refactor to keep a reference so this can all be done
1000                 // by enqueueFunc.
1001
1002                 if n.Op() != ir.OCALLFUNC {
1003                         // Not a standard call.
1004                         return
1005                 }
1006                 if n.X.Op() != ir.OCLOSURE {
1007                         // Not a direct closure call.
1008                         return
1009                 }
1010
1011                 clo := n.X.(*ir.ClosureExpr)
1012                 if ir.IsTrivialClosure(clo) {
1013                         // enqueueFunc will handle trivial closures anyways.
1014                         return
1015                 }
1016
1017                 ir.InitLSym(fn, true)
1018         }
1019
1020         closureInitLSym(n, fn)
1021
1022         if base.Flag.GenDwarfInl > 0 {
1023                 if !sym.WasInlined() {
1024                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1025                         sym.Set(obj.AttrWasInlined, true)
1026                 }
1027         }
1028
1029         if base.Flag.LowerM != 0 {
1030                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1031         }
1032         if base.Flag.LowerM > 2 {
1033                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1034         }
1035
1036         if base.Debug.PGOInline > 0 {
1037                 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
1038                 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
1039                 if _, ok := inlinedCallSites[csi]; !ok {
1040                         inlinedCallSites[csi] = struct{}{}
1041                 }
1042         }
1043
1044         res := InlineCall(n, fn, inlIndex)
1045
1046         if res == nil {
1047                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1048         }
1049
1050         if base.Flag.LowerM > 2 {
1051                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1052         }
1053
1054         *inlCalls = append(*inlCalls, res)
1055
1056         return res
1057 }
1058
1059 // CalleeEffects appends any side effects from evaluating callee to init.
1060 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1061         for {
1062                 init.Append(ir.TakeInit(callee)...)
1063
1064                 switch callee.Op() {
1065                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1066                         return // done
1067
1068                 case ir.OCONVNOP:
1069                         conv := callee.(*ir.ConvExpr)
1070                         callee = conv.X
1071
1072                 case ir.OINLCALL:
1073                         ic := callee.(*ir.InlinedCallExpr)
1074                         init.Append(ic.Body.Take()...)
1075                         callee = ic.SingleResult()
1076
1077                 default:
1078                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1079                 }
1080         }
1081 }
1082
1083 // oldInlineCall creates an InlinedCallExpr to replace the given call
1084 // expression. fn is the callee function to be inlined. inlIndex is
1085 // the inlining tree position index, for use with src.NewInliningBase
1086 // when rewriting positions.
1087 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1088         if base.Debug.TypecheckInl == 0 {
1089                 typecheck.ImportedBody(fn)
1090         }
1091
1092         SSADumpInline(fn)
1093
1094         ninit := call.Init()
1095
1096         // For normal function calls, the function callee expression
1097         // may contain side effects. Make sure to preserve these,
1098         // if necessary (#42703).
1099         if call.Op() == ir.OCALLFUNC {
1100                 CalleeEffects(&ninit, call.X)
1101         }
1102
1103         // Make temp names to use instead of the originals.
1104         inlvars := make(map[*ir.Name]*ir.Name)
1105
1106         // record formals/locals for later post-processing
1107         var inlfvars []*ir.Name
1108
1109         for _, ln := range fn.Inl.Dcl {
1110                 if ln.Op() != ir.ONAME {
1111                         continue
1112                 }
1113                 if ln.Class == ir.PPARAMOUT { // return values handled below.
1114                         continue
1115                 }
1116                 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1117                 inlvars[ln] = inlf
1118                 if base.Flag.GenDwarfInl > 0 {
1119                         if ln.Class == ir.PPARAM {
1120                                 inlf.Name().SetInlFormal(true)
1121                         } else {
1122                                 inlf.Name().SetInlLocal(true)
1123                         }
1124                         inlf.SetPos(ln.Pos())
1125                         inlfvars = append(inlfvars, inlf)
1126                 }
1127         }
1128
1129         // We can delay declaring+initializing result parameters if:
1130         // temporaries for return values.
1131         var retvars []ir.Node
1132         for i, t := range fn.Type().Results().Fields().Slice() {
1133                 var m *ir.Name
1134                 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1135                         n := nn.(*ir.Name)
1136                         m = inlvar(n)
1137                         m = typecheck.Expr(m).(*ir.Name)
1138                         inlvars[n] = m
1139                 } else {
1140                         // anonymous return values, synthesize names for use in assignment that replaces return
1141                         m = retvar(t, i)
1142                 }
1143
1144                 if base.Flag.GenDwarfInl > 0 {
1145                         // Don't update the src.Pos on a return variable if it
1146                         // was manufactured by the inliner (e.g. "~R2"); such vars
1147                         // were not part of the original callee.
1148                         if !strings.HasPrefix(m.Sym().Name, "~R") {
1149                                 m.Name().SetInlFormal(true)
1150                                 m.SetPos(t.Pos)
1151                                 inlfvars = append(inlfvars, m)
1152                         }
1153                 }
1154
1155                 retvars = append(retvars, m)
1156         }
1157
1158         // Assign arguments to the parameters' temp names.
1159         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1160         as.Def = true
1161         if call.Op() == ir.OCALLMETH {
1162                 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1163         }
1164         as.Rhs.Append(call.Args...)
1165
1166         if recv := fn.Type().Recv(); recv != nil {
1167                 as.Lhs.Append(inlParam(recv, as, inlvars))
1168         }
1169         for _, param := range fn.Type().Params().Fields().Slice() {
1170                 as.Lhs.Append(inlParam(param, as, inlvars))
1171         }
1172
1173         if len(as.Rhs) != 0 {
1174                 ninit.Append(typecheck.Stmt(as))
1175         }
1176
1177         if !fn.Inl.CanDelayResults {
1178                 // Zero the return parameters.
1179                 for _, n := range retvars {
1180                         ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1181                         ras := ir.NewAssignStmt(base.Pos, n, nil)
1182                         ninit.Append(typecheck.Stmt(ras))
1183                 }
1184         }
1185
1186         retlabel := typecheck.AutoLabel(".i")
1187
1188         inlgen++
1189
1190         // Add an inline mark just before the inlined body.
1191         // This mark is inline in the code so that it's a reasonable spot
1192         // to put a breakpoint. Not sure if that's really necessary or not
1193         // (in which case it could go at the end of the function instead).
1194         // Note issue 28603.
1195         ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1196
1197         subst := inlsubst{
1198                 retlabel:    retlabel,
1199                 retvars:     retvars,
1200                 inlvars:     inlvars,
1201                 defnMarker:  ir.NilExpr{},
1202                 bases:       make(map[*src.PosBase]*src.PosBase),
1203                 newInlIndex: inlIndex,
1204                 fn:          fn,
1205         }
1206         subst.edit = subst.node
1207
1208         body := subst.list(ir.Nodes(fn.Inl.Body))
1209
1210         lab := ir.NewLabelStmt(base.Pos, retlabel)
1211         body = append(body, lab)
1212
1213         if base.Flag.GenDwarfInl > 0 {
1214                 for _, v := range inlfvars {
1215                         v.SetPos(subst.updatedPos(v.Pos()))
1216                 }
1217         }
1218
1219         //dumplist("ninit post", ninit);
1220
1221         res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1222         res.SetInit(ninit)
1223         res.SetType(call.Type())
1224         res.SetTypecheck(1)
1225         return res
1226 }
1227
1228 // Every time we expand a function we generate a new set of tmpnames,
1229 // PAUTO's in the calling functions, and link them off of the
1230 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1231 func inlvar(var_ *ir.Name) *ir.Name {
1232         if base.Flag.LowerM > 3 {
1233                 fmt.Printf("inlvar %+v\n", var_)
1234         }
1235
1236         n := typecheck.NewName(var_.Sym())
1237         n.SetType(var_.Type())
1238         n.SetTypecheck(1)
1239         n.Class = ir.PAUTO
1240         n.SetUsed(true)
1241         n.SetAutoTemp(var_.AutoTemp())
1242         n.Curfn = ir.CurFunc // the calling function, not the called one
1243         n.SetAddrtaken(var_.Addrtaken())
1244
1245         ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1246         return n
1247 }
1248
1249 // Synthesize a variable to store the inlined function's results in.
1250 func retvar(t *types.Field, i int) *ir.Name {
1251         n := typecheck.NewName(typecheck.LookupNum("~R", i))
1252         n.SetType(t.Type)
1253         n.SetTypecheck(1)
1254         n.Class = ir.PAUTO
1255         n.SetUsed(true)
1256         n.Curfn = ir.CurFunc // the calling function, not the called one
1257         ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1258         return n
1259 }
1260
1261 // The inlsubst type implements the actual inlining of a single
1262 // function call.
1263 type inlsubst struct {
1264         // Target of the goto substituted in place of a return.
1265         retlabel *types.Sym
1266
1267         // Temporary result variables.
1268         retvars []ir.Node
1269
1270         inlvars map[*ir.Name]*ir.Name
1271         // defnMarker is used to mark a Node for reassignment.
1272         // inlsubst.clovar set this during creating new ONAME.
1273         // inlsubst.node will set the correct Defn for inlvar.
1274         defnMarker ir.NilExpr
1275
1276         // bases maps from original PosBase to PosBase with an extra
1277         // inlined call frame.
1278         bases map[*src.PosBase]*src.PosBase
1279
1280         // newInlIndex is the index of the inlined call frame to
1281         // insert for inlined nodes.
1282         newInlIndex int
1283
1284         edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1285
1286         // If non-nil, we are inside a closure inside the inlined function, and
1287         // newclofn is the Func of the new inlined closure.
1288         newclofn *ir.Func
1289
1290         fn *ir.Func // For debug -- the func that is being inlined
1291
1292         // If true, then don't update source positions during substitution
1293         // (retain old source positions).
1294         noPosUpdate bool
1295 }
1296
1297 // list inlines a list of nodes.
1298 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1299         s := make([]ir.Node, 0, len(ll))
1300         for _, n := range ll {
1301                 s = append(s, subst.node(n))
1302         }
1303         return s
1304 }
1305
1306 // fields returns a list of the fields of a struct type representing receiver,
1307 // params, or results, after duplicating the field nodes and substituting the
1308 // Nname nodes inside the field nodes.
1309 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1310         oldfields := oldt.FieldSlice()
1311         newfields := make([]*types.Field, len(oldfields))
1312         for i := range oldfields {
1313                 newfields[i] = oldfields[i].Copy()
1314                 if oldfields[i].Nname != nil {
1315                         newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1316                 }
1317         }
1318         return newfields
1319 }
1320
1321 // clovar creates a new ONAME node for a local variable or param of a closure
1322 // inside a function being inlined.
1323 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1324         m := ir.NewNameAt(n.Pos(), n.Sym())
1325         m.Class = n.Class
1326         m.SetType(n.Type())
1327         m.SetTypecheck(1)
1328         if n.IsClosureVar() {
1329                 m.SetIsClosureVar(true)
1330         }
1331         if n.Addrtaken() {
1332                 m.SetAddrtaken(true)
1333         }
1334         if n.Used() {
1335                 m.SetUsed(true)
1336         }
1337         m.Defn = n.Defn
1338
1339         m.Curfn = subst.newclofn
1340
1341         switch defn := n.Defn.(type) {
1342         case nil:
1343                 // ok
1344         case *ir.Name:
1345                 if !n.IsClosureVar() {
1346                         base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1347                 }
1348                 if n.Sym().Pkg != types.LocalPkg {
1349                         // If the closure came from inlining a function from
1350                         // another package, must change package of captured
1351                         // variable to localpkg, so that the fields of the closure
1352                         // struct are local package and can be accessed even if
1353                         // name is not exported. If you disable this code, you can
1354                         // reproduce the problem by running 'go test
1355                         // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1356                         // how we create closure structs?
1357                         m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1358                 }
1359                 // Make sure any inlvar which is the Defn
1360                 // of an ONAME closure var is rewritten
1361                 // during inlining. Don't substitute
1362                 // if Defn node is outside inlined function.
1363                 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1364                         m.Defn = subst.node(n.Defn)
1365                 }
1366         case *ir.AssignStmt, *ir.AssignListStmt:
1367                 // Mark node for reassignment at the end of inlsubst.node.
1368                 m.Defn = &subst.defnMarker
1369         case *ir.TypeSwitchGuard:
1370                 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1371         case *ir.RangeStmt:
1372                 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1373         default:
1374                 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1375         }
1376
1377         if n.Outer != nil {
1378                 // Either the outer variable is defined in function being inlined,
1379                 // and we will replace it with the substituted variable, or it is
1380                 // defined outside the function being inlined, and we should just
1381                 // skip the outer variable (the closure variable of the function
1382                 // being inlined).
1383                 s := subst.node(n.Outer).(*ir.Name)
1384                 if s == n.Outer {
1385                         s = n.Outer.Outer
1386                 }
1387                 m.Outer = s
1388         }
1389         return m
1390 }
1391
1392 // closure does the necessary substitions for a ClosureExpr n and returns the new
1393 // closure node.
1394 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1395         // Prior to the subst edit, set a flag in the inlsubst to indicate
1396         // that we don't want to update the source positions in the new
1397         // closure function. If we do this, it will appear that the
1398         // closure itself has things inlined into it, which is not the
1399         // case. See issue #46234 for more details. At the same time, we
1400         // do want to update the position in the new ClosureExpr (which is
1401         // part of the function we're working on). See #49171 for an
1402         // example of what happens if we miss that update.
1403         newClosurePos := subst.updatedPos(n.Pos())
1404         defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1405         subst.noPosUpdate = true
1406
1407         //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1408
1409         oldfn := n.Func
1410         newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1411
1412         if subst.newclofn != nil {
1413                 //fmt.Printf("Inlining a closure with a nested closure\n")
1414         }
1415         prevxfunc := subst.newclofn
1416
1417         // Mark that we are now substituting within a closure (within the
1418         // inlined function), and create new nodes for all the local
1419         // vars/params inside this closure.
1420         subst.newclofn = newfn
1421         newfn.Dcl = nil
1422         newfn.ClosureVars = nil
1423         for _, oldv := range oldfn.Dcl {
1424                 newv := subst.clovar(oldv)
1425                 subst.inlvars[oldv] = newv
1426                 newfn.Dcl = append(newfn.Dcl, newv)
1427         }
1428         for _, oldv := range oldfn.ClosureVars {
1429                 newv := subst.clovar(oldv)
1430                 subst.inlvars[oldv] = newv
1431                 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1432         }
1433
1434         // Need to replace ONAME nodes in
1435         // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1436         oldt := oldfn.Type()
1437         newrecvs := subst.fields(oldt.Recvs())
1438         var newrecv *types.Field
1439         if len(newrecvs) > 0 {
1440                 newrecv = newrecvs[0]
1441         }
1442         newt := types.NewSignature(oldt.Pkg(), newrecv,
1443                 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1444
1445         newfn.Nname.SetType(newt)
1446         newfn.Body = subst.list(oldfn.Body)
1447
1448         // Remove the nodes for the current closure from subst.inlvars
1449         for _, oldv := range oldfn.Dcl {
1450                 delete(subst.inlvars, oldv)
1451         }
1452         for _, oldv := range oldfn.ClosureVars {
1453                 delete(subst.inlvars, oldv)
1454         }
1455         // Go back to previous closure func
1456         subst.newclofn = prevxfunc
1457
1458         // Actually create the named function for the closure, now that
1459         // the closure is inlined in a specific function.
1460         newclo := newfn.OClosure
1461         newclo.SetPos(newClosurePos)
1462         newclo.SetInit(subst.list(n.Init()))
1463         return typecheck.Expr(newclo)
1464 }
1465
1466 // node recursively copies a node from the saved pristine body of the
1467 // inlined function, substituting references to input/output
1468 // parameters with ones to the tmpnames, and substituting returns with
1469 // assignments to the output.
1470 func (subst *inlsubst) node(n ir.Node) ir.Node {
1471         if n == nil {
1472                 return nil
1473         }
1474
1475         switch n.Op() {
1476         case ir.ONAME:
1477                 n := n.(*ir.Name)
1478
1479                 // Handle captured variables when inlining closures.
1480                 if n.IsClosureVar() && subst.newclofn == nil {
1481                         o := n.Outer
1482
1483                         // Deal with case where sequence of closures are inlined.
1484                         // TODO(danscales) - write test case to see if we need to
1485                         // go up multiple levels.
1486                         if o.Curfn != ir.CurFunc {
1487                                 o = o.Outer
1488                         }
1489
1490                         // make sure the outer param matches the inlining location
1491                         if o == nil || o.Curfn != ir.CurFunc {
1492                                 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1493                         }
1494
1495                         if base.Flag.LowerM > 2 {
1496                                 fmt.Printf("substituting captured name %+v  ->  %+v\n", n, o)
1497                         }
1498                         return o
1499                 }
1500
1501                 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1502                         if base.Flag.LowerM > 2 {
1503                                 fmt.Printf("substituting name %+v  ->  %+v\n", n, inlvar)
1504                         }
1505                         return inlvar
1506                 }
1507
1508                 if base.Flag.LowerM > 2 {
1509                         fmt.Printf("not substituting name %+v\n", n)
1510                 }
1511                 return n
1512
1513         case ir.OMETHEXPR:
1514                 n := n.(*ir.SelectorExpr)
1515                 return n
1516
1517         case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1518                 // If n is a named constant or type, we can continue
1519                 // using it in the inline copy. Otherwise, make a copy
1520                 // so we can update the line number.
1521                 if n.Sym() != nil {
1522                         return n
1523                 }
1524
1525         case ir.ORETURN:
1526                 if subst.newclofn != nil {
1527                         // Don't do special substitutions if inside a closure
1528                         break
1529                 }
1530                 // Because of the above test for subst.newclofn,
1531                 // this return is guaranteed to belong to the current inlined function.
1532                 n := n.(*ir.ReturnStmt)
1533                 init := subst.list(n.Init())
1534                 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1535                         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1536
1537                         // Make a shallow copy of retvars.
1538                         // Otherwise OINLCALL.Rlist will be the same list,
1539                         // and later walk and typecheck may clobber it.
1540                         for _, n := range subst.retvars {
1541                                 as.Lhs.Append(n)
1542                         }
1543                         as.Rhs = subst.list(n.Results)
1544
1545                         if subst.fn.Inl.CanDelayResults {
1546                                 for _, n := range as.Lhs {
1547                                         as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1548                                         n.Name().Defn = as
1549                                 }
1550                         }
1551
1552                         init = append(init, typecheck.Stmt(as))
1553                 }
1554                 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1555                 typecheck.Stmts(init)
1556                 return ir.NewBlockStmt(base.Pos, init)
1557
1558         case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1559                 if subst.newclofn != nil {
1560                         // Don't do special substitutions if inside a closure
1561                         break
1562                 }
1563                 n := n.(*ir.BranchStmt)
1564                 m := ir.Copy(n).(*ir.BranchStmt)
1565                 m.SetPos(subst.updatedPos(m.Pos()))
1566                 m.SetInit(nil)
1567                 m.Label = translateLabel(n.Label)
1568                 return m
1569
1570         case ir.OLABEL:
1571                 if subst.newclofn != nil {
1572                         // Don't do special substitutions if inside a closure
1573                         break
1574                 }
1575                 n := n.(*ir.LabelStmt)
1576                 m := ir.Copy(n).(*ir.LabelStmt)
1577                 m.SetPos(subst.updatedPos(m.Pos()))
1578                 m.SetInit(nil)
1579                 m.Label = translateLabel(n.Label)
1580                 return m
1581
1582         case ir.OCLOSURE:
1583                 return subst.closure(n.(*ir.ClosureExpr))
1584
1585         }
1586
1587         m := ir.Copy(n)
1588         m.SetPos(subst.updatedPos(m.Pos()))
1589         ir.EditChildren(m, subst.edit)
1590
1591         if subst.newclofn == nil {
1592                 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1593                 switch m.Op() {
1594                 case ir.OFOR:
1595                         m := m.(*ir.ForStmt)
1596                         m.Label = translateLabel(m.Label)
1597                         return m
1598
1599                 case ir.ORANGE:
1600                         m := m.(*ir.RangeStmt)
1601                         m.Label = translateLabel(m.Label)
1602                         return m
1603
1604                 case ir.OSWITCH:
1605                         m := m.(*ir.SwitchStmt)
1606                         m.Label = translateLabel(m.Label)
1607                         return m
1608
1609                 case ir.OSELECT:
1610                         m := m.(*ir.SelectStmt)
1611                         m.Label = translateLabel(m.Label)
1612                         return m
1613                 }
1614         }
1615
1616         switch m := m.(type) {
1617         case *ir.AssignStmt:
1618                 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1619                         lhs.Defn = m
1620                 }
1621         case *ir.AssignListStmt:
1622                 for _, lhs := range m.Lhs {
1623                         if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1624                                 lhs.Defn = m
1625                         }
1626                 }
1627         }
1628
1629         return m
1630 }
1631
1632 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1633 // adding "·inlgen".
1634 func translateLabel(l *types.Sym) *types.Sym {
1635         if l == nil {
1636                 return nil
1637         }
1638         p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1639         return typecheck.Lookup(p)
1640 }
1641
1642 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1643         if subst.noPosUpdate {
1644                 return xpos
1645         }
1646         pos := base.Ctxt.PosTable.Pos(xpos)
1647         oldbase := pos.Base() // can be nil
1648         newbase := subst.bases[oldbase]
1649         if newbase == nil {
1650                 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1651                 subst.bases[oldbase] = newbase
1652         }
1653         pos.SetBase(newbase)
1654         return base.Ctxt.PosTable.XPos(pos)
1655 }
1656
1657 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1658         s := make([]*ir.Name, 0, len(ll))
1659         for _, n := range ll {
1660                 if n.Class == ir.PAUTO {
1661                         if !vis.usedLocals.Has(n) {
1662                                 continue
1663                         }
1664                 }
1665                 s = append(s, n)
1666         }
1667         return s
1668 }
1669
1670 // numNonClosures returns the number of functions in list which are not closures.
1671 func numNonClosures(list []*ir.Func) int {
1672         count := 0
1673         for _, fn := range list {
1674                 if fn.OClosure == nil {
1675                         count++
1676                 }
1677         }
1678         return count
1679 }
1680
1681 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1682         for _, x := range list {
1683                 if x != nil {
1684                         if do(x) {
1685                                 return true
1686                         }
1687                 }
1688         }
1689         return false
1690 }
1691
1692 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1693 // into a coverage counter array.
1694 func isIndexingCoverageCounter(n ir.Node) bool {
1695         if n.Op() != ir.OINDEX {
1696                 return false
1697         }
1698         ixn := n.(*ir.IndexExpr)
1699         if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1700                 return false
1701         }
1702         nn := ixn.X.(*ir.Name)
1703         return nn.CoverageCounter()
1704 }
1705
1706 // isAtomicCoverageCounterUpdate examines the specified node to
1707 // determine whether it represents a call to sync/atomic.AddUint32 to
1708 // increment a coverage counter.
1709 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1710         if cn.X.Op() != ir.ONAME {
1711                 return false
1712         }
1713         name := cn.X.(*ir.Name)
1714         if name.Class != ir.PFUNC {
1715                 return false
1716         }
1717         fn := name.Sym().Name
1718         if name.Sym().Pkg.Path != "sync/atomic" ||
1719                 (fn != "AddUint32" && fn != "StoreUint32") {
1720                 return false
1721         }
1722         if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1723                 return false
1724         }
1725         adn := cn.Args[0].(*ir.AddrExpr)
1726         v := isIndexingCoverageCounter(adn.X)
1727         return v
1728 }