3 // Copyright 2021 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
17 "cmd/compile/internal/base"
18 "cmd/compile/internal/inline"
19 "cmd/compile/internal/ir"
20 "cmd/compile/internal/typecheck"
21 "cmd/compile/internal/types"
22 "cmd/compile/internal/types2"
26 // localPkgReader holds the package reader used for reading the local
27 // package. It exists so the unified IR linker can refer back to it
29 var localPkgReader *pkgReader
31 // unified construct the local package's IR from syntax's AST.
33 // The pipeline contains 2 steps:
35 // (1) Generate package export data "stub".
37 // (2) Generate package IR from package export data.
39 // The package data "stub" at step (1) contains everything from the local package,
40 // but nothing that have been imported. When we're actually writing out export data
41 // to the output files (see writeNewExport function), we run the "linker", which does
44 // + Updates compiler extensions data (e.g., inlining cost, escape analysis results).
46 // + Handles re-exporting any transitive dependencies.
48 // + Prunes out any unnecessary details (e.g., non-inlineable functions, because any
49 // downstream importers only care about inlinable functions).
51 // The source files are typechecked twice, once before writing export data
52 // using types2 checker, once after read export data using gc/typecheck.
53 // This duplication of work will go away once we always use types2 checker,
54 // we can remove the gc/typecheck pass. The reason it is still here:
56 // + It reduces engineering costs in maintaining a fork of typecheck
57 // (e.g., no need to backport fixes like CL 327651).
59 // + It makes it easier to pass toolstash -cmp.
61 // + Historically, we would always re-run the typechecker after import, even though
62 // we know the imported data is valid. It's not ideal, but also not causing any
65 // + There's still transformation that being done during gc/typecheck, like rewriting
66 // multi-valued function call, or transform ir.OINDEX -> ir.OINDEXMAP.
68 // Using syntax+types2 tree, which already has a complete representation of generics,
69 // the unified IR has the full typed AST for doing introspection during step (1).
70 // In other words, we have all necessary information to build the generic IR form
71 // (see writer.captureVars for an example).
72 func unified(noders []*noder) {
73 inline.NewInline = InlineCall
76 writeNewExportFunc = writeNewExport
77 } else if base.Flag.G != 0 {
78 base.Errorf("cannot use -G and -d=quirksmode together")
81 newReadImportFunc = func(data string, pkg1 *types.Pkg, check *types2.Checker, packages map[string]*types2.Package) (pkg2 *types2.Package, err error) {
82 pr := newPkgDecoder(pkg1.Path, data)
84 // Read package descriptors for both types2 and compiler backend.
85 readPackage(newPkgReader(pr), pkg1)
86 pkg2 = readPackage2(check, packages, pr)
90 data := writePkgStub(noders)
92 // We already passed base.Flag.Lang to types2 to handle validating
93 // the user's source code. Bump it up now to the current version and
94 // re-parse, so typecheck doesn't complain if we construct IR that
95 // utilizes newer Go features.
96 base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
99 assert(types.LocalPkg.Path == "")
100 types.LocalPkg.Height = 0 // reset so pkgReader.pkgIdx doesn't complain
101 target := typecheck.Target
103 typecheck.TypecheckAllowed = true
105 localPkgReader = newPkgReader(newPkgDecoder(types.LocalPkg.Path, data))
106 readPackage(localPkgReader, types.LocalPkg)
108 r := localPkgReader.newReader(relocMeta, privateRootIdx, syncPrivate)
110 r.pkgInit(types.LocalPkg, target)
112 // Type-check any top-level assignments. We ignore non-assignments
113 // here because other declarations are typechecked as they're
115 for i, ndecls := 0, len(target.Decls); i < ndecls; i++ {
116 switch n := target.Decls[i]; n.Op() {
117 case ir.OAS, ir.OAS2:
118 target.Decls[i] = typecheck.Stmt(n)
122 // Don't use range--bodyIdx can add closures to todoBodies.
123 for len(todoBodies) > 0 {
124 // The order we expand bodies doesn't matter, so pop from the end
125 // to reduce todoBodies reallocations if it grows further.
126 fn := todoBodies[len(todoBodies)-1]
127 todoBodies = todoBodies[:len(todoBodies)-1]
129 pri, ok := bodyReader[fn]
133 // Instantiated generic function: add to Decls for typechecking
135 if fn.OClosure == nil && len(pri.dict.targs) != 0 {
136 target.Decls = append(target.Decls, fn)
141 // Check that nothing snuck past typechecking.
142 for _, n := range target.Decls {
143 if n.Typecheck() == 0 {
144 base.FatalfAt(n.Pos(), "missed typecheck: %v", n)
147 // For functions, check that at least their first statement (if
148 // any) was typechecked too.
149 if fn, ok := n.(*ir.Func); ok && len(fn.Body) != 0 {
150 if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
151 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
156 base.ExitIfErrors() // just in case
159 // writePkgStub type checks the given parsed source files,
160 // writes an export data package stub representing them,
161 // and returns the result.
162 func writePkgStub(noders []*noder) string {
163 m, pkg, info := checkFiles(noders)
165 pw := newPkgWriter(m, pkg, info)
167 pw.collectDecls(noders)
169 publicRootWriter := pw.newWriter(relocMeta, syncPublic)
170 privateRootWriter := pw.newWriter(relocMeta, syncPrivate)
172 assert(publicRootWriter.idx == publicRootIdx)
173 assert(privateRootWriter.idx == privateRootIdx)
176 w := publicRootWriter
178 w.bool(false) // has init; XXX
181 names := scope.Names()
183 for _, name := range scope.Names() {
184 w.obj(scope.Lookup(name), nil)
192 w := privateRootWriter
198 var sb bytes.Buffer // TODO(mdempsky): strings.Builder after #44505 is resolved
201 // At this point, we're done with types2. Make sure the package is
202 // garbage collected.
208 // freePackage ensures the given package is garbage collected.
209 func freePackage(pkg *types2.Package) {
210 // The GC test below relies on a precise GC that runs finalizers as
211 // soon as objects are unreachable. Our implementation provides
212 // this, but other/older implementations may not (e.g., Go 1.4 does
213 // not because of #22350). To avoid imposing unnecessary
214 // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
215 // during bootstrapping.
216 if base.CompilerBootstrap {
220 // Set a finalizer on pkg so we can detect if/when it's collected.
221 done := make(chan struct{})
222 runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
224 // Important: objects involved in cycles are not finalized, so zero
225 // out pkg to break its cycles and allow the finalizer to run.
226 *pkg = types2.Package{}
228 // It typically takes just 1 or 2 cycles to release pkg, but it
229 // doesn't hurt to try a few more times.
230 for i := 0; i < 10; i++ {
239 base.Fatalf("package never finalized")
242 func readPackage(pr *pkgReader, importpkg *types.Pkg) {
243 r := pr.newReader(relocMeta, publicRootIdx, syncPublic)
246 assert(pkg == importpkg)
249 sym := pkg.Lookup(".inittask")
250 task := ir.NewNameAt(src.NoXPos, sym)
251 task.Class = ir.PEXTERN
255 for i, n := 0, r.len(); i < n; i++ {
258 idx := r.reloc(relocObj)
261 path, name, code := r.p.peekObj(idx)
263 objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil}
268 func writeNewExport(out io.Writer) {
272 pkgs: make(map[string]int),
273 decls: make(map[*types.Sym]int),
276 publicRootWriter := l.pw.newEncoder(relocMeta, syncPublic)
277 assert(publicRootWriter.idx == publicRootIdx)
283 r := pr.newDecoder(relocMeta, publicRootIdx, syncPublic)
286 selfPkgIdx = l.relocIdx(pr, relocPkg, r.reloc(relocPkg))
290 for i, n := 0, r.len(); i < n; i++ {
293 idx := r.reloc(relocObj)
296 xpath, xname, xtag := pr.peekObj(idx)
297 assert(xpath == pr.pkgPath)
298 assert(xtag != objStub)
300 if types.IsExported(xname) {
301 l.relocIdx(pr, relocObj, idx)
310 for _, idx := range l.decls {
311 idxs = append(idxs, idx)
315 w := publicRootWriter
318 w.reloc(relocPkg, selfPkgIdx)
320 w.bool(typecheck.Lookup(".inittask").Def != nil)
323 for _, idx := range idxs {
326 w.reloc(relocObj, idx)