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