]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
cmd/compile/internal/noder: reuse package scope's names
[gostls13.git] / src / cmd / compile / internal / noder / unified.go
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.
4
5 package noder
6
7 import (
8         "fmt"
9         "internal/goversion"
10         "internal/pkgbits"
11         "io"
12         "runtime"
13         "sort"
14         "strings"
15
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"
22         "cmd/internal/src"
23 )
24
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
27 // later.
28 var localPkgReader *pkgReader
29
30 // unified constructs the local package's Internal Representation (IR)
31 // from its syntax tree (AST).
32 //
33 // The pipeline contains 2 steps:
34 //
35 //  1. Generate the export data "stub".
36 //
37 //  2. Generate the IR from the export data above.
38 //
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:
42 //
43 //   - Updates compiler extensions data (e.g. inlining cost, escape analysis results).
44 //
45 //   - Handles re-exporting any transitive dependencies.
46 //
47 //   - Prunes out any unnecessary details (e.g. non-inlineable functions, because any
48 //     downstream importers only care about inlinable functions).
49 //
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:
54 //
55 //   - It reduces the engineering costs in maintaining a fork of typecheck
56 //     (e.g. no need to backport fixes like CL 327651).
57 //
58 //   - It makes it easier to pass toolstash -cmp.
59 //
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.
63 //
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.
66 //
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(noders []*noder) {
72         inline.NewInline = InlineCall
73
74         data := writePkgStub(noders)
75
76         // We already passed base.Flag.Lang to types2 to handle validating
77         // the user's source code. Bump it up now to the current version and
78         // re-parse, so typecheck doesn't complain if we construct IR that
79         // utilizes newer Go features.
80         base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
81         types.ParseLangFlag()
82
83         target := typecheck.Target
84
85         typecheck.TypecheckAllowed = true
86
87         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
88         readPackage(localPkgReader, types.LocalPkg, true)
89
90         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
91         r.pkgInit(types.LocalPkg, target)
92
93         // Type-check any top-level assignments. We ignore non-assignments
94         // here because other declarations are typechecked as they're
95         // constructed.
96         for i, ndecls := 0, len(target.Decls); i < ndecls; i++ {
97                 switch n := target.Decls[i]; n.Op() {
98                 case ir.OAS, ir.OAS2:
99                         target.Decls[i] = typecheck.Stmt(n)
100                 }
101         }
102
103         readBodies(target)
104
105         // Check that nothing snuck past typechecking.
106         for _, n := range target.Decls {
107                 if n.Typecheck() == 0 {
108                         base.FatalfAt(n.Pos(), "missed typecheck: %v", n)
109                 }
110
111                 // For functions, check that at least their first statement (if
112                 // any) was typechecked too.
113                 if fn, ok := n.(*ir.Func); ok && len(fn.Body) != 0 {
114                         if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
115                                 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
116                         }
117                 }
118         }
119
120         base.ExitIfErrors() // just in case
121 }
122
123 // readBodies iteratively expands all pending dictionaries and
124 // function bodies.
125 func readBodies(target *ir.Package) {
126         // Don't use range--bodyIdx can add closures to todoBodies.
127         for {
128                 // The order we expand dictionaries and bodies doesn't matter, so
129                 // pop from the end to reduce todoBodies reallocations if it grows
130                 // further.
131                 //
132                 // However, we do at least need to flush any pending dictionaries
133                 // before reading bodies, because bodies might reference the
134                 // dictionaries.
135
136                 if len(todoDicts) > 0 {
137                         fn := todoDicts[len(todoDicts)-1]
138                         todoDicts = todoDicts[:len(todoDicts)-1]
139                         fn()
140                         continue
141                 }
142
143                 if len(todoBodies) > 0 {
144                         fn := todoBodies[len(todoBodies)-1]
145                         todoBodies = todoBodies[:len(todoBodies)-1]
146
147                         pri, ok := bodyReader[fn]
148                         assert(ok)
149                         pri.funcBody(fn)
150
151                         // Instantiated generic function: add to Decls for typechecking
152                         // and compilation.
153                         if fn.OClosure == nil && len(pri.dict.targs) != 0 {
154                                 target.Decls = append(target.Decls, fn)
155                         }
156
157                         continue
158                 }
159
160                 break
161         }
162
163         todoDicts = nil
164         todoBodies = nil
165 }
166
167 // writePkgStub type checks the given parsed source files,
168 // writes an export data package stub representing them,
169 // and returns the result.
170 func writePkgStub(noders []*noder) string {
171         m, pkg, info := checkFiles(noders)
172
173         pw := newPkgWriter(m, pkg, info)
174
175         pw.collectDecls(noders)
176
177         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
178         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
179
180         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
181         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
182
183         {
184                 w := publicRootWriter
185                 w.pkg(pkg)
186                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
187
188                 scope := pkg.Scope()
189                 names := scope.Names()
190                 w.Len(len(names))
191                 for _, name := range names {
192                         w.obj(scope.Lookup(name), nil)
193                 }
194
195                 w.Sync(pkgbits.SyncEOF)
196                 w.Flush()
197         }
198
199         {
200                 w := privateRootWriter
201                 w.pkgInit(noders)
202                 w.Flush()
203         }
204
205         var sb strings.Builder
206         pw.DumpTo(&sb)
207
208         // At this point, we're done with types2. Make sure the package is
209         // garbage collected.
210         freePackage(pkg)
211
212         return sb.String()
213 }
214
215 // freePackage ensures the given package is garbage collected.
216 func freePackage(pkg *types2.Package) {
217         // The GC test below relies on a precise GC that runs finalizers as
218         // soon as objects are unreachable. Our implementation provides
219         // this, but other/older implementations may not (e.g., Go 1.4 does
220         // not because of #22350). To avoid imposing unnecessary
221         // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
222         // during bootstrapping.
223         if base.CompilerBootstrap {
224                 return
225         }
226
227         // Set a finalizer on pkg so we can detect if/when it's collected.
228         done := make(chan struct{})
229         runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
230
231         // Important: objects involved in cycles are not finalized, so zero
232         // out pkg to break its cycles and allow the finalizer to run.
233         *pkg = types2.Package{}
234
235         // It typically takes just 1 or 2 cycles to release pkg, but it
236         // doesn't hurt to try a few more times.
237         for i := 0; i < 10; i++ {
238                 select {
239                 case <-done:
240                         return
241                 default:
242                         runtime.GC()
243                 }
244         }
245
246         base.Fatalf("package never finalized")
247 }
248
249 // readPackage reads package export data from pr to populate
250 // importpkg.
251 //
252 // localStub indicates whether pr is reading the stub export data for
253 // the local package, as opposed to relocated export data for an
254 // import.
255 func readPackage(pr *pkgReader, importpkg *types.Pkg, localStub bool) {
256         {
257                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
258
259                 pkg := r.pkg()
260                 base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
261
262                 r.Bool() // TODO(mdempsky): Remove; was "has init"
263
264                 for i, n := 0, r.Len(); i < n; i++ {
265                         r.Sync(pkgbits.SyncObject)
266                         assert(!r.Bool())
267                         idx := r.Reloc(pkgbits.RelocObj)
268                         assert(r.Len() == 0)
269
270                         path, name, code := r.p.PeekObj(idx)
271                         if code != pkgbits.ObjStub {
272                                 objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil, nil, nil}
273                         }
274                 }
275
276                 r.Sync(pkgbits.SyncEOF)
277         }
278
279         if !localStub {
280                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
281
282                 if r.Bool() {
283                         sym := importpkg.Lookup(".inittask")
284                         task := ir.NewNameAt(src.NoXPos, sym)
285                         task.Class = ir.PEXTERN
286                         sym.Def = task
287                 }
288
289                 for i, n := 0, r.Len(); i < n; i++ {
290                         path := r.String()
291                         name := r.String()
292                         idx := r.Reloc(pkgbits.RelocBody)
293
294                         sym := types.NewPkg(path, "").Lookup(name)
295                         if _, ok := importBodyReader[sym]; !ok {
296                                 importBodyReader[sym] = pkgReaderIndex{pr, idx, nil, nil, nil}
297                         }
298                 }
299
300                 r.Sync(pkgbits.SyncEOF)
301         }
302 }
303
304 // writeUnifiedExport writes to `out` the finalized, self-contained
305 // Unified IR export data file for the current compilation unit.
306 func writeUnifiedExport(out io.Writer) {
307         l := linker{
308                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
309
310                 pkgs:   make(map[string]pkgbits.Index),
311                 decls:  make(map[*types.Sym]pkgbits.Index),
312                 bodies: make(map[*types.Sym]pkgbits.Index),
313         }
314
315         publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
316         privateRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPrivate)
317         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
318         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
319
320         var selfPkgIdx pkgbits.Index
321
322         {
323                 pr := localPkgReader
324                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
325
326                 r.Sync(pkgbits.SyncPkg)
327                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
328
329                 r.Bool() // TODO(mdempsky): Remove; was "has init"
330
331                 for i, n := 0, r.Len(); i < n; i++ {
332                         r.Sync(pkgbits.SyncObject)
333                         assert(!r.Bool())
334                         idx := r.Reloc(pkgbits.RelocObj)
335                         assert(r.Len() == 0)
336
337                         xpath, xname, xtag := pr.PeekObj(idx)
338                         assert(xpath == pr.PkgPath())
339                         assert(xtag != pkgbits.ObjStub)
340
341                         if types.IsExported(xname) {
342                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
343                         }
344                 }
345
346                 r.Sync(pkgbits.SyncEOF)
347         }
348
349         {
350                 var idxs []pkgbits.Index
351                 for _, idx := range l.decls {
352                         idxs = append(idxs, idx)
353                 }
354                 sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
355
356                 w := publicRootWriter
357
358                 w.Sync(pkgbits.SyncPkg)
359                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
360                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
361
362                 w.Len(len(idxs))
363                 for _, idx := range idxs {
364                         w.Sync(pkgbits.SyncObject)
365                         w.Bool(false)
366                         w.Reloc(pkgbits.RelocObj, idx)
367                         w.Len(0)
368                 }
369
370                 w.Sync(pkgbits.SyncEOF)
371                 w.Flush()
372         }
373
374         {
375                 type symIdx struct {
376                         sym *types.Sym
377                         idx pkgbits.Index
378                 }
379                 var bodies []symIdx
380                 for sym, idx := range l.bodies {
381                         bodies = append(bodies, symIdx{sym, idx})
382                 }
383                 sort.Slice(bodies, func(i, j int) bool { return bodies[i].idx < bodies[j].idx })
384
385                 w := privateRootWriter
386
387                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
388
389                 w.Len(len(bodies))
390                 for _, body := range bodies {
391                         w.String(body.sym.Pkg.Path)
392                         w.String(body.sym.Name)
393                         w.Reloc(pkgbits.RelocBody, body.idx)
394                 }
395
396                 w.Sync(pkgbits.SyncEOF)
397                 w.Flush()
398         }
399
400         base.Ctxt.Fingerprint = l.pw.DumpTo(out)
401 }