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