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"
44 // Inlining budget parameters, gathered in one place
47 inlineExtraAppendCost = 0
48 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
49 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
50 inlineExtraPanicCost = 1 // do not penalize inlining panics.
51 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
54 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
58 // List of all hot callee nodes.
59 // TODO(prattmic): Make this non-global.
60 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62 // List of all hot call sites. CallSiteInfo.Callee is always nil.
63 // TODO(prattmic): Make this non-global.
64 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66 // Threshold in percentage for hot callsite inlining.
67 inlineHotCallSiteThresholdPercent float64
69 // Threshold in CDF percentage for hot callsite inlining,
70 // that is, for a threshold of X the hottest callsites that
71 // make up the top X% of total edge weight will be
72 // considered hot for inlining candidates.
73 inlineCDFHotCallSiteThresholdPercent = float64(99)
75 // Budget increased due to hotness.
76 inlineHotMaxBudget int32 = 2000
79 // pgoInlinePrologue records the hot callsites from ir-graph.
80 func pgoInlinePrologue(p *pgo.Profile, decls []ir.Node) {
81 if base.Debug.PGOInlineCDFThreshold != "" {
82 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
83 inlineCDFHotCallSiteThresholdPercent = s
85 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
88 var hotCallsites []pgo.NodeMapKey
89 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
90 if base.Debug.PGODebug > 0 {
91 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
94 if x := base.Debug.PGOInlineBudget; x != 0 {
95 inlineHotMaxBudget = int32(x)
98 for _, n := range hotCallsites {
99 // mark inlineable callees from hot edges
100 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
101 candHotCalleeMap[callee] = struct{}{}
103 // mark hot call sites
104 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil {
105 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
106 candHotEdgeMap[csi] = struct{}{}
110 if base.Debug.PGODebug >= 2 {
111 fmt.Printf("hot-cg before inline in dot format:")
112 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
116 // hotNodesFromCDF computes an edge weight threshold and the list of hot
117 // nodes that make up the given percentage of the CDF. The threshold, as
118 // a percent, is the lower bound of weight for nodes to be considered hot
119 // (currently only used in debug prints) (in case of equal weights,
120 // comparing with the threshold may not accurately reflect which nodes are
122 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
123 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
125 for n := range p.NodeMap {
129 sort.Slice(nodes, func(i, j int) bool {
130 ni, nj := nodes[i], nodes[j]
131 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
132 return wi > wj // want larger weight first
134 // same weight, order by name/line number
135 if ni.CallerName != nj.CallerName {
136 return ni.CallerName < nj.CallerName
138 if ni.CalleeName != nj.CalleeName {
139 return ni.CalleeName < nj.CalleeName
141 return ni.CallSiteOffset < nj.CallSiteOffset
144 for i, n := range nodes {
145 w := p.NodeMap[n].EWeight
147 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
148 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
149 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
150 // include that node instead of excluding it.)
151 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
157 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
158 func InlinePackage(p *pgo.Profile) {
159 if base.Debug.PGOInline == 0 {
163 InlineDecls(p, typecheck.Target.Decls, true)
165 // Perform a garbage collection of hidden closures functions that
166 // are no longer reachable from top-level functions following
167 // inlining. See #59404 and #59638 for more context.
168 garbageCollectUnreferencedHiddenClosures()
171 // InlineDecls applies inlining to the given batch of declarations.
172 func InlineDecls(p *pgo.Profile, decls []ir.Node, doInline bool) {
174 pgoInlinePrologue(p, decls)
177 doCanInline := func(n *ir.Func, recursive bool, numfns int) {
178 if !recursive || numfns > 1 {
179 // We allow inlining if there is no
180 // recursion, or the recursion cycle is
181 // across more than one function.
184 if base.Flag.LowerM > 1 && n.OClosure == nil {
185 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
190 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
191 numfns := numNonClosures(list)
192 // We visit functions within an SCC in fairly arbitrary order,
193 // so by computing inlinability for all functions in the SCC
194 // before performing any inlining, the results are less
195 // sensitive to the order within the SCC (see #58905 for an
198 // First compute inlinability for all functions in the SCC ...
199 for _, n := range list {
200 doCanInline(n, recursive, numfns)
202 // ... then make a second pass to do inlining of calls.
204 for _, n := range list {
211 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
212 // top-level (non-hidden-closure) functions looking for nested closure
213 // functions that are reachable, then sweeps through the Target.Decls
214 // list and marks any non-reachable hidden closure function as dead.
215 // See issues #59404 and #59638 for more context.
216 func garbageCollectUnreferencedHiddenClosures() {
218 liveFuncs := make(map[*ir.Func]bool)
220 var markLiveFuncs func(fn *ir.Func)
221 markLiveFuncs = func(fn *ir.Func) {
226 ir.Visit(fn, func(n ir.Node) {
227 if clo, ok := n.(*ir.ClosureExpr); ok {
228 markLiveFuncs(clo.Func)
233 for i := 0; i < len(typecheck.Target.Decls); i++ {
234 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
235 if fn.IsHiddenClosure() {
242 for i := 0; i < len(typecheck.Target.Decls); i++ {
243 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
244 if !fn.IsHiddenClosure() {
247 if fn.IsDeadcodeClosure() {
253 fn.SetIsDeadcodeClosure(true)
254 if base.Flag.LowerM > 2 {
255 fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
257 if fn.Inl != nil && fn.LSym == nil {
258 ir.InitLSym(fn, true)
264 // CanInline determines whether fn is inlineable.
265 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
266 // fn and fn.Body will already have been typechecked.
267 func CanInline(fn *ir.Func, profile *pgo.Profile) {
269 base.Fatalf("CanInline no nname %+v", fn)
272 var reason string // reason, if any, that the function was not inlined
273 if base.Flag.LowerM > 1 || logopt.Enabled() {
276 if base.Flag.LowerM > 1 {
277 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
279 if logopt.Enabled() {
280 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
286 // If marked "go:noinline", don't inline
287 if fn.Pragma&ir.Noinline != 0 {
288 reason = "marked go:noinline"
292 // If marked "go:norace" and -race compilation, don't inline.
293 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
294 reason = "marked go:norace with -race compilation"
298 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
299 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
300 reason = "marked go:nocheckptr"
304 // If marked "go:cgo_unsafe_args", don't inline, since the
305 // function makes assumptions about its argument frame layout.
306 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
307 reason = "marked go:cgo_unsafe_args"
311 // If marked as "go:uintptrkeepalive", don't inline, since the
312 // keep alive information is lost during inlining.
314 // TODO(prattmic): This is handled on calls during escape analysis,
315 // which is after inlining. Move prior to inlining so the keep-alive is
316 // maintained after inlining.
317 if fn.Pragma&ir.UintptrKeepAlive != 0 {
318 reason = "marked as having a keep-alive uintptr argument"
322 // If marked as "go:uintptrescapes", don't inline, since the
323 // escape information is lost during inlining.
324 if fn.Pragma&ir.UintptrEscapes != 0 {
325 reason = "marked as having an escaping uintptr argument"
329 // The nowritebarrierrec checker currently works at function
330 // granularity, so inlining yeswritebarrierrec functions can
331 // confuse it (#22342). As a workaround, disallow inlining
333 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
334 reason = "marked go:yeswritebarrierrec"
338 // If fn has no body (is defined outside of Go), cannot inline it.
339 if len(fn.Body) == 0 {
340 reason = "no function body"
344 // If fn is synthetic hash or eq function, cannot inline it.
345 // The function is not generated in Unified IR frontend at this moment.
346 if ir.IsEqOrHashFunc(fn) {
347 reason = "type eq/hash function"
351 if fn.Typecheck() == 0 {
352 base.Fatalf("CanInline on non-typechecked function %v", fn)
356 if n.Func.InlinabilityChecked() {
359 defer n.Func.SetInlinabilityChecked(true)
361 cc := int32(inlineExtraCallCost)
362 if base.Flag.LowerL == 4 {
363 cc = 1 // this appears to yield better performance than 0.
366 // Update the budget for profile-guided inlining.
367 budget := int32(inlineMaxBudget)
369 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
370 if _, ok := candHotCalleeMap[n]; ok {
371 budget = int32(inlineHotMaxBudget)
372 if base.Debug.PGODebug > 0 {
373 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
379 // At this point in the game the function we're looking at may
380 // have "stale" autos, vars that still appear in the Dcl list, but
381 // which no longer have any uses in the function body (due to
382 // elimination by deadcode). We'd like to exclude these dead vars
383 // when creating the "Inline.Dcl" field below; to accomplish this,
384 // the hairyVisitor below builds up a map of used/referenced
385 // locals, and we use this map to produce a pruned Inline.Dcl
386 // list. See issue 25249 for more context.
388 visitor := hairyVisitor{
395 if visitor.tooHairy(fn) {
396 reason = visitor.reason
400 n.Func.Inl = &ir.Inline{
401 Cost: budget - visitor.budget,
402 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
403 Body: inlcopylist(fn.Body),
405 CanDelayResults: canDelayResults(fn),
408 if base.Flag.LowerM > 1 {
409 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))
410 } else if base.Flag.LowerM != 0 {
411 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
413 if logopt.Enabled() {
414 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
418 // canDelayResults reports whether inlined calls to fn can delay
419 // declaring the result parameter until the "return" statement.
420 func canDelayResults(fn *ir.Func) bool {
421 // We can delay declaring+initializing result parameters if:
422 // (1) there's exactly one "return" statement in the inlined function;
423 // (2) it's not an empty return statement (#44355); and
424 // (3) the result parameters aren't named.
427 ir.VisitList(fn.Body, func(n ir.Node) {
428 if n, ok := n.(*ir.ReturnStmt); ok {
430 if len(n.Results) == 0 {
431 nreturns++ // empty return statement (case 2)
437 return false // not exactly one return statement (case 1)
440 // temporaries for return values.
441 for _, param := range fn.Type().Results().FieldSlice() {
442 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
443 return false // found a named result parameter (case 3)
450 // hairyVisitor visits a function body to determine its inlining
451 // hairiness and whether or not it can be inlined.
452 type hairyVisitor struct {
453 // This is needed to access the current caller in the doNode function.
459 usedLocals ir.NameSet
460 do func(ir.Node) bool
464 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
465 v.do = v.doNode // cache closure
466 if ir.DoChildren(fn, v.do) {
470 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
476 // doNode visits n and its children, updates the state in v, and returns true if
477 // n makes the current function too hairy for inlining.
478 func (v *hairyVisitor) doNode(n ir.Node) bool {
483 // Call is okay if inlinable and we have the budget for the body.
485 n := n.(*ir.CallExpr)
486 // Functions that call runtime.getcaller{pc,sp} can not be inlined
487 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
489 // runtime.throw is a "cheap call" like panic in normal code.
491 if n.X.Op() == ir.ONAME {
492 name := n.X.(*ir.Name)
493 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
494 fn := name.Sym().Name
495 if fn == "getcallerpc" || fn == "getcallersp" {
496 v.reason = "call to " + fn
500 v.budget -= inlineExtraThrowCost
504 // Special case for reflect.noescpae. It does just type
505 // conversions to appease the escape analysis, and doesn't
507 if name.Class == ir.PFUNC && types.IsReflectPkg(name.Sym().Pkg) {
508 if name.Sym().Name == "noescape" {
512 // Special case for coverage counter updates; although
513 // these correspond to real operations, we treat them as
514 // zero cost for the moment. This is due to the existence
515 // of tests that are sensitive to inlining-- if the
516 // insertion of coverage instrumentation happens to tip a
517 // given function over the threshold and move it from
518 // "inlinable" to "not-inlinable", this can cause changes
519 // in allocation behavior, which can then result in test
520 // failures (a good example is the TestAllocations in
522 if isAtomicCoverageCounterUpdate(n) {
526 if n.X.Op() == ir.OMETHEXPR {
527 if meth := ir.MethodExprName(n.X); meth != nil {
528 if fn := meth.Func; fn != nil {
530 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
531 // Special case: explicitly allow mid-stack inlining of
532 // runtime.heapBits.next even though it calls slow-path
533 // runtime.heapBits.nextArena.
536 // Special case: on architectures that can do unaligned loads,
537 // explicitly mark encoding/binary methods as cheap,
538 // because in practice they are, even though our inlining
539 // budgeting system does not see that. See issue 42958.
540 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
542 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
543 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
544 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
545 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
546 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
547 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
555 break // treat like any other node, that is, cost of 1
558 // Determine if the callee edge is for an inlinable hot callee or not.
559 if v.profile != nil && v.curFunc != nil {
560 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
561 lineOffset := pgo.NodeLineOffset(n, fn)
562 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
563 if _, o := candHotEdgeMap[csi]; o {
564 if base.Debug.PGODebug > 0 {
565 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
571 if ir.IsIntrinsicCall(n) {
572 // Treat like any other node.
576 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
577 v.budget -= fn.Inl.Cost
581 // Call cost for non-leaf inlining.
582 v.budget -= v.extraCallCost
585 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
587 // Things that are too hairy, irrespective of the budget
588 case ir.OCALL, ir.OCALLINTER:
589 // Call cost for non-leaf inlining.
590 v.budget -= v.extraCallCost
593 n := n.(*ir.UnaryExpr)
594 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
595 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
596 // Before CL 284412, these conversions were introduced later in the
597 // compiler, so they didn't count against inlining budget.
600 v.budget -= inlineExtraPanicCost
603 // recover matches the argument frame pointer to find
604 // the right panic value, so it needs an argument frame.
605 v.reason = "call to recover"
609 if base.Debug.InlFuncsWithClosures == 0 {
610 v.reason = "not inlining functions with closures"
614 // TODO(danscales): Maybe make budget proportional to number of closure
616 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
617 // TODO(austin): However, if we're able to inline this closure into
618 // v.curFunc, then we actually pay nothing for the closure captures. We
619 // should try to account for that if we're going to account for captures.
624 ir.ODCLTYPE, // can't print yet
626 v.reason = "unhandled op " + n.Op().String()
630 v.budget -= inlineExtraAppendCost
633 n := n.(*ir.AddrExpr)
634 // Make "&s.f" cost 0 when f's offset is zero.
635 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
636 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
637 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
642 // *(*X)(unsafe.Pointer(&x)) is low-cost
643 n := n.(*ir.StarExpr)
646 for ptr.Op() == ir.OCONVNOP {
647 ptr = ptr.(*ir.ConvExpr).X
649 if ptr.Op() == ir.OADDR {
650 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
654 // This doesn't produce code, but the children might.
655 v.budget++ // undo default cost
657 case ir.ODCLCONST, ir.OFALL, ir.OTYPE:
658 // These nodes don't produce code; omit from inlining budget.
663 if ir.IsConst(n.Cond, constant.Bool) {
664 // This if and the condition cost nothing.
665 if doList(n.Init(), v.do) {
668 if ir.BoolVal(n.Cond) {
669 return doList(n.Body, v.do)
671 return doList(n.Else, v.do)
677 if n.Class == ir.PAUTO {
682 // The only OBLOCK we should see at this point is an empty one.
683 // In any event, let the visitList(n.List()) below take care of the statements,
684 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
687 case ir.OMETHVALUE, ir.OSLICELIT:
688 v.budget-- // Hack for toolstash -cmp.
691 v.budget++ // Hack for toolstash -cmp.
694 n := n.(*ir.AssignListStmt)
696 // Unified IR unconditionally rewrites:
707 // so that it can insert implicit conversions as necessary. To
708 // minimize impact to the existing inlining heuristics (in
709 // particular, to avoid breaking the existing inlinability regress
710 // tests), we need to compensate for this here.
712 // See also identical logic in isBigFunc.
713 if init := n.Rhs[0].Init(); len(init) == 1 {
714 if _, ok := init[0].(*ir.AssignListStmt); ok {
715 // 4 for each value, because each temporary variable now
716 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
718 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
719 v.budget += 4*int32(len(n.Lhs)) + 1
724 // Special case for coverage counter updates and coverage
725 // function registrations. Although these correspond to real
726 // operations, we treat them as zero cost for the moment. This
727 // is primarily due to the existence of tests that are
728 // sensitive to inlining-- if the insertion of coverage
729 // instrumentation happens to tip a given function over the
730 // threshold and move it from "inlinable" to "not-inlinable",
731 // this can cause changes in allocation behavior, which can
732 // then result in test failures (a good example is the
733 // TestAllocations in crypto/ed25519).
734 n := n.(*ir.AssignStmt)
735 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
742 // When debugging, don't stop early, to get full cost of inlining this function
743 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
744 v.reason = "too expensive"
748 return ir.DoChildren(n, v.do)
751 func isBigFunc(fn *ir.Func) bool {
752 budget := inlineBigFunctionNodes
753 return ir.Any(fn, func(n ir.Node) bool {
754 // See logic in hairyVisitor.doNode, explaining unified IR's
755 // handling of "a, b = f()" assignments.
756 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
757 if init := n.Rhs[0].Init(); len(init) == 1 {
758 if _, ok := init[0].(*ir.AssignListStmt); ok {
759 budget += 4*len(n.Lhs) + 1
769 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
770 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
771 // the body and dcls of an inlineable function.
772 func inlcopylist(ll []ir.Node) []ir.Node {
773 s := make([]ir.Node, len(ll))
774 for i, n := range ll {
780 // inlcopy is like DeepCopy(), but does extra work to copy closures.
781 func inlcopy(n ir.Node) ir.Node {
782 var edit func(ir.Node) ir.Node
783 edit = func(x ir.Node) ir.Node {
785 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
789 ir.EditChildren(m, edit)
790 if x.Op() == ir.OCLOSURE {
791 x := x.(*ir.ClosureExpr)
792 // Need to save/duplicate x.Func.Nname,
793 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
794 // x.Func.Body for iexport and local inlining.
796 newfn := ir.NewFunc(oldfn.Pos())
797 m.(*ir.ClosureExpr).Func = newfn
798 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
799 // XXX OK to share fn.Type() ??
800 newfn.Nname.SetType(oldfn.Nname.Type())
801 newfn.Body = inlcopylist(oldfn.Body)
802 // Make shallow copy of the Dcl and ClosureVar slices
803 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
804 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
811 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
812 // calls made to inlineable functions. This is the external entry point.
813 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
816 bigCaller := isBigFunc(fn)
817 if bigCaller && base.Flag.LowerM > 1 {
818 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
820 var inlCalls []*ir.InlinedCallExpr
821 var edit func(ir.Node) ir.Node
822 edit = func(n ir.Node) ir.Node {
823 return inlnode(n, bigCaller, &inlCalls, edit, profile)
825 ir.EditChildren(fn, edit)
827 // If we inlined any calls, we want to recursively visit their
828 // bodies for further inlining. However, we need to wait until
829 // *after* the original function body has been expanded, or else
830 // inlCallee can have false positives (e.g., #54632).
831 for len(inlCalls) > 0 {
833 inlCalls = inlCalls[1:]
834 ir.EditChildren(call, edit)
840 // inlnode recurses over the tree to find inlineable calls, which will
841 // be turned into OINLCALLs by mkinlcall. When the recursion comes
842 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
843 // nbody and nelse and use one of the 4 inlconv/glue functions above
844 // to turn the OINLCALL into an expression, a statement, or patch it
845 // in to this nodes list or rlist as appropriate.
846 // NOTE it makes no sense to pass the glue functions down the
847 // recursion to the level where the OINLCALL gets created because they
848 // have to edit /this/ n, so you'd have to push that one down as well,
849 // but then you may as well do it here. so this is cleaner and
850 // shorter and less complicated.
851 // The result of inlnode MUST be assigned back to n, e.g.
853 // n.Left = inlnode(n.Left)
854 func inlnode(n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
860 case ir.ODEFER, ir.OGO:
861 n := n.(*ir.GoDeferStmt)
862 switch call := n.Call; call.Op() {
864 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
866 call := call.(*ir.CallExpr)
870 n := n.(*ir.TailCallStmt)
871 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
873 // TODO do them here (or earlier),
874 // so escape analysis can avoid more heapmoves.
878 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
880 n := n.(*ir.CallExpr)
881 if n.X.Op() == ir.OMETHEXPR {
882 // Prevent inlining some reflect.Value methods when using checkptr,
883 // even when package reflect was compiled without it (#35073).
884 if meth := ir.MethodExprName(n.X); meth != nil {
886 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
895 ir.EditChildren(n, edit)
897 // with all the branches out of the way, it is now time to
898 // transmogrify this node itself unless inhibited by the
899 // switch at the top of this function.
902 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
905 call := n.(*ir.CallExpr)
909 if base.Flag.LowerM > 3 {
910 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
912 if ir.IsIntrinsicCall(call) {
915 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
916 n = mkinlcall(call, fn, bigCaller, inlCalls)
925 // inlCallee takes a function-typed expression and returns the underlying function ONAME
926 // that it refers to if statically known. Otherwise, it returns nil.
927 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
928 fn = ir.StaticValue(fn)
931 fn := fn.(*ir.SelectorExpr)
932 n := ir.MethodExprName(fn)
933 // Check that receiver type matches fn.X.
934 // TODO(mdempsky): Handle implicit dereference
935 // of pointer receiver argument?
936 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
942 if fn.Class == ir.PFUNC {
946 fn := fn.(*ir.ClosureExpr)
948 CanInline(c, profile)
956 // SSADumpInline gives the SSA back end a chance to dump the function
957 // when producing output for debugging the compiler itself.
958 var SSADumpInline = func(*ir.Func) {}
960 // InlineCall allows the inliner implementation to be overridden.
961 // If it returns nil, the function will not be inlined.
962 var InlineCall = func(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
963 base.Fatalf("inline.InlineCall not overridden")
967 // inlineCostOK returns true if call n from caller to callee is cheap enough to
968 // inline. bigCaller indicates that caller is a big function.
970 // If inlineCostOK returns false, it also returns the max cost that the callee
972 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
973 maxCost := int32(inlineMaxBudget)
975 // We use this to restrict inlining into very big functions.
976 // See issue 26546 and 17566.
977 maxCost = inlineBigFunctionMaxCost
980 if callee.Inl.Cost <= maxCost {
981 // Simple case. Function is already cheap enough.
985 // We'll also allow inlining of hot functions below inlineHotMaxBudget,
986 // but only in small functions.
988 lineOffset := pgo.NodeLineOffset(n, caller)
989 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
990 if _, ok := candHotEdgeMap[csi]; !ok {
992 return false, maxCost
998 if base.Debug.PGODebug > 0 {
999 fmt.Printf("hot-big check disallows inlining for call %s (cost %d) at %v in big function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1001 return false, maxCost
1004 if callee.Inl.Cost > inlineHotMaxBudget {
1005 return false, inlineHotMaxBudget
1008 if base.Debug.PGODebug > 0 {
1009 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1015 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1016 // function with an inlinable body, return an OINLCALL node that can replace n.
1017 // The returned node's Ninit has the parameter assignments, the Nbody is the
1018 // inlined function body, and (List, Rlist) contain the (input, output)
1020 // The result of mkinlcall MUST be assigned back to n, e.g.
1022 // n.Left = mkinlcall(n.Left, fn, isddd)
1023 func mkinlcall(n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1025 if logopt.Enabled() {
1026 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1027 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
1032 if ok, maxCost := inlineCostOK(n, ir.CurFunc, fn, bigCaller); !ok {
1033 if logopt.Enabled() {
1034 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1035 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
1040 if fn == ir.CurFunc {
1041 // Can't recursively inline a function into itself.
1042 if logopt.Enabled() {
1043 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
1048 if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(fn.Sym().Pkg) {
1049 // Runtime package must not be instrumented.
1050 // Instrument skips runtime package. However, some runtime code can be
1051 // inlined into other packages and instrumented there. To avoid this,
1052 // we disable inlining of runtime functions when instrumenting.
1053 // The example that we observed is inlining of LockOSThread,
1054 // which lead to false race reports on m contents.
1057 if base.Flag.Race && types.IsNoRacePkg(fn.Sym().Pkg) {
1061 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1064 // Check if we've already inlined this function at this particular
1065 // call site, in order to stop inlining when we reach the beginning
1066 // of a recursion cycle again. We don't inline immediately recursive
1067 // functions, but allow inlining if there is a recursion cycle of
1068 // many functions. Most likely, the inlining will stop before we
1069 // even hit the beginning of the cycle again, but this catches the
1071 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1072 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1073 if base.Flag.LowerM > 1 {
1074 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
1080 typecheck.AssertFixedCall(n)
1082 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
1084 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1085 // The linker needs FuncInfo metadata for all inlined
1086 // functions. This is typically handled by gc.enqueueFunc
1087 // calling ir.InitLSym for all function declarations in
1088 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1091 // However, non-trivial closures in Decls are ignored, and are
1092 // insteaded enqueued when walk of the calling function
1095 // This presents a problem for direct calls to closures.
1096 // Inlining will replace the entire closure definition with its
1097 // body, which hides the closure from walk and thus suppresses
1100 // Explicitly create a symbol early in this edge case to ensure
1101 // we keep this metadata.
1103 // TODO: Refactor to keep a reference so this can all be done
1106 if n.Op() != ir.OCALLFUNC {
1107 // Not a standard call.
1110 if n.X.Op() != ir.OCLOSURE {
1111 // Not a direct closure call.
1115 clo := n.X.(*ir.ClosureExpr)
1116 if ir.IsTrivialClosure(clo) {
1117 // enqueueFunc will handle trivial closures anyways.
1121 ir.InitLSym(fn, true)
1124 closureInitLSym(n, fn)
1126 if base.Flag.GenDwarfInl > 0 {
1127 if !sym.WasInlined() {
1128 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1129 sym.Set(obj.AttrWasInlined, true)
1133 if base.Flag.LowerM != 0 {
1134 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1136 if base.Flag.LowerM > 2 {
1137 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1140 res := InlineCall(n, fn, inlIndex)
1143 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1146 if base.Flag.LowerM > 2 {
1147 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1150 *inlCalls = append(*inlCalls, res)
1155 // CalleeEffects appends any side effects from evaluating callee to init.
1156 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1158 init.Append(ir.TakeInit(callee)...)
1160 switch callee.Op() {
1161 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1165 conv := callee.(*ir.ConvExpr)
1169 ic := callee.(*ir.InlinedCallExpr)
1170 init.Append(ic.Body.Take()...)
1171 callee = ic.SingleResult()
1174 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1179 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1180 s := make([]*ir.Name, 0, len(ll))
1181 for _, n := range ll {
1182 if n.Class == ir.PAUTO {
1183 if !vis.usedLocals.Has(n) {
1192 // numNonClosures returns the number of functions in list which are not closures.
1193 func numNonClosures(list []*ir.Func) int {
1195 for _, fn := range list {
1196 if fn.OClosure == nil {
1203 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1204 for _, x := range list {
1214 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1215 // into a coverage counter array.
1216 func isIndexingCoverageCounter(n ir.Node) bool {
1217 if n.Op() != ir.OINDEX {
1220 ixn := n.(*ir.IndexExpr)
1221 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1224 nn := ixn.X.(*ir.Name)
1225 return nn.CoverageCounter()
1228 // isAtomicCoverageCounterUpdate examines the specified node to
1229 // determine whether it represents a call to sync/atomic.AddUint32 to
1230 // increment a coverage counter.
1231 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1232 if cn.X.Op() != ir.ONAME {
1235 name := cn.X.(*ir.Name)
1236 if name.Class != ir.PFUNC {
1239 fn := name.Sym().Name
1240 if name.Sym().Pkg.Path != "sync/atomic" ||
1241 (fn != "AddUint32" && fn != "StoreUint32") {
1244 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1247 adn := cn.Args[0].(*ir.AddrExpr)
1248 v := isIndexingCoverageCounter(adn.X)