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