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