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