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.
5 // The inlining facility makes 2 passes: first CanInline determines which
6 // functions are suitable for inlining, and for those that are it
7 // saves a copy of the body. Then InlineCalls walks each function body to
8 // expand calls to inlinable functions.
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
14 // 1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
17 // 4: allow non-leaf functions
19 // At some point this may get another default and become switch-offable with -N.
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
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.
35 "cmd/compile/internal/base"
36 "cmd/compile/internal/ir"
37 "cmd/compile/internal/logopt"
38 "cmd/compile/internal/pgo"
39 "cmd/compile/internal/typecheck"
40 "cmd/compile/internal/types"
45 // Inlining budget parameters, gathered in one place
48 inlineExtraAppendCost = 0
49 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
50 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
51 inlineExtraPanicCost = 1 // do not penalize inlining panics.
52 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
54 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
55 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
59 // List of all hot ndes.
60 candHotNodeMap = make(map[*pgo.IRNode]struct{})
62 // List of all hot call sites.
63 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
65 // List of inlined call sites.
66 inlinedCallSites = make(map[pgo.CallSiteInfo]struct{})
68 // Threshold in percentage for hot function inlining.
69 inlineHotFuncThresholdPercent = float64(2)
71 // Threshold in percentage for hot callsite inlining.
72 inlineHotCallSiteThresholdPercent = float64(0.1)
74 // Budget increased due to hotness.
75 inlineHotMaxBudget int32 = 160
78 // InlinePrologue records the hot callsites from ir-graph.
79 func InlinePrologue() {
80 if s, err := strconv.ParseFloat(base.Debug.InlineHotFuncThreshold, 64); err == nil {
81 inlineHotFuncThresholdPercent = s
82 if base.Debug.PGOInline > 0 {
83 fmt.Printf("hot-node-thres=%v\n", inlineHotFuncThresholdPercent)
87 if s, err := strconv.ParseFloat(base.Debug.InlineHotCallSiteThreshold, 64); err == nil {
88 inlineHotCallSiteThresholdPercent = s
89 if base.Debug.PGOInline > 0 {
90 fmt.Printf("hot-callsite-thres=%v\n", inlineHotCallSiteThresholdPercent)
94 if base.Debug.InlineHotBudget != 0 {
95 inlineHotMaxBudget = int32(base.Debug.InlineHotBudget)
98 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
99 for _, f := range list {
100 name := ir.PkgFuncName(f)
101 if n, ok := pgo.WeightedCG.IRNodes[name]; ok {
102 nodeweight := pgo.WeightInPercentage(n.Flat, pgo.GlobalTotalNodeWeight)
103 if nodeweight > inlineHotFuncThresholdPercent {
104 candHotNodeMap[n] = struct{}{}
106 for _, e := range pgo.WeightedCG.OutEdges[n] {
108 edgeweightpercent := pgo.WeightInPercentage(e.Weight, pgo.GlobalTotalEdgeWeight)
109 if edgeweightpercent > inlineHotCallSiteThresholdPercent {
110 csi := pgo.CallSiteInfo{Line: e.CallSite, Caller: n.AST, Callee: e.Dst.AST}
111 if _, ok := candHotEdgeMap[csi]; !ok {
112 candHotEdgeMap[csi] = struct{}{}
120 if base.Debug.PGOInline > 0 {
121 fmt.Printf("hot-cg before inline in dot format:")
122 pgo.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
126 // InlineEpilogue updates IRGraph after inlining.
127 func InlineEpilogue() {
128 if base.Debug.PGOInline > 0 {
129 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
130 for _, f := range list {
131 name := ir.PkgFuncName(f)
132 if n, ok := pgo.WeightedCG.IRNodes[name]; ok {
133 pgo.RedirectEdges(n, inlinedCallSites)
137 // Print the call-graph after inlining. This is a debugging feature.
138 fmt.Printf("hot-cg after inline in dot:")
139 pgo.PrintWeightedCallGraphDOT(inlineHotFuncThresholdPercent, inlineHotCallSiteThresholdPercent)
143 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
144 func InlinePackage() {
145 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
146 numfns := numNonClosures(list)
147 for _, n := range list {
148 if !recursive || numfns > 1 {
149 // We allow inlining if there is no
150 // recursion, or the recursion cycle is
151 // across more than one function.
154 if base.Flag.LowerM > 1 {
155 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
163 // CanInline determines whether fn is inlineable.
164 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
165 // fn and fn.Body will already have been typechecked.
166 func CanInline(fn *ir.Func) {
168 base.Fatalf("CanInline no nname %+v", fn)
171 // Initialize an empty list of hot callsites for this caller.
172 pgo.ListOfHotCallSites = make(map[pgo.CallSiteInfo]struct{})
174 var reason string // reason, if any, that the function was not inlined
175 if base.Flag.LowerM > 1 || logopt.Enabled() {
178 if base.Flag.LowerM > 1 {
179 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
181 if logopt.Enabled() {
182 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
188 // If marked "go:noinline", don't inline
189 if fn.Pragma&ir.Noinline != 0 {
190 reason = "marked go:noinline"
194 // If marked "go:norace" and -race compilation, don't inline.
195 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
196 reason = "marked go:norace with -race compilation"
200 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
201 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
202 reason = "marked go:nocheckptr"
206 // If marked "go:cgo_unsafe_args", don't inline, since the
207 // function makes assumptions about its argument frame layout.
208 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
209 reason = "marked go:cgo_unsafe_args"
213 // If marked as "go:uintptrkeepalive", don't inline, since the
214 // keep alive information is lost during inlining.
216 // TODO(prattmic): This is handled on calls during escape analysis,
217 // which is after inlining. Move prior to inlining so the keep-alive is
218 // maintained after inlining.
219 if fn.Pragma&ir.UintptrKeepAlive != 0 {
220 reason = "marked as having a keep-alive uintptr argument"
224 // If marked as "go:uintptrescapes", don't inline, since the
225 // escape information is lost during inlining.
226 if fn.Pragma&ir.UintptrEscapes != 0 {
227 reason = "marked as having an escaping uintptr argument"
231 // The nowritebarrierrec checker currently works at function
232 // granularity, so inlining yeswritebarrierrec functions can
233 // confuse it (#22342). As a workaround, disallow inlining
235 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
236 reason = "marked go:yeswritebarrierrec"
240 // If fn has no body (is defined outside of Go), cannot inline it.
241 if len(fn.Body) == 0 {
242 reason = "no function body"
246 if fn.Typecheck() == 0 {
247 base.Fatalf("CanInline on non-typechecked function %v", fn)
251 if n.Func.InlinabilityChecked() {
254 defer n.Func.SetInlinabilityChecked(true)
256 cc := int32(inlineExtraCallCost)
257 if base.Flag.LowerL == 4 {
258 cc = 1 // this appears to yield better performance than 0.
261 // Update the budget for profile-guided inlining.
262 budget := int32(inlineMaxBudget)
263 if base.Flag.PgoProfile != "" && pgo.WeightedCG != nil {
264 if n, ok := pgo.WeightedCG.IRNodes[ir.PkgFuncName(fn)]; ok {
265 if _, ok := candHotNodeMap[n]; ok {
266 budget = int32(inlineHotMaxBudget)
267 if base.Debug.PGOInline > 0 {
268 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
274 // At this point in the game the function we're looking at may
275 // have "stale" autos, vars that still appear in the Dcl list, but
276 // which no longer have any uses in the function body (due to
277 // elimination by deadcode). We'd like to exclude these dead vars
278 // when creating the "Inline.Dcl" field below; to accomplish this,
279 // the hairyVisitor below builds up a map of used/referenced
280 // locals, and we use this map to produce a pruned Inline.Dcl
281 // list. See issue 25249 for more context.
283 visitor := hairyVisitor{
289 if visitor.tooHairy(fn) {
290 reason = visitor.reason
294 n.Func.Inl = &ir.Inline{
295 Cost: budget - visitor.budget,
296 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
297 Body: inlcopylist(fn.Body),
299 CanDelayResults: canDelayResults(fn),
302 if base.Flag.LowerM > 1 {
303 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(n.Func.Inl.Body))
304 } else if base.Flag.LowerM != 0 {
305 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
307 if logopt.Enabled() {
308 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
312 // canDelayResults reports whether inlined calls to fn can delay
313 // declaring the result parameter until the "return" statement.
314 func canDelayResults(fn *ir.Func) bool {
315 // We can delay declaring+initializing result parameters if:
316 // (1) there's exactly one "return" statement in the inlined function;
317 // (2) it's not an empty return statement (#44355); and
318 // (3) the result parameters aren't named.
321 ir.VisitList(fn.Body, func(n ir.Node) {
322 if n, ok := n.(*ir.ReturnStmt); ok {
324 if len(n.Results) == 0 {
325 nreturns++ // empty return statement (case 2)
331 return false // not exactly one return statement (case 1)
334 // temporaries for return values.
335 for _, param := range fn.Type().Results().FieldSlice() {
336 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
337 return false // found a named result parameter (case 3)
344 // hairyVisitor visits a function body to determine its inlining
345 // hairiness and whether or not it can be inlined.
346 type hairyVisitor struct {
347 // This is needed to access the current caller in the doNode function.
353 usedLocals ir.NameSet
354 do func(ir.Node) bool
357 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
358 v.do = v.doNode // cache closure
359 if ir.DoChildren(fn, v.do) {
363 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
369 func (v *hairyVisitor) doNode(n ir.Node) bool {
374 // Call is okay if inlinable and we have the budget for the body.
376 n := n.(*ir.CallExpr)
377 // Functions that call runtime.getcaller{pc,sp} can not be inlined
378 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
380 // runtime.throw is a "cheap call" like panic in normal code.
381 if n.X.Op() == ir.ONAME {
382 name := n.X.(*ir.Name)
383 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
384 fn := name.Sym().Name
385 if fn == "getcallerpc" || fn == "getcallersp" {
386 v.reason = "call to " + fn
390 v.budget -= inlineExtraThrowCost
394 // Special case for coverage counter updates; although
395 // these correspond to real operations, we treat them as
396 // zero cost for the moment. This is due to the existence
397 // of tests that are sensitive to inlining-- if the
398 // insertion of coverage instrumentation happens to tip a
399 // given function over the threshold and move it from
400 // "inlinable" to "not-inlinable", this can cause changes
401 // in allocation behavior, which can then result in test
402 // failures (a good example is the TestAllocations in
404 if isAtomicCoverageCounterUpdate(n) {
408 if n.X.Op() == ir.OMETHEXPR {
409 if meth := ir.MethodExprName(n.X); meth != nil {
410 if fn := meth.Func; fn != nil {
413 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
414 // Special case: explicitly allow mid-stack inlining of
415 // runtime.heapBits.next even though it calls slow-path
416 // runtime.heapBits.nextArena.
419 // Special case: on architectures that can do unaligned loads,
420 // explicitly mark encoding/binary methods as cheap,
421 // because in practice they are, even though our inlining
422 // budgeting system does not see that. See issue 42958.
423 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
425 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
426 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
427 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
428 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
429 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
430 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
435 break // treat like any other node, that is, cost of 1
441 // Determine if the callee edge is a for hot callee or not.
442 if base.Flag.PgoProfile != "" && pgo.WeightedCG != nil && v.curFunc != nil {
443 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
444 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
445 csi := pgo.CallSiteInfo{Line: line, Caller: v.curFunc, Callee: fn}
446 if _, o := candHotEdgeMap[csi]; o {
447 pgo.ListOfHotCallSites[pgo.CallSiteInfo{Line: line, Caller: v.curFunc}] = struct{}{}
448 if base.Debug.PGOInline > 0 {
449 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
455 if ir.IsIntrinsicCall(n) {
456 // Treat like any other node.
460 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
461 v.budget -= fn.Inl.Cost
465 // Call cost for non-leaf inlining.
466 v.budget -= v.extraCallCost
469 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
471 // Things that are too hairy, irrespective of the budget
472 case ir.OCALL, ir.OCALLINTER:
473 // Call cost for non-leaf inlining.
474 v.budget -= v.extraCallCost
477 n := n.(*ir.UnaryExpr)
478 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
479 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
480 // Before CL 284412, these conversions were introduced later in the
481 // compiler, so they didn't count against inlining budget.
484 v.budget -= inlineExtraPanicCost
487 // recover matches the argument frame pointer to find
488 // the right panic value, so it needs an argument frame.
489 v.reason = "call to recover"
493 if base.Debug.InlFuncsWithClosures == 0 {
494 v.reason = "not inlining functions with closures"
498 // TODO(danscales): Maybe make budget proportional to number of closure
500 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
502 // Scan body of closure (which DoChildren doesn't automatically
503 // do) to check for disallowed ops in the body and include the
504 // body in the budget.
505 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
511 ir.ODCLTYPE, // can't print yet
513 v.reason = "unhandled op " + n.Op().String()
517 v.budget -= inlineExtraAppendCost
520 n := n.(*ir.AddrExpr)
521 // Make "&s.f" cost 0 when f's offset is zero.
522 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
523 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
524 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
529 // *(*X)(unsafe.Pointer(&x)) is low-cost
530 n := n.(*ir.StarExpr)
533 for ptr.Op() == ir.OCONVNOP {
534 ptr = ptr.(*ir.ConvExpr).X
536 if ptr.Op() == ir.OADDR {
537 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
541 // This doesn't produce code, but the children might.
542 v.budget++ // undo default cost
544 case ir.ODCLCONST, ir.OFALL:
545 // These nodes don't produce code; omit from inlining budget.
550 if ir.IsConst(n.Cond, constant.Bool) {
551 // This if and the condition cost nothing.
552 if doList(n.Init(), v.do) {
555 if ir.BoolVal(n.Cond) {
556 return doList(n.Body, v.do)
558 return doList(n.Else, v.do)
564 if n.Class == ir.PAUTO {
569 // The only OBLOCK we should see at this point is an empty one.
570 // In any event, let the visitList(n.List()) below take care of the statements,
571 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
574 case ir.OMETHVALUE, ir.OSLICELIT:
575 v.budget-- // Hack for toolstash -cmp.
578 v.budget++ // Hack for toolstash -cmp.
581 n := n.(*ir.AssignListStmt)
583 // Unified IR unconditionally rewrites:
594 // so that it can insert implicit conversions as necessary. To
595 // minimize impact to the existing inlining heuristics (in
596 // particular, to avoid breaking the existing inlinability regress
597 // tests), we need to compensate for this here.
598 if base.Debug.Unified != 0 {
599 if init := n.Rhs[0].Init(); len(init) == 1 {
600 if _, ok := init[0].(*ir.AssignListStmt); ok {
601 // 4 for each value, because each temporary variable now
602 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
604 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
605 v.budget += 4*int32(len(n.Lhs)) + 1
611 // Special case for coverage counter updates and coverage
612 // function registrations. Although these correspond to real
613 // operations, we treat them as zero cost for the moment. This
614 // is primarily due to the existence of tests that are
615 // sensitive to inlining-- if the insertion of coverage
616 // instrumentation happens to tip a given function over the
617 // threshold and move it from "inlinable" to "not-inlinable",
618 // this can cause changes in allocation behavior, which can
619 // then result in test failures (a good example is the
620 // TestAllocations in crypto/ed25519).
621 n := n.(*ir.AssignStmt)
622 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n) {
629 // When debugging, don't stop early, to get full cost of inlining this function
630 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
631 v.reason = "too expensive"
635 return ir.DoChildren(n, v.do)
638 func isBigFunc(fn *ir.Func) bool {
639 budget := inlineBigFunctionNodes
640 return ir.Any(fn, func(n ir.Node) bool {
646 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
647 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
648 // the body and dcls of an inlineable function.
649 func inlcopylist(ll []ir.Node) []ir.Node {
650 s := make([]ir.Node, len(ll))
651 for i, n := range ll {
657 // inlcopy is like DeepCopy(), but does extra work to copy closures.
658 func inlcopy(n ir.Node) ir.Node {
659 var edit func(ir.Node) ir.Node
660 edit = func(x ir.Node) ir.Node {
662 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
666 ir.EditChildren(m, edit)
667 if x.Op() == ir.OCLOSURE {
668 x := x.(*ir.ClosureExpr)
669 // Need to save/duplicate x.Func.Nname,
670 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
671 // x.Func.Body for iexport and local inlining.
673 newfn := ir.NewFunc(oldfn.Pos())
674 m.(*ir.ClosureExpr).Func = newfn
675 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
676 // XXX OK to share fn.Type() ??
677 newfn.Nname.SetType(oldfn.Nname.Type())
678 newfn.Body = inlcopylist(oldfn.Body)
679 // Make shallow copy of the Dcl and ClosureVar slices
680 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
681 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
688 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
689 // calls made to inlineable functions. This is the external entry point.
690 func InlineCalls(fn *ir.Func) {
693 maxCost := int32(inlineMaxBudget)
695 maxCost = inlineBigFunctionMaxCost
697 var inlCalls []*ir.InlinedCallExpr
698 var edit func(ir.Node) ir.Node
699 edit = func(n ir.Node) ir.Node {
700 return inlnode(n, maxCost, &inlCalls, edit)
702 ir.EditChildren(fn, edit)
704 // If we inlined any calls, we want to recursively visit their
705 // bodies for further inlining. However, we need to wait until
706 // *after* the original function body has been expanded, or else
707 // inlCallee can have false positives (e.g., #54632).
708 for len(inlCalls) > 0 {
710 inlCalls = inlCalls[1:]
711 ir.EditChildren(call, edit)
717 // inlnode recurses over the tree to find inlineable calls, which will
718 // be turned into OINLCALLs by mkinlcall. When the recursion comes
719 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
720 // nbody and nelse and use one of the 4 inlconv/glue functions above
721 // to turn the OINLCALL into an expression, a statement, or patch it
722 // in to this nodes list or rlist as appropriate.
723 // NOTE it makes no sense to pass the glue functions down the
724 // recursion to the level where the OINLCALL gets created because they
725 // have to edit /this/ n, so you'd have to push that one down as well,
726 // but then you may as well do it here. so this is cleaner and
727 // shorter and less complicated.
728 // The result of inlnode MUST be assigned back to n, e.g.
730 // n.Left = inlnode(n.Left)
731 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
737 case ir.ODEFER, ir.OGO:
738 n := n.(*ir.GoDeferStmt)
739 switch call := n.Call; call.Op() {
741 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
743 call := call.(*ir.CallExpr)
747 n := n.(*ir.TailCallStmt)
748 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
750 // TODO do them here (or earlier),
751 // so escape analysis can avoid more heapmoves.
755 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
757 n := n.(*ir.CallExpr)
758 if n.X.Op() == ir.OMETHEXPR {
759 // Prevent inlining some reflect.Value methods when using checkptr,
760 // even when package reflect was compiled without it (#35073).
761 if meth := ir.MethodExprName(n.X); meth != nil {
763 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
772 ir.EditChildren(n, edit)
774 // with all the branches out of the way, it is now time to
775 // transmogrify this node itself unless inhibited by the
776 // switch at the top of this function.
779 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
782 call := n.(*ir.CallExpr)
786 if base.Flag.LowerM > 3 {
787 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
789 if ir.IsIntrinsicCall(call) {
792 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
793 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
802 // inlCallee takes a function-typed expression and returns the underlying function ONAME
803 // that it refers to if statically known. Otherwise, it returns nil.
804 func inlCallee(fn ir.Node) *ir.Func {
805 fn = ir.StaticValue(fn)
808 fn := fn.(*ir.SelectorExpr)
809 n := ir.MethodExprName(fn)
810 // Check that receiver type matches fn.X.
811 // TODO(mdempsky): Handle implicit dereference
812 // of pointer receiver argument?
813 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
819 if fn.Class == ir.PFUNC {
823 fn := fn.(*ir.ClosureExpr)
831 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
835 n := t.Nname.(*ir.Name)
841 base.Fatalf("missing inlvar for %v", n)
843 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
844 inlvar.Name().Defn = as
850 // SSADumpInline gives the SSA back end a chance to dump the function
851 // when producing output for debugging the compiler itself.
852 var SSADumpInline = func(*ir.Func) {}
854 // InlineCall allows the inliner implementation to be overridden.
855 // If it returns nil, the function will not be inlined.
856 var InlineCall = oldInlineCall
858 // If n is a OCALLFUNC node, and fn is an ONAME node for a
859 // function with an inlinable body, return an OINLCALL node that can replace n.
860 // The returned node's Ninit has the parameter assignments, the Nbody is the
861 // inlined function body, and (List, Rlist) contain the (input, output)
863 // The result of mkinlcall MUST be assigned back to n, e.g.
865 // n.Left = mkinlcall(n.Left, fn, isddd)
866 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
868 if logopt.Enabled() {
869 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
870 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
874 if fn.Inl.Cost > maxCost {
875 // If the callsite is hot and it is under the inlineHotMaxBudget budget, then try to inline it, or else bail.
876 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
877 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
878 if _, ok := pgo.ListOfHotCallSites[csi]; ok {
879 if fn.Inl.Cost > inlineHotMaxBudget {
880 if logopt.Enabled() {
881 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
882 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), inlineHotMaxBudget))
886 if base.Debug.PGOInline > 0 {
887 fmt.Printf("hot-budget check allows inlining for callsite at %v\n", ir.Line(n))
890 // The inlined function body is too big. Typically we use this check to restrict
891 // inlining into very big functions. See issue 26546 and 17566.
892 if logopt.Enabled() {
893 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
894 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
900 if fn == ir.CurFunc {
901 // Can't recursively inline a function into itself.
902 if logopt.Enabled() {
903 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
908 // The non-unified frontend has issues with inlining and shape parameters.
909 if base.Debug.Unified == 0 {
910 // Don't inline a function fn that has no shape parameters, but is passed at
911 // least one shape arg. This means we must be inlining a non-generic function
912 // fn that was passed into a generic function, and can be called with a shape
913 // arg because it matches an appropriate type parameters. But fn may include
914 // an interface conversion (that may be applied to a shape arg) that was not
915 // apparent when we first created the instantiation of the generic function.
916 // We can't handle this if we actually do the inlining, since we want to know
917 // all interface conversions immediately after stenciling. So, we avoid
918 // inlining in this case, see issue #49309. (1)
920 // See discussion on go.dev/cl/406475 for more background.
921 if !fn.Type().Params().HasShape() {
922 for _, arg := range n.Args {
923 if arg.Type().HasShape() {
924 if logopt.Enabled() {
925 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
926 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
932 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
933 // See comments (1) above, and issue #51909.
934 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
935 for _, arg := range n.Args {
936 if arg.Type().HasShape() {
942 if logopt.Enabled() {
943 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
944 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
951 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
952 // Runtime package must not be instrumented.
953 // Instrument skips runtime package. However, some runtime code can be
954 // inlined into other packages and instrumented there. To avoid this,
955 // we disable inlining of runtime functions when instrumenting.
956 // The example that we observed is inlining of LockOSThread,
957 // which lead to false race reports on m contents.
961 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
964 // Check if we've already inlined this function at this particular
965 // call site, in order to stop inlining when we reach the beginning
966 // of a recursion cycle again. We don't inline immediately recursive
967 // functions, but allow inlining if there is a recursion cycle of
968 // many functions. Most likely, the inlining will stop before we
969 // even hit the beginning of the cycle again, but this catches the
971 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
972 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
973 if base.Flag.LowerM > 1 {
974 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
980 typecheck.FixVariadicCall(n)
982 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
984 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
985 // The linker needs FuncInfo metadata for all inlined
986 // functions. This is typically handled by gc.enqueueFunc
987 // calling ir.InitLSym for all function declarations in
988 // typecheck.Target.Decls (ir.UseClosure adds all closures to
991 // However, non-trivial closures in Decls are ignored, and are
992 // insteaded enqueued when walk of the calling function
995 // This presents a problem for direct calls to closures.
996 // Inlining will replace the entire closure definition with its
997 // body, which hides the closure from walk and thus suppresses
1000 // Explicitly create a symbol early in this edge case to ensure
1001 // we keep this metadata.
1003 // TODO: Refactor to keep a reference so this can all be done
1006 if n.Op() != ir.OCALLFUNC {
1007 // Not a standard call.
1010 if n.X.Op() != ir.OCLOSURE {
1011 // Not a direct closure call.
1015 clo := n.X.(*ir.ClosureExpr)
1016 if ir.IsTrivialClosure(clo) {
1017 // enqueueFunc will handle trivial closures anyways.
1021 ir.InitLSym(fn, true)
1024 closureInitLSym(n, fn)
1026 if base.Flag.GenDwarfInl > 0 {
1027 if !sym.WasInlined() {
1028 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1029 sym.Set(obj.AttrWasInlined, true)
1033 if base.Flag.LowerM != 0 {
1034 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1036 if base.Flag.LowerM > 2 {
1037 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1040 if base.Debug.PGOInline > 0 {
1041 line := int(base.Ctxt.InnermostPos(n.Pos()).RelLine())
1042 csi := pgo.CallSiteInfo{Line: line, Caller: ir.CurFunc}
1043 if _, ok := inlinedCallSites[csi]; !ok {
1044 inlinedCallSites[csi] = struct{}{}
1048 res := InlineCall(n, fn, inlIndex)
1051 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1054 if base.Flag.LowerM > 2 {
1055 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1058 *inlCalls = append(*inlCalls, res)
1063 // CalleeEffects appends any side effects from evaluating callee to init.
1064 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1066 init.Append(ir.TakeInit(callee)...)
1068 switch callee.Op() {
1069 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1073 conv := callee.(*ir.ConvExpr)
1077 ic := callee.(*ir.InlinedCallExpr)
1078 init.Append(ic.Body.Take()...)
1079 callee = ic.SingleResult()
1082 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1087 // oldInlineCall creates an InlinedCallExpr to replace the given call
1088 // expression. fn is the callee function to be inlined. inlIndex is
1089 // the inlining tree position index, for use with src.NewInliningBase
1090 // when rewriting positions.
1091 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
1092 if base.Debug.TypecheckInl == 0 {
1093 typecheck.ImportedBody(fn)
1098 ninit := call.Init()
1100 // For normal function calls, the function callee expression
1101 // may contain side effects. Make sure to preserve these,
1102 // if necessary (#42703).
1103 if call.Op() == ir.OCALLFUNC {
1104 CalleeEffects(&ninit, call.X)
1107 // Make temp names to use instead of the originals.
1108 inlvars := make(map[*ir.Name]*ir.Name)
1110 // record formals/locals for later post-processing
1111 var inlfvars []*ir.Name
1113 for _, ln := range fn.Inl.Dcl {
1114 if ln.Op() != ir.ONAME {
1117 if ln.Class == ir.PPARAMOUT { // return values handled below.
1120 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
1122 if base.Flag.GenDwarfInl > 0 {
1123 if ln.Class == ir.PPARAM {
1124 inlf.Name().SetInlFormal(true)
1126 inlf.Name().SetInlLocal(true)
1128 inlf.SetPos(ln.Pos())
1129 inlfvars = append(inlfvars, inlf)
1133 // We can delay declaring+initializing result parameters if:
1134 // temporaries for return values.
1135 var retvars []ir.Node
1136 for i, t := range fn.Type().Results().Fields().Slice() {
1138 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
1141 m = typecheck.Expr(m).(*ir.Name)
1144 // anonymous return values, synthesize names for use in assignment that replaces return
1148 if base.Flag.GenDwarfInl > 0 {
1149 // Don't update the src.Pos on a return variable if it
1150 // was manufactured by the inliner (e.g. "~R2"); such vars
1151 // were not part of the original callee.
1152 if !strings.HasPrefix(m.Sym().Name, "~R") {
1153 m.Name().SetInlFormal(true)
1155 inlfvars = append(inlfvars, m)
1159 retvars = append(retvars, m)
1162 // Assign arguments to the parameters' temp names.
1163 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1165 if call.Op() == ir.OCALLMETH {
1166 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1168 as.Rhs.Append(call.Args...)
1170 if recv := fn.Type().Recv(); recv != nil {
1171 as.Lhs.Append(inlParam(recv, as, inlvars))
1173 for _, param := range fn.Type().Params().Fields().Slice() {
1174 as.Lhs.Append(inlParam(param, as, inlvars))
1177 if len(as.Rhs) != 0 {
1178 ninit.Append(typecheck.Stmt(as))
1181 if !fn.Inl.CanDelayResults {
1182 // Zero the return parameters.
1183 for _, n := range retvars {
1184 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1185 ras := ir.NewAssignStmt(base.Pos, n, nil)
1186 ninit.Append(typecheck.Stmt(ras))
1190 retlabel := typecheck.AutoLabel(".i")
1194 // Add an inline mark just before the inlined body.
1195 // This mark is inline in the code so that it's a reasonable spot
1196 // to put a breakpoint. Not sure if that's really necessary or not
1197 // (in which case it could go at the end of the function instead).
1198 // Note issue 28603.
1199 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1205 defnMarker: ir.NilExpr{},
1206 bases: make(map[*src.PosBase]*src.PosBase),
1207 newInlIndex: inlIndex,
1210 subst.edit = subst.node
1212 body := subst.list(ir.Nodes(fn.Inl.Body))
1214 lab := ir.NewLabelStmt(base.Pos, retlabel)
1215 body = append(body, lab)
1217 if base.Flag.GenDwarfInl > 0 {
1218 for _, v := range inlfvars {
1219 v.SetPos(subst.updatedPos(v.Pos()))
1223 //dumplist("ninit post", ninit);
1225 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1227 res.SetType(call.Type())
1232 // Every time we expand a function we generate a new set of tmpnames,
1233 // PAUTO's in the calling functions, and link them off of the
1234 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1235 func inlvar(var_ *ir.Name) *ir.Name {
1236 if base.Flag.LowerM > 3 {
1237 fmt.Printf("inlvar %+v\n", var_)
1240 n := typecheck.NewName(var_.Sym())
1241 n.SetType(var_.Type())
1245 n.SetAutoTemp(var_.AutoTemp())
1246 n.Curfn = ir.CurFunc // the calling function, not the called one
1247 n.SetAddrtaken(var_.Addrtaken())
1249 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1253 // Synthesize a variable to store the inlined function's results in.
1254 func retvar(t *types.Field, i int) *ir.Name {
1255 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1260 n.Curfn = ir.CurFunc // the calling function, not the called one
1261 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1265 // The inlsubst type implements the actual inlining of a single
1267 type inlsubst struct {
1268 // Target of the goto substituted in place of a return.
1271 // Temporary result variables.
1274 inlvars map[*ir.Name]*ir.Name
1275 // defnMarker is used to mark a Node for reassignment.
1276 // inlsubst.clovar set this during creating new ONAME.
1277 // inlsubst.node will set the correct Defn for inlvar.
1278 defnMarker ir.NilExpr
1280 // bases maps from original PosBase to PosBase with an extra
1281 // inlined call frame.
1282 bases map[*src.PosBase]*src.PosBase
1284 // newInlIndex is the index of the inlined call frame to
1285 // insert for inlined nodes.
1288 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1290 // If non-nil, we are inside a closure inside the inlined function, and
1291 // newclofn is the Func of the new inlined closure.
1294 fn *ir.Func // For debug -- the func that is being inlined
1296 // If true, then don't update source positions during substitution
1297 // (retain old source positions).
1301 // list inlines a list of nodes.
1302 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1303 s := make([]ir.Node, 0, len(ll))
1304 for _, n := range ll {
1305 s = append(s, subst.node(n))
1310 // fields returns a list of the fields of a struct type representing receiver,
1311 // params, or results, after duplicating the field nodes and substituting the
1312 // Nname nodes inside the field nodes.
1313 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1314 oldfields := oldt.FieldSlice()
1315 newfields := make([]*types.Field, len(oldfields))
1316 for i := range oldfields {
1317 newfields[i] = oldfields[i].Copy()
1318 if oldfields[i].Nname != nil {
1319 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1325 // clovar creates a new ONAME node for a local variable or param of a closure
1326 // inside a function being inlined.
1327 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1328 m := ir.NewNameAt(n.Pos(), n.Sym())
1332 if n.IsClosureVar() {
1333 m.SetIsClosureVar(true)
1336 m.SetAddrtaken(true)
1343 m.Curfn = subst.newclofn
1345 switch defn := n.Defn.(type) {
1349 if !n.IsClosureVar() {
1350 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1352 if n.Sym().Pkg != types.LocalPkg {
1353 // If the closure came from inlining a function from
1354 // another package, must change package of captured
1355 // variable to localpkg, so that the fields of the closure
1356 // struct are local package and can be accessed even if
1357 // name is not exported. If you disable this code, you can
1358 // reproduce the problem by running 'go test
1359 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1360 // how we create closure structs?
1361 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1363 // Make sure any inlvar which is the Defn
1364 // of an ONAME closure var is rewritten
1365 // during inlining. Don't substitute
1366 // if Defn node is outside inlined function.
1367 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1368 m.Defn = subst.node(n.Defn)
1370 case *ir.AssignStmt, *ir.AssignListStmt:
1371 // Mark node for reassignment at the end of inlsubst.node.
1372 m.Defn = &subst.defnMarker
1373 case *ir.TypeSwitchGuard:
1374 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1376 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1378 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1382 // Either the outer variable is defined in function being inlined,
1383 // and we will replace it with the substituted variable, or it is
1384 // defined outside the function being inlined, and we should just
1385 // skip the outer variable (the closure variable of the function
1387 s := subst.node(n.Outer).(*ir.Name)
1396 // closure does the necessary substitions for a ClosureExpr n and returns the new
1398 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1399 // Prior to the subst edit, set a flag in the inlsubst to indicate
1400 // that we don't want to update the source positions in the new
1401 // closure function. If we do this, it will appear that the
1402 // closure itself has things inlined into it, which is not the
1403 // case. See issue #46234 for more details. At the same time, we
1404 // do want to update the position in the new ClosureExpr (which is
1405 // part of the function we're working on). See #49171 for an
1406 // example of what happens if we miss that update.
1407 newClosurePos := subst.updatedPos(n.Pos())
1408 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1409 subst.noPosUpdate = true
1411 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1414 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1416 if subst.newclofn != nil {
1417 //fmt.Printf("Inlining a closure with a nested closure\n")
1419 prevxfunc := subst.newclofn
1421 // Mark that we are now substituting within a closure (within the
1422 // inlined function), and create new nodes for all the local
1423 // vars/params inside this closure.
1424 subst.newclofn = newfn
1426 newfn.ClosureVars = nil
1427 for _, oldv := range oldfn.Dcl {
1428 newv := subst.clovar(oldv)
1429 subst.inlvars[oldv] = newv
1430 newfn.Dcl = append(newfn.Dcl, newv)
1432 for _, oldv := range oldfn.ClosureVars {
1433 newv := subst.clovar(oldv)
1434 subst.inlvars[oldv] = newv
1435 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1438 // Need to replace ONAME nodes in
1439 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1440 oldt := oldfn.Type()
1441 newrecvs := subst.fields(oldt.Recvs())
1442 var newrecv *types.Field
1443 if len(newrecvs) > 0 {
1444 newrecv = newrecvs[0]
1446 newt := types.NewSignature(oldt.Pkg(), newrecv,
1447 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1449 newfn.Nname.SetType(newt)
1450 newfn.Body = subst.list(oldfn.Body)
1452 // Remove the nodes for the current closure from subst.inlvars
1453 for _, oldv := range oldfn.Dcl {
1454 delete(subst.inlvars, oldv)
1456 for _, oldv := range oldfn.ClosureVars {
1457 delete(subst.inlvars, oldv)
1459 // Go back to previous closure func
1460 subst.newclofn = prevxfunc
1462 // Actually create the named function for the closure, now that
1463 // the closure is inlined in a specific function.
1464 newclo := newfn.OClosure
1465 newclo.SetPos(newClosurePos)
1466 newclo.SetInit(subst.list(n.Init()))
1467 return typecheck.Expr(newclo)
1470 // node recursively copies a node from the saved pristine body of the
1471 // inlined function, substituting references to input/output
1472 // parameters with ones to the tmpnames, and substituting returns with
1473 // assignments to the output.
1474 func (subst *inlsubst) node(n ir.Node) ir.Node {
1483 // Handle captured variables when inlining closures.
1484 if n.IsClosureVar() && subst.newclofn == nil {
1487 // Deal with case where sequence of closures are inlined.
1488 // TODO(danscales) - write test case to see if we need to
1489 // go up multiple levels.
1490 if o.Curfn != ir.CurFunc {
1494 // make sure the outer param matches the inlining location
1495 if o == nil || o.Curfn != ir.CurFunc {
1496 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1499 if base.Flag.LowerM > 2 {
1500 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1505 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1506 if base.Flag.LowerM > 2 {
1507 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1512 if base.Flag.LowerM > 2 {
1513 fmt.Printf("not substituting name %+v\n", n)
1518 n := n.(*ir.SelectorExpr)
1521 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1522 // If n is a named constant or type, we can continue
1523 // using it in the inline copy. Otherwise, make a copy
1524 // so we can update the line number.
1530 if subst.newclofn != nil {
1531 // Don't do special substitutions if inside a closure
1534 // Because of the above test for subst.newclofn,
1535 // this return is guaranteed to belong to the current inlined function.
1536 n := n.(*ir.ReturnStmt)
1537 init := subst.list(n.Init())
1538 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1539 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1541 // Make a shallow copy of retvars.
1542 // Otherwise OINLCALL.Rlist will be the same list,
1543 // and later walk and typecheck may clobber it.
1544 for _, n := range subst.retvars {
1547 as.Rhs = subst.list(n.Results)
1549 if subst.fn.Inl.CanDelayResults {
1550 for _, n := range as.Lhs {
1551 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1556 init = append(init, typecheck.Stmt(as))
1558 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1559 typecheck.Stmts(init)
1560 return ir.NewBlockStmt(base.Pos, init)
1562 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1563 if subst.newclofn != nil {
1564 // Don't do special substitutions if inside a closure
1567 n := n.(*ir.BranchStmt)
1568 m := ir.Copy(n).(*ir.BranchStmt)
1569 m.SetPos(subst.updatedPos(m.Pos()))
1571 m.Label = translateLabel(n.Label)
1575 if subst.newclofn != nil {
1576 // Don't do special substitutions if inside a closure
1579 n := n.(*ir.LabelStmt)
1580 m := ir.Copy(n).(*ir.LabelStmt)
1581 m.SetPos(subst.updatedPos(m.Pos()))
1583 m.Label = translateLabel(n.Label)
1587 return subst.closure(n.(*ir.ClosureExpr))
1592 m.SetPos(subst.updatedPos(m.Pos()))
1593 ir.EditChildren(m, subst.edit)
1595 if subst.newclofn == nil {
1596 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1599 m := m.(*ir.ForStmt)
1600 m.Label = translateLabel(m.Label)
1604 m := m.(*ir.RangeStmt)
1605 m.Label = translateLabel(m.Label)
1609 m := m.(*ir.SwitchStmt)
1610 m.Label = translateLabel(m.Label)
1614 m := m.(*ir.SelectStmt)
1615 m.Label = translateLabel(m.Label)
1620 switch m := m.(type) {
1621 case *ir.AssignStmt:
1622 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1625 case *ir.AssignListStmt:
1626 for _, lhs := range m.Lhs {
1627 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1636 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1637 // adding "·inlgen".
1638 func translateLabel(l *types.Sym) *types.Sym {
1642 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1643 return typecheck.Lookup(p)
1646 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1647 if subst.noPosUpdate {
1650 pos := base.Ctxt.PosTable.Pos(xpos)
1651 oldbase := pos.Base() // can be nil
1652 newbase := subst.bases[oldbase]
1654 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1655 subst.bases[oldbase] = newbase
1657 pos.SetBase(newbase)
1658 return base.Ctxt.PosTable.XPos(pos)
1661 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1662 s := make([]*ir.Name, 0, len(ll))
1663 for _, n := range ll {
1664 if n.Class == ir.PAUTO {
1665 if !vis.usedLocals.Has(n) {
1674 // numNonClosures returns the number of functions in list which are not closures.
1675 func numNonClosures(list []*ir.Func) int {
1677 for _, fn := range list {
1678 if fn.OClosure == nil {
1685 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1686 for _, x := range list {
1696 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1697 // into a coverage counter array.
1698 func isIndexingCoverageCounter(n ir.Node) bool {
1699 if n.Op() != ir.OINDEX {
1702 ixn := n.(*ir.IndexExpr)
1703 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1706 nn := ixn.X.(*ir.Name)
1707 return nn.CoverageCounter()
1710 // isAtomicCoverageCounterUpdate examines the specified node to
1711 // determine whether it represents a call to sync/atomic.AddUint32 to
1712 // increment a coverage counter.
1713 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1714 if cn.X.Op() != ir.ONAME {
1717 name := cn.X.(*ir.Name)
1718 if name.Class != ir.PFUNC {
1721 fn := name.Sym().Name
1722 if name.Sym().Pkg.Path != "sync/atomic" || fn != "AddUint32" {
1725 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1728 adn := cn.Args[0].(*ir.AddrExpr)
1729 v := isIndexingCoverageCounter(adn.X)