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