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