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