Source file 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 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.
     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  	"internal/buildcfg"
    33  	"strconv"
    34  	"strings"
    35  
    36  	"cmd/compile/internal/base"
    37  	"cmd/compile/internal/inline/inlheur"
    38  	"cmd/compile/internal/ir"
    39  	"cmd/compile/internal/logopt"
    40  	"cmd/compile/internal/pgoir"
    41  	"cmd/compile/internal/typecheck"
    42  	"cmd/compile/internal/types"
    43  	"cmd/internal/obj"
    44  	"cmd/internal/pgo"
    45  	"cmd/internal/src"
    46  )
    47  
    48  // Inlining budget parameters, gathered in one place
    49  const (
    50  	inlineMaxBudget       = 80
    51  	inlineExtraAppendCost = 0
    52  	// default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
    53  	inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
    54  	inlineParamCallCost  = 17              // calling a parameter only costs this much extra (inlining might expose a constant function)
    55  	inlineExtraPanicCost = 1               // do not penalize inlining panics.
    56  	inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
    57  
    58  	inlineBigFunctionNodes      = 5000                 // Functions with this many nodes are considered "big".
    59  	inlineBigFunctionMaxCost    = 20                   // Max cost of inlinee when inlining into a "big" function.
    60  	inlineClosureCalledOnceCost = 10 * inlineMaxBudget // if a closure is just called once, inline it.
    61  )
    62  
    63  var (
    64  	// List of all hot callee nodes.
    65  	// TODO(prattmic): Make this non-global.
    66  	candHotCalleeMap = make(map[*pgoir.IRNode]struct{})
    67  
    68  	// Set of functions that contain hot call sites.
    69  	hasHotCall = make(map[*ir.Func]struct{})
    70  
    71  	// List of all hot call sites. CallSiteInfo.Callee is always nil.
    72  	// TODO(prattmic): Make this non-global.
    73  	candHotEdgeMap = make(map[pgoir.CallSiteInfo]struct{})
    74  
    75  	// Threshold in percentage for hot callsite inlining.
    76  	inlineHotCallSiteThresholdPercent float64
    77  
    78  	// Threshold in CDF percentage for hot callsite inlining,
    79  	// that is, for a threshold of X the hottest callsites that
    80  	// make up the top X% of total edge weight will be
    81  	// considered hot for inlining candidates.
    82  	inlineCDFHotCallSiteThresholdPercent = float64(99)
    83  
    84  	// Budget increased due to hotness.
    85  	inlineHotMaxBudget int32 = 2000
    86  )
    87  
    88  func IsPgoHotFunc(fn *ir.Func, profile *pgoir.Profile) bool {
    89  	if profile == nil {
    90  		return false
    91  	}
    92  	if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
    93  		_, ok := candHotCalleeMap[n]
    94  		return ok
    95  	}
    96  	return false
    97  }
    98  
    99  func HasPgoHotInline(fn *ir.Func) bool {
   100  	_, has := hasHotCall[fn]
   101  	return has
   102  }
   103  
   104  // PGOInlinePrologue records the hot callsites from ir-graph.
   105  func PGOInlinePrologue(p *pgoir.Profile) {
   106  	if base.Debug.PGOInlineCDFThreshold != "" {
   107  		if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
   108  			inlineCDFHotCallSiteThresholdPercent = s
   109  		} else {
   110  			base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
   111  		}
   112  	}
   113  	var hotCallsites []pgo.NamedCallEdge
   114  	inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
   115  	if base.Debug.PGODebug > 0 {
   116  		fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
   117  	}
   118  
   119  	if x := base.Debug.PGOInlineBudget; x != 0 {
   120  		inlineHotMaxBudget = int32(x)
   121  	}
   122  
   123  	for _, n := range hotCallsites {
   124  		// mark inlineable callees from hot edges
   125  		if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
   126  			candHotCalleeMap[callee] = struct{}{}
   127  		}
   128  		// mark hot call sites
   129  		if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
   130  			csi := pgoir.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
   131  			candHotEdgeMap[csi] = struct{}{}
   132  		}
   133  	}
   134  
   135  	if base.Debug.PGODebug >= 3 {
   136  		fmt.Printf("hot-cg before inline in dot format:")
   137  		p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
   138  	}
   139  }
   140  
   141  // hotNodesFromCDF computes an edge weight threshold and the list of hot
   142  // nodes that make up the given percentage of the CDF. The threshold, as
   143  // a percent, is the lower bound of weight for nodes to be considered hot
   144  // (currently only used in debug prints) (in case of equal weights,
   145  // comparing with the threshold may not accurately reflect which nodes are
   146  // considered hot).
   147  func hotNodesFromCDF(p *pgoir.Profile) (float64, []pgo.NamedCallEdge) {
   148  	cum := int64(0)
   149  	for i, n := range p.NamedEdgeMap.ByWeight {
   150  		w := p.NamedEdgeMap.Weight[n]
   151  		cum += w
   152  		if pgo.WeightInPercentage(cum, p.TotalWeight) > inlineCDFHotCallSiteThresholdPercent {
   153  			// nodes[:i+1] to include the very last node that makes it to go over the threshold.
   154  			// (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
   155  			// include that node instead of excluding it.)
   156  			return pgo.WeightInPercentage(w, p.TotalWeight), p.NamedEdgeMap.ByWeight[:i+1]
   157  		}
   158  	}
   159  	return 0, p.NamedEdgeMap.ByWeight
   160  }
   161  
   162  // CanInlineFuncs computes whether a batch of functions are inlinable.
   163  func CanInlineFuncs(funcs []*ir.Func, profile *pgoir.Profile) {
   164  	if profile != nil {
   165  		PGOInlinePrologue(profile)
   166  	}
   167  
   168  	if base.Flag.LowerL == 0 {
   169  		return
   170  	}
   171  
   172  	ir.VisitFuncsBottomUp(funcs, func(funcs []*ir.Func, recursive bool) {
   173  		numfns := numNonClosures(funcs)
   174  
   175  		for _, fn := range funcs {
   176  			if !recursive || numfns > 1 {
   177  				// We allow inlining if there is no
   178  				// recursion, or the recursion cycle is
   179  				// across more than one function.
   180  				CanInline(fn, profile)
   181  			} else {
   182  				if base.Flag.LowerM > 1 && fn.OClosure == nil {
   183  					fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(fn), fn.Nname)
   184  				}
   185  			}
   186  			if inlheur.Enabled() {
   187  				analyzeFuncProps(fn, profile)
   188  			}
   189  		}
   190  	})
   191  }
   192  
   193  // inlineBudget determines the max budget for function 'fn' prior to
   194  // analyzing the hairiness of the body of 'fn'. We pass in the pgo
   195  // profile if available (which can change the budget), also a
   196  // 'relaxed' flag, which expands the budget slightly to allow for the
   197  // possibility that a call to the function might have its score
   198  // adjusted downwards. If 'verbose' is set, then print a remark where
   199  // we boost the budget due to PGO.
   200  func inlineBudget(fn *ir.Func, profile *pgoir.Profile, relaxed bool, verbose bool) int32 {
   201  	// Update the budget for profile-guided inlining.
   202  	budget := int32(inlineMaxBudget)
   203  	if IsPgoHotFunc(fn, profile) {
   204  		budget = inlineHotMaxBudget
   205  		if verbose {
   206  			fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
   207  		}
   208  	}
   209  	if relaxed {
   210  		budget += inlheur.BudgetExpansion(inlineMaxBudget)
   211  	}
   212  	if fn.ClosureParent != nil {
   213  		// be very liberal here, if the closure is only called once, the budget is large
   214  		budget = max(budget, inlineClosureCalledOnceCost)
   215  	}
   216  	return budget
   217  }
   218  
   219  // CanInline determines whether fn is inlineable.
   220  // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
   221  // fn and fn.Body will already have been typechecked.
   222  func CanInline(fn *ir.Func, profile *pgoir.Profile) {
   223  	if fn.Nname == nil {
   224  		base.Fatalf("CanInline no nname %+v", fn)
   225  	}
   226  
   227  	var reason string // reason, if any, that the function was not inlined
   228  	if base.Flag.LowerM > 1 || logopt.Enabled() {
   229  		defer func() {
   230  			if reason != "" {
   231  				if base.Flag.LowerM > 1 {
   232  					fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
   233  				}
   234  				if logopt.Enabled() {
   235  					logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
   236  				}
   237  			}
   238  		}()
   239  	}
   240  
   241  	reason = InlineImpossible(fn)
   242  	if reason != "" {
   243  		return
   244  	}
   245  	if fn.Typecheck() == 0 {
   246  		base.Fatalf("CanInline on non-typechecked function %v", fn)
   247  	}
   248  
   249  	n := fn.Nname
   250  	if n.Func.InlinabilityChecked() {
   251  		return
   252  	}
   253  	defer n.Func.SetInlinabilityChecked(true)
   254  
   255  	cc := int32(inlineExtraCallCost)
   256  	if base.Flag.LowerL == 4 {
   257  		cc = 1 // this appears to yield better performance than 0.
   258  	}
   259  
   260  	// Used a "relaxed" inline budget if the new inliner is enabled.
   261  	relaxed := inlheur.Enabled()
   262  
   263  	// Compute the inline budget for this func.
   264  	budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
   265  
   266  	// At this point in the game the function we're looking at may
   267  	// have "stale" autos, vars that still appear in the Dcl list, but
   268  	// which no longer have any uses in the function body (due to
   269  	// elimination by deadcode). We'd like to exclude these dead vars
   270  	// when creating the "Inline.Dcl" field below; to accomplish this,
   271  	// the hairyVisitor below builds up a map of used/referenced
   272  	// locals, and we use this map to produce a pruned Inline.Dcl
   273  	// list. See issue 25459 for more context.
   274  
   275  	visitor := hairyVisitor{
   276  		curFunc:       fn,
   277  		isBigFunc:     IsBigFunc(fn),
   278  		budget:        budget,
   279  		maxBudget:     budget,
   280  		extraCallCost: cc,
   281  		profile:       profile,
   282  	}
   283  	if visitor.tooHairy(fn) {
   284  		reason = visitor.reason
   285  		return
   286  	}
   287  
   288  	n.Func.Inl = &ir.Inline{
   289  		Cost:            budget - visitor.budget,
   290  		Dcl:             pruneUnusedAutos(n.Func.Dcl, &visitor),
   291  		HaveDcl:         true,
   292  		CanDelayResults: canDelayResults(fn),
   293  	}
   294  	if base.Flag.LowerM != 0 || logopt.Enabled() {
   295  		noteInlinableFunc(n, fn, budget-visitor.budget)
   296  	}
   297  }
   298  
   299  // noteInlinableFunc issues a message to the user that the specified
   300  // function is inlinable.
   301  func noteInlinableFunc(n *ir.Name, fn *ir.Func, cost int32) {
   302  	if base.Flag.LowerM > 1 {
   303  		fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, cost, fn.Type(), ir.Nodes(fn.Body))
   304  	} else if base.Flag.LowerM != 0 {
   305  		fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
   306  	}
   307  	// JSON optimization log output.
   308  	if logopt.Enabled() {
   309  		logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", cost))
   310  	}
   311  }
   312  
   313  // InlineImpossible returns a non-empty reason string if fn is impossible to
   314  // inline regardless of cost or contents.
   315  func InlineImpossible(fn *ir.Func) string {
   316  	var reason string // reason, if any, that the function can not be inlined.
   317  	if fn.Nname == nil {
   318  		reason = "no name"
   319  		return reason
   320  	}
   321  
   322  	// If marked "go:noinline", don't inline.
   323  	if fn.Pragma&ir.Noinline != 0 {
   324  		reason = "marked go:noinline"
   325  		return reason
   326  	}
   327  
   328  	// If marked "go:norace" and -race compilation, don't inline.
   329  	if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
   330  		reason = "marked go:norace with -race compilation"
   331  		return reason
   332  	}
   333  
   334  	// If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
   335  	if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
   336  		reason = "marked go:nocheckptr"
   337  		return reason
   338  	}
   339  
   340  	// If marked "go:cgo_unsafe_args", don't inline, since the function
   341  	// makes assumptions about its argument frame layout.
   342  	if fn.Pragma&ir.CgoUnsafeArgs != 0 {
   343  		reason = "marked go:cgo_unsafe_args"
   344  		return reason
   345  	}
   346  
   347  	// If marked as "go:uintptrkeepalive", don't inline, since the keep
   348  	// alive information is lost during inlining.
   349  	//
   350  	// TODO(prattmic): This is handled on calls during escape analysis,
   351  	// which is after inlining. Move prior to inlining so the keep-alive is
   352  	// maintained after inlining.
   353  	if fn.Pragma&ir.UintptrKeepAlive != 0 {
   354  		reason = "marked as having a keep-alive uintptr argument"
   355  		return reason
   356  	}
   357  
   358  	// If marked as "go:uintptrescapes", don't inline, since the escape
   359  	// information is lost during inlining.
   360  	if fn.Pragma&ir.UintptrEscapes != 0 {
   361  		reason = "marked as having an escaping uintptr argument"
   362  		return reason
   363  	}
   364  
   365  	// The nowritebarrierrec checker currently works at function
   366  	// granularity, so inlining yeswritebarrierrec functions can confuse it
   367  	// (#22342). As a workaround, disallow inlining them for now.
   368  	if fn.Pragma&ir.Yeswritebarrierrec != 0 {
   369  		reason = "marked go:yeswritebarrierrec"
   370  		return reason
   371  	}
   372  
   373  	// If a local function has no fn.Body (is defined outside of Go), cannot inline it.
   374  	// Imported functions don't have fn.Body but might have inline body in fn.Inl.
   375  	if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
   376  		reason = "no function body"
   377  		return reason
   378  	}
   379  
   380  	return ""
   381  }
   382  
   383  // canDelayResults reports whether inlined calls to fn can delay
   384  // declaring the result parameter until the "return" statement.
   385  func canDelayResults(fn *ir.Func) bool {
   386  	// We can delay declaring+initializing result parameters if:
   387  	// (1) there's exactly one "return" statement in the inlined function;
   388  	// (2) it's not an empty return statement (#44355); and
   389  	// (3) the result parameters aren't named.
   390  
   391  	nreturns := 0
   392  	ir.VisitList(fn.Body, func(n ir.Node) {
   393  		if n, ok := n.(*ir.ReturnStmt); ok {
   394  			nreturns++
   395  			if len(n.Results) == 0 {
   396  				nreturns++ // empty return statement (case 2)
   397  			}
   398  		}
   399  	})
   400  
   401  	if nreturns != 1 {
   402  		return false // not exactly one return statement (case 1)
   403  	}
   404  
   405  	// temporaries for return values.
   406  	for _, param := range fn.Type().Results() {
   407  		if sym := param.Sym; sym != nil && !sym.IsBlank() {
   408  			return false // found a named result parameter (case 3)
   409  		}
   410  	}
   411  
   412  	return true
   413  }
   414  
   415  // hairyVisitor visits a function body to determine its inlining
   416  // hairiness and whether or not it can be inlined.
   417  type hairyVisitor struct {
   418  	// This is needed to access the current caller in the doNode function.
   419  	curFunc       *ir.Func
   420  	isBigFunc     bool
   421  	budget        int32
   422  	maxBudget     int32
   423  	reason        string
   424  	extraCallCost int32
   425  	usedLocals    ir.NameSet
   426  	do            func(ir.Node) bool
   427  	profile       *pgoir.Profile
   428  }
   429  
   430  func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
   431  	v.do = v.doNode // cache closure
   432  	if ir.DoChildren(fn, v.do) {
   433  		return true
   434  	}
   435  	if v.budget < 0 {
   436  		v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
   437  		return true
   438  	}
   439  	return false
   440  }
   441  
   442  // doNode visits n and its children, updates the state in v, and returns true if
   443  // n makes the current function too hairy for inlining.
   444  func (v *hairyVisitor) doNode(n ir.Node) bool {
   445  	if n == nil {
   446  		return false
   447  	}
   448  opSwitch:
   449  	switch n.Op() {
   450  	// Call is okay if inlinable and we have the budget for the body.
   451  	case ir.OCALLFUNC:
   452  		n := n.(*ir.CallExpr)
   453  		var cheap bool
   454  		if n.Fun.Op() == ir.ONAME {
   455  			name := n.Fun.(*ir.Name)
   456  			if name.Class == ir.PFUNC {
   457  				s := name.Sym()
   458  				fn := s.Name
   459  				switch s.Pkg.Path {
   460  				case "internal/abi":
   461  					switch fn {
   462  					case "NoEscape":
   463  						// Special case for internal/abi.NoEscape. It does just type
   464  						// conversions to appease the escape analysis, and doesn't
   465  						// generate code.
   466  						cheap = true
   467  					}
   468  				case "internal/runtime/sys":
   469  					switch fn {
   470  					case "GetCallerPC", "GetCallerSP":
   471  						// Functions that call GetCallerPC/SP can not be inlined
   472  						// because users expect the PC/SP of the logical caller,
   473  						// but GetCallerPC/SP returns the physical caller.
   474  						v.reason = "call to " + fn
   475  						return true
   476  					}
   477  				case "go.runtime":
   478  					switch fn {
   479  					case "throw":
   480  						// runtime.throw is a "cheap call" like panic in normal code.
   481  						v.budget -= inlineExtraThrowCost
   482  						break opSwitch
   483  					case "panicrangestate":
   484  						cheap = true
   485  					}
   486  				case "hash/maphash":
   487  					if strings.HasPrefix(fn, "escapeForHash[") {
   488  						// hash/maphash.escapeForHash[T] is a compiler intrinsic
   489  						// implemented in the escape analysis phase.
   490  						cheap = true
   491  					}
   492  				}
   493  			}
   494  			// Special case for coverage counter updates; although
   495  			// these correspond to real operations, we treat them as
   496  			// zero cost for the moment. This is due to the existence
   497  			// of tests that are sensitive to inlining-- if the
   498  			// insertion of coverage instrumentation happens to tip a
   499  			// given function over the threshold and move it from
   500  			// "inlinable" to "not-inlinable", this can cause changes
   501  			// in allocation behavior, which can then result in test
   502  			// failures (a good example is the TestAllocations in
   503  			// crypto/ed25519).
   504  			if isAtomicCoverageCounterUpdate(n) {
   505  				return false
   506  			}
   507  		}
   508  		if n.Fun.Op() == ir.OMETHEXPR {
   509  			if meth := ir.MethodExprName(n.Fun); meth != nil {
   510  				if fn := meth.Func; fn != nil {
   511  					s := fn.Sym()
   512  					if types.RuntimeSymName(s) == "heapBits.nextArena" {
   513  						// Special case: explicitly allow mid-stack inlining of
   514  						// runtime.heapBits.next even though it calls slow-path
   515  						// runtime.heapBits.nextArena.
   516  						cheap = true
   517  					}
   518  					// Special case: on architectures that can do unaligned loads,
   519  					// explicitly mark encoding/binary methods as cheap,
   520  					// because in practice they are, even though our inlining
   521  					// budgeting system does not see that. See issue 42958.
   522  					if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
   523  						switch s.Name {
   524  						case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
   525  							"bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
   526  							"littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
   527  							"bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
   528  							"littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
   529  							"bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
   530  							cheap = true
   531  						}
   532  					}
   533  				}
   534  			}
   535  		}
   536  
   537  		// A call to a parameter is optimistically a cheap call, if it's a constant function
   538  		// perhaps it will inline, it also can simplify escape analysis.
   539  		extraCost := v.extraCallCost
   540  
   541  		if n.Fun.Op() == ir.ONAME {
   542  			name := n.Fun.(*ir.Name)
   543  			if name.Class == ir.PFUNC {
   544  				// Special case: on architectures that can do unaligned loads,
   545  				// explicitly mark internal/byteorder methods as cheap,
   546  				// because in practice they are, even though our inlining
   547  				// budgeting system does not see that. See issue 42958.
   548  				if base.Ctxt.Arch.CanMergeLoads && name.Sym().Pkg.Path == "internal/byteorder" {
   549  					switch name.Sym().Name {
   550  					case "LEUint64", "LEUint32", "LEUint16",
   551  						"BEUint64", "BEUint32", "BEUint16",
   552  						"LEPutUint64", "LEPutUint32", "LEPutUint16",
   553  						"BEPutUint64", "BEPutUint32", "BEPutUint16",
   554  						"LEAppendUint64", "LEAppendUint32", "LEAppendUint16",
   555  						"BEAppendUint64", "BEAppendUint32", "BEAppendUint16":
   556  						cheap = true
   557  					}
   558  				}
   559  			}
   560  			if name.Class == ir.PPARAM || name.Class == ir.PAUTOHEAP && name.IsClosureVar() {
   561  				extraCost = min(extraCost, inlineParamCallCost)
   562  			}
   563  		}
   564  
   565  		if cheap {
   566  			break // treat like any other node, that is, cost of 1
   567  		}
   568  
   569  		if ir.IsIntrinsicCall(n) {
   570  			// Treat like any other node.
   571  			break
   572  		}
   573  
   574  		if callee := inlCallee(v.curFunc, n.Fun, v.profile, false); callee != nil && typecheck.HaveInlineBody(callee) {
   575  			// Check whether we'd actually inline this call. Set
   576  			// log == false since we aren't actually doing inlining
   577  			// yet.
   578  			if ok, _, _ := canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false, false); ok {
   579  				// mkinlcall would inline this call [1], so use
   580  				// the cost of the inline body as the cost of
   581  				// the call, as that is what will actually
   582  				// appear in the code.
   583  				//
   584  				// [1] This is almost a perfect match to the
   585  				// mkinlcall logic, except that
   586  				// canInlineCallExpr considers inlining cycles
   587  				// by looking at what has already been inlined.
   588  				// Since we haven't done any inlining yet we
   589  				// will miss those.
   590  				//
   591  				// TODO: in the case of a single-call closure, the inlining budget here is potentially much, much larger.
   592  				//
   593  				v.budget -= callee.Inl.Cost
   594  				break
   595  			}
   596  		}
   597  
   598  		// Call cost for non-leaf inlining.
   599  		v.budget -= extraCost
   600  
   601  	case ir.OCALLMETH:
   602  		base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
   603  
   604  	// Things that are too hairy, irrespective of the budget
   605  	case ir.OCALL, ir.OCALLINTER:
   606  		// Call cost for non-leaf inlining.
   607  		v.budget -= v.extraCallCost
   608  
   609  	case ir.OPANIC:
   610  		n := n.(*ir.UnaryExpr)
   611  		if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
   612  			// Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
   613  			// Before CL 284412, these conversions were introduced later in the
   614  			// compiler, so they didn't count against inlining budget.
   615  			v.budget++
   616  		}
   617  		v.budget -= inlineExtraPanicCost
   618  
   619  	case ir.ORECOVER:
   620  		base.FatalfAt(n.Pos(), "ORECOVER missed typecheck")
   621  	case ir.ORECOVERFP:
   622  		// recover matches the argument frame pointer to find
   623  		// the right panic value, so it needs an argument frame.
   624  		v.reason = "call to recover"
   625  		return true
   626  
   627  	case ir.OCLOSURE:
   628  		if base.Debug.InlFuncsWithClosures == 0 {
   629  			v.reason = "not inlining functions with closures"
   630  			return true
   631  		}
   632  
   633  		// TODO(danscales): Maybe make budget proportional to number of closure
   634  		// variables, e.g.:
   635  		//v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
   636  		// TODO(austin): However, if we're able to inline this closure into
   637  		// v.curFunc, then we actually pay nothing for the closure captures. We
   638  		// should try to account for that if we're going to account for captures.
   639  		v.budget -= 15
   640  
   641  	case ir.OGO, ir.ODEFER, ir.OTAILCALL:
   642  		v.reason = "unhandled op " + n.Op().String()
   643  		return true
   644  
   645  	case ir.OAPPEND:
   646  		v.budget -= inlineExtraAppendCost
   647  
   648  	case ir.OADDR:
   649  		n := n.(*ir.AddrExpr)
   650  		// Make "&s.f" cost 0 when f's offset is zero.
   651  		if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
   652  			if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
   653  				v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
   654  			}
   655  		}
   656  
   657  	case ir.ODEREF:
   658  		// *(*X)(unsafe.Pointer(&x)) is low-cost
   659  		n := n.(*ir.StarExpr)
   660  
   661  		ptr := n.X
   662  		for ptr.Op() == ir.OCONVNOP {
   663  			ptr = ptr.(*ir.ConvExpr).X
   664  		}
   665  		if ptr.Op() == ir.OADDR {
   666  			v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
   667  		}
   668  
   669  	case ir.OCONVNOP:
   670  		// This doesn't produce code, but the children might.
   671  		v.budget++ // undo default cost
   672  
   673  	case ir.OFALL, ir.OTYPE:
   674  		// These nodes don't produce code; omit from inlining budget.
   675  		return false
   676  
   677  	case ir.OIF:
   678  		n := n.(*ir.IfStmt)
   679  		if ir.IsConst(n.Cond, constant.Bool) {
   680  			// This if and the condition cost nothing.
   681  			if doList(n.Init(), v.do) {
   682  				return true
   683  			}
   684  			if ir.BoolVal(n.Cond) {
   685  				return doList(n.Body, v.do)
   686  			} else {
   687  				return doList(n.Else, v.do)
   688  			}
   689  		}
   690  
   691  	case ir.ONAME:
   692  		n := n.(*ir.Name)
   693  		if n.Class == ir.PAUTO {
   694  			v.usedLocals.Add(n)
   695  		}
   696  
   697  	case ir.OBLOCK:
   698  		// The only OBLOCK we should see at this point is an empty one.
   699  		// In any event, let the visitList(n.List()) below take care of the statements,
   700  		// and don't charge for the OBLOCK itself. The ++ undoes the -- below.
   701  		v.budget++
   702  
   703  	case ir.OMETHVALUE, ir.OSLICELIT:
   704  		v.budget-- // Hack for toolstash -cmp.
   705  
   706  	case ir.OMETHEXPR:
   707  		v.budget++ // Hack for toolstash -cmp.
   708  
   709  	case ir.OAS2:
   710  		n := n.(*ir.AssignListStmt)
   711  
   712  		// Unified IR unconditionally rewrites:
   713  		//
   714  		//	a, b = f()
   715  		//
   716  		// into:
   717  		//
   718  		//	DCL tmp1
   719  		//	DCL tmp2
   720  		//	tmp1, tmp2 = f()
   721  		//	a, b = tmp1, tmp2
   722  		//
   723  		// so that it can insert implicit conversions as necessary. To
   724  		// minimize impact to the existing inlining heuristics (in
   725  		// particular, to avoid breaking the existing inlinability regress
   726  		// tests), we need to compensate for this here.
   727  		//
   728  		// See also identical logic in IsBigFunc.
   729  		if len(n.Rhs) > 0 {
   730  			if init := n.Rhs[0].Init(); len(init) == 1 {
   731  				if _, ok := init[0].(*ir.AssignListStmt); ok {
   732  					// 4 for each value, because each temporary variable now
   733  					// appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
   734  					//
   735  					// 1 for the extra "tmp1, tmp2 = f()" assignment statement.
   736  					v.budget += 4*int32(len(n.Lhs)) + 1
   737  				}
   738  			}
   739  		}
   740  
   741  	case ir.OAS:
   742  		// Special case for coverage counter updates and coverage
   743  		// function registrations. Although these correspond to real
   744  		// operations, we treat them as zero cost for the moment. This
   745  		// is primarily due to the existence of tests that are
   746  		// sensitive to inlining-- if the insertion of coverage
   747  		// instrumentation happens to tip a given function over the
   748  		// threshold and move it from "inlinable" to "not-inlinable",
   749  		// this can cause changes in allocation behavior, which can
   750  		// then result in test failures (a good example is the
   751  		// TestAllocations in crypto/ed25519).
   752  		n := n.(*ir.AssignStmt)
   753  		if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
   754  			return false
   755  		}
   756  	}
   757  
   758  	v.budget--
   759  
   760  	// When debugging, don't stop early, to get full cost of inlining this function
   761  	if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
   762  		v.reason = "too expensive"
   763  		return true
   764  	}
   765  
   766  	return ir.DoChildren(n, v.do)
   767  }
   768  
   769  // IsBigFunc reports whether fn is a "big" function.
   770  //
   771  // Note: The criteria for "big" is heuristic and subject to change.
   772  func IsBigFunc(fn *ir.Func) bool {
   773  	budget := inlineBigFunctionNodes
   774  	return ir.Any(fn, func(n ir.Node) bool {
   775  		// See logic in hairyVisitor.doNode, explaining unified IR's
   776  		// handling of "a, b = f()" assignments.
   777  		if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 && len(n.Rhs) > 0 {
   778  			if init := n.Rhs[0].Init(); len(init) == 1 {
   779  				if _, ok := init[0].(*ir.AssignListStmt); ok {
   780  					budget += 4*len(n.Lhs) + 1
   781  				}
   782  			}
   783  		}
   784  
   785  		budget--
   786  		return budget <= 0
   787  	})
   788  }
   789  
   790  // inlineCallCheck returns whether a call will never be inlineable
   791  // for basic reasons, and whether the call is an intrinisic call.
   792  // The intrinsic result singles out intrinsic calls for debug logging.
   793  func inlineCallCheck(callerfn *ir.Func, call *ir.CallExpr) (bool, bool) {
   794  	if base.Flag.LowerL == 0 {
   795  		return false, false
   796  	}
   797  	if call.Op() != ir.OCALLFUNC {
   798  		return false, false
   799  	}
   800  	if call.GoDefer || call.NoInline {
   801  		return false, false
   802  	}
   803  
   804  	// Prevent inlining some reflect.Value methods when using checkptr,
   805  	// even when package reflect was compiled without it (#35073).
   806  	if base.Debug.Checkptr != 0 && call.Fun.Op() == ir.OMETHEXPR {
   807  		if method := ir.MethodExprName(call.Fun); method != nil {
   808  			switch types.ReflectSymName(method.Sym()) {
   809  			case "Value.UnsafeAddr", "Value.Pointer":
   810  				return false, false
   811  			}
   812  		}
   813  	}
   814  
   815  	// hash/maphash.escapeForHash[T] is a compiler intrinsic implemented
   816  	// in the escape analysis phase.
   817  	if fn := ir.StaticCalleeName(call.Fun); fn != nil && fn.Sym().Pkg.Path == "hash/maphash" &&
   818  		strings.HasPrefix(fn.Sym().Name, "escapeForHash[") {
   819  		return false, true
   820  	}
   821  
   822  	if ir.IsIntrinsicCall(call) {
   823  		return false, true
   824  	}
   825  	return true, false
   826  }
   827  
   828  // InlineCallTarget returns the resolved-for-inlining target of a call.
   829  // It does not necessarily guarantee that the target can be inlined, though
   830  // obvious exclusions are applied.
   831  func InlineCallTarget(callerfn *ir.Func, call *ir.CallExpr, profile *pgoir.Profile) *ir.Func {
   832  	if mightInline, _ := inlineCallCheck(callerfn, call); !mightInline {
   833  		return nil
   834  	}
   835  	return inlCallee(callerfn, call.Fun, profile, true)
   836  }
   837  
   838  // TryInlineCall returns an inlined call expression for call, or nil
   839  // if inlining is not possible.
   840  func TryInlineCall(callerfn *ir.Func, call *ir.CallExpr, bigCaller bool, profile *pgoir.Profile, closureCalledOnce bool) *ir.InlinedCallExpr {
   841  	mightInline, isIntrinsic := inlineCallCheck(callerfn, call)
   842  
   843  	// Preserve old logging behavior
   844  	if (mightInline || isIntrinsic) && base.Flag.LowerM > 3 {
   845  		fmt.Printf("%v:call to func %+v\n", ir.Line(call), call.Fun)
   846  	}
   847  	if !mightInline {
   848  		return nil
   849  	}
   850  
   851  	if fn := inlCallee(callerfn, call.Fun, profile, false); fn != nil && typecheck.HaveInlineBody(fn) {
   852  		return mkinlcall(callerfn, call, fn, bigCaller, closureCalledOnce)
   853  	}
   854  	return nil
   855  }
   856  
   857  // inlCallee takes a function-typed expression and returns the underlying function ONAME
   858  // that it refers to if statically known. Otherwise, it returns nil.
   859  // resolveOnly skips cost-based inlineability checks for closures; the result may not actually be inlineable.
   860  func inlCallee(caller *ir.Func, fn ir.Node, profile *pgoir.Profile, resolveOnly bool) (res *ir.Func) {
   861  	fn = ir.StaticValue(fn)
   862  	switch fn.Op() {
   863  	case ir.OMETHEXPR:
   864  		fn := fn.(*ir.SelectorExpr)
   865  		n := ir.MethodExprName(fn)
   866  		// Check that receiver type matches fn.X.
   867  		// TODO(mdempsky): Handle implicit dereference
   868  		// of pointer receiver argument?
   869  		if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
   870  			return nil
   871  		}
   872  		return n.Func
   873  	case ir.ONAME:
   874  		fn := fn.(*ir.Name)
   875  		if fn.Class == ir.PFUNC {
   876  			return fn.Func
   877  		}
   878  	case ir.OCLOSURE:
   879  		fn := fn.(*ir.ClosureExpr)
   880  		c := fn.Func
   881  		if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
   882  			return nil // inliner doesn't support inlining across closure frames
   883  		}
   884  		if !resolveOnly {
   885  			CanInline(c, profile)
   886  		}
   887  		return c
   888  	}
   889  	return nil
   890  }
   891  
   892  var inlgen int
   893  
   894  // SSADumpInline gives the SSA back end a chance to dump the function
   895  // when producing output for debugging the compiler itself.
   896  var SSADumpInline = func(*ir.Func) {}
   897  
   898  // InlineCall allows the inliner implementation to be overridden.
   899  // If it returns nil, the function will not be inlined.
   900  var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
   901  	base.Fatalf("inline.InlineCall not overridden")
   902  	panic("unreachable")
   903  }
   904  
   905  // inlineCostOK returns true if call n from caller to callee is cheap enough to
   906  // inline. bigCaller indicates that caller is a big function.
   907  //
   908  // In addition to the "cost OK" boolean, it also returns
   909  //   - the "max cost" limit used to make the decision (which may differ depending on func size)
   910  //   - the score assigned to this specific callsite
   911  //   - whether the inlined function is "hot" according to PGO.
   912  func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller, closureCalledOnce bool) (bool, int32, int32, bool) {
   913  	maxCost := int32(inlineMaxBudget)
   914  
   915  	if bigCaller {
   916  		// We use this to restrict inlining into very big functions.
   917  		// See issue 26546 and 17566.
   918  		maxCost = inlineBigFunctionMaxCost
   919  	}
   920  
   921  	if callee.ClosureParent != nil {
   922  		maxCost *= 2           // favor inlining closures
   923  		if closureCalledOnce { // really favor inlining the one call to this closure
   924  			maxCost = max(maxCost, inlineClosureCalledOnceCost)
   925  		}
   926  	}
   927  
   928  	metric := callee.Inl.Cost
   929  	if inlheur.Enabled() {
   930  		score, ok := inlheur.GetCallSiteScore(caller, n)
   931  		if ok {
   932  			metric = int32(score)
   933  		}
   934  	}
   935  
   936  	lineOffset := pgoir.NodeLineOffset(n, caller)
   937  	csi := pgoir.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
   938  	_, hot := candHotEdgeMap[csi]
   939  
   940  	if metric <= maxCost {
   941  		// Simple case. Function is already cheap enough.
   942  		return true, 0, metric, hot
   943  	}
   944  
   945  	// We'll also allow inlining of hot functions below inlineHotMaxBudget,
   946  	// but only in small functions.
   947  
   948  	if !hot {
   949  		// Cold
   950  		return false, maxCost, metric, false
   951  	}
   952  
   953  	// Hot
   954  
   955  	if bigCaller {
   956  		if base.Debug.PGODebug > 0 {
   957  			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))
   958  		}
   959  		return false, maxCost, metric, false
   960  	}
   961  
   962  	if metric > inlineHotMaxBudget {
   963  		return false, inlineHotMaxBudget, metric, false
   964  	}
   965  
   966  	if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
   967  		// De-selected by PGO Hash.
   968  		return false, maxCost, metric, false
   969  	}
   970  
   971  	if base.Debug.PGODebug > 0 {
   972  		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))
   973  	}
   974  
   975  	return true, 0, metric, hot
   976  }
   977  
   978  // parsePos returns all the inlining positions and the innermost position.
   979  func parsePos(pos src.XPos, posTmp []src.Pos) ([]src.Pos, src.Pos) {
   980  	ctxt := base.Ctxt
   981  	ctxt.AllPos(pos, func(p src.Pos) {
   982  		posTmp = append(posTmp, p)
   983  	})
   984  	l := len(posTmp) - 1
   985  	return posTmp[:l], posTmp[l]
   986  }
   987  
   988  // canInlineCallExpr returns true if the call n from caller to callee
   989  // can be inlined, plus the score computed for the call expr in question,
   990  // and whether the callee is hot according to PGO.
   991  // bigCaller indicates that caller is a big function. log
   992  // indicates that the 'cannot inline' reason should be logged.
   993  //
   994  // Preconditions: CanInline(callee) has already been called.
   995  func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller, closureCalledOnce bool, log bool) (bool, int32, bool) {
   996  	if callee.Inl == nil {
   997  		// callee is never inlinable.
   998  		if log && logopt.Enabled() {
   999  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1000  				fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
  1001  		}
  1002  		return false, 0, false
  1003  	}
  1004  
  1005  	ok, maxCost, callSiteScore, hot := inlineCostOK(n, callerfn, callee, bigCaller, closureCalledOnce)
  1006  	if !ok {
  1007  		// callee cost too high for this call site.
  1008  		if log && logopt.Enabled() {
  1009  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1010  				fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
  1011  		}
  1012  		return false, 0, false
  1013  	}
  1014  
  1015  	callees, calleeInner := parsePos(n.Pos(), make([]src.Pos, 0, 10))
  1016  
  1017  	for _, p := range callees {
  1018  		if p.Line() == calleeInner.Line() && p.Col() == calleeInner.Col() && p.AbsFilename() == calleeInner.AbsFilename() {
  1019  			if log && logopt.Enabled() {
  1020  				logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
  1021  			}
  1022  			return false, 0, false
  1023  		}
  1024  	}
  1025  
  1026  	if callee == callerfn {
  1027  		// Can't recursively inline a function into itself.
  1028  		if log && logopt.Enabled() {
  1029  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
  1030  		}
  1031  		return false, 0, false
  1032  	}
  1033  
  1034  	isClosureParent := func(closure, parent *ir.Func) bool {
  1035  		for p := closure.ClosureParent; p != nil; p = p.ClosureParent {
  1036  			if p == parent {
  1037  				return true
  1038  			}
  1039  		}
  1040  		return false
  1041  	}
  1042  	if isClosureParent(callerfn, callee) {
  1043  		// Can't recursively inline a parent of the closure into itself.
  1044  		if log && logopt.Enabled() {
  1045  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to closure parent: %s, %s", ir.FuncName(callerfn), ir.FuncName(callee)))
  1046  		}
  1047  		return false, 0, false
  1048  	}
  1049  	if isClosureParent(callee, callerfn) {
  1050  		// Can't recursively inline a closure if there's a call to the parent in closure body.
  1051  		if ir.Any(callee, func(node ir.Node) bool {
  1052  			if call, ok := node.(*ir.CallExpr); ok {
  1053  				if name, ok := call.Fun.(*ir.Name); ok && isClosureParent(callerfn, name.Func) {
  1054  					return true
  1055  				}
  1056  			}
  1057  			return false
  1058  		}) {
  1059  			if log && logopt.Enabled() {
  1060  				logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to closure parent: %s, %s", ir.FuncName(callerfn), ir.FuncName(callee)))
  1061  			}
  1062  			return false, 0, false
  1063  		}
  1064  	}
  1065  	do := func(fn *ir.Func) bool {
  1066  		// Can't recursively inline a function if the function body contains
  1067  		// a call to a function f, which the function f is one of the call arguments.
  1068  		return ir.Any(fn, func(node ir.Node) bool {
  1069  			if call, ok := node.(*ir.CallExpr); ok {
  1070  				for _, arg := range call.Args {
  1071  					if call.Fun == arg {
  1072  						return true
  1073  					}
  1074  				}
  1075  			}
  1076  			return false
  1077  		})
  1078  	}
  1079  	for _, fn := range []*ir.Func{callerfn, callee} {
  1080  		if do(fn) {
  1081  			if log && logopt.Enabled() {
  1082  				logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to function: %s", ir.FuncName(fn)))
  1083  			}
  1084  			return false, 0, false
  1085  		}
  1086  	}
  1087  
  1088  	if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
  1089  		// Runtime package must not be instrumented.
  1090  		// Instrument skips runtime package. However, some runtime code can be
  1091  		// inlined into other packages and instrumented there. To avoid this,
  1092  		// we disable inlining of runtime functions when instrumenting.
  1093  		// The example that we observed is inlining of LockOSThread,
  1094  		// which lead to false race reports on m contents.
  1095  		if log && logopt.Enabled() {
  1096  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1097  				fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
  1098  		}
  1099  		return false, 0, false
  1100  	}
  1101  
  1102  	if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
  1103  		if log && logopt.Enabled() {
  1104  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1105  				fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
  1106  		}
  1107  		return false, 0, false
  1108  	}
  1109  
  1110  	if base.Debug.Checkptr != 0 && types.IsRuntimePkg(callee.Sym().Pkg) {
  1111  		// We don't instrument runtime packages for checkptr (see base/flag.go).
  1112  		if log && logopt.Enabled() {
  1113  			logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1114  				fmt.Sprintf(`call to into runtime package function %s in -d=checkptr build`, ir.PkgFuncName(callee)))
  1115  		}
  1116  		return false, 0, false
  1117  	}
  1118  
  1119  	// Check if we've already inlined this function at this particular
  1120  	// call site, in order to stop inlining when we reach the beginning
  1121  	// of a recursion cycle again. We don't inline immediately recursive
  1122  	// functions, but allow inlining if there is a recursion cycle of
  1123  	// many functions. Most likely, the inlining will stop before we
  1124  	// even hit the beginning of the cycle again, but this catches the
  1125  	// unusual case.
  1126  	parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
  1127  	sym := callee.Linksym()
  1128  	for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
  1129  		if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
  1130  			if log {
  1131  				if base.Flag.LowerM > 1 {
  1132  					fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
  1133  				}
  1134  				if logopt.Enabled() {
  1135  					logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
  1136  						fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
  1137  				}
  1138  			}
  1139  			return false, 0, false
  1140  		}
  1141  	}
  1142  
  1143  	return true, callSiteScore, hot
  1144  }
  1145  
  1146  // mkinlcall returns an OINLCALL node that can replace OCALLFUNC n, or
  1147  // nil if it cannot be inlined. callerfn is the function that contains
  1148  // n, and fn is the function being called.
  1149  //
  1150  // The result of mkinlcall MUST be assigned back to n, e.g.
  1151  //
  1152  //	n.Left = mkinlcall(n.Left, fn, isddd)
  1153  func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller, closureCalledOnce bool) *ir.InlinedCallExpr {
  1154  	ok, score, hot := canInlineCallExpr(callerfn, n, fn, bigCaller, closureCalledOnce, true)
  1155  	if !ok {
  1156  		return nil
  1157  	}
  1158  	if hot {
  1159  		hasHotCall[callerfn] = struct{}{}
  1160  	}
  1161  	typecheck.AssertFixedCall(n)
  1162  
  1163  	parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
  1164  	sym := fn.Linksym()
  1165  	inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
  1166  
  1167  	closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
  1168  		// The linker needs FuncInfo metadata for all inlined
  1169  		// functions. This is typically handled by gc.enqueueFunc
  1170  		// calling ir.InitLSym for all function declarations in
  1171  		// typecheck.Target.Decls (ir.UseClosure adds all closures to
  1172  		// Decls).
  1173  		//
  1174  		// However, closures in Decls are ignored, and are
  1175  		// instead enqueued when walk of the calling function
  1176  		// discovers them.
  1177  		//
  1178  		// This presents a problem for direct calls to closures.
  1179  		// Inlining will replace the entire closure definition with its
  1180  		// body, which hides the closure from walk and thus suppresses
  1181  		// symbol creation.
  1182  		//
  1183  		// Explicitly create a symbol early in this edge case to ensure
  1184  		// we keep this metadata.
  1185  		//
  1186  		// TODO: Refactor to keep a reference so this can all be done
  1187  		// by enqueueFunc.
  1188  
  1189  		if n.Op() != ir.OCALLFUNC {
  1190  			// Not a standard call.
  1191  			return
  1192  		}
  1193  		if n.Fun.Op() != ir.OCLOSURE {
  1194  			// Not a direct closure call.
  1195  			return
  1196  		}
  1197  
  1198  		clo := n.Fun.(*ir.ClosureExpr)
  1199  		if !clo.Func.IsClosure() {
  1200  			// enqueueFunc will handle non closures anyways.
  1201  			return
  1202  		}
  1203  
  1204  		ir.InitLSym(fn, true)
  1205  	}
  1206  
  1207  	closureInitLSym(n, fn)
  1208  
  1209  	if base.Flag.GenDwarfInl > 0 {
  1210  		if !sym.WasInlined() {
  1211  			base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
  1212  			sym.Set(obj.AttrWasInlined, true)
  1213  		}
  1214  	}
  1215  
  1216  	if base.Flag.LowerM != 0 {
  1217  		if buildcfg.Experiment.NewInliner {
  1218  			fmt.Printf("%v: inlining call to %v with score %d\n",
  1219  				ir.Line(n), fn, score)
  1220  		} else {
  1221  			fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
  1222  		}
  1223  	}
  1224  	if base.Flag.LowerM > 2 {
  1225  		fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
  1226  	}
  1227  
  1228  	res := InlineCall(callerfn, n, fn, inlIndex)
  1229  
  1230  	if res == nil {
  1231  		base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
  1232  	}
  1233  
  1234  	if base.Flag.LowerM > 2 {
  1235  		fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
  1236  	}
  1237  
  1238  	if inlheur.Enabled() {
  1239  		inlheur.UpdateCallsiteTable(callerfn, n, res)
  1240  	}
  1241  
  1242  	return res
  1243  }
  1244  
  1245  // CalleeEffects appends any side effects from evaluating callee to init.
  1246  func CalleeEffects(init *ir.Nodes, callee ir.Node) {
  1247  	for {
  1248  		init.Append(ir.TakeInit(callee)...)
  1249  
  1250  		switch callee.Op() {
  1251  		case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
  1252  			return // done
  1253  
  1254  		case ir.OCONVNOP:
  1255  			conv := callee.(*ir.ConvExpr)
  1256  			callee = conv.X
  1257  
  1258  		case ir.OINLCALL:
  1259  			ic := callee.(*ir.InlinedCallExpr)
  1260  			init.Append(ic.Body.Take()...)
  1261  			callee = ic.SingleResult()
  1262  
  1263  		default:
  1264  			base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
  1265  		}
  1266  	}
  1267  }
  1268  
  1269  func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
  1270  	s := make([]*ir.Name, 0, len(ll))
  1271  	for _, n := range ll {
  1272  		if n.Class == ir.PAUTO {
  1273  			if !vis.usedLocals.Has(n) {
  1274  				// TODO(mdempsky): Simplify code after confident that this
  1275  				// never happens anymore.
  1276  				base.FatalfAt(n.Pos(), "unused auto: %v", n)
  1277  				continue
  1278  			}
  1279  		}
  1280  		s = append(s, n)
  1281  	}
  1282  	return s
  1283  }
  1284  
  1285  // numNonClosures returns the number of functions in list which are not closures.
  1286  func numNonClosures(list []*ir.Func) int {
  1287  	count := 0
  1288  	for _, fn := range list {
  1289  		if fn.OClosure == nil {
  1290  			count++
  1291  		}
  1292  	}
  1293  	return count
  1294  }
  1295  
  1296  func doList(list []ir.Node, do func(ir.Node) bool) bool {
  1297  	for _, x := range list {
  1298  		if x != nil {
  1299  			if do(x) {
  1300  				return true
  1301  			}
  1302  		}
  1303  	}
  1304  	return false
  1305  }
  1306  
  1307  // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
  1308  // into a coverage counter array.
  1309  func isIndexingCoverageCounter(n ir.Node) bool {
  1310  	if n.Op() != ir.OINDEX {
  1311  		return false
  1312  	}
  1313  	ixn := n.(*ir.IndexExpr)
  1314  	if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
  1315  		return false
  1316  	}
  1317  	nn := ixn.X.(*ir.Name)
  1318  	// CoverageAuxVar implies either a coverage counter or a package
  1319  	// ID; since the cover tool never emits code to index into ID vars
  1320  	// this is effectively testing whether nn is a coverage counter.
  1321  	return nn.CoverageAuxVar()
  1322  }
  1323  
  1324  // isAtomicCoverageCounterUpdate examines the specified node to
  1325  // determine whether it represents a call to sync/atomic.AddUint32 to
  1326  // increment a coverage counter.
  1327  func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
  1328  	if cn.Fun.Op() != ir.ONAME {
  1329  		return false
  1330  	}
  1331  	name := cn.Fun.(*ir.Name)
  1332  	if name.Class != ir.PFUNC {
  1333  		return false
  1334  	}
  1335  	fn := name.Sym().Name
  1336  	if name.Sym().Pkg.Path != "sync/atomic" ||
  1337  		(fn != "AddUint32" && fn != "StoreUint32") {
  1338  		return false
  1339  	}
  1340  	if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
  1341  		return false
  1342  	}
  1343  	adn := cn.Args[0].(*ir.AddrExpr)
  1344  	v := isIndexingCoverageCounter(adn.X)
  1345  	return v
  1346  }
  1347  
  1348  func PostProcessCallSites(profile *pgoir.Profile) {
  1349  	if base.Debug.DumpInlCallSiteScores != 0 {
  1350  		budgetCallback := func(fn *ir.Func, prof *pgoir.Profile) (int32, bool) {
  1351  			v := inlineBudget(fn, prof, false, false)
  1352  			return v, v == inlineHotMaxBudget
  1353  		}
  1354  		inlheur.DumpInlCallSiteScores(profile, budgetCallback)
  1355  	}
  1356  }
  1357  
  1358  func analyzeFuncProps(fn *ir.Func, p *pgoir.Profile) {
  1359  	canInline := func(fn *ir.Func) { CanInline(fn, p) }
  1360  	budgetForFunc := func(fn *ir.Func) int32 {
  1361  		return inlineBudget(fn, p, true, false)
  1362  	}
  1363  	inlheur.AnalyzeFunc(fn, canInline, budgetForFunc, inlineMaxBudget)
  1364  }
  1365  

View as plain text