1 // Copyright 2017 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.
8 "cmd/compile/internal/base"
11 "internal/types/errors"
15 // Object represents an ir.Node, but without needing to import cmd/compile/internal/ir,
16 // which would cause an import cycle. The uses in other packages must type assert
17 // values of type Object to ir.Node or a more specific type.
18 type Object interface {
24 //go:generate stringer -type Kind -trimprefix T type.go
26 // Kind describes a kind of type.
65 // pseudo-types for literals
66 TIDEAL // untyped numeric constants
70 // pseudo-types used temporarily only during frame layout (CalcSize())
75 TSSA // internal types used by SSA backend (flags, memory, etc.)
76 TTUPLE // a pair of types, used by SSA backend
77 TRESULTS // multiple types; the result of calling a function or method, with a memory at the end.
82 // ChanDir is whether a channel can send, receive, or both.
85 func (c ChanDir) CanRecv() bool { return c&Crecv != 0 }
86 func (c ChanDir) CanSend() bool { return c&Csend != 0 }
90 // must match ../../../../reflect/type.go:/ChanDir
91 Crecv ChanDir = 1 << 0
92 Csend ChanDir = 1 << 1
93 Cboth ChanDir = Crecv | Csend
96 // Types stores pointers to predeclared named types.
98 // It also stores pointers to several special types:
99 // - Types[TANY] is the placeholder "any" type recognized by SubstArgTypes.
100 // - Types[TBLANK] represents the blank variable's type.
101 // - Types[TINTER] is the canonical "interface{}" type.
102 // - Types[TNIL] represents the predeclared "nil" value's type.
103 // - Types[TUNSAFEPTR] is package unsafe's Pointer type.
104 var Types [NTYPE]*Type
107 // Predeclared alias types. These are actually created as distinct
108 // defined types for better error messages, but are then specially
109 // treated as identical to their respective underlying types.
114 // Predeclared error interface type.
116 // Predeclared comparable interface type.
119 // Types to represent untyped string and boolean constants.
120 UntypedString = newType(TSTRING)
121 UntypedBool = newType(TBOOL)
123 // Types to represent untyped numeric constants.
124 UntypedInt = newType(TIDEAL)
125 UntypedRune = newType(TIDEAL)
126 UntypedFloat = newType(TIDEAL)
127 UntypedComplex = newType(TIDEAL)
130 // A Type represents a Go type.
132 // There may be multiple unnamed types with identical structure. However, there must
133 // be a unique Type object for each unique named (defined) type. After noding, a
134 // package-level type can be looked up by building its unique symbol sym (sym =
135 // package.Lookup(name)) and checking sym.Def. If sym.Def is non-nil, the type
136 // already exists at package scope and is available at sym.Def.(*ir.Name).Type().
137 // Local types (which may have the same name as a package-level type) are
138 // distinguished by the value of vargen.
140 // extra contains extra etype-specific fields.
141 // As an optimization, those etype-specific structs which contain exactly
142 // one pointer-shaped field are stored as values rather than pointers when possible.
148 // TINTER: *Interface
149 // TFUNCARGS: FuncArgs
150 // TCHANARGS: ChanArgs
158 // width is the width of this Type in bytes.
159 width int64 // valid if Align > 0
161 // list of base methods (excluding embedding)
163 // list of all methods (including embedding)
166 // canonical OTYPE node for a named type (should be an ir.Name node with same sym)
168 // the underlying type (type literal or predeclared type) for a defined type
171 // Cache of composite types, with this type being the element type.
173 ptr *Type // *T, or nil
174 slice *Type // []T, or nil
177 vargen int32 // unique name for OTYPE/ONAME
179 kind Kind // kind of type
180 align uint8 // the required alignment of this type, in bytes (0 means Width and Align have not yet been computed)
184 // For defined (named) generic types, a pointer to the list of type params
185 // (in order) of this type that need to be instantiated. For instantiated
186 // generic types, this is the targs used to instantiate them. These targs
187 // may be typeparams (for re-instantiated types such as Value[T2]) or
188 // concrete types (for fully instantiated types such as Value[int]).
189 // rparams is only set for named types that are generic or are fully
190 // instantiated from a generic type, and is otherwise set to nil.
191 // TODO(danscales): choose a better name.
195 func (*Type) CanBeAnSSAAux() {}
198 typeNotInHeap = 1 << iota // type cannot be heap allocated
199 typeNoalg // suppress hash and eq algorithm generation
200 typeDeferwidth // width computation has been deferred and type is on deferredTypeStack
202 typeIsShape // represents a set of closely related types, for generics
203 typeHasShape // there is a shape somewhere in the type
206 func (t *Type) NotInHeap() bool { return t.flags&typeNotInHeap != 0 }
207 func (t *Type) Noalg() bool { return t.flags&typeNoalg != 0 }
208 func (t *Type) Deferwidth() bool { return t.flags&typeDeferwidth != 0 }
209 func (t *Type) Recur() bool { return t.flags&typeRecur != 0 }
210 func (t *Type) IsShape() bool { return t.flags&typeIsShape != 0 }
211 func (t *Type) HasShape() bool { return t.flags&typeHasShape != 0 }
213 func (t *Type) SetNotInHeap(b bool) { t.flags.set(typeNotInHeap, b) }
214 func (t *Type) SetNoalg(b bool) { t.flags.set(typeNoalg, b) }
215 func (t *Type) SetDeferwidth(b bool) { t.flags.set(typeDeferwidth, b) }
216 func (t *Type) SetRecur(b bool) { t.flags.set(typeRecur, b) }
218 // Should always do SetHasShape(true) when doing SetIsShape(true).
219 func (t *Type) SetIsShape(b bool) { t.flags.set(typeIsShape, b) }
220 func (t *Type) SetHasShape(b bool) { t.flags.set(typeHasShape, b) }
222 // Kind returns the kind of type t.
223 func (t *Type) Kind() Kind { return t.kind }
225 // Sym returns the name of type t.
226 func (t *Type) Sym() *Sym {
233 // Underlying returns the underlying type of type t.
234 func (t *Type) Underlying() *Type { return t.underlying }
236 // Pos returns a position associated with t, if any.
237 // This should only be used for diagnostics.
238 func (t *Type) Pos() src.XPos {
245 func (t *Type) RParams() []*Type {
246 if t.rparams == nil {
252 func (t *Type) SetRParams(rparams []*Type) {
253 if len(rparams) == 0 {
254 base.Fatalf("Setting nil or zero-length rparams")
257 // HasShape should be set if any type argument is or has a shape type.
258 for _, rparam := range rparams {
259 if rparam.HasShape() {
266 // IsFullyInstantiated reports whether t is a fully instantiated generic type; i.e. an
267 // instantiated generic type where all type arguments are non-generic or fully
268 // instantiated generic types.
269 func (t *Type) IsFullyInstantiated() bool {
270 return len(t.RParams()) > 0
273 // Map contains Type fields specific to maps.
275 Key *Type // Key type
276 Elem *Type // Val (elem) type
278 Bucket *Type // internal struct type representing a hash bucket
279 Hmap *Type // internal struct type representing the Hmap (map header object)
280 Hiter *Type // internal struct type representing hash iterator state
283 // MapType returns t's extra map-specific fields.
284 func (t *Type) MapType() *Map {
286 return t.extra.(*Map)
289 // Forward contains Type fields specific to forward types.
290 type Forward struct {
291 Copyto []*Type // where to copy the eventual value to
292 Embedlineno src.XPos // first use of this type as an embedded type
295 // forwardType returns t's extra forward-type-specific fields.
296 func (t *Type) forwardType() *Forward {
298 return t.extra.(*Forward)
301 // Func contains Type fields specific to func types.
303 Receiver *Type // function receiver
304 Results *Type // function results
305 Params *Type // function params
307 // Argwid is the total width of the function receiver, params, and results.
308 // It gets calculated via a temporary TFUNCARGS type.
309 // Note that TFUNC's Width is Widthptr.
313 // funcType returns t's extra func-specific fields.
314 func (t *Type) funcType() *Func {
316 return t.extra.(*Func)
319 // StructType contains Type fields specific to struct types.
323 // Maps have three associated internal structs (see struct MapType).
324 // Map links such structs back to their map type.
327 Funarg Funarg // type of function arguments for arg struct
330 // Funarg records the kind of function argument
334 FunargNone Funarg = iota
335 FunargRcvr // receiver
336 FunargParams // input parameters
337 FunargResults // output results
338 FunargTparams // type params
341 // StructType returns t's extra struct-specific fields.
342 func (t *Type) StructType() *Struct {
344 return t.extra.(*Struct)
347 // Interface contains Type fields specific to interface types.
348 type Interface struct {
351 // Ptr contains Type fields specific to pointer types.
353 Elem *Type // element type
356 // ChanArgs contains Type fields specific to TCHANARGS types.
357 type ChanArgs struct {
358 T *Type // reference to a chan type whose elements need a width check
361 // // FuncArgs contains Type fields specific to TFUNCARGS types.
362 type FuncArgs struct {
363 T *Type // reference to a func type whose elements need a width check
366 // Chan contains Type fields specific to channel types.
368 Elem *Type // element type
369 Dir ChanDir // channel direction
372 // chanType returns t's extra channel-specific fields.
373 func (t *Type) chanType() *Chan {
375 return t.extra.(*Chan)
381 // Any tuple with a memory type must put that memory type second.
384 // Results are the output from calls that will be late-expanded.
385 type Results struct {
386 Types []*Type // Last element is memory output from call.
389 // Array contains Type fields specific to array types.
391 Elem *Type // element type
392 Bound int64 // number of elements; <0 if unknown yet
395 // Slice contains Type fields specific to slice types.
397 Elem *Type // element type
400 // A Field is a (Sym, Type) pairing along with some other information, and,
401 // depending on the context, is used to represent:
402 // - a field in a struct
403 // - a method in an interface or associated with a named type
404 // - a function parameter
408 Embedded uint8 // embedded field
412 // Name of field/method/parameter. Can be nil for interface fields embedded
413 // in interfaces and unnamed parameters.
415 Type *Type // field type
416 Note string // literal string annotation
418 // For fields that represent function parameters, Nname points to the
419 // associated ONAME Node. For fields that represent methods, Nname points to
420 // the function name node.
423 // Offset in bytes of this field or method within its enclosing struct
424 // or interface Type. Exception: if field is function receiver, arg or
425 // result, then this is BOGUS_FUNARG_OFFSET; types does not know the Abi.
430 fieldIsDDD = 1 << iota // field is ... argument
434 func (f *Field) IsDDD() bool { return f.flags&fieldIsDDD != 0 }
435 func (f *Field) Nointerface() bool { return f.flags&fieldNointerface != 0 }
437 func (f *Field) SetIsDDD(b bool) { f.flags.set(fieldIsDDD, b) }
438 func (f *Field) SetNointerface(b bool) { f.flags.set(fieldNointerface, b) }
440 // End returns the offset of the first byte immediately after this field.
441 func (f *Field) End() int64 {
442 return f.Offset + f.Type.width
445 // IsMethod reports whether f represents a method rather than a struct field.
446 func (f *Field) IsMethod() bool {
447 return f.Type.kind == TFUNC && f.Type.Recv() != nil
450 // Fields is a pointer to a slice of *Field.
451 // This saves space in Types that do not have fields or methods
452 // compared to a simple slice of *Field.
457 // Len returns the number of entries in f.
458 func (f *Fields) Len() int {
465 // Slice returns the entries in f as a slice.
466 // Changes to the slice entries will be reflected in f.
467 func (f *Fields) Slice() []*Field {
474 // Index returns the i'th element of Fields.
475 // It panics if f does not have at least i+1 elements.
476 func (f *Fields) Index(i int) *Field {
480 // Set sets f to a slice.
481 // This takes ownership of the slice.
482 func (f *Fields) Set(s []*Field) {
486 // Copy s and take address of t rather than s to avoid
487 // allocation in the case where len(s) == 0.
493 // Append appends entries to f.
494 func (f *Fields) Append(s ...*Field) {
498 *f.s = append(*f.s, s...)
501 // newType returns a new Type of the specified kind.
502 func newType(et Kind) *Type {
508 // TODO(josharian): lazily initialize some of these?
513 t.extra = new(Forward)
517 t.extra = new(Struct)
519 t.extra = new(Interface)
531 t.extra = new(Results)
536 // NewArray returns a new fixed-length array Type.
537 func NewArray(elem *Type, bound int64) *Type {
539 base.Fatalf("NewArray: invalid bound %v", bound)
542 t.extra = &Array{Elem: elem, Bound: bound}
549 // NewSlice returns the slice Type with element type elem.
550 func NewSlice(elem *Type) *Type {
551 if t := elem.cache.slice; t != nil {
552 if t.Elem() != elem {
553 base.Fatalf("elem mismatch")
555 if elem.HasShape() != t.HasShape() {
556 base.Fatalf("Incorrect HasShape flag for cached slice type")
562 t.extra = Slice{Elem: elem}
570 // NewChan returns a new chan Type with direction dir.
571 func NewChan(elem *Type, dir ChanDir) *Type {
582 func NewTuple(t1, t2 *Type) *Type {
584 t.extra.(*Tuple).first = t1
585 t.extra.(*Tuple).second = t2
586 if t1.HasShape() || t2.HasShape() {
592 func newResults(types []*Type) *Type {
593 t := newType(TRESULTS)
594 t.extra.(*Results).Types = types
598 func NewResults(types []*Type) *Type {
599 if len(types) == 1 && types[0] == TypeMem {
602 return newResults(types)
605 func newSSA(name string) *Type {
611 // NewMap returns a new map Type with key type k and element (aka value) type v.
612 func NewMap(k, v *Type) *Type {
617 if k.HasShape() || v.HasShape() {
623 // NewPtrCacheEnabled controls whether *T Types are cached in T.
624 // Caching is disabled just before starting the backend.
625 // This allows the backend to run concurrently.
626 var NewPtrCacheEnabled = true
628 // NewPtr returns the pointer type pointing to t.
629 func NewPtr(elem *Type) *Type {
631 base.Fatalf("NewPtr: pointer to elem Type is nil")
634 if t := elem.cache.ptr; t != nil {
635 if t.Elem() != elem {
636 base.Fatalf("NewPtr: elem mismatch")
638 if elem.HasShape() != t.HasShape() {
639 base.Fatalf("Incorrect HasShape flag for cached pointer type")
645 t.extra = Ptr{Elem: elem}
646 t.width = int64(PtrSize)
647 t.align = uint8(PtrSize)
648 if NewPtrCacheEnabled {
657 // NewChanArgs returns a new TCHANARGS type for channel type c.
658 func NewChanArgs(c *Type) *Type {
659 t := newType(TCHANARGS)
660 t.extra = ChanArgs{T: c}
664 // NewFuncArgs returns a new TFUNCARGS type for func type f.
665 func NewFuncArgs(f *Type) *Type {
666 t := newType(TFUNCARGS)
667 t.extra = FuncArgs{T: f}
671 func NewField(pos src.XPos, sym *Sym, typ *Type) *Field {
679 base.Fatalf("typ is nil")
684 // SubstAny walks t, replacing instances of "any" with successive
685 // elements removed from types. It returns the substituted type.
686 func SubstAny(t *Type, types *[]*Type) *Type {
693 // Leave the type unchanged.
696 if len(*types) == 0 {
697 base.Fatalf("SubstArgTypes: not enough argument types")
700 *types = (*types)[1:]
703 elem := SubstAny(t.Elem(), types)
704 if elem != t.Elem() {
706 t.extra = Ptr{Elem: elem}
710 elem := SubstAny(t.Elem(), types)
711 if elem != t.Elem() {
713 t.extra.(*Array).Elem = elem
717 elem := SubstAny(t.Elem(), types)
718 if elem != t.Elem() {
720 t.extra = Slice{Elem: elem}
724 elem := SubstAny(t.Elem(), types)
725 if elem != t.Elem() {
727 t.extra.(*Chan).Elem = elem
731 key := SubstAny(t.Key(), types)
732 elem := SubstAny(t.Elem(), types)
733 if key != t.Key() || elem != t.Elem() {
735 t.extra.(*Map).Key = key
736 t.extra.(*Map).Elem = elem
740 recvs := SubstAny(t.Recvs(), types)
741 params := SubstAny(t.Params(), types)
742 results := SubstAny(t.Results(), types)
743 if recvs != t.Recvs() || params != t.Params() || results != t.Results() {
745 t.funcType().Receiver = recvs
746 t.funcType().Results = results
747 t.funcType().Params = params
751 // Make a copy of all fields, including ones whose type does not change.
752 // This prevents aliasing across functions, which can lead to later
753 // fields getting their Offset incorrectly overwritten.
754 fields := t.FieldSlice()
755 nfs := make([]*Field, len(fields))
756 for i, f := range fields {
757 nft := SubstAny(f.Type, types)
768 // copy returns a shallow copy of the Type.
769 func (t *Type) copy() *Type {
774 // copy any *T Extra fields, to avoid aliasing
780 x := *t.extra.(*Forward)
783 x := *t.extra.(*Func)
786 x := *t.extra.(*Struct)
789 x := *t.extra.(*Interface)
792 x := *t.extra.(*Chan)
795 x := *t.extra.(*Array)
797 case TTUPLE, TSSA, TRESULTS:
798 base.Fatalf("ssa types cannot be copied")
800 // TODO(mdempsky): Find out why this is necessary and explain.
801 if t.underlying == t {
807 func (f *Field) Copy() *Field {
812 func (t *Type) wantEtype(et Kind) {
814 base.Fatalf("want %v, but have %v", et, t)
818 func (t *Type) Recvs() *Type { return t.funcType().Receiver }
819 func (t *Type) Params() *Type { return t.funcType().Params }
820 func (t *Type) Results() *Type { return t.funcType().Results }
822 func (t *Type) NumRecvs() int { return t.funcType().Receiver.NumFields() }
823 func (t *Type) NumParams() int { return t.funcType().Params.NumFields() }
824 func (t *Type) NumResults() int { return t.funcType().Results.NumFields() }
826 // IsVariadic reports whether function type t is variadic.
827 func (t *Type) IsVariadic() bool {
829 return n > 0 && t.Params().Field(n-1).IsDDD()
832 // Recv returns the receiver of function type t, if any.
833 func (t *Type) Recv() *Field {
835 if s.NumFields() == 0 {
841 // RecvsParamsResults stores the accessor functions for a function Type's
842 // receiver, parameters, and result parameters, in that order.
843 // It can be used to iterate over all of a function's parameter lists.
844 var RecvsParamsResults = [3]func(*Type) *Type{
845 (*Type).Recvs, (*Type).Params, (*Type).Results,
848 // RecvsParams is like RecvsParamsResults, but omits result parameters.
849 var RecvsParams = [2]func(*Type) *Type{
850 (*Type).Recvs, (*Type).Params,
853 // ParamsResults is like RecvsParamsResults, but omits receiver parameters.
854 var ParamsResults = [2]func(*Type) *Type{
855 (*Type).Params, (*Type).Results,
858 // Key returns the key type of map type t.
859 func (t *Type) Key() *Type {
861 return t.extra.(*Map).Key
864 // Elem returns the type of elements of t.
865 // Usable with pointers, channels, arrays, slices, and maps.
866 func (t *Type) Elem() *Type {
869 return t.extra.(Ptr).Elem
871 return t.extra.(*Array).Elem
873 return t.extra.(Slice).Elem
875 return t.extra.(*Chan).Elem
877 return t.extra.(*Map).Elem
879 base.Fatalf("Type.Elem %s", t.kind)
883 // ChanArgs returns the channel type for TCHANARGS type t.
884 func (t *Type) ChanArgs() *Type {
885 t.wantEtype(TCHANARGS)
886 return t.extra.(ChanArgs).T
889 // FuncArgs returns the func type for TFUNCARGS type t.
890 func (t *Type) FuncArgs() *Type {
891 t.wantEtype(TFUNCARGS)
892 return t.extra.(FuncArgs).T
895 // IsFuncArgStruct reports whether t is a struct representing function parameters or results.
896 func (t *Type) IsFuncArgStruct() bool {
897 return t.kind == TSTRUCT && t.extra.(*Struct).Funarg != FunargNone
900 // Methods returns a pointer to the base methods (excluding embedding) for type t.
901 // These can either be concrete methods (for non-interface types) or interface
902 // methods (for interface types).
903 func (t *Type) Methods() *Fields {
907 // AllMethods returns a pointer to all the methods (including embedding) for type t.
908 // For an interface type, this is the set of methods that are typically iterated
909 // over. For non-interface types, AllMethods() only returns a valid result after
910 // CalcMethods() has been called at least once.
911 func (t *Type) AllMethods() *Fields {
912 if t.kind == TINTER {
913 // Calculate the full method set of an interface type on the fly
914 // now, if not done yet.
920 // SetAllMethods sets the set of all methods (including embedding) for type t.
921 // Use this method instead of t.AllMethods().Set(), which might call CalcSize() on
922 // an uninitialized interface type.
923 func (t *Type) SetAllMethods(fs []*Field) {
927 // Fields returns the fields of struct type t.
928 func (t *Type) Fields() *Fields {
930 return &t.extra.(*Struct).fields
933 // Field returns the i'th field of struct type t.
934 func (t *Type) Field(i int) *Field {
935 return t.Fields().Slice()[i]
938 // FieldSlice returns a slice of containing all fields of
940 func (t *Type) FieldSlice() []*Field {
941 return t.Fields().Slice()
944 // SetFields sets struct type t's fields to fields.
945 func (t *Type) SetFields(fields []*Field) {
946 // If we've calculated the width of t before,
947 // then some other type such as a function signature
948 // might now have the wrong type.
949 // Rather than try to track and invalidate those,
950 // enforce that SetFields cannot be called once
951 // t's width has been calculated.
952 if t.widthCalculated() {
953 base.Fatalf("SetFields of %v: width previously calculated", t)
956 t.Fields().Set(fields)
959 // SetInterface sets the base methods of an interface type t.
960 func (t *Type) SetInterface(methods []*Field) {
962 t.Methods().Set(methods)
965 // ArgWidth returns the total aligned argument size for a function.
966 // It includes the receiver, parameters, and results.
967 func (t *Type) ArgWidth() int64 {
969 return t.extra.(*Func).Argwid
972 func (t *Type) Size() int64 {
983 func (t *Type) Alignment() int64 {
985 return int64(t.align)
988 func (t *Type) SimpleString() string {
989 return t.kind.String()
992 // Cmp is a comparison between values a and b.
1005 // Compare compares types for purposes of the SSA back
1006 // end, returning a Cmp (one of CMPlt, CMPeq, CMPgt).
1007 // The answers are correct for an optimizer
1008 // or code generator, but not necessarily typechecking.
1009 // The order chosen is arbitrary, only consistency and division
1010 // into equivalence classes (Types that compare CMPeq) matters.
1011 func (t *Type) Compare(x *Type) Cmp {
1018 func cmpForNe(x bool) Cmp {
1025 func (r *Sym) cmpsym(s *Sym) Cmp {
1035 // Fast sort, not pretty sort
1036 if len(r.Name) != len(s.Name) {
1037 return cmpForNe(len(r.Name) < len(s.Name))
1040 if len(r.Pkg.Prefix) != len(s.Pkg.Prefix) {
1041 return cmpForNe(len(r.Pkg.Prefix) < len(s.Pkg.Prefix))
1043 if r.Pkg.Prefix != s.Pkg.Prefix {
1044 return cmpForNe(r.Pkg.Prefix < s.Pkg.Prefix)
1047 if r.Name != s.Name {
1048 return cmpForNe(r.Name < s.Name)
1053 // cmp compares two *Types t and x, returning CMPlt,
1054 // CMPeq, CMPgt as t<x, t==x, t>x, for an arbitrary
1055 // and optimizer-centric notion of comparison.
1056 // TODO(josharian): make this safe for recursive interface types
1057 // and use in signatlist sorting. See issue 19869.
1058 func (t *Type) cmp(x *Type) Cmp {
1059 // This follows the structure of function identical in identity.go
1060 // with two exceptions.
1061 // 1. Symbols are compared more carefully because a <,=,> result is desired.
1062 // 2. Maps are treated specially to avoid endless recursion -- maps
1063 // contain an internal data type not expressible in Go source code.
1074 if t.kind != x.kind {
1075 return cmpForNe(t.kind < x.kind)
1078 if t.obj != nil || x.obj != nil {
1079 // Special case: we keep byte and uint8 separate
1080 // for error messages. Treat them as equal.
1083 if (t == Types[TUINT8] || t == ByteType) && (x == Types[TUINT8] || x == ByteType) {
1088 if (t == Types[RuneType.kind] || t == RuneType) && (x == Types[RuneType.kind] || x == RuneType) {
1093 // Make sure named any type matches any empty interface.
1094 if t == AnyType && x.IsEmptyInterface() || x == AnyType && t.IsEmptyInterface() {
1100 if c := t.Sym().cmpsym(x.Sym()); c != CMPeq {
1105 // Syms non-nil, if vargens match then equal.
1106 if t.vargen != x.vargen {
1107 return cmpForNe(t.vargen < x.vargen)
1111 // both syms nil, look at structure below.
1114 case TBOOL, TFLOAT32, TFLOAT64, TCOMPLEX64, TCOMPLEX128, TUNSAFEPTR, TUINTPTR,
1115 TINT8, TINT16, TINT32, TINT64, TINT, TUINT8, TUINT16, TUINT32, TUINT64, TUINT:
1119 tname := t.extra.(string)
1120 xname := x.extra.(string)
1121 // desire fast sorting, not pretty sorting.
1122 if len(tname) == len(xname) {
1131 if len(tname) > len(xname) {
1137 xtup := x.extra.(*Tuple)
1138 ttup := t.extra.(*Tuple)
1139 if c := ttup.first.Compare(xtup.first); c != CMPeq {
1142 return ttup.second.Compare(xtup.second)
1145 xResults := x.extra.(*Results)
1146 tResults := t.extra.(*Results)
1147 xl, tl := len(xResults.Types), len(tResults.Types)
1154 for i := 0; i < tl; i++ {
1155 if c := tResults.Types[i].Compare(xResults.Types[i]); c != CMPeq {
1162 if c := t.Key().cmp(x.Key()); c != CMPeq {
1165 return t.Elem().cmp(x.Elem())
1168 // No special cases for these, they are handled
1169 // by the general code after the switch.
1172 if t.StructType().Map == nil {
1173 if x.StructType().Map != nil {
1174 return CMPlt // nil < non-nil
1176 // to the fallthrough
1177 } else if x.StructType().Map == nil {
1178 return CMPgt // nil > non-nil
1179 } else if t.StructType().Map.MapType().Bucket == t {
1180 // Both have non-nil Map
1181 // Special case for Maps which include a recursive type where the recursion is not broken with a named type
1182 if x.StructType().Map.MapType().Bucket != x {
1183 return CMPlt // bucket maps are least
1185 return t.StructType().Map.cmp(x.StructType().Map)
1186 } else if x.StructType().Map.MapType().Bucket == x {
1187 return CMPgt // bucket maps are least
1188 } // If t != t.Map.Bucket, fall through to general case
1190 tfs := t.FieldSlice()
1191 xfs := x.FieldSlice()
1192 for i := 0; i < len(tfs) && i < len(xfs); i++ {
1193 t1, x1 := tfs[i], xfs[i]
1194 if t1.Embedded != x1.Embedded {
1195 return cmpForNe(t1.Embedded < x1.Embedded)
1197 if t1.Note != x1.Note {
1198 return cmpForNe(t1.Note < x1.Note)
1200 if c := t1.Sym.cmpsym(x1.Sym); c != CMPeq {
1203 if c := t1.Type.cmp(x1.Type); c != CMPeq {
1207 if len(tfs) != len(xfs) {
1208 return cmpForNe(len(tfs) < len(xfs))
1213 tfs := t.AllMethods().Slice()
1214 xfs := x.AllMethods().Slice()
1215 for i := 0; i < len(tfs) && i < len(xfs); i++ {
1216 t1, x1 := tfs[i], xfs[i]
1217 if c := t1.Sym.cmpsym(x1.Sym); c != CMPeq {
1220 if c := t1.Type.cmp(x1.Type); c != CMPeq {
1224 if len(tfs) != len(xfs) {
1225 return cmpForNe(len(tfs) < len(xfs))
1230 for _, f := range RecvsParamsResults {
1231 // Loop over fields in structs, ignoring argument names.
1232 tfs := f(t).FieldSlice()
1233 xfs := f(x).FieldSlice()
1234 for i := 0; i < len(tfs) && i < len(xfs); i++ {
1237 if ta.IsDDD() != tb.IsDDD() {
1238 return cmpForNe(!ta.IsDDD())
1240 if c := ta.Type.cmp(tb.Type); c != CMPeq {
1244 if len(tfs) != len(xfs) {
1245 return cmpForNe(len(tfs) < len(xfs))
1251 if t.NumElem() != x.NumElem() {
1252 return cmpForNe(t.NumElem() < x.NumElem())
1256 if t.ChanDir() != x.ChanDir() {
1257 return cmpForNe(t.ChanDir() < x.ChanDir())
1261 e := fmt.Sprintf("Do not know how to compare %v with %v", t, x)
1265 // Common element type comparison for TARRAY, TCHAN, TPTR, and TSLICE.
1266 return t.Elem().cmp(x.Elem())
1269 // IsKind reports whether t is a Type of the specified kind.
1270 func (t *Type) IsKind(et Kind) bool {
1271 return t != nil && t.kind == et
1274 func (t *Type) IsBoolean() bool {
1275 return t.kind == TBOOL
1278 var unsignedEType = [...]Kind{
1292 // ToUnsigned returns the unsigned equivalent of integer type t.
1293 func (t *Type) ToUnsigned() *Type {
1295 base.Fatalf("unsignedType(%v)", t)
1297 return Types[unsignedEType[t.kind]]
1300 func (t *Type) IsInteger() bool {
1302 case TINT8, TUINT8, TINT16, TUINT16, TINT32, TUINT32, TINT64, TUINT64, TINT, TUINT, TUINTPTR:
1305 return t == UntypedInt || t == UntypedRune
1308 func (t *Type) IsSigned() bool {
1310 case TINT8, TINT16, TINT32, TINT64, TINT:
1316 func (t *Type) IsUnsigned() bool {
1318 case TUINT8, TUINT16, TUINT32, TUINT64, TUINT, TUINTPTR:
1324 func (t *Type) IsFloat() bool {
1325 return t.kind == TFLOAT32 || t.kind == TFLOAT64 || t == UntypedFloat
1328 func (t *Type) IsComplex() bool {
1329 return t.kind == TCOMPLEX64 || t.kind == TCOMPLEX128 || t == UntypedComplex
1332 // IsPtr reports whether t is a regular Go pointer type.
1333 // This does not include unsafe.Pointer.
1334 func (t *Type) IsPtr() bool {
1335 return t.kind == TPTR
1338 // IsPtrElem reports whether t is the element of a pointer (to t).
1339 func (t *Type) IsPtrElem() bool {
1340 return t.cache.ptr != nil
1343 // IsUnsafePtr reports whether t is an unsafe pointer.
1344 func (t *Type) IsUnsafePtr() bool {
1345 return t.kind == TUNSAFEPTR
1348 // IsUintptr reports whether t is a uintptr.
1349 func (t *Type) IsUintptr() bool {
1350 return t.kind == TUINTPTR
1353 // IsPtrShaped reports whether t is represented by a single machine pointer.
1354 // In addition to regular Go pointer types, this includes map, channel, and
1355 // function types and unsafe.Pointer. It does not include array or struct types
1356 // that consist of a single pointer shaped type.
1357 // TODO(mdempsky): Should it? See golang.org/issue/15028.
1358 func (t *Type) IsPtrShaped() bool {
1359 return t.kind == TPTR || t.kind == TUNSAFEPTR ||
1360 t.kind == TMAP || t.kind == TCHAN || t.kind == TFUNC
1363 // HasNil reports whether the set of values determined by t includes nil.
1364 func (t *Type) HasNil() bool {
1366 case TCHAN, TFUNC, TINTER, TMAP, TNIL, TPTR, TSLICE, TUNSAFEPTR:
1372 func (t *Type) IsString() bool {
1373 return t.kind == TSTRING
1376 func (t *Type) IsMap() bool {
1377 return t.kind == TMAP
1380 func (t *Type) IsChan() bool {
1381 return t.kind == TCHAN
1384 func (t *Type) IsSlice() bool {
1385 return t.kind == TSLICE
1388 func (t *Type) IsArray() bool {
1389 return t.kind == TARRAY
1392 func (t *Type) IsStruct() bool {
1393 return t.kind == TSTRUCT
1396 func (t *Type) IsInterface() bool {
1397 return t.kind == TINTER
1400 // IsEmptyInterface reports whether t is an empty interface type.
1401 func (t *Type) IsEmptyInterface() bool {
1402 return t.IsInterface() && t.AllMethods().Len() == 0
1405 // IsScalar reports whether 't' is a scalar Go type, e.g.
1406 // bool/int/float/complex. Note that struct and array types consisting
1407 // of a single scalar element are not considered scalar, likewise
1408 // pointer types are also not considered scalar.
1409 func (t *Type) IsScalar() bool {
1411 case TBOOL, TINT8, TUINT8, TINT16, TUINT16, TINT32,
1412 TUINT32, TINT64, TUINT64, TINT, TUINT,
1413 TUINTPTR, TCOMPLEX64, TCOMPLEX128, TFLOAT32, TFLOAT64:
1419 func (t *Type) PtrTo() *Type {
1423 func (t *Type) NumFields() int {
1424 if t.kind == TRESULTS {
1425 return len(t.extra.(*Results).Types)
1427 return t.Fields().Len()
1429 func (t *Type) FieldType(i int) *Type {
1430 if t.kind == TTUPLE {
1433 return t.extra.(*Tuple).first
1435 return t.extra.(*Tuple).second
1437 panic("bad tuple index")
1440 if t.kind == TRESULTS {
1441 return t.extra.(*Results).Types[i]
1443 return t.Field(i).Type
1445 func (t *Type) FieldOff(i int) int64 {
1446 return t.Field(i).Offset
1448 func (t *Type) FieldName(i int) string {
1449 return t.Field(i).Sym.Name
1452 func (t *Type) NumElem() int64 {
1454 return t.extra.(*Array).Bound
1457 type componentsIncludeBlankFields bool
1460 IgnoreBlankFields componentsIncludeBlankFields = false
1461 CountBlankFields componentsIncludeBlankFields = true
1464 // NumComponents returns the number of primitive elements that compose t.
1465 // Struct and array types are flattened for the purpose of counting.
1466 // All other types (including string, slice, and interface types) count as one element.
1467 // If countBlank is IgnoreBlankFields, then blank struct fields
1468 // (and their comprised elements) are excluded from the count.
1469 // struct { x, y [3]int } has six components; [10]struct{ x, y string } has twenty.
1470 func (t *Type) NumComponents(countBlank componentsIncludeBlankFields) int64 {
1473 if t.IsFuncArgStruct() {
1474 base.Fatalf("NumComponents func arg struct")
1477 for _, f := range t.FieldSlice() {
1478 if countBlank == IgnoreBlankFields && f.Sym.IsBlank() {
1481 n += f.Type.NumComponents(countBlank)
1485 return t.NumElem() * t.Elem().NumComponents(countBlank)
1490 // SoleComponent returns the only primitive component in t,
1491 // if there is exactly one. Otherwise, it returns nil.
1492 // Components are counted as in NumComponents, including blank fields.
1493 // Keep in sync with cmd/compile/internal/walk/convert.go:soleComponent.
1494 func (t *Type) SoleComponent() *Type {
1497 if t.IsFuncArgStruct() {
1498 base.Fatalf("SoleComponent func arg struct")
1500 if t.NumFields() != 1 {
1503 return t.Field(0).Type.SoleComponent()
1505 if t.NumElem() != 1 {
1508 return t.Elem().SoleComponent()
1513 // ChanDir returns the direction of a channel type t.
1514 // The direction will be one of Crecv, Csend, or Cboth.
1515 func (t *Type) ChanDir() ChanDir {
1517 return t.extra.(*Chan).Dir
1520 func (t *Type) IsMemory() bool {
1521 if t == TypeMem || t.kind == TTUPLE && t.extra.(*Tuple).second == TypeMem {
1524 if t.kind == TRESULTS {
1525 if types := t.extra.(*Results).Types; len(types) > 0 && types[len(types)-1] == TypeMem {
1531 func (t *Type) IsFlags() bool { return t == TypeFlags }
1532 func (t *Type) IsVoid() bool { return t == TypeVoid }
1533 func (t *Type) IsTuple() bool { return t.kind == TTUPLE }
1534 func (t *Type) IsResults() bool { return t.kind == TRESULTS }
1536 // IsUntyped reports whether t is an untyped type.
1537 func (t *Type) IsUntyped() bool {
1541 if t == UntypedString || t == UntypedBool {
1551 // HasPointers reports whether t contains a heap pointer.
1552 // Note that this function ignores pointers to not-in-heap types.
1553 func (t *Type) HasPointers() bool {
1554 return PtrDataSize(t) > 0
1559 // FakeRecvType returns the singleton type used for interface method receivers.
1560 func FakeRecvType() *Type {
1561 if recvType == nil {
1562 recvType = NewPtr(newType(TSTRUCT))
1567 func FakeRecv() *Field {
1568 return NewField(base.AutogeneratedPos, nil, FakeRecvType())
1572 // TSSA types. HasPointers assumes these are pointer-free.
1573 TypeInvalid = newSSA("invalid")
1574 TypeMem = newSSA("mem")
1575 TypeFlags = newSSA("flags")
1576 TypeVoid = newSSA("void")
1577 TypeInt128 = newSSA("int128")
1578 TypeResultMem = newResults([]*Type{TypeMem})
1582 TypeInt128.width = 16
1583 TypeInt128.align = 8
1586 // NewNamed returns a new named type for the given type name. obj should be an
1587 // ir.Name. The new type is incomplete (marked as TFORW kind), and the underlying
1588 // type should be set later via SetUnderlying(). References to the type are
1589 // maintained until the type is filled in, so those references can be updated when
1590 // the type is complete.
1591 func NewNamed(obj Object) *Type {
1594 if obj.Sym().Pkg == ShapePkg {
1601 // Obj returns the canonical type name node for a named type t, nil for an unnamed type.
1602 func (t *Type) Obj() Object {
1606 // typeGen tracks the number of function-scoped defined types that
1607 // have been declared. It's used to generate unique linker symbols for
1608 // their runtime type descriptors.
1611 // SetVargen assigns a unique generation number to type t, which must
1612 // be a defined type declared within function scope. The generation
1613 // number is used to distinguish it from other similarly spelled
1614 // defined types from the same package.
1616 // TODO(mdempsky): Come up with a better solution.
1617 func (t *Type) SetVargen() {
1618 base.Assertf(t.Sym() != nil, "SetVargen on anonymous type %v", t)
1619 base.Assertf(t.vargen == 0, "type %v already has Vargen %v", t, t.vargen)
1625 // SetUnderlying sets the underlying type of an incomplete type (i.e. type whose kind
1626 // is currently TFORW). SetUnderlying automatically updates any types that were waiting
1627 // for this type to be completed.
1628 func (t *Type) SetUnderlying(underlying *Type) {
1629 if underlying.kind == TFORW {
1630 // This type isn't computed yet; when it is, update n.
1631 underlying.forwardType().Copyto = append(underlying.forwardType().Copyto, t)
1635 ft := t.forwardType()
1637 // TODO(mdempsky): Fix Type rekinding.
1638 t.kind = underlying.kind
1639 t.extra = underlying.extra
1640 t.width = underlying.width
1641 t.align = underlying.align
1642 t.underlying = underlying.underlying
1644 if underlying.NotInHeap() {
1645 t.SetNotInHeap(true)
1647 if underlying.HasShape() {
1651 // spec: "The declared type does not inherit any methods bound
1652 // to the existing type, but the method set of an interface
1653 // type [...] remains unchanged."
1654 if t.IsInterface() {
1655 t.methods = underlying.methods
1656 t.allMethods = underlying.allMethods
1659 // Update types waiting on this type.
1660 for _, w := range ft.Copyto {
1664 // Double-check use of type as embedded type.
1665 if ft.Embedlineno.IsKnown() {
1666 if t.IsPtr() || t.IsUnsafePtr() {
1667 base.ErrorfAt(ft.Embedlineno, errors.InvalidPtrEmbed, "embedded type cannot be a pointer")
1672 func fieldsHasShape(fields []*Field) bool {
1673 for _, f := range fields {
1674 if f.Type != nil && f.Type.HasShape() {
1681 // newBasic returns a new basic type of the given kind.
1682 func newBasic(kind Kind, obj Object) *Type {
1688 // NewInterface returns a new interface for the given methods and
1689 // embedded types. Embedded types are specified as fields with no Sym.
1690 func NewInterface(methods []*Field) *Type {
1691 t := newType(TINTER)
1692 t.SetInterface(methods)
1693 for _, f := range methods {
1694 // f.Type could be nil for a broken interface declaration
1695 if f.Type != nil && f.Type.HasShape() {
1703 const BOGUS_FUNARG_OFFSET = -1000000000
1705 func unzeroFieldOffsets(f []*Field) {
1707 f[i].Offset = BOGUS_FUNARG_OFFSET // This will cause an explosion if it is not corrected
1711 // NewSignature returns a new function type for the given receiver,
1712 // parameters, and results, any of which may be nil.
1713 func NewSignature(recv *Field, params, results []*Field) *Type {
1716 recvs = []*Field{recv}
1722 funargs := func(fields []*Field, funarg Funarg) *Type {
1723 s := NewStruct(fields)
1724 s.StructType().Funarg = funarg
1729 recv.Offset = BOGUS_FUNARG_OFFSET
1731 unzeroFieldOffsets(params)
1732 unzeroFieldOffsets(results)
1733 ft.Receiver = funargs(recvs, FunargRcvr)
1734 ft.Params = funargs(params, FunargParams)
1735 ft.Results = funargs(results, FunargResults)
1736 if fieldsHasShape(recvs) || fieldsHasShape(params) || fieldsHasShape(results) {
1743 // NewStruct returns a new struct with the given fields.
1744 func NewStruct(fields []*Field) *Type {
1745 t := newType(TSTRUCT)
1747 if fieldsHasShape(fields) {
1756 IsComplex [NTYPE]bool
1757 IsSimple [NTYPE]bool
1760 var IsOrdered [NTYPE]bool
1762 // IsReflexive reports whether t has a reflexive equality operator.
1763 // That is, if x==x for all x of type t.
1764 func IsReflexive(t *Type) bool {
1792 return IsReflexive(t.Elem())
1795 for _, t1 := range t.Fields().Slice() {
1796 if !IsReflexive(t1.Type) {
1803 base.Fatalf("bad type for map key: %v", t)
1808 // Can this type be stored directly in an interface word?
1809 // Yes, if the representation is a single pointer.
1810 func IsDirectIface(t *Type) bool {
1813 // Pointers to notinheap types must be stored indirectly. See issue 42076.
1814 return !t.Elem().NotInHeap()
1822 // Array of 1 direct iface type can be direct.
1823 return t.NumElem() == 1 && IsDirectIface(t.Elem())
1826 // Struct with 1 field of direct iface type can be direct.
1827 return t.NumFields() == 1 && IsDirectIface(t.Field(0).Type)
1833 // IsInterfaceMethod reports whether (field) m is
1834 // an interface method. Such methods have the
1835 // special receiver type types.FakeRecvType().
1836 func IsInterfaceMethod(f *Type) bool {
1837 return f.Recv().Type == FakeRecvType()
1840 // IsMethodApplicable reports whether method m can be called on a
1841 // value of type t. This is necessary because we compute a single
1842 // method set for both T and *T, but some *T methods are not
1843 // applicable to T receivers.
1844 func IsMethodApplicable(t *Type, m *Field) bool {
1845 return t.IsPtr() || !m.Type.Recv().Type.IsPtr() || IsInterfaceMethod(m.Type) || m.Embedded == 2
1848 // IsRuntimePkg reports whether p is package runtime.
1849 func IsRuntimePkg(p *Pkg) bool {
1850 if base.Flag.CompilingRuntime && p == LocalPkg {
1853 return p.Path == "runtime"
1856 // IsReflectPkg reports whether p is package reflect.
1857 func IsReflectPkg(p *Pkg) bool {
1858 return p.Path == "reflect"
1861 // IsNoInstrumentPkg reports whether p is a package that
1862 // should not be instrumented.
1863 func IsNoInstrumentPkg(p *Pkg) bool {
1864 for _, np := range base.NoInstrumentPkgs {
1872 // IsNoRacePkg reports whether p is a package that
1873 // should not be race instrumented.
1874 func IsNoRacePkg(p *Pkg) bool {
1875 for _, np := range base.NoRacePkgs {
1883 // ReceiverBaseType returns the underlying type, if any,
1884 // that owns methods with receiver parameter t.
1885 // The result is either a named type or an anonymous struct.
1886 func ReceiverBaseType(t *Type) *Type {
1891 // Strip away pointer if it's there.
1902 // Must be a named type or anonymous struct.
1903 if t.Sym() == nil && !t.IsStruct() {
1908 if IsSimple[t.Kind()] {
1912 case TARRAY, TCHAN, TFUNC, TMAP, TSLICE, TSTRING, TSTRUCT:
1918 func FloatForComplex(t *Type) *Type {
1921 return Types[TFLOAT32]
1923 return Types[TFLOAT64]
1925 base.Fatalf("unexpected type: %v", t)
1929 func ComplexForFloat(t *Type) *Type {
1932 return Types[TCOMPLEX64]
1934 return Types[TCOMPLEX128]
1936 base.Fatalf("unexpected type: %v", t)
1940 func TypeSym(t *Type) *Sym {
1941 return TypeSymLookup(TypeSymName(t))
1944 func TypeSymLookup(name string) *Sym {
1946 s := typepkg.Lookup(name)
1951 func TypeSymName(t *Type) string {
1952 name := t.LinkString()
1953 // Use a separate symbol name for Noalg types for #17752.
1954 if TypeHasNoAlg(t) {
1955 name = "noalg." + name
1960 // Fake package for runtime type info (headers)
1961 // Don't access directly, use typeLookup below.
1963 typepkgmu sync.Mutex // protects typepkg lookups
1964 typepkg = NewPkg("type", "type")
1967 var SimType [NTYPE]Kind
1969 // Fake package for shape types (see typecheck.Shapify()).
1970 var ShapePkg = NewPkg("go.shape", "go.shape")