2015-02-13 14:40:36 -05:00
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
2022-10-17 11:28:52 +00:00
// The inlining facility makes 2 passes: first CanInline determines which
2015-02-13 14:40:36 -05:00
// functions are suitable for inlining, and for those that are it
2021-01-15 14:12:35 -08:00
// saves a copy of the body. Then InlineCalls walks each function body to
2015-02-13 14:40:36 -05:00
// expand calls to inlinable functions.
//
2020-10-19 11:31:10 +02:00
// The Debug.l flag controls the aggressiveness. Note that main() swaps level 0 and 1,
2017-10-20 15:20:56 -07:00
// making 1 the default and -l disable. Additional levels (beyond -l) may be buggy and
// are not supported.
2015-02-13 14:40:36 -05:00
// 0: disabled
2018-04-27 12:13:17 -04:00
// 1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
2017-10-20 15:20:56 -07:00
// 2: (unassigned)
2018-03-13 12:59:41 -07:00
// 3: (unassigned)
2017-10-20 15:20:56 -07:00
// 4: allow non-leaf functions
2015-02-13 14:40:36 -05:00
//
2017-10-20 15:20:56 -07:00
// At some point this may get another default and become switch-offable with -N.
2015-02-13 14:40:36 -05:00
//
2017-10-20 15:20:56 -07:00
// The -d typcheckinl flag enables early typechecking of all imported bodies,
// which is useful to flush out bugs.
//
2020-10-19 11:31:10 +02:00
// The Debug.m flag enables diagnostic output. a single -m is useful for verifying
2017-10-20 15:20:56 -07:00
// which calls get inlined or not, more is for debugging, and may go away at any point.
2015-02-13 14:40:36 -05:00
2020-12-23 00:44:42 -05:00
package inline
2015-02-13 14:40:36 -05:00
2016-12-06 17:08:06 -08:00
import (
2020-12-23 00:44:42 -05:00
"fmt"
"go/constant"
2023-11-07 10:28:56 -05:00
"internal/buildcfg"
2022-09-09 11:29:32 -07:00
"strconv"
hash/maphash, cmd/compile: make Comparable[string] not escape its argument
Currently, maphash.Comparable forces its argument to escape if it
contains a pointer, as we cannot hash stack pointers, which will
change when the stack moves. However, for a string, it is actually
okay if its data pointer points to the stack, as the hash depends
on only the content, not the pointer.
Currently there is no way to write this type-dependent escape
logic in Go code. So we implement it in the compiler as an
intrinsic. The compiler can also recognize not just the string
type, but types whose pointers are all string pointers, and make
them not escape.
Fixes #70560.
Change-Id: I3bf219ad71a238d2e35f0ea33de96487bc8cc231
Reviewed-on: https://go-review.googlesource.com/c/go/+/632715
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-01 23:53:23 -05:00
"strings"
2020-12-23 00:44:42 -05:00
2020-11-19 20:49:23 -05:00
"cmd/compile/internal/base"
2023-06-29 15:37:26 -04:00
"cmd/compile/internal/inline/inlheur"
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
"cmd/compile/internal/ir"
2019-10-29 17:25:56 -04:00
"cmd/compile/internal/logopt"
2024-03-05 11:04:26 -05:00
"cmd/compile/internal/pgoir"
[dev.regabi] cmd/compile: split out package typecheck [generated]
This commit splits the typechecking logic into its own package,
the first of a sequence of CLs to break package gc into more
manageable units.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# The binary import/export has to be part of typechecking,
# because we load inlined function bodies lazily, but "exporter"
# should not be. Move that out of bexport.go.
mv exporter exporter.markObject exporter.markType export.go
# Use the typechecking helpers, so that the calls left behind
# in package gc do not need access to ctxExpr etc.
ex {
import "cmd/compile/internal/ir"
# TODO(rsc): Should not be necessary.
avoid TypecheckExpr
avoid TypecheckStmt
avoid TypecheckExprs
avoid TypecheckStmts
avoid TypecheckAssignExpr
avoid TypecheckCallee
var n ir.Node
var ns []ir.Node
typecheck(n, ctxExpr) -> TypecheckExpr(n)
typecheck(n, ctxStmt) -> TypecheckStmt(n)
typecheckslice(ns, ctxExpr) -> TypecheckExprs(ns)
typecheckslice(ns, ctxStmt) -> TypecheckStmts(ns)
typecheck(n, ctxExpr|ctxAssign) -> TypecheckAssignExpr(n)
typecheck(n, ctxExpr|ctxCallee) -> TypecheckCallee(n)
}
# Move some typechecking API to typecheck.
mv syslook LookupRuntime
mv substArgTypes SubstArgTypes
mv LookupRuntime SubstArgTypes syms.go
mv conv Conv
mv convnop ConvNop
mv Conv ConvNop typecheck.go
mv colasdefn AssignDefn
mv colasname assignableName
mv Target target.go
mv initname autoexport exportsym dcl.go
mv exportsym Export
# Export API to be called from outside typecheck.
# The ones with "Typecheck" prefixes will be renamed later to drop the prefix.
mv adddot AddImplicitDots
mv assignconv AssignConv
mv expandmeth CalcMethods
mv capturevarscomplete CaptureVarsComplete
mv checkMapKeys CheckMapKeys
mv checkreturn CheckReturn
mv dclcontext DeclContext
mv dclfunc DeclFunc
mv declare Declare
mv dotImportRefs DotImportRefs
mv declImporter DeclImporter
mv variter DeclVars
mv defaultlit DefaultLit
mv evalConst EvalConst
mv expandInline ImportBody
mv finishUniverse declareUniverse
mv funcbody FinishFuncBody
mv funchdr StartFuncBody
mv indexconst IndexConst
mv initTodo InitTodoFunc
mv lookup Lookup
mv resolve Resolve
mv lookupN LookupNum
mv nodAddr NodAddr
mv nodAddrAt NodAddrAt
mv nodnil NodNil
mv origBoolConst OrigBool
mv origConst OrigConst
mv origIntConst OrigInt
mv redeclare Redeclared
mv tostruct NewStructType
mv functype NewFuncType
mv methodfunc NewMethodType
mv structargs NewFuncParams
mv temp Temp
mv tempAt TempAt
mv typecheckok TypecheckAllowed
mv typecheck _typecheck # make room for typecheck pkg
mv typecheckinl TypecheckImportedBody
mv typecheckFunc TypecheckFunc
mv iimport ReadImports
mv iexport WriteExports
mv sysfunc LookupRuntimeFunc
mv sysvar LookupRuntimeVar
# Move function constructors to typecheck.
mv mkdotargslice MakeDotArgs
mv fixVariadicCall FixVariadicCall
mv closureType ClosureType
mv partialCallType PartialCallType
mv capturevars CaptureVars
mv MakeDotArgs FixVariadicCall ClosureType PartialCallType CaptureVars typecheckclosure func.go
mv autolabel AutoLabel
mv AutoLabel syms.go
mv Dlist dlist
mv Symlink symlink
mv \
AssignDefn assignableName \
AssignConv \
CaptureVarsComplete \
DeclContext \
DeclFunc \
DeclImporter \
DeclVars \
Declare \
DotImportRefs \
Export \
InitTodoFunc \
Lookup \
LookupNum \
LookupRuntimeFunc \
LookupRuntimeVar \
NewFuncParams \
NewName \
NodAddr \
NodAddrAt \
NodNil \
Redeclared \
StartFuncBody \
FinishFuncBody \
TypecheckImportedBody \
AddImplicitDots \
CalcMethods \
CheckFuncStack \
NewFuncType \
NewMethodType \
NewStructType \
TypecheckAllowed \
Temp \
TempAt \
adddot1 \
dotlist \
addmethod \
assignconvfn \
assignop \
autotmpname \
autoexport \
bexport.go \
checkdupfields \
checkembeddedtype \
closurename \
convertop \
declare_typegen \
decldepth \
dlist \
dotpath \
expand0 \
expand1 \
expandDecl \
fakeRecvField \
fnpkg \
funcStack \
funcStackEnt \
funcarg \
funcarg2 \
funcargs \
funcargs2 \
globClosgen \
ifacelookdot \
implements \
importalias \
importconst \
importfunc \
importobj \
importsym \
importtype \
importvar \
inimport \
initname \
isptrto \
loadsys \
lookdot0 \
lookdot1 \
makepartialcall \
okfor \
okforlen \
operandType \
slist \
symlink \
tointerface \
typeSet \
typeSet.add \
typeSetEntry \
typecheckExprSwitch \
typecheckTypeSwitch \
typecheckpartialcall \
typecheckrange \
typecheckrangeExpr \
typecheckselect \
typecheckswitch \
vargen \
builtin.go \
builtin_test.go \
const.go \
func.go \
iexport.go \
iimport.go \
mapfile_mmap.go \
syms.go \
target.go \
typecheck.go \
unsafe.go \
universe.go \
cmd/compile/internal/typecheck
'
rm gen.go types.go types_acc.go
sed -i '' 's/package gc/package typecheck/' mapfile_read.go mkbuiltin.go
mv mapfile_read.go ../typecheck # not part of default build
mv mkbuiltin.go ../typecheck # package main helper
mv builtin ../typecheck
cd ../typecheck
mv dcl.go dcl1.go
mv typecheck.go typecheck1.go
mv universe.go universe1.go
rf '
# Sweep some small files into larger ones.
# "mv sym... file1.go file.go" (after the mv file1.go file.go above)
# lets us insert sym... at the top of file.go.
mv okfor okforeq universe1.go universe.go
mv DeclContext vargen dcl1.go Temp TempAt autotmpname NewMethodType dcl.go
mv InitTodoFunc inimport decldepth TypecheckAllowed typecheck1.go typecheck.go
mv inl.go closure.go func.go
mv range.go select.go swt.go stmt.go
mv Lookup loadsys LookupRuntimeFunc LookupRuntimeVar syms.go
mv unsafe.go const.go
mv TypecheckAssignExpr AssignExpr
mv TypecheckExpr Expr
mv TypecheckStmt Stmt
mv TypecheckExprs Exprs
mv TypecheckStmts Stmts
mv TypecheckCall Call
mv TypecheckCallee Callee
mv _typecheck check
mv TypecheckFunc Func
mv TypecheckFuncBody FuncBody
mv TypecheckImports AllImportedBodies
mv TypecheckImportedBody ImportedBody
mv TypecheckInit Init
mv TypecheckPackage Package
'
rm gen.go go.go init.go main.go reflect.go
Change-Id: Iea6a7aaf6407d690670ec58aeb36cc0b280f80b0
Reviewed-on: https://go-review.googlesource.com/c/go/+/279236
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-23 00:41:49 -05:00
"cmd/compile/internal/typecheck"
cmd/compile: factor out Pkg, Sym, and Type into package types
- created new package cmd/compile/internal/types
- moved Pkg, Sym, Type to new package
- to break cycles, for now we need the (ugly) types/utils.go
file which contains a handful of functions that must be installed
early by the gc frontend
- to break cycles, for now we need two functions to convert between
*gc.Node and *types.Node (the latter is a dummy type)
- adjusted the gc's code to use the new package and the conversion
functions as needed
- made several Pkg, Sym, and Type methods functions as needed
- renamed constructors typ, typPtr, typArray, etc. to types.New,
types.NewPtr, types.NewArray, etc.
Passes toolstash-check -all.
Change-Id: I8adfa5e85c731645d0a7fd2030375ed6ebf54b72
Reviewed-on: https://go-review.googlesource.com/39855
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2017-04-04 17:54:02 -07:00
"cmd/compile/internal/types"
2017-10-06 11:32:28 -04:00
"cmd/internal/obj"
2024-03-04 13:29:39 -05:00
"cmd/internal/pgo"
2025-03-05 13:44:12 -05:00
"cmd/internal/src"
2016-12-06 17:08:06 -08:00
)
2015-02-13 14:40:36 -05:00
2018-04-27 12:13:17 -04:00
// Inlining budget parameters, gathered in one place
const (
inlineMaxBudget = 80
inlineExtraAppendCost = 0
2018-11-04 19:23:08 -08:00
// default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
2018-11-30 08:36:00 -05:00
inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
2024-08-28 10:34:54 -04:00
inlineParamCallCost = 17 // calling a parameter only costs this much extra (inlining might expose a constant function)
2018-11-04 19:23:08 -08:00
inlineExtraPanicCost = 1 // do not penalize inlining panics.
inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
2018-07-23 13:09:48 -07:00
2024-11-19 17:18:38 -05:00
inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
inlineClosureCalledOnceCost = 10 * inlineMaxBudget // if a closure is just called once, inline it.
2018-04-27 12:13:17 -04:00
)
2022-09-09 11:29:32 -07:00
var (
cmd/compile: use edge weights to decide inlineability in PGO
Currently, with PGO, the inliner uses node weights to decide if a
function is inlineable (with a larger budget). But the actual
inlining is determined by the weight of the call edge. There is a
discrepancy that, if a callee node is hot but the call edge is not,
it would not inlined, and marking the callee inlineable would of
no use.
Instead of using two kinds of weights, we just use the edge
weights to decide inlineability. If a function is the callee of a
hot call edge, its inlineability is determined with a larger
threshold. For a function that exceeds the regular inlining budget,
it is still inlined only when the call edge is hot, as it would
exceed the regular inlining cost for non-hot call sites, even if
it is marked inlineable.
For #55022.
Change-Id: I93fa9919fc6bcbb394e6cfe54ec96a96eede08f7
Reviewed-on: https://go-review.googlesource.com/c/go/+/447015
Run-TryBot: Cherry Mui <cherryyz@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2022-11-01 11:40:29 -04:00
// List of all hot callee nodes.
2022-10-31 12:20:09 -04:00
// TODO(prattmic): Make this non-global.
2024-03-04 13:29:39 -05:00
candHotCalleeMap = make ( map [ * pgoir . IRNode ] struct { } )
2022-09-09 11:29:32 -07:00
2024-04-02 11:12:44 -04:00
// Set of functions that contain hot call sites.
hasHotCall = make ( map [ * ir . Func ] struct { } )
2022-10-31 12:20:09 -04:00
// List of all hot call sites. CallSiteInfo.Callee is always nil.
// TODO(prattmic): Make this non-global.
2024-03-04 13:29:39 -05:00
candHotEdgeMap = make ( map [ pgoir . CallSiteInfo ] struct { } )
2022-09-09 11:29:32 -07:00
// Threshold in percentage for hot callsite inlining.
2022-11-01 12:33:58 -04:00
inlineHotCallSiteThresholdPercent float64
// Threshold in CDF percentage for hot callsite inlining,
// that is, for a threshold of X the hottest callsites that
// make up the top X% of total edge weight will be
// considered hot for inlining candidates.
2022-11-10 11:33:00 -05:00
inlineCDFHotCallSiteThresholdPercent = float64 ( 99 )
2022-09-09 11:29:32 -07:00
// Budget increased due to hotness.
2022-11-10 11:33:00 -05:00
inlineHotMaxBudget int32 = 2000
2022-09-09 11:29:32 -07:00
)
2024-04-02 11:12:44 -04:00
func IsPgoHotFunc ( fn * ir . Func , profile * pgoir . Profile ) bool {
if profile == nil {
return false
}
if n , ok := profile . WeightedCG . IRNodes [ ir . LinkFuncName ( fn ) ] ; ok {
_ , ok := candHotCalleeMap [ n ]
return ok
}
return false
}
func HasPgoHotInline ( fn * ir . Func ) bool {
_ , has := hasHotCall [ fn ]
return has
}
2023-11-18 20:16:47 -08:00
// PGOInlinePrologue records the hot callsites from ir-graph.
2024-03-04 13:29:39 -05:00
func PGOInlinePrologue ( p * pgoir . Profile ) {
2022-11-15 13:32:32 -05:00
if base . Debug . PGOInlineCDFThreshold != "" {
if s , err := strconv . ParseFloat ( base . Debug . PGOInlineCDFThreshold , 64 ) ; err == nil && s >= 0 && s <= 100 {
inlineCDFHotCallSiteThresholdPercent = s
} else {
base . Fatalf ( "invalid PGOInlineCDFThreshold, must be between 0 and 100" )
}
2022-11-01 12:33:58 -04:00
}
2023-09-19 17:04:06 -04:00
var hotCallsites [ ] pgo . NamedCallEdge
2022-11-15 13:32:32 -05:00
inlineHotCallSiteThresholdPercent , hotCallsites = hotNodesFromCDF ( p )
2023-05-12 15:36:37 -04:00
if base . Debug . PGODebug > 0 {
2022-11-01 12:33:58 -04:00
fmt . Printf ( "hot-callsite-thres-from-CDF=%v\n" , inlineHotCallSiteThresholdPercent )
2022-09-09 11:29:32 -07:00
}
2022-11-10 11:33:00 -05:00
if x := base . Debug . PGOInlineBudget ; x != 0 {
inlineHotMaxBudget = int32 ( x )
2022-09-09 11:29:32 -07:00
}
2022-11-04 13:54:59 -04:00
for _ , n := range hotCallsites {
2022-11-15 13:32:32 -05:00
// mark inlineable callees from hot edges
if callee := p . WeightedCG . IRNodes [ n . CalleeName ] ; callee != nil {
candHotCalleeMap [ callee ] = struct { } { }
2022-11-04 13:54:59 -04:00
}
2022-11-15 13:32:32 -05:00
// mark hot call sites
2023-05-12 16:39:43 -04:00
if caller := p . WeightedCG . IRNodes [ n . CallerName ] ; caller != nil && caller . AST != nil {
2024-03-04 13:29:39 -05:00
csi := pgoir . CallSiteInfo { LineOffset : n . CallSiteOffset , Caller : caller . AST }
2022-11-15 13:32:32 -05:00
candHotEdgeMap [ csi ] = struct { } { }
2022-09-09 11:29:32 -07:00
}
2022-11-15 13:32:32 -05:00
}
2023-05-12 16:39:43 -04:00
if base . Debug . PGODebug >= 3 {
2022-09-09 11:29:32 -07:00
fmt . Printf ( "hot-cg before inline in dot format:" )
cmd/compile: use edge weights to decide inlineability in PGO
Currently, with PGO, the inliner uses node weights to decide if a
function is inlineable (with a larger budget). But the actual
inlining is determined by the weight of the call edge. There is a
discrepancy that, if a callee node is hot but the call edge is not,
it would not inlined, and marking the callee inlineable would of
no use.
Instead of using two kinds of weights, we just use the edge
weights to decide inlineability. If a function is the callee of a
hot call edge, its inlineability is determined with a larger
threshold. For a function that exceeds the regular inlining budget,
it is still inlined only when the call edge is hot, as it would
exceed the regular inlining cost for non-hot call sites, even if
it is marked inlineable.
For #55022.
Change-Id: I93fa9919fc6bcbb394e6cfe54ec96a96eede08f7
Reviewed-on: https://go-review.googlesource.com/c/go/+/447015
Run-TryBot: Cherry Mui <cherryyz@google.com>
Reviewed-by: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2022-11-01 11:40:29 -04:00
p . PrintWeightedCallGraphDOT ( inlineHotCallSiteThresholdPercent )
2022-09-09 11:29:32 -07:00
}
}
2022-11-15 13:32:32 -05:00
// hotNodesFromCDF computes an edge weight threshold and the list of hot
// nodes that make up the given percentage of the CDF. The threshold, as
// a percent, is the lower bound of weight for nodes to be considered hot
// (currently only used in debug prints) (in case of equal weights,
// comparing with the threshold may not accurately reflect which nodes are
2024-02-05 17:12:17 +00:00
// considered hot).
2024-03-04 13:29:39 -05:00
func hotNodesFromCDF ( p * pgoir . Profile ) ( float64 , [ ] pgo . NamedCallEdge ) {
2022-11-01 12:33:58 -04:00
cum := int64 ( 0 )
2023-09-19 17:04:06 -04:00
for i , n := range p . NamedEdgeMap . ByWeight {
w := p . NamedEdgeMap . Weight [ n ]
2022-11-01 12:33:58 -04:00
cum += w
2023-09-19 17:04:06 -04:00
if pgo . WeightInPercentage ( cum , p . TotalWeight ) > inlineCDFHotCallSiteThresholdPercent {
2022-11-15 13:32:32 -05:00
// nodes[:i+1] to include the very last node that makes it to go over the threshold.
// (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
// include that node instead of excluding it.)
2023-09-19 17:04:06 -04:00
return pgo . WeightInPercentage ( w , p . TotalWeight ) , p . NamedEdgeMap . ByWeight [ : i + 1 ]
2022-11-01 12:33:58 -04:00
}
}
2023-09-19 17:04:06 -04:00
return 0 , p . NamedEdgeMap . ByWeight
2022-11-01 12:33:58 -04:00
}
2023-11-18 20:16:47 -08:00
// CanInlineFuncs computes whether a batch of functions are inlinable.
2024-03-04 13:29:39 -05:00
func CanInlineFuncs ( funcs [ ] * ir . Func , profile * pgoir . Profile ) {
2023-11-18 20:16:47 -08:00
if profile != nil {
2024-02-05 17:12:17 +00:00
PGOInlinePrologue ( profile )
2023-05-12 15:36:37 -04:00
}
2023-11-18 20:16:47 -08:00
if base . Flag . LowerL == 0 {
return
2022-10-28 17:34:43 -04:00
}
2024-02-07 10:23:53 -08:00
ir . VisitFuncsBottomUp ( funcs , func ( funcs [ ] * ir . Func , recursive bool ) {
for _ , fn := range funcs {
2025-03-05 14:27:15 -05:00
CanInline ( fn , profile )
2024-02-07 10:23:53 -08:00
if inlheur . Enabled ( ) {
analyzeFuncProps ( fn , profile )
2023-03-09 09:59:26 -05:00
}
}
2024-02-07 10:23:53 -08:00
} )
2023-04-14 14:07:37 -04:00
}
2023-07-31 15:26:26 -04:00
// inlineBudget determines the max budget for function 'fn' prior to
2024-02-05 17:12:17 +00:00
// analyzing the hairiness of the body of 'fn'. We pass in the pgo
2023-08-11 09:40:31 -04:00
// profile if available (which can change the budget), also a
// 'relaxed' flag, which expands the budget slightly to allow for the
// possibility that a call to the function might have its score
// adjusted downwards. If 'verbose' is set, then print a remark where
// we boost the budget due to PGO.
2024-03-04 13:29:39 -05:00
func inlineBudget ( fn * ir . Func , profile * pgoir . Profile , relaxed bool , verbose bool ) int32 {
2023-07-31 15:26:26 -04:00
// Update the budget for profile-guided inlining.
budget := int32 ( inlineMaxBudget )
2024-04-02 11:12:44 -04:00
if IsPgoHotFunc ( fn , profile ) {
budget = inlineHotMaxBudget
if verbose {
fmt . Printf ( "hot-node enabled increased budget=%v for func=%v\n" , budget , ir . PkgFuncName ( fn ) )
2023-07-31 15:26:26 -04:00
}
}
2023-08-11 09:40:31 -04:00
if relaxed {
2023-09-28 14:07:29 -04:00
budget += inlheur . BudgetExpansion ( inlineMaxBudget )
2023-08-11 09:40:31 -04:00
}
2024-11-15 17:08:34 -05:00
if fn . ClosureParent != nil {
2024-11-19 17:18:38 -05:00
// be very liberal here, if the closure is only called once, the budget is large
budget = max ( budget , inlineClosureCalledOnceCost )
2024-11-15 17:08:34 -05:00
}
2023-07-31 15:26:26 -04:00
return budget
}
2021-01-21 14:13:36 +08:00
// CanInline determines whether fn is inlineable.
2021-04-26 14:32:23 -07:00
// If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
// fn and fn.Body will already have been typechecked.
2024-03-04 13:29:39 -05:00
func CanInline ( fn * ir . Func , profile * pgoir . Profile ) {
2020-11-28 07:31:18 -05:00
if fn . Nname == nil {
2021-01-15 14:12:35 -08:00
base . Fatalf ( "CanInline no nname %+v" , fn )
2015-02-13 14:40:36 -05:00
}
2016-05-03 17:21:32 -07:00
var reason string // reason, if any, that the function was not inlined
2020-11-19 20:49:23 -05:00
if base . Flag . LowerM > 1 || logopt . Enabled ( ) {
2016-05-03 17:21:32 -07:00
defer func ( ) {
if reason != "" {
2020-11-19 20:49:23 -05:00
if base . Flag . LowerM > 1 {
2020-11-28 07:31:18 -05:00
fmt . Printf ( "%v: cannot inline %v: %s\n" , ir . Line ( fn ) , fn . Nname , reason )
2019-10-29 17:25:56 -04:00
}
if logopt . Enabled ( ) {
2020-11-22 09:59:15 -05:00
logopt . LogOpt ( fn . Pos ( ) , "cannotInlineFunction" , "inline" , ir . FuncName ( fn ) , reason )
2019-10-29 17:25:56 -04:00
}
2016-05-03 17:21:32 -07:00
}
} ( )
}
2023-05-12 16:39:43 -04:00
reason = InlineImpossible ( fn )
if reason != "" {
2023-02-17 11:19:32 +07:00
return
}
2017-04-25 18:02:43 -07:00
if fn . Typecheck ( ) == 0 {
2021-01-15 14:12:35 -08:00
base . Fatalf ( "CanInline on non-typechecked function %v" , fn )
2015-02-13 14:40:36 -05:00
}
2020-11-28 07:31:18 -05:00
n := fn . Nname
2020-12-23 00:02:08 -05:00
if n . Func . InlinabilityChecked ( ) {
2017-09-18 14:54:10 -07:00
return
}
2020-12-23 00:02:08 -05:00
defer n . Func . SetInlinabilityChecked ( true )
2017-09-18 14:54:10 -07:00
2018-04-27 12:13:17 -04:00
cc := int32 ( inlineExtraCallCost )
2020-11-19 20:49:23 -05:00
if base . Flag . LowerL == 4 {
2018-04-27 12:13:17 -04:00
cc = 1 // this appears to yield better performance than 0.
}
2023-11-10 07:57:46 -05:00
// Used a "relaxed" inline budget if the new inliner is enabled.
2023-10-31 13:21:41 -04:00
relaxed := inlheur . Enabled ( )
2023-08-11 09:40:31 -04:00
// Compute the inline budget for this func.
budget := inlineBudget ( fn , profile , relaxed , base . Debug . PGODebug > 0 )
2022-09-09 11:29:32 -07:00
2018-05-23 15:31:52 -04:00
// At this point in the game the function we're looking at may
// have "stale" autos, vars that still appear in the Dcl list, but
// which no longer have any uses in the function body (due to
// elimination by deadcode). We'd like to exclude these dead vars
// when creating the "Inline.Dcl" field below; to accomplish this,
// the hairyVisitor below builds up a map of used/referenced
// locals, and we use this map to produce a pruned Inline.Dcl
2023-08-26 16:37:24 -07:00
// list. See issue 25459 for more context.
2018-05-23 15:31:52 -04:00
visitor := hairyVisitor {
2022-09-09 11:29:32 -07:00
curFunc : fn ,
2023-11-18 20:16:47 -08:00
isBigFunc : IsBigFunc ( fn ) ,
2022-09-09 11:29:32 -07:00
budget : budget ,
maxBudget : budget ,
2018-05-23 15:31:52 -04:00
extraCallCost : cc ,
2022-10-28 17:34:43 -04:00
profile : profile ,
2018-05-23 15:31:52 -04:00
}
2020-12-02 20:18:47 -05:00
if visitor . tooHairy ( fn ) {
2017-04-19 16:32:41 -04:00
reason = visitor . reason
2016-05-03 17:21:32 -07:00
return
}
2015-02-13 14:40:36 -05:00
2020-12-23 00:02:08 -05:00
n . Func . Inl = & ir . Inline {
2024-02-05 17:12:17 +00:00
Cost : budget - visitor . budget ,
Dcl : pruneUnusedAutos ( n . Func . Dcl , & visitor ) ,
HaveDcl : true ,
2021-05-27 02:47:04 -07:00
CanDelayResults : canDelayResults ( fn ) ,
2018-04-04 15:53:27 -07:00
}
2023-11-07 10:28:56 -05:00
if base . Flag . LowerM != 0 || logopt . Enabled ( ) {
noteInlinableFunc ( n , fn , budget - visitor . budget )
}
}
2015-02-13 14:40:36 -05:00
2023-11-07 10:28:56 -05:00
// noteInlinableFunc issues a message to the user that the specified
// function is inlinable.
func noteInlinableFunc ( n * ir . Name , fn * ir . Func , cost int32 ) {
2020-11-19 20:49:23 -05:00
if base . Flag . LowerM > 1 {
2023-11-07 10:28:56 -05:00
fmt . Printf ( "%v: can inline %v with cost %d as: %v { %v }\n" , ir . Line ( fn ) , n , cost , fn . Type ( ) , ir . Nodes ( fn . Body ) )
2020-11-19 20:49:23 -05:00
} else if base . Flag . LowerM != 0 {
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
fmt . Printf ( "%v: can inline %v\n" , ir . Line ( fn ) , n )
2015-02-13 14:40:36 -05:00
}
2023-11-07 10:28:56 -05:00
// JSON optimization log output.
2019-10-29 17:25:56 -04:00
if logopt . Enabled ( ) {
2023-11-07 10:28:56 -05:00
logopt . LogOpt ( fn . Pos ( ) , "canInlineFunction" , "inline" , ir . FuncName ( fn ) , fmt . Sprintf ( "cost: %d" , cost ) )
2019-10-29 17:25:56 -04:00
}
2015-02-13 14:40:36 -05:00
}
2023-05-12 16:39:43 -04:00
// InlineImpossible returns a non-empty reason string if fn is impossible to
// inline regardless of cost or contents.
func InlineImpossible ( fn * ir . Func ) string {
var reason string // reason, if any, that the function can not be inlined.
if fn . Nname == nil {
reason = "no name"
return reason
}
// If marked "go:noinline", don't inline.
if fn . Pragma & ir . Noinline != 0 {
reason = "marked go:noinline"
return reason
}
// If marked "go:norace" and -race compilation, don't inline.
if base . Flag . Race && fn . Pragma & ir . Norace != 0 {
reason = "marked go:norace with -race compilation"
return reason
}
// If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
if base . Debug . Checkptr != 0 && fn . Pragma & ir . NoCheckPtr != 0 {
reason = "marked go:nocheckptr"
return reason
}
// If marked "go:cgo_unsafe_args", don't inline, since the function
// makes assumptions about its argument frame layout.
if fn . Pragma & ir . CgoUnsafeArgs != 0 {
reason = "marked go:cgo_unsafe_args"
return reason
}
// If marked as "go:uintptrkeepalive", don't inline, since the keep
// alive information is lost during inlining.
//
// TODO(prattmic): This is handled on calls during escape analysis,
// which is after inlining. Move prior to inlining so the keep-alive is
// maintained after inlining.
if fn . Pragma & ir . UintptrKeepAlive != 0 {
reason = "marked as having a keep-alive uintptr argument"
return reason
}
// If marked as "go:uintptrescapes", don't inline, since the escape
// information is lost during inlining.
if fn . Pragma & ir . UintptrEscapes != 0 {
reason = "marked as having an escaping uintptr argument"
return reason
}
// The nowritebarrierrec checker currently works at function
// granularity, so inlining yeswritebarrierrec functions can confuse it
// (#22342). As a workaround, disallow inlining them for now.
if fn . Pragma & ir . Yeswritebarrierrec != 0 {
reason = "marked go:yeswritebarrierrec"
return reason
}
2023-06-03 00:56:31 +00:00
// If a local function has no fn.Body (is defined outside of Go), cannot inline it.
// Imported functions don't have fn.Body but might have inline body in fn.Inl.
if len ( fn . Body ) == 0 && ! typecheck . HaveInlineBody ( fn ) {
2023-05-12 16:39:43 -04:00
reason = "no function body"
return reason
}
return ""
}
2021-05-27 02:47:04 -07:00
// canDelayResults reports whether inlined calls to fn can delay
// declaring the result parameter until the "return" statement.
func canDelayResults ( fn * ir . Func ) bool {
// We can delay declaring+initializing result parameters if:
// (1) there's exactly one "return" statement in the inlined function;
// (2) it's not an empty return statement (#44355); and
// (3) the result parameters aren't named.
nreturns := 0
ir . VisitList ( fn . Body , func ( n ir . Node ) {
if n , ok := n . ( * ir . ReturnStmt ) ; ok {
nreturns ++
if len ( n . Results ) == 0 {
nreturns ++ // empty return statement (case 2)
}
}
} )
if nreturns != 1 {
return false // not exactly one return statement (case 1)
}
// temporaries for return values.
2023-08-20 10:05:29 -07:00
for _ , param := range fn . Type ( ) . Results ( ) {
2023-09-11 17:45:37 -07:00
if sym := param . Sym ; sym != nil && ! sym . IsBlank ( ) {
2021-05-27 02:47:04 -07:00
return false // found a named result parameter (case 3)
}
}
return true
}
2017-04-19 16:32:41 -04:00
// hairyVisitor visits a function body to determine its inlining
// hairiness and whether or not it can be inlined.
type hairyVisitor struct {
2022-09-09 11:29:32 -07:00
// This is needed to access the current caller in the doNode function.
curFunc * ir . Func
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
isBigFunc bool
2018-04-27 12:13:17 -04:00
budget int32
2022-09-09 11:29:32 -07:00
maxBudget int32
2018-04-27 12:13:17 -04:00
reason string
extraCallCost int32
2021-01-21 14:13:36 +08:00
usedLocals ir . NameSet
2021-01-07 11:17:57 +08:00
do func ( ir . Node ) bool
2024-03-04 13:29:39 -05:00
profile * pgoir . Profile
2017-04-19 16:32:41 -04:00
}
2020-12-02 20:18:47 -05:00
func ( v * hairyVisitor ) tooHairy ( fn * ir . Func ) bool {
v . do = v . doNode // cache closure
2021-01-07 11:17:57 +08:00
if ir . DoChildren ( fn , v . do ) {
2020-12-02 20:18:47 -05:00
return true
}
if v . budget < 0 {
2022-09-09 11:29:32 -07:00
v . reason = fmt . Sprintf ( "function too complex: cost %d exceeds budget %d" , v . maxBudget - v . budget , v . maxBudget )
2020-12-02 20:18:47 -05:00
return true
2016-02-27 14:31:33 -08:00
}
return false
}
cmd/compile: allow more inlining of functions that construct closures
[This is a roll-forward of CL 479095, which was reverted due to a bad
interaction between inlining and escape analysis, then later fixed
first with an attempt in CL 482355, then again in CL 484859, and then
one more time with CL 492135.]
Currently, when the inliner is determining if a function is
inlineable, it descends into the bodies of closures constructed by
that function. This has several unfortunate consequences:
- If the closure contains a disallowed operation (e.g., a defer), then
the outer function can't be inlined. It makes sense that the
*closure* can't be inlined in this case, but it doesn't make sense
to punish the function that constructs the closure.
- The hairiness of the closure counts against the inlining budget of
the outer function. Since we currently copy the closure body when
inlining the outer function, this makes sense from the perspective
of export data size and binary size, but ultimately doesn't make
much sense from the perspective of what should be inlineable.
- Since the inliner walks into every closure created by an outer
function in addition to starting a walk at every closure, this adds
an n^2 factor to inlinability analysis.
This CL simply drops this behavior.
In std, this makes 57 more functions inlinable, and disallows inlining
for 10 (due to the basic instability of our bottom-up inlining
approach), for an net increase of 47 inlinable functions (+0.6%).
This will help significantly with the performance of the functions to
be added for #56102, which have a somewhat complicated nesting of
closures with a performance-critical fast path.
The downside of this seems to be a potential increase in export data
and text size, but the practical impact of this seems to be
negligible:
│ before │ after │
│ bytes │ bytes vs base │
Go/binary 15.12Mi ± 0% 15.14Mi ± 0% +0.16% (n=1)
Go/text 5.220Mi ± 0% 5.237Mi ± 0% +0.32% (n=1)
Compile/binary 22.92Mi ± 0% 22.94Mi ± 0% +0.07% (n=1)
Compile/text 8.428Mi ± 0% 8.435Mi ± 0% +0.08% (n=1)
Change-Id: I5f75fcceb177f05853996b75184a486528eafe96
Reviewed-on: https://go-review.googlesource.com/c/go/+/492017
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Than McIntosh <thanm@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
2023-04-04 18:31:46 -04:00
// doNode visits n and its children, updates the state in v, and returns true if
// n makes the current function too hairy for inlining.
2021-01-07 11:17:57 +08:00
func ( v * hairyVisitor ) doNode ( n ir . Node ) bool {
2015-02-17 22:13:49 -05:00
if n == nil {
2021-01-07 11:17:57 +08:00
return false
2015-02-13 14:40:36 -05:00
}
cmd/compile: redo IsRuntimePkg/IsReflectPkg predicate
Currently, the types package has IsRuntimePkg and IsReflectPkg
predicates for testing if a Pkg is the runtime or reflect packages.
IsRuntimePkg returns "true" for any "CompilingRuntime" package, which
includes all of the packages imported by the runtime. This isn't
inherently wrong, except that all but one use of it is of the form "is
this Sym a specific runtime.X symbol?" for which we clearly only want
the package "runtime" itself. IsRuntimePkg was introduced (as
isRuntime) in CL 37538 as part of separating the real runtime package
from the compiler built-in fake runtime package. As of that CL, the
"runtime" package couldn't import any other packages, so this was
adequate at the time.
We could fix this by just changing the implementation of IsRuntimePkg,
but the meaning of this API is clearly somewhat ambiguous. Instead, we
replace it with a new RuntimeSymName function that returns the name of
a symbol if it's in package "runtime", or "" if not. This is what
every call site (except one) actually wants, which lets us simplify
the callers, and also more clearly addresses the ambiguity between
package "runtime" and the general concept of a runtime package.
IsReflectPkg doesn't have the same issue of ambiguity, but it
parallels IsRuntimePkg and is used in the same way, so we replace it
with a new ReflectSymName for consistency.
Change-Id: If3a81d7d11732a9ab2cac9488d17508415cfb597
Reviewed-on: https://go-review.googlesource.com/c/go/+/521696
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Run-TryBot: Austin Clements <austin@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-07 16:16:30 -04:00
opSwitch :
2020-11-22 09:59:15 -05:00
switch n . Op ( ) {
2015-02-24 12:19:01 -05:00
// Call is okay if inlinable and we have the budget for the body.
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . OCALLFUNC :
2020-12-10 18:46:45 -05:00
n := n . ( * ir . CallExpr )
2022-06-17 13:06:16 -04:00
var cheap bool
2023-10-04 15:22:49 -07:00
if n . Fun . Op ( ) == ir . ONAME {
name := n . Fun . ( * ir . Name )
cmd/compile: redo IsRuntimePkg/IsReflectPkg predicate
Currently, the types package has IsRuntimePkg and IsReflectPkg
predicates for testing if a Pkg is the runtime or reflect packages.
IsRuntimePkg returns "true" for any "CompilingRuntime" package, which
includes all of the packages imported by the runtime. This isn't
inherently wrong, except that all but one use of it is of the form "is
this Sym a specific runtime.X symbol?" for which we clearly only want
the package "runtime" itself. IsRuntimePkg was introduced (as
isRuntime) in CL 37538 as part of separating the real runtime package
from the compiler built-in fake runtime package. As of that CL, the
"runtime" package couldn't import any other packages, so this was
adequate at the time.
We could fix this by just changing the implementation of IsRuntimePkg,
but the meaning of this API is clearly somewhat ambiguous. Instead, we
replace it with a new RuntimeSymName function that returns the name of
a symbol if it's in package "runtime", or "" if not. This is what
every call site (except one) actually wants, which lets us simplify
the callers, and also more clearly addresses the ambiguity between
package "runtime" and the general concept of a runtime package.
IsReflectPkg doesn't have the same issue of ambiguity, but it
parallels IsRuntimePkg and is used in the same way, so we replace it
with a new ReflectSymName for consistency.
Change-Id: If3a81d7d11732a9ab2cac9488d17508415cfb597
Reviewed-on: https://go-review.googlesource.com/c/go/+/521696
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Run-TryBot: Austin Clements <austin@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-07 16:16:30 -04:00
if name . Class == ir . PFUNC {
2024-09-16 14:07:43 -04:00
s := name . Sym ( )
fn := s . Name
switch s . Pkg . Path {
case "internal/abi" :
switch fn {
case "NoEscape" :
// Special case for internal/abi.NoEscape. It does just type
// conversions to appease the escape analysis, and doesn't
// generate code.
cheap = true
}
case "internal/runtime/sys" :
switch fn {
2024-09-16 15:58:36 -04:00
case "GetCallerPC" , "GetCallerSP" :
// Functions that call GetCallerPC/SP can not be inlined
// because users expect the PC/SP of the logical caller,
// but GetCallerPC/SP returns the physical caller.
2024-09-16 14:07:43 -04:00
v . reason = "call to " + fn
return true
}
2024-10-24 14:17:39 -04:00
case "go.runtime" :
2024-09-16 14:07:43 -04:00
switch fn {
case "throw" :
// runtime.throw is a "cheap call" like panic in normal code.
v . budget -= inlineExtraThrowCost
break opSwitch
case "panicrangestate" :
cheap = true
}
hash/maphash, cmd/compile: make Comparable[string] not escape its argument
Currently, maphash.Comparable forces its argument to escape if it
contains a pointer, as we cannot hash stack pointers, which will
change when the stack moves. However, for a string, it is actually
okay if its data pointer points to the stack, as the hash depends
on only the content, not the pointer.
Currently there is no way to write this type-dependent escape
logic in Go code. So we implement it in the compiler as an
intrinsic. The compiler can also recognize not just the string
type, but types whose pointers are all string pointers, and make
them not escape.
Fixes #70560.
Change-Id: I3bf219ad71a238d2e35f0ea33de96487bc8cc231
Reviewed-on: https://go-review.googlesource.com/c/go/+/632715
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-01 23:53:23 -05:00
case "hash/maphash" :
if strings . HasPrefix ( fn , "escapeForHash[" ) {
// hash/maphash.escapeForHash[T] is a compiler intrinsic
// implemented in the escape analysis phase.
cheap = true
}
2022-06-17 13:06:16 -04:00
}
}
2022-10-10 13:39:30 -04:00
// Special case for coverage counter updates; although
// these correspond to real operations, we treat them as
// zero cost for the moment. This is due to the existence
// of tests that are sensitive to inlining-- if the
// insertion of coverage instrumentation happens to tip a
// given function over the threshold and move it from
// "inlinable" to "not-inlinable", this can cause changes
// in allocation behavior, which can then result in test
// failures (a good example is the TestAllocations in
// crypto/ed25519).
if isAtomicCoverageCounterUpdate ( n ) {
2022-10-28 13:21:36 -04:00
return false
2022-10-10 13:39:30 -04:00
}
2017-04-19 12:57:52 -04:00
}
2023-10-04 15:22:49 -07:00
if n . Fun . Op ( ) == ir . OMETHEXPR {
if meth := ir . MethodExprName ( n . Fun ) ; meth != nil {
cmd/compile: make encoding/binary loads/stores cheaper to inline
The encoding/binary little- and big-endian load and store routines are
frequently used in performance sensitive code. They look fairly complex
to the inliner. Though the routines themselves can be inlined,
code using them typically cannot be.
Yet they typically compile down to an instruction or two
on architectures that support merging such loads.
This change teaches the inliner to treat calls to these methods as cheap,
so that code using them will be more inlineable.
It'd be better to teach the inliner that this pattern of code is cheap,
rather than these particular methods. However, that is difficult to do
robustly when working with the IR representation. And the broader project
of which that would be a part, namely to model the rest of the compiler
in the inliner, is probably a non-starter. By way of contrast, imperfect
though it is, this change is an easy, cheap, and useful heuristic.
If/when we base inlining decisions on more accurate information obtained
later in the compilation process, or on PGO/FGO, we can remove this
and other such heuristics.
Newly inlineable functions in the standard library:
crypto/cipher.gcmInc32
crypto/sha512.appendUint64
crypto/md5.appendUint64
crypto/sha1.appendUint64
crypto/sha256.appendUint64
vendor/golang.org/x/crypto/poly1305.initialize
encoding/gob.(*encoderState).encodeUint
vendor/golang.org/x/text/unicode/norm.buildRecompMap
net/http.(*http2SettingsFrame).Setting
net/http.http2parseGoAwayFrame
net/http.http2parseWindowUpdateFrame
Benchmark impact for encoding/gob (the only package I measured):
name old time/op new time/op delta
EndToEndPipe-8 2.25µs ± 1% 2.21µs ± 3% -1.79% (p=0.000 n=28+27)
EndToEndByteBuffer-8 93.3ns ± 5% 94.2ns ± 5% ~ (p=0.174 n=30+30)
EndToEndSliceByteBuffer-8 10.5µs ± 1% 10.6µs ± 1% +0.87% (p=0.000 n=30+30)
EncodeComplex128Slice-8 1.81µs ± 0% 1.75µs ± 1% -3.23% (p=0.000 n=28+30)
EncodeFloat64Slice-8 900ns ± 1% 847ns ± 0% -5.91% (p=0.000 n=29+28)
EncodeInt32Slice-8 1.02µs ± 0% 0.90µs ± 0% -11.82% (p=0.000 n=28+26)
EncodeStringSlice-8 1.16µs ± 1% 1.04µs ± 1% -10.20% (p=0.000 n=29+26)
EncodeInterfaceSlice-8 28.7µs ± 3% 29.2µs ± 6% ~ (p=0.067 n=29+30)
DecodeComplex128Slice-8 7.98µs ± 1% 7.96µs ± 1% -0.27% (p=0.017 n=30+30)
DecodeFloat64Slice-8 4.33µs ± 1% 4.34µs ± 1% +0.24% (p=0.022 n=30+29)
DecodeInt32Slice-8 4.18µs ± 1% 4.18µs ± 0% ~ (p=0.074 n=30+28)
DecodeStringSlice-8 13.2µs ± 1% 13.1µs ± 1% -0.64% (p=0.000 n=28+28)
DecodeStringsSlice-8 31.9µs ± 1% 31.8µs ± 1% -0.34% (p=0.001 n=30+30)
DecodeBytesSlice-8 8.88µs ± 1% 8.84µs ± 1% -0.48% (p=0.000 n=30+30)
DecodeInterfaceSlice-8 64.1µs ± 1% 64.2µs ± 1% ~ (p=0.173 n=30+28)
DecodeMap-8 74.3µs ± 0% 74.2µs ± 0% ~ (p=0.131 n=29+30)
Fixes #42958
Change-Id: Ie048b8976fb403d8bcc72ac6bde4b33e133e2a47
Reviewed-on: https://go-review.googlesource.com/c/go/+/349931
Trust: Josh Bleecher Snyder <josharian@gmail.com>
Run-TryBot: Josh Bleecher Snyder <josharian@gmail.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
2021-09-13 15:28:55 -07:00
if fn := meth . Func ; fn != nil {
s := fn . Sym ( )
cmd/compile: redo IsRuntimePkg/IsReflectPkg predicate
Currently, the types package has IsRuntimePkg and IsReflectPkg
predicates for testing if a Pkg is the runtime or reflect packages.
IsRuntimePkg returns "true" for any "CompilingRuntime" package, which
includes all of the packages imported by the runtime. This isn't
inherently wrong, except that all but one use of it is of the form "is
this Sym a specific runtime.X symbol?" for which we clearly only want
the package "runtime" itself. IsRuntimePkg was introduced (as
isRuntime) in CL 37538 as part of separating the real runtime package
from the compiler built-in fake runtime package. As of that CL, the
"runtime" package couldn't import any other packages, so this was
adequate at the time.
We could fix this by just changing the implementation of IsRuntimePkg,
but the meaning of this API is clearly somewhat ambiguous. Instead, we
replace it with a new RuntimeSymName function that returns the name of
a symbol if it's in package "runtime", or "" if not. This is what
every call site (except one) actually wants, which lets us simplify
the callers, and also more clearly addresses the ambiguity between
package "runtime" and the general concept of a runtime package.
IsReflectPkg doesn't have the same issue of ambiguity, but it
parallels IsRuntimePkg and is used in the same way, so we replace it
with a new ReflectSymName for consistency.
Change-Id: If3a81d7d11732a9ab2cac9488d17508415cfb597
Reviewed-on: https://go-review.googlesource.com/c/go/+/521696
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Run-TryBot: Austin Clements <austin@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2023-07-07 16:16:30 -04:00
if types . RuntimeSymName ( s ) == "heapBits.nextArena" {
cmd/compile: make encoding/binary loads/stores cheaper to inline
The encoding/binary little- and big-endian load and store routines are
frequently used in performance sensitive code. They look fairly complex
to the inliner. Though the routines themselves can be inlined,
code using them typically cannot be.
Yet they typically compile down to an instruction or two
on architectures that support merging such loads.
This change teaches the inliner to treat calls to these methods as cheap,
so that code using them will be more inlineable.
It'd be better to teach the inliner that this pattern of code is cheap,
rather than these particular methods. However, that is difficult to do
robustly when working with the IR representation. And the broader project
of which that would be a part, namely to model the rest of the compiler
in the inliner, is probably a non-starter. By way of contrast, imperfect
though it is, this change is an easy, cheap, and useful heuristic.
If/when we base inlining decisions on more accurate information obtained
later in the compilation process, or on PGO/FGO, we can remove this
and other such heuristics.
Newly inlineable functions in the standard library:
crypto/cipher.gcmInc32
crypto/sha512.appendUint64
crypto/md5.appendUint64
crypto/sha1.appendUint64
crypto/sha256.appendUint64
vendor/golang.org/x/crypto/poly1305.initialize
encoding/gob.(*encoderState).encodeUint
vendor/golang.org/x/text/unicode/norm.buildRecompMap
net/http.(*http2SettingsFrame).Setting
net/http.http2parseGoAwayFrame
net/http.http2parseWindowUpdateFrame
Benchmark impact for encoding/gob (the only package I measured):
name old time/op new time/op delta
EndToEndPipe-8 2.25µs ± 1% 2.21µs ± 3% -1.79% (p=0.000 n=28+27)
EndToEndByteBuffer-8 93.3ns ± 5% 94.2ns ± 5% ~ (p=0.174 n=30+30)
EndToEndSliceByteBuffer-8 10.5µs ± 1% 10.6µs ± 1% +0.87% (p=0.000 n=30+30)
EncodeComplex128Slice-8 1.81µs ± 0% 1.75µs ± 1% -3.23% (p=0.000 n=28+30)
EncodeFloat64Slice-8 900ns ± 1% 847ns ± 0% -5.91% (p=0.000 n=29+28)
EncodeInt32Slice-8 1.02µs ± 0% 0.90µs ± 0% -11.82% (p=0.000 n=28+26)
EncodeStringSlice-8 1.16µs ± 1% 1.04µs ± 1% -10.20% (p=0.000 n=29+26)
EncodeInterfaceSlice-8 28.7µs ± 3% 29.2µs ± 6% ~ (p=0.067 n=29+30)
DecodeComplex128Slice-8 7.98µs ± 1% 7.96µs ± 1% -0.27% (p=0.017 n=30+30)
DecodeFloat64Slice-8 4.33µs ± 1% 4.34µs ± 1% +0.24% (p=0.022 n=30+29)
DecodeInt32Slice-8 4.18µs ± 1% 4.18µs ± 0% ~ (p=0.074 n=30+28)
DecodeStringSlice-8 13.2µs ± 1% 13.1µs ± 1% -0.64% (p=0.000 n=28+28)
DecodeStringsSlice-8 31.9µs ± 1% 31.8µs ± 1% -0.34% (p=0.001 n=30+30)
DecodeBytesSlice-8 8.88µs ± 1% 8.84µs ± 1% -0.48% (p=0.000 n=30+30)
DecodeInterfaceSlice-8 64.1µs ± 1% 64.2µs ± 1% ~ (p=0.173 n=30+28)
DecodeMap-8 74.3µs ± 0% 74.2µs ± 0% ~ (p=0.131 n=29+30)
Fixes #42958
Change-Id: Ie048b8976fb403d8bcc72ac6bde4b33e133e2a47
Reviewed-on: https://go-review.googlesource.com/c/go/+/349931
Trust: Josh Bleecher Snyder <josharian@gmail.com>
Run-TryBot: Josh Bleecher Snyder <josharian@gmail.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
2021-09-13 15:28:55 -07:00
// Special case: explicitly allow mid-stack inlining of
// runtime.heapBits.next even though it calls slow-path
// runtime.heapBits.nextArena.
cheap = true
}
// Special case: on architectures that can do unaligned loads,
// explicitly mark encoding/binary methods as cheap,
// because in practice they are, even though our inlining
// budgeting system does not see that. See issue 42958.
if base . Ctxt . Arch . CanMergeLoads && s . Pkg . Path == "encoding/binary" {
switch s . Name {
case "littleEndian.Uint64" , "littleEndian.Uint32" , "littleEndian.Uint16" ,
"bigEndian.Uint64" , "bigEndian.Uint32" , "bigEndian.Uint16" ,
"littleEndian.PutUint64" , "littleEndian.PutUint32" , "littleEndian.PutUint16" ,
2022-09-15 15:14:52 +08:00
"bigEndian.PutUint64" , "bigEndian.PutUint32" , "bigEndian.PutUint16" ,
"littleEndian.AppendUint64" , "littleEndian.AppendUint32" , "littleEndian.AppendUint16" ,
"bigEndian.AppendUint64" , "bigEndian.AppendUint32" , "bigEndian.AppendUint16" :
cmd/compile: make encoding/binary loads/stores cheaper to inline
The encoding/binary little- and big-endian load and store routines are
frequently used in performance sensitive code. They look fairly complex
to the inliner. Though the routines themselves can be inlined,
code using them typically cannot be.
Yet they typically compile down to an instruction or two
on architectures that support merging such loads.
This change teaches the inliner to treat calls to these methods as cheap,
so that code using them will be more inlineable.
It'd be better to teach the inliner that this pattern of code is cheap,
rather than these particular methods. However, that is difficult to do
robustly when working with the IR representation. And the broader project
of which that would be a part, namely to model the rest of the compiler
in the inliner, is probably a non-starter. By way of contrast, imperfect
though it is, this change is an easy, cheap, and useful heuristic.
If/when we base inlining decisions on more accurate information obtained
later in the compilation process, or on PGO/FGO, we can remove this
and other such heuristics.
Newly inlineable functions in the standard library:
crypto/cipher.gcmInc32
crypto/sha512.appendUint64
crypto/md5.appendUint64
crypto/sha1.appendUint64
crypto/sha256.appendUint64
vendor/golang.org/x/crypto/poly1305.initialize
encoding/gob.(*encoderState).encodeUint
vendor/golang.org/x/text/unicode/norm.buildRecompMap
net/http.(*http2SettingsFrame).Setting
net/http.http2parseGoAwayFrame
net/http.http2parseWindowUpdateFrame
Benchmark impact for encoding/gob (the only package I measured):
name old time/op new time/op delta
EndToEndPipe-8 2.25µs ± 1% 2.21µs ± 3% -1.79% (p=0.000 n=28+27)
EndToEndByteBuffer-8 93.3ns ± 5% 94.2ns ± 5% ~ (p=0.174 n=30+30)
EndToEndSliceByteBuffer-8 10.5µs ± 1% 10.6µs ± 1% +0.87% (p=0.000 n=30+30)
EncodeComplex128Slice-8 1.81µs ± 0% 1.75µs ± 1% -3.23% (p=0.000 n=28+30)
EncodeFloat64Slice-8 900ns ± 1% 847ns ± 0% -5.91% (p=0.000 n=29+28)
EncodeInt32Slice-8 1.02µs ± 0% 0.90µs ± 0% -11.82% (p=0.000 n=28+26)
EncodeStringSlice-8 1.16µs ± 1% 1.04µs ± 1% -10.20% (p=0.000 n=29+26)
EncodeInterfaceSlice-8 28.7µs ± 3% 29.2µs ± 6% ~ (p=0.067 n=29+30)
DecodeComplex128Slice-8 7.98µs ± 1% 7.96µs ± 1% -0.27% (p=0.017 n=30+30)
DecodeFloat64Slice-8 4.33µs ± 1% 4.34µs ± 1% +0.24% (p=0.022 n=30+29)
DecodeInt32Slice-8 4.18µs ± 1% 4.18µs ± 0% ~ (p=0.074 n=30+28)
DecodeStringSlice-8 13.2µs ± 1% 13.1µs ± 1% -0.64% (p=0.000 n=28+28)
DecodeStringsSlice-8 31.9µs ± 1% 31.8µs ± 1% -0.34% (p=0.001 n=30+30)
DecodeBytesSlice-8 8.88µs ± 1% 8.84µs ± 1% -0.48% (p=0.000 n=30+30)
DecodeInterfaceSlice-8 64.1µs ± 1% 64.2µs ± 1% ~ (p=0.173 n=30+28)
DecodeMap-8 74.3µs ± 0% 74.2µs ± 0% ~ (p=0.131 n=29+30)
Fixes #42958
Change-Id: Ie048b8976fb403d8bcc72ac6bde4b33e133e2a47
Reviewed-on: https://go-review.googlesource.com/c/go/+/349931
Trust: Josh Bleecher Snyder <josharian@gmail.com>
Run-TryBot: Josh Bleecher Snyder <josharian@gmail.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
2021-09-13 15:28:55 -07:00
cheap = true
}
}
2021-06-25 22:24:29 +07:00
}
}
}
2024-05-10 06:06:47 +00:00
2024-08-28 10:34:54 -04:00
// A call to a parameter is optimistically a cheap call, if it's a constant function
// perhaps it will inline, it also can simplify escape analysis.
extraCost := v . extraCallCost
2024-05-10 06:06:47 +00:00
if n . Fun . Op ( ) == ir . ONAME {
name := n . Fun . ( * ir . Name )
if name . Class == ir . PFUNC {
// Special case: on architectures that can do unaligned loads,
// explicitly mark internal/byteorder methods as cheap,
// because in practice they are, even though our inlining
// budgeting system does not see that. See issue 42958.
if base . Ctxt . Arch . CanMergeLoads && name . Sym ( ) . Pkg . Path == "internal/byteorder" {
switch name . Sym ( ) . Name {
2024-11-12 23:39:27 +01:00
case "LEUint64" , "LEUint32" , "LEUint16" ,
"BEUint64" , "BEUint32" , "BEUint16" ,
"LEPutUint64" , "LEPutUint32" , "LEPutUint16" ,
"BEPutUint64" , "BEPutUint32" , "BEPutUint16" ,
"LEAppendUint64" , "LEAppendUint32" , "LEAppendUint16" ,
"BEAppendUint64" , "BEAppendUint32" , "BEAppendUint16" :
2024-05-10 06:06:47 +00:00
cheap = true
}
}
}
2024-10-14 13:28:28 -04:00
if name . Class == ir . PPARAM || name . Class == ir . PAUTOHEAP && name . IsClosureVar ( ) {
2024-08-28 10:34:54 -04:00
extraCost = min ( extraCost , inlineParamCallCost )
}
2024-05-10 06:06:47 +00:00
}
2022-06-17 13:06:16 -04:00
if cheap {
break // treat like any other node, that is, cost of 1
}
2017-04-19 12:57:52 -04:00
[dev.regabi] cmd/compile: move helpers into package ir [generated]
[git-generate]
cd src/cmd/compile/internal/gc
sed -i '' 's/TestBuiltin.*/& t.Skip("mkbuiltin needs fixing")/' builtin_test.go
gofmt -w builtin_test.go
rf '
# Inline a few little-used constructors to avoid bringing them.
ex {
import "cmd/compile/internal/base"
import "cmd/compile/internal/ir"
import "cmd/compile/internal/types"
import "cmd/internal/src"
var typ *types.Type
var sym *types.Sym
var str string
symfield(sym, typ) -> ir.NewField(base.Pos, sym, nil, typ)
anonfield(typ) -> ir.NewField(base.Pos, nil, nil, typ)
namedfield(str, typ) -> ir.NewField(base.Pos, lookup(str), nil, typ)
var cp *ir.CallPartExpr
callpartMethod(cp) -> cp.Method
var n ir.Node
callpartMethod(n) -> n.(*ir.CallPartExpr).Method
var ns []ir.Node
liststmt(ns) -> ir.NewBlockStmt(src.NoXPos, ns)
}
rm symfield anonfield namedfield liststmt callpartMethod
mv maxStackVarSize MaxStackVarSize
mv maxImplicitStackVarSize MaxImplicitStackVarSize
mv smallArrayBytes MaxSmallArraySize
mv MaxStackVarSize cfg.go
mv nodbool NewBool
mv nodintconst NewInt
mv nodstr NewString
mv NewBool NewInt NewString const.go
mv Mpprec ConstPrec
mv bigFloatVal BigFloat
mv doesoverflow ConstOverflow
mv isGoConst IsConstNode
mv smallintconst IsSmallIntConst
mv isZero IsZero
mv islvalue IsAssignable
mv staticValue StaticValue
mv samesafeexpr SameSafeExpr
mv checkPtr ShouldCheckPtr
mv isReflectHeaderDataField IsReflectHeaderDataField
mv paramNnames ParamNames
mv methodSym MethodSym
mv methodSymSuffix MethodSymSuffix
mv methodExprFunc MethodExprFunc
mv methodExprName MethodExprName
mv IsZero IsAssignable StaticValue staticValue1 reassigned \
IsIntrinsicCall \
SameSafeExpr ShouldCheckPtr IsReflectHeaderDataField \
ParamNames MethodSym MethodSymSuffix \
MethodExprName MethodExprFunc \
expr.go
mv Curfn CurFunc
mv funcsymname FuncSymName
mv newFuncNameAt NewFuncNameAt
mv setNodeNameFunc MarkFunc
mv CurFunc FuncSymName NewFuncNameAt MarkFunc func.go
mv isParamStackCopy IsParamStackCopy
mv isParamHeapCopy IsParamHeapCopy
mv nodfp RegFP
mv IsParamStackCopy IsParamHeapCopy RegFP name.go
mv hasUniquePos HasUniquePos
mv setlineno SetPos
mv initExpr InitExpr
mv hasNamedResults HasNamedResults
mv outervalue OuterValue
mv HasNamedResults HasUniquePos SetPos InitExpr OuterValue EscNever node.go
mv visitBottomUp VisitFuncsBottomUp # scc.go
mv cfg.go \
NewBool NewInt NewString \ # parts of const.go
ConstPrec BigFloat ConstOverflow IsConstNode IsSmallIntConst \
expr.go func.go name.go node.go scc.go \
cmd/compile/internal/ir
'
Change-Id: I13402c5a2cedbf78d993a1eae2940718f23ac166
Reviewed-on: https://go-review.googlesource.com/c/go/+/279421
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-23 00:38:15 -05:00
if ir . IsIntrinsicCall ( n ) {
2020-02-14 11:42:58 -08:00
// Treat like any other node.
2019-04-15 21:27:04 -04:00
break
}
2024-11-19 17:18:38 -05:00
if callee := inlCallee ( v . curFunc , n . Fun , v . profile , false ) ; callee != nil && typecheck . HaveInlineBody ( callee ) {
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
// Check whether we'd actually inline this call. Set
// log == false since we aren't actually doing inlining
// yet.
2024-11-19 17:18:38 -05:00
if ok , _ , _ := canInlineCallExpr ( v . curFunc , n , callee , v . isBigFunc , false , false ) ; ok {
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
// mkinlcall would inline this call [1], so use
// the cost of the inline body as the cost of
// the call, as that is what will actually
// appear in the code.
//
// [1] This is almost a perfect match to the
// mkinlcall logic, except that
// canInlineCallExpr considers inlining cycles
// by looking at what has already been inlined.
// Since we haven't done any inlining yet we
// will miss those.
2024-11-19 17:18:38 -05:00
//
// TODO: in the case of a single-call closure, the inlining budget here is potentially much, much larger.
//
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
v . budget -= callee . Inl . Cost
2023-08-11 09:40:31 -04:00
break
}
2017-03-16 14:08:31 -07:00
}
2018-04-27 12:13:17 -04:00
// Call cost for non-leaf inlining.
2024-08-28 10:34:54 -04:00
v . budget -= extraCost
2015-02-24 12:19:01 -05:00
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . OCALLMETH :
2021-06-25 22:24:29 +07:00
base . FatalfAt ( n . Pos ( ) , "OCALLMETH missed by typecheck" )
2015-02-24 12:19:01 -05:00
// Things that are too hairy, irrespective of the budget
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . OCALL , ir . OCALLINTER :
2018-04-27 12:13:17 -04:00
// Call cost for non-leaf inlining.
v . budget -= v . extraCallCost
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . OPANIC :
[dev.regabi] cmd/compile: convert OPANIC argument to interface{} during typecheck
Currently, typecheck leaves arguments to OPANIC as their original
type. This CL changes it to insert implicit OCONVIFACE operations to
convert arguments to `interface{}` like how any other function call
would be handled.
No immediate benefits, other than getting to remove a tiny bit of
special-case logic in order.go's handling of OPANICs. Instead, the
generic code path for handling OCONVIFACE is used, if necessary.
Longer term, this should be marginally helpful for #43753, as it
reduces the number of cases where we need values to be addressable for
runtime calls.
However, this does require adding some hacks to appease existing
tests:
1. We need yet another kludge in inline budgeting, to ensure that
reflect.flag.mustBe stays inlinable for cmd/compile/internal/test's
TestIntendedInlining.
2. Since the OCONVIFACE expressions are now being introduced during
typecheck, they're now visible to escape analysis. So expressions like
"panic(1)" are now seen as "panic(interface{}(1))", and escape
analysis warns that the "interface{}(1)" escapes to the heap. These
have always escaped to heap, just now we're accurately reporting about
it.
(Also, unfortunately fmt.go hides implicit conversions by default in
diagnostics messages, so instead of reporting "interface{}(1) escapes
to heap", it actually reports "1 escapes to heap", which is
confusing. However, this confusing messaging also isn't new.)
Change-Id: Icedf60e1d2e464e219441b8d1233a313770272af
Reviewed-on: https://go-review.googlesource.com/c/go/+/284412
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Trust: Matthew Dempsky <mdempsky@google.com>
2021-01-17 16:14:48 -08:00
n := n . ( * ir . UnaryExpr )
if n . X . Op ( ) == ir . OCONVIFACE && n . X . ( * ir . ConvExpr ) . Implicit ( ) {
// Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
// Before CL 284412, these conversions were introduced later in the
// compiler, so they didn't count against inlining budget.
v . budget ++
}
2018-06-06 12:38:35 -04:00
v . budget -= inlineExtraPanicCost
2015-02-13 14:40:36 -05:00
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . ORECOVER :
2023-08-11 17:29:08 -07:00
base . FatalfAt ( n . Pos ( ) , "ORECOVER missed typecheck" )
case ir . ORECOVERFP :
2018-01-25 17:22:41 -05:00
// recover matches the argument frame pointer to find
// the right panic value, so it needs an argument frame.
2021-01-07 11:17:57 +08:00
v . reason = "call to recover"
return true
2018-01-25 17:22:41 -05:00
[dev.regabi] cmd/compile: exporting, importing, and inlining functions with OCLOSURE
I have exporting, importing, and inlining of functions with closures
working in all cases (issue #28727). all.bash runs successfully without
errors.
Approach:
- Write out the Func type, Dcls, ClosureVars, and Body when exporting
an OCLOSURE.
- When importing an OCLOSURE, read in the type, dcls, closure vars,
and body, and then do roughly equivalent code to (*noder).funcLit
- During inlining of a closure within inlined function, create new
nodes for all params and local variables (including closure
variables), so they can have a new Curfn and some other field
values. Must substitute not only on the Nbody of the closure, but
also the Type, Cvars, and Dcl fields.
Fixes #28727
Change-Id: I4da1e2567c3fa31a5121afbe82dc4e5ee32b3170
Reviewed-on: https://go-review.googlesource.com/c/go/+/283112
Run-TryBot: Dan Scales <danscales@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Trust: Dan Scales <danscales@google.com>
2020-12-01 14:48:03 -08:00
case ir . OCLOSURE :
2021-04-11 09:47:13 -07:00
if base . Debug . InlFuncsWithClosures == 0 {
2021-02-24 13:03:17 -08:00
v . reason = "not inlining functions with closures"
[dev.typeparams] all: merge dev.regabi (7e0a81d) into dev.typeparams
As with CL 285875, this required resolving some conflicts around
handling of //go:embed directives. Still further work is needed to
reject uses of //go:embed in files that don't import "embed", so this
is left as a TODO. (When this code was written for dev.typeparams, we
were still leaning towards not requiring the "embed" import.)
Also, the recent support for inlining closures (CL 283112) interacts
poorly with -G=3 mode. There are some known issues with this code
already (#43818), so for now this CL disables inlining of closures
when in -G=3 mode with a TODO to revisit this once closure inlining is
working fully.
Conflicts:
- src/cmd/compile/internal/noder/noder.go
- src/cmd/compile/internal/typecheck/dcl.go
- src/cmd/compile/internal/typecheck/func.go
- test/run.go
Merge List:
+ 2021-01-22 7e0a81d280 [dev.regabi] all: merge master (dab3e5a) into dev.regabi
+ 2021-01-22 dab3e5affe runtime: switch runtime to libc for openbsd/amd64
+ 2021-01-22 a1b53d85da cmd/go: add documentation for test and xtest fields output by go list
+ 2021-01-22 b268b60774 runtime: remove pthread_kill/pthread_self for openbsd
+ 2021-01-22 ec4051763d runtime: fix typo in mgcscavenge.go
+ 2021-01-22 7ece3a7b17 net/http: fix flaky TestDisableKeepAliveUpgrade
+ 2021-01-22 50cba0506f time: clarify Timer.Reset behavior on AfterFunc Timers
+ 2021-01-22 cf10e69f17 doc/go1.16: mention net/http.Transport.GetProxyConnectHeader
+ 2021-01-22 ec1b945265 doc/go1.16: mention path/filepath.WalkDir
+ 2021-01-22 11def3d40b doc/go1.16: mention syscall.AllThreadsSyscall
+ 2021-01-21 07b0235609 doc/go1.16: add notes about package-specific fs.FS changes
+ 2021-01-21 e2b4f1fea5 doc/go1.16: minor formatting fix
+ 2021-01-21 9f43a9e07b doc/go1.16: mention new debug/elf constants
+ 2021-01-21 3c2f11ba5b cmd/go: overwrite program name with full path
+ 2021-01-21 953d1feca9 all: introduce and use internal/execabs
+ 2021-01-21 b186e4d70d cmd/go: add test case for cgo CC setting
+ 2021-01-21 5a8a2265fb cmd/cgo: report exec errors a bit more clearly
+ 2021-01-21 46e2e2e9d9 cmd/go: pass resolved CC, GCCGO to cgo
+ 2021-01-21 3d40895e36 runtime: switch openbsd/arm64 to pthreads
+ 2021-01-21 d95ca91380 crypto/elliptic: fix P-224 field reduction
+ 2021-01-21 d7e71c01ad [dev.regabi] cmd/compile: replace ir.Name map with ir.NameSet for dwarf
+ 2021-01-21 5248f59a22 [dev.regabi] cmd/compile: replace ir.Name map with ir.NameSet for SSA
+ 2021-01-21 970d8b6cb2 [dev.regabi] cmd/compile: replace ir.Name map with ir.NameSet in inlining
+ 2021-01-21 68a4664475 [dev.regabi] cmd/compile: remove tempAssigns in walkCall1
+ 2021-01-21 fd9a391cdd [dev.regabi] cmd/compile: remove CallExpr.Rargs
+ 2021-01-21 19a6db6b63 [dev.regabi] cmd/compile: make sure mkcall* passed non-nil init
+ 2021-01-21 9f036844db [dev.regabi] cmd/compile: use ir.DoChildren directly in inlining
+ 2021-01-21 213c3905e9 [dev.regabi] cmd/compile: use node walked flag to prevent double walk for walkSelect
+ 2021-01-20 1760d736f6 [dev.regabi] cmd/compile: exporting, importing, and inlining functions with OCLOSURE
+ 2021-01-20 ecf4ebf100 cmd/internal/moddeps: check content of all modules in GOROOT
+ 2021-01-20 92cb157cf3 [dev.regabi] cmd/compile: late expansion of return values
+ 2021-01-20 d2d155d1ae runtime: don't adjust timer pp field in timerWaiting status
+ 2021-01-20 803d18fc6c cmd/go: set Incomplete field on go list output if no files match embed
+ 2021-01-20 6e243ce71d cmd/go: have go mod vendor copy embedded files in subdirs
+ 2021-01-20 be28e5abc5 cmd/go: fix mod_get_fallback test
+ 2021-01-20 928bda4f4a runtime: convert openbsd/amd64 locking to libc
+ 2021-01-19 824f2d635c cmd/go: allow go fmt to complete when embedded file is missing
+ 2021-01-19 0575e35e50 cmd/compile: require 'go 1.16' go.mod line for //go:embed
+ 2021-01-19 9423d50d53 [dev.regabi] cmd/compile: use '%q' for printing rune values less than 128
+ 2021-01-19 ccb2e90688 cmd/link: exit before Asmb2 if error
+ 2021-01-19 ca5774a5a5 embed: treat uninitialized FS as empty
+ 2021-01-19 d047c91a6c cmd/link,runtime: switch openbsd/amd64 to pthreads
+ 2021-01-19 61debffd97 runtime: factor out usesLibcall
+ 2021-01-19 9fed39d281 runtime: factor out mStackIsSystemAllocated
+ 2021-01-19 a2f825c542 [dev.regabi] cmd/compile: directly create go.map and go.track symbols
+ 2021-01-19 4a4212c0e5 [dev.regabi] cmd/compile: refactor Linksym creation
+ 2021-01-19 4f5c603c0f [dev.regabi] cmd/compile: cleanup callTargetLSym
+ 2021-01-18 dbab079835 runtime: free Windows event handles after last lock is dropped
+ 2021-01-18 5a8fbb0d2d os: do not close syscall.Stdin in TestReadStdin
+ 2021-01-18 422f38fb6c [dev.regabi] cmd/compile: move stack objects to liveness
+ 2021-01-18 6113db0bb4 [dev.regabi] cmd/compile: convert OPANIC argument to interface{} during typecheck
+ 2021-01-18 4c835f9169 [dev.regabi] cmd/compile: use LinksymOffsetExpr in TypePtr/ItabAddr
+ 2021-01-18 0ffa1ead6e [dev.regabi] cmd/compile: use *obj.LSym instead of *ir.Name for staticdata functions
+ 2021-01-17 7e0fa38aad [dev.regabi] cmd/compile: remove unneeded packages from ir.Pkgs
+ 2021-01-17 99a5db11ac [dev.regabi] cmd/compile: use LinksymOffsetExpr in walkConvInterface
+ 2021-01-17 87845d14f9 [dev.regabi] cmd/compile: add ir.TailCallStmt
+ 2021-01-17 e3027c6828 [dev.regabi] cmd/compile: fix linux-amd64-noopt builder
+ 2021-01-17 59ff93fe64 [dev.regabi] cmd/compile: rename NameOffsetExpr to LinksymOffsetExpr
+ 2021-01-17 82b9cae700 [dev.regabi] cmd/compile: change ir.NameOffsetExpr to use *obj.LSym instead of *Name
+ 2021-01-17 88956fc4b1 [dev.regabi] cmd/compile: stop analyze NameOffsetExpr.Name_ in escape analysis
+ 2021-01-17 7ce2a8383d [dev.regabi] cmd/compile: simplify stack temp initialization
+ 2021-01-17 ba0e8a92fa [dev.regabi] cmd/compile: refactor temp construction in walk
+ 2021-01-17 78e5aabcdb [dev.regabi] cmd/compile: replace Node.HasCall with walk.mayCall
+ 2021-01-16 6de9423445 [dev.regabi] cmd/compile: cleanup OAS2FUNC ordering
+ 2021-01-16 a956a0e909 [dev.regabi] cmd/compile, runtime: fix up comments/error messages from recent renames
+ 2021-01-16 ab3b67abfd [dev.regabi] cmd/compile: remove ONEWOBJ
+ 2021-01-16 c9b1445ac8 [dev.regabi] cmd/compile: remove TypeAssertExpr {Src,Dst}Type fields
+ 2021-01-15 682a1d2176 runtime: detect errors in DuplicateHandle
+ 2021-01-15 9f83418b83 cmd/link: remove GOROOT write in TestBuildForTvOS
+ 2021-01-15 ec9470162f cmd/compile: allow embed into any string or byte slice type
+ 2021-01-15 54198b04db cmd/compile: disallow embed of var inside func
+ 2021-01-15 b386c735e7 cmd/go: fix go generate docs
+ 2021-01-15 bb5075a525 syscall: remove RtlGenRandom and move it into internal/syscall
+ 2021-01-15 1deae0b597 os: invoke processKiller synchronously in testKillProcess
+ 2021-01-15 03a875137f [dev.regabi] cmd/compile: unexport reflectdata.WriteType
+ 2021-01-15 14537e6e54 [dev.regabi] cmd/compile: move stkobj symbol generation to SSA
+ 2021-01-15 ab523fc510 [dev.regabi] cmd/compile: don't promote Byval CaptureVars if Addrtaken
+ 2021-01-15 ff196c3e84 crypto/x509: update iOS bundled roots to version 55188.40.9
+ 2021-01-15 b7a698c73f [dev.regabi] test: disable test on windows because expected contains path separators.
+ 2021-01-15 4be7af23f9 [dev.regabi] cmd/compile: fix ICE during ir.Dump
+ 2021-01-14 e125ccd10e cmd/go: in 'go mod edit', validate versions given to -retract and -exclude
+ 2021-01-14 eb330020dc cmd/dist, cmd/go: pass -arch for C compilation on Darwin
+ 2021-01-14 84e8a06f62 cmd/cgo: remove unnecessary space in cgo export header
+ 2021-01-14 0c86b999c3 cmd/test2json: document passing -test.paniconexit0
+ 2021-01-14 9135795891 cmd/go/internal/load: report positions for embed errors
+ 2021-01-14 35b9c66601 [dev.regabi] cmd/compile,cmd/link: additional code review suggestions for CL 270863
+ 2021-01-14 d9b79e53bb cmd/compile: fix wrong complement for arm64 floating-point comparisons
+ 2021-01-14 c73232d08f cmd/go/internal/load: refactor setErrorPos to PackageError.setPos
+ 2021-01-14 6aa28d3e06 go/build: report positions for go:embed directives
+ 2021-01-14 9734fd482d [dev.regabi] cmd/compile: use node walked flag to prevent double walk for walkSwitch
+ 2021-01-14 f97983249a [dev.regabi] cmd/compile: move more PAUTOHEAP to SSA construction
+ 2021-01-14 4476300425 [dev.regabi] cmd/compile: use byte for CallExpr.Use
+ 2021-01-14 5a5ab24689 [dev.regabi] cmd/compile: do not rely on CallExpr.Rargs for detect already walked calls
+ 2021-01-14 983ac4b086 [dev.regabi] cmd/compile: fix ICE when initializing blank vars
+ 2021-01-13 7eb31d999c cmd/go: add hints to more missing sum error messages
+ 2021-01-13 d6d4673728 [dev.regabi] cmd/compile: fix GOEXPERIMENT=regabi builder
+ 2021-01-13 c41b999ad4 [dev.regabi] cmd/compile: refactor abiutils from "gc" into new "abi"
+ 2021-01-13 861707a8c8 [dev.regabi] cmd/compile: added limited //go:registerparams pragma for new ABI dev
+ 2021-01-13 c1370e918f [dev.regabi] cmd/compile: add code to support register ABI spills around morestack calls
+ 2021-01-13 2abd24f3b7 [dev.regabi] test: make run.go error messages slightly more informative
+ 2021-01-13 9a19481acb [dev.regabi] cmd/compile: make ordering for InvertFlags more stable
+ 2021-01-12 ba76567bc2 cmd/go/internal/modload: delete unused *mvsReqs.next method
+ 2021-01-12 665def2c11 encoding/asn1: document unmarshaling behavior for IMPLICIT string fields
+ 2021-01-11 81ea89adf3 cmd/go: fix non-script staleness checks interacting badly with GOFLAGS
+ 2021-01-11 759309029f doc: update editors.html for Go 1.16
+ 2021-01-11 c3b4c7093a cmd/internal/objfile: don't require runtime.symtab symbol for XCOFF
+ 2021-01-08 59bfc18e34 cmd/go: add hint to read 'go help vcs' to GOVCS errors
+ 2021-01-08 cd6f3a54e4 cmd/go: revise 'go help' documentation for modules
+ 2021-01-08 6192b98751 cmd/go: make hints in error messages more consistent
+ 2021-01-08 25886cf4bd cmd/go: preserve sums for indirect deps fetched by 'go mod download'
+ 2021-01-08 6250833911 runtime/metrics: mark histogram metrics as cumulative
+ 2021-01-08 8f6a9acbb3 runtime/metrics: remove unused StopTheWorld Description field
+ 2021-01-08 6598c65646 cmd/compile: fix exponential-time init-cycle reporting
+ 2021-01-08 fefad1dc85 test: fix timeout code for invoking compiler
+ 2021-01-08 6728118e0a cmd/go: pass signals forward during "go tool"
+ 2021-01-08 e65c543f3c go/build/constraint: add parser for build tag constraint expressions
+ 2021-01-08 0c5afc4fb7 testing/fstest,os: clarify racy behavior of TestFS
+ 2021-01-08 32afcc9436 runtime/metrics: change unit on *-by-size metrics to match bucket unit
+ 2021-01-08 c6513bca5a io/fs: minor corrections to Glob doc
+ 2021-01-08 304f769ffc cmd/compile: don't short-circuit copies whose source is volatile
+ 2021-01-08 ae97717133 runtime,runtime/metrics: use explicit histogram boundaries
+ 2021-01-08 a9ccd2d795 go/build: skip string literal while findEmbed
+ 2021-01-08 d92f8add32 archive/tar: fix typo in comment
+ 2021-01-08 cab1202183 cmd/link: accept extra blocks in TestFallocate
+ 2021-01-08 ee4d32249b io/fs: minor corrections to Glob release date
+ 2021-01-08 54bd1ccce2 cmd: update to latest golang.org/x/tools
+ 2021-01-07 9ec21a8f34 Revert "reflect: support multiple keys in struct tags"
+ 2021-01-07 091414b5b7 io/fs: correct WalkDirFunc documentation
+ 2021-01-07 9b55088d6b doc/go1.16: add release note for disallowing non-ASCII import paths
+ 2021-01-07 fa90aaca7d cmd/compile: fix late expand_calls leaf type for OpStructSelect/OpArraySelect
+ 2021-01-07 7cee66d4cb cmd/go: add documentation for Embed fields in go list output
+ 2021-01-07 e60cffa4ca html/template: attach functions to namespace
+ 2021-01-07 6da2d3b7d7 cmd/link: fix typo in asm.go
+ 2021-01-07 df81a15819 runtime: check mips64 VDSO clock_gettime return code
+ 2021-01-06 4787e906cf crypto/x509: rollback new CertificateRequest fields
+ 2021-01-06 c9658bee93 cmd/go: make module suggestion more friendly
+ 2021-01-06 4c668b25c6 runtime/metrics: fix panic message for Float64Histogram
+ 2021-01-06 d2131704a6 net/http/httputil: fix deadlock in DumpRequestOut
+ 2021-01-05 3e1e13ce6d cmd/go: set cfg.BuildMod to "readonly" by default with no module root
+ 2021-01-05 0b0d004983 cmd/go: pass embedcfg to gccgo if supported
+ 2021-01-05 1b85e7c057 cmd/go: don't scan gccgo standard library packages for imports
+ 2021-01-05 6b37b15d95 runtime: don't take allglock in tracebackothers
+ 2021-01-04 9eef49cfa6 math/rand: fix typo in comment
+ 2021-01-04 b01fb2af9e testing/fstest: fix typo in error message
+ 2021-01-01 3dd5867605 doc: 2021 is the Year of the Gopher
+ 2020-12-31 95ce805d14 io/fs: remove darwin/arm64 special condition
+ 2020-12-30 20d0991b86 lib/time, time/tzdata: update tzdata to 2020f
+ 2020-12-30 ed301733bb misc/cgo/testcarchive: remove special flags for Darwin/ARM
+ 2020-12-30 0ae2e032f2 misc/cgo/test: enable TestCrossPackageTests on darwin/arm64
+ 2020-12-29 780b4de16b misc/ios: fix wording for command line instructions
+ 2020-12-29 b4a71c95d2 doc/go1.16: reference misc/ios/README for how to build iOS programs
+ 2020-12-29 f83e0f6616 misc/ios: add to README how to build ios executables
+ 2020-12-28 4fd9455882 io/fs: fix typo in comment
Change-Id: If24bb93f1e1e7deb1d92ba223c85940ab93b2732
2021-01-22 15:35:11 -08:00
return true
}
2018-01-25 17:22:41 -05:00
2021-02-24 13:03:17 -08:00
// TODO(danscales): Maybe make budget proportional to number of closure
// variables, e.g.:
[dev.regabi] cmd/compile: exporting, importing, and inlining functions with OCLOSURE
I have exporting, importing, and inlining of functions with closures
working in all cases (issue #28727). all.bash runs successfully without
errors.
Approach:
- Write out the Func type, Dcls, ClosureVars, and Body when exporting
an OCLOSURE.
- When importing an OCLOSURE, read in the type, dcls, closure vars,
and body, and then do roughly equivalent code to (*noder).funcLit
- During inlining of a closure within inlined function, create new
nodes for all params and local variables (including closure
variables), so they can have a new Curfn and some other field
values. Must substitute not only on the Nbody of the closure, but
also the Type, Cvars, and Dcl fields.
Fixes #28727
Change-Id: I4da1e2567c3fa31a5121afbe82dc4e5ee32b3170
Reviewed-on: https://go-review.googlesource.com/c/go/+/283112
Run-TryBot: Dan Scales <danscales@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Trust: Dan Scales <danscales@google.com>
2020-12-01 14:48:03 -08:00
//v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
cmd/compile: allow more inlining of functions that construct closures
[This is a roll-forward of CL 479095, which was reverted due to a bad
interaction between inlining and escape analysis, then later fixed
first with an attempt in CL 482355, then again in CL 484859, and then
one more time with CL 492135.]
Currently, when the inliner is determining if a function is
inlineable, it descends into the bodies of closures constructed by
that function. This has several unfortunate consequences:
- If the closure contains a disallowed operation (e.g., a defer), then
the outer function can't be inlined. It makes sense that the
*closure* can't be inlined in this case, but it doesn't make sense
to punish the function that constructs the closure.
- The hairiness of the closure counts against the inlining budget of
the outer function. Since we currently copy the closure body when
inlining the outer function, this makes sense from the perspective
of export data size and binary size, but ultimately doesn't make
much sense from the perspective of what should be inlineable.
- Since the inliner walks into every closure created by an outer
function in addition to starting a walk at every closure, this adds
an n^2 factor to inlinability analysis.
This CL simply drops this behavior.
In std, this makes 57 more functions inlinable, and disallows inlining
for 10 (due to the basic instability of our bottom-up inlining
approach), for an net increase of 47 inlinable functions (+0.6%).
This will help significantly with the performance of the functions to
be added for #56102, which have a somewhat complicated nesting of
closures with a performance-critical fast path.
The downside of this seems to be a potential increase in export data
and text size, but the practical impact of this seems to be
negligible:
│ before │ after │
│ bytes │ bytes vs base │
Go/binary 15.12Mi ± 0% 15.14Mi ± 0% +0.16% (n=1)
Go/text 5.220Mi ± 0% 5.237Mi ± 0% +0.32% (n=1)
Compile/binary 22.92Mi ± 0% 22.94Mi ± 0% +0.07% (n=1)
Compile/text 8.428Mi ± 0% 8.435Mi ± 0% +0.08% (n=1)
Change-Id: I5f75fcceb177f05853996b75184a486528eafe96
Reviewed-on: https://go-review.googlesource.com/c/go/+/492017
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Than McIntosh <thanm@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
2023-04-04 18:31:46 -04:00
// TODO(austin): However, if we're able to inline this closure into
// v.curFunc, then we actually pay nothing for the closure captures. We
// should try to account for that if we're going to account for captures.
2021-01-22 14:32:06 -08:00
v . budget -= 15
[dev.regabi] cmd/compile: exporting, importing, and inlining functions with OCLOSURE
I have exporting, importing, and inlining of functions with closures
working in all cases (issue #28727). all.bash runs successfully without
errors.
Approach:
- Write out the Func type, Dcls, ClosureVars, and Body when exporting
an OCLOSURE.
- When importing an OCLOSURE, read in the type, dcls, closure vars,
and body, and then do roughly equivalent code to (*noder).funcLit
- During inlining of a closure within inlined function, create new
nodes for all params and local variables (including closure
variables), so they can have a new Curfn and some other field
values. Must substitute not only on the Nbody of the closure, but
also the Type, Cvars, and Dcl fields.
Fixes #28727
Change-Id: I4da1e2567c3fa31a5121afbe82dc4e5ee32b3170
Reviewed-on: https://go-review.googlesource.com/c/go/+/283112
Run-TryBot: Dan Scales <danscales@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Trust: Dan Scales <danscales@google.com>
2020-12-01 14:48:03 -08:00
2023-08-16 17:29:41 -07:00
case ir . OGO , ir . ODEFER , ir . OTAILCALL :
2021-01-07 11:17:57 +08:00
v . reason = "unhandled op " + n . Op ( ) . String ( )
return true
2017-09-03 23:53:38 +10:00
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . OAPPEND :
2018-04-27 12:13:17 -04:00
v . budget -= inlineExtraAppendCost
2022-09-15 23:04:53 +07:00
case ir . OADDR :
n := n . ( * ir . AddrExpr )
// Make "&s.f" cost 0 when f's offset is zero.
if dot , ok := n . X . ( * ir . SelectorExpr ) ; ok && ( dot . Op ( ) == ir . ODOT || dot . Op ( ) == ir . ODOTPTR ) {
if _ , ok := dot . X . ( * ir . Name ) ; ok && dot . Selection . Offset == 0 {
v . budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
}
}
2021-01-02 16:28:11 +02:00
case ir . ODEREF :
// *(*X)(unsafe.Pointer(&x)) is low-cost
n := n . ( * ir . StarExpr )
ptr := n . X
for ptr . Op ( ) == ir . OCONVNOP {
ptr = ptr . ( * ir . ConvExpr ) . X
}
if ptr . Op ( ) == ir . OADDR {
v . budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
}
case ir . OCONVNOP :
// This doesn't produce code, but the children might.
v . budget ++ // undo default cost
2023-08-16 17:29:41 -07:00
case ir . OFALL , ir . OTYPE :
2017-09-03 23:53:38 +10:00
// These nodes don't produce code; omit from inlining budget.
2021-01-07 11:17:57 +08:00
return false
2018-02-22 19:58:59 -05:00
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . OIF :
[dev.regabi] cmd/compile: remove Node.Left etc [generated]
This automated CL adds type assertions on the true branches of
n.Op() equality tests, to redeclare n with a more specific type, when
it is safe to do so. (That is, when n is not reassigned with a more
general type, when n is not reassigned and then used outside the
scope, and so on.) All the "unsafe" times that the automated tool
would avoid have been removed or rewritten in earlier CLs, so that
after this CL and the next one, which removes the use of ir.Nod,
every use of the Left, Right, and so on methods is done using concrete
types, never the Node interface.
Having done that, the CL locks in the progress by deleting many of
the access methods, including Left, SetLeft and so on, from the
Node interface.
There are still uses of Name, Func, Sym, some of the tracking
bits, and a few other miscellaneous fields, but all the main access
methods are gone from the Node interface. The others will be cleaned
up in smaller CLs.
Passes buildall w/ toolstash -cmp.
[git-generate]
cd src/cmd/compile/internal/gc
rf 'typeassert {
import "cmd/compile/internal/ir"
var n ir.Node
n.Op() == ir.OADD -> n.(*ir.BinaryExpr)
n.Op() == ir.OADDR -> n.(*ir.AddrExpr)
n.Op() == ir.OADDSTR -> n.(*ir.AddStringExpr)
n.Op() == ir.OALIGNOF -> n.(*ir.UnaryExpr)
n.Op() == ir.OAND -> n.(*ir.BinaryExpr)
n.Op() == ir.OANDAND -> n.(*ir.LogicalExpr)
n.Op() == ir.OANDNOT -> n.(*ir.BinaryExpr)
n.Op() == ir.OAPPEND -> n.(*ir.CallExpr)
n.Op() == ir.OARRAYLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OAS -> n.(*ir.AssignStmt)
n.Op() == ir.OAS2 -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2DOTTYPE -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2FUNC -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2MAPR -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2RECV -> n.(*ir.AssignListStmt)
n.Op() == ir.OASOP -> n.(*ir.AssignOpStmt)
n.Op() == ir.OBITNOT -> n.(*ir.UnaryExpr)
n.Op() == ir.OBLOCK -> n.(*ir.BlockStmt)
n.Op() == ir.OBREAK -> n.(*ir.BranchStmt)
n.Op() == ir.OBYTES2STR -> n.(*ir.ConvExpr)
n.Op() == ir.OBYTES2STRTMP -> n.(*ir.ConvExpr)
n.Op() == ir.OCALL -> n.(*ir.CallExpr)
n.Op() == ir.OCALLFUNC -> n.(*ir.CallExpr)
n.Op() == ir.OCALLINTER -> n.(*ir.CallExpr)
n.Op() == ir.OCALLMETH -> n.(*ir.CallExpr)
n.Op() == ir.OCALLPART -> n.(*ir.CallPartExpr)
n.Op() == ir.OCAP -> n.(*ir.UnaryExpr)
n.Op() == ir.OCASE -> n.(*ir.CaseStmt)
n.Op() == ir.OCFUNC -> n.(*ir.UnaryExpr)
n.Op() == ir.OCHECKNIL -> n.(*ir.UnaryExpr)
n.Op() == ir.OCLOSE -> n.(*ir.UnaryExpr)
n.Op() == ir.OCOMPLEX -> n.(*ir.BinaryExpr)
n.Op() == ir.OCOMPLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OCONTINUE -> n.(*ir.BranchStmt)
n.Op() == ir.OCONV -> n.(*ir.ConvExpr)
n.Op() == ir.OCONVIFACE -> n.(*ir.ConvExpr)
n.Op() == ir.OCONVNOP -> n.(*ir.ConvExpr)
n.Op() == ir.OCOPY -> n.(*ir.BinaryExpr)
n.Op() == ir.ODCL -> n.(*ir.Decl)
n.Op() == ir.ODCLCONST -> n.(*ir.Decl)
n.Op() == ir.ODCLFUNC -> n.(*ir.Func)
n.Op() == ir.ODCLTYPE -> n.(*ir.Decl)
n.Op() == ir.ODEFER -> n.(*ir.GoDeferStmt)
n.Op() == ir.ODELETE -> n.(*ir.CallExpr)
n.Op() == ir.ODEREF -> n.(*ir.StarExpr)
n.Op() == ir.ODIV -> n.(*ir.BinaryExpr)
n.Op() == ir.ODOT -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTINTER -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTMETH -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTPTR -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTTYPE -> n.(*ir.TypeAssertExpr)
n.Op() == ir.ODOTTYPE2 -> n.(*ir.TypeAssertExpr)
n.Op() == ir.OEFACE -> n.(*ir.BinaryExpr)
n.Op() == ir.OEQ -> n.(*ir.BinaryExpr)
n.Op() == ir.OFALL -> n.(*ir.BranchStmt)
n.Op() == ir.OFOR -> n.(*ir.ForStmt)
n.Op() == ir.OFORUNTIL -> n.(*ir.ForStmt)
n.Op() == ir.OGE -> n.(*ir.BinaryExpr)
n.Op() == ir.OGETG -> n.(*ir.CallExpr)
n.Op() == ir.OGO -> n.(*ir.GoDeferStmt)
n.Op() == ir.OGOTO -> n.(*ir.BranchStmt)
n.Op() == ir.OGT -> n.(*ir.BinaryExpr)
n.Op() == ir.OIDATA -> n.(*ir.UnaryExpr)
n.Op() == ir.OIF -> n.(*ir.IfStmt)
n.Op() == ir.OIMAG -> n.(*ir.UnaryExpr)
n.Op() == ir.OINDEX -> n.(*ir.IndexExpr)
n.Op() == ir.OINDEXMAP -> n.(*ir.IndexExpr)
n.Op() == ir.OINLCALL -> n.(*ir.InlinedCallExpr)
n.Op() == ir.OINLMARK -> n.(*ir.InlineMarkStmt)
n.Op() == ir.OITAB -> n.(*ir.UnaryExpr)
n.Op() == ir.OKEY -> n.(*ir.KeyExpr)
n.Op() == ir.OLABEL -> n.(*ir.LabelStmt)
n.Op() == ir.OLE -> n.(*ir.BinaryExpr)
n.Op() == ir.OLEN -> n.(*ir.UnaryExpr)
n.Op() == ir.OLSH -> n.(*ir.BinaryExpr)
n.Op() == ir.OLT -> n.(*ir.BinaryExpr)
n.Op() == ir.OMAKE -> n.(*ir.CallExpr)
n.Op() == ir.OMAKECHAN -> n.(*ir.MakeExpr)
n.Op() == ir.OMAKEMAP -> n.(*ir.MakeExpr)
n.Op() == ir.OMAKESLICE -> n.(*ir.MakeExpr)
n.Op() == ir.OMAKESLICECOPY -> n.(*ir.MakeExpr)
n.Op() == ir.OMAPLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OMETHEXPR -> n.(*ir.MethodExpr)
n.Op() == ir.OMOD -> n.(*ir.BinaryExpr)
n.Op() == ir.OMUL -> n.(*ir.BinaryExpr)
n.Op() == ir.ONAME -> n.(*ir.Name)
n.Op() == ir.ONE -> n.(*ir.BinaryExpr)
n.Op() == ir.ONEG -> n.(*ir.UnaryExpr)
n.Op() == ir.ONEW -> n.(*ir.UnaryExpr)
n.Op() == ir.ONEWOBJ -> n.(*ir.UnaryExpr)
n.Op() == ir.ONIL -> n.(*ir.NilExpr)
n.Op() == ir.ONOT -> n.(*ir.UnaryExpr)
n.Op() == ir.OOFFSETOF -> n.(*ir.UnaryExpr)
n.Op() == ir.OOR -> n.(*ir.BinaryExpr)
n.Op() == ir.OOROR -> n.(*ir.LogicalExpr)
n.Op() == ir.OPACK -> n.(*ir.PkgName)
n.Op() == ir.OPANIC -> n.(*ir.UnaryExpr)
n.Op() == ir.OPAREN -> n.(*ir.ParenExpr)
n.Op() == ir.OPLUS -> n.(*ir.UnaryExpr)
n.Op() == ir.OPRINT -> n.(*ir.CallExpr)
n.Op() == ir.OPRINTN -> n.(*ir.CallExpr)
n.Op() == ir.OPTRLIT -> n.(*ir.AddrExpr)
n.Op() == ir.ORANGE -> n.(*ir.RangeStmt)
n.Op() == ir.OREAL -> n.(*ir.UnaryExpr)
n.Op() == ir.ORECOVER -> n.(*ir.CallExpr)
n.Op() == ir.ORECV -> n.(*ir.UnaryExpr)
n.Op() == ir.ORESULT -> n.(*ir.ResultExpr)
n.Op() == ir.ORETJMP -> n.(*ir.BranchStmt)
n.Op() == ir.ORETURN -> n.(*ir.ReturnStmt)
n.Op() == ir.ORSH -> n.(*ir.BinaryExpr)
n.Op() == ir.ORUNES2STR -> n.(*ir.ConvExpr)
n.Op() == ir.ORUNESTR -> n.(*ir.ConvExpr)
n.Op() == ir.OSELECT -> n.(*ir.SelectStmt)
n.Op() == ir.OSELRECV2 -> n.(*ir.AssignListStmt)
n.Op() == ir.OSEND -> n.(*ir.SendStmt)
n.Op() == ir.OSIZEOF -> n.(*ir.UnaryExpr)
n.Op() == ir.OSLICE -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICE3 -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICE3ARR -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICEARR -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICEHEADER -> n.(*ir.SliceHeaderExpr)
n.Op() == ir.OSLICELIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OSLICESTR -> n.(*ir.SliceExpr)
n.Op() == ir.OSPTR -> n.(*ir.UnaryExpr)
n.Op() == ir.OSTR2BYTES -> n.(*ir.ConvExpr)
n.Op() == ir.OSTR2BYTESTMP -> n.(*ir.ConvExpr)
n.Op() == ir.OSTR2RUNES -> n.(*ir.ConvExpr)
n.Op() == ir.OSTRUCTLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OSUB -> n.(*ir.BinaryExpr)
n.Op() == ir.OSWITCH -> n.(*ir.SwitchStmt)
n.Op() == ir.OTYPESW -> n.(*ir.TypeSwitchGuard)
n.Op() == ir.OVARDEF -> n.(*ir.UnaryExpr)
n.Op() == ir.OVARKILL -> n.(*ir.UnaryExpr)
n.Op() == ir.OVARLIVE -> n.(*ir.UnaryExpr)
n.Op() == ir.OXDOT -> n.(*ir.SelectorExpr)
n.Op() == ir.OXOR -> n.(*ir.BinaryExpr)
}
'
cd ../ir
rf '
rm \
Node.SetOp \
miniNode.SetOp \
Node.Func \
miniNode.Func \
Node.Left Node.SetLeft \
miniNode.Left miniNode.SetLeft \
Node.Right Node.SetRight \
miniNode.Right miniNode.SetRight \
Node.List Node.PtrList Node.SetList \
miniNode.List miniNode.PtrList miniNode.SetList \
Node.Rlist Node.PtrRlist Node.SetRlist \
miniNode.Rlist miniNode.PtrRlist miniNode.SetRlist \
Node.Body Node.PtrBody Node.SetBody \
miniNode.Body miniNode.PtrBody miniNode.SetBody \
Node.SubOp Node.SetSubOp \
miniNode.SubOp miniNode.SetSubOp \
Node.SetSym \
miniNode.SetSym \
Node.Offset Node.SetOffset \
miniNode.Offset miniNode.SetOffset \
Node.Class Node.SetClass \
miniNode.Class miniNode.SetClass \
Node.Iota Node.SetIota \
miniNode.Iota miniNode.SetIota \
Node.Colas Node.SetColas \
miniNode.Colas miniNode.SetColas \
Node.Transient Node.SetTransient \
miniNode.Transient miniNode.SetTransient \
Node.Implicit Node.SetImplicit \
miniNode.Implicit miniNode.SetImplicit \
Node.IsDDD Node.SetIsDDD \
miniNode.IsDDD miniNode.SetIsDDD \
Node.MarkReadonly \
miniNode.MarkReadonly \
Node.Likely Node.SetLikely \
miniNode.Likely miniNode.SetLikely \
Node.SliceBounds Node.SetSliceBounds \
miniNode.SliceBounds miniNode.SetSliceBounds \
Node.NoInline Node.SetNoInline \
miniNode.NoInline miniNode.SetNoInline \
Node.IndexMapLValue Node.SetIndexMapLValue \
miniNode.IndexMapLValue miniNode.SetIndexMapLValue \
Node.ResetAux \
miniNode.ResetAux \
Node.HasBreak Node.SetHasBreak \
miniNode.HasBreak miniNode.SetHasBreak \
Node.Bounded Node.SetBounded \
miniNode.Bounded miniNode.SetBounded \
miniNode.Embedded miniNode.SetEmbedded \
miniNode.Int64Val miniNode.Uint64Val miniNode.CanInt64 \
miniNode.BoolVal miniNode.StringVal \
miniNode.TChanDir miniNode.SetTChanDir \
miniNode.Format \
miniNode.copy miniNode.doChildren miniNode.editChildren \
'
Change-Id: I2a05b535963b43f83b1849fcf653f82b99af6035
Reviewed-on: https://go-review.googlesource.com/c/go/+/277934
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-22 23:56:32 -05:00
n := n . ( * ir . IfStmt )
2020-12-23 00:02:08 -05:00
if ir . IsConst ( n . Cond , constant . Bool ) {
2018-02-22 19:58:59 -05:00
// This if and the condition cost nothing.
2021-09-07 00:38:40 -07:00
if doList ( n . Init ( ) , v . do ) {
return true
}
if ir . BoolVal ( n . Cond ) {
return doList ( n . Body , v . do )
} else {
return doList ( n . Else , v . do )
}
2018-02-22 19:58:59 -05:00
}
2018-05-23 15:31:52 -04:00
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
case ir . ONAME :
2020-12-06 18:28:49 -08:00
n := n . ( * ir . Name )
2021-01-03 20:14:00 -08:00
if n . Class == ir . PAUTO {
2021-01-21 14:13:36 +08:00
v . usedLocals . Add ( n )
2018-05-23 15:31:52 -04:00
}
2020-11-30 21:56:24 -05:00
case ir . OBLOCK :
// The only OBLOCK we should see at this point is an empty one.
// In any event, let the visitList(n.List()) below take care of the statements,
// and don't charge for the OBLOCK itself. The ++ undoes the -- below.
v . budget ++
2020-12-02 21:38:20 -08:00
2021-06-27 01:28:38 +07:00
case ir . OMETHVALUE , ir . OSLICELIT :
2020-12-02 21:38:20 -08:00
v . budget -- // Hack for toolstash -cmp.
2020-12-28 16:14:11 -08:00
case ir . OMETHEXPR :
v . budget ++ // Hack for toolstash -cmp.
[dev.unified] cmd/compile/internal/noder: implicit conversions for multi-valued expressions
This CL changes GOEXPERIMENT=unified to insert implicit conversions
for multi-valued expressions.
Unfortunately, IR doesn't have strong, first-class support for
multi-valued expressions, so this CL takes the approach of spilling
them to temporary variables, which can then be implicitly converted.
This is the same approach taken by walk, but doing it this early does
introduce some minor complications:
1. For select case clauses with comma-ok assignments (e.g., `case x,
ok := <-ch:`), the compiler middle end wants to see the OAS2RECV
assignment is the CommClause.Comm statement. So when constructing
select statements, we need to massage this around a little.
2. The extra temporary variables and assignments skew the existing
inlining heuristics. As mentioned, the temporaries/assignments will
eventually be added (and often optimized away again) anyway, but now
they're visible to the inliner. So this CL also kludges the inlining
heuristics in this case to keep things comparable.
Change-Id: I3e3ea756ad92472ebe28bae3963be61ed7684a75
Reviewed-on: https://go-review.googlesource.com/c/go/+/415244
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2022-06-28 16:31:29 -07:00
case ir . OAS2 :
n := n . ( * ir . AssignListStmt )
// Unified IR unconditionally rewrites:
//
// a, b = f()
//
// into:
//
// DCL tmp1
// DCL tmp2
// tmp1, tmp2 = f()
// a, b = tmp1, tmp2
//
// so that it can insert implicit conversions as necessary. To
// minimize impact to the existing inlining heuristics (in
// particular, to avoid breaking the existing inlinability regress
// tests), we need to compensate for this here.
2023-01-03 12:11:44 -08:00
//
2023-11-18 20:16:47 -08:00
// See also identical logic in IsBigFunc.
if len ( n . Rhs ) > 0 {
if init := n . Rhs [ 0 ] . Init ( ) ; len ( init ) == 1 {
if _ , ok := init [ 0 ] . ( * ir . AssignListStmt ) ; ok {
// 4 for each value, because each temporary variable now
// appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
//
// 1 for the extra "tmp1, tmp2 = f()" assignment statement.
v . budget += 4 * int32 ( len ( n . Lhs ) ) + 1
}
[dev.unified] cmd/compile/internal/noder: implicit conversions for multi-valued expressions
This CL changes GOEXPERIMENT=unified to insert implicit conversions
for multi-valued expressions.
Unfortunately, IR doesn't have strong, first-class support for
multi-valued expressions, so this CL takes the approach of spilling
them to temporary variables, which can then be implicitly converted.
This is the same approach taken by walk, but doing it this early does
introduce some minor complications:
1. For select case clauses with comma-ok assignments (e.g., `case x,
ok := <-ch:`), the compiler middle end wants to see the OAS2RECV
assignment is the CommClause.Comm statement. So when constructing
select statements, we need to massage this around a little.
2. The extra temporary variables and assignments skew the existing
inlining heuristics. As mentioned, the temporaries/assignments will
eventually be added (and often optimized away again) anyway, but now
they're visible to the inliner. So this CL also kludges the inlining
heuristics in this case to keep things comparable.
Change-Id: I3e3ea756ad92472ebe28bae3963be61ed7684a75
Reviewed-on: https://go-review.googlesource.com/c/go/+/415244
Reviewed-by: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
Reviewed-by: David Chase <drchase@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
2022-06-28 16:31:29 -07:00
}
}
2022-04-19 19:41:40 -04:00
case ir . OAS :
// Special case for coverage counter updates and coverage
// function registrations. Although these correspond to real
// operations, we treat them as zero cost for the moment. This
// is primarily due to the existence of tests that are
// sensitive to inlining-- if the insertion of coverage
// instrumentation happens to tip a given function over the
// threshold and move it from "inlinable" to "not-inlinable",
// this can cause changes in allocation behavior, which can
// then result in test failures (a good example is the
// TestAllocations in crypto/ed25519).
n := n . ( * ir . AssignStmt )
2022-10-28 13:21:36 -04:00
if n . X . Op ( ) == ir . OINDEX && isIndexingCoverageCounter ( n . X ) {
2022-10-10 13:39:30 -04:00
return false
2022-04-19 19:41:40 -04:00
}
2015-02-13 14:40:36 -05:00
}
2017-04-19 16:32:41 -04:00
v . budget --
2015-02-13 14:40:36 -05:00
2017-09-12 13:53:55 -05:00
// When debugging, don't stop early, to get full cost of inlining this function
2020-11-19 20:49:23 -05:00
if v . budget < 0 && base . Flag . LowerM < 2 && ! logopt . Enabled ( ) {
2021-01-07 11:17:57 +08:00
v . reason = "too expensive"
return true
2016-11-08 22:18:38 -08:00
}
2021-01-07 11:17:57 +08:00
return ir . DoChildren ( n , v . do )
2015-02-13 14:40:36 -05:00
}
2023-11-18 20:16:47 -08:00
// IsBigFunc reports whether fn is a "big" function.
//
// Note: The criteria for "big" is heuristic and subject to change.
func IsBigFunc ( fn * ir . Func ) bool {
2020-12-02 20:18:47 -05:00
budget := inlineBigFunctionNodes
[dev.regabi] cmd/compile: rename ir.Find to ir.Any and update uses
ir.Find is called "any" in C#, Dart, Haskell, Python, R, Ruby, and Rust,
and "any_of" in C++, "anyMatch" in Java, "some" in JavaScript,
"exists in OCaml, and "existsb" in Coq.
(Thanks to Matthew Dempsky for the research.)
This CL changes Find to Any to use the mostly standard name.
It also updates wrapper helpers to use the any terminology:
hasCall -> anyCall
hasCallOrChan -> anyCallOrChan
hasSideEffects -> anySideEffects
Unchanged are "hasNamedResults", "hasUniquePos", and "hasDefaultCase",
which are all about a single node, not any node in the IR tree.
I also renamed hasFall to endsInFallthrough, since its semantics are
neither that of "any" nor that of the remaining "has" functions.
So the new terminology helps separate different kinds of predicates nicely.
Change-Id: I9bb3c9ebf060a30447224be09a5c34ad5244ea0d
Reviewed-on: https://go-review.googlesource.com/c/go/+/278912
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-16 10:53:20 -05:00
return ir . Any ( fn , func ( n ir . Node ) bool {
2023-01-03 12:11:44 -08:00
// See logic in hairyVisitor.doNode, explaining unified IR's
// handling of "a, b = f()" assignments.
2023-11-18 20:16:47 -08:00
if n , ok := n . ( * ir . AssignListStmt ) ; ok && n . Op ( ) == ir . OAS2 && len ( n . Rhs ) > 0 {
2023-01-03 12:11:44 -08:00
if init := n . Rhs [ 0 ] . Init ( ) ; len ( init ) == 1 {
if _ , ok := init [ 0 ] . ( * ir . AssignListStmt ) ; ok {
budget += 4 * len ( n . Lhs ) + 1
}
}
}
2020-12-02 20:18:47 -05:00
budget --
2020-12-12 18:50:21 -05:00
return budget <= 0
2020-12-02 20:18:47 -05:00
} )
2018-07-23 13:09:48 -07:00
}
2024-11-19 17:18:38 -05:00
// inlineCallCheck returns whether a call will never be inlineable
// for basic reasons, and whether the call is an intrinisic call.
// The intrinsic result singles out intrinsic calls for debug logging.
func inlineCallCheck ( callerfn * ir . Func , call * ir . CallExpr ) ( bool , bool ) {
2023-11-18 20:16:47 -08:00
if base . Flag . LowerL == 0 {
2024-11-19 17:18:38 -05:00
return false , false
2018-07-23 13:09:48 -07:00
}
2023-11-18 20:16:47 -08:00
if call . Op ( ) != ir . OCALLFUNC {
2024-11-19 17:18:38 -05:00
return false , false
2015-02-13 14:40:36 -05:00
}
2023-11-18 20:16:47 -08:00
if call . GoDefer || call . NoInline {
2024-11-19 17:18:38 -05:00
return false , false
2015-02-13 14:40:36 -05:00
}
2023-11-18 20:16:47 -08:00
// Prevent inlining some reflect.Value methods when using checkptr,
// even when package reflect was compiled without it (#35073).
if base . Debug . Checkptr != 0 && call . Fun . Op ( ) == ir . OMETHEXPR {
if method := ir . MethodExprName ( call . Fun ) ; method != nil {
switch types . ReflectSymName ( method . Sym ( ) ) {
case "Value.UnsafeAddr" , "Value.Pointer" :
2024-11-19 17:18:38 -05:00
return false , false
2021-06-25 22:24:29 +07:00
}
2020-03-11 12:51:44 +07:00
}
2015-02-13 14:40:36 -05:00
}
hash/maphash, cmd/compile: make Comparable[string] not escape its argument
Currently, maphash.Comparable forces its argument to escape if it
contains a pointer, as we cannot hash stack pointers, which will
change when the stack moves. However, for a string, it is actually
okay if its data pointer points to the stack, as the hash depends
on only the content, not the pointer.
Currently there is no way to write this type-dependent escape
logic in Go code. So we implement it in the compiler as an
intrinsic. The compiler can also recognize not just the string
type, but types whose pointers are all string pointers, and make
them not escape.
Fixes #70560.
Change-Id: I3bf219ad71a238d2e35f0ea33de96487bc8cc231
Reviewed-on: https://go-review.googlesource.com/c/go/+/632715
Reviewed-by: David Chase <drchase@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
2024-12-01 23:53:23 -05:00
// hash/maphash.escapeForHash[T] is a compiler intrinsic implemented
// in the escape analysis phase.
if fn := ir . StaticCalleeName ( call . Fun ) ; fn != nil && fn . Sym ( ) . Pkg . Path == "hash/maphash" &&
strings . HasPrefix ( fn . Sym ( ) . Name , "escapeForHash[" ) {
return false , true
}
2024-11-19 17:18:38 -05:00
if ir . IsIntrinsicCall ( call ) {
return false , true
}
return true , false
}
// InlineCallTarget returns the resolved-for-inlining target of a call.
// It does not necessarily guarantee that the target can be inlined, though
// obvious exclusions are applied.
func InlineCallTarget ( callerfn * ir . Func , call * ir . CallExpr , profile * pgoir . Profile ) * ir . Func {
if mightInline , _ := inlineCallCheck ( callerfn , call ) ; ! mightInline {
return nil
}
return inlCallee ( callerfn , call . Fun , profile , true )
}
// TryInlineCall returns an inlined call expression for call, or nil
// if inlining is not possible.
func TryInlineCall ( callerfn * ir . Func , call * ir . CallExpr , bigCaller bool , profile * pgoir . Profile , closureCalledOnce bool ) * ir . InlinedCallExpr {
mightInline , isIntrinsic := inlineCallCheck ( callerfn , call )
2015-02-13 14:40:36 -05:00
2024-11-19 17:18:38 -05:00
// Preserve old logging behavior
if ( mightInline || isIntrinsic ) && base . Flag . LowerM > 3 {
2023-11-18 20:16:47 -08:00
fmt . Printf ( "%v:call to func %+v\n" , ir . Line ( call ) , call . Fun )
2015-02-13 14:40:36 -05:00
}
2024-11-19 17:18:38 -05:00
if ! mightInline {
2023-11-18 20:16:47 -08:00
return nil
}
2024-11-19 17:18:38 -05:00
if fn := inlCallee ( callerfn , call . Fun , profile , false ) ; fn != nil && typecheck . HaveInlineBody ( fn ) {
return mkinlcall ( callerfn , call , fn , bigCaller , closureCalledOnce )
2023-11-18 20:16:47 -08:00
}
return nil
2015-02-13 14:40:36 -05:00
}
2020-09-22 02:19:14 -07:00
// inlCallee takes a function-typed expression and returns the underlying function ONAME
// that it refers to if statically known. Otherwise, it returns nil.
2024-11-19 17:18:38 -05:00
// resolveOnly skips cost-based inlineability checks for closures; the result may not actually be inlineable.
func inlCallee ( caller * ir . Func , fn ir . Node , profile * pgoir . Profile , resolveOnly bool ) ( res * ir . Func ) {
[dev.regabi] cmd/compile: move helpers into package ir [generated]
[git-generate]
cd src/cmd/compile/internal/gc
sed -i '' 's/TestBuiltin.*/& t.Skip("mkbuiltin needs fixing")/' builtin_test.go
gofmt -w builtin_test.go
rf '
# Inline a few little-used constructors to avoid bringing them.
ex {
import "cmd/compile/internal/base"
import "cmd/compile/internal/ir"
import "cmd/compile/internal/types"
import "cmd/internal/src"
var typ *types.Type
var sym *types.Sym
var str string
symfield(sym, typ) -> ir.NewField(base.Pos, sym, nil, typ)
anonfield(typ) -> ir.NewField(base.Pos, nil, nil, typ)
namedfield(str, typ) -> ir.NewField(base.Pos, lookup(str), nil, typ)
var cp *ir.CallPartExpr
callpartMethod(cp) -> cp.Method
var n ir.Node
callpartMethod(n) -> n.(*ir.CallPartExpr).Method
var ns []ir.Node
liststmt(ns) -> ir.NewBlockStmt(src.NoXPos, ns)
}
rm symfield anonfield namedfield liststmt callpartMethod
mv maxStackVarSize MaxStackVarSize
mv maxImplicitStackVarSize MaxImplicitStackVarSize
mv smallArrayBytes MaxSmallArraySize
mv MaxStackVarSize cfg.go
mv nodbool NewBool
mv nodintconst NewInt
mv nodstr NewString
mv NewBool NewInt NewString const.go
mv Mpprec ConstPrec
mv bigFloatVal BigFloat
mv doesoverflow ConstOverflow
mv isGoConst IsConstNode
mv smallintconst IsSmallIntConst
mv isZero IsZero
mv islvalue IsAssignable
mv staticValue StaticValue
mv samesafeexpr SameSafeExpr
mv checkPtr ShouldCheckPtr
mv isReflectHeaderDataField IsReflectHeaderDataField
mv paramNnames ParamNames
mv methodSym MethodSym
mv methodSymSuffix MethodSymSuffix
mv methodExprFunc MethodExprFunc
mv methodExprName MethodExprName
mv IsZero IsAssignable StaticValue staticValue1 reassigned \
IsIntrinsicCall \
SameSafeExpr ShouldCheckPtr IsReflectHeaderDataField \
ParamNames MethodSym MethodSymSuffix \
MethodExprName MethodExprFunc \
expr.go
mv Curfn CurFunc
mv funcsymname FuncSymName
mv newFuncNameAt NewFuncNameAt
mv setNodeNameFunc MarkFunc
mv CurFunc FuncSymName NewFuncNameAt MarkFunc func.go
mv isParamStackCopy IsParamStackCopy
mv isParamHeapCopy IsParamHeapCopy
mv nodfp RegFP
mv IsParamStackCopy IsParamHeapCopy RegFP name.go
mv hasUniquePos HasUniquePos
mv setlineno SetPos
mv initExpr InitExpr
mv hasNamedResults HasNamedResults
mv outervalue OuterValue
mv HasNamedResults HasUniquePos SetPos InitExpr OuterValue EscNever node.go
mv visitBottomUp VisitFuncsBottomUp # scc.go
mv cfg.go \
NewBool NewInt NewString \ # parts of const.go
ConstPrec BigFloat ConstOverflow IsConstNode IsSmallIntConst \
expr.go func.go name.go node.go scc.go \
cmd/compile/internal/ir
'
Change-Id: I13402c5a2cedbf78d993a1eae2940718f23ac166
Reviewed-on: https://go-review.googlesource.com/c/go/+/279421
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-23 00:38:15 -05:00
fn = ir . StaticValue ( fn )
2020-12-10 18:46:45 -05:00
switch fn . Op ( ) {
case ir . OMETHEXPR :
2020-12-28 16:14:11 -08:00
fn := fn . ( * ir . SelectorExpr )
[dev.regabi] cmd/compile: move helpers into package ir [generated]
[git-generate]
cd src/cmd/compile/internal/gc
sed -i '' 's/TestBuiltin.*/& t.Skip("mkbuiltin needs fixing")/' builtin_test.go
gofmt -w builtin_test.go
rf '
# Inline a few little-used constructors to avoid bringing them.
ex {
import "cmd/compile/internal/base"
import "cmd/compile/internal/ir"
import "cmd/compile/internal/types"
import "cmd/internal/src"
var typ *types.Type
var sym *types.Sym
var str string
symfield(sym, typ) -> ir.NewField(base.Pos, sym, nil, typ)
anonfield(typ) -> ir.NewField(base.Pos, nil, nil, typ)
namedfield(str, typ) -> ir.NewField(base.Pos, lookup(str), nil, typ)
var cp *ir.CallPartExpr
callpartMethod(cp) -> cp.Method
var n ir.Node
callpartMethod(n) -> n.(*ir.CallPartExpr).Method
var ns []ir.Node
liststmt(ns) -> ir.NewBlockStmt(src.NoXPos, ns)
}
rm symfield anonfield namedfield liststmt callpartMethod
mv maxStackVarSize MaxStackVarSize
mv maxImplicitStackVarSize MaxImplicitStackVarSize
mv smallArrayBytes MaxSmallArraySize
mv MaxStackVarSize cfg.go
mv nodbool NewBool
mv nodintconst NewInt
mv nodstr NewString
mv NewBool NewInt NewString const.go
mv Mpprec ConstPrec
mv bigFloatVal BigFloat
mv doesoverflow ConstOverflow
mv isGoConst IsConstNode
mv smallintconst IsSmallIntConst
mv isZero IsZero
mv islvalue IsAssignable
mv staticValue StaticValue
mv samesafeexpr SameSafeExpr
mv checkPtr ShouldCheckPtr
mv isReflectHeaderDataField IsReflectHeaderDataField
mv paramNnames ParamNames
mv methodSym MethodSym
mv methodSymSuffix MethodSymSuffix
mv methodExprFunc MethodExprFunc
mv methodExprName MethodExprName
mv IsZero IsAssignable StaticValue staticValue1 reassigned \
IsIntrinsicCall \
SameSafeExpr ShouldCheckPtr IsReflectHeaderDataField \
ParamNames MethodSym MethodSymSuffix \
MethodExprName MethodExprFunc \
expr.go
mv Curfn CurFunc
mv funcsymname FuncSymName
mv newFuncNameAt NewFuncNameAt
mv setNodeNameFunc MarkFunc
mv CurFunc FuncSymName NewFuncNameAt MarkFunc func.go
mv isParamStackCopy IsParamStackCopy
mv isParamHeapCopy IsParamHeapCopy
mv nodfp RegFP
mv IsParamStackCopy IsParamHeapCopy RegFP name.go
mv hasUniquePos HasUniquePos
mv setlineno SetPos
mv initExpr InitExpr
mv hasNamedResults HasNamedResults
mv outervalue OuterValue
mv HasNamedResults HasUniquePos SetPos InitExpr OuterValue EscNever node.go
mv visitBottomUp VisitFuncsBottomUp # scc.go
mv cfg.go \
NewBool NewInt NewString \ # parts of const.go
ConstPrec BigFloat ConstOverflow IsConstNode IsSmallIntConst \
expr.go func.go name.go node.go scc.go \
cmd/compile/internal/ir
'
Change-Id: I13402c5a2cedbf78d993a1eae2940718f23ac166
Reviewed-on: https://go-review.googlesource.com/c/go/+/279421
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-23 00:38:15 -05:00
n := ir . MethodExprName ( fn )
2020-12-28 16:14:11 -08:00
// Check that receiver type matches fn.X.
2020-11-18 11:25:29 -05:00
// TODO(mdempsky): Handle implicit dereference
// of pointer receiver argument?
2020-12-28 16:14:11 -08:00
if n == nil || ! types . Identical ( n . Type ( ) . Recv ( ) . Type , fn . X . Type ( ) ) {
2020-11-18 11:25:29 -05:00
return nil
2020-09-22 02:19:14 -07:00
}
2020-12-23 00:02:08 -05:00
return n . Func
2020-12-10 18:46:45 -05:00
case ir . ONAME :
[dev.regabi] cmd/compile: remove Node.Left etc [generated]
This automated CL adds type assertions on the true branches of
n.Op() equality tests, to redeclare n with a more specific type, when
it is safe to do so. (That is, when n is not reassigned with a more
general type, when n is not reassigned and then used outside the
scope, and so on.) All the "unsafe" times that the automated tool
would avoid have been removed or rewritten in earlier CLs, so that
after this CL and the next one, which removes the use of ir.Nod,
every use of the Left, Right, and so on methods is done using concrete
types, never the Node interface.
Having done that, the CL locks in the progress by deleting many of
the access methods, including Left, SetLeft and so on, from the
Node interface.
There are still uses of Name, Func, Sym, some of the tracking
bits, and a few other miscellaneous fields, but all the main access
methods are gone from the Node interface. The others will be cleaned
up in smaller CLs.
Passes buildall w/ toolstash -cmp.
[git-generate]
cd src/cmd/compile/internal/gc
rf 'typeassert {
import "cmd/compile/internal/ir"
var n ir.Node
n.Op() == ir.OADD -> n.(*ir.BinaryExpr)
n.Op() == ir.OADDR -> n.(*ir.AddrExpr)
n.Op() == ir.OADDSTR -> n.(*ir.AddStringExpr)
n.Op() == ir.OALIGNOF -> n.(*ir.UnaryExpr)
n.Op() == ir.OAND -> n.(*ir.BinaryExpr)
n.Op() == ir.OANDAND -> n.(*ir.LogicalExpr)
n.Op() == ir.OANDNOT -> n.(*ir.BinaryExpr)
n.Op() == ir.OAPPEND -> n.(*ir.CallExpr)
n.Op() == ir.OARRAYLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OAS -> n.(*ir.AssignStmt)
n.Op() == ir.OAS2 -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2DOTTYPE -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2FUNC -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2MAPR -> n.(*ir.AssignListStmt)
n.Op() == ir.OAS2RECV -> n.(*ir.AssignListStmt)
n.Op() == ir.OASOP -> n.(*ir.AssignOpStmt)
n.Op() == ir.OBITNOT -> n.(*ir.UnaryExpr)
n.Op() == ir.OBLOCK -> n.(*ir.BlockStmt)
n.Op() == ir.OBREAK -> n.(*ir.BranchStmt)
n.Op() == ir.OBYTES2STR -> n.(*ir.ConvExpr)
n.Op() == ir.OBYTES2STRTMP -> n.(*ir.ConvExpr)
n.Op() == ir.OCALL -> n.(*ir.CallExpr)
n.Op() == ir.OCALLFUNC -> n.(*ir.CallExpr)
n.Op() == ir.OCALLINTER -> n.(*ir.CallExpr)
n.Op() == ir.OCALLMETH -> n.(*ir.CallExpr)
n.Op() == ir.OCALLPART -> n.(*ir.CallPartExpr)
n.Op() == ir.OCAP -> n.(*ir.UnaryExpr)
n.Op() == ir.OCASE -> n.(*ir.CaseStmt)
n.Op() == ir.OCFUNC -> n.(*ir.UnaryExpr)
n.Op() == ir.OCHECKNIL -> n.(*ir.UnaryExpr)
n.Op() == ir.OCLOSE -> n.(*ir.UnaryExpr)
n.Op() == ir.OCOMPLEX -> n.(*ir.BinaryExpr)
n.Op() == ir.OCOMPLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OCONTINUE -> n.(*ir.BranchStmt)
n.Op() == ir.OCONV -> n.(*ir.ConvExpr)
n.Op() == ir.OCONVIFACE -> n.(*ir.ConvExpr)
n.Op() == ir.OCONVNOP -> n.(*ir.ConvExpr)
n.Op() == ir.OCOPY -> n.(*ir.BinaryExpr)
n.Op() == ir.ODCL -> n.(*ir.Decl)
n.Op() == ir.ODCLCONST -> n.(*ir.Decl)
n.Op() == ir.ODCLFUNC -> n.(*ir.Func)
n.Op() == ir.ODCLTYPE -> n.(*ir.Decl)
n.Op() == ir.ODEFER -> n.(*ir.GoDeferStmt)
n.Op() == ir.ODELETE -> n.(*ir.CallExpr)
n.Op() == ir.ODEREF -> n.(*ir.StarExpr)
n.Op() == ir.ODIV -> n.(*ir.BinaryExpr)
n.Op() == ir.ODOT -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTINTER -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTMETH -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTPTR -> n.(*ir.SelectorExpr)
n.Op() == ir.ODOTTYPE -> n.(*ir.TypeAssertExpr)
n.Op() == ir.ODOTTYPE2 -> n.(*ir.TypeAssertExpr)
n.Op() == ir.OEFACE -> n.(*ir.BinaryExpr)
n.Op() == ir.OEQ -> n.(*ir.BinaryExpr)
n.Op() == ir.OFALL -> n.(*ir.BranchStmt)
n.Op() == ir.OFOR -> n.(*ir.ForStmt)
n.Op() == ir.OFORUNTIL -> n.(*ir.ForStmt)
n.Op() == ir.OGE -> n.(*ir.BinaryExpr)
n.Op() == ir.OGETG -> n.(*ir.CallExpr)
n.Op() == ir.OGO -> n.(*ir.GoDeferStmt)
n.Op() == ir.OGOTO -> n.(*ir.BranchStmt)
n.Op() == ir.OGT -> n.(*ir.BinaryExpr)
n.Op() == ir.OIDATA -> n.(*ir.UnaryExpr)
n.Op() == ir.OIF -> n.(*ir.IfStmt)
n.Op() == ir.OIMAG -> n.(*ir.UnaryExpr)
n.Op() == ir.OINDEX -> n.(*ir.IndexExpr)
n.Op() == ir.OINDEXMAP -> n.(*ir.IndexExpr)
n.Op() == ir.OINLCALL -> n.(*ir.InlinedCallExpr)
n.Op() == ir.OINLMARK -> n.(*ir.InlineMarkStmt)
n.Op() == ir.OITAB -> n.(*ir.UnaryExpr)
n.Op() == ir.OKEY -> n.(*ir.KeyExpr)
n.Op() == ir.OLABEL -> n.(*ir.LabelStmt)
n.Op() == ir.OLE -> n.(*ir.BinaryExpr)
n.Op() == ir.OLEN -> n.(*ir.UnaryExpr)
n.Op() == ir.OLSH -> n.(*ir.BinaryExpr)
n.Op() == ir.OLT -> n.(*ir.BinaryExpr)
n.Op() == ir.OMAKE -> n.(*ir.CallExpr)
n.Op() == ir.OMAKECHAN -> n.(*ir.MakeExpr)
n.Op() == ir.OMAKEMAP -> n.(*ir.MakeExpr)
n.Op() == ir.OMAKESLICE -> n.(*ir.MakeExpr)
n.Op() == ir.OMAKESLICECOPY -> n.(*ir.MakeExpr)
n.Op() == ir.OMAPLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OMETHEXPR -> n.(*ir.MethodExpr)
n.Op() == ir.OMOD -> n.(*ir.BinaryExpr)
n.Op() == ir.OMUL -> n.(*ir.BinaryExpr)
n.Op() == ir.ONAME -> n.(*ir.Name)
n.Op() == ir.ONE -> n.(*ir.BinaryExpr)
n.Op() == ir.ONEG -> n.(*ir.UnaryExpr)
n.Op() == ir.ONEW -> n.(*ir.UnaryExpr)
n.Op() == ir.ONEWOBJ -> n.(*ir.UnaryExpr)
n.Op() == ir.ONIL -> n.(*ir.NilExpr)
n.Op() == ir.ONOT -> n.(*ir.UnaryExpr)
n.Op() == ir.OOFFSETOF -> n.(*ir.UnaryExpr)
n.Op() == ir.OOR -> n.(*ir.BinaryExpr)
n.Op() == ir.OOROR -> n.(*ir.LogicalExpr)
n.Op() == ir.OPACK -> n.(*ir.PkgName)
n.Op() == ir.OPANIC -> n.(*ir.UnaryExpr)
n.Op() == ir.OPAREN -> n.(*ir.ParenExpr)
n.Op() == ir.OPLUS -> n.(*ir.UnaryExpr)
n.Op() == ir.OPRINT -> n.(*ir.CallExpr)
n.Op() == ir.OPRINTN -> n.(*ir.CallExpr)
n.Op() == ir.OPTRLIT -> n.(*ir.AddrExpr)
n.Op() == ir.ORANGE -> n.(*ir.RangeStmt)
n.Op() == ir.OREAL -> n.(*ir.UnaryExpr)
n.Op() == ir.ORECOVER -> n.(*ir.CallExpr)
n.Op() == ir.ORECV -> n.(*ir.UnaryExpr)
n.Op() == ir.ORESULT -> n.(*ir.ResultExpr)
n.Op() == ir.ORETJMP -> n.(*ir.BranchStmt)
n.Op() == ir.ORETURN -> n.(*ir.ReturnStmt)
n.Op() == ir.ORSH -> n.(*ir.BinaryExpr)
n.Op() == ir.ORUNES2STR -> n.(*ir.ConvExpr)
n.Op() == ir.ORUNESTR -> n.(*ir.ConvExpr)
n.Op() == ir.OSELECT -> n.(*ir.SelectStmt)
n.Op() == ir.OSELRECV2 -> n.(*ir.AssignListStmt)
n.Op() == ir.OSEND -> n.(*ir.SendStmt)
n.Op() == ir.OSIZEOF -> n.(*ir.UnaryExpr)
n.Op() == ir.OSLICE -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICE3 -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICE3ARR -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICEARR -> n.(*ir.SliceExpr)
n.Op() == ir.OSLICEHEADER -> n.(*ir.SliceHeaderExpr)
n.Op() == ir.OSLICELIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OSLICESTR -> n.(*ir.SliceExpr)
n.Op() == ir.OSPTR -> n.(*ir.UnaryExpr)
n.Op() == ir.OSTR2BYTES -> n.(*ir.ConvExpr)
n.Op() == ir.OSTR2BYTESTMP -> n.(*ir.ConvExpr)
n.Op() == ir.OSTR2RUNES -> n.(*ir.ConvExpr)
n.Op() == ir.OSTRUCTLIT -> n.(*ir.CompLitExpr)
n.Op() == ir.OSUB -> n.(*ir.BinaryExpr)
n.Op() == ir.OSWITCH -> n.(*ir.SwitchStmt)
n.Op() == ir.OTYPESW -> n.(*ir.TypeSwitchGuard)
n.Op() == ir.OVARDEF -> n.(*ir.UnaryExpr)
n.Op() == ir.OVARKILL -> n.(*ir.UnaryExpr)
n.Op() == ir.OVARLIVE -> n.(*ir.UnaryExpr)
n.Op() == ir.OXDOT -> n.(*ir.SelectorExpr)
n.Op() == ir.OXOR -> n.(*ir.BinaryExpr)
}
'
cd ../ir
rf '
rm \
Node.SetOp \
miniNode.SetOp \
Node.Func \
miniNode.Func \
Node.Left Node.SetLeft \
miniNode.Left miniNode.SetLeft \
Node.Right Node.SetRight \
miniNode.Right miniNode.SetRight \
Node.List Node.PtrList Node.SetList \
miniNode.List miniNode.PtrList miniNode.SetList \
Node.Rlist Node.PtrRlist Node.SetRlist \
miniNode.Rlist miniNode.PtrRlist miniNode.SetRlist \
Node.Body Node.PtrBody Node.SetBody \
miniNode.Body miniNode.PtrBody miniNode.SetBody \
Node.SubOp Node.SetSubOp \
miniNode.SubOp miniNode.SetSubOp \
Node.SetSym \
miniNode.SetSym \
Node.Offset Node.SetOffset \
miniNode.Offset miniNode.SetOffset \
Node.Class Node.SetClass \
miniNode.Class miniNode.SetClass \
Node.Iota Node.SetIota \
miniNode.Iota miniNode.SetIota \
Node.Colas Node.SetColas \
miniNode.Colas miniNode.SetColas \
Node.Transient Node.SetTransient \
miniNode.Transient miniNode.SetTransient \
Node.Implicit Node.SetImplicit \
miniNode.Implicit miniNode.SetImplicit \
Node.IsDDD Node.SetIsDDD \
miniNode.IsDDD miniNode.SetIsDDD \
Node.MarkReadonly \
miniNode.MarkReadonly \
Node.Likely Node.SetLikely \
miniNode.Likely miniNode.SetLikely \
Node.SliceBounds Node.SetSliceBounds \
miniNode.SliceBounds miniNode.SetSliceBounds \
Node.NoInline Node.SetNoInline \
miniNode.NoInline miniNode.SetNoInline \
Node.IndexMapLValue Node.SetIndexMapLValue \
miniNode.IndexMapLValue miniNode.SetIndexMapLValue \
Node.ResetAux \
miniNode.ResetAux \
Node.HasBreak Node.SetHasBreak \
miniNode.HasBreak miniNode.SetHasBreak \
Node.Bounded Node.SetBounded \
miniNode.Bounded miniNode.SetBounded \
miniNode.Embedded miniNode.SetEmbedded \
miniNode.Int64Val miniNode.Uint64Val miniNode.CanInt64 \
miniNode.BoolVal miniNode.StringVal \
miniNode.TChanDir miniNode.SetTChanDir \
miniNode.Format \
miniNode.copy miniNode.doChildren miniNode.editChildren \
'
Change-Id: I2a05b535963b43f83b1849fcf653f82b99af6035
Reviewed-on: https://go-review.googlesource.com/c/go/+/277934
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-12-22 23:56:32 -05:00
fn := fn . ( * ir . Name )
2021-01-03 20:14:00 -08:00
if fn . Class == ir . PFUNC {
2020-12-23 00:02:08 -05:00
return fn . Func
2020-12-10 18:46:45 -05:00
}
case ir . OCLOSURE :
2020-12-21 15:10:26 -05:00
fn := fn . ( * ir . ClosureExpr )
2020-12-23 00:02:08 -05:00
c := fn . Func
2023-08-11 18:21:22 -07:00
if len ( c . ClosureVars ) != 0 && c . ClosureVars [ 0 ] . Outer . Curfn != caller {
return nil // inliner doesn't support inlining across closure frames
}
2024-11-19 17:18:38 -05:00
if ! resolveOnly {
CanInline ( c , profile )
}
2020-11-28 07:31:18 -05:00
return c
2017-09-18 14:54:10 -07:00
}
2020-09-22 02:19:14 -07:00
return nil
2017-09-18 14:54:10 -07:00
}
2015-02-13 14:40:36 -05:00
var inlgen int
2020-12-21 01:44:49 -05:00
// SSADumpInline gives the SSA back end a chance to dump the function
// when producing output for debugging the compiler itself.
var SSADumpInline = func ( * ir . Func ) { }
2022-08-31 13:48:06 -07:00
// InlineCall allows the inliner implementation to be overridden.
2022-07-25 21:37:30 -07:00
// If it returns nil, the function will not be inlined.
2023-08-17 22:13:22 -07:00
var InlineCall = func ( callerfn * ir . Func , call * ir . CallExpr , fn * ir . Func , inlIndex int ) * ir . InlinedCallExpr {
2022-12-01 16:33:59 -08:00
base . Fatalf ( "inline.InlineCall not overridden" )
panic ( "unreachable" )
}
2021-05-27 02:47:04 -07:00
2023-03-28 12:45:17 -04:00
// inlineCostOK returns true if call n from caller to callee is cheap enough to
// inline. bigCaller indicates that caller is a big function.
//
2024-04-02 11:12:44 -04:00
// In addition to the "cost OK" boolean, it also returns
// - the "max cost" limit used to make the decision (which may differ depending on func size)
// - the score assigned to this specific callsite
// - whether the inlined function is "hot" according to PGO.
2024-11-19 17:18:38 -05:00
func inlineCostOK ( n * ir . CallExpr , caller , callee * ir . Func , bigCaller , closureCalledOnce bool ) ( bool , int32 , int32 , bool ) {
2023-03-28 12:45:17 -04:00
maxCost := int32 ( inlineMaxBudget )
2024-11-15 17:08:34 -05:00
2023-03-28 12:45:17 -04:00
if bigCaller {
// We use this to restrict inlining into very big functions.
// See issue 26546 and 17566.
maxCost = inlineBigFunctionMaxCost
}
2024-11-19 17:18:38 -05:00
if callee . ClosureParent != nil {
maxCost *= 2 // favor inlining closures
if closureCalledOnce { // really favor inlining the one call to this closure
maxCost = max ( maxCost , inlineClosureCalledOnceCost )
}
}
2023-08-11 09:40:31 -04:00
metric := callee . Inl . Cost
2023-10-31 13:21:41 -04:00
if inlheur . Enabled ( ) {
2023-09-21 13:47:05 -04:00
score , ok := inlheur . GetCallSiteScore ( caller , n )
2023-08-11 09:40:31 -04:00
if ok {
metric = int32 ( score )
}
}
2024-04-02 11:12:44 -04:00
lineOffset := pgoir . NodeLineOffset ( n , caller )
csi := pgoir . CallSiteInfo { LineOffset : lineOffset , Caller : caller }
_ , hot := candHotEdgeMap [ csi ]
2023-08-11 09:40:31 -04:00
if metric <= maxCost {
2023-03-28 12:45:17 -04:00
// Simple case. Function is already cheap enough.
2024-04-02 11:12:44 -04:00
return true , 0 , metric , hot
2023-03-28 12:45:17 -04:00
}
// We'll also allow inlining of hot functions below inlineHotMaxBudget,
// but only in small functions.
2024-04-02 11:12:44 -04:00
if ! hot {
2023-03-28 12:45:17 -04:00
// Cold
2024-04-02 11:12:44 -04:00
return false , maxCost , metric , false
2023-03-28 12:45:17 -04:00
}
// Hot
if bigCaller {
2023-05-12 15:36:37 -04:00
if base . Debug . PGODebug > 0 {
2023-03-28 12:45:17 -04:00
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 ) )
}
2024-04-02 11:12:44 -04:00
return false , maxCost , metric , false
2023-03-28 12:45:17 -04:00
}
2023-08-11 09:40:31 -04:00
if metric > inlineHotMaxBudget {
2024-04-02 11:12:44 -04:00
return false , inlineHotMaxBudget , metric , false
2023-03-28 12:45:17 -04:00
}
2023-09-15 12:13:09 -04:00
if ! base . PGOHash . MatchPosWithInfo ( n . Pos ( ) , "inline" , nil ) {
// De-selected by PGO Hash.
2024-04-02 11:12:44 -04:00
return false , maxCost , metric , false
2023-09-15 12:13:09 -04:00
}
2023-05-12 15:36:37 -04:00
if base . Debug . PGODebug > 0 {
2023-03-28 12:45:17 -04:00
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 ) )
}
2024-04-02 11:12:44 -04:00
return true , 0 , metric , hot
2023-03-28 12:45:17 -04:00
}
2025-03-05 13:44:12 -05:00
// parsePos returns all the inlining positions and the innermost position.
func parsePos ( pos src . XPos , posTmp [ ] src . Pos ) ( [ ] src . Pos , src . Pos ) {
ctxt := base . Ctxt
ctxt . AllPos ( pos , func ( p src . Pos ) {
posTmp = append ( posTmp , p )
} )
l := len ( posTmp ) - 1
return posTmp [ : l ] , posTmp [ l ]
}
2024-02-02 17:30:03 +08:00
// canInlineCallExpr returns true if the call n from caller to callee
2024-04-02 11:12:44 -04:00
// can be inlined, plus the score computed for the call expr in question,
// and whether the callee is hot according to PGO.
// bigCaller indicates that caller is a big function. log
2023-11-07 10:28:56 -05:00
// indicates that the 'cannot inline' reason should be logged.
2022-02-03 14:12:08 -05:00
//
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
// Preconditions: CanInline(callee) has already been called.
2024-11-19 17:18:38 -05:00
func canInlineCallExpr ( callerfn * ir . Func , n * ir . CallExpr , callee * ir . Func , bigCaller , closureCalledOnce bool , log bool ) ( bool , int32 , bool ) {
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
if callee . Inl == nil {
// callee is never inlinable.
if log && logopt . Enabled ( ) {
2023-08-17 22:13:22 -07:00
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , ir . FuncName ( callerfn ) ,
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
fmt . Sprintf ( "%s cannot be inlined" , ir . PkgFuncName ( callee ) ) )
2020-03-04 16:33:54 -05:00
}
2024-04-02 11:12:44 -04:00
return false , 0 , false
2015-02-13 14:40:36 -05:00
}
2023-03-28 12:45:17 -04:00
2024-11-19 17:18:38 -05:00
ok , maxCost , callSiteScore , hot := inlineCostOK ( n , callerfn , callee , bigCaller , closureCalledOnce )
2023-11-07 10:28:56 -05:00
if ! ok {
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
// callee cost too high for this call site.
if log && logopt . Enabled ( ) {
2023-08-17 22:13:22 -07:00
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , ir . FuncName ( callerfn ) ,
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
fmt . Sprintf ( "cost %d of %s exceeds max caller cost %d" , callee . Inl . Cost , ir . PkgFuncName ( callee ) , maxCost ) )
2019-10-29 17:25:56 -04:00
}
2024-04-02 11:12:44 -04:00
return false , 0 , false
2018-07-23 13:09:48 -07:00
}
2015-02-13 14:40:36 -05:00
2025-03-05 13:44:12 -05:00
callees , calleeInner := parsePos ( n . Pos ( ) , make ( [ ] src . Pos , 0 , 10 ) )
for _ , p := range callees {
if p . Line ( ) == calleeInner . Line ( ) && p . Col ( ) == calleeInner . Col ( ) && p . AbsFilename ( ) == calleeInner . AbsFilename ( ) {
if log && logopt . Enabled ( ) {
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , fmt . Sprintf ( "recursive call to %s" , ir . FuncName ( callerfn ) ) )
}
return false , 0 , false
}
}
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
if base . Flag . Cfg . Instrumenting && types . IsNoInstrumentPkg ( callee . Sym ( ) . Pkg ) {
2018-03-27 15:35:51 -07:00
// Runtime package must not be instrumented.
// Instrument skips runtime package. However, some runtime code can be
// inlined into other packages and instrumented there. To avoid this,
// we disable inlining of runtime functions when instrumenting.
// The example that we observed is inlining of LockOSThread,
// which lead to false race reports on m contents.
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
if log && logopt . Enabled ( ) {
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , ir . FuncName ( callerfn ) ,
fmt . Sprintf ( "call to runtime function %s in instrumented build" , ir . PkgFuncName ( callee ) ) )
}
2024-04-02 11:12:44 -04:00
return false , 0 , false
2023-05-16 19:52:41 -04:00
}
2018-03-27 15:35:51 -07:00
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
if base . Flag . Race && types . IsNoRacePkg ( callee . Sym ( ) . Pkg ) {
if log && logopt . Enabled ( ) {
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , ir . FuncName ( callerfn ) ,
fmt . Sprintf ( ` call to into "no-race" package function %s in race build ` , ir . PkgFuncName ( callee ) ) )
}
2024-04-02 11:12:44 -04:00
return false , 0 , false
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
}
2022-08-23 16:34:26 -07:00
2024-07-18 14:51:34 -04:00
if base . Debug . Checkptr != 0 && types . IsRuntimePkg ( callee . Sym ( ) . Pkg ) {
2024-08-20 17:54:39 +00:00
// We don't instrument runtime packages for checkptr (see base/flag.go).
2024-07-18 14:51:34 -04:00
if log && logopt . Enabled ( ) {
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , ir . FuncName ( callerfn ) ,
fmt . Sprintf ( ` call to into runtime package function %s in -d=checkptr build ` , ir . PkgFuncName ( callee ) ) )
}
return false , 0 , false
}
2022-08-23 16:34:26 -07:00
// Check if we've already inlined this function at this particular
// call site, in order to stop inlining when we reach the beginning
// of a recursion cycle again. We don't inline immediately recursive
// functions, but allow inlining if there is a recursion cycle of
// many functions. Most likely, the inlining will stop before we
// even hit the beginning of the cycle again, but this catches the
// unusual case.
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
parent := base . Ctxt . PosTable . Pos ( n . Pos ( ) ) . Base ( ) . InliningIndex ( )
sym := callee . Linksym ( )
2022-08-23 16:34:26 -07:00
for inlIndex := parent ; inlIndex >= 0 ; inlIndex = base . Ctxt . InlTree . Parent ( inlIndex ) {
if base . Ctxt . InlTree . InlinedFunction ( inlIndex ) == sym {
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
if log {
if base . Flag . LowerM > 1 {
fmt . Printf ( "%v: cannot inline %v into %v: repeated recursive cycle\n" , ir . Line ( n ) , callee , ir . FuncName ( callerfn ) )
}
if logopt . Enabled ( ) {
logopt . LogOpt ( n . Pos ( ) , "cannotInlineCall" , "inline" , ir . FuncName ( callerfn ) ,
fmt . Sprintf ( "repeated recursive cycle to %s" , ir . PkgFuncName ( callee ) ) )
}
2022-08-23 16:34:26 -07:00
}
2024-04-02 11:12:44 -04:00
return false , 0 , false
2020-03-31 20:24:05 -07:00
}
}
2021-05-25 20:14:33 -07:00
2024-04-02 11:12:44 -04:00
return true , callSiteScore , hot
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
}
2023-11-18 20:16:47 -08:00
// mkinlcall returns an OINLCALL node that can replace OCALLFUNC n, or
// nil if it cannot be inlined. callerfn is the function that contains
// n, and fn is the function being called.
//
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
// The result of mkinlcall MUST be assigned back to n, e.g.
//
// n.Left = mkinlcall(n.Left, fn, isddd)
2024-11-19 17:18:38 -05:00
func mkinlcall ( callerfn * ir . Func , n * ir . CallExpr , fn * ir . Func , bigCaller , closureCalledOnce bool ) * ir . InlinedCallExpr {
ok , score , hot := canInlineCallExpr ( callerfn , n , fn , bigCaller , closureCalledOnce , true )
2023-11-07 10:28:56 -05:00
if ! ok {
2023-11-18 20:16:47 -08:00
return nil
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
}
2024-04-02 11:12:44 -04:00
if hot {
hasHotCall [ callerfn ] = struct { } { }
}
2022-12-20 11:23:23 -08:00
typecheck . AssertFixedCall ( n )
2021-05-25 20:14:33 -07:00
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
When computing function cost, hairyVisitor.doNode has two primary cases
for determining the cost of a call inside the function:
* Normal calls are simply cost 57.
* Calls that can be inlined have the cost of the inlined function body,
since that body will end up in this function.
Determining which "calls can be inlined" is where this breaks down.
doNode simply assumes that any function with `fn.Inl != nil` will get
inlined. However, this are more complex in mkinlcall, which has a
variety of cases where it may not inline.
For standard builds, most of these reasons are fairly rare (recursive
calls, calls to runtime functions in instrumented builds, etc), so this
simplification isn't too build.
However, for PGO builds, any function involved in at least one inlinable
hot callsite will have `fn.Inl != nil`, even though mkinlcall will only
inline at the hot callsites. As a result, cold functions calling hot
functions will use the (potentially very large) hot function inline body
cost in their call budget. This could make these functions too expensive
to inline even though they won't actually inline the hot function.
Handle this case plus the other inlinability cases (recursive calls,
etc) by consolidating mkinlcall's inlinability logic into
canInlineCallExpr, which is shared by doNode.
mkinlcall and doNode now have identical logic, except for one case: we
check for recursive cycles via inlined functions by looking at the
inline tree. Since we haven't actually done any inlining yet when in
doNode, we will miss those cases.
This CL doesn't change any inlining decisions in a standard build of the
compiler.
In the new inliner, the inlining decision is also based on the call
site, so this synchronization is also helpful.
Fixes #59484
Change-Id: I6ace66e37d50526535972215497ef75cd71f8b9d
Reviewed-on: https://go-review.googlesource.com/c/go/+/483196
Reviewed-by: Than McIntosh <thanm@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
2023-04-10 17:11:39 -04:00
parent := base . Ctxt . PosTable . Pos ( n . Pos ( ) ) . Base ( ) . InliningIndex ( )
sym := fn . Linksym ( )
cmd/compile: incorporate inlined function names into closure naming
In Go 1.17, cmd/compile gained the ability to inline calls to
functions that contain function literals (aka "closures"). This was
implemented by duplicating the function literal body and emitting a
second LSym, because in general it might be optimized better than the
original function literal.
However, the second LSym was named simply as any other function
literal appearing literally in the enclosing function would be named.
E.g., if f has a closure "f.funcX", and f is inlined into g, we would
create "g.funcY" (N.B., X and Y need not be the same.). Users then
have no idea this function originally came from f.
With this CL, the inlined call stack is incorporated into the clone
LSym's name: instead of "g.funcY", it's named "g.f.funcY".
In the future, it seems desirable to arrange for the clone's name to
appear exactly as the original name, so stack traces remain the same
as when -l or -d=inlfuncswithclosures are used. But it's unclear
whether the linker supports that today, or whether any downstream
tooling would be confused by this.
Updates #60324.
Change-Id: Ifad0ccef7e959e72005beeecdfffd872f63982f8
Reviewed-on: https://go-review.googlesource.com/c/go/+/497137
Reviewed-by: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
2023-05-22 13:25:15 -07:00
inlIndex := base . Ctxt . InlTree . Add ( parent , n . Pos ( ) , sym , ir . FuncName ( fn ) )
2021-05-27 02:47:04 -07:00
2022-09-09 16:23:39 -04:00
closureInitLSym := func ( n * ir . CallExpr , fn * ir . Func ) {
// The linker needs FuncInfo metadata for all inlined
// functions. This is typically handled by gc.enqueueFunc
// calling ir.InitLSym for all function declarations in
// typecheck.Target.Decls (ir.UseClosure adds all closures to
// Decls).
//
2024-09-09 22:03:54 +07:00
// However, closures in Decls are ignored, and are
2024-03-15 08:12:33 +00:00
// instead enqueued when walk of the calling function
2022-09-09 16:23:39 -04:00
// discovers them.
//
// This presents a problem for direct calls to closures.
// Inlining will replace the entire closure definition with its
// body, which hides the closure from walk and thus suppresses
// symbol creation.
//
// Explicitly create a symbol early in this edge case to ensure
// we keep this metadata.
//
// TODO: Refactor to keep a reference so this can all be done
// by enqueueFunc.
if n . Op ( ) != ir . OCALLFUNC {
// Not a standard call.
return
}
2023-10-04 15:22:49 -07:00
if n . Fun . Op ( ) != ir . OCLOSURE {
2022-09-09 16:23:39 -04:00
// Not a direct closure call.
return
}
2023-10-04 15:22:49 -07:00
clo := n . Fun . ( * ir . ClosureExpr )
2024-09-09 22:03:54 +07:00
if ! clo . Func . IsClosure ( ) {
// enqueueFunc will handle non closures anyways.
2022-09-09 16:23:39 -04:00
return
}
ir . InitLSym ( fn , true )
}
closureInitLSym ( n , fn )
2021-05-27 02:47:04 -07:00
if base . Flag . GenDwarfInl > 0 {
if ! sym . WasInlined ( ) {
base . Ctxt . DwFixups . SetPrecursorFunc ( sym , fn )
sym . Set ( obj . AttrWasInlined , true )
}
2015-02-13 14:40:36 -05:00
}
2021-05-27 02:47:04 -07:00
if base . Flag . LowerM != 0 {
2023-11-07 10:28:56 -05:00
if buildcfg . Experiment . NewInliner {
fmt . Printf ( "%v: inlining call to %v with score %d\n" ,
ir . Line ( n ) , fn , score )
} else {
fmt . Printf ( "%v: inlining call to %v\n" , ir . Line ( n ) , fn )
}
2015-02-13 14:40:36 -05:00
}
2020-11-19 20:49:23 -05:00
if base . Flag . LowerM > 2 {
[dev.regabi] cmd/compile: introduce cmd/compile/internal/ir [generated]
If we want to break up package gc at all, we will need to move
the compiler IR it defines into a separate package that can be
imported by packages that gc itself imports. This CL does that.
It also removes the TINT8 etc aliases so that all code is clear
about which package things are coming from.
This CL is automatically generated by the script below.
See the comments in the script for details about the changes.
[git-generate]
cd src/cmd/compile/internal/gc
rf '
# These names were never fully qualified
# when the types package was added.
# Do it now, to avoid confusion about where they live.
inline -rm \
Txxx \
TINT8 \
TUINT8 \
TINT16 \
TUINT16 \
TINT32 \
TUINT32 \
TINT64 \
TUINT64 \
TINT \
TUINT \
TUINTPTR \
TCOMPLEX64 \
TCOMPLEX128 \
TFLOAT32 \
TFLOAT64 \
TBOOL \
TPTR \
TFUNC \
TSLICE \
TARRAY \
TSTRUCT \
TCHAN \
TMAP \
TINTER \
TFORW \
TANY \
TSTRING \
TUNSAFEPTR \
TIDEAL \
TNIL \
TBLANK \
TFUNCARGS \
TCHANARGS \
NTYPE \
BADWIDTH
# esc.go and escape.go do not need to be split.
# Append esc.go onto the end of escape.go.
mv esc.go escape.go
# Pull out the type format installation from func Main,
# so it can be carried into package ir.
mv Main:/Sconv.=/-0,/TypeLinkSym/-1 InstallTypeFormats
# Names that need to be exported for use by code left in gc.
mv Isconst IsConst
mv asNode AsNode
mv asNodes AsNodes
mv asTypesNode AsTypesNode
mv basicnames BasicTypeNames
mv builtinpkg BuiltinPkg
mv consttype ConstType
mv dumplist DumpList
mv fdumplist FDumpList
mv fmtMode FmtMode
mv goopnames OpNames
mv inspect Inspect
mv inspectList InspectList
mv localpkg LocalPkg
mv nblank BlankNode
mv numImport NumImport
mv opprec OpPrec
mv origSym OrigSym
mv stmtwithinit StmtWithInit
mv dump DumpAny
mv fdump FDumpAny
mv nod Nod
mv nodl NodAt
mv newname NewName
mv newnamel NewNameAt
mv assertRepresents AssertValidTypeForConst
mv represents ValidTypeForConst
mv nodlit NewLiteral
# Types and fields that need to be exported for use by gc.
mv nowritebarrierrecCallSym SymAndPos
mv SymAndPos.lineno SymAndPos.Pos
mv SymAndPos.target SymAndPos.Sym
mv Func.lsym Func.LSym
mv Func.setWBPos Func.SetWBPos
mv Func.numReturns Func.NumReturns
mv Func.numDefers Func.NumDefers
mv Func.nwbrCalls Func.NWBRCalls
# initLSym is an algorithm left behind in gc,
# not an operation on Func itself.
mv Func.initLSym initLSym
mv nodeQueue NodeQueue
mv NodeQueue.empty NodeQueue.Empty
mv NodeQueue.popLeft NodeQueue.PopLeft
mv NodeQueue.pushRight NodeQueue.PushRight
# Many methods on Node are actually algorithms that
# would apply to any node implementation.
# Those become plain functions.
mv Node.funcname FuncName
mv Node.isBlank IsBlank
mv Node.isGoConst isGoConst
mv Node.isNil IsNil
mv Node.isParamHeapCopy isParamHeapCopy
mv Node.isParamStackCopy isParamStackCopy
mv Node.isSimpleName isSimpleName
mv Node.mayBeShared MayBeShared
mv Node.pkgFuncName PkgFuncName
mv Node.backingArrayPtrLen backingArrayPtrLen
mv Node.isterminating isTermNode
mv Node.labeledControl labeledControl
mv Nodes.isterminating isTermNodes
mv Nodes.sigerr fmtSignature
mv Node.MethodName methodExprName
mv Node.MethodFunc methodExprFunc
mv Node.IsMethod IsMethod
# Every node will need to implement RawCopy;
# Copy and SepCopy algorithms will use it.
mv Node.rawcopy Node.RawCopy
mv Node.copy Copy
mv Node.sepcopy SepCopy
# Extract Node.Format method body into func FmtNode,
# but leave method wrapper behind.
mv Node.Format:0,$ FmtNode
# Formatting helpers that will apply to all node implementations.
mv Node.Line Line
mv Node.exprfmt exprFmt
mv Node.jconv jconvFmt
mv Node.modeString modeString
mv Node.nconv nconvFmt
mv Node.nodedump nodeDumpFmt
mv Node.nodefmt nodeFmt
mv Node.stmtfmt stmtFmt
# Constant support needed for code moving to ir.
mv okforconst OKForConst
mv vconv FmtConst
mv int64Val Int64Val
mv float64Val Float64Val
mv Node.ValueInterface ConstValue
# Organize code into files.
mv LocalPkg BuiltinPkg ir.go
mv NumImport InstallTypeFormats Line fmt.go
mv syntax.go Nod NodAt NewNameAt Class Pxxx PragmaFlag Nointerface SymAndPos \
AsNode AsTypesNode BlankNode OrigSym \
Node.SliceBounds Node.SetSliceBounds Op.IsSlice3 \
IsConst Node.Int64Val Node.CanInt64 Node.Uint64Val Node.BoolVal Node.StringVal \
Node.RawCopy SepCopy Copy \
IsNil IsBlank IsMethod \
Node.Typ Node.StorageClass node.go
mv ConstType ConstValue Int64Val Float64Val AssertValidTypeForConst ValidTypeForConst NewLiteral idealType OKForConst val.go
# Move files to new ir package.
mv bitset.go class_string.go dump.go fmt.go \
ir.go node.go op_string.go val.go \
sizeof_test.go cmd/compile/internal/ir
'
: # fix mkbuiltin.go to generate the changes made to builtin.go during rf
sed -i '' '
s/\[T/[types.T/g
s/\*Node/*ir.Node/g
/internal\/types/c \
fmt.Fprintln(&b, `import (`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/ir"`) \
fmt.Fprintln(&b, ` "cmd/compile/internal/types"`) \
fmt.Fprintln(&b, `)`)
' mkbuiltin.go
gofmt -w mkbuiltin.go
: # update cmd/dist to add internal/ir
cd ../../../dist
sed -i '' '/compile.internal.gc/a\
"cmd/compile/internal/ir",
' buildtool.go
gofmt -w buildtool.go
: # update cmd/compile TestFormats
cd ../..
go install std cmd
cd cmd/compile
go test -u || go test # first one updates but fails; second passes
Change-Id: I5f7caf6b20629b51970279e81231a3574d5b51db
Reviewed-on: https://go-review.googlesource.com/c/go/+/273008
Trust: Russ Cox <rsc@golang.org>
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2020-11-19 21:09:22 -05:00
fmt . Printf ( "%v: Before inlining: %+v\n" , ir . Line ( n ) , n )
2015-02-13 14:40:36 -05:00
}
2023-08-17 22:13:22 -07:00
res := InlineCall ( callerfn , n , fn , inlIndex )
2022-09-09 11:29:32 -07:00
2021-05-27 02:47:04 -07:00
if res == nil {
2022-08-31 13:48:06 -07:00
base . FatalfAt ( n . Pos ( ) , "inlining call to %v failed" , fn )
2021-05-27 02:47:04 -07:00
}
if base . Flag . LowerM > 2 {
fmt . Printf ( "%v: After inlining %+v\n\n" , ir . Line ( res ) , res )
}
2023-10-31 13:21:41 -04:00
if inlheur . Enabled ( ) {
2023-09-21 15:22:28 -04:00
inlheur . UpdateCallsiteTable ( callerfn , n , res )
}
2021-05-27 02:47:04 -07:00
return res
}
2021-07-03 04:53:25 -07:00
// CalleeEffects appends any side effects from evaluating callee to init.
func CalleeEffects ( init * ir . Nodes , callee ir . Node ) {
for {
2022-08-08 12:31:33 -07:00
init . Append ( ir . TakeInit ( callee ) ... )
2021-07-03 04:53:25 -07:00
switch callee . Op ( ) {
case ir . ONAME , ir . OCLOSURE , ir . OMETHEXPR :
return // done
case ir . OCONVNOP :
conv := callee . ( * ir . ConvExpr )
callee = conv . X
case ir . OINLCALL :
ic := callee . ( * ir . InlinedCallExpr )
init . Append ( ic . Body . Take ( ) ... )
callee = ic . SingleResult ( )
default :
base . FatalfAt ( callee . Pos ( ) , "unexpected callee expression: %v" , callee )
}
}
}
2020-11-28 07:31:18 -05:00
func pruneUnusedAutos ( ll [ ] * ir . Name , vis * hairyVisitor ) [ ] * ir . Name {
s := make ( [ ] * ir . Name , 0 , len ( ll ) )
2018-05-23 15:31:52 -04:00
for _ , n := range ll {
2021-01-03 20:14:00 -08:00
if n . Class == ir . PAUTO {
2021-01-21 14:13:36 +08:00
if ! vis . usedLocals . Has ( n ) {
2023-08-26 16:37:24 -07:00
// TODO(mdempsky): Simplify code after confident that this
// never happens anymore.
base . FatalfAt ( n . Pos ( ) , "unused auto: %v" , n )
2018-05-23 15:31:52 -04:00
continue
}
}
s = append ( s , n )
}
return s
}
2020-10-28 18:49:10 -07:00
2020-12-23 00:44:42 -05:00
// numNonClosures returns the number of functions in list which are not closures.
func numNonClosures ( list [ ] * ir . Func ) int {
count := 0
for _ , fn := range list {
if fn . OClosure == nil {
count ++
}
}
return count
}
2020-12-29 19:46:31 -08:00
2021-01-07 11:17:57 +08:00
func doList ( list [ ] ir . Node , do func ( ir . Node ) bool ) bool {
2020-12-29 19:46:31 -08:00
for _ , x := range list {
if x != nil {
2021-01-07 11:17:57 +08:00
if do ( x ) {
return true
2020-12-29 19:46:31 -08:00
}
}
}
2021-01-07 11:17:57 +08:00
return false
2020-12-29 19:46:31 -08:00
}
2022-10-10 13:39:30 -04:00
// isIndexingCoverageCounter returns true if the specified node 'n' is indexing
// into a coverage counter array.
func isIndexingCoverageCounter ( n ir . Node ) bool {
if n . Op ( ) != ir . OINDEX {
return false
}
ixn := n . ( * ir . IndexExpr )
if ixn . X . Op ( ) != ir . ONAME || ! ixn . X . Type ( ) . IsArray ( ) {
return false
}
nn := ixn . X . ( * ir . Name )
2024-03-05 15:52:28 +00:00
// CoverageAuxVar implies either a coverage counter or a package
// ID; since the cover tool never emits code to index into ID vars
// this is effectively testing whether nn is a coverage counter.
return nn . CoverageAuxVar ( )
2022-10-10 13:39:30 -04:00
}
// isAtomicCoverageCounterUpdate examines the specified node to
// determine whether it represents a call to sync/atomic.AddUint32 to
// increment a coverage counter.
func isAtomicCoverageCounterUpdate ( cn * ir . CallExpr ) bool {
2023-10-04 15:22:49 -07:00
if cn . Fun . Op ( ) != ir . ONAME {
2022-10-10 13:39:30 -04:00
return false
}
2023-10-04 15:22:49 -07:00
name := cn . Fun . ( * ir . Name )
2022-10-10 13:39:30 -04:00
if name . Class != ir . PFUNC {
return false
}
fn := name . Sym ( ) . Name
2022-10-28 13:21:36 -04:00
if name . Sym ( ) . Pkg . Path != "sync/atomic" ||
( fn != "AddUint32" && fn != "StoreUint32" ) {
2022-10-10 13:39:30 -04:00
return false
}
if len ( cn . Args ) != 2 || cn . Args [ 0 ] . Op ( ) != ir . OADDR {
return false
}
adn := cn . Args [ 0 ] . ( * ir . AddrExpr )
v := isIndexingCoverageCounter ( adn . X )
return v
}
2023-07-24 10:58:26 -04:00
2024-03-04 13:29:39 -05:00
func PostProcessCallSites ( profile * pgoir . Profile ) {
2023-07-24 10:58:26 -04:00
if base . Debug . DumpInlCallSiteScores != 0 {
2024-03-04 13:29:39 -05:00
budgetCallback := func ( fn * ir . Func , prof * pgoir . Profile ) ( int32 , bool ) {
2023-07-24 10:58:26 -04:00
v := inlineBudget ( fn , prof , false , false )
return v , v == inlineHotMaxBudget
}
inlheur . DumpInlCallSiteScores ( profile , budgetCallback )
}
}
2023-10-31 13:21:41 -04:00
2024-03-04 13:29:39 -05:00
func analyzeFuncProps ( fn * ir . Func , p * pgoir . Profile ) {
2023-10-31 13:21:41 -04:00
canInline := func ( fn * ir . Func ) { CanInline ( fn , p ) }
budgetForFunc := func ( fn * ir . Func ) int32 {
return inlineBudget ( fn , p , true , false )
}
inlheur . AnalyzeFunc ( fn , canInline , budgetForFunc , inlineMaxBudget )
}