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