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