]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
all: fix various doc comment formatting nits
[gostls13.git] / src / cmd / compile / internal / noder / unified.go
1 // UNREVIEWED
2
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.
6
7 package noder
8
9 import (
10         "bytes"
11         "fmt"
12         "internal/goversion"
13         "internal/pkgbits"
14         "io"
15         "runtime"
16         "sort"
17
18         "cmd/compile/internal/base"
19         "cmd/compile/internal/importer"
20         "cmd/compile/internal/inline"
21         "cmd/compile/internal/ir"
22         "cmd/compile/internal/typecheck"
23         "cmd/compile/internal/types"
24         "cmd/compile/internal/types2"
25         "cmd/internal/src"
26 )
27
28 // localPkgReader holds the package reader used for reading the local
29 // package. It exists so the unified IR linker can refer back to it
30 // later.
31 var localPkgReader *pkgReader
32
33 // unified construct the local package's IR from syntax's AST.
34 //
35 // The pipeline contains 2 steps:
36 //
37 //  1) Generate package export data "stub".
38 //
39 //  2) Generate package IR from package export data.
40 //
41 // The package data "stub" at step (1) contains everything from the local package,
42 // but nothing that have been imported. When we're actually writing out export data
43 // to the output files (see writeNewExport function), we run the "linker", which does
44 // a few things:
45 //
46 //  + Updates compiler extensions data (e.g., inlining cost, escape analysis results).
47 //
48 //  + Handles re-exporting any transitive dependencies.
49 //
50 //  + Prunes out any unnecessary details (e.g., non-inlineable functions, because any
51 //    downstream importers only care about inlinable functions).
52 //
53 // The source files are typechecked twice, once before writing export data
54 // using types2 checker, once after read export data using gc/typecheck.
55 // This duplication of work will go away once we always use types2 checker,
56 // we can remove the gc/typecheck pass. The reason it is still here:
57 //
58 //  + It reduces engineering costs in maintaining a fork of typecheck
59 //    (e.g., no need to backport fixes like CL 327651).
60 //
61 //  + It makes it easier to pass toolstash -cmp.
62 //
63 //  + Historically, we would always re-run the typechecker after import, even though
64 //    we know the imported data is valid. It's not ideal, but also not causing any
65 //    problem either.
66 //
67 //  + There's still transformation that being done during gc/typecheck, like rewriting
68 //    multi-valued function call, or transform ir.OINDEX -> ir.OINDEXMAP.
69 //
70 // Using syntax+types2 tree, which already has a complete representation of generics,
71 // the unified IR has the full typed AST for doing introspection during step (1).
72 // In other words, we have all necessary information to build the generic IR form
73 // (see writer.captureVars for an example).
74 func unified(noders []*noder) {
75         inline.NewInline = InlineCall
76
77         writeNewExportFunc = writeNewExport
78
79         newReadImportFunc = func(data string, pkg1 *types.Pkg, ctxt *types2.Context, packages map[string]*types2.Package) (pkg2 *types2.Package, err error) {
80                 pr := pkgbits.NewPkgDecoder(pkg1.Path, data)
81
82                 // Read package descriptors for both types2 and compiler backend.
83                 readPackage(newPkgReader(pr), pkg1)
84                 pkg2 = importer.ReadPackage(ctxt, packages, pr)
85                 return
86         }
87
88         data := writePkgStub(noders)
89
90         // We already passed base.Flag.Lang to types2 to handle validating
91         // the user's source code. Bump it up now to the current version and
92         // re-parse, so typecheck doesn't complain if we construct IR that
93         // utilizes newer Go features.
94         base.Flag.Lang = fmt.Sprintf("go1.%d", goversion.Version)
95         types.ParseLangFlag()
96
97         assert(types.LocalPkg.Path == "")
98         types.LocalPkg.Height = 0 // reset so pkgReader.pkgIdx doesn't complain
99         target := typecheck.Target
100
101         typecheck.TypecheckAllowed = true
102
103         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
104         readPackage(localPkgReader, types.LocalPkg)
105
106         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
107         r.pkgInit(types.LocalPkg, target)
108
109         // Type-check any top-level assignments. We ignore non-assignments
110         // here because other declarations are typechecked as they're
111         // constructed.
112         for i, ndecls := 0, len(target.Decls); i < ndecls; i++ {
113                 switch n := target.Decls[i]; n.Op() {
114                 case ir.OAS, ir.OAS2:
115                         target.Decls[i] = typecheck.Stmt(n)
116                 }
117         }
118
119         readBodies(target)
120
121         // Check that nothing snuck past typechecking.
122         for _, n := range target.Decls {
123                 if n.Typecheck() == 0 {
124                         base.FatalfAt(n.Pos(), "missed typecheck: %v", n)
125                 }
126
127                 // For functions, check that at least their first statement (if
128                 // any) was typechecked too.
129                 if fn, ok := n.(*ir.Func); ok && len(fn.Body) != 0 {
130                         if stmt := fn.Body[0]; stmt.Typecheck() == 0 {
131                                 base.FatalfAt(stmt.Pos(), "missed typecheck: %v", stmt)
132                         }
133                 }
134         }
135
136         base.ExitIfErrors() // just in case
137 }
138
139 // readBodies reads in bodies for any
140 func readBodies(target *ir.Package) {
141         // Don't use range--bodyIdx can add closures to todoBodies.
142         for len(todoBodies) > 0 {
143                 // The order we expand bodies doesn't matter, so pop from the end
144                 // to reduce todoBodies reallocations if it grows further.
145                 fn := todoBodies[len(todoBodies)-1]
146                 todoBodies = todoBodies[:len(todoBodies)-1]
147
148                 pri, ok := bodyReader[fn]
149                 assert(ok)
150                 pri.funcBody(fn)
151
152                 // Instantiated generic function: add to Decls for typechecking
153                 // and compilation.
154                 if fn.OClosure == nil && len(pri.dict.targs) != 0 {
155                         target.Decls = append(target.Decls, fn)
156                 }
157         }
158         todoBodies = nil
159 }
160
161 // writePkgStub type checks the given parsed source files,
162 // writes an export data package stub representing them,
163 // and returns the result.
164 func writePkgStub(noders []*noder) string {
165         m, pkg, info := checkFiles(noders)
166
167         pw := newPkgWriter(m, pkg, info)
168
169         pw.collectDecls(noders)
170
171         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
172         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
173
174         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
175         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
176
177         {
178                 w := publicRootWriter
179                 w.pkg(pkg)
180                 w.Bool(false) // has init; XXX
181
182                 scope := pkg.Scope()
183                 names := scope.Names()
184                 w.Len(len(names))
185                 for _, name := range scope.Names() {
186                         w.obj(scope.Lookup(name), nil)
187                 }
188
189                 w.Sync(pkgbits.SyncEOF)
190                 w.Flush()
191         }
192
193         {
194                 w := privateRootWriter
195                 w.pkgInit(noders)
196                 w.Flush()
197         }
198
199         var sb bytes.Buffer // TODO(mdempsky): strings.Builder after #44505 is resolved
200         pw.DumpTo(&sb)
201
202         // At this point, we're done with types2. Make sure the package is
203         // garbage collected.
204         freePackage(pkg)
205
206         return sb.String()
207 }
208
209 // freePackage ensures the given package is garbage collected.
210 func freePackage(pkg *types2.Package) {
211         // The GC test below relies on a precise GC that runs finalizers as
212         // soon as objects are unreachable. Our implementation provides
213         // this, but other/older implementations may not (e.g., Go 1.4 does
214         // not because of #22350). To avoid imposing unnecessary
215         // restrictions on the GOROOT_BOOTSTRAP toolchain, we skip the test
216         // during bootstrapping.
217         if base.CompilerBootstrap {
218                 return
219         }
220
221         // Set a finalizer on pkg so we can detect if/when it's collected.
222         done := make(chan struct{})
223         runtime.SetFinalizer(pkg, func(*types2.Package) { close(done) })
224
225         // Important: objects involved in cycles are not finalized, so zero
226         // out pkg to break its cycles and allow the finalizer to run.
227         *pkg = types2.Package{}
228
229         // It typically takes just 1 or 2 cycles to release pkg, but it
230         // doesn't hurt to try a few more times.
231         for i := 0; i < 10; i++ {
232                 select {
233                 case <-done:
234                         return
235                 default:
236                         runtime.GC()
237                 }
238         }
239
240         base.Fatalf("package never finalized")
241 }
242
243 func readPackage(pr *pkgReader, importpkg *types.Pkg) {
244         r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
245
246         pkg := r.pkg()
247         assert(pkg == importpkg)
248
249         if r.Bool() {
250                 sym := pkg.Lookup(".inittask")
251                 task := ir.NewNameAt(src.NoXPos, sym)
252                 task.Class = ir.PEXTERN
253                 sym.Def = task
254         }
255
256         for i, n := 0, r.Len(); i < n; i++ {
257                 r.Sync(pkgbits.SyncObject)
258                 assert(!r.Bool())
259                 idx := r.Reloc(pkgbits.RelocObj)
260                 assert(r.Len() == 0)
261
262                 path, name, code := r.p.PeekObj(idx)
263                 if code != pkgbits.ObjStub {
264                         objReader[types.NewPkg(path, "").Lookup(name)] = pkgReaderIndex{pr, idx, nil}
265                 }
266         }
267 }
268
269 func writeNewExport(out io.Writer) {
270         l := linker{
271                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
272
273                 pkgs:  make(map[string]int),
274                 decls: make(map[*types.Sym]int),
275         }
276
277         publicRootWriter := l.pw.NewEncoder(pkgbits.RelocMeta, pkgbits.SyncPublic)
278         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
279
280         var selfPkgIdx int
281
282         {
283                 pr := localPkgReader
284                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
285
286                 r.Sync(pkgbits.SyncPkg)
287                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
288
289                 r.Bool() // has init
290
291                 for i, n := 0, r.Len(); i < n; i++ {
292                         r.Sync(pkgbits.SyncObject)
293                         assert(!r.Bool())
294                         idx := r.Reloc(pkgbits.RelocObj)
295                         assert(r.Len() == 0)
296
297                         xpath, xname, xtag := pr.PeekObj(idx)
298                         assert(xpath == pr.PkgPath())
299                         assert(xtag != pkgbits.ObjStub)
300
301                         if types.IsExported(xname) {
302                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
303                         }
304                 }
305
306                 r.Sync(pkgbits.SyncEOF)
307         }
308
309         {
310                 var idxs []int
311                 for _, idx := range l.decls {
312                         idxs = append(idxs, idx)
313                 }
314                 sort.Ints(idxs)
315
316                 w := publicRootWriter
317
318                 w.Sync(pkgbits.SyncPkg)
319                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
320
321                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
322
323                 w.Len(len(idxs))
324                 for _, idx := range idxs {
325                         w.Sync(pkgbits.SyncObject)
326                         w.Bool(false)
327                         w.Reloc(pkgbits.RelocObj, idx)
328                         w.Len(0)
329                 }
330
331                 w.Sync(pkgbits.SyncEOF)
332                 w.Flush()
333         }
334
335         l.pw.DumpTo(out)
336 }