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.
15 "cmd/compile/internal/base"
16 "cmd/compile/internal/inline"
17 "cmd/compile/internal/ir"
18 "cmd/compile/internal/pgo"
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 // LookupMethodFunc returns the ir.Func for an arbitrary full symbol name if
31 // that function exists in the set of available export data.
33 // This allows lookup of arbitrary methods that aren't otherwise referenced by
34 // the local package and thus haven't been read yet.
36 // TODO(prattmic): Does not handle instantiation of generic types. Currently
37 // profiles don't contain the original type arguments, so we won't be able to
38 // create the runtime dictionaries.
40 // TODO(prattmic): Hit rate of this function is usually fairly low, and errors
41 // are only used when debug logging is enabled. Consider constructing cheaper
43 func LookupMethodFunc(fullName string) (*ir.Func, error) {
44 pkgPath, symName, err := ir.ParseLinkFuncName(fullName)
46 return nil, fmt.Errorf("error parsing symbol name %q: %v", fullName, err)
49 pkg, ok := types.PkgMap()[pkgPath]
51 return nil, fmt.Errorf("pkg %s doesn't exist in %v", pkgPath, types.PkgMap())
54 // N.B. readPackage creates a Sym for every object in the package to
55 // initialize objReader and importBodyReader, even if the object isn't
58 // However, objReader is only initialized for top-level objects, so we
59 // must first lookup the type and use that to find the method rather
60 // than looking for the method directly.
61 typ, meth, err := ir.LookupMethodSelector(pkg, symName)
63 return nil, fmt.Errorf("error looking up method symbol %q: %v", symName, err)
66 pri, ok := objReader[typ]
68 return nil, fmt.Errorf("type sym %v missing objReader", typ)
71 name := pri.pr.objIdx(pri.idx, nil, nil, false).(*ir.Name)
72 if name.Op() != ir.OTYPE {
73 return nil, fmt.Errorf("type sym %v refers to non-type name: %v", typ, name)
76 return nil, fmt.Errorf("type sym %v refers to alias", typ)
79 for _, m := range name.Type().Methods() {
81 fn := m.Nname.(*ir.Name).Func
86 return nil, fmt.Errorf("method %s missing from method set of %v", symName, typ)
89 // unified constructs the local package's Internal Representation (IR)
90 // from its syntax tree (AST).
92 // The pipeline contains 2 steps:
94 // 1. Generate the export data "stub".
96 // 2. Generate the IR from the export data above.
98 // The package data "stub" at step (1) contains everything from the local package,
99 // but nothing that has been imported. When we're actually writing out export data
100 // to the output files (see writeNewExport), we run the "linker", which:
102 // - Updates compiler extensions data (e.g. inlining cost, escape analysis results).
104 // - Handles re-exporting any transitive dependencies.
106 // - Prunes out any unnecessary details (e.g. non-inlineable functions, because any
107 // downstream importers only care about inlinable functions).
109 // The source files are typechecked twice: once before writing the export data
110 // using types2, and again after reading the export data using gc/typecheck.
111 // The duplication of work will go away once we only use the types2 type checker,
112 // removing the gc/typecheck step. For now, it is kept because:
114 // - It reduces the engineering costs in maintaining a fork of typecheck
115 // (e.g. no need to backport fixes like CL 327651).
117 // - It makes it easier to pass toolstash -cmp.
119 // - Historically, we would always re-run the typechecker after importing a package,
120 // even though we know the imported data is valid. It's not ideal, but it's
121 // not causing any problems either.
123 // - gc/typecheck is still in charge of some transformations, such as rewriting
124 // multi-valued function calls or transforming ir.OINDEX to ir.OINDEXMAP.
126 // Using the syntax tree with types2, which has a complete representation of generics,
127 // the unified IR has the full typed AST needed for introspection during step (1).
128 // In other words, we have all the necessary information to build the generic IR form
129 // (see writer.captureVars for an example).
130 func unified(m posMap, noders []*noder) {
131 inline.InlineCall = unifiedInlineCall
132 typecheck.HaveInlineBody = unifiedHaveInlineBody
133 pgo.LookupMethodFunc = LookupMethodFunc
135 data := writePkgStub(m, noders)
137 target := typecheck.Target
139 localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
140 readPackage(localPkgReader, types.LocalPkg, true)
142 r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
143 r.pkgInit(types.LocalPkg, target)
145 readBodies(target, false)
147 // Check that nothing snuck past typechecking.
148 for _, fn := range target.Funcs {
149 if fn.Typecheck() == 0 {
150 base.FatalfAt(fn.Pos(), "missed typecheck: %v", fn)
153 // For functions, check that at least their first statement (if
154 // any) was typechecked too.
155 if len(fn.Body) != 0 {
156 if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
157 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
162 // For functions originally came from package runtime,
163 // mark as norace to prevent instrumenting, see issue #60439.
164 for _, fn := range target.Funcs {
165 if !base.Flag.CompilingRuntime && types.RuntimeSymName(fn.Sym()) != "" {
166 fn.Pragma |= ir.Norace
170 base.ExitIfErrors() // just in case
173 // readBodies iteratively expands all pending dictionaries and
176 // If duringInlining is true, then the inline.InlineDecls is called as
177 // necessary on instantiations of imported generic functions, so their
178 // inlining costs can be computed.
179 func readBodies(target *ir.Package, duringInlining bool) {
180 var inlDecls []*ir.Func
182 // Don't use range--bodyIdx can add closures to todoBodies.
184 // The order we expand dictionaries and bodies doesn't matter, so
185 // pop from the end to reduce todoBodies reallocations if it grows
188 // However, we do at least need to flush any pending dictionaries
189 // before reading bodies, because bodies might reference the
192 if len(todoDicts) > 0 {
193 fn := todoDicts[len(todoDicts)-1]
194 todoDicts = todoDicts[:len(todoDicts)-1]
199 if len(todoBodies) > 0 {
200 fn := todoBodies[len(todoBodies)-1]
201 todoBodies = todoBodies[:len(todoBodies)-1]
203 pri, ok := bodyReader[fn]
207 // Instantiated generic function: add to Decls for typechecking
209 if fn.OClosure == nil && len(pri.dict.targs) != 0 {
210 // cmd/link does not support a type symbol referencing a method symbol
211 // across DSO boundary, so force re-compiling methods on a generic type
212 // even it was seen from imported package in linkshared mode, see #58966.
213 canSkipNonGenericMethod := !(base.Ctxt.Flag_linkshared && ir.IsMethod(fn))
214 if duringInlining && canSkipNonGenericMethod {
215 inlDecls = append(inlDecls, fn)
217 target.Funcs = append(target.Funcs, fn)
230 if len(inlDecls) != 0 {
231 // If we instantiated any generic functions during inlining, we need
232 // to call CanInline on them so they'll be transitively inlined
233 // correctly (#56280).
235 // We know these functions were already compiled in an imported
236 // package though, so we don't need to actually apply InlineCalls or
237 // save the function bodies any further than this.
239 // We can also lower the -m flag to 0, to suppress duplicate "can
240 // inline" diagnostics reported against the imported package. Again,
241 // we already reported those diagnostics in the original package, so
242 // it's pointless repeating them here.
244 oldLowerM := base.Flag.LowerM
246 inline.InlineDecls(nil, inlDecls, false)
247 base.Flag.LowerM = oldLowerM
249 for _, fn := range inlDecls {
250 fn.Body = nil // free memory
255 // writePkgStub type checks the given parsed source files,
256 // writes an export data package stub representing them,
257 // and returns the result.
258 func writePkgStub(m posMap, noders []*noder) string {
259 pkg, info := checkFiles(m, noders)
261 pw := newPkgWriter(m, pkg, info)
263 pw.collectDecls(noders)
265 publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
266 privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
268 assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
269 assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
272 w := publicRootWriter
274 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
277 names := scope.Names()
279 for _, name := range names {
280 w.obj(scope.Lookup(name), nil)
283 w.Sync(pkgbits.SyncEOF)
288 w := privateRootWriter
293 var sb strings.Builder
296 // At this point, we're done with types2. Make sure the package is
297 // garbage collected.
303 // freePackage ensures the given package is garbage collected.
304 func freePackage(pkg *types2.Package) {
305 // The GC test below relies on a precise GC that runs finalizers as
306 // soon as objects are unreachable. Our implementation provides
307 // this, but other/older implementations may not (e.g., Go 1.4 does
308 // not because of #22350). To avoid imposing unnecessary
309 // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
310 // during bootstrapping.
311 if base.CompilerBootstrap || base.Debug.GCCheck == 0 {
312 *pkg = types2.Package{}
316 // Set a finalizer on pkg so we can detect if/when it's collected.
317 done := make(chan struct{})
318 runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
320 // Important: objects involved in cycles are not finalized, so zero
321 // out pkg to break its cycles and allow the finalizer to run.
322 *pkg = types2.Package{}
324 // It typically takes just 1 or 2 cycles to release pkg, but it
325 // doesn't hurt to try a few more times.
326 for i := 0; i < 10; i++ {
335 base.Fatalf("package never finalized")
338 // readPackage reads package export data from pr to populate
341 // localStub indicates whether pr is reading the stub export data for
342 // the local package, as opposed to relocated export data for an
344 func readPackage(pr *pkgReader, importpkg *types.Pkg, localStub bool) {
346 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
349 base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
351 r.Bool() // TODO(mdempsky): Remove; was "has init"
353 for i, n := 0, r.Len(); i < n; i++ {
354 r.Sync(pkgbits.SyncObject)
356 idx := r.Reloc(pkgbits.RelocObj)
359 path, name, code := r.p.PeekObj(idx)
360 if code != pkgbits.ObjStub {
361 objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil, nil, nil}
365 r.Sync(pkgbits.SyncEOF)
369 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
372 sym := importpkg.Lookup(".inittask")
373 task := ir.NewNameAt(src.NoXPos, sym, nil)
374 task.Class = ir.PEXTERN
378 for i, n := 0, r.Len(); i < n; i++ {
381 idx := r.Reloc(pkgbits.RelocBody)
383 sym := types.NewPkg(path, "").Lookup(name)
384 if _, ok := importBodyReader[sym]; !ok {
385 importBodyReader[sym] = pkgReaderIndex{pr, idx, nil, nil, nil}
389 r.Sync(pkgbits.SyncEOF)
393 // writeUnifiedExport writes to `out` the finalized, self-contained
394 // Unified IR export data file for the current compilation unit.
395 func writeUnifiedExport(out io.Writer) {
397 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
399 pkgs: make(map[string]pkgbits.Index),
400 decls: make(map[*types.Sym]pkgbits.Index),
401 bodies: make(map[*types.Sym]pkgbits.Index),
404 publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
405 privateRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPrivate)
406 assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
407 assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
409 var selfPkgIdx pkgbits.Index
413 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
415 r.Sync(pkgbits.SyncPkg)
416 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
418 r.Bool() // TODO(mdempsky): Remove; was "has init"
420 for i, n := 0, r.Len(); i < n; i++ {
421 r.Sync(pkgbits.SyncObject)
423 idx := r.Reloc(pkgbits.RelocObj)
426 xpath, xname, xtag := pr.PeekObj(idx)
427 assert(xpath == pr.PkgPath())
428 assert(xtag != pkgbits.ObjStub)
430 if types.IsExported(xname) {
431 l.relocIdx(pr, pkgbits.RelocObj, idx)
435 r.Sync(pkgbits.SyncEOF)
439 var idxs []pkgbits.Index
440 for _, idx := range l.decls {
441 idxs = append(idxs, idx)
443 sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
445 w := publicRootWriter
447 w.Sync(pkgbits.SyncPkg)
448 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
449 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
452 for _, idx := range idxs {
453 w.Sync(pkgbits.SyncObject)
455 w.Reloc(pkgbits.RelocObj, idx)
459 w.Sync(pkgbits.SyncEOF)
469 for sym, idx := range l.bodies {
470 bodies = append(bodies, symIdx{sym, idx})
472 sort.Slice(bodies, func(i, j int) bool { return bodies[i].idx < bodies[j].idx })
474 w := privateRootWriter
476 w.Bool(typecheck.Lookup(".inittask").Def != nil)
479 for _, body := range bodies {
480 w.String(body.sym.Pkg.Path)
481 w.String(body.sym.Name)
482 w.Reloc(pkgbits.RelocBody, body.idx)
485 w.Sync(pkgbits.SyncEOF)
489 base.Ctxt.Fingerprint = l.pw.DumpTo(out)