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 "llvm/ADT/APSInt.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 using namespace clang;
30
isStrictSupersetOf(Qualifiers Other) const31 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
32 return (*this != Other) &&
33 // CVR qualifiers superset
34 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
35 // ObjC GC qualifiers superset
36 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
37 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
38 // Address space superset.
39 ((getAddressSpace() == Other.getAddressSpace()) ||
40 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
41 // Lifetime qualifier superset.
42 ((getObjCLifetime() == Other.getObjCLifetime()) ||
43 (hasObjCLifetime() && !Other.hasObjCLifetime()));
44 }
45
getBaseTypeIdentifier() const46 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
47 const Type* ty = getTypePtr();
48 NamedDecl *ND = NULL;
49 if (ty->isPointerType() || ty->isReferenceType())
50 return ty->getPointeeType().getBaseTypeIdentifier();
51 else if (ty->isRecordType())
52 ND = ty->getAs<RecordType>()->getDecl();
53 else if (ty->isEnumeralType())
54 ND = ty->getAs<EnumType>()->getDecl();
55 else if (ty->getTypeClass() == Type::Typedef)
56 ND = ty->getAs<TypedefType>()->getDecl();
57 else if (ty->isArrayType())
58 return ty->castAsArrayTypeUnsafe()->
59 getElementType().getBaseTypeIdentifier();
60
61 if (ND)
62 return ND->getIdentifier();
63 return NULL;
64 }
65
isConstant(QualType T,ASTContext & Ctx)66 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
67 if (T.isConstQualified())
68 return true;
69
70 if (const ArrayType *AT = Ctx.getAsArrayType(T))
71 return AT->getElementType().isConstant(Ctx);
72
73 return false;
74 }
75
getNumAddressingBits(ASTContext & Context,QualType ElementType,const llvm::APInt & NumElements)76 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
77 QualType ElementType,
78 const llvm::APInt &NumElements) {
79 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
80
81 // Fast path the common cases so we can avoid the conservative computation
82 // below, which in common cases allocates "large" APSInt values, which are
83 // slow.
84
85 // If the element size is a power of 2, we can directly compute the additional
86 // number of addressing bits beyond those required for the element count.
87 if (llvm::isPowerOf2_64(ElementSize)) {
88 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
89 }
90
91 // If both the element count and element size fit in 32-bits, we can do the
92 // computation directly in 64-bits.
93 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
94 (NumElements.getZExtValue() >> 32) == 0) {
95 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
96 return 64 - llvm::countLeadingZeros(TotalSize);
97 }
98
99 // Otherwise, use APSInt to handle arbitrary sized values.
100 llvm::APSInt SizeExtended(NumElements, true);
101 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
102 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
103 SizeExtended.getBitWidth()) * 2);
104
105 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
106 TotalSize *= SizeExtended;
107
108 return TotalSize.getActiveBits();
109 }
110
getMaxSizeBits(ASTContext & Context)111 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
112 unsigned Bits = Context.getTypeSize(Context.getSizeType());
113
114 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
115 // integer (see PR8256). We can do this as currently there is no hardware
116 // that supports full 64-bit virtual space.
117 if (Bits > 61)
118 Bits = 61;
119
120 return Bits;
121 }
122
DependentSizedArrayType(const ASTContext & Context,QualType et,QualType can,Expr * e,ArraySizeModifier sm,unsigned tq,SourceRange brackets)123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
124 QualType et, QualType can,
125 Expr *e, ArraySizeModifier sm,
126 unsigned tq,
127 SourceRange brackets)
128 : ArrayType(DependentSizedArray, et, can, sm, tq,
129 (et->containsUnexpandedParameterPack() ||
130 (e && e->containsUnexpandedParameterPack()))),
131 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
132 {
133 }
134
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType ET,ArraySizeModifier SizeMod,unsigned TypeQuals,Expr * E)135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
136 const ASTContext &Context,
137 QualType ET,
138 ArraySizeModifier SizeMod,
139 unsigned TypeQuals,
140 Expr *E) {
141 ID.AddPointer(ET.getAsOpaquePtr());
142 ID.AddInteger(SizeMod);
143 ID.AddInteger(TypeQuals);
144 E->Profile(ID, Context, true);
145 }
146
DependentSizedExtVectorType(const ASTContext & Context,QualType ElementType,QualType can,Expr * SizeExpr,SourceLocation loc)147 DependentSizedExtVectorType::DependentSizedExtVectorType(const
148 ASTContext &Context,
149 QualType ElementType,
150 QualType can,
151 Expr *SizeExpr,
152 SourceLocation loc)
153 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
154 /*InstantiationDependent=*/true,
155 ElementType->isVariablyModifiedType(),
156 (ElementType->containsUnexpandedParameterPack() ||
157 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
158 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
159 loc(loc)
160 {
161 }
162
163 void
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType ElementType,Expr * SizeExpr)164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
165 const ASTContext &Context,
166 QualType ElementType, Expr *SizeExpr) {
167 ID.AddPointer(ElementType.getAsOpaquePtr());
168 SizeExpr->Profile(ID, Context, true);
169 }
170
VectorType(QualType vecType,unsigned nElements,QualType canonType,VectorKind vecKind)171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
172 VectorKind vecKind)
173 : Type(Vector, canonType, vecType->isDependentType(),
174 vecType->isInstantiationDependentType(),
175 vecType->isVariablyModifiedType(),
176 vecType->containsUnexpandedParameterPack()),
177 ElementType(vecType)
178 {
179 VectorTypeBits.VecKind = vecKind;
180 VectorTypeBits.NumElements = nElements;
181 }
182
VectorType(TypeClass tc,QualType vecType,unsigned nElements,QualType canonType,VectorKind vecKind)183 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
184 QualType canonType, VectorKind vecKind)
185 : Type(tc, canonType, vecType->isDependentType(),
186 vecType->isInstantiationDependentType(),
187 vecType->isVariablyModifiedType(),
188 vecType->containsUnexpandedParameterPack()),
189 ElementType(vecType)
190 {
191 VectorTypeBits.VecKind = vecKind;
192 VectorTypeBits.NumElements = nElements;
193 }
194
195 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
196 /// element type of the array, potentially with type qualifiers missing.
197 /// This method should never be used when type qualifiers are meaningful.
getArrayElementTypeNoTypeQual() const198 const Type *Type::getArrayElementTypeNoTypeQual() const {
199 // If this is directly an array type, return it.
200 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
201 return ATy->getElementType().getTypePtr();
202
203 // If the canonical form of this type isn't the right kind, reject it.
204 if (!isa<ArrayType>(CanonicalType))
205 return 0;
206
207 // If this is a typedef for an array type, strip the typedef off without
208 // losing all typedef information.
209 return cast<ArrayType>(getUnqualifiedDesugaredType())
210 ->getElementType().getTypePtr();
211 }
212
213 /// getDesugaredType - Return the specified type with any "sugar" removed from
214 /// the type. This takes off typedefs, typeof's etc. If the outer level of
215 /// the type is already concrete, it returns it unmodified. This is similar
216 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
217 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
218 /// concrete.
getDesugaredType(QualType T,const ASTContext & Context)219 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
220 SplitQualType split = getSplitDesugaredType(T);
221 return Context.getQualifiedType(split.Ty, split.Quals);
222 }
223
getSingleStepDesugaredTypeImpl(QualType type,const ASTContext & Context)224 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
225 const ASTContext &Context) {
226 SplitQualType split = type.split();
227 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
228 return Context.getQualifiedType(desugar, split.Quals);
229 }
230
getLocallyUnqualifiedSingleStepDesugaredType() const231 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
232 switch (getTypeClass()) {
233 #define ABSTRACT_TYPE(Class, Parent)
234 #define TYPE(Class, Parent) \
235 case Type::Class: { \
236 const Class##Type *ty = cast<Class##Type>(this); \
237 if (!ty->isSugared()) return QualType(ty, 0); \
238 return ty->desugar(); \
239 }
240 #include "clang/AST/TypeNodes.def"
241 }
242 llvm_unreachable("bad type kind!");
243 }
244
getSplitDesugaredType(QualType T)245 SplitQualType QualType::getSplitDesugaredType(QualType T) {
246 QualifierCollector Qs;
247
248 QualType Cur = T;
249 while (true) {
250 const Type *CurTy = Qs.strip(Cur);
251 switch (CurTy->getTypeClass()) {
252 #define ABSTRACT_TYPE(Class, Parent)
253 #define TYPE(Class, Parent) \
254 case Type::Class: { \
255 const Class##Type *Ty = cast<Class##Type>(CurTy); \
256 if (!Ty->isSugared()) \
257 return SplitQualType(Ty, Qs); \
258 Cur = Ty->desugar(); \
259 break; \
260 }
261 #include "clang/AST/TypeNodes.def"
262 }
263 }
264 }
265
getSplitUnqualifiedTypeImpl(QualType type)266 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
267 SplitQualType split = type.split();
268
269 // All the qualifiers we've seen so far.
270 Qualifiers quals = split.Quals;
271
272 // The last type node we saw with any nodes inside it.
273 const Type *lastTypeWithQuals = split.Ty;
274
275 while (true) {
276 QualType next;
277
278 // Do a single-step desugar, aborting the loop if the type isn't
279 // sugared.
280 switch (split.Ty->getTypeClass()) {
281 #define ABSTRACT_TYPE(Class, Parent)
282 #define TYPE(Class, Parent) \
283 case Type::Class: { \
284 const Class##Type *ty = cast<Class##Type>(split.Ty); \
285 if (!ty->isSugared()) goto done; \
286 next = ty->desugar(); \
287 break; \
288 }
289 #include "clang/AST/TypeNodes.def"
290 }
291
292 // Otherwise, split the underlying type. If that yields qualifiers,
293 // update the information.
294 split = next.split();
295 if (!split.Quals.empty()) {
296 lastTypeWithQuals = split.Ty;
297 quals.addConsistentQualifiers(split.Quals);
298 }
299 }
300
301 done:
302 return SplitQualType(lastTypeWithQuals, quals);
303 }
304
IgnoreParens(QualType T)305 QualType QualType::IgnoreParens(QualType T) {
306 // FIXME: this seems inherently un-qualifiers-safe.
307 while (const ParenType *PT = T->getAs<ParenType>())
308 T = PT->getInnerType();
309 return T;
310 }
311
312 /// \brief This will check for a T (which should be a Type which can act as
313 /// sugar, such as a TypedefType) by removing any existing sugar until it
314 /// reaches a T or a non-sugared type.
getAsSugar(const Type * Cur)315 template<typename T> static const T *getAsSugar(const Type *Cur) {
316 while (true) {
317 if (const T *Sugar = dyn_cast<T>(Cur))
318 return Sugar;
319 switch (Cur->getTypeClass()) {
320 #define ABSTRACT_TYPE(Class, Parent)
321 #define TYPE(Class, Parent) \
322 case Type::Class: { \
323 const Class##Type *Ty = cast<Class##Type>(Cur); \
324 if (!Ty->isSugared()) return 0; \
325 Cur = Ty->desugar().getTypePtr(); \
326 break; \
327 }
328 #include "clang/AST/TypeNodes.def"
329 }
330 }
331 }
332
getAs() const333 template <> const TypedefType *Type::getAs() const {
334 return getAsSugar<TypedefType>(this);
335 }
336
getAs() const337 template <> const TemplateSpecializationType *Type::getAs() const {
338 return getAsSugar<TemplateSpecializationType>(this);
339 }
340
getAs() const341 template <> const AttributedType *Type::getAs() const {
342 return getAsSugar<AttributedType>(this);
343 }
344
345 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
346 /// sugar off the given type. This should produce an object of the
347 /// same dynamic type as the canonical type.
getUnqualifiedDesugaredType() const348 const Type *Type::getUnqualifiedDesugaredType() const {
349 const Type *Cur = this;
350
351 while (true) {
352 switch (Cur->getTypeClass()) {
353 #define ABSTRACT_TYPE(Class, Parent)
354 #define TYPE(Class, Parent) \
355 case Class: { \
356 const Class##Type *Ty = cast<Class##Type>(Cur); \
357 if (!Ty->isSugared()) return Cur; \
358 Cur = Ty->desugar().getTypePtr(); \
359 break; \
360 }
361 #include "clang/AST/TypeNodes.def"
362 }
363 }
364 }
isClassType() const365 bool Type::isClassType() const {
366 if (const RecordType *RT = getAs<RecordType>())
367 return RT->getDecl()->isClass();
368 return false;
369 }
isStructureType() const370 bool Type::isStructureType() const {
371 if (const RecordType *RT = getAs<RecordType>())
372 return RT->getDecl()->isStruct();
373 return false;
374 }
isInterfaceType() const375 bool Type::isInterfaceType() const {
376 if (const RecordType *RT = getAs<RecordType>())
377 return RT->getDecl()->isInterface();
378 return false;
379 }
isStructureOrClassType() const380 bool Type::isStructureOrClassType() const {
381 if (const RecordType *RT = getAs<RecordType>())
382 return RT->getDecl()->isStruct() || RT->getDecl()->isClass() ||
383 RT->getDecl()->isInterface();
384 return false;
385 }
isVoidPointerType() const386 bool Type::isVoidPointerType() const {
387 if (const PointerType *PT = getAs<PointerType>())
388 return PT->getPointeeType()->isVoidType();
389 return false;
390 }
391
isUnionType() const392 bool Type::isUnionType() const {
393 if (const RecordType *RT = getAs<RecordType>())
394 return RT->getDecl()->isUnion();
395 return false;
396 }
397
isComplexType() const398 bool Type::isComplexType() const {
399 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
400 return CT->getElementType()->isFloatingType();
401 return false;
402 }
403
isComplexIntegerType() const404 bool Type::isComplexIntegerType() const {
405 // Check for GCC complex integer extension.
406 return getAsComplexIntegerType();
407 }
408
getAsComplexIntegerType() const409 const ComplexType *Type::getAsComplexIntegerType() const {
410 if (const ComplexType *Complex = getAs<ComplexType>())
411 if (Complex->getElementType()->isIntegerType())
412 return Complex;
413 return 0;
414 }
415
getPointeeType() const416 QualType Type::getPointeeType() const {
417 if (const PointerType *PT = getAs<PointerType>())
418 return PT->getPointeeType();
419 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
420 return OPT->getPointeeType();
421 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
422 return BPT->getPointeeType();
423 if (const ReferenceType *RT = getAs<ReferenceType>())
424 return RT->getPointeeType();
425 return QualType();
426 }
427
getAsStructureType() const428 const RecordType *Type::getAsStructureType() const {
429 // If this is directly a structure type, return it.
430 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
431 if (RT->getDecl()->isStruct())
432 return RT;
433 }
434
435 // If the canonical form of this type isn't the right kind, reject it.
436 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
437 if (!RT->getDecl()->isStruct())
438 return 0;
439
440 // If this is a typedef for a structure type, strip the typedef off without
441 // losing all typedef information.
442 return cast<RecordType>(getUnqualifiedDesugaredType());
443 }
444 return 0;
445 }
446
getAsUnionType() const447 const RecordType *Type::getAsUnionType() const {
448 // If this is directly a union type, return it.
449 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
450 if (RT->getDecl()->isUnion())
451 return RT;
452 }
453
454 // If the canonical form of this type isn't the right kind, reject it.
455 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
456 if (!RT->getDecl()->isUnion())
457 return 0;
458
459 // If this is a typedef for a union type, strip the typedef off without
460 // losing all typedef information.
461 return cast<RecordType>(getUnqualifiedDesugaredType());
462 }
463
464 return 0;
465 }
466
ObjCObjectType(QualType Canonical,QualType Base,ObjCProtocolDecl * const * Protocols,unsigned NumProtocols)467 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
468 ObjCProtocolDecl * const *Protocols,
469 unsigned NumProtocols)
470 : Type(ObjCObject, Canonical, false, false, false, false),
471 BaseType(Base)
472 {
473 ObjCObjectTypeBits.NumProtocols = NumProtocols;
474 assert(getNumProtocols() == NumProtocols &&
475 "bitfield overflow in protocol count");
476 if (NumProtocols)
477 memcpy(getProtocolStorage(), Protocols,
478 NumProtocols * sizeof(ObjCProtocolDecl*));
479 }
480
getAsObjCQualifiedInterfaceType() const481 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
482 // There is no sugar for ObjCObjectType's, just return the canonical
483 // type pointer if it is the right class. There is no typedef information to
484 // return and these cannot be Address-space qualified.
485 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
486 if (T->getNumProtocols() && T->getInterface())
487 return T;
488 return 0;
489 }
490
isObjCQualifiedInterfaceType() const491 bool Type::isObjCQualifiedInterfaceType() const {
492 return getAsObjCQualifiedInterfaceType() != 0;
493 }
494
getAsObjCQualifiedIdType() const495 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
496 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
497 // type pointer if it is the right class.
498 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
499 if (OPT->isObjCQualifiedIdType())
500 return OPT;
501 }
502 return 0;
503 }
504
getAsObjCQualifiedClassType() const505 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
506 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
507 // type pointer if it is the right class.
508 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
509 if (OPT->isObjCQualifiedClassType())
510 return OPT;
511 }
512 return 0;
513 }
514
getAsObjCInterfacePointerType() const515 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
516 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
517 if (OPT->getInterfaceType())
518 return OPT;
519 }
520 return 0;
521 }
522
getPointeeCXXRecordDecl() const523 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
524 QualType PointeeType;
525 if (const PointerType *PT = getAs<PointerType>())
526 PointeeType = PT->getPointeeType();
527 else if (const ReferenceType *RT = getAs<ReferenceType>())
528 PointeeType = RT->getPointeeType();
529 else
530 return 0;
531
532 if (const RecordType *RT = PointeeType->getAs<RecordType>())
533 return dyn_cast<CXXRecordDecl>(RT->getDecl());
534
535 return 0;
536 }
537
getAsCXXRecordDecl() const538 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
539 if (const RecordType *RT = getAs<RecordType>())
540 return dyn_cast<CXXRecordDecl>(RT->getDecl());
541 else if (const InjectedClassNameType *Injected
542 = getAs<InjectedClassNameType>())
543 return Injected->getDecl();
544
545 return 0;
546 }
547
548 namespace {
549 class GetContainedAutoVisitor :
550 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
551 public:
552 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
Visit(QualType T)553 AutoType *Visit(QualType T) {
554 if (T.isNull())
555 return 0;
556 return Visit(T.getTypePtr());
557 }
558
559 // The 'auto' type itself.
VisitAutoType(const AutoType * AT)560 AutoType *VisitAutoType(const AutoType *AT) {
561 return const_cast<AutoType*>(AT);
562 }
563
564 // Only these types can contain the desired 'auto' type.
VisitPointerType(const PointerType * T)565 AutoType *VisitPointerType(const PointerType *T) {
566 return Visit(T->getPointeeType());
567 }
VisitBlockPointerType(const BlockPointerType * T)568 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
569 return Visit(T->getPointeeType());
570 }
VisitReferenceType(const ReferenceType * T)571 AutoType *VisitReferenceType(const ReferenceType *T) {
572 return Visit(T->getPointeeTypeAsWritten());
573 }
VisitMemberPointerType(const MemberPointerType * T)574 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
575 return Visit(T->getPointeeType());
576 }
VisitArrayType(const ArrayType * T)577 AutoType *VisitArrayType(const ArrayType *T) {
578 return Visit(T->getElementType());
579 }
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)580 AutoType *VisitDependentSizedExtVectorType(
581 const DependentSizedExtVectorType *T) {
582 return Visit(T->getElementType());
583 }
VisitVectorType(const VectorType * T)584 AutoType *VisitVectorType(const VectorType *T) {
585 return Visit(T->getElementType());
586 }
VisitFunctionType(const FunctionType * T)587 AutoType *VisitFunctionType(const FunctionType *T) {
588 return Visit(T->getResultType());
589 }
VisitParenType(const ParenType * T)590 AutoType *VisitParenType(const ParenType *T) {
591 return Visit(T->getInnerType());
592 }
VisitAttributedType(const AttributedType * T)593 AutoType *VisitAttributedType(const AttributedType *T) {
594 return Visit(T->getModifiedType());
595 }
596 };
597 }
598
getContainedAutoType() const599 AutoType *Type::getContainedAutoType() const {
600 return GetContainedAutoVisitor().Visit(this);
601 }
602
hasIntegerRepresentation() const603 bool Type::hasIntegerRepresentation() const {
604 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
605 return VT->getElementType()->isIntegerType();
606 else
607 return isIntegerType();
608 }
609
610 /// \brief Determine whether this type is an integral type.
611 ///
612 /// This routine determines whether the given type is an integral type per
613 /// C++ [basic.fundamental]p7. Although the C standard does not define the
614 /// term "integral type", it has a similar term "integer type", and in C++
615 /// the two terms are equivalent. However, C's "integer type" includes
616 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
617 /// parameter is used to determine whether we should be following the C or
618 /// C++ rules when determining whether this type is an integral/integer type.
619 ///
620 /// For cases where C permits "an integer type" and C++ permits "an integral
621 /// type", use this routine.
622 ///
623 /// For cases where C permits "an integer type" and C++ permits "an integral
624 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
625 ///
626 /// \param Ctx The context in which this type occurs.
627 ///
628 /// \returns true if the type is considered an integral type, false otherwise.
isIntegralType(ASTContext & Ctx) const629 bool Type::isIntegralType(ASTContext &Ctx) const {
630 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
631 return BT->getKind() >= BuiltinType::Bool &&
632 BT->getKind() <= BuiltinType::Int128;
633
634 if (!Ctx.getLangOpts().CPlusPlus)
635 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
636 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
637
638 return false;
639 }
640
641
isIntegralOrUnscopedEnumerationType() const642 bool Type::isIntegralOrUnscopedEnumerationType() const {
643 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
644 return BT->getKind() >= BuiltinType::Bool &&
645 BT->getKind() <= BuiltinType::Int128;
646
647 // Check for a complete enum type; incomplete enum types are not properly an
648 // enumeration type in the sense required here.
649 // C++0x: However, if the underlying type of the enum is fixed, it is
650 // considered complete.
651 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
652 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
653
654 return false;
655 }
656
657
658
isCharType() const659 bool Type::isCharType() const {
660 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
661 return BT->getKind() == BuiltinType::Char_U ||
662 BT->getKind() == BuiltinType::UChar ||
663 BT->getKind() == BuiltinType::Char_S ||
664 BT->getKind() == BuiltinType::SChar;
665 return false;
666 }
667
isWideCharType() const668 bool Type::isWideCharType() const {
669 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
670 return BT->getKind() == BuiltinType::WChar_S ||
671 BT->getKind() == BuiltinType::WChar_U;
672 return false;
673 }
674
isChar16Type() const675 bool Type::isChar16Type() const {
676 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
677 return BT->getKind() == BuiltinType::Char16;
678 return false;
679 }
680
isChar32Type() const681 bool Type::isChar32Type() const {
682 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
683 return BT->getKind() == BuiltinType::Char32;
684 return false;
685 }
686
687 /// \brief Determine whether this type is any of the built-in character
688 /// types.
isAnyCharacterType() const689 bool Type::isAnyCharacterType() const {
690 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
691 if (BT == 0) return false;
692 switch (BT->getKind()) {
693 default: return false;
694 case BuiltinType::Char_U:
695 case BuiltinType::UChar:
696 case BuiltinType::WChar_U:
697 case BuiltinType::Char16:
698 case BuiltinType::Char32:
699 case BuiltinType::Char_S:
700 case BuiltinType::SChar:
701 case BuiltinType::WChar_S:
702 return true;
703 }
704 }
705
706 /// isSignedIntegerType - Return true if this is an integer type that is
707 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
708 /// an enum decl which has a signed representation
isSignedIntegerType() const709 bool Type::isSignedIntegerType() const {
710 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
711 return BT->getKind() >= BuiltinType::Char_S &&
712 BT->getKind() <= BuiltinType::Int128;
713 }
714
715 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
716 // Incomplete enum types are not treated as integer types.
717 // FIXME: In C++, enum types are never integer types.
718 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
719 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
720 }
721
722 return false;
723 }
724
isSignedIntegerOrEnumerationType() const725 bool Type::isSignedIntegerOrEnumerationType() const {
726 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
727 return BT->getKind() >= BuiltinType::Char_S &&
728 BT->getKind() <= BuiltinType::Int128;
729 }
730
731 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
732 if (ET->getDecl()->isComplete())
733 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
734 }
735
736 return false;
737 }
738
hasSignedIntegerRepresentation() const739 bool Type::hasSignedIntegerRepresentation() const {
740 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
741 return VT->getElementType()->isSignedIntegerOrEnumerationType();
742 else
743 return isSignedIntegerOrEnumerationType();
744 }
745
746 /// isUnsignedIntegerType - Return true if this is an integer type that is
747 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
748 /// decl which has an unsigned representation
isUnsignedIntegerType() const749 bool Type::isUnsignedIntegerType() const {
750 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
751 return BT->getKind() >= BuiltinType::Bool &&
752 BT->getKind() <= BuiltinType::UInt128;
753 }
754
755 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
756 // Incomplete enum types are not treated as integer types.
757 // FIXME: In C++, enum types are never integer types.
758 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
759 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
760 }
761
762 return false;
763 }
764
isUnsignedIntegerOrEnumerationType() const765 bool Type::isUnsignedIntegerOrEnumerationType() const {
766 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
767 return BT->getKind() >= BuiltinType::Bool &&
768 BT->getKind() <= BuiltinType::UInt128;
769 }
770
771 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
772 if (ET->getDecl()->isComplete())
773 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
774 }
775
776 return false;
777 }
778
hasUnsignedIntegerRepresentation() const779 bool Type::hasUnsignedIntegerRepresentation() const {
780 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
781 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
782 else
783 return isUnsignedIntegerOrEnumerationType();
784 }
785
isFloatingType() const786 bool Type::isFloatingType() const {
787 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
788 return BT->getKind() >= BuiltinType::Half &&
789 BT->getKind() <= BuiltinType::LongDouble;
790 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
791 return CT->getElementType()->isFloatingType();
792 return false;
793 }
794
hasFloatingRepresentation() const795 bool Type::hasFloatingRepresentation() const {
796 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
797 return VT->getElementType()->isFloatingType();
798 else
799 return isFloatingType();
800 }
801
isRealFloatingType() const802 bool Type::isRealFloatingType() const {
803 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
804 return BT->isFloatingPoint();
805 return false;
806 }
807
isRealType() const808 bool Type::isRealType() const {
809 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
810 return BT->getKind() >= BuiltinType::Bool &&
811 BT->getKind() <= BuiltinType::LongDouble;
812 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
813 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
814 return false;
815 }
816
isArithmeticType() const817 bool Type::isArithmeticType() const {
818 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
819 return BT->getKind() >= BuiltinType::Bool &&
820 BT->getKind() <= BuiltinType::LongDouble;
821 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
822 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
823 // If a body isn't seen by the time we get here, return false.
824 //
825 // C++0x: Enumerations are not arithmetic types. For now, just return
826 // false for scoped enumerations since that will disable any
827 // unwanted implicit conversions.
828 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
829 return isa<ComplexType>(CanonicalType);
830 }
831
getScalarTypeKind() const832 Type::ScalarTypeKind Type::getScalarTypeKind() const {
833 assert(isScalarType());
834
835 const Type *T = CanonicalType.getTypePtr();
836 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
837 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
838 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
839 if (BT->isInteger()) return STK_Integral;
840 if (BT->isFloatingPoint()) return STK_Floating;
841 llvm_unreachable("unknown scalar builtin type");
842 } else if (isa<PointerType>(T)) {
843 return STK_CPointer;
844 } else if (isa<BlockPointerType>(T)) {
845 return STK_BlockPointer;
846 } else if (isa<ObjCObjectPointerType>(T)) {
847 return STK_ObjCObjectPointer;
848 } else if (isa<MemberPointerType>(T)) {
849 return STK_MemberPointer;
850 } else if (isa<EnumType>(T)) {
851 assert(cast<EnumType>(T)->getDecl()->isComplete());
852 return STK_Integral;
853 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
854 if (CT->getElementType()->isRealFloatingType())
855 return STK_FloatingComplex;
856 return STK_IntegralComplex;
857 }
858
859 llvm_unreachable("unknown scalar type");
860 }
861
862 /// \brief Determines whether the type is a C++ aggregate type or C
863 /// aggregate or union type.
864 ///
865 /// An aggregate type is an array or a class type (struct, union, or
866 /// class) that has no user-declared constructors, no private or
867 /// protected non-static data members, no base classes, and no virtual
868 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
869 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
870 /// includes union types.
isAggregateType() const871 bool Type::isAggregateType() const {
872 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
873 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
874 return ClassDecl->isAggregate();
875
876 return true;
877 }
878
879 return isa<ArrayType>(CanonicalType);
880 }
881
882 /// isConstantSizeType - Return true if this is not a variable sized type,
883 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
884 /// incomplete types or dependent types.
isConstantSizeType() const885 bool Type::isConstantSizeType() const {
886 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
887 assert(!isDependentType() && "This doesn't make sense for dependent types");
888 // The VAT must have a size, as it is known to be complete.
889 return !isa<VariableArrayType>(CanonicalType);
890 }
891
892 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
893 /// - a type that can describe objects, but which lacks information needed to
894 /// determine its size.
isIncompleteType(NamedDecl ** Def) const895 bool Type::isIncompleteType(NamedDecl **Def) const {
896 if (Def)
897 *Def = 0;
898
899 switch (CanonicalType->getTypeClass()) {
900 default: return false;
901 case Builtin:
902 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
903 // be completed.
904 return isVoidType();
905 case Enum: {
906 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
907 if (Def)
908 *Def = EnumD;
909
910 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
911 if (EnumD->isFixed())
912 return false;
913
914 return !EnumD->isCompleteDefinition();
915 }
916 case Record: {
917 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
918 // forward declaration, but not a full definition (C99 6.2.5p22).
919 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
920 if (Def)
921 *Def = Rec;
922 return !Rec->isCompleteDefinition();
923 }
924 case ConstantArray:
925 // An array is incomplete if its element type is incomplete
926 // (C++ [dcl.array]p1).
927 // We don't handle variable arrays (they're not allowed in C++) or
928 // dependent-sized arrays (dependent types are never treated as incomplete).
929 return cast<ArrayType>(CanonicalType)->getElementType()
930 ->isIncompleteType(Def);
931 case IncompleteArray:
932 // An array of unknown size is an incomplete type (C99 6.2.5p22).
933 return true;
934 case ObjCObject:
935 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
936 ->isIncompleteType(Def);
937 case ObjCInterface: {
938 // ObjC interfaces are incomplete if they are @class, not @interface.
939 ObjCInterfaceDecl *Interface
940 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
941 if (Def)
942 *Def = Interface;
943 return !Interface->hasDefinition();
944 }
945 }
946 }
947
isPODType(ASTContext & Context) const948 bool QualType::isPODType(ASTContext &Context) const {
949 // C++11 has a more relaxed definition of POD.
950 if (Context.getLangOpts().CPlusPlus11)
951 return isCXX11PODType(Context);
952
953 return isCXX98PODType(Context);
954 }
955
isCXX98PODType(ASTContext & Context) const956 bool QualType::isCXX98PODType(ASTContext &Context) const {
957 // The compiler shouldn't query this for incomplete types, but the user might.
958 // We return false for that case. Except for incomplete arrays of PODs, which
959 // are PODs according to the standard.
960 if (isNull())
961 return 0;
962
963 if ((*this)->isIncompleteArrayType())
964 return Context.getBaseElementType(*this).isCXX98PODType(Context);
965
966 if ((*this)->isIncompleteType())
967 return false;
968
969 if (Context.getLangOpts().ObjCAutoRefCount) {
970 switch (getObjCLifetime()) {
971 case Qualifiers::OCL_ExplicitNone:
972 return true;
973
974 case Qualifiers::OCL_Strong:
975 case Qualifiers::OCL_Weak:
976 case Qualifiers::OCL_Autoreleasing:
977 return false;
978
979 case Qualifiers::OCL_None:
980 break;
981 }
982 }
983
984 QualType CanonicalType = getTypePtr()->CanonicalType;
985 switch (CanonicalType->getTypeClass()) {
986 // Everything not explicitly mentioned is not POD.
987 default: return false;
988 case Type::VariableArray:
989 case Type::ConstantArray:
990 // IncompleteArray is handled above.
991 return Context.getBaseElementType(*this).isCXX98PODType(Context);
992
993 case Type::ObjCObjectPointer:
994 case Type::BlockPointer:
995 case Type::Builtin:
996 case Type::Complex:
997 case Type::Pointer:
998 case Type::MemberPointer:
999 case Type::Vector:
1000 case Type::ExtVector:
1001 return true;
1002
1003 case Type::Enum:
1004 return true;
1005
1006 case Type::Record:
1007 if (CXXRecordDecl *ClassDecl
1008 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1009 return ClassDecl->isPOD();
1010
1011 // C struct/union is POD.
1012 return true;
1013 }
1014 }
1015
isTrivialType(ASTContext & Context) const1016 bool QualType::isTrivialType(ASTContext &Context) const {
1017 // The compiler shouldn't query this for incomplete types, but the user might.
1018 // We return false for that case. Except for incomplete arrays of PODs, which
1019 // are PODs according to the standard.
1020 if (isNull())
1021 return 0;
1022
1023 if ((*this)->isArrayType())
1024 return Context.getBaseElementType(*this).isTrivialType(Context);
1025
1026 // Return false for incomplete types after skipping any incomplete array
1027 // types which are expressly allowed by the standard and thus our API.
1028 if ((*this)->isIncompleteType())
1029 return false;
1030
1031 if (Context.getLangOpts().ObjCAutoRefCount) {
1032 switch (getObjCLifetime()) {
1033 case Qualifiers::OCL_ExplicitNone:
1034 return true;
1035
1036 case Qualifiers::OCL_Strong:
1037 case Qualifiers::OCL_Weak:
1038 case Qualifiers::OCL_Autoreleasing:
1039 return false;
1040
1041 case Qualifiers::OCL_None:
1042 if ((*this)->isObjCLifetimeType())
1043 return false;
1044 break;
1045 }
1046 }
1047
1048 QualType CanonicalType = getTypePtr()->CanonicalType;
1049 if (CanonicalType->isDependentType())
1050 return false;
1051
1052 // C++0x [basic.types]p9:
1053 // Scalar types, trivial class types, arrays of such types, and
1054 // cv-qualified versions of these types are collectively called trivial
1055 // types.
1056
1057 // As an extension, Clang treats vector types as Scalar types.
1058 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1059 return true;
1060 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1061 if (const CXXRecordDecl *ClassDecl =
1062 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1063 // C++11 [class]p6:
1064 // A trivial class is a class that has a default constructor,
1065 // has no non-trivial default constructors, and is trivially
1066 // copyable.
1067 return ClassDecl->hasDefaultConstructor() &&
1068 !ClassDecl->hasNonTrivialDefaultConstructor() &&
1069 ClassDecl->isTriviallyCopyable();
1070 }
1071
1072 return true;
1073 }
1074
1075 // No other types can match.
1076 return false;
1077 }
1078
isTriviallyCopyableType(ASTContext & Context) const1079 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1080 if ((*this)->isArrayType())
1081 return Context.getBaseElementType(*this).isTrivialType(Context);
1082
1083 if (Context.getLangOpts().ObjCAutoRefCount) {
1084 switch (getObjCLifetime()) {
1085 case Qualifiers::OCL_ExplicitNone:
1086 return true;
1087
1088 case Qualifiers::OCL_Strong:
1089 case Qualifiers::OCL_Weak:
1090 case Qualifiers::OCL_Autoreleasing:
1091 return false;
1092
1093 case Qualifiers::OCL_None:
1094 if ((*this)->isObjCLifetimeType())
1095 return false;
1096 break;
1097 }
1098 }
1099
1100 // C++11 [basic.types]p9
1101 // Scalar types, trivially copyable class types, arrays of such types, and
1102 // non-volatile const-qualified versions of these types are collectively
1103 // called trivially copyable types.
1104
1105 QualType CanonicalType = getCanonicalType();
1106 if (CanonicalType->isDependentType())
1107 return false;
1108
1109 if (CanonicalType.isVolatileQualified())
1110 return false;
1111
1112 // Return false for incomplete types after skipping any incomplete array types
1113 // which are expressly allowed by the standard and thus our API.
1114 if (CanonicalType->isIncompleteType())
1115 return false;
1116
1117 // As an extension, Clang treats vector types as Scalar types.
1118 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1119 return true;
1120
1121 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1122 if (const CXXRecordDecl *ClassDecl =
1123 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1124 if (!ClassDecl->isTriviallyCopyable()) return false;
1125 }
1126
1127 return true;
1128 }
1129
1130 // No other types can match.
1131 return false;
1132 }
1133
1134
1135
isLiteralType(const ASTContext & Ctx) const1136 bool Type::isLiteralType(const ASTContext &Ctx) const {
1137 if (isDependentType())
1138 return false;
1139
1140 // C++1y [basic.types]p10:
1141 // A type is a literal type if it is:
1142 // -- cv void; or
1143 if (Ctx.getLangOpts().CPlusPlus1y && isVoidType())
1144 return true;
1145
1146 // C++11 [basic.types]p10:
1147 // A type is a literal type if it is:
1148 // [...]
1149 // -- an array of literal type other than an array of runtime bound; or
1150 if (isVariableArrayType())
1151 return false;
1152 const Type *BaseTy = getBaseElementTypeUnsafe();
1153 assert(BaseTy && "NULL element type");
1154
1155 // Return false for incomplete types after skipping any incomplete array
1156 // types; those are expressly allowed by the standard and thus our API.
1157 if (BaseTy->isIncompleteType())
1158 return false;
1159
1160 // C++11 [basic.types]p10:
1161 // A type is a literal type if it is:
1162 // -- a scalar type; or
1163 // As an extension, Clang treats vector types and complex types as
1164 // literal types.
1165 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1166 BaseTy->isAnyComplexType())
1167 return true;
1168 // -- a reference type; or
1169 if (BaseTy->isReferenceType())
1170 return true;
1171 // -- a class type that has all of the following properties:
1172 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1173 // -- a trivial destructor,
1174 // -- every constructor call and full-expression in the
1175 // brace-or-equal-initializers for non-static data members (if any)
1176 // is a constant expression,
1177 // -- it is an aggregate type or has at least one constexpr
1178 // constructor or constructor template that is not a copy or move
1179 // constructor, and
1180 // -- all non-static data members and base classes of literal types
1181 //
1182 // We resolve DR1361 by ignoring the second bullet.
1183 if (const CXXRecordDecl *ClassDecl =
1184 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1185 return ClassDecl->isLiteral();
1186
1187 return true;
1188 }
1189
1190 // We treat _Atomic T as a literal type if T is a literal type.
1191 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1192 return AT->getValueType()->isLiteralType(Ctx);
1193
1194 // If this type hasn't been deduced yet, then conservatively assume that
1195 // it'll work out to be a literal type.
1196 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1197 return true;
1198
1199 return false;
1200 }
1201
isStandardLayoutType() const1202 bool Type::isStandardLayoutType() const {
1203 if (isDependentType())
1204 return false;
1205
1206 // C++0x [basic.types]p9:
1207 // Scalar types, standard-layout class types, arrays of such types, and
1208 // cv-qualified versions of these types are collectively called
1209 // standard-layout types.
1210 const Type *BaseTy = getBaseElementTypeUnsafe();
1211 assert(BaseTy && "NULL element type");
1212
1213 // Return false for incomplete types after skipping any incomplete array
1214 // types which are expressly allowed by the standard and thus our API.
1215 if (BaseTy->isIncompleteType())
1216 return false;
1217
1218 // As an extension, Clang treats vector types as Scalar types.
1219 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1220 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1221 if (const CXXRecordDecl *ClassDecl =
1222 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1223 if (!ClassDecl->isStandardLayout())
1224 return false;
1225
1226 // Default to 'true' for non-C++ class types.
1227 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1228 // all the requirements of standard layout classes.
1229 return true;
1230 }
1231
1232 // No other types can match.
1233 return false;
1234 }
1235
1236 // This is effectively the intersection of isTrivialType and
1237 // isStandardLayoutType. We implement it directly to avoid redundant
1238 // conversions from a type to a CXXRecordDecl.
isCXX11PODType(ASTContext & Context) const1239 bool QualType::isCXX11PODType(ASTContext &Context) const {
1240 const Type *ty = getTypePtr();
1241 if (ty->isDependentType())
1242 return false;
1243
1244 if (Context.getLangOpts().ObjCAutoRefCount) {
1245 switch (getObjCLifetime()) {
1246 case Qualifiers::OCL_ExplicitNone:
1247 return true;
1248
1249 case Qualifiers::OCL_Strong:
1250 case Qualifiers::OCL_Weak:
1251 case Qualifiers::OCL_Autoreleasing:
1252 return false;
1253
1254 case Qualifiers::OCL_None:
1255 break;
1256 }
1257 }
1258
1259 // C++11 [basic.types]p9:
1260 // Scalar types, POD classes, arrays of such types, and cv-qualified
1261 // versions of these types are collectively called trivial types.
1262 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1263 assert(BaseTy && "NULL element type");
1264
1265 // Return false for incomplete types after skipping any incomplete array
1266 // types which are expressly allowed by the standard and thus our API.
1267 if (BaseTy->isIncompleteType())
1268 return false;
1269
1270 // As an extension, Clang treats vector types as Scalar types.
1271 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1272 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1273 if (const CXXRecordDecl *ClassDecl =
1274 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1275 // C++11 [class]p10:
1276 // A POD struct is a non-union class that is both a trivial class [...]
1277 if (!ClassDecl->isTrivial()) return false;
1278
1279 // C++11 [class]p10:
1280 // A POD struct is a non-union class that is both a trivial class and
1281 // a standard-layout class [...]
1282 if (!ClassDecl->isStandardLayout()) return false;
1283
1284 // C++11 [class]p10:
1285 // A POD struct is a non-union class that is both a trivial class and
1286 // a standard-layout class, and has no non-static data members of type
1287 // non-POD struct, non-POD union (or array of such types). [...]
1288 //
1289 // We don't directly query the recursive aspect as the requiremets for
1290 // both standard-layout classes and trivial classes apply recursively
1291 // already.
1292 }
1293
1294 return true;
1295 }
1296
1297 // No other types can match.
1298 return false;
1299 }
1300
isPromotableIntegerType() const1301 bool Type::isPromotableIntegerType() const {
1302 if (const BuiltinType *BT = getAs<BuiltinType>())
1303 switch (BT->getKind()) {
1304 case BuiltinType::Bool:
1305 case BuiltinType::Char_S:
1306 case BuiltinType::Char_U:
1307 case BuiltinType::SChar:
1308 case BuiltinType::UChar:
1309 case BuiltinType::Short:
1310 case BuiltinType::UShort:
1311 case BuiltinType::WChar_S:
1312 case BuiltinType::WChar_U:
1313 case BuiltinType::Char16:
1314 case BuiltinType::Char32:
1315 return true;
1316 default:
1317 return false;
1318 }
1319
1320 // Enumerated types are promotable to their compatible integer types
1321 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1322 if (const EnumType *ET = getAs<EnumType>()){
1323 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1324 || ET->getDecl()->isScoped())
1325 return false;
1326
1327 return true;
1328 }
1329
1330 return false;
1331 }
1332
isSpecifierType() const1333 bool Type::isSpecifierType() const {
1334 // Note that this intentionally does not use the canonical type.
1335 switch (getTypeClass()) {
1336 case Builtin:
1337 case Record:
1338 case Enum:
1339 case Typedef:
1340 case Complex:
1341 case TypeOfExpr:
1342 case TypeOf:
1343 case TemplateTypeParm:
1344 case SubstTemplateTypeParm:
1345 case TemplateSpecialization:
1346 case Elaborated:
1347 case DependentName:
1348 case DependentTemplateSpecialization:
1349 case ObjCInterface:
1350 case ObjCObject:
1351 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1352 return true;
1353 default:
1354 return false;
1355 }
1356 }
1357
1358 ElaboratedTypeKeyword
getKeywordForTypeSpec(unsigned TypeSpec)1359 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1360 switch (TypeSpec) {
1361 default: return ETK_None;
1362 case TST_typename: return ETK_Typename;
1363 case TST_class: return ETK_Class;
1364 case TST_struct: return ETK_Struct;
1365 case TST_interface: return ETK_Interface;
1366 case TST_union: return ETK_Union;
1367 case TST_enum: return ETK_Enum;
1368 }
1369 }
1370
1371 TagTypeKind
getTagTypeKindForTypeSpec(unsigned TypeSpec)1372 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1373 switch(TypeSpec) {
1374 case TST_class: return TTK_Class;
1375 case TST_struct: return TTK_Struct;
1376 case TST_interface: return TTK_Interface;
1377 case TST_union: return TTK_Union;
1378 case TST_enum: return TTK_Enum;
1379 }
1380
1381 llvm_unreachable("Type specifier is not a tag type kind.");
1382 }
1383
1384 ElaboratedTypeKeyword
getKeywordForTagTypeKind(TagTypeKind Kind)1385 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1386 switch (Kind) {
1387 case TTK_Class: return ETK_Class;
1388 case TTK_Struct: return ETK_Struct;
1389 case TTK_Interface: return ETK_Interface;
1390 case TTK_Union: return ETK_Union;
1391 case TTK_Enum: return ETK_Enum;
1392 }
1393 llvm_unreachable("Unknown tag type kind.");
1394 }
1395
1396 TagTypeKind
getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)1397 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1398 switch (Keyword) {
1399 case ETK_Class: return TTK_Class;
1400 case ETK_Struct: return TTK_Struct;
1401 case ETK_Interface: return TTK_Interface;
1402 case ETK_Union: return TTK_Union;
1403 case ETK_Enum: return TTK_Enum;
1404 case ETK_None: // Fall through.
1405 case ETK_Typename:
1406 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1407 }
1408 llvm_unreachable("Unknown elaborated type keyword.");
1409 }
1410
1411 bool
KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword)1412 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1413 switch (Keyword) {
1414 case ETK_None:
1415 case ETK_Typename:
1416 return false;
1417 case ETK_Class:
1418 case ETK_Struct:
1419 case ETK_Interface:
1420 case ETK_Union:
1421 case ETK_Enum:
1422 return true;
1423 }
1424 llvm_unreachable("Unknown elaborated type keyword.");
1425 }
1426
1427 const char*
getKeywordName(ElaboratedTypeKeyword Keyword)1428 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1429 switch (Keyword) {
1430 case ETK_None: return "";
1431 case ETK_Typename: return "typename";
1432 case ETK_Class: return "class";
1433 case ETK_Struct: return "struct";
1434 case ETK_Interface: return "__interface";
1435 case ETK_Union: return "union";
1436 case ETK_Enum: return "enum";
1437 }
1438
1439 llvm_unreachable("Unknown elaborated type keyword.");
1440 }
1441
DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,unsigned NumArgs,const TemplateArgument * Args,QualType Canon)1442 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1443 ElaboratedTypeKeyword Keyword,
1444 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1445 unsigned NumArgs, const TemplateArgument *Args,
1446 QualType Canon)
1447 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1448 /*VariablyModified=*/false,
1449 NNS && NNS->containsUnexpandedParameterPack()),
1450 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1451 assert((!NNS || NNS->isDependent()) &&
1452 "DependentTemplateSpecializatonType requires dependent qualifier");
1453 for (unsigned I = 0; I != NumArgs; ++I) {
1454 if (Args[I].containsUnexpandedParameterPack())
1455 setContainsUnexpandedParameterPack();
1456
1457 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1458 }
1459 }
1460
1461 void
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,ElaboratedTypeKeyword Keyword,NestedNameSpecifier * Qualifier,const IdentifierInfo * Name,unsigned NumArgs,const TemplateArgument * Args)1462 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1463 const ASTContext &Context,
1464 ElaboratedTypeKeyword Keyword,
1465 NestedNameSpecifier *Qualifier,
1466 const IdentifierInfo *Name,
1467 unsigned NumArgs,
1468 const TemplateArgument *Args) {
1469 ID.AddInteger(Keyword);
1470 ID.AddPointer(Qualifier);
1471 ID.AddPointer(Name);
1472 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1473 Args[Idx].Profile(ID, Context);
1474 }
1475
isElaboratedTypeSpecifier() const1476 bool Type::isElaboratedTypeSpecifier() const {
1477 ElaboratedTypeKeyword Keyword;
1478 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1479 Keyword = Elab->getKeyword();
1480 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1481 Keyword = DepName->getKeyword();
1482 else if (const DependentTemplateSpecializationType *DepTST =
1483 dyn_cast<DependentTemplateSpecializationType>(this))
1484 Keyword = DepTST->getKeyword();
1485 else
1486 return false;
1487
1488 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1489 }
1490
getTypeClassName() const1491 const char *Type::getTypeClassName() const {
1492 switch (TypeBits.TC) {
1493 #define ABSTRACT_TYPE(Derived, Base)
1494 #define TYPE(Derived, Base) case Derived: return #Derived;
1495 #include "clang/AST/TypeNodes.def"
1496 }
1497
1498 llvm_unreachable("Invalid type class.");
1499 }
1500
getName(const PrintingPolicy & Policy) const1501 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1502 switch (getKind()) {
1503 case Void: return "void";
1504 case Bool: return Policy.Bool ? "bool" : "_Bool";
1505 case Char_S: return "char";
1506 case Char_U: return "char";
1507 case SChar: return "signed char";
1508 case Short: return "short";
1509 case Int: return "int";
1510 case Long: return "long";
1511 case LongLong: return "long long";
1512 case Int128: return "__int128";
1513 case UChar: return "unsigned char";
1514 case UShort: return "unsigned short";
1515 case UInt: return "unsigned int";
1516 case ULong: return "unsigned long";
1517 case ULongLong: return "unsigned long long";
1518 case UInt128: return "unsigned __int128";
1519 case Half: return "half";
1520 case Float: return "float";
1521 case Double: return "double";
1522 case LongDouble: return "long double";
1523 case WChar_S:
1524 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1525 case Char16: return "char16_t";
1526 case Char32: return "char32_t";
1527 case NullPtr: return "nullptr_t";
1528 case Overload: return "<overloaded function type>";
1529 case BoundMember: return "<bound member function type>";
1530 case PseudoObject: return "<pseudo-object type>";
1531 case Dependent: return "<dependent type>";
1532 case UnknownAny: return "<unknown type>";
1533 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1534 case BuiltinFn: return "<builtin fn type>";
1535 case ObjCId: return "id";
1536 case ObjCClass: return "Class";
1537 case ObjCSel: return "SEL";
1538 case OCLImage1d: return "image1d_t";
1539 case OCLImage1dArray: return "image1d_array_t";
1540 case OCLImage1dBuffer: return "image1d_buffer_t";
1541 case OCLImage2d: return "image2d_t";
1542 case OCLImage2dArray: return "image2d_array_t";
1543 case OCLImage3d: return "image3d_t";
1544 case OCLSampler: return "sampler_t";
1545 case OCLEvent: return "event_t";
1546 }
1547
1548 llvm_unreachable("Invalid builtin type.");
1549 }
1550
getNonLValueExprType(const ASTContext & Context) const1551 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1552 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1553 return RefType->getPointeeType();
1554
1555 // C++0x [basic.lval]:
1556 // Class prvalues can have cv-qualified types; non-class prvalues always
1557 // have cv-unqualified types.
1558 //
1559 // See also C99 6.3.2.1p2.
1560 if (!Context.getLangOpts().CPlusPlus ||
1561 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1562 return getUnqualifiedType();
1563
1564 return *this;
1565 }
1566
getNameForCallConv(CallingConv CC)1567 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1568 switch (CC) {
1569 case CC_C: return "cdecl";
1570 case CC_X86StdCall: return "stdcall";
1571 case CC_X86FastCall: return "fastcall";
1572 case CC_X86ThisCall: return "thiscall";
1573 case CC_X86Pascal: return "pascal";
1574 case CC_X86_64Win64: return "ms_abi";
1575 case CC_X86_64SysV: return "sysv_abi";
1576 case CC_AAPCS: return "aapcs";
1577 case CC_AAPCS_VFP: return "aapcs-vfp";
1578 case CC_PnaclCall: return "pnaclcall";
1579 case CC_IntelOclBicc: return "intel_ocl_bicc";
1580 }
1581
1582 llvm_unreachable("Invalid calling convention.");
1583 }
1584
FunctionProtoType(QualType result,ArrayRef<QualType> args,QualType canonical,const ExtProtoInfo & epi)1585 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> args,
1586 QualType canonical,
1587 const ExtProtoInfo &epi)
1588 : FunctionType(FunctionProto, result, epi.TypeQuals,
1589 canonical,
1590 result->isDependentType(),
1591 result->isInstantiationDependentType(),
1592 result->isVariablyModifiedType(),
1593 result->containsUnexpandedParameterPack(),
1594 epi.ExtInfo),
1595 NumArgs(args.size()), NumExceptions(epi.NumExceptions),
1596 ExceptionSpecType(epi.ExceptionSpecType),
1597 HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1598 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn),
1599 RefQualifier(epi.RefQualifier)
1600 {
1601 assert(NumArgs == args.size() && "function has too many parameters");
1602
1603 // Fill in the trailing argument array.
1604 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1605 for (unsigned i = 0; i != NumArgs; ++i) {
1606 if (args[i]->isDependentType())
1607 setDependent();
1608 else if (args[i]->isInstantiationDependentType())
1609 setInstantiationDependent();
1610
1611 if (args[i]->containsUnexpandedParameterPack())
1612 setContainsUnexpandedParameterPack();
1613
1614 argSlot[i] = args[i];
1615 }
1616
1617 if (getExceptionSpecType() == EST_Dynamic) {
1618 // Fill in the exception array.
1619 QualType *exnSlot = argSlot + NumArgs;
1620 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1621 if (epi.Exceptions[i]->isDependentType())
1622 setDependent();
1623 else if (epi.Exceptions[i]->isInstantiationDependentType())
1624 setInstantiationDependent();
1625
1626 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1627 setContainsUnexpandedParameterPack();
1628
1629 exnSlot[i] = epi.Exceptions[i];
1630 }
1631 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1632 // Store the noexcept expression and context.
1633 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + NumArgs);
1634 *noexSlot = epi.NoexceptExpr;
1635
1636 if (epi.NoexceptExpr) {
1637 if (epi.NoexceptExpr->isValueDependent()
1638 || epi.NoexceptExpr->isTypeDependent())
1639 setDependent();
1640 else if (epi.NoexceptExpr->isInstantiationDependent())
1641 setInstantiationDependent();
1642 }
1643 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1644 // Store the function decl from which we will resolve our
1645 // exception specification.
1646 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs);
1647 slot[0] = epi.ExceptionSpecDecl;
1648 slot[1] = epi.ExceptionSpecTemplate;
1649 // This exception specification doesn't make the type dependent, because
1650 // it's not instantiated as part of instantiating the type.
1651 } else if (getExceptionSpecType() == EST_Unevaluated) {
1652 // Store the function decl from which we will resolve our
1653 // exception specification.
1654 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs);
1655 slot[0] = epi.ExceptionSpecDecl;
1656 }
1657
1658 if (epi.ConsumedArguments) {
1659 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1660 for (unsigned i = 0; i != NumArgs; ++i)
1661 consumedArgs[i] = epi.ConsumedArguments[i];
1662 }
1663 }
1664
1665 FunctionProtoType::NoexceptResult
getNoexceptSpec(const ASTContext & ctx) const1666 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1667 ExceptionSpecificationType est = getExceptionSpecType();
1668 if (est == EST_BasicNoexcept)
1669 return NR_Nothrow;
1670
1671 if (est != EST_ComputedNoexcept)
1672 return NR_NoNoexcept;
1673
1674 Expr *noexceptExpr = getNoexceptExpr();
1675 if (!noexceptExpr)
1676 return NR_BadNoexcept;
1677 if (noexceptExpr->isValueDependent())
1678 return NR_Dependent;
1679
1680 llvm::APSInt value;
1681 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1682 /*evaluated*/false);
1683 (void)isICE;
1684 assert(isICE && "AST should not contain bad noexcept expressions.");
1685
1686 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1687 }
1688
isTemplateVariadic() const1689 bool FunctionProtoType::isTemplateVariadic() const {
1690 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1691 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1692 return true;
1693
1694 return false;
1695 }
1696
Profile(llvm::FoldingSetNodeID & ID,QualType Result,const QualType * ArgTys,unsigned NumArgs,const ExtProtoInfo & epi,const ASTContext & Context)1697 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1698 const QualType *ArgTys, unsigned NumArgs,
1699 const ExtProtoInfo &epi,
1700 const ASTContext &Context) {
1701
1702 // We have to be careful not to get ambiguous profile encodings.
1703 // Note that valid type pointers are never ambiguous with anything else.
1704 //
1705 // The encoding grammar begins:
1706 // type type* bool int bool
1707 // If that final bool is true, then there is a section for the EH spec:
1708 // bool type*
1709 // This is followed by an optional "consumed argument" section of the
1710 // same length as the first type sequence:
1711 // bool*
1712 // Finally, we have the ext info and trailing return type flag:
1713 // int bool
1714 //
1715 // There is no ambiguity between the consumed arguments and an empty EH
1716 // spec because of the leading 'bool' which unambiguously indicates
1717 // whether the following bool is the EH spec or part of the arguments.
1718
1719 ID.AddPointer(Result.getAsOpaquePtr());
1720 for (unsigned i = 0; i != NumArgs; ++i)
1721 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1722 // This method is relatively performance sensitive, so as a performance
1723 // shortcut, use one AddInteger call instead of four for the next four
1724 // fields.
1725 assert(!(unsigned(epi.Variadic) & ~1) &&
1726 !(unsigned(epi.TypeQuals) & ~255) &&
1727 !(unsigned(epi.RefQualifier) & ~3) &&
1728 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1729 "Values larger than expected.");
1730 ID.AddInteger(unsigned(epi.Variadic) +
1731 (epi.TypeQuals << 1) +
1732 (epi.RefQualifier << 9) +
1733 (epi.ExceptionSpecType << 11));
1734 if (epi.ExceptionSpecType == EST_Dynamic) {
1735 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1736 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1737 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1738 epi.NoexceptExpr->Profile(ID, Context, false);
1739 } else if (epi.ExceptionSpecType == EST_Uninstantiated ||
1740 epi.ExceptionSpecType == EST_Unevaluated) {
1741 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1742 }
1743 if (epi.ConsumedArguments) {
1744 for (unsigned i = 0; i != NumArgs; ++i)
1745 ID.AddBoolean(epi.ConsumedArguments[i]);
1746 }
1747 epi.ExtInfo.Profile(ID);
1748 ID.AddBoolean(epi.HasTrailingReturn);
1749 }
1750
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Ctx)1751 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1752 const ASTContext &Ctx) {
1753 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1754 Ctx);
1755 }
1756
desugar() const1757 QualType TypedefType::desugar() const {
1758 return getDecl()->getUnderlyingType();
1759 }
1760
TypeOfExprType(Expr * E,QualType can)1761 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1762 : Type(TypeOfExpr, can, E->isTypeDependent(),
1763 E->isInstantiationDependent(),
1764 E->getType()->isVariablyModifiedType(),
1765 E->containsUnexpandedParameterPack()),
1766 TOExpr(E) {
1767 }
1768
isSugared() const1769 bool TypeOfExprType::isSugared() const {
1770 return !TOExpr->isTypeDependent();
1771 }
1772
desugar() const1773 QualType TypeOfExprType::desugar() const {
1774 if (isSugared())
1775 return getUnderlyingExpr()->getType();
1776
1777 return QualType(this, 0);
1778 }
1779
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,Expr * E)1780 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1781 const ASTContext &Context, Expr *E) {
1782 E->Profile(ID, Context, true);
1783 }
1784
DecltypeType(Expr * E,QualType underlyingType,QualType can)1785 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1786 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1787 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1788 // type-dependent even if its expression is only instantiation-dependent.
1789 : Type(Decltype, can, E->isInstantiationDependent(),
1790 E->isInstantiationDependent(),
1791 E->getType()->isVariablyModifiedType(),
1792 E->containsUnexpandedParameterPack()),
1793 E(E),
1794 UnderlyingType(underlyingType) {
1795 }
1796
isSugared() const1797 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1798
desugar() const1799 QualType DecltypeType::desugar() const {
1800 if (isSugared())
1801 return getUnderlyingType();
1802
1803 return QualType(this, 0);
1804 }
1805
DependentDecltypeType(const ASTContext & Context,Expr * E)1806 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1807 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1808
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,Expr * E)1809 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1810 const ASTContext &Context, Expr *E) {
1811 E->Profile(ID, Context, true);
1812 }
1813
TagType(TypeClass TC,const TagDecl * D,QualType can)1814 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1815 : Type(TC, can, D->isDependentType(),
1816 /*InstantiationDependent=*/D->isDependentType(),
1817 /*VariablyModified=*/false,
1818 /*ContainsUnexpandedParameterPack=*/false),
1819 decl(const_cast<TagDecl*>(D)) {}
1820
getInterestingTagDecl(TagDecl * decl)1821 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1822 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1823 E = decl->redecls_end();
1824 I != E; ++I) {
1825 if (I->isCompleteDefinition() || I->isBeingDefined())
1826 return *I;
1827 }
1828 // If there's no definition (not even in progress), return what we have.
1829 return decl;
1830 }
1831
UnaryTransformType(QualType BaseType,QualType UnderlyingType,UTTKind UKind,QualType CanonicalType)1832 UnaryTransformType::UnaryTransformType(QualType BaseType,
1833 QualType UnderlyingType,
1834 UTTKind UKind,
1835 QualType CanonicalType)
1836 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1837 UnderlyingType->isInstantiationDependentType(),
1838 UnderlyingType->isVariablyModifiedType(),
1839 BaseType->containsUnexpandedParameterPack())
1840 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1841 {}
1842
getDecl() const1843 TagDecl *TagType::getDecl() const {
1844 return getInterestingTagDecl(decl);
1845 }
1846
isBeingDefined() const1847 bool TagType::isBeingDefined() const {
1848 return getDecl()->isBeingDefined();
1849 }
1850
isMSTypeSpec() const1851 bool AttributedType::isMSTypeSpec() const {
1852 switch (getAttrKind()) {
1853 default: return false;
1854 case attr_ptr32:
1855 case attr_ptr64:
1856 case attr_sptr:
1857 case attr_uptr:
1858 return true;
1859 }
1860 llvm_unreachable("invalid attr kind");
1861 }
1862
isCallingConv() const1863 bool AttributedType::isCallingConv() const {
1864 switch (getAttrKind()) {
1865 case attr_ptr32:
1866 case attr_ptr64:
1867 case attr_sptr:
1868 case attr_uptr:
1869 case attr_address_space:
1870 case attr_regparm:
1871 case attr_vector_size:
1872 case attr_neon_vector_type:
1873 case attr_neon_polyvector_type:
1874 case attr_objc_gc:
1875 case attr_objc_ownership:
1876 case attr_noreturn:
1877 return false;
1878 case attr_pcs:
1879 case attr_pcs_vfp:
1880 case attr_cdecl:
1881 case attr_fastcall:
1882 case attr_stdcall:
1883 case attr_thiscall:
1884 case attr_pascal:
1885 case attr_ms_abi:
1886 case attr_sysv_abi:
1887 case attr_pnaclcall:
1888 case attr_inteloclbicc:
1889 return true;
1890 }
1891 llvm_unreachable("invalid attr kind");
1892 }
1893
getDecl() const1894 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1895 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1896 }
1897
getIdentifier() const1898 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1899 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1900 }
1901
1902 SubstTemplateTypeParmPackType::
SubstTemplateTypeParmPackType(const TemplateTypeParmType * Param,QualType Canon,const TemplateArgument & ArgPack)1903 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1904 QualType Canon,
1905 const TemplateArgument &ArgPack)
1906 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1907 Replaced(Param),
1908 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1909 {
1910 }
1911
getArgumentPack() const1912 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1913 return TemplateArgument(Arguments, NumArguments);
1914 }
1915
Profile(llvm::FoldingSetNodeID & ID)1916 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1917 Profile(ID, getReplacedParameter(), getArgumentPack());
1918 }
1919
Profile(llvm::FoldingSetNodeID & ID,const TemplateTypeParmType * Replaced,const TemplateArgument & ArgPack)1920 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1921 const TemplateTypeParmType *Replaced,
1922 const TemplateArgument &ArgPack) {
1923 ID.AddPointer(Replaced);
1924 ID.AddInteger(ArgPack.pack_size());
1925 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1926 PEnd = ArgPack.pack_end();
1927 P != PEnd; ++P)
1928 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1929 }
1930
1931 bool TemplateSpecializationType::
anyDependentTemplateArguments(const TemplateArgumentListInfo & Args,bool & InstantiationDependent)1932 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1933 bool &InstantiationDependent) {
1934 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1935 InstantiationDependent);
1936 }
1937
1938 bool TemplateSpecializationType::
anyDependentTemplateArguments(const TemplateArgumentLoc * Args,unsigned N,bool & InstantiationDependent)1939 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1940 bool &InstantiationDependent) {
1941 for (unsigned i = 0; i != N; ++i) {
1942 if (Args[i].getArgument().isDependent()) {
1943 InstantiationDependent = true;
1944 return true;
1945 }
1946
1947 if (Args[i].getArgument().isInstantiationDependent())
1948 InstantiationDependent = true;
1949 }
1950 return false;
1951 }
1952
1953 #ifndef NDEBUG
1954 static bool
anyDependentTemplateArguments(const TemplateArgument * Args,unsigned N,bool & InstantiationDependent)1955 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1956 bool &InstantiationDependent) {
1957 for (unsigned i = 0; i != N; ++i) {
1958 if (Args[i].isDependent()) {
1959 InstantiationDependent = true;
1960 return true;
1961 }
1962
1963 if (Args[i].isInstantiationDependent())
1964 InstantiationDependent = true;
1965 }
1966 return false;
1967 }
1968 #endif
1969
1970 TemplateSpecializationType::
TemplateSpecializationType(TemplateName T,const TemplateArgument * Args,unsigned NumArgs,QualType Canon,QualType AliasedType)1971 TemplateSpecializationType(TemplateName T,
1972 const TemplateArgument *Args, unsigned NumArgs,
1973 QualType Canon, QualType AliasedType)
1974 : Type(TemplateSpecialization,
1975 Canon.isNull()? QualType(this, 0) : Canon,
1976 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1977 Canon.isNull()? T.isDependent()
1978 : Canon->isInstantiationDependentType(),
1979 false,
1980 T.containsUnexpandedParameterPack()),
1981 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1982 assert(!T.getAsDependentTemplateName() &&
1983 "Use DependentTemplateSpecializationType for dependent template-name");
1984 assert((T.getKind() == TemplateName::Template ||
1985 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1986 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1987 "Unexpected template name for TemplateSpecializationType");
1988 bool InstantiationDependent;
1989 (void)InstantiationDependent;
1990 assert((!Canon.isNull() ||
1991 T.isDependent() ||
1992 ::anyDependentTemplateArguments(Args, NumArgs,
1993 InstantiationDependent)) &&
1994 "No canonical type for non-dependent class template specialization");
1995
1996 TemplateArgument *TemplateArgs
1997 = reinterpret_cast<TemplateArgument *>(this + 1);
1998 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1999 // Update dependent and variably-modified bits.
2000 // If the canonical type exists and is non-dependent, the template
2001 // specialization type can be non-dependent even if one of the type
2002 // arguments is. Given:
2003 // template<typename T> using U = int;
2004 // U<T> is always non-dependent, irrespective of the type T.
2005 // However, U<Ts> contains an unexpanded parameter pack, even though
2006 // its expansion (and thus its desugared type) doesn't.
2007 if (Canon.isNull() && Args[Arg].isDependent())
2008 setDependent();
2009 else if (Args[Arg].isInstantiationDependent())
2010 setInstantiationDependent();
2011
2012 if (Args[Arg].getKind() == TemplateArgument::Type &&
2013 Args[Arg].getAsType()->isVariablyModifiedType())
2014 setVariablyModified();
2015 if (Args[Arg].containsUnexpandedParameterPack())
2016 setContainsUnexpandedParameterPack();
2017
2018 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2019 }
2020
2021 // Store the aliased type if this is a type alias template specialization.
2022 if (TypeAlias) {
2023 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2024 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2025 }
2026 }
2027
2028 void
Profile(llvm::FoldingSetNodeID & ID,TemplateName T,const TemplateArgument * Args,unsigned NumArgs,const ASTContext & Context)2029 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2030 TemplateName T,
2031 const TemplateArgument *Args,
2032 unsigned NumArgs,
2033 const ASTContext &Context) {
2034 T.Profile(ID);
2035 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2036 Args[Idx].Profile(ID, Context);
2037 }
2038
2039 QualType
apply(const ASTContext & Context,QualType QT) const2040 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2041 if (!hasNonFastQualifiers())
2042 return QT.withFastQualifiers(getFastQualifiers());
2043
2044 return Context.getQualifiedType(QT, *this);
2045 }
2046
2047 QualType
apply(const ASTContext & Context,const Type * T) const2048 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2049 if (!hasNonFastQualifiers())
2050 return QualType(T, getFastQualifiers());
2051
2052 return Context.getQualifiedType(T, *this);
2053 }
2054
Profile(llvm::FoldingSetNodeID & ID,QualType BaseType,ObjCProtocolDecl * const * Protocols,unsigned NumProtocols)2055 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2056 QualType BaseType,
2057 ObjCProtocolDecl * const *Protocols,
2058 unsigned NumProtocols) {
2059 ID.AddPointer(BaseType.getAsOpaquePtr());
2060 for (unsigned i = 0; i != NumProtocols; i++)
2061 ID.AddPointer(Protocols[i]);
2062 }
2063
Profile(llvm::FoldingSetNodeID & ID)2064 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2065 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2066 }
2067
2068 namespace {
2069
2070 /// \brief The cached properties of a type.
2071 class CachedProperties {
2072 Linkage L;
2073 bool local;
2074
2075 public:
CachedProperties(Linkage L,bool local)2076 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2077
getLinkage() const2078 Linkage getLinkage() const { return L; }
hasLocalOrUnnamedType() const2079 bool hasLocalOrUnnamedType() const { return local; }
2080
merge(CachedProperties L,CachedProperties R)2081 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2082 Linkage MergedLinkage = minLinkage(L.L, R.L);
2083 return CachedProperties(MergedLinkage,
2084 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2085 }
2086 };
2087 }
2088
2089 static CachedProperties computeCachedProperties(const Type *T);
2090
2091 namespace clang {
2092 /// The type-property cache. This is templated so as to be
2093 /// instantiated at an internal type to prevent unnecessary symbol
2094 /// leakage.
2095 template <class Private> class TypePropertyCache {
2096 public:
get(QualType T)2097 static CachedProperties get(QualType T) {
2098 return get(T.getTypePtr());
2099 }
2100
get(const Type * T)2101 static CachedProperties get(const Type *T) {
2102 ensure(T);
2103 return CachedProperties(T->TypeBits.getLinkage(),
2104 T->TypeBits.hasLocalOrUnnamedType());
2105 }
2106
ensure(const Type * T)2107 static void ensure(const Type *T) {
2108 // If the cache is valid, we're okay.
2109 if (T->TypeBits.isCacheValid()) return;
2110
2111 // If this type is non-canonical, ask its canonical type for the
2112 // relevant information.
2113 if (!T->isCanonicalUnqualified()) {
2114 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2115 ensure(CT);
2116 T->TypeBits.CacheValid = true;
2117 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2118 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2119 return;
2120 }
2121
2122 // Compute the cached properties and then set the cache.
2123 CachedProperties Result = computeCachedProperties(T);
2124 T->TypeBits.CacheValid = true;
2125 T->TypeBits.CachedLinkage = Result.getLinkage();
2126 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2127 }
2128 };
2129 }
2130
2131 // Instantiate the friend template at a private class. In a
2132 // reasonable implementation, these symbols will be internal.
2133 // It is terrible that this is the best way to accomplish this.
2134 namespace { class Private {}; }
2135 typedef TypePropertyCache<Private> Cache;
2136
computeCachedProperties(const Type * T)2137 static CachedProperties computeCachedProperties(const Type *T) {
2138 switch (T->getTypeClass()) {
2139 #define TYPE(Class,Base)
2140 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2141 #include "clang/AST/TypeNodes.def"
2142 llvm_unreachable("didn't expect a non-canonical type here");
2143
2144 #define TYPE(Class,Base)
2145 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2146 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2147 #include "clang/AST/TypeNodes.def"
2148 // Treat instantiation-dependent types as external.
2149 assert(T->isInstantiationDependentType());
2150 return CachedProperties(ExternalLinkage, false);
2151
2152 case Type::Auto:
2153 // Give non-deduced 'auto' types external linkage. We should only see them
2154 // here in error recovery.
2155 return CachedProperties(ExternalLinkage, false);
2156
2157 case Type::Builtin:
2158 // C++ [basic.link]p8:
2159 // A type is said to have linkage if and only if:
2160 // - it is a fundamental type (3.9.1); or
2161 return CachedProperties(ExternalLinkage, false);
2162
2163 case Type::Record:
2164 case Type::Enum: {
2165 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2166
2167 // C++ [basic.link]p8:
2168 // - it is a class or enumeration type that is named (or has a name
2169 // for linkage purposes (7.1.3)) and the name has linkage; or
2170 // - it is a specialization of a class template (14); or
2171 Linkage L = Tag->getLinkageInternal();
2172 bool IsLocalOrUnnamed =
2173 Tag->getDeclContext()->isFunctionOrMethod() ||
2174 !Tag->hasNameForLinkage();
2175 return CachedProperties(L, IsLocalOrUnnamed);
2176 }
2177
2178 // C++ [basic.link]p8:
2179 // - it is a compound type (3.9.2) other than a class or enumeration,
2180 // compounded exclusively from types that have linkage; or
2181 case Type::Complex:
2182 return Cache::get(cast<ComplexType>(T)->getElementType());
2183 case Type::Pointer:
2184 return Cache::get(cast<PointerType>(T)->getPointeeType());
2185 case Type::BlockPointer:
2186 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2187 case Type::LValueReference:
2188 case Type::RValueReference:
2189 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2190 case Type::MemberPointer: {
2191 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2192 return merge(Cache::get(MPT->getClass()),
2193 Cache::get(MPT->getPointeeType()));
2194 }
2195 case Type::ConstantArray:
2196 case Type::IncompleteArray:
2197 case Type::VariableArray:
2198 return Cache::get(cast<ArrayType>(T)->getElementType());
2199 case Type::Vector:
2200 case Type::ExtVector:
2201 return Cache::get(cast<VectorType>(T)->getElementType());
2202 case Type::FunctionNoProto:
2203 return Cache::get(cast<FunctionType>(T)->getResultType());
2204 case Type::FunctionProto: {
2205 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2206 CachedProperties result = Cache::get(FPT->getResultType());
2207 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2208 ae = FPT->arg_type_end(); ai != ae; ++ai)
2209 result = merge(result, Cache::get(*ai));
2210 return result;
2211 }
2212 case Type::ObjCInterface: {
2213 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2214 return CachedProperties(L, false);
2215 }
2216 case Type::ObjCObject:
2217 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2218 case Type::ObjCObjectPointer:
2219 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2220 case Type::Atomic:
2221 return Cache::get(cast<AtomicType>(T)->getValueType());
2222 }
2223
2224 llvm_unreachable("unhandled type class");
2225 }
2226
2227 /// \brief Determine the linkage of this type.
getLinkage() const2228 Linkage Type::getLinkage() const {
2229 Cache::ensure(this);
2230 return TypeBits.getLinkage();
2231 }
2232
hasUnnamedOrLocalType() const2233 bool Type::hasUnnamedOrLocalType() const {
2234 Cache::ensure(this);
2235 return TypeBits.hasLocalOrUnnamedType();
2236 }
2237
2238 static LinkageInfo computeLinkageInfo(QualType T);
2239
computeLinkageInfo(const Type * T)2240 static LinkageInfo computeLinkageInfo(const Type *T) {
2241 switch (T->getTypeClass()) {
2242 #define TYPE(Class,Base)
2243 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2244 #include "clang/AST/TypeNodes.def"
2245 llvm_unreachable("didn't expect a non-canonical type here");
2246
2247 #define TYPE(Class,Base)
2248 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2249 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2250 #include "clang/AST/TypeNodes.def"
2251 // Treat instantiation-dependent types as external.
2252 assert(T->isInstantiationDependentType());
2253 return LinkageInfo::external();
2254
2255 case Type::Builtin:
2256 return LinkageInfo::external();
2257
2258 case Type::Auto:
2259 return LinkageInfo::external();
2260
2261 case Type::Record:
2262 case Type::Enum:
2263 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2264
2265 case Type::Complex:
2266 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2267 case Type::Pointer:
2268 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2269 case Type::BlockPointer:
2270 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2271 case Type::LValueReference:
2272 case Type::RValueReference:
2273 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2274 case Type::MemberPointer: {
2275 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2276 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2277 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2278 return LV;
2279 }
2280 case Type::ConstantArray:
2281 case Type::IncompleteArray:
2282 case Type::VariableArray:
2283 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2284 case Type::Vector:
2285 case Type::ExtVector:
2286 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2287 case Type::FunctionNoProto:
2288 return computeLinkageInfo(cast<FunctionType>(T)->getResultType());
2289 case Type::FunctionProto: {
2290 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2291 LinkageInfo LV = computeLinkageInfo(FPT->getResultType());
2292 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2293 ae = FPT->arg_type_end(); ai != ae; ++ai)
2294 LV.merge(computeLinkageInfo(*ai));
2295 return LV;
2296 }
2297 case Type::ObjCInterface:
2298 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2299 case Type::ObjCObject:
2300 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2301 case Type::ObjCObjectPointer:
2302 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2303 case Type::Atomic:
2304 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2305 }
2306
2307 llvm_unreachable("unhandled type class");
2308 }
2309
computeLinkageInfo(QualType T)2310 static LinkageInfo computeLinkageInfo(QualType T) {
2311 return computeLinkageInfo(T.getTypePtr());
2312 }
2313
isLinkageValid() const2314 bool Type::isLinkageValid() const {
2315 if (!TypeBits.isCacheValid())
2316 return true;
2317
2318 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2319 TypeBits.getLinkage();
2320 }
2321
getLinkageAndVisibility() const2322 LinkageInfo Type::getLinkageAndVisibility() const {
2323 if (!isCanonicalUnqualified())
2324 return computeLinkageInfo(getCanonicalTypeInternal());
2325
2326 LinkageInfo LV = computeLinkageInfo(this);
2327 assert(LV.getLinkage() == getLinkage());
2328 return LV;
2329 }
2330
getObjCARCImplicitLifetime() const2331 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2332 if (isObjCARCImplicitlyUnretainedType())
2333 return Qualifiers::OCL_ExplicitNone;
2334 return Qualifiers::OCL_Strong;
2335 }
2336
isObjCARCImplicitlyUnretainedType() const2337 bool Type::isObjCARCImplicitlyUnretainedType() const {
2338 assert(isObjCLifetimeType() &&
2339 "cannot query implicit lifetime for non-inferrable type");
2340
2341 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2342
2343 // Walk down to the base type. We don't care about qualifiers for this.
2344 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2345 canon = array->getElementType().getTypePtr();
2346
2347 if (const ObjCObjectPointerType *opt
2348 = dyn_cast<ObjCObjectPointerType>(canon)) {
2349 // Class and Class<Protocol> don't require retension.
2350 if (opt->getObjectType()->isObjCClass())
2351 return true;
2352 }
2353
2354 return false;
2355 }
2356
isObjCNSObjectType() const2357 bool Type::isObjCNSObjectType() const {
2358 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2359 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2360 return false;
2361 }
isObjCRetainableType() const2362 bool Type::isObjCRetainableType() const {
2363 return isObjCObjectPointerType() ||
2364 isBlockPointerType() ||
2365 isObjCNSObjectType();
2366 }
isObjCIndirectLifetimeType() const2367 bool Type::isObjCIndirectLifetimeType() const {
2368 if (isObjCLifetimeType())
2369 return true;
2370 if (const PointerType *OPT = getAs<PointerType>())
2371 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2372 if (const ReferenceType *Ref = getAs<ReferenceType>())
2373 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2374 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2375 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2376 return false;
2377 }
2378
2379 /// Returns true if objects of this type have lifetime semantics under
2380 /// ARC.
isObjCLifetimeType() const2381 bool Type::isObjCLifetimeType() const {
2382 const Type *type = this;
2383 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2384 type = array->getElementType().getTypePtr();
2385 return type->isObjCRetainableType();
2386 }
2387
2388 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2389 /// which is either an Objective-C object pointer type or an
isObjCARCBridgableType() const2390 bool Type::isObjCARCBridgableType() const {
2391 return isObjCObjectPointerType() || isBlockPointerType();
2392 }
2393
2394 /// \brief Determine whether the given type T is a "bridgeable" C type.
isCARCBridgableType() const2395 bool Type::isCARCBridgableType() const {
2396 const PointerType *Pointer = getAs<PointerType>();
2397 if (!Pointer)
2398 return false;
2399
2400 QualType Pointee = Pointer->getPointeeType();
2401 return Pointee->isVoidType() || Pointee->isRecordType();
2402 }
2403
hasSizedVLAType() const2404 bool Type::hasSizedVLAType() const {
2405 if (!isVariablyModifiedType()) return false;
2406
2407 if (const PointerType *ptr = getAs<PointerType>())
2408 return ptr->getPointeeType()->hasSizedVLAType();
2409 if (const ReferenceType *ref = getAs<ReferenceType>())
2410 return ref->getPointeeType()->hasSizedVLAType();
2411 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2412 if (isa<VariableArrayType>(arr) &&
2413 cast<VariableArrayType>(arr)->getSizeExpr())
2414 return true;
2415
2416 return arr->getElementType()->hasSizedVLAType();
2417 }
2418
2419 return false;
2420 }
2421
isDestructedTypeImpl(QualType type)2422 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2423 switch (type.getObjCLifetime()) {
2424 case Qualifiers::OCL_None:
2425 case Qualifiers::OCL_ExplicitNone:
2426 case Qualifiers::OCL_Autoreleasing:
2427 break;
2428
2429 case Qualifiers::OCL_Strong:
2430 return DK_objc_strong_lifetime;
2431 case Qualifiers::OCL_Weak:
2432 return DK_objc_weak_lifetime;
2433 }
2434
2435 /// Currently, the only destruction kind we recognize is C++ objects
2436 /// with non-trivial destructors.
2437 const CXXRecordDecl *record =
2438 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2439 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2440 return DK_cxx_destructor;
2441
2442 return DK_none;
2443 }
2444