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.
16 "cmd/compile/internal/base"
17 "cmd/compile/internal/bitvec"
18 "cmd/compile/internal/escape"
19 "cmd/compile/internal/inline"
20 "cmd/compile/internal/ir"
21 "cmd/compile/internal/objw"
22 "cmd/compile/internal/typebits"
23 "cmd/compile/internal/typecheck"
24 "cmd/compile/internal/types"
31 type itabEntry struct {
33 lsym *obj.LSym // symbol of the itab itself
35 // symbols of each method in
36 // the itab, sorted by byte offset;
37 // filled in by CompileITabs
41 type ptabEntry struct {
46 func CountTabs() (numPTabs, numITabs int) {
47 return len(ptabs), len(itabs)
50 // runtime interface and reflection data structures
52 signatmu sync.Mutex // protects signatset and signatslice
53 signatset = make(map[*types.Type]struct{})
54 signatslice []*types.Type
56 gcsymmu sync.Mutex // protects gcsymset and gcsymslice
57 gcsymset = make(map[*types.Type]struct{})
71 // Builds a type representing a Bucket structure for
72 // the given map type. This type is not visible to users -
73 // we include only enough information to generate a correct GC
75 // Make sure this stays in sync with runtime/map.go.
82 func structfieldSize() int { return 3 * types.PtrSize } // Sizeof(runtime.structfield{})
83 func imethodSize() int { return 4 + 4 } // Sizeof(runtime.imethod{})
84 func commonSize() int { return 4*types.PtrSize + 8 + 8 } // Sizeof(runtime._type{})
86 func uncommonSize(t *types.Type) int { // Sizeof(runtime.uncommontype{})
87 if t.Sym() == nil && len(methods(t)) == 0 {
90 return 4 + 2 + 2 + 4 + 4
93 func makefield(name string, t *types.Type) *types.Field {
94 sym := (*types.Pkg)(nil).Lookup(name)
95 return types.NewField(src.NoXPos, sym, t)
98 // MapBucketType makes the map bucket type given the type of the map.
99 func MapBucketType(t *types.Type) *types.Type {
100 if t.MapType().Bucket != nil {
101 return t.MapType().Bucket
106 types.CalcSize(keytype)
107 types.CalcSize(elemtype)
108 if keytype.Width > MAXKEYSIZE {
109 keytype = types.NewPtr(keytype)
111 if elemtype.Width > MAXELEMSIZE {
112 elemtype = types.NewPtr(elemtype)
115 field := make([]*types.Field, 0, 5)
117 // The first field is: uint8 topbits[BUCKETSIZE].
118 arr := types.NewArray(types.Types[types.TUINT8], BUCKETSIZE)
119 field = append(field, makefield("topbits", arr))
121 arr = types.NewArray(keytype, BUCKETSIZE)
123 keys := makefield("keys", arr)
124 field = append(field, keys)
126 arr = types.NewArray(elemtype, BUCKETSIZE)
128 elems := makefield("elems", arr)
129 field = append(field, elems)
131 // If keys and elems have no pointers, the map implementation
132 // can keep a list of overflow pointers on the side so that
133 // buckets can be marked as having no pointers.
134 // Arrange for the bucket to have no pointers by changing
135 // the type of the overflow field to uintptr in this case.
136 // See comment on hmap.overflow in runtime/map.go.
137 otyp := types.Types[types.TUNSAFEPTR]
138 if !elemtype.HasPointers() && !keytype.HasPointers() {
139 otyp = types.Types[types.TUINTPTR]
141 overflow := makefield("overflow", otyp)
142 field = append(field, overflow)
145 bucket := types.NewStruct(types.NoPkg, field[:])
146 bucket.SetNoalg(true)
147 types.CalcSize(bucket)
149 // Check invariants that map code depends on.
150 if !types.IsComparable(t.Key()) {
151 base.Fatalf("unsupported map key type for %v", t)
154 base.Fatalf("bucket size too small for proper alignment")
156 if keytype.Align > BUCKETSIZE {
157 base.Fatalf("key align too big for %v", t)
159 if elemtype.Align > BUCKETSIZE {
160 base.Fatalf("elem align too big for %v", t)
162 if keytype.Width > MAXKEYSIZE {
163 base.Fatalf("key size to large for %v", t)
165 if elemtype.Width > MAXELEMSIZE {
166 base.Fatalf("elem size to large for %v", t)
168 if t.Key().Width > MAXKEYSIZE && !keytype.IsPtr() {
169 base.Fatalf("key indirect incorrect for %v", t)
171 if t.Elem().Width > MAXELEMSIZE && !elemtype.IsPtr() {
172 base.Fatalf("elem indirect incorrect for %v", t)
174 if keytype.Width%int64(keytype.Align) != 0 {
175 base.Fatalf("key size not a multiple of key align for %v", t)
177 if elemtype.Width%int64(elemtype.Align) != 0 {
178 base.Fatalf("elem size not a multiple of elem align for %v", t)
180 if bucket.Align%keytype.Align != 0 {
181 base.Fatalf("bucket align not multiple of key align %v", t)
183 if bucket.Align%elemtype.Align != 0 {
184 base.Fatalf("bucket align not multiple of elem align %v", t)
186 if keys.Offset%int64(keytype.Align) != 0 {
187 base.Fatalf("bad alignment of keys in bmap for %v", t)
189 if elems.Offset%int64(elemtype.Align) != 0 {
190 base.Fatalf("bad alignment of elems in bmap for %v", t)
193 // Double-check that overflow field is final memory in struct,
194 // with no padding at end.
195 if overflow.Offset != bucket.Width-int64(types.PtrSize) {
196 base.Fatalf("bad offset of overflow in bmap for %v", t)
199 t.MapType().Bucket = bucket
201 bucket.StructType().Map = t
205 // MapType builds a type representing a Hmap structure for the given map type.
206 // Make sure this stays in sync with runtime/map.go.
207 func MapType(t *types.Type) *types.Type {
208 if t.MapType().Hmap != nil {
209 return t.MapType().Hmap
212 bmap := MapBucketType(t)
215 // type hmap struct {
224 // extra unsafe.Pointer // *mapextra
226 // must match runtime/map.go:hmap.
227 fields := []*types.Field{
228 makefield("count", types.Types[types.TINT]),
229 makefield("flags", types.Types[types.TUINT8]),
230 makefield("B", types.Types[types.TUINT8]),
231 makefield("noverflow", types.Types[types.TUINT16]),
232 makefield("hash0", types.Types[types.TUINT32]), // Used in walk.go for OMAKEMAP.
233 makefield("buckets", types.NewPtr(bmap)), // Used in walk.go for OMAKEMAP.
234 makefield("oldbuckets", types.NewPtr(bmap)),
235 makefield("nevacuate", types.Types[types.TUINTPTR]),
236 makefield("extra", types.Types[types.TUNSAFEPTR]),
239 hmap := types.NewStruct(types.NoPkg, fields)
243 // The size of hmap should be 48 bytes on 64 bit
244 // and 28 bytes on 32 bit platforms.
245 if size := int64(8 + 5*types.PtrSize); hmap.Width != size {
246 base.Fatalf("hmap size not correct: got %d, want %d", hmap.Width, size)
249 t.MapType().Hmap = hmap
250 hmap.StructType().Map = t
254 // MapIterType builds a type representing an Hiter structure for the given map type.
255 // Make sure this stays in sync with runtime/map.go.
256 func MapIterType(t *types.Type) *types.Type {
257 if t.MapType().Hiter != nil {
258 return t.MapType().Hiter
262 bmap := MapBucketType(t)
265 // type hiter struct {
268 // t unsafe.Pointer // *MapType
272 // overflow unsafe.Pointer // *[]*bmap
273 // oldoverflow unsafe.Pointer // *[]*bmap
274 // startBucket uintptr
280 // checkBucket uintptr
282 // must match runtime/map.go:hiter.
283 fields := []*types.Field{
284 makefield("key", types.NewPtr(t.Key())), // Used in range.go for TMAP.
285 makefield("elem", types.NewPtr(t.Elem())), // Used in range.go for TMAP.
286 makefield("t", types.Types[types.TUNSAFEPTR]),
287 makefield("h", types.NewPtr(hmap)),
288 makefield("buckets", types.NewPtr(bmap)),
289 makefield("bptr", types.NewPtr(bmap)),
290 makefield("overflow", types.Types[types.TUNSAFEPTR]),
291 makefield("oldoverflow", types.Types[types.TUNSAFEPTR]),
292 makefield("startBucket", types.Types[types.TUINTPTR]),
293 makefield("offset", types.Types[types.TUINT8]),
294 makefield("wrapped", types.Types[types.TBOOL]),
295 makefield("B", types.Types[types.TUINT8]),
296 makefield("i", types.Types[types.TUINT8]),
297 makefield("bucket", types.Types[types.TUINTPTR]),
298 makefield("checkBucket", types.Types[types.TUINTPTR]),
301 // build iterator struct holding the above fields
302 hiter := types.NewStruct(types.NoPkg, fields)
304 types.CalcSize(hiter)
305 if hiter.Width != int64(12*types.PtrSize) {
306 base.Fatalf("hash_iter size not correct %d %d", hiter.Width, 12*types.PtrSize)
308 t.MapType().Hiter = hiter
309 hiter.StructType().Map = t
313 // methods returns the methods of the non-interface type t, sorted by name.
314 // Generates stub functions as needed.
315 func methods(t *types.Type) []*typeSig {
317 mt := types.ReceiverBaseType(t)
322 typecheck.CalcMethods(mt)
324 // type stored in interface word
327 if !types.IsDirectIface(it) {
331 // make list of methods for t,
332 // generating code if necessary.
334 for _, f := range mt.AllMethods().Slice() {
336 base.Fatalf("method with no sym on %v", mt)
339 base.Fatalf("non-method on %v method %v %v", mt, f.Sym, f)
341 if f.Type.Recv() == nil {
342 base.Fatalf("receiver with no type on %v method %v %v", mt, f.Sym, f)
348 // get receiver type for this particular method.
349 // if pointer receiver but non-pointer t and
350 // this is not an embedded pointer inside a struct,
351 // method does not apply.
352 if !types.IsMethodApplicable(t, f) {
358 isym: methodWrapper(it, f),
359 tsym: methodWrapper(t, f),
360 type_: typecheck.NewMethodType(f.Type, t),
361 mtype: typecheck.NewMethodType(f.Type, nil),
369 // imethods returns the methods of the interface type t, sorted by name.
370 func imethods(t *types.Type) []*typeSig {
371 var methods []*typeSig
372 for _, f := range t.AllMethods().Slice() {
373 if f.Type.Kind() != types.TFUNC || f.Sym == nil {
377 base.Fatalf("unexpected blank symbol in interface method set")
379 if n := len(methods); n > 0 {
381 if !last.name.Less(f.Sym) {
382 base.Fatalf("sigcmp vs sortinter %v %v", last.name, f.Sym)
389 type_: typecheck.NewMethodType(f.Type, nil),
391 methods = append(methods, sig)
393 // NOTE(rsc): Perhaps an oversight that
394 // IfaceType.Method is not in the reflect data.
395 // Generate the method body, so that compiled
396 // code can refer to it.
403 func dimportpath(p *types.Pkg) {
404 if p.Pathsym != nil {
408 // If we are compiling the runtime package, there are two runtime packages around
409 // -- localpkg and Pkgs.Runtime. We don't want to produce import path symbols for
410 // both of them, so just produce one for localpkg.
411 if base.Ctxt.Pkgpath == "runtime" && p == ir.Pkgs.Runtime {
416 if p == types.LocalPkg {
417 // Note: myimportpath != "", or else dgopkgpath won't call dimportpath.
418 str = base.Ctxt.Pkgpath
421 s := base.Ctxt.Lookup("type..importpath." + p.Prefix + ".")
422 ot := dnameData(s, 0, str, "", nil, false)
423 objw.Global(s, int32(ot), obj.DUPOK|obj.RODATA)
424 s.Set(obj.AttrContentAddressable, true)
428 func dgopkgpath(s *obj.LSym, ot int, pkg *types.Pkg) int {
430 return objw.Uintptr(s, ot, 0)
433 if pkg == types.LocalPkg && base.Ctxt.Pkgpath == "" {
434 // If we don't know the full import path of the package being compiled
435 // (i.e. -p was not passed on the compiler command line), emit a reference to
436 // type..importpath.""., which the linker will rewrite using the correct import path.
437 // Every package that imports this one directly defines the symbol.
438 // See also https://groups.google.com/forum/#!topic/golang-dev/myb9s53HxGQ.
439 ns := base.Ctxt.Lookup(`type..importpath."".`)
440 return objw.SymPtr(s, ot, ns, 0)
444 return objw.SymPtr(s, ot, pkg.Pathsym, 0)
447 // dgopkgpathOff writes an offset relocation in s at offset ot to the pkg path symbol.
448 func dgopkgpathOff(s *obj.LSym, ot int, pkg *types.Pkg) int {
450 return objw.Uint32(s, ot, 0)
452 if pkg == types.LocalPkg && base.Ctxt.Pkgpath == "" {
453 // If we don't know the full import path of the package being compiled
454 // (i.e. -p was not passed on the compiler command line), emit a reference to
455 // type..importpath.""., which the linker will rewrite using the correct import path.
456 // Every package that imports this one directly defines the symbol.
457 // See also https://groups.google.com/forum/#!topic/golang-dev/myb9s53HxGQ.
458 ns := base.Ctxt.Lookup(`type..importpath."".`)
459 return objw.SymPtrOff(s, ot, ns)
463 return objw.SymPtrOff(s, ot, pkg.Pathsym)
466 // dnameField dumps a reflect.name for a struct field.
467 func dnameField(lsym *obj.LSym, ot int, spkg *types.Pkg, ft *types.Field) int {
468 if !types.IsExported(ft.Sym.Name) && ft.Sym.Pkg != spkg {
469 base.Fatalf("package mismatch for %v", ft.Sym)
471 nsym := dname(ft.Sym.Name, ft.Note, nil, types.IsExported(ft.Sym.Name))
472 return objw.SymPtr(lsym, ot, nsym, 0)
475 // dnameData writes the contents of a reflect.name into s at offset ot.
476 func dnameData(s *obj.LSym, ot int, name, tag string, pkg *types.Pkg, exported bool) int {
477 if len(name) >= 1<<29 {
478 base.Fatalf("name too long: %d %s...", len(name), name[:1024])
480 if len(tag) >= 1<<29 {
481 base.Fatalf("tag too long: %d %s...", len(tag), tag[:1024])
483 var nameLen [binary.MaxVarintLen64]byte
484 nameLenLen := binary.PutUvarint(nameLen[:], uint64(len(name)))
485 var tagLen [binary.MaxVarintLen64]byte
486 tagLenLen := binary.PutUvarint(tagLen[:], uint64(len(tag)))
488 // Encode name and tag. See reflect/type.go for details.
490 l := 1 + nameLenLen + len(name)
495 l += tagLenLen + len(tag)
503 copy(b[1:], nameLen[:nameLenLen])
504 copy(b[1+nameLenLen:], name)
506 tb := b[1+nameLenLen+len(name):]
507 copy(tb, tagLen[:tagLenLen])
508 copy(tb[tagLenLen:], tag)
511 ot = int(s.WriteBytes(base.Ctxt, int64(ot), b))
514 ot = dgopkgpathOff(s, ot, pkg)
522 // dname creates a reflect.name for a struct field or method.
523 func dname(name, tag string, pkg *types.Pkg, exported bool) *obj.LSym {
524 // Write out data as "type.." to signal two things to the
525 // linker, first that when dynamically linking, the symbol
526 // should be moved to a relro section, and second that the
527 // contents should not be decoded as a type.
528 sname := "type..namedata."
530 // In the common case, share data with other packages.
533 sname += "-noname-exported." + tag
535 sname += "-noname-unexported." + tag
539 sname += name + "." + tag
541 sname += name + "-" + tag
545 sname = fmt.Sprintf(`%s"".%d`, sname, dnameCount)
548 s := base.Ctxt.Lookup(sname)
552 ot := dnameData(s, 0, name, tag, pkg, exported)
553 objw.Global(s, int32(ot), obj.DUPOK|obj.RODATA)
554 s.Set(obj.AttrContentAddressable, true)
558 // dextratype dumps the fields of a runtime.uncommontype.
559 // dataAdd is the offset in bytes after the header where the
560 // backing array of the []method field is written (by dextratypeData).
561 func dextratype(lsym *obj.LSym, ot int, t *types.Type, dataAdd int) int {
563 if t.Sym() == nil && len(m) == 0 {
566 noff := int(types.Rnd(int64(ot), int64(types.PtrSize)))
568 base.Fatalf("unexpected alignment in dextratype for %v", t)
571 for _, a := range m {
575 ot = dgopkgpathOff(lsym, ot, typePkg(t))
577 dataAdd += uncommonSize(t)
579 if mcount != int(uint16(mcount)) {
580 base.Fatalf("too many methods on %v: %d", t, mcount)
582 xcount := sort.Search(mcount, func(i int) bool { return !types.IsExported(m[i].name.Name) })
583 if dataAdd != int(uint32(dataAdd)) {
584 base.Fatalf("methods are too far away on %v: %d", t, dataAdd)
587 ot = objw.Uint16(lsym, ot, uint16(mcount))
588 ot = objw.Uint16(lsym, ot, uint16(xcount))
589 ot = objw.Uint32(lsym, ot, uint32(dataAdd))
590 ot = objw.Uint32(lsym, ot, 0)
594 func typePkg(t *types.Type) *types.Pkg {
598 case types.TARRAY, types.TSLICE, types.TPTR, types.TCHAN:
600 tsym = t.Elem().Sym()
604 if tsym != nil && tsym.Pkg != types.BuiltinPkg {
610 // dextratypeData dumps the backing array for the []method field of
611 // runtime.uncommontype.
612 func dextratypeData(lsym *obj.LSym, ot int, t *types.Type) int {
613 for _, a := range methods(t) {
614 // ../../../../runtime/type.go:/method
615 exported := types.IsExported(a.name.Name)
617 if !exported && a.name.Pkg != typePkg(t) {
620 nsym := dname(a.name.Name, "", pkg, exported)
622 ot = objw.SymPtrOff(lsym, ot, nsym)
623 ot = dmethodptrOff(lsym, ot, writeType(a.mtype))
624 ot = dmethodptrOff(lsym, ot, a.isym)
625 ot = dmethodptrOff(lsym, ot, a.tsym)
630 func dmethodptrOff(s *obj.LSym, ot int, x *obj.LSym) int {
631 objw.Uint32(s, ot, 0)
636 r.Type = objabi.R_METHODOFF
641 types.TINT: objabi.KindInt,
642 types.TUINT: objabi.KindUint,
643 types.TINT8: objabi.KindInt8,
644 types.TUINT8: objabi.KindUint8,
645 types.TINT16: objabi.KindInt16,
646 types.TUINT16: objabi.KindUint16,
647 types.TINT32: objabi.KindInt32,
648 types.TUINT32: objabi.KindUint32,
649 types.TINT64: objabi.KindInt64,
650 types.TUINT64: objabi.KindUint64,
651 types.TUINTPTR: objabi.KindUintptr,
652 types.TFLOAT32: objabi.KindFloat32,
653 types.TFLOAT64: objabi.KindFloat64,
654 types.TBOOL: objabi.KindBool,
655 types.TSTRING: objabi.KindString,
656 types.TPTR: objabi.KindPtr,
657 types.TSTRUCT: objabi.KindStruct,
658 types.TINTER: objabi.KindInterface,
659 types.TCHAN: objabi.KindChan,
660 types.TMAP: objabi.KindMap,
661 types.TARRAY: objabi.KindArray,
662 types.TSLICE: objabi.KindSlice,
663 types.TFUNC: objabi.KindFunc,
664 types.TCOMPLEX64: objabi.KindComplex64,
665 types.TCOMPLEX128: objabi.KindComplex128,
666 types.TUNSAFEPTR: objabi.KindUnsafePointer,
669 // tflag is documented in reflect/type.go.
671 // tflag values must be kept in sync with copies in:
672 // cmd/compile/internal/gc/reflect.go
673 // cmd/link/internal/ld/decodesym.go
677 tflagUncommon = 1 << 0
678 tflagExtraStar = 1 << 1
680 tflagRegularMemory = 1 << 3
684 memhashvarlen *obj.LSym
685 memequalvarlen *obj.LSym
688 // dcommontype dumps the contents of a reflect.rtype (runtime._type).
689 func dcommontype(lsym *obj.LSym, t *types.Type) int {
695 if !t.IsPtr() || t.IsPtrElem() {
696 tptr := types.NewPtr(t)
697 if t.Sym() != nil || methods(tptr) != nil {
700 sptr = writeType(tptr)
703 gcsym, useGCProg, ptrdata := dgcsym(t, true)
706 // ../../../../reflect/type.go:/^type.rtype
707 // actual type structure
708 // type rtype struct {
716 // equal func(unsafe.Pointer, unsafe.Pointer) bool
722 ot = objw.Uintptr(lsym, ot, uint64(t.Width))
723 ot = objw.Uintptr(lsym, ot, uint64(ptrdata))
724 ot = objw.Uint32(lsym, ot, types.TypeHash(t))
727 if uncommonSize(t) != 0 {
728 tflag |= tflagUncommon
730 if t.Sym() != nil && t.Sym().Name != "" {
733 if isRegularMemory(t) {
734 tflag |= tflagRegularMemory
739 // If we're writing out type T,
740 // we are very likely to write out type *T as well.
741 // Use the string "*T"[1:] for "T", so that the two
742 // share storage. This is a cheap way to reduce the
743 // amount of space taken up by reflect strings.
744 if !strings.HasPrefix(p, "*") {
746 tflag |= tflagExtraStar
748 exported = types.IsExported(t.Sym().Name)
751 if t.Elem() != nil && t.Elem().Sym() != nil {
752 exported = types.IsExported(t.Elem().Sym().Name)
756 ot = objw.Uint8(lsym, ot, tflag)
758 // runtime (and common sense) expects alignment to be a power of two.
765 base.Fatalf("invalid alignment %d for %v", t.Align, t)
767 ot = objw.Uint8(lsym, ot, t.Align) // align
768 ot = objw.Uint8(lsym, ot, t.Align) // fieldAlign
771 if types.IsDirectIface(t) {
772 i |= objabi.KindDirectIface
775 i |= objabi.KindGCProg
777 ot = objw.Uint8(lsym, ot, uint8(i)) // kind
779 ot = objw.SymPtr(lsym, ot, eqfunc, 0) // equality function
781 ot = objw.Uintptr(lsym, ot, 0) // type we can't do == with
783 ot = objw.SymPtr(lsym, ot, gcsym, 0) // gcdata
785 nsym := dname(p, "", nil, exported)
786 ot = objw.SymPtrOff(lsym, ot, nsym) // str
789 ot = objw.Uint32(lsym, ot, 0)
791 ot = objw.SymPtrWeakOff(lsym, ot, sptr)
793 ot = objw.SymPtrOff(lsym, ot, sptr)
799 // TrackSym returns the symbol for tracking use of field/method f, assumed
800 // to be a member of struct/interface type t.
801 func TrackSym(t *types.Type, f *types.Field) *obj.LSym {
802 return base.PkgLinksym("go.track", t.ShortString()+"."+f.Sym.Name, obj.ABI0)
805 func TypeSymPrefix(prefix string, t *types.Type) *types.Sym {
806 p := prefix + "." + t.ShortString()
807 s := types.TypeSymLookup(p)
809 // This function is for looking up type-related generated functions
810 // (e.g. eq and hash). Make sure they are indeed generated.
815 //print("algsym: %s -> %+S\n", p, s);
820 func TypeSym(t *types.Type) *types.Sym {
821 if t == nil || (t.IsPtr() && t.Elem() == nil) || t.IsUntyped() {
822 base.Fatalf("TypeSym %v", t)
824 if t.Kind() == types.TFUNC && t.Recv() != nil {
825 base.Fatalf("misuse of method type: %v", t)
827 s := types.TypeSym(t)
834 func TypeLinksymPrefix(prefix string, t *types.Type) *obj.LSym {
835 return TypeSymPrefix(prefix, t).Linksym()
838 func TypeLinksymLookup(name string) *obj.LSym {
839 return types.TypeSymLookup(name).Linksym()
842 func TypeLinksym(t *types.Type) *obj.LSym {
843 return TypeSym(t).Linksym()
846 func TypePtr(t *types.Type) *ir.AddrExpr {
847 n := ir.NewLinksymExpr(base.Pos, TypeLinksym(t), types.Types[types.TUINT8])
848 return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
851 func ITabAddr(t, itype *types.Type) *ir.AddrExpr {
852 if t == nil || (t.IsPtr() && t.Elem() == nil) || t.IsUntyped() || !itype.IsInterface() || itype.IsEmptyInterface() {
853 base.Fatalf("ITabAddr(%v, %v)", t, itype)
855 s, existed := ir.Pkgs.Itab.LookupOK(t.ShortString() + "," + itype.ShortString())
857 itabs = append(itabs, itabEntry{t: t, itype: itype, lsym: s.Linksym()})
861 n := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
862 return typecheck.Expr(typecheck.NodAddr(n)).(*ir.AddrExpr)
865 // needkeyupdate reports whether map updates with t as a key
866 // need the key to be updated.
867 func needkeyupdate(t *types.Type) bool {
869 case types.TBOOL, types.TINT, types.TUINT, types.TINT8, types.TUINT8, types.TINT16, types.TUINT16, types.TINT32, types.TUINT32,
870 types.TINT64, types.TUINT64, types.TUINTPTR, types.TPTR, types.TUNSAFEPTR, types.TCHAN:
873 case types.TFLOAT32, types.TFLOAT64, types.TCOMPLEX64, types.TCOMPLEX128, // floats and complex can be +0/-0
875 types.TSTRING: // strings might have smaller backing stores
879 return needkeyupdate(t.Elem())
882 for _, t1 := range t.Fields().Slice() {
883 if needkeyupdate(t1.Type) {
890 base.Fatalf("bad type for map key: %v", t)
895 // hashMightPanic reports whether the hash of a map key of type t might panic.
896 func hashMightPanic(t *types.Type) bool {
902 return hashMightPanic(t.Elem())
905 for _, t1 := range t.Fields().Slice() {
906 if hashMightPanic(t1.Type) {
917 // formalType replaces byte and rune aliases with real types.
918 // They've been separate internally to make error messages
919 // better, but we have to merge them in the reflect tables.
920 func formalType(t *types.Type) *types.Type {
921 if t == types.ByteType || t == types.RuneType {
922 return types.Types[t.Kind()]
927 func writeType(t *types.Type) *obj.LSym {
930 base.Fatalf("writeType %v", t)
933 s := types.TypeSym(t)
940 // special case (look for runtime below):
941 // when compiling package runtime,
942 // emit the type structures for int, float, etc.
945 if t.IsPtr() && t.Sym() == nil && t.Elem().Sym() != nil {
949 if tbase.Sym() == nil {
953 if base.Ctxt.Pkgpath != "runtime" || (tbase != types.Types[tbase.Kind()] && tbase != types.ByteType && tbase != types.RuneType && tbase != types.ErrorType) { // int, float, etc
954 // Named types from other files are defined only by those files.
955 // However, as an exception, we can write out instantiated types
956 // in the local package, even if they may be marked as part of
957 // another package (the package of their base generic type).
958 if tbase.Sym() != nil && tbase.Sym().Pkg != types.LocalPkg &&
959 len(tbase.RParams()) == 0 {
960 if i := typecheck.BaseTypeIndex(t); i >= 0 {
961 lsym.Pkg = tbase.Sym().Pkg.Prefix
962 lsym.SymIdx = int32(i)
963 lsym.Set(obj.AttrIndexed, true)
967 // TODO(mdempsky): Investigate whether this can happen.
968 if tbase.Kind() == types.TFORW {
976 ot = dcommontype(lsym, t)
977 ot = dextratype(lsym, ot, t, 0)
980 // ../../../../runtime/type.go:/arrayType
981 s1 := writeType(t.Elem())
982 t2 := types.NewSlice(t.Elem())
984 ot = dcommontype(lsym, t)
985 ot = objw.SymPtr(lsym, ot, s1, 0)
986 ot = objw.SymPtr(lsym, ot, s2, 0)
987 ot = objw.Uintptr(lsym, ot, uint64(t.NumElem()))
988 ot = dextratype(lsym, ot, t, 0)
991 // ../../../../runtime/type.go:/sliceType
992 s1 := writeType(t.Elem())
993 ot = dcommontype(lsym, t)
994 ot = objw.SymPtr(lsym, ot, s1, 0)
995 ot = dextratype(lsym, ot, t, 0)
998 // ../../../../runtime/type.go:/chanType
999 s1 := writeType(t.Elem())
1000 ot = dcommontype(lsym, t)
1001 ot = objw.SymPtr(lsym, ot, s1, 0)
1002 ot = objw.Uintptr(lsym, ot, uint64(t.ChanDir()))
1003 ot = dextratype(lsym, ot, t, 0)
1006 for _, t1 := range t.Recvs().Fields().Slice() {
1010 for _, t1 := range t.Params().Fields().Slice() {
1014 for _, t1 := range t.Results().Fields().Slice() {
1018 ot = dcommontype(lsym, t)
1019 inCount := t.NumRecvs() + t.NumParams()
1020 outCount := t.NumResults()
1024 ot = objw.Uint16(lsym, ot, uint16(inCount))
1025 ot = objw.Uint16(lsym, ot, uint16(outCount))
1026 if types.PtrSize == 8 {
1027 ot += 4 // align for *rtype
1030 dataAdd := (inCount + t.NumResults()) * types.PtrSize
1031 ot = dextratype(lsym, ot, t, dataAdd)
1033 // Array of rtype pointers follows funcType.
1034 for _, t1 := range t.Recvs().Fields().Slice() {
1035 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1037 for _, t1 := range t.Params().Fields().Slice() {
1038 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1040 for _, t1 := range t.Results().Fields().Slice() {
1041 ot = objw.SymPtr(lsym, ot, writeType(t1.Type), 0)
1047 for _, a := range m {
1051 // ../../../../runtime/type.go:/interfaceType
1052 ot = dcommontype(lsym, t)
1055 if t.Sym() != nil && t != types.Types[t.Kind()] && t != types.ErrorType {
1058 ot = dgopkgpath(lsym, ot, tpkg)
1060 ot = objw.SymPtr(lsym, ot, lsym, ot+3*types.PtrSize+uncommonSize(t))
1061 ot = objw.Uintptr(lsym, ot, uint64(n))
1062 ot = objw.Uintptr(lsym, ot, uint64(n))
1063 dataAdd := imethodSize() * n
1064 ot = dextratype(lsym, ot, t, dataAdd)
1066 for _, a := range m {
1067 // ../../../../runtime/type.go:/imethod
1068 exported := types.IsExported(a.name.Name)
1070 if !exported && a.name.Pkg != tpkg {
1073 nsym := dname(a.name.Name, "", pkg, exported)
1075 ot = objw.SymPtrOff(lsym, ot, nsym)
1076 ot = objw.SymPtrOff(lsym, ot, writeType(a.type_))
1079 // ../../../../runtime/type.go:/mapType
1081 s1 := writeType(t.Key())
1082 s2 := writeType(t.Elem())
1083 s3 := writeType(MapBucketType(t))
1084 hasher := genhash(t.Key())
1086 ot = dcommontype(lsym, t)
1087 ot = objw.SymPtr(lsym, ot, s1, 0)
1088 ot = objw.SymPtr(lsym, ot, s2, 0)
1089 ot = objw.SymPtr(lsym, ot, s3, 0)
1090 ot = objw.SymPtr(lsym, ot, hasher, 0)
1092 // Note: flags must match maptype accessors in ../../../../runtime/type.go
1093 // and maptype builder in ../../../../reflect/type.go:MapOf.
1094 if t.Key().Width > MAXKEYSIZE {
1095 ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1096 flags |= 1 // indirect key
1098 ot = objw.Uint8(lsym, ot, uint8(t.Key().Width))
1101 if t.Elem().Width > MAXELEMSIZE {
1102 ot = objw.Uint8(lsym, ot, uint8(types.PtrSize))
1103 flags |= 2 // indirect value
1105 ot = objw.Uint8(lsym, ot, uint8(t.Elem().Width))
1107 ot = objw.Uint16(lsym, ot, uint16(MapBucketType(t).Width))
1108 if types.IsReflexive(t.Key()) {
1109 flags |= 4 // reflexive key
1111 if needkeyupdate(t.Key()) {
1112 flags |= 8 // need key update
1114 if hashMightPanic(t.Key()) {
1115 flags |= 16 // hash might panic
1117 ot = objw.Uint32(lsym, ot, flags)
1118 ot = dextratype(lsym, ot, t, 0)
1119 if u := t.Underlying(); u != t {
1120 // If t is a named map type, also keep the underlying map
1121 // type live in the binary. This is important to make sure that
1122 // a named map and that same map cast to its underlying type via
1123 // reflection, use the same hash function. See issue 37716.
1124 r := obj.Addrel(lsym)
1125 r.Sym = writeType(u)
1126 r.Type = objabi.R_KEEP
1130 if t.Elem().Kind() == types.TANY {
1131 // ../../../../runtime/type.go:/UnsafePointerType
1132 ot = dcommontype(lsym, t)
1133 ot = dextratype(lsym, ot, t, 0)
1138 // ../../../../runtime/type.go:/ptrType
1139 s1 := writeType(t.Elem())
1141 ot = dcommontype(lsym, t)
1142 ot = objw.SymPtr(lsym, ot, s1, 0)
1143 ot = dextratype(lsym, ot, t, 0)
1145 // ../../../../runtime/type.go:/structType
1146 // for security, only the exported fields.
1148 fields := t.Fields().Slice()
1149 for _, t1 := range fields {
1153 // All non-exported struct field names within a struct
1154 // type must originate from a single package. By
1155 // identifying and recording that package within the
1156 // struct type descriptor, we can omit that
1157 // information from the field descriptors.
1159 for _, f := range fields {
1160 if !types.IsExported(f.Sym.Name) {
1166 ot = dcommontype(lsym, t)
1167 ot = dgopkgpath(lsym, ot, spkg)
1168 ot = objw.SymPtr(lsym, ot, lsym, ot+3*types.PtrSize+uncommonSize(t))
1169 ot = objw.Uintptr(lsym, ot, uint64(len(fields)))
1170 ot = objw.Uintptr(lsym, ot, uint64(len(fields)))
1172 dataAdd := len(fields) * structfieldSize()
1173 ot = dextratype(lsym, ot, t, dataAdd)
1175 for _, f := range fields {
1176 // ../../../../runtime/type.go:/structField
1177 ot = dnameField(lsym, ot, spkg, f)
1178 ot = objw.SymPtr(lsym, ot, writeType(f.Type), 0)
1179 offsetAnon := uint64(f.Offset) << 1
1180 if offsetAnon>>1 != uint64(f.Offset) {
1181 base.Fatalf("%v: bad field offset for %s", t, f.Sym.Name)
1183 if f.Embedded != 0 {
1186 ot = objw.Uintptr(lsym, ot, offsetAnon)
1190 ot = dextratypeData(lsym, ot, t)
1191 objw.Global(lsym, int32(ot), int16(dupok|obj.RODATA))
1193 // The linker will leave a table of all the typelinks for
1194 // types in the binary, so the runtime can find them.
1196 // When buildmode=shared, all types are in typelinks so the
1197 // runtime can deduplicate type pointers.
1198 keep := base.Ctxt.Flag_dynlink
1199 if !keep && t.Sym() == nil {
1200 // For an unnamed type, we only need the link if the type can
1201 // be created at run time by reflect.PtrTo and similar
1202 // functions. If the type exists in the program, those
1203 // functions must return the existing type structure rather
1204 // than creating a new one.
1206 case types.TPTR, types.TARRAY, types.TCHAN, types.TFUNC, types.TMAP, types.TSLICE, types.TSTRUCT:
1210 // Do not put Noalg types in typelinks. See issue #22605.
1211 if types.TypeHasNoAlg(t) {
1214 lsym.Set(obj.AttrMakeTypelink, keep)
1219 // InterfaceMethodOffset returns the offset of the i-th method in the interface
1220 // type descriptor, ityp.
1221 func InterfaceMethodOffset(ityp *types.Type, i int64) int64 {
1222 // interface type descriptor layout is struct {
1223 // _type // commonSize
1224 // pkgpath // 1 word
1225 // []imethod // 3 words (pointing to [...]imethod below)
1226 // uncommontype // uncommonSize
1229 // The size of imethod is 8.
1230 return int64(commonSize()+4*types.PtrSize+uncommonSize(ityp)) + i*8
1233 // for each itabEntry, gather the methods on
1234 // the concrete type that implement the interface
1235 func CompileITabs() {
1236 for i := range itabs {
1238 methods := genfun(tab.t, tab.itype)
1239 if len(methods) == 0 {
1242 tab.entries = methods
1246 // for the given concrete type and interface
1247 // type, return the (sorted) set of methods
1248 // on the concrete type that implement the interface
1249 func genfun(t, it *types.Type) []*obj.LSym {
1250 if t == nil || it == nil {
1253 sigs := imethods(it)
1254 methods := methods(t)
1255 out := make([]*obj.LSym, 0, len(sigs))
1256 // TODO(mdempsky): Short circuit before calling methods(t)?
1257 // See discussion on CL 105039.
1262 // both sigs and methods are sorted by name,
1263 // so we can find the intersect in a single pass
1264 for _, m := range methods {
1265 if m.name == sigs[0].name {
1266 out = append(out, m.isym)
1275 base.Fatalf("incomplete itab")
1281 // ITabSym uses the information gathered in
1282 // CompileITabs to de-virtualize interface methods.
1283 // Since this is called by the SSA backend, it shouldn't
1284 // generate additional Nodes, Syms, etc.
1285 func ITabSym(it *obj.LSym, offset int64) *obj.LSym {
1286 var syms []*obj.LSym
1291 for i := range itabs {
1302 // keep this arithmetic in sync with *itab layout
1303 methodnum := int((offset - 2*int64(types.PtrSize) - 8) / int64(types.PtrSize))
1304 if methodnum >= len(syms) {
1307 return syms[methodnum]
1310 // NeedRuntimeType ensures that a runtime type descriptor is emitted for t.
1311 func NeedRuntimeType(t *types.Type) {
1313 // Generic types don't have a runtime type descriptor (but will
1314 // have a dictionary)
1317 if _, ok := signatset[t]; !ok {
1318 signatset[t] = struct{}{}
1319 signatslice = append(signatslice, t)
1323 func WriteRuntimeTypes() {
1324 // Process signatset. Use a loop, as writeType adds
1325 // entries to signatset while it is being processed.
1326 signats := make([]typeAndStr, len(signatslice))
1327 for len(signatslice) > 0 {
1328 signats = signats[:0]
1329 // Transfer entries to a slice and sort, for reproducible builds.
1330 for _, t := range signatslice {
1331 signats = append(signats, typeAndStr{t: t, short: types.TypeSymName(t), regular: t.String()})
1332 delete(signatset, t)
1334 signatslice = signatslice[:0]
1335 sort.Sort(typesByString(signats))
1336 for _, ts := range signats {
1340 writeType(types.NewPtr(t))
1345 // Emit GC data symbols.
1346 gcsyms := make([]typeAndStr, 0, len(gcsymset))
1347 for t := range gcsymset {
1348 gcsyms = append(gcsyms, typeAndStr{t: t, short: types.TypeSymName(t), regular: t.String()})
1350 sort.Sort(typesByString(gcsyms))
1351 for _, ts := range gcsyms {
1358 for _, i := range itabs {
1359 // dump empty itab symbol into i.sym
1360 // type itab struct {
1361 // inter *interfacetype
1365 // fun [1]uintptr // variable sized
1367 o := objw.SymPtr(i.lsym, 0, writeType(i.itype), 0)
1368 o = objw.SymPtr(i.lsym, o, writeType(i.t), 0)
1369 o = objw.Uint32(i.lsym, o, types.TypeHash(i.t)) // copy of type hash
1370 o += 4 // skip unused field
1371 for _, fn := range genfun(i.t, i.itype) {
1372 o = objw.SymPtrWeak(i.lsym, o, fn, 0) // method pointer for each method
1374 // Nothing writes static itabs, so they are read only.
1375 objw.Global(i.lsym, int32(o), int16(obj.DUPOK|obj.RODATA))
1376 i.lsym.Set(obj.AttrContentAddressable, true)
1380 if types.LocalPkg.Name == "main" && len(ptabs) > 0 {
1382 s := base.Ctxt.Lookup("go.plugin.tabs")
1383 for _, p := range ptabs {
1384 // Dump ptab symbol into go.pluginsym package.
1386 // type ptab struct {
1388 // typ typeOff // pointer to symbol
1390 nsym := dname(p.Sym().Name, "", nil, true)
1392 if p.Class != ir.PFUNC {
1395 tsym := writeType(t)
1396 ot = objw.SymPtrOff(s, ot, nsym)
1397 ot = objw.SymPtrOff(s, ot, tsym)
1398 // Plugin exports symbols as interfaces. Mark their types
1400 tsym.Set(obj.AttrUsedInIface, true)
1402 objw.Global(s, int32(ot), int16(obj.RODATA))
1405 s = base.Ctxt.Lookup("go.plugin.exports")
1406 for _, p := range ptabs {
1407 ot = objw.SymPtr(s, ot, p.Linksym(), 0)
1409 objw.Global(s, int32(ot), int16(obj.RODATA))
1413 func WriteImportStrings() {
1414 // generate import strings for imported packages
1415 for _, p := range types.ImportedPkgList() {
1420 func WriteBasicTypes() {
1421 // do basic types if compiling package runtime.
1422 // they have to be in at least one package,
1423 // and runtime is always loaded implicitly,
1424 // so this is as good as any.
1425 // another possible choice would be package main,
1426 // but using runtime means fewer copies in object files.
1427 if base.Ctxt.Pkgpath == "runtime" {
1428 for i := types.Kind(1); i <= types.TBOOL; i++ {
1429 writeType(types.NewPtr(types.Types[i]))
1431 writeType(types.NewPtr(types.Types[types.TSTRING]))
1432 writeType(types.NewPtr(types.Types[types.TUNSAFEPTR]))
1434 // emit type structs for error and func(error) string.
1435 // The latter is the type of an auto-generated wrapper.
1436 writeType(types.NewPtr(types.ErrorType))
1438 writeType(types.NewSignature(types.NoPkg, nil, nil, []*types.Field{
1439 types.NewField(base.Pos, nil, types.ErrorType),
1441 types.NewField(base.Pos, nil, types.Types[types.TSTRING]),
1444 // add paths for runtime and main, which 6l imports implicitly.
1445 dimportpath(ir.Pkgs.Runtime)
1448 dimportpath(types.NewPkg("runtime/race", ""))
1451 dimportpath(types.NewPkg("runtime/msan", ""))
1454 dimportpath(types.NewPkg("main", ""))
1458 type typeAndStr struct {
1464 type typesByString []typeAndStr
1466 func (a typesByString) Len() int { return len(a) }
1467 func (a typesByString) Less(i, j int) bool {
1468 if a[i].short != a[j].short {
1469 return a[i].short < a[j].short
1471 // When the only difference between the types is whether
1472 // they refer to byte or uint8, such as **byte vs **uint8,
1473 // the types' ShortStrings can be identical.
1474 // To preserve deterministic sort ordering, sort these by String().
1475 if a[i].regular != a[j].regular {
1476 return a[i].regular < a[j].regular
1478 // Identical anonymous interfaces defined in different locations
1479 // will be equal for the above checks, but different in DWARF output.
1480 // Sort by source position to ensure deterministic order.
1481 // See issues 27013 and 30202.
1482 if a[i].t.Kind() == types.TINTER && a[i].t.Methods().Len() > 0 {
1483 return a[i].t.Methods().Index(0).Pos.Before(a[j].t.Methods().Index(0).Pos)
1487 func (a typesByString) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
1489 // maxPtrmaskBytes is the maximum length of a GC ptrmask bitmap,
1490 // which holds 1-bit entries describing where pointers are in a given type.
1491 // Above this length, the GC information is recorded as a GC program,
1492 // which can express repetition compactly. In either form, the
1493 // information is used by the runtime to initialize the heap bitmap,
1494 // and for large types (like 128 or more words), they are roughly the
1495 // same speed. GC programs are never much larger and often more
1496 // compact. (If large arrays are involved, they can be arbitrarily
1499 // The cutoff must be large enough that any allocation large enough to
1500 // use a GC program is large enough that it does not share heap bitmap
1501 // bytes with any other objects, allowing the GC program execution to
1502 // assume an aligned start and not use atomic operations. In the current
1503 // runtime, this means all malloc size classes larger than the cutoff must
1504 // be multiples of four words. On 32-bit systems that's 16 bytes, and
1505 // all size classes >= 16 bytes are 16-byte aligned, so no real constraint.
1506 // On 64-bit systems, that's 32 bytes, and 32-byte alignment is guaranteed
1507 // for size classes >= 256 bytes. On a 64-bit system, 256 bytes allocated
1508 // is 32 pointers, the bits for which fit in 4 bytes. So maxPtrmaskBytes
1511 // We used to use 16 because the GC programs do have some constant overhead
1512 // to get started, and processing 128 pointers seems to be enough to
1513 // amortize that overhead well.
1515 // To make sure that the runtime's chansend can call typeBitsBulkBarrier,
1516 // we raised the limit to 2048, so that even 32-bit systems are guaranteed to
1517 // use bitmaps for objects up to 64 kB in size.
1519 // Also known to reflect/type.go.
1521 const maxPtrmaskBytes = 2048
1523 // GCSym returns a data symbol containing GC information for type t, along
1524 // with a boolean reporting whether the UseGCProg bit should be set in the
1525 // type kind, and the ptrdata field to record in the reflect type information.
1526 // GCSym may be called in concurrent backend, so it does not emit the symbol
1528 func GCSym(t *types.Type) (lsym *obj.LSym, useGCProg bool, ptrdata int64) {
1529 // Record that we need to emit the GC symbol.
1531 if _, ok := gcsymset[t]; !ok {
1532 gcsymset[t] = struct{}{}
1536 return dgcsym(t, false)
1539 // dgcsym returns a data symbol containing GC information for type t, along
1540 // with a boolean reporting whether the UseGCProg bit should be set in the
1541 // type kind, and the ptrdata field to record in the reflect type information.
1542 // When write is true, it writes the symbol data.
1543 func dgcsym(t *types.Type, write bool) (lsym *obj.LSym, useGCProg bool, ptrdata int64) {
1544 ptrdata = types.PtrDataSize(t)
1545 if ptrdata/int64(types.PtrSize) <= maxPtrmaskBytes*8 {
1546 lsym = dgcptrmask(t, write)
1551 lsym, ptrdata = dgcprog(t, write)
1555 // dgcptrmask emits and returns the symbol containing a pointer mask for type t.
1556 func dgcptrmask(t *types.Type, write bool) *obj.LSym {
1557 ptrmask := make([]byte, (types.PtrDataSize(t)/int64(types.PtrSize)+7)/8)
1558 fillptrmask(t, ptrmask)
1559 p := fmt.Sprintf("runtime.gcbits.%x", ptrmask)
1561 lsym := base.Ctxt.Lookup(p)
1562 if write && !lsym.OnList() {
1563 for i, x := range ptrmask {
1564 objw.Uint8(lsym, i, x)
1566 objw.Global(lsym, int32(len(ptrmask)), obj.DUPOK|obj.RODATA|obj.LOCAL)
1567 lsym.Set(obj.AttrContentAddressable, true)
1572 // fillptrmask fills in ptrmask with 1s corresponding to the
1573 // word offsets in t that hold pointers.
1574 // ptrmask is assumed to fit at least types.PtrDataSize(t)/PtrSize bits.
1575 func fillptrmask(t *types.Type, ptrmask []byte) {
1576 for i := range ptrmask {
1579 if !t.HasPointers() {
1583 vec := bitvec.New(8 * int32(len(ptrmask)))
1584 typebits.Set(t, 0, vec)
1586 nptr := types.PtrDataSize(t) / int64(types.PtrSize)
1587 for i := int64(0); i < nptr; i++ {
1588 if vec.Get(int32(i)) {
1589 ptrmask[i/8] |= 1 << (uint(i) % 8)
1594 // dgcprog emits and returns the symbol containing a GC program for type t
1595 // along with the size of the data described by the program (in the range
1596 // [types.PtrDataSize(t), t.Width]).
1597 // In practice, the size is types.PtrDataSize(t) except for non-trivial arrays.
1598 // For non-trivial arrays, the program describes the full t.Width size.
1599 func dgcprog(t *types.Type, write bool) (*obj.LSym, int64) {
1601 if t.Width == types.BADWIDTH {
1602 base.Fatalf("dgcprog: %v badwidth", t)
1604 lsym := TypeLinksymPrefix(".gcprog", t)
1608 offset := p.w.BitIndex() * int64(types.PtrSize)
1610 if ptrdata := types.PtrDataSize(t); offset < ptrdata || offset > t.Width {
1611 base.Fatalf("dgcprog: %v: offset=%d but ptrdata=%d size=%d", t, offset, ptrdata, t.Width)
1616 type gcProg struct {
1623 func (p *gcProg) init(lsym *obj.LSym, write bool) {
1625 p.write = write && !lsym.OnList()
1626 p.symoff = 4 // first 4 bytes hold program length
1628 p.w.Init(func(byte) {})
1631 p.w.Init(p.writeByte)
1632 if base.Debug.GCProg > 0 {
1633 fmt.Fprintf(os.Stderr, "compile: start GCProg for %v\n", lsym)
1634 p.w.Debug(os.Stderr)
1638 func (p *gcProg) writeByte(x byte) {
1639 p.symoff = objw.Uint8(p.lsym, p.symoff, x)
1642 func (p *gcProg) end() {
1647 objw.Uint32(p.lsym, 0, uint32(p.symoff-4))
1648 objw.Global(p.lsym, int32(p.symoff), obj.DUPOK|obj.RODATA|obj.LOCAL)
1649 p.lsym.Set(obj.AttrContentAddressable, true)
1650 if base.Debug.GCProg > 0 {
1651 fmt.Fprintf(os.Stderr, "compile: end GCProg for %v\n", p.lsym)
1655 func (p *gcProg) emit(t *types.Type, offset int64) {
1657 if !t.HasPointers() {
1660 if t.Width == int64(types.PtrSize) {
1661 p.w.Ptr(offset / int64(types.PtrSize))
1666 base.Fatalf("gcProg.emit: unexpected type %v", t)
1669 p.w.Ptr(offset / int64(types.PtrSize))
1672 // Note: the first word isn't a pointer. See comment in typebits.Set
1673 p.w.Ptr(offset/int64(types.PtrSize) + 1)
1676 p.w.Ptr(offset / int64(types.PtrSize))
1679 if t.NumElem() == 0 {
1680 // should have been handled by haspointers check above
1681 base.Fatalf("gcProg.emit: empty array")
1684 // Flatten array-of-array-of-array to just a big array by multiplying counts.
1685 count := t.NumElem()
1687 for elem.IsArray() {
1688 count *= elem.NumElem()
1692 if !p.w.ShouldRepeat(elem.Width/int64(types.PtrSize), count) {
1693 // Cheaper to just emit the bits.
1694 for i := int64(0); i < count; i++ {
1695 p.emit(elem, offset+i*elem.Width)
1699 p.emit(elem, offset)
1700 p.w.ZeroUntil((offset + elem.Width) / int64(types.PtrSize))
1701 p.w.Repeat(elem.Width/int64(types.PtrSize), count-1)
1704 for _, t1 := range t.Fields().Slice() {
1705 p.emit(t1.Type, offset+t1.Offset)
1710 // ZeroAddr returns the address of a symbol with at least
1711 // size bytes of zeros.
1712 func ZeroAddr(size int64) ir.Node {
1714 base.Fatalf("map elem too big %d", size)
1716 if ZeroSize < size {
1719 lsym := base.PkgLinksym("go.map", "zero", obj.ABI0)
1720 x := ir.NewLinksymExpr(base.Pos, lsym, types.Types[types.TUINT8])
1721 return typecheck.Expr(typecheck.NodAddr(x))
1724 func CollectPTabs() {
1725 if !base.Ctxt.Flag_dynlink || types.LocalPkg.Name != "main" {
1728 for _, exportn := range typecheck.Target.Exports {
1730 nn := ir.AsNode(s.Def)
1734 if nn.Op() != ir.ONAME {
1738 if !types.IsExported(s.Name) {
1741 if s.Pkg.Name != "main" {
1744 ptabs = append(ptabs, n)
1748 // Generate a wrapper function to convert from
1749 // a receiver of type T to a receiver of type U.
1756 // already exists; this function generates
1762 // where the types T and U are such that u.M() is valid
1763 // and calls the T.M method.
1764 // The resulting function is for use in method tables.
1767 // method - M func (t T)(), a TFIELD type struct
1768 func methodWrapper(rcvr *types.Type, method *types.Field) *obj.LSym {
1769 newnam := ir.MethodSym(rcvr, method.Sym)
1770 lsym := newnam.Linksym()
1771 if newnam.Siggen() {
1774 newnam.SetSiggen(true)
1776 if types.Identical(rcvr, method.Type.Recv().Type) {
1780 // Only generate (*T).M wrappers for T.M in T's own package.
1781 if rcvr.IsPtr() && rcvr.Elem() == method.Type.Recv().Type &&
1782 rcvr.Elem().Sym() != nil && rcvr.Elem().Sym().Pkg != types.LocalPkg {
1786 // Only generate I.M wrappers for I in I's own package
1787 // but keep doing it for error.Error (was issue #29304).
1788 if rcvr.IsInterface() && rcvr.Sym() != nil && rcvr.Sym().Pkg != types.LocalPkg && rcvr != types.ErrorType {
1792 base.Pos = base.AutogeneratedPos
1793 typecheck.DeclContext = ir.PEXTERN
1795 tfn := ir.NewFuncType(base.Pos,
1796 ir.NewField(base.Pos, typecheck.Lookup(".this"), nil, rcvr),
1797 typecheck.NewFuncParams(method.Type.Params(), true),
1798 typecheck.NewFuncParams(method.Type.Results(), false))
1800 // TODO(austin): SelectorExpr may have created one or more
1801 // ir.Names for these already with a nil Func field. We should
1802 // consolidate these and always attach a Func to the Name.
1803 fn := typecheck.DeclFunc(newnam, tfn)
1806 nthis := ir.AsNode(tfn.Type().Recv().Nname)
1808 methodrcvr := method.Type.Recv().Type
1810 // generate nil pointer check for better error
1811 if rcvr.IsPtr() && rcvr.Elem() == methodrcvr {
1812 // generating wrapper from *T to T.
1813 n := ir.NewIfStmt(base.Pos, nil, nil, nil)
1814 n.Cond = ir.NewBinaryExpr(base.Pos, ir.OEQ, nthis, typecheck.NodNil())
1815 call := ir.NewCallExpr(base.Pos, ir.OCALL, typecheck.LookupRuntime("panicwrap"), nil)
1816 n.Body = []ir.Node{call}
1820 dot := typecheck.AddImplicitDots(ir.NewSelectorExpr(base.Pos, ir.OXDOT, nthis, method.Sym))
1823 // It's not possible to use a tail call when dynamic linking on ppc64le. The
1824 // bad scenario is when a local call is made to the wrapper: the wrapper will
1825 // call the implementation, which might be in a different module and so set
1826 // the TOC to the appropriate value for that module. But if it returns
1827 // directly to the wrapper's caller, nothing will reset it to the correct
1828 // value for that function.
1830 // Disable tailcall for RegabiArgs for now. The IR does not connect the
1831 // arguments with the OTAILCALL node, and the arguments are not marshaled
1833 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 {
1834 // generate tail call: adjust pointer receiver and jump to embedded method.
1835 left := dot.X // skip final .M
1836 if !left.Type().IsPtr() {
1837 left = typecheck.NodAddr(left)
1839 as := ir.NewAssignStmt(base.Pos, nthis, typecheck.ConvNop(left, rcvr))
1841 fn.Body.Append(ir.NewTailCallStmt(base.Pos, method.Nname.(*ir.Name)))
1843 fn.SetWrapper(true) // ignore frame for panic+recover matching
1844 call := ir.NewCallExpr(base.Pos, ir.OCALL, dot, nil)
1845 call.Args = ir.ParamNames(tfn.Type())
1846 call.IsDDD = tfn.Type().IsVariadic()
1847 if method.Type.NumResults() > 0 {
1848 ret := ir.NewReturnStmt(base.Pos, nil)
1849 ret.Results = []ir.Node{call}
1852 fn.Body.Append(call)
1856 typecheck.FinishFuncBody()
1857 if base.Debug.DclStack != 0 {
1858 types.CheckDclstack()
1863 typecheck.Stmts(fn.Body)
1865 // Inline calls within (*T).M wrappers. This is safe because we only
1866 // generate those wrappers within the same compilation unit as (T).M.
1867 // TODO(mdempsky): Investigate why we can't enable this more generally.
1868 if rcvr.IsPtr() && rcvr.Elem() == method.Type.Recv().Type && rcvr.Elem().Sym() != nil {
1869 inline.InlineCalls(fn)
1871 escape.Batch([]*ir.Func{fn}, false)
1874 typecheck.Target.Decls = append(typecheck.Target.Decls, fn)
1881 // MarkTypeUsedInInterface marks that type t is converted to an interface.
1882 // This information is used in the linker in dead method elimination.
1883 func MarkTypeUsedInInterface(t *types.Type, from *obj.LSym) {
1884 tsym := TypeLinksym(t)
1885 // Emit a marker relocation. The linker will know the type is converted
1886 // to an interface if "from" is reachable.
1887 r := obj.Addrel(from)
1889 r.Type = objabi.R_USEIFACE
1892 // MarkUsedIfaceMethod marks that an interface method is used in the current
1893 // function. n is OCALLINTER node.
1894 func MarkUsedIfaceMethod(n *ir.CallExpr) {
1895 // skip unnamed functions (func _())
1896 if ir.CurFunc.LSym == nil {
1899 dot := n.X.(*ir.SelectorExpr)
1900 ityp := dot.X.Type()
1901 tsym := TypeLinksym(ityp)
1902 r := obj.Addrel(ir.CurFunc.LSym)
1904 // dot.Xoffset is the method index * PtrSize (the offset of code pointer
1906 midx := dot.Offset() / int64(types.PtrSize)
1907 r.Add = InterfaceMethodOffset(ityp, midx)
1908 r.Type = objabi.R_USEIFACEMETHOD