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

View as plain text