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.
5 //go:generate go run mkbuiltin.go
12 "cmd/compile/internal/base"
13 "cmd/compile/internal/ir"
14 "cmd/compile/internal/logopt"
15 "cmd/compile/internal/ssa"
16 "cmd/compile/internal/types"
40 if base.Debug.Panic == 0 && base.Errors() > 0 {
41 // If we've already complained about things
42 // in the program, don't bother complaining
43 // about a panic too; let the user clean up
44 // the code and try again.
45 if err := recover(); err != nil {
54 // Target is the package being compiled.
55 var Target *ir.Package
57 // timing data for compiler phases
60 // Main parses flags and Go source files specified in the command-line
61 // arguments, type-checks the parsed Go package, compiles functions to machine
62 // code, and finally writes the compiled package definition to disk.
63 func Main(archInit func(*Arch)) {
64 timings.Start("fe", "init")
70 base.Ctxt = obj.Linknew(thearch.LinkArch)
71 base.Ctxt.DiagFunc = base.Errorf
72 base.Ctxt.DiagFlush = base.FlushErrors
73 base.Ctxt.Bso = bufio.NewWriter(os.Stdout)
75 // UseBASEntries is preferred because it shaves about 2% off build time, but LLDB, dsymutil, and dwarfdump
76 // on Darwin don't support it properly, especially since macOS 10.14 (Mojave). This is exposed as a flag
77 // to allow testing with LLVM tools on Linux, and to help with reporting this bug to the LLVM project.
78 // See bugs 31188 and 21945 (CLs 170638, 98075, 72371).
79 base.Ctxt.UseBASEntries = base.Ctxt.Headtype != objabi.Hdarwin
81 types.LocalPkg = types.NewPkg("", "")
82 types.LocalPkg.Prefix = "\"\""
84 // We won't know localpkg's height until after import
85 // processing. In the mean time, set to MaxPkgHeight to ensure
86 // height comparisons at least work until then.
87 types.LocalPkg.Height = types.MaxPkgHeight
89 // pseudo-package, for scoping
90 types.BuiltinPkg = types.NewPkg("go.builtin", "") // TODO(gri) name this package go.builtin?
91 types.BuiltinPkg.Prefix = "go.builtin" // not go%2ebuiltin
93 // pseudo-package, accessed by import "unsafe"
94 unsafepkg = types.NewPkg("unsafe", "unsafe")
96 // Pseudo-package that contains the compiler's builtin
97 // declarations for package runtime. These are declared in a
98 // separate package to avoid conflicts with package runtime's
99 // actual declarations, which may differ intentionally but
101 Runtimepkg = types.NewPkg("go.runtime", "runtime")
102 Runtimepkg.Prefix = "runtime"
104 // pseudo-packages used in symbol tables
105 itabpkg = types.NewPkg("go.itab", "go.itab")
106 itabpkg.Prefix = "go.itab" // not go%2eitab
108 itablinkpkg = types.NewPkg("go.itablink", "go.itablink")
109 itablinkpkg.Prefix = "go.itablink" // not go%2eitablink
111 trackpkg = types.NewPkg("go.track", "go.track")
112 trackpkg.Prefix = "go.track" // not go%2etrack
114 // pseudo-package used for map zero values
115 mappkg = types.NewPkg("go.map", "go.map")
116 mappkg.Prefix = "go.map"
118 // pseudo-package used for methods with anonymous receivers
119 gopkg = types.NewPkg("go", "")
121 base.DebugSSA = ssa.PhaseOption
124 // Record flags that affect the build result. (And don't
125 // record flags that don't, since that would cause spurious
126 // changes in the binary.)
127 recordFlags("B", "N", "l", "msan", "race", "shared", "dynlink", "dwarflocationlists", "dwarfbasentries", "smallframes", "spectre")
129 if !enableTrace && base.Flag.LowerT {
130 log.Fatalf("compiler not built with support for -t")
133 // Enable inlining (after recordFlags, to avoid recording the rewritten -l). For now:
134 // default: inlining on. (Flag.LowerL == 1)
135 // -l: inlining off (Flag.LowerL == 0)
136 // -l=2, -l=3: inlining on again, with extra debugging (Flag.LowerL > 1)
137 if base.Flag.LowerL <= 1 {
138 base.Flag.LowerL = 1 - base.Flag.LowerL
141 if base.Flag.SmallFrames {
142 maxStackVarSize = 128 * 1024
143 maxImplicitStackVarSize = 16 * 1024
147 base.Ctxt.DebugInfo = debuginfo
148 base.Ctxt.GenAbstractFunc = genAbstractFunc
149 base.Ctxt.DwFixups = obj.NewDwarfFixupTable(base.Ctxt)
151 // turn off inline generation if no dwarf at all
152 base.Flag.GenDwarfInl = 0
153 base.Ctxt.Flag_locationlists = false
155 if base.Ctxt.Flag_locationlists && len(base.Ctxt.Arch.DWARFRegisters) == 0 {
156 log.Fatalf("location lists requested but register mapping not available on %v", base.Ctxt.Arch.Name)
161 if base.Flag.SymABIs != "" {
162 readSymABIs(base.Flag.SymABIs, base.Ctxt.Pkgpath)
165 if ispkgin(omit_pkgs) {
166 base.Flag.Race = false
167 base.Flag.MSan = false
170 thearch.LinkArch.Init(base.Ctxt)
173 racepkg = types.NewPkg("runtime/race", "")
176 msanpkg = types.NewPkg("runtime/msan", "")
178 if base.Flag.Race || base.Flag.MSan {
182 dwarf.EnableLogging(base.Debug.DwarfInl != 0)
184 if base.Debug.SoftFloat != 0 {
185 thearch.SoftFloat = true
188 if base.Flag.JSON != "" { // parse version,destination from json logging optimization.
189 logopt.LogJsonOption(base.Flag.JSON)
192 IsIntrinsicCall = isIntrinsicCall
193 SSADumpInline = ssaDumpInline
195 ssaDump = os.Getenv("GOSSAFUNC")
196 ssaDir = os.Getenv("GOSSADIR")
198 if strings.HasSuffix(ssaDump, "+") {
199 ssaDump = ssaDump[:len(ssaDump)-1]
202 spl := strings.Split(ssaDump, ":")
209 Widthptr = thearch.LinkArch.PtrSize
210 Widthreg = thearch.LinkArch.RegSize
212 Target = new(ir.Package)
214 // initialize types package
215 // (we need to do this to break dependencies that otherwise
216 // would lead to import cycles)
217 initializeTypesPackage()
219 dclcontext = ir.PEXTERN
221 autogeneratedPos = makePos(src.NewFileBase("<autogenerated>", "<autogenerated>"), 1, 0)
223 timings.Start("fe", "loadsys")
226 timings.Start("fe", "parse")
227 lines := parseFiles(flag.Args())
230 timings.AddEvent(int64(lines), "lines")
231 if base.Flag.G != 0 && base.Flag.G < 3 {
232 // can only parse generic code for now
243 // Process top-level declarations in phases.
245 // Phase 1: const, type, and names and types of funcs.
246 // This will gather all the information about types
247 // and methods but doesn't depend on any of it.
249 // We also defer type alias declarations until phase 2
250 // to avoid cycles like #18640.
251 // TODO(gri) Remove this again once we have a fix for #25838.
253 // Don't use range--typecheck can add closures to Target.Decls.
254 timings.Start("fe", "typecheck", "top1")
255 for i := 0; i < len(Target.Decls); i++ {
257 if op := n.Op(); op != ir.ODCL && op != ir.OAS && op != ir.OAS2 && (op != ir.ODCLTYPE || !n.(*ir.Decl).Left().Name().Alias()) {
258 Target.Decls[i] = typecheck(n, ctxStmt)
262 // Phase 2: Variable assignments.
263 // To check interface assignments, depends on phase 1.
265 // Don't use range--typecheck can add closures to Target.Decls.
266 timings.Start("fe", "typecheck", "top2")
267 for i := 0; i < len(Target.Decls); i++ {
269 if op := n.Op(); op == ir.ODCL || op == ir.OAS || op == ir.OAS2 || op == ir.ODCLTYPE && n.(*ir.Decl).Left().Name().Alias() {
270 Target.Decls[i] = typecheck(n, ctxStmt)
274 // Phase 3: Type check function bodies.
275 // Don't use range--typecheck can add closures to Target.Decls.
276 timings.Start("fe", "typecheck", "func")
278 for i := 0; i < len(Target.Decls); i++ {
280 if n.Op() == ir.ODCLFUNC {
283 errorsBefore := base.Errors()
284 typecheckslice(Curfn.Body().Slice(), ctxStmt)
286 if base.Errors() > errorsBefore {
287 Curfn.PtrBody().Set(nil) // type errors; do not compile
289 // Now that we've checked whether n terminates,
290 // we can eliminate some obviously dead code.
296 // Phase 3.11: Check external declarations.
297 // TODO(mdempsky): This should be handled when type checking their
298 // corresponding ODCL nodes.
299 timings.Start("fe", "typecheck", "externdcls")
300 for i, n := range Target.Externs {
301 if n.Op() == ir.ONAME {
302 Target.Externs[i] = typecheck(Target.Externs[i], ctxExpr)
306 // Phase 3.14: With all user code type-checked, it's now safe to verify map keys
307 // and unused dot imports.
312 timings.AddEvent(fcount, "funcs")
314 if initTask := fninit(); initTask != nil {
318 // Phase 4: Decide how to capture closed variables.
319 // This needs to run before escape analysis,
320 // because variables captured by value do not escape.
321 timings.Start("fe", "capturevars")
322 for _, n := range Target.Decls {
323 if n.Op() == ir.ODCLFUNC && n.Func().OClosure != nil {
328 capturevarscomplete = true
333 timings.Start("fe", "inlining")
334 if base.Debug.TypecheckInl != 0 {
335 // Typecheck imported function bodies if Debug.l > 1,
336 // otherwise lazily when used or re-exported.
337 for _, n := range importlist {
345 if base.Flag.LowerL != 0 {
346 // Find functions that can be inlined and clone them before walk expands them.
347 visitBottomUp(Target.Decls, func(list []*ir.Func, recursive bool) {
348 numfns := numNonClosures(list)
349 for _, n := range list {
350 if !recursive || numfns > 1 {
351 // We allow inlining if there is no
352 // recursion, or the recursion cycle is
353 // across more than one function.
356 if base.Flag.LowerM > 1 {
357 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
365 for _, n := range Target.Decls {
366 if n.Op() == ir.ODCLFUNC {
367 devirtualize(n.(*ir.Func))
372 // Phase 6: Escape analysis.
373 // Required for moving heap allocations onto stack,
374 // which in turn is required by the closure implementation,
375 // which stores the addresses of stack variables into the closure.
376 // If the closure does not escape, it needs to be on the stack
377 // or else the stack copier will not update it.
378 // Large values are also moved off stack in escape analysis;
379 // because large values may contain pointers, it must happen early.
380 timings.Start("fe", "escapes")
381 escapes(Target.Decls)
383 // Collect information for go:nowritebarrierrec
384 // checking. This must happen before transformclosure.
385 // We'll do the final check after write barriers are
387 if base.Flag.CompilingRuntime {
388 EnableNoWriteBarrierRecCheck()
391 // Phase 7: Transform closure bodies to properly reference captured variables.
392 // This needs to happen before walk, because closures must be transformed
393 // before walk reaches a call of a closure.
394 timings.Start("fe", "xclosures")
395 for _, n := range Target.Decls {
396 if n.Op() == ir.ODCLFUNC && n.Func().OClosure != nil {
398 transformclosure(Curfn)
402 // Prepare for SSA compilation.
403 // This must be before peekitabs, because peekitabs
404 // can trigger function compilation.
407 // Just before compilation, compile itabs found on
408 // the right side of OCONVIFACE so that methods
409 // can be de-virtualized during compilation.
413 // Phase 8: Compile top level functions.
414 // Don't use range--walk can add functions to Target.Decls.
415 timings.Start("be", "compilefuncs")
417 for i := 0; i < len(Target.Decls); i++ {
419 if n.Op() == ir.ODCLFUNC {
420 funccompile(n.(*ir.Func))
424 timings.AddEvent(fcount, "funcs")
428 if base.Flag.CompilingRuntime {
429 // Write barriers are now known. Check the call graph.
430 NoWriteBarrierRecCheck()
433 // Finalize DWARF inline routine DIEs, then explicitly turn off
434 // DWARF inlining gen so as to avoid problems with generated
436 if base.Ctxt.DwFixups != nil {
437 base.Ctxt.DwFixups.Finalize(base.Ctxt.Pkgpath, base.Debug.DwarfInl != 0)
438 base.Ctxt.DwFixups = nil
439 base.Flag.GenDwarfInl = 0
442 // Write object data to disk.
443 timings.Start("be", "dumpobj")
445 base.Ctxt.NumberSyms()
447 if base.Flag.AsmHdr != "" {
451 // Check whether any of the functions we have compiled have gigantic stack frames.
452 sort.Slice(largeStackFrames, func(i, j int) bool {
453 return largeStackFrames[i].pos.Before(largeStackFrames[j].pos)
455 for _, large := range largeStackFrames {
456 if large.callee != 0 {
457 base.ErrorfAt(large.pos, "stack frame too large (>1GB): %d MB locals + %d MB args + %d MB callee", large.locals>>20, large.args>>20, large.callee>>20)
459 base.ErrorfAt(large.pos, "stack frame too large (>1GB): %d MB locals + %d MB args", large.locals>>20, large.args>>20)
463 if len(funcStack) != 0 {
464 base.Fatalf("funcStack is non-empty: %v", len(funcStack))
466 if len(compilequeue) != 0 {
467 base.Fatalf("%d uncompiled functions", len(compilequeue))
470 logopt.FlushLoggedOpts(base.Ctxt, base.Ctxt.Pkgpath)
476 if base.Flag.Bench != "" {
477 if err := writebench(base.Flag.Bench); err != nil {
478 log.Fatalf("cannot write benchmark data: %v", err)
484 // The linker expects an ABI0 wrapper for all cgo-exported
486 for _, prag := range Target.CgoPragmas {
488 case "cgo_export_static", "cgo_export_dynamic":
489 if symabiRefs == nil {
490 symabiRefs = make(map[string]obj.ABI)
492 symabiRefs[prag[1]] = obj.ABI0
497 // numNonClosures returns the number of functions in list which are not closures.
498 func numNonClosures(list []*ir.Func) int {
500 for _, fn := range list {
501 if fn.OClosure == nil {
508 func writebench(filename string) error {
509 f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
515 fmt.Fprintln(&buf, "commit:", objabi.Version)
516 fmt.Fprintln(&buf, "goos:", runtime.GOOS)
517 fmt.Fprintln(&buf, "goarch:", runtime.GOARCH)
518 timings.Write(&buf, "BenchmarkCompile:"+base.Ctxt.Pkgpath+":")
520 n, err := f.Write(buf.Bytes())
531 // symabiDefs and symabiRefs record the defined and referenced ABIs of
532 // symbols required by non-Go code. These are keyed by link symbol
533 // name, where the local package prefix is always `"".`
534 var symabiDefs, symabiRefs map[string]obj.ABI
536 // readSymABIs reads a symabis file that specifies definitions and
537 // references of text symbols by ABI.
539 // The symabis format is a set of lines, where each line is a sequence
540 // of whitespace-separated fields. The first field is a verb and is
541 // either "def" for defining a symbol ABI or "ref" for referencing a
542 // symbol using an ABI. For both "def" and "ref", the second field is
543 // the symbol name and the third field is the ABI name, as one of the
544 // named cmd/internal/obj.ABI constants.
545 func readSymABIs(file, myimportpath string) {
546 data, err := ioutil.ReadFile(file)
548 log.Fatalf("-symabis: %v", err)
551 symabiDefs = make(map[string]obj.ABI)
552 symabiRefs = make(map[string]obj.ABI)
555 if myimportpath != "" {
556 // Symbols in this package may be written either as
557 // "".X or with the package's import path already in
559 localPrefix = objabi.PathToPrefix(myimportpath) + "."
562 for lineNum, line := range strings.Split(string(data), "\n") {
564 line = strings.TrimSpace(line)
565 if line == "" || strings.HasPrefix(line, "#") {
569 parts := strings.Fields(line)
574 log.Fatalf(`%s:%d: invalid symabi: syntax is "%s sym abi"`, file, lineNum, parts[0])
576 sym, abistr := parts[1], parts[2]
577 abi, valid := obj.ParseABI(abistr)
579 log.Fatalf(`%s:%d: invalid symabi: unknown abi "%s"`, file, lineNum, abistr)
582 // If the symbol is already prefixed with
583 // myimportpath, rewrite it to start with ""
584 // so it matches the compiler's internal
586 if localPrefix != "" && strings.HasPrefix(sym, localPrefix) {
587 sym = `"".` + sym[len(localPrefix):]
591 if parts[0] == "def" {
592 symabiDefs[sym] = abi
594 symabiRefs[sym] = abi
597 log.Fatalf(`%s:%d: invalid symabi type "%s"`, file, lineNum, parts[0])
602 func arsize(b *bufio.Reader, name string) int {
603 var buf [ArhdrSize]byte
604 if _, err := io.ReadFull(b, buf[:]); err != nil {
607 aname := strings.Trim(string(buf[0:16]), " ")
608 if !strings.HasPrefix(aname, name) {
611 asize := strings.Trim(string(buf[48:58]), " ")
612 i, _ := strconv.Atoi(asize)
616 func isDriveLetter(b byte) bool {
617 return 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z'
620 // is this path a local name? begins with ./ or ../ or /
621 func islocalname(name string) bool {
622 return strings.HasPrefix(name, "/") ||
623 runtime.GOOS == "windows" && len(name) >= 3 && isDriveLetter(name[0]) && name[1] == ':' && name[2] == '/' ||
624 strings.HasPrefix(name, "./") || name == "." ||
625 strings.HasPrefix(name, "../") || name == ".."
628 func findpkg(name string) (file string, ok bool) {
629 if islocalname(name) {
630 if base.Flag.NoLocalImports {
634 if base.Flag.Cfg.PackageFile != nil {
635 file, ok = base.Flag.Cfg.PackageFile[name]
639 // try .a before .6. important for building libraries:
640 // if there is an array.6 in the array.a library,
641 // want to find all of array.a, not just array.6.
642 file = fmt.Sprintf("%s.a", name)
643 if _, err := os.Stat(file); err == nil {
646 file = fmt.Sprintf("%s.o", name)
647 if _, err := os.Stat(file); err == nil {
653 // local imports should be canonicalized already.
654 // don't want to see "encoding/../encoding/base64"
655 // as different from "encoding/base64".
656 if q := path.Clean(name); q != name {
657 base.Errorf("non-canonical import path %q (should be %q)", name, q)
661 if base.Flag.Cfg.PackageFile != nil {
662 file, ok = base.Flag.Cfg.PackageFile[name]
666 for _, dir := range base.Flag.Cfg.ImportDirs {
667 file = fmt.Sprintf("%s/%s.a", dir, name)
668 if _, err := os.Stat(file); err == nil {
671 file = fmt.Sprintf("%s/%s.o", dir, name)
672 if _, err := os.Stat(file); err == nil {
677 if objabi.GOROOT != "" {
680 if base.Flag.InstallSuffix != "" {
682 suffix = base.Flag.InstallSuffix
683 } else if base.Flag.Race {
686 } else if base.Flag.MSan {
691 file = fmt.Sprintf("%s/pkg/%s_%s%s%s/%s.a", objabi.GOROOT, objabi.GOOS, objabi.GOARCH, suffixsep, suffix, name)
692 if _, err := os.Stat(file); err == nil {
695 file = fmt.Sprintf("%s/pkg/%s_%s%s%s/%s.o", objabi.GOROOT, objabi.GOOS, objabi.GOARCH, suffixsep, suffix, name)
696 if _, err := os.Stat(file); err == nil {
704 // loadsys loads the definitions for the low-level runtime functions,
705 // so that the compiler can generate calls to them,
706 // but does not make them visible to user code.
713 typs := runtimeTypes()
714 for _, d := range &runtimeDecls {
715 sym := Runtimepkg.Lookup(d.name)
719 importfunc(Runtimepkg, src.NoXPos, sym, typ)
721 importvar(Runtimepkg, src.NoXPos, sym, typ)
723 base.Fatalf("unhandled declaration tag %v", d.tag)
731 // myheight tracks the local package's height based on packages
735 func importfile(f constant.Value) *types.Pkg {
736 if f.Kind() != constant.String {
737 base.Errorf("import path must be a string")
741 path_ := constant.StringVal(f)
743 base.Errorf("import path is empty")
747 if isbadimport(path_, false) {
751 // The package name main is no longer reserved,
752 // but we reserve the import path "main" to identify
753 // the main package, just as we reserve the import
754 // path "math" to identify the standard math package.
756 base.Errorf("cannot import \"main\"")
760 if base.Ctxt.Pkgpath != "" && path_ == base.Ctxt.Pkgpath {
761 base.Errorf("import %q while compiling that package (import cycle)", path_)
765 if mapped, ok := base.Flag.Cfg.ImportMap[path_]; ok {
769 if path_ == "unsafe" {
773 if islocalname(path_) {
775 base.Errorf("import path cannot be absolute path")
779 prefix := base.Ctxt.Pathname
780 if base.Flag.D != "" {
783 path_ = path.Join(prefix, path_)
785 if isbadimport(path_, true) {
790 file, found := findpkg(path_)
792 base.Errorf("can't find import: %q", path_)
796 importpkg := types.NewPkg(path_, "")
797 if importpkg.Imported {
801 importpkg.Imported = true
803 imp, err := bio.Open(file)
805 base.Errorf("can't open import: %q: %v", path_, err)
810 // check object header
811 p, err := imp.ReadString('\n')
813 base.Errorf("import %s: reading input: %v", file, err)
817 if p == "!<arch>\n" { // package archive
818 // package export block should be first
819 sz := arsize(imp.Reader, "__.PKGDEF")
821 base.Errorf("import %s: not a package file", file)
824 p, err = imp.ReadString('\n')
826 base.Errorf("import %s: reading input: %v", file, err)
831 if !strings.HasPrefix(p, "go object ") {
832 base.Errorf("import %s: not a go object file: %s", file, p)
835 q := fmt.Sprintf("%s %s %s %s\n", objabi.GOOS, objabi.GOARCH, objabi.Version, objabi.Expstring())
837 base.Errorf("import %s: object is [%s] expected [%s]", file, p[10:], q)
841 // process header lines
843 p, err = imp.ReadString('\n')
845 base.Errorf("import %s: reading input: %v", file, err)
849 break // header ends with blank line
853 // Expect $$B\n to signal binary import format.
858 c, err = imp.ReadByte()
863 c, err = imp.ReadByte()
864 if c == '$' || err != nil {
870 // get character after $$
872 c, _ = imp.ReadByte()
875 var fingerprint goobj.FingerprintType
878 base.Errorf("cannot import %s: old export format no longer supported (recompile library)", path_)
882 if base.Debug.Export != 0 {
883 fmt.Printf("importing %s (%s)\n", path_, file)
885 imp.ReadByte() // skip \n after $$B
887 c, err = imp.ReadByte()
889 base.Errorf("import %s: reading input: %v", file, err)
893 // Indexed format is distinguished by an 'i' byte,
894 // whereas previous export formats started with 'c', 'd', or 'v'.
896 base.Errorf("import %s: unexpected package format byte: %v", file, c)
899 fingerprint = iimport(importpkg, imp)
902 base.Errorf("no import in %q", path_)
906 // assume files move (get installed) so don't record the full path
907 if base.Flag.Cfg.PackageFile != nil {
908 // If using a packageFile map, assume path_ can be recorded directly.
909 base.Ctxt.AddImport(path_, fingerprint)
911 // For file "/Users/foo/go/pkg/darwin_amd64/math.a" record "math.a".
912 base.Ctxt.AddImport(file[len(file)-len(path_)-len(".a"):], fingerprint)
915 if importpkg.Height >= myheight {
916 myheight = importpkg.Height + 1
922 func pkgnotused(lineno src.XPos, path string, name string) {
923 // If the package was imported with a name other than the final
924 // import path element, show it explicitly in the error message.
925 // Note that this handles both renamed imports and imports of
926 // packages containing unconventional package declarations.
927 // Note that this uses / always, even on Windows, because Go import
928 // paths always use forward slashes.
930 if i := strings.LastIndex(elem, "/"); i >= 0 {
933 if name == "" || elem == name {
934 base.ErrorfAt(lineno, "imported and not used: %q", path)
936 base.ErrorfAt(lineno, "imported and not used: %q as %s", path, name)
940 func mkpackage(pkgname string) {
941 if types.LocalPkg.Name == "" {
943 base.Errorf("invalid package name _")
945 types.LocalPkg.Name = pkgname
947 if pkgname != types.LocalPkg.Name {
948 base.Errorf("package %s; expected %s", pkgname, types.LocalPkg.Name)
953 func clearImports() {
954 type importedPkg struct {
959 var unused []importedPkg
961 for _, s := range types.LocalPkg.Syms {
962 n := ir.AsNode(s.Def)
966 if n.Op() == ir.OPACK {
967 // throw away top-level package name left over
968 // from previous file.
969 // leave s->block set to cause redeclaration
970 // errors if a conflicting top-level name is
971 // introduced by a different file.
973 if !p.Used && base.SyntaxErrors() == 0 {
974 unused = append(unused, importedPkg{p.Pos(), p.Pkg.Path, s.Name})
980 // throw away top-level name left over
981 // from previous import . "x"
982 // We'll report errors after type checking in checkDotImports.
988 sort.Slice(unused, func(i, j int) bool { return unused[i].pos.Before(unused[j].pos) })
989 for _, pkg := range unused {
990 pkgnotused(pkg.pos, pkg.path, pkg.name)
994 func IsAlias(sym *types.Sym) bool {
995 return sym.Def != nil && sym.Def.Sym() != sym
998 // recordFlags records the specified command-line flags to be placed
999 // in the DWARF info.
1000 func recordFlags(flags ...string) {
1001 if base.Ctxt.Pkgpath == "" {
1002 // We can't record the flags if we don't know what the
1007 type BoolFlag interface {
1010 type CountFlag interface {
1013 var cmd bytes.Buffer
1014 for _, name := range flags {
1015 f := flag.Lookup(name)
1019 getter := f.Value.(flag.Getter)
1020 if getter.String() == f.DefValue {
1021 // Flag has default value, so omit it.
1024 if bf, ok := f.Value.(BoolFlag); ok && bf.IsBoolFlag() {
1025 val, ok := getter.Get().(bool)
1027 fmt.Fprintf(&cmd, " -%s", f.Name)
1031 if cf, ok := f.Value.(CountFlag); ok && cf.IsCountFlag() {
1032 val, ok := getter.Get().(int)
1034 fmt.Fprintf(&cmd, " -%s", f.Name)
1038 fmt.Fprintf(&cmd, " -%s=%v", f.Name, getter.Get())
1044 s := base.Ctxt.Lookup(dwarf.CUInfoPrefix + "producer." + base.Ctxt.Pkgpath)
1045 s.Type = objabi.SDWARFCUINFO
1046 // Sometimes (for example when building tests) we can link
1047 // together two package main archives. So allow dups.
1048 s.Set(obj.AttrDuplicateOK, true)
1049 base.Ctxt.Data = append(base.Ctxt.Data, s)
1050 s.P = cmd.Bytes()[1:]
1053 // recordPackageName records the name of the package being
1054 // compiled, so that the linker can save it in the compile unit's DIE.
1055 func recordPackageName() {
1056 s := base.Ctxt.Lookup(dwarf.CUInfoPrefix + "packagename." + base.Ctxt.Pkgpath)
1057 s.Type = objabi.SDWARFCUINFO
1058 // Sometimes (for example when building tests) we can link
1059 // together two package main archives. So allow dups.
1060 s.Set(obj.AttrDuplicateOK, true)
1061 base.Ctxt.Data = append(base.Ctxt.Data, s)
1062 s.P = []byte(types.LocalPkg.Name)
1065 // currentLang returns the current language version.
1066 func currentLang() string {
1067 return fmt.Sprintf("go1.%d", goversion.Version)
1070 // goVersionRE is a regular expression that matches the valid
1071 // arguments to the -lang flag.
1072 var goVersionRE = regexp.MustCompile(`^go([1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
1074 // A lang is a language version broken into major and minor numbers.
1079 // langWant is the desired language version set by the -lang flag.
1080 // If the -lang flag is not set, this is the zero value, meaning that
1081 // any language version is supported.
1084 // langSupported reports whether language version major.minor is
1085 // supported in a particular package.
1086 func langSupported(major, minor int, pkg *types.Pkg) bool {
1088 // TODO(mdempsky): Set Pkg for local types earlier.
1089 pkg = types.LocalPkg
1091 if pkg != types.LocalPkg {
1092 // Assume imported packages passed type-checking.
1096 if langWant.major == 0 && langWant.minor == 0 {
1099 return langWant.major > major || (langWant.major == major && langWant.minor >= minor)
1102 // checkLang verifies that the -lang flag holds a valid value, and
1103 // exits if not. It initializes data used by langSupported.
1105 if base.Flag.Lang == "" {
1110 langWant, err = parseLang(base.Flag.Lang)
1112 log.Fatalf("invalid value %q for -lang: %v", base.Flag.Lang, err)
1115 if def := currentLang(); base.Flag.Lang != def {
1116 defVers, err := parseLang(def)
1118 log.Fatalf("internal error parsing default lang %q: %v", def, err)
1120 if langWant.major > defVers.major || (langWant.major == defVers.major && langWant.minor > defVers.minor) {
1121 log.Fatalf("invalid value %q for -lang: max known version is %q", base.Flag.Lang, def)
1126 // parseLang parses a -lang option into a langVer.
1127 func parseLang(s string) (lang, error) {
1128 matches := goVersionRE.FindStringSubmatch(s)
1130 return lang{}, fmt.Errorf(`should be something like "go1.12"`)
1132 major, err := strconv.Atoi(matches[1])
1136 minor, err := strconv.Atoi(matches[2])
1140 return lang{major: major, minor: minor}, nil
1143 func initializeTypesPackage() {
1144 types.Widthptr = Widthptr
1145 types.Dowidth = dowidth
1146 types.TypeLinkSym = func(t *types.Type) *obj.LSym {
1147 return typenamesym(t).Linksym()