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