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