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