1 // Copyright 2021 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.
16 "cmd/compile/internal/base"
17 "cmd/compile/internal/inline"
18 "cmd/compile/internal/ir"
19 "cmd/compile/internal/typecheck"
20 "cmd/compile/internal/types"
21 "cmd/compile/internal/types2"
25 // localPkgReader holds the package reader used for reading the local
26 // package. It exists so the unified IR linker can refer back to it
28 var localPkgReader *pkgReader
30 // unified constructs the local package's Internal Representation (IR)
31 // from its syntax tree (AST).
33 // The pipeline contains 2 steps:
35 // 1. Generate the export data "stub".
37 // 2. Generate the IR from the export data above.
39 // The package data "stub" at step (1) contains everything from the local package,
40 // but nothing that has been imported. When we're actually writing out export data
41 // to the output files (see writeNewExport), we run the "linker", which:
43 // - Updates compiler extensions data (e.g. inlining cost, escape analysis results).
45 // - Handles re-exporting any transitive dependencies.
47 // - Prunes out any unnecessary details (e.g. non-inlineable functions, because any
48 // downstream importers only care about inlinable functions).
50 // The source files are typechecked twice: once before writing the export data
51 // using types2, and again after reading the export data using gc/typecheck.
52 // The duplication of work will go away once we only use the types2 type checker,
53 // removing the gc/typecheck step. For now, it is kept because:
55 // - It reduces the engineering costs in maintaining a fork of typecheck
56 // (e.g. no need to backport fixes like CL 327651).
58 // - It makes it easier to pass toolstash -cmp.
60 // - Historically, we would always re-run the typechecker after importing a package,
61 // even though we know the imported data is valid. It's not ideal, but it's
62 // not causing any problems either.
64 // - gc/typecheck is still in charge of some transformations, such as rewriting
65 // multi-valued function calls or transforming ir.OINDEX to ir.OINDEXMAP.
67 // Using the syntax tree with types2, which has a complete representation of generics,
68 // the unified IR has the full typed AST needed for introspection during step (1).
69 // In other words, we have all the necessary information to build the generic IR form
70 // (see writer.captureVars for an example).
71 func unified(m posMap, noders []*noder) {
72 inline.InlineCall = unifiedInlineCall
73 typecheck.HaveInlineBody = unifiedHaveInlineBody
75 data := writePkgStub(m, noders)
77 // We already passed base.Flag.Lang to types2 to handle validating
78 // the user's source code. Bump it up now to the current version and
79 // re-parse, so typecheck doesn't complain if we construct IR that
80 // utilizes newer Go features.
81 base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
84 target := typecheck.Target
86 localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
87 readPackage(localPkgReader, types.LocalPkg, true)
89 r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
90 r.pkgInit(types.LocalPkg, target)
92 readBodies(target, false)
94 // Check that nothing snuck past typechecking.
95 for _, fn := range target.Funcs {
96 if fn.Typecheck() == 0 {
97 base.FatalfAt(fn.Pos(), "missed typecheck: %v", fn)
100 // For functions, check that at least their first statement (if
101 // any) was typechecked too.
102 if len(fn.Body) != 0 {
103 if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
104 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
109 // For functions originally came from package runtime,
110 // mark as norace to prevent instrumenting, see issue #60439.
111 for _, fn := range target.Funcs {
112 if !base.Flag.CompilingRuntime && types.RuntimeSymName(fn.Sym()) != "" {
113 fn.Pragma |= ir.Norace
117 base.ExitIfErrors() // just in case
120 // readBodies iteratively expands all pending dictionaries and
123 // If duringInlining is true, then the inline.InlineDecls is called as
124 // necessary on instantiations of imported generic functions, so their
125 // inlining costs can be computed.
126 func readBodies(target *ir.Package, duringInlining bool) {
127 var inlDecls []*ir.Func
129 // Don't use range--bodyIdx can add closures to todoBodies.
131 // The order we expand dictionaries and bodies doesn't matter, so
132 // pop from the end to reduce todoBodies reallocations if it grows
135 // However, we do at least need to flush any pending dictionaries
136 // before reading bodies, because bodies might reference the
139 if len(todoDicts) > 0 {
140 fn := todoDicts[len(todoDicts)-1]
141 todoDicts = todoDicts[:len(todoDicts)-1]
146 if len(todoBodies) > 0 {
147 fn := todoBodies[len(todoBodies)-1]
148 todoBodies = todoBodies[:len(todoBodies)-1]
150 pri, ok := bodyReader[fn]
154 // Instantiated generic function: add to Decls for typechecking
156 if fn.OClosure == nil && len(pri.dict.targs) != 0 {
157 // cmd/link does not support a type symbol referencing a method symbol
158 // across DSO boundary, so force re-compiling methods on a generic type
159 // even it was seen from imported package in linkshared mode, see #58966.
160 canSkipNonGenericMethod := !(base.Ctxt.Flag_linkshared && ir.IsMethod(fn))
161 if duringInlining && canSkipNonGenericMethod {
162 inlDecls = append(inlDecls, fn)
164 target.Funcs = append(target.Funcs, fn)
177 if len(inlDecls) != 0 {
178 // If we instantiated any generic functions during inlining, we need
179 // to call CanInline on them so they'll be transitively inlined
180 // correctly (#56280).
182 // We know these functions were already compiled in an imported
183 // package though, so we don't need to actually apply InlineCalls or
184 // save the function bodies any further than this.
186 // We can also lower the -m flag to 0, to suppress duplicate "can
187 // inline" diagnostics reported against the imported package. Again,
188 // we already reported those diagnostics in the original package, so
189 // it's pointless repeating them here.
191 oldLowerM := base.Flag.LowerM
193 inline.InlineDecls(nil, inlDecls, false)
194 base.Flag.LowerM = oldLowerM
196 for _, fn := range inlDecls {
197 fn.Body = nil // free memory
202 // writePkgStub type checks the given parsed source files,
203 // writes an export data package stub representing them,
204 // and returns the result.
205 func writePkgStub(m posMap, noders []*noder) string {
206 pkg, info := checkFiles(m, noders)
208 pw := newPkgWriter(m, pkg, info)
210 pw.collectDecls(noders)
212 publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
213 privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
215 assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
216 assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
219 w := publicRootWriter
221 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
224 names := scope.Names()
226 for _, name := range names {
227 w.obj(scope.Lookup(name), nil)
230 w.Sync(pkgbits.SyncEOF)
235 w := privateRootWriter
240 var sb strings.Builder
243 // At this point, we're done with types2. Make sure the package is
244 // garbage collected.
250 // freePackage ensures the given package is garbage collected.
251 func freePackage(pkg *types2.Package) {
252 // The GC test below relies on a precise GC that runs finalizers as
253 // soon as objects are unreachable. Our implementation provides
254 // this, but other/older implementations may not (e.g., Go 1.4 does
255 // not because of #22350). To avoid imposing unnecessary
256 // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
257 // during bootstrapping.
258 if base.CompilerBootstrap || base.Debug.GCCheck == 0 {
259 *pkg = types2.Package{}
263 // Set a finalizer on pkg so we can detect if/when it's collected.
264 done := make(chan struct{})
265 runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
267 // Important: objects involved in cycles are not finalized, so zero
268 // out pkg to break its cycles and allow the finalizer to run.
269 *pkg = types2.Package{}
271 // It typically takes just 1 or 2 cycles to release pkg, but it
272 // doesn't hurt to try a few more times.
273 for i := 0; i < 10; i++ {
282 base.Fatalf("package never finalized")
285 // readPackage reads package export data from pr to populate
288 // localStub indicates whether pr is reading the stub export data for
289 // the local package, as opposed to relocated export data for an
291 func readPackage(pr *pkgReader, importpkg *types.Pkg, localStub bool) {
293 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
296 base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
298 r.Bool() // TODO(mdempsky): Remove; was "has init"
300 for i, n := 0, r.Len(); i < n; i++ {
301 r.Sync(pkgbits.SyncObject)
303 idx := r.Reloc(pkgbits.RelocObj)
306 path, name, code := r.p.PeekObj(idx)
307 if code != pkgbits.ObjStub {
308 objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil, nil, nil}
312 r.Sync(pkgbits.SyncEOF)
316 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
319 sym := importpkg.Lookup(".inittask")
320 task := ir.NewNameAt(src.NoXPos, sym, nil)
321 task.Class = ir.PEXTERN
325 for i, n := 0, r.Len(); i < n; i++ {
328 idx := r.Reloc(pkgbits.RelocBody)
330 sym := types.NewPkg(path, "").Lookup(name)
331 if _, ok := importBodyReader[sym]; !ok {
332 importBodyReader[sym] = pkgReaderIndex{pr, idx, nil, nil, nil}
336 r.Sync(pkgbits.SyncEOF)
340 // writeUnifiedExport writes to `out` the finalized, self-contained
341 // Unified IR export data file for the current compilation unit.
342 func writeUnifiedExport(out io.Writer) {
344 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
346 pkgs: make(map[string]pkgbits.Index),
347 decls: make(map[*types.Sym]pkgbits.Index),
348 bodies: make(map[*types.Sym]pkgbits.Index),
351 publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
352 privateRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPrivate)
353 assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
354 assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
356 var selfPkgIdx pkgbits.Index
360 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
362 r.Sync(pkgbits.SyncPkg)
363 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
365 r.Bool() // TODO(mdempsky): Remove; was "has init"
367 for i, n := 0, r.Len(); i < n; i++ {
368 r.Sync(pkgbits.SyncObject)
370 idx := r.Reloc(pkgbits.RelocObj)
373 xpath, xname, xtag := pr.PeekObj(idx)
374 assert(xpath == pr.PkgPath())
375 assert(xtag != pkgbits.ObjStub)
377 if types.IsExported(xname) {
378 l.relocIdx(pr, pkgbits.RelocObj, idx)
382 r.Sync(pkgbits.SyncEOF)
386 var idxs []pkgbits.Index
387 for _, idx := range l.decls {
388 idxs = append(idxs, idx)
390 sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
392 w := publicRootWriter
394 w.Sync(pkgbits.SyncPkg)
395 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
396 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
399 for _, idx := range idxs {
400 w.Sync(pkgbits.SyncObject)
402 w.Reloc(pkgbits.RelocObj, idx)
406 w.Sync(pkgbits.SyncEOF)
416 for sym, idx := range l.bodies {
417 bodies = append(bodies, symIdx{sym, idx})
419 sort.Slice(bodies, func(i, j int) bool { return bodies[i].idx < bodies[j].idx })
421 w := privateRootWriter
423 w.Bool(typecheck.Lookup(".inittask").Def != nil)
426 for _, body := range bodies {
427 w.String(body.sym.Pkg.Path)
428 w.String(body.sym.Name)
429 w.Reloc(pkgbits.RelocBody, body.idx)
432 w.Sync(pkgbits.SyncEOF)
436 base.Ctxt.Fingerprint = l.pw.DumpTo(out)