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.
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"
30 type itabEntry struct {
32 lsym *obj.LSym // symbol of the itab itself
34 // symbols of each method in
35 // the itab, sorted by byte offset;
36 // filled in by CompileITabs
40 type ptabEntry struct {
45 func CountTabs() (numPTabs, numITabs int) {
46 return len(ptabs), len(itabs)
49 // runtime interface and reflection data structures
51 signatmu sync.Mutex // protects signatset and signatslice
52 signatset = make(map[*types.Type]struct{})
53 signatslice []*types.Type
55 gcsymmu sync.Mutex // protects gcsymset and gcsymslice
56 gcsymset = make(map[*types.Type]struct{})
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
74 // Make sure this stays in sync with runtime/map.go.
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{})
85 func uncommonSize(t *types.Type) int { // Sizeof(runtime.uncommontype{})
86 if t.Sym() == nil && len(methods(t)) == 0 {
89 return 4 + 2 + 2 + 4 + 4
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)
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
105 types.CalcSize(keytype)
106 types.CalcSize(elemtype)
107 if keytype.Width > MAXKEYSIZE {
108 keytype = types.NewPtr(keytype)
110 if elemtype.Width > MAXELEMSIZE {
111 elemtype = types.NewPtr(elemtype)
114 field := make([]*types.Field, 0, 5)
116 // The first field is: uint8 topbits[BUCKETSIZE].
117 arr := types.NewArray(types.Types[types.TUINT8], BUCKETSIZE)
118 field = append(field, makefield("topbits", arr))
120 arr = types.NewArray(keytype, BUCKETSIZE)
122 keys := makefield("keys", arr)
123 field = append(field, keys)
125 arr = types.NewArray(elemtype, BUCKETSIZE)
127 elems := makefield("elems", arr)
128 field = append(field, elems)
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]
140 overflow := makefield("overflow", otyp)
141 field = append(field, overflow)
144 bucket := types.NewStruct(types.NoPkg, field[:])
145 bucket.SetNoalg(true)
146 types.CalcSize(bucket)
148 // Check invariants that map code depends on.
149 if !types.IsComparable(t.Key()) {
150 base.Fatalf("unsupported map key type for %v", t)
153 base.Fatalf("bucket size too small for proper alignment")
155 if keytype.Align > BUCKETSIZE {
156 base.Fatalf("key align too big for %v", t)
158 if elemtype.Align > BUCKETSIZE {
159 base.Fatalf("elem align too big for %v", t)
161 if keytype.Width > MAXKEYSIZE {
162 base.Fatalf("key size to large for %v", t)
164 if elemtype.Width > MAXELEMSIZE {
165 base.Fatalf("elem size to large for %v", t)
167 if t.Key().Width > MAXKEYSIZE && !keytype.IsPtr() {
168 base.Fatalf("key indirect incorrect for %v", t)
170 if t.Elem().Width > MAXELEMSIZE && !elemtype.IsPtr() {
171 base.Fatalf("elem indirect incorrect for %v", t)
173 if keytype.Width%int64(keytype.Align) != 0 {
174 base.Fatalf("key size not a multiple of key align for %v", t)
176 if elemtype.Width%int64(elemtype.Align) != 0 {
177 base.Fatalf("elem size not a multiple of elem align for %v", t)
179 if bucket.Align%keytype.Align != 0 {
180 base.Fatalf("bucket align not multiple of key align %v", t)
182 if bucket.Align%elemtype.Align != 0 {
183 base.Fatalf("bucket align not multiple of elem align %v", t)
185 if keys.Offset%int64(keytype.Align) != 0 {
186 base.Fatalf("bad alignment of keys in bmap for %v", t)
188 if elems.Offset%int64(elemtype.Align) != 0 {
189 base.Fatalf("bad alignment of elems in bmap for %v", t)
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)
198 t.MapType().Bucket = bucket
200 bucket.StructType().Map = t
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
211 bmap := MapBucketType(t)
214 // type hmap struct {
223 // extra unsafe.Pointer // *mapextra
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]),
238 hmap := types.NewStruct(types.NoPkg, fields)
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)
248 t.MapType().Hmap = hmap
249 hmap.StructType().Map = t
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
261 bmap := MapBucketType(t)
264 // type hiter struct {
267 // t unsafe.Pointer // *MapType
271 // overflow unsafe.Pointer // *[]*bmap
272 // oldoverflow unsafe.Pointer // *[]*bmap
273 // startBucket uintptr
279 // checkBucket uintptr
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]),
300 // build iterator struct holding the above fields
301 hiter := types.NewStruct(types.NoPkg, fields)
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)
307 t.MapType().Hiter = hiter
308 hiter.StructType().Map = t
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 {
316 mt := types.ReceiverBaseType(t)
321 typecheck.CalcMethods(mt)
323 // type stored in interface word
326 if !types.IsDirectIface(it) {
330 // make list of methods for t,
331 // generating code if necessary.
333 for _, f := range mt.AllMethods().Slice() {
335 base.Fatalf("method with no sym on %v", mt)
338 base.Fatalf("non-method on %v method %v %v", mt, f.Sym, f)
340 if f.Type.Recv() == nil {
341 base.Fatalf("receiver with no type on %v method %v %v", mt, f.Sym, f)
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) {
357 isym: methodWrapper(it, f),
358 tsym: methodWrapper(t, f),
359 type_: typecheck.NewMethodType(f.Type, t),
360 mtype: typecheck.NewMethodType(f.Type, nil),
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 {
376 base.Fatalf("unexpected blank symbol in interface method set")
378 if n := len(methods); n > 0 {
380 if !last.name.Less(f.Sym) {
381 base.Fatalf("sigcmp vs sortinter %v %v", last.name, f.Sym)
388 type_: typecheck.NewMethodType(f.Type, nil),
390 methods = append(methods, sig)
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.
402 func dimportpath(p *types.Pkg) {
403 if p.Pathsym != nil {
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 {
415 if p == types.LocalPkg {
416 // Note: myimportpath != "", or else dgopkgpath won't call dimportpath.
417 str = base.Ctxt.Pkgpath
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)
427 func dgopkgpath(s *obj.LSym, ot int, pkg *types.Pkg) int {
429 return objw.Uintptr(s, ot, 0)
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)
443 return objw.SymPtr(s, ot, pkg.Pathsym, 0)
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 {
449 return objw.Uint32(s, ot, 0)
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)
462 return objw.SymPtrOff(s, ot, pkg.Pathsym)
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)
470 nsym := dname(ft.Sym.Name, ft.Note, nil, types.IsExported(ft.Sym.Name))
471 return objw.SymPtr(lsym, ot, nsym, 0)
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)
479 if len(tag) > 1<<16-1 {
480 base.Fatalf("tag too long: %s", tag)
483 // Encode name and tag. See reflect/type.go for details.
485 l := 1 + 2 + len(name)
498 b[1] = uint8(len(name) >> 8)
499 b[2] = uint8(len(name))
502 tb := b[3+len(name):]
503 tb[0] = uint8(len(tag) >> 8)
504 tb[1] = uint8(len(tag))
508 ot = int(s.WriteBytes(base.Ctxt, int64(ot), b))
511 ot = dgopkgpathOff(s, ot, pkg)
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."
527 // In the common case, share data with other packages.
530 sname += "-noname-exported." + tag
532 sname += "-noname-unexported." + tag
536 sname += name + "." + tag
538 sname += name + "-" + tag
542 sname = fmt.Sprintf(`%s"".%d`, sname, dnameCount)
545 s := base.Ctxt.Lookup(sname)
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)
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 {
560 if t.Sym() == nil && len(m) == 0 {
563 noff := int(types.Rnd(int64(ot), int64(types.PtrSize)))
565 base.Fatalf("unexpected alignment in dextratype for %v", t)
568 for _, a := range m {
572 ot = dgopkgpathOff(lsym, ot, typePkg(t))
574 dataAdd += uncommonSize(t)
576 if mcount != int(uint16(mcount)) {
577 base.Fatalf("too many methods on %v: %d", t, mcount)
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)
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)
591 func typePkg(t *types.Type) *types.Pkg {
595 case types.TARRAY, types.TSLICE, types.TPTR, types.TCHAN:
597 tsym = t.Elem().Sym()
601 if tsym != nil && tsym.Pkg != types.BuiltinPkg {
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)
614 if !exported && a.name.Pkg != typePkg(t) {
617 nsym := dname(a.name.Name, "", pkg, exported)
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)
627 func dmethodptrOff(s *obj.LSym, ot int, x *obj.LSym) int {
628 objw.Uint32(s, ot, 0)
633 r.Type = objabi.R_METHODOFF
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,
666 // tflag is documented in reflect/type.go.
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
674 tflagUncommon = 1 << 0
675 tflagExtraStar = 1 << 1
677 tflagRegularMemory = 1 << 3
681 memhashvarlen *obj.LSym
682 memequalvarlen *obj.LSym
685 // dcommontype dumps the contents of a reflect.rtype (runtime._type).
686 func dcommontype(lsym *obj.LSym, t *types.Type) int {
692 if !t.IsPtr() || t.IsPtrElem() {
693 tptr := types.NewPtr(t)
694 if t.Sym() != nil || methods(tptr) != nil {
697 sptr = writeType(tptr)
700 gcsym, useGCProg, ptrdata := dgcsym(t, true)
703 // ../../../../reflect/type.go:/^type.rtype
704 // actual type structure
705 // type rtype struct {
713 // equal func(unsafe.Pointer, unsafe.Pointer) bool
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))
724 if uncommonSize(t) != 0 {
725 tflag |= tflagUncommon
727 if t.Sym() != nil && t.Sym().Name != "" {
730 if isRegularMemory(t) {
731 tflag |= tflagRegularMemory
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, "*") {
743 tflag |= tflagExtraStar
745 exported = types.IsExported(t.Sym().Name)
748 if t.Elem() != nil && t.Elem().Sym() != nil {
749 exported = types.IsExported(t.Elem().Sym().Name)
753 ot = objw.Uint8(lsym, ot, tflag)
755 // runtime (and common sense) expects alignment to be a power of two.
762 base.Fatalf("invalid alignment %d for %v", t.Align, t)
764 ot = objw.Uint8(lsym, ot, t.Align) // align
765 ot = objw.Uint8(lsym, ot, t.Align) // fieldAlign
768 if types.IsDirectIface(t) {
769 i |= objabi.KindDirectIface
772 i |= objabi.KindGCProg
774 ot = objw.Uint8(lsym, ot, uint8(i)) // kind
776 ot = objw.SymPtr(lsym, ot, eqfunc, 0) // equality function
778 ot = objw.Uintptr(lsym, ot, 0) // type we can't do == with
780 ot = objw.SymPtr(lsym, ot, gcsym, 0) // gcdata
782 nsym := dname(p, "", nil, exported)
783 ot = objw.SymPtrOff(lsym, ot, nsym) // str
786 ot = objw.Uint32(lsym, ot, 0)
788 ot = objw.SymPtrWeakOff(lsym, ot, sptr)
790 ot = objw.SymPtrOff(lsym, ot, sptr)
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)
802 func TypeSymPrefix(prefix string, t *types.Type) *types.Sym {
803 p := prefix + "." + t.ShortString()
804 s := types.TypeSymLookup(p)
806 // This function is for looking up type-related generated functions
807 // (e.g. eq and hash). Make sure they are indeed generated.
812 //print("algsym: %s -> %+S\n", p, s);
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)
821 if t.Kind() == types.TFUNC && t.Recv() != nil {
822 base.Fatalf("misuse of method type: %v", t)
824 s := types.TypeSym(t)
831 func TypeLinksymPrefix(prefix string, t *types.Type) *obj.LSym {
832 return TypeSymPrefix(prefix, t).Linksym()
835 func TypeLinksymLookup(name string) *obj.LSym {
836 return types.TypeSymLookup(name).Linksym()
839 func TypeLinksym(t *types.Type) *obj.LSym {
840 return TypeSym(t).Linksym()
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)
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)
852 s, existed := ir.Pkgs.Itab.LookupOK(t.ShortString() + "," + itype.ShortString())
854 itabs = append(itabs, itabEntry{t: t, itype: itype, lsym: s.Linksym()})
858 n := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
859 return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
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 {
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:
870 case types.TFLOAT32, types.TFLOAT64, types.TCOMPLEX64, types.TCOMPLEX128, // floats and complex can be +0/-0
872 types.TSTRING: // strings might have smaller backing stores
876 return needkeyupdate(t.Elem())
879 for _, t1 := range t.Fields().Slice() {
880 if needkeyupdate(t1.Type) {
887 base.Fatalf("bad type for map key: %v", t)
892 // hashMightPanic reports whether the hash of a map key of type t might panic.
893 func hashMightPanic(t *types.Type) bool {
899 return hashMightPanic(t.Elem())
902 for _, t1 := range t.Fields().Slice() {
903 if hashMightPanic(t1.Type) {
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()]
924 func writeType(t *types.Type) *obj.LSym {
927 base.Fatalf("writeType %v", t)
930 s := types.TypeSym(t)
937 // special case (look for runtime below):
938 // when compiling package runtime,
939 // emit the type structures for int, float, etc.
942 if t.IsPtr() && t.Sym() == nil && t.Elem().Sym() != nil {
946 if tbase.Sym() == nil {
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)
960 // TODO(mdempsky): Investigate whether this can happen.
961 if tbase.Kind() == types.TFORW {
969 ot = dcommontype(lsym, t)
970 ot = dextratype(lsym, ot, t, 0)
973 // ../../../../runtime/type.go:/arrayType
974 s1 := writeType(t.Elem())
975 t2 := types.NewSlice(t.Elem())
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)
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)
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)
999 for _, t1 := range t.Recvs().Fields().Slice() {
1003 for _, t1 := range t.Params().Fields().Slice() {
1007 for _, t1 := range t.Results().Fields().Slice() {
1011 ot = dcommontype(lsym, t)
1012 inCount := t.NumRecvs() + t.NumParams()
1013 outCount := t.NumResults()
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
1023 dataAdd := (inCount + t.NumResults()) * types.PtrSize
1024 ot = dextratype(lsym, ot, t, dataAdd)
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)
1030 for _, t1 := range t.Params().Fields().Slice() {
1031 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1033 for _, t1 := range t.Results().Fields().Slice() {
1034 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1040 for _, a := range m {
1044 // ../../../../runtime/type.go:/interfaceType
1045 ot = dcommontype(lsym, t)
1048 if t.Sym() != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
1051 ot = dgopkgpath(lsym, ot, tpkg)
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)
1059 for _, a := range m {
1060 // ../../../../runtime/type.go:/imethod
1061 exported := types.IsExported(a.name.Name)
1063 if !exported && a.name.Pkg != tpkg {
1066 nsym := dname(a.name.Name, "", pkg, exported)
1068 ot = objw.SymPtrOff(lsym, ot, nsym)
1069 ot = objw.SymPtrOff(lsym, ot, writeType(a.type_))
1072 // ../../../../runtime/type.go:/mapType
1074 s1 := writeType(t.Key())
1075 s2 := writeType(t.Elem())
1076 s3 := writeType(MapBucketType(t))
1077 hasher := genhash(t.Key())
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)
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
1091 ot = objw.Uint8(lsym, ot, uint8(t.Key().Width))
1094 if t.Elem().Width > MAXELEMSIZE {
1095 ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1096 flags |= 2 // indirect value
1098 ot = objw.Uint8(lsym, ot, uint8(t.Elem().Width))
1100 ot = objw.Uint16(lsym, ot, uint16(MapBucketType(t).Width))
1101 if types.IsReflexive(t.Key()) {
1102 flags |= 4 // reflexive key
1104 if needkeyupdate(t.Key()) {
1105 flags |= 8 // need key update
1107 if hashMightPanic(t.Key()) {
1108 flags |= 16 // hash might panic
1110 ot = objw.Uint32(lsym, ot, flags)
1111 ot = dextratype(lsym, ot, t, 0)
1114 if t.Elem().Kind() == types.TANY {
1115 // ../../../../runtime/type.go:/UnsafePointerType
1116 ot = dcommontype(lsym, t)
1117 ot = dextratype(lsym, ot, t, 0)
1122 // ../../../../runtime/type.go:/ptrType
1123 s1 := writeType(t.Elem())
1125 ot = dcommontype(lsym, t)
1126 ot = objw.SymPtr(lsym, ot, s1, 0)
1127 ot = dextratype(lsym, ot, t, 0)
1129 // ../../../../runtime/type.go:/structType
1130 // for security, only the exported fields.
1132 fields := t.Fields().Slice()
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 {
1146 path := t.Sym.Pkg.Path
1147 if t.Sym.Pkg == types.LocalPkg {
1148 path = base.Ctxt.Pkgpath
1150 return strings.HasPrefix(path, "crypto/")
1152 newFields := fields[:0:0]
1153 for _, t1 := range fields {
1154 if !omitFieldForAwfulBoringCryptoKludge(t1) {
1155 newFields = append(newFields, t1)
1160 for _, t1 := range fields {
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.
1170 for _, f := range fields {
1171 if !types.IsExported(f.Sym.Name) {
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)))
1183 dataAdd := len(fields) * structfieldSize()
1184 ot = dextratype(lsym, ot, t, dataAdd)
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)
1194 if f.Embedded != 0 {
1197 ot = objw.Uintptr(lsym, ot, offsetAnon)
1201 ot = dextratypeData(lsym, ot, t)
1202 objw.Global(lsym, int32(ot), int16(dupok|obj.RODATA))
1204 // The linker will leave a table of all the typelinks for
1205 // types in the binary, so the runtime can find them.
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.
1217 case types.TPTR, types.TARRAY, types.TCHAN, types.TFUNC, types.TMAP, types.TSLICE, types.TSTRUCT:
1221 // Do not put Noalg types in typelinks. See issue #22605.
1222 if types.TypeHasNoAlg(t) {
1225 lsym.Set(obj.AttrMakeTypelink, keep)
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
1240 // The size of imethod is 8.
1241 return int64(commonSize()+4*types.PtrSize+uncommonSize(ityp)) + i*8
1244 // for each itabEntry, gather the methods on
1245 // the concrete type that implement the interface
1246 func CompileITabs() {
1247 for i := range itabs {
1249 methods := genfun(tab.t, tab.itype)
1250 if len(methods) == 0 {
1253 tab.entries = methods
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 {
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.
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)
1286 base.Fatalf("incomplete itab")
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
1302 for i := range itabs {
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) {
1318 return syms[methodnum]
1321 // NeedRuntimeType ensures that a runtime type descriptor is emitted for t.
1322 func NeedRuntimeType(t *types.Type) {
1324 // Generic types don't have a runtime type descriptor (but will
1325 // have a dictionary)
1328 if _, ok := signatset[t]; !ok {
1329 signatset[t] = struct{}{}
1330 signatslice = append(signatslice, t)
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)
1345 signatslice = signatslice[:0]
1346 sort.Sort(typesByString(signats))
1347 for _, ts := range signats {
1351 writeType(types.NewPtr(t))
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()})
1361 sort.Sort(typesByString(gcsyms))
1362 for _, ts := range gcsyms {
1369 for _, i := range itabs {
1370 // dump empty itab symbol into i.sym
1371 // type itab struct {
1372 // inter *interfacetype
1376 // fun [1]uintptr // variable sized
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
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)
1391 if types.LocalPkg.Name == "main" && len(ptabs) > 0 {
1393 s := base.Ctxt.Lookup("go.plugin.tabs")
1394 for _, p := range ptabs {
1395 // Dump ptab symbol into go.pluginsym package.
1397 // type ptab struct {
1399 // typ typeOff // pointer to symbol
1401 nsym := dname(p.Sym().Name, "", nil, true)
1403 if p.Class != ir.PFUNC {
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
1411 tsym.Set(obj.AttrUsedInIface, true)
1413 objw.Global(s, int32(ot), int16(obj.RODATA))
1416 s = base.Ctxt.Lookup("go.plugin.exports")
1417 for _, p := range ptabs {
1418 ot = objw.SymPtr(s, ot, p.Linksym(), 0)
1420 objw.Global(s, int32(ot), int16(obj.RODATA))
1424 func WriteImportStrings() {
1425 // generate import strings for imported packages
1426 for _, p := range types.ImportedPkgList() {
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]))
1442 writeType(types.NewPtr(types.Types[types.TSTRING]))
1443 writeType(types.NewPtr(types.Types[types.TUNSAFEPTR]))
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))
1449 writeType(types.NewSignature(types.NoPkg, nil, nil, []*types.Field{
1450 types.NewField(base.Pos, nil, types.ErrorType),
1452 types.NewField(base.Pos, nil, types.Types[types.TSTRING]),
1455 // add paths for runtime and main, which 6l imports implicitly.
1456 dimportpath(ir.Pkgs.Runtime)
1459 dimportpath(types.NewPkg("runtime/race", ""))
1462 dimportpath(types.NewPkg("runtime/msan", ""))
1465 dimportpath(types.NewPkg("main", ""))
1469 type typeAndStr struct {
1475 type typesByString []typeAndStr
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
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
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)
1498 func (a typesByString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
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
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
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.
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.
1530 // Also known to reflect/type.go.
1532 const maxPtrmaskBytes = 2048
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
1539 func GCSym(t *types.Type) (lsym *obj.LSym, useGCProg bool, ptrdata int64) {
1540 // Record that we need to emit the GC symbol.
1542 if _, ok := gcsymset[t]; !ok {
1543 gcsymset[t] = struct{}{}
1547 return dgcsym(t, false)
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)
1562 lsym, ptrdata = dgcprog(t, write)
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)
1572 lsym := base.Ctxt.Lookup(p)
1573 if write && !lsym.OnList() {
1574 for i, x := range ptrmask {
1575 objw.Uint8(lsym, i, x)
1577 objw.Global(lsym, int32(len(ptrmask)), obj.DUPOK|obj.RODATA|obj.LOCAL)
1578 lsym.Set(obj.AttrContentAddressable, true)
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 {
1590 if !t.HasPointers() {
1594 vec := bitvec.New(8 * int32(len(ptrmask)))
1595 typebits.Set(t, 0, vec)
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)
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) {
1612 if t.Width == types.BADWIDTH {
1613 base.Fatalf("dgcprog: %v badwidth", t)
1615 lsym := TypeLinksymPrefix(".gcprog", t)
1619 offset := p.w.BitIndex() * int64(types.PtrSize)
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)
1627 type gcProg struct {
1634 func (p *gcProg) init(lsym *obj.LSym, write bool) {
1636 p.write = write && !lsym.OnList()
1637 p.symoff = 4 // first 4 bytes hold program length
1639 p.w.Init(func(byte) {})
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)
1649 func (p *gcProg) writeByte(x byte) {
1650 p.symoff = objw.Uint8(p.lsym, p.symoff, x)
1653 func (p *gcProg) end() {
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)
1666 func (p *gcProg) emit(t *types.Type, offset int64) {
1668 if !t.HasPointers() {
1671 if t.Width == int64(types.PtrSize) {
1672 p.w.Ptr(offset / int64(types.PtrSize))
1677 base.Fatalf("gcProg.emit: unexpected type %v", t)
1680 p.w.Ptr(offset / int64(types.PtrSize))
1683 // Note: the first word isn't a pointer. See comment in typebits.Set
1684 p.w.Ptr(offset/int64(types.PtrSize) + 1)
1687 p.w.Ptr(offset / int64(types.PtrSize))
1690 if t.NumElem() == 0 {
1691 // should have been handled by haspointers check above
1692 base.Fatalf("gcProg.emit: empty array")
1695 // Flatten array-of-array-of-array to just a big array by multiplying counts.
1696 count := t.NumElem()
1698 for elem.IsArray() {
1699 count *= elem.NumElem()
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)
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)
1715 for _, t1 := range t.Fields().Slice() {
1716 p.emit(t1.Type, offset+t1.Offset)
1721 // ZeroAddr returns the address of a symbol with at least
1722 // size bytes of zeros.
1723 func ZeroAddr(size int64) ir.Node {
1725 base.Fatalf("map elem too big %d", size)
1727 if ZeroSize < size {
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))
1735 func CollectPTabs() {
1736 if !base.Ctxt.Flag_dynlink || types.LocalPkg.Name != "main" {
1739 for _, exportn := range typecheck.Target.Exports {
1741 nn := ir.AsNode(s.Def)
1745 if nn.Op() != ir.ONAME {
1749 if !types.IsExported(s.Name) {
1752 if s.Pkg.Name != "main" {
1755 ptabs = append(ptabs, n)
1759 // Generate a wrapper function to convert from
1760 // a receiver of type T to a receiver of type U.
1767 // already exists; this function generates
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.
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() {
1785 newnam.SetSiggen(true)
1787 if types.Identical(rcvr, method.Type.Recv().Type) {
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 {
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 {
1803 base.Pos = base.AutogeneratedPos
1804 typecheck.DeclContext = ir.PEXTERN
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))
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)
1817 nthis := ir.AsNode(tfn.Type().Recv().Nname)
1819 methodrcvr := method.Type.Recv().Type
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}
1831 dot := typecheck.AddImplicitDots(ir.NewSelectorExpr(base.Pos, ir.OXDOT, nthis, method.Sym))
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.
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
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)
1850 as := ir.NewAssignStmt(base.Pos, nthis, typecheck.ConvNop(left, rcvr))
1852 fn.Body.Append(ir.NewTailCallStmt(base.Pos, method.Nname.(*ir.Name)))
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}
1863 fn.Body.Append(call)
1867 typecheck.FinishFuncBody()
1868 if base.Debug.DclStack != 0 {
1869 types.CheckDclstack()
1874 typecheck.Stmts(fn.Body)
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)
1882 escape.Batch([]*ir.Func{fn}, false)
1885 typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
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)
1900 r.Type = objabi.R_USEIFACE
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 {
1910 dot := n.X.(*ir.SelectorExpr)
1911 ityp := dot.X.Type()
1912 tsym := TypeLinksym(ityp)
1913 r := obj.Addrel(ir.CurFunc.LSym)
1915 // dot.Xoffset is the method index * PtrSize (the offset of code pointer
1917 midx := dot.Offset() / int64(types.PtrSize)
1918 r.Add = InterfaceMethodOffset(ityp, midx)
1919 r.Type = objabi.R_USEIFACEMETHOD