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