]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
cmd/compile: use HaveInlineBody for unified IR
[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         var inlCalls []*ir.InlinedCallExpr
536         var edit func(ir.Node) ir.Node
537         edit = func(n ir.Node) ir.Node {
538                 return inlnode(n, maxCost, &inlCalls, edit)
539         }
540         ir.EditChildren(fn, edit)
541
542         // If we inlined any calls, we want to recursively visit their
543         // bodies for further inlining. However, we need to wait until
544         // *after* the original function body has been expanded, or else
545         // inlCallee can have false positives (e.g., #54632).
546         for len(inlCalls) > 0 {
547                 call := inlCalls[0]
548                 inlCalls = inlCalls[1:]
549                 ir.EditChildren(call, edit)
550         }
551
552         ir.CurFunc = savefn
553 }
554
555 // inlnode recurses over the tree to find inlineable calls, which will
556 // be turned into OINLCALLs by mkinlcall. When the recursion comes
557 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
558 // nbody and nelse and use one of the 4 inlconv/glue functions above
559 // to turn the OINLCALL into an expression, a statement, or patch it
560 // in to this nodes list or rlist as appropriate.
561 // NOTE it makes no sense to pass the glue functions down the
562 // recursion to the level where the OINLCALL gets created because they
563 // have to edit /this/ n, so you'd have to push that one down as well,
564 // but then you may as well do it here.  so this is cleaner and
565 // shorter and less complicated.
566 // The result of inlnode MUST be assigned back to n, e.g.
567 //
568 //      n.Left = inlnode(n.Left)
569 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
570         if n == nil {
571                 return n
572         }
573
574         switch n.Op() {
575         case ir.ODEFER, ir.OGO:
576                 n := n.(*ir.GoDeferStmt)
577                 switch call := n.Call; call.Op() {
578                 case ir.OCALLMETH:
579                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
580                 case ir.OCALLFUNC:
581                         call := call.(*ir.CallExpr)
582                         call.NoInline = true
583                 }
584         case ir.OTAILCALL:
585                 n := n.(*ir.TailCallStmt)
586                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
587
588         // TODO do them here (or earlier),
589         // so escape analysis can avoid more heapmoves.
590         case ir.OCLOSURE:
591                 return n
592         case ir.OCALLMETH:
593                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
594         case ir.OCALLFUNC:
595                 n := n.(*ir.CallExpr)
596                 if n.X.Op() == ir.OMETHEXPR {
597                         // Prevent inlining some reflect.Value methods when using checkptr,
598                         // even when package reflect was compiled without it (#35073).
599                         if meth := ir.MethodExprName(n.X); meth != nil {
600                                 s := meth.Sym()
601                                 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
602                                         return n
603                                 }
604                         }
605                 }
606         }
607
608         lno := ir.SetPos(n)
609
610         ir.EditChildren(n, edit)
611
612         // with all the branches out of the way, it is now time to
613         // transmogrify this node itself unless inhibited by the
614         // switch at the top of this function.
615         switch n.Op() {
616         case ir.OCALLMETH:
617                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
618
619         case ir.OCALLFUNC:
620                 call := n.(*ir.CallExpr)
621                 if call.NoInline {
622                         break
623                 }
624                 if base.Flag.LowerM > 3 {
625                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
626                 }
627                 if ir.IsIntrinsicCall(call) {
628                         break
629                 }
630                 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
631                         n = mkinlcall(call, fn, maxCost, inlCalls, edit)
632                 }
633         }
634
635         base.Pos = lno
636
637         return n
638 }
639
640 // inlCallee takes a function-typed expression and returns the underlying function ONAME
641 // that it refers to if statically known. Otherwise, it returns nil.
642 func inlCallee(fn ir.Node) *ir.Func {
643         fn = ir.StaticValue(fn)
644         switch fn.Op() {
645         case ir.OMETHEXPR:
646                 fn := fn.(*ir.SelectorExpr)
647                 n := ir.MethodExprName(fn)
648                 // Check that receiver type matches fn.X.
649                 // TODO(mdempsky): Handle implicit dereference
650                 // of pointer receiver argument?
651                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
652                         return nil
653                 }
654                 return n.Func
655         case ir.ONAME:
656                 fn := fn.(*ir.Name)
657                 if fn.Class == ir.PFUNC {
658                         return fn.Func
659                 }
660         case ir.OCLOSURE:
661                 fn := fn.(*ir.ClosureExpr)
662                 c := fn.Func
663                 CanInline(c)
664                 return c
665         }
666         return nil
667 }
668
669 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
670         if t.Nname == nil {
671                 return ir.BlankNode
672         }
673         n := t.Nname.(*ir.Name)
674         if ir.IsBlank(n) {
675                 return ir.BlankNode
676         }
677         inlvar := inlvars[n]
678         if inlvar == nil {
679                 base.Fatalf("missing inlvar for %v", n)
680         }
681         as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
682         inlvar.Name().Defn = as
683         return inlvar
684 }
685
686 var inlgen int
687
688 // SSADumpInline gives the SSA back end a chance to dump the function
689 // when producing output for debugging the compiler itself.
690 var SSADumpInline = func(*ir.Func) {}
691
692 // InlineCall allows the inliner implementation to be overridden.
693 // If it returns nil, the function will not be inlined.
694 var InlineCall = oldInlineCall
695
696 // If n is a OCALLFUNC node, and fn is an ONAME node for a
697 // function with an inlinable body, return an OINLCALL node that can replace n.
698 // The returned node's Ninit has the parameter assignments, the Nbody is the
699 // inlined function body, and (List, Rlist) contain the (input, output)
700 // parameters.
701 // The result of mkinlcall MUST be assigned back to n, e.g.
702 //
703 //      n.Left = mkinlcall(n.Left, fn, isddd)
704 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
705         if fn.Inl == nil {
706                 if logopt.Enabled() {
707                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
708                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
709                 }
710                 return n
711         }
712         if fn.Inl.Cost > maxCost {
713                 // The inlined function body is too big. Typically we use this check to restrict
714                 // inlining into very big functions.  See issue 26546 and 17566.
715                 if logopt.Enabled() {
716                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
717                                 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
718                 }
719                 return n
720         }
721
722         if fn == ir.CurFunc {
723                 // Can't recursively inline a function into itself.
724                 if logopt.Enabled() {
725                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
726                 }
727                 return n
728         }
729
730         // The non-unified frontend has issues with inlining and shape parameters.
731         if base.Debug.Unified == 0 {
732                 // Don't inline a function fn that has no shape parameters, but is passed at
733                 // least one shape arg. This means we must be inlining a non-generic function
734                 // fn that was passed into a generic function, and can be called with a shape
735                 // arg because it matches an appropriate type parameters. But fn may include
736                 // an interface conversion (that may be applied to a shape arg) that was not
737                 // apparent when we first created the instantiation of the generic function.
738                 // We can't handle this if we actually do the inlining, since we want to know
739                 // all interface conversions immediately after stenciling. So, we avoid
740                 // inlining in this case, see issue #49309. (1)
741                 //
742                 // See discussion on go.dev/cl/406475 for more background.
743                 if !fn.Type().Params().HasShape() {
744                         for _, arg := range n.Args {
745                                 if arg.Type().HasShape() {
746                                         if logopt.Enabled() {
747                                                 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
748                                                         fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
749                                         }
750                                         return n
751                                 }
752                         }
753                 } else {
754                         // Don't inline a function fn that has shape parameters, but is passed no shape arg.
755                         // See comments (1) above, and issue #51909.
756                         inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
757                         for _, arg := range n.Args {
758                                 if arg.Type().HasShape() {
759                                         inlineable = true
760                                         break
761                                 }
762                         }
763                         if !inlineable {
764                                 if logopt.Enabled() {
765                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
766                                                 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
767                                 }
768                                 return n
769                         }
770                 }
771         }
772
773         if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
774                 // Runtime package must not be instrumented.
775                 // Instrument skips runtime package. However, some runtime code can be
776                 // inlined into other packages and instrumented there. To avoid this,
777                 // we disable inlining of runtime functions when instrumenting.
778                 // The example that we observed is inlining of LockOSThread,
779                 // which lead to false race reports on m contents.
780                 return n
781         }
782
783         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
784         sym := fn.Linksym()
785
786         // Check if we've already inlined this function at this particular
787         // call site, in order to stop inlining when we reach the beginning
788         // of a recursion cycle again. We don't inline immediately recursive
789         // functions, but allow inlining if there is a recursion cycle of
790         // many functions. Most likely, the inlining will stop before we
791         // even hit the beginning of the cycle again, but this catches the
792         // unusual case.
793         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
794                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
795                         if base.Flag.LowerM > 1 {
796                                 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
797                         }
798                         return n
799                 }
800         }
801
802         typecheck.FixVariadicCall(n)
803
804         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
805
806         if base.Flag.GenDwarfInl > 0 {
807                 if !sym.WasInlined() {
808                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
809                         sym.Set(obj.AttrWasInlined, true)
810                 }
811         }
812
813         if base.Flag.LowerM != 0 {
814                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
815         }
816         if base.Flag.LowerM > 2 {
817                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
818         }
819
820         res := InlineCall(n, fn, inlIndex)
821         if res == nil {
822                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
823         }
824
825         if base.Flag.LowerM > 2 {
826                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
827         }
828
829         *inlCalls = append(*inlCalls, res)
830
831         return res
832 }
833
834 // CalleeEffects appends any side effects from evaluating callee to init.
835 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
836         for {
837                 init.Append(ir.TakeInit(callee)...)
838
839                 switch callee.Op() {
840                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
841                         return // done
842
843                 case ir.OCONVNOP:
844                         conv := callee.(*ir.ConvExpr)
845                         callee = conv.X
846
847                 case ir.OINLCALL:
848                         ic := callee.(*ir.InlinedCallExpr)
849                         init.Append(ic.Body.Take()...)
850                         callee = ic.SingleResult()
851
852                 default:
853                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
854                 }
855         }
856 }
857
858 // oldInlineCall creates an InlinedCallExpr to replace the given call
859 // expression. fn is the callee function to be inlined. inlIndex is
860 // the inlining tree position index, for use with src.NewInliningBase
861 // when rewriting positions.
862 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
863         if base.Debug.TypecheckInl == 0 {
864                 typecheck.ImportedBody(fn)
865         }
866
867         SSADumpInline(fn)
868
869         ninit := call.Init()
870
871         // For normal function calls, the function callee expression
872         // may contain side effects. Make sure to preserve these,
873         // if necessary (#42703).
874         if call.Op() == ir.OCALLFUNC {
875                 CalleeEffects(&ninit, call.X)
876         }
877
878         // Make temp names to use instead of the originals.
879         inlvars := make(map[*ir.Name]*ir.Name)
880
881         // record formals/locals for later post-processing
882         var inlfvars []*ir.Name
883
884         for _, ln := range fn.Inl.Dcl {
885                 if ln.Op() != ir.ONAME {
886                         continue
887                 }
888                 if ln.Class == ir.PPARAMOUT { // return values handled below.
889                         continue
890                 }
891                 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
892                 inlvars[ln] = inlf
893                 if base.Flag.GenDwarfInl > 0 {
894                         if ln.Class == ir.PPARAM {
895                                 inlf.Name().SetInlFormal(true)
896                         } else {
897                                 inlf.Name().SetInlLocal(true)
898                         }
899                         inlf.SetPos(ln.Pos())
900                         inlfvars = append(inlfvars, inlf)
901                 }
902         }
903
904         // We can delay declaring+initializing result parameters if:
905         // temporaries for return values.
906         var retvars []ir.Node
907         for i, t := range fn.Type().Results().Fields().Slice() {
908                 var m *ir.Name
909                 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
910                         n := nn.(*ir.Name)
911                         m = inlvar(n)
912                         m = typecheck.Expr(m).(*ir.Name)
913                         inlvars[n] = m
914                 } else {
915                         // anonymous return values, synthesize names for use in assignment that replaces return
916                         m = retvar(t, i)
917                 }
918
919                 if base.Flag.GenDwarfInl > 0 {
920                         // Don't update the src.Pos on a return variable if it
921                         // was manufactured by the inliner (e.g. "~R2"); such vars
922                         // were not part of the original callee.
923                         if !strings.HasPrefix(m.Sym().Name, "~R") {
924                                 m.Name().SetInlFormal(true)
925                                 m.SetPos(t.Pos)
926                                 inlfvars = append(inlfvars, m)
927                         }
928                 }
929
930                 retvars = append(retvars, m)
931         }
932
933         // Assign arguments to the parameters' temp names.
934         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
935         as.Def = true
936         if call.Op() == ir.OCALLMETH {
937                 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
938         }
939         as.Rhs.Append(call.Args...)
940
941         if recv := fn.Type().Recv(); recv != nil {
942                 as.Lhs.Append(inlParam(recv, as, inlvars))
943         }
944         for _, param := range fn.Type().Params().Fields().Slice() {
945                 as.Lhs.Append(inlParam(param, as, inlvars))
946         }
947
948         if len(as.Rhs) != 0 {
949                 ninit.Append(typecheck.Stmt(as))
950         }
951
952         if !fn.Inl.CanDelayResults {
953                 // Zero the return parameters.
954                 for _, n := range retvars {
955                         ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
956                         ras := ir.NewAssignStmt(base.Pos, n, nil)
957                         ninit.Append(typecheck.Stmt(ras))
958                 }
959         }
960
961         retlabel := typecheck.AutoLabel(".i")
962
963         inlgen++
964
965         // Add an inline mark just before the inlined body.
966         // This mark is inline in the code so that it's a reasonable spot
967         // to put a breakpoint. Not sure if that's really necessary or not
968         // (in which case it could go at the end of the function instead).
969         // Note issue 28603.
970         ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
971
972         subst := inlsubst{
973                 retlabel:    retlabel,
974                 retvars:     retvars,
975                 inlvars:     inlvars,
976                 defnMarker:  ir.NilExpr{},
977                 bases:       make(map[*src.PosBase]*src.PosBase),
978                 newInlIndex: inlIndex,
979                 fn:          fn,
980         }
981         subst.edit = subst.node
982
983         body := subst.list(ir.Nodes(fn.Inl.Body))
984
985         lab := ir.NewLabelStmt(base.Pos, retlabel)
986         body = append(body, lab)
987
988         if base.Flag.GenDwarfInl > 0 {
989                 for _, v := range inlfvars {
990                         v.SetPos(subst.updatedPos(v.Pos()))
991                 }
992         }
993
994         //dumplist("ninit post", ninit);
995
996         res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
997         res.SetInit(ninit)
998         res.SetType(call.Type())
999         res.SetTypecheck(1)
1000         return res
1001 }
1002
1003 // Every time we expand a function we generate a new set of tmpnames,
1004 // PAUTO's in the calling functions, and link them off of the
1005 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1006 func inlvar(var_ *ir.Name) *ir.Name {
1007         if base.Flag.LowerM > 3 {
1008                 fmt.Printf("inlvar %+v\n", var_)
1009         }
1010
1011         n := typecheck.NewName(var_.Sym())
1012         n.SetType(var_.Type())
1013         n.SetTypecheck(1)
1014         n.Class = ir.PAUTO
1015         n.SetUsed(true)
1016         n.SetAutoTemp(var_.AutoTemp())
1017         n.Curfn = ir.CurFunc // the calling function, not the called one
1018         n.SetAddrtaken(var_.Addrtaken())
1019
1020         ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1021         return n
1022 }
1023
1024 // Synthesize a variable to store the inlined function's results in.
1025 func retvar(t *types.Field, i int) *ir.Name {
1026         n := typecheck.NewName(typecheck.LookupNum("~R", i))
1027         n.SetType(t.Type)
1028         n.SetTypecheck(1)
1029         n.Class = ir.PAUTO
1030         n.SetUsed(true)
1031         n.Curfn = ir.CurFunc // the calling function, not the called one
1032         ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1033         return n
1034 }
1035
1036 // The inlsubst type implements the actual inlining of a single
1037 // function call.
1038 type inlsubst struct {
1039         // Target of the goto substituted in place of a return.
1040         retlabel *types.Sym
1041
1042         // Temporary result variables.
1043         retvars []ir.Node
1044
1045         inlvars map[*ir.Name]*ir.Name
1046         // defnMarker is used to mark a Node for reassignment.
1047         // inlsubst.clovar set this during creating new ONAME.
1048         // inlsubst.node will set the correct Defn for inlvar.
1049         defnMarker ir.NilExpr
1050
1051         // bases maps from original PosBase to PosBase with an extra
1052         // inlined call frame.
1053         bases map[*src.PosBase]*src.PosBase
1054
1055         // newInlIndex is the index of the inlined call frame to
1056         // insert for inlined nodes.
1057         newInlIndex int
1058
1059         edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1060
1061         // If non-nil, we are inside a closure inside the inlined function, and
1062         // newclofn is the Func of the new inlined closure.
1063         newclofn *ir.Func
1064
1065         fn *ir.Func // For debug -- the func that is being inlined
1066
1067         // If true, then don't update source positions during substitution
1068         // (retain old source positions).
1069         noPosUpdate bool
1070 }
1071
1072 // list inlines a list of nodes.
1073 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1074         s := make([]ir.Node, 0, len(ll))
1075         for _, n := range ll {
1076                 s = append(s, subst.node(n))
1077         }
1078         return s
1079 }
1080
1081 // fields returns a list of the fields of a struct type representing receiver,
1082 // params, or results, after duplicating the field nodes and substituting the
1083 // Nname nodes inside the field nodes.
1084 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1085         oldfields := oldt.FieldSlice()
1086         newfields := make([]*types.Field, len(oldfields))
1087         for i := range oldfields {
1088                 newfields[i] = oldfields[i].Copy()
1089                 if oldfields[i].Nname != nil {
1090                         newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1091                 }
1092         }
1093         return newfields
1094 }
1095
1096 // clovar creates a new ONAME node for a local variable or param of a closure
1097 // inside a function being inlined.
1098 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1099         m := ir.NewNameAt(n.Pos(), n.Sym())
1100         m.Class = n.Class
1101         m.SetType(n.Type())
1102         m.SetTypecheck(1)
1103         if n.IsClosureVar() {
1104                 m.SetIsClosureVar(true)
1105         }
1106         if n.Addrtaken() {
1107                 m.SetAddrtaken(true)
1108         }
1109         if n.Used() {
1110                 m.SetUsed(true)
1111         }
1112         m.Defn = n.Defn
1113
1114         m.Curfn = subst.newclofn
1115
1116         switch defn := n.Defn.(type) {
1117         case nil:
1118                 // ok
1119         case *ir.Name:
1120                 if !n.IsClosureVar() {
1121                         base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1122                 }
1123                 if n.Sym().Pkg != types.LocalPkg {
1124                         // If the closure came from inlining a function from
1125                         // another package, must change package of captured
1126                         // variable to localpkg, so that the fields of the closure
1127                         // struct are local package and can be accessed even if
1128                         // name is not exported. If you disable this code, you can
1129                         // reproduce the problem by running 'go test
1130                         // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1131                         // how we create closure structs?
1132                         m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1133                 }
1134                 // Make sure any inlvar which is the Defn
1135                 // of an ONAME closure var is rewritten
1136                 // during inlining. Don't substitute
1137                 // if Defn node is outside inlined function.
1138                 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1139                         m.Defn = subst.node(n.Defn)
1140                 }
1141         case *ir.AssignStmt, *ir.AssignListStmt:
1142                 // Mark node for reassignment at the end of inlsubst.node.
1143                 m.Defn = &subst.defnMarker
1144         case *ir.TypeSwitchGuard:
1145                 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1146         case *ir.RangeStmt:
1147                 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1148         default:
1149                 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1150         }
1151
1152         if n.Outer != nil {
1153                 // Either the outer variable is defined in function being inlined,
1154                 // and we will replace it with the substituted variable, or it is
1155                 // defined outside the function being inlined, and we should just
1156                 // skip the outer variable (the closure variable of the function
1157                 // being inlined).
1158                 s := subst.node(n.Outer).(*ir.Name)
1159                 if s == n.Outer {
1160                         s = n.Outer.Outer
1161                 }
1162                 m.Outer = s
1163         }
1164         return m
1165 }
1166
1167 // closure does the necessary substitions for a ClosureExpr n and returns the new
1168 // closure node.
1169 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1170         // Prior to the subst edit, set a flag in the inlsubst to indicate
1171         // that we don't want to update the source positions in the new
1172         // closure function. If we do this, it will appear that the
1173         // closure itself has things inlined into it, which is not the
1174         // case. See issue #46234 for more details. At the same time, we
1175         // do want to update the position in the new ClosureExpr (which is
1176         // part of the function we're working on). See #49171 for an
1177         // example of what happens if we miss that update.
1178         newClosurePos := subst.updatedPos(n.Pos())
1179         defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1180         subst.noPosUpdate = true
1181
1182         //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1183
1184         oldfn := n.Func
1185         newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1186
1187         if subst.newclofn != nil {
1188                 //fmt.Printf("Inlining a closure with a nested closure\n")
1189         }
1190         prevxfunc := subst.newclofn
1191
1192         // Mark that we are now substituting within a closure (within the
1193         // inlined function), and create new nodes for all the local
1194         // vars/params inside this closure.
1195         subst.newclofn = newfn
1196         newfn.Dcl = nil
1197         newfn.ClosureVars = nil
1198         for _, oldv := range oldfn.Dcl {
1199                 newv := subst.clovar(oldv)
1200                 subst.inlvars[oldv] = newv
1201                 newfn.Dcl = append(newfn.Dcl, newv)
1202         }
1203         for _, oldv := range oldfn.ClosureVars {
1204                 newv := subst.clovar(oldv)
1205                 subst.inlvars[oldv] = newv
1206                 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1207         }
1208
1209         // Need to replace ONAME nodes in
1210         // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1211         oldt := oldfn.Type()
1212         newrecvs := subst.fields(oldt.Recvs())
1213         var newrecv *types.Field
1214         if len(newrecvs) > 0 {
1215                 newrecv = newrecvs[0]
1216         }
1217         newt := types.NewSignature(oldt.Pkg(), newrecv,
1218                 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1219
1220         newfn.Nname.SetType(newt)
1221         newfn.Body = subst.list(oldfn.Body)
1222
1223         // Remove the nodes for the current closure from subst.inlvars
1224         for _, oldv := range oldfn.Dcl {
1225                 delete(subst.inlvars, oldv)
1226         }
1227         for _, oldv := range oldfn.ClosureVars {
1228                 delete(subst.inlvars, oldv)
1229         }
1230         // Go back to previous closure func
1231         subst.newclofn = prevxfunc
1232
1233         // Actually create the named function for the closure, now that
1234         // the closure is inlined in a specific function.
1235         newclo := newfn.OClosure
1236         newclo.SetPos(newClosurePos)
1237         newclo.SetInit(subst.list(n.Init()))
1238         return typecheck.Expr(newclo)
1239 }
1240
1241 // node recursively copies a node from the saved pristine body of the
1242 // inlined function, substituting references to input/output
1243 // parameters with ones to the tmpnames, and substituting returns with
1244 // assignments to the output.
1245 func (subst *inlsubst) node(n ir.Node) ir.Node {
1246         if n == nil {
1247                 return nil
1248         }
1249
1250         switch n.Op() {
1251         case ir.ONAME:
1252                 n := n.(*ir.Name)
1253
1254                 // Handle captured variables when inlining closures.
1255                 if n.IsClosureVar() && subst.newclofn == nil {
1256                         o := n.Outer
1257
1258                         // Deal with case where sequence of closures are inlined.
1259                         // TODO(danscales) - write test case to see if we need to
1260                         // go up multiple levels.
1261                         if o.Curfn != ir.CurFunc {
1262                                 o = o.Outer
1263                         }
1264
1265                         // make sure the outer param matches the inlining location
1266                         if o == nil || o.Curfn != ir.CurFunc {
1267                                 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1268                         }
1269
1270                         if base.Flag.LowerM > 2 {
1271                                 fmt.Printf("substituting captured name %+v  ->  %+v\n", n, o)
1272                         }
1273                         return o
1274                 }
1275
1276                 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1277                         if base.Flag.LowerM > 2 {
1278                                 fmt.Printf("substituting name %+v  ->  %+v\n", n, inlvar)
1279                         }
1280                         return inlvar
1281                 }
1282
1283                 if base.Flag.LowerM > 2 {
1284                         fmt.Printf("not substituting name %+v\n", n)
1285                 }
1286                 return n
1287
1288         case ir.OMETHEXPR:
1289                 n := n.(*ir.SelectorExpr)
1290                 return n
1291
1292         case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1293                 // If n is a named constant or type, we can continue
1294                 // using it in the inline copy. Otherwise, make a copy
1295                 // so we can update the line number.
1296                 if n.Sym() != nil {
1297                         return n
1298                 }
1299
1300         case ir.ORETURN:
1301                 if subst.newclofn != nil {
1302                         // Don't do special substitutions if inside a closure
1303                         break
1304                 }
1305                 // Because of the above test for subst.newclofn,
1306                 // this return is guaranteed to belong to the current inlined function.
1307                 n := n.(*ir.ReturnStmt)
1308                 init := subst.list(n.Init())
1309                 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1310                         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1311
1312                         // Make a shallow copy of retvars.
1313                         // Otherwise OINLCALL.Rlist will be the same list,
1314                         // and later walk and typecheck may clobber it.
1315                         for _, n := range subst.retvars {
1316                                 as.Lhs.Append(n)
1317                         }
1318                         as.Rhs = subst.list(n.Results)
1319
1320                         if subst.fn.Inl.CanDelayResults {
1321                                 for _, n := range as.Lhs {
1322                                         as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1323                                         n.Name().Defn = as
1324                                 }
1325                         }
1326
1327                         init = append(init, typecheck.Stmt(as))
1328                 }
1329                 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1330                 typecheck.Stmts(init)
1331                 return ir.NewBlockStmt(base.Pos, init)
1332
1333         case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1334                 if subst.newclofn != nil {
1335                         // Don't do special substitutions if inside a closure
1336                         break
1337                 }
1338                 n := n.(*ir.BranchStmt)
1339                 m := ir.Copy(n).(*ir.BranchStmt)
1340                 m.SetPos(subst.updatedPos(m.Pos()))
1341                 m.SetInit(nil)
1342                 m.Label = translateLabel(n.Label)
1343                 return m
1344
1345         case ir.OLABEL:
1346                 if subst.newclofn != nil {
1347                         // Don't do special substitutions if inside a closure
1348                         break
1349                 }
1350                 n := n.(*ir.LabelStmt)
1351                 m := ir.Copy(n).(*ir.LabelStmt)
1352                 m.SetPos(subst.updatedPos(m.Pos()))
1353                 m.SetInit(nil)
1354                 m.Label = translateLabel(n.Label)
1355                 return m
1356
1357         case ir.OCLOSURE:
1358                 return subst.closure(n.(*ir.ClosureExpr))
1359
1360         }
1361
1362         m := ir.Copy(n)
1363         m.SetPos(subst.updatedPos(m.Pos()))
1364         ir.EditChildren(m, subst.edit)
1365
1366         if subst.newclofn == nil {
1367                 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1368                 switch m.Op() {
1369                 case ir.OFOR:
1370                         m := m.(*ir.ForStmt)
1371                         m.Label = translateLabel(m.Label)
1372                         return m
1373
1374                 case ir.ORANGE:
1375                         m := m.(*ir.RangeStmt)
1376                         m.Label = translateLabel(m.Label)
1377                         return m
1378
1379                 case ir.OSWITCH:
1380                         m := m.(*ir.SwitchStmt)
1381                         m.Label = translateLabel(m.Label)
1382                         return m
1383
1384                 case ir.OSELECT:
1385                         m := m.(*ir.SelectStmt)
1386                         m.Label = translateLabel(m.Label)
1387                         return m
1388                 }
1389         }
1390
1391         switch m := m.(type) {
1392         case *ir.AssignStmt:
1393                 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1394                         lhs.Defn = m
1395                 }
1396         case *ir.AssignListStmt:
1397                 for _, lhs := range m.Lhs {
1398                         if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1399                                 lhs.Defn = m
1400                         }
1401                 }
1402         }
1403
1404         return m
1405 }
1406
1407 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1408 // adding "·inlgen".
1409 func translateLabel(l *types.Sym) *types.Sym {
1410         if l == nil {
1411                 return nil
1412         }
1413         p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1414         return typecheck.Lookup(p)
1415 }
1416
1417 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1418         if subst.noPosUpdate {
1419                 return xpos
1420         }
1421         pos := base.Ctxt.PosTable.Pos(xpos)
1422         oldbase := pos.Base() // can be nil
1423         newbase := subst.bases[oldbase]
1424         if newbase == nil {
1425                 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1426                 subst.bases[oldbase] = newbase
1427         }
1428         pos.SetBase(newbase)
1429         return base.Ctxt.PosTable.XPos(pos)
1430 }
1431
1432 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1433         s := make([]*ir.Name, 0, len(ll))
1434         for _, n := range ll {
1435                 if n.Class == ir.PAUTO {
1436                         if !vis.usedLocals.Has(n) {
1437                                 continue
1438                         }
1439                 }
1440                 s = append(s, n)
1441         }
1442         return s
1443 }
1444
1445 // numNonClosures returns the number of functions in list which are not closures.
1446 func numNonClosures(list []*ir.Func) int {
1447         count := 0
1448         for _, fn := range list {
1449                 if fn.OClosure == nil {
1450                         count++
1451                 }
1452         }
1453         return count
1454 }
1455
1456 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1457         for _, x := range list {
1458                 if x != nil {
1459                         if do(x) {
1460                                 return true
1461                         }
1462                 }
1463         }
1464         return false
1465 }