Source file src/cmd/compile/internal/types/type.go

     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.
     4  
     5  package types
     6  
     7  import (
     8  	"cmd/compile/internal/base"
     9  	"cmd/internal/objabi"
    10  	"cmd/internal/src"
    11  	"fmt"
    12  	"go/constant"
    13  	"internal/types/errors"
    14  	"sync"
    15  )
    16  
    17  // Object represents an ir.Node, but without needing to import cmd/compile/internal/ir,
    18  // which would cause an import cycle. The uses in other packages must type assert
    19  // values of type Object to ir.Node or a more specific type.
    20  type Object interface {
    21  	Pos() src.XPos
    22  	Sym() *Sym
    23  	Type() *Type
    24  }
    25  
    26  //go:generate stringer -type Kind -trimprefix T type.go
    27  
    28  // Kind describes a kind of type.
    29  type Kind uint8
    30  
    31  const (
    32  	Txxx Kind = iota
    33  
    34  	TINT8
    35  	TUINT8
    36  	TINT16
    37  	TUINT16
    38  	TINT32
    39  	TUINT32
    40  	TINT64
    41  	TUINT64
    42  	TINT
    43  	TUINT
    44  	TUINTPTR
    45  
    46  	TCOMPLEX64
    47  	TCOMPLEX128
    48  
    49  	TFLOAT32
    50  	TFLOAT64
    51  
    52  	TBOOL
    53  
    54  	TPTR
    55  	TFUNC
    56  	TSLICE
    57  	TARRAY
    58  	TSTRUCT
    59  	TCHAN
    60  	TMAP
    61  	TINTER
    62  	TFORW
    63  	TANY
    64  	TSTRING
    65  	TUNSAFEPTR
    66  
    67  	// pseudo-types for literals
    68  	TIDEAL // untyped numeric constants
    69  	TNIL
    70  	TBLANK
    71  
    72  	// pseudo-types used temporarily only during frame layout (CalcSize())
    73  	TFUNCARGS
    74  	TCHANARGS
    75  
    76  	// SSA backend types
    77  	TSSA     // internal types used by SSA backend (flags, memory, etc.)
    78  	TTUPLE   // a pair of types, used by SSA backend
    79  	TRESULTS // multiple types; the result of calling a function or method, with a memory at the end.
    80  
    81  	NTYPE
    82  )
    83  
    84  // ChanDir is whether a channel can send, receive, or both.
    85  type ChanDir uint8
    86  
    87  func (c ChanDir) CanRecv() bool { return c&Crecv != 0 }
    88  func (c ChanDir) CanSend() bool { return c&Csend != 0 }
    89  
    90  const (
    91  	// types of channel
    92  	// must match ../../../../reflect/type.go:/ChanDir
    93  	Crecv ChanDir = 1 << 0
    94  	Csend ChanDir = 1 << 1
    95  	Cboth ChanDir = Crecv | Csend
    96  )
    97  
    98  // Types stores pointers to predeclared named types.
    99  //
   100  // It also stores pointers to several special types:
   101  //   - Types[TANY] is the placeholder "any" type recognized by SubstArgTypes.
   102  //   - Types[TBLANK] represents the blank variable's type.
   103  //   - Types[TINTER] is the canonical "interface{}" type.
   104  //   - Types[TNIL] represents the predeclared "nil" value's type.
   105  //   - Types[TUNSAFEPTR] is package unsafe's Pointer type.
   106  var Types [NTYPE]*Type
   107  
   108  var (
   109  	// Predeclared alias types. These are actually created as distinct
   110  	// defined types for better error messages, but are then specially
   111  	// treated as identical to their respective underlying types.
   112  	AnyType  *Type
   113  	ByteType *Type
   114  	RuneType *Type
   115  
   116  	// Predeclared error interface type.
   117  	ErrorType *Type
   118  	// Predeclared comparable interface type.
   119  	ComparableType *Type
   120  
   121  	// Types to represent untyped string and boolean constants.
   122  	UntypedString = newType(TSTRING)
   123  	UntypedBool   = newType(TBOOL)
   124  
   125  	// Types to represent untyped numeric constants.
   126  	UntypedInt     = newType(TIDEAL)
   127  	UntypedRune    = newType(TIDEAL)
   128  	UntypedFloat   = newType(TIDEAL)
   129  	UntypedComplex = newType(TIDEAL)
   130  )
   131  
   132  // UntypedTypes maps from a constant.Kind to its untyped Type
   133  // representation.
   134  var UntypedTypes = [...]*Type{
   135  	constant.Bool:    UntypedBool,
   136  	constant.String:  UntypedString,
   137  	constant.Int:     UntypedInt,
   138  	constant.Float:   UntypedFloat,
   139  	constant.Complex: UntypedComplex,
   140  }
   141  
   142  // DefaultKinds maps from a constant.Kind to its default Kind.
   143  var DefaultKinds = [...]Kind{
   144  	constant.Bool:    TBOOL,
   145  	constant.String:  TSTRING,
   146  	constant.Int:     TINT,
   147  	constant.Float:   TFLOAT64,
   148  	constant.Complex: TCOMPLEX128,
   149  }
   150  
   151  // A Type represents a Go type.
   152  //
   153  // There may be multiple unnamed types with identical structure. However, there must
   154  // be a unique Type object for each unique named (defined) type. After noding, a
   155  // package-level type can be looked up by building its unique symbol sym (sym =
   156  // package.Lookup(name)) and checking sym.Def. If sym.Def is non-nil, the type
   157  // already exists at package scope and is available at sym.Def.(*ir.Name).Type().
   158  // Local types (which may have the same name as a package-level type) are
   159  // distinguished by their vargen, which is embedded in their symbol name.
   160  type Type struct {
   161  	// extra contains extra etype-specific fields.
   162  	// As an optimization, those etype-specific structs which contain exactly
   163  	// one pointer-shaped field are stored as values rather than pointers when possible.
   164  	//
   165  	// TMAP: *Map
   166  	// TFORW: *Forward
   167  	// TFUNC: *Func
   168  	// TSTRUCT: *Struct
   169  	// TINTER: *Interface
   170  	// TFUNCARGS: FuncArgs
   171  	// TCHANARGS: ChanArgs
   172  	// TCHAN: *Chan
   173  	// TPTR: Ptr
   174  	// TARRAY: *Array
   175  	// TSLICE: Slice
   176  	// TSSA: string
   177  	extra interface{}
   178  
   179  	// width is the width of this Type in bytes.
   180  	width int64 // valid if Align > 0
   181  
   182  	// list of base methods (excluding embedding)
   183  	methods fields
   184  	// list of all methods (including embedding)
   185  	allMethods fields
   186  
   187  	// canonical OTYPE node for a named type (should be an ir.Name node with same sym)
   188  	obj Object
   189  	// the underlying type (type literal or predeclared type) for a defined type
   190  	underlying *Type
   191  
   192  	// Cache of composite types, with this type being the element type.
   193  	cache struct {
   194  		ptr   *Type // *T, or nil
   195  		slice *Type // []T, or nil
   196  	}
   197  
   198  	kind  Kind  // kind of type
   199  	align uint8 // the required alignment of this type, in bytes (0 means Width and Align have not yet been computed)
   200  
   201  	intRegs, floatRegs uint8 // registers needed for ABIInternal
   202  
   203  	flags bitset8
   204  
   205  	// For defined (named) generic types, a pointer to the list of type params
   206  	// (in order) of this type that need to be instantiated. For instantiated
   207  	// generic types, this is the targs used to instantiate them. These targs
   208  	// may be typeparams (for re-instantiated types such as Value[T2]) or
   209  	// concrete types (for fully instantiated types such as Value[int]).
   210  	// rparams is only set for named types that are generic or are fully
   211  	// instantiated from a generic type, and is otherwise set to nil.
   212  	// TODO(danscales): choose a better name.
   213  	rparams *[]*Type
   214  }
   215  
   216  // Registers returns the number of integer and floating-point
   217  // registers required to represent a parameter of this type under the
   218  // ABIInternal calling conventions.
   219  //
   220  // If t must be passed by memory, Registers returns (math.MaxUint8,
   221  // math.MaxUint8).
   222  func (t *Type) Registers() (uint8, uint8) {
   223  	CalcSize(t)
   224  	return t.intRegs, t.floatRegs
   225  }
   226  
   227  func (*Type) CanBeAnSSAAux() {}
   228  
   229  const (
   230  	typeNotInHeap  = 1 << iota // type cannot be heap allocated
   231  	typeNoalg                  // suppress hash and eq algorithm generation
   232  	typeDeferwidth             // width computation has been deferred and type is on deferredTypeStack
   233  	typeRecur
   234  	typeIsShape  // represents a set of closely related types, for generics
   235  	typeHasShape // there is a shape somewhere in the type
   236  )
   237  
   238  func (t *Type) NotInHeap() bool  { return t.flags&typeNotInHeap != 0 }
   239  func (t *Type) Noalg() bool      { return t.flags&typeNoalg != 0 }
   240  func (t *Type) Deferwidth() bool { return t.flags&typeDeferwidth != 0 }
   241  func (t *Type) Recur() bool      { return t.flags&typeRecur != 0 }
   242  func (t *Type) IsShape() bool    { return t.flags&typeIsShape != 0 }
   243  func (t *Type) HasShape() bool   { return t.flags&typeHasShape != 0 }
   244  
   245  func (t *Type) SetNotInHeap(b bool)  { t.flags.set(typeNotInHeap, b) }
   246  func (t *Type) SetNoalg(b bool)      { t.flags.set(typeNoalg, b) }
   247  func (t *Type) SetDeferwidth(b bool) { t.flags.set(typeDeferwidth, b) }
   248  func (t *Type) SetRecur(b bool)      { t.flags.set(typeRecur, b) }
   249  
   250  // Should always do SetHasShape(true) when doing SetIsShape(true).
   251  func (t *Type) SetIsShape(b bool)  { t.flags.set(typeIsShape, b) }
   252  func (t *Type) SetHasShape(b bool) { t.flags.set(typeHasShape, b) }
   253  
   254  // Kind returns the kind of type t.
   255  func (t *Type) Kind() Kind { return t.kind }
   256  
   257  // Sym returns the name of type t.
   258  func (t *Type) Sym() *Sym {
   259  	if t.obj != nil {
   260  		return t.obj.Sym()
   261  	}
   262  	return nil
   263  }
   264  
   265  // Underlying returns the underlying type of type t.
   266  func (t *Type) Underlying() *Type { return t.underlying }
   267  
   268  // Pos returns a position associated with t, if any.
   269  // This should only be used for diagnostics.
   270  func (t *Type) Pos() src.XPos {
   271  	if t.obj != nil {
   272  		return t.obj.Pos()
   273  	}
   274  	return src.NoXPos
   275  }
   276  
   277  func (t *Type) RParams() []*Type {
   278  	if t.rparams == nil {
   279  		return nil
   280  	}
   281  	return *t.rparams
   282  }
   283  
   284  func (t *Type) SetRParams(rparams []*Type) {
   285  	if len(rparams) == 0 {
   286  		base.Fatalf("Setting nil or zero-length rparams")
   287  	}
   288  	t.rparams = &rparams
   289  	// HasShape should be set if any type argument is or has a shape type.
   290  	for _, rparam := range rparams {
   291  		if rparam.HasShape() {
   292  			t.SetHasShape(true)
   293  			break
   294  		}
   295  	}
   296  }
   297  
   298  // IsFullyInstantiated reports whether t is a fully instantiated generic type; i.e. an
   299  // instantiated generic type where all type arguments are non-generic or fully
   300  // instantiated generic types.
   301  func (t *Type) IsFullyInstantiated() bool {
   302  	return len(t.RParams()) > 0
   303  }
   304  
   305  // Map contains Type fields specific to maps.
   306  type Map struct {
   307  	Key  *Type // Key type
   308  	Elem *Type // Val (elem) type
   309  
   310  	Bucket *Type // internal struct type representing a hash bucket
   311  }
   312  
   313  // MapType returns t's extra map-specific fields.
   314  func (t *Type) MapType() *Map {
   315  	t.wantEtype(TMAP)
   316  	return t.extra.(*Map)
   317  }
   318  
   319  // Forward contains Type fields specific to forward types.
   320  type Forward struct {
   321  	Copyto      []*Type  // where to copy the eventual value to
   322  	Embedlineno src.XPos // first use of this type as an embedded type
   323  }
   324  
   325  // forwardType returns t's extra forward-type-specific fields.
   326  func (t *Type) forwardType() *Forward {
   327  	t.wantEtype(TFORW)
   328  	return t.extra.(*Forward)
   329  }
   330  
   331  // Func contains Type fields specific to func types.
   332  type Func struct {
   333  	allParams []*Field // slice of all parameters, in receiver/params/results order
   334  
   335  	startParams  int // index of the start of the (regular) parameters section
   336  	startResults int // index of the start of the results section
   337  
   338  	resultsTuple *Type // struct-like type representing multi-value results
   339  
   340  	// Argwid is the total width of the function receiver, params, and results.
   341  	// It gets calculated via a temporary TFUNCARGS type.
   342  	// Note that TFUNC's Width is Widthptr.
   343  	Argwid int64
   344  }
   345  
   346  func (ft *Func) recvs() []*Field         { return ft.allParams[:ft.startParams] }
   347  func (ft *Func) params() []*Field        { return ft.allParams[ft.startParams:ft.startResults] }
   348  func (ft *Func) results() []*Field       { return ft.allParams[ft.startResults:] }
   349  func (ft *Func) recvParams() []*Field    { return ft.allParams[:ft.startResults] }
   350  func (ft *Func) paramsResults() []*Field { return ft.allParams[ft.startParams:] }
   351  
   352  // funcType returns t's extra func-specific fields.
   353  func (t *Type) funcType() *Func {
   354  	t.wantEtype(TFUNC)
   355  	return t.extra.(*Func)
   356  }
   357  
   358  // StructType contains Type fields specific to struct types.
   359  type Struct struct {
   360  	fields fields
   361  
   362  	// Maps have three associated internal structs (see struct MapType).
   363  	// Map links such structs back to their map type.
   364  	Map *Type
   365  
   366  	ParamTuple bool // whether this struct is actually a tuple of signature parameters
   367  }
   368  
   369  // StructType returns t's extra struct-specific fields.
   370  func (t *Type) StructType() *Struct {
   371  	t.wantEtype(TSTRUCT)
   372  	return t.extra.(*Struct)
   373  }
   374  
   375  // Interface contains Type fields specific to interface types.
   376  type Interface struct {
   377  }
   378  
   379  // Ptr contains Type fields specific to pointer types.
   380  type Ptr struct {
   381  	Elem *Type // element type
   382  }
   383  
   384  // ChanArgs contains Type fields specific to TCHANARGS types.
   385  type ChanArgs struct {
   386  	T *Type // reference to a chan type whose elements need a width check
   387  }
   388  
   389  // // FuncArgs contains Type fields specific to TFUNCARGS types.
   390  type FuncArgs struct {
   391  	T *Type // reference to a func type whose elements need a width check
   392  }
   393  
   394  // Chan contains Type fields specific to channel types.
   395  type Chan struct {
   396  	Elem *Type   // element type
   397  	Dir  ChanDir // channel direction
   398  }
   399  
   400  // chanType returns t's extra channel-specific fields.
   401  func (t *Type) chanType() *Chan {
   402  	t.wantEtype(TCHAN)
   403  	return t.extra.(*Chan)
   404  }
   405  
   406  type Tuple struct {
   407  	first  *Type
   408  	second *Type
   409  	// Any tuple with a memory type must put that memory type second.
   410  }
   411  
   412  // Results are the output from calls that will be late-expanded.
   413  type Results struct {
   414  	Types []*Type // Last element is memory output from call.
   415  }
   416  
   417  // Array contains Type fields specific to array types.
   418  type Array struct {
   419  	Elem  *Type // element type
   420  	Bound int64 // number of elements; <0 if unknown yet
   421  }
   422  
   423  // Slice contains Type fields specific to slice types.
   424  type Slice struct {
   425  	Elem *Type // element type
   426  }
   427  
   428  // A Field is a (Sym, Type) pairing along with some other information, and,
   429  // depending on the context, is used to represent:
   430  //   - a field in a struct
   431  //   - a method in an interface or associated with a named type
   432  //   - a function parameter
   433  type Field struct {
   434  	flags bitset8
   435  
   436  	Embedded uint8 // embedded field
   437  
   438  	Pos src.XPos
   439  
   440  	// Name of field/method/parameter. Can be nil for interface fields embedded
   441  	// in interfaces and unnamed parameters.
   442  	Sym  *Sym
   443  	Type *Type  // field type
   444  	Note string // literal string annotation
   445  
   446  	// For fields that represent function parameters, Nname points to the
   447  	// associated ONAME Node. For fields that represent methods, Nname points to
   448  	// the function name node.
   449  	Nname Object
   450  
   451  	// Offset in bytes of this field or method within its enclosing struct
   452  	// or interface Type. For parameters, this is BADWIDTH.
   453  	Offset int64
   454  }
   455  
   456  const (
   457  	fieldIsDDD = 1 << iota // field is ... argument
   458  	fieldNointerface
   459  )
   460  
   461  func (f *Field) IsDDD() bool       { return f.flags&fieldIsDDD != 0 }
   462  func (f *Field) Nointerface() bool { return f.flags&fieldNointerface != 0 }
   463  
   464  func (f *Field) SetIsDDD(b bool)       { f.flags.set(fieldIsDDD, b) }
   465  func (f *Field) SetNointerface(b bool) { f.flags.set(fieldNointerface, b) }
   466  
   467  // End returns the offset of the first byte immediately after this field.
   468  func (f *Field) End() int64 {
   469  	return f.Offset + f.Type.width
   470  }
   471  
   472  // IsMethod reports whether f represents a method rather than a struct field.
   473  func (f *Field) IsMethod() bool {
   474  	return f.Type.kind == TFUNC && f.Type.Recv() != nil
   475  }
   476  
   477  // fields is a pointer to a slice of *Field.
   478  // This saves space in Types that do not have fields or methods
   479  // compared to a simple slice of *Field.
   480  type fields struct {
   481  	s *[]*Field
   482  }
   483  
   484  // Slice returns the entries in f as a slice.
   485  // Changes to the slice entries will be reflected in f.
   486  func (f *fields) Slice() []*Field {
   487  	if f.s == nil {
   488  		return nil
   489  	}
   490  	return *f.s
   491  }
   492  
   493  // Set sets f to a slice.
   494  // This takes ownership of the slice.
   495  func (f *fields) Set(s []*Field) {
   496  	if len(s) == 0 {
   497  		f.s = nil
   498  	} else {
   499  		// Copy s and take address of t rather than s to avoid
   500  		// allocation in the case where len(s) == 0.
   501  		t := s
   502  		f.s = &t
   503  	}
   504  }
   505  
   506  // newType returns a new Type of the specified kind.
   507  func newType(et Kind) *Type {
   508  	t := &Type{
   509  		kind:  et,
   510  		width: BADWIDTH,
   511  	}
   512  	t.underlying = t
   513  	// TODO(josharian): lazily initialize some of these?
   514  	switch t.kind {
   515  	case TMAP:
   516  		t.extra = new(Map)
   517  	case TFORW:
   518  		t.extra = new(Forward)
   519  	case TFUNC:
   520  		t.extra = new(Func)
   521  	case TSTRUCT:
   522  		t.extra = new(Struct)
   523  	case TINTER:
   524  		t.extra = new(Interface)
   525  	case TPTR:
   526  		t.extra = Ptr{}
   527  	case TCHANARGS:
   528  		t.extra = ChanArgs{}
   529  	case TFUNCARGS:
   530  		t.extra = FuncArgs{}
   531  	case TCHAN:
   532  		t.extra = new(Chan)
   533  	case TTUPLE:
   534  		t.extra = new(Tuple)
   535  	case TRESULTS:
   536  		t.extra = new(Results)
   537  	}
   538  	return t
   539  }
   540  
   541  // NewArray returns a new fixed-length array Type.
   542  func NewArray(elem *Type, bound int64) *Type {
   543  	if bound < 0 {
   544  		base.Fatalf("NewArray: invalid bound %v", bound)
   545  	}
   546  	t := newType(TARRAY)
   547  	t.extra = &Array{Elem: elem, Bound: bound}
   548  	if elem.HasShape() {
   549  		t.SetHasShape(true)
   550  	}
   551  	return t
   552  }
   553  
   554  // NewSlice returns the slice Type with element type elem.
   555  func NewSlice(elem *Type) *Type {
   556  	if t := elem.cache.slice; t != nil {
   557  		if t.Elem() != elem {
   558  			base.Fatalf("elem mismatch")
   559  		}
   560  		if elem.HasShape() != t.HasShape() {
   561  			base.Fatalf("Incorrect HasShape flag for cached slice type")
   562  		}
   563  		return t
   564  	}
   565  
   566  	t := newType(TSLICE)
   567  	t.extra = Slice{Elem: elem}
   568  	elem.cache.slice = t
   569  	if elem.HasShape() {
   570  		t.SetHasShape(true)
   571  	}
   572  	return t
   573  }
   574  
   575  // NewChan returns a new chan Type with direction dir.
   576  func NewChan(elem *Type, dir ChanDir) *Type {
   577  	t := newType(TCHAN)
   578  	ct := t.chanType()
   579  	ct.Elem = elem
   580  	ct.Dir = dir
   581  	if elem.HasShape() {
   582  		t.SetHasShape(true)
   583  	}
   584  	return t
   585  }
   586  
   587  func NewTuple(t1, t2 *Type) *Type {
   588  	t := newType(TTUPLE)
   589  	t.extra.(*Tuple).first = t1
   590  	t.extra.(*Tuple).second = t2
   591  	if t1.HasShape() || t2.HasShape() {
   592  		t.SetHasShape(true)
   593  	}
   594  	return t
   595  }
   596  
   597  func newResults(types []*Type) *Type {
   598  	t := newType(TRESULTS)
   599  	t.extra.(*Results).Types = types
   600  	return t
   601  }
   602  
   603  func NewResults(types []*Type) *Type {
   604  	if len(types) == 1 && types[0] == TypeMem {
   605  		return TypeResultMem
   606  	}
   607  	return newResults(types)
   608  }
   609  
   610  func newSSA(name string) *Type {
   611  	t := newType(TSSA)
   612  	t.extra = name
   613  	return t
   614  }
   615  
   616  // NewMap returns a new map Type with key type k and element (aka value) type v.
   617  func NewMap(k, v *Type) *Type {
   618  	t := newType(TMAP)
   619  	mt := t.MapType()
   620  	mt.Key = k
   621  	mt.Elem = v
   622  	if k.HasShape() || v.HasShape() {
   623  		t.SetHasShape(true)
   624  	}
   625  	return t
   626  }
   627  
   628  // NewPtrCacheEnabled controls whether *T Types are cached in T.
   629  // Caching is disabled just before starting the backend.
   630  // This allows the backend to run concurrently.
   631  var NewPtrCacheEnabled = true
   632  
   633  // NewPtr returns the pointer type pointing to t.
   634  func NewPtr(elem *Type) *Type {
   635  	if elem == nil {
   636  		base.Fatalf("NewPtr: pointer to elem Type is nil")
   637  	}
   638  
   639  	if t := elem.cache.ptr; t != nil {
   640  		if t.Elem() != elem {
   641  			base.Fatalf("NewPtr: elem mismatch")
   642  		}
   643  		if elem.HasShape() != t.HasShape() {
   644  			base.Fatalf("Incorrect HasShape flag for cached pointer type")
   645  		}
   646  		return t
   647  	}
   648  
   649  	t := newType(TPTR)
   650  	t.extra = Ptr{Elem: elem}
   651  	t.width = int64(PtrSize)
   652  	t.align = uint8(PtrSize)
   653  	t.intRegs = 1
   654  	if NewPtrCacheEnabled {
   655  		elem.cache.ptr = t
   656  	}
   657  	if elem.HasShape() {
   658  		t.SetHasShape(true)
   659  	}
   660  	if elem.Noalg() {
   661  		t.SetNoalg(true)
   662  	}
   663  	return t
   664  }
   665  
   666  // NewChanArgs returns a new TCHANARGS type for channel type c.
   667  func NewChanArgs(c *Type) *Type {
   668  	t := newType(TCHANARGS)
   669  	t.extra = ChanArgs{T: c}
   670  	return t
   671  }
   672  
   673  // NewFuncArgs returns a new TFUNCARGS type for func type f.
   674  func NewFuncArgs(f *Type) *Type {
   675  	t := newType(TFUNCARGS)
   676  	t.extra = FuncArgs{T: f}
   677  	return t
   678  }
   679  
   680  func NewField(pos src.XPos, sym *Sym, typ *Type) *Field {
   681  	f := &Field{
   682  		Pos:    pos,
   683  		Sym:    sym,
   684  		Type:   typ,
   685  		Offset: BADWIDTH,
   686  	}
   687  	if typ == nil {
   688  		base.Fatalf("typ is nil")
   689  	}
   690  	return f
   691  }
   692  
   693  // SubstAny walks t, replacing instances of "any" with successive
   694  // elements removed from types.  It returns the substituted type.
   695  func SubstAny(t *Type, types *[]*Type) *Type {
   696  	if t == nil {
   697  		return nil
   698  	}
   699  
   700  	switch t.kind {
   701  	default:
   702  		// Leave the type unchanged.
   703  
   704  	case TANY:
   705  		if len(*types) == 0 {
   706  			base.Fatalf("SubstArgTypes: not enough argument types")
   707  		}
   708  		t = (*types)[0]
   709  		*types = (*types)[1:]
   710  
   711  	case TPTR:
   712  		elem := SubstAny(t.Elem(), types)
   713  		if elem != t.Elem() {
   714  			t = t.copy()
   715  			t.extra = Ptr{Elem: elem}
   716  		}
   717  
   718  	case TARRAY:
   719  		elem := SubstAny(t.Elem(), types)
   720  		if elem != t.Elem() {
   721  			t = t.copy()
   722  			t.extra.(*Array).Elem = elem
   723  		}
   724  
   725  	case TSLICE:
   726  		elem := SubstAny(t.Elem(), types)
   727  		if elem != t.Elem() {
   728  			t = t.copy()
   729  			t.extra = Slice{Elem: elem}
   730  		}
   731  
   732  	case TCHAN:
   733  		elem := SubstAny(t.Elem(), types)
   734  		if elem != t.Elem() {
   735  			t = t.copy()
   736  			t.extra.(*Chan).Elem = elem
   737  		}
   738  
   739  	case TMAP:
   740  		key := SubstAny(t.Key(), types)
   741  		elem := SubstAny(t.Elem(), types)
   742  		if key != t.Key() || elem != t.Elem() {
   743  			t = t.copy()
   744  			t.extra.(*Map).Key = key
   745  			t.extra.(*Map).Elem = elem
   746  		}
   747  
   748  	case TFUNC:
   749  		ft := t.funcType()
   750  		allParams := substFields(ft.allParams, types)
   751  
   752  		t = t.copy()
   753  		ft = t.funcType()
   754  		ft.allParams = allParams
   755  
   756  		rt := ft.resultsTuple
   757  		rt = rt.copy()
   758  		ft.resultsTuple = rt
   759  		rt.setFields(t.Results())
   760  
   761  	case TSTRUCT:
   762  		// Make a copy of all fields, including ones whose type does not change.
   763  		// This prevents aliasing across functions, which can lead to later
   764  		// fields getting their Offset incorrectly overwritten.
   765  		nfs := substFields(t.Fields(), types)
   766  		t = t.copy()
   767  		t.setFields(nfs)
   768  	}
   769  
   770  	return t
   771  }
   772  
   773  func substFields(fields []*Field, types *[]*Type) []*Field {
   774  	nfs := make([]*Field, len(fields))
   775  	for i, f := range fields {
   776  		nft := SubstAny(f.Type, types)
   777  		nfs[i] = f.Copy()
   778  		nfs[i].Type = nft
   779  	}
   780  	return nfs
   781  }
   782  
   783  // copy returns a shallow copy of the Type.
   784  func (t *Type) copy() *Type {
   785  	if t == nil {
   786  		return nil
   787  	}
   788  	nt := *t
   789  	// copy any *T Extra fields, to avoid aliasing
   790  	switch t.kind {
   791  	case TMAP:
   792  		x := *t.extra.(*Map)
   793  		nt.extra = &x
   794  	case TFORW:
   795  		x := *t.extra.(*Forward)
   796  		nt.extra = &x
   797  	case TFUNC:
   798  		x := *t.extra.(*Func)
   799  		nt.extra = &x
   800  	case TSTRUCT:
   801  		x := *t.extra.(*Struct)
   802  		nt.extra = &x
   803  	case TINTER:
   804  		x := *t.extra.(*Interface)
   805  		nt.extra = &x
   806  	case TCHAN:
   807  		x := *t.extra.(*Chan)
   808  		nt.extra = &x
   809  	case TARRAY:
   810  		x := *t.extra.(*Array)
   811  		nt.extra = &x
   812  	case TTUPLE, TSSA, TRESULTS:
   813  		base.Fatalf("ssa types cannot be copied")
   814  	}
   815  	// TODO(mdempsky): Find out why this is necessary and explain.
   816  	if t.underlying == t {
   817  		nt.underlying = &nt
   818  	}
   819  	return &nt
   820  }
   821  
   822  func (f *Field) Copy() *Field {
   823  	nf := *f
   824  	return &nf
   825  }
   826  
   827  func (t *Type) wantEtype(et Kind) {
   828  	if t.kind != et {
   829  		base.Fatalf("want %v, but have %v", et, t)
   830  	}
   831  }
   832  
   833  // ResultTuple returns the result type of signature type t as a tuple.
   834  // This can be used as the type of multi-valued call expressions.
   835  func (t *Type) ResultsTuple() *Type { return t.funcType().resultsTuple }
   836  
   837  // Recvs returns a slice of receiver parameters of signature type t.
   838  // The returned slice always has length 0 or 1.
   839  func (t *Type) Recvs() []*Field { return t.funcType().recvs() }
   840  
   841  // Params returns a slice of regular parameters of signature type t.
   842  func (t *Type) Params() []*Field { return t.funcType().params() }
   843  
   844  // Results returns a slice of result parameters of signature type t.
   845  func (t *Type) Results() []*Field { return t.funcType().results() }
   846  
   847  // RecvsParamsResults returns a slice containing all of the
   848  // signature's parameters in receiver (if any), (normal) parameters,
   849  // and then results.
   850  func (t *Type) RecvParamsResults() []*Field { return t.funcType().allParams }
   851  
   852  // RecvParams returns a slice containing the signature's receiver (if
   853  // any) followed by its (normal) parameters.
   854  func (t *Type) RecvParams() []*Field { return t.funcType().recvParams() }
   855  
   856  // ParamsResults returns a slice containing the signature's (normal)
   857  // parameters followed by its results.
   858  func (t *Type) ParamsResults() []*Field { return t.funcType().paramsResults() }
   859  
   860  func (t *Type) NumRecvs() int   { return len(t.Recvs()) }
   861  func (t *Type) NumParams() int  { return len(t.Params()) }
   862  func (t *Type) NumResults() int { return len(t.Results()) }
   863  
   864  // IsVariadic reports whether function type t is variadic.
   865  func (t *Type) IsVariadic() bool {
   866  	n := t.NumParams()
   867  	return n > 0 && t.Param(n-1).IsDDD()
   868  }
   869  
   870  // Recv returns the receiver of function type t, if any.
   871  func (t *Type) Recv() *Field {
   872  	if s := t.Recvs(); len(s) == 1 {
   873  		return s[0]
   874  	}
   875  	return nil
   876  }
   877  
   878  // Param returns the i'th parameter of signature type t.
   879  func (t *Type) Param(i int) *Field { return t.Params()[i] }
   880  
   881  // Result returns the i'th result of signature type t.
   882  func (t *Type) Result(i int) *Field { return t.Results()[i] }
   883  
   884  // Key returns the key type of map type t.
   885  func (t *Type) Key() *Type {
   886  	t.wantEtype(TMAP)
   887  	return t.extra.(*Map).Key
   888  }
   889  
   890  // Elem returns the type of elements of t.
   891  // Usable with pointers, channels, arrays, slices, and maps.
   892  func (t *Type) Elem() *Type {
   893  	switch t.kind {
   894  	case TPTR:
   895  		return t.extra.(Ptr).Elem
   896  	case TARRAY:
   897  		return t.extra.(*Array).Elem
   898  	case TSLICE:
   899  		return t.extra.(Slice).Elem
   900  	case TCHAN:
   901  		return t.extra.(*Chan).Elem
   902  	case TMAP:
   903  		return t.extra.(*Map).Elem
   904  	}
   905  	base.Fatalf("Type.Elem %s", t.kind)
   906  	return nil
   907  }
   908  
   909  // ChanArgs returns the channel type for TCHANARGS type t.
   910  func (t *Type) ChanArgs() *Type {
   911  	t.wantEtype(TCHANARGS)
   912  	return t.extra.(ChanArgs).T
   913  }
   914  
   915  // FuncArgs returns the func type for TFUNCARGS type t.
   916  func (t *Type) FuncArgs() *Type {
   917  	t.wantEtype(TFUNCARGS)
   918  	return t.extra.(FuncArgs).T
   919  }
   920  
   921  // IsFuncArgStruct reports whether t is a struct representing function parameters or results.
   922  func (t *Type) IsFuncArgStruct() bool {
   923  	return t.kind == TSTRUCT && t.extra.(*Struct).ParamTuple
   924  }
   925  
   926  // Methods returns a pointer to the base methods (excluding embedding) for type t.
   927  // These can either be concrete methods (for non-interface types) or interface
   928  // methods (for interface types).
   929  func (t *Type) Methods() []*Field {
   930  	return t.methods.Slice()
   931  }
   932  
   933  // AllMethods returns a pointer to all the methods (including embedding) for type t.
   934  // For an interface type, this is the set of methods that are typically iterated
   935  // over. For non-interface types, AllMethods() only returns a valid result after
   936  // CalcMethods() has been called at least once.
   937  func (t *Type) AllMethods() []*Field {
   938  	if t.kind == TINTER {
   939  		// Calculate the full method set of an interface type on the fly
   940  		// now, if not done yet.
   941  		CalcSize(t)
   942  	}
   943  	return t.allMethods.Slice()
   944  }
   945  
   946  // SetMethods sets the direct method set for type t (i.e., *not*
   947  // including promoted methods from embedded types).
   948  func (t *Type) SetMethods(fs []*Field) {
   949  	t.methods.Set(fs)
   950  }
   951  
   952  // SetAllMethods sets the set of all methods for type t (i.e.,
   953  // including promoted methods from embedded types).
   954  func (t *Type) SetAllMethods(fs []*Field) {
   955  	t.allMethods.Set(fs)
   956  }
   957  
   958  // fields returns the fields of struct type t.
   959  func (t *Type) fields() *fields {
   960  	t.wantEtype(TSTRUCT)
   961  	return &t.extra.(*Struct).fields
   962  }
   963  
   964  // Field returns the i'th field of struct type t.
   965  func (t *Type) Field(i int) *Field { return t.Fields()[i] }
   966  
   967  // Fields returns a slice of containing all fields of
   968  // a struct type t.
   969  func (t *Type) Fields() []*Field { return t.fields().Slice() }
   970  
   971  // setFields sets struct type t's fields to fields.
   972  func (t *Type) setFields(fields []*Field) {
   973  	// If we've calculated the width of t before,
   974  	// then some other type such as a function signature
   975  	// might now have the wrong type.
   976  	// Rather than try to track and invalidate those,
   977  	// enforce that SetFields cannot be called once
   978  	// t's width has been calculated.
   979  	if t.widthCalculated() {
   980  		base.Fatalf("SetFields of %v: width previously calculated", t)
   981  	}
   982  	t.wantEtype(TSTRUCT)
   983  	t.fields().Set(fields)
   984  }
   985  
   986  // SetInterface sets the base methods of an interface type t.
   987  func (t *Type) SetInterface(methods []*Field) {
   988  	t.wantEtype(TINTER)
   989  	t.methods.Set(methods)
   990  }
   991  
   992  // ArgWidth returns the total aligned argument size for a function.
   993  // It includes the receiver, parameters, and results.
   994  func (t *Type) ArgWidth() int64 {
   995  	t.wantEtype(TFUNC)
   996  	return t.extra.(*Func).Argwid
   997  }
   998  
   999  func (t *Type) Size() int64 {
  1000  	if t.kind == TSSA {
  1001  		if t == TypeInt128 {
  1002  			return 16
  1003  		}
  1004  		return 0
  1005  	}
  1006  	CalcSize(t)
  1007  	return t.width
  1008  }
  1009  
  1010  func (t *Type) Alignment() int64 {
  1011  	CalcSize(t)
  1012  	return int64(t.align)
  1013  }
  1014  
  1015  func (t *Type) SimpleString() string {
  1016  	return t.kind.String()
  1017  }
  1018  
  1019  // Cmp is a comparison between values a and b.
  1020  //
  1021  //	-1 if a < b
  1022  //	 0 if a == b
  1023  //	 1 if a > b
  1024  type Cmp int8
  1025  
  1026  const (
  1027  	CMPlt = Cmp(-1)
  1028  	CMPeq = Cmp(0)
  1029  	CMPgt = Cmp(1)
  1030  )
  1031  
  1032  // Compare compares types for purposes of the SSA back
  1033  // end, returning a Cmp (one of CMPlt, CMPeq, CMPgt).
  1034  // The answers are correct for an optimizer
  1035  // or code generator, but not necessarily typechecking.
  1036  // The order chosen is arbitrary, only consistency and division
  1037  // into equivalence classes (Types that compare CMPeq) matters.
  1038  func (t *Type) Compare(x *Type) Cmp {
  1039  	if x == t {
  1040  		return CMPeq
  1041  	}
  1042  	return t.cmp(x)
  1043  }
  1044  
  1045  func cmpForNe(x bool) Cmp {
  1046  	if x {
  1047  		return CMPlt
  1048  	}
  1049  	return CMPgt
  1050  }
  1051  
  1052  func (r *Sym) cmpsym(s *Sym) Cmp {
  1053  	if r == s {
  1054  		return CMPeq
  1055  	}
  1056  	if r == nil {
  1057  		return CMPlt
  1058  	}
  1059  	if s == nil {
  1060  		return CMPgt
  1061  	}
  1062  	// Fast sort, not pretty sort
  1063  	if len(r.Name) != len(s.Name) {
  1064  		return cmpForNe(len(r.Name) < len(s.Name))
  1065  	}
  1066  	if r.Pkg != s.Pkg {
  1067  		if len(r.Pkg.Prefix) != len(s.Pkg.Prefix) {
  1068  			return cmpForNe(len(r.Pkg.Prefix) < len(s.Pkg.Prefix))
  1069  		}
  1070  		if r.Pkg.Prefix != s.Pkg.Prefix {
  1071  			return cmpForNe(r.Pkg.Prefix < s.Pkg.Prefix)
  1072  		}
  1073  	}
  1074  	if r.Name != s.Name {
  1075  		return cmpForNe(r.Name < s.Name)
  1076  	}
  1077  	return CMPeq
  1078  }
  1079  
  1080  // cmp compares two *Types t and x, returning CMPlt,
  1081  // CMPeq, CMPgt as t<x, t==x, t>x, for an arbitrary
  1082  // and optimizer-centric notion of comparison.
  1083  // TODO(josharian): make this safe for recursive interface types
  1084  // and use in signatlist sorting. See issue 19869.
  1085  func (t *Type) cmp(x *Type) Cmp {
  1086  	// This follows the structure of function identical in identity.go
  1087  	// with two exceptions.
  1088  	// 1. Symbols are compared more carefully because a <,=,> result is desired.
  1089  	// 2. Maps are treated specially to avoid endless recursion -- maps
  1090  	//    contain an internal data type not expressible in Go source code.
  1091  	if t == x {
  1092  		return CMPeq
  1093  	}
  1094  	if t == nil {
  1095  		return CMPlt
  1096  	}
  1097  	if x == nil {
  1098  		return CMPgt
  1099  	}
  1100  
  1101  	if t.kind != x.kind {
  1102  		return cmpForNe(t.kind < x.kind)
  1103  	}
  1104  
  1105  	if t.obj != nil || x.obj != nil {
  1106  		// Special case: we keep byte and uint8 separate
  1107  		// for error messages. Treat them as equal.
  1108  		switch t.kind {
  1109  		case TUINT8:
  1110  			if (t == Types[TUINT8] || t == ByteType) && (x == Types[TUINT8] || x == ByteType) {
  1111  				return CMPeq
  1112  			}
  1113  
  1114  		case TINT32:
  1115  			if (t == Types[RuneType.kind] || t == RuneType) && (x == Types[RuneType.kind] || x == RuneType) {
  1116  				return CMPeq
  1117  			}
  1118  
  1119  		case TINTER:
  1120  			// Make sure named any type matches any empty interface.
  1121  			if t == AnyType && x.IsEmptyInterface() || x == AnyType && t.IsEmptyInterface() {
  1122  				return CMPeq
  1123  			}
  1124  		}
  1125  	}
  1126  
  1127  	if c := t.Sym().cmpsym(x.Sym()); c != CMPeq {
  1128  		return c
  1129  	}
  1130  
  1131  	if x.obj != nil {
  1132  		return CMPeq
  1133  	}
  1134  	// both syms nil, look at structure below.
  1135  
  1136  	switch t.kind {
  1137  	case TBOOL, TFLOAT32, TFLOAT64, TCOMPLEX64, TCOMPLEX128, TUNSAFEPTR, TUINTPTR,
  1138  		TINT8, TINT16, TINT32, TINT64, TINT, TUINT8, TUINT16, TUINT32, TUINT64, TUINT:
  1139  		return CMPeq
  1140  
  1141  	case TSSA:
  1142  		tname := t.extra.(string)
  1143  		xname := x.extra.(string)
  1144  		// desire fast sorting, not pretty sorting.
  1145  		if len(tname) == len(xname) {
  1146  			if tname == xname {
  1147  				return CMPeq
  1148  			}
  1149  			if tname < xname {
  1150  				return CMPlt
  1151  			}
  1152  			return CMPgt
  1153  		}
  1154  		if len(tname) > len(xname) {
  1155  			return CMPgt
  1156  		}
  1157  		return CMPlt
  1158  
  1159  	case TTUPLE:
  1160  		xtup := x.extra.(*Tuple)
  1161  		ttup := t.extra.(*Tuple)
  1162  		if c := ttup.first.Compare(xtup.first); c != CMPeq {
  1163  			return c
  1164  		}
  1165  		return ttup.second.Compare(xtup.second)
  1166  
  1167  	case TRESULTS:
  1168  		xResults := x.extra.(*Results)
  1169  		tResults := t.extra.(*Results)
  1170  		xl, tl := len(xResults.Types), len(tResults.Types)
  1171  		if tl != xl {
  1172  			if tl < xl {
  1173  				return CMPlt
  1174  			}
  1175  			return CMPgt
  1176  		}
  1177  		for i := 0; i < tl; i++ {
  1178  			if c := tResults.Types[i].Compare(xResults.Types[i]); c != CMPeq {
  1179  				return c
  1180  			}
  1181  		}
  1182  		return CMPeq
  1183  
  1184  	case TMAP:
  1185  		if c := t.Key().cmp(x.Key()); c != CMPeq {
  1186  			return c
  1187  		}
  1188  		return t.Elem().cmp(x.Elem())
  1189  
  1190  	case TPTR, TSLICE:
  1191  		// No special cases for these, they are handled
  1192  		// by the general code after the switch.
  1193  
  1194  	case TSTRUCT:
  1195  		if t.StructType().Map == nil {
  1196  			if x.StructType().Map != nil {
  1197  				return CMPlt // nil < non-nil
  1198  			}
  1199  			// to the fallthrough
  1200  		} else if x.StructType().Map == nil {
  1201  			return CMPgt // nil > non-nil
  1202  		} else if t.StructType().Map.MapType().Bucket == t {
  1203  			// Both have non-nil Map
  1204  			// Special case for Maps which include a recursive type where the recursion is not broken with a named type
  1205  			if x.StructType().Map.MapType().Bucket != x {
  1206  				return CMPlt // bucket maps are least
  1207  			}
  1208  			return t.StructType().Map.cmp(x.StructType().Map)
  1209  		} else if x.StructType().Map.MapType().Bucket == x {
  1210  			return CMPgt // bucket maps are least
  1211  		} // If t != t.Map.Bucket, fall through to general case
  1212  
  1213  		tfs := t.Fields()
  1214  		xfs := x.Fields()
  1215  		for i := 0; i < len(tfs) && i < len(xfs); i++ {
  1216  			t1, x1 := tfs[i], xfs[i]
  1217  			if t1.Embedded != x1.Embedded {
  1218  				return cmpForNe(t1.Embedded < x1.Embedded)
  1219  			}
  1220  			if t1.Note != x1.Note {
  1221  				return cmpForNe(t1.Note < x1.Note)
  1222  			}
  1223  			if c := t1.Sym.cmpsym(x1.Sym); c != CMPeq {
  1224  				return c
  1225  			}
  1226  			if c := t1.Type.cmp(x1.Type); c != CMPeq {
  1227  				return c
  1228  			}
  1229  		}
  1230  		if len(tfs) != len(xfs) {
  1231  			return cmpForNe(len(tfs) < len(xfs))
  1232  		}
  1233  		return CMPeq
  1234  
  1235  	case TINTER:
  1236  		tfs := t.AllMethods()
  1237  		xfs := x.AllMethods()
  1238  		for i := 0; i < len(tfs) && i < len(xfs); i++ {
  1239  			t1, x1 := tfs[i], xfs[i]
  1240  			if c := t1.Sym.cmpsym(x1.Sym); c != CMPeq {
  1241  				return c
  1242  			}
  1243  			if c := t1.Type.cmp(x1.Type); c != CMPeq {
  1244  				return c
  1245  			}
  1246  		}
  1247  		if len(tfs) != len(xfs) {
  1248  			return cmpForNe(len(tfs) < len(xfs))
  1249  		}
  1250  		return CMPeq
  1251  
  1252  	case TFUNC:
  1253  		if tn, xn := t.NumRecvs(), x.NumRecvs(); tn != xn {
  1254  			return cmpForNe(tn < xn)
  1255  		}
  1256  		if tn, xn := t.NumParams(), x.NumParams(); tn != xn {
  1257  			return cmpForNe(tn < xn)
  1258  		}
  1259  		if tn, xn := t.NumResults(), x.NumResults(); tn != xn {
  1260  			return cmpForNe(tn < xn)
  1261  		}
  1262  		if tv, xv := t.IsVariadic(), x.IsVariadic(); tv != xv {
  1263  			return cmpForNe(!tv)
  1264  		}
  1265  
  1266  		tfs := t.RecvParamsResults()
  1267  		xfs := x.RecvParamsResults()
  1268  		for i, tf := range tfs {
  1269  			if c := tf.Type.cmp(xfs[i].Type); c != CMPeq {
  1270  				return c
  1271  			}
  1272  		}
  1273  		return CMPeq
  1274  
  1275  	case TARRAY:
  1276  		if t.NumElem() != x.NumElem() {
  1277  			return cmpForNe(t.NumElem() < x.NumElem())
  1278  		}
  1279  
  1280  	case TCHAN:
  1281  		if t.ChanDir() != x.ChanDir() {
  1282  			return cmpForNe(t.ChanDir() < x.ChanDir())
  1283  		}
  1284  
  1285  	default:
  1286  		e := fmt.Sprintf("Do not know how to compare %v with %v", t, x)
  1287  		panic(e)
  1288  	}
  1289  
  1290  	// Common element type comparison for TARRAY, TCHAN, TPTR, and TSLICE.
  1291  	return t.Elem().cmp(x.Elem())
  1292  }
  1293  
  1294  // IsKind reports whether t is a Type of the specified kind.
  1295  func (t *Type) IsKind(et Kind) bool {
  1296  	return t != nil && t.kind == et
  1297  }
  1298  
  1299  func (t *Type) IsBoolean() bool {
  1300  	return t.kind == TBOOL
  1301  }
  1302  
  1303  var unsignedEType = [...]Kind{
  1304  	TINT8:    TUINT8,
  1305  	TUINT8:   TUINT8,
  1306  	TINT16:   TUINT16,
  1307  	TUINT16:  TUINT16,
  1308  	TINT32:   TUINT32,
  1309  	TUINT32:  TUINT32,
  1310  	TINT64:   TUINT64,
  1311  	TUINT64:  TUINT64,
  1312  	TINT:     TUINT,
  1313  	TUINT:    TUINT,
  1314  	TUINTPTR: TUINTPTR,
  1315  }
  1316  
  1317  // ToUnsigned returns the unsigned equivalent of integer type t.
  1318  func (t *Type) ToUnsigned() *Type {
  1319  	if !t.IsInteger() {
  1320  		base.Fatalf("unsignedType(%v)", t)
  1321  	}
  1322  	return Types[unsignedEType[t.kind]]
  1323  }
  1324  
  1325  func (t *Type) IsInteger() bool {
  1326  	switch t.kind {
  1327  	case TINT8, TUINT8, TINT16, TUINT16, TINT32, TUINT32, TINT64, TUINT64, TINT, TUINT, TUINTPTR:
  1328  		return true
  1329  	}
  1330  	return t == UntypedInt || t == UntypedRune
  1331  }
  1332  
  1333  func (t *Type) IsSigned() bool {
  1334  	switch t.kind {
  1335  	case TINT8, TINT16, TINT32, TINT64, TINT:
  1336  		return true
  1337  	}
  1338  	return false
  1339  }
  1340  
  1341  func (t *Type) IsUnsigned() bool {
  1342  	switch t.kind {
  1343  	case TUINT8, TUINT16, TUINT32, TUINT64, TUINT, TUINTPTR:
  1344  		return true
  1345  	}
  1346  	return false
  1347  }
  1348  
  1349  func (t *Type) IsFloat() bool {
  1350  	return t.kind == TFLOAT32 || t.kind == TFLOAT64 || t == UntypedFloat
  1351  }
  1352  
  1353  func (t *Type) IsComplex() bool {
  1354  	return t.kind == TCOMPLEX64 || t.kind == TCOMPLEX128 || t == UntypedComplex
  1355  }
  1356  
  1357  // IsPtr reports whether t is a regular Go pointer type.
  1358  // This does not include unsafe.Pointer.
  1359  func (t *Type) IsPtr() bool {
  1360  	return t.kind == TPTR
  1361  }
  1362  
  1363  // IsPtrElem reports whether t is the element of a pointer (to t).
  1364  func (t *Type) IsPtrElem() bool {
  1365  	return t.cache.ptr != nil
  1366  }
  1367  
  1368  // IsUnsafePtr reports whether t is an unsafe pointer.
  1369  func (t *Type) IsUnsafePtr() bool {
  1370  	return t.kind == TUNSAFEPTR
  1371  }
  1372  
  1373  // IsUintptr reports whether t is a uintptr.
  1374  func (t *Type) IsUintptr() bool {
  1375  	return t.kind == TUINTPTR
  1376  }
  1377  
  1378  // IsPtrShaped reports whether t is represented by a single machine pointer.
  1379  // In addition to regular Go pointer types, this includes map, channel, and
  1380  // function types and unsafe.Pointer. It does not include array or struct types
  1381  // that consist of a single pointer shaped type.
  1382  // TODO(mdempsky): Should it? See golang.org/issue/15028.
  1383  func (t *Type) IsPtrShaped() bool {
  1384  	return t.kind == TPTR || t.kind == TUNSAFEPTR ||
  1385  		t.kind == TMAP || t.kind == TCHAN || t.kind == TFUNC
  1386  }
  1387  
  1388  // HasNil reports whether the set of values determined by t includes nil.
  1389  func (t *Type) HasNil() bool {
  1390  	switch t.kind {
  1391  	case TCHAN, TFUNC, TINTER, TMAP, TNIL, TPTR, TSLICE, TUNSAFEPTR:
  1392  		return true
  1393  	}
  1394  	return false
  1395  }
  1396  
  1397  func (t *Type) IsString() bool {
  1398  	return t.kind == TSTRING
  1399  }
  1400  
  1401  func (t *Type) IsMap() bool {
  1402  	return t.kind == TMAP
  1403  }
  1404  
  1405  func (t *Type) IsChan() bool {
  1406  	return t.kind == TCHAN
  1407  }
  1408  
  1409  func (t *Type) IsSlice() bool {
  1410  	return t.kind == TSLICE
  1411  }
  1412  
  1413  func (t *Type) IsArray() bool {
  1414  	return t.kind == TARRAY
  1415  }
  1416  
  1417  func (t *Type) IsStruct() bool {
  1418  	return t.kind == TSTRUCT
  1419  }
  1420  
  1421  func (t *Type) IsInterface() bool {
  1422  	return t.kind == TINTER
  1423  }
  1424  
  1425  // IsEmptyInterface reports whether t is an empty interface type.
  1426  func (t *Type) IsEmptyInterface() bool {
  1427  	return t.IsInterface() && len(t.AllMethods()) == 0
  1428  }
  1429  
  1430  // IsScalar reports whether 't' is a scalar Go type, e.g.
  1431  // bool/int/float/complex. Note that struct and array types consisting
  1432  // of a single scalar element are not considered scalar, likewise
  1433  // pointer types are also not considered scalar.
  1434  func (t *Type) IsScalar() bool {
  1435  	switch t.kind {
  1436  	case TBOOL, TINT8, TUINT8, TINT16, TUINT16, TINT32,
  1437  		TUINT32, TINT64, TUINT64, TINT, TUINT,
  1438  		TUINTPTR, TCOMPLEX64, TCOMPLEX128, TFLOAT32, TFLOAT64:
  1439  		return true
  1440  	}
  1441  	return false
  1442  }
  1443  
  1444  func (t *Type) PtrTo() *Type {
  1445  	return NewPtr(t)
  1446  }
  1447  
  1448  func (t *Type) NumFields() int {
  1449  	if t.kind == TRESULTS {
  1450  		return len(t.extra.(*Results).Types)
  1451  	}
  1452  	return len(t.Fields())
  1453  }
  1454  func (t *Type) FieldType(i int) *Type {
  1455  	if t.kind == TTUPLE {
  1456  		switch i {
  1457  		case 0:
  1458  			return t.extra.(*Tuple).first
  1459  		case 1:
  1460  			return t.extra.(*Tuple).second
  1461  		default:
  1462  			panic("bad tuple index")
  1463  		}
  1464  	}
  1465  	if t.kind == TRESULTS {
  1466  		return t.extra.(*Results).Types[i]
  1467  	}
  1468  	return t.Field(i).Type
  1469  }
  1470  func (t *Type) FieldOff(i int) int64 {
  1471  	return t.Field(i).Offset
  1472  }
  1473  func (t *Type) FieldName(i int) string {
  1474  	return t.Field(i).Sym.Name
  1475  }
  1476  
  1477  // OffsetOf reports the offset of the field of a struct.
  1478  // The field is looked up by name.
  1479  func (t *Type) OffsetOf(name string) int64 {
  1480  	if t.kind != TSTRUCT {
  1481  		base.Fatalf("can't call OffsetOf on non-struct %v", t)
  1482  	}
  1483  	for _, f := range t.Fields() {
  1484  		if f.Sym.Name == name {
  1485  			return f.Offset
  1486  		}
  1487  	}
  1488  	base.Fatalf("couldn't find field %s in %v", name, t)
  1489  	return -1
  1490  }
  1491  
  1492  func (t *Type) NumElem() int64 {
  1493  	t.wantEtype(TARRAY)
  1494  	return t.extra.(*Array).Bound
  1495  }
  1496  
  1497  type componentsIncludeBlankFields bool
  1498  
  1499  const (
  1500  	IgnoreBlankFields componentsIncludeBlankFields = false
  1501  	CountBlankFields  componentsIncludeBlankFields = true
  1502  )
  1503  
  1504  // NumComponents returns the number of primitive elements that compose t.
  1505  // Struct and array types are flattened for the purpose of counting.
  1506  // All other types (including string, slice, and interface types) count as one element.
  1507  // If countBlank is IgnoreBlankFields, then blank struct fields
  1508  // (and their comprised elements) are excluded from the count.
  1509  // struct { x, y [3]int } has six components; [10]struct{ x, y string } has twenty.
  1510  func (t *Type) NumComponents(countBlank componentsIncludeBlankFields) int64 {
  1511  	switch t.kind {
  1512  	case TSTRUCT:
  1513  		if t.IsFuncArgStruct() {
  1514  			base.Fatalf("NumComponents func arg struct")
  1515  		}
  1516  		var n int64
  1517  		for _, f := range t.Fields() {
  1518  			if countBlank == IgnoreBlankFields && f.Sym.IsBlank() {
  1519  				continue
  1520  			}
  1521  			n += f.Type.NumComponents(countBlank)
  1522  		}
  1523  		return n
  1524  	case TARRAY:
  1525  		return t.NumElem() * t.Elem().NumComponents(countBlank)
  1526  	}
  1527  	return 1
  1528  }
  1529  
  1530  // SoleComponent returns the only primitive component in t,
  1531  // if there is exactly one. Otherwise, it returns nil.
  1532  // Components are counted as in NumComponents, including blank fields.
  1533  // Keep in sync with cmd/compile/internal/walk/convert.go:soleComponent.
  1534  func (t *Type) SoleComponent() *Type {
  1535  	switch t.kind {
  1536  	case TSTRUCT:
  1537  		if t.IsFuncArgStruct() {
  1538  			base.Fatalf("SoleComponent func arg struct")
  1539  		}
  1540  		if t.NumFields() != 1 {
  1541  			return nil
  1542  		}
  1543  		return t.Field(0).Type.SoleComponent()
  1544  	case TARRAY:
  1545  		if t.NumElem() != 1 {
  1546  			return nil
  1547  		}
  1548  		return t.Elem().SoleComponent()
  1549  	}
  1550  	return t
  1551  }
  1552  
  1553  // ChanDir returns the direction of a channel type t.
  1554  // The direction will be one of Crecv, Csend, or Cboth.
  1555  func (t *Type) ChanDir() ChanDir {
  1556  	t.wantEtype(TCHAN)
  1557  	return t.extra.(*Chan).Dir
  1558  }
  1559  
  1560  func (t *Type) IsMemory() bool {
  1561  	if t == TypeMem || t.kind == TTUPLE && t.extra.(*Tuple).second == TypeMem {
  1562  		return true
  1563  	}
  1564  	if t.kind == TRESULTS {
  1565  		if types := t.extra.(*Results).Types; len(types) > 0 && types[len(types)-1] == TypeMem {
  1566  			return true
  1567  		}
  1568  	}
  1569  	return false
  1570  }
  1571  func (t *Type) IsFlags() bool   { return t == TypeFlags }
  1572  func (t *Type) IsVoid() bool    { return t == TypeVoid }
  1573  func (t *Type) IsTuple() bool   { return t.kind == TTUPLE }
  1574  func (t *Type) IsResults() bool { return t.kind == TRESULTS }
  1575  
  1576  // IsUntyped reports whether t is an untyped type.
  1577  func (t *Type) IsUntyped() bool {
  1578  	if t == nil {
  1579  		return false
  1580  	}
  1581  	if t == UntypedString || t == UntypedBool {
  1582  		return true
  1583  	}
  1584  	switch t.kind {
  1585  	case TNIL, TIDEAL:
  1586  		return true
  1587  	}
  1588  	return false
  1589  }
  1590  
  1591  // HasPointers reports whether t contains a heap pointer.
  1592  // Note that this function ignores pointers to not-in-heap types.
  1593  func (t *Type) HasPointers() bool {
  1594  	return PtrDataSize(t) > 0
  1595  }
  1596  
  1597  var recvType *Type
  1598  
  1599  // FakeRecvType returns the singleton type used for interface method receivers.
  1600  func FakeRecvType() *Type {
  1601  	if recvType == nil {
  1602  		recvType = NewPtr(newType(TSTRUCT))
  1603  	}
  1604  	return recvType
  1605  }
  1606  
  1607  func FakeRecv() *Field {
  1608  	return NewField(base.AutogeneratedPos, nil, FakeRecvType())
  1609  }
  1610  
  1611  var (
  1612  	// TSSA types. HasPointers assumes these are pointer-free.
  1613  	TypeInvalid   = newSSA("invalid")
  1614  	TypeMem       = newSSA("mem")
  1615  	TypeFlags     = newSSA("flags")
  1616  	TypeVoid      = newSSA("void")
  1617  	TypeInt128    = newSSA("int128")
  1618  	TypeResultMem = newResults([]*Type{TypeMem})
  1619  )
  1620  
  1621  func init() {
  1622  	TypeInt128.width = 16
  1623  	TypeInt128.align = 8
  1624  }
  1625  
  1626  // NewNamed returns a new named type for the given type name. obj should be an
  1627  // ir.Name. The new type is incomplete (marked as TFORW kind), and the underlying
  1628  // type should be set later via SetUnderlying(). References to the type are
  1629  // maintained until the type is filled in, so those references can be updated when
  1630  // the type is complete.
  1631  func NewNamed(obj Object) *Type {
  1632  	t := newType(TFORW)
  1633  	t.obj = obj
  1634  	if obj.Sym().Pkg == ShapePkg {
  1635  		t.SetIsShape(true)
  1636  		t.SetHasShape(true)
  1637  	}
  1638  	return t
  1639  }
  1640  
  1641  // Obj returns the canonical type name node for a named type t, nil for an unnamed type.
  1642  func (t *Type) Obj() Object {
  1643  	return t.obj
  1644  }
  1645  
  1646  // SetUnderlying sets the underlying type of an incomplete type (i.e. type whose kind
  1647  // is currently TFORW). SetUnderlying automatically updates any types that were waiting
  1648  // for this type to be completed.
  1649  func (t *Type) SetUnderlying(underlying *Type) {
  1650  	if underlying.kind == TFORW {
  1651  		// This type isn't computed yet; when it is, update n.
  1652  		underlying.forwardType().Copyto = append(underlying.forwardType().Copyto, t)
  1653  		return
  1654  	}
  1655  
  1656  	ft := t.forwardType()
  1657  
  1658  	// TODO(mdempsky): Fix Type rekinding.
  1659  	t.kind = underlying.kind
  1660  	t.extra = underlying.extra
  1661  	t.width = underlying.width
  1662  	t.align = underlying.align
  1663  	t.intRegs = underlying.intRegs
  1664  	t.floatRegs = underlying.floatRegs
  1665  	t.underlying = underlying.underlying
  1666  
  1667  	if underlying.NotInHeap() {
  1668  		t.SetNotInHeap(true)
  1669  	}
  1670  	if underlying.HasShape() {
  1671  		t.SetHasShape(true)
  1672  	}
  1673  
  1674  	// spec: "The declared type does not inherit any methods bound
  1675  	// to the existing type, but the method set of an interface
  1676  	// type [...] remains unchanged."
  1677  	if t.IsInterface() {
  1678  		t.methods = underlying.methods
  1679  		t.allMethods = underlying.allMethods
  1680  	}
  1681  
  1682  	// Update types waiting on this type.
  1683  	for _, w := range ft.Copyto {
  1684  		w.SetUnderlying(t)
  1685  	}
  1686  
  1687  	// Double-check use of type as embedded type.
  1688  	if ft.Embedlineno.IsKnown() {
  1689  		if t.IsPtr() || t.IsUnsafePtr() {
  1690  			base.ErrorfAt(ft.Embedlineno, errors.InvalidPtrEmbed, "embedded type cannot be a pointer")
  1691  		}
  1692  	}
  1693  }
  1694  
  1695  func fieldsHasShape(fields []*Field) bool {
  1696  	for _, f := range fields {
  1697  		if f.Type != nil && f.Type.HasShape() {
  1698  			return true
  1699  		}
  1700  	}
  1701  	return false
  1702  }
  1703  
  1704  // newBasic returns a new basic type of the given kind.
  1705  func newBasic(kind Kind, obj Object) *Type {
  1706  	t := newType(kind)
  1707  	t.obj = obj
  1708  	return t
  1709  }
  1710  
  1711  // NewInterface returns a new interface for the given methods and
  1712  // embedded types. Embedded types are specified as fields with no Sym.
  1713  func NewInterface(methods []*Field) *Type {
  1714  	t := newType(TINTER)
  1715  	t.SetInterface(methods)
  1716  	for _, f := range methods {
  1717  		// f.Type could be nil for a broken interface declaration
  1718  		if f.Type != nil && f.Type.HasShape() {
  1719  			t.SetHasShape(true)
  1720  			break
  1721  		}
  1722  	}
  1723  	return t
  1724  }
  1725  
  1726  // NewSignature returns a new function type for the given receiver,
  1727  // parameters, and results, any of which may be nil.
  1728  func NewSignature(recv *Field, params, results []*Field) *Type {
  1729  	startParams := 0
  1730  	if recv != nil {
  1731  		startParams = 1
  1732  	}
  1733  	startResults := startParams + len(params)
  1734  
  1735  	allParams := make([]*Field, startResults+len(results))
  1736  	if recv != nil {
  1737  		allParams[0] = recv
  1738  	}
  1739  	copy(allParams[startParams:], params)
  1740  	copy(allParams[startResults:], results)
  1741  
  1742  	t := newType(TFUNC)
  1743  	ft := t.funcType()
  1744  
  1745  	funargs := func(fields []*Field) *Type {
  1746  		s := NewStruct(fields)
  1747  		s.StructType().ParamTuple = true
  1748  		return s
  1749  	}
  1750  
  1751  	ft.allParams = allParams
  1752  	ft.startParams = startParams
  1753  	ft.startResults = startResults
  1754  
  1755  	ft.resultsTuple = funargs(allParams[startResults:])
  1756  
  1757  	if fieldsHasShape(allParams) {
  1758  		t.SetHasShape(true)
  1759  	}
  1760  
  1761  	return t
  1762  }
  1763  
  1764  // NewStruct returns a new struct with the given fields.
  1765  func NewStruct(fields []*Field) *Type {
  1766  	t := newType(TSTRUCT)
  1767  	t.setFields(fields)
  1768  	if fieldsHasShape(fields) {
  1769  		t.SetHasShape(true)
  1770  	}
  1771  	return t
  1772  }
  1773  
  1774  var (
  1775  	IsInt     [NTYPE]bool
  1776  	IsFloat   [NTYPE]bool
  1777  	IsComplex [NTYPE]bool
  1778  	IsSimple  [NTYPE]bool
  1779  )
  1780  
  1781  var IsOrdered [NTYPE]bool
  1782  
  1783  // IsReflexive reports whether t has a reflexive equality operator.
  1784  // That is, if x==x for all x of type t.
  1785  func IsReflexive(t *Type) bool {
  1786  	switch t.Kind() {
  1787  	case TBOOL,
  1788  		TINT,
  1789  		TUINT,
  1790  		TINT8,
  1791  		TUINT8,
  1792  		TINT16,
  1793  		TUINT16,
  1794  		TINT32,
  1795  		TUINT32,
  1796  		TINT64,
  1797  		TUINT64,
  1798  		TUINTPTR,
  1799  		TPTR,
  1800  		TUNSAFEPTR,
  1801  		TSTRING,
  1802  		TCHAN:
  1803  		return true
  1804  
  1805  	case TFLOAT32,
  1806  		TFLOAT64,
  1807  		TCOMPLEX64,
  1808  		TCOMPLEX128,
  1809  		TINTER:
  1810  		return false
  1811  
  1812  	case TARRAY:
  1813  		return IsReflexive(t.Elem())
  1814  
  1815  	case TSTRUCT:
  1816  		for _, t1 := range t.Fields() {
  1817  			if !IsReflexive(t1.Type) {
  1818  				return false
  1819  			}
  1820  		}
  1821  		return true
  1822  
  1823  	default:
  1824  		base.Fatalf("bad type for map key: %v", t)
  1825  		return false
  1826  	}
  1827  }
  1828  
  1829  // Can this type be stored directly in an interface word?
  1830  // Yes, if the representation is a single pointer.
  1831  func IsDirectIface(t *Type) bool {
  1832  	switch t.Kind() {
  1833  	case TPTR:
  1834  		// Pointers to notinheap types must be stored indirectly. See issue 42076.
  1835  		return !t.Elem().NotInHeap()
  1836  	case TCHAN,
  1837  		TMAP,
  1838  		TFUNC,
  1839  		TUNSAFEPTR:
  1840  		return true
  1841  
  1842  	case TARRAY:
  1843  		// Array of 1 direct iface type can be direct.
  1844  		return t.NumElem() == 1 && IsDirectIface(t.Elem())
  1845  
  1846  	case TSTRUCT:
  1847  		// Struct with 1 field of direct iface type can be direct.
  1848  		return t.NumFields() == 1 && IsDirectIface(t.Field(0).Type)
  1849  	}
  1850  
  1851  	return false
  1852  }
  1853  
  1854  // IsInterfaceMethod reports whether (field) m is
  1855  // an interface method. Such methods have the
  1856  // special receiver type types.FakeRecvType().
  1857  func IsInterfaceMethod(f *Type) bool {
  1858  	return f.Recv().Type == FakeRecvType()
  1859  }
  1860  
  1861  // IsMethodApplicable reports whether method m can be called on a
  1862  // value of type t. This is necessary because we compute a single
  1863  // method set for both T and *T, but some *T methods are not
  1864  // applicable to T receivers.
  1865  func IsMethodApplicable(t *Type, m *Field) bool {
  1866  	return t.IsPtr() || !m.Type.Recv().Type.IsPtr() || IsInterfaceMethod(m.Type) || m.Embedded == 2
  1867  }
  1868  
  1869  // RuntimeSymName returns the name of s if it's in package "runtime"; otherwise
  1870  // it returns "".
  1871  func RuntimeSymName(s *Sym) string {
  1872  	if s.Pkg.Path == "runtime" {
  1873  		return s.Name
  1874  	}
  1875  	return ""
  1876  }
  1877  
  1878  // ReflectSymName returns the name of s if it's in package "reflect"; otherwise
  1879  // it returns "".
  1880  func ReflectSymName(s *Sym) string {
  1881  	if s.Pkg.Path == "reflect" {
  1882  		return s.Name
  1883  	}
  1884  	return ""
  1885  }
  1886  
  1887  // IsNoInstrumentPkg reports whether p is a package that
  1888  // should not be instrumented.
  1889  func IsNoInstrumentPkg(p *Pkg) bool {
  1890  	return objabi.LookupPkgSpecial(p.Path).NoInstrument
  1891  }
  1892  
  1893  // IsNoRacePkg reports whether p is a package that
  1894  // should not be race instrumented.
  1895  func IsNoRacePkg(p *Pkg) bool {
  1896  	return objabi.LookupPkgSpecial(p.Path).NoRaceFunc
  1897  }
  1898  
  1899  // ReceiverBaseType returns the underlying type, if any,
  1900  // that owns methods with receiver parameter t.
  1901  // The result is either a named type or an anonymous struct.
  1902  func ReceiverBaseType(t *Type) *Type {
  1903  	if t == nil {
  1904  		return nil
  1905  	}
  1906  
  1907  	// Strip away pointer if it's there.
  1908  	if t.IsPtr() {
  1909  		if t.Sym() != nil {
  1910  			return nil
  1911  		}
  1912  		t = t.Elem()
  1913  		if t == nil {
  1914  			return nil
  1915  		}
  1916  	}
  1917  
  1918  	// Must be a named type or anonymous struct.
  1919  	if t.Sym() == nil && !t.IsStruct() {
  1920  		return nil
  1921  	}
  1922  
  1923  	// Check types.
  1924  	if IsSimple[t.Kind()] {
  1925  		return t
  1926  	}
  1927  	switch t.Kind() {
  1928  	case TARRAY, TCHAN, TFUNC, TMAP, TSLICE, TSTRING, TSTRUCT:
  1929  		return t
  1930  	}
  1931  	return nil
  1932  }
  1933  
  1934  func FloatForComplex(t *Type) *Type {
  1935  	switch t.Kind() {
  1936  	case TCOMPLEX64:
  1937  		return Types[TFLOAT32]
  1938  	case TCOMPLEX128:
  1939  		return Types[TFLOAT64]
  1940  	}
  1941  	base.Fatalf("unexpected type: %v", t)
  1942  	return nil
  1943  }
  1944  
  1945  func ComplexForFloat(t *Type) *Type {
  1946  	switch t.Kind() {
  1947  	case TFLOAT32:
  1948  		return Types[TCOMPLEX64]
  1949  	case TFLOAT64:
  1950  		return Types[TCOMPLEX128]
  1951  	}
  1952  	base.Fatalf("unexpected type: %v", t)
  1953  	return nil
  1954  }
  1955  
  1956  func TypeSym(t *Type) *Sym {
  1957  	return TypeSymLookup(TypeSymName(t))
  1958  }
  1959  
  1960  func TypeSymLookup(name string) *Sym {
  1961  	typepkgmu.Lock()
  1962  	s := typepkg.Lookup(name)
  1963  	typepkgmu.Unlock()
  1964  	return s
  1965  }
  1966  
  1967  func TypeSymName(t *Type) string {
  1968  	name := t.LinkString()
  1969  	// Use a separate symbol name for Noalg types for #17752.
  1970  	if TypeHasNoAlg(t) {
  1971  		name = "noalg." + name
  1972  	}
  1973  	return name
  1974  }
  1975  
  1976  // Fake package for runtime type info (headers)
  1977  // Don't access directly, use typeLookup below.
  1978  var (
  1979  	typepkgmu sync.Mutex // protects typepkg lookups
  1980  	typepkg   = NewPkg("type", "type")
  1981  )
  1982  
  1983  var SimType [NTYPE]Kind
  1984  
  1985  // Fake package for shape types (see typecheck.Shapify()).
  1986  var ShapePkg = NewPkg("go.shape", "go.shape")
  1987  

View as plain text