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