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