]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/reflectdata/reflect.go
[dev.boringcrypto] all: merge commit 9d0819b27c (CL 314609) into dev.boringcrypto
[gostls13.git] / src / cmd / compile / internal / reflectdata / reflect.go
1 // Copyright 2009 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 reflectdata
6
7 import (
8         "fmt"
9         "internal/buildcfg"
10         "os"
11         "sort"
12         "strings"
13         "sync"
14
15         "cmd/compile/internal/base"
16         "cmd/compile/internal/bitvec"
17         "cmd/compile/internal/escape"
18         "cmd/compile/internal/inline"
19         "cmd/compile/internal/ir"
20         "cmd/compile/internal/objw"
21         "cmd/compile/internal/typebits"
22         "cmd/compile/internal/typecheck"
23         "cmd/compile/internal/types"
24         "cmd/internal/gcprog"
25         "cmd/internal/obj"
26         "cmd/internal/objabi"
27         "cmd/internal/src"
28 )
29
30 type itabEntry struct {
31         t, itype *types.Type
32         lsym     *obj.LSym // symbol of the itab itself
33
34         // symbols of each method in
35         // the itab, sorted by byte offset;
36         // filled in by CompileITabs
37         entries []*obj.LSym
38 }
39
40 type ptabEntry struct {
41         s *types.Sym
42         t *types.Type
43 }
44
45 func CountTabs() (numPTabs, numITabs int) {
46         return len(ptabs), len(itabs)
47 }
48
49 // runtime interface and reflection data structures
50 var (
51         signatmu    sync.Mutex // protects signatset and signatslice
52         signatset   = make(map[*types.Type]struct{})
53         signatslice []*types.Type
54
55         gcsymmu  sync.Mutex // protects gcsymset and gcsymslice
56         gcsymset = make(map[*types.Type]struct{})
57
58         itabs []itabEntry
59         ptabs []*ir.Name
60 )
61
62 type typeSig struct {
63         name  *types.Sym
64         isym  *obj.LSym
65         tsym  *obj.LSym
66         type_ *types.Type
67         mtype *types.Type
68 }
69
70 // Builds a type representing a Bucket structure for
71 // the given map type. This type is not visible to users -
72 // we include only enough information to generate a correct GC
73 // program for it.
74 // Make sure this stays in sync with runtime/map.go.
75 const (
76         BUCKETSIZE  = 8
77         MAXKEYSIZE  = 128
78         MAXELEMSIZE = 128
79 )
80
81 func structfieldSize() int { return 3 * types.PtrSize }       // Sizeof(runtime.structfield{})
82 func imethodSize() int     { return 4 + 4 }                   // Sizeof(runtime.imethod{})
83 func commonSize() int      { return 4*types.PtrSize + 8 + 8 } // Sizeof(runtime._type{})
84
85 func uncommonSize(t *types.Type) int { // Sizeof(runtime.uncommontype{})
86         if t.Sym() == nil && len(methods(t)) == 0 {
87                 return 0
88         }
89         return 4 + 2 + 2 + 4 + 4
90 }
91
92 func makefield(name string, t *types.Type) *types.Field {
93         sym := (*types.Pkg)(nil).Lookup(name)
94         return types.NewField(src.NoXPos, sym, t)
95 }
96
97 // MapBucketType makes the map bucket type given the type of the map.
98 func MapBucketType(t *types.Type) *types.Type {
99         if t.MapType().Bucket != nil {
100                 return t.MapType().Bucket
101         }
102
103         keytype := t.Key()
104         elemtype := t.Elem()
105         types.CalcSize(keytype)
106         types.CalcSize(elemtype)
107         if keytype.Width > MAXKEYSIZE {
108                 keytype = types.NewPtr(keytype)
109         }
110         if elemtype.Width > MAXELEMSIZE {
111                 elemtype = types.NewPtr(elemtype)
112         }
113
114         field := make([]*types.Field, 0, 5)
115
116         // The first field is: uint8 topbits[BUCKETSIZE].
117         arr := types.NewArray(types.Types[types.TUINT8], BUCKETSIZE)
118         field = append(field, makefield("topbits", arr))
119
120         arr = types.NewArray(keytype, BUCKETSIZE)
121         arr.SetNoalg(true)
122         keys := makefield("keys", arr)
123         field = append(field, keys)
124
125         arr = types.NewArray(elemtype, BUCKETSIZE)
126         arr.SetNoalg(true)
127         elems := makefield("elems", arr)
128         field = append(field, elems)
129
130         // If keys and elems have no pointers, the map implementation
131         // can keep a list of overflow pointers on the side so that
132         // buckets can be marked as having no pointers.
133         // Arrange for the bucket to have no pointers by changing
134         // the type of the overflow field to uintptr in this case.
135         // See comment on hmap.overflow in runtime/map.go.
136         otyp := types.Types[types.TUNSAFEPTR]
137         if !elemtype.HasPointers() && !keytype.HasPointers() {
138                 otyp = types.Types[types.TUINTPTR]
139         }
140         overflow := makefield("overflow", otyp)
141         field = append(field, overflow)
142
143         // link up fields
144         bucket := types.NewStruct(types.NoPkg, field[:])
145         bucket.SetNoalg(true)
146         types.CalcSize(bucket)
147
148         // Check invariants that map code depends on.
149         if !types.IsComparable(t.Key()) {
150                 base.Fatalf("unsupported map key type for %v", t)
151         }
152         if BUCKETSIZE < 8 {
153                 base.Fatalf("bucket size too small for proper alignment")
154         }
155         if keytype.Align > BUCKETSIZE {
156                 base.Fatalf("key align too big for %v", t)
157         }
158         if elemtype.Align > BUCKETSIZE {
159                 base.Fatalf("elem align too big for %v", t)
160         }
161         if keytype.Width > MAXKEYSIZE {
162                 base.Fatalf("key size to large for %v", t)
163         }
164         if elemtype.Width > MAXELEMSIZE {
165                 base.Fatalf("elem size to large for %v", t)
166         }
167         if t.Key().Width > MAXKEYSIZE && !keytype.IsPtr() {
168                 base.Fatalf("key indirect incorrect for %v", t)
169         }
170         if t.Elem().Width > MAXELEMSIZE && !elemtype.IsPtr() {
171                 base.Fatalf("elem indirect incorrect for %v", t)
172         }
173         if keytype.Width%int64(keytype.Align) != 0 {
174                 base.Fatalf("key size not a multiple of key align for %v", t)
175         }
176         if elemtype.Width%int64(elemtype.Align) != 0 {
177                 base.Fatalf("elem size not a multiple of elem align for %v", t)
178         }
179         if bucket.Align%keytype.Align != 0 {
180                 base.Fatalf("bucket align not multiple of key align %v", t)
181         }
182         if bucket.Align%elemtype.Align != 0 {
183                 base.Fatalf("bucket align not multiple of elem align %v", t)
184         }
185         if keys.Offset%int64(keytype.Align) != 0 {
186                 base.Fatalf("bad alignment of keys in bmap for %v", t)
187         }
188         if elems.Offset%int64(elemtype.Align) != 0 {
189                 base.Fatalf("bad alignment of elems in bmap for %v", t)
190         }
191
192         // Double-check that overflow field is final memory in struct,
193         // with no padding at end.
194         if overflow.Offset != bucket.Width-int64(types.PtrSize) {
195                 base.Fatalf("bad offset of overflow in bmap for %v", t)
196         }
197
198         t.MapType().Bucket = bucket
199
200         bucket.StructType().Map = t
201         return bucket
202 }
203
204 // MapType builds a type representing a Hmap structure for the given map type.
205 // Make sure this stays in sync with runtime/map.go.
206 func MapType(t *types.Type) *types.Type {
207         if t.MapType().Hmap != nil {
208                 return t.MapType().Hmap
209         }
210
211         bmap := MapBucketType(t)
212
213         // build a struct:
214         // type hmap struct {
215         //    count      int
216         //    flags      uint8
217         //    B          uint8
218         //    noverflow  uint16
219         //    hash0      uint32
220         //    buckets    *bmap
221         //    oldbuckets *bmap
222         //    nevacuate  uintptr
223         //    extra      unsafe.Pointer // *mapextra
224         // }
225         // must match runtime/map.go:hmap.
226         fields := []*types.Field{
227                 makefield("count", types.Types[types.TINT]),
228                 makefield("flags", types.Types[types.TUINT8]),
229                 makefield("B", types.Types[types.TUINT8]),
230                 makefield("noverflow", types.Types[types.TUINT16]),
231                 makefield("hash0", types.Types[types.TUINT32]), // Used in walk.go for OMAKEMAP.
232                 makefield("buckets", types.NewPtr(bmap)),       // Used in walk.go for OMAKEMAP.
233                 makefield("oldbuckets", types.NewPtr(bmap)),
234                 makefield("nevacuate", types.Types[types.TUINTPTR]),
235                 makefield("extra", types.Types[types.TUNSAFEPTR]),
236         }
237
238         hmap := types.NewStruct(types.NoPkg, fields)
239         hmap.SetNoalg(true)
240         types.CalcSize(hmap)
241
242         // The size of hmap should be 48 bytes on 64 bit
243         // and 28 bytes on 32 bit platforms.
244         if size := int64(8 + 5*types.PtrSize); hmap.Width != size {
245                 base.Fatalf("hmap size not correct: got %d, want %d", hmap.Width, size)
246         }
247
248         t.MapType().Hmap = hmap
249         hmap.StructType().Map = t
250         return hmap
251 }
252
253 // MapIterType builds a type representing an Hiter structure for the given map type.
254 // Make sure this stays in sync with runtime/map.go.
255 func MapIterType(t *types.Type) *types.Type {
256         if t.MapType().Hiter != nil {
257                 return t.MapType().Hiter
258         }
259
260         hmap := MapType(t)
261         bmap := MapBucketType(t)
262
263         // build a struct:
264         // type hiter struct {
265         //    key         *Key
266         //    elem        *Elem
267         //    t           unsafe.Pointer // *MapType
268         //    h           *hmap
269         //    buckets     *bmap
270         //    bptr        *bmap
271         //    overflow    unsafe.Pointer // *[]*bmap
272         //    oldoverflow unsafe.Pointer // *[]*bmap
273         //    startBucket uintptr
274         //    offset      uint8
275         //    wrapped     bool
276         //    B           uint8
277         //    i           uint8
278         //    bucket      uintptr
279         //    checkBucket uintptr
280         // }
281         // must match runtime/map.go:hiter.
282         fields := []*types.Field{
283                 makefield("key", types.NewPtr(t.Key())),   // Used in range.go for TMAP.
284                 makefield("elem", types.NewPtr(t.Elem())), // Used in range.go for TMAP.
285                 makefield("t", types.Types[types.TUNSAFEPTR]),
286                 makefield("h", types.NewPtr(hmap)),
287                 makefield("buckets", types.NewPtr(bmap)),
288                 makefield("bptr", types.NewPtr(bmap)),
289                 makefield("overflow", types.Types[types.TUNSAFEPTR]),
290                 makefield("oldoverflow", types.Types[types.TUNSAFEPTR]),
291                 makefield("startBucket", types.Types[types.TUINTPTR]),
292                 makefield("offset", types.Types[types.TUINT8]),
293                 makefield("wrapped", types.Types[types.TBOOL]),
294                 makefield("B", types.Types[types.TUINT8]),
295                 makefield("i", types.Types[types.TUINT8]),
296                 makefield("bucket", types.Types[types.TUINTPTR]),
297                 makefield("checkBucket", types.Types[types.TUINTPTR]),
298         }
299
300         // build iterator struct holding the above fields
301         hiter := types.NewStruct(types.NoPkg, fields)
302         hiter.SetNoalg(true)
303         types.CalcSize(hiter)
304         if hiter.Width != int64(12*types.PtrSize) {
305                 base.Fatalf("hash_iter size not correct %d %d", hiter.Width, 12*types.PtrSize)
306         }
307         t.MapType().Hiter = hiter
308         hiter.StructType().Map = t
309         return hiter
310 }
311
312 // methods returns the methods of the non-interface type t, sorted by name.
313 // Generates stub functions as needed.
314 func methods(t *types.Type) []*typeSig {
315         // method type
316         mt := types.ReceiverBaseType(t)
317
318         if mt == nil {
319                 return nil
320         }
321         typecheck.CalcMethods(mt)
322
323         // type stored in interface word
324         it := t
325
326         if !types.IsDirectIface(it) {
327                 it = types.NewPtr(t)
328         }
329
330         // make list of methods for t,
331         // generating code if necessary.
332         var ms []*typeSig
333         for _, f := range mt.AllMethods().Slice() {
334                 if f.Sym == nil {
335                         base.Fatalf("method with no sym on %v", mt)
336                 }
337                 if !f.IsMethod() {
338                         base.Fatalf("non-method on %v method %v %v", mt, f.Sym, f)
339                 }
340                 if f.Type.Recv() == nil {
341                         base.Fatalf("receiver with no type on %v method %v %v", mt, f.Sym, f)
342                 }
343                 if f.Nointerface() {
344                         continue
345                 }
346
347                 // get receiver type for this particular method.
348                 // if pointer receiver but non-pointer t and
349                 // this is not an embedded pointer inside a struct,
350                 // method does not apply.
351                 if !types.IsMethodApplicable(t, f) {
352                         continue
353                 }
354
355                 sig := &typeSig{
356                         name:  f.Sym,
357                         isym:  methodWrapper(it, f),
358                         tsym:  methodWrapper(t, f),
359                         type_: typecheck.NewMethodType(f.Type, t),
360                         mtype: typecheck.NewMethodType(f.Type, nil),
361                 }
362                 ms = append(ms, sig)
363         }
364
365         return ms
366 }
367
368 // imethods returns the methods of the interface type t, sorted by name.
369 func imethods(t *types.Type) []*typeSig {
370         var methods []*typeSig
371         for _, f := range t.AllMethods().Slice() {
372                 if f.Type.Kind() != types.TFUNC || f.Sym == nil {
373                         continue
374                 }
375                 if f.Sym.IsBlank() {
376                         base.Fatalf("unexpected blank symbol in interface method set")
377                 }
378                 if n := len(methods); n > 0 {
379                         last := methods[n-1]
380                         if !last.name.Less(f.Sym) {
381                                 base.Fatalf("sigcmp vs sortinter %v %v", last.name, f.Sym)
382                         }
383                 }
384
385                 sig := &typeSig{
386                         name:  f.Sym,
387                         mtype: f.Type,
388                         type_: typecheck.NewMethodType(f.Type, nil),
389                 }
390                 methods = append(methods, sig)
391
392                 // NOTE(rsc): Perhaps an oversight that
393                 // IfaceType.Method is not in the reflect data.
394                 // Generate the method body, so that compiled
395                 // code can refer to it.
396                 methodWrapper(t, f)
397         }
398
399         return methods
400 }
401
402 func dimportpath(p *types.Pkg) {
403         if p.Pathsym != nil {
404                 return
405         }
406
407         // If we are compiling the runtime package, there are two runtime packages around
408         // -- localpkg and Pkgs.Runtime. We don't want to produce import path symbols for
409         // both of them, so just produce one for localpkg.
410         if base.Ctxt.Pkgpath == "runtime" && p == ir.Pkgs.Runtime {
411                 return
412         }
413
414         str := p.Path
415         if p == types.LocalPkg {
416                 // Note: myimportpath != "", or else dgopkgpath won't call dimportpath.
417                 str = base.Ctxt.Pkgpath
418         }
419
420         s := base.Ctxt.Lookup("type..importpath." + p.Prefix + ".")
421         ot := dnameData(s, 0, str, "", nil, false)
422         objw.Global(s, int32(ot), obj.DUPOK|obj.RODATA)
423         s.Set(obj.AttrContentAddressable, true)
424         p.Pathsym = s
425 }
426
427 func dgopkgpath(s *obj.LSym, ot int, pkg *types.Pkg) int {
428         if pkg == nil {
429                 return objw.Uintptr(s, ot, 0)
430         }
431
432         if pkg == types.LocalPkg && base.Ctxt.Pkgpath == "" {
433                 // If we don't know the full import path of the package being compiled
434                 // (i.e. -p was not passed on the compiler command line), emit a reference to
435                 // type..importpath.""., which the linker will rewrite using the correct import path.
436                 // Every package that imports this one directly defines the symbol.
437                 // See also https://groups.google.com/forum/#!topic/golang-dev/myb9s53HxGQ.
438                 ns := base.Ctxt.Lookup(`type..importpath."".`)
439                 return objw.SymPtr(s, ot, ns, 0)
440         }
441
442         dimportpath(pkg)
443         return objw.SymPtr(s, ot, pkg.Pathsym, 0)
444 }
445
446 // dgopkgpathOff writes an offset relocation in s at offset ot to the pkg path symbol.
447 func dgopkgpathOff(s *obj.LSym, ot int, pkg *types.Pkg) int {
448         if pkg == nil {
449                 return objw.Uint32(s, ot, 0)
450         }
451         if pkg == types.LocalPkg && base.Ctxt.Pkgpath == "" {
452                 // If we don't know the full import path of the package being compiled
453                 // (i.e. -p was not passed on the compiler command line), emit a reference to
454                 // type..importpath.""., which the linker will rewrite using the correct import path.
455                 // Every package that imports this one directly defines the symbol.
456                 // See also https://groups.google.com/forum/#!topic/golang-dev/myb9s53HxGQ.
457                 ns := base.Ctxt.Lookup(`type..importpath."".`)
458                 return objw.SymPtrOff(s, ot, ns)
459         }
460
461         dimportpath(pkg)
462         return objw.SymPtrOff(s, ot, pkg.Pathsym)
463 }
464
465 // dnameField dumps a reflect.name for a struct field.
466 func dnameField(lsym *obj.LSym, ot int, spkg *types.Pkg, ft *types.Field) int {
467         if !types.IsExported(ft.Sym.Name) && ft.Sym.Pkg != spkg {
468                 base.Fatalf("package mismatch for %v", ft.Sym)
469         }
470         nsym := dname(ft.Sym.Name, ft.Note, nil, types.IsExported(ft.Sym.Name))
471         return objw.SymPtr(lsym, ot, nsym, 0)
472 }
473
474 // dnameData writes the contents of a reflect.name into s at offset ot.
475 func dnameData(s *obj.LSym, ot int, name, tag string, pkg *types.Pkg, exported bool) int {
476         if len(name) > 1<<16-1 {
477                 base.Fatalf("name too long: %s", name)
478         }
479         if len(tag) > 1<<16-1 {
480                 base.Fatalf("tag too long: %s", tag)
481         }
482
483         // Encode name and tag. See reflect/type.go for details.
484         var bits byte
485         l := 1 + 2 + len(name)
486         if exported {
487                 bits |= 1 << 0
488         }
489         if len(tag) > 0 {
490                 l += 2 + len(tag)
491                 bits |= 1 << 1
492         }
493         if pkg != nil {
494                 bits |= 1 << 2
495         }
496         b := make([]byte, l)
497         b[0] = bits
498         b[1] = uint8(len(name) >> 8)
499         b[2] = uint8(len(name))
500         copy(b[3:], name)
501         if len(tag) > 0 {
502                 tb := b[3+len(name):]
503                 tb[0] = uint8(len(tag) >> 8)
504                 tb[1] = uint8(len(tag))
505                 copy(tb[2:], tag)
506         }
507
508         ot = int(s.WriteBytes(base.Ctxt, int64(ot), b))
509
510         if pkg != nil {
511                 ot = dgopkgpathOff(s, ot, pkg)
512         }
513
514         return ot
515 }
516
517 var dnameCount int
518
519 // dname creates a reflect.name for a struct field or method.
520 func dname(name, tag string, pkg *types.Pkg, exported bool) *obj.LSym {
521         // Write out data as "type.." to signal two things to the
522         // linker, first that when dynamically linking, the symbol
523         // should be moved to a relro section, and second that the
524         // contents should not be decoded as a type.
525         sname := "type..namedata."
526         if pkg == nil {
527                 // In the common case, share data with other packages.
528                 if name == "" {
529                         if exported {
530                                 sname += "-noname-exported." + tag
531                         } else {
532                                 sname += "-noname-unexported." + tag
533                         }
534                 } else {
535                         if exported {
536                                 sname += name + "." + tag
537                         } else {
538                                 sname += name + "-" + tag
539                         }
540                 }
541         } else {
542                 sname = fmt.Sprintf(`%s"".%d`, sname, dnameCount)
543                 dnameCount++
544         }
545         s := base.Ctxt.Lookup(sname)
546         if len(s.P) > 0 {
547                 return s
548         }
549         ot := dnameData(s, 0, name, tag, pkg, exported)
550         objw.Global(s, int32(ot), obj.DUPOK|obj.RODATA)
551         s.Set(obj.AttrContentAddressable, true)
552         return s
553 }
554
555 // dextratype dumps the fields of a runtime.uncommontype.
556 // dataAdd is the offset in bytes after the header where the
557 // backing array of the []method field is written (by dextratypeData).
558 func dextratype(lsym *obj.LSym, ot int, t *types.Type, dataAdd int) int {
559         m := methods(t)
560         if t.Sym() == nil && len(m) == 0 {
561                 return ot
562         }
563         noff := int(types.Rnd(int64(ot), int64(types.PtrSize)))
564         if noff != ot {
565                 base.Fatalf("unexpected alignment in dextratype for %v", t)
566         }
567
568         for _, a := range m {
569                 writeType(a.type_)
570         }
571
572         ot = dgopkgpathOff(lsym, ot, typePkg(t))
573
574         dataAdd += uncommonSize(t)
575         mcount := len(m)
576         if mcount != int(uint16(mcount)) {
577                 base.Fatalf("too many methods on %v: %d", t, mcount)
578         }
579         xcount := sort.Search(mcount, func(i int) bool { return !types.IsExported(m[i].name.Name) })
580         if dataAdd != int(uint32(dataAdd)) {
581                 base.Fatalf("methods are too far away on %v: %d", t, dataAdd)
582         }
583
584         ot = objw.Uint16(lsym, ot, uint16(mcount))
585         ot = objw.Uint16(lsym, ot, uint16(xcount))
586         ot = objw.Uint32(lsym, ot, uint32(dataAdd))
587         ot = objw.Uint32(lsym, ot, 0)
588         return ot
589 }
590
591 func typePkg(t *types.Type) *types.Pkg {
592         tsym := t.Sym()
593         if tsym == nil {
594                 switch t.Kind() {
595                 case types.TARRAY, types.TSLICE, types.TPTR, types.TCHAN:
596                         if t.Elem() != nil {
597                                 tsym = t.Elem().Sym()
598                         }
599                 }
600         }
601         if tsym != nil && tsym.Pkg != types.BuiltinPkg {
602                 return tsym.Pkg
603         }
604         return nil
605 }
606
607 // dextratypeData dumps the backing array for the []method field of
608 // runtime.uncommontype.
609 func dextratypeData(lsym *obj.LSym, ot int, t *types.Type) int {
610         for _, a := range methods(t) {
611                 // ../../../../runtime/type.go:/method
612                 exported := types.IsExported(a.name.Name)
613                 var pkg *types.Pkg
614                 if !exported && a.name.Pkg != typePkg(t) {
615                         pkg = a.name.Pkg
616                 }
617                 nsym := dname(a.name.Name, "", pkg, exported)
618
619                 ot = objw.SymPtrOff(lsym, ot, nsym)
620                 ot = dmethodptrOff(lsym, ot, writeType(a.mtype))
621                 ot = dmethodptrOff(lsym, ot, a.isym)
622                 ot = dmethodptrOff(lsym, ot, a.tsym)
623         }
624         return ot
625 }
626
627 func dmethodptrOff(s *obj.LSym, ot int, x *obj.LSym) int {
628         objw.Uint32(s, ot, 0)
629         r := obj.Addrel(s)
630         r.Off = int32(ot)
631         r.Siz = 4
632         r.Sym = x
633         r.Type = objabi.R_METHODOFF
634         return ot + 4
635 }
636
637 var kinds = []int{
638         types.TINT:        objabi.KindInt,
639         types.TUINT:       objabi.KindUint,
640         types.TINT8:       objabi.KindInt8,
641         types.TUINT8:      objabi.KindUint8,
642         types.TINT16:      objabi.KindInt16,
643         types.TUINT16:     objabi.KindUint16,
644         types.TINT32:      objabi.KindInt32,
645         types.TUINT32:     objabi.KindUint32,
646         types.TINT64:      objabi.KindInt64,
647         types.TUINT64:     objabi.KindUint64,
648         types.TUINTPTR:    objabi.KindUintptr,
649         types.TFLOAT32:    objabi.KindFloat32,
650         types.TFLOAT64:    objabi.KindFloat64,
651         types.TBOOL:       objabi.KindBool,
652         types.TSTRING:     objabi.KindString,
653         types.TPTR:        objabi.KindPtr,
654         types.TSTRUCT:     objabi.KindStruct,
655         types.TINTER:      objabi.KindInterface,
656         types.TCHAN:       objabi.KindChan,
657         types.TMAP:        objabi.KindMap,
658         types.TARRAY:      objabi.KindArray,
659         types.TSLICE:      objabi.KindSlice,
660         types.TFUNC:       objabi.KindFunc,
661         types.TCOMPLEX64:  objabi.KindComplex64,
662         types.TCOMPLEX128: objabi.KindComplex128,
663         types.TUNSAFEPTR:  objabi.KindUnsafePointer,
664 }
665
666 // tflag is documented in reflect/type.go.
667 //
668 // tflag values must be kept in sync with copies in:
669 //      cmd/compile/internal/gc/reflect.go
670 //      cmd/link/internal/ld/decodesym.go
671 //      reflect/type.go
672 //      runtime/type.go
673 const (
674         tflagUncommon      = 1 << 0
675         tflagExtraStar     = 1 << 1
676         tflagNamed         = 1 << 2
677         tflagRegularMemory = 1 << 3
678 )
679
680 var (
681         memhashvarlen  *obj.LSym
682         memequalvarlen *obj.LSym
683 )
684
685 // dcommontype dumps the contents of a reflect.rtype (runtime._type).
686 func dcommontype(lsym *obj.LSym, t *types.Type) int {
687         types.CalcSize(t)
688         eqfunc := geneq(t)
689
690         sptrWeak := true
691         var sptr *obj.LSym
692         if !t.IsPtr() || t.IsPtrElem() {
693                 tptr := types.NewPtr(t)
694                 if t.Sym() != nil || methods(tptr) != nil {
695                         sptrWeak = false
696                 }
697                 sptr = writeType(tptr)
698         }
699
700         gcsym, useGCProg, ptrdata := dgcsym(t, true)
701         delete(gcsymset, t)
702
703         // ../../../../reflect/type.go:/^type.rtype
704         // actual type structure
705         //      type rtype struct {
706         //              size          uintptr
707         //              ptrdata       uintptr
708         //              hash          uint32
709         //              tflag         tflag
710         //              align         uint8
711         //              fieldAlign    uint8
712         //              kind          uint8
713         //              equal         func(unsafe.Pointer, unsafe.Pointer) bool
714         //              gcdata        *byte
715         //              str           nameOff
716         //              ptrToThis     typeOff
717         //      }
718         ot := 0
719         ot = objw.Uintptr(lsym, ot, uint64(t.Width))
720         ot = objw.Uintptr(lsym, ot, uint64(ptrdata))
721         ot = objw.Uint32(lsym, ot, types.TypeHash(t))
722
723         var tflag uint8
724         if uncommonSize(t) != 0 {
725                 tflag |= tflagUncommon
726         }
727         if t.Sym() != nil && t.Sym().Name != "" {
728                 tflag |= tflagNamed
729         }
730         if isRegularMemory(t) {
731                 tflag |= tflagRegularMemory
732         }
733
734         exported := false
735         p := t.LongString()
736         // If we're writing out type T,
737         // we are very likely to write out type *T as well.
738         // Use the string "*T"[1:] for "T", so that the two
739         // share storage. This is a cheap way to reduce the
740         // amount of space taken up by reflect strings.
741         if !strings.HasPrefix(p, "*") {
742                 p = "*" + p
743                 tflag |= tflagExtraStar
744                 if t.Sym() != nil {
745                         exported = types.IsExported(t.Sym().Name)
746                 }
747         } else {
748                 if t.Elem() != nil && t.Elem().Sym() != nil {
749                         exported = types.IsExported(t.Elem().Sym().Name)
750                 }
751         }
752
753         ot = objw.Uint8(lsym, ot, tflag)
754
755         // runtime (and common sense) expects alignment to be a power of two.
756         i := int(t.Align)
757
758         if i == 0 {
759                 i = 1
760         }
761         if i&(i-1) != 0 {
762                 base.Fatalf("invalid alignment %d for %v", t.Align, t)
763         }
764         ot = objw.Uint8(lsym, ot, t.Align) // align
765         ot = objw.Uint8(lsym, ot, t.Align) // fieldAlign
766
767         i = kinds[t.Kind()]
768         if types.IsDirectIface(t) {
769                 i |= objabi.KindDirectIface
770         }
771         if useGCProg {
772                 i |= objabi.KindGCProg
773         }
774         ot = objw.Uint8(lsym, ot, uint8(i)) // kind
775         if eqfunc != nil {
776                 ot = objw.SymPtr(lsym, ot, eqfunc, 0) // equality function
777         } else {
778                 ot = objw.Uintptr(lsym, ot, 0) // type we can't do == with
779         }
780         ot = objw.SymPtr(lsym, ot, gcsym, 0) // gcdata
781
782         nsym := dname(p, "", nil, exported)
783         ot = objw.SymPtrOff(lsym, ot, nsym) // str
784         // ptrToThis
785         if sptr == nil {
786                 ot = objw.Uint32(lsym, ot, 0)
787         } else if sptrWeak {
788                 ot = objw.SymPtrWeakOff(lsym, ot, sptr)
789         } else {
790                 ot = objw.SymPtrOff(lsym, ot, sptr)
791         }
792
793         return ot
794 }
795
796 // TrackSym returns the symbol for tracking use of field/method f, assumed
797 // to be a member of struct/interface type t.
798 func TrackSym(t *types.Type, f *types.Field) *obj.LSym {
799         return base.PkgLinksym("go.track", t.ShortString()+"."+f.Sym.Name, obj.ABI0)
800 }
801
802 func TypeSymPrefix(prefix string, t *types.Type) *types.Sym {
803         p := prefix + "." + t.ShortString()
804         s := types.TypeSymLookup(p)
805
806         // This function is for looking up type-related generated functions
807         // (e.g. eq and hash). Make sure they are indeed generated.
808         signatmu.Lock()
809         NeedRuntimeType(t)
810         signatmu.Unlock()
811
812         //print("algsym: %s -> %+S\n", p, s);
813
814         return s
815 }
816
817 func TypeSym(t *types.Type) *types.Sym {
818         if t == nil || (t.IsPtr() && t.Elem() == nil) || t.IsUntyped() {
819                 base.Fatalf("TypeSym %v", t)
820         }
821         if t.Kind() == types.TFUNC && t.Recv() != nil {
822                 base.Fatalf("misuse of method type: %v", t)
823         }
824         s := types.TypeSym(t)
825         signatmu.Lock()
826         NeedRuntimeType(t)
827         signatmu.Unlock()
828         return s
829 }
830
831 func TypeLinksymPrefix(prefix string, t *types.Type) *obj.LSym {
832         return TypeSymPrefix(prefix, t).Linksym()
833 }
834
835 func TypeLinksymLookup(name string) *obj.LSym {
836         return types.TypeSymLookup(name).Linksym()
837 }
838
839 func TypeLinksym(t *types.Type) *obj.LSym {
840         return TypeSym(t).Linksym()
841 }
842
843 func TypePtr(t *types.Type) *ir.AddrExpr {
844         n := ir.NewLinksymExpr(base.Pos, TypeLinksym(t), types.Types[types.TUINT8])
845         return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
846 }
847
848 func ITabAddr(t, itype *types.Type) *ir.AddrExpr {
849         if t == nil || (t.IsPtr() && t.Elem() == nil) || t.IsUntyped() || !itype.IsInterface() || itype.IsEmptyInterface() {
850                 base.Fatalf("ITabAddr(%v, %v)", t, itype)
851         }
852         s, existed := ir.Pkgs.Itab.LookupOK(t.ShortString() + "," + itype.ShortString())
853         if !existed {
854                 itabs = append(itabs, itabEntry{t: t, itype: itype, lsym: s.Linksym()})
855         }
856
857         lsym := s.Linksym()
858         n := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
859         return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
860 }
861
862 // needkeyupdate reports whether map updates with t as a key
863 // need the key to be updated.
864 func needkeyupdate(t *types.Type) bool {
865         switch t.Kind() {
866         case types.TBOOL, types.TINT, types.TUINT, types.TINT8, types.TUINT8, types.TINT16, types.TUINT16, types.TINT32, types.TUINT32,
867                 types.TINT64, types.TUINT64, types.TUINTPTR, types.TPTR, types.TUNSAFEPTR, types.TCHAN:
868                 return false
869
870         case types.TFLOAT32, types.TFLOAT64, types.TCOMPLEX64, types.TCOMPLEX128, // floats and complex can be +0/-0
871                 types.TINTER,
872                 types.TSTRING: // strings might have smaller backing stores
873                 return true
874
875         case types.TARRAY:
876                 return needkeyupdate(t.Elem())
877
878         case types.TSTRUCT:
879                 for _, t1 := range t.Fields().Slice() {
880                         if needkeyupdate(t1.Type) {
881                                 return true
882                         }
883                 }
884                 return false
885
886         default:
887                 base.Fatalf("bad type for map key: %v", t)
888                 return true
889         }
890 }
891
892 // hashMightPanic reports whether the hash of a map key of type t might panic.
893 func hashMightPanic(t *types.Type) bool {
894         switch t.Kind() {
895         case types.TINTER:
896                 return true
897
898         case types.TARRAY:
899                 return hashMightPanic(t.Elem())
900
901         case types.TSTRUCT:
902                 for _, t1 := range t.Fields().Slice() {
903                         if hashMightPanic(t1.Type) {
904                                 return true
905                         }
906                 }
907                 return false
908
909         default:
910                 return false
911         }
912 }
913
914 // formalType replaces byte and rune aliases with real types.
915 // They've been separate internally to make error messages
916 // better, but we have to merge them in the reflect tables.
917 func formalType(t *types.Type) *types.Type {
918         if t == types.ByteType || t == types.RuneType {
919                 return types.Types[t.Kind()]
920         }
921         return t
922 }
923
924 func writeType(t *types.Type) *obj.LSym {
925         t = formalType(t)
926         if t.IsUntyped() {
927                 base.Fatalf("writeType %v", t)
928         }
929
930         s := types.TypeSym(t)
931         lsym := s.Linksym()
932         if s.Siggen() {
933                 return lsym
934         }
935         s.SetSiggen(true)
936
937         // special case (look for runtime below):
938         // when compiling package runtime,
939         // emit the type structures for int, float, etc.
940         tbase := t
941
942         if t.IsPtr() && t.Sym() == nil && t.Elem().Sym() != nil {
943                 tbase = t.Elem()
944         }
945         dupok := 0
946         if tbase.Sym() == nil {
947                 dupok = obj.DUPOK
948         }
949
950         if base.Ctxt.Pkgpath != "runtime" || (tbase != types.Types[tbase.Kind()] && tbase != types.ByteType && tbase != types.RuneType && tbase != types.ErrorType) { // int, float, etc
951                 // named types from other files are defined only by those files
952                 if tbase.Sym() != nil && tbase.Sym().Pkg != types.LocalPkg {
953                         if i := typecheck.BaseTypeIndex(t); i >= 0 {
954                                 lsym.Pkg = tbase.Sym().Pkg.Prefix
955                                 lsym.SymIdx = int32(i)
956                                 lsym.Set(obj.AttrIndexed, true)
957                         }
958                         return lsym
959                 }
960                 // TODO(mdempsky): Investigate whether this can happen.
961                 if tbase.Kind() == types.TFORW {
962                         return lsym
963                 }
964         }
965
966         ot := 0
967         switch t.Kind() {
968         default:
969                 ot = dcommontype(lsym, t)
970                 ot = dextratype(lsym, ot, t, 0)
971
972         case types.TARRAY:
973                 // ../../../../runtime/type.go:/arrayType
974                 s1 := writeType(t.Elem())
975                 t2 := types.NewSlice(t.Elem())
976                 s2 := writeType(t2)
977                 ot = dcommontype(lsym, t)
978                 ot = objw.SymPtr(lsym, ot, s1, 0)
979                 ot = objw.SymPtr(lsym, ot, s2, 0)
980                 ot = objw.Uintptr(lsym, ot, uint64(t.NumElem()))
981                 ot = dextratype(lsym, ot, t, 0)
982
983         case types.TSLICE:
984                 // ../../../../runtime/type.go:/sliceType
985                 s1 := writeType(t.Elem())
986                 ot = dcommontype(lsym, t)
987                 ot = objw.SymPtr(lsym, ot, s1, 0)
988                 ot = dextratype(lsym, ot, t, 0)
989
990         case types.TCHAN:
991                 // ../../../../runtime/type.go:/chanType
992                 s1 := writeType(t.Elem())
993                 ot = dcommontype(lsym, t)
994                 ot = objw.SymPtr(lsym, ot, s1, 0)
995                 ot = objw.Uintptr(lsym, ot, uint64(t.ChanDir()))
996                 ot = dextratype(lsym, ot, t, 0)
997
998         case types.TFUNC:
999                 for _, t1 := range t.Recvs().Fields().Slice() {
1000                         writeType(t1.Type)
1001                 }
1002                 isddd := false
1003                 for _, t1 := range t.Params().Fields().Slice() {
1004                         isddd = t1.IsDDD()
1005                         writeType(t1.Type)
1006                 }
1007                 for _, t1 := range t.Results().Fields().Slice() {
1008                         writeType(t1.Type)
1009                 }
1010
1011                 ot = dcommontype(lsym, t)
1012                 inCount := t.NumRecvs() + t.NumParams()
1013                 outCount := t.NumResults()
1014                 if isddd {
1015                         outCount |= 1 << 15
1016                 }
1017                 ot = objw.Uint16(lsym, ot, uint16(inCount))
1018                 ot = objw.Uint16(lsym, ot, uint16(outCount))
1019                 if types.PtrSize == 8 {
1020                         ot += 4 // align for *rtype
1021                 }
1022
1023                 dataAdd := (inCount + t.NumResults()) * types.PtrSize
1024                 ot = dextratype(lsym, ot, t, dataAdd)
1025
1026                 // Array of rtype pointers follows funcType.
1027                 for _, t1 := range t.Recvs().Fields().Slice() {
1028                         ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1029                 }
1030                 for _, t1 := range t.Params().Fields().Slice() {
1031                         ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1032                 }
1033                 for _, t1 := range t.Results().Fields().Slice() {
1034                         ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1035                 }
1036
1037         case types.TINTER:
1038                 m := imethods(t)
1039                 n := len(m)
1040                 for _, a := range m {
1041                         writeType(a.type_)
1042                 }
1043
1044                 // ../../../../runtime/type.go:/interfaceType
1045                 ot = dcommontype(lsym, t)
1046
1047                 var tpkg *types.Pkg
1048                 if t.Sym() != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
1049                         tpkg = t.Sym().Pkg
1050                 }
1051                 ot = dgopkgpath(lsym, ot, tpkg)
1052
1053                 ot = objw.SymPtr(lsym, ot, lsym, ot+3*types.PtrSize+uncommonSize(t))
1054                 ot = objw.Uintptr(lsym, ot, uint64(n))
1055                 ot = objw.Uintptr(lsym, ot, uint64(n))
1056                 dataAdd := imethodSize() * n
1057                 ot = dextratype(lsym, ot, t, dataAdd)
1058
1059                 for _, a := range m {
1060                         // ../../../../runtime/type.go:/imethod
1061                         exported := types.IsExported(a.name.Name)
1062                         var pkg *types.Pkg
1063                         if !exported && a.name.Pkg != tpkg {
1064                                 pkg = a.name.Pkg
1065                         }
1066                         nsym := dname(a.name.Name, "", pkg, exported)
1067
1068                         ot = objw.SymPtrOff(lsym, ot, nsym)
1069                         ot = objw.SymPtrOff(lsym, ot, writeType(a.type_))
1070                 }
1071
1072         // ../../../../runtime/type.go:/mapType
1073         case types.TMAP:
1074                 s1 := writeType(t.Key())
1075                 s2 := writeType(t.Elem())
1076                 s3 := writeType(MapBucketType(t))
1077                 hasher := genhash(t.Key())
1078
1079                 ot = dcommontype(lsym, t)
1080                 ot = objw.SymPtr(lsym, ot, s1, 0)
1081                 ot = objw.SymPtr(lsym, ot, s2, 0)
1082                 ot = objw.SymPtr(lsym, ot, s3, 0)
1083                 ot = objw.SymPtr(lsym, ot, hasher, 0)
1084                 var flags uint32
1085                 // Note: flags must match maptype accessors in ../../../../runtime/type.go
1086                 // and maptype builder in ../../../../reflect/type.go:MapOf.
1087                 if t.Key().Width > MAXKEYSIZE {
1088                         ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1089                         flags |= 1 // indirect key
1090                 } else {
1091                         ot = objw.Uint8(lsym, ot, uint8(t.Key().Width))
1092                 }
1093
1094                 if t.Elem().Width > MAXELEMSIZE {
1095                         ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1096                         flags |= 2 // indirect value
1097                 } else {
1098                         ot = objw.Uint8(lsym, ot, uint8(t.Elem().Width))
1099                 }
1100                 ot = objw.Uint16(lsym, ot, uint16(MapBucketType(t).Width))
1101                 if types.IsReflexive(t.Key()) {
1102                         flags |= 4 // reflexive key
1103                 }
1104                 if needkeyupdate(t.Key()) {
1105                         flags |= 8 // need key update
1106                 }
1107                 if hashMightPanic(t.Key()) {
1108                         flags |= 16 // hash might panic
1109                 }
1110                 ot = objw.Uint32(lsym, ot, flags)
1111                 ot = dextratype(lsym, ot, t, 0)
1112
1113         case types.TPTR:
1114                 if t.Elem().Kind() == types.TANY {
1115                         // ../../../../runtime/type.go:/UnsafePointerType
1116                         ot = dcommontype(lsym, t)
1117                         ot = dextratype(lsym, ot, t, 0)
1118
1119                         break
1120                 }
1121
1122                 // ../../../../runtime/type.go:/ptrType
1123                 s1 := writeType(t.Elem())
1124
1125                 ot = dcommontype(lsym, t)
1126                 ot = objw.SymPtr(lsym, ot, s1, 0)
1127                 ot = dextratype(lsym, ot, t, 0)
1128
1129         // ../../../../runtime/type.go:/structType
1130         // for security, only the exported fields.
1131         case types.TSTRUCT:
1132                 fields := t.Fields().Slice()
1133
1134                 // omitFieldForAwfulBoringCryptoKludge reports whether
1135                 // the field t should be omitted from the reflect data.
1136                 // In the crypto/... packages we omit an unexported field
1137                 // named "boring", to keep from breaking client code that
1138                 // expects rsa.PublicKey etc to have only public fields.
1139                 // As the name suggests, this is an awful kludge, but it is
1140                 // limited to the dev.boringcrypto branch and avoids
1141                 // much more invasive effects elsewhere.
1142                 omitFieldForAwfulBoringCryptoKludge := func(t *types.Field) bool {
1143                         if t.Sym == nil || t.Sym.Name != "boring" || t.Sym.Pkg == nil {
1144                                 return false
1145                         }
1146                         path := t.Sym.Pkg.Path
1147                         if t.Sym.Pkg == types.LocalPkg {
1148                                 path = base.Ctxt.Pkgpath
1149                         }
1150                         return strings.HasPrefix(path, "crypto/")
1151                 }
1152                 newFields := fields[:0:0]
1153                 for _, t1 := range fields {
1154                         if !omitFieldForAwfulBoringCryptoKludge(t1) {
1155                                 newFields = append(newFields, t1)
1156                         }
1157                 }
1158                 fields = newFields
1159
1160                 for _, t1 := range fields {
1161                         writeType(t1.Type)
1162                 }
1163
1164                 // All non-exported struct field names within a struct
1165                 // type must originate from a single package. By
1166                 // identifying and recording that package within the
1167                 // struct type descriptor, we can omit that
1168                 // information from the field descriptors.
1169                 var spkg *types.Pkg
1170                 for _, f := range fields {
1171                         if !types.IsExported(f.Sym.Name) {
1172                                 spkg = f.Sym.Pkg
1173                                 break
1174                         }
1175                 }
1176
1177                 ot = dcommontype(lsym, t)
1178                 ot = dgopkgpath(lsym, ot, spkg)
1179                 ot = objw.SymPtr(lsym, ot, lsym, ot+3*types.PtrSize+uncommonSize(t))
1180                 ot = objw.Uintptr(lsym, ot, uint64(len(fields)))
1181                 ot = objw.Uintptr(lsym, ot, uint64(len(fields)))
1182
1183                 dataAdd := len(fields) * structfieldSize()
1184                 ot = dextratype(lsym, ot, t, dataAdd)
1185
1186                 for _, f := range fields {
1187                         // ../../../../runtime/type.go:/structField
1188                         ot = dnameField(lsym, ot, spkg, f)
1189                         ot = objw.SymPtr(lsym, ot, writeType(f.Type), 0)
1190                         offsetAnon := uint64(f.Offset) << 1
1191                         if offsetAnon>>1 != uint64(f.Offset) {
1192                                 base.Fatalf("%v: bad field offset for %s", t, f.Sym.Name)
1193                         }
1194                         if f.Embedded != 0 {
1195                                 offsetAnon |= 1
1196                         }
1197                         ot = objw.Uintptr(lsym, ot, offsetAnon)
1198                 }
1199         }
1200
1201         ot = dextratypeData(lsym, ot, t)
1202         objw.Global(lsym, int32(ot), int16(dupok|obj.RODATA))
1203
1204         // The linker will leave a table of all the typelinks for
1205         // types in the binary, so the runtime can find them.
1206         //
1207         // When buildmode=shared, all types are in typelinks so the
1208         // runtime can deduplicate type pointers.
1209         keep := base.Ctxt.Flag_dynlink
1210         if !keep && t.Sym() == nil {
1211                 // For an unnamed type, we only need the link if the type can
1212                 // be created at run time by reflect.PtrTo and similar
1213                 // functions. If the type exists in the program, those
1214                 // functions must return the existing type structure rather
1215                 // than creating a new one.
1216                 switch t.Kind() {
1217                 case types.TPTR, types.TARRAY, types.TCHAN, types.TFUNC, types.TMAP, types.TSLICE, types.TSTRUCT:
1218                         keep = true
1219                 }
1220         }
1221         // Do not put Noalg types in typelinks.  See issue #22605.
1222         if types.TypeHasNoAlg(t) {
1223                 keep = false
1224         }
1225         lsym.Set(obj.AttrMakeTypelink, keep)
1226
1227         return lsym
1228 }
1229
1230 // InterfaceMethodOffset returns the offset of the i-th method in the interface
1231 // type descriptor, ityp.
1232 func InterfaceMethodOffset(ityp *types.Type, i int64) int64 {
1233         // interface type descriptor layout is struct {
1234         //   _type        // commonSize
1235         //   pkgpath      // 1 word
1236         //   []imethod    // 3 words (pointing to [...]imethod below)
1237         //   uncommontype // uncommonSize
1238         //   [...]imethod
1239         // }
1240         // The size of imethod is 8.
1241         return int64(commonSize()+4*types.PtrSize+uncommonSize(ityp)) + i*8
1242 }
1243
1244 // for each itabEntry, gather the methods on
1245 // the concrete type that implement the interface
1246 func CompileITabs() {
1247         for i := range itabs {
1248                 tab := &itabs[i]
1249                 methods := genfun(tab.t, tab.itype)
1250                 if len(methods) == 0 {
1251                         continue
1252                 }
1253                 tab.entries = methods
1254         }
1255 }
1256
1257 // for the given concrete type and interface
1258 // type, return the (sorted) set of methods
1259 // on the concrete type that implement the interface
1260 func genfun(t, it *types.Type) []*obj.LSym {
1261         if t == nil || it == nil {
1262                 return nil
1263         }
1264         sigs := imethods(it)
1265         methods := methods(t)
1266         out := make([]*obj.LSym, 0, len(sigs))
1267         // TODO(mdempsky): Short circuit before calling methods(t)?
1268         // See discussion on CL 105039.
1269         if len(sigs) == 0 {
1270                 return nil
1271         }
1272
1273         // both sigs and methods are sorted by name,
1274         // so we can find the intersect in a single pass
1275         for _, m := range methods {
1276                 if m.name == sigs[0].name {
1277                         out = append(out, m.isym)
1278                         sigs = sigs[1:]
1279                         if len(sigs) == 0 {
1280                                 break
1281                         }
1282                 }
1283         }
1284
1285         if len(sigs) != 0 {
1286                 base.Fatalf("incomplete itab")
1287         }
1288
1289         return out
1290 }
1291
1292 // ITabSym uses the information gathered in
1293 // CompileITabs to de-virtualize interface methods.
1294 // Since this is called by the SSA backend, it shouldn't
1295 // generate additional Nodes, Syms, etc.
1296 func ITabSym(it *obj.LSym, offset int64) *obj.LSym {
1297         var syms []*obj.LSym
1298         if it == nil {
1299                 return nil
1300         }
1301
1302         for i := range itabs {
1303                 e := &itabs[i]
1304                 if e.lsym == it {
1305                         syms = e.entries
1306                         break
1307                 }
1308         }
1309         if syms == nil {
1310                 return nil
1311         }
1312
1313         // keep this arithmetic in sync with *itab layout
1314         methodnum := int((offset - 2*int64(types.PtrSize) - 8) / int64(types.PtrSize))
1315         if methodnum >= len(syms) {
1316                 return nil
1317         }
1318         return syms[methodnum]
1319 }
1320
1321 // NeedRuntimeType ensures that a runtime type descriptor is emitted for t.
1322 func NeedRuntimeType(t *types.Type) {
1323         if t.HasTParam() {
1324                 // Generic types don't have a runtime type descriptor (but will
1325                 // have a dictionary)
1326                 return
1327         }
1328         if _, ok := signatset[t]; !ok {
1329                 signatset[t] = struct{}{}
1330                 signatslice = append(signatslice, t)
1331         }
1332 }
1333
1334 func WriteRuntimeTypes() {
1335         // Process signatset. Use a loop, as writeType adds
1336         // entries to signatset while it is being processed.
1337         signats := make([]typeAndStr, len(signatslice))
1338         for len(signatslice) > 0 {
1339                 signats = signats[:0]
1340                 // Transfer entries to a slice and sort, for reproducible builds.
1341                 for _, t := range signatslice {
1342                         signats = append(signats, typeAndStr{t: t, short: types.TypeSymName(t), regular: t.String()})
1343                         delete(signatset, t)
1344                 }
1345                 signatslice = signatslice[:0]
1346                 sort.Sort(typesByString(signats))
1347                 for _, ts := range signats {
1348                         t := ts.t
1349                         writeType(t)
1350                         if t.Sym() != nil {
1351                                 writeType(types.NewPtr(t))
1352                         }
1353                 }
1354         }
1355
1356         // Emit GC data symbols.
1357         gcsyms := make([]typeAndStr, 0, len(gcsymset))
1358         for t := range gcsymset {
1359                 gcsyms = append(gcsyms, typeAndStr{t: t, short: types.TypeSymName(t), regular: t.String()})
1360         }
1361         sort.Sort(typesByString(gcsyms))
1362         for _, ts := range gcsyms {
1363                 dgcsym(ts.t, true)
1364         }
1365 }
1366
1367 func WriteTabs() {
1368         // process itabs
1369         for _, i := range itabs {
1370                 // dump empty itab symbol into i.sym
1371                 // type itab struct {
1372                 //   inter  *interfacetype
1373                 //   _type  *_type
1374                 //   hash   uint32
1375                 //   _      [4]byte
1376                 //   fun    [1]uintptr // variable sized
1377                 // }
1378                 o := objw.SymPtr(i.lsym, 0, writeType(i.itype), 0)
1379                 o = objw.SymPtr(i.lsym, o, writeType(i.t), 0)
1380                 o = objw.Uint32(i.lsym, o, types.TypeHash(i.t)) // copy of type hash
1381                 o += 4                                          // skip unused field
1382                 for _, fn := range genfun(i.t, i.itype) {
1383                         o = objw.SymPtrWeak(i.lsym, o, fn, 0) // method pointer for each method
1384                 }
1385                 // Nothing writes static itabs, so they are read only.
1386                 objw.Global(i.lsym, int32(o), int16(obj.DUPOK|obj.RODATA))
1387                 i.lsym.Set(obj.AttrContentAddressable, true)
1388         }
1389
1390         // process ptabs
1391         if types.LocalPkg.Name == "main" && len(ptabs) > 0 {
1392                 ot := 0
1393                 s := base.Ctxt.Lookup("go.plugin.tabs")
1394                 for _, p := range ptabs {
1395                         // Dump ptab symbol into go.pluginsym package.
1396                         //
1397                         // type ptab struct {
1398                         //      name nameOff
1399                         //      typ  typeOff // pointer to symbol
1400                         // }
1401                         nsym := dname(p.Sym().Name, "", nil, true)
1402                         t := p.Type()
1403                         if p.Class != ir.PFUNC {
1404                                 t = types.NewPtr(t)
1405                         }
1406                         tsym := writeType(t)
1407                         ot = objw.SymPtrOff(s, ot, nsym)
1408                         ot = objw.SymPtrOff(s, ot, tsym)
1409                         // Plugin exports symbols as interfaces. Mark their types
1410                         // as UsedInIface.
1411                         tsym.Set(obj.AttrUsedInIface, true)
1412                 }
1413                 objw.Global(s, int32(ot), int16(obj.RODATA))
1414
1415                 ot = 0
1416                 s = base.Ctxt.Lookup("go.plugin.exports")
1417                 for _, p := range ptabs {
1418                         ot = objw.SymPtr(s, ot, p.Linksym(), 0)
1419                 }
1420                 objw.Global(s, int32(ot), int16(obj.RODATA))
1421         }
1422 }
1423
1424 func WriteImportStrings() {
1425         // generate import strings for imported packages
1426         for _, p := range types.ImportedPkgList() {
1427                 dimportpath(p)
1428         }
1429 }
1430
1431 func WriteBasicTypes() {
1432         // do basic types if compiling package runtime.
1433         // they have to be in at least one package,
1434         // and runtime is always loaded implicitly,
1435         // so this is as good as any.
1436         // another possible choice would be package main,
1437         // but using runtime means fewer copies in object files.
1438         if base.Ctxt.Pkgpath == "runtime" {
1439                 for i := types.Kind(1); i <= types.TBOOL; i++ {
1440                         writeType(types.NewPtr(types.Types[i]))
1441                 }
1442                 writeType(types.NewPtr(types.Types[types.TSTRING]))
1443                 writeType(types.NewPtr(types.Types[types.TUNSAFEPTR]))
1444
1445                 // emit type structs for error and func(error) string.
1446                 // The latter is the type of an auto-generated wrapper.
1447                 writeType(types.NewPtr(types.ErrorType))
1448
1449                 writeType(types.NewSignature(types.NoPkg, nil, nil, []*types.Field{
1450                         types.NewField(base.Pos, nil, types.ErrorType),
1451                 }, []*types.Field{
1452                         types.NewField(base.Pos, nil, types.Types[types.TSTRING]),
1453                 }))
1454
1455                 // add paths for runtime and main, which 6l imports implicitly.
1456                 dimportpath(ir.Pkgs.Runtime)
1457
1458                 if base.Flag.Race {
1459                         dimportpath(types.NewPkg("runtime/race", ""))
1460                 }
1461                 if base.Flag.MSan {
1462                         dimportpath(types.NewPkg("runtime/msan", ""))
1463                 }
1464
1465                 dimportpath(types.NewPkg("main", ""))
1466         }
1467 }
1468
1469 type typeAndStr struct {
1470         t       *types.Type
1471         short   string
1472         regular string
1473 }
1474
1475 type typesByString []typeAndStr
1476
1477 func (a typesByString) Len() int { return len(a) }
1478 func (a typesByString) Less(i, j int) bool {
1479         if a[i].short != a[j].short {
1480                 return a[i].short < a[j].short
1481         }
1482         // When the only difference between the types is whether
1483         // they refer to byte or uint8, such as **byte vs **uint8,
1484         // the types' ShortStrings can be identical.
1485         // To preserve deterministic sort ordering, sort these by String().
1486         if a[i].regular != a[j].regular {
1487                 return a[i].regular < a[j].regular
1488         }
1489         // Identical anonymous interfaces defined in different locations
1490         // will be equal for the above checks, but different in DWARF output.
1491         // Sort by source position to ensure deterministic order.
1492         // See issues 27013 and 30202.
1493         if a[i].t.Kind() == types.TINTER && a[i].t.Methods().Len() > 0 {
1494                 return a[i].t.Methods().Index(0).Pos.Before(a[j].t.Methods().Index(0).Pos)
1495         }
1496         return false
1497 }
1498 func (a typesByString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
1499
1500 // maxPtrmaskBytes is the maximum length of a GC ptrmask bitmap,
1501 // which holds 1-bit entries describing where pointers are in a given type.
1502 // Above this length, the GC information is recorded as a GC program,
1503 // which can express repetition compactly. In either form, the
1504 // information is used by the runtime to initialize the heap bitmap,
1505 // and for large types (like 128 or more words), they are roughly the
1506 // same speed. GC programs are never much larger and often more
1507 // compact. (If large arrays are involved, they can be arbitrarily
1508 // more compact.)
1509 //
1510 // The cutoff must be large enough that any allocation large enough to
1511 // use a GC program is large enough that it does not share heap bitmap
1512 // bytes with any other objects, allowing the GC program execution to
1513 // assume an aligned start and not use atomic operations. In the current
1514 // runtime, this means all malloc size classes larger than the cutoff must
1515 // be multiples of four words. On 32-bit systems that's 16 bytes, and
1516 // all size classes >= 16 bytes are 16-byte aligned, so no real constraint.
1517 // On 64-bit systems, that's 32 bytes, and 32-byte alignment is guaranteed
1518 // for size classes >= 256 bytes. On a 64-bit system, 256 bytes allocated
1519 // is 32 pointers, the bits for which fit in 4 bytes. So maxPtrmaskBytes
1520 // must be >= 4.
1521 //
1522 // We used to use 16 because the GC programs do have some constant overhead
1523 // to get started, and processing 128 pointers seems to be enough to
1524 // amortize that overhead well.
1525 //
1526 // To make sure that the runtime's chansend can call typeBitsBulkBarrier,
1527 // we raised the limit to 2048, so that even 32-bit systems are guaranteed to
1528 // use bitmaps for objects up to 64 kB in size.
1529 //
1530 // Also known to reflect/type.go.
1531 //
1532 const maxPtrmaskBytes = 2048
1533
1534 // GCSym returns a data symbol containing GC information for type t, along
1535 // with a boolean reporting whether the UseGCProg bit should be set in the
1536 // type kind, and the ptrdata field to record in the reflect type information.
1537 // GCSym may be called in concurrent backend, so it does not emit the symbol
1538 // content.
1539 func GCSym(t *types.Type) (lsym *obj.LSym, useGCProg bool, ptrdata int64) {
1540         // Record that we need to emit the GC symbol.
1541         gcsymmu.Lock()
1542         if _, ok := gcsymset[t]; !ok {
1543                 gcsymset[t] = struct{}{}
1544         }
1545         gcsymmu.Unlock()
1546
1547         return dgcsym(t, false)
1548 }
1549
1550 // dgcsym returns a data symbol containing GC information for type t, along
1551 // with a boolean reporting whether the UseGCProg bit should be set in the
1552 // type kind, and the ptrdata field to record in the reflect type information.
1553 // When write is true, it writes the symbol data.
1554 func dgcsym(t *types.Type, write bool) (lsym *obj.LSym, useGCProg bool, ptrdata int64) {
1555         ptrdata = types.PtrDataSize(t)
1556         if ptrdata/int64(types.PtrSize) <= maxPtrmaskBytes*8 {
1557                 lsym = dgcptrmask(t, write)
1558                 return
1559         }
1560
1561         useGCProg = true
1562         lsym, ptrdata = dgcprog(t, write)
1563         return
1564 }
1565
1566 // dgcptrmask emits and returns the symbol containing a pointer mask for type t.
1567 func dgcptrmask(t *types.Type, write bool) *obj.LSym {
1568         ptrmask := make([]byte, (types.PtrDataSize(t)/int64(types.PtrSize)+7)/8)
1569         fillptrmask(t, ptrmask)
1570         p := fmt.Sprintf("runtime.gcbits.%x", ptrmask)
1571
1572         lsym := base.Ctxt.Lookup(p)
1573         if write && !lsym.OnList() {
1574                 for i, x := range ptrmask {
1575                         objw.Uint8(lsym, i, x)
1576                 }
1577                 objw.Global(lsym, int32(len(ptrmask)), obj.DUPOK|obj.RODATA|obj.LOCAL)
1578                 lsym.Set(obj.AttrContentAddressable, true)
1579         }
1580         return lsym
1581 }
1582
1583 // fillptrmask fills in ptrmask with 1s corresponding to the
1584 // word offsets in t that hold pointers.
1585 // ptrmask is assumed to fit at least types.PtrDataSize(t)/PtrSize bits.
1586 func fillptrmask(t *types.Type, ptrmask []byte) {
1587         for i := range ptrmask {
1588                 ptrmask[i] = 0
1589         }
1590         if !t.HasPointers() {
1591                 return
1592         }
1593
1594         vec := bitvec.New(8 * int32(len(ptrmask)))
1595         typebits.Set(t, 0, vec)
1596
1597         nptr := types.PtrDataSize(t) / int64(types.PtrSize)
1598         for i := int64(0); i < nptr; i++ {
1599                 if vec.Get(int32(i)) {
1600                         ptrmask[i/8] |= 1 << (uint(i) % 8)
1601                 }
1602         }
1603 }
1604
1605 // dgcprog emits and returns the symbol containing a GC program for type t
1606 // along with the size of the data described by the program (in the range
1607 // [types.PtrDataSize(t), t.Width]).
1608 // In practice, the size is types.PtrDataSize(t) except for non-trivial arrays.
1609 // For non-trivial arrays, the program describes the full t.Width size.
1610 func dgcprog(t *types.Type, write bool) (*obj.LSym, int64) {
1611         types.CalcSize(t)
1612         if t.Width == types.BADWIDTH {
1613                 base.Fatalf("dgcprog: %v badwidth", t)
1614         }
1615         lsym := TypeLinksymPrefix(".gcprog", t)
1616         var p gcProg
1617         p.init(lsym, write)
1618         p.emit(t, 0)
1619         offset := p.w.BitIndex() * int64(types.PtrSize)
1620         p.end()
1621         if ptrdata := types.PtrDataSize(t); offset < ptrdata || offset > t.Width {
1622                 base.Fatalf("dgcprog: %v: offset=%d but ptrdata=%d size=%d", t, offset, ptrdata, t.Width)
1623         }
1624         return lsym, offset
1625 }
1626
1627 type gcProg struct {
1628         lsym   *obj.LSym
1629         symoff int
1630         w      gcprog.Writer
1631         write  bool
1632 }
1633
1634 func (p *gcProg) init(lsym *obj.LSym, write bool) {
1635         p.lsym = lsym
1636         p.write = write && !lsym.OnList()
1637         p.symoff = 4 // first 4 bytes hold program length
1638         if !write {
1639                 p.w.Init(func(byte) {})
1640                 return
1641         }
1642         p.w.Init(p.writeByte)
1643         if base.Debug.GCProg > 0 {
1644                 fmt.Fprintf(os.Stderr, "compile: start GCProg for %v\n", lsym)
1645                 p.w.Debug(os.Stderr)
1646         }
1647 }
1648
1649 func (p *gcProg) writeByte(x byte) {
1650         p.symoff = objw.Uint8(p.lsym, p.symoff, x)
1651 }
1652
1653 func (p *gcProg) end() {
1654         p.w.End()
1655         if !p.write {
1656                 return
1657         }
1658         objw.Uint32(p.lsym, 0, uint32(p.symoff-4))
1659         objw.Global(p.lsym, int32(p.symoff), obj.DUPOK|obj.RODATA|obj.LOCAL)
1660         p.lsym.Set(obj.AttrContentAddressable, true)
1661         if base.Debug.GCProg > 0 {
1662                 fmt.Fprintf(os.Stderr, "compile: end GCProg for %v\n", p.lsym)
1663         }
1664 }
1665
1666 func (p *gcProg) emit(t *types.Type, offset int64) {
1667         types.CalcSize(t)
1668         if !t.HasPointers() {
1669                 return
1670         }
1671         if t.Width == int64(types.PtrSize) {
1672                 p.w.Ptr(offset / int64(types.PtrSize))
1673                 return
1674         }
1675         switch t.Kind() {
1676         default:
1677                 base.Fatalf("gcProg.emit: unexpected type %v", t)
1678
1679         case types.TSTRING:
1680                 p.w.Ptr(offset / int64(types.PtrSize))
1681
1682         case types.TINTER:
1683                 // Note: the first word isn't a pointer. See comment in typebits.Set
1684                 p.w.Ptr(offset/int64(types.PtrSize) + 1)
1685
1686         case types.TSLICE:
1687                 p.w.Ptr(offset / int64(types.PtrSize))
1688
1689         case types.TARRAY:
1690                 if t.NumElem() == 0 {
1691                         // should have been handled by haspointers check above
1692                         base.Fatalf("gcProg.emit: empty array")
1693                 }
1694
1695                 // Flatten array-of-array-of-array to just a big array by multiplying counts.
1696                 count := t.NumElem()
1697                 elem := t.Elem()
1698                 for elem.IsArray() {
1699                         count *= elem.NumElem()
1700                         elem = elem.Elem()
1701                 }
1702
1703                 if !p.w.ShouldRepeat(elem.Width/int64(types.PtrSize), count) {
1704                         // Cheaper to just emit the bits.
1705                         for i := int64(0); i < count; i++ {
1706                                 p.emit(elem, offset+i*elem.Width)
1707                         }
1708                         return
1709                 }
1710                 p.emit(elem, offset)
1711                 p.w.ZeroUntil((offset + elem.Width) / int64(types.PtrSize))
1712                 p.w.Repeat(elem.Width/int64(types.PtrSize), count-1)
1713
1714         case types.TSTRUCT:
1715                 for _, t1 := range t.Fields().Slice() {
1716                         p.emit(t1.Type, offset+t1.Offset)
1717                 }
1718         }
1719 }
1720
1721 // ZeroAddr returns the address of a symbol with at least
1722 // size bytes of zeros.
1723 func ZeroAddr(size int64) ir.Node {
1724         if size >= 1<<31 {
1725                 base.Fatalf("map elem too big %d", size)
1726         }
1727         if ZeroSize < size {
1728                 ZeroSize = size
1729         }
1730         lsym := base.PkgLinksym("go.map", "zero", obj.ABI0)
1731         x := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
1732         return typecheck.Expr(typecheck.NodAddr(x))
1733 }
1734
1735 func CollectPTabs() {
1736         if !base.Ctxt.Flag_dynlink || types.LocalPkg.Name != "main" {
1737                 return
1738         }
1739         for _, exportn := range typecheck.Target.Exports {
1740                 s := exportn.Sym()
1741                 nn := ir.AsNode(s.Def)
1742                 if nn == nil {
1743                         continue
1744                 }
1745                 if nn.Op() != ir.ONAME {
1746                         continue
1747                 }
1748                 n := nn.(*ir.Name)
1749                 if !types.IsExported(s.Name) {
1750                         continue
1751                 }
1752                 if s.Pkg.Name != "main" {
1753                         continue
1754                 }
1755                 ptabs = append(ptabs, n)
1756         }
1757 }
1758
1759 // Generate a wrapper function to convert from
1760 // a receiver of type T to a receiver of type U.
1761 // That is,
1762 //
1763 //      func (t T) M() {
1764 //              ...
1765 //      }
1766 //
1767 // already exists; this function generates
1768 //
1769 //      func (u U) M() {
1770 //              u.M()
1771 //      }
1772 //
1773 // where the types T and U are such that u.M() is valid
1774 // and calls the T.M method.
1775 // The resulting function is for use in method tables.
1776 //
1777 //      rcvr - U
1778 //      method - M func (t T)(), a TFIELD type struct
1779 func methodWrapper(rcvr *types.Type, method *types.Field) *obj.LSym {
1780         newnam := ir.MethodSym(rcvr, method.Sym)
1781         lsym := newnam.Linksym()
1782         if newnam.Siggen() {
1783                 return lsym
1784         }
1785         newnam.SetSiggen(true)
1786
1787         if types.Identical(rcvr, method.Type.Recv().Type) {
1788                 return lsym
1789         }
1790
1791         // Only generate (*T).M wrappers for T.M in T's own package.
1792         if rcvr.IsPtr() && rcvr.Elem() == method.Type.Recv().Type &&
1793                 rcvr.Elem().Sym() != nil && rcvr.Elem().Sym().Pkg != types.LocalPkg {
1794                 return lsym
1795         }
1796
1797         // Only generate I.M wrappers for I in I's own package
1798         // but keep doing it for error.Error (was issue #29304).
1799         if rcvr.IsInterface() && rcvr.Sym() != nil && rcvr.Sym().Pkg != types.LocalPkg && rcvr != types.ErrorType {
1800                 return lsym
1801         }
1802
1803         base.Pos = base.AutogeneratedPos
1804         typecheck.DeclContext = ir.PEXTERN
1805
1806         tfn := ir.NewFuncType(base.Pos,
1807                 ir.NewField(base.Pos, typecheck.Lookup(".this"), nil, rcvr),
1808                 typecheck.NewFuncParams(method.Type.Params(), true),
1809                 typecheck.NewFuncParams(method.Type.Results(), false))
1810
1811         // TODO(austin): SelectorExpr may have created one or more
1812         // ir.Names for these already with a nil Func field. We should
1813         // consolidate these and always attach a Func to the Name.
1814         fn := typecheck.DeclFunc(newnam, tfn)
1815         fn.SetDupok(true)
1816
1817         nthis := ir.AsNode(tfn.Type().Recv().Nname)
1818
1819         methodrcvr := method.Type.Recv().Type
1820
1821         // generate nil pointer check for better error
1822         if rcvr.IsPtr() && rcvr.Elem() == methodrcvr {
1823                 // generating wrapper from *T to T.
1824                 n := ir.NewIfStmt(base.Pos, nil, nil, nil)
1825                 n.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, nthis, typecheck.NodNil())
1826                 call := ir.NewCallExpr(base.Pos, ir.OCALL, typecheck.LookupRuntime("panicwrap"), nil)
1827                 n.Body = []ir.Node{call}
1828                 fn.Body.Append(n)
1829         }
1830
1831         dot := typecheck.AddImplicitDots(ir.NewSelectorExpr(base.Pos, ir.OXDOT, nthis, method.Sym))
1832
1833         // generate call
1834         // It's not possible to use a tail call when dynamic linking on ppc64le. The
1835         // bad scenario is when a local call is made to the wrapper: the wrapper will
1836         // call the implementation, which might be in a different module and so set
1837         // the TOC to the appropriate value for that module. But if it returns
1838         // directly to the wrapper's caller, nothing will reset it to the correct
1839         // value for that function.
1840         //
1841         // Disable tailcall for RegabiArgs for now. The IR does not connect the
1842         // arguments with the OTAILCALL node, and the arguments are not marshaled
1843         // correctly.
1844         if !base.Flag.Cfg.Instrumenting && rcvr.IsPtr() && methodrcvr.IsPtr() && method.Embedded != 0 && !types.IsInterfaceMethod(method.Type) && !(base.Ctxt.Arch.Name == "ppc64le" && base.Ctxt.Flag_dynlink) && !buildcfg.Experiment.RegabiArgs {
1845                 // generate tail call: adjust pointer receiver and jump to embedded method.
1846                 left := dot.X // skip final .M
1847                 if !left.Type().IsPtr() {
1848                         left = typecheck.NodAddr(left)
1849                 }
1850                 as := ir.NewAssignStmt(base.Pos, nthis, typecheck.ConvNop(left, rcvr))
1851                 fn.Body.Append(as)
1852                 fn.Body.Append(ir.NewTailCallStmt(base.Pos, method.Nname.(*ir.Name)))
1853         } else {
1854                 fn.SetWrapper(true) // ignore frame for panic+recover matching
1855                 call := ir.NewCallExpr(base.Pos, ir.OCALL, dot, nil)
1856                 call.Args = ir.ParamNames(tfn.Type())
1857                 call.IsDDD = tfn.Type().IsVariadic()
1858                 if method.Type.NumResults() > 0 {
1859                         ret := ir.NewReturnStmt(base.Pos, nil)
1860                         ret.Results = []ir.Node{call}
1861                         fn.Body.Append(ret)
1862                 } else {
1863                         fn.Body.Append(call)
1864                 }
1865         }
1866
1867         typecheck.FinishFuncBody()
1868         if base.Debug.DclStack != 0 {
1869                 types.CheckDclstack()
1870         }
1871
1872         typecheck.Func(fn)
1873         ir.CurFunc = fn
1874         typecheck.Stmts(fn.Body)
1875
1876         // Inline calls within (*T).M wrappers. This is safe because we only
1877         // generate those wrappers within the same compilation unit as (T).M.
1878         // TODO(mdempsky): Investigate why we can't enable this more generally.
1879         if rcvr.IsPtr() && rcvr.Elem() == method.Type.Recv().Type && rcvr.Elem().Sym() != nil {
1880                 inline.InlineCalls(fn)
1881         }
1882         escape.Batch([]*ir.Func{fn}, false)
1883
1884         ir.CurFunc = nil
1885         typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
1886
1887         return lsym
1888 }
1889
1890 var ZeroSize int64
1891
1892 // MarkTypeUsedInInterface marks that type t is converted to an interface.
1893 // This information is used in the linker in dead method elimination.
1894 func MarkTypeUsedInInterface(t *types.Type, from *obj.LSym) {
1895         tsym := TypeLinksym(t)
1896         // Emit a marker relocation. The linker will know the type is converted
1897         // to an interface if "from" is reachable.
1898         r := obj.Addrel(from)
1899         r.Sym = tsym
1900         r.Type = objabi.R_USEIFACE
1901 }
1902
1903 // MarkUsedIfaceMethod marks that an interface method is used in the current
1904 // function. n is OCALLINTER node.
1905 func MarkUsedIfaceMethod(n *ir.CallExpr) {
1906         // skip unnamed functions (func _())
1907         if ir.CurFunc.LSym == nil {
1908                 return
1909         }
1910         dot := n.X.(*ir.SelectorExpr)
1911         ityp := dot.X.Type()
1912         tsym := TypeLinksym(ityp)
1913         r := obj.Addrel(ir.CurFunc.LSym)
1914         r.Sym = tsym
1915         // dot.Xoffset is the method index * PtrSize (the offset of code pointer
1916         // in itab).
1917         midx := dot.Offset() / int64(types.PtrSize)
1918         r.Add = InterfaceMethodOffset(ityp, midx)
1919         r.Type = objabi.R_USEIFACEMETHOD
1920 }