Source file src/cmd/compile/internal/gc/main.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package gc
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"cmd/compile/internal/base"
    11  	"cmd/compile/internal/bloop"
    12  	"cmd/compile/internal/coverage"
    13  	"cmd/compile/internal/deadlocals"
    14  	"cmd/compile/internal/dwarfgen"
    15  	"cmd/compile/internal/escape"
    16  	"cmd/compile/internal/inline"
    17  	"cmd/compile/internal/inline/interleaved"
    18  	"cmd/compile/internal/ir"
    19  	"cmd/compile/internal/logopt"
    20  	"cmd/compile/internal/loopvar"
    21  	"cmd/compile/internal/noder"
    22  	"cmd/compile/internal/pgoir"
    23  	"cmd/compile/internal/pkginit"
    24  	"cmd/compile/internal/reflectdata"
    25  	"cmd/compile/internal/rewriteresults"
    26  	"cmd/compile/internal/rttype"
    27  	"cmd/compile/internal/slice"
    28  	"cmd/compile/internal/ssacompile"
    29  	"cmd/compile/internal/ssagen"
    30  	"cmd/compile/internal/staticinit"
    31  	"cmd/compile/internal/typecheck"
    32  	"cmd/compile/internal/types"
    33  	"cmd/internal/dwarf"
    34  	"cmd/internal/obj"
    35  	"cmd/internal/objabi"
    36  	"cmd/internal/src"
    37  	"cmd/internal/telemetry/counter"
    38  	"flag"
    39  	"fmt"
    40  	"internal/buildcfg"
    41  	"log"
    42  	"os"
    43  	"runtime"
    44  )
    45  
    46  // handlePanic ensures that we print out an "internal compiler error" for any panic
    47  // or runtime exception during front-end compiler processing (unless there have
    48  // already been some compiler errors). It may also be invoked from the explicit panic in
    49  // hcrash(), in which case, we pass the panic on through.
    50  func handlePanic() {
    51  	ir.CloseHTMLWriters()
    52  	noder.CloseHTMLWriters()
    53  	if err := recover(); err != nil {
    54  		if err == "-h" {
    55  			// Force real panic now with -h option (hcrash) - the error
    56  			// information will have already been printed.
    57  			panic(err)
    58  		}
    59  		base.Fatalf("panic: %v", err)
    60  	}
    61  }
    62  
    63  // Main parses flags and Go source files specified in the command-line
    64  // arguments, type-checks the parsed Go package, compiles functions to machine
    65  // code, and finally writes the compiled package definition to disk.
    66  func Main(archInit func(*ssagen.ArchInfo)) {
    67  	base.Timer.Start("fe", "init")
    68  	counter.Open()
    69  	counter.Inc("compile/invocations")
    70  
    71  	defer handlePanic()
    72  
    73  	archInit(&ssagen.Arch)
    74  
    75  	base.Ctxt = obj.Linknew(ssagen.Arch.LinkArch)
    76  	base.Ctxt.DiagFunc = base.Errorf
    77  	base.Ctxt.DiagFlush = base.FlushErrors
    78  	base.Ctxt.Bso = bufio.NewWriter(os.Stdout)
    79  
    80  	// UseBASEntries is preferred because it shaves about 2% off build time, but LLDB, dsymutil, and dwarfdump
    81  	// on Darwin don't support it properly, especially since macOS 10.14 (Mojave).  This is exposed as a flag
    82  	// to allow testing with LLVM tools on Linux, and to help with reporting this bug to the LLVM project.
    83  	// See bugs 31188 and 21945 (CLs 170638, 98075, 72371).
    84  	base.Ctxt.UseBASEntries = base.Ctxt.Headtype != objabi.Hdarwin
    85  
    86  	base.DebugSSA = ssacompile.PhaseOption
    87  	base.ParseFlags()
    88  
    89  	if flagGCStart := base.Debug.GCStart; flagGCStart > 0 || // explicit flags overrides environment variable disable of GC boost
    90  		os.Getenv("GOGC") == "" && os.Getenv("GOMEMLIMIT") == "" && base.Flag.LowerC != 1 { // explicit GC knobs or no concurrency implies default heap
    91  		startHeapMB := int64(128)
    92  		if flagGCStart > 0 {
    93  			startHeapMB = int64(flagGCStart)
    94  		}
    95  		base.AdjustStartingHeap(uint64(startHeapMB)<<20, 0, 0, 0, base.Debug.GCAdjust == 1)
    96  	}
    97  
    98  	types.LocalPkg = types.NewPkg(base.Ctxt.Pkgpath, "")
    99  
   100  	// pseudo-package, for scoping
   101  	types.BuiltinPkg = types.NewPkg("go.builtin", "") // TODO(gri) name this package go.builtin?
   102  	types.BuiltinPkg.Prefix = "go:builtin"
   103  
   104  	// pseudo-package, accessed by import "unsafe"
   105  	types.UnsafePkg = types.NewPkg("unsafe", "unsafe")
   106  
   107  	// Pseudo-package that contains the compiler's builtin
   108  	// declarations for package runtime. These are declared in a
   109  	// separate package to avoid conflicts with package runtime's
   110  	// actual declarations, which may differ intentionally but
   111  	// insignificantly.
   112  	ir.Pkgs.Runtime = types.NewPkg("go.runtime", "runtime")
   113  	ir.Pkgs.Runtime.Prefix = "runtime"
   114  
   115  	// Pseudo-package that contains the compiler's builtin
   116  	// declarations for maps.
   117  	ir.Pkgs.InternalMaps = types.NewPkg("go.internal/runtime/maps", "internal/runtime/maps")
   118  	ir.Pkgs.InternalMaps.Prefix = "internal/runtime/maps"
   119  
   120  	// pseudo-packages used in symbol tables
   121  	ir.Pkgs.Itab = types.NewPkg("go.itab", "go.itab")
   122  	ir.Pkgs.Itab.Prefix = "go:itab"
   123  
   124  	// pseudo-package used for methods with anonymous receivers
   125  	ir.Pkgs.Go = types.NewPkg("go", "")
   126  
   127  	// pseudo-package for use with code coverage instrumentation.
   128  	ir.Pkgs.Coverage = types.NewPkg("go.coverage", "runtime/coverage")
   129  	ir.Pkgs.Coverage.Prefix = "runtime/coverage"
   130  
   131  	// Record flags that affect the build result. (And don't
   132  	// record flags that don't, since that would cause spurious
   133  	// changes in the binary.)
   134  	dwarfgen.RecordFlags("B", "N", "l", "msan", "race", "asan", "shared", "dynlink", "dwarf", "dwarflocationlists", "dwarfbasentries", "smallframes", "spectre")
   135  
   136  	if !base.EnableTrace && base.Flag.LowerT {
   137  		log.Fatalf("compiler not built with support for -t")
   138  	}
   139  
   140  	// Enable inlining (after RecordFlags, to avoid recording the rewritten -l).  For now:
   141  	//	default: inlining on.  (Flag.LowerL == 1)
   142  	//	-l: inlining off  (Flag.LowerL == 0)
   143  	//	-l=2, -l=3: inlining on again, with extra debugging (Flag.LowerL > 1)
   144  	if base.Flag.LowerL <= 1 {
   145  		base.Flag.LowerL = 1 - base.Flag.LowerL
   146  	}
   147  
   148  	if base.Flag.SmallFrames {
   149  		ir.MaxStackVarSize = 64 * 1024
   150  		ir.MaxImplicitStackVarSize = 16 * 1024
   151  	}
   152  
   153  	if base.Flag.Dwarf {
   154  		base.Ctxt.DebugInfo = dwarfgen.Info
   155  		base.Ctxt.GenAbstractFunc = dwarfgen.AbstractFunc
   156  		base.Ctxt.DwFixups = obj.NewDwarfFixupTable(base.Ctxt)
   157  	} else {
   158  		// turn off inline generation if no dwarf at all
   159  		base.Flag.GenDwarfInl = 0
   160  		base.Ctxt.Flag_locationlists = false
   161  	}
   162  	if base.Ctxt.Flag_locationlists && len(base.Ctxt.Arch.DWARFRegisters) == 0 {
   163  		log.Fatalf("location lists requested but register mapping not available on %v", base.Ctxt.Arch.Name)
   164  	}
   165  
   166  	types.ParseLangFlag()
   167  
   168  	symABIs := ssagen.NewSymABIs()
   169  	if base.Flag.SymABIs != "" {
   170  		symABIs.ReadSymABIs(base.Flag.SymABIs)
   171  	}
   172  
   173  	if objabi.LookupPkgSpecial(base.Ctxt.Pkgpath).NoInstrument {
   174  		base.Flag.Race = false
   175  		base.Flag.MSan = false
   176  		base.Flag.ASan = false
   177  	}
   178  
   179  	ssagen.Arch.LinkArch.Init(base.Ctxt)
   180  	startProfile()
   181  	if base.Flag.Race || base.Flag.MSan || base.Flag.ASan {
   182  		base.Flag.Cfg.Instrumenting = true
   183  	}
   184  	if base.Flag.Dwarf {
   185  		dwarf.EnableLogging(base.Debug.DwarfInl != 0)
   186  	}
   187  	if base.Debug.SoftFloat != 0 {
   188  		ssagen.Arch.SoftFloat = true
   189  	}
   190  
   191  	if base.Flag.JSON != "" { // parse version,destination from json logging optimization.
   192  		logopt.LogJsonOption(base.Flag.JSON)
   193  	}
   194  
   195  	ir.EscFmt = escape.Fmt
   196  	ir.IsIntrinsicCall = ssagen.IsIntrinsicCall
   197  	ir.IsIntrinsicSym = ssagen.IsIntrinsicSym
   198  	inline.SSADumpInline = ssagen.DumpInline
   199  	ssagen.InitEnv()
   200  
   201  	types.PtrSize = ssagen.Arch.LinkArch.PtrSize
   202  	types.RegSize = ssagen.Arch.LinkArch.RegSize
   203  	types.MaxWidth = ssagen.Arch.MAXWIDTH
   204  
   205  	typecheck.Target = new(ir.Package)
   206  
   207  	base.AutogeneratedPos = makePos(src.NewFileBase("<autogenerated>", "<autogenerated>"), 1, 0)
   208  
   209  	typecheck.InitUniverse()
   210  	typecheck.InitRuntime()
   211  	rttype.Init()
   212  
   213  	// Some intrinsics (notably, the simd intrinsics) mention
   214  	// types "eagerly", thus ssagen must be initialized AFTER
   215  	// the type system is ready.
   216  	ssagen.InitTables()
   217  
   218  	// Parse and typecheck input.
   219  	noder.LoadPackage(flag.Args())
   220  
   221  	// As a convenience to users (toolchain maintainers, in particular),
   222  	// when compiling a package named "main", we default the package
   223  	// path to "main" if the -p flag was not specified.
   224  	if base.Ctxt.Pkgpath == obj.UnlinkablePkg && types.LocalPkg.Name == "main" {
   225  		base.Ctxt.Pkgpath = "main"
   226  		types.LocalPkg.Path = "main"
   227  		types.LocalPkg.Prefix = "main"
   228  	}
   229  
   230  	dwarfgen.RecordPackageName()
   231  
   232  	// Prepare for backend processing.
   233  	ssagen.InitConfig(ssacompile.NewConfig(ssagen.Arch.SoftFloat))
   234  
   235  	// Apply coverage fixups, if applicable.
   236  	coverage.Fixup()
   237  
   238  	// Read profile file and build profile-graph and weighted-call-graph.
   239  	base.Timer.Start("fe", "pgo-load-profile")
   240  	var profile *pgoir.Profile
   241  	if base.Flag.PgoProfile != "" {
   242  		var err error
   243  		profile, err = pgoir.New(base.Flag.PgoProfile)
   244  		if err != nil {
   245  			log.Fatalf("%s: PGO error: %v", base.Flag.PgoProfile, err)
   246  		}
   247  	}
   248  
   249  	for _, fn := range typecheck.Target.Funcs {
   250  		if ir.MatchAstDump(fn, "start") {
   251  			ir.AstDump(fn, "start, "+ir.FuncName(fn))
   252  		}
   253  	}
   254  
   255  	// Apply bloop markings.
   256  	bloop.Walk(typecheck.Target)
   257  
   258  	// Interleaved devirtualization and inlining.
   259  	base.Timer.Start("fe", "devirtualize-and-inline")
   260  	interleaved.DevirtualizeAndInlinePackage(typecheck.Target, profile)
   261  
   262  	for _, fn := range typecheck.Target.Funcs {
   263  		if ir.MatchAstDump(fn, "devirtualize-and-inline") {
   264  			ir.AstDump(fn, "devirtualize-and-inline, "+ir.FuncName(fn))
   265  		}
   266  	}
   267  
   268  	noder.MakeWrappers(typecheck.Target) // must happen after inlining
   269  
   270  	// Get variable capture right in for loops.
   271  	var transformed []loopvar.VarAndLoop
   272  	for _, fn := range typecheck.Target.Funcs {
   273  		transformed = append(transformed, loopvar.ForCapture(fn)...)
   274  	}
   275  	ir.CurFunc = nil
   276  
   277  	// Build init task, if needed.
   278  	pkginit.MakeTask()
   279  
   280  	// Generate ABI wrappers. Must happen before escape analysis
   281  	// and doesn't benefit from dead-coding or inlining.
   282  	symABIs.GenABIWrappers()
   283  
   284  	deadlocals.Funcs(typecheck.Target.Funcs)
   285  
   286  	// Escape analysis.
   287  	// Required for moving heap allocations onto stack,
   288  	// which in turn is required by the closure implementation,
   289  	// which stores the addresses of stack variables into the closure.
   290  	// If the closure does not escape, it needs to be on the stack
   291  	// or else the stack copier will not update it.
   292  	// Large values are also moved off stack in escape analysis;
   293  	// because large values may contain pointers, it must happen early.
   294  	base.Timer.Start("fe", "escapes")
   295  	escape.Funcs(typecheck.Target.Funcs)
   296  
   297  	rewriteresults.Funcs(typecheck.Target.Funcs)
   298  
   299  	slice.Funcs(typecheck.Target.Funcs)
   300  
   301  	loopvar.LogTransformations(transformed)
   302  
   303  	// Collect information for go:nowritebarrierrec
   304  	// checking. This must happen before transforming closures during Walk
   305  	// We'll do the final check after write barriers are
   306  	// inserted.
   307  	if base.Flag.CompilingRuntime {
   308  		ssagen.EnableNoWriteBarrierRecCheck()
   309  	}
   310  
   311  	ir.CurFunc = nil
   312  
   313  	reflectdata.WriteBasicTypes()
   314  
   315  	// Compile top-level declarations.
   316  	//
   317  	// There are cyclic dependencies between all of these phases, so we
   318  	// need to iterate all of them until we reach a fixed point.
   319  	base.Timer.Start("be", "compilefuncs")
   320  	for nextFunc, nextExtern := 0, 0; ; {
   321  		reflectdata.WriteRuntimeTypes()
   322  
   323  		if nextExtern < len(typecheck.Target.Externs) {
   324  			switch n := typecheck.Target.Externs[nextExtern]; n.Op() {
   325  			case ir.ONAME:
   326  				dumpGlobal(n)
   327  			case ir.OLITERAL:
   328  				dumpGlobalConst(n)
   329  			case ir.OTYPE:
   330  				reflectdata.NeedRuntimeType(n.Type())
   331  			}
   332  			nextExtern++
   333  			continue
   334  		}
   335  
   336  		if nextFunc < len(typecheck.Target.Funcs) {
   337  			enqueueFunc(typecheck.Target.Funcs[nextFunc], symABIs)
   338  			nextFunc++
   339  			continue
   340  		}
   341  
   342  		// The SSA backend supports using multiple goroutines, so keep it
   343  		// as late as possible to maximize how much work we can batch and
   344  		// process concurrently.
   345  		if len(compilequeue) != 0 {
   346  			compileFunctions(profile)
   347  			continue
   348  		}
   349  
   350  		// Finalize DWARF inline routine DIEs, then explicitly turn off
   351  		// further DWARF inlining generation to avoid problems with
   352  		// generated method wrappers.
   353  		//
   354  		// Note: The DWARF fixup code for inlined calls currently doesn't
   355  		// allow multiple invocations, so we intentionally run it just
   356  		// once after everything else. Worst case, some generated
   357  		// functions have slightly larger DWARF DIEs.
   358  		if base.Ctxt.DwFixups != nil {
   359  			base.Ctxt.DwFixups.Finalize(base.Ctxt.Pkgpath, base.Debug.DwarfInl != 0)
   360  			base.Ctxt.DwFixups = nil
   361  			base.Flag.GenDwarfInl = 0
   362  			continue // may have called reflectdata.TypeLinksym (#62156)
   363  		}
   364  
   365  		break
   366  	}
   367  
   368  	base.Timer.AddEvent(int64(len(typecheck.Target.Funcs)), "funcs")
   369  
   370  	if base.Flag.CompilingRuntime {
   371  		// Write barriers are now known. Check the call graph.
   372  		ssagen.NoWriteBarrierRecCheck()
   373  	}
   374  
   375  	// Add keep relocations for global maps.
   376  	if base.Debug.WrapGlobalMapCtl != 1 {
   377  		staticinit.AddKeepRelocations()
   378  	}
   379  
   380  	// Write object data to disk.
   381  	base.Timer.Start("be", "dumpobj")
   382  	dumpdata()
   383  	base.Ctxt.NumberSyms()
   384  	dumpobj()
   385  	if base.Flag.AsmHdr != "" {
   386  		dumpasmhdr()
   387  	}
   388  
   389  	ssagen.CheckLargeStacks()
   390  	typecheck.CheckFuncStack()
   391  
   392  	if len(compilequeue) != 0 {
   393  		base.Fatalf("%d uncompiled functions", len(compilequeue))
   394  	}
   395  
   396  	logopt.FlushLoggedOpts(base.Ctxt, base.Ctxt.Pkgpath)
   397  	base.ExitIfErrors()
   398  
   399  	base.FlushErrors()
   400  	base.Timer.Stop()
   401  
   402  	if base.Flag.Bench != "" {
   403  		if err := writebench(base.Flag.Bench); err != nil {
   404  			log.Fatalf("cannot write benchmark data: %v", err)
   405  		}
   406  	}
   407  }
   408  
   409  func writebench(filename string) error {
   410  	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
   411  	if err != nil {
   412  		return err
   413  	}
   414  
   415  	var buf bytes.Buffer
   416  	fmt.Fprintln(&buf, "commit:", buildcfg.Version)
   417  	fmt.Fprintln(&buf, "goos:", runtime.GOOS)
   418  	fmt.Fprintln(&buf, "goarch:", runtime.GOARCH)
   419  	base.Timer.Write(&buf, "BenchmarkCompile:"+base.Ctxt.Pkgpath+":")
   420  
   421  	n, err := f.Write(buf.Bytes())
   422  	if err != nil {
   423  		return err
   424  	}
   425  	if n != buf.Len() {
   426  		panic("bad writer")
   427  	}
   428  
   429  	return f.Close()
   430  }
   431  
   432  func makePos(b *src.PosBase, line, col uint) src.XPos {
   433  	return base.Ctxt.PosTable.XPos(src.MakePos(b, line, col))
   434  }
   435  

View as plain text