]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/reader.go
760170ddfc7c85d500bbe7173c3180a83f63157c
[gostls13.git] / src / cmd / compile / internal / noder / reader.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         "go/constant"
10         "internal/buildcfg"
11         "internal/goexperiment"
12         "internal/pkgbits"
13         "path/filepath"
14         "strings"
15
16         "cmd/compile/internal/base"
17         "cmd/compile/internal/dwarfgen"
18         "cmd/compile/internal/inline"
19         "cmd/compile/internal/ir"
20         "cmd/compile/internal/objw"
21         "cmd/compile/internal/reflectdata"
22         "cmd/compile/internal/staticinit"
23         "cmd/compile/internal/typecheck"
24         "cmd/compile/internal/types"
25         "cmd/internal/obj"
26         "cmd/internal/objabi"
27         "cmd/internal/src"
28 )
29
30 // This file implements cmd/compile backend's reader for the Unified
31 // IR export data.
32
33 // A pkgReader reads Unified IR export data.
34 type pkgReader struct {
35         pkgbits.PkgDecoder
36
37         // Indices for encoded things; lazily populated as needed.
38         //
39         // Note: Objects (i.e., ir.Names) are lazily instantiated by
40         // populating their types.Sym.Def; see objReader below.
41
42         posBases []*src.PosBase
43         pkgs     []*types.Pkg
44         typs     []*types.Type
45
46         // offset for rewriting the given (absolute!) index into the output,
47         // but bitwise inverted so we can detect if we're missing the entry
48         // or not.
49         newindex []pkgbits.Index
50 }
51
52 func newPkgReader(pr pkgbits.PkgDecoder) *pkgReader {
53         return &pkgReader{
54                 PkgDecoder: pr,
55
56                 posBases: make([]*src.PosBase, pr.NumElems(pkgbits.RelocPosBase)),
57                 pkgs:     make([]*types.Pkg, pr.NumElems(pkgbits.RelocPkg)),
58                 typs:     make([]*types.Type, pr.NumElems(pkgbits.RelocType)),
59
60                 newindex: make([]pkgbits.Index, pr.TotalElems()),
61         }
62 }
63
64 // A pkgReaderIndex compactly identifies an index (and its
65 // corresponding dictionary) within a package's export data.
66 type pkgReaderIndex struct {
67         pr        *pkgReader
68         idx       pkgbits.Index
69         dict      *readerDict
70         methodSym *types.Sym
71
72         synthetic func(pos src.XPos, r *reader)
73 }
74
75 func (pri pkgReaderIndex) asReader(k pkgbits.RelocKind, marker pkgbits.SyncMarker) *reader {
76         if pri.synthetic != nil {
77                 return &reader{synthetic: pri.synthetic}
78         }
79
80         r := pri.pr.newReader(k, pri.idx, marker)
81         r.dict = pri.dict
82         r.methodSym = pri.methodSym
83         return r
84 }
85
86 func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
87         return &reader{
88                 Decoder: pr.NewDecoder(k, idx, marker),
89                 p:       pr,
90         }
91 }
92
93 // A reader provides APIs for reading an individual element.
94 type reader struct {
95         pkgbits.Decoder
96
97         p *pkgReader
98
99         dict *readerDict
100
101         // TODO(mdempsky): The state below is all specific to reading
102         // function bodies. It probably makes sense to split it out
103         // separately so that it doesn't take up space in every reader
104         // instance.
105
106         curfn       *ir.Func
107         locals      []*ir.Name
108         closureVars []*ir.Name
109
110         funarghack bool
111
112         // methodSym is the name of method's name, if reading a method.
113         // It's nil if reading a normal function or closure body.
114         methodSym *types.Sym
115
116         // dictParam is the .dict param, if any.
117         dictParam *ir.Name
118
119         // synthetic is a callback function to construct a synthetic
120         // function body. It's used for creating the bodies of function
121         // literals used to curry arguments to shaped functions.
122         synthetic func(pos src.XPos, r *reader)
123
124         // scopeVars is a stack tracking the number of variables declared in
125         // the current function at the moment each open scope was opened.
126         scopeVars         []int
127         marker            dwarfgen.ScopeMarker
128         lastCloseScopePos src.XPos
129
130         // === details for handling inline body expansion ===
131
132         // If we're reading in a function body because of inlining, this is
133         // the call that we're inlining for.
134         inlCaller    *ir.Func
135         inlCall      *ir.CallExpr
136         inlFunc      *ir.Func
137         inlTreeIndex int
138         inlPosBases  map[*src.PosBase]*src.PosBase
139
140         // suppressInlPos tracks whether position base rewriting for
141         // inlining should be suppressed. See funcLit.
142         suppressInlPos int
143
144         delayResults bool
145
146         // Label to return to.
147         retlabel *types.Sym
148
149         // inlvars is the list of variables that the inlinee's arguments are
150         // assigned to, one for each receiver and normal parameter, in order.
151         inlvars ir.Nodes
152
153         // retvars is the list of variables that the inlinee's results are
154         // assigned to, one for each result parameter, in order.
155         retvars ir.Nodes
156 }
157
158 // A readerDict represents an instantiated "compile-time dictionary,"
159 // used for resolving any derived types needed for instantiating a
160 // generic object.
161 //
162 // A compile-time dictionary can either be "shaped" or "non-shaped."
163 // Shaped compile-time dictionaries are only used for instantiating
164 // shaped type definitions and function bodies, while non-shaped
165 // compile-time dictionaries are used for instantiating runtime
166 // dictionaries.
167 type readerDict struct {
168         shaped bool // whether this is a shaped dictionary
169
170         // baseSym is the symbol for the object this dictionary belongs to.
171         // If the object is an instantiated function or defined type, then
172         // baseSym is the mangled symbol, including any type arguments.
173         baseSym *types.Sym
174
175         // For non-shaped dictionaries, shapedObj is a reference to the
176         // corresponding shaped object (always a function or defined type).
177         shapedObj *ir.Name
178
179         // targs holds the implicit and explicit type arguments in use for
180         // reading the current object. For example:
181         //
182         //      func F[T any]() {
183         //              type X[U any] struct { t T; u U }
184         //              var _ X[string]
185         //      }
186         //
187         //      var _ = F[int]
188         //
189         // While instantiating F[int], we need to in turn instantiate
190         // X[string]. [int] and [string] are explicit type arguments for F
191         // and X, respectively; but [int] is also the implicit type
192         // arguments for X.
193         //
194         // (As an analogy to function literals, explicits are the function
195         // literal's formal parameters, while implicits are variables
196         // captured by the function literal.)
197         targs []*types.Type
198
199         // implicits counts how many of types within targs are implicit type
200         // arguments; the rest are explicit.
201         implicits int
202
203         derived      []derivedInfo // reloc index of the derived type's descriptor
204         derivedTypes []*types.Type // slice of previously computed derived types
205
206         // These slices correspond to entries in the runtime dictionary.
207         typeParamMethodExprs []readerMethodExprInfo
208         subdicts             []objInfo
209         rtypes               []typeInfo
210         itabs                []itabInfo
211 }
212
213 type readerMethodExprInfo struct {
214         typeParamIdx int
215         method       *types.Sym
216 }
217
218 func setType(n ir.Node, typ *types.Type) {
219         n.SetType(typ)
220         n.SetTypecheck(1)
221 }
222
223 func setValue(name *ir.Name, val constant.Value) {
224         name.SetVal(val)
225         name.Defn = nil
226 }
227
228 // @@@ Positions
229
230 // pos reads a position from the bitstream.
231 func (r *reader) pos() src.XPos {
232         return base.Ctxt.PosTable.XPos(r.pos0())
233 }
234
235 // origPos reads a position from the bitstream, and returns both the
236 // original raw position and an inlining-adjusted position.
237 func (r *reader) origPos() (origPos, inlPos src.XPos) {
238         r.suppressInlPos++
239         origPos = r.pos()
240         r.suppressInlPos--
241         inlPos = r.inlPos(origPos)
242         return
243 }
244
245 func (r *reader) pos0() src.Pos {
246         r.Sync(pkgbits.SyncPos)
247         if !r.Bool() {
248                 return src.NoPos
249         }
250
251         posBase := r.posBase()
252         line := r.Uint()
253         col := r.Uint()
254         return src.MakePos(posBase, line, col)
255 }
256
257 // posBase reads a position base from the bitstream.
258 func (r *reader) posBase() *src.PosBase {
259         return r.inlPosBase(r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase)))
260 }
261
262 // posBaseIdx returns the specified position base, reading it first if
263 // needed.
264 func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) *src.PosBase {
265         if b := pr.posBases[idx]; b != nil {
266                 return b
267         }
268
269         r := pr.newReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase)
270         var b *src.PosBase
271
272         absFilename := r.String()
273         filename := absFilename
274
275         // For build artifact stability, the export data format only
276         // contains the "absolute" filename as returned by objabi.AbsFile.
277         // However, some tests (e.g., test/run.go's asmcheck tests) expect
278         // to see the full, original filename printed out. Re-expanding
279         // "$GOROOT" to buildcfg.GOROOT is a close-enough approximation to
280         // satisfy this.
281         //
282         // The export data format only ever uses slash paths
283         // (for cross-operating-system reproducible builds),
284         // but error messages need to use native paths (backslash on Windows)
285         // as if they had been specified on the command line.
286         // (The go command always passes native paths to the compiler.)
287         const dollarGOROOT = "$GOROOT"
288         if buildcfg.GOROOT != "" && strings.HasPrefix(filename, dollarGOROOT) {
289                 filename = filepath.FromSlash(buildcfg.GOROOT + filename[len(dollarGOROOT):])
290         }
291
292         if r.Bool() {
293                 b = src.NewFileBase(filename, absFilename)
294         } else {
295                 pos := r.pos0()
296                 line := r.Uint()
297                 col := r.Uint()
298                 b = src.NewLinePragmaBase(pos, filename, absFilename, line, col)
299         }
300
301         pr.posBases[idx] = b
302         return b
303 }
304
305 // inlPosBase returns the inlining-adjusted src.PosBase corresponding
306 // to oldBase, which must be a non-inlined position. When not
307 // inlining, this is just oldBase.
308 func (r *reader) inlPosBase(oldBase *src.PosBase) *src.PosBase {
309         if index := oldBase.InliningIndex(); index >= 0 {
310                 base.Fatalf("oldBase %v already has inlining index %v", oldBase, index)
311         }
312
313         if r.inlCall == nil || r.suppressInlPos != 0 {
314                 return oldBase
315         }
316
317         if newBase, ok := r.inlPosBases[oldBase]; ok {
318                 return newBase
319         }
320
321         newBase := src.NewInliningBase(oldBase, r.inlTreeIndex)
322         r.inlPosBases[oldBase] = newBase
323         return newBase
324 }
325
326 // inlPos returns the inlining-adjusted src.XPos corresponding to
327 // xpos, which must be a non-inlined position. When not inlining, this
328 // is just xpos.
329 func (r *reader) inlPos(xpos src.XPos) src.XPos {
330         pos := base.Ctxt.PosTable.Pos(xpos)
331         pos.SetBase(r.inlPosBase(pos.Base()))
332         return base.Ctxt.PosTable.XPos(pos)
333 }
334
335 // @@@ Packages
336
337 // pkg reads a package reference from the bitstream.
338 func (r *reader) pkg() *types.Pkg {
339         r.Sync(pkgbits.SyncPkg)
340         return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg))
341 }
342
343 // pkgIdx returns the specified package from the export data, reading
344 // it first if needed.
345 func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Pkg {
346         if pkg := pr.pkgs[idx]; pkg != nil {
347                 return pkg
348         }
349
350         pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg()
351         pr.pkgs[idx] = pkg
352         return pkg
353 }
354
355 // doPkg reads a package definition from the bitstream.
356 func (r *reader) doPkg() *types.Pkg {
357         path := r.String()
358         switch path {
359         case "":
360                 path = r.p.PkgPath()
361         case "builtin":
362                 return types.BuiltinPkg
363         case "unsafe":
364                 return types.UnsafePkg
365         }
366
367         name := r.String()
368
369         pkg := types.NewPkg(path, "")
370
371         if pkg.Name == "" {
372                 pkg.Name = name
373         } else {
374                 base.Assertf(pkg.Name == name, "package %q has name %q, but want %q", pkg.Path, pkg.Name, name)
375         }
376
377         return pkg
378 }
379
380 // @@@ Types
381
382 func (r *reader) typ() *types.Type {
383         return r.typWrapped(true)
384 }
385
386 // typWrapped is like typ, but allows suppressing generation of
387 // unnecessary wrappers as a compile-time optimization.
388 func (r *reader) typWrapped(wrapped bool) *types.Type {
389         return r.p.typIdx(r.typInfo(), r.dict, wrapped)
390 }
391
392 func (r *reader) typInfo() typeInfo {
393         r.Sync(pkgbits.SyncType)
394         if r.Bool() {
395                 return typeInfo{idx: pkgbits.Index(r.Len()), derived: true}
396         }
397         return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false}
398 }
399
400 // typListIdx returns a list of the specified types, resolving derived
401 // types within the given dictionary.
402 func (pr *pkgReader) typListIdx(infos []typeInfo, dict *readerDict) []*types.Type {
403         typs := make([]*types.Type, len(infos))
404         for i, info := range infos {
405                 typs[i] = pr.typIdx(info, dict, true)
406         }
407         return typs
408 }
409
410 // typIdx returns the specified type. If info specifies a derived
411 // type, it's resolved within the given dictionary. If wrapped is
412 // true, then method wrappers will be generated, if appropriate.
413 func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict, wrapped bool) *types.Type {
414         idx := info.idx
415         var where **types.Type
416         if info.derived {
417                 where = &dict.derivedTypes[idx]
418                 idx = dict.derived[idx].idx
419         } else {
420                 where = &pr.typs[idx]
421         }
422
423         if typ := *where; typ != nil {
424                 return typ
425         }
426
427         r := pr.newReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx)
428         r.dict = dict
429
430         typ := r.doTyp()
431         assert(typ != nil)
432
433         // For recursive type declarations involving interfaces and aliases,
434         // above r.doTyp() call may have already set pr.typs[idx], so just
435         // double check and return the type.
436         //
437         // Example:
438         //
439         //     type F = func(I)
440         //
441         //     type I interface {
442         //         m(F)
443         //     }
444         //
445         // The writer writes data types in following index order:
446         //
447         //     0: func(I)
448         //     1: I
449         //     2: interface{m(func(I))}
450         //
451         // The reader resolves it in following index order:
452         //
453         //     0 -> 1 -> 2 -> 0 -> 1
454         //
455         // and can divide in logically 2 steps:
456         //
457         //  - 0 -> 1     : first time the reader reach type I,
458         //                 it creates new named type with symbol I.
459         //
460         //  - 2 -> 0 -> 1: the reader ends up reaching symbol I again,
461         //                 now the symbol I was setup in above step, so
462         //                 the reader just return the named type.
463         //
464         // Now, the functions called return, the pr.typs looks like below:
465         //
466         //  - 0 -> 1 -> 2 -> 0 : [<T> I <T>]
467         //  - 0 -> 1 -> 2      : [func(I) I <T>]
468         //  - 0 -> 1           : [func(I) I interface { "".m(func("".I)) }]
469         //
470         // The idx 1, corresponding with type I was resolved successfully
471         // after r.doTyp() call.
472
473         if prev := *where; prev != nil {
474                 return prev
475         }
476
477         if wrapped {
478                 // Only cache if we're adding wrappers, so that other callers that
479                 // find a cached type know it was wrapped.
480                 *where = typ
481
482                 r.needWrapper(typ)
483         }
484
485         if !typ.IsUntyped() {
486                 types.CheckSize(typ)
487         }
488
489         return typ
490 }
491
492 func (r *reader) doTyp() *types.Type {
493         switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag {
494         default:
495                 panic(fmt.Sprintf("unexpected type: %v", tag))
496
497         case pkgbits.TypeBasic:
498                 return *basics[r.Len()]
499
500         case pkgbits.TypeNamed:
501                 obj := r.obj()
502                 assert(obj.Op() == ir.OTYPE)
503                 return obj.Type()
504
505         case pkgbits.TypeTypeParam:
506                 return r.dict.targs[r.Len()]
507
508         case pkgbits.TypeArray:
509                 len := int64(r.Uint64())
510                 return types.NewArray(r.typ(), len)
511         case pkgbits.TypeChan:
512                 dir := dirs[r.Len()]
513                 return types.NewChan(r.typ(), dir)
514         case pkgbits.TypeMap:
515                 return types.NewMap(r.typ(), r.typ())
516         case pkgbits.TypePointer:
517                 return types.NewPtr(r.typ())
518         case pkgbits.TypeSignature:
519                 return r.signature(nil)
520         case pkgbits.TypeSlice:
521                 return types.NewSlice(r.typ())
522         case pkgbits.TypeStruct:
523                 return r.structType()
524         case pkgbits.TypeInterface:
525                 return r.interfaceType()
526         case pkgbits.TypeUnion:
527                 return r.unionType()
528         }
529 }
530
531 func (r *reader) unionType() *types.Type {
532         // In the types1 universe, we only need to handle value types.
533         // Impure interfaces (i.e., interfaces with non-trivial type sets
534         // like "int | string") can only appear as type parameter bounds,
535         // and this is enforced by the types2 type checker.
536         //
537         // However, type unions can still appear in pure interfaces if the
538         // type union is equivalent to "any". E.g., typeparam/issue52124.go
539         // declares variables with the type "interface { any | int }".
540         //
541         // To avoid needing to represent type unions in types1 (since we
542         // don't have any uses for that today anyway), we simply fold them
543         // to "any".
544
545         // TODO(mdempsky): Restore consistency check to make sure folding to
546         // "any" is safe. This is unfortunately tricky, because a pure
547         // interface can reference impure interfaces too, including
548         // cyclically (#60117).
549         if false {
550                 pure := false
551                 for i, n := 0, r.Len(); i < n; i++ {
552                         _ = r.Bool() // tilde
553                         term := r.typ()
554                         if term.IsEmptyInterface() {
555                                 pure = true
556                         }
557                 }
558                 if !pure {
559                         base.Fatalf("impure type set used in value type")
560                 }
561         }
562
563         return types.Types[types.TINTER]
564 }
565
566 func (r *reader) interfaceType() *types.Type {
567         nmethods, nembeddeds := r.Len(), r.Len()
568         implicit := nmethods == 0 && nembeddeds == 1 && r.Bool()
569         assert(!implicit) // implicit interfaces only appear in constraints
570
571         fields := make([]*types.Field, nmethods+nembeddeds)
572         methods, embeddeds := fields[:nmethods], fields[nmethods:]
573
574         for i := range methods {
575                 pos := r.pos()
576                 _, sym := r.selector()
577                 mtyp := r.signature(types.FakeRecv())
578                 methods[i] = types.NewField(pos, sym, mtyp)
579         }
580         for i := range embeddeds {
581                 embeddeds[i] = types.NewField(src.NoXPos, nil, r.typ())
582         }
583
584         if len(fields) == 0 {
585                 return types.Types[types.TINTER] // empty interface
586         }
587         return types.NewInterface(fields)
588 }
589
590 func (r *reader) structType() *types.Type {
591         fields := make([]*types.Field, r.Len())
592         for i := range fields {
593                 pos := r.pos()
594                 _, sym := r.selector()
595                 ftyp := r.typ()
596                 tag := r.String()
597                 embedded := r.Bool()
598
599                 f := types.NewField(pos, sym, ftyp)
600                 f.Note = tag
601                 if embedded {
602                         f.Embedded = 1
603                 }
604                 fields[i] = f
605         }
606         return types.NewStruct(fields)
607 }
608
609 func (r *reader) signature(recv *types.Field) *types.Type {
610         r.Sync(pkgbits.SyncSignature)
611
612         params := r.params()
613         results := r.params()
614         if r.Bool() { // variadic
615                 params[len(params)-1].SetIsDDD(true)
616         }
617
618         return types.NewSignature(recv, params, results)
619 }
620
621 func (r *reader) params() []*types.Field {
622         r.Sync(pkgbits.SyncParams)
623         fields := make([]*types.Field, r.Len())
624         for i := range fields {
625                 _, fields[i] = r.param()
626         }
627         return fields
628 }
629
630 func (r *reader) param() (*types.Pkg, *types.Field) {
631         r.Sync(pkgbits.SyncParam)
632
633         pos := r.pos()
634         pkg, sym := r.localIdent()
635         typ := r.typ()
636
637         return pkg, types.NewField(pos, sym, typ)
638 }
639
640 // @@@ Objects
641
642 // objReader maps qualified identifiers (represented as *types.Sym) to
643 // a pkgReader and corresponding index that can be used for reading
644 // that object's definition.
645 var objReader = map[*types.Sym]pkgReaderIndex{}
646
647 // obj reads an instantiated object reference from the bitstream.
648 func (r *reader) obj() ir.Node {
649         return r.p.objInstIdx(r.objInfo(), r.dict, false)
650 }
651
652 // objInfo reads an instantiated object reference from the bitstream
653 // and returns the encoded reference to it, without instantiating it.
654 func (r *reader) objInfo() objInfo {
655         r.Sync(pkgbits.SyncObject)
656         assert(!r.Bool()) // TODO(mdempsky): Remove; was derived func inst.
657         idx := r.Reloc(pkgbits.RelocObj)
658
659         explicits := make([]typeInfo, r.Len())
660         for i := range explicits {
661                 explicits[i] = r.typInfo()
662         }
663
664         return objInfo{idx, explicits}
665 }
666
667 // objInstIdx returns the encoded, instantiated object. If shaped is
668 // true, then the shaped variant of the object is returned instead.
669 func (pr *pkgReader) objInstIdx(info objInfo, dict *readerDict, shaped bool) ir.Node {
670         explicits := pr.typListIdx(info.explicits, dict)
671
672         var implicits []*types.Type
673         if dict != nil {
674                 implicits = dict.targs
675         }
676
677         return pr.objIdx(info.idx, implicits, explicits, shaped)
678 }
679
680 // objIdx returns the specified object, instantiated with the given
681 // type arguments, if any. If shaped is true, then the shaped variant
682 // of the object is returned instead.
683 func (pr *pkgReader) objIdx(idx pkgbits.Index, implicits, explicits []*types.Type, shaped bool) ir.Node {
684         rname := pr.newReader(pkgbits.RelocName, idx, pkgbits.SyncObject1)
685         _, sym := rname.qualifiedIdent()
686         tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
687
688         if tag == pkgbits.ObjStub {
689                 assert(!sym.IsBlank())
690                 switch sym.Pkg {
691                 case types.BuiltinPkg, types.UnsafePkg:
692                         return sym.Def.(ir.Node)
693                 }
694                 if pri, ok := objReader[sym]; ok {
695                         return pri.pr.objIdx(pri.idx, nil, explicits, shaped)
696                 }
697                 base.Fatalf("unresolved stub: %v", sym)
698         }
699
700         dict := pr.objDictIdx(sym, idx, implicits, explicits, shaped)
701
702         sym = dict.baseSym
703         if !sym.IsBlank() && sym.Def != nil {
704                 return sym.Def.(*ir.Name)
705         }
706
707         r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1)
708         rext := pr.newReader(pkgbits.RelocObjExt, idx, pkgbits.SyncObject1)
709
710         r.dict = dict
711         rext.dict = dict
712
713         do := func(op ir.Op, hasTParams bool) *ir.Name {
714                 pos := r.pos()
715                 setBasePos(pos)
716                 if hasTParams {
717                         r.typeParamNames()
718                 }
719
720                 name := ir.NewDeclNameAt(pos, op, sym)
721                 name.Class = ir.PEXTERN // may be overridden later
722                 if !sym.IsBlank() {
723                         if sym.Def != nil {
724                                 base.FatalfAt(name.Pos(), "already have a definition for %v", name)
725                         }
726                         assert(sym.Def == nil)
727                         sym.Def = name
728                 }
729                 return name
730         }
731
732         switch tag {
733         default:
734                 panic("unexpected object")
735
736         case pkgbits.ObjAlias:
737                 name := do(ir.OTYPE, false)
738                 setType(name, r.typ())
739                 name.SetAlias(true)
740                 return name
741
742         case pkgbits.ObjConst:
743                 name := do(ir.OLITERAL, false)
744                 typ := r.typ()
745                 val := FixValue(typ, r.Value())
746                 setType(name, typ)
747                 setValue(name, val)
748                 return name
749
750         case pkgbits.ObjFunc:
751                 if sym.Name == "init" {
752                         sym = Renameinit()
753                 }
754
755                 npos := r.pos()
756                 setBasePos(npos)
757                 r.typeParamNames()
758                 typ := r.signature(nil)
759                 fpos := r.pos()
760
761                 fn := ir.NewFunc(fpos, npos, sym, typ)
762                 name := fn.Nname
763                 if !sym.IsBlank() {
764                         if sym.Def != nil {
765                                 base.FatalfAt(name.Pos(), "already have a definition for %v", name)
766                         }
767                         assert(sym.Def == nil)
768                         sym.Def = name
769                 }
770
771                 if r.hasTypeParams() {
772                         name.Func.SetDupok(true)
773                         if r.dict.shaped {
774                                 setType(name, shapeSig(name.Func, r.dict))
775                         } else {
776                                 todoDicts = append(todoDicts, func() {
777                                         r.dict.shapedObj = pr.objIdx(idx, implicits, explicits, true).(*ir.Name)
778                                 })
779                         }
780                 }
781
782                 rext.funcExt(name, nil)
783                 return name
784
785         case pkgbits.ObjType:
786                 name := do(ir.OTYPE, true)
787                 typ := types.NewNamed(name)
788                 setType(name, typ)
789                 if r.hasTypeParams() && r.dict.shaped {
790                         typ.SetHasShape(true)
791                 }
792
793                 // Important: We need to do this before SetUnderlying.
794                 rext.typeExt(name)
795
796                 // We need to defer CheckSize until we've called SetUnderlying to
797                 // handle recursive types.
798                 types.DeferCheckSize()
799                 typ.SetUnderlying(r.typWrapped(false))
800                 types.ResumeCheckSize()
801
802                 if r.hasTypeParams() && !r.dict.shaped {
803                         todoDicts = append(todoDicts, func() {
804                                 r.dict.shapedObj = pr.objIdx(idx, implicits, explicits, true).(*ir.Name)
805                         })
806                 }
807
808                 methods := make([]*types.Field, r.Len())
809                 for i := range methods {
810                         methods[i] = r.method(rext)
811                 }
812                 if len(methods) != 0 {
813                         typ.SetMethods(methods)
814                 }
815
816                 if !r.dict.shaped {
817                         r.needWrapper(typ)
818                 }
819
820                 return name
821
822         case pkgbits.ObjVar:
823                 name := do(ir.ONAME, false)
824                 setType(name, r.typ())
825                 rext.varExt(name)
826                 return name
827         }
828 }
829
830 func (dict *readerDict) mangle(sym *types.Sym) *types.Sym {
831         if !dict.hasTypeParams() {
832                 return sym
833         }
834
835         // If sym is a locally defined generic type, we need the suffix to
836         // stay at the end after mangling so that types/fmt.go can strip it
837         // out again when writing the type's runtime descriptor (#54456).
838         base, suffix := types.SplitVargenSuffix(sym.Name)
839
840         var buf strings.Builder
841         buf.WriteString(base)
842         buf.WriteByte('[')
843         for i, targ := range dict.targs {
844                 if i > 0 {
845                         if i == dict.implicits {
846                                 buf.WriteByte(';')
847                         } else {
848                                 buf.WriteByte(',')
849                         }
850                 }
851                 buf.WriteString(targ.LinkString())
852         }
853         buf.WriteByte(']')
854         buf.WriteString(suffix)
855         return sym.Pkg.Lookup(buf.String())
856 }
857
858 // shapify returns the shape type for targ.
859 //
860 // If basic is true, then the type argument is used to instantiate a
861 // type parameter whose constraint is a basic interface.
862 func shapify(targ *types.Type, basic bool) *types.Type {
863         if targ.Kind() == types.TFORW {
864                 if targ.IsFullyInstantiated() {
865                         // For recursive instantiated type argument, it may  still be a TFORW
866                         // when shapifying happens. If we don't have targ's underlying type,
867                         // shapify won't work. The worst case is we end up not reusing code
868                         // optimally in some tricky cases.
869                         if base.Debug.Shapify != 0 {
870                                 base.Warn("skipping shaping of recursive type %v", targ)
871                         }
872                         if targ.HasShape() {
873                                 return targ
874                         }
875                 } else {
876                         base.Fatalf("%v is missing its underlying type", targ)
877                 }
878         }
879
880         // When a pointer type is used to instantiate a type parameter
881         // constrained by a basic interface, we know the pointer's element
882         // type can't matter to the generated code. In this case, we can use
883         // an arbitrary pointer type as the shape type. (To match the
884         // non-unified frontend, we use `*byte`.)
885         //
886         // Otherwise, we simply use the type's underlying type as its shape.
887         //
888         // TODO(mdempsky): It should be possible to do much more aggressive
889         // shaping still; e.g., collapsing all pointer-shaped types into a
890         // common type, collapsing scalars of the same size/alignment into a
891         // common type, recursively shaping the element types of composite
892         // types, and discarding struct field names and tags. However, we'll
893         // need to start tracking how type parameters are actually used to
894         // implement some of these optimizations.
895         under := targ.Underlying()
896         if basic && targ.IsPtr() && !targ.Elem().NotInHeap() {
897                 under = types.NewPtr(types.Types[types.TUINT8])
898         }
899
900         sym := types.ShapePkg.Lookup(under.LinkString())
901         if sym.Def == nil {
902                 name := ir.NewDeclNameAt(under.Pos(), ir.OTYPE, sym)
903                 typ := types.NewNamed(name)
904                 typ.SetUnderlying(under)
905                 sym.Def = typed(typ, name)
906         }
907         res := sym.Def.Type()
908         assert(res.IsShape())
909         assert(res.HasShape())
910         return res
911 }
912
913 // objDictIdx reads and returns the specified object dictionary.
914 func (pr *pkgReader) objDictIdx(sym *types.Sym, idx pkgbits.Index, implicits, explicits []*types.Type, shaped bool) *readerDict {
915         r := pr.newReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1)
916
917         dict := readerDict{
918                 shaped: shaped,
919         }
920
921         nimplicits := r.Len()
922         nexplicits := r.Len()
923
924         if nimplicits > len(implicits) || nexplicits != len(explicits) {
925                 base.Fatalf("%v has %v+%v params, but instantiated with %v+%v args", sym, nimplicits, nexplicits, len(implicits), len(explicits))
926         }
927
928         dict.targs = append(implicits[:nimplicits:nimplicits], explicits...)
929         dict.implicits = nimplicits
930
931         // Within the compiler, we can just skip over the type parameters.
932         for range dict.targs[dict.implicits:] {
933                 // Skip past bounds without actually evaluating them.
934                 r.typInfo()
935         }
936
937         dict.derived = make([]derivedInfo, r.Len())
938         dict.derivedTypes = make([]*types.Type, len(dict.derived))
939         for i := range dict.derived {
940                 dict.derived[i] = derivedInfo{r.Reloc(pkgbits.RelocType), r.Bool()}
941         }
942
943         // Runtime dictionary information; private to the compiler.
944
945         // If any type argument is already shaped, then we're constructing a
946         // shaped object, even if not explicitly requested (i.e., calling
947         // objIdx with shaped==true). This can happen with instantiating
948         // types that are referenced within a function body.
949         for _, targ := range dict.targs {
950                 if targ.HasShape() {
951                         dict.shaped = true
952                         break
953                 }
954         }
955
956         // And if we're constructing a shaped object, then shapify all type
957         // arguments.
958         for i, targ := range dict.targs {
959                 basic := r.Bool()
960                 if dict.shaped {
961                         dict.targs[i] = shapify(targ, basic)
962                 }
963         }
964
965         dict.baseSym = dict.mangle(sym)
966
967         dict.typeParamMethodExprs = make([]readerMethodExprInfo, r.Len())
968         for i := range dict.typeParamMethodExprs {
969                 typeParamIdx := r.Len()
970                 _, method := r.selector()
971
972                 dict.typeParamMethodExprs[i] = readerMethodExprInfo{typeParamIdx, method}
973         }
974
975         dict.subdicts = make([]objInfo, r.Len())
976         for i := range dict.subdicts {
977                 dict.subdicts[i] = r.objInfo()
978         }
979
980         dict.rtypes = make([]typeInfo, r.Len())
981         for i := range dict.rtypes {
982                 dict.rtypes[i] = r.typInfo()
983         }
984
985         dict.itabs = make([]itabInfo, r.Len())
986         for i := range dict.itabs {
987                 dict.itabs[i] = itabInfo{typ: r.typInfo(), iface: r.typInfo()}
988         }
989
990         return &dict
991 }
992
993 func (r *reader) typeParamNames() {
994         r.Sync(pkgbits.SyncTypeParamNames)
995
996         for range r.dict.targs[r.dict.implicits:] {
997                 r.pos()
998                 r.localIdent()
999         }
1000 }
1001
1002 func (r *reader) method(rext *reader) *types.Field {
1003         r.Sync(pkgbits.SyncMethod)
1004         npos := r.pos()
1005         _, sym := r.selector()
1006         r.typeParamNames()
1007         _, recv := r.param()
1008         typ := r.signature(recv)
1009
1010         fpos := r.pos()
1011         fn := ir.NewFunc(fpos, npos, ir.MethodSym(recv.Type, sym), typ)
1012         name := fn.Nname
1013
1014         if r.hasTypeParams() {
1015                 name.Func.SetDupok(true)
1016                 if r.dict.shaped {
1017                         typ = shapeSig(name.Func, r.dict)
1018                         setType(name, typ)
1019                 }
1020         }
1021
1022         rext.funcExt(name, sym)
1023
1024         meth := types.NewField(name.Func.Pos(), sym, typ)
1025         meth.Nname = name
1026         meth.SetNointerface(name.Func.Pragma&ir.Nointerface != 0)
1027
1028         return meth
1029 }
1030
1031 func (r *reader) qualifiedIdent() (pkg *types.Pkg, sym *types.Sym) {
1032         r.Sync(pkgbits.SyncSym)
1033         pkg = r.pkg()
1034         if name := r.String(); name != "" {
1035                 sym = pkg.Lookup(name)
1036         }
1037         return
1038 }
1039
1040 func (r *reader) localIdent() (pkg *types.Pkg, sym *types.Sym) {
1041         r.Sync(pkgbits.SyncLocalIdent)
1042         pkg = r.pkg()
1043         if name := r.String(); name != "" {
1044                 sym = pkg.Lookup(name)
1045         }
1046         return
1047 }
1048
1049 func (r *reader) selector() (origPkg *types.Pkg, sym *types.Sym) {
1050         r.Sync(pkgbits.SyncSelector)
1051         origPkg = r.pkg()
1052         name := r.String()
1053         pkg := origPkg
1054         if types.IsExported(name) {
1055                 pkg = types.LocalPkg
1056         }
1057         sym = pkg.Lookup(name)
1058         return
1059 }
1060
1061 func (r *reader) hasTypeParams() bool {
1062         return r.dict.hasTypeParams()
1063 }
1064
1065 func (dict *readerDict) hasTypeParams() bool {
1066         return dict != nil && len(dict.targs) != 0
1067 }
1068
1069 // @@@ Compiler extensions
1070
1071 func (r *reader) funcExt(name *ir.Name, method *types.Sym) {
1072         r.Sync(pkgbits.SyncFuncExt)
1073
1074         fn := name.Func
1075
1076         // XXX: Workaround because linker doesn't know how to copy Pos.
1077         if !fn.Pos().IsKnown() {
1078                 fn.SetPos(name.Pos())
1079         }
1080
1081         // Normally, we only compile local functions, which saves redundant compilation work.
1082         // n.Defn is not nil for local functions, and is nil for imported function. But for
1083         // generic functions, we might have an instantiation that no other package has seen before.
1084         // So we need to be conservative and compile it again.
1085         //
1086         // That's why name.Defn is set here, so ir.VisitFuncsBottomUp can analyze function.
1087         // TODO(mdempsky,cuonglm): find a cleaner way to handle this.
1088         if name.Sym().Pkg == types.LocalPkg || r.hasTypeParams() {
1089                 name.Defn = fn
1090         }
1091
1092         fn.Pragma = r.pragmaFlag()
1093         r.linkname(name)
1094
1095         if buildcfg.GOARCH == "wasm" {
1096                 xmod := r.String()
1097                 xname := r.String()
1098
1099                 if xmod != "" && xname != "" {
1100                         fn.WasmImport = &ir.WasmImport{
1101                                 Module: xmod,
1102                                 Name:   xname,
1103                         }
1104                 }
1105         }
1106
1107         if r.Bool() {
1108                 assert(name.Defn == nil)
1109
1110                 fn.ABI = obj.ABI(r.Uint64())
1111
1112                 // Escape analysis.
1113                 for _, f := range name.Type().RecvParams() {
1114                         f.Note = r.String()
1115                 }
1116
1117                 if r.Bool() {
1118                         fn.Inl = &ir.Inline{
1119                                 Cost:            int32(r.Len()),
1120                                 CanDelayResults: r.Bool(),
1121                         }
1122                         if goexperiment.NewInliner {
1123                                 fn.Inl.Properties = r.String()
1124                         }
1125                 }
1126         } else {
1127                 r.addBody(name.Func, method)
1128         }
1129         r.Sync(pkgbits.SyncEOF)
1130 }
1131
1132 func (r *reader) typeExt(name *ir.Name) {
1133         r.Sync(pkgbits.SyncTypeExt)
1134
1135         typ := name.Type()
1136
1137         if r.hasTypeParams() {
1138                 // Set "RParams" (really type arguments here, not parameters) so
1139                 // this type is treated as "fully instantiated". This ensures the
1140                 // type descriptor is written out as DUPOK and method wrappers are
1141                 // generated even for imported types.
1142                 var targs []*types.Type
1143                 targs = append(targs, r.dict.targs...)
1144                 typ.SetRParams(targs)
1145         }
1146
1147         name.SetPragma(r.pragmaFlag())
1148
1149         typecheck.SetBaseTypeIndex(typ, r.Int64(), r.Int64())
1150 }
1151
1152 func (r *reader) varExt(name *ir.Name) {
1153         r.Sync(pkgbits.SyncVarExt)
1154         r.linkname(name)
1155 }
1156
1157 func (r *reader) linkname(name *ir.Name) {
1158         assert(name.Op() == ir.ONAME)
1159         r.Sync(pkgbits.SyncLinkname)
1160
1161         if idx := r.Int64(); idx >= 0 {
1162                 lsym := name.Linksym()
1163                 lsym.SymIdx = int32(idx)
1164                 lsym.Set(obj.AttrIndexed, true)
1165         } else {
1166                 name.Sym().Linkname = r.String()
1167         }
1168 }
1169
1170 func (r *reader) pragmaFlag() ir.PragmaFlag {
1171         r.Sync(pkgbits.SyncPragma)
1172         return ir.PragmaFlag(r.Int())
1173 }
1174
1175 // @@@ Function bodies
1176
1177 // bodyReader tracks where the serialized IR for a local or imported,
1178 // generic function's body can be found.
1179 var bodyReader = map[*ir.Func]pkgReaderIndex{}
1180
1181 // importBodyReader tracks where the serialized IR for an imported,
1182 // static (i.e., non-generic) function body can be read.
1183 var importBodyReader = map[*types.Sym]pkgReaderIndex{}
1184
1185 // bodyReaderFor returns the pkgReaderIndex for reading fn's
1186 // serialized IR, and whether one was found.
1187 func bodyReaderFor(fn *ir.Func) (pri pkgReaderIndex, ok bool) {
1188         if fn.Nname.Defn != nil {
1189                 pri, ok = bodyReader[fn]
1190                 base.AssertfAt(ok, base.Pos, "must have bodyReader for %v", fn) // must always be available
1191         } else {
1192                 pri, ok = importBodyReader[fn.Sym()]
1193         }
1194         return
1195 }
1196
1197 // todoDicts holds the list of dictionaries that still need their
1198 // runtime dictionary objects constructed.
1199 var todoDicts []func()
1200
1201 // todoBodies holds the list of function bodies that still need to be
1202 // constructed.
1203 var todoBodies []*ir.Func
1204
1205 // addBody reads a function body reference from the element bitstream,
1206 // and associates it with fn.
1207 func (r *reader) addBody(fn *ir.Func, method *types.Sym) {
1208         // addBody should only be called for local functions or imported
1209         // generic functions; see comment in funcExt.
1210         assert(fn.Nname.Defn != nil)
1211
1212         idx := r.Reloc(pkgbits.RelocBody)
1213
1214         pri := pkgReaderIndex{r.p, idx, r.dict, method, nil}
1215         bodyReader[fn] = pri
1216
1217         if r.curfn == nil {
1218                 todoBodies = append(todoBodies, fn)
1219                 return
1220         }
1221
1222         pri.funcBody(fn)
1223 }
1224
1225 func (pri pkgReaderIndex) funcBody(fn *ir.Func) {
1226         r := pri.asReader(pkgbits.RelocBody, pkgbits.SyncFuncBody)
1227         r.funcBody(fn)
1228 }
1229
1230 // funcBody reads a function body definition from the element
1231 // bitstream, and populates fn with it.
1232 func (r *reader) funcBody(fn *ir.Func) {
1233         r.curfn = fn
1234         r.closureVars = fn.ClosureVars
1235         if len(r.closureVars) != 0 && r.hasTypeParams() {
1236                 r.dictParam = r.closureVars[len(r.closureVars)-1] // dictParam is last; see reader.funcLit
1237         }
1238
1239         ir.WithFunc(fn, func() {
1240                 r.funcargs(fn)
1241
1242                 if r.syntheticBody(fn.Pos()) {
1243                         return
1244                 }
1245
1246                 if !r.Bool() {
1247                         return
1248                 }
1249
1250                 body := r.stmts()
1251                 if body == nil {
1252                         body = []ir.Node{typecheck.Stmt(ir.NewBlockStmt(src.NoXPos, nil))}
1253                 }
1254                 fn.Body = body
1255                 fn.Endlineno = r.pos()
1256         })
1257
1258         r.marker.WriteTo(fn)
1259 }
1260
1261 // syntheticBody adds a synthetic body to r.curfn if appropriate, and
1262 // reports whether it did.
1263 func (r *reader) syntheticBody(pos src.XPos) bool {
1264         if r.synthetic != nil {
1265                 r.synthetic(pos, r)
1266                 return true
1267         }
1268
1269         // If this function has type parameters and isn't shaped, then we
1270         // just tail call its corresponding shaped variant.
1271         if r.hasTypeParams() && !r.dict.shaped {
1272                 r.callShaped(pos)
1273                 return true
1274         }
1275
1276         return false
1277 }
1278
1279 // callShaped emits a tail call to r.shapedFn, passing along the
1280 // arguments to the current function.
1281 func (r *reader) callShaped(pos src.XPos) {
1282         shapedObj := r.dict.shapedObj
1283         assert(shapedObj != nil)
1284
1285         var shapedFn ir.Node
1286         if r.methodSym == nil {
1287                 // Instantiating a generic function; shapedObj is the shaped
1288                 // function itself.
1289                 assert(shapedObj.Op() == ir.ONAME && shapedObj.Class == ir.PFUNC)
1290                 shapedFn = shapedObj
1291         } else {
1292                 // Instantiating a generic type's method; shapedObj is the shaped
1293                 // type, so we need to select it's corresponding method.
1294                 shapedFn = shapedMethodExpr(pos, shapedObj, r.methodSym)
1295         }
1296
1297         recvs, params := r.syntheticArgs(pos)
1298
1299         // Construct the arguments list: receiver (if any), then runtime
1300         // dictionary, and finally normal parameters.
1301         //
1302         // Note: For simplicity, shaped methods are added as normal methods
1303         // on their shaped types. So existing code (e.g., packages ir and
1304         // typecheck) expects the shaped type to appear as the receiver
1305         // parameter (or first parameter, as a method expression). Hence
1306         // putting the dictionary parameter after that is the least invasive
1307         // solution at the moment.
1308         var args ir.Nodes
1309         args.Append(recvs...)
1310         args.Append(typecheck.Expr(ir.NewAddrExpr(pos, r.p.dictNameOf(r.dict))))
1311         args.Append(params...)
1312
1313         r.syntheticTailCall(pos, shapedFn, args)
1314 }
1315
1316 // syntheticArgs returns the recvs and params arguments passed to the
1317 // current function.
1318 func (r *reader) syntheticArgs(pos src.XPos) (recvs, params ir.Nodes) {
1319         sig := r.curfn.Nname.Type()
1320
1321         inlVarIdx := 0
1322         addParams := func(out *ir.Nodes, params []*types.Field) {
1323                 for _, param := range params {
1324                         var arg ir.Node
1325                         if param.Nname != nil {
1326                                 name := param.Nname.(*ir.Name)
1327                                 if !ir.IsBlank(name) {
1328                                         if r.inlCall != nil {
1329                                                 // During inlining, we want the respective inlvar where we
1330                                                 // assigned the callee's arguments.
1331                                                 arg = r.inlvars[inlVarIdx]
1332                                         } else {
1333                                                 // Otherwise, we can use the parameter itself directly.
1334                                                 base.AssertfAt(name.Curfn == r.curfn, name.Pos(), "%v has curfn %v, but want %v", name, name.Curfn, r.curfn)
1335                                                 arg = name
1336                                         }
1337                                 }
1338                         }
1339
1340                         // For anonymous and blank parameters, we don't have an *ir.Name
1341                         // to use as the argument. However, since we know the shaped
1342                         // function won't use the value either, we can just pass the
1343                         // zero value.
1344                         if arg == nil {
1345                                 arg = ir.NewZero(pos, param.Type)
1346                         }
1347
1348                         out.Append(arg)
1349                         inlVarIdx++
1350                 }
1351         }
1352
1353         addParams(&recvs, sig.Recvs())
1354         addParams(&params, sig.Params())
1355         return
1356 }
1357
1358 // syntheticTailCall emits a tail call to fn, passing the given
1359 // arguments list.
1360 func (r *reader) syntheticTailCall(pos src.XPos, fn ir.Node, args ir.Nodes) {
1361         // Mark the function as a wrapper so it doesn't show up in stack
1362         // traces.
1363         r.curfn.SetWrapper(true)
1364
1365         call := typecheck.Call(pos, fn, args, fn.Type().IsVariadic()).(*ir.CallExpr)
1366
1367         var stmt ir.Node
1368         if fn.Type().NumResults() != 0 {
1369                 stmt = typecheck.Stmt(ir.NewReturnStmt(pos, []ir.Node{call}))
1370         } else {
1371                 stmt = call
1372         }
1373         r.curfn.Body.Append(stmt)
1374 }
1375
1376 // dictNameOf returns the runtime dictionary corresponding to dict.
1377 func (pr *pkgReader) dictNameOf(dict *readerDict) *ir.Name {
1378         pos := base.AutogeneratedPos
1379
1380         // Check that we only instantiate runtime dictionaries with real types.
1381         base.AssertfAt(!dict.shaped, pos, "runtime dictionary of shaped object %v", dict.baseSym)
1382
1383         sym := dict.baseSym.Pkg.Lookup(objabi.GlobalDictPrefix + "." + dict.baseSym.Name)
1384         if sym.Def != nil {
1385                 return sym.Def.(*ir.Name)
1386         }
1387
1388         name := ir.NewNameAt(pos, sym, dict.varType())
1389         name.Class = ir.PEXTERN
1390         sym.Def = name // break cycles with mutual subdictionaries
1391
1392         lsym := name.Linksym()
1393         ot := 0
1394
1395         assertOffset := func(section string, offset int) {
1396                 base.AssertfAt(ot == offset*types.PtrSize, pos, "writing section %v at offset %v, but it should be at %v*%v", section, ot, offset, types.PtrSize)
1397         }
1398
1399         assertOffset("type param method exprs", dict.typeParamMethodExprsOffset())
1400         for _, info := range dict.typeParamMethodExprs {
1401                 typeParam := dict.targs[info.typeParamIdx]
1402                 method := typecheck.NewMethodExpr(pos, typeParam, info.method)
1403
1404                 rsym := method.FuncName().Linksym()
1405                 assert(rsym.ABI() == obj.ABIInternal) // must be ABIInternal; see ir.OCFUNC in ssagen/ssa.go
1406
1407                 ot = objw.SymPtr(lsym, ot, rsym, 0)
1408         }
1409
1410         assertOffset("subdictionaries", dict.subdictsOffset())
1411         for _, info := range dict.subdicts {
1412                 explicits := pr.typListIdx(info.explicits, dict)
1413
1414                 // Careful: Due to subdictionary cycles, name may not be fully
1415                 // initialized yet.
1416                 name := pr.objDictName(info.idx, dict.targs, explicits)
1417
1418                 ot = objw.SymPtr(lsym, ot, name.Linksym(), 0)
1419         }
1420
1421         assertOffset("rtypes", dict.rtypesOffset())
1422         for _, info := range dict.rtypes {
1423                 typ := pr.typIdx(info, dict, true)
1424                 ot = objw.SymPtr(lsym, ot, reflectdata.TypeLinksym(typ), 0)
1425
1426                 // TODO(mdempsky): Double check this.
1427                 reflectdata.MarkTypeUsedInInterface(typ, lsym)
1428         }
1429
1430         // For each (typ, iface) pair, we write the *runtime.itab pointer
1431         // for the pair. For pairs that don't actually require an itab
1432         // (i.e., typ is an interface, or iface is an empty interface), we
1433         // write a nil pointer instead. This is wasteful, but rare in
1434         // practice (e.g., instantiating a type parameter with an interface
1435         // type).
1436         assertOffset("itabs", dict.itabsOffset())
1437         for _, info := range dict.itabs {
1438                 typ := pr.typIdx(info.typ, dict, true)
1439                 iface := pr.typIdx(info.iface, dict, true)
1440
1441                 if !typ.IsInterface() && iface.IsInterface() && !iface.IsEmptyInterface() {
1442                         ot = objw.SymPtr(lsym, ot, reflectdata.ITabLsym(typ, iface), 0)
1443                 } else {
1444                         ot += types.PtrSize
1445                 }
1446
1447                 // TODO(mdempsky): Double check this.
1448                 reflectdata.MarkTypeUsedInInterface(typ, lsym)
1449                 reflectdata.MarkTypeUsedInInterface(iface, lsym)
1450         }
1451
1452         objw.Global(lsym, int32(ot), obj.DUPOK|obj.RODATA)
1453
1454         return name
1455 }
1456
1457 // typeParamMethodExprsOffset returns the offset of the runtime
1458 // dictionary's type parameter method expressions section, in words.
1459 func (dict *readerDict) typeParamMethodExprsOffset() int {
1460         return 0
1461 }
1462
1463 // subdictsOffset returns the offset of the runtime dictionary's
1464 // subdictionary section, in words.
1465 func (dict *readerDict) subdictsOffset() int {
1466         return dict.typeParamMethodExprsOffset() + len(dict.typeParamMethodExprs)
1467 }
1468
1469 // rtypesOffset returns the offset of the runtime dictionary's rtypes
1470 // section, in words.
1471 func (dict *readerDict) rtypesOffset() int {
1472         return dict.subdictsOffset() + len(dict.subdicts)
1473 }
1474
1475 // itabsOffset returns the offset of the runtime dictionary's itabs
1476 // section, in words.
1477 func (dict *readerDict) itabsOffset() int {
1478         return dict.rtypesOffset() + len(dict.rtypes)
1479 }
1480
1481 // numWords returns the total number of words that comprise dict's
1482 // runtime dictionary variable.
1483 func (dict *readerDict) numWords() int64 {
1484         return int64(dict.itabsOffset() + len(dict.itabs))
1485 }
1486
1487 // varType returns the type of dict's runtime dictionary variable.
1488 func (dict *readerDict) varType() *types.Type {
1489         return types.NewArray(types.Types[types.TUINTPTR], dict.numWords())
1490 }
1491
1492 func (r *reader) funcargs(fn *ir.Func) {
1493         sig := fn.Nname.Type()
1494
1495         if recv := sig.Recv(); recv != nil {
1496                 r.funcarg(recv, recv.Sym, ir.PPARAM)
1497         }
1498         for _, param := range sig.Params() {
1499                 r.funcarg(param, param.Sym, ir.PPARAM)
1500         }
1501
1502         for i, param := range sig.Results() {
1503                 sym := param.Sym
1504
1505                 if sym == nil || sym.IsBlank() {
1506                         prefix := "~r"
1507                         if r.inlCall != nil {
1508                                 prefix = "~R"
1509                         } else if sym != nil {
1510                                 prefix = "~b"
1511                         }
1512                         sym = typecheck.LookupNum(prefix, i)
1513                 }
1514
1515                 r.funcarg(param, sym, ir.PPARAMOUT)
1516         }
1517 }
1518
1519 func (r *reader) funcarg(param *types.Field, sym *types.Sym, ctxt ir.Class) {
1520         if sym == nil {
1521                 assert(ctxt == ir.PPARAM)
1522                 if r.inlCall != nil {
1523                         r.inlvars.Append(ir.BlankNode)
1524                 }
1525                 return
1526         }
1527
1528         name := r.addLocal(r.inlPos(param.Pos), sym, ctxt, param.Type)
1529
1530         if r.inlCall == nil {
1531                 if !r.funarghack {
1532                         param.Nname = name
1533                 }
1534         } else {
1535                 if ctxt == ir.PPARAMOUT {
1536                         r.retvars.Append(name)
1537                 } else {
1538                         r.inlvars.Append(name)
1539                 }
1540         }
1541 }
1542
1543 func (r *reader) addLocal(pos src.XPos, sym *types.Sym, ctxt ir.Class, typ *types.Type) *ir.Name {
1544         assert(ctxt == ir.PAUTO || ctxt == ir.PPARAM || ctxt == ir.PPARAMOUT)
1545
1546         name := ir.NewNameAt(pos, sym, typ)
1547
1548         if name.Sym().Name == dictParamName {
1549                 r.dictParam = name
1550         } else {
1551                 if r.synthetic == nil {
1552                         r.Sync(pkgbits.SyncAddLocal)
1553                         if r.p.SyncMarkers() {
1554                                 want := r.Int()
1555                                 if have := len(r.locals); have != want {
1556                                         base.FatalfAt(name.Pos(), "locals table has desynced")
1557                                 }
1558                         }
1559                         r.varDictIndex(name)
1560                 }
1561
1562                 r.locals = append(r.locals, name)
1563         }
1564
1565         name.SetUsed(true)
1566
1567         // TODO(mdempsky): Move earlier.
1568         if ir.IsBlank(name) {
1569                 return name
1570         }
1571
1572         if r.inlCall != nil {
1573                 if ctxt == ir.PAUTO {
1574                         name.SetInlLocal(true)
1575                 } else {
1576                         name.SetInlFormal(true)
1577                         ctxt = ir.PAUTO
1578                 }
1579         }
1580
1581         name.Class = ctxt
1582         name.Curfn = r.curfn
1583
1584         r.curfn.Dcl = append(r.curfn.Dcl, name)
1585
1586         if ctxt == ir.PAUTO {
1587                 name.SetFrameOffset(0)
1588         }
1589
1590         return name
1591 }
1592
1593 func (r *reader) useLocal() *ir.Name {
1594         r.Sync(pkgbits.SyncUseObjLocal)
1595         if r.Bool() {
1596                 return r.locals[r.Len()]
1597         }
1598         return r.closureVars[r.Len()]
1599 }
1600
1601 func (r *reader) openScope() {
1602         r.Sync(pkgbits.SyncOpenScope)
1603         pos := r.pos()
1604
1605         if base.Flag.Dwarf {
1606                 r.scopeVars = append(r.scopeVars, len(r.curfn.Dcl))
1607                 r.marker.Push(pos)
1608         }
1609 }
1610
1611 func (r *reader) closeScope() {
1612         r.Sync(pkgbits.SyncCloseScope)
1613         r.lastCloseScopePos = r.pos()
1614
1615         r.closeAnotherScope()
1616 }
1617
1618 // closeAnotherScope is like closeScope, but it reuses the same mark
1619 // position as the last closeScope call. This is useful for "for" and
1620 // "if" statements, as their implicit blocks always end at the same
1621 // position as an explicit block.
1622 func (r *reader) closeAnotherScope() {
1623         r.Sync(pkgbits.SyncCloseAnotherScope)
1624
1625         if base.Flag.Dwarf {
1626                 scopeVars := r.scopeVars[len(r.scopeVars)-1]
1627                 r.scopeVars = r.scopeVars[:len(r.scopeVars)-1]
1628
1629                 // Quirkish: noder decides which scopes to keep before
1630                 // typechecking, whereas incremental typechecking during IR
1631                 // construction can result in new autotemps being allocated. To
1632                 // produce identical output, we ignore autotemps here for the
1633                 // purpose of deciding whether to retract the scope.
1634                 //
1635                 // This is important for net/http/fcgi, because it contains:
1636                 //
1637                 //      var body io.ReadCloser
1638                 //      if len(content) > 0 {
1639                 //              body, req.pw = io.Pipe()
1640                 //      } else { â€¦ }
1641                 //
1642                 // Notably, io.Pipe is inlinable, and inlining it introduces a ~R0
1643                 // variable at the call site.
1644                 //
1645                 // Noder does not preserve the scope where the io.Pipe() call
1646                 // resides, because it doesn't contain any declared variables in
1647                 // source. So the ~R0 variable ends up being assigned to the
1648                 // enclosing scope instead.
1649                 //
1650                 // However, typechecking this assignment also introduces
1651                 // autotemps, because io.Pipe's results need conversion before
1652                 // they can be assigned to their respective destination variables.
1653                 //
1654                 // TODO(mdempsky): We should probably just keep all scopes, and
1655                 // let dwarfgen take care of pruning them instead.
1656                 retract := true
1657                 for _, n := range r.curfn.Dcl[scopeVars:] {
1658                         if !n.AutoTemp() {
1659                                 retract = false
1660                                 break
1661                         }
1662                 }
1663
1664                 if retract {
1665                         // no variables were declared in this scope, so we can retract it.
1666                         r.marker.Unpush()
1667                 } else {
1668                         r.marker.Pop(r.lastCloseScopePos)
1669                 }
1670         }
1671 }
1672
1673 // @@@ Statements
1674
1675 func (r *reader) stmt() ir.Node {
1676         return block(r.stmts())
1677 }
1678
1679 func block(stmts []ir.Node) ir.Node {
1680         switch len(stmts) {
1681         case 0:
1682                 return nil
1683         case 1:
1684                 return stmts[0]
1685         default:
1686                 return ir.NewBlockStmt(stmts[0].Pos(), stmts)
1687         }
1688 }
1689
1690 func (r *reader) stmts() ir.Nodes {
1691         assert(ir.CurFunc == r.curfn)
1692         var res ir.Nodes
1693
1694         r.Sync(pkgbits.SyncStmts)
1695         for {
1696                 tag := codeStmt(r.Code(pkgbits.SyncStmt1))
1697                 if tag == stmtEnd {
1698                         r.Sync(pkgbits.SyncStmtsEnd)
1699                         return res
1700                 }
1701
1702                 if n := r.stmt1(tag, &res); n != nil {
1703                         res.Append(typecheck.Stmt(n))
1704                 }
1705         }
1706 }
1707
1708 func (r *reader) stmt1(tag codeStmt, out *ir.Nodes) ir.Node {
1709         var label *types.Sym
1710         if n := len(*out); n > 0 {
1711                 if ls, ok := (*out)[n-1].(*ir.LabelStmt); ok {
1712                         label = ls.Label
1713                 }
1714         }
1715
1716         switch tag {
1717         default:
1718                 panic("unexpected statement")
1719
1720         case stmtAssign:
1721                 pos := r.pos()
1722                 names, lhs := r.assignList()
1723                 rhs := r.multiExpr()
1724
1725                 if len(rhs) == 0 {
1726                         for _, name := range names {
1727                                 as := ir.NewAssignStmt(pos, name, nil)
1728                                 as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, name))
1729                                 out.Append(typecheck.Stmt(as))
1730                         }
1731                         return nil
1732                 }
1733
1734                 if len(lhs) == 1 && len(rhs) == 1 {
1735                         n := ir.NewAssignStmt(pos, lhs[0], rhs[0])
1736                         n.Def = r.initDefn(n, names)
1737                         return n
1738                 }
1739
1740                 n := ir.NewAssignListStmt(pos, ir.OAS2, lhs, rhs)
1741                 n.Def = r.initDefn(n, names)
1742                 return n
1743
1744         case stmtAssignOp:
1745                 op := r.op()
1746                 lhs := r.expr()
1747                 pos := r.pos()
1748                 rhs := r.expr()
1749                 return ir.NewAssignOpStmt(pos, op, lhs, rhs)
1750
1751         case stmtIncDec:
1752                 op := r.op()
1753                 lhs := r.expr()
1754                 pos := r.pos()
1755                 n := ir.NewAssignOpStmt(pos, op, lhs, ir.NewOne(pos, lhs.Type()))
1756                 n.IncDec = true
1757                 return n
1758
1759         case stmtBlock:
1760                 out.Append(r.blockStmt()...)
1761                 return nil
1762
1763         case stmtBranch:
1764                 pos := r.pos()
1765                 op := r.op()
1766                 sym := r.optLabel()
1767                 return ir.NewBranchStmt(pos, op, sym)
1768
1769         case stmtCall:
1770                 pos := r.pos()
1771                 op := r.op()
1772                 call := r.expr()
1773                 return ir.NewGoDeferStmt(pos, op, call)
1774
1775         case stmtExpr:
1776                 return r.expr()
1777
1778         case stmtFor:
1779                 return r.forStmt(label)
1780
1781         case stmtIf:
1782                 return r.ifStmt()
1783
1784         case stmtLabel:
1785                 pos := r.pos()
1786                 sym := r.label()
1787                 return ir.NewLabelStmt(pos, sym)
1788
1789         case stmtReturn:
1790                 pos := r.pos()
1791                 results := r.multiExpr()
1792                 return ir.NewReturnStmt(pos, results)
1793
1794         case stmtSelect:
1795                 return r.selectStmt(label)
1796
1797         case stmtSend:
1798                 pos := r.pos()
1799                 ch := r.expr()
1800                 value := r.expr()
1801                 return ir.NewSendStmt(pos, ch, value)
1802
1803         case stmtSwitch:
1804                 return r.switchStmt(label)
1805         }
1806 }
1807
1808 func (r *reader) assignList() ([]*ir.Name, []ir.Node) {
1809         lhs := make([]ir.Node, r.Len())
1810         var names []*ir.Name
1811
1812         for i := range lhs {
1813                 expr, def := r.assign()
1814                 lhs[i] = expr
1815                 if def {
1816                         names = append(names, expr.(*ir.Name))
1817                 }
1818         }
1819
1820         return names, lhs
1821 }
1822
1823 // assign returns an assignee expression. It also reports whether the
1824 // returned expression is a newly declared variable.
1825 func (r *reader) assign() (ir.Node, bool) {
1826         switch tag := codeAssign(r.Code(pkgbits.SyncAssign)); tag {
1827         default:
1828                 panic("unhandled assignee expression")
1829
1830         case assignBlank:
1831                 return typecheck.AssignExpr(ir.BlankNode), false
1832
1833         case assignDef:
1834                 pos := r.pos()
1835                 setBasePos(pos)
1836                 _, sym := r.localIdent()
1837                 typ := r.typ()
1838
1839                 name := r.addLocal(pos, sym, ir.PAUTO, typ)
1840                 return name, true
1841
1842         case assignExpr:
1843                 return r.expr(), false
1844         }
1845 }
1846
1847 func (r *reader) blockStmt() []ir.Node {
1848         r.Sync(pkgbits.SyncBlockStmt)
1849         r.openScope()
1850         stmts := r.stmts()
1851         r.closeScope()
1852         return stmts
1853 }
1854
1855 func (r *reader) forStmt(label *types.Sym) ir.Node {
1856         r.Sync(pkgbits.SyncForStmt)
1857
1858         r.openScope()
1859
1860         if r.Bool() {
1861                 pos := r.pos()
1862                 rang := ir.NewRangeStmt(pos, nil, nil, nil, nil, false)
1863                 rang.Label = label
1864
1865                 names, lhs := r.assignList()
1866                 if len(lhs) >= 1 {
1867                         rang.Key = lhs[0]
1868                         if len(lhs) >= 2 {
1869                                 rang.Value = lhs[1]
1870                         }
1871                 }
1872                 rang.Def = r.initDefn(rang, names)
1873
1874                 rang.X = r.expr()
1875                 if rang.X.Type().IsMap() {
1876                         rang.RType = r.rtype(pos)
1877                 }
1878                 if rang.Key != nil && !ir.IsBlank(rang.Key) {
1879                         rang.KeyTypeWord, rang.KeySrcRType = r.convRTTI(pos)
1880                 }
1881                 if rang.Value != nil && !ir.IsBlank(rang.Value) {
1882                         rang.ValueTypeWord, rang.ValueSrcRType = r.convRTTI(pos)
1883                 }
1884
1885                 rang.Body = r.blockStmt()
1886                 rang.DistinctVars = r.Bool()
1887                 r.closeAnotherScope()
1888
1889                 return rang
1890         }
1891
1892         pos := r.pos()
1893         init := r.stmt()
1894         cond := r.optExpr()
1895         post := r.stmt()
1896         body := r.blockStmt()
1897         perLoopVars := r.Bool()
1898         r.closeAnotherScope()
1899
1900         if ir.IsConst(cond, constant.Bool) && !ir.BoolVal(cond) {
1901                 return init // simplify "for init; false; post { ... }" into "init"
1902         }
1903
1904         stmt := ir.NewForStmt(pos, init, cond, post, body, perLoopVars)
1905         stmt.Label = label
1906         return stmt
1907 }
1908
1909 func (r *reader) ifStmt() ir.Node {
1910         r.Sync(pkgbits.SyncIfStmt)
1911         r.openScope()
1912         pos := r.pos()
1913         init := r.stmts()
1914         cond := r.expr()
1915         staticCond := r.Int()
1916         var then, els []ir.Node
1917         if staticCond >= 0 {
1918                 then = r.blockStmt()
1919         } else {
1920                 r.lastCloseScopePos = r.pos()
1921         }
1922         if staticCond <= 0 {
1923                 els = r.stmts()
1924         }
1925         r.closeAnotherScope()
1926
1927         if staticCond != 0 {
1928                 // We may have removed a dead return statement, which can trip up
1929                 // later passes (#62211). To avoid confusion, we instead flatten
1930                 // the if statement into a block.
1931
1932                 if cond.Op() != ir.OLITERAL {
1933                         init.Append(typecheck.Stmt(ir.NewAssignStmt(pos, ir.BlankNode, cond))) // for side effects
1934                 }
1935                 init.Append(then...)
1936                 init.Append(els...)
1937                 return block(init)
1938         }
1939
1940         n := ir.NewIfStmt(pos, cond, then, els)
1941         n.SetInit(init)
1942         return n
1943 }
1944
1945 func (r *reader) selectStmt(label *types.Sym) ir.Node {
1946         r.Sync(pkgbits.SyncSelectStmt)
1947
1948         pos := r.pos()
1949         clauses := make([]*ir.CommClause, r.Len())
1950         for i := range clauses {
1951                 if i > 0 {
1952                         r.closeScope()
1953                 }
1954                 r.openScope()
1955
1956                 pos := r.pos()
1957                 comm := r.stmt()
1958                 body := r.stmts()
1959
1960                 // "case i = <-c: ..." may require an implicit conversion (e.g.,
1961                 // see fixedbugs/bug312.go). Currently, typecheck throws away the
1962                 // implicit conversion and relies on it being reinserted later,
1963                 // but that would lose any explicit RTTI operands too. To preserve
1964                 // RTTI, we rewrite this as "case tmp := <-c: i = tmp; ...".
1965                 if as, ok := comm.(*ir.AssignStmt); ok && as.Op() == ir.OAS && !as.Def {
1966                         if conv, ok := as.Y.(*ir.ConvExpr); ok && conv.Op() == ir.OCONVIFACE {
1967                                 base.AssertfAt(conv.Implicit(), conv.Pos(), "expected implicit conversion: %v", conv)
1968
1969                                 recv := conv.X
1970                                 base.AssertfAt(recv.Op() == ir.ORECV, recv.Pos(), "expected receive expression: %v", recv)
1971
1972                                 tmp := r.temp(pos, recv.Type())
1973
1974                                 // Replace comm with `tmp := <-c`.
1975                                 tmpAs := ir.NewAssignStmt(pos, tmp, recv)
1976                                 tmpAs.Def = true
1977                                 tmpAs.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp))
1978                                 comm = tmpAs
1979
1980                                 // Change original assignment to `i = tmp`, and prepend to body.
1981                                 conv.X = tmp
1982                                 body = append([]ir.Node{as}, body...)
1983                         }
1984                 }
1985
1986                 // multiExpr will have desugared a comma-ok receive expression
1987                 // into a separate statement. However, the rest of the compiler
1988                 // expects comm to be the OAS2RECV statement itself, so we need to
1989                 // shuffle things around to fit that pattern.
1990                 if as2, ok := comm.(*ir.AssignListStmt); ok && as2.Op() == ir.OAS2 {
1991                         init := ir.TakeInit(as2.Rhs[0])
1992                         base.AssertfAt(len(init) == 1 && init[0].Op() == ir.OAS2RECV, as2.Pos(), "unexpected assignment: %+v", as2)
1993
1994                         comm = init[0]
1995                         body = append([]ir.Node{as2}, body...)
1996                 }
1997
1998                 clauses[i] = ir.NewCommStmt(pos, comm, body)
1999         }
2000         if len(clauses) > 0 {
2001                 r.closeScope()
2002         }
2003         n := ir.NewSelectStmt(pos, clauses)
2004         n.Label = label
2005         return n
2006 }
2007
2008 func (r *reader) switchStmt(label *types.Sym) ir.Node {
2009         r.Sync(pkgbits.SyncSwitchStmt)
2010
2011         r.openScope()
2012         pos := r.pos()
2013         init := r.stmt()
2014
2015         var tag ir.Node
2016         var ident *ir.Ident
2017         var iface *types.Type
2018         if r.Bool() {
2019                 pos := r.pos()
2020                 if r.Bool() {
2021                         pos := r.pos()
2022                         _, sym := r.localIdent()
2023                         ident = ir.NewIdent(pos, sym)
2024                 }
2025                 x := r.expr()
2026                 iface = x.Type()
2027                 tag = ir.NewTypeSwitchGuard(pos, ident, x)
2028         } else {
2029                 tag = r.optExpr()
2030         }
2031
2032         clauses := make([]*ir.CaseClause, r.Len())
2033         for i := range clauses {
2034                 if i > 0 {
2035                         r.closeScope()
2036                 }
2037                 r.openScope()
2038
2039                 pos := r.pos()
2040                 var cases, rtypes []ir.Node
2041                 if iface != nil {
2042                         cases = make([]ir.Node, r.Len())
2043                         if len(cases) == 0 {
2044                                 cases = nil // TODO(mdempsky): Unclear if this matters.
2045                         }
2046                         for i := range cases {
2047                                 if r.Bool() { // case nil
2048                                         cases[i] = typecheck.Expr(types.BuiltinPkg.Lookup("nil").Def.(*ir.NilExpr))
2049                                 } else {
2050                                         cases[i] = r.exprType()
2051                                 }
2052                         }
2053                 } else {
2054                         cases = r.exprList()
2055
2056                         // For `switch { case any(true): }` (e.g., issue 3980 in
2057                         // test/switch.go), the backend still creates a mixed bool/any
2058                         // comparison, and we need to explicitly supply the RTTI for the
2059                         // comparison.
2060                         //
2061                         // TODO(mdempsky): Change writer.go to desugar "switch {" into
2062                         // "switch true {", which we already handle correctly.
2063                         if tag == nil {
2064                                 for i, cas := range cases {
2065                                         if cas.Type().IsEmptyInterface() {
2066                                                 for len(rtypes) < i {
2067                                                         rtypes = append(rtypes, nil)
2068                                                 }
2069                                                 rtypes = append(rtypes, reflectdata.TypePtrAt(cas.Pos(), types.Types[types.TBOOL]))
2070                                         }
2071                                 }
2072                         }
2073                 }
2074
2075                 clause := ir.NewCaseStmt(pos, cases, nil)
2076                 clause.RTypes = rtypes
2077
2078                 if ident != nil {
2079                         pos := r.pos()
2080                         typ := r.typ()
2081
2082                         name := r.addLocal(pos, ident.Sym(), ir.PAUTO, typ)
2083                         clause.Var = name
2084                         name.Defn = tag
2085                 }
2086
2087                 clause.Body = r.stmts()
2088                 clauses[i] = clause
2089         }
2090         if len(clauses) > 0 {
2091                 r.closeScope()
2092         }
2093         r.closeScope()
2094
2095         n := ir.NewSwitchStmt(pos, tag, clauses)
2096         n.Label = label
2097         if init != nil {
2098                 n.SetInit([]ir.Node{init})
2099         }
2100         return n
2101 }
2102
2103 func (r *reader) label() *types.Sym {
2104         r.Sync(pkgbits.SyncLabel)
2105         name := r.String()
2106         if r.inlCall != nil {
2107                 name = fmt.Sprintf("~%s·%d", name, inlgen)
2108         }
2109         return typecheck.Lookup(name)
2110 }
2111
2112 func (r *reader) optLabel() *types.Sym {
2113         r.Sync(pkgbits.SyncOptLabel)
2114         if r.Bool() {
2115                 return r.label()
2116         }
2117         return nil
2118 }
2119
2120 // initDefn marks the given names as declared by defn and populates
2121 // its Init field with ODCL nodes. It then reports whether any names
2122 // were so declared, which can be used to initialize defn.Def.
2123 func (r *reader) initDefn(defn ir.InitNode, names []*ir.Name) bool {
2124         if len(names) == 0 {
2125                 return false
2126         }
2127
2128         init := make([]ir.Node, len(names))
2129         for i, name := range names {
2130                 name.Defn = defn
2131                 init[i] = ir.NewDecl(name.Pos(), ir.ODCL, name)
2132         }
2133         defn.SetInit(init)
2134         return true
2135 }
2136
2137 // @@@ Expressions
2138
2139 // expr reads and returns a typechecked expression.
2140 func (r *reader) expr() (res ir.Node) {
2141         defer func() {
2142                 if res != nil && res.Typecheck() == 0 {
2143                         base.FatalfAt(res.Pos(), "%v missed typecheck", res)
2144                 }
2145         }()
2146
2147         switch tag := codeExpr(r.Code(pkgbits.SyncExpr)); tag {
2148         default:
2149                 panic("unhandled expression")
2150
2151         case exprLocal:
2152                 return typecheck.Expr(r.useLocal())
2153
2154         case exprGlobal:
2155                 // Callee instead of Expr allows builtins
2156                 // TODO(mdempsky): Handle builtins directly in exprCall, like method calls?
2157                 return typecheck.Callee(r.obj())
2158
2159         case exprFuncInst:
2160                 origPos, pos := r.origPos()
2161                 wrapperFn, baseFn, dictPtr := r.funcInst(pos)
2162                 if wrapperFn != nil {
2163                         return wrapperFn
2164                 }
2165                 return r.curry(origPos, false, baseFn, dictPtr, nil)
2166
2167         case exprConst:
2168                 pos := r.pos()
2169                 typ := r.typ()
2170                 val := FixValue(typ, r.Value())
2171                 return ir.NewBasicLit(pos, typ, val)
2172
2173         case exprZero:
2174                 pos := r.pos()
2175                 typ := r.typ()
2176                 return ir.NewZero(pos, typ)
2177
2178         case exprCompLit:
2179                 return r.compLit()
2180
2181         case exprFuncLit:
2182                 return r.funcLit()
2183
2184         case exprFieldVal:
2185                 x := r.expr()
2186                 pos := r.pos()
2187                 _, sym := r.selector()
2188
2189                 return typecheck.XDotField(pos, x, sym)
2190
2191         case exprMethodVal:
2192                 recv := r.expr()
2193                 origPos, pos := r.origPos()
2194                 wrapperFn, baseFn, dictPtr := r.methodExpr()
2195
2196                 // For simple wrapperFn values, the existing machinery for creating
2197                 // and deduplicating wrapperFn value wrappers still works fine.
2198                 if wrapperFn, ok := wrapperFn.(*ir.SelectorExpr); ok && wrapperFn.Op() == ir.OMETHEXPR {
2199                         // The receiver expression we constructed may have a shape type.
2200                         // For example, in fixedbugs/issue54343.go, `New[int]()` is
2201                         // constructed as `New[go.shape.int](&.dict.New[int])`, which
2202                         // has type `*T[go.shape.int]`, not `*T[int]`.
2203                         //
2204                         // However, the method we want to select here is `(*T[int]).M`,
2205                         // not `(*T[go.shape.int]).M`, so we need to manually convert
2206                         // the type back so that the OXDOT resolves correctly.
2207                         //
2208                         // TODO(mdempsky): Logically it might make more sense for
2209                         // exprCall to take responsibility for setting a non-shaped
2210                         // result type, but this is the only place where we care
2211                         // currently. And only because existing ir.OMETHVALUE backend
2212                         // code relies on n.X.Type() instead of n.Selection.Recv().Type
2213                         // (because the latter is types.FakeRecvType() in the case of
2214                         // interface method values).
2215                         //
2216                         if recv.Type().HasShape() {
2217                                 typ := wrapperFn.Type().Param(0).Type
2218                                 if !types.Identical(typ, recv.Type()) {
2219                                         base.FatalfAt(wrapperFn.Pos(), "receiver %L does not match %L", recv, wrapperFn)
2220                                 }
2221                                 recv = typecheck.Expr(ir.NewConvExpr(recv.Pos(), ir.OCONVNOP, typ, recv))
2222                         }
2223
2224                         n := typecheck.XDotMethod(pos, recv, wrapperFn.Sel, false)
2225
2226                         // As a consistency check here, we make sure "n" selected the
2227                         // same method (represented by a types.Field) that wrapperFn
2228                         // selected. However, for anonymous receiver types, there can be
2229                         // multiple such types.Field instances (#58563). So we may need
2230                         // to fallback to making sure Sym and Type (including the
2231                         // receiver parameter's type) match.
2232                         if n.Selection != wrapperFn.Selection {
2233                                 assert(n.Selection.Sym == wrapperFn.Selection.Sym)
2234                                 assert(types.Identical(n.Selection.Type, wrapperFn.Selection.Type))
2235                                 assert(types.Identical(n.Selection.Type.Recv().Type, wrapperFn.Selection.Type.Recv().Type))
2236                         }
2237
2238                         wrapper := methodValueWrapper{
2239                                 rcvr:   n.X.Type(),
2240                                 method: n.Selection,
2241                         }
2242
2243                         if r.importedDef() {
2244                                 haveMethodValueWrappers = append(haveMethodValueWrappers, wrapper)
2245                         } else {
2246                                 needMethodValueWrappers = append(needMethodValueWrappers, wrapper)
2247                         }
2248                         return n
2249                 }
2250
2251                 // For more complicated method expressions, we construct a
2252                 // function literal wrapper.
2253                 return r.curry(origPos, true, baseFn, recv, dictPtr)
2254
2255         case exprMethodExpr:
2256                 recv := r.typ()
2257
2258                 implicits := make([]int, r.Len())
2259                 for i := range implicits {
2260                         implicits[i] = r.Len()
2261                 }
2262                 var deref, addr bool
2263                 if r.Bool() {
2264                         deref = true
2265                 } else if r.Bool() {
2266                         addr = true
2267                 }
2268
2269                 origPos, pos := r.origPos()
2270                 wrapperFn, baseFn, dictPtr := r.methodExpr()
2271
2272                 // If we already have a wrapper and don't need to do anything with
2273                 // it, we can just return the wrapper directly.
2274                 //
2275                 // N.B., we use implicits/deref/addr here as the source of truth
2276                 // rather than types.Identical, because the latter can be confused
2277                 // by tricky promoted methods (e.g., typeparam/mdempsky/21.go).
2278                 if wrapperFn != nil && len(implicits) == 0 && !deref && !addr {
2279                         if !types.Identical(recv, wrapperFn.Type().Param(0).Type) {
2280                                 base.FatalfAt(pos, "want receiver type %v, but have method %L", recv, wrapperFn)
2281                         }
2282                         return wrapperFn
2283                 }
2284
2285                 // Otherwise, if the wrapper function is a static method
2286                 // expression (OMETHEXPR) and the receiver type is unshaped, then
2287                 // we can rely on a statically generated wrapper being available.
2288                 if method, ok := wrapperFn.(*ir.SelectorExpr); ok && method.Op() == ir.OMETHEXPR && !recv.HasShape() {
2289                         return typecheck.NewMethodExpr(pos, recv, method.Sel)
2290                 }
2291
2292                 return r.methodExprWrap(origPos, recv, implicits, deref, addr, baseFn, dictPtr)
2293
2294         case exprIndex:
2295                 x := r.expr()
2296                 pos := r.pos()
2297                 index := r.expr()
2298                 n := typecheck.Expr(ir.NewIndexExpr(pos, x, index))
2299                 switch n.Op() {
2300                 case ir.OINDEXMAP:
2301                         n := n.(*ir.IndexExpr)
2302                         n.RType = r.rtype(pos)
2303                 }
2304                 return n
2305
2306         case exprSlice:
2307                 x := r.expr()
2308                 pos := r.pos()
2309                 var index [3]ir.Node
2310                 for i := range index {
2311                         index[i] = r.optExpr()
2312                 }
2313                 op := ir.OSLICE
2314                 if index[2] != nil {
2315                         op = ir.OSLICE3
2316                 }
2317                 return typecheck.Expr(ir.NewSliceExpr(pos, op, x, index[0], index[1], index[2]))
2318
2319         case exprAssert:
2320                 x := r.expr()
2321                 pos := r.pos()
2322                 typ := r.exprType()
2323                 srcRType := r.rtype(pos)
2324
2325                 // TODO(mdempsky): Always emit ODYNAMICDOTTYPE for uniformity?
2326                 if typ, ok := typ.(*ir.DynamicType); ok && typ.Op() == ir.ODYNAMICTYPE {
2327                         assert := ir.NewDynamicTypeAssertExpr(pos, ir.ODYNAMICDOTTYPE, x, typ.RType)
2328                         assert.SrcRType = srcRType
2329                         assert.ITab = typ.ITab
2330                         return typed(typ.Type(), assert)
2331                 }
2332                 return typecheck.Expr(ir.NewTypeAssertExpr(pos, x, typ.Type()))
2333
2334         case exprUnaryOp:
2335                 op := r.op()
2336                 pos := r.pos()
2337                 x := r.expr()
2338
2339                 switch op {
2340                 case ir.OADDR:
2341                         return typecheck.Expr(typecheck.NodAddrAt(pos, x))
2342                 case ir.ODEREF:
2343                         return typecheck.Expr(ir.NewStarExpr(pos, x))
2344                 }
2345                 return typecheck.Expr(ir.NewUnaryExpr(pos, op, x))
2346
2347         case exprBinaryOp:
2348                 op := r.op()
2349                 x := r.expr()
2350                 pos := r.pos()
2351                 y := r.expr()
2352
2353                 switch op {
2354                 case ir.OANDAND, ir.OOROR:
2355                         return typecheck.Expr(ir.NewLogicalExpr(pos, op, x, y))
2356                 }
2357                 return typecheck.Expr(ir.NewBinaryExpr(pos, op, x, y))
2358
2359         case exprRecv:
2360                 x := r.expr()
2361                 pos := r.pos()
2362                 for i, n := 0, r.Len(); i < n; i++ {
2363                         x = Implicit(typecheck.DotField(pos, x, r.Len()))
2364                 }
2365                 if r.Bool() { // needs deref
2366                         x = Implicit(Deref(pos, x.Type().Elem(), x))
2367                 } else if r.Bool() { // needs addr
2368                         x = Implicit(Addr(pos, x))
2369                 }
2370                 return x
2371
2372         case exprCall:
2373                 var fun ir.Node
2374                 var args ir.Nodes
2375                 if r.Bool() { // method call
2376                         recv := r.expr()
2377                         _, method, dictPtr := r.methodExpr()
2378
2379                         if recv.Type().IsInterface() && method.Op() == ir.OMETHEXPR {
2380                                 method := method.(*ir.SelectorExpr)
2381
2382                                 // The compiler backend (e.g., devirtualization) handle
2383                                 // OCALLINTER/ODOTINTER better than OCALLFUNC/OMETHEXPR for
2384                                 // interface calls, so we prefer to continue constructing
2385                                 // calls that way where possible.
2386                                 //
2387                                 // There are also corner cases where semantically it's perhaps
2388                                 // significant; e.g., fixedbugs/issue15975.go, #38634, #52025.
2389
2390                                 fun = typecheck.XDotMethod(method.Pos(), recv, method.Sel, true)
2391                         } else {
2392                                 if recv.Type().IsInterface() {
2393                                         // N.B., this happens currently for typeparam/issue51521.go
2394                                         // and typeparam/typeswitch3.go.
2395                                         if base.Flag.LowerM != 0 {
2396                                                 base.WarnfAt(method.Pos(), "imprecise interface call")
2397                                         }
2398                                 }
2399
2400                                 fun = method
2401                                 args.Append(recv)
2402                         }
2403                         if dictPtr != nil {
2404                                 args.Append(dictPtr)
2405                         }
2406                 } else if r.Bool() { // call to instanced function
2407                         pos := r.pos()
2408                         _, shapedFn, dictPtr := r.funcInst(pos)
2409                         fun = shapedFn
2410                         args.Append(dictPtr)
2411                 } else {
2412                         fun = r.expr()
2413                 }
2414                 pos := r.pos()
2415                 args.Append(r.multiExpr()...)
2416                 dots := r.Bool()
2417                 n := typecheck.Call(pos, fun, args, dots)
2418                 switch n.Op() {
2419                 case ir.OAPPEND:
2420                         n := n.(*ir.CallExpr)
2421                         n.RType = r.rtype(pos)
2422                         // For append(a, b...), we don't need the implicit conversion. The typechecker already
2423                         // ensured that a and b are both slices with the same base type, or []byte and string.
2424                         if n.IsDDD {
2425                                 if conv, ok := n.Args[1].(*ir.ConvExpr); ok && conv.Op() == ir.OCONVNOP && conv.Implicit() {
2426                                         n.Args[1] = conv.X
2427                                 }
2428                         }
2429                 case ir.OCOPY:
2430                         n := n.(*ir.BinaryExpr)
2431                         n.RType = r.rtype(pos)
2432                 case ir.ODELETE:
2433                         n := n.(*ir.CallExpr)
2434                         n.RType = r.rtype(pos)
2435                 case ir.OUNSAFESLICE:
2436                         n := n.(*ir.BinaryExpr)
2437                         n.RType = r.rtype(pos)
2438                 }
2439                 return n
2440
2441         case exprMake:
2442                 pos := r.pos()
2443                 typ := r.exprType()
2444                 extra := r.exprs()
2445                 n := typecheck.Expr(ir.NewCallExpr(pos, ir.OMAKE, nil, append([]ir.Node{typ}, extra...))).(*ir.MakeExpr)
2446                 n.RType = r.rtype(pos)
2447                 return n
2448
2449         case exprNew:
2450                 pos := r.pos()
2451                 typ := r.exprType()
2452                 return typecheck.Expr(ir.NewUnaryExpr(pos, ir.ONEW, typ))
2453
2454         case exprSizeof:
2455                 return ir.NewUintptr(r.pos(), r.typ().Size())
2456
2457         case exprAlignof:
2458                 return ir.NewUintptr(r.pos(), r.typ().Alignment())
2459
2460         case exprOffsetof:
2461                 pos := r.pos()
2462                 typ := r.typ()
2463                 types.CalcSize(typ)
2464
2465                 var offset int64
2466                 for i := r.Len(); i >= 0; i-- {
2467                         field := typ.Field(r.Len())
2468                         offset += field.Offset
2469                         typ = field.Type
2470                 }
2471
2472                 return ir.NewUintptr(pos, offset)
2473
2474         case exprReshape:
2475                 typ := r.typ()
2476                 x := r.expr()
2477
2478                 if types.IdenticalStrict(x.Type(), typ) {
2479                         return x
2480                 }
2481
2482                 // Comparison expressions are constructed as "untyped bool" still.
2483                 //
2484                 // TODO(mdempsky): It should be safe to reshape them here too, but
2485                 // maybe it's better to construct them with the proper type
2486                 // instead.
2487                 if x.Type() == types.UntypedBool && typ.IsBoolean() {
2488                         return x
2489                 }
2490
2491                 base.AssertfAt(x.Type().HasShape() || typ.HasShape(), x.Pos(), "%L and %v are not shape types", x, typ)
2492                 base.AssertfAt(types.Identical(x.Type(), typ), x.Pos(), "%L is not shape-identical to %v", x, typ)
2493
2494                 // We use ir.HasUniquePos here as a check that x only appears once
2495                 // in the AST, so it's okay for us to call SetType without
2496                 // breaking any other uses of it.
2497                 //
2498                 // Notably, any ONAMEs should already have the exactly right shape
2499                 // type and been caught by types.IdenticalStrict above.
2500                 base.AssertfAt(ir.HasUniquePos(x), x.Pos(), "cannot call SetType(%v) on %L", typ, x)
2501
2502                 if base.Debug.Reshape != 0 {
2503                         base.WarnfAt(x.Pos(), "reshaping %L to %v", x, typ)
2504                 }
2505
2506                 x.SetType(typ)
2507                 return x
2508
2509         case exprConvert:
2510                 implicit := r.Bool()
2511                 typ := r.typ()
2512                 pos := r.pos()
2513                 typeWord, srcRType := r.convRTTI(pos)
2514                 dstTypeParam := r.Bool()
2515                 identical := r.Bool()
2516                 x := r.expr()
2517
2518                 // TODO(mdempsky): Stop constructing expressions of untyped type.
2519                 x = typecheck.DefaultLit(x, typ)
2520
2521                 ce := ir.NewConvExpr(pos, ir.OCONV, typ, x)
2522                 ce.TypeWord, ce.SrcRType = typeWord, srcRType
2523                 if implicit {
2524                         ce.SetImplicit(true)
2525                 }
2526                 n := typecheck.Expr(ce)
2527
2528                 // Conversions between non-identical, non-empty interfaces always
2529                 // requires a runtime call, even if they have identical underlying
2530                 // interfaces. This is because we create separate itab instances
2531                 // for each unique interface type, not merely each unique
2532                 // interface shape.
2533                 //
2534                 // However, due to shape types, typecheck.Expr might mistakenly
2535                 // think a conversion between two non-empty interfaces are
2536                 // identical and set ir.OCONVNOP, instead of ir.OCONVIFACE. To
2537                 // ensure we update the itab field appropriately, we force it to
2538                 // ir.OCONVIFACE instead when shape types are involved.
2539                 //
2540                 // TODO(mdempsky): Are there other places we might get this wrong?
2541                 // Should this be moved down into typecheck.{Assign,Convert}op?
2542                 // This would be a non-issue if itabs were unique for each
2543                 // *underlying* interface type instead.
2544                 if !identical {
2545                         if n, ok := n.(*ir.ConvExpr); ok && n.Op() == ir.OCONVNOP && n.Type().IsInterface() && !n.Type().IsEmptyInterface() && (n.Type().HasShape() || n.X.Type().HasShape()) {
2546                                 n.SetOp(ir.OCONVIFACE)
2547                         }
2548                 }
2549
2550                 // spec: "If the type is a type parameter, the constant is converted
2551                 // into a non-constant value of the type parameter."
2552                 if dstTypeParam && ir.IsConstNode(n) {
2553                         // Wrap in an OCONVNOP node to ensure result is non-constant.
2554                         n = Implicit(ir.NewConvExpr(pos, ir.OCONVNOP, n.Type(), n))
2555                         n.SetTypecheck(1)
2556                 }
2557                 return n
2558         }
2559 }
2560
2561 // funcInst reads an instantiated function reference, and returns
2562 // three (possibly nil) expressions related to it:
2563 //
2564 // baseFn is always non-nil: it's either a function of the appropriate
2565 // type already, or it has an extra dictionary parameter as the first
2566 // parameter.
2567 //
2568 // If dictPtr is non-nil, then it's a dictionary argument that must be
2569 // passed as the first argument to baseFn.
2570 //
2571 // If wrapperFn is non-nil, then it's either the same as baseFn (if
2572 // dictPtr is nil), or it's semantically equivalent to currying baseFn
2573 // to pass dictPtr. (wrapperFn is nil when dictPtr is an expression
2574 // that needs to be computed dynamically.)
2575 //
2576 // For callers that are creating a call to the returned function, it's
2577 // best to emit a call to baseFn, and include dictPtr in the arguments
2578 // list as appropriate.
2579 //
2580 // For callers that want to return the function without invoking it,
2581 // they may return wrapperFn if it's non-nil; but otherwise, they need
2582 // to create their own wrapper.
2583 func (r *reader) funcInst(pos src.XPos) (wrapperFn, baseFn, dictPtr ir.Node) {
2584         // Like in methodExpr, I'm pretty sure this isn't needed.
2585         var implicits []*types.Type
2586         if r.dict != nil {
2587                 implicits = r.dict.targs
2588         }
2589
2590         if r.Bool() { // dynamic subdictionary
2591                 idx := r.Len()
2592                 info := r.dict.subdicts[idx]
2593                 explicits := r.p.typListIdx(info.explicits, r.dict)
2594
2595                 baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
2596
2597                 // TODO(mdempsky): Is there a more robust way to get the
2598                 // dictionary pointer type here?
2599                 dictPtrType := baseFn.Type().Param(0).Type
2600                 dictPtr = typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx)))
2601
2602                 return
2603         }
2604
2605         info := r.objInfo()
2606         explicits := r.p.typListIdx(info.explicits, r.dict)
2607
2608         wrapperFn = r.p.objIdx(info.idx, implicits, explicits, false).(*ir.Name)
2609         baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
2610
2611         dictName := r.p.objDictName(info.idx, implicits, explicits)
2612         dictPtr = typecheck.Expr(ir.NewAddrExpr(pos, dictName))
2613
2614         return
2615 }
2616
2617 func (pr *pkgReader) objDictName(idx pkgbits.Index, implicits, explicits []*types.Type) *ir.Name {
2618         rname := pr.newReader(pkgbits.RelocName, idx, pkgbits.SyncObject1)
2619         _, sym := rname.qualifiedIdent()
2620         tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
2621
2622         if tag == pkgbits.ObjStub {
2623                 assert(!sym.IsBlank())
2624                 if pri, ok := objReader[sym]; ok {
2625                         return pri.pr.objDictName(pri.idx, nil, explicits)
2626                 }
2627                 base.Fatalf("unresolved stub: %v", sym)
2628         }
2629
2630         dict := pr.objDictIdx(sym, idx, implicits, explicits, false)
2631
2632         return pr.dictNameOf(dict)
2633 }
2634
2635 // curry returns a function literal that calls fun with arg0 and
2636 // (optionally) arg1, accepting additional arguments to the function
2637 // literal as necessary to satisfy fun's signature.
2638 //
2639 // If nilCheck is true and arg0 is an interface value, then it's
2640 // checked to be non-nil as an initial step at the point of evaluating
2641 // the function literal itself.
2642 func (r *reader) curry(origPos src.XPos, ifaceHack bool, fun ir.Node, arg0, arg1 ir.Node) ir.Node {
2643         var captured ir.Nodes
2644         captured.Append(fun, arg0)
2645         if arg1 != nil {
2646                 captured.Append(arg1)
2647         }
2648
2649         params, results := syntheticSig(fun.Type())
2650         params = params[len(captured)-1:] // skip curried parameters
2651         typ := types.NewSignature(nil, params, results)
2652
2653         addBody := func(pos src.XPos, r *reader, captured []ir.Node) {
2654                 recvs, params := r.syntheticArgs(pos)
2655                 assert(len(recvs) == 0)
2656
2657                 fun := captured[0]
2658
2659                 var args ir.Nodes
2660                 args.Append(captured[1:]...)
2661                 args.Append(params...)
2662
2663                 r.syntheticTailCall(pos, fun, args)
2664         }
2665
2666         return r.syntheticClosure(origPos, typ, ifaceHack, captured, addBody)
2667 }
2668
2669 // methodExprWrap returns a function literal that changes method's
2670 // first parameter's type to recv, and uses implicits/deref/addr to
2671 // select the appropriate receiver parameter to pass to method.
2672 func (r *reader) methodExprWrap(origPos src.XPos, recv *types.Type, implicits []int, deref, addr bool, method, dictPtr ir.Node) ir.Node {
2673         var captured ir.Nodes
2674         captured.Append(method)
2675
2676         params, results := syntheticSig(method.Type())
2677
2678         // Change first parameter to recv.
2679         params[0].Type = recv
2680
2681         // If we have a dictionary pointer argument to pass, then omit the
2682         // underlying method expression's dictionary parameter from the
2683         // returned signature too.
2684         if dictPtr != nil {
2685                 captured.Append(dictPtr)
2686                 params = append(params[:1], params[2:]...)
2687         }
2688
2689         typ := types.NewSignature(nil, params, results)
2690
2691         addBody := func(pos src.XPos, r *reader, captured []ir.Node) {
2692                 recvs, args := r.syntheticArgs(pos)
2693                 assert(len(recvs) == 0)
2694
2695                 fn := captured[0]
2696
2697                 // Rewrite first argument based on implicits/deref/addr.
2698                 {
2699                         arg := args[0]
2700                         for _, ix := range implicits {
2701                                 arg = Implicit(typecheck.DotField(pos, arg, ix))
2702                         }
2703                         if deref {
2704                                 arg = Implicit(Deref(pos, arg.Type().Elem(), arg))
2705                         } else if addr {
2706                                 arg = Implicit(Addr(pos, arg))
2707                         }
2708                         args[0] = arg
2709                 }
2710
2711                 // Insert dictionary argument, if provided.
2712                 if dictPtr != nil {
2713                         newArgs := make([]ir.Node, len(args)+1)
2714                         newArgs[0] = args[0]
2715                         newArgs[1] = captured[1]
2716                         copy(newArgs[2:], args[1:])
2717                         args = newArgs
2718                 }
2719
2720                 r.syntheticTailCall(pos, fn, args)
2721         }
2722
2723         return r.syntheticClosure(origPos, typ, false, captured, addBody)
2724 }
2725
2726 // syntheticClosure constructs a synthetic function literal for
2727 // currying dictionary arguments. origPos is the position used for the
2728 // closure, which must be a non-inlined position. typ is the function
2729 // literal's signature type.
2730 //
2731 // captures is a list of expressions that need to be evaluated at the
2732 // point of function literal evaluation and captured by the function
2733 // literal. If ifaceHack is true and captures[1] is an interface type,
2734 // it's checked to be non-nil after evaluation.
2735 //
2736 // addBody is a callback function to populate the function body. The
2737 // list of captured values passed back has the captured variables for
2738 // use within the function literal, corresponding to the expressions
2739 // in captures.
2740 func (r *reader) syntheticClosure(origPos src.XPos, typ *types.Type, ifaceHack bool, captures ir.Nodes, addBody func(pos src.XPos, r *reader, captured []ir.Node)) ir.Node {
2741         // isSafe reports whether n is an expression that we can safely
2742         // defer to evaluating inside the closure instead, to avoid storing
2743         // them into the closure.
2744         //
2745         // In practice this is always (and only) the wrappee function.
2746         isSafe := func(n ir.Node) bool {
2747                 if n.Op() == ir.ONAME && n.(*ir.Name).Class == ir.PFUNC {
2748                         return true
2749                 }
2750                 if n.Op() == ir.OMETHEXPR {
2751                         return true
2752                 }
2753
2754                 return false
2755         }
2756
2757         fn := r.inlClosureFunc(origPos, typ)
2758         fn.SetWrapper(true)
2759
2760         clo := fn.OClosure
2761         inlPos := clo.Pos()
2762
2763         var init ir.Nodes
2764         for i, n := range captures {
2765                 if isSafe(n) {
2766                         continue // skip capture; can reference directly
2767                 }
2768
2769                 tmp := r.tempCopy(inlPos, n, &init)
2770                 ir.NewClosureVar(origPos, fn, tmp)
2771
2772                 // We need to nil check interface receivers at the point of method
2773                 // value evaluation, ugh.
2774                 if ifaceHack && i == 1 && n.Type().IsInterface() {
2775                         check := ir.NewUnaryExpr(inlPos, ir.OCHECKNIL, ir.NewUnaryExpr(inlPos, ir.OITAB, tmp))
2776                         init.Append(typecheck.Stmt(check))
2777                 }
2778         }
2779
2780         pri := pkgReaderIndex{synthetic: func(pos src.XPos, r *reader) {
2781                 captured := make([]ir.Node, len(captures))
2782                 next := 0
2783                 for i, n := range captures {
2784                         if isSafe(n) {
2785                                 captured[i] = n
2786                         } else {
2787                                 captured[i] = r.closureVars[next]
2788                                 next++
2789                         }
2790                 }
2791                 assert(next == len(r.closureVars))
2792
2793                 addBody(origPos, r, captured)
2794         }}
2795         bodyReader[fn] = pri
2796         pri.funcBody(fn)
2797
2798         return ir.InitExpr(init, clo)
2799 }
2800
2801 // syntheticSig duplicates and returns the params and results lists
2802 // for sig, but renaming anonymous parameters so they can be assigned
2803 // ir.Names.
2804 func syntheticSig(sig *types.Type) (params, results []*types.Field) {
2805         clone := func(params []*types.Field) []*types.Field {
2806                 res := make([]*types.Field, len(params))
2807                 for i, param := range params {
2808                         sym := param.Sym
2809                         if sym == nil || sym.Name == "_" {
2810                                 sym = typecheck.LookupNum(".anon", i)
2811                         }
2812                         // TODO(mdempsky): It would be nice to preserve the original
2813                         // parameter positions here instead, but at least
2814                         // typecheck.NewMethodType replaces them with base.Pos, making
2815                         // them useless. Worse, the positions copied from base.Pos may
2816                         // have inlining contexts, which we definitely don't want here
2817                         // (e.g., #54625).
2818                         res[i] = types.NewField(base.AutogeneratedPos, sym, param.Type)
2819                         res[i].SetIsDDD(param.IsDDD())
2820                 }
2821                 return res
2822         }
2823
2824         return clone(sig.Params()), clone(sig.Results())
2825 }
2826
2827 func (r *reader) optExpr() ir.Node {
2828         if r.Bool() {
2829                 return r.expr()
2830         }
2831         return nil
2832 }
2833
2834 // methodExpr reads a method expression reference, and returns three
2835 // (possibly nil) expressions related to it:
2836 //
2837 // baseFn is always non-nil: it's either a function of the appropriate
2838 // type already, or it has an extra dictionary parameter as the second
2839 // parameter (i.e., immediately after the promoted receiver
2840 // parameter).
2841 //
2842 // If dictPtr is non-nil, then it's a dictionary argument that must be
2843 // passed as the second argument to baseFn.
2844 //
2845 // If wrapperFn is non-nil, then it's either the same as baseFn (if
2846 // dictPtr is nil), or it's semantically equivalent to currying baseFn
2847 // to pass dictPtr. (wrapperFn is nil when dictPtr is an expression
2848 // that needs to be computed dynamically.)
2849 //
2850 // For callers that are creating a call to the returned method, it's
2851 // best to emit a call to baseFn, and include dictPtr in the arguments
2852 // list as appropriate.
2853 //
2854 // For callers that want to return a method expression without
2855 // invoking it, they may return wrapperFn if it's non-nil; but
2856 // otherwise, they need to create their own wrapper.
2857 func (r *reader) methodExpr() (wrapperFn, baseFn, dictPtr ir.Node) {
2858         recv := r.typ()
2859         sig0 := r.typ()
2860         pos := r.pos()
2861         _, sym := r.selector()
2862
2863         // Signature type to return (i.e., recv prepended to the method's
2864         // normal parameters list).
2865         sig := typecheck.NewMethodType(sig0, recv)
2866
2867         if r.Bool() { // type parameter method expression
2868                 idx := r.Len()
2869                 word := r.dictWord(pos, r.dict.typeParamMethodExprsOffset()+idx)
2870
2871                 // TODO(mdempsky): If the type parameter was instantiated with an
2872                 // interface type (i.e., embed.IsInterface()), then we could
2873                 // return the OMETHEXPR instead and save an indirection.
2874
2875                 // We wrote the method expression's entry point PC into the
2876                 // dictionary, but for Go `func` values we need to return a
2877                 // closure (i.e., pointer to a structure with the PC as the first
2878                 // field). Because method expressions don't have any closure
2879                 // variables, we pun the dictionary entry as the closure struct.
2880                 fn := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, sig, ir.NewAddrExpr(pos, word)))
2881                 return fn, fn, nil
2882         }
2883
2884         // TODO(mdempsky): I'm pretty sure this isn't needed: implicits is
2885         // only relevant to locally defined types, but they can't have
2886         // (non-promoted) methods.
2887         var implicits []*types.Type
2888         if r.dict != nil {
2889                 implicits = r.dict.targs
2890         }
2891
2892         if r.Bool() { // dynamic subdictionary
2893                 idx := r.Len()
2894                 info := r.dict.subdicts[idx]
2895                 explicits := r.p.typListIdx(info.explicits, r.dict)
2896
2897                 shapedObj := r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
2898                 shapedFn := shapedMethodExpr(pos, shapedObj, sym)
2899
2900                 // TODO(mdempsky): Is there a more robust way to get the
2901                 // dictionary pointer type here?
2902                 dictPtrType := shapedFn.Type().Param(1).Type
2903                 dictPtr := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx)))
2904
2905                 return nil, shapedFn, dictPtr
2906         }
2907
2908         if r.Bool() { // static dictionary
2909                 info := r.objInfo()
2910                 explicits := r.p.typListIdx(info.explicits, r.dict)
2911
2912                 shapedObj := r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
2913                 shapedFn := shapedMethodExpr(pos, shapedObj, sym)
2914
2915                 dict := r.p.objDictName(info.idx, implicits, explicits)
2916                 dictPtr := typecheck.Expr(ir.NewAddrExpr(pos, dict))
2917
2918                 // Check that dictPtr matches shapedFn's dictionary parameter.
2919                 if !types.Identical(dictPtr.Type(), shapedFn.Type().Param(1).Type) {
2920                         base.FatalfAt(pos, "dict %L, but shaped method %L", dict, shapedFn)
2921                 }
2922
2923                 // For statically known instantiations, we can take advantage of
2924                 // the stenciled wrapper.
2925                 base.AssertfAt(!recv.HasShape(), pos, "shaped receiver %v", recv)
2926                 wrapperFn := typecheck.NewMethodExpr(pos, recv, sym)
2927                 base.AssertfAt(types.Identical(sig, wrapperFn.Type()), pos, "wrapper %L does not have type %v", wrapperFn, sig)
2928
2929                 return wrapperFn, shapedFn, dictPtr
2930         }
2931
2932         // Simple method expression; no dictionary needed.
2933         base.AssertfAt(!recv.HasShape() || recv.IsInterface(), pos, "shaped receiver %v", recv)
2934         fn := typecheck.NewMethodExpr(pos, recv, sym)
2935         return fn, fn, nil
2936 }
2937
2938 // shapedMethodExpr returns the specified method on the given shaped
2939 // type.
2940 func shapedMethodExpr(pos src.XPos, obj *ir.Name, sym *types.Sym) *ir.SelectorExpr {
2941         assert(obj.Op() == ir.OTYPE)
2942
2943         typ := obj.Type()
2944         assert(typ.HasShape())
2945
2946         method := func() *types.Field {
2947                 for _, method := range typ.Methods() {
2948                         if method.Sym == sym {
2949                                 return method
2950                         }
2951                 }
2952
2953                 base.FatalfAt(pos, "failed to find method %v in shaped type %v", sym, typ)
2954                 panic("unreachable")
2955         }()
2956
2957         // Construct an OMETHEXPR node.
2958         recv := method.Type.Recv().Type
2959         return typecheck.NewMethodExpr(pos, recv, sym)
2960 }
2961
2962 func (r *reader) multiExpr() []ir.Node {
2963         r.Sync(pkgbits.SyncMultiExpr)
2964
2965         if r.Bool() { // N:1
2966                 pos := r.pos()
2967                 expr := r.expr()
2968
2969                 results := make([]ir.Node, r.Len())
2970                 as := ir.NewAssignListStmt(pos, ir.OAS2, nil, []ir.Node{expr})
2971                 as.Def = true
2972                 for i := range results {
2973                         tmp := r.temp(pos, r.typ())
2974                         as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp))
2975                         as.Lhs.Append(tmp)
2976
2977                         res := ir.Node(tmp)
2978                         if r.Bool() {
2979                                 n := ir.NewConvExpr(pos, ir.OCONV, r.typ(), res)
2980                                 n.TypeWord, n.SrcRType = r.convRTTI(pos)
2981                                 n.SetImplicit(true)
2982                                 res = typecheck.Expr(n)
2983                         }
2984                         results[i] = res
2985                 }
2986
2987                 // TODO(mdempsky): Could use ir.InlinedCallExpr instead?
2988                 results[0] = ir.InitExpr([]ir.Node{typecheck.Stmt(as)}, results[0])
2989                 return results
2990         }
2991
2992         // N:N
2993         exprs := make([]ir.Node, r.Len())
2994         if len(exprs) == 0 {
2995                 return nil
2996         }
2997         for i := range exprs {
2998                 exprs[i] = r.expr()
2999         }
3000         return exprs
3001 }
3002
3003 // temp returns a new autotemp of the specified type.
3004 func (r *reader) temp(pos src.XPos, typ *types.Type) *ir.Name {
3005         return typecheck.TempAt(pos, r.curfn, typ)
3006 }
3007
3008 // tempCopy declares and returns a new autotemp initialized to the
3009 // value of expr.
3010 func (r *reader) tempCopy(pos src.XPos, expr ir.Node, init *ir.Nodes) *ir.Name {
3011         tmp := r.temp(pos, expr.Type())
3012
3013         init.Append(typecheck.Stmt(ir.NewDecl(pos, ir.ODCL, tmp)))
3014
3015         assign := ir.NewAssignStmt(pos, tmp, expr)
3016         assign.Def = true
3017         init.Append(typecheck.Stmt(ir.NewAssignStmt(pos, tmp, expr)))
3018
3019         tmp.Defn = assign
3020
3021         return tmp
3022 }
3023
3024 func (r *reader) compLit() ir.Node {
3025         r.Sync(pkgbits.SyncCompLit)
3026         pos := r.pos()
3027         typ0 := r.typ()
3028
3029         typ := typ0
3030         if typ.IsPtr() {
3031                 typ = typ.Elem()
3032         }
3033         if typ.Kind() == types.TFORW {
3034                 base.FatalfAt(pos, "unresolved composite literal type: %v", typ)
3035         }
3036         var rtype ir.Node
3037         if typ.IsMap() {
3038                 rtype = r.rtype(pos)
3039         }
3040         isStruct := typ.Kind() == types.TSTRUCT
3041
3042         elems := make([]ir.Node, r.Len())
3043         for i := range elems {
3044                 elemp := &elems[i]
3045
3046                 if isStruct {
3047                         sk := ir.NewStructKeyExpr(r.pos(), typ.Field(r.Len()), nil)
3048                         *elemp, elemp = sk, &sk.Value
3049                 } else if r.Bool() {
3050                         kv := ir.NewKeyExpr(r.pos(), r.expr(), nil)
3051                         *elemp, elemp = kv, &kv.Value
3052                 }
3053
3054                 *elemp = wrapName(r.pos(), r.expr())
3055         }
3056
3057         lit := typecheck.Expr(ir.NewCompLitExpr(pos, ir.OCOMPLIT, typ, elems))
3058         if rtype != nil {
3059                 lit := lit.(*ir.CompLitExpr)
3060                 lit.RType = rtype
3061         }
3062         if typ0.IsPtr() {
3063                 lit = typecheck.Expr(typecheck.NodAddrAt(pos, lit))
3064                 lit.SetType(typ0)
3065         }
3066         return lit
3067 }
3068
3069 func wrapName(pos src.XPos, x ir.Node) ir.Node {
3070         // These nodes do not carry line numbers.
3071         // Introduce a wrapper node to give them the correct line.
3072         switch x.Op() {
3073         case ir.OTYPE, ir.OLITERAL:
3074                 if x.Sym() == nil {
3075                         break
3076                 }
3077                 fallthrough
3078         case ir.ONAME, ir.ONONAME, ir.ONIL:
3079                 p := ir.NewParenExpr(pos, x)
3080                 p.SetImplicit(true)
3081                 return p
3082         }
3083         return x
3084 }
3085
3086 func (r *reader) funcLit() ir.Node {
3087         r.Sync(pkgbits.SyncFuncLit)
3088
3089         // The underlying function declaration (including its parameters'
3090         // positions, if any) need to remain the original, uninlined
3091         // positions. This is because we track inlining-context on nodes so
3092         // we can synthesize the extra implied stack frames dynamically when
3093         // generating tracebacks, whereas those stack frames don't make
3094         // sense *within* the function literal. (Any necessary inlining
3095         // adjustments will have been applied to the call expression
3096         // instead.)
3097         //
3098         // This is subtle, and getting it wrong leads to cycles in the
3099         // inlining tree, which lead to infinite loops during stack
3100         // unwinding (#46234, #54625).
3101         //
3102         // Note that we *do* want the inline-adjusted position for the
3103         // OCLOSURE node, because that position represents where any heap
3104         // allocation of the closure is credited (#49171).
3105         r.suppressInlPos++
3106         origPos := r.pos()
3107         sig := r.signature(nil)
3108         r.suppressInlPos--
3109
3110         fn := r.inlClosureFunc(origPos, sig)
3111
3112         fn.ClosureVars = make([]*ir.Name, 0, r.Len())
3113         for len(fn.ClosureVars) < cap(fn.ClosureVars) {
3114                 // TODO(mdempsky): I think these should be original positions too
3115                 // (i.e., not inline-adjusted).
3116                 ir.NewClosureVar(r.pos(), fn, r.useLocal())
3117         }
3118         if param := r.dictParam; param != nil {
3119                 // If we have a dictionary parameter, capture it too. For
3120                 // simplicity, we capture it last and unconditionally.
3121                 ir.NewClosureVar(param.Pos(), fn, param)
3122         }
3123
3124         r.addBody(fn, nil)
3125
3126         // un-hide closures belong to init function.
3127         if (r.curfn.IsPackageInit() || strings.HasPrefix(r.curfn.Sym().Name, "init.")) && ir.IsTrivialClosure(fn.OClosure) {
3128                 fn.SetIsHiddenClosure(false)
3129         }
3130
3131         return fn.OClosure
3132 }
3133
3134 // inlClosureFunc constructs a new closure function, but correctly
3135 // handles inlining.
3136 func (r *reader) inlClosureFunc(origPos src.XPos, sig *types.Type) *ir.Func {
3137         curfn := r.inlCaller
3138         if curfn == nil {
3139                 curfn = r.curfn
3140         }
3141
3142         // TODO(mdempsky): Remove hard-coding of typecheck.Target.
3143         return ir.NewClosureFunc(origPos, r.inlPos(origPos), ir.OCLOSURE, sig, curfn, typecheck.Target)
3144 }
3145
3146 func (r *reader) exprList() []ir.Node {
3147         r.Sync(pkgbits.SyncExprList)
3148         return r.exprs()
3149 }
3150
3151 func (r *reader) exprs() []ir.Node {
3152         r.Sync(pkgbits.SyncExprs)
3153         nodes := make([]ir.Node, r.Len())
3154         if len(nodes) == 0 {
3155                 return nil // TODO(mdempsky): Unclear if this matters.
3156         }
3157         for i := range nodes {
3158                 nodes[i] = r.expr()
3159         }
3160         return nodes
3161 }
3162
3163 // dictWord returns an expression to return the specified
3164 // uintptr-typed word from the dictionary parameter.
3165 func (r *reader) dictWord(pos src.XPos, idx int) ir.Node {
3166         base.AssertfAt(r.dictParam != nil, pos, "expected dictParam in %v", r.curfn)
3167         return typecheck.Expr(ir.NewIndexExpr(pos, r.dictParam, ir.NewInt(pos, int64(idx))))
3168 }
3169
3170 // rttiWord is like dictWord, but converts it to *byte (the type used
3171 // internally to represent *runtime._type and *runtime.itab).
3172 func (r *reader) rttiWord(pos src.XPos, idx int) ir.Node {
3173         return typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, types.NewPtr(types.Types[types.TUINT8]), r.dictWord(pos, idx)))
3174 }
3175
3176 // rtype reads a type reference from the element bitstream, and
3177 // returns an expression of type *runtime._type representing that
3178 // type.
3179 func (r *reader) rtype(pos src.XPos) ir.Node {
3180         _, rtype := r.rtype0(pos)
3181         return rtype
3182 }
3183
3184 func (r *reader) rtype0(pos src.XPos) (typ *types.Type, rtype ir.Node) {
3185         r.Sync(pkgbits.SyncRType)
3186         if r.Bool() { // derived type
3187                 idx := r.Len()
3188                 info := r.dict.rtypes[idx]
3189                 typ = r.p.typIdx(info, r.dict, true)
3190                 rtype = r.rttiWord(pos, r.dict.rtypesOffset()+idx)
3191                 return
3192         }
3193
3194         typ = r.typ()
3195         rtype = reflectdata.TypePtrAt(pos, typ)
3196         return
3197 }
3198
3199 // varDictIndex populates name.DictIndex if name is a derived type.
3200 func (r *reader) varDictIndex(name *ir.Name) {
3201         if r.Bool() {
3202                 idx := 1 + r.dict.rtypesOffset() + r.Len()
3203                 if int(uint16(idx)) != idx {
3204                         base.FatalfAt(name.Pos(), "DictIndex overflow for %v: %v", name, idx)
3205                 }
3206                 name.DictIndex = uint16(idx)
3207         }
3208 }
3209
3210 // itab returns a (typ, iface) pair of types.
3211 //
3212 // typRType and ifaceRType are expressions that evaluate to the
3213 // *runtime._type for typ and iface, respectively.
3214 //
3215 // If typ is a concrete type and iface is a non-empty interface type,
3216 // then itab is an expression that evaluates to the *runtime.itab for
3217 // the pair. Otherwise, itab is nil.
3218 func (r *reader) itab(pos src.XPos) (typ *types.Type, typRType ir.Node, iface *types.Type, ifaceRType ir.Node, itab ir.Node) {
3219         typ, typRType = r.rtype0(pos)
3220         iface, ifaceRType = r.rtype0(pos)
3221
3222         idx := -1
3223         if r.Bool() {
3224                 idx = r.Len()
3225         }
3226
3227         if !typ.IsInterface() && iface.IsInterface() && !iface.IsEmptyInterface() {
3228                 if idx >= 0 {
3229                         itab = r.rttiWord(pos, r.dict.itabsOffset()+idx)
3230                 } else {
3231                         base.AssertfAt(!typ.HasShape(), pos, "%v is a shape type", typ)
3232                         base.AssertfAt(!iface.HasShape(), pos, "%v is a shape type", iface)
3233
3234                         lsym := reflectdata.ITabLsym(typ, iface)
3235                         itab = typecheck.LinksymAddr(pos, lsym, types.Types[types.TUINT8])
3236                 }
3237         }
3238
3239         return
3240 }
3241
3242 // convRTTI returns expressions appropriate for populating an
3243 // ir.ConvExpr's TypeWord and SrcRType fields, respectively.
3244 func (r *reader) convRTTI(pos src.XPos) (typeWord, srcRType ir.Node) {
3245         r.Sync(pkgbits.SyncConvRTTI)
3246         src, srcRType0, dst, dstRType, itab := r.itab(pos)
3247         if !dst.IsInterface() {
3248                 return
3249         }
3250
3251         // See reflectdata.ConvIfaceTypeWord.
3252         switch {
3253         case dst.IsEmptyInterface():
3254                 if !src.IsInterface() {
3255                         typeWord = srcRType0 // direct eface construction
3256                 }
3257         case !src.IsInterface():
3258                 typeWord = itab // direct iface construction
3259         default:
3260                 typeWord = dstRType // convI2I
3261         }
3262
3263         // See reflectdata.ConvIfaceSrcRType.
3264         if !src.IsInterface() {
3265                 srcRType = srcRType0
3266         }
3267
3268         return
3269 }
3270
3271 func (r *reader) exprType() ir.Node {
3272         r.Sync(pkgbits.SyncExprType)
3273         pos := r.pos()
3274
3275         var typ *types.Type
3276         var rtype, itab ir.Node
3277
3278         if r.Bool() {
3279                 typ, rtype, _, _, itab = r.itab(pos)
3280                 if !typ.IsInterface() {
3281                         rtype = nil // TODO(mdempsky): Leave set?
3282                 }
3283         } else {
3284                 typ, rtype = r.rtype0(pos)
3285
3286                 if !r.Bool() { // not derived
3287                         return ir.TypeNode(typ)
3288                 }
3289         }
3290
3291         dt := ir.NewDynamicType(pos, rtype)
3292         dt.ITab = itab
3293         return typed(typ, dt)
3294 }
3295
3296 func (r *reader) op() ir.Op {
3297         r.Sync(pkgbits.SyncOp)
3298         return ir.Op(r.Len())
3299 }
3300
3301 // @@@ Package initialization
3302
3303 func (r *reader) pkgInit(self *types.Pkg, target *ir.Package) {
3304         cgoPragmas := make([][]string, r.Len())
3305         for i := range cgoPragmas {
3306                 cgoPragmas[i] = r.Strings()
3307         }
3308         target.CgoPragmas = cgoPragmas
3309
3310         r.pkgInitOrder(target)
3311
3312         r.pkgDecls(target)
3313
3314         r.Sync(pkgbits.SyncEOF)
3315 }
3316
3317 // pkgInitOrder creates a synthetic init function to handle any
3318 // package-scope initialization statements.
3319 func (r *reader) pkgInitOrder(target *ir.Package) {
3320         initOrder := make([]ir.Node, r.Len())
3321         if len(initOrder) == 0 {
3322                 return
3323         }
3324
3325         // Make a function that contains all the initialization statements.
3326         pos := base.AutogeneratedPos
3327         base.Pos = pos
3328
3329         fn := ir.NewFunc(pos, pos, typecheck.Lookup("init"), types.NewSignature(nil, nil, nil))
3330         fn.SetIsPackageInit(true)
3331         fn.SetInlinabilityChecked(true) // suppress useless "can inline" diagnostics
3332
3333         typecheck.DeclFunc(fn)
3334         r.curfn = fn
3335
3336         for i := range initOrder {
3337                 lhs := make([]ir.Node, r.Len())
3338                 for j := range lhs {
3339                         lhs[j] = r.obj()
3340                 }
3341                 rhs := r.expr()
3342                 pos := lhs[0].Pos()
3343
3344                 var as ir.Node
3345                 if len(lhs) == 1 {
3346                         as = typecheck.Stmt(ir.NewAssignStmt(pos, lhs[0], rhs))
3347                 } else {
3348                         as = typecheck.Stmt(ir.NewAssignListStmt(pos, ir.OAS2, lhs, []ir.Node{rhs}))
3349                 }
3350
3351                 for _, v := range lhs {
3352                         v.(*ir.Name).Defn = as
3353                 }
3354
3355                 initOrder[i] = as
3356         }
3357
3358         fn.Body = initOrder
3359
3360         typecheck.FinishFuncBody()
3361         r.curfn = nil
3362         r.locals = nil
3363
3364         // Outline (if legal/profitable) global map inits.
3365         staticinit.OutlineMapInits(fn)
3366
3367         target.Inits = append(target.Inits, fn)
3368 }
3369
3370 func (r *reader) pkgDecls(target *ir.Package) {
3371         r.Sync(pkgbits.SyncDecls)
3372         for {
3373                 switch code := codeDecl(r.Code(pkgbits.SyncDecl)); code {
3374                 default:
3375                         panic(fmt.Sprintf("unhandled decl: %v", code))
3376
3377                 case declEnd:
3378                         return
3379
3380                 case declFunc:
3381                         names := r.pkgObjs(target)
3382                         assert(len(names) == 1)
3383                         target.Funcs = append(target.Funcs, names[0].Func)
3384
3385                 case declMethod:
3386                         typ := r.typ()
3387                         _, sym := r.selector()
3388
3389                         method := typecheck.Lookdot1(nil, sym, typ, typ.Methods(), 0)
3390                         target.Funcs = append(target.Funcs, method.Nname.(*ir.Name).Func)
3391
3392                 case declVar:
3393                         names := r.pkgObjs(target)
3394
3395                         if n := r.Len(); n > 0 {
3396                                 assert(len(names) == 1)
3397                                 embeds := make([]ir.Embed, n)
3398                                 for i := range embeds {
3399                                         embeds[i] = ir.Embed{Pos: r.pos(), Patterns: r.Strings()}
3400                                 }
3401                                 names[0].Embed = &embeds
3402                                 target.Embeds = append(target.Embeds, names[0])
3403                         }
3404
3405                 case declOther:
3406                         r.pkgObjs(target)
3407                 }
3408         }
3409 }
3410
3411 func (r *reader) pkgObjs(target *ir.Package) []*ir.Name {
3412         r.Sync(pkgbits.SyncDeclNames)
3413         nodes := make([]*ir.Name, r.Len())
3414         for i := range nodes {
3415                 r.Sync(pkgbits.SyncDeclName)
3416
3417                 name := r.obj().(*ir.Name)
3418                 nodes[i] = name
3419
3420                 sym := name.Sym()
3421                 if sym.IsBlank() {
3422                         continue
3423                 }
3424
3425                 switch name.Class {
3426                 default:
3427                         base.FatalfAt(name.Pos(), "unexpected class: %v", name.Class)
3428
3429                 case ir.PEXTERN:
3430                         target.Externs = append(target.Externs, name)
3431
3432                 case ir.PFUNC:
3433                         assert(name.Type().Recv() == nil)
3434
3435                         // TODO(mdempsky): Cleaner way to recognize init?
3436                         if strings.HasPrefix(sym.Name, "init.") {
3437                                 target.Inits = append(target.Inits, name.Func)
3438                         }
3439                 }
3440
3441                 if base.Ctxt.Flag_dynlink && types.LocalPkg.Name == "main" && types.IsExported(sym.Name) && name.Op() == ir.ONAME {
3442                         assert(!sym.OnExportList())
3443                         target.PluginExports = append(target.PluginExports, name)
3444                         sym.SetOnExportList(true)
3445                 }
3446
3447                 if base.Flag.AsmHdr != "" && (name.Op() == ir.OLITERAL || name.Op() == ir.OTYPE) {
3448                         assert(!sym.Asm())
3449                         target.AsmHdrDecls = append(target.AsmHdrDecls, name)
3450                         sym.SetAsm(true)
3451                 }
3452         }
3453
3454         return nodes
3455 }
3456
3457 // @@@ Inlining
3458
3459 // unifiedHaveInlineBody reports whether we have the function body for
3460 // fn, so we can inline it.
3461 func unifiedHaveInlineBody(fn *ir.Func) bool {
3462         if fn.Inl == nil {
3463                 return false
3464         }
3465
3466         _, ok := bodyReaderFor(fn)
3467         return ok
3468 }
3469
3470 var inlgen = 0
3471
3472 // unifiedInlineCall implements inline.NewInline by re-reading the function
3473 // body from its Unified IR export data.
3474 func unifiedInlineCall(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
3475         pri, ok := bodyReaderFor(fn)
3476         if !ok {
3477                 base.FatalfAt(call.Pos(), "cannot inline call to %v: missing inline body", fn)
3478         }
3479
3480         if !fn.Inl.HaveDcl {
3481                 expandInline(fn, pri)
3482         }
3483
3484         r := pri.asReader(pkgbits.RelocBody, pkgbits.SyncFuncBody)
3485
3486         tmpfn := ir.NewFunc(fn.Pos(), fn.Nname.Pos(), callerfn.Sym(), fn.Type())
3487
3488         r.curfn = tmpfn
3489
3490         r.inlCaller = callerfn
3491         r.inlCall = call
3492         r.inlFunc = fn
3493         r.inlTreeIndex = inlIndex
3494         r.inlPosBases = make(map[*src.PosBase]*src.PosBase)
3495
3496         r.closureVars = make([]*ir.Name, len(r.inlFunc.ClosureVars))
3497         for i, cv := range r.inlFunc.ClosureVars {
3498                 // TODO(mdempsky): It should be possible to support this case, but
3499                 // for now we rely on the inliner avoiding it.
3500                 if cv.Outer.Curfn != callerfn {
3501                         base.FatalfAt(call.Pos(), "inlining closure call across frames")
3502                 }
3503                 r.closureVars[i] = cv.Outer
3504         }
3505         if len(r.closureVars) != 0 && r.hasTypeParams() {
3506                 r.dictParam = r.closureVars[len(r.closureVars)-1] // dictParam is last; see reader.funcLit
3507         }
3508
3509         r.funcargs(fn)
3510
3511         r.delayResults = fn.Inl.CanDelayResults
3512
3513         r.retlabel = typecheck.AutoLabel(".i")
3514         inlgen++
3515
3516         init := ir.TakeInit(call)
3517
3518         // For normal function calls, the function callee expression
3519         // may contain side effects. Make sure to preserve these,
3520         // if necessary (#42703).
3521         if call.Op() == ir.OCALLFUNC {
3522                 inline.CalleeEffects(&init, call.X)
3523         }
3524
3525         var args ir.Nodes
3526         if call.Op() == ir.OCALLMETH {
3527                 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
3528         }
3529         args.Append(call.Args...)
3530
3531         // Create assignment to declare and initialize inlvars.
3532         as2 := ir.NewAssignListStmt(call.Pos(), ir.OAS2, r.inlvars, args)
3533         as2.Def = true
3534         var as2init ir.Nodes
3535         for _, name := range r.inlvars {
3536                 if ir.IsBlank(name) {
3537                         continue
3538                 }
3539                 // TODO(mdempsky): Use inlined position of name.Pos() instead?
3540                 name := name.(*ir.Name)
3541                 as2init.Append(ir.NewDecl(call.Pos(), ir.ODCL, name))
3542                 name.Defn = as2
3543         }
3544         as2.SetInit(as2init)
3545         init.Append(typecheck.Stmt(as2))
3546
3547         if !r.delayResults {
3548                 // If not delaying retvars, declare and zero initialize the
3549                 // result variables now.
3550                 for _, name := range r.retvars {
3551                         // TODO(mdempsky): Use inlined position of name.Pos() instead?
3552                         name := name.(*ir.Name)
3553                         init.Append(ir.NewDecl(call.Pos(), ir.ODCL, name))
3554                         ras := ir.NewAssignStmt(call.Pos(), name, nil)
3555                         init.Append(typecheck.Stmt(ras))
3556                 }
3557         }
3558
3559         // Add an inline mark just before the inlined body.
3560         // This mark is inline in the code so that it's a reasonable spot
3561         // to put a breakpoint. Not sure if that's really necessary or not
3562         // (in which case it could go at the end of the function instead).
3563         // Note issue 28603.
3564         init.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(r.inlTreeIndex)))
3565
3566         ir.WithFunc(r.curfn, func() {
3567                 if !r.syntheticBody(call.Pos()) {
3568                         assert(r.Bool()) // have body
3569
3570                         r.curfn.Body = r.stmts()
3571                         r.curfn.Endlineno = r.pos()
3572                 }
3573
3574                 // TODO(mdempsky): This shouldn't be necessary. Inlining might
3575                 // read in new function/method declarations, which could
3576                 // potentially be recursively inlined themselves; but we shouldn't
3577                 // need to read in the non-inlined bodies for the declarations
3578                 // themselves. But currently it's an easy fix to #50552.
3579                 readBodies(typecheck.Target, true)
3580
3581                 // Replace any "return" statements within the function body.
3582                 var edit func(ir.Node) ir.Node
3583                 edit = func(n ir.Node) ir.Node {
3584                         if ret, ok := n.(*ir.ReturnStmt); ok {
3585                                 n = typecheck.Stmt(r.inlReturn(ret))
3586                         }
3587                         ir.EditChildren(n, edit)
3588                         return n
3589                 }
3590                 edit(r.curfn)
3591         })
3592
3593         body := ir.Nodes(r.curfn.Body)
3594
3595         // Reparent any declarations into the caller function.
3596         for _, name := range r.curfn.Dcl {
3597                 name.Curfn = callerfn
3598                 callerfn.Dcl = append(callerfn.Dcl, name)
3599
3600                 if name.AutoTemp() {
3601                         name.SetEsc(ir.EscUnknown)
3602                         name.SetInlLocal(true)
3603                 }
3604         }
3605
3606         body.Append(ir.NewLabelStmt(call.Pos(), r.retlabel))
3607
3608         res := ir.NewInlinedCallExpr(call.Pos(), body, append([]ir.Node(nil), r.retvars...))
3609         res.SetInit(init)
3610         res.SetType(call.Type())
3611         res.SetTypecheck(1)
3612
3613         // Inlining shouldn't add any functions to todoBodies.
3614         assert(len(todoBodies) == 0)
3615
3616         return res
3617 }
3618
3619 // inlReturn returns a statement that can substitute for the given
3620 // return statement when inlining.
3621 func (r *reader) inlReturn(ret *ir.ReturnStmt) *ir.BlockStmt {
3622         pos := r.inlCall.Pos()
3623
3624         block := ir.TakeInit(ret)
3625
3626         if results := ret.Results; len(results) != 0 {
3627                 assert(len(r.retvars) == len(results))
3628
3629                 as2 := ir.NewAssignListStmt(pos, ir.OAS2, append([]ir.Node(nil), r.retvars...), ret.Results)
3630
3631                 if r.delayResults {
3632                         for _, name := range r.retvars {
3633                                 // TODO(mdempsky): Use inlined position of name.Pos() instead?
3634                                 name := name.(*ir.Name)
3635                                 block.Append(ir.NewDecl(pos, ir.ODCL, name))
3636                                 name.Defn = as2
3637                         }
3638                 }
3639
3640                 block.Append(as2)
3641         }
3642
3643         block.Append(ir.NewBranchStmt(pos, ir.OGOTO, r.retlabel))
3644         return ir.NewBlockStmt(pos, block)
3645 }
3646
3647 // expandInline reads in an extra copy of IR to populate
3648 // fn.Inl.Dcl.
3649 func expandInline(fn *ir.Func, pri pkgReaderIndex) {
3650         // TODO(mdempsky): Remove this function. It's currently needed by
3651         // dwarfgen/dwarf.go:preInliningDcls, which requires fn.Inl.Dcl to
3652         // create abstract function DIEs. But we should be able to provide it
3653         // with the same information some other way.
3654
3655         fndcls := len(fn.Dcl)
3656         topdcls := len(typecheck.Target.Funcs)
3657
3658         tmpfn := ir.NewFunc(fn.Pos(), fn.Nname.Pos(), fn.Sym(), fn.Type())
3659         tmpfn.ClosureVars = fn.ClosureVars
3660
3661         {
3662                 r := pri.asReader(pkgbits.RelocBody, pkgbits.SyncFuncBody)
3663
3664                 // Don't change parameter's Sym/Nname fields.
3665                 r.funarghack = true
3666
3667                 r.funcBody(tmpfn)
3668         }
3669
3670         used := usedLocals(tmpfn.Body)
3671
3672         for _, name := range tmpfn.Dcl {
3673                 if name.Class != ir.PAUTO || used.Has(name) {
3674                         name.Curfn = fn
3675                         fn.Inl.Dcl = append(fn.Inl.Dcl, name)
3676                 } else {
3677                         // TODO(mdempsky): Simplify code after confident that this never
3678                         // happens anymore.
3679                         base.FatalfAt(name.Pos(), "unused auto: %v", name)
3680                 }
3681         }
3682         fn.Inl.HaveDcl = true
3683
3684         // Double check that we didn't change fn.Dcl by accident.
3685         assert(fndcls == len(fn.Dcl))
3686
3687         // typecheck.Stmts may have added function literals to
3688         // typecheck.Target.Decls. Remove them again so we don't risk trying
3689         // to compile them multiple times.
3690         typecheck.Target.Funcs = typecheck.Target.Funcs[:topdcls]
3691 }
3692
3693 // usedLocals returns a set of local variables that are used within body.
3694 func usedLocals(body []ir.Node) ir.NameSet {
3695         var used ir.NameSet
3696         ir.VisitList(body, func(n ir.Node) {
3697                 if n, ok := n.(*ir.Name); ok && n.Op() == ir.ONAME && n.Class == ir.PAUTO {
3698                         used.Add(n)
3699                 }
3700         })
3701         return used
3702 }
3703
3704 // @@@ Method wrappers
3705
3706 // needWrapperTypes lists types for which we may need to generate
3707 // method wrappers.
3708 var needWrapperTypes []*types.Type
3709
3710 // haveWrapperTypes lists types for which we know we already have
3711 // method wrappers, because we found the type in an imported package.
3712 var haveWrapperTypes []*types.Type
3713
3714 // needMethodValueWrappers lists methods for which we may need to
3715 // generate method value wrappers.
3716 var needMethodValueWrappers []methodValueWrapper
3717
3718 // haveMethodValueWrappers lists methods for which we know we already
3719 // have method value wrappers, because we found it in an imported
3720 // package.
3721 var haveMethodValueWrappers []methodValueWrapper
3722
3723 type methodValueWrapper struct {
3724         rcvr   *types.Type
3725         method *types.Field
3726 }
3727
3728 func (r *reader) needWrapper(typ *types.Type) {
3729         if typ.IsPtr() {
3730                 return
3731         }
3732
3733         // If a type was found in an imported package, then we can assume
3734         // that package (or one of its transitive dependencies) already
3735         // generated method wrappers for it.
3736         if r.importedDef() {
3737                 haveWrapperTypes = append(haveWrapperTypes, typ)
3738         } else {
3739                 needWrapperTypes = append(needWrapperTypes, typ)
3740         }
3741 }
3742
3743 // importedDef reports whether r is reading from an imported and
3744 // non-generic element.
3745 //
3746 // If a type was found in an imported package, then we can assume that
3747 // package (or one of its transitive dependencies) already generated
3748 // method wrappers for it.
3749 //
3750 // Exception: If we're instantiating an imported generic type or
3751 // function, we might be instantiating it with type arguments not
3752 // previously seen before.
3753 //
3754 // TODO(mdempsky): Distinguish when a generic function or type was
3755 // instantiated in an imported package so that we can add types to
3756 // haveWrapperTypes instead.
3757 func (r *reader) importedDef() bool {
3758         return r.p != localPkgReader && !r.hasTypeParams()
3759 }
3760
3761 func MakeWrappers(target *ir.Package) {
3762         // always generate a wrapper for error.Error (#29304)
3763         needWrapperTypes = append(needWrapperTypes, types.ErrorType)
3764
3765         seen := make(map[string]*types.Type)
3766
3767         for _, typ := range haveWrapperTypes {
3768                 wrapType(typ, target, seen, false)
3769         }
3770         haveWrapperTypes = nil
3771
3772         for _, typ := range needWrapperTypes {
3773                 wrapType(typ, target, seen, true)
3774         }
3775         needWrapperTypes = nil
3776
3777         for _, wrapper := range haveMethodValueWrappers {
3778                 wrapMethodValue(wrapper.rcvr, wrapper.method, target, false)
3779         }
3780         haveMethodValueWrappers = nil
3781
3782         for _, wrapper := range needMethodValueWrappers {
3783                 wrapMethodValue(wrapper.rcvr, wrapper.method, target, true)
3784         }
3785         needMethodValueWrappers = nil
3786 }
3787
3788 func wrapType(typ *types.Type, target *ir.Package, seen map[string]*types.Type, needed bool) {
3789         key := typ.LinkString()
3790         if prev := seen[key]; prev != nil {
3791                 if !types.Identical(typ, prev) {
3792                         base.Fatalf("collision: types %v and %v have link string %q", typ, prev, key)
3793                 }
3794                 return
3795         }
3796         seen[key] = typ
3797
3798         if !needed {
3799                 // Only called to add to 'seen'.
3800                 return
3801         }
3802
3803         if !typ.IsInterface() {
3804                 typecheck.CalcMethods(typ)
3805         }
3806         for _, meth := range typ.AllMethods() {
3807                 if meth.Sym.IsBlank() || !meth.IsMethod() {
3808                         base.FatalfAt(meth.Pos, "invalid method: %v", meth)
3809                 }
3810
3811                 methodWrapper(0, typ, meth, target)
3812
3813                 // For non-interface types, we also want *T wrappers.
3814                 if !typ.IsInterface() {
3815                         methodWrapper(1, typ, meth, target)
3816
3817                         // For not-in-heap types, *T is a scalar, not pointer shaped,
3818                         // so the interface wrappers use **T.
3819                         if typ.NotInHeap() {
3820                                 methodWrapper(2, typ, meth, target)
3821                         }
3822                 }
3823         }
3824 }
3825
3826 func methodWrapper(derefs int, tbase *types.Type, method *types.Field, target *ir.Package) {
3827         wrapper := tbase
3828         for i := 0; i < derefs; i++ {
3829                 wrapper = types.NewPtr(wrapper)
3830         }
3831
3832         sym := ir.MethodSym(wrapper, method.Sym)
3833         base.Assertf(!sym.Siggen(), "already generated wrapper %v", sym)
3834         sym.SetSiggen(true)
3835
3836         wrappee := method.Type.Recv().Type
3837         if types.Identical(wrapper, wrappee) ||
3838                 !types.IsMethodApplicable(wrapper, method) ||
3839                 !reflectdata.NeedEmit(tbase) {
3840                 return
3841         }
3842
3843         // TODO(mdempsky): Use method.Pos instead?
3844         pos := base.AutogeneratedPos
3845
3846         fn := newWrapperFunc(pos, sym, wrapper, method)
3847
3848         var recv ir.Node = fn.Nname.Type().Recv().Nname.(*ir.Name)
3849
3850         // For simple *T wrappers around T methods, panicwrap produces a
3851         // nicer panic message.
3852         if wrapper.IsPtr() && types.Identical(wrapper.Elem(), wrappee) {
3853                 cond := ir.NewBinaryExpr(pos, ir.OEQ, recv, types.BuiltinPkg.Lookup("nil").Def.(ir.Node))
3854                 then := []ir.Node{ir.NewCallExpr(pos, ir.OCALL, typecheck.LookupRuntime("panicwrap"), nil)}
3855                 fn.Body.Append(ir.NewIfStmt(pos, cond, then, nil))
3856         }
3857
3858         // typecheck will add one implicit deref, if necessary,
3859         // but not-in-heap types require more for their **T wrappers.
3860         for i := 1; i < derefs; i++ {
3861                 recv = Implicit(ir.NewStarExpr(pos, recv))
3862         }
3863
3864         addTailCall(pos, fn, recv, method)
3865
3866         finishWrapperFunc(fn, target)
3867 }
3868
3869 func wrapMethodValue(recvType *types.Type, method *types.Field, target *ir.Package, needed bool) {
3870         sym := ir.MethodSymSuffix(recvType, method.Sym, "-fm")
3871         if sym.Uniq() {
3872                 return
3873         }
3874         sym.SetUniq(true)
3875
3876         // TODO(mdempsky): Use method.Pos instead?
3877         pos := base.AutogeneratedPos
3878
3879         fn := newWrapperFunc(pos, sym, nil, method)
3880         sym.Def = fn.Nname
3881
3882         // Declare and initialize variable holding receiver.
3883         recv := ir.NewHiddenParam(pos, fn, typecheck.Lookup(".this"), recvType)
3884
3885         if !needed {
3886                 return
3887         }
3888
3889         addTailCall(pos, fn, recv, method)
3890
3891         finishWrapperFunc(fn, target)
3892 }
3893
3894 func newWrapperFunc(pos src.XPos, sym *types.Sym, wrapper *types.Type, method *types.Field) *ir.Func {
3895         sig := newWrapperType(wrapper, method)
3896
3897         fn := ir.NewFunc(pos, pos, sym, sig)
3898         fn.SetDupok(true) // TODO(mdempsky): Leave unset for local, non-generic wrappers?
3899
3900         // TODO(mdempsky): De-duplicate with similar logic in funcargs.
3901         defParams := func(class ir.Class, params []*types.Field) {
3902                 for _, param := range params {
3903                         param.Nname = fn.NewLocal(param.Pos, param.Sym, class, param.Type)
3904                 }
3905         }
3906
3907         defParams(ir.PPARAM, sig.Recvs())
3908         defParams(ir.PPARAM, sig.Params())
3909         defParams(ir.PPARAMOUT, sig.Results())
3910
3911         return fn
3912 }
3913
3914 func finishWrapperFunc(fn *ir.Func, target *ir.Package) {
3915         ir.WithFunc(fn, func() {
3916                 typecheck.Stmts(fn.Body)
3917         })
3918
3919         // We generate wrappers after the global inlining pass,
3920         // so we're responsible for applying inlining ourselves here.
3921         // TODO(prattmic): plumb PGO.
3922         inline.InlineCalls(fn, nil)
3923
3924         // The body of wrapper function after inlining may reveal new ir.OMETHVALUE node,
3925         // we don't know whether wrapper function has been generated for it or not, so
3926         // generate one immediately here.
3927         //
3928         // Further, after CL 492017, function that construct closures is allowed to be inlined,
3929         // even though the closure itself can't be inline. So we also need to visit body of any
3930         // closure that we see when visiting body of the wrapper function.
3931         ir.VisitFuncAndClosures(fn, func(n ir.Node) {
3932                 if n, ok := n.(*ir.SelectorExpr); ok && n.Op() == ir.OMETHVALUE {
3933                         wrapMethodValue(n.X.Type(), n.Selection, target, true)
3934                 }
3935         })
3936
3937         fn.Nname.Defn = fn
3938         target.Funcs = append(target.Funcs, fn)
3939 }
3940
3941 // newWrapperType returns a copy of the given signature type, but with
3942 // the receiver parameter type substituted with recvType.
3943 // If recvType is nil, newWrapperType returns a signature
3944 // without a receiver parameter.
3945 func newWrapperType(recvType *types.Type, method *types.Field) *types.Type {
3946         clone := func(params []*types.Field) []*types.Field {
3947                 res := make([]*types.Field, len(params))
3948                 for i, param := range params {
3949                         sym := param.Sym
3950                         if sym == nil || sym.Name == "_" {
3951                                 sym = typecheck.LookupNum(".anon", i)
3952                         }
3953                         res[i] = types.NewField(param.Pos, sym, param.Type)
3954                         res[i].SetIsDDD(param.IsDDD())
3955                 }
3956                 return res
3957         }
3958
3959         sig := method.Type
3960
3961         var recv *types.Field
3962         if recvType != nil {
3963                 recv = types.NewField(sig.Recv().Pos, typecheck.Lookup(".this"), recvType)
3964         }
3965         params := clone(sig.Params())
3966         results := clone(sig.Results())
3967
3968         return types.NewSignature(recv, params, results)
3969 }
3970
3971 func addTailCall(pos src.XPos, fn *ir.Func, recv ir.Node, method *types.Field) {
3972         sig := fn.Nname.Type()
3973         args := make([]ir.Node, sig.NumParams())
3974         for i, param := range sig.Params() {
3975                 args[i] = param.Nname.(*ir.Name)
3976         }
3977
3978         // TODO(mdempsky): Support creating OTAILCALL, when possible. See reflectdata.methodWrapper.
3979         // Not urgent though, because tail calls are currently incompatible with regabi anyway.
3980
3981         fn.SetWrapper(true) // TODO(mdempsky): Leave unset for tail calls?
3982
3983         dot := typecheck.XDotMethod(pos, recv, method.Sym, true)
3984         call := typecheck.Call(pos, dot, args, method.Type.IsVariadic()).(*ir.CallExpr)
3985
3986         if method.Type.NumResults() == 0 {
3987                 fn.Body.Append(call)
3988                 return
3989         }
3990
3991         ret := ir.NewReturnStmt(pos, nil)
3992         ret.Results = []ir.Node{call}
3993         fn.Body.Append(ret)
3994 }
3995
3996 func setBasePos(pos src.XPos) {
3997         // Set the position for any error messages we might print (e.g. too large types).
3998         base.Pos = pos
3999 }
4000
4001 // dictParamName is the name of the synthetic dictionary parameter
4002 // added to shaped functions.
4003 //
4004 // N.B., this variable name is known to Delve:
4005 // https://github.com/go-delve/delve/blob/cb91509630529e6055be845688fd21eb89ae8714/pkg/proc/eval.go#L28
4006 const dictParamName = typecheck.LocalDictName
4007
4008 // shapeSig returns a copy of fn's signature, except adding a
4009 // dictionary parameter and promoting the receiver parameter (if any)
4010 // to a normal parameter.
4011 //
4012 // The parameter types.Fields are all copied too, so their Nname
4013 // fields can be initialized for use by the shape function.
4014 func shapeSig(fn *ir.Func, dict *readerDict) *types.Type {
4015         sig := fn.Nname.Type()
4016         oldRecv := sig.Recv()
4017
4018         var recv *types.Field
4019         if oldRecv != nil {
4020                 recv = types.NewField(oldRecv.Pos, oldRecv.Sym, oldRecv.Type)
4021         }
4022
4023         params := make([]*types.Field, 1+sig.NumParams())
4024         params[0] = types.NewField(fn.Pos(), fn.Sym().Pkg.Lookup(dictParamName), types.NewPtr(dict.varType()))
4025         for i, param := range sig.Params() {
4026                 d := types.NewField(param.Pos, param.Sym, param.Type)
4027                 d.SetIsDDD(param.IsDDD())
4028                 params[1+i] = d
4029         }
4030
4031         results := make([]*types.Field, sig.NumResults())
4032         for i, result := range sig.Results() {
4033                 results[i] = types.NewField(result.Pos, result.Sym, result.Type)
4034         }
4035
4036         return types.NewSignature(recv, params, results)
4037 }