}
os.Exit(code)
}
+
+// To enable tracing support (-t flag), set EnableTrace to true.
+const EnableTrace = false
+
+func Compiling(pkgs []string) bool {
+ if Ctxt.Pkgpath != "" {
+ for _, p := range pkgs {
+ if Ctxt.Pkgpath == p {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+// The racewalk pass is currently handled in three parts.
+//
+// First, for flag_race, it inserts calls to racefuncenter and
+// racefuncexit at the start and end (respectively) of each
+// function. This is handled below.
+//
+// Second, during buildssa, it inserts appropriate instrumentation
+// calls immediately before each memory load or store. This is handled
+// by the (*state).instrument method in ssa.go, so here we just set
+// the Func.InstrumentBody flag as needed. For background on why this
+// is done during SSA construction rather than a separate SSA pass,
+// see issue #19054.
+//
+// Third we remove calls to racefuncenter and racefuncexit, for leaf
+// functions without instrumented operations. This is done as part of
+// ssa opt pass via special rule.
+
+// TODO(dvyukov): do not instrument initialization as writes:
+// a := make([]int, 10)
+
+// Do not instrument the following packages at all,
+// at best instrumentation would cause infinite recursion.
+var NoInstrumentPkgs = []string{
+ "runtime/internal/atomic",
+ "runtime/internal/sys",
+ "runtime/internal/math",
+ "runtime",
+ "runtime/race",
+ "runtime/msan",
+ "internal/cpu",
+}
+
+// Don't insert racefuncenterfp/racefuncexit into the following packages.
+// Memory accesses in the packages are either uninteresting or will cause false positives.
+var NoRacePkgs = []string{"sync", "sync/atomic"}
ImportMap map[string]string // set by -importmap OR -importcfg
PackageFile map[string]string // set by -importcfg; nil means not in use
SpectreIndex bool // set by -spectre=index or -spectre=all
+ // Whether we are adding any sort of code instrumentation, such as
+ // when the race detector is enabled.
+ Instrumenting bool
}
}
ErrorExit()
}
}
+
+var AutogeneratedPos src.XPos
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
-package gc
+package base
import (
"fmt"
"time"
)
-var timings Timings
+var Timer Timings
// Timings collects the execution times of labeled phases
// which are added trough a sequence of Start/Stop calls.
fmt.Printf("genhash %v %v %v\n", closure, sym, t)
}
- base.Pos = autogeneratedPos // less confusing than end of input
+ base.Pos = base.AutogeneratedPos // less confusing than end of input
dclcontext = ir.PEXTERN
// func sym(p *T, h uintptr) uintptr
// Autogenerate code for equality of structs and arrays.
- base.Pos = autogeneratedPos // less confusing than end of input
+ base.Pos = base.AutogeneratedPos // less confusing than end of input
dclcontext = ir.PEXTERN
// func sym(p, q *T) bool
func dowidth(t *types.Type) {
// Calling dowidth when typecheck tracing enabled is not safe.
// See issue #33658.
- if enableTrace && skipDowidthForTracing {
+ if base.EnableTrace && skipDowidthForTracing {
return
}
if Widthptr == 0 {
"cmd/compile/internal/ssa"
"cmd/compile/internal/types"
"cmd/internal/obj"
- "cmd/internal/src"
"sync"
)
var typecheckok bool
-// Whether we are adding any sort of code instrumentation, such as
-// when the race detector is enabled.
-var instrumenting bool
-
var nodfp *ir.Name
-var autogeneratedPos src.XPos
-
// interface to back end
type Arch struct {
savedclcontext := dclcontext
savedcurfn := Curfn
- base.Pos = autogeneratedPos
+ base.Pos = base.AutogeneratedPos
dclcontext = ir.PEXTERN
// At the moment we don't support wrapping a method, we'd need machinery
return n
}
- if instrumenting && isRuntimePkg(fn.Sym().Pkg) {
+ if base.Flag.Cfg.Instrumenting && isRuntimePkg(fn.Sym().Pkg) {
// 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,
// arguments, type-checks the parsed Go package, compiles functions to machine
// code, and finally writes the compiled package definition to disk.
func Main(archInit func(*Arch)) {
- timings.Start("fe", "init")
+ base.Timer.Start("fe", "init")
defer hidePanic()
// changes in the binary.)
recordFlags("B", "N", "l", "msan", "race", "shared", "dynlink", "dwarflocationlists", "dwarfbasentries", "smallframes", "spectre")
- if !enableTrace && base.Flag.LowerT {
+ if !base.EnableTrace && base.Flag.LowerT {
log.Fatalf("compiler not built with support for -t")
}
readSymABIs(base.Flag.SymABIs, base.Ctxt.Pkgpath)
}
- if ispkgin(omit_pkgs) {
+ if base.Compiling(base.NoInstrumentPkgs) {
base.Flag.Race = false
base.Flag.MSan = false
}
msanpkg = types.NewPkg("runtime/msan", "")
}
if base.Flag.Race || base.Flag.MSan {
- instrumenting = true
+ base.Flag.Cfg.Instrumenting = true
}
if base.Flag.Dwarf {
dwarf.EnableLogging(base.Debug.DwarfInl != 0)
NeedITab = func(t, iface *types.Type) { itabname(t, iface) }
NeedRuntimeType = addsignat // TODO(rsc): typenamesym for lock?
- autogeneratedPos = makePos(src.NewFileBase("<autogenerated>", "<autogenerated>"), 1, 0)
+ base.AutogeneratedPos = makePos(src.NewFileBase("<autogenerated>", "<autogenerated>"), 1, 0)
types.TypeLinkSym = func(t *types.Type) *obj.LSym {
return typenamesym(t).Linksym()
TypecheckInit()
// Parse input.
- timings.Start("fe", "parse")
+ base.Timer.Start("fe", "parse")
lines := parseFiles(flag.Args())
cgoSymABIs()
- timings.Stop()
- timings.AddEvent(int64(lines), "lines")
+ base.Timer.Stop()
+ base.Timer.AddEvent(int64(lines), "lines")
recordPackageName()
// Typecheck.
}
// Inlining
- timings.Start("fe", "inlining")
+ base.Timer.Start("fe", "inlining")
if base.Flag.LowerL != 0 {
InlinePackage()
}
// or else the stack copier will not update it.
// Large values are also moved off stack in escape analysis;
// because large values may contain pointers, it must happen early.
- timings.Start("fe", "escapes")
+ base.Timer.Start("fe", "escapes")
escapes(Target.Decls)
// Collect information for go:nowritebarrierrec
// Transform closure bodies to properly reference captured variables.
// This needs to happen before walk, because closures must be transformed
// before walk reaches a call of a closure.
- timings.Start("fe", "xclosures")
+ base.Timer.Start("fe", "xclosures")
for _, n := range Target.Decls {
if n.Op() == ir.ODCLFUNC {
n := n.(*ir.Func)
// Compile top level functions.
// Don't use range--walk can add functions to Target.Decls.
- timings.Start("be", "compilefuncs")
+ base.Timer.Start("be", "compilefuncs")
fcount := int64(0)
for i := 0; i < len(Target.Decls); i++ {
n := Target.Decls[i]
fcount++
}
}
- timings.AddEvent(fcount, "funcs")
+ base.Timer.AddEvent(fcount, "funcs")
compileFunctions()
}
// Write object data to disk.
- timings.Start("be", "dumpobj")
+ base.Timer.Start("be", "dumpobj")
dumpdata()
base.Ctxt.NumberSyms()
dumpobj()
base.ExitIfErrors()
base.FlushErrors()
- timings.Stop()
+ base.Timer.Stop()
if base.Flag.Bench != "" {
if err := writebench(base.Flag.Bench); err != nil {
fmt.Fprintln(&buf, "commit:", objabi.Version)
fmt.Fprintln(&buf, "goos:", runtime.GOOS)
fmt.Fprintln(&buf, "goarch:", runtime.GOARCH)
- timings.Write(&buf, "BenchmarkCompile:"+base.Ctxt.Pkgpath+":")
+ base.Timer.Write(&buf, "BenchmarkCompile:"+base.Ctxt.Pkgpath+":")
n, err := f.Write(buf.Bytes())
if err != nil {
// and rewrites it to:
// m = OMAKESLICECOPY([]T, x, s); nil
func orderMakeSliceCopy(s []ir.Node) {
- if base.Flag.N != 0 || instrumenting {
+ if base.Flag.N != 0 || base.Flag.Cfg.Instrumenting {
return
}
if len(s) < 2 || s[0] == nil || s[0].Op() != ir.OAS || s[1] == nil || s[1].Op() != ir.OCOPY {
m.Index = o.copyExpr(m.Index)
}
fallthrough
- case instrumenting && n.Op() == ir.OAS2FUNC && !ir.IsBlank(m):
+ case base.Flag.Cfg.Instrumenting && n.Op() == ir.OAS2FUNC && !ir.IsBlank(m):
t := o.newTemp(m.Type(), false)
n.Lhs[i] = t
a := ir.NewAssignStmt(base.Pos, m, t)
n.X = o.expr(n.X, nil)
n.Y = o.expr(n.Y, nil)
- if instrumenting || n.X.Op() == ir.OINDEXMAP && (n.AsOp == ir.ODIV || n.AsOp == ir.OMOD) {
+ if base.Flag.Cfg.Instrumenting || n.X.Op() == ir.OINDEXMAP && (n.AsOp == ir.ODIV || n.AsOp == ir.OMOD) {
// Rewrite m[k] op= r into m[k] = m[k] op r so
// that we can ensure that if op panics
// because r is zero, the panic happens before
t := o.markTemp()
n.Chan = o.expr(n.Chan, nil)
n.Value = o.expr(n.Value, nil)
- if instrumenting {
+ if base.Flag.Cfg.Instrumenting {
// Force copying to the stack so that (chan T)(nil) <- x
// is still instrumented as a read of x.
n.Value = o.copyExpr(n.Value)
// conversions. See copyExpr a few lines below.
needCopy = mapKeyReplaceStrConv(n.Index)
- if instrumenting {
+ if base.Flag.Cfg.Instrumenting {
// Race detector needs the copy.
needCopy = true
}
// together. See golang.org/issue/15329.
o.init(call)
o.call(call)
- if lhs == nil || lhs.Op() != ir.ONAME || instrumenting {
+ if lhs == nil || lhs.Op() != ir.ONAME || base.Flag.Cfg.Instrumenting {
return o.copyExpr(n)
}
} else {
o.call(n)
}
- if lhs == nil || lhs.Op() != ir.ONAME || instrumenting {
+ if lhs == nil || lhs.Op() != ir.ONAME || base.Flag.Cfg.Instrumenting {
return o.copyExpr(n)
}
return n
case ir.ODOTTYPE, ir.ODOTTYPE2:
n := n.(*ir.TypeAssertExpr)
n.X = o.expr(n.X, nil)
- if !isdirectiface(n.Type()) || instrumenting {
+ if !isdirectiface(n.Type()) || base.Flag.Cfg.Instrumenting {
return o.copyExprClear(n)
}
return n
"cmd/internal/sys"
)
-// The racewalk pass is currently handled in three parts.
-//
-// First, for flag_race, it inserts calls to racefuncenter and
-// racefuncexit at the start and end (respectively) of each
-// function. This is handled below.
-//
-// Second, during buildssa, it inserts appropriate instrumentation
-// calls immediately before each memory load or store. This is handled
-// by the (*state).instrument method in ssa.go, so here we just set
-// the Func.InstrumentBody flag as needed. For background on why this
-// is done during SSA construction rather than a separate SSA pass,
-// see issue #19054.
-//
-// Third we remove calls to racefuncenter and racefuncexit, for leaf
-// functions without instrumented operations. This is done as part of
-// ssa opt pass via special rule.
-
-// TODO(dvyukov): do not instrument initialization as writes:
-// a := make([]int, 10)
-
-// Do not instrument the following packages at all,
-// at best instrumentation would cause infinite recursion.
-var omit_pkgs = []string{
- "runtime/internal/atomic",
- "runtime/internal/sys",
- "runtime/internal/math",
- "runtime",
- "runtime/race",
- "runtime/msan",
- "internal/cpu",
-}
-
-// Don't insert racefuncenterfp/racefuncexit into the following packages.
-// Memory accesses in the packages are either uninteresting or will cause false positives.
-var norace_inst_pkgs = []string{"sync", "sync/atomic"}
-
-func ispkgin(pkgs []string) bool {
- if base.Ctxt.Pkgpath != "" {
- for _, p := range pkgs {
- if base.Ctxt.Pkgpath == p {
- return true
- }
- }
- }
-
- return false
-}
-
func instrument(fn *ir.Func) {
if fn.Pragma&ir.Norace != 0 || (fn.Sym().Linksym() != nil && fn.Sym().Linksym().ABIWrapper()) {
return
}
- if !base.Flag.Race || !ispkgin(norace_inst_pkgs) {
+ if !base.Flag.Race || !base.Compiling(base.NoRacePkgs) {
fn.SetInstrumentBody(true)
}
//
// where == for keys of map m is reflexive.
func isMapClear(n *ir.RangeStmt) bool {
- if base.Flag.N != 0 || instrumenting {
+ if base.Flag.N != 0 || base.Flag.Cfg.Instrumenting {
return false
}
//
// Parameters are as in walkrange: "for v1, v2 = range a".
func arrayClear(loop *ir.RangeStmt, v1, v2, a ir.Node) ir.Node {
- if base.Flag.N != 0 || instrumenting {
+ if base.Flag.N != 0 || base.Flag.Cfg.Instrumenting {
return nil
}
return nil
}
- if instrumenting {
+ if base.Flag.Cfg.Instrumenting {
// These appear to be fine, but they fail the
// integer constraint below, so okay them here.
// Sample non-integer conversion: map[string]string -> *uint8
}
/******** runtime ********/
- if !instrumenting {
+ if !base.Flag.Cfg.Instrumenting {
add("runtime", "slicebytetostringtmp",
func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
// Compiler frontend optimizations emit OBYTES2STRTMP nodes
case ir.OANDAND, ir.OOROR:
// hard with instrumented code
n := n.(*ir.LogicalExpr)
- if instrumenting {
+ if base.Flag.Cfg.Instrumenting {
return true
}
return n.X.HasCall() || n.Y.HasCall()
return
}
- base.Pos = autogeneratedPos
+ base.Pos = base.AutogeneratedPos
dclcontext = ir.PEXTERN
tfn := ir.NewFuncType(base.Pos,
// the TOC to the appropriate value for that module. But if it returns
// directly to the wrapper's caller, nothing will reset it to the correct
// value for that function.
- if !instrumenting && rcvr.IsPtr() && methodrcvr.IsPtr() && method.Embedded != 0 && !isifacemethod(method.Type) && !(thearch.LinkArch.Name == "ppc64le" && base.Ctxt.Flag_dynlink) {
+ if !base.Flag.Cfg.Instrumenting && rcvr.IsPtr() && methodrcvr.IsPtr() && method.Embedded != 0 && !isifacemethod(method.Type) && !(thearch.LinkArch.Name == "ppc64le" && base.Ctxt.Flag_dynlink) {
// generate tail call: adjust pointer receiver and jump to embedded method.
left := dot.X // skip final .M
if !left.Type().IsPtr() {
types.Dowidth = dowidth
initUniverse()
dclcontext = ir.PEXTERN
- timings.Start("fe", "loadsys")
+ base.Timer.Start("fe", "loadsys")
loadsys()
}
// TODO(gri) Remove this again once we have a fix for #25838.
// Don't use range--typecheck can add closures to Target.Decls.
- timings.Start("fe", "typecheck", "top1")
+ base.Timer.Start("fe", "typecheck", "top1")
for i := 0; i < len(Target.Decls); i++ {
n := Target.Decls[i]
if op := n.Op(); op != ir.ODCL && op != ir.OAS && op != ir.OAS2 && (op != ir.ODCLTYPE || !n.(*ir.Decl).X.Name().Alias()) {
// To check interface assignments, depends on phase 1.
// Don't use range--typecheck can add closures to Target.Decls.
- timings.Start("fe", "typecheck", "top2")
+ base.Timer.Start("fe", "typecheck", "top2")
for i := 0; i < len(Target.Decls); i++ {
n := Target.Decls[i]
if op := n.Op(); op == ir.ODCL || op == ir.OAS || op == ir.OAS2 || op == ir.ODCLTYPE && n.(*ir.Decl).X.Name().Alias() {
// Phase 3: Type check function bodies.
// Don't use range--typecheck can add closures to Target.Decls.
- timings.Start("fe", "typecheck", "func")
+ base.Timer.Start("fe", "typecheck", "func")
var fcount int64
for i := 0; i < len(Target.Decls); i++ {
n := Target.Decls[i]
// Phase 4: Check external declarations.
// TODO(mdempsky): This should be handled when type checking their
// corresponding ODCL nodes.
- timings.Start("fe", "typecheck", "externdcls")
+ base.Timer.Start("fe", "typecheck", "externdcls")
for i, n := range Target.Externs {
if n.Op() == ir.ONAME {
Target.Externs[i] = typecheck(Target.Externs[i], ctxExpr)
// Phase 6: Decide how to capture closed variables.
// This needs to run before escape analysis,
// because variables captured by value do not escape.
- timings.Start("fe", "capturevars")
+ base.Timer.Start("fe", "capturevars")
for _, n := range Target.Decls {
if n.Op() == ir.ODCLFUNC {
n := n.(*ir.Func)
}
}
-// To enable tracing support (-t flag), set enableTrace to true.
-const enableTrace = false
-
var traceIndent []byte
var skipDowidthForTracing bool
}
// only trace if there's work to do
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("resolve", n)(&res)
}
}
// only trace if there's work to do
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheck", n)(&res)
}
// typecheck1 should ONLY be called from typecheck.
func typecheck1(n ir.Node, top int) (res ir.Node) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheck1", n)(&res)
}
// typecheckMethodExpr checks selector expressions (ODOT) where the
// base expression is a type expression (OTYPE).
func typecheckMethodExpr(n *ir.SelectorExpr) (res ir.Node) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckMethodExpr", n)(&res)
}
// The result of typecheckcomplit MUST be assigned back to n, e.g.
// n.Left = typecheckcomplit(n.Left)
func typecheckcomplit(n *ir.CompLitExpr) (res ir.Node) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckcomplit", n)(&res)
}
// if this assignment is the definition of a var on the left side,
// fill in the var's type.
func typecheckas(n *ir.AssignStmt) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckas", n)(nil)
}
}
func typecheckas2(n *ir.AssignListStmt) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckas2", n)(nil)
}
// To be called by typecheck, not directly.
// (Call typecheckFunc instead.)
func typecheckfunc(n *ir.Func) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckfunc", n)(nil)
}
}
func typecheckdeftype(n *ir.Name) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckdeftype", n)(nil)
}
}
func typecheckdef(n ir.Node) {
- if enableTrace && base.Flag.LowerT {
+ if base.EnableTrace && base.Flag.LowerT {
defer tracePrint("typecheckdef", n)(nil)
}
ir.DumpList(s, Curfn.Enter)
}
- if instrumenting {
+ if base.Flag.Cfg.Instrumenting {
instrument(fn)
}
}
return as
}
- if !instrumenting && isZero(as.Y) {
+ if !base.Flag.Cfg.Instrumenting && isZero(as.Y) {
return as
}
panic("unreachable")
case ir.OCOPY:
- return copyany(n.(*ir.BinaryExpr), init, instrumenting && !base.Flag.CompilingRuntime)
+ return copyany(n.(*ir.BinaryExpr), init, base.Flag.Cfg.Instrumenting && !base.Flag.CompilingRuntime)
case ir.OCLOSE:
// cannot use chanfn - closechan takes any, not chan any
case ir.OBYTES2STRTMP:
n := n.(*ir.ConvExpr)
n.X = walkexpr(n.X, init)
- if !instrumenting {
+ if !base.Flag.Cfg.Instrumenting {
// Let the backend handle OBYTES2STRTMP directly
// to avoid a function call to slicebytetostringtmp.
return n
} else {
t = params.Field(i).Type
}
- if instrumenting || fncall(arg, t) {
+ if base.Flag.Cfg.Instrumenting || fncall(arg, t) {
// make assignment of fncall to tempAt
tmp := temp(t)
a := convas(ir.NewAssignStmt(base.Pos, tmp, arg), init)
ptr1, len1 := backingArrayPtrLen(cheapexpr(slice, &nodes))
ptr2, len2 := backingArrayPtrLen(l2)
ncopy = mkcall1(fn, types.Types[types.TINT], &nodes, typename(elemtype), ptr1, len1, ptr2, len2)
- } else if instrumenting && !base.Flag.CompilingRuntime {
+ } else if base.Flag.Cfg.Instrumenting && !base.Flag.CompilingRuntime {
// rely on runtime to instrument:
// copy(s[len(l1):], l2)
// l2 can be a slice or string.
// isAppendOfMake reports whether n is of the form append(x , make([]T, y)...).
// isAppendOfMake assumes n has already been typechecked.
func isAppendOfMake(n ir.Node) bool {
- if base.Flag.N != 0 || instrumenting {
+ if base.Flag.N != 0 || base.Flag.Cfg.Instrumenting {
return false
}
// General case, with no function calls left as arguments.
// Leave for gen, except that instrumentation requires old form.
- if !instrumenting || base.Flag.CompilingRuntime {
+ if !base.Flag.Cfg.Instrumenting || base.Flag.CompilingRuntime {
return n
}
// isRuneCount reports whether n is of the form len([]rune(string)).
// These are optimized into a call to runtime.countrunes.
func isRuneCount(n ir.Node) bool {
- return base.Flag.N == 0 && !instrumenting && n.Op() == ir.OLEN && n.(*ir.UnaryExpr).X.Op() == ir.OSTR2RUNES
+ return base.Flag.N == 0 && !base.Flag.Cfg.Instrumenting && n.Op() == ir.OLEN && n.(*ir.UnaryExpr).X.Op() == ir.OSTR2RUNES
}
func walkCheckPtrAlignment(n *ir.ConvExpr, init *ir.Nodes, count ir.Node) ir.Node {