1 //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// C Language Family Type Representation 11 /// 12 /// This file defines the clang::Type interface and subclasses, used to 13 /// represent types for languages in the C family. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_CLANG_AST_TYPE_H 18 #define LLVM_CLANG_AST_TYPE_H 19 20 #include "clang/AST/DependenceFlags.h" 21 #include "clang/AST/NestedNameSpecifier.h" 22 #include "clang/AST/TemplateName.h" 23 #include "clang/Basic/AddressSpaces.h" 24 #include "clang/Basic/AttrKinds.h" 25 #include "clang/Basic/Diagnostic.h" 26 #include "clang/Basic/ExceptionSpecificationType.h" 27 #include "clang/Basic/LLVM.h" 28 #include "clang/Basic/Linkage.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceLocation.h" 31 #include "clang/Basic/Specifiers.h" 32 #include "clang/Basic/Visibility.h" 33 #include "llvm/ADT/APInt.h" 34 #include "llvm/ADT/APSInt.h" 35 #include "llvm/ADT/ArrayRef.h" 36 #include "llvm/ADT/FoldingSet.h" 37 #include "llvm/ADT/None.h" 38 #include "llvm/ADT/Optional.h" 39 #include "llvm/ADT/PointerIntPair.h" 40 #include "llvm/ADT/PointerUnion.h" 41 #include "llvm/ADT/StringRef.h" 42 #include "llvm/ADT/Twine.h" 43 #include "llvm/ADT/iterator_range.h" 44 #include "llvm/Support/Casting.h" 45 #include "llvm/Support/Compiler.h" 46 #include "llvm/Support/ErrorHandling.h" 47 #include "llvm/Support/PointerLikeTypeTraits.h" 48 #include "llvm/Support/TrailingObjects.h" 49 #include "llvm/Support/type_traits.h" 50 #include <cassert> 51 #include <cstddef> 52 #include <cstdint> 53 #include <cstring> 54 #include <string> 55 #include <type_traits> 56 #include <utility> 57 58 namespace clang { 59 60 class ExtQuals; 61 class QualType; 62 class ConceptDecl; 63 class TagDecl; 64 class Type; 65 66 enum { 67 TypeAlignmentInBits = 4, 68 TypeAlignment = 1 << TypeAlignmentInBits 69 }; 70 71 namespace serialization { 72 template <class T> class AbstractTypeReader; 73 template <class T> class AbstractTypeWriter; 74 } 75 76 } // namespace clang 77 78 namespace llvm { 79 80 template <typename T> 81 struct PointerLikeTypeTraits; 82 template<> 83 struct PointerLikeTypeTraits< ::clang::Type*> { 84 static inline void *getAsVoidPointer(::clang::Type *P) { return P; } 85 86 static inline ::clang::Type *getFromVoidPointer(void *P) { 87 return static_cast< ::clang::Type*>(P); 88 } 89 90 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; 91 }; 92 93 template<> 94 struct PointerLikeTypeTraits< ::clang::ExtQuals*> { 95 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } 96 97 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { 98 return static_cast< ::clang::ExtQuals*>(P); 99 } 100 101 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; 102 }; 103 104 } // namespace llvm 105 106 namespace clang { 107 108 class ASTContext; 109 template <typename> class CanQual; 110 class CXXRecordDecl; 111 class DeclContext; 112 class EnumDecl; 113 class Expr; 114 class ExtQualsTypeCommonBase; 115 class FunctionDecl; 116 class IdentifierInfo; 117 class NamedDecl; 118 class ObjCInterfaceDecl; 119 class ObjCProtocolDecl; 120 class ObjCTypeParamDecl; 121 struct PrintingPolicy; 122 class RecordDecl; 123 class Stmt; 124 class TagDecl; 125 class TemplateArgument; 126 class TemplateArgumentListInfo; 127 class TemplateArgumentLoc; 128 class TemplateTypeParmDecl; 129 class TypedefNameDecl; 130 class UnresolvedUsingTypenameDecl; 131 132 using CanQualType = CanQual<Type>; 133 134 // Provide forward declarations for all of the *Type classes. 135 #define TYPE(Class, Base) class Class##Type; 136 #include "clang/AST/TypeNodes.inc" 137 138 /// The collection of all-type qualifiers we support. 139 /// Clang supports five independent qualifiers: 140 /// * C99: const, volatile, and restrict 141 /// * MS: __unaligned 142 /// * Embedded C (TR18037): address spaces 143 /// * Objective C: the GC attributes (none, weak, or strong) 144 class Qualifiers { 145 public: 146 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. 147 Const = 0x1, 148 Restrict = 0x2, 149 Volatile = 0x4, 150 CVRMask = Const | Volatile | Restrict 151 }; 152 153 enum GC { 154 GCNone = 0, 155 Weak, 156 Strong 157 }; 158 159 enum ObjCLifetime { 160 /// There is no lifetime qualification on this type. 161 OCL_None, 162 163 /// This object can be modified without requiring retains or 164 /// releases. 165 OCL_ExplicitNone, 166 167 /// Assigning into this object requires the old value to be 168 /// released and the new value to be retained. The timing of the 169 /// release of the old value is inexact: it may be moved to 170 /// immediately after the last known point where the value is 171 /// live. 172 OCL_Strong, 173 174 /// Reading or writing from this object requires a barrier call. 175 OCL_Weak, 176 177 /// Assigning into this object requires a lifetime extension. 178 OCL_Autoreleasing 179 }; 180 181 enum { 182 /// The maximum supported address space number. 183 /// 23 bits should be enough for anyone. 184 MaxAddressSpace = 0x7fffffu, 185 186 /// The width of the "fast" qualifier mask. 187 FastWidth = 3, 188 189 /// The fast qualifier mask. 190 FastMask = (1 << FastWidth) - 1 191 }; 192 193 /// Returns the common set of qualifiers while removing them from 194 /// the given sets. 195 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { 196 // If both are only CVR-qualified, bit operations are sufficient. 197 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { 198 Qualifiers Q; 199 Q.Mask = L.Mask & R.Mask; 200 L.Mask &= ~Q.Mask; 201 R.Mask &= ~Q.Mask; 202 return Q; 203 } 204 205 Qualifiers Q; 206 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); 207 Q.addCVRQualifiers(CommonCRV); 208 L.removeCVRQualifiers(CommonCRV); 209 R.removeCVRQualifiers(CommonCRV); 210 211 if (L.getObjCGCAttr() == R.getObjCGCAttr()) { 212 Q.setObjCGCAttr(L.getObjCGCAttr()); 213 L.removeObjCGCAttr(); 214 R.removeObjCGCAttr(); 215 } 216 217 if (L.getObjCLifetime() == R.getObjCLifetime()) { 218 Q.setObjCLifetime(L.getObjCLifetime()); 219 L.removeObjCLifetime(); 220 R.removeObjCLifetime(); 221 } 222 223 if (L.getAddressSpace() == R.getAddressSpace()) { 224 Q.setAddressSpace(L.getAddressSpace()); 225 L.removeAddressSpace(); 226 R.removeAddressSpace(); 227 } 228 return Q; 229 } 230 231 static Qualifiers fromFastMask(unsigned Mask) { 232 Qualifiers Qs; 233 Qs.addFastQualifiers(Mask); 234 return Qs; 235 } 236 237 static Qualifiers fromCVRMask(unsigned CVR) { 238 Qualifiers Qs; 239 Qs.addCVRQualifiers(CVR); 240 return Qs; 241 } 242 243 static Qualifiers fromCVRUMask(unsigned CVRU) { 244 Qualifiers Qs; 245 Qs.addCVRUQualifiers(CVRU); 246 return Qs; 247 } 248 249 // Deserialize qualifiers from an opaque representation. 250 static Qualifiers fromOpaqueValue(unsigned opaque) { 251 Qualifiers Qs; 252 Qs.Mask = opaque; 253 return Qs; 254 } 255 256 // Serialize these qualifiers into an opaque representation. 257 unsigned getAsOpaqueValue() const { 258 return Mask; 259 } 260 261 bool hasConst() const { return Mask & Const; } 262 bool hasOnlyConst() const { return Mask == Const; } 263 void removeConst() { Mask &= ~Const; } 264 void addConst() { Mask |= Const; } 265 266 bool hasVolatile() const { return Mask & Volatile; } 267 bool hasOnlyVolatile() const { return Mask == Volatile; } 268 void removeVolatile() { Mask &= ~Volatile; } 269 void addVolatile() { Mask |= Volatile; } 270 271 bool hasRestrict() const { return Mask & Restrict; } 272 bool hasOnlyRestrict() const { return Mask == Restrict; } 273 void removeRestrict() { Mask &= ~Restrict; } 274 void addRestrict() { Mask |= Restrict; } 275 276 bool hasCVRQualifiers() const { return getCVRQualifiers(); } 277 unsigned getCVRQualifiers() const { return Mask & CVRMask; } 278 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } 279 280 void setCVRQualifiers(unsigned mask) { 281 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); 282 Mask = (Mask & ~CVRMask) | mask; 283 } 284 void removeCVRQualifiers(unsigned mask) { 285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); 286 Mask &= ~mask; 287 } 288 void removeCVRQualifiers() { 289 removeCVRQualifiers(CVRMask); 290 } 291 void addCVRQualifiers(unsigned mask) { 292 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); 293 Mask |= mask; 294 } 295 void addCVRUQualifiers(unsigned mask) { 296 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"); 297 Mask |= mask; 298 } 299 300 bool hasUnaligned() const { return Mask & UMask; } 301 void setUnaligned(bool flag) { 302 Mask = (Mask & ~UMask) | (flag ? UMask : 0); 303 } 304 void removeUnaligned() { Mask &= ~UMask; } 305 void addUnaligned() { Mask |= UMask; } 306 307 bool hasObjCGCAttr() const { return Mask & GCAttrMask; } 308 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } 309 void setObjCGCAttr(GC type) { 310 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); 311 } 312 void removeObjCGCAttr() { setObjCGCAttr(GCNone); } 313 void addObjCGCAttr(GC type) { 314 assert(type); 315 setObjCGCAttr(type); 316 } 317 Qualifiers withoutObjCGCAttr() const { 318 Qualifiers qs = *this; 319 qs.removeObjCGCAttr(); 320 return qs; 321 } 322 Qualifiers withoutObjCLifetime() const { 323 Qualifiers qs = *this; 324 qs.removeObjCLifetime(); 325 return qs; 326 } 327 Qualifiers withoutAddressSpace() const { 328 Qualifiers qs = *this; 329 qs.removeAddressSpace(); 330 return qs; 331 } 332 333 bool hasObjCLifetime() const { return Mask & LifetimeMask; } 334 ObjCLifetime getObjCLifetime() const { 335 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); 336 } 337 void setObjCLifetime(ObjCLifetime type) { 338 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); 339 } 340 void removeObjCLifetime() { setObjCLifetime(OCL_None); } 341 void addObjCLifetime(ObjCLifetime type) { 342 assert(type); 343 assert(!hasObjCLifetime()); 344 Mask |= (type << LifetimeShift); 345 } 346 347 /// True if the lifetime is neither None or ExplicitNone. 348 bool hasNonTrivialObjCLifetime() const { 349 ObjCLifetime lifetime = getObjCLifetime(); 350 return (lifetime > OCL_ExplicitNone); 351 } 352 353 /// True if the lifetime is either strong or weak. 354 bool hasStrongOrWeakObjCLifetime() const { 355 ObjCLifetime lifetime = getObjCLifetime(); 356 return (lifetime == OCL_Strong || lifetime == OCL_Weak); 357 } 358 359 bool hasAddressSpace() const { return Mask & AddressSpaceMask; } 360 LangAS getAddressSpace() const { 361 return static_cast<LangAS>(Mask >> AddressSpaceShift); 362 } 363 bool hasTargetSpecificAddressSpace() const { 364 return isTargetAddressSpace(getAddressSpace()); 365 } 366 /// Get the address space attribute value to be printed by diagnostics. 367 unsigned getAddressSpaceAttributePrintValue() const { 368 auto Addr = getAddressSpace(); 369 // This function is not supposed to be used with language specific 370 // address spaces. If that happens, the diagnostic message should consider 371 // printing the QualType instead of the address space value. 372 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace()); 373 if (Addr != LangAS::Default) 374 return toTargetAddressSpace(Addr); 375 // TODO: The diagnostic messages where Addr may be 0 should be fixed 376 // since it cannot differentiate the situation where 0 denotes the default 377 // address space or user specified __attribute__((address_space(0))). 378 return 0; 379 } 380 void setAddressSpace(LangAS space) { 381 assert((unsigned)space <= MaxAddressSpace); 382 Mask = (Mask & ~AddressSpaceMask) 383 | (((uint32_t) space) << AddressSpaceShift); 384 } 385 void removeAddressSpace() { setAddressSpace(LangAS::Default); } 386 void addAddressSpace(LangAS space) { 387 assert(space != LangAS::Default); 388 setAddressSpace(space); 389 } 390 391 // Fast qualifiers are those that can be allocated directly 392 // on a QualType object. 393 bool hasFastQualifiers() const { return getFastQualifiers(); } 394 unsigned getFastQualifiers() const { return Mask & FastMask; } 395 void setFastQualifiers(unsigned mask) { 396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); 397 Mask = (Mask & ~FastMask) | mask; 398 } 399 void removeFastQualifiers(unsigned mask) { 400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); 401 Mask &= ~mask; 402 } 403 void removeFastQualifiers() { 404 removeFastQualifiers(FastMask); 405 } 406 void addFastQualifiers(unsigned mask) { 407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); 408 Mask |= mask; 409 } 410 411 /// Return true if the set contains any qualifiers which require an ExtQuals 412 /// node to be allocated. 413 bool hasNonFastQualifiers() const { return Mask & ~FastMask; } 414 Qualifiers getNonFastQualifiers() const { 415 Qualifiers Quals = *this; 416 Quals.setFastQualifiers(0); 417 return Quals; 418 } 419 420 /// Return true if the set contains any qualifiers. 421 bool hasQualifiers() const { return Mask; } 422 bool empty() const { return !Mask; } 423 424 /// Add the qualifiers from the given set to this set. 425 void addQualifiers(Qualifiers Q) { 426 // If the other set doesn't have any non-boolean qualifiers, just 427 // bit-or it in. 428 if (!(Q.Mask & ~CVRMask)) 429 Mask |= Q.Mask; 430 else { 431 Mask |= (Q.Mask & CVRMask); 432 if (Q.hasAddressSpace()) 433 addAddressSpace(Q.getAddressSpace()); 434 if (Q.hasObjCGCAttr()) 435 addObjCGCAttr(Q.getObjCGCAttr()); 436 if (Q.hasObjCLifetime()) 437 addObjCLifetime(Q.getObjCLifetime()); 438 } 439 } 440 441 /// Remove the qualifiers from the given set from this set. 442 void removeQualifiers(Qualifiers Q) { 443 // If the other set doesn't have any non-boolean qualifiers, just 444 // bit-and the inverse in. 445 if (!(Q.Mask & ~CVRMask)) 446 Mask &= ~Q.Mask; 447 else { 448 Mask &= ~(Q.Mask & CVRMask); 449 if (getObjCGCAttr() == Q.getObjCGCAttr()) 450 removeObjCGCAttr(); 451 if (getObjCLifetime() == Q.getObjCLifetime()) 452 removeObjCLifetime(); 453 if (getAddressSpace() == Q.getAddressSpace()) 454 removeAddressSpace(); 455 } 456 } 457 458 /// Add the qualifiers from the given set to this set, given that 459 /// they don't conflict. 460 void addConsistentQualifiers(Qualifiers qs) { 461 assert(getAddressSpace() == qs.getAddressSpace() || 462 !hasAddressSpace() || !qs.hasAddressSpace()); 463 assert(getObjCGCAttr() == qs.getObjCGCAttr() || 464 !hasObjCGCAttr() || !qs.hasObjCGCAttr()); 465 assert(getObjCLifetime() == qs.getObjCLifetime() || 466 !hasObjCLifetime() || !qs.hasObjCLifetime()); 467 Mask |= qs.Mask; 468 } 469 470 /// Returns true if address space A is equal to or a superset of B. 471 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of 472 /// overlapping address spaces. 473 /// CL1.1 or CL1.2: 474 /// every address space is a superset of itself. 475 /// CL2.0 adds: 476 /// __generic is a superset of any address space except for __constant. 477 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { 478 // Address spaces must match exactly. 479 return A == B || 480 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except 481 // for __constant can be used as __generic. 482 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || 483 // Consider pointer size address spaces to be equivalent to default. 484 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && 485 (isPtrSizeAddressSpace(B) || B == LangAS::Default)); 486 } 487 488 /// Returns true if the address space in these qualifiers is equal to or 489 /// a superset of the address space in the argument qualifiers. 490 bool isAddressSpaceSupersetOf(Qualifiers other) const { 491 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); 492 } 493 494 /// Determines if these qualifiers compatibly include another set. 495 /// Generally this answers the question of whether an object with the other 496 /// qualifiers can be safely used as an object with these qualifiers. 497 bool compatiblyIncludes(Qualifiers other) const { 498 return isAddressSpaceSupersetOf(other) && 499 // ObjC GC qualifiers can match, be added, or be removed, but can't 500 // be changed. 501 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || 502 !other.hasObjCGCAttr()) && 503 // ObjC lifetime qualifiers must match exactly. 504 getObjCLifetime() == other.getObjCLifetime() && 505 // CVR qualifiers may subset. 506 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && 507 // U qualifier may superset. 508 (!other.hasUnaligned() || hasUnaligned()); 509 } 510 511 /// Determines if these qualifiers compatibly include another set of 512 /// qualifiers from the narrow perspective of Objective-C ARC lifetime. 513 /// 514 /// One set of Objective-C lifetime qualifiers compatibly includes the other 515 /// if the lifetime qualifiers match, or if both are non-__weak and the 516 /// including set also contains the 'const' qualifier, or both are non-__weak 517 /// and one is None (which can only happen in non-ARC modes). 518 bool compatiblyIncludesObjCLifetime(Qualifiers other) const { 519 if (getObjCLifetime() == other.getObjCLifetime()) 520 return true; 521 522 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) 523 return false; 524 525 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) 526 return true; 527 528 return hasConst(); 529 } 530 531 /// Determine whether this set of qualifiers is a strict superset of 532 /// another set of qualifiers, not considering qualifier compatibility. 533 bool isStrictSupersetOf(Qualifiers Other) const; 534 535 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } 536 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } 537 538 explicit operator bool() const { return hasQualifiers(); } 539 540 Qualifiers &operator+=(Qualifiers R) { 541 addQualifiers(R); 542 return *this; 543 } 544 545 // Union two qualifier sets. If an enumerated qualifier appears 546 // in both sets, use the one from the right. 547 friend Qualifiers operator+(Qualifiers L, Qualifiers R) { 548 L += R; 549 return L; 550 } 551 552 Qualifiers &operator-=(Qualifiers R) { 553 removeQualifiers(R); 554 return *this; 555 } 556 557 /// Compute the difference between two qualifier sets. 558 friend Qualifiers operator-(Qualifiers L, Qualifiers R) { 559 L -= R; 560 return L; 561 } 562 563 std::string getAsString() const; 564 std::string getAsString(const PrintingPolicy &Policy) const; 565 566 static std::string getAddrSpaceAsString(LangAS AS); 567 568 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; 569 void print(raw_ostream &OS, const PrintingPolicy &Policy, 570 bool appendSpaceIfNonEmpty = false) const; 571 572 void Profile(llvm::FoldingSetNodeID &ID) const { 573 ID.AddInteger(Mask); 574 } 575 576 private: 577 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| 578 // |C R V|U|GCAttr|Lifetime|AddressSpace| 579 uint32_t Mask = 0; 580 581 static const uint32_t UMask = 0x8; 582 static const uint32_t UShift = 3; 583 static const uint32_t GCAttrMask = 0x30; 584 static const uint32_t GCAttrShift = 4; 585 static const uint32_t LifetimeMask = 0x1C0; 586 static const uint32_t LifetimeShift = 6; 587 static const uint32_t AddressSpaceMask = 588 ~(CVRMask | UMask | GCAttrMask | LifetimeMask); 589 static const uint32_t AddressSpaceShift = 9; 590 }; 591 592 /// A std::pair-like structure for storing a qualified type split 593 /// into its local qualifiers and its locally-unqualified type. 594 struct SplitQualType { 595 /// The locally-unqualified type. 596 const Type *Ty = nullptr; 597 598 /// The local qualifiers. 599 Qualifiers Quals; 600 601 SplitQualType() = default; 602 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} 603 604 SplitQualType getSingleStepDesugaredType() const; // end of this file 605 606 // Make std::tie work. 607 std::pair<const Type *,Qualifiers> asPair() const { 608 return std::pair<const Type *, Qualifiers>(Ty, Quals); 609 } 610 611 friend bool operator==(SplitQualType a, SplitQualType b) { 612 return a.Ty == b.Ty && a.Quals == b.Quals; 613 } 614 friend bool operator!=(SplitQualType a, SplitQualType b) { 615 return a.Ty != b.Ty || a.Quals != b.Quals; 616 } 617 }; 618 619 /// The kind of type we are substituting Objective-C type arguments into. 620 /// 621 /// The kind of substitution affects the replacement of type parameters when 622 /// no concrete type information is provided, e.g., when dealing with an 623 /// unspecialized type. 624 enum class ObjCSubstitutionContext { 625 /// An ordinary type. 626 Ordinary, 627 628 /// The result type of a method or function. 629 Result, 630 631 /// The parameter type of a method or function. 632 Parameter, 633 634 /// The type of a property. 635 Property, 636 637 /// The superclass of a type. 638 Superclass, 639 }; 640 641 /// A (possibly-)qualified type. 642 /// 643 /// For efficiency, we don't store CV-qualified types as nodes on their 644 /// own: instead each reference to a type stores the qualifiers. This 645 /// greatly reduces the number of nodes we need to allocate for types (for 646 /// example we only need one for 'int', 'const int', 'volatile int', 647 /// 'const volatile int', etc). 648 /// 649 /// As an added efficiency bonus, instead of making this a pair, we 650 /// just store the two bits we care about in the low bits of the 651 /// pointer. To handle the packing/unpacking, we make QualType be a 652 /// simple wrapper class that acts like a smart pointer. A third bit 653 /// indicates whether there are extended qualifiers present, in which 654 /// case the pointer points to a special structure. 655 class QualType { 656 friend class QualifierCollector; 657 658 // Thankfully, these are efficiently composable. 659 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, 660 Qualifiers::FastWidth> Value; 661 662 const ExtQuals *getExtQualsUnsafe() const { 663 return Value.getPointer().get<const ExtQuals*>(); 664 } 665 666 const Type *getTypePtrUnsafe() const { 667 return Value.getPointer().get<const Type*>(); 668 } 669 670 const ExtQualsTypeCommonBase *getCommonPtr() const { 671 assert(!isNull() && "Cannot retrieve a NULL type pointer"); 672 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); 673 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); 674 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); 675 } 676 677 public: 678 QualType() = default; 679 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} 680 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} 681 682 unsigned getLocalFastQualifiers() const { return Value.getInt(); } 683 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } 684 685 /// Retrieves a pointer to the underlying (unqualified) type. 686 /// 687 /// This function requires that the type not be NULL. If the type might be 688 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). 689 const Type *getTypePtr() const; 690 691 const Type *getTypePtrOrNull() const; 692 693 /// Retrieves a pointer to the name of the base type. 694 const IdentifierInfo *getBaseTypeIdentifier() const; 695 696 /// Divides a QualType into its unqualified type and a set of local 697 /// qualifiers. 698 SplitQualType split() const; 699 700 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } 701 702 static QualType getFromOpaquePtr(const void *Ptr) { 703 QualType T; 704 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); 705 return T; 706 } 707 708 const Type &operator*() const { 709 return *getTypePtr(); 710 } 711 712 const Type *operator->() const { 713 return getTypePtr(); 714 } 715 716 bool isCanonical() const; 717 bool isCanonicalAsParam() const; 718 719 /// Return true if this QualType doesn't point to a type yet. 720 bool isNull() const { 721 return Value.getPointer().isNull(); 722 } 723 724 /// Determine whether this particular QualType instance has the 725 /// "const" qualifier set, without looking through typedefs that may have 726 /// added "const" at a different level. 727 bool isLocalConstQualified() const { 728 return (getLocalFastQualifiers() & Qualifiers::Const); 729 } 730 731 /// Determine whether this type is const-qualified. 732 bool isConstQualified() const; 733 734 /// Determine whether this particular QualType instance has the 735 /// "restrict" qualifier set, without looking through typedefs that may have 736 /// added "restrict" at a different level. 737 bool isLocalRestrictQualified() const { 738 return (getLocalFastQualifiers() & Qualifiers::Restrict); 739 } 740 741 /// Determine whether this type is restrict-qualified. 742 bool isRestrictQualified() const; 743 744 /// Determine whether this particular QualType instance has the 745 /// "volatile" qualifier set, without looking through typedefs that may have 746 /// added "volatile" at a different level. 747 bool isLocalVolatileQualified() const { 748 return (getLocalFastQualifiers() & Qualifiers::Volatile); 749 } 750 751 /// Determine whether this type is volatile-qualified. 752 bool isVolatileQualified() const; 753 754 /// Determine whether this particular QualType instance has any 755 /// qualifiers, without looking through any typedefs that might add 756 /// qualifiers at a different level. 757 bool hasLocalQualifiers() const { 758 return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); 759 } 760 761 /// Determine whether this type has any qualifiers. 762 bool hasQualifiers() const; 763 764 /// Determine whether this particular QualType instance has any 765 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType 766 /// instance. 767 bool hasLocalNonFastQualifiers() const { 768 return Value.getPointer().is<const ExtQuals*>(); 769 } 770 771 /// Retrieve the set of qualifiers local to this particular QualType 772 /// instance, not including any qualifiers acquired through typedefs or 773 /// other sugar. 774 Qualifiers getLocalQualifiers() const; 775 776 /// Retrieve the set of qualifiers applied to this type. 777 Qualifiers getQualifiers() const; 778 779 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers 780 /// local to this particular QualType instance, not including any qualifiers 781 /// acquired through typedefs or other sugar. 782 unsigned getLocalCVRQualifiers() const { 783 return getLocalFastQualifiers(); 784 } 785 786 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers 787 /// applied to this type. 788 unsigned getCVRQualifiers() const; 789 790 bool isConstant(const ASTContext& Ctx) const { 791 return QualType::isConstant(*this, Ctx); 792 } 793 794 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). 795 bool isPODType(const ASTContext &Context) const; 796 797 /// Return true if this is a POD type according to the rules of the C++98 798 /// standard, regardless of the current compilation's language. 799 bool isCXX98PODType(const ASTContext &Context) const; 800 801 /// Return true if this is a POD type according to the more relaxed rules 802 /// of the C++11 standard, regardless of the current compilation's language. 803 /// (C++0x [basic.types]p9). Note that, unlike 804 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. 805 bool isCXX11PODType(const ASTContext &Context) const; 806 807 /// Return true if this is a trivial type per (C++0x [basic.types]p9) 808 bool isTrivialType(const ASTContext &Context) const; 809 810 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) 811 bool isTriviallyCopyableType(const ASTContext &Context) const; 812 813 814 /// Returns true if it is a class and it might be dynamic. 815 bool mayBeDynamicClass() const; 816 817 /// Returns true if it is not a class or if the class might not be dynamic. 818 bool mayBeNotDynamicClass() const; 819 820 // Don't promise in the API that anything besides 'const' can be 821 // easily added. 822 823 /// Add the `const` type qualifier to this QualType. 824 void addConst() { 825 addFastQualifiers(Qualifiers::Const); 826 } 827 QualType withConst() const { 828 return withFastQualifiers(Qualifiers::Const); 829 } 830 831 /// Add the `volatile` type qualifier to this QualType. 832 void addVolatile() { 833 addFastQualifiers(Qualifiers::Volatile); 834 } 835 QualType withVolatile() const { 836 return withFastQualifiers(Qualifiers::Volatile); 837 } 838 839 /// Add the `restrict` qualifier to this QualType. 840 void addRestrict() { 841 addFastQualifiers(Qualifiers::Restrict); 842 } 843 QualType withRestrict() const { 844 return withFastQualifiers(Qualifiers::Restrict); 845 } 846 847 QualType withCVRQualifiers(unsigned CVR) const { 848 return withFastQualifiers(CVR); 849 } 850 851 void addFastQualifiers(unsigned TQs) { 852 assert(!(TQs & ~Qualifiers::FastMask) 853 && "non-fast qualifier bits set in mask!"); 854 Value.setInt(Value.getInt() | TQs); 855 } 856 857 void removeLocalConst(); 858 void removeLocalVolatile(); 859 void removeLocalRestrict(); 860 void removeLocalCVRQualifiers(unsigned Mask); 861 862 void removeLocalFastQualifiers() { Value.setInt(0); } 863 void removeLocalFastQualifiers(unsigned Mask) { 864 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"); 865 Value.setInt(Value.getInt() & ~Mask); 866 } 867 868 // Creates a type with the given qualifiers in addition to any 869 // qualifiers already on this type. 870 QualType withFastQualifiers(unsigned TQs) const { 871 QualType T = *this; 872 T.addFastQualifiers(TQs); 873 return T; 874 } 875 876 // Creates a type with exactly the given fast qualifiers, removing 877 // any existing fast qualifiers. 878 QualType withExactLocalFastQualifiers(unsigned TQs) const { 879 return withoutLocalFastQualifiers().withFastQualifiers(TQs); 880 } 881 882 // Removes fast qualifiers, but leaves any extended qualifiers in place. 883 QualType withoutLocalFastQualifiers() const { 884 QualType T = *this; 885 T.removeLocalFastQualifiers(); 886 return T; 887 } 888 889 QualType getCanonicalType() const; 890 891 /// Return this type with all of the instance-specific qualifiers 892 /// removed, but without removing any qualifiers that may have been applied 893 /// through typedefs. 894 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } 895 896 /// Retrieve the unqualified variant of the given type, 897 /// removing as little sugar as possible. 898 /// 899 /// This routine looks through various kinds of sugar to find the 900 /// least-desugared type that is unqualified. For example, given: 901 /// 902 /// \code 903 /// typedef int Integer; 904 /// typedef const Integer CInteger; 905 /// typedef CInteger DifferenceType; 906 /// \endcode 907 /// 908 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will 909 /// desugar until we hit the type \c Integer, which has no qualifiers on it. 910 /// 911 /// The resulting type might still be qualified if it's sugar for an array 912 /// type. To strip qualifiers even from within a sugared array type, use 913 /// ASTContext::getUnqualifiedArrayType. 914 inline QualType getUnqualifiedType() const; 915 916 /// Retrieve the unqualified variant of the given type, removing as little 917 /// sugar as possible. 918 /// 919 /// Like getUnqualifiedType(), but also returns the set of 920 /// qualifiers that were built up. 921 /// 922 /// The resulting type might still be qualified if it's sugar for an array 923 /// type. To strip qualifiers even from within a sugared array type, use 924 /// ASTContext::getUnqualifiedArrayType. 925 inline SplitQualType getSplitUnqualifiedType() const; 926 927 /// Determine whether this type is more qualified than the other 928 /// given type, requiring exact equality for non-CVR qualifiers. 929 bool isMoreQualifiedThan(QualType Other) const; 930 931 /// Determine whether this type is at least as qualified as the other 932 /// given type, requiring exact equality for non-CVR qualifiers. 933 bool isAtLeastAsQualifiedAs(QualType Other) const; 934 935 QualType getNonReferenceType() const; 936 937 /// Determine the type of a (typically non-lvalue) expression with the 938 /// specified result type. 939 /// 940 /// This routine should be used for expressions for which the return type is 941 /// explicitly specified (e.g., in a cast or call) and isn't necessarily 942 /// an lvalue. It removes a top-level reference (since there are no 943 /// expressions of reference type) and deletes top-level cvr-qualifiers 944 /// from non-class types (in C++) or all types (in C). 945 QualType getNonLValueExprType(const ASTContext &Context) const; 946 947 /// Remove an outer pack expansion type (if any) from this type. Used as part 948 /// of converting the type of a declaration to the type of an expression that 949 /// references that expression. It's meaningless for an expression to have a 950 /// pack expansion type. 951 QualType getNonPackExpansionType() const; 952 953 /// Return the specified type with any "sugar" removed from 954 /// the type. This takes off typedefs, typeof's etc. If the outer level of 955 /// the type is already concrete, it returns it unmodified. This is similar 956 /// to getting the canonical type, but it doesn't remove *all* typedefs. For 957 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is 958 /// concrete. 959 /// 960 /// Qualifiers are left in place. 961 QualType getDesugaredType(const ASTContext &Context) const { 962 return getDesugaredType(*this, Context); 963 } 964 965 SplitQualType getSplitDesugaredType() const { 966 return getSplitDesugaredType(*this); 967 } 968 969 /// Return the specified type with one level of "sugar" removed from 970 /// the type. 971 /// 972 /// This routine takes off the first typedef, typeof, etc. If the outer level 973 /// of the type is already concrete, it returns it unmodified. 974 QualType getSingleStepDesugaredType(const ASTContext &Context) const { 975 return getSingleStepDesugaredTypeImpl(*this, Context); 976 } 977 978 /// Returns the specified type after dropping any 979 /// outer-level parentheses. 980 QualType IgnoreParens() const { 981 if (isa<ParenType>(*this)) 982 return QualType::IgnoreParens(*this); 983 return *this; 984 } 985 986 /// Indicate whether the specified types and qualifiers are identical. 987 friend bool operator==(const QualType &LHS, const QualType &RHS) { 988 return LHS.Value == RHS.Value; 989 } 990 friend bool operator!=(const QualType &LHS, const QualType &RHS) { 991 return LHS.Value != RHS.Value; 992 } 993 friend bool operator<(const QualType &LHS, const QualType &RHS) { 994 return LHS.Value < RHS.Value; 995 } 996 997 static std::string getAsString(SplitQualType split, 998 const PrintingPolicy &Policy) { 999 return getAsString(split.Ty, split.Quals, Policy); 1000 } 1001 static std::string getAsString(const Type *ty, Qualifiers qs, 1002 const PrintingPolicy &Policy); 1003 1004 std::string getAsString() const; 1005 std::string getAsString(const PrintingPolicy &Policy) const; 1006 1007 void print(raw_ostream &OS, const PrintingPolicy &Policy, 1008 const Twine &PlaceHolder = Twine(), 1009 unsigned Indentation = 0) const; 1010 1011 static void print(SplitQualType split, raw_ostream &OS, 1012 const PrintingPolicy &policy, const Twine &PlaceHolder, 1013 unsigned Indentation = 0) { 1014 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); 1015 } 1016 1017 static void print(const Type *ty, Qualifiers qs, 1018 raw_ostream &OS, const PrintingPolicy &policy, 1019 const Twine &PlaceHolder, 1020 unsigned Indentation = 0); 1021 1022 void getAsStringInternal(std::string &Str, 1023 const PrintingPolicy &Policy) const; 1024 1025 static void getAsStringInternal(SplitQualType split, std::string &out, 1026 const PrintingPolicy &policy) { 1027 return getAsStringInternal(split.Ty, split.Quals, out, policy); 1028 } 1029 1030 static void getAsStringInternal(const Type *ty, Qualifiers qs, 1031 std::string &out, 1032 const PrintingPolicy &policy); 1033 1034 class StreamedQualTypeHelper { 1035 const QualType &T; 1036 const PrintingPolicy &Policy; 1037 const Twine &PlaceHolder; 1038 unsigned Indentation; 1039 1040 public: 1041 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, 1042 const Twine &PlaceHolder, unsigned Indentation) 1043 : T(T), Policy(Policy), PlaceHolder(PlaceHolder), 1044 Indentation(Indentation) {} 1045 1046 friend raw_ostream &operator<<(raw_ostream &OS, 1047 const StreamedQualTypeHelper &SQT) { 1048 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); 1049 return OS; 1050 } 1051 }; 1052 1053 StreamedQualTypeHelper stream(const PrintingPolicy &Policy, 1054 const Twine &PlaceHolder = Twine(), 1055 unsigned Indentation = 0) const { 1056 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); 1057 } 1058 1059 void dump(const char *s) const; 1060 void dump() const; 1061 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; 1062 1063 void Profile(llvm::FoldingSetNodeID &ID) const { 1064 ID.AddPointer(getAsOpaquePtr()); 1065 } 1066 1067 /// Check if this type has any address space qualifier. 1068 inline bool hasAddressSpace() const; 1069 1070 /// Return the address space of this type. 1071 inline LangAS getAddressSpace() const; 1072 1073 /// Returns true if address space qualifiers overlap with T address space 1074 /// qualifiers. 1075 /// OpenCL C defines conversion rules for pointers to different address spaces 1076 /// and notion of overlapping address spaces. 1077 /// CL1.1 or CL1.2: 1078 /// address spaces overlap iff they are they same. 1079 /// OpenCL C v2.0 s6.5.5 adds: 1080 /// __generic overlaps with any address space except for __constant. 1081 bool isAddressSpaceOverlapping(QualType T) const { 1082 Qualifiers Q = getQualifiers(); 1083 Qualifiers TQ = T.getQualifiers(); 1084 // Address spaces overlap if at least one of them is a superset of another 1085 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); 1086 } 1087 1088 /// Returns gc attribute of this type. 1089 inline Qualifiers::GC getObjCGCAttr() const; 1090 1091 /// true when Type is objc's weak. 1092 bool isObjCGCWeak() const { 1093 return getObjCGCAttr() == Qualifiers::Weak; 1094 } 1095 1096 /// true when Type is objc's strong. 1097 bool isObjCGCStrong() const { 1098 return getObjCGCAttr() == Qualifiers::Strong; 1099 } 1100 1101 /// Returns lifetime attribute of this type. 1102 Qualifiers::ObjCLifetime getObjCLifetime() const { 1103 return getQualifiers().getObjCLifetime(); 1104 } 1105 1106 bool hasNonTrivialObjCLifetime() const { 1107 return getQualifiers().hasNonTrivialObjCLifetime(); 1108 } 1109 1110 bool hasStrongOrWeakObjCLifetime() const { 1111 return getQualifiers().hasStrongOrWeakObjCLifetime(); 1112 } 1113 1114 // true when Type is objc's weak and weak is enabled but ARC isn't. 1115 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; 1116 1117 enum PrimitiveDefaultInitializeKind { 1118 /// The type does not fall into any of the following categories. Note that 1119 /// this case is zero-valued so that values of this enum can be used as a 1120 /// boolean condition for non-triviality. 1121 PDIK_Trivial, 1122 1123 /// The type is an Objective-C retainable pointer type that is qualified 1124 /// with the ARC __strong qualifier. 1125 PDIK_ARCStrong, 1126 1127 /// The type is an Objective-C retainable pointer type that is qualified 1128 /// with the ARC __weak qualifier. 1129 PDIK_ARCWeak, 1130 1131 /// The type is a struct containing a field whose type is not PCK_Trivial. 1132 PDIK_Struct 1133 }; 1134 1135 /// Functions to query basic properties of non-trivial C struct types. 1136 1137 /// Check if this is a non-trivial type that would cause a C struct 1138 /// transitively containing this type to be non-trivial to default initialize 1139 /// and return the kind. 1140 PrimitiveDefaultInitializeKind 1141 isNonTrivialToPrimitiveDefaultInitialize() const; 1142 1143 enum PrimitiveCopyKind { 1144 /// The type does not fall into any of the following categories. Note that 1145 /// this case is zero-valued so that values of this enum can be used as a 1146 /// boolean condition for non-triviality. 1147 PCK_Trivial, 1148 1149 /// The type would be trivial except that it is volatile-qualified. Types 1150 /// that fall into one of the other non-trivial cases may additionally be 1151 /// volatile-qualified. 1152 PCK_VolatileTrivial, 1153 1154 /// The type is an Objective-C retainable pointer type that is qualified 1155 /// with the ARC __strong qualifier. 1156 PCK_ARCStrong, 1157 1158 /// The type is an Objective-C retainable pointer type that is qualified 1159 /// with the ARC __weak qualifier. 1160 PCK_ARCWeak, 1161 1162 /// The type is a struct containing a field whose type is neither 1163 /// PCK_Trivial nor PCK_VolatileTrivial. 1164 /// Note that a C++ struct type does not necessarily match this; C++ copying 1165 /// semantics are too complex to express here, in part because they depend 1166 /// on the exact constructor or assignment operator that is chosen by 1167 /// overload resolution to do the copy. 1168 PCK_Struct 1169 }; 1170 1171 /// Check if this is a non-trivial type that would cause a C struct 1172 /// transitively containing this type to be non-trivial to copy and return the 1173 /// kind. 1174 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; 1175 1176 /// Check if this is a non-trivial type that would cause a C struct 1177 /// transitively containing this type to be non-trivial to destructively 1178 /// move and return the kind. Destructive move in this context is a C++-style 1179 /// move in which the source object is placed in a valid but unspecified state 1180 /// after it is moved, as opposed to a truly destructive move in which the 1181 /// source object is placed in an uninitialized state. 1182 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; 1183 1184 enum DestructionKind { 1185 DK_none, 1186 DK_cxx_destructor, 1187 DK_objc_strong_lifetime, 1188 DK_objc_weak_lifetime, 1189 DK_nontrivial_c_struct 1190 }; 1191 1192 /// Returns a nonzero value if objects of this type require 1193 /// non-trivial work to clean up after. Non-zero because it's 1194 /// conceivable that qualifiers (objc_gc(weak)?) could make 1195 /// something require destruction. 1196 DestructionKind isDestructedType() const { 1197 return isDestructedTypeImpl(*this); 1198 } 1199 1200 /// Check if this is or contains a C union that is non-trivial to 1201 /// default-initialize, which is a union that has a member that is non-trivial 1202 /// to default-initialize. If this returns true, 1203 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. 1204 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; 1205 1206 /// Check if this is or contains a C union that is non-trivial to destruct, 1207 /// which is a union that has a member that is non-trivial to destruct. If 1208 /// this returns true, isDestructedType returns DK_nontrivial_c_struct. 1209 bool hasNonTrivialToPrimitiveDestructCUnion() const; 1210 1211 /// Check if this is or contains a C union that is non-trivial to copy, which 1212 /// is a union that has a member that is non-trivial to copy. If this returns 1213 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. 1214 bool hasNonTrivialToPrimitiveCopyCUnion() const; 1215 1216 /// Determine whether expressions of the given type are forbidden 1217 /// from being lvalues in C. 1218 /// 1219 /// The expression types that are forbidden to be lvalues are: 1220 /// - 'void', but not qualified void 1221 /// - function types 1222 /// 1223 /// The exact rule here is C99 6.3.2.1: 1224 /// An lvalue is an expression with an object type or an incomplete 1225 /// type other than void. 1226 bool isCForbiddenLValueType() const; 1227 1228 /// Substitute type arguments for the Objective-C type parameters used in the 1229 /// subject type. 1230 /// 1231 /// \param ctx ASTContext in which the type exists. 1232 /// 1233 /// \param typeArgs The type arguments that will be substituted for the 1234 /// Objective-C type parameters in the subject type, which are generally 1235 /// computed via \c Type::getObjCSubstitutions. If empty, the type 1236 /// parameters will be replaced with their bounds or id/Class, as appropriate 1237 /// for the context. 1238 /// 1239 /// \param context The context in which the subject type was written. 1240 /// 1241 /// \returns the resulting type. 1242 QualType substObjCTypeArgs(ASTContext &ctx, 1243 ArrayRef<QualType> typeArgs, 1244 ObjCSubstitutionContext context) const; 1245 1246 /// Substitute type arguments from an object type for the Objective-C type 1247 /// parameters used in the subject type. 1248 /// 1249 /// This operation combines the computation of type arguments for 1250 /// substitution (\c Type::getObjCSubstitutions) with the actual process of 1251 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of 1252 /// callers that need to perform a single substitution in isolation. 1253 /// 1254 /// \param objectType The type of the object whose member type we're 1255 /// substituting into. For example, this might be the receiver of a message 1256 /// or the base of a property access. 1257 /// 1258 /// \param dc The declaration context from which the subject type was 1259 /// retrieved, which indicates (for example) which type parameters should 1260 /// be substituted. 1261 /// 1262 /// \param context The context in which the subject type was written. 1263 /// 1264 /// \returns the subject type after replacing all of the Objective-C type 1265 /// parameters with their corresponding arguments. 1266 QualType substObjCMemberType(QualType objectType, 1267 const DeclContext *dc, 1268 ObjCSubstitutionContext context) const; 1269 1270 /// Strip Objective-C "__kindof" types from the given type. 1271 QualType stripObjCKindOfType(const ASTContext &ctx) const; 1272 1273 /// Remove all qualifiers including _Atomic. 1274 QualType getAtomicUnqualifiedType() const; 1275 1276 private: 1277 // These methods are implemented in a separate translation unit; 1278 // "static"-ize them to avoid creating temporary QualTypes in the 1279 // caller. 1280 static bool isConstant(QualType T, const ASTContext& Ctx); 1281 static QualType getDesugaredType(QualType T, const ASTContext &Context); 1282 static SplitQualType getSplitDesugaredType(QualType T); 1283 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); 1284 static QualType getSingleStepDesugaredTypeImpl(QualType type, 1285 const ASTContext &C); 1286 static QualType IgnoreParens(QualType T); 1287 static DestructionKind isDestructedTypeImpl(QualType type); 1288 1289 /// Check if \param RD is or contains a non-trivial C union. 1290 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); 1291 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); 1292 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); 1293 }; 1294 1295 } // namespace clang 1296 1297 namespace llvm { 1298 1299 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType 1300 /// to a specific Type class. 1301 template<> struct simplify_type< ::clang::QualType> { 1302 using SimpleType = const ::clang::Type *; 1303 1304 static SimpleType getSimplifiedValue(::clang::QualType Val) { 1305 return Val.getTypePtr(); 1306 } 1307 }; 1308 1309 // Teach SmallPtrSet that QualType is "basically a pointer". 1310 template<> 1311 struct PointerLikeTypeTraits<clang::QualType> { 1312 static inline void *getAsVoidPointer(clang::QualType P) { 1313 return P.getAsOpaquePtr(); 1314 } 1315 1316 static inline clang::QualType getFromVoidPointer(void *P) { 1317 return clang::QualType::getFromOpaquePtr(P); 1318 } 1319 1320 // Various qualifiers go in low bits. 1321 static constexpr int NumLowBitsAvailable = 0; 1322 }; 1323 1324 } // namespace llvm 1325 1326 namespace clang { 1327 1328 /// Base class that is common to both the \c ExtQuals and \c Type 1329 /// classes, which allows \c QualType to access the common fields between the 1330 /// two. 1331 class ExtQualsTypeCommonBase { 1332 friend class ExtQuals; 1333 friend class QualType; 1334 friend class Type; 1335 1336 /// The "base" type of an extended qualifiers type (\c ExtQuals) or 1337 /// a self-referential pointer (for \c Type). 1338 /// 1339 /// This pointer allows an efficient mapping from a QualType to its 1340 /// underlying type pointer. 1341 const Type *const BaseType; 1342 1343 /// The canonical type of this type. A QualType. 1344 QualType CanonicalType; 1345 1346 ExtQualsTypeCommonBase(const Type *baseType, QualType canon) 1347 : BaseType(baseType), CanonicalType(canon) {} 1348 }; 1349 1350 /// We can encode up to four bits in the low bits of a 1351 /// type pointer, but there are many more type qualifiers that we want 1352 /// to be able to apply to an arbitrary type. Therefore we have this 1353 /// struct, intended to be heap-allocated and used by QualType to 1354 /// store qualifiers. 1355 /// 1356 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers 1357 /// in three low bits on the QualType pointer; a fourth bit records whether 1358 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, 1359 /// Objective-C GC attributes) are much more rare. 1360 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { 1361 // NOTE: changing the fast qualifiers should be straightforward as 1362 // long as you don't make 'const' non-fast. 1363 // 1. Qualifiers: 1364 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). 1365 // Fast qualifiers must occupy the low-order bits. 1366 // b) Update Qualifiers::FastWidth and FastMask. 1367 // 2. QualType: 1368 // a) Update is{Volatile,Restrict}Qualified(), defined inline. 1369 // b) Update remove{Volatile,Restrict}, defined near the end of 1370 // this header. 1371 // 3. ASTContext: 1372 // a) Update get{Volatile,Restrict}Type. 1373 1374 /// The immutable set of qualifiers applied by this node. Always contains 1375 /// extended qualifiers. 1376 Qualifiers Quals; 1377 1378 ExtQuals *this_() { return this; } 1379 1380 public: 1381 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) 1382 : ExtQualsTypeCommonBase(baseType, 1383 canon.isNull() ? QualType(this_(), 0) : canon), 1384 Quals(quals) { 1385 assert(Quals.hasNonFastQualifiers() 1386 && "ExtQuals created with no fast qualifiers"); 1387 assert(!Quals.hasFastQualifiers() 1388 && "ExtQuals created with fast qualifiers"); 1389 } 1390 1391 Qualifiers getQualifiers() const { return Quals; } 1392 1393 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } 1394 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } 1395 1396 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } 1397 Qualifiers::ObjCLifetime getObjCLifetime() const { 1398 return Quals.getObjCLifetime(); 1399 } 1400 1401 bool hasAddressSpace() const { return Quals.hasAddressSpace(); } 1402 LangAS getAddressSpace() const { return Quals.getAddressSpace(); } 1403 1404 const Type *getBaseType() const { return BaseType; } 1405 1406 public: 1407 void Profile(llvm::FoldingSetNodeID &ID) const { 1408 Profile(ID, getBaseType(), Quals); 1409 } 1410 1411 static void Profile(llvm::FoldingSetNodeID &ID, 1412 const Type *BaseType, 1413 Qualifiers Quals) { 1414 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"); 1415 ID.AddPointer(BaseType); 1416 Quals.Profile(ID); 1417 } 1418 }; 1419 1420 /// The kind of C++11 ref-qualifier associated with a function type. 1421 /// This determines whether a member function's "this" object can be an 1422 /// lvalue, rvalue, or neither. 1423 enum RefQualifierKind { 1424 /// No ref-qualifier was provided. 1425 RQ_None = 0, 1426 1427 /// An lvalue ref-qualifier was provided (\c &). 1428 RQ_LValue, 1429 1430 /// An rvalue ref-qualifier was provided (\c &&). 1431 RQ_RValue 1432 }; 1433 1434 /// Which keyword(s) were used to create an AutoType. 1435 enum class AutoTypeKeyword { 1436 /// auto 1437 Auto, 1438 1439 /// decltype(auto) 1440 DecltypeAuto, 1441 1442 /// __auto_type (GNU extension) 1443 GNUAutoType 1444 }; 1445 1446 /// The base class of the type hierarchy. 1447 /// 1448 /// A central concept with types is that each type always has a canonical 1449 /// type. A canonical type is the type with any typedef names stripped out 1450 /// of it or the types it references. For example, consider: 1451 /// 1452 /// typedef int foo; 1453 /// typedef foo* bar; 1454 /// 'int *' 'foo *' 'bar' 1455 /// 1456 /// There will be a Type object created for 'int'. Since int is canonical, its 1457 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a 1458 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next 1459 /// there is a PointerType that represents 'int*', which, like 'int', is 1460 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical 1461 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type 1462 /// is also 'int*'. 1463 /// 1464 /// Non-canonical types are useful for emitting diagnostics, without losing 1465 /// information about typedefs being used. Canonical types are useful for type 1466 /// comparisons (they allow by-pointer equality tests) and useful for reasoning 1467 /// about whether something has a particular form (e.g. is a function type), 1468 /// because they implicitly, recursively, strip all typedefs out of a type. 1469 /// 1470 /// Types, once created, are immutable. 1471 /// 1472 class alignas(8) Type : public ExtQualsTypeCommonBase { 1473 public: 1474 enum TypeClass { 1475 #define TYPE(Class, Base) Class, 1476 #define LAST_TYPE(Class) TypeLast = Class 1477 #define ABSTRACT_TYPE(Class, Base) 1478 #include "clang/AST/TypeNodes.inc" 1479 }; 1480 1481 private: 1482 /// Bitfields required by the Type class. 1483 class TypeBitfields { 1484 friend class Type; 1485 template <class T> friend class TypePropertyCache; 1486 1487 /// TypeClass bitfield - Enum that specifies what subclass this belongs to. 1488 unsigned TC : 8; 1489 1490 /// Store information on the type dependency. 1491 unsigned Dependence : llvm::BitWidth<TypeDependence>; 1492 1493 /// True if the cache (i.e. the bitfields here starting with 1494 /// 'Cache') is valid. 1495 mutable unsigned CacheValid : 1; 1496 1497 /// Linkage of this type. 1498 mutable unsigned CachedLinkage : 3; 1499 1500 /// Whether this type involves and local or unnamed types. 1501 mutable unsigned CachedLocalOrUnnamed : 1; 1502 1503 /// Whether this type comes from an AST file. 1504 mutable unsigned FromAST : 1; 1505 1506 bool isCacheValid() const { 1507 return CacheValid; 1508 } 1509 1510 Linkage getLinkage() const { 1511 assert(isCacheValid() && "getting linkage from invalid cache"); 1512 return static_cast<Linkage>(CachedLinkage); 1513 } 1514 1515 bool hasLocalOrUnnamedType() const { 1516 assert(isCacheValid() && "getting linkage from invalid cache"); 1517 return CachedLocalOrUnnamed; 1518 } 1519 }; 1520 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; 1521 1522 protected: 1523 // These classes allow subclasses to somewhat cleanly pack bitfields 1524 // into Type. 1525 1526 class ArrayTypeBitfields { 1527 friend class ArrayType; 1528 1529 unsigned : NumTypeBits; 1530 1531 /// CVR qualifiers from declarations like 1532 /// 'int X[static restrict 4]'. For function parameters only. 1533 unsigned IndexTypeQuals : 3; 1534 1535 /// Storage class qualifiers from declarations like 1536 /// 'int X[static restrict 4]'. For function parameters only. 1537 /// Actually an ArrayType::ArraySizeModifier. 1538 unsigned SizeModifier : 3; 1539 }; 1540 1541 class ConstantArrayTypeBitfields { 1542 friend class ConstantArrayType; 1543 1544 unsigned : NumTypeBits + 3 + 3; 1545 1546 /// Whether we have a stored size expression. 1547 unsigned HasStoredSizeExpr : 1; 1548 }; 1549 1550 class BuiltinTypeBitfields { 1551 friend class BuiltinType; 1552 1553 unsigned : NumTypeBits; 1554 1555 /// The kind (BuiltinType::Kind) of builtin type this is. 1556 unsigned Kind : 8; 1557 }; 1558 1559 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. 1560 /// Only common bits are stored here. Additional uncommon bits are stored 1561 /// in a trailing object after FunctionProtoType. 1562 class FunctionTypeBitfields { 1563 friend class FunctionProtoType; 1564 friend class FunctionType; 1565 1566 unsigned : NumTypeBits; 1567 1568 /// Extra information which affects how the function is called, like 1569 /// regparm and the calling convention. 1570 unsigned ExtInfo : 13; 1571 1572 /// The ref-qualifier associated with a \c FunctionProtoType. 1573 /// 1574 /// This is a value of type \c RefQualifierKind. 1575 unsigned RefQualifier : 2; 1576 1577 /// Used only by FunctionProtoType, put here to pack with the 1578 /// other bitfields. 1579 /// The qualifiers are part of FunctionProtoType because... 1580 /// 1581 /// C++ 8.3.5p4: The return type, the parameter type list and the 1582 /// cv-qualifier-seq, [...], are part of the function type. 1583 unsigned FastTypeQuals : Qualifiers::FastWidth; 1584 /// Whether this function has extended Qualifiers. 1585 unsigned HasExtQuals : 1; 1586 1587 /// The number of parameters this function has, not counting '...'. 1588 /// According to [implimits] 8 bits should be enough here but this is 1589 /// somewhat easy to exceed with metaprogramming and so we would like to 1590 /// keep NumParams as wide as reasonably possible. 1591 unsigned NumParams : 16; 1592 1593 /// The type of exception specification this function has. 1594 unsigned ExceptionSpecType : 4; 1595 1596 /// Whether this function has extended parameter information. 1597 unsigned HasExtParameterInfos : 1; 1598 1599 /// Whether the function is variadic. 1600 unsigned Variadic : 1; 1601 1602 /// Whether this function has a trailing return type. 1603 unsigned HasTrailingReturn : 1; 1604 }; 1605 1606 class ObjCObjectTypeBitfields { 1607 friend class ObjCObjectType; 1608 1609 unsigned : NumTypeBits; 1610 1611 /// The number of type arguments stored directly on this object type. 1612 unsigned NumTypeArgs : 7; 1613 1614 /// The number of protocols stored directly on this object type. 1615 unsigned NumProtocols : 6; 1616 1617 /// Whether this is a "kindof" type. 1618 unsigned IsKindOf : 1; 1619 }; 1620 1621 class ReferenceTypeBitfields { 1622 friend class ReferenceType; 1623 1624 unsigned : NumTypeBits; 1625 1626 /// True if the type was originally spelled with an lvalue sigil. 1627 /// This is never true of rvalue references but can also be false 1628 /// on lvalue references because of C++0x [dcl.typedef]p9, 1629 /// as follows: 1630 /// 1631 /// typedef int &ref; // lvalue, spelled lvalue 1632 /// typedef int &&rvref; // rvalue 1633 /// ref &a; // lvalue, inner ref, spelled lvalue 1634 /// ref &&a; // lvalue, inner ref 1635 /// rvref &a; // lvalue, inner ref, spelled lvalue 1636 /// rvref &&a; // rvalue, inner ref 1637 unsigned SpelledAsLValue : 1; 1638 1639 /// True if the inner type is a reference type. This only happens 1640 /// in non-canonical forms. 1641 unsigned InnerRef : 1; 1642 }; 1643 1644 class TypeWithKeywordBitfields { 1645 friend class TypeWithKeyword; 1646 1647 unsigned : NumTypeBits; 1648 1649 /// An ElaboratedTypeKeyword. 8 bits for efficient access. 1650 unsigned Keyword : 8; 1651 }; 1652 1653 enum { NumTypeWithKeywordBits = 8 }; 1654 1655 class ElaboratedTypeBitfields { 1656 friend class ElaboratedType; 1657 1658 unsigned : NumTypeBits; 1659 unsigned : NumTypeWithKeywordBits; 1660 1661 /// Whether the ElaboratedType has a trailing OwnedTagDecl. 1662 unsigned HasOwnedTagDecl : 1; 1663 }; 1664 1665 class VectorTypeBitfields { 1666 friend class VectorType; 1667 friend class DependentVectorType; 1668 1669 unsigned : NumTypeBits; 1670 1671 /// The kind of vector, either a generic vector type or some 1672 /// target-specific vector type such as for AltiVec or Neon. 1673 unsigned VecKind : 3; 1674 /// The number of elements in the vector. 1675 uint32_t NumElements; 1676 }; 1677 1678 class ConstantMatrixTypeBitfields { 1679 friend class ConstantMatrixType; 1680 1681 unsigned : NumTypeBits; 1682 1683 /// Number of rows and columns. Using 20 bits allows supporting very large 1684 /// matrixes, while keeping 24 bits to accommodate NumTypeBits. 1685 unsigned NumRows : 20; 1686 unsigned NumColumns : 20; 1687 1688 static constexpr uint32_t MaxElementsPerDimension = (1 << 20) - 1; 1689 }; 1690 1691 class AttributedTypeBitfields { 1692 friend class AttributedType; 1693 1694 unsigned : NumTypeBits; 1695 1696 /// An AttributedType::Kind 1697 unsigned AttrKind : 32 - NumTypeBits; 1698 }; 1699 1700 class AutoTypeBitfields { 1701 friend class AutoType; 1702 1703 unsigned : NumTypeBits; 1704 1705 /// Was this placeholder type spelled as 'auto', 'decltype(auto)', 1706 /// or '__auto_type'? AutoTypeKeyword value. 1707 unsigned Keyword : 2; 1708 1709 /// The number of template arguments in the type-constraints, which is 1710 /// expected to be able to hold at least 1024 according to [implimits]. 1711 /// However as this limit is somewhat easy to hit with template 1712 /// metaprogramming we'd prefer to keep it as large as possible. 1713 /// At the moment it has been left as a non-bitfield since this type 1714 /// safely fits in 64 bits as an unsigned, so there is no reason to 1715 /// introduce the performance impact of a bitfield. 1716 unsigned NumArgs; 1717 }; 1718 1719 class SubstTemplateTypeParmPackTypeBitfields { 1720 friend class SubstTemplateTypeParmPackType; 1721 1722 unsigned : NumTypeBits; 1723 1724 /// The number of template arguments in \c Arguments, which is 1725 /// expected to be able to hold at least 1024 according to [implimits]. 1726 /// However as this limit is somewhat easy to hit with template 1727 /// metaprogramming we'd prefer to keep it as large as possible. 1728 /// At the moment it has been left as a non-bitfield since this type 1729 /// safely fits in 64 bits as an unsigned, so there is no reason to 1730 /// introduce the performance impact of a bitfield. 1731 unsigned NumArgs; 1732 }; 1733 1734 class TemplateSpecializationTypeBitfields { 1735 friend class TemplateSpecializationType; 1736 1737 unsigned : NumTypeBits; 1738 1739 /// Whether this template specialization type is a substituted type alias. 1740 unsigned TypeAlias : 1; 1741 1742 /// The number of template arguments named in this class template 1743 /// specialization, which is expected to be able to hold at least 1024 1744 /// according to [implimits]. However, as this limit is somewhat easy to 1745 /// hit with template metaprogramming we'd prefer to keep it as large 1746 /// as possible. At the moment it has been left as a non-bitfield since 1747 /// this type safely fits in 64 bits as an unsigned, so there is no reason 1748 /// to introduce the performance impact of a bitfield. 1749 unsigned NumArgs; 1750 }; 1751 1752 class DependentTemplateSpecializationTypeBitfields { 1753 friend class DependentTemplateSpecializationType; 1754 1755 unsigned : NumTypeBits; 1756 unsigned : NumTypeWithKeywordBits; 1757 1758 /// The number of template arguments named in this class template 1759 /// specialization, which is expected to be able to hold at least 1024 1760 /// according to [implimits]. However, as this limit is somewhat easy to 1761 /// hit with template metaprogramming we'd prefer to keep it as large 1762 /// as possible. At the moment it has been left as a non-bitfield since 1763 /// this type safely fits in 64 bits as an unsigned, so there is no reason 1764 /// to introduce the performance impact of a bitfield. 1765 unsigned NumArgs; 1766 }; 1767 1768 class PackExpansionTypeBitfields { 1769 friend class PackExpansionType; 1770 1771 unsigned : NumTypeBits; 1772 1773 /// The number of expansions that this pack expansion will 1774 /// generate when substituted (+1), which is expected to be able to 1775 /// hold at least 1024 according to [implimits]. However, as this limit 1776 /// is somewhat easy to hit with template metaprogramming we'd prefer to 1777 /// keep it as large as possible. At the moment it has been left as a 1778 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so 1779 /// there is no reason to introduce the performance impact of a bitfield. 1780 /// 1781 /// This field will only have a non-zero value when some of the parameter 1782 /// packs that occur within the pattern have been substituted but others 1783 /// have not. 1784 unsigned NumExpansions; 1785 }; 1786 1787 union { 1788 TypeBitfields TypeBits; 1789 ArrayTypeBitfields ArrayTypeBits; 1790 ConstantArrayTypeBitfields ConstantArrayTypeBits; 1791 AttributedTypeBitfields AttributedTypeBits; 1792 AutoTypeBitfields AutoTypeBits; 1793 BuiltinTypeBitfields BuiltinTypeBits; 1794 FunctionTypeBitfields FunctionTypeBits; 1795 ObjCObjectTypeBitfields ObjCObjectTypeBits; 1796 ReferenceTypeBitfields ReferenceTypeBits; 1797 TypeWithKeywordBitfields TypeWithKeywordBits; 1798 ElaboratedTypeBitfields ElaboratedTypeBits; 1799 VectorTypeBitfields VectorTypeBits; 1800 ConstantMatrixTypeBitfields ConstantMatrixTypeBits; 1801 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; 1802 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; 1803 DependentTemplateSpecializationTypeBitfields 1804 DependentTemplateSpecializationTypeBits; 1805 PackExpansionTypeBitfields PackExpansionTypeBits; 1806 }; 1807 1808 static_assert(sizeof(TypeBitfields) <= 8, 1809 "TypeBitfields is larger than 8 bytes!"); 1810 static_assert(sizeof(ArrayTypeBitfields) <= 8, 1811 "ArrayTypeBitfields is larger than 8 bytes!"); 1812 static_assert(sizeof(AttributedTypeBitfields) <= 8, 1813 "AttributedTypeBitfields is larger than 8 bytes!"); 1814 static_assert(sizeof(AutoTypeBitfields) <= 8, 1815 "AutoTypeBitfields is larger than 8 bytes!"); 1816 static_assert(sizeof(BuiltinTypeBitfields) <= 8, 1817 "BuiltinTypeBitfields is larger than 8 bytes!"); 1818 static_assert(sizeof(FunctionTypeBitfields) <= 8, 1819 "FunctionTypeBitfields is larger than 8 bytes!"); 1820 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8, 1821 "ObjCObjectTypeBitfields is larger than 8 bytes!"); 1822 static_assert(sizeof(ReferenceTypeBitfields) <= 8, 1823 "ReferenceTypeBitfields is larger than 8 bytes!"); 1824 static_assert(sizeof(TypeWithKeywordBitfields) <= 8, 1825 "TypeWithKeywordBitfields is larger than 8 bytes!"); 1826 static_assert(sizeof(ElaboratedTypeBitfields) <= 8, 1827 "ElaboratedTypeBitfields is larger than 8 bytes!"); 1828 static_assert(sizeof(VectorTypeBitfields) <= 8, 1829 "VectorTypeBitfields is larger than 8 bytes!"); 1830 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8, 1831 "SubstTemplateTypeParmPackTypeBitfields is larger" 1832 " than 8 bytes!"); 1833 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8, 1834 "TemplateSpecializationTypeBitfields is larger" 1835 " than 8 bytes!"); 1836 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8, 1837 "DependentTemplateSpecializationTypeBitfields is larger" 1838 " than 8 bytes!"); 1839 static_assert(sizeof(PackExpansionTypeBitfields) <= 8, 1840 "PackExpansionTypeBitfields is larger than 8 bytes"); 1841 1842 private: 1843 template <class T> friend class TypePropertyCache; 1844 1845 /// Set whether this type comes from an AST file. 1846 void setFromAST(bool V = true) const { 1847 TypeBits.FromAST = V; 1848 } 1849 1850 protected: 1851 friend class ASTContext; 1852 1853 Type(TypeClass tc, QualType canon, TypeDependence Dependence) 1854 : ExtQualsTypeCommonBase(this, 1855 canon.isNull() ? QualType(this_(), 0) : canon) { 1856 TypeBits.TC = tc; 1857 TypeBits.Dependence = static_cast<unsigned>(Dependence); 1858 TypeBits.CacheValid = false; 1859 TypeBits.CachedLocalOrUnnamed = false; 1860 TypeBits.CachedLinkage = NoLinkage; 1861 TypeBits.FromAST = false; 1862 } 1863 1864 // silence VC++ warning C4355: 'this' : used in base member initializer list 1865 Type *this_() { return this; } 1866 1867 void setDependence(TypeDependence D) { 1868 TypeBits.Dependence = static_cast<unsigned>(D); 1869 } 1870 1871 void addDependence(TypeDependence D) { setDependence(getDependence() | D); } 1872 1873 public: 1874 friend class ASTReader; 1875 friend class ASTWriter; 1876 template <class T> friend class serialization::AbstractTypeReader; 1877 template <class T> friend class serialization::AbstractTypeWriter; 1878 1879 Type(const Type &) = delete; 1880 Type(Type &&) = delete; 1881 Type &operator=(const Type &) = delete; 1882 Type &operator=(Type &&) = delete; 1883 1884 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } 1885 1886 /// Whether this type comes from an AST file. 1887 bool isFromAST() const { return TypeBits.FromAST; } 1888 1889 /// Whether this type is or contains an unexpanded parameter 1890 /// pack, used to support C++0x variadic templates. 1891 /// 1892 /// A type that contains a parameter pack shall be expanded by the 1893 /// ellipsis operator at some point. For example, the typedef in the 1894 /// following example contains an unexpanded parameter pack 'T': 1895 /// 1896 /// \code 1897 /// template<typename ...T> 1898 /// struct X { 1899 /// typedef T* pointer_types; // ill-formed; T is a parameter pack. 1900 /// }; 1901 /// \endcode 1902 /// 1903 /// Note that this routine does not specify which 1904 bool containsUnexpandedParameterPack() const { 1905 return getDependence() & TypeDependence::UnexpandedPack; 1906 } 1907 1908 /// Determines if this type would be canonical if it had no further 1909 /// qualification. 1910 bool isCanonicalUnqualified() const { 1911 return CanonicalType == QualType(this, 0); 1912 } 1913 1914 /// Pull a single level of sugar off of this locally-unqualified type. 1915 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() 1916 /// or QualType::getSingleStepDesugaredType(const ASTContext&). 1917 QualType getLocallyUnqualifiedSingleStepDesugaredType() const; 1918 1919 /// As an extension, we classify types as one of "sized" or "sizeless"; 1920 /// every type is one or the other. Standard types are all sized; 1921 /// sizeless types are purely an extension. 1922 /// 1923 /// Sizeless types contain data with no specified size, alignment, 1924 /// or layout. 1925 bool isSizelessType() const; 1926 bool isSizelessBuiltinType() const; 1927 1928 /// Types are partitioned into 3 broad categories (C99 6.2.5p1): 1929 /// object types, function types, and incomplete types. 1930 1931 /// Return true if this is an incomplete type. 1932 /// A type that can describe objects, but which lacks information needed to 1933 /// determine its size (e.g. void, or a fwd declared struct). Clients of this 1934 /// routine will need to determine if the size is actually required. 1935 /// 1936 /// Def If non-null, and the type refers to some kind of declaration 1937 /// that can be completed (such as a C struct, C++ class, or Objective-C 1938 /// class), will be set to the declaration. 1939 bool isIncompleteType(NamedDecl **Def = nullptr) const; 1940 1941 /// Return true if this is an incomplete or object 1942 /// type, in other words, not a function type. 1943 bool isIncompleteOrObjectType() const { 1944 return !isFunctionType(); 1945 } 1946 1947 /// Determine whether this type is an object type. 1948 bool isObjectType() const { 1949 // C++ [basic.types]p8: 1950 // An object type is a (possibly cv-qualified) type that is not a 1951 // function type, not a reference type, and not a void type. 1952 return !isReferenceType() && !isFunctionType() && !isVoidType(); 1953 } 1954 1955 /// Return true if this is a literal type 1956 /// (C++11 [basic.types]p10) 1957 bool isLiteralType(const ASTContext &Ctx) const; 1958 1959 /// Test if this type is a standard-layout type. 1960 /// (C++0x [basic.type]p9) 1961 bool isStandardLayoutType() const; 1962 1963 /// Helper methods to distinguish type categories. All type predicates 1964 /// operate on the canonical type, ignoring typedefs and qualifiers. 1965 1966 /// Returns true if the type is a builtin type. 1967 bool isBuiltinType() const; 1968 1969 /// Test for a particular builtin type. 1970 bool isSpecificBuiltinType(unsigned K) const; 1971 1972 /// Test for a type which does not represent an actual type-system type but 1973 /// is instead used as a placeholder for various convenient purposes within 1974 /// Clang. All such types are BuiltinTypes. 1975 bool isPlaceholderType() const; 1976 const BuiltinType *getAsPlaceholderType() const; 1977 1978 /// Test for a specific placeholder type. 1979 bool isSpecificPlaceholderType(unsigned K) const; 1980 1981 /// Test for a placeholder type other than Overload; see 1982 /// BuiltinType::isNonOverloadPlaceholderType. 1983 bool isNonOverloadPlaceholderType() const; 1984 1985 /// isIntegerType() does *not* include complex integers (a GCC extension). 1986 /// isComplexIntegerType() can be used to test for complex integers. 1987 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) 1988 bool isEnumeralType() const; 1989 1990 /// Determine whether this type is a scoped enumeration type. 1991 bool isScopedEnumeralType() const; 1992 bool isBooleanType() const; 1993 bool isCharType() const; 1994 bool isWideCharType() const; 1995 bool isChar8Type() const; 1996 bool isChar16Type() const; 1997 bool isChar32Type() const; 1998 bool isAnyCharacterType() const; 1999 bool isIntegralType(const ASTContext &Ctx) const; 2000 2001 /// Determine whether this type is an integral or enumeration type. 2002 bool isIntegralOrEnumerationType() const; 2003 2004 /// Determine whether this type is an integral or unscoped enumeration type. 2005 bool isIntegralOrUnscopedEnumerationType() const; 2006 bool isUnscopedEnumerationType() const; 2007 2008 /// Floating point categories. 2009 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) 2010 /// isComplexType() does *not* include complex integers (a GCC extension). 2011 /// isComplexIntegerType() can be used to test for complex integers. 2012 bool isComplexType() const; // C99 6.2.5p11 (complex) 2013 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. 2014 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) 2015 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) 2016 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 2017 bool isBFloat16Type() const; 2018 bool isFloat128Type() const; 2019 bool isRealType() const; // C99 6.2.5p17 (real floating + integer) 2020 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) 2021 bool isVoidType() const; // C99 6.2.5p19 2022 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) 2023 bool isAggregateType() const; 2024 bool isFundamentalType() const; 2025 bool isCompoundType() const; 2026 2027 // Type Predicates: Check to see if this type is structurally the specified 2028 // type, ignoring typedefs and qualifiers. 2029 bool isFunctionType() const; 2030 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } 2031 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } 2032 bool isPointerType() const; 2033 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer 2034 bool isBlockPointerType() const; 2035 bool isVoidPointerType() const; 2036 bool isReferenceType() const; 2037 bool isLValueReferenceType() const; 2038 bool isRValueReferenceType() const; 2039 bool isObjectPointerType() const; 2040 bool isFunctionPointerType() const; 2041 bool isFunctionReferenceType() const; 2042 bool isMemberPointerType() const; 2043 bool isMemberFunctionPointerType() const; 2044 bool isMemberDataPointerType() const; 2045 bool isArrayType() const; 2046 bool isConstantArrayType() const; 2047 bool isIncompleteArrayType() const; 2048 bool isVariableArrayType() const; 2049 bool isDependentSizedArrayType() const; 2050 bool isRecordType() const; 2051 bool isClassType() const; 2052 bool isStructureType() const; 2053 bool isObjCBoxableRecordType() const; 2054 bool isInterfaceType() const; 2055 bool isStructureOrClassType() const; 2056 bool isUnionType() const; 2057 bool isComplexIntegerType() const; // GCC _Complex integer type. 2058 bool isVectorType() const; // GCC vector type. 2059 bool isExtVectorType() const; // Extended vector type. 2060 bool isMatrixType() const; // Matrix type. 2061 bool isConstantMatrixType() const; // Constant matrix type. 2062 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier 2063 bool isObjCObjectPointerType() const; // pointer to ObjC object 2064 bool isObjCRetainableType() const; // ObjC object or block pointer 2065 bool isObjCLifetimeType() const; // (array of)* retainable type 2066 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type 2067 bool isObjCNSObjectType() const; // __attribute__((NSObject)) 2068 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) 2069 // FIXME: change this to 'raw' interface type, so we can used 'interface' type 2070 // for the common case. 2071 bool isObjCObjectType() const; // NSString or typeof(*(id)0) 2072 bool isObjCQualifiedInterfaceType() const; // NSString<foo> 2073 bool isObjCQualifiedIdType() const; // id<foo> 2074 bool isObjCQualifiedClassType() const; // Class<foo> 2075 bool isObjCObjectOrInterfaceType() const; 2076 bool isObjCIdType() const; // id 2077 bool isDecltypeType() const; 2078 /// Was this type written with the special inert-in-ARC __unsafe_unretained 2079 /// qualifier? 2080 /// 2081 /// This approximates the answer to the following question: if this 2082 /// translation unit were compiled in ARC, would this type be qualified 2083 /// with __unsafe_unretained? 2084 bool isObjCInertUnsafeUnretainedType() const { 2085 return hasAttr(attr::ObjCInertUnsafeUnretained); 2086 } 2087 2088 /// Whether the type is Objective-C 'id' or a __kindof type of an 2089 /// object type, e.g., __kindof NSView * or __kindof id 2090 /// <NSCopying>. 2091 /// 2092 /// \param bound Will be set to the bound on non-id subtype types, 2093 /// which will be (possibly specialized) Objective-C class type, or 2094 /// null for 'id. 2095 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, 2096 const ObjCObjectType *&bound) const; 2097 2098 bool isObjCClassType() const; // Class 2099 2100 /// Whether the type is Objective-C 'Class' or a __kindof type of an 2101 /// Class type, e.g., __kindof Class <NSCopying>. 2102 /// 2103 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound 2104 /// here because Objective-C's type system cannot express "a class 2105 /// object for a subclass of NSFoo". 2106 bool isObjCClassOrClassKindOfType() const; 2107 2108 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; 2109 bool isObjCSelType() const; // Class 2110 bool isObjCBuiltinType() const; // 'id' or 'Class' 2111 bool isObjCARCBridgableType() const; 2112 bool isCARCBridgableType() const; 2113 bool isTemplateTypeParmType() const; // C++ template type parameter 2114 bool isNullPtrType() const; // C++11 std::nullptr_t 2115 bool isNothrowT() const; // C++ std::nothrow_t 2116 bool isAlignValT() const; // C++17 std::align_val_t 2117 bool isStdByteType() const; // C++17 std::byte 2118 bool isAtomicType() const; // C11 _Atomic() 2119 bool isUndeducedAutoType() const; // C++11 auto or 2120 // C++14 decltype(auto) 2121 2122 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2123 bool is##Id##Type() const; 2124 #include "clang/Basic/OpenCLImageTypes.def" 2125 2126 bool isImageType() const; // Any OpenCL image type 2127 2128 bool isSamplerT() const; // OpenCL sampler_t 2129 bool isEventT() const; // OpenCL event_t 2130 bool isClkEventT() const; // OpenCL clk_event_t 2131 bool isQueueT() const; // OpenCL queue_t 2132 bool isReserveIDT() const; // OpenCL reserve_id_t 2133 2134 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2135 bool is##Id##Type() const; 2136 #include "clang/Basic/OpenCLExtensionTypes.def" 2137 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension 2138 bool isOCLIntelSubgroupAVCType() const; 2139 bool isOCLExtOpaqueType() const; // Any OpenCL extension type 2140 2141 bool isPipeType() const; // OpenCL pipe type 2142 bool isExtIntType() const; // Extended Int Type 2143 bool isOpenCLSpecificType() const; // Any OpenCL specific type 2144 2145 /// Determines if this type, which must satisfy 2146 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather 2147 /// than implicitly __strong. 2148 bool isObjCARCImplicitlyUnretainedType() const; 2149 2150 /// Check if the type is the CUDA device builtin surface type. 2151 bool isCUDADeviceBuiltinSurfaceType() const; 2152 /// Check if the type is the CUDA device builtin texture type. 2153 bool isCUDADeviceBuiltinTextureType() const; 2154 2155 /// Return the implicit lifetime for this type, which must not be dependent. 2156 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; 2157 2158 enum ScalarTypeKind { 2159 STK_CPointer, 2160 STK_BlockPointer, 2161 STK_ObjCObjectPointer, 2162 STK_MemberPointer, 2163 STK_Bool, 2164 STK_Integral, 2165 STK_Floating, 2166 STK_IntegralComplex, 2167 STK_FloatingComplex, 2168 STK_FixedPoint 2169 }; 2170 2171 /// Given that this is a scalar type, classify it. 2172 ScalarTypeKind getScalarTypeKind() const; 2173 2174 TypeDependence getDependence() const { 2175 return static_cast<TypeDependence>(TypeBits.Dependence); 2176 } 2177 2178 /// Whether this type is an error type. 2179 bool containsErrors() const { 2180 return getDependence() & TypeDependence::Error; 2181 } 2182 2183 /// Whether this type is a dependent type, meaning that its definition 2184 /// somehow depends on a template parameter (C++ [temp.dep.type]). 2185 bool isDependentType() const { 2186 return getDependence() & TypeDependence::Dependent; 2187 } 2188 2189 /// Determine whether this type is an instantiation-dependent type, 2190 /// meaning that the type involves a template parameter (even if the 2191 /// definition does not actually depend on the type substituted for that 2192 /// template parameter). 2193 bool isInstantiationDependentType() const { 2194 return getDependence() & TypeDependence::Instantiation; 2195 } 2196 2197 /// Determine whether this type is an undeduced type, meaning that 2198 /// it somehow involves a C++11 'auto' type or similar which has not yet been 2199 /// deduced. 2200 bool isUndeducedType() const; 2201 2202 /// Whether this type is a variably-modified type (C99 6.7.5). 2203 bool isVariablyModifiedType() const { 2204 return getDependence() & TypeDependence::VariablyModified; 2205 } 2206 2207 /// Whether this type involves a variable-length array type 2208 /// with a definite size. 2209 bool hasSizedVLAType() const; 2210 2211 /// Whether this type is or contains a local or unnamed type. 2212 bool hasUnnamedOrLocalType() const; 2213 2214 bool isOverloadableType() const; 2215 2216 /// Determine wither this type is a C++ elaborated-type-specifier. 2217 bool isElaboratedTypeSpecifier() const; 2218 2219 bool canDecayToPointerType() const; 2220 2221 /// Whether this type is represented natively as a pointer. This includes 2222 /// pointers, references, block pointers, and Objective-C interface, 2223 /// qualified id, and qualified interface types, as well as nullptr_t. 2224 bool hasPointerRepresentation() const; 2225 2226 /// Whether this type can represent an objective pointer type for the 2227 /// purpose of GC'ability 2228 bool hasObjCPointerRepresentation() const; 2229 2230 /// Determine whether this type has an integer representation 2231 /// of some sort, e.g., it is an integer type or a vector. 2232 bool hasIntegerRepresentation() const; 2233 2234 /// Determine whether this type has an signed integer representation 2235 /// of some sort, e.g., it is an signed integer type or a vector. 2236 bool hasSignedIntegerRepresentation() const; 2237 2238 /// Determine whether this type has an unsigned integer representation 2239 /// of some sort, e.g., it is an unsigned integer type or a vector. 2240 bool hasUnsignedIntegerRepresentation() const; 2241 2242 /// Determine whether this type has a floating-point representation 2243 /// of some sort, e.g., it is a floating-point type or a vector thereof. 2244 bool hasFloatingRepresentation() const; 2245 2246 // Type Checking Functions: Check to see if this type is structurally the 2247 // specified type, ignoring typedefs and qualifiers, and return a pointer to 2248 // the best type we can. 2249 const RecordType *getAsStructureType() const; 2250 /// NOTE: getAs*ArrayType are methods on ASTContext. 2251 const RecordType *getAsUnionType() const; 2252 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. 2253 const ObjCObjectType *getAsObjCInterfaceType() const; 2254 2255 // The following is a convenience method that returns an ObjCObjectPointerType 2256 // for object declared using an interface. 2257 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; 2258 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; 2259 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; 2260 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; 2261 2262 /// Retrieves the CXXRecordDecl that this type refers to, either 2263 /// because the type is a RecordType or because it is the injected-class-name 2264 /// type of a class template or class template partial specialization. 2265 CXXRecordDecl *getAsCXXRecordDecl() const; 2266 2267 /// Retrieves the RecordDecl this type refers to. 2268 RecordDecl *getAsRecordDecl() const; 2269 2270 /// Retrieves the TagDecl that this type refers to, either 2271 /// because the type is a TagType or because it is the injected-class-name 2272 /// type of a class template or class template partial specialization. 2273 TagDecl *getAsTagDecl() const; 2274 2275 /// If this is a pointer or reference to a RecordType, return the 2276 /// CXXRecordDecl that the type refers to. 2277 /// 2278 /// If this is not a pointer or reference, or the type being pointed to does 2279 /// not refer to a CXXRecordDecl, returns NULL. 2280 const CXXRecordDecl *getPointeeCXXRecordDecl() const; 2281 2282 /// Get the DeducedType whose type will be deduced for a variable with 2283 /// an initializer of this type. This looks through declarators like pointer 2284 /// types, but not through decltype or typedefs. 2285 DeducedType *getContainedDeducedType() const; 2286 2287 /// Get the AutoType whose type will be deduced for a variable with 2288 /// an initializer of this type. This looks through declarators like pointer 2289 /// types, but not through decltype or typedefs. 2290 AutoType *getContainedAutoType() const { 2291 return dyn_cast_or_null<AutoType>(getContainedDeducedType()); 2292 } 2293 2294 /// Determine whether this type was written with a leading 'auto' 2295 /// corresponding to a trailing return type (possibly for a nested 2296 /// function type within a pointer to function type or similar). 2297 bool hasAutoForTrailingReturnType() const; 2298 2299 /// Member-template getAs<specific type>'. Look through sugar for 2300 /// an instance of \<specific type>. This scheme will eventually 2301 /// replace the specific getAsXXXX methods above. 2302 /// 2303 /// There are some specializations of this member template listed 2304 /// immediately following this class. 2305 template <typename T> const T *getAs() const; 2306 2307 /// Member-template getAsAdjusted<specific type>. Look through specific kinds 2308 /// of sugar (parens, attributes, etc) for an instance of \<specific type>. 2309 /// This is used when you need to walk over sugar nodes that represent some 2310 /// kind of type adjustment from a type that was written as a \<specific type> 2311 /// to another type that is still canonically a \<specific type>. 2312 template <typename T> const T *getAsAdjusted() const; 2313 2314 /// A variant of getAs<> for array types which silently discards 2315 /// qualifiers from the outermost type. 2316 const ArrayType *getAsArrayTypeUnsafe() const; 2317 2318 /// Member-template castAs<specific type>. Look through sugar for 2319 /// the underlying instance of \<specific type>. 2320 /// 2321 /// This method has the same relationship to getAs<T> as cast<T> has 2322 /// to dyn_cast<T>; which is to say, the underlying type *must* 2323 /// have the intended type, and this method will never return null. 2324 template <typename T> const T *castAs() const; 2325 2326 /// A variant of castAs<> for array type which silently discards 2327 /// qualifiers from the outermost type. 2328 const ArrayType *castAsArrayTypeUnsafe() const; 2329 2330 /// Determine whether this type had the specified attribute applied to it 2331 /// (looking through top-level type sugar). 2332 bool hasAttr(attr::Kind AK) const; 2333 2334 /// Get the base element type of this type, potentially discarding type 2335 /// qualifiers. This should never be used when type qualifiers 2336 /// are meaningful. 2337 const Type *getBaseElementTypeUnsafe() const; 2338 2339 /// If this is an array type, return the element type of the array, 2340 /// potentially with type qualifiers missing. 2341 /// This should never be used when type qualifiers are meaningful. 2342 const Type *getArrayElementTypeNoTypeQual() const; 2343 2344 /// If this is a pointer type, return the pointee type. 2345 /// If this is an array type, return the array element type. 2346 /// This should never be used when type qualifiers are meaningful. 2347 const Type *getPointeeOrArrayElementType() const; 2348 2349 /// If this is a pointer, ObjC object pointer, or block 2350 /// pointer, this returns the respective pointee. 2351 QualType getPointeeType() const; 2352 2353 /// Return the specified type with any "sugar" removed from the type, 2354 /// removing any typedefs, typeofs, etc., as well as any qualifiers. 2355 const Type *getUnqualifiedDesugaredType() const; 2356 2357 /// More type predicates useful for type checking/promotion 2358 bool isPromotableIntegerType() const; // C99 6.3.1.1p2 2359 2360 /// Return true if this is an integer type that is 2361 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 2362 /// or an enum decl which has a signed representation. 2363 bool isSignedIntegerType() const; 2364 2365 /// Return true if this is an integer type that is 2366 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], 2367 /// or an enum decl which has an unsigned representation. 2368 bool isUnsignedIntegerType() const; 2369 2370 /// Determines whether this is an integer type that is signed or an 2371 /// enumeration types whose underlying type is a signed integer type. 2372 bool isSignedIntegerOrEnumerationType() const; 2373 2374 /// Determines whether this is an integer type that is unsigned or an 2375 /// enumeration types whose underlying type is a unsigned integer type. 2376 bool isUnsignedIntegerOrEnumerationType() const; 2377 2378 /// Return true if this is a fixed point type according to 2379 /// ISO/IEC JTC1 SC22 WG14 N1169. 2380 bool isFixedPointType() const; 2381 2382 /// Return true if this is a fixed point or integer type. 2383 bool isFixedPointOrIntegerType() const; 2384 2385 /// Return true if this is a saturated fixed point type according to 2386 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. 2387 bool isSaturatedFixedPointType() const; 2388 2389 /// Return true if this is a saturated fixed point type according to 2390 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. 2391 bool isUnsaturatedFixedPointType() const; 2392 2393 /// Return true if this is a fixed point type that is signed according 2394 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. 2395 bool isSignedFixedPointType() const; 2396 2397 /// Return true if this is a fixed point type that is unsigned according 2398 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. 2399 bool isUnsignedFixedPointType() const; 2400 2401 /// Return true if this is not a variable sized type, 2402 /// according to the rules of C99 6.7.5p3. It is not legal to call this on 2403 /// incomplete types. 2404 bool isConstantSizeType() const; 2405 2406 /// Returns true if this type can be represented by some 2407 /// set of type specifiers. 2408 bool isSpecifierType() const; 2409 2410 /// Determine the linkage of this type. 2411 Linkage getLinkage() const; 2412 2413 /// Determine the visibility of this type. 2414 Visibility getVisibility() const { 2415 return getLinkageAndVisibility().getVisibility(); 2416 } 2417 2418 /// Return true if the visibility was explicitly set is the code. 2419 bool isVisibilityExplicit() const { 2420 return getLinkageAndVisibility().isVisibilityExplicit(); 2421 } 2422 2423 /// Determine the linkage and visibility of this type. 2424 LinkageInfo getLinkageAndVisibility() const; 2425 2426 /// True if the computed linkage is valid. Used for consistency 2427 /// checking. Should always return true. 2428 bool isLinkageValid() const; 2429 2430 /// Determine the nullability of the given type. 2431 /// 2432 /// Note that nullability is only captured as sugar within the type 2433 /// system, not as part of the canonical type, so nullability will 2434 /// be lost by canonicalization and desugaring. 2435 Optional<NullabilityKind> getNullability(const ASTContext &context) const; 2436 2437 /// Determine whether the given type can have a nullability 2438 /// specifier applied to it, i.e., if it is any kind of pointer type. 2439 /// 2440 /// \param ResultIfUnknown The value to return if we don't yet know whether 2441 /// this type can have nullability because it is dependent. 2442 bool canHaveNullability(bool ResultIfUnknown = true) const; 2443 2444 /// Retrieve the set of substitutions required when accessing a member 2445 /// of the Objective-C receiver type that is declared in the given context. 2446 /// 2447 /// \c *this is the type of the object we're operating on, e.g., the 2448 /// receiver for a message send or the base of a property access, and is 2449 /// expected to be of some object or object pointer type. 2450 /// 2451 /// \param dc The declaration context for which we are building up a 2452 /// substitution mapping, which should be an Objective-C class, extension, 2453 /// category, or method within. 2454 /// 2455 /// \returns an array of type arguments that can be substituted for 2456 /// the type parameters of the given declaration context in any type described 2457 /// within that context, or an empty optional to indicate that no 2458 /// substitution is required. 2459 Optional<ArrayRef<QualType>> 2460 getObjCSubstitutions(const DeclContext *dc) const; 2461 2462 /// Determines if this is an ObjC interface type that may accept type 2463 /// parameters. 2464 bool acceptsObjCTypeParams() const; 2465 2466 const char *getTypeClassName() const; 2467 2468 QualType getCanonicalTypeInternal() const { 2469 return CanonicalType; 2470 } 2471 2472 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h 2473 void dump() const; 2474 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; 2475 }; 2476 2477 /// This will check for a TypedefType by removing any existing sugar 2478 /// until it reaches a TypedefType or a non-sugared type. 2479 template <> const TypedefType *Type::getAs() const; 2480 2481 /// This will check for a TemplateSpecializationType by removing any 2482 /// existing sugar until it reaches a TemplateSpecializationType or a 2483 /// non-sugared type. 2484 template <> const TemplateSpecializationType *Type::getAs() const; 2485 2486 /// This will check for an AttributedType by removing any existing sugar 2487 /// until it reaches an AttributedType or a non-sugared type. 2488 template <> const AttributedType *Type::getAs() const; 2489 2490 // We can do canonical leaf types faster, because we don't have to 2491 // worry about preserving child type decoration. 2492 #define TYPE(Class, Base) 2493 #define LEAF_TYPE(Class) \ 2494 template <> inline const Class##Type *Type::getAs() const { \ 2495 return dyn_cast<Class##Type>(CanonicalType); \ 2496 } \ 2497 template <> inline const Class##Type *Type::castAs() const { \ 2498 return cast<Class##Type>(CanonicalType); \ 2499 } 2500 #include "clang/AST/TypeNodes.inc" 2501 2502 /// This class is used for builtin types like 'int'. Builtin 2503 /// types are always canonical and have a literal name field. 2504 class BuiltinType : public Type { 2505 public: 2506 enum Kind { 2507 // OpenCL image types 2508 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, 2509 #include "clang/Basic/OpenCLImageTypes.def" 2510 // OpenCL extension types 2511 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, 2512 #include "clang/Basic/OpenCLExtensionTypes.def" 2513 // SVE Types 2514 #define SVE_TYPE(Name, Id, SingletonId) Id, 2515 #include "clang/Basic/AArch64SVEACLETypes.def" 2516 // All other builtin types 2517 #define BUILTIN_TYPE(Id, SingletonId) Id, 2518 #define LAST_BUILTIN_TYPE(Id) LastKind = Id 2519 #include "clang/AST/BuiltinTypes.def" 2520 }; 2521 2522 private: 2523 friend class ASTContext; // ASTContext creates these. 2524 2525 BuiltinType(Kind K) 2526 : Type(Builtin, QualType(), 2527 K == Dependent ? TypeDependence::DependentInstantiation 2528 : TypeDependence::None) { 2529 BuiltinTypeBits.Kind = K; 2530 } 2531 2532 public: 2533 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } 2534 StringRef getName(const PrintingPolicy &Policy) const; 2535 2536 const char *getNameAsCString(const PrintingPolicy &Policy) const { 2537 // The StringRef is null-terminated. 2538 StringRef str = getName(Policy); 2539 assert(!str.empty() && str.data()[str.size()] == '\0'); 2540 return str.data(); 2541 } 2542 2543 bool isSugared() const { return false; } 2544 QualType desugar() const { return QualType(this, 0); } 2545 2546 bool isInteger() const { 2547 return getKind() >= Bool && getKind() <= Int128; 2548 } 2549 2550 bool isSignedInteger() const { 2551 return getKind() >= Char_S && getKind() <= Int128; 2552 } 2553 2554 bool isUnsignedInteger() const { 2555 return getKind() >= Bool && getKind() <= UInt128; 2556 } 2557 2558 bool isFloatingPoint() const { 2559 return getKind() >= Half && getKind() <= Float128; 2560 } 2561 2562 /// Determines whether the given kind corresponds to a placeholder type. 2563 static bool isPlaceholderTypeKind(Kind K) { 2564 return K >= Overload; 2565 } 2566 2567 /// Determines whether this type is a placeholder type, i.e. a type 2568 /// which cannot appear in arbitrary positions in a fully-formed 2569 /// expression. 2570 bool isPlaceholderType() const { 2571 return isPlaceholderTypeKind(getKind()); 2572 } 2573 2574 /// Determines whether this type is a placeholder type other than 2575 /// Overload. Most placeholder types require only syntactic 2576 /// information about their context in order to be resolved (e.g. 2577 /// whether it is a call expression), which means they can (and 2578 /// should) be resolved in an earlier "phase" of analysis. 2579 /// Overload expressions sometimes pick up further information 2580 /// from their context, like whether the context expects a 2581 /// specific function-pointer type, and so frequently need 2582 /// special treatment. 2583 bool isNonOverloadPlaceholderType() const { 2584 return getKind() > Overload; 2585 } 2586 2587 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } 2588 }; 2589 2590 /// Complex values, per C99 6.2.5p11. This supports the C99 complex 2591 /// types (_Complex float etc) as well as the GCC integer complex extensions. 2592 class ComplexType : public Type, public llvm::FoldingSetNode { 2593 friend class ASTContext; // ASTContext creates these. 2594 2595 QualType ElementType; 2596 2597 ComplexType(QualType Element, QualType CanonicalPtr) 2598 : Type(Complex, CanonicalPtr, Element->getDependence()), 2599 ElementType(Element) {} 2600 2601 public: 2602 QualType getElementType() const { return ElementType; } 2603 2604 bool isSugared() const { return false; } 2605 QualType desugar() const { return QualType(this, 0); } 2606 2607 void Profile(llvm::FoldingSetNodeID &ID) { 2608 Profile(ID, getElementType()); 2609 } 2610 2611 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { 2612 ID.AddPointer(Element.getAsOpaquePtr()); 2613 } 2614 2615 static bool classof(const Type *T) { return T->getTypeClass() == Complex; } 2616 }; 2617 2618 /// Sugar for parentheses used when specifying types. 2619 class ParenType : public Type, public llvm::FoldingSetNode { 2620 friend class ASTContext; // ASTContext creates these. 2621 2622 QualType Inner; 2623 2624 ParenType(QualType InnerType, QualType CanonType) 2625 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} 2626 2627 public: 2628 QualType getInnerType() const { return Inner; } 2629 2630 bool isSugared() const { return true; } 2631 QualType desugar() const { return getInnerType(); } 2632 2633 void Profile(llvm::FoldingSetNodeID &ID) { 2634 Profile(ID, getInnerType()); 2635 } 2636 2637 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { 2638 Inner.Profile(ID); 2639 } 2640 2641 static bool classof(const Type *T) { return T->getTypeClass() == Paren; } 2642 }; 2643 2644 /// PointerType - C99 6.7.5.1 - Pointer Declarators. 2645 class PointerType : public Type, public llvm::FoldingSetNode { 2646 friend class ASTContext; // ASTContext creates these. 2647 2648 QualType PointeeType; 2649 2650 PointerType(QualType Pointee, QualType CanonicalPtr) 2651 : Type(Pointer, CanonicalPtr, Pointee->getDependence()), 2652 PointeeType(Pointee) {} 2653 2654 public: 2655 QualType getPointeeType() const { return PointeeType; } 2656 2657 bool isSugared() const { return false; } 2658 QualType desugar() const { return QualType(this, 0); } 2659 2660 void Profile(llvm::FoldingSetNodeID &ID) { 2661 Profile(ID, getPointeeType()); 2662 } 2663 2664 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { 2665 ID.AddPointer(Pointee.getAsOpaquePtr()); 2666 } 2667 2668 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } 2669 }; 2670 2671 /// Represents a type which was implicitly adjusted by the semantic 2672 /// engine for arbitrary reasons. For example, array and function types can 2673 /// decay, and function types can have their calling conventions adjusted. 2674 class AdjustedType : public Type, public llvm::FoldingSetNode { 2675 QualType OriginalTy; 2676 QualType AdjustedTy; 2677 2678 protected: 2679 friend class ASTContext; // ASTContext creates these. 2680 2681 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, 2682 QualType CanonicalPtr) 2683 : Type(TC, CanonicalPtr, OriginalTy->getDependence()), 2684 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} 2685 2686 public: 2687 QualType getOriginalType() const { return OriginalTy; } 2688 QualType getAdjustedType() const { return AdjustedTy; } 2689 2690 bool isSugared() const { return true; } 2691 QualType desugar() const { return AdjustedTy; } 2692 2693 void Profile(llvm::FoldingSetNodeID &ID) { 2694 Profile(ID, OriginalTy, AdjustedTy); 2695 } 2696 2697 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { 2698 ID.AddPointer(Orig.getAsOpaquePtr()); 2699 ID.AddPointer(New.getAsOpaquePtr()); 2700 } 2701 2702 static bool classof(const Type *T) { 2703 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; 2704 } 2705 }; 2706 2707 /// Represents a pointer type decayed from an array or function type. 2708 class DecayedType : public AdjustedType { 2709 friend class ASTContext; // ASTContext creates these. 2710 2711 inline 2712 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); 2713 2714 public: 2715 QualType getDecayedType() const { return getAdjustedType(); } 2716 2717 inline QualType getPointeeType() const; 2718 2719 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } 2720 }; 2721 2722 /// Pointer to a block type. 2723 /// This type is to represent types syntactically represented as 2724 /// "void (^)(int)", etc. Pointee is required to always be a function type. 2725 class BlockPointerType : public Type, public llvm::FoldingSetNode { 2726 friend class ASTContext; // ASTContext creates these. 2727 2728 // Block is some kind of pointer type 2729 QualType PointeeType; 2730 2731 BlockPointerType(QualType Pointee, QualType CanonicalCls) 2732 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), 2733 PointeeType(Pointee) {} 2734 2735 public: 2736 // Get the pointee type. Pointee is required to always be a function type. 2737 QualType getPointeeType() const { return PointeeType; } 2738 2739 bool isSugared() const { return false; } 2740 QualType desugar() const { return QualType(this, 0); } 2741 2742 void Profile(llvm::FoldingSetNodeID &ID) { 2743 Profile(ID, getPointeeType()); 2744 } 2745 2746 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { 2747 ID.AddPointer(Pointee.getAsOpaquePtr()); 2748 } 2749 2750 static bool classof(const Type *T) { 2751 return T->getTypeClass() == BlockPointer; 2752 } 2753 }; 2754 2755 /// Base for LValueReferenceType and RValueReferenceType 2756 class ReferenceType : public Type, public llvm::FoldingSetNode { 2757 QualType PointeeType; 2758 2759 protected: 2760 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, 2761 bool SpelledAsLValue) 2762 : Type(tc, CanonicalRef, Referencee->getDependence()), 2763 PointeeType(Referencee) { 2764 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; 2765 ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); 2766 } 2767 2768 public: 2769 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } 2770 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } 2771 2772 QualType getPointeeTypeAsWritten() const { return PointeeType; } 2773 2774 QualType getPointeeType() const { 2775 // FIXME: this might strip inner qualifiers; okay? 2776 const ReferenceType *T = this; 2777 while (T->isInnerRef()) 2778 T = T->PointeeType->castAs<ReferenceType>(); 2779 return T->PointeeType; 2780 } 2781 2782 void Profile(llvm::FoldingSetNodeID &ID) { 2783 Profile(ID, PointeeType, isSpelledAsLValue()); 2784 } 2785 2786 static void Profile(llvm::FoldingSetNodeID &ID, 2787 QualType Referencee, 2788 bool SpelledAsLValue) { 2789 ID.AddPointer(Referencee.getAsOpaquePtr()); 2790 ID.AddBoolean(SpelledAsLValue); 2791 } 2792 2793 static bool classof(const Type *T) { 2794 return T->getTypeClass() == LValueReference || 2795 T->getTypeClass() == RValueReference; 2796 } 2797 }; 2798 2799 /// An lvalue reference type, per C++11 [dcl.ref]. 2800 class LValueReferenceType : public ReferenceType { 2801 friend class ASTContext; // ASTContext creates these 2802 2803 LValueReferenceType(QualType Referencee, QualType CanonicalRef, 2804 bool SpelledAsLValue) 2805 : ReferenceType(LValueReference, Referencee, CanonicalRef, 2806 SpelledAsLValue) {} 2807 2808 public: 2809 bool isSugared() const { return false; } 2810 QualType desugar() const { return QualType(this, 0); } 2811 2812 static bool classof(const Type *T) { 2813 return T->getTypeClass() == LValueReference; 2814 } 2815 }; 2816 2817 /// An rvalue reference type, per C++11 [dcl.ref]. 2818 class RValueReferenceType : public ReferenceType { 2819 friend class ASTContext; // ASTContext creates these 2820 2821 RValueReferenceType(QualType Referencee, QualType CanonicalRef) 2822 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} 2823 2824 public: 2825 bool isSugared() const { return false; } 2826 QualType desugar() const { return QualType(this, 0); } 2827 2828 static bool classof(const Type *T) { 2829 return T->getTypeClass() == RValueReference; 2830 } 2831 }; 2832 2833 /// A pointer to member type per C++ 8.3.3 - Pointers to members. 2834 /// 2835 /// This includes both pointers to data members and pointer to member functions. 2836 class MemberPointerType : public Type, public llvm::FoldingSetNode { 2837 friend class ASTContext; // ASTContext creates these. 2838 2839 QualType PointeeType; 2840 2841 /// The class of which the pointee is a member. Must ultimately be a 2842 /// RecordType, but could be a typedef or a template parameter too. 2843 const Type *Class; 2844 2845 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) 2846 : Type(MemberPointer, CanonicalPtr, 2847 (Cls->getDependence() & ~TypeDependence::VariablyModified) | 2848 Pointee->getDependence()), 2849 PointeeType(Pointee), Class(Cls) {} 2850 2851 public: 2852 QualType getPointeeType() const { return PointeeType; } 2853 2854 /// Returns true if the member type (i.e. the pointee type) is a 2855 /// function type rather than a data-member type. 2856 bool isMemberFunctionPointer() const { 2857 return PointeeType->isFunctionProtoType(); 2858 } 2859 2860 /// Returns true if the member type (i.e. the pointee type) is a 2861 /// data type rather than a function type. 2862 bool isMemberDataPointer() const { 2863 return !PointeeType->isFunctionProtoType(); 2864 } 2865 2866 const Type *getClass() const { return Class; } 2867 CXXRecordDecl *getMostRecentCXXRecordDecl() const; 2868 2869 bool isSugared() const { return false; } 2870 QualType desugar() const { return QualType(this, 0); } 2871 2872 void Profile(llvm::FoldingSetNodeID &ID) { 2873 Profile(ID, getPointeeType(), getClass()); 2874 } 2875 2876 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, 2877 const Type *Class) { 2878 ID.AddPointer(Pointee.getAsOpaquePtr()); 2879 ID.AddPointer(Class); 2880 } 2881 2882 static bool classof(const Type *T) { 2883 return T->getTypeClass() == MemberPointer; 2884 } 2885 }; 2886 2887 /// Represents an array type, per C99 6.7.5.2 - Array Declarators. 2888 class ArrayType : public Type, public llvm::FoldingSetNode { 2889 public: 2890 /// Capture whether this is a normal array (e.g. int X[4]) 2891 /// an array with a static size (e.g. int X[static 4]), or an array 2892 /// with a star size (e.g. int X[*]). 2893 /// 'static' is only allowed on function parameters. 2894 enum ArraySizeModifier { 2895 Normal, Static, Star 2896 }; 2897 2898 private: 2899 /// The element type of the array. 2900 QualType ElementType; 2901 2902 protected: 2903 friend class ASTContext; // ASTContext creates these. 2904 2905 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, 2906 unsigned tq, const Expr *sz = nullptr); 2907 2908 public: 2909 QualType getElementType() const { return ElementType; } 2910 2911 ArraySizeModifier getSizeModifier() const { 2912 return ArraySizeModifier(ArrayTypeBits.SizeModifier); 2913 } 2914 2915 Qualifiers getIndexTypeQualifiers() const { 2916 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); 2917 } 2918 2919 unsigned getIndexTypeCVRQualifiers() const { 2920 return ArrayTypeBits.IndexTypeQuals; 2921 } 2922 2923 static bool classof(const Type *T) { 2924 return T->getTypeClass() == ConstantArray || 2925 T->getTypeClass() == VariableArray || 2926 T->getTypeClass() == IncompleteArray || 2927 T->getTypeClass() == DependentSizedArray; 2928 } 2929 }; 2930 2931 /// Represents the canonical version of C arrays with a specified constant size. 2932 /// For example, the canonical type for 'int A[4 + 4*100]' is a 2933 /// ConstantArrayType where the element type is 'int' and the size is 404. 2934 class ConstantArrayType final 2935 : public ArrayType, 2936 private llvm::TrailingObjects<ConstantArrayType, const Expr *> { 2937 friend class ASTContext; // ASTContext creates these. 2938 friend TrailingObjects; 2939 2940 llvm::APInt Size; // Allows us to unique the type. 2941 2942 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, 2943 const Expr *sz, ArraySizeModifier sm, unsigned tq) 2944 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { 2945 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; 2946 if (ConstantArrayTypeBits.HasStoredSizeExpr) { 2947 assert(!can.isNull() && "canonical constant array should not have size"); 2948 *getTrailingObjects<const Expr*>() = sz; 2949 } 2950 } 2951 2952 unsigned numTrailingObjects(OverloadToken<const Expr*>) const { 2953 return ConstantArrayTypeBits.HasStoredSizeExpr; 2954 } 2955 2956 public: 2957 const llvm::APInt &getSize() const { return Size; } 2958 const Expr *getSizeExpr() const { 2959 return ConstantArrayTypeBits.HasStoredSizeExpr 2960 ? *getTrailingObjects<const Expr *>() 2961 : nullptr; 2962 } 2963 bool isSugared() const { return false; } 2964 QualType desugar() const { return QualType(this, 0); } 2965 2966 /// Determine the number of bits required to address a member of 2967 // an array with the given element type and number of elements. 2968 static unsigned getNumAddressingBits(const ASTContext &Context, 2969 QualType ElementType, 2970 const llvm::APInt &NumElements); 2971 2972 /// Determine the maximum number of active bits that an array's size 2973 /// can require, which limits the maximum size of the array. 2974 static unsigned getMaxSizeBits(const ASTContext &Context); 2975 2976 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { 2977 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), 2978 getSizeModifier(), getIndexTypeCVRQualifiers()); 2979 } 2980 2981 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, 2982 QualType ET, const llvm::APInt &ArraySize, 2983 const Expr *SizeExpr, ArraySizeModifier SizeMod, 2984 unsigned TypeQuals); 2985 2986 static bool classof(const Type *T) { 2987 return T->getTypeClass() == ConstantArray; 2988 } 2989 }; 2990 2991 /// Represents a C array with an unspecified size. For example 'int A[]' has 2992 /// an IncompleteArrayType where the element type is 'int' and the size is 2993 /// unspecified. 2994 class IncompleteArrayType : public ArrayType { 2995 friend class ASTContext; // ASTContext creates these. 2996 2997 IncompleteArrayType(QualType et, QualType can, 2998 ArraySizeModifier sm, unsigned tq) 2999 : ArrayType(IncompleteArray, et, can, sm, tq) {} 3000 3001 public: 3002 friend class StmtIteratorBase; 3003 3004 bool isSugared() const { return false; } 3005 QualType desugar() const { return QualType(this, 0); } 3006 3007 static bool classof(const Type *T) { 3008 return T->getTypeClass() == IncompleteArray; 3009 } 3010 3011 void Profile(llvm::FoldingSetNodeID &ID) { 3012 Profile(ID, getElementType(), getSizeModifier(), 3013 getIndexTypeCVRQualifiers()); 3014 } 3015 3016 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, 3017 ArraySizeModifier SizeMod, unsigned TypeQuals) { 3018 ID.AddPointer(ET.getAsOpaquePtr()); 3019 ID.AddInteger(SizeMod); 3020 ID.AddInteger(TypeQuals); 3021 } 3022 }; 3023 3024 /// Represents a C array with a specified size that is not an 3025 /// integer-constant-expression. For example, 'int s[x+foo()]'. 3026 /// Since the size expression is an arbitrary expression, we store it as such. 3027 /// 3028 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and 3029 /// should not be: two lexically equivalent variable array types could mean 3030 /// different things, for example, these variables do not have the same type 3031 /// dynamically: 3032 /// 3033 /// void foo(int x) { 3034 /// int Y[x]; 3035 /// ++x; 3036 /// int Z[x]; 3037 /// } 3038 class VariableArrayType : public ArrayType { 3039 friend class ASTContext; // ASTContext creates these. 3040 3041 /// An assignment-expression. VLA's are only permitted within 3042 /// a function block. 3043 Stmt *SizeExpr; 3044 3045 /// The range spanned by the left and right array brackets. 3046 SourceRange Brackets; 3047 3048 VariableArrayType(QualType et, QualType can, Expr *e, 3049 ArraySizeModifier sm, unsigned tq, 3050 SourceRange brackets) 3051 : ArrayType(VariableArray, et, can, sm, tq, e), 3052 SizeExpr((Stmt*) e), Brackets(brackets) {} 3053 3054 public: 3055 friend class StmtIteratorBase; 3056 3057 Expr *getSizeExpr() const { 3058 // We use C-style casts instead of cast<> here because we do not wish 3059 // to have a dependency of Type.h on Stmt.h/Expr.h. 3060 return (Expr*) SizeExpr; 3061 } 3062 3063 SourceRange getBracketsRange() const { return Brackets; } 3064 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } 3065 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } 3066 3067 bool isSugared() const { return false; } 3068 QualType desugar() const { return QualType(this, 0); } 3069 3070 static bool classof(const Type *T) { 3071 return T->getTypeClass() == VariableArray; 3072 } 3073 3074 void Profile(llvm::FoldingSetNodeID &ID) { 3075 llvm_unreachable("Cannot unique VariableArrayTypes."); 3076 } 3077 }; 3078 3079 /// Represents an array type in C++ whose size is a value-dependent expression. 3080 /// 3081 /// For example: 3082 /// \code 3083 /// template<typename T, int Size> 3084 /// class array { 3085 /// T data[Size]; 3086 /// }; 3087 /// \endcode 3088 /// 3089 /// For these types, we won't actually know what the array bound is 3090 /// until template instantiation occurs, at which point this will 3091 /// become either a ConstantArrayType or a VariableArrayType. 3092 class DependentSizedArrayType : public ArrayType { 3093 friend class ASTContext; // ASTContext creates these. 3094 3095 const ASTContext &Context; 3096 3097 /// An assignment expression that will instantiate to the 3098 /// size of the array. 3099 /// 3100 /// The expression itself might be null, in which case the array 3101 /// type will have its size deduced from an initializer. 3102 Stmt *SizeExpr; 3103 3104 /// The range spanned by the left and right array brackets. 3105 SourceRange Brackets; 3106 3107 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, 3108 Expr *e, ArraySizeModifier sm, unsigned tq, 3109 SourceRange brackets); 3110 3111 public: 3112 friend class StmtIteratorBase; 3113 3114 Expr *getSizeExpr() const { 3115 // We use C-style casts instead of cast<> here because we do not wish 3116 // to have a dependency of Type.h on Stmt.h/Expr.h. 3117 return (Expr*) SizeExpr; 3118 } 3119 3120 SourceRange getBracketsRange() const { return Brackets; } 3121 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } 3122 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } 3123 3124 bool isSugared() const { return false; } 3125 QualType desugar() const { return QualType(this, 0); } 3126 3127 static bool classof(const Type *T) { 3128 return T->getTypeClass() == DependentSizedArray; 3129 } 3130 3131 void Profile(llvm::FoldingSetNodeID &ID) { 3132 Profile(ID, Context, getElementType(), 3133 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); 3134 } 3135 3136 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3137 QualType ET, ArraySizeModifier SizeMod, 3138 unsigned TypeQuals, Expr *E); 3139 }; 3140 3141 /// Represents an extended address space qualifier where the input address space 3142 /// value is dependent. Non-dependent address spaces are not represented with a 3143 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. 3144 /// 3145 /// For example: 3146 /// \code 3147 /// template<typename T, int AddrSpace> 3148 /// class AddressSpace { 3149 /// typedef T __attribute__((address_space(AddrSpace))) type; 3150 /// } 3151 /// \endcode 3152 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { 3153 friend class ASTContext; 3154 3155 const ASTContext &Context; 3156 Expr *AddrSpaceExpr; 3157 QualType PointeeType; 3158 SourceLocation loc; 3159 3160 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, 3161 QualType can, Expr *AddrSpaceExpr, 3162 SourceLocation loc); 3163 3164 public: 3165 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } 3166 QualType getPointeeType() const { return PointeeType; } 3167 SourceLocation getAttributeLoc() const { return loc; } 3168 3169 bool isSugared() const { return false; } 3170 QualType desugar() const { return QualType(this, 0); } 3171 3172 static bool classof(const Type *T) { 3173 return T->getTypeClass() == DependentAddressSpace; 3174 } 3175 3176 void Profile(llvm::FoldingSetNodeID &ID) { 3177 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); 3178 } 3179 3180 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3181 QualType PointeeType, Expr *AddrSpaceExpr); 3182 }; 3183 3184 /// Represents an extended vector type where either the type or size is 3185 /// dependent. 3186 /// 3187 /// For example: 3188 /// \code 3189 /// template<typename T, int Size> 3190 /// class vector { 3191 /// typedef T __attribute__((ext_vector_type(Size))) type; 3192 /// } 3193 /// \endcode 3194 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { 3195 friend class ASTContext; 3196 3197 const ASTContext &Context; 3198 Expr *SizeExpr; 3199 3200 /// The element type of the array. 3201 QualType ElementType; 3202 3203 SourceLocation loc; 3204 3205 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, 3206 QualType can, Expr *SizeExpr, SourceLocation loc); 3207 3208 public: 3209 Expr *getSizeExpr() const { return SizeExpr; } 3210 QualType getElementType() const { return ElementType; } 3211 SourceLocation getAttributeLoc() const { return loc; } 3212 3213 bool isSugared() const { return false; } 3214 QualType desugar() const { return QualType(this, 0); } 3215 3216 static bool classof(const Type *T) { 3217 return T->getTypeClass() == DependentSizedExtVector; 3218 } 3219 3220 void Profile(llvm::FoldingSetNodeID &ID) { 3221 Profile(ID, Context, getElementType(), getSizeExpr()); 3222 } 3223 3224 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3225 QualType ElementType, Expr *SizeExpr); 3226 }; 3227 3228 3229 /// Represents a GCC generic vector type. This type is created using 3230 /// __attribute__((vector_size(n)), where "n" specifies the vector size in 3231 /// bytes; or from an Altivec __vector or vector declaration. 3232 /// Since the constructor takes the number of vector elements, the 3233 /// client is responsible for converting the size into the number of elements. 3234 class VectorType : public Type, public llvm::FoldingSetNode { 3235 public: 3236 enum VectorKind { 3237 /// not a target-specific vector type 3238 GenericVector, 3239 3240 /// is AltiVec vector 3241 AltiVecVector, 3242 3243 /// is AltiVec 'vector Pixel' 3244 AltiVecPixel, 3245 3246 /// is AltiVec 'vector bool ...' 3247 AltiVecBool, 3248 3249 /// is ARM Neon vector 3250 NeonVector, 3251 3252 /// is ARM Neon polynomial vector 3253 NeonPolyVector 3254 }; 3255 3256 protected: 3257 friend class ASTContext; // ASTContext creates these. 3258 3259 /// The element type of the vector. 3260 QualType ElementType; 3261 3262 VectorType(QualType vecType, unsigned nElements, QualType canonType, 3263 VectorKind vecKind); 3264 3265 VectorType(TypeClass tc, QualType vecType, unsigned nElements, 3266 QualType canonType, VectorKind vecKind); 3267 3268 public: 3269 QualType getElementType() const { return ElementType; } 3270 unsigned getNumElements() const { return VectorTypeBits.NumElements; } 3271 3272 bool isSugared() const { return false; } 3273 QualType desugar() const { return QualType(this, 0); } 3274 3275 VectorKind getVectorKind() const { 3276 return VectorKind(VectorTypeBits.VecKind); 3277 } 3278 3279 void Profile(llvm::FoldingSetNodeID &ID) { 3280 Profile(ID, getElementType(), getNumElements(), 3281 getTypeClass(), getVectorKind()); 3282 } 3283 3284 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, 3285 unsigned NumElements, TypeClass TypeClass, 3286 VectorKind VecKind) { 3287 ID.AddPointer(ElementType.getAsOpaquePtr()); 3288 ID.AddInteger(NumElements); 3289 ID.AddInteger(TypeClass); 3290 ID.AddInteger(VecKind); 3291 } 3292 3293 static bool classof(const Type *T) { 3294 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; 3295 } 3296 }; 3297 3298 /// Represents a vector type where either the type or size is dependent. 3299 //// 3300 /// For example: 3301 /// \code 3302 /// template<typename T, int Size> 3303 /// class vector { 3304 /// typedef T __attribute__((vector_size(Size))) type; 3305 /// } 3306 /// \endcode 3307 class DependentVectorType : public Type, public llvm::FoldingSetNode { 3308 friend class ASTContext; 3309 3310 const ASTContext &Context; 3311 QualType ElementType; 3312 Expr *SizeExpr; 3313 SourceLocation Loc; 3314 3315 DependentVectorType(const ASTContext &Context, QualType ElementType, 3316 QualType CanonType, Expr *SizeExpr, 3317 SourceLocation Loc, VectorType::VectorKind vecKind); 3318 3319 public: 3320 Expr *getSizeExpr() const { return SizeExpr; } 3321 QualType getElementType() const { return ElementType; } 3322 SourceLocation getAttributeLoc() const { return Loc; } 3323 VectorType::VectorKind getVectorKind() const { 3324 return VectorType::VectorKind(VectorTypeBits.VecKind); 3325 } 3326 3327 bool isSugared() const { return false; } 3328 QualType desugar() const { return QualType(this, 0); } 3329 3330 static bool classof(const Type *T) { 3331 return T->getTypeClass() == DependentVector; 3332 } 3333 3334 void Profile(llvm::FoldingSetNodeID &ID) { 3335 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); 3336 } 3337 3338 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3339 QualType ElementType, const Expr *SizeExpr, 3340 VectorType::VectorKind VecKind); 3341 }; 3342 3343 /// ExtVectorType - Extended vector type. This type is created using 3344 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. 3345 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This 3346 /// class enables syntactic extensions, like Vector Components for accessing 3347 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL 3348 /// Shading Language). 3349 class ExtVectorType : public VectorType { 3350 friend class ASTContext; // ASTContext creates these. 3351 3352 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) 3353 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} 3354 3355 public: 3356 static int getPointAccessorIdx(char c) { 3357 switch (c) { 3358 default: return -1; 3359 case 'x': case 'r': return 0; 3360 case 'y': case 'g': return 1; 3361 case 'z': case 'b': return 2; 3362 case 'w': case 'a': return 3; 3363 } 3364 } 3365 3366 static int getNumericAccessorIdx(char c) { 3367 switch (c) { 3368 default: return -1; 3369 case '0': return 0; 3370 case '1': return 1; 3371 case '2': return 2; 3372 case '3': return 3; 3373 case '4': return 4; 3374 case '5': return 5; 3375 case '6': return 6; 3376 case '7': return 7; 3377 case '8': return 8; 3378 case '9': return 9; 3379 case 'A': 3380 case 'a': return 10; 3381 case 'B': 3382 case 'b': return 11; 3383 case 'C': 3384 case 'c': return 12; 3385 case 'D': 3386 case 'd': return 13; 3387 case 'E': 3388 case 'e': return 14; 3389 case 'F': 3390 case 'f': return 15; 3391 } 3392 } 3393 3394 static int getAccessorIdx(char c, bool isNumericAccessor) { 3395 if (isNumericAccessor) 3396 return getNumericAccessorIdx(c); 3397 else 3398 return getPointAccessorIdx(c); 3399 } 3400 3401 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { 3402 if (int idx = getAccessorIdx(c, isNumericAccessor)+1) 3403 return unsigned(idx-1) < getNumElements(); 3404 return false; 3405 } 3406 3407 bool isSugared() const { return false; } 3408 QualType desugar() const { return QualType(this, 0); } 3409 3410 static bool classof(const Type *T) { 3411 return T->getTypeClass() == ExtVector; 3412 } 3413 }; 3414 3415 /// Represents a matrix type, as defined in the Matrix Types clang extensions. 3416 /// __attribute__((matrix_type(rows, columns))), where "rows" specifies 3417 /// number of rows and "columns" specifies the number of columns. 3418 class MatrixType : public Type, public llvm::FoldingSetNode { 3419 protected: 3420 friend class ASTContext; 3421 3422 /// The element type of the matrix. 3423 QualType ElementType; 3424 3425 MatrixType(QualType ElementTy, QualType CanonElementTy); 3426 3427 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, 3428 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); 3429 3430 public: 3431 /// Returns type of the elements being stored in the matrix 3432 QualType getElementType() const { return ElementType; } 3433 3434 /// Valid elements types are the following: 3435 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types 3436 /// and _Bool 3437 /// * the standard floating types float or double 3438 /// * a half-precision floating point type, if one is supported on the target 3439 static bool isValidElementType(QualType T) { 3440 return T->isDependentType() || 3441 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); 3442 } 3443 3444 bool isSugared() const { return false; } 3445 QualType desugar() const { return QualType(this, 0); } 3446 3447 static bool classof(const Type *T) { 3448 return T->getTypeClass() == ConstantMatrix || 3449 T->getTypeClass() == DependentSizedMatrix; 3450 } 3451 }; 3452 3453 /// Represents a concrete matrix type with constant number of rows and columns 3454 class ConstantMatrixType final : public MatrixType { 3455 protected: 3456 friend class ASTContext; 3457 3458 /// The element type of the matrix. 3459 QualType ElementType; 3460 3461 ConstantMatrixType(QualType MatrixElementType, unsigned NRows, 3462 unsigned NColumns, QualType CanonElementType); 3463 3464 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, 3465 unsigned NColumns, QualType CanonElementType); 3466 3467 public: 3468 /// Returns the number of rows in the matrix. 3469 unsigned getNumRows() const { return ConstantMatrixTypeBits.NumRows; } 3470 3471 /// Returns the number of columns in the matrix. 3472 unsigned getNumColumns() const { return ConstantMatrixTypeBits.NumColumns; } 3473 3474 /// Returns the number of elements required to embed the matrix into a vector. 3475 unsigned getNumElementsFlattened() const { 3476 return ConstantMatrixTypeBits.NumRows * ConstantMatrixTypeBits.NumColumns; 3477 } 3478 3479 /// Returns true if \p NumElements is a valid matrix dimension. 3480 static bool isDimensionValid(uint64_t NumElements) { 3481 return NumElements > 0 && 3482 NumElements <= ConstantMatrixTypeBitfields::MaxElementsPerDimension; 3483 } 3484 3485 /// Returns the maximum number of elements per dimension. 3486 static unsigned getMaxElementsPerDimension() { 3487 return ConstantMatrixTypeBitfields::MaxElementsPerDimension; 3488 } 3489 3490 void Profile(llvm::FoldingSetNodeID &ID) { 3491 Profile(ID, getElementType(), getNumRows(), getNumColumns(), 3492 getTypeClass()); 3493 } 3494 3495 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, 3496 unsigned NumRows, unsigned NumColumns, 3497 TypeClass TypeClass) { 3498 ID.AddPointer(ElementType.getAsOpaquePtr()); 3499 ID.AddInteger(NumRows); 3500 ID.AddInteger(NumColumns); 3501 ID.AddInteger(TypeClass); 3502 } 3503 3504 static bool classof(const Type *T) { 3505 return T->getTypeClass() == ConstantMatrix; 3506 } 3507 }; 3508 3509 /// Represents a matrix type where the type and the number of rows and columns 3510 /// is dependent on a template. 3511 class DependentSizedMatrixType final : public MatrixType { 3512 friend class ASTContext; 3513 3514 const ASTContext &Context; 3515 Expr *RowExpr; 3516 Expr *ColumnExpr; 3517 3518 SourceLocation loc; 3519 3520 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, 3521 QualType CanonicalType, Expr *RowExpr, 3522 Expr *ColumnExpr, SourceLocation loc); 3523 3524 public: 3525 QualType getElementType() const { return ElementType; } 3526 Expr *getRowExpr() const { return RowExpr; } 3527 Expr *getColumnExpr() const { return ColumnExpr; } 3528 SourceLocation getAttributeLoc() const { return loc; } 3529 3530 bool isSugared() const { return false; } 3531 QualType desugar() const { return QualType(this, 0); } 3532 3533 static bool classof(const Type *T) { 3534 return T->getTypeClass() == DependentSizedMatrix; 3535 } 3536 3537 void Profile(llvm::FoldingSetNodeID &ID) { 3538 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); 3539 } 3540 3541 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3542 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); 3543 }; 3544 3545 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base 3546 /// class of FunctionNoProtoType and FunctionProtoType. 3547 class FunctionType : public Type { 3548 // The type returned by the function. 3549 QualType ResultType; 3550 3551 public: 3552 /// Interesting information about a specific parameter that can't simply 3553 /// be reflected in parameter's type. This is only used by FunctionProtoType 3554 /// but is in FunctionType to make this class available during the 3555 /// specification of the bases of FunctionProtoType. 3556 /// 3557 /// It makes sense to model language features this way when there's some 3558 /// sort of parameter-specific override (such as an attribute) that 3559 /// affects how the function is called. For example, the ARC ns_consumed 3560 /// attribute changes whether a parameter is passed at +0 (the default) 3561 /// or +1 (ns_consumed). This must be reflected in the function type, 3562 /// but isn't really a change to the parameter type. 3563 /// 3564 /// One serious disadvantage of modelling language features this way is 3565 /// that they generally do not work with language features that attempt 3566 /// to destructure types. For example, template argument deduction will 3567 /// not be able to match a parameter declared as 3568 /// T (*)(U) 3569 /// against an argument of type 3570 /// void (*)(__attribute__((ns_consumed)) id) 3571 /// because the substitution of T=void, U=id into the former will 3572 /// not produce the latter. 3573 class ExtParameterInfo { 3574 enum { 3575 ABIMask = 0x0F, 3576 IsConsumed = 0x10, 3577 HasPassObjSize = 0x20, 3578 IsNoEscape = 0x40, 3579 }; 3580 unsigned char Data = 0; 3581 3582 public: 3583 ExtParameterInfo() = default; 3584 3585 /// Return the ABI treatment of this parameter. 3586 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } 3587 ExtParameterInfo withABI(ParameterABI kind) const { 3588 ExtParameterInfo copy = *this; 3589 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); 3590 return copy; 3591 } 3592 3593 /// Is this parameter considered "consumed" by Objective-C ARC? 3594 /// Consumed parameters must have retainable object type. 3595 bool isConsumed() const { return (Data & IsConsumed); } 3596 ExtParameterInfo withIsConsumed(bool consumed) const { 3597 ExtParameterInfo copy = *this; 3598 if (consumed) 3599 copy.Data |= IsConsumed; 3600 else 3601 copy.Data &= ~IsConsumed; 3602 return copy; 3603 } 3604 3605 bool hasPassObjectSize() const { return Data & HasPassObjSize; } 3606 ExtParameterInfo withHasPassObjectSize() const { 3607 ExtParameterInfo Copy = *this; 3608 Copy.Data |= HasPassObjSize; 3609 return Copy; 3610 } 3611 3612 bool isNoEscape() const { return Data & IsNoEscape; } 3613 ExtParameterInfo withIsNoEscape(bool NoEscape) const { 3614 ExtParameterInfo Copy = *this; 3615 if (NoEscape) 3616 Copy.Data |= IsNoEscape; 3617 else 3618 Copy.Data &= ~IsNoEscape; 3619 return Copy; 3620 } 3621 3622 unsigned char getOpaqueValue() const { return Data; } 3623 static ExtParameterInfo getFromOpaqueValue(unsigned char data) { 3624 ExtParameterInfo result; 3625 result.Data = data; 3626 return result; 3627 } 3628 3629 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { 3630 return lhs.Data == rhs.Data; 3631 } 3632 3633 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { 3634 return lhs.Data != rhs.Data; 3635 } 3636 }; 3637 3638 /// A class which abstracts out some details necessary for 3639 /// making a call. 3640 /// 3641 /// It is not actually used directly for storing this information in 3642 /// a FunctionType, although FunctionType does currently use the 3643 /// same bit-pattern. 3644 /// 3645 // If you add a field (say Foo), other than the obvious places (both, 3646 // constructors, compile failures), what you need to update is 3647 // * Operator== 3648 // * getFoo 3649 // * withFoo 3650 // * functionType. Add Foo, getFoo. 3651 // * ASTContext::getFooType 3652 // * ASTContext::mergeFunctionTypes 3653 // * FunctionNoProtoType::Profile 3654 // * FunctionProtoType::Profile 3655 // * TypePrinter::PrintFunctionProto 3656 // * AST read and write 3657 // * Codegen 3658 class ExtInfo { 3659 friend class FunctionType; 3660 3661 // Feel free to rearrange or add bits, but if you go over 16, you'll need to 3662 // adjust the Bits field below, and if you add bits, you'll need to adjust 3663 // Type::FunctionTypeBitfields::ExtInfo as well. 3664 3665 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| 3666 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | 3667 // 3668 // regparm is either 0 (no regparm attribute) or the regparm value+1. 3669 enum { CallConvMask = 0x1F }; 3670 enum { NoReturnMask = 0x20 }; 3671 enum { ProducesResultMask = 0x40 }; 3672 enum { NoCallerSavedRegsMask = 0x80 }; 3673 enum { 3674 RegParmMask = 0x700, 3675 RegParmOffset = 8 3676 }; 3677 enum { NoCfCheckMask = 0x800 }; 3678 enum { CmseNSCallMask = 0x1000 }; 3679 uint16_t Bits = CC_C; 3680 3681 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} 3682 3683 public: 3684 // Constructor with no defaults. Use this when you know that you 3685 // have all the elements (when reading an AST file for example). 3686 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, 3687 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, 3688 bool cmseNSCall) { 3689 assert((!hasRegParm || regParm < 7) && "Invalid regparm value"); 3690 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | 3691 (producesResult ? ProducesResultMask : 0) | 3692 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | 3693 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | 3694 (NoCfCheck ? NoCfCheckMask : 0) | 3695 (cmseNSCall ? CmseNSCallMask : 0); 3696 } 3697 3698 // Constructor with all defaults. Use when for example creating a 3699 // function known to use defaults. 3700 ExtInfo() = default; 3701 3702 // Constructor with just the calling convention, which is an important part 3703 // of the canonical type. 3704 ExtInfo(CallingConv CC) : Bits(CC) {} 3705 3706 bool getNoReturn() const { return Bits & NoReturnMask; } 3707 bool getProducesResult() const { return Bits & ProducesResultMask; } 3708 bool getCmseNSCall() const { return Bits & CmseNSCallMask; } 3709 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } 3710 bool getNoCfCheck() const { return Bits & NoCfCheckMask; } 3711 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } 3712 3713 unsigned getRegParm() const { 3714 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; 3715 if (RegParm > 0) 3716 --RegParm; 3717 return RegParm; 3718 } 3719 3720 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } 3721 3722 bool operator==(ExtInfo Other) const { 3723 return Bits == Other.Bits; 3724 } 3725 bool operator!=(ExtInfo Other) const { 3726 return Bits != Other.Bits; 3727 } 3728 3729 // Note that we don't have setters. That is by design, use 3730 // the following with methods instead of mutating these objects. 3731 3732 ExtInfo withNoReturn(bool noReturn) const { 3733 if (noReturn) 3734 return ExtInfo(Bits | NoReturnMask); 3735 else 3736 return ExtInfo(Bits & ~NoReturnMask); 3737 } 3738 3739 ExtInfo withProducesResult(bool producesResult) const { 3740 if (producesResult) 3741 return ExtInfo(Bits | ProducesResultMask); 3742 else 3743 return ExtInfo(Bits & ~ProducesResultMask); 3744 } 3745 3746 ExtInfo withCmseNSCall(bool cmseNSCall) const { 3747 if (cmseNSCall) 3748 return ExtInfo(Bits | CmseNSCallMask); 3749 else 3750 return ExtInfo(Bits & ~CmseNSCallMask); 3751 } 3752 3753 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { 3754 if (noCallerSavedRegs) 3755 return ExtInfo(Bits | NoCallerSavedRegsMask); 3756 else 3757 return ExtInfo(Bits & ~NoCallerSavedRegsMask); 3758 } 3759 3760 ExtInfo withNoCfCheck(bool noCfCheck) const { 3761 if (noCfCheck) 3762 return ExtInfo(Bits | NoCfCheckMask); 3763 else 3764 return ExtInfo(Bits & ~NoCfCheckMask); 3765 } 3766 3767 ExtInfo withRegParm(unsigned RegParm) const { 3768 assert(RegParm < 7 && "Invalid regparm value"); 3769 return ExtInfo((Bits & ~RegParmMask) | 3770 ((RegParm + 1) << RegParmOffset)); 3771 } 3772 3773 ExtInfo withCallingConv(CallingConv cc) const { 3774 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); 3775 } 3776 3777 void Profile(llvm::FoldingSetNodeID &ID) const { 3778 ID.AddInteger(Bits); 3779 } 3780 }; 3781 3782 /// A simple holder for a QualType representing a type in an 3783 /// exception specification. Unfortunately needed by FunctionProtoType 3784 /// because TrailingObjects cannot handle repeated types. 3785 struct ExceptionType { QualType Type; }; 3786 3787 /// A simple holder for various uncommon bits which do not fit in 3788 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the 3789 /// alignment of subsequent objects in TrailingObjects. You must update 3790 /// hasExtraBitfields in FunctionProtoType after adding extra data here. 3791 struct alignas(void *) FunctionTypeExtraBitfields { 3792 /// The number of types in the exception specification. 3793 /// A whole unsigned is not needed here and according to 3794 /// [implimits] 8 bits would be enough here. 3795 unsigned NumExceptionType; 3796 }; 3797 3798 protected: 3799 FunctionType(TypeClass tc, QualType res, QualType Canonical, 3800 TypeDependence Dependence, ExtInfo Info) 3801 : Type(tc, Canonical, Dependence), ResultType(res) { 3802 FunctionTypeBits.ExtInfo = Info.Bits; 3803 } 3804 3805 Qualifiers getFastTypeQuals() const { 3806 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); 3807 } 3808 3809 public: 3810 QualType getReturnType() const { return ResultType; } 3811 3812 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } 3813 unsigned getRegParmType() const { return getExtInfo().getRegParm(); } 3814 3815 /// Determine whether this function type includes the GNU noreturn 3816 /// attribute. The C++11 [[noreturn]] attribute does not affect the function 3817 /// type. 3818 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } 3819 3820 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } 3821 CallingConv getCallConv() const { return getExtInfo().getCC(); } 3822 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } 3823 3824 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, 3825 "Const, volatile and restrict are assumed to be a subset of " 3826 "the fast qualifiers."); 3827 3828 bool isConst() const { return getFastTypeQuals().hasConst(); } 3829 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } 3830 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } 3831 3832 /// Determine the type of an expression that calls a function of 3833 /// this type. 3834 QualType getCallResultType(const ASTContext &Context) const { 3835 return getReturnType().getNonLValueExprType(Context); 3836 } 3837 3838 static StringRef getNameForCallConv(CallingConv CC); 3839 3840 static bool classof(const Type *T) { 3841 return T->getTypeClass() == FunctionNoProto || 3842 T->getTypeClass() == FunctionProto; 3843 } 3844 }; 3845 3846 /// Represents a K&R-style 'int foo()' function, which has 3847 /// no information available about its arguments. 3848 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { 3849 friend class ASTContext; // ASTContext creates these. 3850 3851 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) 3852 : FunctionType(FunctionNoProto, Result, Canonical, 3853 Result->getDependence() & 3854 ~(TypeDependence::DependentInstantiation | 3855 TypeDependence::UnexpandedPack), 3856 Info) {} 3857 3858 public: 3859 // No additional state past what FunctionType provides. 3860 3861 bool isSugared() const { return false; } 3862 QualType desugar() const { return QualType(this, 0); } 3863 3864 void Profile(llvm::FoldingSetNodeID &ID) { 3865 Profile(ID, getReturnType(), getExtInfo()); 3866 } 3867 3868 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, 3869 ExtInfo Info) { 3870 Info.Profile(ID); 3871 ID.AddPointer(ResultType.getAsOpaquePtr()); 3872 } 3873 3874 static bool classof(const Type *T) { 3875 return T->getTypeClass() == FunctionNoProto; 3876 } 3877 }; 3878 3879 /// Represents a prototype with parameter type info, e.g. 3880 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no 3881 /// parameters, not as having a single void parameter. Such a type can have 3882 /// an exception specification, but this specification is not part of the 3883 /// canonical type. FunctionProtoType has several trailing objects, some of 3884 /// which optional. For more information about the trailing objects see 3885 /// the first comment inside FunctionProtoType. 3886 class FunctionProtoType final 3887 : public FunctionType, 3888 public llvm::FoldingSetNode, 3889 private llvm::TrailingObjects< 3890 FunctionProtoType, QualType, SourceLocation, 3891 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, 3892 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { 3893 friend class ASTContext; // ASTContext creates these. 3894 friend TrailingObjects; 3895 3896 // FunctionProtoType is followed by several trailing objects, some of 3897 // which optional. They are in order: 3898 // 3899 // * An array of getNumParams() QualType holding the parameter types. 3900 // Always present. Note that for the vast majority of FunctionProtoType, 3901 // these will be the only trailing objects. 3902 // 3903 // * Optionally if the function is variadic, the SourceLocation of the 3904 // ellipsis. 3905 // 3906 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields 3907 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): 3908 // a single FunctionTypeExtraBitfields. Present if and only if 3909 // hasExtraBitfields() is true. 3910 // 3911 // * Optionally exactly one of: 3912 // * an array of getNumExceptions() ExceptionType, 3913 // * a single Expr *, 3914 // * a pair of FunctionDecl *, 3915 // * a single FunctionDecl * 3916 // used to store information about the various types of exception 3917 // specification. See getExceptionSpecSize for the details. 3918 // 3919 // * Optionally an array of getNumParams() ExtParameterInfo holding 3920 // an ExtParameterInfo for each of the parameters. Present if and 3921 // only if hasExtParameterInfos() is true. 3922 // 3923 // * Optionally a Qualifiers object to represent extra qualifiers that can't 3924 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only 3925 // if hasExtQualifiers() is true. 3926 // 3927 // The optional FunctionTypeExtraBitfields has to be before the data 3928 // related to the exception specification since it contains the number 3929 // of exception types. 3930 // 3931 // We put the ExtParameterInfos last. If all were equal, it would make 3932 // more sense to put these before the exception specification, because 3933 // it's much easier to skip past them compared to the elaborate switch 3934 // required to skip the exception specification. However, all is not 3935 // equal; ExtParameterInfos are used to model very uncommon features, 3936 // and it's better not to burden the more common paths. 3937 3938 public: 3939 /// Holds information about the various types of exception specification. 3940 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is 3941 /// used to group together the various bits of information about the 3942 /// exception specification. 3943 struct ExceptionSpecInfo { 3944 /// The kind of exception specification this is. 3945 ExceptionSpecificationType Type = EST_None; 3946 3947 /// Explicitly-specified list of exception types. 3948 ArrayRef<QualType> Exceptions; 3949 3950 /// Noexcept expression, if this is a computed noexcept specification. 3951 Expr *NoexceptExpr = nullptr; 3952 3953 /// The function whose exception specification this is, for 3954 /// EST_Unevaluated and EST_Uninstantiated. 3955 FunctionDecl *SourceDecl = nullptr; 3956 3957 /// The function template whose exception specification this is instantiated 3958 /// from, for EST_Uninstantiated. 3959 FunctionDecl *SourceTemplate = nullptr; 3960 3961 ExceptionSpecInfo() = default; 3962 3963 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} 3964 }; 3965 3966 /// Extra information about a function prototype. ExtProtoInfo is not 3967 /// stored as such in FunctionProtoType but is used to group together 3968 /// the various bits of extra information about a function prototype. 3969 struct ExtProtoInfo { 3970 FunctionType::ExtInfo ExtInfo; 3971 bool Variadic : 1; 3972 bool HasTrailingReturn : 1; 3973 Qualifiers TypeQuals; 3974 RefQualifierKind RefQualifier = RQ_None; 3975 ExceptionSpecInfo ExceptionSpec; 3976 const ExtParameterInfo *ExtParameterInfos = nullptr; 3977 SourceLocation EllipsisLoc; 3978 3979 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} 3980 3981 ExtProtoInfo(CallingConv CC) 3982 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} 3983 3984 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { 3985 ExtProtoInfo Result(*this); 3986 Result.ExceptionSpec = ESI; 3987 return Result; 3988 } 3989 }; 3990 3991 private: 3992 unsigned numTrailingObjects(OverloadToken<QualType>) const { 3993 return getNumParams(); 3994 } 3995 3996 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { 3997 return isVariadic(); 3998 } 3999 4000 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { 4001 return hasExtraBitfields(); 4002 } 4003 4004 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { 4005 return getExceptionSpecSize().NumExceptionType; 4006 } 4007 4008 unsigned numTrailingObjects(OverloadToken<Expr *>) const { 4009 return getExceptionSpecSize().NumExprPtr; 4010 } 4011 4012 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { 4013 return getExceptionSpecSize().NumFunctionDeclPtr; 4014 } 4015 4016 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { 4017 return hasExtParameterInfos() ? getNumParams() : 0; 4018 } 4019 4020 /// Determine whether there are any argument types that 4021 /// contain an unexpanded parameter pack. 4022 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, 4023 unsigned numArgs) { 4024 for (unsigned Idx = 0; Idx < numArgs; ++Idx) 4025 if (ArgArray[Idx]->containsUnexpandedParameterPack()) 4026 return true; 4027 4028 return false; 4029 } 4030 4031 FunctionProtoType(QualType result, ArrayRef<QualType> params, 4032 QualType canonical, const ExtProtoInfo &epi); 4033 4034 /// This struct is returned by getExceptionSpecSize and is used to 4035 /// translate an ExceptionSpecificationType to the number and kind 4036 /// of trailing objects related to the exception specification. 4037 struct ExceptionSpecSizeHolder { 4038 unsigned NumExceptionType; 4039 unsigned NumExprPtr; 4040 unsigned NumFunctionDeclPtr; 4041 }; 4042 4043 /// Return the number and kind of trailing objects 4044 /// related to the exception specification. 4045 static ExceptionSpecSizeHolder 4046 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { 4047 switch (EST) { 4048 case EST_None: 4049 case EST_DynamicNone: 4050 case EST_MSAny: 4051 case EST_BasicNoexcept: 4052 case EST_Unparsed: 4053 case EST_NoThrow: 4054 return {0, 0, 0}; 4055 4056 case EST_Dynamic: 4057 return {NumExceptions, 0, 0}; 4058 4059 case EST_DependentNoexcept: 4060 case EST_NoexceptFalse: 4061 case EST_NoexceptTrue: 4062 return {0, 1, 0}; 4063 4064 case EST_Uninstantiated: 4065 return {0, 0, 2}; 4066 4067 case EST_Unevaluated: 4068 return {0, 0, 1}; 4069 } 4070 llvm_unreachable("bad exception specification kind"); 4071 } 4072 4073 /// Return the number and kind of trailing objects 4074 /// related to the exception specification. 4075 ExceptionSpecSizeHolder getExceptionSpecSize() const { 4076 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); 4077 } 4078 4079 /// Whether the trailing FunctionTypeExtraBitfields is present. 4080 static bool hasExtraBitfields(ExceptionSpecificationType EST) { 4081 // If the exception spec type is EST_Dynamic then we have > 0 exception 4082 // types and the exact number is stored in FunctionTypeExtraBitfields. 4083 return EST == EST_Dynamic; 4084 } 4085 4086 /// Whether the trailing FunctionTypeExtraBitfields is present. 4087 bool hasExtraBitfields() const { 4088 return hasExtraBitfields(getExceptionSpecType()); 4089 } 4090 4091 bool hasExtQualifiers() const { 4092 return FunctionTypeBits.HasExtQuals; 4093 } 4094 4095 public: 4096 unsigned getNumParams() const { return FunctionTypeBits.NumParams; } 4097 4098 QualType getParamType(unsigned i) const { 4099 assert(i < getNumParams() && "invalid parameter index"); 4100 return param_type_begin()[i]; 4101 } 4102 4103 ArrayRef<QualType> getParamTypes() const { 4104 return llvm::makeArrayRef(param_type_begin(), param_type_end()); 4105 } 4106 4107 ExtProtoInfo getExtProtoInfo() const { 4108 ExtProtoInfo EPI; 4109 EPI.ExtInfo = getExtInfo(); 4110 EPI.Variadic = isVariadic(); 4111 EPI.EllipsisLoc = getEllipsisLoc(); 4112 EPI.HasTrailingReturn = hasTrailingReturn(); 4113 EPI.ExceptionSpec = getExceptionSpecInfo(); 4114 EPI.TypeQuals = getMethodQuals(); 4115 EPI.RefQualifier = getRefQualifier(); 4116 EPI.ExtParameterInfos = getExtParameterInfosOrNull(); 4117 return EPI; 4118 } 4119 4120 /// Get the kind of exception specification on this function. 4121 ExceptionSpecificationType getExceptionSpecType() const { 4122 return static_cast<ExceptionSpecificationType>( 4123 FunctionTypeBits.ExceptionSpecType); 4124 } 4125 4126 /// Return whether this function has any kind of exception spec. 4127 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } 4128 4129 /// Return whether this function has a dynamic (throw) exception spec. 4130 bool hasDynamicExceptionSpec() const { 4131 return isDynamicExceptionSpec(getExceptionSpecType()); 4132 } 4133 4134 /// Return whether this function has a noexcept exception spec. 4135 bool hasNoexceptExceptionSpec() const { 4136 return isNoexceptExceptionSpec(getExceptionSpecType()); 4137 } 4138 4139 /// Return whether this function has a dependent exception spec. 4140 bool hasDependentExceptionSpec() const; 4141 4142 /// Return whether this function has an instantiation-dependent exception 4143 /// spec. 4144 bool hasInstantiationDependentExceptionSpec() const; 4145 4146 /// Return all the available information about this type's exception spec. 4147 ExceptionSpecInfo getExceptionSpecInfo() const { 4148 ExceptionSpecInfo Result; 4149 Result.Type = getExceptionSpecType(); 4150 if (Result.Type == EST_Dynamic) { 4151 Result.Exceptions = exceptions(); 4152 } else if (isComputedNoexcept(Result.Type)) { 4153 Result.NoexceptExpr = getNoexceptExpr(); 4154 } else if (Result.Type == EST_Uninstantiated) { 4155 Result.SourceDecl = getExceptionSpecDecl(); 4156 Result.SourceTemplate = getExceptionSpecTemplate(); 4157 } else if (Result.Type == EST_Unevaluated) { 4158 Result.SourceDecl = getExceptionSpecDecl(); 4159 } 4160 return Result; 4161 } 4162 4163 /// Return the number of types in the exception specification. 4164 unsigned getNumExceptions() const { 4165 return getExceptionSpecType() == EST_Dynamic 4166 ? getTrailingObjects<FunctionTypeExtraBitfields>() 4167 ->NumExceptionType 4168 : 0; 4169 } 4170 4171 /// Return the ith exception type, where 0 <= i < getNumExceptions(). 4172 QualType getExceptionType(unsigned i) const { 4173 assert(i < getNumExceptions() && "Invalid exception number!"); 4174 return exception_begin()[i]; 4175 } 4176 4177 /// Return the expression inside noexcept(expression), or a null pointer 4178 /// if there is none (because the exception spec is not of this form). 4179 Expr *getNoexceptExpr() const { 4180 if (!isComputedNoexcept(getExceptionSpecType())) 4181 return nullptr; 4182 return *getTrailingObjects<Expr *>(); 4183 } 4184 4185 /// If this function type has an exception specification which hasn't 4186 /// been determined yet (either because it has not been evaluated or because 4187 /// it has not been instantiated), this is the function whose exception 4188 /// specification is represented by this type. 4189 FunctionDecl *getExceptionSpecDecl() const { 4190 if (getExceptionSpecType() != EST_Uninstantiated && 4191 getExceptionSpecType() != EST_Unevaluated) 4192 return nullptr; 4193 return getTrailingObjects<FunctionDecl *>()[0]; 4194 } 4195 4196 /// If this function type has an uninstantiated exception 4197 /// specification, this is the function whose exception specification 4198 /// should be instantiated to find the exception specification for 4199 /// this type. 4200 FunctionDecl *getExceptionSpecTemplate() const { 4201 if (getExceptionSpecType() != EST_Uninstantiated) 4202 return nullptr; 4203 return getTrailingObjects<FunctionDecl *>()[1]; 4204 } 4205 4206 /// Determine whether this function type has a non-throwing exception 4207 /// specification. 4208 CanThrowResult canThrow() const; 4209 4210 /// Determine whether this function type has a non-throwing exception 4211 /// specification. If this depends on template arguments, returns 4212 /// \c ResultIfDependent. 4213 bool isNothrow(bool ResultIfDependent = false) const { 4214 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; 4215 } 4216 4217 /// Whether this function prototype is variadic. 4218 bool isVariadic() const { return FunctionTypeBits.Variadic; } 4219 4220 SourceLocation getEllipsisLoc() const { 4221 return isVariadic() ? *getTrailingObjects<SourceLocation>() 4222 : SourceLocation(); 4223 } 4224 4225 /// Determines whether this function prototype contains a 4226 /// parameter pack at the end. 4227 /// 4228 /// A function template whose last parameter is a parameter pack can be 4229 /// called with an arbitrary number of arguments, much like a variadic 4230 /// function. 4231 bool isTemplateVariadic() const; 4232 4233 /// Whether this function prototype has a trailing return type. 4234 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } 4235 4236 Qualifiers getMethodQuals() const { 4237 if (hasExtQualifiers()) 4238 return *getTrailingObjects<Qualifiers>(); 4239 else 4240 return getFastTypeQuals(); 4241 } 4242 4243 /// Retrieve the ref-qualifier associated with this function type. 4244 RefQualifierKind getRefQualifier() const { 4245 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); 4246 } 4247 4248 using param_type_iterator = const QualType *; 4249 using param_type_range = llvm::iterator_range<param_type_iterator>; 4250 4251 param_type_range param_types() const { 4252 return param_type_range(param_type_begin(), param_type_end()); 4253 } 4254 4255 param_type_iterator param_type_begin() const { 4256 return getTrailingObjects<QualType>(); 4257 } 4258 4259 param_type_iterator param_type_end() const { 4260 return param_type_begin() + getNumParams(); 4261 } 4262 4263 using exception_iterator = const QualType *; 4264 4265 ArrayRef<QualType> exceptions() const { 4266 return llvm::makeArrayRef(exception_begin(), exception_end()); 4267 } 4268 4269 exception_iterator exception_begin() const { 4270 return reinterpret_cast<exception_iterator>( 4271 getTrailingObjects<ExceptionType>()); 4272 } 4273 4274 exception_iterator exception_end() const { 4275 return exception_begin() + getNumExceptions(); 4276 } 4277 4278 /// Is there any interesting extra information for any of the parameters 4279 /// of this function type? 4280 bool hasExtParameterInfos() const { 4281 return FunctionTypeBits.HasExtParameterInfos; 4282 } 4283 4284 ArrayRef<ExtParameterInfo> getExtParameterInfos() const { 4285 assert(hasExtParameterInfos()); 4286 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), 4287 getNumParams()); 4288 } 4289 4290 /// Return a pointer to the beginning of the array of extra parameter 4291 /// information, if present, or else null if none of the parameters 4292 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. 4293 const ExtParameterInfo *getExtParameterInfosOrNull() const { 4294 if (!hasExtParameterInfos()) 4295 return nullptr; 4296 return getTrailingObjects<ExtParameterInfo>(); 4297 } 4298 4299 ExtParameterInfo getExtParameterInfo(unsigned I) const { 4300 assert(I < getNumParams() && "parameter index out of range"); 4301 if (hasExtParameterInfos()) 4302 return getTrailingObjects<ExtParameterInfo>()[I]; 4303 return ExtParameterInfo(); 4304 } 4305 4306 ParameterABI getParameterABI(unsigned I) const { 4307 assert(I < getNumParams() && "parameter index out of range"); 4308 if (hasExtParameterInfos()) 4309 return getTrailingObjects<ExtParameterInfo>()[I].getABI(); 4310 return ParameterABI::Ordinary; 4311 } 4312 4313 bool isParamConsumed(unsigned I) const { 4314 assert(I < getNumParams() && "parameter index out of range"); 4315 if (hasExtParameterInfos()) 4316 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); 4317 return false; 4318 } 4319 4320 bool isSugared() const { return false; } 4321 QualType desugar() const { return QualType(this, 0); } 4322 4323 void printExceptionSpecification(raw_ostream &OS, 4324 const PrintingPolicy &Policy) const; 4325 4326 static bool classof(const Type *T) { 4327 return T->getTypeClass() == FunctionProto; 4328 } 4329 4330 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); 4331 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, 4332 param_type_iterator ArgTys, unsigned NumArgs, 4333 const ExtProtoInfo &EPI, const ASTContext &Context, 4334 bool Canonical); 4335 }; 4336 4337 /// Represents the dependent type named by a dependently-scoped 4338 /// typename using declaration, e.g. 4339 /// using typename Base<T>::foo; 4340 /// 4341 /// Template instantiation turns these into the underlying type. 4342 class UnresolvedUsingType : public Type { 4343 friend class ASTContext; // ASTContext creates these. 4344 4345 UnresolvedUsingTypenameDecl *Decl; 4346 4347 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) 4348 : Type(UnresolvedUsing, QualType(), 4349 TypeDependence::DependentInstantiation), 4350 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {} 4351 4352 public: 4353 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } 4354 4355 bool isSugared() const { return false; } 4356 QualType desugar() const { return QualType(this, 0); } 4357 4358 static bool classof(const Type *T) { 4359 return T->getTypeClass() == UnresolvedUsing; 4360 } 4361 4362 void Profile(llvm::FoldingSetNodeID &ID) { 4363 return Profile(ID, Decl); 4364 } 4365 4366 static void Profile(llvm::FoldingSetNodeID &ID, 4367 UnresolvedUsingTypenameDecl *D) { 4368 ID.AddPointer(D); 4369 } 4370 }; 4371 4372 class TypedefType : public Type { 4373 TypedefNameDecl *Decl; 4374 4375 protected: 4376 friend class ASTContext; // ASTContext creates these. 4377 4378 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can) 4379 : Type(tc, can, can->getDependence() & ~TypeDependence::UnexpandedPack), 4380 Decl(const_cast<TypedefNameDecl *>(D)) { 4381 assert(!isa<TypedefType>(can) && "Invalid canonical type"); 4382 } 4383 4384 public: 4385 TypedefNameDecl *getDecl() const { return Decl; } 4386 4387 bool isSugared() const { return true; } 4388 QualType desugar() const; 4389 4390 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } 4391 }; 4392 4393 /// Sugar type that represents a type that was qualified by a qualifier written 4394 /// as a macro invocation. 4395 class MacroQualifiedType : public Type { 4396 friend class ASTContext; // ASTContext creates these. 4397 4398 QualType UnderlyingTy; 4399 const IdentifierInfo *MacroII; 4400 4401 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, 4402 const IdentifierInfo *MacroII) 4403 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()), 4404 UnderlyingTy(UnderlyingTy), MacroII(MacroII) { 4405 assert(isa<AttributedType>(UnderlyingTy) && 4406 "Expected a macro qualified type to only wrap attributed types."); 4407 } 4408 4409 public: 4410 const IdentifierInfo *getMacroIdentifier() const { return MacroII; } 4411 QualType getUnderlyingType() const { return UnderlyingTy; } 4412 4413 /// Return this attributed type's modified type with no qualifiers attached to 4414 /// it. 4415 QualType getModifiedType() const; 4416 4417 bool isSugared() const { return true; } 4418 QualType desugar() const; 4419 4420 static bool classof(const Type *T) { 4421 return T->getTypeClass() == MacroQualified; 4422 } 4423 }; 4424 4425 /// Represents a `typeof` (or __typeof__) expression (a GCC extension). 4426 class TypeOfExprType : public Type { 4427 Expr *TOExpr; 4428 4429 protected: 4430 friend class ASTContext; // ASTContext creates these. 4431 4432 TypeOfExprType(Expr *E, QualType can = QualType()); 4433 4434 public: 4435 Expr *getUnderlyingExpr() const { return TOExpr; } 4436 4437 /// Remove a single level of sugar. 4438 QualType desugar() const; 4439 4440 /// Returns whether this type directly provides sugar. 4441 bool isSugared() const; 4442 4443 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } 4444 }; 4445 4446 /// Internal representation of canonical, dependent 4447 /// `typeof(expr)` types. 4448 /// 4449 /// This class is used internally by the ASTContext to manage 4450 /// canonical, dependent types, only. Clients will only see instances 4451 /// of this class via TypeOfExprType nodes. 4452 class DependentTypeOfExprType 4453 : public TypeOfExprType, public llvm::FoldingSetNode { 4454 const ASTContext &Context; 4455 4456 public: 4457 DependentTypeOfExprType(const ASTContext &Context, Expr *E) 4458 : TypeOfExprType(E), Context(Context) {} 4459 4460 void Profile(llvm::FoldingSetNodeID &ID) { 4461 Profile(ID, Context, getUnderlyingExpr()); 4462 } 4463 4464 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4465 Expr *E); 4466 }; 4467 4468 /// Represents `typeof(type)`, a GCC extension. 4469 class TypeOfType : public Type { 4470 friend class ASTContext; // ASTContext creates these. 4471 4472 QualType TOType; 4473 4474 TypeOfType(QualType T, QualType can) 4475 : Type(TypeOf, can, T->getDependence()), TOType(T) { 4476 assert(!isa<TypedefType>(can) && "Invalid canonical type"); 4477 } 4478 4479 public: 4480 QualType getUnderlyingType() const { return TOType; } 4481 4482 /// Remove a single level of sugar. 4483 QualType desugar() const { return getUnderlyingType(); } 4484 4485 /// Returns whether this type directly provides sugar. 4486 bool isSugared() const { return true; } 4487 4488 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } 4489 }; 4490 4491 /// Represents the type `decltype(expr)` (C++11). 4492 class DecltypeType : public Type { 4493 Expr *E; 4494 QualType UnderlyingType; 4495 4496 protected: 4497 friend class ASTContext; // ASTContext creates these. 4498 4499 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); 4500 4501 public: 4502 Expr *getUnderlyingExpr() const { return E; } 4503 QualType getUnderlyingType() const { return UnderlyingType; } 4504 4505 /// Remove a single level of sugar. 4506 QualType desugar() const; 4507 4508 /// Returns whether this type directly provides sugar. 4509 bool isSugared() const; 4510 4511 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } 4512 }; 4513 4514 /// Internal representation of canonical, dependent 4515 /// decltype(expr) types. 4516 /// 4517 /// This class is used internally by the ASTContext to manage 4518 /// canonical, dependent types, only. Clients will only see instances 4519 /// of this class via DecltypeType nodes. 4520 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { 4521 const ASTContext &Context; 4522 4523 public: 4524 DependentDecltypeType(const ASTContext &Context, Expr *E); 4525 4526 void Profile(llvm::FoldingSetNodeID &ID) { 4527 Profile(ID, Context, getUnderlyingExpr()); 4528 } 4529 4530 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4531 Expr *E); 4532 }; 4533 4534 /// A unary type transform, which is a type constructed from another. 4535 class UnaryTransformType : public Type { 4536 public: 4537 enum UTTKind { 4538 EnumUnderlyingType 4539 }; 4540 4541 private: 4542 /// The untransformed type. 4543 QualType BaseType; 4544 4545 /// The transformed type if not dependent, otherwise the same as BaseType. 4546 QualType UnderlyingType; 4547 4548 UTTKind UKind; 4549 4550 protected: 4551 friend class ASTContext; 4552 4553 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, 4554 QualType CanonicalTy); 4555 4556 public: 4557 bool isSugared() const { return !isDependentType(); } 4558 QualType desugar() const { return UnderlyingType; } 4559 4560 QualType getUnderlyingType() const { return UnderlyingType; } 4561 QualType getBaseType() const { return BaseType; } 4562 4563 UTTKind getUTTKind() const { return UKind; } 4564 4565 static bool classof(const Type *T) { 4566 return T->getTypeClass() == UnaryTransform; 4567 } 4568 }; 4569 4570 /// Internal representation of canonical, dependent 4571 /// __underlying_type(type) types. 4572 /// 4573 /// This class is used internally by the ASTContext to manage 4574 /// canonical, dependent types, only. Clients will only see instances 4575 /// of this class via UnaryTransformType nodes. 4576 class DependentUnaryTransformType : public UnaryTransformType, 4577 public llvm::FoldingSetNode { 4578 public: 4579 DependentUnaryTransformType(const ASTContext &C, QualType BaseType, 4580 UTTKind UKind); 4581 4582 void Profile(llvm::FoldingSetNodeID &ID) { 4583 Profile(ID, getBaseType(), getUTTKind()); 4584 } 4585 4586 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, 4587 UTTKind UKind) { 4588 ID.AddPointer(BaseType.getAsOpaquePtr()); 4589 ID.AddInteger((unsigned)UKind); 4590 } 4591 }; 4592 4593 class TagType : public Type { 4594 friend class ASTReader; 4595 template <class T> friend class serialization::AbstractTypeReader; 4596 4597 /// Stores the TagDecl associated with this type. The decl may point to any 4598 /// TagDecl that declares the entity. 4599 TagDecl *decl; 4600 4601 protected: 4602 TagType(TypeClass TC, const TagDecl *D, QualType can); 4603 4604 public: 4605 TagDecl *getDecl() const; 4606 4607 /// Determines whether this type is in the process of being defined. 4608 bool isBeingDefined() const; 4609 4610 static bool classof(const Type *T) { 4611 return T->getTypeClass() == Enum || T->getTypeClass() == Record; 4612 } 4613 }; 4614 4615 /// A helper class that allows the use of isa/cast/dyncast 4616 /// to detect TagType objects of structs/unions/classes. 4617 class RecordType : public TagType { 4618 protected: 4619 friend class ASTContext; // ASTContext creates these. 4620 4621 explicit RecordType(const RecordDecl *D) 4622 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} 4623 explicit RecordType(TypeClass TC, RecordDecl *D) 4624 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} 4625 4626 public: 4627 RecordDecl *getDecl() const { 4628 return reinterpret_cast<RecordDecl*>(TagType::getDecl()); 4629 } 4630 4631 /// Recursively check all fields in the record for const-ness. If any field 4632 /// is declared const, return true. Otherwise, return false. 4633 bool hasConstFields() const; 4634 4635 bool isSugared() const { return false; } 4636 QualType desugar() const { return QualType(this, 0); } 4637 4638 static bool classof(const Type *T) { return T->getTypeClass() == Record; } 4639 }; 4640 4641 /// A helper class that allows the use of isa/cast/dyncast 4642 /// to detect TagType objects of enums. 4643 class EnumType : public TagType { 4644 friend class ASTContext; // ASTContext creates these. 4645 4646 explicit EnumType(const EnumDecl *D) 4647 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} 4648 4649 public: 4650 EnumDecl *getDecl() const { 4651 return reinterpret_cast<EnumDecl*>(TagType::getDecl()); 4652 } 4653 4654 bool isSugared() const { return false; } 4655 QualType desugar() const { return QualType(this, 0); } 4656 4657 static bool classof(const Type *T) { return T->getTypeClass() == Enum; } 4658 }; 4659 4660 /// An attributed type is a type to which a type attribute has been applied. 4661 /// 4662 /// The "modified type" is the fully-sugared type to which the attributed 4663 /// type was applied; generally it is not canonically equivalent to the 4664 /// attributed type. The "equivalent type" is the minimally-desugared type 4665 /// which the type is canonically equivalent to. 4666 /// 4667 /// For example, in the following attributed type: 4668 /// int32_t __attribute__((vector_size(16))) 4669 /// - the modified type is the TypedefType for int32_t 4670 /// - the equivalent type is VectorType(16, int32_t) 4671 /// - the canonical type is VectorType(16, int) 4672 class AttributedType : public Type, public llvm::FoldingSetNode { 4673 public: 4674 using Kind = attr::Kind; 4675 4676 private: 4677 friend class ASTContext; // ASTContext creates these 4678 4679 QualType ModifiedType; 4680 QualType EquivalentType; 4681 4682 AttributedType(QualType canon, attr::Kind attrKind, QualType modified, 4683 QualType equivalent) 4684 : Type(Attributed, canon, equivalent->getDependence()), 4685 ModifiedType(modified), EquivalentType(equivalent) { 4686 AttributedTypeBits.AttrKind = attrKind; 4687 } 4688 4689 public: 4690 Kind getAttrKind() const { 4691 return static_cast<Kind>(AttributedTypeBits.AttrKind); 4692 } 4693 4694 QualType getModifiedType() const { return ModifiedType; } 4695 QualType getEquivalentType() const { return EquivalentType; } 4696 4697 bool isSugared() const { return true; } 4698 QualType desugar() const { return getEquivalentType(); } 4699 4700 /// Does this attribute behave like a type qualifier? 4701 /// 4702 /// A type qualifier adjusts a type to provide specialized rules for 4703 /// a specific object, like the standard const and volatile qualifiers. 4704 /// This includes attributes controlling things like nullability, 4705 /// address spaces, and ARC ownership. The value of the object is still 4706 /// largely described by the modified type. 4707 /// 4708 /// In contrast, many type attributes "rewrite" their modified type to 4709 /// produce a fundamentally different type, not necessarily related in any 4710 /// formalizable way to the original type. For example, calling convention 4711 /// and vector attributes are not simple type qualifiers. 4712 /// 4713 /// Type qualifiers are often, but not always, reflected in the canonical 4714 /// type. 4715 bool isQualifier() const; 4716 4717 bool isMSTypeSpec() const; 4718 4719 bool isCallingConv() const; 4720 4721 llvm::Optional<NullabilityKind> getImmediateNullability() const; 4722 4723 /// Retrieve the attribute kind corresponding to the given 4724 /// nullability kind. 4725 static Kind getNullabilityAttrKind(NullabilityKind kind) { 4726 switch (kind) { 4727 case NullabilityKind::NonNull: 4728 return attr::TypeNonNull; 4729 4730 case NullabilityKind::Nullable: 4731 return attr::TypeNullable; 4732 4733 case NullabilityKind::Unspecified: 4734 return attr::TypeNullUnspecified; 4735 } 4736 llvm_unreachable("Unknown nullability kind."); 4737 } 4738 4739 /// Strip off the top-level nullability annotation on the given 4740 /// type, if it's there. 4741 /// 4742 /// \param T The type to strip. If the type is exactly an 4743 /// AttributedType specifying nullability (without looking through 4744 /// type sugar), the nullability is returned and this type changed 4745 /// to the underlying modified type. 4746 /// 4747 /// \returns the top-level nullability, if present. 4748 static Optional<NullabilityKind> stripOuterNullability(QualType &T); 4749 4750 void Profile(llvm::FoldingSetNodeID &ID) { 4751 Profile(ID, getAttrKind(), ModifiedType, EquivalentType); 4752 } 4753 4754 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, 4755 QualType modified, QualType equivalent) { 4756 ID.AddInteger(attrKind); 4757 ID.AddPointer(modified.getAsOpaquePtr()); 4758 ID.AddPointer(equivalent.getAsOpaquePtr()); 4759 } 4760 4761 static bool classof(const Type *T) { 4762 return T->getTypeClass() == Attributed; 4763 } 4764 }; 4765 4766 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { 4767 friend class ASTContext; // ASTContext creates these 4768 4769 // Helper data collector for canonical types. 4770 struct CanonicalTTPTInfo { 4771 unsigned Depth : 15; 4772 unsigned ParameterPack : 1; 4773 unsigned Index : 16; 4774 }; 4775 4776 union { 4777 // Info for the canonical type. 4778 CanonicalTTPTInfo CanTTPTInfo; 4779 4780 // Info for the non-canonical type. 4781 TemplateTypeParmDecl *TTPDecl; 4782 }; 4783 4784 /// Build a non-canonical type. 4785 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) 4786 : Type(TemplateTypeParm, Canon, 4787 TypeDependence::DependentInstantiation | 4788 (Canon->getDependence() & TypeDependence::UnexpandedPack)), 4789 TTPDecl(TTPDecl) {} 4790 4791 /// Build the canonical type. 4792 TemplateTypeParmType(unsigned D, unsigned I, bool PP) 4793 : Type(TemplateTypeParm, QualType(this, 0), 4794 TypeDependence::DependentInstantiation | 4795 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) { 4796 CanTTPTInfo.Depth = D; 4797 CanTTPTInfo.Index = I; 4798 CanTTPTInfo.ParameterPack = PP; 4799 } 4800 4801 const CanonicalTTPTInfo& getCanTTPTInfo() const { 4802 QualType Can = getCanonicalTypeInternal(); 4803 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; 4804 } 4805 4806 public: 4807 unsigned getDepth() const { return getCanTTPTInfo().Depth; } 4808 unsigned getIndex() const { return getCanTTPTInfo().Index; } 4809 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } 4810 4811 TemplateTypeParmDecl *getDecl() const { 4812 return isCanonicalUnqualified() ? nullptr : TTPDecl; 4813 } 4814 4815 IdentifierInfo *getIdentifier() const; 4816 4817 bool isSugared() const { return false; } 4818 QualType desugar() const { return QualType(this, 0); } 4819 4820 void Profile(llvm::FoldingSetNodeID &ID) { 4821 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); 4822 } 4823 4824 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, 4825 unsigned Index, bool ParameterPack, 4826 TemplateTypeParmDecl *TTPDecl) { 4827 ID.AddInteger(Depth); 4828 ID.AddInteger(Index); 4829 ID.AddBoolean(ParameterPack); 4830 ID.AddPointer(TTPDecl); 4831 } 4832 4833 static bool classof(const Type *T) { 4834 return T->getTypeClass() == TemplateTypeParm; 4835 } 4836 }; 4837 4838 /// Represents the result of substituting a type for a template 4839 /// type parameter. 4840 /// 4841 /// Within an instantiated template, all template type parameters have 4842 /// been replaced with these. They are used solely to record that a 4843 /// type was originally written as a template type parameter; 4844 /// therefore they are never canonical. 4845 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { 4846 friend class ASTContext; 4847 4848 // The original type parameter. 4849 const TemplateTypeParmType *Replaced; 4850 4851 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) 4852 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), 4853 Replaced(Param) {} 4854 4855 public: 4856 /// Gets the template parameter that was substituted for. 4857 const TemplateTypeParmType *getReplacedParameter() const { 4858 return Replaced; 4859 } 4860 4861 /// Gets the type that was substituted for the template 4862 /// parameter. 4863 QualType getReplacementType() const { 4864 return getCanonicalTypeInternal(); 4865 } 4866 4867 bool isSugared() const { return true; } 4868 QualType desugar() const { return getReplacementType(); } 4869 4870 void Profile(llvm::FoldingSetNodeID &ID) { 4871 Profile(ID, getReplacedParameter(), getReplacementType()); 4872 } 4873 4874 static void Profile(llvm::FoldingSetNodeID &ID, 4875 const TemplateTypeParmType *Replaced, 4876 QualType Replacement) { 4877 ID.AddPointer(Replaced); 4878 ID.AddPointer(Replacement.getAsOpaquePtr()); 4879 } 4880 4881 static bool classof(const Type *T) { 4882 return T->getTypeClass() == SubstTemplateTypeParm; 4883 } 4884 }; 4885 4886 /// Represents the result of substituting a set of types for a template 4887 /// type parameter pack. 4888 /// 4889 /// When a pack expansion in the source code contains multiple parameter packs 4890 /// and those parameter packs correspond to different levels of template 4891 /// parameter lists, this type node is used to represent a template type 4892 /// parameter pack from an outer level, which has already had its argument pack 4893 /// substituted but that still lives within a pack expansion that itself 4894 /// could not be instantiated. When actually performing a substitution into 4895 /// that pack expansion (e.g., when all template parameters have corresponding 4896 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType 4897 /// at the current pack substitution index. 4898 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { 4899 friend class ASTContext; 4900 4901 /// The original type parameter. 4902 const TemplateTypeParmType *Replaced; 4903 4904 /// A pointer to the set of template arguments that this 4905 /// parameter pack is instantiated with. 4906 const TemplateArgument *Arguments; 4907 4908 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 4909 QualType Canon, 4910 const TemplateArgument &ArgPack); 4911 4912 public: 4913 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } 4914 4915 /// Gets the template parameter that was substituted for. 4916 const TemplateTypeParmType *getReplacedParameter() const { 4917 return Replaced; 4918 } 4919 4920 unsigned getNumArgs() const { 4921 return SubstTemplateTypeParmPackTypeBits.NumArgs; 4922 } 4923 4924 bool isSugared() const { return false; } 4925 QualType desugar() const { return QualType(this, 0); } 4926 4927 TemplateArgument getArgumentPack() const; 4928 4929 void Profile(llvm::FoldingSetNodeID &ID); 4930 static void Profile(llvm::FoldingSetNodeID &ID, 4931 const TemplateTypeParmType *Replaced, 4932 const TemplateArgument &ArgPack); 4933 4934 static bool classof(const Type *T) { 4935 return T->getTypeClass() == SubstTemplateTypeParmPack; 4936 } 4937 }; 4938 4939 /// Common base class for placeholders for types that get replaced by 4940 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced 4941 /// class template types, and constrained type names. 4942 /// 4943 /// These types are usually a placeholder for a deduced type. However, before 4944 /// the initializer is attached, or (usually) if the initializer is 4945 /// type-dependent, there is no deduced type and the type is canonical. In 4946 /// the latter case, it is also a dependent type. 4947 class DeducedType : public Type { 4948 protected: 4949 DeducedType(TypeClass TC, QualType DeducedAsType, 4950 TypeDependence ExtraDependence) 4951 : Type(TC, 4952 // FIXME: Retain the sugared deduced type? 4953 DeducedAsType.isNull() ? QualType(this, 0) 4954 : DeducedAsType.getCanonicalType(), 4955 ExtraDependence | (DeducedAsType.isNull() 4956 ? TypeDependence::None 4957 : DeducedAsType->getDependence() & 4958 ~TypeDependence::VariablyModified)) {} 4959 4960 public: 4961 bool isSugared() const { return !isCanonicalUnqualified(); } 4962 QualType desugar() const { return getCanonicalTypeInternal(); } 4963 4964 /// Get the type deduced for this placeholder type, or null if it's 4965 /// either not been deduced or was deduced to a dependent type. 4966 QualType getDeducedType() const { 4967 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); 4968 } 4969 bool isDeduced() const { 4970 return !isCanonicalUnqualified() || isDependentType(); 4971 } 4972 4973 static bool classof(const Type *T) { 4974 return T->getTypeClass() == Auto || 4975 T->getTypeClass() == DeducedTemplateSpecialization; 4976 } 4977 }; 4978 4979 /// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained 4980 /// by a type-constraint. 4981 class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode { 4982 friend class ASTContext; // ASTContext creates these 4983 4984 ConceptDecl *TypeConstraintConcept; 4985 4986 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, 4987 TypeDependence ExtraDependence, ConceptDecl *CD, 4988 ArrayRef<TemplateArgument> TypeConstraintArgs); 4989 4990 const TemplateArgument *getArgBuffer() const { 4991 return reinterpret_cast<const TemplateArgument*>(this+1); 4992 } 4993 4994 TemplateArgument *getArgBuffer() { 4995 return reinterpret_cast<TemplateArgument*>(this+1); 4996 } 4997 4998 public: 4999 /// Retrieve the template arguments. 5000 const TemplateArgument *getArgs() const { 5001 return getArgBuffer(); 5002 } 5003 5004 /// Retrieve the number of template arguments. 5005 unsigned getNumArgs() const { 5006 return AutoTypeBits.NumArgs; 5007 } 5008 5009 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h 5010 5011 ArrayRef<TemplateArgument> getTypeConstraintArguments() const { 5012 return {getArgs(), getNumArgs()}; 5013 } 5014 5015 ConceptDecl *getTypeConstraintConcept() const { 5016 return TypeConstraintConcept; 5017 } 5018 5019 bool isConstrained() const { 5020 return TypeConstraintConcept != nullptr; 5021 } 5022 5023 bool isDecltypeAuto() const { 5024 return getKeyword() == AutoTypeKeyword::DecltypeAuto; 5025 } 5026 5027 AutoTypeKeyword getKeyword() const { 5028 return (AutoTypeKeyword)AutoTypeBits.Keyword; 5029 } 5030 5031 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { 5032 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), 5033 getTypeConstraintConcept(), getTypeConstraintArguments()); 5034 } 5035 5036 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 5037 QualType Deduced, AutoTypeKeyword Keyword, 5038 bool IsDependent, ConceptDecl *CD, 5039 ArrayRef<TemplateArgument> Arguments); 5040 5041 static bool classof(const Type *T) { 5042 return T->getTypeClass() == Auto; 5043 } 5044 }; 5045 5046 /// Represents a C++17 deduced template specialization type. 5047 class DeducedTemplateSpecializationType : public DeducedType, 5048 public llvm::FoldingSetNode { 5049 friend class ASTContext; // ASTContext creates these 5050 5051 /// The name of the template whose arguments will be deduced. 5052 TemplateName Template; 5053 5054 DeducedTemplateSpecializationType(TemplateName Template, 5055 QualType DeducedAsType, 5056 bool IsDeducedAsDependent) 5057 : DeducedType(DeducedTemplateSpecialization, DeducedAsType, 5058 toTypeDependence(Template.getDependence()) | 5059 (IsDeducedAsDependent 5060 ? TypeDependence::DependentInstantiation 5061 : TypeDependence::None)), 5062 Template(Template) {} 5063 5064 public: 5065 /// Retrieve the name of the template that we are deducing. 5066 TemplateName getTemplateName() const { return Template;} 5067 5068 void Profile(llvm::FoldingSetNodeID &ID) { 5069 Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); 5070 } 5071 5072 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, 5073 QualType Deduced, bool IsDependent) { 5074 Template.Profile(ID); 5075 ID.AddPointer(Deduced.getAsOpaquePtr()); 5076 ID.AddBoolean(IsDependent); 5077 } 5078 5079 static bool classof(const Type *T) { 5080 return T->getTypeClass() == DeducedTemplateSpecialization; 5081 } 5082 }; 5083 5084 /// Represents a type template specialization; the template 5085 /// must be a class template, a type alias template, or a template 5086 /// template parameter. A template which cannot be resolved to one of 5087 /// these, e.g. because it is written with a dependent scope 5088 /// specifier, is instead represented as a 5089 /// @c DependentTemplateSpecializationType. 5090 /// 5091 /// A non-dependent template specialization type is always "sugar", 5092 /// typically for a \c RecordType. For example, a class template 5093 /// specialization type of \c vector<int> will refer to a tag type for 5094 /// the instantiation \c std::vector<int, std::allocator<int>> 5095 /// 5096 /// Template specializations are dependent if either the template or 5097 /// any of the template arguments are dependent, in which case the 5098 /// type may also be canonical. 5099 /// 5100 /// Instances of this type are allocated with a trailing array of 5101 /// TemplateArguments, followed by a QualType representing the 5102 /// non-canonical aliased type when the template is a type alias 5103 /// template. 5104 class alignas(8) TemplateSpecializationType 5105 : public Type, 5106 public llvm::FoldingSetNode { 5107 friend class ASTContext; // ASTContext creates these 5108 5109 /// The name of the template being specialized. This is 5110 /// either a TemplateName::Template (in which case it is a 5111 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a 5112 /// TypeAliasTemplateDecl*), a 5113 /// TemplateName::SubstTemplateTemplateParmPack, or a 5114 /// TemplateName::SubstTemplateTemplateParm (in which case the 5115 /// replacement must, recursively, be one of these). 5116 TemplateName Template; 5117 5118 TemplateSpecializationType(TemplateName T, 5119 ArrayRef<TemplateArgument> Args, 5120 QualType Canon, 5121 QualType Aliased); 5122 5123 public: 5124 /// Determine whether any of the given template arguments are dependent. 5125 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 5126 bool &InstantiationDependent); 5127 5128 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, 5129 bool &InstantiationDependent); 5130 5131 /// True if this template specialization type matches a current 5132 /// instantiation in the context in which it is found. 5133 bool isCurrentInstantiation() const { 5134 return isa<InjectedClassNameType>(getCanonicalTypeInternal()); 5135 } 5136 5137 /// Determine if this template specialization type is for a type alias 5138 /// template that has been substituted. 5139 /// 5140 /// Nearly every template specialization type whose template is an alias 5141 /// template will be substituted. However, this is not the case when 5142 /// the specialization contains a pack expansion but the template alias 5143 /// does not have a corresponding parameter pack, e.g., 5144 /// 5145 /// \code 5146 /// template<typename T, typename U, typename V> struct S; 5147 /// template<typename T, typename U> using A = S<T, int, U>; 5148 /// template<typename... Ts> struct X { 5149 /// typedef A<Ts...> type; // not a type alias 5150 /// }; 5151 /// \endcode 5152 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } 5153 5154 /// Get the aliased type, if this is a specialization of a type alias 5155 /// template. 5156 QualType getAliasedType() const { 5157 assert(isTypeAlias() && "not a type alias template specialization"); 5158 return *reinterpret_cast<const QualType*>(end()); 5159 } 5160 5161 using iterator = const TemplateArgument *; 5162 5163 iterator begin() const { return getArgs(); } 5164 iterator end() const; // defined inline in TemplateBase.h 5165 5166 /// Retrieve the name of the template that we are specializing. 5167 TemplateName getTemplateName() const { return Template; } 5168 5169 /// Retrieve the template arguments. 5170 const TemplateArgument *getArgs() const { 5171 return reinterpret_cast<const TemplateArgument *>(this + 1); 5172 } 5173 5174 /// Retrieve the number of template arguments. 5175 unsigned getNumArgs() const { 5176 return TemplateSpecializationTypeBits.NumArgs; 5177 } 5178 5179 /// Retrieve a specific template argument as a type. 5180 /// \pre \c isArgType(Arg) 5181 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h 5182 5183 ArrayRef<TemplateArgument> template_arguments() const { 5184 return {getArgs(), getNumArgs()}; 5185 } 5186 5187 bool isSugared() const { 5188 return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); 5189 } 5190 5191 QualType desugar() const { 5192 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); 5193 } 5194 5195 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { 5196 Profile(ID, Template, template_arguments(), Ctx); 5197 if (isTypeAlias()) 5198 getAliasedType().Profile(ID); 5199 } 5200 5201 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, 5202 ArrayRef<TemplateArgument> Args, 5203 const ASTContext &Context); 5204 5205 static bool classof(const Type *T) { 5206 return T->getTypeClass() == TemplateSpecialization; 5207 } 5208 }; 5209 5210 /// Print a template argument list, including the '<' and '>' 5211 /// enclosing the template arguments. 5212 void printTemplateArgumentList(raw_ostream &OS, 5213 ArrayRef<TemplateArgument> Args, 5214 const PrintingPolicy &Policy); 5215 5216 void printTemplateArgumentList(raw_ostream &OS, 5217 ArrayRef<TemplateArgumentLoc> Args, 5218 const PrintingPolicy &Policy); 5219 5220 void printTemplateArgumentList(raw_ostream &OS, 5221 const TemplateArgumentListInfo &Args, 5222 const PrintingPolicy &Policy); 5223 5224 /// The injected class name of a C++ class template or class 5225 /// template partial specialization. Used to record that a type was 5226 /// spelled with a bare identifier rather than as a template-id; the 5227 /// equivalent for non-templated classes is just RecordType. 5228 /// 5229 /// Injected class name types are always dependent. Template 5230 /// instantiation turns these into RecordTypes. 5231 /// 5232 /// Injected class name types are always canonical. This works 5233 /// because it is impossible to compare an injected class name type 5234 /// with the corresponding non-injected template type, for the same 5235 /// reason that it is impossible to directly compare template 5236 /// parameters from different dependent contexts: injected class name 5237 /// types can only occur within the scope of a particular templated 5238 /// declaration, and within that scope every template specialization 5239 /// will canonicalize to the injected class name (when appropriate 5240 /// according to the rules of the language). 5241 class InjectedClassNameType : public Type { 5242 friend class ASTContext; // ASTContext creates these. 5243 friend class ASTNodeImporter; 5244 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not 5245 // currently suitable for AST reading, too much 5246 // interdependencies. 5247 template <class T> friend class serialization::AbstractTypeReader; 5248 5249 CXXRecordDecl *Decl; 5250 5251 /// The template specialization which this type represents. 5252 /// For example, in 5253 /// template <class T> class A { ... }; 5254 /// this is A<T>, whereas in 5255 /// template <class X, class Y> class A<B<X,Y> > { ... }; 5256 /// this is A<B<X,Y> >. 5257 /// 5258 /// It is always unqualified, always a template specialization type, 5259 /// and always dependent. 5260 QualType InjectedType; 5261 5262 InjectedClassNameType(CXXRecordDecl *D, QualType TST) 5263 : Type(InjectedClassName, QualType(), 5264 TypeDependence::DependentInstantiation), 5265 Decl(D), InjectedType(TST) { 5266 assert(isa<TemplateSpecializationType>(TST)); 5267 assert(!TST.hasQualifiers()); 5268 assert(TST->isDependentType()); 5269 } 5270 5271 public: 5272 QualType getInjectedSpecializationType() const { return InjectedType; } 5273 5274 const TemplateSpecializationType *getInjectedTST() const { 5275 return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); 5276 } 5277 5278 TemplateName getTemplateName() const { 5279 return getInjectedTST()->getTemplateName(); 5280 } 5281 5282 CXXRecordDecl *getDecl() const; 5283 5284 bool isSugared() const { return false; } 5285 QualType desugar() const { return QualType(this, 0); } 5286 5287 static bool classof(const Type *T) { 5288 return T->getTypeClass() == InjectedClassName; 5289 } 5290 }; 5291 5292 /// The kind of a tag type. 5293 enum TagTypeKind { 5294 /// The "struct" keyword. 5295 TTK_Struct, 5296 5297 /// The "__interface" keyword. 5298 TTK_Interface, 5299 5300 /// The "union" keyword. 5301 TTK_Union, 5302 5303 /// The "class" keyword. 5304 TTK_Class, 5305 5306 /// The "enum" keyword. 5307 TTK_Enum 5308 }; 5309 5310 /// The elaboration keyword that precedes a qualified type name or 5311 /// introduces an elaborated-type-specifier. 5312 enum ElaboratedTypeKeyword { 5313 /// The "struct" keyword introduces the elaborated-type-specifier. 5314 ETK_Struct, 5315 5316 /// The "__interface" keyword introduces the elaborated-type-specifier. 5317 ETK_Interface, 5318 5319 /// The "union" keyword introduces the elaborated-type-specifier. 5320 ETK_Union, 5321 5322 /// The "class" keyword introduces the elaborated-type-specifier. 5323 ETK_Class, 5324 5325 /// The "enum" keyword introduces the elaborated-type-specifier. 5326 ETK_Enum, 5327 5328 /// The "typename" keyword precedes the qualified type name, e.g., 5329 /// \c typename T::type. 5330 ETK_Typename, 5331 5332 /// No keyword precedes the qualified type name. 5333 ETK_None 5334 }; 5335 5336 /// A helper class for Type nodes having an ElaboratedTypeKeyword. 5337 /// The keyword in stored in the free bits of the base class. 5338 /// Also provides a few static helpers for converting and printing 5339 /// elaborated type keyword and tag type kind enumerations. 5340 class TypeWithKeyword : public Type { 5341 protected: 5342 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, 5343 QualType Canonical, TypeDependence Dependence) 5344 : Type(tc, Canonical, Dependence) { 5345 TypeWithKeywordBits.Keyword = Keyword; 5346 } 5347 5348 public: 5349 ElaboratedTypeKeyword getKeyword() const { 5350 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); 5351 } 5352 5353 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. 5354 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); 5355 5356 /// Converts a type specifier (DeclSpec::TST) into a tag type kind. 5357 /// It is an error to provide a type specifier which *isn't* a tag kind here. 5358 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); 5359 5360 /// Converts a TagTypeKind into an elaborated type keyword. 5361 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); 5362 5363 /// Converts an elaborated type keyword into a TagTypeKind. 5364 /// It is an error to provide an elaborated type keyword 5365 /// which *isn't* a tag kind here. 5366 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); 5367 5368 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); 5369 5370 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); 5371 5372 static StringRef getTagTypeKindName(TagTypeKind Kind) { 5373 return getKeywordName(getKeywordForTagTypeKind(Kind)); 5374 } 5375 5376 class CannotCastToThisType {}; 5377 static CannotCastToThisType classof(const Type *); 5378 }; 5379 5380 /// Represents a type that was referred to using an elaborated type 5381 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, 5382 /// or both. 5383 /// 5384 /// This type is used to keep track of a type name as written in the 5385 /// source code, including tag keywords and any nested-name-specifiers. 5386 /// The type itself is always "sugar", used to express what was written 5387 /// in the source code but containing no additional semantic information. 5388 class ElaboratedType final 5389 : public TypeWithKeyword, 5390 public llvm::FoldingSetNode, 5391 private llvm::TrailingObjects<ElaboratedType, TagDecl *> { 5392 friend class ASTContext; // ASTContext creates these 5393 friend TrailingObjects; 5394 5395 /// The nested name specifier containing the qualifier. 5396 NestedNameSpecifier *NNS; 5397 5398 /// The type that this qualified name refers to. 5399 QualType NamedType; 5400 5401 /// The (re)declaration of this tag type owned by this occurrence is stored 5402 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain 5403 /// it, or obtain a null pointer if there is none. 5404 5405 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 5406 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) 5407 : TypeWithKeyword(Keyword, Elaborated, CanonType, 5408 NamedType->getDependence()), 5409 NNS(NNS), NamedType(NamedType) { 5410 ElaboratedTypeBits.HasOwnedTagDecl = false; 5411 if (OwnedTagDecl) { 5412 ElaboratedTypeBits.HasOwnedTagDecl = true; 5413 *getTrailingObjects<TagDecl *>() = OwnedTagDecl; 5414 } 5415 assert(!(Keyword == ETK_None && NNS == nullptr) && 5416 "ElaboratedType cannot have elaborated type keyword " 5417 "and name qualifier both null."); 5418 } 5419 5420 public: 5421 /// Retrieve the qualification on this type. 5422 NestedNameSpecifier *getQualifier() const { return NNS; } 5423 5424 /// Retrieve the type named by the qualified-id. 5425 QualType getNamedType() const { return NamedType; } 5426 5427 /// Remove a single level of sugar. 5428 QualType desugar() const { return getNamedType(); } 5429 5430 /// Returns whether this type directly provides sugar. 5431 bool isSugared() const { return true; } 5432 5433 /// Return the (re)declaration of this type owned by this occurrence of this 5434 /// type, or nullptr if there is none. 5435 TagDecl *getOwnedTagDecl() const { 5436 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() 5437 : nullptr; 5438 } 5439 5440 void Profile(llvm::FoldingSetNodeID &ID) { 5441 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); 5442 } 5443 5444 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, 5445 NestedNameSpecifier *NNS, QualType NamedType, 5446 TagDecl *OwnedTagDecl) { 5447 ID.AddInteger(Keyword); 5448 ID.AddPointer(NNS); 5449 NamedType.Profile(ID); 5450 ID.AddPointer(OwnedTagDecl); 5451 } 5452 5453 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } 5454 }; 5455 5456 /// Represents a qualified type name for which the type name is 5457 /// dependent. 5458 /// 5459 /// DependentNameType represents a class of dependent types that involve a 5460 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a 5461 /// name of a type. The DependentNameType may start with a "typename" (for a 5462 /// typename-specifier), "class", "struct", "union", or "enum" (for a 5463 /// dependent elaborated-type-specifier), or nothing (in contexts where we 5464 /// know that we must be referring to a type, e.g., in a base class specifier). 5465 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility 5466 /// mode, this type is used with non-dependent names to delay name lookup until 5467 /// instantiation. 5468 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { 5469 friend class ASTContext; // ASTContext creates these 5470 5471 /// The nested name specifier containing the qualifier. 5472 NestedNameSpecifier *NNS; 5473 5474 /// The type that this typename specifier refers to. 5475 const IdentifierInfo *Name; 5476 5477 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 5478 const IdentifierInfo *Name, QualType CanonType) 5479 : TypeWithKeyword(Keyword, DependentName, CanonType, 5480 TypeDependence::DependentInstantiation | 5481 toTypeDependence(NNS->getDependence())), 5482 NNS(NNS), Name(Name) {} 5483 5484 public: 5485 /// Retrieve the qualification on this type. 5486 NestedNameSpecifier *getQualifier() const { return NNS; } 5487 5488 /// Retrieve the type named by the typename specifier as an identifier. 5489 /// 5490 /// This routine will return a non-NULL identifier pointer when the 5491 /// form of the original typename was terminated by an identifier, 5492 /// e.g., "typename T::type". 5493 const IdentifierInfo *getIdentifier() const { 5494 return Name; 5495 } 5496 5497 bool isSugared() const { return false; } 5498 QualType desugar() const { return QualType(this, 0); } 5499 5500 void Profile(llvm::FoldingSetNodeID &ID) { 5501 Profile(ID, getKeyword(), NNS, Name); 5502 } 5503 5504 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, 5505 NestedNameSpecifier *NNS, const IdentifierInfo *Name) { 5506 ID.AddInteger(Keyword); 5507 ID.AddPointer(NNS); 5508 ID.AddPointer(Name); 5509 } 5510 5511 static bool classof(const Type *T) { 5512 return T->getTypeClass() == DependentName; 5513 } 5514 }; 5515 5516 /// Represents a template specialization type whose template cannot be 5517 /// resolved, e.g. 5518 /// A<T>::template B<T> 5519 class alignas(8) DependentTemplateSpecializationType 5520 : public TypeWithKeyword, 5521 public llvm::FoldingSetNode { 5522 friend class ASTContext; // ASTContext creates these 5523 5524 /// The nested name specifier containing the qualifier. 5525 NestedNameSpecifier *NNS; 5526 5527 /// The identifier of the template. 5528 const IdentifierInfo *Name; 5529 5530 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, 5531 NestedNameSpecifier *NNS, 5532 const IdentifierInfo *Name, 5533 ArrayRef<TemplateArgument> Args, 5534 QualType Canon); 5535 5536 const TemplateArgument *getArgBuffer() const { 5537 return reinterpret_cast<const TemplateArgument*>(this+1); 5538 } 5539 5540 TemplateArgument *getArgBuffer() { 5541 return reinterpret_cast<TemplateArgument*>(this+1); 5542 } 5543 5544 public: 5545 NestedNameSpecifier *getQualifier() const { return NNS; } 5546 const IdentifierInfo *getIdentifier() const { return Name; } 5547 5548 /// Retrieve the template arguments. 5549 const TemplateArgument *getArgs() const { 5550 return getArgBuffer(); 5551 } 5552 5553 /// Retrieve the number of template arguments. 5554 unsigned getNumArgs() const { 5555 return DependentTemplateSpecializationTypeBits.NumArgs; 5556 } 5557 5558 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h 5559 5560 ArrayRef<TemplateArgument> template_arguments() const { 5561 return {getArgs(), getNumArgs()}; 5562 } 5563 5564 using iterator = const TemplateArgument *; 5565 5566 iterator begin() const { return getArgs(); } 5567 iterator end() const; // inline in TemplateBase.h 5568 5569 bool isSugared() const { return false; } 5570 QualType desugar() const { return QualType(this, 0); } 5571 5572 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { 5573 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); 5574 } 5575 5576 static void Profile(llvm::FoldingSetNodeID &ID, 5577 const ASTContext &Context, 5578 ElaboratedTypeKeyword Keyword, 5579 NestedNameSpecifier *Qualifier, 5580 const IdentifierInfo *Name, 5581 ArrayRef<TemplateArgument> Args); 5582 5583 static bool classof(const Type *T) { 5584 return T->getTypeClass() == DependentTemplateSpecialization; 5585 } 5586 }; 5587 5588 /// Represents a pack expansion of types. 5589 /// 5590 /// Pack expansions are part of C++11 variadic templates. A pack 5591 /// expansion contains a pattern, which itself contains one or more 5592 /// "unexpanded" parameter packs. When instantiated, a pack expansion 5593 /// produces a series of types, each instantiated from the pattern of 5594 /// the expansion, where the Ith instantiation of the pattern uses the 5595 /// Ith arguments bound to each of the unexpanded parameter packs. The 5596 /// pack expansion is considered to "expand" these unexpanded 5597 /// parameter packs. 5598 /// 5599 /// \code 5600 /// template<typename ...Types> struct tuple; 5601 /// 5602 /// template<typename ...Types> 5603 /// struct tuple_of_references { 5604 /// typedef tuple<Types&...> type; 5605 /// }; 5606 /// \endcode 5607 /// 5608 /// Here, the pack expansion \c Types&... is represented via a 5609 /// PackExpansionType whose pattern is Types&. 5610 class PackExpansionType : public Type, public llvm::FoldingSetNode { 5611 friend class ASTContext; // ASTContext creates these 5612 5613 /// The pattern of the pack expansion. 5614 QualType Pattern; 5615 5616 PackExpansionType(QualType Pattern, QualType Canon, 5617 Optional<unsigned> NumExpansions) 5618 : Type(PackExpansion, Canon, 5619 (Pattern->getDependence() | TypeDependence::Instantiation) & 5620 ~TypeDependence::UnexpandedPack), 5621 Pattern(Pattern) { 5622 PackExpansionTypeBits.NumExpansions = 5623 NumExpansions ? *NumExpansions + 1 : 0; 5624 } 5625 5626 public: 5627 /// Retrieve the pattern of this pack expansion, which is the 5628 /// type that will be repeatedly instantiated when instantiating the 5629 /// pack expansion itself. 5630 QualType getPattern() const { return Pattern; } 5631 5632 /// Retrieve the number of expansions that this pack expansion will 5633 /// generate, if known. 5634 Optional<unsigned> getNumExpansions() const { 5635 if (PackExpansionTypeBits.NumExpansions) 5636 return PackExpansionTypeBits.NumExpansions - 1; 5637 return None; 5638 } 5639 5640 bool isSugared() const { return !Pattern->isDependentType(); } 5641 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); } 5642 5643 void Profile(llvm::FoldingSetNodeID &ID) { 5644 Profile(ID, getPattern(), getNumExpansions()); 5645 } 5646 5647 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, 5648 Optional<unsigned> NumExpansions) { 5649 ID.AddPointer(Pattern.getAsOpaquePtr()); 5650 ID.AddBoolean(NumExpansions.hasValue()); 5651 if (NumExpansions) 5652 ID.AddInteger(*NumExpansions); 5653 } 5654 5655 static bool classof(const Type *T) { 5656 return T->getTypeClass() == PackExpansion; 5657 } 5658 }; 5659 5660 /// This class wraps the list of protocol qualifiers. For types that can 5661 /// take ObjC protocol qualifers, they can subclass this class. 5662 template <class T> 5663 class ObjCProtocolQualifiers { 5664 protected: 5665 ObjCProtocolQualifiers() = default; 5666 5667 ObjCProtocolDecl * const *getProtocolStorage() const { 5668 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); 5669 } 5670 5671 ObjCProtocolDecl **getProtocolStorage() { 5672 return static_cast<T*>(this)->getProtocolStorageImpl(); 5673 } 5674 5675 void setNumProtocols(unsigned N) { 5676 static_cast<T*>(this)->setNumProtocolsImpl(N); 5677 } 5678 5679 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { 5680 setNumProtocols(protocols.size()); 5681 assert(getNumProtocols() == protocols.size() && 5682 "bitfield overflow in protocol count"); 5683 if (!protocols.empty()) 5684 memcpy(getProtocolStorage(), protocols.data(), 5685 protocols.size() * sizeof(ObjCProtocolDecl*)); 5686 } 5687 5688 public: 5689 using qual_iterator = ObjCProtocolDecl * const *; 5690 using qual_range = llvm::iterator_range<qual_iterator>; 5691 5692 qual_range quals() const { return qual_range(qual_begin(), qual_end()); } 5693 qual_iterator qual_begin() const { return getProtocolStorage(); } 5694 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } 5695 5696 bool qual_empty() const { return getNumProtocols() == 0; } 5697 5698 /// Return the number of qualifying protocols in this type, or 0 if 5699 /// there are none. 5700 unsigned getNumProtocols() const { 5701 return static_cast<const T*>(this)->getNumProtocolsImpl(); 5702 } 5703 5704 /// Fetch a protocol by index. 5705 ObjCProtocolDecl *getProtocol(unsigned I) const { 5706 assert(I < getNumProtocols() && "Out-of-range protocol access"); 5707 return qual_begin()[I]; 5708 } 5709 5710 /// Retrieve all of the protocol qualifiers. 5711 ArrayRef<ObjCProtocolDecl *> getProtocols() const { 5712 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); 5713 } 5714 }; 5715 5716 /// Represents a type parameter type in Objective C. It can take 5717 /// a list of protocols. 5718 class ObjCTypeParamType : public Type, 5719 public ObjCProtocolQualifiers<ObjCTypeParamType>, 5720 public llvm::FoldingSetNode { 5721 friend class ASTContext; 5722 friend class ObjCProtocolQualifiers<ObjCTypeParamType>; 5723 5724 /// The number of protocols stored on this type. 5725 unsigned NumProtocols : 6; 5726 5727 ObjCTypeParamDecl *OTPDecl; 5728 5729 /// The protocols are stored after the ObjCTypeParamType node. In the 5730 /// canonical type, the list of protocols are sorted alphabetically 5731 /// and uniqued. 5732 ObjCProtocolDecl **getProtocolStorageImpl(); 5733 5734 /// Return the number of qualifying protocols in this interface type, 5735 /// or 0 if there are none. 5736 unsigned getNumProtocolsImpl() const { 5737 return NumProtocols; 5738 } 5739 5740 void setNumProtocolsImpl(unsigned N) { 5741 NumProtocols = N; 5742 } 5743 5744 ObjCTypeParamType(const ObjCTypeParamDecl *D, 5745 QualType can, 5746 ArrayRef<ObjCProtocolDecl *> protocols); 5747 5748 public: 5749 bool isSugared() const { return true; } 5750 QualType desugar() const { return getCanonicalTypeInternal(); } 5751 5752 static bool classof(const Type *T) { 5753 return T->getTypeClass() == ObjCTypeParam; 5754 } 5755 5756 void Profile(llvm::FoldingSetNodeID &ID); 5757 static void Profile(llvm::FoldingSetNodeID &ID, 5758 const ObjCTypeParamDecl *OTPDecl, 5759 QualType CanonicalType, 5760 ArrayRef<ObjCProtocolDecl *> protocols); 5761 5762 ObjCTypeParamDecl *getDecl() const { return OTPDecl; } 5763 }; 5764 5765 /// Represents a class type in Objective C. 5766 /// 5767 /// Every Objective C type is a combination of a base type, a set of 5768 /// type arguments (optional, for parameterized classes) and a list of 5769 /// protocols. 5770 /// 5771 /// Given the following declarations: 5772 /// \code 5773 /// \@class C<T>; 5774 /// \@protocol P; 5775 /// \endcode 5776 /// 5777 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType 5778 /// with base C and no protocols. 5779 /// 5780 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. 5781 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no 5782 /// protocol list. 5783 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', 5784 /// and protocol list [P]. 5785 /// 5786 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose 5787 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType 5788 /// and no protocols. 5789 /// 5790 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType 5791 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually 5792 /// this should get its own sugar class to better represent the source. 5793 class ObjCObjectType : public Type, 5794 public ObjCProtocolQualifiers<ObjCObjectType> { 5795 friend class ObjCProtocolQualifiers<ObjCObjectType>; 5796 5797 // ObjCObjectType.NumTypeArgs - the number of type arguments stored 5798 // after the ObjCObjectPointerType node. 5799 // ObjCObjectType.NumProtocols - the number of protocols stored 5800 // after the type arguments of ObjCObjectPointerType node. 5801 // 5802 // These protocols are those written directly on the type. If 5803 // protocol qualifiers ever become additive, the iterators will need 5804 // to get kindof complicated. 5805 // 5806 // In the canonical object type, these are sorted alphabetically 5807 // and uniqued. 5808 5809 /// Either a BuiltinType or an InterfaceType or sugar for either. 5810 QualType BaseType; 5811 5812 /// Cached superclass type. 5813 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> 5814 CachedSuperClassType; 5815 5816 QualType *getTypeArgStorage(); 5817 const QualType *getTypeArgStorage() const { 5818 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); 5819 } 5820 5821 ObjCProtocolDecl **getProtocolStorageImpl(); 5822 /// Return the number of qualifying protocols in this interface type, 5823 /// or 0 if there are none. 5824 unsigned getNumProtocolsImpl() const { 5825 return ObjCObjectTypeBits.NumProtocols; 5826 } 5827 void setNumProtocolsImpl(unsigned N) { 5828 ObjCObjectTypeBits.NumProtocols = N; 5829 } 5830 5831 protected: 5832 enum Nonce_ObjCInterface { Nonce_ObjCInterface }; 5833 5834 ObjCObjectType(QualType Canonical, QualType Base, 5835 ArrayRef<QualType> typeArgs, 5836 ArrayRef<ObjCProtocolDecl *> protocols, 5837 bool isKindOf); 5838 5839 ObjCObjectType(enum Nonce_ObjCInterface) 5840 : Type(ObjCInterface, QualType(), TypeDependence::None), 5841 BaseType(QualType(this_(), 0)) { 5842 ObjCObjectTypeBits.NumProtocols = 0; 5843 ObjCObjectTypeBits.NumTypeArgs = 0; 5844 ObjCObjectTypeBits.IsKindOf = 0; 5845 } 5846 5847 void computeSuperClassTypeSlow() const; 5848 5849 public: 5850 /// Gets the base type of this object type. This is always (possibly 5851 /// sugar for) one of: 5852 /// - the 'id' builtin type (as opposed to the 'id' type visible to the 5853 /// user, which is a typedef for an ObjCObjectPointerType) 5854 /// - the 'Class' builtin type (same caveat) 5855 /// - an ObjCObjectType (currently always an ObjCInterfaceType) 5856 QualType getBaseType() const { return BaseType; } 5857 5858 bool isObjCId() const { 5859 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); 5860 } 5861 5862 bool isObjCClass() const { 5863 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); 5864 } 5865 5866 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } 5867 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } 5868 bool isObjCUnqualifiedIdOrClass() const { 5869 if (!qual_empty()) return false; 5870 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) 5871 return T->getKind() == BuiltinType::ObjCId || 5872 T->getKind() == BuiltinType::ObjCClass; 5873 return false; 5874 } 5875 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } 5876 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } 5877 5878 /// Gets the interface declaration for this object type, if the base type 5879 /// really is an interface. 5880 ObjCInterfaceDecl *getInterface() const; 5881 5882 /// Determine whether this object type is "specialized", meaning 5883 /// that it has type arguments. 5884 bool isSpecialized() const; 5885 5886 /// Determine whether this object type was written with type arguments. 5887 bool isSpecializedAsWritten() const { 5888 return ObjCObjectTypeBits.NumTypeArgs > 0; 5889 } 5890 5891 /// Determine whether this object type is "unspecialized", meaning 5892 /// that it has no type arguments. 5893 bool isUnspecialized() const { return !isSpecialized(); } 5894 5895 /// Determine whether this object type is "unspecialized" as 5896 /// written, meaning that it has no type arguments. 5897 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } 5898 5899 /// Retrieve the type arguments of this object type (semantically). 5900 ArrayRef<QualType> getTypeArgs() const; 5901 5902 /// Retrieve the type arguments of this object type as they were 5903 /// written. 5904 ArrayRef<QualType> getTypeArgsAsWritten() const { 5905 return llvm::makeArrayRef(getTypeArgStorage(), 5906 ObjCObjectTypeBits.NumTypeArgs); 5907 } 5908 5909 /// Whether this is a "__kindof" type as written. 5910 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } 5911 5912 /// Whether this ia a "__kindof" type (semantically). 5913 bool isKindOfType() const; 5914 5915 /// Retrieve the type of the superclass of this object type. 5916 /// 5917 /// This operation substitutes any type arguments into the 5918 /// superclass of the current class type, potentially producing a 5919 /// specialization of the superclass type. Produces a null type if 5920 /// there is no superclass. 5921 QualType getSuperClassType() const { 5922 if (!CachedSuperClassType.getInt()) 5923 computeSuperClassTypeSlow(); 5924 5925 assert(CachedSuperClassType.getInt() && "Superclass not set?"); 5926 return QualType(CachedSuperClassType.getPointer(), 0); 5927 } 5928 5929 /// Strip off the Objective-C "kindof" type and (with it) any 5930 /// protocol qualifiers. 5931 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; 5932 5933 bool isSugared() const { return false; } 5934 QualType desugar() const { return QualType(this, 0); } 5935 5936 static bool classof(const Type *T) { 5937 return T->getTypeClass() == ObjCObject || 5938 T->getTypeClass() == ObjCInterface; 5939 } 5940 }; 5941 5942 /// A class providing a concrete implementation 5943 /// of ObjCObjectType, so as to not increase the footprint of 5944 /// ObjCInterfaceType. Code outside of ASTContext and the core type 5945 /// system should not reference this type. 5946 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { 5947 friend class ASTContext; 5948 5949 // If anyone adds fields here, ObjCObjectType::getProtocolStorage() 5950 // will need to be modified. 5951 5952 ObjCObjectTypeImpl(QualType Canonical, QualType Base, 5953 ArrayRef<QualType> typeArgs, 5954 ArrayRef<ObjCProtocolDecl *> protocols, 5955 bool isKindOf) 5956 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} 5957 5958 public: 5959 void Profile(llvm::FoldingSetNodeID &ID); 5960 static void Profile(llvm::FoldingSetNodeID &ID, 5961 QualType Base, 5962 ArrayRef<QualType> typeArgs, 5963 ArrayRef<ObjCProtocolDecl *> protocols, 5964 bool isKindOf); 5965 }; 5966 5967 inline QualType *ObjCObjectType::getTypeArgStorage() { 5968 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); 5969 } 5970 5971 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { 5972 return reinterpret_cast<ObjCProtocolDecl**>( 5973 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); 5974 } 5975 5976 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { 5977 return reinterpret_cast<ObjCProtocolDecl**>( 5978 static_cast<ObjCTypeParamType*>(this)+1); 5979 } 5980 5981 /// Interfaces are the core concept in Objective-C for object oriented design. 5982 /// They basically correspond to C++ classes. There are two kinds of interface 5983 /// types: normal interfaces like `NSString`, and qualified interfaces, which 5984 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. 5985 /// 5986 /// ObjCInterfaceType guarantees the following properties when considered 5987 /// as a subtype of its superclass, ObjCObjectType: 5988 /// - There are no protocol qualifiers. To reinforce this, code which 5989 /// tries to invoke the protocol methods via an ObjCInterfaceType will 5990 /// fail to compile. 5991 /// - It is its own base type. That is, if T is an ObjCInterfaceType*, 5992 /// T->getBaseType() == QualType(T, 0). 5993 class ObjCInterfaceType : public ObjCObjectType { 5994 friend class ASTContext; // ASTContext creates these. 5995 friend class ASTReader; 5996 friend class ObjCInterfaceDecl; 5997 template <class T> friend class serialization::AbstractTypeReader; 5998 5999 mutable ObjCInterfaceDecl *Decl; 6000 6001 ObjCInterfaceType(const ObjCInterfaceDecl *D) 6002 : ObjCObjectType(Nonce_ObjCInterface), 6003 Decl(const_cast<ObjCInterfaceDecl*>(D)) {} 6004 6005 public: 6006 /// Get the declaration of this interface. 6007 ObjCInterfaceDecl *getDecl() const { return Decl; } 6008 6009 bool isSugared() const { return false; } 6010 QualType desugar() const { return QualType(this, 0); } 6011 6012 static bool classof(const Type *T) { 6013 return T->getTypeClass() == ObjCInterface; 6014 } 6015 6016 // Nonsense to "hide" certain members of ObjCObjectType within this 6017 // class. People asking for protocols on an ObjCInterfaceType are 6018 // not going to get what they want: ObjCInterfaceTypes are 6019 // guaranteed to have no protocols. 6020 enum { 6021 qual_iterator, 6022 qual_begin, 6023 qual_end, 6024 getNumProtocols, 6025 getProtocol 6026 }; 6027 }; 6028 6029 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { 6030 QualType baseType = getBaseType(); 6031 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { 6032 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) 6033 return T->getDecl(); 6034 6035 baseType = ObjT->getBaseType(); 6036 } 6037 6038 return nullptr; 6039 } 6040 6041 /// Represents a pointer to an Objective C object. 6042 /// 6043 /// These are constructed from pointer declarators when the pointee type is 6044 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' 6045 /// types are typedefs for these, and the protocol-qualified types 'id<P>' 6046 /// and 'Class<P>' are translated into these. 6047 /// 6048 /// Pointers to pointers to Objective C objects are still PointerTypes; 6049 /// only the first level of pointer gets it own type implementation. 6050 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { 6051 friend class ASTContext; // ASTContext creates these. 6052 6053 QualType PointeeType; 6054 6055 ObjCObjectPointerType(QualType Canonical, QualType Pointee) 6056 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()), 6057 PointeeType(Pointee) {} 6058 6059 public: 6060 /// Gets the type pointed to by this ObjC pointer. 6061 /// The result will always be an ObjCObjectType or sugar thereof. 6062 QualType getPointeeType() const { return PointeeType; } 6063 6064 /// Gets the type pointed to by this ObjC pointer. Always returns non-null. 6065 /// 6066 /// This method is equivalent to getPointeeType() except that 6067 /// it discards any typedefs (or other sugar) between this 6068 /// type and the "outermost" object type. So for: 6069 /// \code 6070 /// \@class A; \@protocol P; \@protocol Q; 6071 /// typedef A<P> AP; 6072 /// typedef A A1; 6073 /// typedef A1<P> A1P; 6074 /// typedef A1P<Q> A1PQ; 6075 /// \endcode 6076 /// For 'A*', getObjectType() will return 'A'. 6077 /// For 'A<P>*', getObjectType() will return 'A<P>'. 6078 /// For 'AP*', getObjectType() will return 'A<P>'. 6079 /// For 'A1*', getObjectType() will return 'A'. 6080 /// For 'A1<P>*', getObjectType() will return 'A1<P>'. 6081 /// For 'A1P*', getObjectType() will return 'A1<P>'. 6082 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because 6083 /// adding protocols to a protocol-qualified base discards the 6084 /// old qualifiers (for now). But if it didn't, getObjectType() 6085 /// would return 'A1P<Q>' (and we'd have to make iterating over 6086 /// qualifiers more complicated). 6087 const ObjCObjectType *getObjectType() const { 6088 return PointeeType->castAs<ObjCObjectType>(); 6089 } 6090 6091 /// If this pointer points to an Objective C 6092 /// \@interface type, gets the type for that interface. Any protocol 6093 /// qualifiers on the interface are ignored. 6094 /// 6095 /// \return null if the base type for this pointer is 'id' or 'Class' 6096 const ObjCInterfaceType *getInterfaceType() const; 6097 6098 /// If this pointer points to an Objective \@interface 6099 /// type, gets the declaration for that interface. 6100 /// 6101 /// \return null if the base type for this pointer is 'id' or 'Class' 6102 ObjCInterfaceDecl *getInterfaceDecl() const { 6103 return getObjectType()->getInterface(); 6104 } 6105 6106 /// True if this is equivalent to the 'id' type, i.e. if 6107 /// its object type is the primitive 'id' type with no protocols. 6108 bool isObjCIdType() const { 6109 return getObjectType()->isObjCUnqualifiedId(); 6110 } 6111 6112 /// True if this is equivalent to the 'Class' type, 6113 /// i.e. if its object tive is the primitive 'Class' type with no protocols. 6114 bool isObjCClassType() const { 6115 return getObjectType()->isObjCUnqualifiedClass(); 6116 } 6117 6118 /// True if this is equivalent to the 'id' or 'Class' type, 6119 bool isObjCIdOrClassType() const { 6120 return getObjectType()->isObjCUnqualifiedIdOrClass(); 6121 } 6122 6123 /// True if this is equivalent to 'id<P>' for some non-empty set of 6124 /// protocols. 6125 bool isObjCQualifiedIdType() const { 6126 return getObjectType()->isObjCQualifiedId(); 6127 } 6128 6129 /// True if this is equivalent to 'Class<P>' for some non-empty set of 6130 /// protocols. 6131 bool isObjCQualifiedClassType() const { 6132 return getObjectType()->isObjCQualifiedClass(); 6133 } 6134 6135 /// Whether this is a "__kindof" type. 6136 bool isKindOfType() const { return getObjectType()->isKindOfType(); } 6137 6138 /// Whether this type is specialized, meaning that it has type arguments. 6139 bool isSpecialized() const { return getObjectType()->isSpecialized(); } 6140 6141 /// Whether this type is specialized, meaning that it has type arguments. 6142 bool isSpecializedAsWritten() const { 6143 return getObjectType()->isSpecializedAsWritten(); 6144 } 6145 6146 /// Whether this type is unspecialized, meaning that is has no type arguments. 6147 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } 6148 6149 /// Determine whether this object type is "unspecialized" as 6150 /// written, meaning that it has no type arguments. 6151 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } 6152 6153 /// Retrieve the type arguments for this type. 6154 ArrayRef<QualType> getTypeArgs() const { 6155 return getObjectType()->getTypeArgs(); 6156 } 6157 6158 /// Retrieve the type arguments for this type. 6159 ArrayRef<QualType> getTypeArgsAsWritten() const { 6160 return getObjectType()->getTypeArgsAsWritten(); 6161 } 6162 6163 /// An iterator over the qualifiers on the object type. Provided 6164 /// for convenience. This will always iterate over the full set of 6165 /// protocols on a type, not just those provided directly. 6166 using qual_iterator = ObjCObjectType::qual_iterator; 6167 using qual_range = llvm::iterator_range<qual_iterator>; 6168 6169 qual_range quals() const { return qual_range(qual_begin(), qual_end()); } 6170 6171 qual_iterator qual_begin() const { 6172 return getObjectType()->qual_begin(); 6173 } 6174 6175 qual_iterator qual_end() const { 6176 return getObjectType()->qual_end(); 6177 } 6178 6179 bool qual_empty() const { return getObjectType()->qual_empty(); } 6180 6181 /// Return the number of qualifying protocols on the object type. 6182 unsigned getNumProtocols() const { 6183 return getObjectType()->getNumProtocols(); 6184 } 6185 6186 /// Retrieve a qualifying protocol by index on the object type. 6187 ObjCProtocolDecl *getProtocol(unsigned I) const { 6188 return getObjectType()->getProtocol(I); 6189 } 6190 6191 bool isSugared() const { return false; } 6192 QualType desugar() const { return QualType(this, 0); } 6193 6194 /// Retrieve the type of the superclass of this object pointer type. 6195 /// 6196 /// This operation substitutes any type arguments into the 6197 /// superclass of the current class type, potentially producing a 6198 /// pointer to a specialization of the superclass type. Produces a 6199 /// null type if there is no superclass. 6200 QualType getSuperClassType() const; 6201 6202 /// Strip off the Objective-C "kindof" type and (with it) any 6203 /// protocol qualifiers. 6204 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( 6205 const ASTContext &ctx) const; 6206 6207 void Profile(llvm::FoldingSetNodeID &ID) { 6208 Profile(ID, getPointeeType()); 6209 } 6210 6211 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { 6212 ID.AddPointer(T.getAsOpaquePtr()); 6213 } 6214 6215 static bool classof(const Type *T) { 6216 return T->getTypeClass() == ObjCObjectPointer; 6217 } 6218 }; 6219 6220 class AtomicType : public Type, public llvm::FoldingSetNode { 6221 friend class ASTContext; // ASTContext creates these. 6222 6223 QualType ValueType; 6224 6225 AtomicType(QualType ValTy, QualType Canonical) 6226 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {} 6227 6228 public: 6229 /// Gets the type contained by this atomic type, i.e. 6230 /// the type returned by performing an atomic load of this atomic type. 6231 QualType getValueType() const { return ValueType; } 6232 6233 bool isSugared() const { return false; } 6234 QualType desugar() const { return QualType(this, 0); } 6235 6236 void Profile(llvm::FoldingSetNodeID &ID) { 6237 Profile(ID, getValueType()); 6238 } 6239 6240 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { 6241 ID.AddPointer(T.getAsOpaquePtr()); 6242 } 6243 6244 static bool classof(const Type *T) { 6245 return T->getTypeClass() == Atomic; 6246 } 6247 }; 6248 6249 /// PipeType - OpenCL20. 6250 class PipeType : public Type, public llvm::FoldingSetNode { 6251 friend class ASTContext; // ASTContext creates these. 6252 6253 QualType ElementType; 6254 bool isRead; 6255 6256 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) 6257 : Type(Pipe, CanonicalPtr, elemType->getDependence()), 6258 ElementType(elemType), isRead(isRead) {} 6259 6260 public: 6261 QualType getElementType() const { return ElementType; } 6262 6263 bool isSugared() const { return false; } 6264 6265 QualType desugar() const { return QualType(this, 0); } 6266 6267 void Profile(llvm::FoldingSetNodeID &ID) { 6268 Profile(ID, getElementType(), isReadOnly()); 6269 } 6270 6271 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { 6272 ID.AddPointer(T.getAsOpaquePtr()); 6273 ID.AddBoolean(isRead); 6274 } 6275 6276 static bool classof(const Type *T) { 6277 return T->getTypeClass() == Pipe; 6278 } 6279 6280 bool isReadOnly() const { return isRead; } 6281 }; 6282 6283 /// A fixed int type of a specified bitwidth. 6284 class ExtIntType final : public Type, public llvm::FoldingSetNode { 6285 friend class ASTContext; 6286 unsigned IsUnsigned : 1; 6287 unsigned NumBits : 24; 6288 6289 protected: 6290 ExtIntType(bool isUnsigned, unsigned NumBits); 6291 6292 public: 6293 bool isUnsigned() const { return IsUnsigned; } 6294 bool isSigned() const { return !IsUnsigned; } 6295 unsigned getNumBits() const { return NumBits; } 6296 6297 bool isSugared() const { return false; } 6298 QualType desugar() const { return QualType(this, 0); } 6299 6300 void Profile(llvm::FoldingSetNodeID &ID) { 6301 Profile(ID, isUnsigned(), getNumBits()); 6302 } 6303 6304 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned, 6305 unsigned NumBits) { 6306 ID.AddBoolean(IsUnsigned); 6307 ID.AddInteger(NumBits); 6308 } 6309 6310 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; } 6311 }; 6312 6313 class DependentExtIntType final : public Type, public llvm::FoldingSetNode { 6314 friend class ASTContext; 6315 const ASTContext &Context; 6316 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned; 6317 6318 protected: 6319 DependentExtIntType(const ASTContext &Context, bool IsUnsigned, 6320 Expr *NumBits); 6321 6322 public: 6323 bool isUnsigned() const; 6324 bool isSigned() const { return !isUnsigned(); } 6325 Expr *getNumBitsExpr() const; 6326 6327 bool isSugared() const { return false; } 6328 QualType desugar() const { return QualType(this, 0); } 6329 6330 void Profile(llvm::FoldingSetNodeID &ID) { 6331 Profile(ID, Context, isUnsigned(), getNumBitsExpr()); 6332 } 6333 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 6334 bool IsUnsigned, Expr *NumBitsExpr); 6335 6336 static bool classof(const Type *T) { 6337 return T->getTypeClass() == DependentExtInt; 6338 } 6339 }; 6340 6341 /// A qualifier set is used to build a set of qualifiers. 6342 class QualifierCollector : public Qualifiers { 6343 public: 6344 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} 6345 6346 /// Collect any qualifiers on the given type and return an 6347 /// unqualified type. The qualifiers are assumed to be consistent 6348 /// with those already in the type. 6349 const Type *strip(QualType type) { 6350 addFastQualifiers(type.getLocalFastQualifiers()); 6351 if (!type.hasLocalNonFastQualifiers()) 6352 return type.getTypePtrUnsafe(); 6353 6354 const ExtQuals *extQuals = type.getExtQualsUnsafe(); 6355 addConsistentQualifiers(extQuals->getQualifiers()); 6356 return extQuals->getBaseType(); 6357 } 6358 6359 /// Apply the collected qualifiers to the given type. 6360 QualType apply(const ASTContext &Context, QualType QT) const; 6361 6362 /// Apply the collected qualifiers to the given type. 6363 QualType apply(const ASTContext &Context, const Type* T) const; 6364 }; 6365 6366 /// A container of type source information. 6367 /// 6368 /// A client can read the relevant info using TypeLoc wrappers, e.g: 6369 /// @code 6370 /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); 6371 /// TL.getBeginLoc().print(OS, SrcMgr); 6372 /// @endcode 6373 class alignas(8) TypeSourceInfo { 6374 // Contains a memory block after the class, used for type source information, 6375 // allocated by ASTContext. 6376 friend class ASTContext; 6377 6378 QualType Ty; 6379 6380 TypeSourceInfo(QualType ty) : Ty(ty) {} 6381 6382 public: 6383 /// Return the type wrapped by this type source info. 6384 QualType getType() const { return Ty; } 6385 6386 /// Return the TypeLoc wrapper for the type source info. 6387 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h 6388 6389 /// Override the type stored in this TypeSourceInfo. Use with caution! 6390 void overrideType(QualType T) { Ty = T; } 6391 }; 6392 6393 // Inline function definitions. 6394 6395 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { 6396 SplitQualType desugar = 6397 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); 6398 desugar.Quals.addConsistentQualifiers(Quals); 6399 return desugar; 6400 } 6401 6402 inline const Type *QualType::getTypePtr() const { 6403 return getCommonPtr()->BaseType; 6404 } 6405 6406 inline const Type *QualType::getTypePtrOrNull() const { 6407 return (isNull() ? nullptr : getCommonPtr()->BaseType); 6408 } 6409 6410 inline SplitQualType QualType::split() const { 6411 if (!hasLocalNonFastQualifiers()) 6412 return SplitQualType(getTypePtrUnsafe(), 6413 Qualifiers::fromFastMask(getLocalFastQualifiers())); 6414 6415 const ExtQuals *eq = getExtQualsUnsafe(); 6416 Qualifiers qs = eq->getQualifiers(); 6417 qs.addFastQualifiers(getLocalFastQualifiers()); 6418 return SplitQualType(eq->getBaseType(), qs); 6419 } 6420 6421 inline Qualifiers QualType::getLocalQualifiers() const { 6422 Qualifiers Quals; 6423 if (hasLocalNonFastQualifiers()) 6424 Quals = getExtQualsUnsafe()->getQualifiers(); 6425 Quals.addFastQualifiers(getLocalFastQualifiers()); 6426 return Quals; 6427 } 6428 6429 inline Qualifiers QualType::getQualifiers() const { 6430 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); 6431 quals.addFastQualifiers(getLocalFastQualifiers()); 6432 return quals; 6433 } 6434 6435 inline unsigned QualType::getCVRQualifiers() const { 6436 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); 6437 cvr |= getLocalCVRQualifiers(); 6438 return cvr; 6439 } 6440 6441 inline QualType QualType::getCanonicalType() const { 6442 QualType canon = getCommonPtr()->CanonicalType; 6443 return canon.withFastQualifiers(getLocalFastQualifiers()); 6444 } 6445 6446 inline bool QualType::isCanonical() const { 6447 return getTypePtr()->isCanonicalUnqualified(); 6448 } 6449 6450 inline bool QualType::isCanonicalAsParam() const { 6451 if (!isCanonical()) return false; 6452 if (hasLocalQualifiers()) return false; 6453 6454 const Type *T = getTypePtr(); 6455 if (T->isVariablyModifiedType() && T->hasSizedVLAType()) 6456 return false; 6457 6458 return !isa<FunctionType>(T) && !isa<ArrayType>(T); 6459 } 6460 6461 inline bool QualType::isConstQualified() const { 6462 return isLocalConstQualified() || 6463 getCommonPtr()->CanonicalType.isLocalConstQualified(); 6464 } 6465 6466 inline bool QualType::isRestrictQualified() const { 6467 return isLocalRestrictQualified() || 6468 getCommonPtr()->CanonicalType.isLocalRestrictQualified(); 6469 } 6470 6471 6472 inline bool QualType::isVolatileQualified() const { 6473 return isLocalVolatileQualified() || 6474 getCommonPtr()->CanonicalType.isLocalVolatileQualified(); 6475 } 6476 6477 inline bool QualType::hasQualifiers() const { 6478 return hasLocalQualifiers() || 6479 getCommonPtr()->CanonicalType.hasLocalQualifiers(); 6480 } 6481 6482 inline QualType QualType::getUnqualifiedType() const { 6483 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) 6484 return QualType(getTypePtr(), 0); 6485 6486 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); 6487 } 6488 6489 inline SplitQualType QualType::getSplitUnqualifiedType() const { 6490 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) 6491 return split(); 6492 6493 return getSplitUnqualifiedTypeImpl(*this); 6494 } 6495 6496 inline void QualType::removeLocalConst() { 6497 removeLocalFastQualifiers(Qualifiers::Const); 6498 } 6499 6500 inline void QualType::removeLocalRestrict() { 6501 removeLocalFastQualifiers(Qualifiers::Restrict); 6502 } 6503 6504 inline void QualType::removeLocalVolatile() { 6505 removeLocalFastQualifiers(Qualifiers::Volatile); 6506 } 6507 6508 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { 6509 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"); 6510 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, 6511 "Fast bits differ from CVR bits!"); 6512 6513 // Fast path: we don't need to touch the slow qualifiers. 6514 removeLocalFastQualifiers(Mask); 6515 } 6516 6517 /// Check if this type has any address space qualifier. 6518 inline bool QualType::hasAddressSpace() const { 6519 return getQualifiers().hasAddressSpace(); 6520 } 6521 6522 /// Return the address space of this type. 6523 inline LangAS QualType::getAddressSpace() const { 6524 return getQualifiers().getAddressSpace(); 6525 } 6526 6527 /// Return the gc attribute of this type. 6528 inline Qualifiers::GC QualType::getObjCGCAttr() const { 6529 return getQualifiers().getObjCGCAttr(); 6530 } 6531 6532 inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { 6533 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) 6534 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); 6535 return false; 6536 } 6537 6538 inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { 6539 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) 6540 return hasNonTrivialToPrimitiveDestructCUnion(RD); 6541 return false; 6542 } 6543 6544 inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { 6545 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) 6546 return hasNonTrivialToPrimitiveCopyCUnion(RD); 6547 return false; 6548 } 6549 6550 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { 6551 if (const auto *PT = t.getAs<PointerType>()) { 6552 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) 6553 return FT->getExtInfo(); 6554 } else if (const auto *FT = t.getAs<FunctionType>()) 6555 return FT->getExtInfo(); 6556 6557 return FunctionType::ExtInfo(); 6558 } 6559 6560 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { 6561 return getFunctionExtInfo(*t); 6562 } 6563 6564 /// Determine whether this type is more 6565 /// qualified than the Other type. For example, "const volatile int" 6566 /// is more qualified than "const int", "volatile int", and 6567 /// "int". However, it is not more qualified than "const volatile 6568 /// int". 6569 inline bool QualType::isMoreQualifiedThan(QualType other) const { 6570 Qualifiers MyQuals = getQualifiers(); 6571 Qualifiers OtherQuals = other.getQualifiers(); 6572 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); 6573 } 6574 6575 /// Determine whether this type is at last 6576 /// as qualified as the Other type. For example, "const volatile 6577 /// int" is at least as qualified as "const int", "volatile int", 6578 /// "int", and "const volatile int". 6579 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { 6580 Qualifiers OtherQuals = other.getQualifiers(); 6581 6582 // Ignore __unaligned qualifier if this type is a void. 6583 if (getUnqualifiedType()->isVoidType()) 6584 OtherQuals.removeUnaligned(); 6585 6586 return getQualifiers().compatiblyIncludes(OtherQuals); 6587 } 6588 6589 /// If Type is a reference type (e.g., const 6590 /// int&), returns the type that the reference refers to ("const 6591 /// int"). Otherwise, returns the type itself. This routine is used 6592 /// throughout Sema to implement C++ 5p6: 6593 /// 6594 /// If an expression initially has the type "reference to T" (8.3.2, 6595 /// 8.5.3), the type is adjusted to "T" prior to any further 6596 /// analysis, the expression designates the object or function 6597 /// denoted by the reference, and the expression is an lvalue. 6598 inline QualType QualType::getNonReferenceType() const { 6599 if (const auto *RefType = (*this)->getAs<ReferenceType>()) 6600 return RefType->getPointeeType(); 6601 else 6602 return *this; 6603 } 6604 6605 inline bool QualType::isCForbiddenLValueType() const { 6606 return ((getTypePtr()->isVoidType() && !hasQualifiers()) || 6607 getTypePtr()->isFunctionType()); 6608 } 6609 6610 /// Tests whether the type is categorized as a fundamental type. 6611 /// 6612 /// \returns True for types specified in C++0x [basic.fundamental]. 6613 inline bool Type::isFundamentalType() const { 6614 return isVoidType() || 6615 isNullPtrType() || 6616 // FIXME: It's really annoying that we don't have an 6617 // 'isArithmeticType()' which agrees with the standard definition. 6618 (isArithmeticType() && !isEnumeralType()); 6619 } 6620 6621 /// Tests whether the type is categorized as a compound type. 6622 /// 6623 /// \returns True for types specified in C++0x [basic.compound]. 6624 inline bool Type::isCompoundType() const { 6625 // C++0x [basic.compound]p1: 6626 // Compound types can be constructed in the following ways: 6627 // -- arrays of objects of a given type [...]; 6628 return isArrayType() || 6629 // -- functions, which have parameters of given types [...]; 6630 isFunctionType() || 6631 // -- pointers to void or objects or functions [...]; 6632 isPointerType() || 6633 // -- references to objects or functions of a given type. [...] 6634 isReferenceType() || 6635 // -- classes containing a sequence of objects of various types, [...]; 6636 isRecordType() || 6637 // -- unions, which are classes capable of containing objects of different 6638 // types at different times; 6639 isUnionType() || 6640 // -- enumerations, which comprise a set of named constant values. [...]; 6641 isEnumeralType() || 6642 // -- pointers to non-static class members, [...]. 6643 isMemberPointerType(); 6644 } 6645 6646 inline bool Type::isFunctionType() const { 6647 return isa<FunctionType>(CanonicalType); 6648 } 6649 6650 inline bool Type::isPointerType() const { 6651 return isa<PointerType>(CanonicalType); 6652 } 6653 6654 inline bool Type::isAnyPointerType() const { 6655 return isPointerType() || isObjCObjectPointerType(); 6656 } 6657 6658 inline bool Type::isBlockPointerType() const { 6659 return isa<BlockPointerType>(CanonicalType); 6660 } 6661 6662 inline bool Type::isReferenceType() const { 6663 return isa<ReferenceType>(CanonicalType); 6664 } 6665 6666 inline bool Type::isLValueReferenceType() const { 6667 return isa<LValueReferenceType>(CanonicalType); 6668 } 6669 6670 inline bool Type::isRValueReferenceType() const { 6671 return isa<RValueReferenceType>(CanonicalType); 6672 } 6673 6674 inline bool Type::isObjectPointerType() const { 6675 // Note: an "object pointer type" is not the same thing as a pointer to an 6676 // object type; rather, it is a pointer to an object type or a pointer to cv 6677 // void. 6678 if (const auto *T = getAs<PointerType>()) 6679 return !T->getPointeeType()->isFunctionType(); 6680 else 6681 return false; 6682 } 6683 6684 inline bool Type::isFunctionPointerType() const { 6685 if (const auto *T = getAs<PointerType>()) 6686 return T->getPointeeType()->isFunctionType(); 6687 else 6688 return false; 6689 } 6690 6691 inline bool Type::isFunctionReferenceType() const { 6692 if (const auto *T = getAs<ReferenceType>()) 6693 return T->getPointeeType()->isFunctionType(); 6694 else 6695 return false; 6696 } 6697 6698 inline bool Type::isMemberPointerType() const { 6699 return isa<MemberPointerType>(CanonicalType); 6700 } 6701 6702 inline bool Type::isMemberFunctionPointerType() const { 6703 if (const auto *T = getAs<MemberPointerType>()) 6704 return T->isMemberFunctionPointer(); 6705 else 6706 return false; 6707 } 6708 6709 inline bool Type::isMemberDataPointerType() const { 6710 if (const auto *T = getAs<MemberPointerType>()) 6711 return T->isMemberDataPointer(); 6712 else 6713 return false; 6714 } 6715 6716 inline bool Type::isArrayType() const { 6717 return isa<ArrayType>(CanonicalType); 6718 } 6719 6720 inline bool Type::isConstantArrayType() const { 6721 return isa<ConstantArrayType>(CanonicalType); 6722 } 6723 6724 inline bool Type::isIncompleteArrayType() const { 6725 return isa<IncompleteArrayType>(CanonicalType); 6726 } 6727 6728 inline bool Type::isVariableArrayType() const { 6729 return isa<VariableArrayType>(CanonicalType); 6730 } 6731 6732 inline bool Type::isDependentSizedArrayType() const { 6733 return isa<DependentSizedArrayType>(CanonicalType); 6734 } 6735 6736 inline bool Type::isBuiltinType() const { 6737 return isa<BuiltinType>(CanonicalType); 6738 } 6739 6740 inline bool Type::isRecordType() const { 6741 return isa<RecordType>(CanonicalType); 6742 } 6743 6744 inline bool Type::isEnumeralType() const { 6745 return isa<EnumType>(CanonicalType); 6746 } 6747 6748 inline bool Type::isAnyComplexType() const { 6749 return isa<ComplexType>(CanonicalType); 6750 } 6751 6752 inline bool Type::isVectorType() const { 6753 return isa<VectorType>(CanonicalType); 6754 } 6755 6756 inline bool Type::isExtVectorType() const { 6757 return isa<ExtVectorType>(CanonicalType); 6758 } 6759 6760 inline bool Type::isMatrixType() const { 6761 return isa<MatrixType>(CanonicalType); 6762 } 6763 6764 inline bool Type::isConstantMatrixType() const { 6765 return isa<ConstantMatrixType>(CanonicalType); 6766 } 6767 6768 inline bool Type::isDependentAddressSpaceType() const { 6769 return isa<DependentAddressSpaceType>(CanonicalType); 6770 } 6771 6772 inline bool Type::isObjCObjectPointerType() const { 6773 return isa<ObjCObjectPointerType>(CanonicalType); 6774 } 6775 6776 inline bool Type::isObjCObjectType() const { 6777 return isa<ObjCObjectType>(CanonicalType); 6778 } 6779 6780 inline bool Type::isObjCObjectOrInterfaceType() const { 6781 return isa<ObjCInterfaceType>(CanonicalType) || 6782 isa<ObjCObjectType>(CanonicalType); 6783 } 6784 6785 inline bool Type::isAtomicType() const { 6786 return isa<AtomicType>(CanonicalType); 6787 } 6788 6789 inline bool Type::isUndeducedAutoType() const { 6790 return isa<AutoType>(CanonicalType); 6791 } 6792 6793 inline bool Type::isObjCQualifiedIdType() const { 6794 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6795 return OPT->isObjCQualifiedIdType(); 6796 return false; 6797 } 6798 6799 inline bool Type::isObjCQualifiedClassType() const { 6800 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6801 return OPT->isObjCQualifiedClassType(); 6802 return false; 6803 } 6804 6805 inline bool Type::isObjCIdType() const { 6806 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6807 return OPT->isObjCIdType(); 6808 return false; 6809 } 6810 6811 inline bool Type::isObjCClassType() const { 6812 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6813 return OPT->isObjCClassType(); 6814 return false; 6815 } 6816 6817 inline bool Type::isObjCSelType() const { 6818 if (const auto *OPT = getAs<PointerType>()) 6819 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); 6820 return false; 6821 } 6822 6823 inline bool Type::isObjCBuiltinType() const { 6824 return isObjCIdType() || isObjCClassType() || isObjCSelType(); 6825 } 6826 6827 inline bool Type::isDecltypeType() const { 6828 return isa<DecltypeType>(this); 6829 } 6830 6831 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6832 inline bool Type::is##Id##Type() const { \ 6833 return isSpecificBuiltinType(BuiltinType::Id); \ 6834 } 6835 #include "clang/Basic/OpenCLImageTypes.def" 6836 6837 inline bool Type::isSamplerT() const { 6838 return isSpecificBuiltinType(BuiltinType::OCLSampler); 6839 } 6840 6841 inline bool Type::isEventT() const { 6842 return isSpecificBuiltinType(BuiltinType::OCLEvent); 6843 } 6844 6845 inline bool Type::isClkEventT() const { 6846 return isSpecificBuiltinType(BuiltinType::OCLClkEvent); 6847 } 6848 6849 inline bool Type::isQueueT() const { 6850 return isSpecificBuiltinType(BuiltinType::OCLQueue); 6851 } 6852 6853 inline bool Type::isReserveIDT() const { 6854 return isSpecificBuiltinType(BuiltinType::OCLReserveID); 6855 } 6856 6857 inline bool Type::isImageType() const { 6858 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || 6859 return 6860 #include "clang/Basic/OpenCLImageTypes.def" 6861 false; // end boolean or operation 6862 } 6863 6864 inline bool Type::isPipeType() const { 6865 return isa<PipeType>(CanonicalType); 6866 } 6867 6868 inline bool Type::isExtIntType() const { 6869 return isa<ExtIntType>(CanonicalType); 6870 } 6871 6872 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6873 inline bool Type::is##Id##Type() const { \ 6874 return isSpecificBuiltinType(BuiltinType::Id); \ 6875 } 6876 #include "clang/Basic/OpenCLExtensionTypes.def" 6877 6878 inline bool Type::isOCLIntelSubgroupAVCType() const { 6879 #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ 6880 isOCLIntelSubgroupAVC##Id##Type() || 6881 return 6882 #include "clang/Basic/OpenCLExtensionTypes.def" 6883 false; // end of boolean or operation 6884 } 6885 6886 inline bool Type::isOCLExtOpaqueType() const { 6887 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || 6888 return 6889 #include "clang/Basic/OpenCLExtensionTypes.def" 6890 false; // end of boolean or operation 6891 } 6892 6893 inline bool Type::isOpenCLSpecificType() const { 6894 return isSamplerT() || isEventT() || isImageType() || isClkEventT() || 6895 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); 6896 } 6897 6898 inline bool Type::isTemplateTypeParmType() const { 6899 return isa<TemplateTypeParmType>(CanonicalType); 6900 } 6901 6902 inline bool Type::isSpecificBuiltinType(unsigned K) const { 6903 if (const BuiltinType *BT = getAs<BuiltinType>()) { 6904 return BT->getKind() == static_cast<BuiltinType::Kind>(K); 6905 } 6906 return false; 6907 } 6908 6909 inline bool Type::isPlaceholderType() const { 6910 if (const auto *BT = dyn_cast<BuiltinType>(this)) 6911 return BT->isPlaceholderType(); 6912 return false; 6913 } 6914 6915 inline const BuiltinType *Type::getAsPlaceholderType() const { 6916 if (const auto *BT = dyn_cast<BuiltinType>(this)) 6917 if (BT->isPlaceholderType()) 6918 return BT; 6919 return nullptr; 6920 } 6921 6922 inline bool Type::isSpecificPlaceholderType(unsigned K) const { 6923 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)); 6924 return isSpecificBuiltinType(K); 6925 } 6926 6927 inline bool Type::isNonOverloadPlaceholderType() const { 6928 if (const auto *BT = dyn_cast<BuiltinType>(this)) 6929 return BT->isNonOverloadPlaceholderType(); 6930 return false; 6931 } 6932 6933 inline bool Type::isVoidType() const { 6934 return isSpecificBuiltinType(BuiltinType::Void); 6935 } 6936 6937 inline bool Type::isHalfType() const { 6938 // FIXME: Should we allow complex __fp16? Probably not. 6939 return isSpecificBuiltinType(BuiltinType::Half); 6940 } 6941 6942 inline bool Type::isFloat16Type() const { 6943 return isSpecificBuiltinType(BuiltinType::Float16); 6944 } 6945 6946 inline bool Type::isBFloat16Type() const { 6947 return isSpecificBuiltinType(BuiltinType::BFloat16); 6948 } 6949 6950 inline bool Type::isFloat128Type() const { 6951 return isSpecificBuiltinType(BuiltinType::Float128); 6952 } 6953 6954 inline bool Type::isNullPtrType() const { 6955 return isSpecificBuiltinType(BuiltinType::NullPtr); 6956 } 6957 6958 bool IsEnumDeclComplete(EnumDecl *); 6959 bool IsEnumDeclScoped(EnumDecl *); 6960 6961 inline bool Type::isIntegerType() const { 6962 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 6963 return BT->getKind() >= BuiltinType::Bool && 6964 BT->getKind() <= BuiltinType::Int128; 6965 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 6966 // Incomplete enum types are not treated as integer types. 6967 // FIXME: In C++, enum types are never integer types. 6968 return IsEnumDeclComplete(ET->getDecl()) && 6969 !IsEnumDeclScoped(ET->getDecl()); 6970 } 6971 return isExtIntType(); 6972 } 6973 6974 inline bool Type::isFixedPointType() const { 6975 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 6976 return BT->getKind() >= BuiltinType::ShortAccum && 6977 BT->getKind() <= BuiltinType::SatULongFract; 6978 } 6979 return false; 6980 } 6981 6982 inline bool Type::isFixedPointOrIntegerType() const { 6983 return isFixedPointType() || isIntegerType(); 6984 } 6985 6986 inline bool Type::isSaturatedFixedPointType() const { 6987 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 6988 return BT->getKind() >= BuiltinType::SatShortAccum && 6989 BT->getKind() <= BuiltinType::SatULongFract; 6990 } 6991 return false; 6992 } 6993 6994 inline bool Type::isUnsaturatedFixedPointType() const { 6995 return isFixedPointType() && !isSaturatedFixedPointType(); 6996 } 6997 6998 inline bool Type::isSignedFixedPointType() const { 6999 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 7000 return ((BT->getKind() >= BuiltinType::ShortAccum && 7001 BT->getKind() <= BuiltinType::LongAccum) || 7002 (BT->getKind() >= BuiltinType::ShortFract && 7003 BT->getKind() <= BuiltinType::LongFract) || 7004 (BT->getKind() >= BuiltinType::SatShortAccum && 7005 BT->getKind() <= BuiltinType::SatLongAccum) || 7006 (BT->getKind() >= BuiltinType::SatShortFract && 7007 BT->getKind() <= BuiltinType::SatLongFract)); 7008 } 7009 return false; 7010 } 7011 7012 inline bool Type::isUnsignedFixedPointType() const { 7013 return isFixedPointType() && !isSignedFixedPointType(); 7014 } 7015 7016 inline bool Type::isScalarType() const { 7017 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7018 return BT->getKind() > BuiltinType::Void && 7019 BT->getKind() <= BuiltinType::NullPtr; 7020 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 7021 // Enums are scalar types, but only if they are defined. Incomplete enums 7022 // are not treated as scalar types. 7023 return IsEnumDeclComplete(ET->getDecl()); 7024 return isa<PointerType>(CanonicalType) || 7025 isa<BlockPointerType>(CanonicalType) || 7026 isa<MemberPointerType>(CanonicalType) || 7027 isa<ComplexType>(CanonicalType) || 7028 isa<ObjCObjectPointerType>(CanonicalType) || 7029 isExtIntType(); 7030 } 7031 7032 inline bool Type::isIntegralOrEnumerationType() const { 7033 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7034 return BT->getKind() >= BuiltinType::Bool && 7035 BT->getKind() <= BuiltinType::Int128; 7036 7037 // Check for a complete enum type; incomplete enum types are not properly an 7038 // enumeration type in the sense required here. 7039 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 7040 return IsEnumDeclComplete(ET->getDecl()); 7041 7042 return isExtIntType(); 7043 } 7044 7045 inline bool Type::isBooleanType() const { 7046 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7047 return BT->getKind() == BuiltinType::Bool; 7048 return false; 7049 } 7050 7051 inline bool Type::isUndeducedType() const { 7052 auto *DT = getContainedDeducedType(); 7053 return DT && !DT->isDeduced(); 7054 } 7055 7056 /// Determines whether this is a type for which one can define 7057 /// an overloaded operator. 7058 inline bool Type::isOverloadableType() const { 7059 return isDependentType() || isRecordType() || isEnumeralType(); 7060 } 7061 7062 /// Determines whether this type can decay to a pointer type. 7063 inline bool Type::canDecayToPointerType() const { 7064 return isFunctionType() || isArrayType(); 7065 } 7066 7067 inline bool Type::hasPointerRepresentation() const { 7068 return (isPointerType() || isReferenceType() || isBlockPointerType() || 7069 isObjCObjectPointerType() || isNullPtrType()); 7070 } 7071 7072 inline bool Type::hasObjCPointerRepresentation() const { 7073 return isObjCObjectPointerType(); 7074 } 7075 7076 inline const Type *Type::getBaseElementTypeUnsafe() const { 7077 const Type *type = this; 7078 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) 7079 type = arrayType->getElementType().getTypePtr(); 7080 return type; 7081 } 7082 7083 inline const Type *Type::getPointeeOrArrayElementType() const { 7084 const Type *type = this; 7085 if (type->isAnyPointerType()) 7086 return type->getPointeeType().getTypePtr(); 7087 else if (type->isArrayType()) 7088 return type->getBaseElementTypeUnsafe(); 7089 return type; 7090 } 7091 /// Insertion operator for diagnostics. This allows sending address spaces into 7092 /// a diagnostic with <<. 7093 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 7094 LangAS AS) { 7095 DB.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), 7096 DiagnosticsEngine::ArgumentKind::ak_addrspace); 7097 return DB; 7098 } 7099 7100 /// Insertion operator for partial diagnostics. This allows sending adress 7101 /// spaces into a diagnostic with <<. 7102 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, 7103 LangAS AS) { 7104 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), 7105 DiagnosticsEngine::ArgumentKind::ak_addrspace); 7106 return PD; 7107 } 7108 7109 /// Insertion operator for diagnostics. This allows sending Qualifiers into a 7110 /// diagnostic with <<. 7111 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 7112 Qualifiers Q) { 7113 DB.AddTaggedVal(Q.getAsOpaqueValue(), 7114 DiagnosticsEngine::ArgumentKind::ak_qual); 7115 return DB; 7116 } 7117 7118 /// Insertion operator for partial diagnostics. This allows sending Qualifiers 7119 /// into a diagnostic with <<. 7120 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, 7121 Qualifiers Q) { 7122 PD.AddTaggedVal(Q.getAsOpaqueValue(), 7123 DiagnosticsEngine::ArgumentKind::ak_qual); 7124 return PD; 7125 } 7126 7127 /// Insertion operator for diagnostics. This allows sending QualType's into a 7128 /// diagnostic with <<. 7129 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 7130 QualType T) { 7131 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), 7132 DiagnosticsEngine::ak_qualtype); 7133 return DB; 7134 } 7135 7136 /// Insertion operator for partial diagnostics. This allows sending QualType's 7137 /// into a diagnostic with <<. 7138 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, 7139 QualType T) { 7140 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), 7141 DiagnosticsEngine::ak_qualtype); 7142 return PD; 7143 } 7144 7145 // Helper class template that is used by Type::getAs to ensure that one does 7146 // not try to look through a qualified type to get to an array type. 7147 template <typename T> 7148 using TypeIsArrayType = 7149 std::integral_constant<bool, std::is_same<T, ArrayType>::value || 7150 std::is_base_of<ArrayType, T>::value>; 7151 7152 // Member-template getAs<specific type>'. 7153 template <typename T> const T *Type::getAs() const { 7154 static_assert(!TypeIsArrayType<T>::value, 7155 "ArrayType cannot be used with getAs!"); 7156 7157 // If this is directly a T type, return it. 7158 if (const auto *Ty = dyn_cast<T>(this)) 7159 return Ty; 7160 7161 // If the canonical form of this type isn't the right kind, reject it. 7162 if (!isa<T>(CanonicalType)) 7163 return nullptr; 7164 7165 // If this is a typedef for the type, strip the typedef off without 7166 // losing all typedef information. 7167 return cast<T>(getUnqualifiedDesugaredType()); 7168 } 7169 7170 template <typename T> const T *Type::getAsAdjusted() const { 7171 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); 7172 7173 // If this is directly a T type, return it. 7174 if (const auto *Ty = dyn_cast<T>(this)) 7175 return Ty; 7176 7177 // If the canonical form of this type isn't the right kind, reject it. 7178 if (!isa<T>(CanonicalType)) 7179 return nullptr; 7180 7181 // Strip off type adjustments that do not modify the underlying nature of the 7182 // type. 7183 const Type *Ty = this; 7184 while (Ty) { 7185 if (const auto *A = dyn_cast<AttributedType>(Ty)) 7186 Ty = A->getModifiedType().getTypePtr(); 7187 else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) 7188 Ty = E->desugar().getTypePtr(); 7189 else if (const auto *P = dyn_cast<ParenType>(Ty)) 7190 Ty = P->desugar().getTypePtr(); 7191 else if (const auto *A = dyn_cast<AdjustedType>(Ty)) 7192 Ty = A->desugar().getTypePtr(); 7193 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) 7194 Ty = M->desugar().getTypePtr(); 7195 else 7196 break; 7197 } 7198 7199 // Just because the canonical type is correct does not mean we can use cast<>, 7200 // since we may not have stripped off all the sugar down to the base type. 7201 return dyn_cast<T>(Ty); 7202 } 7203 7204 inline const ArrayType *Type::getAsArrayTypeUnsafe() const { 7205 // If this is directly an array type, return it. 7206 if (const auto *arr = dyn_cast<ArrayType>(this)) 7207 return arr; 7208 7209 // If the canonical form of this type isn't the right kind, reject it. 7210 if (!isa<ArrayType>(CanonicalType)) 7211 return nullptr; 7212 7213 // If this is a typedef for the type, strip the typedef off without 7214 // losing all typedef information. 7215 return cast<ArrayType>(getUnqualifiedDesugaredType()); 7216 } 7217 7218 template <typename T> const T *Type::castAs() const { 7219 static_assert(!TypeIsArrayType<T>::value, 7220 "ArrayType cannot be used with castAs!"); 7221 7222 if (const auto *ty = dyn_cast<T>(this)) return ty; 7223 assert(isa<T>(CanonicalType)); 7224 return cast<T>(getUnqualifiedDesugaredType()); 7225 } 7226 7227 inline const ArrayType *Type::castAsArrayTypeUnsafe() const { 7228 assert(isa<ArrayType>(CanonicalType)); 7229 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; 7230 return cast<ArrayType>(getUnqualifiedDesugaredType()); 7231 } 7232 7233 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, 7234 QualType CanonicalPtr) 7235 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { 7236 #ifndef NDEBUG 7237 QualType Adjusted = getAdjustedType(); 7238 (void)AttributedType::stripOuterNullability(Adjusted); 7239 assert(isa<PointerType>(Adjusted)); 7240 #endif 7241 } 7242 7243 QualType DecayedType::getPointeeType() const { 7244 QualType Decayed = getDecayedType(); 7245 (void)AttributedType::stripOuterNullability(Decayed); 7246 return cast<PointerType>(Decayed)->getPointeeType(); 7247 } 7248 7249 // Get the decimal string representation of a fixed point type, represented 7250 // as a scaled integer. 7251 // TODO: At some point, we should change the arguments to instead just accept an 7252 // APFixedPoint instead of APSInt and scale. 7253 void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, 7254 unsigned Scale); 7255 7256 } // namespace clang 7257 7258 #endif // LLVM_CLANG_AST_TYPE_H 7259