xref: /llvm-project-15.0.7/clang/lib/AST/Type.cpp (revision f489e2bf)
1 //===- Type.cpp - Type representation and manipulation --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements type-related functionality.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Type.h"
15 #include "Linkage.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/TemplateBase.h"
28 #include "clang/AST/TemplateName.h"
29 #include "clang/AST/TypeVisitor.h"
30 #include "clang/Basic/AddressSpaces.h"
31 #include "clang/Basic/ExceptionSpecificationType.h"
32 #include "clang/Basic/IdentifierTable.h"
33 #include "clang/Basic/LLVM.h"
34 #include "clang/Basic/LangOptions.h"
35 #include "clang/Basic/Linkage.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetCXXABI.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Visibility.h"
40 #include "llvm/ADT/APInt.h"
41 #include "llvm/ADT/APSInt.h"
42 #include "llvm/ADT/ArrayRef.h"
43 #include "llvm/ADT/FoldingSet.h"
44 #include "llvm/ADT/None.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <cstring>
53 
54 using namespace clang;
55 
56 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
57   return (*this != Other) &&
58     // CVR qualifiers superset
59     (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
60     // ObjC GC qualifiers superset
61     ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
62      (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
63     // Address space superset.
64     ((getAddressSpace() == Other.getAddressSpace()) ||
65      (hasAddressSpace()&& !Other.hasAddressSpace())) &&
66     // Lifetime qualifier superset.
67     ((getObjCLifetime() == Other.getObjCLifetime()) ||
68      (hasObjCLifetime() && !Other.hasObjCLifetime()));
69 }
70 
71 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
72   const Type* ty = getTypePtr();
73   NamedDecl *ND = nullptr;
74   if (ty->isPointerType() || ty->isReferenceType())
75     return ty->getPointeeType().getBaseTypeIdentifier();
76   else if (ty->isRecordType())
77     ND = ty->getAs<RecordType>()->getDecl();
78   else if (ty->isEnumeralType())
79     ND = ty->getAs<EnumType>()->getDecl();
80   else if (ty->getTypeClass() == Type::Typedef)
81     ND = ty->getAs<TypedefType>()->getDecl();
82   else if (ty->isArrayType())
83     return ty->castAsArrayTypeUnsafe()->
84         getElementType().getBaseTypeIdentifier();
85 
86   if (ND)
87     return ND->getIdentifier();
88   return nullptr;
89 }
90 
91 bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
92   if (T.isConstQualified())
93     return true;
94 
95   if (const ArrayType *AT = Ctx.getAsArrayType(T))
96     return AT->getElementType().isConstant(Ctx);
97 
98   return T.getAddressSpace() == LangAS::opencl_constant;
99 }
100 
101 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
102                                                  QualType ElementType,
103                                                const llvm::APInt &NumElements) {
104   uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
105 
106   // Fast path the common cases so we can avoid the conservative computation
107   // below, which in common cases allocates "large" APSInt values, which are
108   // slow.
109 
110   // If the element size is a power of 2, we can directly compute the additional
111   // number of addressing bits beyond those required for the element count.
112   if (llvm::isPowerOf2_64(ElementSize)) {
113     return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
114   }
115 
116   // If both the element count and element size fit in 32-bits, we can do the
117   // computation directly in 64-bits.
118   if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
119       (NumElements.getZExtValue() >> 32) == 0) {
120     uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
121     return 64 - llvm::countLeadingZeros(TotalSize);
122   }
123 
124   // Otherwise, use APSInt to handle arbitrary sized values.
125   llvm::APSInt SizeExtended(NumElements, true);
126   unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
127   SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
128                                               SizeExtended.getBitWidth()) * 2);
129 
130   llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
131   TotalSize *= SizeExtended;
132 
133   return TotalSize.getActiveBits();
134 }
135 
136 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
137   unsigned Bits = Context.getTypeSize(Context.getSizeType());
138 
139   // Limit the number of bits in size_t so that maximal bit size fits 64 bit
140   // integer (see PR8256).  We can do this as currently there is no hardware
141   // that supports full 64-bit virtual space.
142   if (Bits > 61)
143     Bits = 61;
144 
145   return Bits;
146 }
147 
148 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
149                                                  QualType et, QualType can,
150                                                  Expr *e, ArraySizeModifier sm,
151                                                  unsigned tq,
152                                                  SourceRange brackets)
153     : ArrayType(DependentSizedArray, et, can, sm, tq,
154                 (et->containsUnexpandedParameterPack() ||
155                  (e && e->containsUnexpandedParameterPack()))),
156       Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
157 
158 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
159                                       const ASTContext &Context,
160                                       QualType ET,
161                                       ArraySizeModifier SizeMod,
162                                       unsigned TypeQuals,
163                                       Expr *E) {
164   ID.AddPointer(ET.getAsOpaquePtr());
165   ID.AddInteger(SizeMod);
166   ID.AddInteger(TypeQuals);
167   E->Profile(ID, Context, true);
168 }
169 
170 DependentSizedExtVectorType::DependentSizedExtVectorType(const
171                                                          ASTContext &Context,
172                                                          QualType ElementType,
173                                                          QualType can,
174                                                          Expr *SizeExpr,
175                                                          SourceLocation loc)
176     : Type(DependentSizedExtVector, can, /*Dependent=*/true,
177            /*InstantiationDependent=*/true,
178            ElementType->isVariablyModifiedType(),
179            (ElementType->containsUnexpandedParameterPack() ||
180             (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
181       Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
182       loc(loc) {}
183 
184 void
185 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
186                                      const ASTContext &Context,
187                                      QualType ElementType, Expr *SizeExpr) {
188   ID.AddPointer(ElementType.getAsOpaquePtr());
189   SizeExpr->Profile(ID, Context, true);
190 }
191 
192 DependentAddressSpaceType::DependentAddressSpaceType(
193     const ASTContext &Context, QualType PointeeType, QualType can,
194     Expr *AddrSpaceExpr, SourceLocation loc)
195     : Type(DependentAddressSpace, can, /*Dependent=*/true,
196            /*InstantiationDependent=*/true,
197            PointeeType->isVariablyModifiedType(),
198            (PointeeType->containsUnexpandedParameterPack() ||
199             (AddrSpaceExpr &&
200              AddrSpaceExpr->containsUnexpandedParameterPack()))),
201       Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
202       loc(loc) {}
203 
204 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
205                                         const ASTContext &Context,
206                                         QualType PointeeType,
207                                         Expr *AddrSpaceExpr) {
208   ID.AddPointer(PointeeType.getAsOpaquePtr());
209   AddrSpaceExpr->Profile(ID, Context, true);
210 }
211 
212 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
213                        VectorKind vecKind)
214     : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
215 
216 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
217                        QualType canonType, VectorKind vecKind)
218     : Type(tc, canonType, vecType->isDependentType(),
219            vecType->isInstantiationDependentType(),
220            vecType->isVariablyModifiedType(),
221            vecType->containsUnexpandedParameterPack()),
222       ElementType(vecType) {
223   VectorTypeBits.VecKind = vecKind;
224   VectorTypeBits.NumElements = nElements;
225 }
226 
227 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
228 /// element type of the array, potentially with type qualifiers missing.
229 /// This method should never be used when type qualifiers are meaningful.
230 const Type *Type::getArrayElementTypeNoTypeQual() const {
231   // If this is directly an array type, return it.
232   if (const auto *ATy = dyn_cast<ArrayType>(this))
233     return ATy->getElementType().getTypePtr();
234 
235   // If the canonical form of this type isn't the right kind, reject it.
236   if (!isa<ArrayType>(CanonicalType))
237     return nullptr;
238 
239   // If this is a typedef for an array type, strip the typedef off without
240   // losing all typedef information.
241   return cast<ArrayType>(getUnqualifiedDesugaredType())
242     ->getElementType().getTypePtr();
243 }
244 
245 /// getDesugaredType - Return the specified type with any "sugar" removed from
246 /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
247 /// the type is already concrete, it returns it unmodified.  This is similar
248 /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
249 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
250 /// concrete.
251 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
252   SplitQualType split = getSplitDesugaredType(T);
253   return Context.getQualifiedType(split.Ty, split.Quals);
254 }
255 
256 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
257                                                   const ASTContext &Context) {
258   SplitQualType split = type.split();
259   QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
260   return Context.getQualifiedType(desugar, split.Quals);
261 }
262 
263 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
264   switch (getTypeClass()) {
265 #define ABSTRACT_TYPE(Class, Parent)
266 #define TYPE(Class, Parent) \
267   case Type::Class: { \
268     const auto *ty = cast<Class##Type>(this); \
269     if (!ty->isSugared()) return QualType(ty, 0); \
270     return ty->desugar(); \
271   }
272 #include "clang/AST/TypeNodes.def"
273   }
274   llvm_unreachable("bad type kind!");
275 }
276 
277 SplitQualType QualType::getSplitDesugaredType(QualType T) {
278   QualifierCollector Qs;
279 
280   QualType Cur = T;
281   while (true) {
282     const Type *CurTy = Qs.strip(Cur);
283     switch (CurTy->getTypeClass()) {
284 #define ABSTRACT_TYPE(Class, Parent)
285 #define TYPE(Class, Parent) \
286     case Type::Class: { \
287       const auto *Ty = cast<Class##Type>(CurTy); \
288       if (!Ty->isSugared()) \
289         return SplitQualType(Ty, Qs); \
290       Cur = Ty->desugar(); \
291       break; \
292     }
293 #include "clang/AST/TypeNodes.def"
294     }
295   }
296 }
297 
298 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
299   SplitQualType split = type.split();
300 
301   // All the qualifiers we've seen so far.
302   Qualifiers quals = split.Quals;
303 
304   // The last type node we saw with any nodes inside it.
305   const Type *lastTypeWithQuals = split.Ty;
306 
307   while (true) {
308     QualType next;
309 
310     // Do a single-step desugar, aborting the loop if the type isn't
311     // sugared.
312     switch (split.Ty->getTypeClass()) {
313 #define ABSTRACT_TYPE(Class, Parent)
314 #define TYPE(Class, Parent) \
315     case Type::Class: { \
316       const auto *ty = cast<Class##Type>(split.Ty); \
317       if (!ty->isSugared()) goto done; \
318       next = ty->desugar(); \
319       break; \
320     }
321 #include "clang/AST/TypeNodes.def"
322     }
323 
324     // Otherwise, split the underlying type.  If that yields qualifiers,
325     // update the information.
326     split = next.split();
327     if (!split.Quals.empty()) {
328       lastTypeWithQuals = split.Ty;
329       quals.addConsistentQualifiers(split.Quals);
330     }
331   }
332 
333  done:
334   return SplitQualType(lastTypeWithQuals, quals);
335 }
336 
337 QualType QualType::IgnoreParens(QualType T) {
338   // FIXME: this seems inherently un-qualifiers-safe.
339   while (const auto *PT = T->getAs<ParenType>())
340     T = PT->getInnerType();
341   return T;
342 }
343 
344 /// This will check for a T (which should be a Type which can act as
345 /// sugar, such as a TypedefType) by removing any existing sugar until it
346 /// reaches a T or a non-sugared type.
347 template<typename T> static const T *getAsSugar(const Type *Cur) {
348   while (true) {
349     if (const auto *Sugar = dyn_cast<T>(Cur))
350       return Sugar;
351     switch (Cur->getTypeClass()) {
352 #define ABSTRACT_TYPE(Class, Parent)
353 #define TYPE(Class, Parent) \
354     case Type::Class: { \
355       const auto *Ty = cast<Class##Type>(Cur); \
356       if (!Ty->isSugared()) return 0; \
357       Cur = Ty->desugar().getTypePtr(); \
358       break; \
359     }
360 #include "clang/AST/TypeNodes.def"
361     }
362   }
363 }
364 
365 template <> const TypedefType *Type::getAs() const {
366   return getAsSugar<TypedefType>(this);
367 }
368 
369 template <> const TemplateSpecializationType *Type::getAs() const {
370   return getAsSugar<TemplateSpecializationType>(this);
371 }
372 
373 template <> const AttributedType *Type::getAs() const {
374   return getAsSugar<AttributedType>(this);
375 }
376 
377 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
378 /// sugar off the given type.  This should produce an object of the
379 /// same dynamic type as the canonical type.
380 const Type *Type::getUnqualifiedDesugaredType() const {
381   const Type *Cur = this;
382 
383   while (true) {
384     switch (Cur->getTypeClass()) {
385 #define ABSTRACT_TYPE(Class, Parent)
386 #define TYPE(Class, Parent) \
387     case Class: { \
388       const auto *Ty = cast<Class##Type>(Cur); \
389       if (!Ty->isSugared()) return Cur; \
390       Cur = Ty->desugar().getTypePtr(); \
391       break; \
392     }
393 #include "clang/AST/TypeNodes.def"
394     }
395   }
396 }
397 
398 bool Type::isClassType() const {
399   if (const auto *RT = getAs<RecordType>())
400     return RT->getDecl()->isClass();
401   return false;
402 }
403 
404 bool Type::isStructureType() const {
405   if (const auto *RT = getAs<RecordType>())
406     return RT->getDecl()->isStruct();
407   return false;
408 }
409 
410 bool Type::isObjCBoxableRecordType() const {
411   if (const auto *RT = getAs<RecordType>())
412     return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
413   return false;
414 }
415 
416 bool Type::isInterfaceType() const {
417   if (const auto *RT = getAs<RecordType>())
418     return RT->getDecl()->isInterface();
419   return false;
420 }
421 
422 bool Type::isStructureOrClassType() const {
423   if (const auto *RT = getAs<RecordType>()) {
424     RecordDecl *RD = RT->getDecl();
425     return RD->isStruct() || RD->isClass() || RD->isInterface();
426   }
427   return false;
428 }
429 
430 bool Type::isVoidPointerType() const {
431   if (const auto *PT = getAs<PointerType>())
432     return PT->getPointeeType()->isVoidType();
433   return false;
434 }
435 
436 bool Type::isUnionType() const {
437   if (const auto *RT = getAs<RecordType>())
438     return RT->getDecl()->isUnion();
439   return false;
440 }
441 
442 bool Type::isComplexType() const {
443   if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
444     return CT->getElementType()->isFloatingType();
445   return false;
446 }
447 
448 bool Type::isComplexIntegerType() const {
449   // Check for GCC complex integer extension.
450   return getAsComplexIntegerType();
451 }
452 
453 const ComplexType *Type::getAsComplexIntegerType() const {
454   if (const auto *Complex = getAs<ComplexType>())
455     if (Complex->getElementType()->isIntegerType())
456       return Complex;
457   return nullptr;
458 }
459 
460 QualType Type::getPointeeType() const {
461   if (const auto *PT = getAs<PointerType>())
462     return PT->getPointeeType();
463   if (const auto *OPT = getAs<ObjCObjectPointerType>())
464     return OPT->getPointeeType();
465   if (const auto *BPT = getAs<BlockPointerType>())
466     return BPT->getPointeeType();
467   if (const auto *RT = getAs<ReferenceType>())
468     return RT->getPointeeType();
469   if (const auto *MPT = getAs<MemberPointerType>())
470     return MPT->getPointeeType();
471   if (const auto *DT = getAs<DecayedType>())
472     return DT->getPointeeType();
473   return {};
474 }
475 
476 const RecordType *Type::getAsStructureType() const {
477   // If this is directly a structure type, return it.
478   if (const auto *RT = dyn_cast<RecordType>(this)) {
479     if (RT->getDecl()->isStruct())
480       return RT;
481   }
482 
483   // If the canonical form of this type isn't the right kind, reject it.
484   if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
485     if (!RT->getDecl()->isStruct())
486       return nullptr;
487 
488     // If this is a typedef for a structure type, strip the typedef off without
489     // losing all typedef information.
490     return cast<RecordType>(getUnqualifiedDesugaredType());
491   }
492   return nullptr;
493 }
494 
495 const RecordType *Type::getAsUnionType() const {
496   // If this is directly a union type, return it.
497   if (const auto *RT = dyn_cast<RecordType>(this)) {
498     if (RT->getDecl()->isUnion())
499       return RT;
500   }
501 
502   // If the canonical form of this type isn't the right kind, reject it.
503   if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
504     if (!RT->getDecl()->isUnion())
505       return nullptr;
506 
507     // If this is a typedef for a union type, strip the typedef off without
508     // losing all typedef information.
509     return cast<RecordType>(getUnqualifiedDesugaredType());
510   }
511 
512   return nullptr;
513 }
514 
515 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
516                                       const ObjCObjectType *&bound) const {
517   bound = nullptr;
518 
519   const auto *OPT = getAs<ObjCObjectPointerType>();
520   if (!OPT)
521     return false;
522 
523   // Easy case: id.
524   if (OPT->isObjCIdType())
525     return true;
526 
527   // If it's not a __kindof type, reject it now.
528   if (!OPT->isKindOfType())
529     return false;
530 
531   // If it's Class or qualified Class, it's not an object type.
532   if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
533     return false;
534 
535   // Figure out the type bound for the __kindof type.
536   bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
537             ->getAs<ObjCObjectType>();
538   return true;
539 }
540 
541 bool Type::isObjCClassOrClassKindOfType() const {
542   const auto *OPT = getAs<ObjCObjectPointerType>();
543   if (!OPT)
544     return false;
545 
546   // Easy case: Class.
547   if (OPT->isObjCClassType())
548     return true;
549 
550   // If it's not a __kindof type, reject it now.
551   if (!OPT->isKindOfType())
552     return false;
553 
554   // If it's Class or qualified Class, it's a class __kindof type.
555   return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
556 }
557 
558 /// Was this type written with the special inert-in-MRC __unsafe_unretained
559 /// qualifier?
560 ///
561 /// This approximates the answer to the following question: if this
562 /// translation unit were compiled in ARC, would this type be qualified
563 /// with __unsafe_unretained?
564 bool Type::isObjCInertUnsafeUnretainedType() const {
565   const Type *cur = this;
566   while (true) {
567     if (const auto attributed = dyn_cast<AttributedType>(cur)) {
568       if (attributed->getAttrKind() ==
569             AttributedType::attr_objc_inert_unsafe_unretained)
570         return true;
571     }
572 
573     // Single-step desugar until we run out of sugar.
574     QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
575     if (next.getTypePtr() == cur) return false;
576     cur = next.getTypePtr();
577   }
578 }
579 
580 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D,
581                                      QualType can,
582                                      ArrayRef<ObjCProtocolDecl *> protocols)
583     : Type(ObjCTypeParam, can, can->isDependentType(),
584            can->isInstantiationDependentType(),
585            can->isVariablyModifiedType(),
586            /*ContainsUnexpandedParameterPack=*/false),
587       OTPDecl(const_cast<ObjCTypeParamDecl*>(D)) {
588   initialize(protocols);
589 }
590 
591 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
592                                ArrayRef<QualType> typeArgs,
593                                ArrayRef<ObjCProtocolDecl *> protocols,
594                                bool isKindOf)
595     : Type(ObjCObject, Canonical, Base->isDependentType(),
596            Base->isInstantiationDependentType(),
597            Base->isVariablyModifiedType(),
598            Base->containsUnexpandedParameterPack()),
599       BaseType(Base) {
600   ObjCObjectTypeBits.IsKindOf = isKindOf;
601 
602   ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
603   assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
604          "bitfield overflow in type argument count");
605   if (!typeArgs.empty())
606     memcpy(getTypeArgStorage(), typeArgs.data(),
607            typeArgs.size() * sizeof(QualType));
608 
609   for (auto typeArg : typeArgs) {
610     if (typeArg->isDependentType())
611       setDependent();
612     else if (typeArg->isInstantiationDependentType())
613       setInstantiationDependent();
614 
615     if (typeArg->containsUnexpandedParameterPack())
616       setContainsUnexpandedParameterPack();
617   }
618   // Initialize the protocol qualifiers. The protocol storage is known
619   // after we set number of type arguments.
620   initialize(protocols);
621 }
622 
623 bool ObjCObjectType::isSpecialized() const {
624   // If we have type arguments written here, the type is specialized.
625   if (ObjCObjectTypeBits.NumTypeArgs > 0)
626     return true;
627 
628   // Otherwise, check whether the base type is specialized.
629   if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
630     // Terminate when we reach an interface type.
631     if (isa<ObjCInterfaceType>(objcObject))
632       return false;
633 
634     return objcObject->isSpecialized();
635   }
636 
637   // Not specialized.
638   return false;
639 }
640 
641 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
642   // We have type arguments written on this type.
643   if (isSpecializedAsWritten())
644     return getTypeArgsAsWritten();
645 
646   // Look at the base type, which might have type arguments.
647   if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
648     // Terminate when we reach an interface type.
649     if (isa<ObjCInterfaceType>(objcObject))
650       return {};
651 
652     return objcObject->getTypeArgs();
653   }
654 
655   // No type arguments.
656   return {};
657 }
658 
659 bool ObjCObjectType::isKindOfType() const {
660   if (isKindOfTypeAsWritten())
661     return true;
662 
663   // Look at the base type, which might have type arguments.
664   if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
665     // Terminate when we reach an interface type.
666     if (isa<ObjCInterfaceType>(objcObject))
667       return false;
668 
669     return objcObject->isKindOfType();
670   }
671 
672   // Not a "__kindof" type.
673   return false;
674 }
675 
676 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
677            const ASTContext &ctx) const {
678   if (!isKindOfType() && qual_empty())
679     return QualType(this, 0);
680 
681   // Recursively strip __kindof.
682   SplitQualType splitBaseType = getBaseType().split();
683   QualType baseType(splitBaseType.Ty, 0);
684   if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
685     baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
686 
687   return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
688                                                     splitBaseType.Quals),
689                                getTypeArgsAsWritten(),
690                                /*protocols=*/{},
691                                /*isKindOf=*/false);
692 }
693 
694 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
695                                const ASTContext &ctx) const {
696   if (!isKindOfType() && qual_empty())
697     return this;
698 
699   QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
700   return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
701 }
702 
703 template<typename F>
704 static QualType simpleTransform(ASTContext &ctx, QualType type, F &&f);
705 
706 namespace {
707 
708 /// Visitor used by simpleTransform() to perform the transformation.
709 template<typename F>
710 struct SimpleTransformVisitor
711          : public TypeVisitor<SimpleTransformVisitor<F>, QualType> {
712   ASTContext &Ctx;
713   F &&TheFunc;
714 
715   QualType recurse(QualType type) {
716     return simpleTransform(Ctx, type, std::move(TheFunc));
717   }
718 
719 public:
720   SimpleTransformVisitor(ASTContext &ctx, F &&f)
721       : Ctx(ctx), TheFunc(std::move(f)) {}
722 
723   // None of the clients of this transformation can occur where
724   // there are dependent types, so skip dependent types.
725 #define TYPE(Class, Base)
726 #define DEPENDENT_TYPE(Class, Base) \
727   QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
728 #include "clang/AST/TypeNodes.def"
729 
730 #define TRIVIAL_TYPE_CLASS(Class) \
731   QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
732 
733   TRIVIAL_TYPE_CLASS(Builtin)
734 
735   QualType VisitComplexType(const ComplexType *T) {
736     QualType elementType = recurse(T->getElementType());
737     if (elementType.isNull())
738       return {};
739 
740     if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
741       return QualType(T, 0);
742 
743     return Ctx.getComplexType(elementType);
744   }
745 
746   QualType VisitPointerType(const PointerType *T) {
747     QualType pointeeType = recurse(T->getPointeeType());
748     if (pointeeType.isNull())
749       return {};
750 
751     if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
752       return QualType(T, 0);
753 
754     return Ctx.getPointerType(pointeeType);
755   }
756 
757   QualType VisitBlockPointerType(const BlockPointerType *T) {
758     QualType pointeeType = recurse(T->getPointeeType());
759     if (pointeeType.isNull())
760       return {};
761 
762     if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
763       return QualType(T, 0);
764 
765     return Ctx.getBlockPointerType(pointeeType);
766   }
767 
768   QualType VisitLValueReferenceType(const LValueReferenceType *T) {
769     QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
770     if (pointeeType.isNull())
771       return {};
772 
773     if (pointeeType.getAsOpaquePtr()
774           == T->getPointeeTypeAsWritten().getAsOpaquePtr())
775       return QualType(T, 0);
776 
777     return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
778   }
779 
780   QualType VisitRValueReferenceType(const RValueReferenceType *T) {
781     QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
782     if (pointeeType.isNull())
783       return {};
784 
785     if (pointeeType.getAsOpaquePtr()
786           == T->getPointeeTypeAsWritten().getAsOpaquePtr())
787       return QualType(T, 0);
788 
789     return Ctx.getRValueReferenceType(pointeeType);
790   }
791 
792   QualType VisitMemberPointerType(const MemberPointerType *T) {
793     QualType pointeeType = recurse(T->getPointeeType());
794     if (pointeeType.isNull())
795       return {};
796 
797     if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
798       return QualType(T, 0);
799 
800     return Ctx.getMemberPointerType(pointeeType, T->getClass());
801   }
802 
803   QualType VisitConstantArrayType(const ConstantArrayType *T) {
804     QualType elementType = recurse(T->getElementType());
805     if (elementType.isNull())
806       return {};
807 
808     if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
809       return QualType(T, 0);
810 
811     return Ctx.getConstantArrayType(elementType, T->getSize(),
812                                     T->getSizeModifier(),
813                                     T->getIndexTypeCVRQualifiers());
814   }
815 
816   QualType VisitVariableArrayType(const VariableArrayType *T) {
817     QualType elementType = recurse(T->getElementType());
818     if (elementType.isNull())
819       return {};
820 
821     if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
822       return QualType(T, 0);
823 
824     return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
825                                     T->getSizeModifier(),
826                                     T->getIndexTypeCVRQualifiers(),
827                                     T->getBracketsRange());
828   }
829 
830   QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
831     QualType elementType = recurse(T->getElementType());
832     if (elementType.isNull())
833       return {};
834 
835     if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
836       return QualType(T, 0);
837 
838     return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
839                                       T->getIndexTypeCVRQualifiers());
840   }
841 
842   QualType VisitVectorType(const VectorType *T) {
843     QualType elementType = recurse(T->getElementType());
844     if (elementType.isNull())
845       return {};
846 
847     if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
848       return QualType(T, 0);
849 
850     return Ctx.getVectorType(elementType, T->getNumElements(),
851                              T->getVectorKind());
852   }
853 
854   QualType VisitExtVectorType(const ExtVectorType *T) {
855     QualType elementType = recurse(T->getElementType());
856     if (elementType.isNull())
857       return {};
858 
859     if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
860       return QualType(T, 0);
861 
862     return Ctx.getExtVectorType(elementType, T->getNumElements());
863   }
864 
865   QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
866     QualType returnType = recurse(T->getReturnType());
867     if (returnType.isNull())
868       return {};
869 
870     if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
871       return QualType(T, 0);
872 
873     return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
874   }
875 
876   QualType VisitFunctionProtoType(const FunctionProtoType *T) {
877     QualType returnType = recurse(T->getReturnType());
878     if (returnType.isNull())
879       return {};
880 
881     // Transform parameter types.
882     SmallVector<QualType, 4> paramTypes;
883     bool paramChanged = false;
884     for (auto paramType : T->getParamTypes()) {
885       QualType newParamType = recurse(paramType);
886       if (newParamType.isNull())
887         return {};
888 
889       if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
890         paramChanged = true;
891 
892       paramTypes.push_back(newParamType);
893     }
894 
895     // Transform extended info.
896     FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
897     bool exceptionChanged = false;
898     if (info.ExceptionSpec.Type == EST_Dynamic) {
899       SmallVector<QualType, 4> exceptionTypes;
900       for (auto exceptionType : info.ExceptionSpec.Exceptions) {
901         QualType newExceptionType = recurse(exceptionType);
902         if (newExceptionType.isNull())
903           return {};
904 
905         if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
906           exceptionChanged = true;
907 
908         exceptionTypes.push_back(newExceptionType);
909       }
910 
911       if (exceptionChanged) {
912         info.ExceptionSpec.Exceptions =
913             llvm::makeArrayRef(exceptionTypes).copy(Ctx);
914       }
915     }
916 
917     if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
918         !paramChanged && !exceptionChanged)
919       return QualType(T, 0);
920 
921     return Ctx.getFunctionType(returnType, paramTypes, info);
922   }
923 
924   QualType VisitParenType(const ParenType *T) {
925     QualType innerType = recurse(T->getInnerType());
926     if (innerType.isNull())
927       return {};
928 
929     if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
930       return QualType(T, 0);
931 
932     return Ctx.getParenType(innerType);
933   }
934 
935   TRIVIAL_TYPE_CLASS(Typedef)
936   TRIVIAL_TYPE_CLASS(ObjCTypeParam)
937 
938   QualType VisitAdjustedType(const AdjustedType *T) {
939     QualType originalType = recurse(T->getOriginalType());
940     if (originalType.isNull())
941       return {};
942 
943     QualType adjustedType = recurse(T->getAdjustedType());
944     if (adjustedType.isNull())
945       return {};
946 
947     if (originalType.getAsOpaquePtr()
948           == T->getOriginalType().getAsOpaquePtr() &&
949         adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
950       return QualType(T, 0);
951 
952     return Ctx.getAdjustedType(originalType, adjustedType);
953   }
954 
955   QualType VisitDecayedType(const DecayedType *T) {
956     QualType originalType = recurse(T->getOriginalType());
957     if (originalType.isNull())
958       return {};
959 
960     if (originalType.getAsOpaquePtr()
961           == T->getOriginalType().getAsOpaquePtr())
962       return QualType(T, 0);
963 
964     return Ctx.getDecayedType(originalType);
965   }
966 
967   TRIVIAL_TYPE_CLASS(TypeOfExpr)
968   TRIVIAL_TYPE_CLASS(TypeOf)
969   TRIVIAL_TYPE_CLASS(Decltype)
970   TRIVIAL_TYPE_CLASS(UnaryTransform)
971   TRIVIAL_TYPE_CLASS(Record)
972   TRIVIAL_TYPE_CLASS(Enum)
973 
974   // FIXME: Non-trivial to implement, but important for C++
975   TRIVIAL_TYPE_CLASS(Elaborated)
976 
977   QualType VisitAttributedType(const AttributedType *T) {
978     QualType modifiedType = recurse(T->getModifiedType());
979     if (modifiedType.isNull())
980       return {};
981 
982     QualType equivalentType = recurse(T->getEquivalentType());
983     if (equivalentType.isNull())
984       return {};
985 
986     if (modifiedType.getAsOpaquePtr()
987           == T->getModifiedType().getAsOpaquePtr() &&
988         equivalentType.getAsOpaquePtr()
989           == T->getEquivalentType().getAsOpaquePtr())
990       return QualType(T, 0);
991 
992     return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
993                                  equivalentType);
994   }
995 
996   QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
997     QualType replacementType = recurse(T->getReplacementType());
998     if (replacementType.isNull())
999       return {};
1000 
1001     if (replacementType.getAsOpaquePtr()
1002           == T->getReplacementType().getAsOpaquePtr())
1003       return QualType(T, 0);
1004 
1005     return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
1006                                             replacementType);
1007   }
1008 
1009   // FIXME: Non-trivial to implement, but important for C++
1010   TRIVIAL_TYPE_CLASS(TemplateSpecialization)
1011 
1012   QualType VisitAutoType(const AutoType *T) {
1013     if (!T->isDeduced())
1014       return QualType(T, 0);
1015 
1016     QualType deducedType = recurse(T->getDeducedType());
1017     if (deducedType.isNull())
1018       return {};
1019 
1020     if (deducedType.getAsOpaquePtr()
1021           == T->getDeducedType().getAsOpaquePtr())
1022       return QualType(T, 0);
1023 
1024     return Ctx.getAutoType(deducedType, T->getKeyword(),
1025                            T->isDependentType());
1026   }
1027 
1028   // FIXME: Non-trivial to implement, but important for C++
1029   TRIVIAL_TYPE_CLASS(PackExpansion)
1030 
1031   QualType VisitObjCObjectType(const ObjCObjectType *T) {
1032     QualType baseType = recurse(T->getBaseType());
1033     if (baseType.isNull())
1034       return {};
1035 
1036     // Transform type arguments.
1037     bool typeArgChanged = false;
1038     SmallVector<QualType, 4> typeArgs;
1039     for (auto typeArg : T->getTypeArgsAsWritten()) {
1040       QualType newTypeArg = recurse(typeArg);
1041       if (newTypeArg.isNull())
1042         return {};
1043 
1044       if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1045         typeArgChanged = true;
1046 
1047       typeArgs.push_back(newTypeArg);
1048     }
1049 
1050     if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1051         !typeArgChanged)
1052       return QualType(T, 0);
1053 
1054     return Ctx.getObjCObjectType(baseType, typeArgs,
1055                                  llvm::makeArrayRef(T->qual_begin(),
1056                                                     T->getNumProtocols()),
1057                                  T->isKindOfTypeAsWritten());
1058   }
1059 
1060   TRIVIAL_TYPE_CLASS(ObjCInterface)
1061 
1062   QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1063     QualType pointeeType = recurse(T->getPointeeType());
1064     if (pointeeType.isNull())
1065       return {};
1066 
1067     if (pointeeType.getAsOpaquePtr()
1068           == T->getPointeeType().getAsOpaquePtr())
1069       return QualType(T, 0);
1070 
1071     return Ctx.getObjCObjectPointerType(pointeeType);
1072   }
1073 
1074   QualType VisitAtomicType(const AtomicType *T) {
1075     QualType valueType = recurse(T->getValueType());
1076     if (valueType.isNull())
1077       return {};
1078 
1079     if (valueType.getAsOpaquePtr()
1080           == T->getValueType().getAsOpaquePtr())
1081       return QualType(T, 0);
1082 
1083     return Ctx.getAtomicType(valueType);
1084   }
1085 
1086 #undef TRIVIAL_TYPE_CLASS
1087 };
1088 
1089 } // namespace
1090 
1091 /// Perform a simple type transformation that does not change the
1092 /// semantics of the type.
1093 template<typename F>
1094 static QualType simpleTransform(ASTContext &ctx, QualType type, F &&f) {
1095   // Transform the type. If it changed, return the transformed result.
1096   QualType transformed = f(type);
1097   if (transformed.getAsOpaquePtr() != type.getAsOpaquePtr())
1098     return transformed;
1099 
1100   // Split out the qualifiers from the type.
1101   SplitQualType splitType = type.split();
1102 
1103   // Visit the type itself.
1104   SimpleTransformVisitor<F> visitor(ctx, std::forward<F>(f));
1105   QualType result = visitor.Visit(splitType.Ty);
1106   if (result.isNull())
1107     return result;
1108 
1109   // Reconstruct the transformed type by applying the local qualifiers
1110   // from the split type.
1111   return ctx.getQualifiedType(result, splitType.Quals);
1112 }
1113 
1114 /// Substitute the given type arguments for Objective-C type
1115 /// parameters within the given type, recursively.
1116 QualType QualType::substObjCTypeArgs(
1117            ASTContext &ctx,
1118            ArrayRef<QualType> typeArgs,
1119            ObjCSubstitutionContext context) const {
1120   return simpleTransform(ctx, *this,
1121                          [&](QualType type) -> QualType {
1122     SplitQualType splitType = type.split();
1123 
1124     // Replace an Objective-C type parameter reference with the corresponding
1125     // type argument.
1126     if (const auto *OTPTy = dyn_cast<ObjCTypeParamType>(splitType.Ty)) {
1127       ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1128       // If we have type arguments, use them.
1129       if (!typeArgs.empty()) {
1130         QualType argType = typeArgs[typeParam->getIndex()];
1131         if (OTPTy->qual_empty())
1132           return ctx.getQualifiedType(argType, splitType.Quals);
1133 
1134         // Apply protocol lists if exists.
1135         bool hasError;
1136         SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
1137         protocolsVec.append(OTPTy->qual_begin(),
1138                             OTPTy->qual_end());
1139         ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1140         QualType resultTy = ctx.applyObjCProtocolQualifiers(argType,
1141             protocolsToApply, hasError, true/*allowOnPointerType*/);
1142 
1143         return ctx.getQualifiedType(resultTy, splitType.Quals);
1144       }
1145 
1146       switch (context) {
1147       case ObjCSubstitutionContext::Ordinary:
1148       case ObjCSubstitutionContext::Parameter:
1149       case ObjCSubstitutionContext::Superclass:
1150         // Substitute the bound.
1151         return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1152                                     splitType.Quals);
1153 
1154       case ObjCSubstitutionContext::Result:
1155       case ObjCSubstitutionContext::Property: {
1156         // Substitute the __kindof form of the underlying type.
1157         const auto *objPtr = typeParam->getUnderlyingType()
1158           ->castAs<ObjCObjectPointerType>();
1159 
1160         // __kindof types, id, and Class don't need an additional
1161         // __kindof.
1162         if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1163           return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1164                                       splitType.Quals);
1165 
1166         // Add __kindof.
1167         const auto *obj = objPtr->getObjectType();
1168         QualType resultTy = ctx.getObjCObjectType(obj->getBaseType(),
1169                                                   obj->getTypeArgsAsWritten(),
1170                                                   obj->getProtocols(),
1171                                                   /*isKindOf=*/true);
1172 
1173         // Rebuild object pointer type.
1174         resultTy = ctx.getObjCObjectPointerType(resultTy);
1175         return ctx.getQualifiedType(resultTy, splitType.Quals);
1176       }
1177       }
1178     }
1179 
1180     // If we have a function type, update the context appropriately.
1181     if (const auto *funcType = dyn_cast<FunctionType>(splitType.Ty)) {
1182       // Substitute result type.
1183       QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1184                               ctx,
1185                               typeArgs,
1186                               ObjCSubstitutionContext::Result);
1187       if (returnType.isNull())
1188         return {};
1189 
1190       // Handle non-prototyped functions, which only substitute into the result
1191       // type.
1192       if (isa<FunctionNoProtoType>(funcType)) {
1193         // If the return type was unchanged, do nothing.
1194         if (returnType.getAsOpaquePtr()
1195               == funcType->getReturnType().getAsOpaquePtr())
1196           return type;
1197 
1198         // Otherwise, build a new type.
1199         return ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1200       }
1201 
1202       const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1203 
1204       // Transform parameter types.
1205       SmallVector<QualType, 4> paramTypes;
1206       bool paramChanged = false;
1207       for (auto paramType : funcProtoType->getParamTypes()) {
1208         QualType newParamType = paramType.substObjCTypeArgs(
1209                                   ctx,
1210                                   typeArgs,
1211                                   ObjCSubstitutionContext::Parameter);
1212         if (newParamType.isNull())
1213           return {};
1214 
1215         if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1216           paramChanged = true;
1217 
1218         paramTypes.push_back(newParamType);
1219       }
1220 
1221       // Transform extended info.
1222       FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1223       bool exceptionChanged = false;
1224       if (info.ExceptionSpec.Type == EST_Dynamic) {
1225         SmallVector<QualType, 4> exceptionTypes;
1226         for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1227           QualType newExceptionType = exceptionType.substObjCTypeArgs(
1228                                         ctx,
1229                                         typeArgs,
1230                                         ObjCSubstitutionContext::Ordinary);
1231           if (newExceptionType.isNull())
1232             return {};
1233 
1234           if (newExceptionType.getAsOpaquePtr()
1235               != exceptionType.getAsOpaquePtr())
1236             exceptionChanged = true;
1237 
1238           exceptionTypes.push_back(newExceptionType);
1239         }
1240 
1241         if (exceptionChanged) {
1242           info.ExceptionSpec.Exceptions =
1243               llvm::makeArrayRef(exceptionTypes).copy(ctx);
1244         }
1245       }
1246 
1247       if (returnType.getAsOpaquePtr()
1248             == funcProtoType->getReturnType().getAsOpaquePtr() &&
1249           !paramChanged && !exceptionChanged)
1250         return type;
1251 
1252       return ctx.getFunctionType(returnType, paramTypes, info);
1253     }
1254 
1255     // Substitute into the type arguments of a specialized Objective-C object
1256     // type.
1257     if (const auto *objcObjectType = dyn_cast<ObjCObjectType>(splitType.Ty)) {
1258       if (objcObjectType->isSpecializedAsWritten()) {
1259         SmallVector<QualType, 4> newTypeArgs;
1260         bool anyChanged = false;
1261         for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1262           QualType newTypeArg = typeArg.substObjCTypeArgs(
1263                                   ctx, typeArgs,
1264                                   ObjCSubstitutionContext::Ordinary);
1265           if (newTypeArg.isNull())
1266             return {};
1267 
1268           if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1269             // If we're substituting based on an unspecialized context type,
1270             // produce an unspecialized type.
1271             ArrayRef<ObjCProtocolDecl *> protocols(
1272                                            objcObjectType->qual_begin(),
1273                                            objcObjectType->getNumProtocols());
1274             if (typeArgs.empty() &&
1275                 context != ObjCSubstitutionContext::Superclass) {
1276               return ctx.getObjCObjectType(
1277                        objcObjectType->getBaseType(), {},
1278                        protocols,
1279                        objcObjectType->isKindOfTypeAsWritten());
1280             }
1281 
1282             anyChanged = true;
1283           }
1284 
1285           newTypeArgs.push_back(newTypeArg);
1286         }
1287 
1288         if (anyChanged) {
1289           ArrayRef<ObjCProtocolDecl *> protocols(
1290                                          objcObjectType->qual_begin(),
1291                                          objcObjectType->getNumProtocols());
1292           return ctx.getObjCObjectType(objcObjectType->getBaseType(),
1293                                        newTypeArgs, protocols,
1294                                        objcObjectType->isKindOfTypeAsWritten());
1295         }
1296       }
1297 
1298       return type;
1299     }
1300 
1301     return type;
1302   });
1303 }
1304 
1305 QualType QualType::substObjCMemberType(QualType objectType,
1306                                        const DeclContext *dc,
1307                                        ObjCSubstitutionContext context) const {
1308   if (auto subs = objectType->getObjCSubstitutions(dc))
1309     return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1310 
1311   return *this;
1312 }
1313 
1314 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1315   // FIXME: Because ASTContext::getAttributedType() is non-const.
1316   auto &ctx = const_cast<ASTContext &>(constCtx);
1317   return simpleTransform(ctx, *this,
1318            [&](QualType type) -> QualType {
1319              SplitQualType splitType = type.split();
1320              if (auto *objType = splitType.Ty->getAs<ObjCObjectType>()) {
1321                if (!objType->isKindOfType())
1322                  return type;
1323 
1324                QualType baseType
1325                  = objType->getBaseType().stripObjCKindOfType(ctx);
1326                return ctx.getQualifiedType(
1327                         ctx.getObjCObjectType(baseType,
1328                                               objType->getTypeArgsAsWritten(),
1329                                               objType->getProtocols(),
1330                                               /*isKindOf=*/false),
1331                         splitType.Quals);
1332              }
1333 
1334              return type;
1335            });
1336 }
1337 
1338 QualType QualType::getAtomicUnqualifiedType() const {
1339   if (const auto AT = getTypePtr()->getAs<AtomicType>())
1340     return AT->getValueType().getUnqualifiedType();
1341   return getUnqualifiedType();
1342 }
1343 
1344 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
1345                                const DeclContext *dc) const {
1346   // Look through method scopes.
1347   if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
1348     dc = method->getDeclContext();
1349 
1350   // Find the class or category in which the type we're substituting
1351   // was declared.
1352   const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1353   const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1354   ObjCTypeParamList *dcTypeParams = nullptr;
1355   if (dcClassDecl) {
1356     // If the class does not have any type parameters, there's no
1357     // substitution to do.
1358     dcTypeParams = dcClassDecl->getTypeParamList();
1359     if (!dcTypeParams)
1360       return None;
1361   } else {
1362     // If we are in neither a class nor a category, there's no
1363     // substitution to perform.
1364     dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1365     if (!dcCategoryDecl)
1366       return None;
1367 
1368     // If the category does not have any type parameters, there's no
1369     // substitution to do.
1370     dcTypeParams = dcCategoryDecl->getTypeParamList();
1371     if (!dcTypeParams)
1372       return None;
1373 
1374     dcClassDecl = dcCategoryDecl->getClassInterface();
1375     if (!dcClassDecl)
1376       return None;
1377   }
1378   assert(dcTypeParams && "No substitutions to perform");
1379   assert(dcClassDecl && "No class context");
1380 
1381   // Find the underlying object type.
1382   const ObjCObjectType *objectType;
1383   if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1384     objectType = objectPointerType->getObjectType();
1385   } else if (getAs<BlockPointerType>()) {
1386     ASTContext &ctx = dc->getParentASTContext();
1387     objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
1388                    ->castAs<ObjCObjectType>();
1389   } else {
1390     objectType = getAs<ObjCObjectType>();
1391   }
1392 
1393   /// Extract the class from the receiver object type.
1394   ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1395                                                : nullptr;
1396   if (!curClassDecl) {
1397     // If we don't have a context type (e.g., this is "id" or some
1398     // variant thereof), substitute the bounds.
1399     return llvm::ArrayRef<QualType>();
1400   }
1401 
1402   // Follow the superclass chain until we've mapped the receiver type
1403   // to the same class as the context.
1404   while (curClassDecl != dcClassDecl) {
1405     // Map to the superclass type.
1406     QualType superType = objectType->getSuperClassType();
1407     if (superType.isNull()) {
1408       objectType = nullptr;
1409       break;
1410     }
1411 
1412     objectType = superType->castAs<ObjCObjectType>();
1413     curClassDecl = objectType->getInterface();
1414   }
1415 
1416   // If we don't have a receiver type, or the receiver type does not
1417   // have type arguments, substitute in the defaults.
1418   if (!objectType || objectType->isUnspecialized()) {
1419     return llvm::ArrayRef<QualType>();
1420   }
1421 
1422   // The receiver type has the type arguments we want.
1423   return objectType->getTypeArgs();
1424 }
1425 
1426 bool Type::acceptsObjCTypeParams() const {
1427   if (auto *IfaceT = getAsObjCInterfaceType()) {
1428     if (auto *ID = IfaceT->getInterface()) {
1429       if (ID->getTypeParamList())
1430         return true;
1431     }
1432   }
1433 
1434   return false;
1435 }
1436 
1437 void ObjCObjectType::computeSuperClassTypeSlow() const {
1438   // Retrieve the class declaration for this type. If there isn't one
1439   // (e.g., this is some variant of "id" or "Class"), then there is no
1440   // superclass type.
1441   ObjCInterfaceDecl *classDecl = getInterface();
1442   if (!classDecl) {
1443     CachedSuperClassType.setInt(true);
1444     return;
1445   }
1446 
1447   // Extract the superclass type.
1448   const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1449   if (!superClassObjTy) {
1450     CachedSuperClassType.setInt(true);
1451     return;
1452   }
1453 
1454   ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1455   if (!superClassDecl) {
1456     CachedSuperClassType.setInt(true);
1457     return;
1458   }
1459 
1460   // If the superclass doesn't have type parameters, then there is no
1461   // substitution to perform.
1462   QualType superClassType(superClassObjTy, 0);
1463   ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1464   if (!superClassTypeParams) {
1465     CachedSuperClassType.setPointerAndInt(
1466       superClassType->castAs<ObjCObjectType>(), true);
1467     return;
1468   }
1469 
1470   // If the superclass reference is unspecialized, return it.
1471   if (superClassObjTy->isUnspecialized()) {
1472     CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1473     return;
1474   }
1475 
1476   // If the subclass is not parameterized, there aren't any type
1477   // parameters in the superclass reference to substitute.
1478   ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1479   if (!typeParams) {
1480     CachedSuperClassType.setPointerAndInt(
1481       superClassType->castAs<ObjCObjectType>(), true);
1482     return;
1483   }
1484 
1485   // If the subclass type isn't specialized, return the unspecialized
1486   // superclass.
1487   if (isUnspecialized()) {
1488     QualType unspecializedSuper
1489       = classDecl->getASTContext().getObjCInterfaceType(
1490           superClassObjTy->getInterface());
1491     CachedSuperClassType.setPointerAndInt(
1492       unspecializedSuper->castAs<ObjCObjectType>(),
1493       true);
1494     return;
1495   }
1496 
1497   // Substitute the provided type arguments into the superclass type.
1498   ArrayRef<QualType> typeArgs = getTypeArgs();
1499   assert(typeArgs.size() == typeParams->size());
1500   CachedSuperClassType.setPointerAndInt(
1501     superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1502                                      ObjCSubstitutionContext::Superclass)
1503       ->castAs<ObjCObjectType>(),
1504     true);
1505 }
1506 
1507 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1508   if (auto interfaceDecl = getObjectType()->getInterface()) {
1509     return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1510              ->castAs<ObjCInterfaceType>();
1511   }
1512 
1513   return nullptr;
1514 }
1515 
1516 QualType ObjCObjectPointerType::getSuperClassType() const {
1517   QualType superObjectType = getObjectType()->getSuperClassType();
1518   if (superObjectType.isNull())
1519     return superObjectType;
1520 
1521   ASTContext &ctx = getInterfaceDecl()->getASTContext();
1522   return ctx.getObjCObjectPointerType(superObjectType);
1523 }
1524 
1525 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1526   // There is no sugar for ObjCObjectType's, just return the canonical
1527   // type pointer if it is the right class.  There is no typedef information to
1528   // return and these cannot be Address-space qualified.
1529   if (const auto *T = getAs<ObjCObjectType>())
1530     if (T->getNumProtocols() && T->getInterface())
1531       return T;
1532   return nullptr;
1533 }
1534 
1535 bool Type::isObjCQualifiedInterfaceType() const {
1536   return getAsObjCQualifiedInterfaceType() != nullptr;
1537 }
1538 
1539 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1540   // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1541   // type pointer if it is the right class.
1542   if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1543     if (OPT->isObjCQualifiedIdType())
1544       return OPT;
1545   }
1546   return nullptr;
1547 }
1548 
1549 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1550   // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1551   // type pointer if it is the right class.
1552   if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1553     if (OPT->isObjCQualifiedClassType())
1554       return OPT;
1555   }
1556   return nullptr;
1557 }
1558 
1559 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1560   if (const auto *OT = getAs<ObjCObjectType>()) {
1561     if (OT->getInterface())
1562       return OT;
1563   }
1564   return nullptr;
1565 }
1566 
1567 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1568   if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1569     if (OPT->getInterfaceType())
1570       return OPT;
1571   }
1572   return nullptr;
1573 }
1574 
1575 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1576   QualType PointeeType;
1577   if (const auto *PT = getAs<PointerType>())
1578     PointeeType = PT->getPointeeType();
1579   else if (const auto *RT = getAs<ReferenceType>())
1580     PointeeType = RT->getPointeeType();
1581   else
1582     return nullptr;
1583 
1584   if (const auto *RT = PointeeType->getAs<RecordType>())
1585     return dyn_cast<CXXRecordDecl>(RT->getDecl());
1586 
1587   return nullptr;
1588 }
1589 
1590 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1591   return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1592 }
1593 
1594 TagDecl *Type::getAsTagDecl() const {
1595   if (const auto *TT = getAs<TagType>())
1596     return TT->getDecl();
1597   if (const auto *Injected = getAs<InjectedClassNameType>())
1598     return Injected->getDecl();
1599 
1600   return nullptr;
1601 }
1602 
1603 namespace {
1604 
1605   class GetContainedDeducedTypeVisitor :
1606     public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1607     bool Syntactic;
1608 
1609   public:
1610     GetContainedDeducedTypeVisitor(bool Syntactic = false)
1611         : Syntactic(Syntactic) {}
1612 
1613     using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1614 
1615     Type *Visit(QualType T) {
1616       if (T.isNull())
1617         return nullptr;
1618       return Visit(T.getTypePtr());
1619     }
1620 
1621     // The deduced type itself.
1622     Type *VisitDeducedType(const DeducedType *AT) {
1623       return const_cast<DeducedType*>(AT);
1624     }
1625 
1626     // Only these types can contain the desired 'auto' type.
1627 
1628     Type *VisitElaboratedType(const ElaboratedType *T) {
1629       return Visit(T->getNamedType());
1630     }
1631 
1632     Type *VisitPointerType(const PointerType *T) {
1633       return Visit(T->getPointeeType());
1634     }
1635 
1636     Type *VisitBlockPointerType(const BlockPointerType *T) {
1637       return Visit(T->getPointeeType());
1638     }
1639 
1640     Type *VisitReferenceType(const ReferenceType *T) {
1641       return Visit(T->getPointeeTypeAsWritten());
1642     }
1643 
1644     Type *VisitMemberPointerType(const MemberPointerType *T) {
1645       return Visit(T->getPointeeType());
1646     }
1647 
1648     Type *VisitArrayType(const ArrayType *T) {
1649       return Visit(T->getElementType());
1650     }
1651 
1652     Type *VisitDependentSizedExtVectorType(
1653       const DependentSizedExtVectorType *T) {
1654       return Visit(T->getElementType());
1655     }
1656 
1657     Type *VisitVectorType(const VectorType *T) {
1658       return Visit(T->getElementType());
1659     }
1660 
1661     Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1662       if (Syntactic && T->hasTrailingReturn())
1663         return const_cast<FunctionProtoType*>(T);
1664       return VisitFunctionType(T);
1665     }
1666 
1667     Type *VisitFunctionType(const FunctionType *T) {
1668       return Visit(T->getReturnType());
1669     }
1670 
1671     Type *VisitParenType(const ParenType *T) {
1672       return Visit(T->getInnerType());
1673     }
1674 
1675     Type *VisitAttributedType(const AttributedType *T) {
1676       return Visit(T->getModifiedType());
1677     }
1678 
1679     Type *VisitAdjustedType(const AdjustedType *T) {
1680       return Visit(T->getOriginalType());
1681     }
1682   };
1683 
1684 } // namespace
1685 
1686 DeducedType *Type::getContainedDeducedType() const {
1687   return cast_or_null<DeducedType>(
1688       GetContainedDeducedTypeVisitor().Visit(this));
1689 }
1690 
1691 bool Type::hasAutoForTrailingReturnType() const {
1692   return dyn_cast_or_null<FunctionType>(
1693       GetContainedDeducedTypeVisitor(true).Visit(this));
1694 }
1695 
1696 bool Type::hasIntegerRepresentation() const {
1697   if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1698     return VT->getElementType()->isIntegerType();
1699   else
1700     return isIntegerType();
1701 }
1702 
1703 /// Determine whether this type is an integral type.
1704 ///
1705 /// This routine determines whether the given type is an integral type per
1706 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1707 /// term "integral type", it has a similar term "integer type", and in C++
1708 /// the two terms are equivalent. However, C's "integer type" includes
1709 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1710 /// parameter is used to determine whether we should be following the C or
1711 /// C++ rules when determining whether this type is an integral/integer type.
1712 ///
1713 /// For cases where C permits "an integer type" and C++ permits "an integral
1714 /// type", use this routine.
1715 ///
1716 /// For cases where C permits "an integer type" and C++ permits "an integral
1717 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1718 ///
1719 /// \param Ctx The context in which this type occurs.
1720 ///
1721 /// \returns true if the type is considered an integral type, false otherwise.
1722 bool Type::isIntegralType(const ASTContext &Ctx) const {
1723   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1724     return BT->getKind() >= BuiltinType::Bool &&
1725            BT->getKind() <= BuiltinType::Int128;
1726 
1727   // Complete enum types are integral in C.
1728   if (!Ctx.getLangOpts().CPlusPlus)
1729     if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1730       return ET->getDecl()->isComplete();
1731 
1732   return false;
1733 }
1734 
1735 bool Type::isIntegralOrUnscopedEnumerationType() const {
1736   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1737     return BT->getKind() >= BuiltinType::Bool &&
1738            BT->getKind() <= BuiltinType::Int128;
1739 
1740   // Check for a complete enum type; incomplete enum types are not properly an
1741   // enumeration type in the sense required here.
1742   // C++0x: However, if the underlying type of the enum is fixed, it is
1743   // considered complete.
1744   if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1745     return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1746 
1747   return false;
1748 }
1749 
1750 bool Type::isCharType() const {
1751   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1752     return BT->getKind() == BuiltinType::Char_U ||
1753            BT->getKind() == BuiltinType::UChar ||
1754            BT->getKind() == BuiltinType::Char_S ||
1755            BT->getKind() == BuiltinType::SChar;
1756   return false;
1757 }
1758 
1759 bool Type::isWideCharType() const {
1760   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1761     return BT->getKind() == BuiltinType::WChar_S ||
1762            BT->getKind() == BuiltinType::WChar_U;
1763   return false;
1764 }
1765 
1766 bool Type::isChar8Type() const {
1767   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1768     return BT->getKind() == BuiltinType::Char8;
1769   return false;
1770 }
1771 
1772 bool Type::isChar16Type() const {
1773   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1774     return BT->getKind() == BuiltinType::Char16;
1775   return false;
1776 }
1777 
1778 bool Type::isChar32Type() const {
1779   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1780     return BT->getKind() == BuiltinType::Char32;
1781   return false;
1782 }
1783 
1784 /// Determine whether this type is any of the built-in character
1785 /// types.
1786 bool Type::isAnyCharacterType() const {
1787   const auto *BT = dyn_cast<BuiltinType>(CanonicalType);
1788   if (!BT) return false;
1789   switch (BT->getKind()) {
1790   default: return false;
1791   case BuiltinType::Char_U:
1792   case BuiltinType::UChar:
1793   case BuiltinType::WChar_U:
1794   case BuiltinType::Char8:
1795   case BuiltinType::Char16:
1796   case BuiltinType::Char32:
1797   case BuiltinType::Char_S:
1798   case BuiltinType::SChar:
1799   case BuiltinType::WChar_S:
1800     return true;
1801   }
1802 }
1803 
1804 /// isSignedIntegerType - Return true if this is an integer type that is
1805 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1806 /// an enum decl which has a signed representation
1807 bool Type::isSignedIntegerType() const {
1808   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1809     return BT->getKind() >= BuiltinType::Char_S &&
1810            BT->getKind() <= BuiltinType::Int128;
1811   }
1812 
1813   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1814     // Incomplete enum types are not treated as integer types.
1815     // FIXME: In C++, enum types are never integer types.
1816     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1817       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1818   }
1819 
1820   return false;
1821 }
1822 
1823 bool Type::isSignedIntegerOrEnumerationType() const {
1824   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1825     return BT->getKind() >= BuiltinType::Char_S &&
1826            BT->getKind() <= BuiltinType::Int128;
1827   }
1828 
1829   if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
1830     if (ET->getDecl()->isComplete())
1831       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1832   }
1833 
1834   return false;
1835 }
1836 
1837 bool Type::hasSignedIntegerRepresentation() const {
1838   if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1839     return VT->getElementType()->isSignedIntegerOrEnumerationType();
1840   else
1841     return isSignedIntegerOrEnumerationType();
1842 }
1843 
1844 /// isUnsignedIntegerType - Return true if this is an integer type that is
1845 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1846 /// decl which has an unsigned representation
1847 bool Type::isUnsignedIntegerType() const {
1848   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1849     return BT->getKind() >= BuiltinType::Bool &&
1850            BT->getKind() <= BuiltinType::UInt128;
1851   }
1852 
1853   if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
1854     // Incomplete enum types are not treated as integer types.
1855     // FIXME: In C++, enum types are never integer types.
1856     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1857       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1858   }
1859 
1860   return false;
1861 }
1862 
1863 bool Type::isUnsignedIntegerOrEnumerationType() const {
1864   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1865     return BT->getKind() >= BuiltinType::Bool &&
1866     BT->getKind() <= BuiltinType::UInt128;
1867   }
1868 
1869   if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
1870     if (ET->getDecl()->isComplete())
1871       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1872   }
1873 
1874   return false;
1875 }
1876 
1877 bool Type::hasUnsignedIntegerRepresentation() const {
1878   if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1879     return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
1880   else
1881     return isUnsignedIntegerOrEnumerationType();
1882 }
1883 
1884 bool Type::isFloatingType() const {
1885   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1886     return BT->getKind() >= BuiltinType::Half &&
1887            BT->getKind() <= BuiltinType::Float128;
1888   if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
1889     return CT->getElementType()->isFloatingType();
1890   return false;
1891 }
1892 
1893 bool Type::hasFloatingRepresentation() const {
1894   if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1895     return VT->getElementType()->isFloatingType();
1896   else
1897     return isFloatingType();
1898 }
1899 
1900 bool Type::isRealFloatingType() const {
1901   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1902     return BT->isFloatingPoint();
1903   return false;
1904 }
1905 
1906 bool Type::isRealType() const {
1907   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1908     return BT->getKind() >= BuiltinType::Bool &&
1909            BT->getKind() <= BuiltinType::Float128;
1910   if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1911       return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1912   return false;
1913 }
1914 
1915 bool Type::isArithmeticType() const {
1916   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1917     return BT->getKind() >= BuiltinType::Bool &&
1918            BT->getKind() <= BuiltinType::Float128;
1919   if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1920     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
1921     // If a body isn't seen by the time we get here, return false.
1922     //
1923     // C++0x: Enumerations are not arithmetic types. For now, just return
1924     // false for scoped enumerations since that will disable any
1925     // unwanted implicit conversions.
1926     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
1927   return isa<ComplexType>(CanonicalType);
1928 }
1929 
1930 Type::ScalarTypeKind Type::getScalarTypeKind() const {
1931   assert(isScalarType());
1932 
1933   const Type *T = CanonicalType.getTypePtr();
1934   if (const auto *BT = dyn_cast<BuiltinType>(T)) {
1935     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
1936     if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
1937     if (BT->isInteger()) return STK_Integral;
1938     if (BT->isFloatingPoint()) return STK_Floating;
1939     llvm_unreachable("unknown scalar builtin type");
1940   } else if (isa<PointerType>(T)) {
1941     return STK_CPointer;
1942   } else if (isa<BlockPointerType>(T)) {
1943     return STK_BlockPointer;
1944   } else if (isa<ObjCObjectPointerType>(T)) {
1945     return STK_ObjCObjectPointer;
1946   } else if (isa<MemberPointerType>(T)) {
1947     return STK_MemberPointer;
1948   } else if (isa<EnumType>(T)) {
1949     assert(cast<EnumType>(T)->getDecl()->isComplete());
1950     return STK_Integral;
1951   } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
1952     if (CT->getElementType()->isRealFloatingType())
1953       return STK_FloatingComplex;
1954     return STK_IntegralComplex;
1955   }
1956 
1957   llvm_unreachable("unknown scalar type");
1958 }
1959 
1960 /// Determines whether the type is a C++ aggregate type or C
1961 /// aggregate or union type.
1962 ///
1963 /// An aggregate type is an array or a class type (struct, union, or
1964 /// class) that has no user-declared constructors, no private or
1965 /// protected non-static data members, no base classes, and no virtual
1966 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
1967 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
1968 /// includes union types.
1969 bool Type::isAggregateType() const {
1970   if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
1971     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
1972       return ClassDecl->isAggregate();
1973 
1974     return true;
1975   }
1976 
1977   return isa<ArrayType>(CanonicalType);
1978 }
1979 
1980 /// isConstantSizeType - Return true if this is not a variable sized type,
1981 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1982 /// incomplete types or dependent types.
1983 bool Type::isConstantSizeType() const {
1984   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
1985   assert(!isDependentType() && "This doesn't make sense for dependent types");
1986   // The VAT must have a size, as it is known to be complete.
1987   return !isa<VariableArrayType>(CanonicalType);
1988 }
1989 
1990 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
1991 /// - a type that can describe objects, but which lacks information needed to
1992 /// determine its size.
1993 bool Type::isIncompleteType(NamedDecl **Def) const {
1994   if (Def)
1995     *Def = nullptr;
1996 
1997   switch (CanonicalType->getTypeClass()) {
1998   default: return false;
1999   case Builtin:
2000     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
2001     // be completed.
2002     return isVoidType();
2003   case Enum: {
2004     EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2005     if (Def)
2006       *Def = EnumD;
2007     return !EnumD->isComplete();
2008   }
2009   case Record: {
2010     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2011     // forward declaration, but not a full definition (C99 6.2.5p22).
2012     RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2013     if (Def)
2014       *Def = Rec;
2015     return !Rec->isCompleteDefinition();
2016   }
2017   case ConstantArray:
2018     // An array is incomplete if its element type is incomplete
2019     // (C++ [dcl.array]p1).
2020     // We don't handle variable arrays (they're not allowed in C++) or
2021     // dependent-sized arrays (dependent types are never treated as incomplete).
2022     return cast<ArrayType>(CanonicalType)->getElementType()
2023              ->isIncompleteType(Def);
2024   case IncompleteArray:
2025     // An array of unknown size is an incomplete type (C99 6.2.5p22).
2026     return true;
2027   case MemberPointer: {
2028     // Member pointers in the MS ABI have special behavior in
2029     // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2030     // to indicate which inheritance model to use.
2031     auto *MPTy = cast<MemberPointerType>(CanonicalType);
2032     const Type *ClassTy = MPTy->getClass();
2033     // Member pointers with dependent class types don't get special treatment.
2034     if (ClassTy->isDependentType())
2035       return false;
2036     const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2037     ASTContext &Context = RD->getASTContext();
2038     // Member pointers not in the MS ABI don't get special treatment.
2039     if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2040       return false;
2041     // The inheritance attribute might only be present on the most recent
2042     // CXXRecordDecl, use that one.
2043     RD = RD->getMostRecentDecl();
2044     // Nothing interesting to do if the inheritance attribute is already set.
2045     if (RD->hasAttr<MSInheritanceAttr>())
2046       return false;
2047     return true;
2048   }
2049   case ObjCObject:
2050     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2051              ->isIncompleteType(Def);
2052   case ObjCInterface: {
2053     // ObjC interfaces are incomplete if they are @class, not @interface.
2054     ObjCInterfaceDecl *Interface
2055       = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2056     if (Def)
2057       *Def = Interface;
2058     return !Interface->hasDefinition();
2059   }
2060   }
2061 }
2062 
2063 bool QualType::isPODType(const ASTContext &Context) const {
2064   // C++11 has a more relaxed definition of POD.
2065   if (Context.getLangOpts().CPlusPlus11)
2066     return isCXX11PODType(Context);
2067 
2068   return isCXX98PODType(Context);
2069 }
2070 
2071 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2072   // The compiler shouldn't query this for incomplete types, but the user might.
2073   // We return false for that case. Except for incomplete arrays of PODs, which
2074   // are PODs according to the standard.
2075   if (isNull())
2076     return false;
2077 
2078   if ((*this)->isIncompleteArrayType())
2079     return Context.getBaseElementType(*this).isCXX98PODType(Context);
2080 
2081   if ((*this)->isIncompleteType())
2082     return false;
2083 
2084   if (hasNonTrivialObjCLifetime())
2085     return false;
2086 
2087   QualType CanonicalType = getTypePtr()->CanonicalType;
2088   switch (CanonicalType->getTypeClass()) {
2089     // Everything not explicitly mentioned is not POD.
2090   default: return false;
2091   case Type::VariableArray:
2092   case Type::ConstantArray:
2093     // IncompleteArray is handled above.
2094     return Context.getBaseElementType(*this).isCXX98PODType(Context);
2095 
2096   case Type::ObjCObjectPointer:
2097   case Type::BlockPointer:
2098   case Type::Builtin:
2099   case Type::Complex:
2100   case Type::Pointer:
2101   case Type::MemberPointer:
2102   case Type::Vector:
2103   case Type::ExtVector:
2104     return true;
2105 
2106   case Type::Enum:
2107     return true;
2108 
2109   case Type::Record:
2110     if (const auto *ClassDecl =
2111             dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2112       return ClassDecl->isPOD();
2113 
2114     // C struct/union is POD.
2115     return true;
2116   }
2117 }
2118 
2119 bool QualType::isTrivialType(const ASTContext &Context) const {
2120   // The compiler shouldn't query this for incomplete types, but the user might.
2121   // We return false for that case. Except for incomplete arrays of PODs, which
2122   // are PODs according to the standard.
2123   if (isNull())
2124     return false;
2125 
2126   if ((*this)->isArrayType())
2127     return Context.getBaseElementType(*this).isTrivialType(Context);
2128 
2129   // Return false for incomplete types after skipping any incomplete array
2130   // types which are expressly allowed by the standard and thus our API.
2131   if ((*this)->isIncompleteType())
2132     return false;
2133 
2134   if (hasNonTrivialObjCLifetime())
2135     return false;
2136 
2137   QualType CanonicalType = getTypePtr()->CanonicalType;
2138   if (CanonicalType->isDependentType())
2139     return false;
2140 
2141   // C++0x [basic.types]p9:
2142   //   Scalar types, trivial class types, arrays of such types, and
2143   //   cv-qualified versions of these types are collectively called trivial
2144   //   types.
2145 
2146   // As an extension, Clang treats vector types as Scalar types.
2147   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2148     return true;
2149   if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2150     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2151       // C++11 [class]p6:
2152       //   A trivial class is a class that has a default constructor,
2153       //   has no non-trivial default constructors, and is trivially
2154       //   copyable.
2155       return ClassDecl->hasDefaultConstructor() &&
2156              !ClassDecl->hasNonTrivialDefaultConstructor() &&
2157              ClassDecl->isTriviallyCopyable();
2158     }
2159 
2160     return true;
2161   }
2162 
2163   // No other types can match.
2164   return false;
2165 }
2166 
2167 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2168   if ((*this)->isArrayType())
2169     return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2170 
2171   if (hasNonTrivialObjCLifetime())
2172     return false;
2173 
2174   // C++11 [basic.types]p9 - See Core 2094
2175   //   Scalar types, trivially copyable class types, arrays of such types, and
2176   //   cv-qualified versions of these types are collectively
2177   //   called trivially copyable types.
2178 
2179   QualType CanonicalType = getCanonicalType();
2180   if (CanonicalType->isDependentType())
2181     return false;
2182 
2183   // Return false for incomplete types after skipping any incomplete array types
2184   // which are expressly allowed by the standard and thus our API.
2185   if (CanonicalType->isIncompleteType())
2186     return false;
2187 
2188   // As an extension, Clang treats vector types as Scalar types.
2189   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2190     return true;
2191 
2192   if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2193     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2194       if (!ClassDecl->isTriviallyCopyable()) return false;
2195     }
2196 
2197     return true;
2198   }
2199 
2200   // No other types can match.
2201   return false;
2202 }
2203 
2204 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2205   return !Context.getLangOpts().ObjCAutoRefCount &&
2206          Context.getLangOpts().ObjCWeak &&
2207          getObjCLifetime() != Qualifiers::OCL_Weak;
2208 }
2209 
2210 QualType::PrimitiveDefaultInitializeKind
2211 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2212   if (const auto *RT =
2213           getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2214     if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2215       return PDIK_Struct;
2216 
2217   switch (getQualifiers().getObjCLifetime()) {
2218   case Qualifiers::OCL_Strong:
2219     return PDIK_ARCStrong;
2220   case Qualifiers::OCL_Weak:
2221     return PDIK_ARCWeak;
2222   default:
2223     return PDIK_Trivial;
2224   }
2225 }
2226 
2227 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2228   if (const auto *RT =
2229           getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2230     if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2231       return PCK_Struct;
2232 
2233   Qualifiers Qs = getQualifiers();
2234   switch (Qs.getObjCLifetime()) {
2235   case Qualifiers::OCL_Strong:
2236     return PCK_ARCStrong;
2237   case Qualifiers::OCL_Weak:
2238     return PCK_ARCWeak;
2239   default:
2240     return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2241   }
2242 }
2243 
2244 QualType::PrimitiveCopyKind
2245 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2246   return isNonTrivialToPrimitiveCopy();
2247 }
2248 
2249 bool Type::isLiteralType(const ASTContext &Ctx) const {
2250   if (isDependentType())
2251     return false;
2252 
2253   // C++1y [basic.types]p10:
2254   //   A type is a literal type if it is:
2255   //   -- cv void; or
2256   if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2257     return true;
2258 
2259   // C++11 [basic.types]p10:
2260   //   A type is a literal type if it is:
2261   //   [...]
2262   //   -- an array of literal type other than an array of runtime bound; or
2263   if (isVariableArrayType())
2264     return false;
2265   const Type *BaseTy = getBaseElementTypeUnsafe();
2266   assert(BaseTy && "NULL element type");
2267 
2268   // Return false for incomplete types after skipping any incomplete array
2269   // types; those are expressly allowed by the standard and thus our API.
2270   if (BaseTy->isIncompleteType())
2271     return false;
2272 
2273   // C++11 [basic.types]p10:
2274   //   A type is a literal type if it is:
2275   //    -- a scalar type; or
2276   // As an extension, Clang treats vector types and complex types as
2277   // literal types.
2278   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2279       BaseTy->isAnyComplexType())
2280     return true;
2281   //    -- a reference type; or
2282   if (BaseTy->isReferenceType())
2283     return true;
2284   //    -- a class type that has all of the following properties:
2285   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2286     //    -- a trivial destructor,
2287     //    -- every constructor call and full-expression in the
2288     //       brace-or-equal-initializers for non-static data members (if any)
2289     //       is a constant expression,
2290     //    -- it is an aggregate type or has at least one constexpr
2291     //       constructor or constructor template that is not a copy or move
2292     //       constructor, and
2293     //    -- all non-static data members and base classes of literal types
2294     //
2295     // We resolve DR1361 by ignoring the second bullet.
2296     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2297       return ClassDecl->isLiteral();
2298 
2299     return true;
2300   }
2301 
2302   // We treat _Atomic T as a literal type if T is a literal type.
2303   if (const auto *AT = BaseTy->getAs<AtomicType>())
2304     return AT->getValueType()->isLiteralType(Ctx);
2305 
2306   // If this type hasn't been deduced yet, then conservatively assume that
2307   // it'll work out to be a literal type.
2308   if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2309     return true;
2310 
2311   return false;
2312 }
2313 
2314 bool Type::isStandardLayoutType() const {
2315   if (isDependentType())
2316     return false;
2317 
2318   // C++0x [basic.types]p9:
2319   //   Scalar types, standard-layout class types, arrays of such types, and
2320   //   cv-qualified versions of these types are collectively called
2321   //   standard-layout types.
2322   const Type *BaseTy = getBaseElementTypeUnsafe();
2323   assert(BaseTy && "NULL element type");
2324 
2325   // Return false for incomplete types after skipping any incomplete array
2326   // types which are expressly allowed by the standard and thus our API.
2327   if (BaseTy->isIncompleteType())
2328     return false;
2329 
2330   // As an extension, Clang treats vector types as Scalar types.
2331   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2332   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2333     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2334       if (!ClassDecl->isStandardLayout())
2335         return false;
2336 
2337     // Default to 'true' for non-C++ class types.
2338     // FIXME: This is a bit dubious, but plain C structs should trivially meet
2339     // all the requirements of standard layout classes.
2340     return true;
2341   }
2342 
2343   // No other types can match.
2344   return false;
2345 }
2346 
2347 // This is effectively the intersection of isTrivialType and
2348 // isStandardLayoutType. We implement it directly to avoid redundant
2349 // conversions from a type to a CXXRecordDecl.
2350 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2351   const Type *ty = getTypePtr();
2352   if (ty->isDependentType())
2353     return false;
2354 
2355   if (hasNonTrivialObjCLifetime())
2356     return false;
2357 
2358   // C++11 [basic.types]p9:
2359   //   Scalar types, POD classes, arrays of such types, and cv-qualified
2360   //   versions of these types are collectively called trivial types.
2361   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2362   assert(BaseTy && "NULL element type");
2363 
2364   // Return false for incomplete types after skipping any incomplete array
2365   // types which are expressly allowed by the standard and thus our API.
2366   if (BaseTy->isIncompleteType())
2367     return false;
2368 
2369   // As an extension, Clang treats vector types as Scalar types.
2370   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2371   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2372     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2373       // C++11 [class]p10:
2374       //   A POD struct is a non-union class that is both a trivial class [...]
2375       if (!ClassDecl->isTrivial()) return false;
2376 
2377       // C++11 [class]p10:
2378       //   A POD struct is a non-union class that is both a trivial class and
2379       //   a standard-layout class [...]
2380       if (!ClassDecl->isStandardLayout()) return false;
2381 
2382       // C++11 [class]p10:
2383       //   A POD struct is a non-union class that is both a trivial class and
2384       //   a standard-layout class, and has no non-static data members of type
2385       //   non-POD struct, non-POD union (or array of such types). [...]
2386       //
2387       // We don't directly query the recursive aspect as the requirements for
2388       // both standard-layout classes and trivial classes apply recursively
2389       // already.
2390     }
2391 
2392     return true;
2393   }
2394 
2395   // No other types can match.
2396   return false;
2397 }
2398 
2399 bool Type::isAlignValT() const {
2400   if (const auto *ET = getAs<EnumType>()) {
2401     IdentifierInfo *II = ET->getDecl()->getIdentifier();
2402     if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2403       return true;
2404   }
2405   return false;
2406 }
2407 
2408 bool Type::isStdByteType() const {
2409   if (const auto *ET = getAs<EnumType>()) {
2410     IdentifierInfo *II = ET->getDecl()->getIdentifier();
2411     if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2412       return true;
2413   }
2414   return false;
2415 }
2416 
2417 bool Type::isPromotableIntegerType() const {
2418   if (const auto *BT = getAs<BuiltinType>())
2419     switch (BT->getKind()) {
2420     case BuiltinType::Bool:
2421     case BuiltinType::Char_S:
2422     case BuiltinType::Char_U:
2423     case BuiltinType::SChar:
2424     case BuiltinType::UChar:
2425     case BuiltinType::Short:
2426     case BuiltinType::UShort:
2427     case BuiltinType::WChar_S:
2428     case BuiltinType::WChar_U:
2429     case BuiltinType::Char8:
2430     case BuiltinType::Char16:
2431     case BuiltinType::Char32:
2432       return true;
2433     default:
2434       return false;
2435     }
2436 
2437   // Enumerated types are promotable to their compatible integer types
2438   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2439   if (const auto *ET = getAs<EnumType>()){
2440     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
2441         || ET->getDecl()->isScoped())
2442       return false;
2443 
2444     return true;
2445   }
2446 
2447   return false;
2448 }
2449 
2450 bool Type::isSpecifierType() const {
2451   // Note that this intentionally does not use the canonical type.
2452   switch (getTypeClass()) {
2453   case Builtin:
2454   case Record:
2455   case Enum:
2456   case Typedef:
2457   case Complex:
2458   case TypeOfExpr:
2459   case TypeOf:
2460   case TemplateTypeParm:
2461   case SubstTemplateTypeParm:
2462   case TemplateSpecialization:
2463   case Elaborated:
2464   case DependentName:
2465   case DependentTemplateSpecialization:
2466   case ObjCInterface:
2467   case ObjCObject:
2468   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
2469     return true;
2470   default:
2471     return false;
2472   }
2473 }
2474 
2475 ElaboratedTypeKeyword
2476 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2477   switch (TypeSpec) {
2478   default: return ETK_None;
2479   case TST_typename: return ETK_Typename;
2480   case TST_class: return ETK_Class;
2481   case TST_struct: return ETK_Struct;
2482   case TST_interface: return ETK_Interface;
2483   case TST_union: return ETK_Union;
2484   case TST_enum: return ETK_Enum;
2485   }
2486 }
2487 
2488 TagTypeKind
2489 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2490   switch(TypeSpec) {
2491   case TST_class: return TTK_Class;
2492   case TST_struct: return TTK_Struct;
2493   case TST_interface: return TTK_Interface;
2494   case TST_union: return TTK_Union;
2495   case TST_enum: return TTK_Enum;
2496   }
2497 
2498   llvm_unreachable("Type specifier is not a tag type kind.");
2499 }
2500 
2501 ElaboratedTypeKeyword
2502 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2503   switch (Kind) {
2504   case TTK_Class: return ETK_Class;
2505   case TTK_Struct: return ETK_Struct;
2506   case TTK_Interface: return ETK_Interface;
2507   case TTK_Union: return ETK_Union;
2508   case TTK_Enum: return ETK_Enum;
2509   }
2510   llvm_unreachable("Unknown tag type kind.");
2511 }
2512 
2513 TagTypeKind
2514 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2515   switch (Keyword) {
2516   case ETK_Class: return TTK_Class;
2517   case ETK_Struct: return TTK_Struct;
2518   case ETK_Interface: return TTK_Interface;
2519   case ETK_Union: return TTK_Union;
2520   case ETK_Enum: return TTK_Enum;
2521   case ETK_None: // Fall through.
2522   case ETK_Typename:
2523     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2524   }
2525   llvm_unreachable("Unknown elaborated type keyword.");
2526 }
2527 
2528 bool
2529 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2530   switch (Keyword) {
2531   case ETK_None:
2532   case ETK_Typename:
2533     return false;
2534   case ETK_Class:
2535   case ETK_Struct:
2536   case ETK_Interface:
2537   case ETK_Union:
2538   case ETK_Enum:
2539     return true;
2540   }
2541   llvm_unreachable("Unknown elaborated type keyword.");
2542 }
2543 
2544 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2545   switch (Keyword) {
2546   case ETK_None: return {};
2547   case ETK_Typename: return "typename";
2548   case ETK_Class:  return "class";
2549   case ETK_Struct: return "struct";
2550   case ETK_Interface: return "__interface";
2551   case ETK_Union:  return "union";
2552   case ETK_Enum:   return "enum";
2553   }
2554 
2555   llvm_unreachable("Unknown elaborated type keyword.");
2556 }
2557 
2558 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2559                          ElaboratedTypeKeyword Keyword,
2560                          NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2561                          ArrayRef<TemplateArgument> Args,
2562                          QualType Canon)
2563   : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
2564                     /*VariablyModified=*/false,
2565                     NNS && NNS->containsUnexpandedParameterPack()),
2566     NNS(NNS), Name(Name), NumArgs(Args.size()) {
2567   assert((!NNS || NNS->isDependent()) &&
2568          "DependentTemplateSpecializatonType requires dependent qualifier");
2569   TemplateArgument *ArgBuffer = getArgBuffer();
2570   for (const TemplateArgument &Arg : Args) {
2571     if (Arg.containsUnexpandedParameterPack())
2572       setContainsUnexpandedParameterPack();
2573 
2574     new (ArgBuffer++) TemplateArgument(Arg);
2575   }
2576 }
2577 
2578 void
2579 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2580                                              const ASTContext &Context,
2581                                              ElaboratedTypeKeyword Keyword,
2582                                              NestedNameSpecifier *Qualifier,
2583                                              const IdentifierInfo *Name,
2584                                              ArrayRef<TemplateArgument> Args) {
2585   ID.AddInteger(Keyword);
2586   ID.AddPointer(Qualifier);
2587   ID.AddPointer(Name);
2588   for (const TemplateArgument &Arg : Args)
2589     Arg.Profile(ID, Context);
2590 }
2591 
2592 bool Type::isElaboratedTypeSpecifier() const {
2593   ElaboratedTypeKeyword Keyword;
2594   if (const auto *Elab = dyn_cast<ElaboratedType>(this))
2595     Keyword = Elab->getKeyword();
2596   else if (const auto *DepName = dyn_cast<DependentNameType>(this))
2597     Keyword = DepName->getKeyword();
2598   else if (const auto *DepTST =
2599                dyn_cast<DependentTemplateSpecializationType>(this))
2600     Keyword = DepTST->getKeyword();
2601   else
2602     return false;
2603 
2604   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2605 }
2606 
2607 const char *Type::getTypeClassName() const {
2608   switch (TypeBits.TC) {
2609 #define ABSTRACT_TYPE(Derived, Base)
2610 #define TYPE(Derived, Base) case Derived: return #Derived;
2611 #include "clang/AST/TypeNodes.def"
2612   }
2613 
2614   llvm_unreachable("Invalid type class.");
2615 }
2616 
2617 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2618   switch (getKind()) {
2619   case Void:
2620     return "void";
2621   case Bool:
2622     return Policy.Bool ? "bool" : "_Bool";
2623   case Char_S:
2624     return "char";
2625   case Char_U:
2626     return "char";
2627   case SChar:
2628     return "signed char";
2629   case Short:
2630     return "short";
2631   case Int:
2632     return "int";
2633   case Long:
2634     return "long";
2635   case LongLong:
2636     return "long long";
2637   case Int128:
2638     return "__int128";
2639   case UChar:
2640     return "unsigned char";
2641   case UShort:
2642     return "unsigned short";
2643   case UInt:
2644     return "unsigned int";
2645   case ULong:
2646     return "unsigned long";
2647   case ULongLong:
2648     return "unsigned long long";
2649   case UInt128:
2650     return "unsigned __int128";
2651   case Half:
2652     return Policy.Half ? "half" : "__fp16";
2653   case Float:
2654     return "float";
2655   case Double:
2656     return "double";
2657   case LongDouble:
2658     return "long double";
2659   case Float16:
2660     return "_Float16";
2661   case Float128:
2662     return "__float128";
2663   case WChar_S:
2664   case WChar_U:
2665     return Policy.MSWChar ? "__wchar_t" : "wchar_t";
2666   case Char8:
2667     return "char8_t";
2668   case Char16:
2669     return "char16_t";
2670   case Char32:
2671     return "char32_t";
2672   case NullPtr:
2673     return "nullptr_t";
2674   case Overload:
2675     return "<overloaded function type>";
2676   case BoundMember:
2677     return "<bound member function type>";
2678   case PseudoObject:
2679     return "<pseudo-object type>";
2680   case Dependent:
2681     return "<dependent type>";
2682   case UnknownAny:
2683     return "<unknown type>";
2684   case ARCUnbridgedCast:
2685     return "<ARC unbridged cast type>";
2686   case BuiltinFn:
2687     return "<builtin fn type>";
2688   case ObjCId:
2689     return "id";
2690   case ObjCClass:
2691     return "Class";
2692   case ObjCSel:
2693     return "SEL";
2694 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2695   case Id: \
2696     return "__" #Access " " #ImgType "_t";
2697 #include "clang/Basic/OpenCLImageTypes.def"
2698   case OCLSampler:
2699     return "sampler_t";
2700   case OCLEvent:
2701     return "event_t";
2702   case OCLClkEvent:
2703     return "clk_event_t";
2704   case OCLQueue:
2705     return "queue_t";
2706   case OCLReserveID:
2707     return "reserve_id_t";
2708   case OMPArraySection:
2709     return "<OpenMP array section type>";
2710   }
2711 
2712   llvm_unreachable("Invalid builtin type.");
2713 }
2714 
2715 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
2716   if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
2717     return RefType->getPointeeType();
2718 
2719   // C++0x [basic.lval]:
2720   //   Class prvalues can have cv-qualified types; non-class prvalues always
2721   //   have cv-unqualified types.
2722   //
2723   // See also C99 6.3.2.1p2.
2724   if (!Context.getLangOpts().CPlusPlus ||
2725       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
2726     return getUnqualifiedType();
2727 
2728   return *this;
2729 }
2730 
2731 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
2732   switch (CC) {
2733   case CC_C: return "cdecl";
2734   case CC_X86StdCall: return "stdcall";
2735   case CC_X86FastCall: return "fastcall";
2736   case CC_X86ThisCall: return "thiscall";
2737   case CC_X86Pascal: return "pascal";
2738   case CC_X86VectorCall: return "vectorcall";
2739   case CC_Win64: return "ms_abi";
2740   case CC_X86_64SysV: return "sysv_abi";
2741   case CC_X86RegCall : return "regcall";
2742   case CC_AAPCS: return "aapcs";
2743   case CC_AAPCS_VFP: return "aapcs-vfp";
2744   case CC_IntelOclBicc: return "intel_ocl_bicc";
2745   case CC_SpirFunction: return "spir_function";
2746   case CC_OpenCLKernel: return "opencl_kernel";
2747   case CC_Swift: return "swiftcall";
2748   case CC_PreserveMost: return "preserve_most";
2749   case CC_PreserveAll: return "preserve_all";
2750   }
2751 
2752   llvm_unreachable("Invalid calling convention.");
2753 }
2754 
2755 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
2756                                      QualType canonical,
2757                                      const ExtProtoInfo &epi)
2758     : FunctionType(FunctionProto, result, canonical,
2759                    result->isDependentType(),
2760                    result->isInstantiationDependentType(),
2761                    result->isVariablyModifiedType(),
2762                    result->containsUnexpandedParameterPack(), epi.ExtInfo),
2763       NumParams(params.size()),
2764       NumExceptions(epi.ExceptionSpec.Exceptions.size()),
2765       ExceptionSpecType(epi.ExceptionSpec.Type),
2766       HasExtParameterInfos(epi.ExtParameterInfos != nullptr),
2767       Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
2768   assert(NumParams == params.size() && "function has too many parameters");
2769 
2770   FunctionTypeBits.TypeQuals = epi.TypeQuals;
2771   FunctionTypeBits.RefQualifier = epi.RefQualifier;
2772 
2773   // Fill in the trailing argument array.
2774   auto *argSlot = reinterpret_cast<QualType *>(this+1);
2775   for (unsigned i = 0; i != NumParams; ++i) {
2776     if (params[i]->isDependentType())
2777       setDependent();
2778     else if (params[i]->isInstantiationDependentType())
2779       setInstantiationDependent();
2780 
2781     if (params[i]->containsUnexpandedParameterPack())
2782       setContainsUnexpandedParameterPack();
2783 
2784     argSlot[i] = params[i];
2785   }
2786 
2787   if (getExceptionSpecType() == EST_Dynamic) {
2788     // Fill in the exception array.
2789     QualType *exnSlot = argSlot + NumParams;
2790     unsigned I = 0;
2791     for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
2792       // Note that, before C++17, a dependent exception specification does
2793       // *not* make a type dependent; it's not even part of the C++ type
2794       // system.
2795       if (ExceptionType->isInstantiationDependentType())
2796         setInstantiationDependent();
2797 
2798       if (ExceptionType->containsUnexpandedParameterPack())
2799         setContainsUnexpandedParameterPack();
2800 
2801       exnSlot[I++] = ExceptionType;
2802     }
2803   } else if (isComputedNoexcept(getExceptionSpecType())) {
2804     assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
2805     assert((getExceptionSpecType() == EST_DependentNoexcept) ==
2806            epi.ExceptionSpec.NoexceptExpr->isValueDependent());
2807 
2808     // Store the noexcept expression and context.
2809     auto **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
2810     *noexSlot = epi.ExceptionSpec.NoexceptExpr;
2811 
2812     if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
2813         epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
2814       setInstantiationDependent();
2815 
2816     if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
2817       setContainsUnexpandedParameterPack();
2818   } else if (getExceptionSpecType() == EST_Uninstantiated) {
2819     // Store the function decl from which we will resolve our
2820     // exception specification.
2821     auto **slot = reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2822     slot[0] = epi.ExceptionSpec.SourceDecl;
2823     slot[1] = epi.ExceptionSpec.SourceTemplate;
2824     // This exception specification doesn't make the type dependent, because
2825     // it's not instantiated as part of instantiating the type.
2826   } else if (getExceptionSpecType() == EST_Unevaluated) {
2827     // Store the function decl from which we will resolve our
2828     // exception specification.
2829     auto **slot = reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2830     slot[0] = epi.ExceptionSpec.SourceDecl;
2831   }
2832 
2833   // If this is a canonical type, and its exception specification is dependent,
2834   // then it's a dependent type. This only happens in C++17 onwards.
2835   if (isCanonicalUnqualified()) {
2836     if (getExceptionSpecType() == EST_Dynamic ||
2837         getExceptionSpecType() == EST_DependentNoexcept) {
2838       assert(hasDependentExceptionSpec() && "type should not be canonical");
2839       setDependent();
2840     }
2841   } else if (getCanonicalTypeInternal()->isDependentType()) {
2842     // Ask our canonical type whether our exception specification was dependent.
2843     setDependent();
2844   }
2845 
2846   if (epi.ExtParameterInfos) {
2847     auto *extParamInfos =
2848       const_cast<ExtParameterInfo *>(getExtParameterInfosBuffer());
2849     for (unsigned i = 0; i != NumParams; ++i)
2850       extParamInfos[i] = epi.ExtParameterInfos[i];
2851   }
2852 }
2853 
2854 bool FunctionProtoType::hasDependentExceptionSpec() const {
2855   if (Expr *NE = getNoexceptExpr())
2856     return NE->isValueDependent();
2857   for (QualType ET : exceptions())
2858     // A pack expansion with a non-dependent pattern is still dependent,
2859     // because we don't know whether the pattern is in the exception spec
2860     // or not (that depends on whether the pack has 0 expansions).
2861     if (ET->isDependentType() || ET->getAs<PackExpansionType>())
2862       return true;
2863   return false;
2864 }
2865 
2866 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
2867   if (Expr *NE = getNoexceptExpr())
2868     return NE->isInstantiationDependent();
2869   for (QualType ET : exceptions())
2870     if (ET->isInstantiationDependentType())
2871       return true;
2872   return false;
2873 }
2874 
2875 CanThrowResult FunctionProtoType::canThrow() const {
2876   switch (getExceptionSpecType()) {
2877   case EST_Unparsed:
2878   case EST_Unevaluated:
2879   case EST_Uninstantiated:
2880     llvm_unreachable("should not call this with unresolved exception specs");
2881 
2882   case EST_DynamicNone:
2883   case EST_BasicNoexcept:
2884   case EST_NoexceptTrue:
2885     return CT_Cannot;
2886 
2887   case EST_None:
2888   case EST_MSAny:
2889   case EST_NoexceptFalse:
2890     return CT_Can;
2891 
2892   case EST_Dynamic:
2893     // A dynamic exception specification is throwing unless every exception
2894     // type is an (unexpanded) pack expansion type.
2895     for (unsigned I = 0, N = NumExceptions; I != N; ++I)
2896       if (!getExceptionType(I)->getAs<PackExpansionType>())
2897         return CT_Can;
2898     return CT_Dependent;
2899 
2900   case EST_DependentNoexcept:
2901     return CT_Dependent;
2902   }
2903 
2904   llvm_unreachable("unexpected exception specification kind");
2905 }
2906 
2907 bool FunctionProtoType::isTemplateVariadic() const {
2908   for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
2909     if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
2910       return true;
2911 
2912   return false;
2913 }
2914 
2915 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2916                                 const QualType *ArgTys, unsigned NumParams,
2917                                 const ExtProtoInfo &epi,
2918                                 const ASTContext &Context, bool Canonical) {
2919   // We have to be careful not to get ambiguous profile encodings.
2920   // Note that valid type pointers are never ambiguous with anything else.
2921   //
2922   // The encoding grammar begins:
2923   //      type type* bool int bool
2924   // If that final bool is true, then there is a section for the EH spec:
2925   //      bool type*
2926   // This is followed by an optional "consumed argument" section of the
2927   // same length as the first type sequence:
2928   //      bool*
2929   // Finally, we have the ext info and trailing return type flag:
2930   //      int bool
2931   //
2932   // There is no ambiguity between the consumed arguments and an empty EH
2933   // spec because of the leading 'bool' which unambiguously indicates
2934   // whether the following bool is the EH spec or part of the arguments.
2935 
2936   ID.AddPointer(Result.getAsOpaquePtr());
2937   for (unsigned i = 0; i != NumParams; ++i)
2938     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
2939   // This method is relatively performance sensitive, so as a performance
2940   // shortcut, use one AddInteger call instead of four for the next four
2941   // fields.
2942   assert(!(unsigned(epi.Variadic) & ~1) &&
2943          !(unsigned(epi.TypeQuals) & ~255) &&
2944          !(unsigned(epi.RefQualifier) & ~3) &&
2945          !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
2946          "Values larger than expected.");
2947   ID.AddInteger(unsigned(epi.Variadic) +
2948                 (epi.TypeQuals << 1) +
2949                 (epi.RefQualifier << 9) +
2950                 (epi.ExceptionSpec.Type << 11));
2951   if (epi.ExceptionSpec.Type == EST_Dynamic) {
2952     for (QualType Ex : epi.ExceptionSpec.Exceptions)
2953       ID.AddPointer(Ex.getAsOpaquePtr());
2954   } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
2955     epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
2956   } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
2957              epi.ExceptionSpec.Type == EST_Unevaluated) {
2958     ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
2959   }
2960   if (epi.ExtParameterInfos) {
2961     for (unsigned i = 0; i != NumParams; ++i)
2962       ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
2963   }
2964   epi.ExtInfo.Profile(ID);
2965   ID.AddBoolean(epi.HasTrailingReturn);
2966 }
2967 
2968 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
2969                                 const ASTContext &Ctx) {
2970   Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
2971           Ctx, isCanonicalUnqualified());
2972 }
2973 
2974 QualType TypedefType::desugar() const {
2975   return getDecl()->getUnderlyingType();
2976 }
2977 
2978 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
2979     : Type(TypeOfExpr, can, E->isTypeDependent(),
2980            E->isInstantiationDependent(),
2981            E->getType()->isVariablyModifiedType(),
2982            E->containsUnexpandedParameterPack()),
2983       TOExpr(E) {}
2984 
2985 bool TypeOfExprType::isSugared() const {
2986   return !TOExpr->isTypeDependent();
2987 }
2988 
2989 QualType TypeOfExprType::desugar() const {
2990   if (isSugared())
2991     return getUnderlyingExpr()->getType();
2992 
2993   return QualType(this, 0);
2994 }
2995 
2996 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
2997                                       const ASTContext &Context, Expr *E) {
2998   E->Profile(ID, Context, true);
2999 }
3000 
3001 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
3002   // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3003   // decltype(e) denotes a unique dependent type." Hence a decltype type is
3004   // type-dependent even if its expression is only instantiation-dependent.
3005     : Type(Decltype, can, E->isInstantiationDependent(),
3006            E->isInstantiationDependent(),
3007            E->getType()->isVariablyModifiedType(),
3008            E->containsUnexpandedParameterPack()),
3009       E(E), UnderlyingType(underlyingType) {}
3010 
3011 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
3012 
3013 QualType DecltypeType::desugar() const {
3014   if (isSugared())
3015     return getUnderlyingType();
3016 
3017   return QualType(this, 0);
3018 }
3019 
3020 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
3021     : DecltypeType(E, Context.DependentTy), Context(Context) {}
3022 
3023 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3024                                     const ASTContext &Context, Expr *E) {
3025   E->Profile(ID, Context, true);
3026 }
3027 
3028 UnaryTransformType::UnaryTransformType(QualType BaseType,
3029                                        QualType UnderlyingType,
3030                                        UTTKind UKind,
3031                                        QualType CanonicalType)
3032     : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(),
3033            BaseType->isInstantiationDependentType(),
3034            BaseType->isVariablyModifiedType(),
3035            BaseType->containsUnexpandedParameterPack()),
3036       BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3037 
3038 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3039                                                          QualType BaseType,
3040                                                          UTTKind UKind)
3041      : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3042 
3043 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3044     : Type(TC, can, D->isDependentType(),
3045            /*InstantiationDependent=*/D->isDependentType(),
3046            /*VariablyModified=*/false,
3047            /*ContainsUnexpandedParameterPack=*/false),
3048       decl(const_cast<TagDecl*>(D)) {}
3049 
3050 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3051   for (auto I : decl->redecls()) {
3052     if (I->isCompleteDefinition() || I->isBeingDefined())
3053       return I;
3054   }
3055   // If there's no definition (not even in progress), return what we have.
3056   return decl;
3057 }
3058 
3059 TagDecl *TagType::getDecl() const {
3060   return getInterestingTagDecl(decl);
3061 }
3062 
3063 bool TagType::isBeingDefined() const {
3064   return getDecl()->isBeingDefined();
3065 }
3066 
3067 bool RecordType::hasConstFields() const {
3068   for (FieldDecl *FD : getDecl()->fields()) {
3069     QualType FieldTy = FD->getType();
3070     if (FieldTy.isConstQualified())
3071       return true;
3072     FieldTy = FieldTy.getCanonicalType();
3073     if (const auto *FieldRecTy = FieldTy->getAs<RecordType>())
3074       if (FieldRecTy->hasConstFields())
3075         return true;
3076   }
3077   return false;
3078 }
3079 
3080 bool AttributedType::isQualifier() const {
3081   switch (getAttrKind()) {
3082   // These are type qualifiers in the traditional C sense: they annotate
3083   // something about a specific value/variable of a type.  (They aren't
3084   // always part of the canonical type, though.)
3085   case AttributedType::attr_address_space:
3086   case AttributedType::attr_objc_gc:
3087   case AttributedType::attr_objc_ownership:
3088   case AttributedType::attr_objc_inert_unsafe_unretained:
3089   case AttributedType::attr_nonnull:
3090   case AttributedType::attr_nullable:
3091   case AttributedType::attr_null_unspecified:
3092     return true;
3093 
3094   // These aren't qualifiers; they rewrite the modified type to be a
3095   // semantically different type.
3096   case AttributedType::attr_regparm:
3097   case AttributedType::attr_vector_size:
3098   case AttributedType::attr_neon_vector_type:
3099   case AttributedType::attr_neon_polyvector_type:
3100   case AttributedType::attr_pcs:
3101   case AttributedType::attr_pcs_vfp:
3102   case AttributedType::attr_noreturn:
3103   case AttributedType::attr_cdecl:
3104   case AttributedType::attr_fastcall:
3105   case AttributedType::attr_stdcall:
3106   case AttributedType::attr_thiscall:
3107   case AttributedType::attr_regcall:
3108   case AttributedType::attr_pascal:
3109   case AttributedType::attr_swiftcall:
3110   case AttributedType::attr_vectorcall:
3111   case AttributedType::attr_inteloclbicc:
3112   case AttributedType::attr_preserve_most:
3113   case AttributedType::attr_preserve_all:
3114   case AttributedType::attr_ms_abi:
3115   case AttributedType::attr_sysv_abi:
3116   case AttributedType::attr_ptr32:
3117   case AttributedType::attr_ptr64:
3118   case AttributedType::attr_sptr:
3119   case AttributedType::attr_uptr:
3120   case AttributedType::attr_objc_kindof:
3121   case AttributedType::attr_ns_returns_retained:
3122   case AttributedType::attr_nocf_check:
3123     return false;
3124   }
3125   llvm_unreachable("bad attributed type kind");
3126 }
3127 
3128 bool AttributedType::isMSTypeSpec() const {
3129   switch (getAttrKind()) {
3130   default:  return false;
3131   case attr_ptr32:
3132   case attr_ptr64:
3133   case attr_sptr:
3134   case attr_uptr:
3135     return true;
3136   }
3137   llvm_unreachable("invalid attr kind");
3138 }
3139 
3140 bool AttributedType::isCallingConv() const {
3141   switch (getAttrKind()) {
3142   case attr_ptr32:
3143   case attr_ptr64:
3144   case attr_sptr:
3145   case attr_uptr:
3146   case attr_address_space:
3147   case attr_regparm:
3148   case attr_vector_size:
3149   case attr_neon_vector_type:
3150   case attr_neon_polyvector_type:
3151   case attr_objc_gc:
3152   case attr_objc_ownership:
3153   case attr_objc_inert_unsafe_unretained:
3154   case attr_noreturn:
3155   case attr_nonnull:
3156   case attr_ns_returns_retained:
3157   case attr_nullable:
3158   case attr_null_unspecified:
3159   case attr_objc_kindof:
3160   case attr_nocf_check:
3161     return false;
3162 
3163   case attr_pcs:
3164   case attr_pcs_vfp:
3165   case attr_cdecl:
3166   case attr_fastcall:
3167   case attr_stdcall:
3168   case attr_thiscall:
3169   case attr_regcall:
3170   case attr_swiftcall:
3171   case attr_vectorcall:
3172   case attr_pascal:
3173   case attr_ms_abi:
3174   case attr_sysv_abi:
3175   case attr_inteloclbicc:
3176   case attr_preserve_most:
3177   case attr_preserve_all:
3178     return true;
3179   }
3180   llvm_unreachable("invalid attr kind");
3181 }
3182 
3183 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3184   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3185 }
3186 
3187 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3188   return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3189 }
3190 
3191 SubstTemplateTypeParmPackType::
3192 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3193                               QualType Canon,
3194                               const TemplateArgument &ArgPack)
3195     : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
3196       Replaced(Param),
3197       Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) {}
3198 
3199 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3200   return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
3201 }
3202 
3203 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3204   Profile(ID, getReplacedParameter(), getArgumentPack());
3205 }
3206 
3207 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3208                                            const TemplateTypeParmType *Replaced,
3209                                             const TemplateArgument &ArgPack) {
3210   ID.AddPointer(Replaced);
3211   ID.AddInteger(ArgPack.pack_size());
3212   for (const auto &P : ArgPack.pack_elements())
3213     ID.AddPointer(P.getAsType().getAsOpaquePtr());
3214 }
3215 
3216 bool TemplateSpecializationType::
3217 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
3218                               bool &InstantiationDependent) {
3219   return anyDependentTemplateArguments(Args.arguments(),
3220                                        InstantiationDependent);
3221 }
3222 
3223 bool TemplateSpecializationType::
3224 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3225                               bool &InstantiationDependent) {
3226   for (const TemplateArgumentLoc &ArgLoc : Args) {
3227     if (ArgLoc.getArgument().isDependent()) {
3228       InstantiationDependent = true;
3229       return true;
3230     }
3231 
3232     if (ArgLoc.getArgument().isInstantiationDependent())
3233       InstantiationDependent = true;
3234   }
3235   return false;
3236 }
3237 
3238 TemplateSpecializationType::
3239 TemplateSpecializationType(TemplateName T,
3240                            ArrayRef<TemplateArgument> Args,
3241                            QualType Canon, QualType AliasedType)
3242   : Type(TemplateSpecialization,
3243          Canon.isNull()? QualType(this, 0) : Canon,
3244          Canon.isNull()? true : Canon->isDependentType(),
3245          Canon.isNull()? true : Canon->isInstantiationDependentType(),
3246          false,
3247          T.containsUnexpandedParameterPack()),
3248     Template(T), NumArgs(Args.size()), TypeAlias(!AliasedType.isNull()) {
3249   assert(!T.getAsDependentTemplateName() &&
3250          "Use DependentTemplateSpecializationType for dependent template-name");
3251   assert((T.getKind() == TemplateName::Template ||
3252           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3253           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
3254          "Unexpected template name for TemplateSpecializationType");
3255 
3256   auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3257   for (const TemplateArgument &Arg : Args) {
3258     // Update instantiation-dependent and variably-modified bits.
3259     // If the canonical type exists and is non-dependent, the template
3260     // specialization type can be non-dependent even if one of the type
3261     // arguments is. Given:
3262     //   template<typename T> using U = int;
3263     // U<T> is always non-dependent, irrespective of the type T.
3264     // However, U<Ts> contains an unexpanded parameter pack, even though
3265     // its expansion (and thus its desugared type) doesn't.
3266     if (Arg.isInstantiationDependent())
3267       setInstantiationDependent();
3268     if (Arg.getKind() == TemplateArgument::Type &&
3269         Arg.getAsType()->isVariablyModifiedType())
3270       setVariablyModified();
3271     if (Arg.containsUnexpandedParameterPack())
3272       setContainsUnexpandedParameterPack();
3273     new (TemplateArgs++) TemplateArgument(Arg);
3274   }
3275 
3276   // Store the aliased type if this is a type alias template specialization.
3277   if (TypeAlias) {
3278     auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3279     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
3280   }
3281 }
3282 
3283 void
3284 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3285                                     TemplateName T,
3286                                     ArrayRef<TemplateArgument> Args,
3287                                     const ASTContext &Context) {
3288   T.Profile(ID);
3289   for (const TemplateArgument &Arg : Args)
3290     Arg.Profile(ID, Context);
3291 }
3292 
3293 QualType
3294 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3295   if (!hasNonFastQualifiers())
3296     return QT.withFastQualifiers(getFastQualifiers());
3297 
3298   return Context.getQualifiedType(QT, *this);
3299 }
3300 
3301 QualType
3302 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3303   if (!hasNonFastQualifiers())
3304     return QualType(T, getFastQualifiers());
3305 
3306   return Context.getQualifiedType(T, *this);
3307 }
3308 
3309 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3310                                  QualType BaseType,
3311                                  ArrayRef<QualType> typeArgs,
3312                                  ArrayRef<ObjCProtocolDecl *> protocols,
3313                                  bool isKindOf) {
3314   ID.AddPointer(BaseType.getAsOpaquePtr());
3315   ID.AddInteger(typeArgs.size());
3316   for (auto typeArg : typeArgs)
3317     ID.AddPointer(typeArg.getAsOpaquePtr());
3318   ID.AddInteger(protocols.size());
3319   for (auto proto : protocols)
3320     ID.AddPointer(proto);
3321   ID.AddBoolean(isKindOf);
3322 }
3323 
3324 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3325   Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3326           llvm::makeArrayRef(qual_begin(), getNumProtocols()),
3327           isKindOfTypeAsWritten());
3328 }
3329 
3330 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
3331                                 const ObjCTypeParamDecl *OTPDecl,
3332                                 ArrayRef<ObjCProtocolDecl *> protocols) {
3333   ID.AddPointer(OTPDecl);
3334   ID.AddInteger(protocols.size());
3335   for (auto proto : protocols)
3336     ID.AddPointer(proto);
3337 }
3338 
3339 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
3340   Profile(ID, getDecl(),
3341           llvm::makeArrayRef(qual_begin(), getNumProtocols()));
3342 }
3343 
3344 namespace {
3345 
3346 /// The cached properties of a type.
3347 class CachedProperties {
3348   Linkage L;
3349   bool local;
3350 
3351 public:
3352   CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3353 
3354   Linkage getLinkage() const { return L; }
3355   bool hasLocalOrUnnamedType() const { return local; }
3356 
3357   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3358     Linkage MergedLinkage = minLinkage(L.L, R.L);
3359     return CachedProperties(MergedLinkage,
3360                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
3361   }
3362 };
3363 
3364 } // namespace
3365 
3366 static CachedProperties computeCachedProperties(const Type *T);
3367 
3368 namespace clang {
3369 
3370 /// The type-property cache.  This is templated so as to be
3371 /// instantiated at an internal type to prevent unnecessary symbol
3372 /// leakage.
3373 template <class Private> class TypePropertyCache {
3374 public:
3375   static CachedProperties get(QualType T) {
3376     return get(T.getTypePtr());
3377   }
3378 
3379   static CachedProperties get(const Type *T) {
3380     ensure(T);
3381     return CachedProperties(T->TypeBits.getLinkage(),
3382                             T->TypeBits.hasLocalOrUnnamedType());
3383   }
3384 
3385   static void ensure(const Type *T) {
3386     // If the cache is valid, we're okay.
3387     if (T->TypeBits.isCacheValid()) return;
3388 
3389     // If this type is non-canonical, ask its canonical type for the
3390     // relevant information.
3391     if (!T->isCanonicalUnqualified()) {
3392       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3393       ensure(CT);
3394       T->TypeBits.CacheValid = true;
3395       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3396       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3397       return;
3398     }
3399 
3400     // Compute the cached properties and then set the cache.
3401     CachedProperties Result = computeCachedProperties(T);
3402     T->TypeBits.CacheValid = true;
3403     T->TypeBits.CachedLinkage = Result.getLinkage();
3404     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3405   }
3406 };
3407 
3408 } // namespace clang
3409 
3410 // Instantiate the friend template at a private class.  In a
3411 // reasonable implementation, these symbols will be internal.
3412 // It is terrible that this is the best way to accomplish this.
3413 namespace {
3414 
3415 class Private {};
3416 
3417 } // namespace
3418 
3419 using Cache = TypePropertyCache<Private>;
3420 
3421 static CachedProperties computeCachedProperties(const Type *T) {
3422   switch (T->getTypeClass()) {
3423 #define TYPE(Class,Base)
3424 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3425 #include "clang/AST/TypeNodes.def"
3426     llvm_unreachable("didn't expect a non-canonical type here");
3427 
3428 #define TYPE(Class,Base)
3429 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3430 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3431 #include "clang/AST/TypeNodes.def"
3432     // Treat instantiation-dependent types as external.
3433     assert(T->isInstantiationDependentType());
3434     return CachedProperties(ExternalLinkage, false);
3435 
3436   case Type::Auto:
3437   case Type::DeducedTemplateSpecialization:
3438     // Give non-deduced 'auto' types external linkage. We should only see them
3439     // here in error recovery.
3440     return CachedProperties(ExternalLinkage, false);
3441 
3442   case Type::Builtin:
3443     // C++ [basic.link]p8:
3444     //   A type is said to have linkage if and only if:
3445     //     - it is a fundamental type (3.9.1); or
3446     return CachedProperties(ExternalLinkage, false);
3447 
3448   case Type::Record:
3449   case Type::Enum: {
3450     const TagDecl *Tag = cast<TagType>(T)->getDecl();
3451 
3452     // C++ [basic.link]p8:
3453     //     - it is a class or enumeration type that is named (or has a name
3454     //       for linkage purposes (7.1.3)) and the name has linkage; or
3455     //     -  it is a specialization of a class template (14); or
3456     Linkage L = Tag->getLinkageInternal();
3457     bool IsLocalOrUnnamed =
3458       Tag->getDeclContext()->isFunctionOrMethod() ||
3459       !Tag->hasNameForLinkage();
3460     return CachedProperties(L, IsLocalOrUnnamed);
3461   }
3462 
3463     // C++ [basic.link]p8:
3464     //   - it is a compound type (3.9.2) other than a class or enumeration,
3465     //     compounded exclusively from types that have linkage; or
3466   case Type::Complex:
3467     return Cache::get(cast<ComplexType>(T)->getElementType());
3468   case Type::Pointer:
3469     return Cache::get(cast<PointerType>(T)->getPointeeType());
3470   case Type::BlockPointer:
3471     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
3472   case Type::LValueReference:
3473   case Type::RValueReference:
3474     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
3475   case Type::MemberPointer: {
3476     const auto *MPT = cast<MemberPointerType>(T);
3477     return merge(Cache::get(MPT->getClass()),
3478                  Cache::get(MPT->getPointeeType()));
3479   }
3480   case Type::ConstantArray:
3481   case Type::IncompleteArray:
3482   case Type::VariableArray:
3483     return Cache::get(cast<ArrayType>(T)->getElementType());
3484   case Type::Vector:
3485   case Type::ExtVector:
3486     return Cache::get(cast<VectorType>(T)->getElementType());
3487   case Type::FunctionNoProto:
3488     return Cache::get(cast<FunctionType>(T)->getReturnType());
3489   case Type::FunctionProto: {
3490     const auto *FPT = cast<FunctionProtoType>(T);
3491     CachedProperties result = Cache::get(FPT->getReturnType());
3492     for (const auto &ai : FPT->param_types())
3493       result = merge(result, Cache::get(ai));
3494     return result;
3495   }
3496   case Type::ObjCInterface: {
3497     Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
3498     return CachedProperties(L, false);
3499   }
3500   case Type::ObjCObject:
3501     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
3502   case Type::ObjCObjectPointer:
3503     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
3504   case Type::Atomic:
3505     return Cache::get(cast<AtomicType>(T)->getValueType());
3506   case Type::Pipe:
3507     return Cache::get(cast<PipeType>(T)->getElementType());
3508   }
3509 
3510   llvm_unreachable("unhandled type class");
3511 }
3512 
3513 /// Determine the linkage of this type.
3514 Linkage Type::getLinkage() const {
3515   Cache::ensure(this);
3516   return TypeBits.getLinkage();
3517 }
3518 
3519 bool Type::hasUnnamedOrLocalType() const {
3520   Cache::ensure(this);
3521   return TypeBits.hasLocalOrUnnamedType();
3522 }
3523 
3524 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
3525   switch (T->getTypeClass()) {
3526 #define TYPE(Class,Base)
3527 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3528 #include "clang/AST/TypeNodes.def"
3529     llvm_unreachable("didn't expect a non-canonical type here");
3530 
3531 #define TYPE(Class,Base)
3532 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3533 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3534 #include "clang/AST/TypeNodes.def"
3535     // Treat instantiation-dependent types as external.
3536     assert(T->isInstantiationDependentType());
3537     return LinkageInfo::external();
3538 
3539   case Type::Builtin:
3540     return LinkageInfo::external();
3541 
3542   case Type::Auto:
3543   case Type::DeducedTemplateSpecialization:
3544     return LinkageInfo::external();
3545 
3546   case Type::Record:
3547   case Type::Enum:
3548     return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
3549 
3550   case Type::Complex:
3551     return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
3552   case Type::Pointer:
3553     return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
3554   case Type::BlockPointer:
3555     return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
3556   case Type::LValueReference:
3557   case Type::RValueReference:
3558     return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
3559   case Type::MemberPointer: {
3560     const auto *MPT = cast<MemberPointerType>(T);
3561     LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
3562     LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
3563     return LV;
3564   }
3565   case Type::ConstantArray:
3566   case Type::IncompleteArray:
3567   case Type::VariableArray:
3568     return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
3569   case Type::Vector:
3570   case Type::ExtVector:
3571     return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
3572   case Type::FunctionNoProto:
3573     return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
3574   case Type::FunctionProto: {
3575     const auto *FPT = cast<FunctionProtoType>(T);
3576     LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
3577     for (const auto &ai : FPT->param_types())
3578       LV.merge(computeTypeLinkageInfo(ai));
3579     return LV;
3580   }
3581   case Type::ObjCInterface:
3582     return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
3583   case Type::ObjCObject:
3584     return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
3585   case Type::ObjCObjectPointer:
3586     return computeTypeLinkageInfo(
3587         cast<ObjCObjectPointerType>(T)->getPointeeType());
3588   case Type::Atomic:
3589     return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
3590   case Type::Pipe:
3591     return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
3592   }
3593 
3594   llvm_unreachable("unhandled type class");
3595 }
3596 
3597 bool Type::isLinkageValid() const {
3598   if (!TypeBits.isCacheValid())
3599     return true;
3600 
3601   Linkage L = LinkageComputer{}
3602                   .computeTypeLinkageInfo(getCanonicalTypeInternal())
3603                   .getLinkage();
3604   return L == TypeBits.getLinkage();
3605 }
3606 
3607 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
3608   if (!T->isCanonicalUnqualified())
3609     return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
3610 
3611   LinkageInfo LV = computeTypeLinkageInfo(T);
3612   assert(LV.getLinkage() == T->getLinkage());
3613   return LV;
3614 }
3615 
3616 LinkageInfo Type::getLinkageAndVisibility() const {
3617   return LinkageComputer{}.getTypeLinkageAndVisibility(this);
3618 }
3619 
3620 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
3621   QualType type(this, 0);
3622   do {
3623     // Check whether this is an attributed type with nullability
3624     // information.
3625     if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
3626       if (auto nullability = attributed->getImmediateNullability())
3627         return nullability;
3628     }
3629 
3630     // Desugar the type. If desugaring does nothing, we're done.
3631     QualType desugared = type.getSingleStepDesugaredType(context);
3632     if (desugared.getTypePtr() == type.getTypePtr())
3633       return None;
3634 
3635     type = desugared;
3636   } while (true);
3637 }
3638 
3639 bool Type::canHaveNullability(bool ResultIfUnknown) const {
3640   QualType type = getCanonicalTypeInternal();
3641 
3642   switch (type->getTypeClass()) {
3643   // We'll only see canonical types here.
3644 #define NON_CANONICAL_TYPE(Class, Parent)       \
3645   case Type::Class:                             \
3646     llvm_unreachable("non-canonical type");
3647 #define TYPE(Class, Parent)
3648 #include "clang/AST/TypeNodes.def"
3649 
3650   // Pointer types.
3651   case Type::Pointer:
3652   case Type::BlockPointer:
3653   case Type::MemberPointer:
3654   case Type::ObjCObjectPointer:
3655     return true;
3656 
3657   // Dependent types that could instantiate to pointer types.
3658   case Type::UnresolvedUsing:
3659   case Type::TypeOfExpr:
3660   case Type::TypeOf:
3661   case Type::Decltype:
3662   case Type::UnaryTransform:
3663   case Type::TemplateTypeParm:
3664   case Type::SubstTemplateTypeParmPack:
3665   case Type::DependentName:
3666   case Type::DependentTemplateSpecialization:
3667   case Type::Auto:
3668     return ResultIfUnknown;
3669 
3670   // Dependent template specializations can instantiate to pointer
3671   // types unless they're known to be specializations of a class
3672   // template.
3673   case Type::TemplateSpecialization:
3674     if (TemplateDecl *templateDecl
3675           = cast<TemplateSpecializationType>(type.getTypePtr())
3676               ->getTemplateName().getAsTemplateDecl()) {
3677       if (isa<ClassTemplateDecl>(templateDecl))
3678         return false;
3679     }
3680     return ResultIfUnknown;
3681 
3682   case Type::Builtin:
3683     switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
3684       // Signed, unsigned, and floating-point types cannot have nullability.
3685 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3686 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3687 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
3688 #define BUILTIN_TYPE(Id, SingletonId)
3689 #include "clang/AST/BuiltinTypes.def"
3690       return false;
3691 
3692     // Dependent types that could instantiate to a pointer type.
3693     case BuiltinType::Dependent:
3694     case BuiltinType::Overload:
3695     case BuiltinType::BoundMember:
3696     case BuiltinType::PseudoObject:
3697     case BuiltinType::UnknownAny:
3698     case BuiltinType::ARCUnbridgedCast:
3699       return ResultIfUnknown;
3700 
3701     case BuiltinType::Void:
3702     case BuiltinType::ObjCId:
3703     case BuiltinType::ObjCClass:
3704     case BuiltinType::ObjCSel:
3705 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3706     case BuiltinType::Id:
3707 #include "clang/Basic/OpenCLImageTypes.def"
3708     case BuiltinType::OCLSampler:
3709     case BuiltinType::OCLEvent:
3710     case BuiltinType::OCLClkEvent:
3711     case BuiltinType::OCLQueue:
3712     case BuiltinType::OCLReserveID:
3713     case BuiltinType::BuiltinFn:
3714     case BuiltinType::NullPtr:
3715     case BuiltinType::OMPArraySection:
3716       return false;
3717     }
3718     llvm_unreachable("unknown builtin type");
3719 
3720   // Non-pointer types.
3721   case Type::Complex:
3722   case Type::LValueReference:
3723   case Type::RValueReference:
3724   case Type::ConstantArray:
3725   case Type::IncompleteArray:
3726   case Type::VariableArray:
3727   case Type::DependentSizedArray:
3728   case Type::DependentSizedExtVector:
3729   case Type::Vector:
3730   case Type::ExtVector:
3731   case Type::DependentAddressSpace:
3732   case Type::FunctionProto:
3733   case Type::FunctionNoProto:
3734   case Type::Record:
3735   case Type::DeducedTemplateSpecialization:
3736   case Type::Enum:
3737   case Type::InjectedClassName:
3738   case Type::PackExpansion:
3739   case Type::ObjCObject:
3740   case Type::ObjCInterface:
3741   case Type::Atomic:
3742   case Type::Pipe:
3743     return false;
3744   }
3745   llvm_unreachable("bad type kind!");
3746 }
3747 
3748 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
3749   if (getAttrKind() == AttributedType::attr_nonnull)
3750     return NullabilityKind::NonNull;
3751   if (getAttrKind() == AttributedType::attr_nullable)
3752     return NullabilityKind::Nullable;
3753   if (getAttrKind() == AttributedType::attr_null_unspecified)
3754     return NullabilityKind::Unspecified;
3755   return None;
3756 }
3757 
3758 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
3759   if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
3760     if (auto nullability = attributed->getImmediateNullability()) {
3761       T = attributed->getModifiedType();
3762       return nullability;
3763     }
3764   }
3765 
3766   return None;
3767 }
3768 
3769 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
3770   const auto *objcPtr = getAs<ObjCObjectPointerType>();
3771   if (!objcPtr)
3772     return false;
3773 
3774   if (objcPtr->isObjCIdType()) {
3775     // id is always okay.
3776     return true;
3777   }
3778 
3779   // Blocks are NSObjects.
3780   if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
3781     if (iface->getIdentifier() != ctx.getNSObjectName())
3782       return false;
3783 
3784     // Continue to check qualifiers, below.
3785   } else if (objcPtr->isObjCQualifiedIdType()) {
3786     // Continue to check qualifiers, below.
3787   } else {
3788     return false;
3789   }
3790 
3791   // Check protocol qualifiers.
3792   for (ObjCProtocolDecl *proto : objcPtr->quals()) {
3793     // Blocks conform to NSObject and NSCopying.
3794     if (proto->getIdentifier() != ctx.getNSObjectName() &&
3795         proto->getIdentifier() != ctx.getNSCopyingName())
3796       return false;
3797   }
3798 
3799   return true;
3800 }
3801 
3802 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
3803   if (isObjCARCImplicitlyUnretainedType())
3804     return Qualifiers::OCL_ExplicitNone;
3805   return Qualifiers::OCL_Strong;
3806 }
3807 
3808 bool Type::isObjCARCImplicitlyUnretainedType() const {
3809   assert(isObjCLifetimeType() &&
3810          "cannot query implicit lifetime for non-inferrable type");
3811 
3812   const Type *canon = getCanonicalTypeInternal().getTypePtr();
3813 
3814   // Walk down to the base type.  We don't care about qualifiers for this.
3815   while (const auto *array = dyn_cast<ArrayType>(canon))
3816     canon = array->getElementType().getTypePtr();
3817 
3818   if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
3819     // Class and Class<Protocol> don't require retention.
3820     if (opt->getObjectType()->isObjCClass())
3821       return true;
3822   }
3823 
3824   return false;
3825 }
3826 
3827 bool Type::isObjCNSObjectType() const {
3828   const Type *cur = this;
3829   while (true) {
3830     if (const auto *typedefType = dyn_cast<TypedefType>(cur))
3831       return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
3832 
3833     // Single-step desugar until we run out of sugar.
3834     QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
3835     if (next.getTypePtr() == cur) return false;
3836     cur = next.getTypePtr();
3837   }
3838 }
3839 
3840 bool Type::isObjCIndependentClassType() const {
3841   if (const auto *typedefType = dyn_cast<TypedefType>(this))
3842     return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
3843   return false;
3844 }
3845 
3846 bool Type::isObjCRetainableType() const {
3847   return isObjCObjectPointerType() ||
3848          isBlockPointerType() ||
3849          isObjCNSObjectType();
3850 }
3851 
3852 bool Type::isObjCIndirectLifetimeType() const {
3853   if (isObjCLifetimeType())
3854     return true;
3855   if (const auto *OPT = getAs<PointerType>())
3856     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
3857   if (const auto *Ref = getAs<ReferenceType>())
3858     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
3859   if (const auto *MemPtr = getAs<MemberPointerType>())
3860     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
3861   return false;
3862 }
3863 
3864 /// Returns true if objects of this type have lifetime semantics under
3865 /// ARC.
3866 bool Type::isObjCLifetimeType() const {
3867   const Type *type = this;
3868   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
3869     type = array->getElementType().getTypePtr();
3870   return type->isObjCRetainableType();
3871 }
3872 
3873 /// Determine whether the given type T is a "bridgable" Objective-C type,
3874 /// which is either an Objective-C object pointer type or an
3875 bool Type::isObjCARCBridgableType() const {
3876   return isObjCObjectPointerType() || isBlockPointerType();
3877 }
3878 
3879 /// Determine whether the given type T is a "bridgeable" C type.
3880 bool Type::isCARCBridgableType() const {
3881   const auto *Pointer = getAs<PointerType>();
3882   if (!Pointer)
3883     return false;
3884 
3885   QualType Pointee = Pointer->getPointeeType();
3886   return Pointee->isVoidType() || Pointee->isRecordType();
3887 }
3888 
3889 bool Type::hasSizedVLAType() const {
3890   if (!isVariablyModifiedType()) return false;
3891 
3892   if (const auto *ptr = getAs<PointerType>())
3893     return ptr->getPointeeType()->hasSizedVLAType();
3894   if (const auto *ref = getAs<ReferenceType>())
3895     return ref->getPointeeType()->hasSizedVLAType();
3896   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
3897     if (isa<VariableArrayType>(arr) &&
3898         cast<VariableArrayType>(arr)->getSizeExpr())
3899       return true;
3900 
3901     return arr->getElementType()->hasSizedVLAType();
3902   }
3903 
3904   return false;
3905 }
3906 
3907 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
3908   switch (type.getObjCLifetime()) {
3909   case Qualifiers::OCL_None:
3910   case Qualifiers::OCL_ExplicitNone:
3911   case Qualifiers::OCL_Autoreleasing:
3912     break;
3913 
3914   case Qualifiers::OCL_Strong:
3915     return DK_objc_strong_lifetime;
3916   case Qualifiers::OCL_Weak:
3917     return DK_objc_weak_lifetime;
3918   }
3919 
3920   if (const auto *RT =
3921           type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
3922     const RecordDecl *RD = RT->getDecl();
3923     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3924       /// Check if this is a C++ object with a non-trivial destructor.
3925       if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
3926         return DK_cxx_destructor;
3927     } else {
3928       /// Check if this is a C struct that is non-trivial to destroy or an array
3929       /// that contains such a struct.
3930       if (RD->isNonTrivialToPrimitiveDestroy())
3931         return DK_nontrivial_c_struct;
3932     }
3933   }
3934 
3935   return DK_none;
3936 }
3937 
3938 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
3939   return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();
3940 }
3941