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