]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/unified.go
cmd/compile: initial function value devirtualization
[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/pkgbits"
10         "io"
11         "runtime"
12         "sort"
13         "strings"
14
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"
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 // LookupMethodFunc returns the ir.Func for an arbitrary full symbol name if
31 // that function exists in the set of available export data.
32 //
33 // This allows lookup of arbitrary methods that aren't otherwise referenced by
34 // the local package and thus haven't been read yet.
35 //
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.
39 //
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
42 // errors by default.
43 func LookupMethodFunc(fullName string) (*ir.Func, error) {
44         pkgPath, symName, err := ir.ParseLinkFuncName(fullName)
45         if err != nil {
46                 return nil, fmt.Errorf("error parsing symbol name %q: %v", fullName, err)
47         }
48
49         pkg, ok := types.PkgMap()[pkgPath]
50         if !ok {
51                 return nil, fmt.Errorf("pkg %s doesn't exist in %v", pkgPath, types.PkgMap())
52         }
53
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
56         // read.
57         //
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)
62         if err != nil {
63                 return nil, fmt.Errorf("error looking up method symbol %q: %v", symName, err)
64         }
65
66         pri, ok := objReader[typ]
67         if !ok {
68                 return nil, fmt.Errorf("type sym %v missing objReader", typ)
69         }
70
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)
74         }
75         if name.Alias() {
76                 return nil, fmt.Errorf("type sym %v refers to alias", typ)
77         }
78
79         for _, m := range name.Type().Methods() {
80                 if m.Sym == meth {
81                         fn := m.Nname.(*ir.Name).Func
82                         return fn, nil
83                 }
84         }
85
86         return nil, fmt.Errorf("method %s missing from method set of %v", symName, typ)
87 }
88
89 // unified constructs the local package's Internal Representation (IR)
90 // from its syntax tree (AST).
91 //
92 // The pipeline contains 2 steps:
93 //
94 //  1. Generate the export data "stub".
95 //
96 //  2. Generate the IR from the export data above.
97 //
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:
101 //
102 //   - Updates compiler extensions data (e.g. inlining cost, escape analysis results).
103 //
104 //   - Handles re-exporting any transitive dependencies.
105 //
106 //   - Prunes out any unnecessary details (e.g. non-inlineable functions, because any
107 //     downstream importers only care about inlinable functions).
108 //
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:
113 //
114 //   - It reduces the engineering costs in maintaining a fork of typecheck
115 //     (e.g. no need to backport fixes like CL 327651).
116 //
117 //   - It makes it easier to pass toolstash -cmp.
118 //
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.
122 //
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.
125 //
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
134
135         data := writePkgStub(m, noders)
136
137         target := typecheck.Target
138
139         localPkgReader = newPkgReader(pkgbits.NewPkgDecoder(types.LocalPkg.Path, data))
140         readPackage(localPkgReader, types.LocalPkg, true)
141
142         r := localPkgReader.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
143         r.pkgInit(types.LocalPkg, target)
144
145         readBodies(target, false)
146
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)
151                 }
152
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)
158                         }
159                 }
160         }
161
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
167                 }
168         }
169
170         base.ExitIfErrors() // just in case
171 }
172
173 // readBodies iteratively expands all pending dictionaries and
174 // function bodies.
175 //
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
181
182         // Don't use range--bodyIdx can add closures to todoBodies.
183         for {
184                 // The order we expand dictionaries and bodies doesn't matter, so
185                 // pop from the end to reduce todoBodies reallocations if it grows
186                 // further.
187                 //
188                 // However, we do at least need to flush any pending dictionaries
189                 // before reading bodies, because bodies might reference the
190                 // dictionaries.
191
192                 if len(todoDicts) > 0 {
193                         fn := todoDicts[len(todoDicts)-1]
194                         todoDicts = todoDicts[:len(todoDicts)-1]
195                         fn()
196                         continue
197                 }
198
199                 if len(todoBodies) > 0 {
200                         fn := todoBodies[len(todoBodies)-1]
201                         todoBodies = todoBodies[:len(todoBodies)-1]
202
203                         pri, ok := bodyReader[fn]
204                         assert(ok)
205                         pri.funcBody(fn)
206
207                         // Instantiated generic function: add to Decls for typechecking
208                         // and compilation.
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)
216                                 } else {
217                                         target.Funcs = append(target.Funcs, fn)
218                                 }
219                         }
220
221                         continue
222                 }
223
224                 break
225         }
226
227         todoDicts = nil
228         todoBodies = nil
229
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).
234                 //
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.
238                 //
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.
243
244                 oldLowerM := base.Flag.LowerM
245                 base.Flag.LowerM = 0
246                 inline.InlineDecls(nil, inlDecls, false)
247                 base.Flag.LowerM = oldLowerM
248
249                 for _, fn := range inlDecls {
250                         fn.Body = nil // free memory
251                 }
252         }
253 }
254
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)
260
261         pw := newPkgWriter(m, pkg, info)
262
263         pw.collectDecls(noders)
264
265         publicRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPublic)
266         privateRootWriter := pw.newWriter(pkgbits.RelocMeta, pkgbits.SyncPrivate)
267
268         assert(publicRootWriter.Idx == pkgbits.PublicRootIdx)
269         assert(privateRootWriter.Idx == pkgbits.PrivateRootIdx)
270
271         {
272                 w := publicRootWriter
273                 w.pkg(pkg)
274                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
275
276                 scope := pkg.Scope()
277                 names := scope.Names()
278                 w.Len(len(names))
279                 for _, name := range names {
280                         w.obj(scope.Lookup(name), nil)
281                 }
282
283                 w.Sync(pkgbits.SyncEOF)
284                 w.Flush()
285         }
286
287         {
288                 w := privateRootWriter
289                 w.pkgInit(noders)
290                 w.Flush()
291         }
292
293         var sb strings.Builder
294         pw.DumpTo(&sb)
295
296         // At this point, we're done with types2. Make sure the package is
297         // garbage collected.
298         freePackage(pkg)
299
300         return sb.String()
301 }
302
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{}
313                 return
314         }
315
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) })
319
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{}
323
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++ {
327                 select {
328                 case <-done:
329                         return
330                 default:
331                         runtime.GC()
332                 }
333         }
334
335         base.Fatalf("package never finalized")
336 }
337
338 // readPackage reads package export data from pr to populate
339 // importpkg.
340 //
341 // localStub indicates whether pr is reading the stub export data for
342 // the local package, as opposed to relocated export data for an
343 // import.
344 func readPackage(pr *pkgReader, importpkg *types.Pkg, localStub bool) {
345         {
346                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
347
348                 pkg := r.pkg()
349                 base.Assertf(pkg == importpkg, "have package %q (%p), want package %q (%p)", pkg.Path, pkg, importpkg.Path, importpkg)
350
351                 r.Bool() // TODO(mdempsky): Remove; was "has init"
352
353                 for i, n := 0, r.Len(); i < n; i++ {
354                         r.Sync(pkgbits.SyncObject)
355                         assert(!r.Bool())
356                         idx := r.Reloc(pkgbits.RelocObj)
357                         assert(r.Len() == 0)
358
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}
362                         }
363                 }
364
365                 r.Sync(pkgbits.SyncEOF)
366         }
367
368         if !localStub {
369                 r := pr.newReader(pkgbits.RelocMeta, pkgbits.PrivateRootIdx, pkgbits.SyncPrivate)
370
371                 if r.Bool() {
372                         sym := importpkg.Lookup(".inittask")
373                         task := ir.NewNameAt(src.NoXPos, sym, nil)
374                         task.Class = ir.PEXTERN
375                         sym.Def = task
376                 }
377
378                 for i, n := 0, r.Len(); i < n; i++ {
379                         path := r.String()
380                         name := r.String()
381                         idx := r.Reloc(pkgbits.RelocBody)
382
383                         sym := types.NewPkg(path, "").Lookup(name)
384                         if _, ok := importBodyReader[sym]; !ok {
385                                 importBodyReader[sym] = pkgReaderIndex{pr, idx, nil, nil, nil}
386                         }
387                 }
388
389                 r.Sync(pkgbits.SyncEOF)
390         }
391 }
392
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) {
396         l := linker{
397                 pw: pkgbits.NewPkgEncoder(base.Debug.SyncFrames),
398
399                 pkgs:   make(map[string]pkgbits.Index),
400                 decls:  make(map[*types.Sym]pkgbits.Index),
401                 bodies: make(map[*types.Sym]pkgbits.Index),
402         }
403
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)
408
409         var selfPkgIdx pkgbits.Index
410
411         {
412                 pr := localPkgReader
413                 r := pr.NewDecoder(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
414
415                 r.Sync(pkgbits.SyncPkg)
416                 selfPkgIdx = l.relocIdx(pr, pkgbits.RelocPkg, r.Reloc(pkgbits.RelocPkg))
417
418                 r.Bool() // TODO(mdempsky): Remove; was "has init"
419
420                 for i, n := 0, r.Len(); i < n; i++ {
421                         r.Sync(pkgbits.SyncObject)
422                         assert(!r.Bool())
423                         idx := r.Reloc(pkgbits.RelocObj)
424                         assert(r.Len() == 0)
425
426                         xpath, xname, xtag := pr.PeekObj(idx)
427                         assert(xpath == pr.PkgPath())
428                         assert(xtag != pkgbits.ObjStub)
429
430                         if types.IsExported(xname) {
431                                 l.relocIdx(pr, pkgbits.RelocObj, idx)
432                         }
433                 }
434
435                 r.Sync(pkgbits.SyncEOF)
436         }
437
438         {
439                 var idxs []pkgbits.Index
440                 for _, idx := range l.decls {
441                         idxs = append(idxs, idx)
442                 }
443                 sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
444
445                 w := publicRootWriter
446
447                 w.Sync(pkgbits.SyncPkg)
448                 w.Reloc(pkgbits.RelocPkg, selfPkgIdx)
449                 w.Bool(false) // TODO(mdempsky): Remove; was "has init"
450
451                 w.Len(len(idxs))
452                 for _, idx := range idxs {
453                         w.Sync(pkgbits.SyncObject)
454                         w.Bool(false)
455                         w.Reloc(pkgbits.RelocObj, idx)
456                         w.Len(0)
457                 }
458
459                 w.Sync(pkgbits.SyncEOF)
460                 w.Flush()
461         }
462
463         {
464                 type symIdx struct {
465                         sym *types.Sym
466                         idx pkgbits.Index
467                 }
468                 var bodies []symIdx
469                 for sym, idx := range l.bodies {
470                         bodies = append(bodies, symIdx{sym, idx})
471                 }
472                 sort.Slice(bodies, func(i, j int) bool { return bodies[i].idx < bodies[j].idx })
473
474                 w := privateRootWriter
475
476                 w.Bool(typecheck.Lookup(".inittask").Def != nil)
477
478                 w.Len(len(bodies))
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)
483                 }
484
485                 w.Sync(pkgbits.SyncEOF)
486                 w.Flush()
487         }
488
489         base.Ctxt.Fingerprint = l.pw.DumpTo(out)
490 }