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