Type.cpp revision bbd340717422bf011d56cd0164d2576601368111
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/Basic/Specifiers.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Support/raw_ostream.h"
25#include <algorithm>
26using namespace clang;
27
28bool QualType::isConstant(QualType T, ASTContext &Ctx) {
29  if (T.isConstQualified())
30    return true;
31
32  if (const ArrayType *AT = Ctx.getAsArrayType(T))
33    return AT->getElementType().isConstant(Ctx);
34
35  return false;
36}
37
38Type::~Type() { }
39
40unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
41                                                 QualType ElementType,
42                                               const llvm::APInt &NumElements) {
43  llvm::APSInt SizeExtended(NumElements, true);
44  unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
45  SizeExtended.extend(std::max(SizeTypeBits, SizeExtended.getBitWidth()) * 2);
46
47  uint64_t ElementSize
48    = Context.getTypeSizeInChars(ElementType).getQuantity();
49  llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
50  TotalSize *= SizeExtended;
51
52  return TotalSize.getActiveBits();
53}
54
55unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
56  unsigned Bits = Context.getTypeSize(Context.getSizeType());
57
58  // GCC appears to only allow 63 bits worth of address space when compiling
59  // for 64-bit, so we do the same.
60  if (Bits == 64)
61    --Bits;
62
63  return Bits;
64}
65
66void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
67                                      ASTContext &Context,
68                                      QualType ET,
69                                      ArraySizeModifier SizeMod,
70                                      unsigned TypeQuals,
71                                      Expr *E) {
72  ID.AddPointer(ET.getAsOpaquePtr());
73  ID.AddInteger(SizeMod);
74  ID.AddInteger(TypeQuals);
75  E->Profile(ID, Context, true);
76}
77
78void
79DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
80                                     ASTContext &Context,
81                                     QualType ElementType, Expr *SizeExpr) {
82  ID.AddPointer(ElementType.getAsOpaquePtr());
83  SizeExpr->Profile(ID, Context, true);
84}
85
86/// getArrayElementTypeNoTypeQual - If this is an array type, return the
87/// element type of the array, potentially with type qualifiers missing.
88/// This method should never be used when type qualifiers are meaningful.
89const Type *Type::getArrayElementTypeNoTypeQual() const {
90  // If this is directly an array type, return it.
91  if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
92    return ATy->getElementType().getTypePtr();
93
94  // If the canonical form of this type isn't the right kind, reject it.
95  if (!isa<ArrayType>(CanonicalType))
96    return 0;
97
98  // If this is a typedef for an array type, strip the typedef off without
99  // losing all typedef information.
100  return cast<ArrayType>(getUnqualifiedDesugaredType())
101    ->getElementType().getTypePtr();
102}
103
104/// \brief Retrieve the unqualified variant of the given type, removing as
105/// little sugar as possible.
106///
107/// This routine looks through various kinds of sugar to find the
108/// least-desuraged type that is unqualified. For example, given:
109///
110/// \code
111/// typedef int Integer;
112/// typedef const Integer CInteger;
113/// typedef CInteger DifferenceType;
114/// \endcode
115///
116/// Executing \c getUnqualifiedTypeSlow() on the type \c DifferenceType will
117/// desugar until we hit the type \c Integer, which has no qualifiers on it.
118QualType QualType::getUnqualifiedTypeSlow() const {
119  QualType Cur = *this;
120  while (true) {
121    if (!Cur.hasQualifiers())
122      return Cur;
123
124    const Type *CurTy = Cur.getTypePtr();
125    switch (CurTy->getTypeClass()) {
126#define ABSTRACT_TYPE(Class, Parent)
127#define TYPE(Class, Parent)                                  \
128    case Type::Class: {                                      \
129      const Class##Type *Ty = cast<Class##Type>(CurTy);      \
130      if (!Ty->isSugared())                                  \
131        return Cur.getLocalUnqualifiedType();                \
132      Cur = Ty->desugar();                                   \
133      break;                                                 \
134    }
135#include "clang/AST/TypeNodes.def"
136    }
137  }
138
139  return Cur.getUnqualifiedType();
140}
141
142/// getDesugaredType - Return the specified type with any "sugar" removed from
143/// the type.  This takes off typedefs, typeof's etc.  If the outer level of
144/// the type is already concrete, it returns it unmodified.  This is similar
145/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
146/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
147/// concrete.
148QualType QualType::getDesugaredType(QualType T) {
149  QualifierCollector Qs;
150
151  QualType Cur = T;
152  while (true) {
153    const Type *CurTy = Qs.strip(Cur);
154    switch (CurTy->getTypeClass()) {
155#define ABSTRACT_TYPE(Class, Parent)
156#define TYPE(Class, Parent) \
157    case Type::Class: { \
158      const Class##Type *Ty = cast<Class##Type>(CurTy); \
159      if (!Ty->isSugared()) \
160        return Qs.apply(Cur); \
161      Cur = Ty->desugar(); \
162      break; \
163    }
164#include "clang/AST/TypeNodes.def"
165    }
166  }
167}
168
169/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
170/// sugar off the given type.  This should produce an object of the
171/// same dynamic type as the canonical type.
172const Type *Type::getUnqualifiedDesugaredType() const {
173  const Type *Cur = this;
174
175  while (true) {
176    switch (Cur->getTypeClass()) {
177#define ABSTRACT_TYPE(Class, Parent)
178#define TYPE(Class, Parent) \
179    case Class: { \
180      const Class##Type *Ty = cast<Class##Type>(Cur); \
181      if (!Ty->isSugared()) return Cur; \
182      Cur = Ty->desugar().getTypePtr(); \
183      break; \
184    }
185#include "clang/AST/TypeNodes.def"
186    }
187  }
188}
189
190/// isVoidType - Helper method to determine if this is the 'void' type.
191bool Type::isVoidType() const {
192  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
193    return BT->getKind() == BuiltinType::Void;
194  return false;
195}
196
197bool Type::isDerivedType() const {
198  switch (CanonicalType->getTypeClass()) {
199  case Pointer:
200  case VariableArray:
201  case ConstantArray:
202  case IncompleteArray:
203  case FunctionProto:
204  case FunctionNoProto:
205  case LValueReference:
206  case RValueReference:
207  case Record:
208    return true;
209  default:
210    return false;
211  }
212}
213
214bool Type::isClassType() const {
215  if (const RecordType *RT = getAs<RecordType>())
216    return RT->getDecl()->isClass();
217  return false;
218}
219bool Type::isStructureType() const {
220  if (const RecordType *RT = getAs<RecordType>())
221    return RT->getDecl()->isStruct();
222  return false;
223}
224bool Type::isStructureOrClassType() const {
225  if (const RecordType *RT = getAs<RecordType>())
226    return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
227  return false;
228}
229bool Type::isVoidPointerType() const {
230  if (const PointerType *PT = getAs<PointerType>())
231    return PT->getPointeeType()->isVoidType();
232  return false;
233}
234
235bool Type::isUnionType() const {
236  if (const RecordType *RT = getAs<RecordType>())
237    return RT->getDecl()->isUnion();
238  return false;
239}
240
241bool Type::isComplexType() const {
242  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
243    return CT->getElementType()->isFloatingType();
244  return false;
245}
246
247bool Type::isComplexIntegerType() const {
248  // Check for GCC complex integer extension.
249  return getAsComplexIntegerType();
250}
251
252const ComplexType *Type::getAsComplexIntegerType() const {
253  if (const ComplexType *Complex = getAs<ComplexType>())
254    if (Complex->getElementType()->isIntegerType())
255      return Complex;
256  return 0;
257}
258
259QualType Type::getPointeeType() const {
260  if (const PointerType *PT = getAs<PointerType>())
261    return PT->getPointeeType();
262  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
263    return OPT->getPointeeType();
264  if (const BlockPointerType *BPT = getAs<BlockPointerType>())
265    return BPT->getPointeeType();
266  if (const ReferenceType *RT = getAs<ReferenceType>())
267    return RT->getPointeeType();
268  return QualType();
269}
270
271const RecordType *Type::getAsStructureType() const {
272  // If this is directly a structure type, return it.
273  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
274    if (RT->getDecl()->isStruct())
275      return RT;
276  }
277
278  // If the canonical form of this type isn't the right kind, reject it.
279  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
280    if (!RT->getDecl()->isStruct())
281      return 0;
282
283    // If this is a typedef for a structure type, strip the typedef off without
284    // losing all typedef information.
285    return cast<RecordType>(getUnqualifiedDesugaredType());
286  }
287  return 0;
288}
289
290const RecordType *Type::getAsUnionType() const {
291  // If this is directly a union type, return it.
292  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
293    if (RT->getDecl()->isUnion())
294      return RT;
295  }
296
297  // If the canonical form of this type isn't the right kind, reject it.
298  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
299    if (!RT->getDecl()->isUnion())
300      return 0;
301
302    // If this is a typedef for a union type, strip the typedef off without
303    // losing all typedef information.
304    return cast<RecordType>(getUnqualifiedDesugaredType());
305  }
306
307  return 0;
308}
309
310ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
311                               ObjCProtocolDecl * const *Protocols,
312                               unsigned NumProtocols)
313  : Type(ObjCObject, Canonical, false, false),
314    BaseType(Base) {
315  ObjCObjectTypeBits.NumProtocols = NumProtocols;
316  assert(getNumProtocols() == NumProtocols &&
317         "bitfield overflow in protocol count");
318  if (NumProtocols)
319    memcpy(getProtocolStorage(), Protocols,
320           NumProtocols * sizeof(ObjCProtocolDecl*));
321}
322
323const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
324  // There is no sugar for ObjCObjectType's, just return the canonical
325  // type pointer if it is the right class.  There is no typedef information to
326  // return and these cannot be Address-space qualified.
327  if (const ObjCObjectType *T = getAs<ObjCObjectType>())
328    if (T->getNumProtocols() && T->getInterface())
329      return T;
330  return 0;
331}
332
333bool Type::isObjCQualifiedInterfaceType() const {
334  return getAsObjCQualifiedInterfaceType() != 0;
335}
336
337const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
338  // There is no sugar for ObjCQualifiedIdType's, just return the canonical
339  // type pointer if it is the right class.
340  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
341    if (OPT->isObjCQualifiedIdType())
342      return OPT;
343  }
344  return 0;
345}
346
347const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
348  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
349    if (OPT->getInterfaceType())
350      return OPT;
351  }
352  return 0;
353}
354
355const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
356  if (const PointerType *PT = getAs<PointerType>())
357    if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
358      return dyn_cast<CXXRecordDecl>(RT->getDecl());
359  return 0;
360}
361
362CXXRecordDecl *Type::getAsCXXRecordDecl() const {
363  if (const RecordType *RT = getAs<RecordType>())
364    return dyn_cast<CXXRecordDecl>(RT->getDecl());
365  else if (const InjectedClassNameType *Injected
366                                  = getAs<InjectedClassNameType>())
367    return Injected->getDecl();
368
369  return 0;
370}
371
372bool Type::isIntegerType() const {
373  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
374    return BT->getKind() >= BuiltinType::Bool &&
375           BT->getKind() <= BuiltinType::Int128;
376  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
377    // Incomplete enum types are not treated as integer types.
378    // FIXME: In C++, enum types are never integer types.
379    return ET->getDecl()->isComplete();
380  return false;
381}
382
383bool Type::hasIntegerRepresentation() const {
384  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
385    return VT->getElementType()->isIntegerType();
386  else
387    return isIntegerType();
388}
389
390/// \brief Determine whether this type is an integral type.
391///
392/// This routine determines whether the given type is an integral type per
393/// C++ [basic.fundamental]p7. Although the C standard does not define the
394/// term "integral type", it has a similar term "integer type", and in C++
395/// the two terms are equivalent. However, C's "integer type" includes
396/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
397/// parameter is used to determine whether we should be following the C or
398/// C++ rules when determining whether this type is an integral/integer type.
399///
400/// For cases where C permits "an integer type" and C++ permits "an integral
401/// type", use this routine.
402///
403/// For cases where C permits "an integer type" and C++ permits "an integral
404/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
405///
406/// \param Ctx The context in which this type occurs.
407///
408/// \returns true if the type is considered an integral type, false otherwise.
409bool Type::isIntegralType(ASTContext &Ctx) const {
410  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
411    return BT->getKind() >= BuiltinType::Bool &&
412    BT->getKind() <= BuiltinType::Int128;
413
414  if (!Ctx.getLangOptions().CPlusPlus)
415    if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
416      return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
417
418  return false;
419}
420
421bool Type::isIntegralOrEnumerationType() const {
422  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
423    return BT->getKind() >= BuiltinType::Bool &&
424           BT->getKind() <= BuiltinType::Int128;
425
426  // Check for a complete enum type; incomplete enum types are not properly an
427  // enumeration type in the sense required here.
428  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
429    return ET->getDecl()->isComplete();
430
431  return false;
432}
433
434bool Type::isIntegralOrUnscopedEnumerationType() const {
435  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
436    return BT->getKind() >= BuiltinType::Bool &&
437           BT->getKind() <= BuiltinType::Int128;
438
439  // Check for a complete enum type; incomplete enum types are not properly an
440  // enumeration type in the sense required here.
441  // C++0x: However, if the underlying type of the enum is fixed, it is
442  // considered complete.
443  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
444    return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
445
446  return false;
447}
448
449
450bool Type::isBooleanType() const {
451  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
452    return BT->getKind() == BuiltinType::Bool;
453  return false;
454}
455
456bool Type::isCharType() const {
457  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
458    return BT->getKind() == BuiltinType::Char_U ||
459           BT->getKind() == BuiltinType::UChar ||
460           BT->getKind() == BuiltinType::Char_S ||
461           BT->getKind() == BuiltinType::SChar;
462  return false;
463}
464
465bool Type::isWideCharType() const {
466  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
467    return BT->getKind() == BuiltinType::WChar;
468  return false;
469}
470
471/// \brief Determine whether this type is any of the built-in character
472/// types.
473bool Type::isAnyCharacterType() const {
474  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
475    return (BT->getKind() >= BuiltinType::Char_U &&
476            BT->getKind() <= BuiltinType::Char32) ||
477           (BT->getKind() >= BuiltinType::Char_S &&
478            BT->getKind() <= BuiltinType::WChar);
479
480  return false;
481}
482
483/// isSignedIntegerType - Return true if this is an integer type that is
484/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
485/// an enum decl which has a signed representation
486bool Type::isSignedIntegerType() const {
487  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
488    return BT->getKind() >= BuiltinType::Char_S &&
489           BT->getKind() <= BuiltinType::Int128;
490  }
491
492  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
493    // Incomplete enum types are not treated as integer types.
494    // FIXME: In C++, enum types are never integer types.
495    if (ET->getDecl()->isComplete())
496      return ET->getDecl()->getIntegerType()->isSignedIntegerType();
497  }
498
499  return false;
500}
501
502bool Type::hasSignedIntegerRepresentation() const {
503  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
504    return VT->getElementType()->isSignedIntegerType();
505  else
506    return isSignedIntegerType();
507}
508
509/// isUnsignedIntegerType - Return true if this is an integer type that is
510/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
511/// decl which has an unsigned representation
512bool Type::isUnsignedIntegerType() const {
513  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
514    return BT->getKind() >= BuiltinType::Bool &&
515           BT->getKind() <= BuiltinType::UInt128;
516  }
517
518  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
519    // Incomplete enum types are not treated as integer types.
520    // FIXME: In C++, enum types are never integer types.
521    if (ET->getDecl()->isComplete())
522      return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
523  }
524
525  return false;
526}
527
528bool Type::hasUnsignedIntegerRepresentation() const {
529  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
530    return VT->getElementType()->isUnsignedIntegerType();
531  else
532    return isUnsignedIntegerType();
533}
534
535bool Type::isFloatingType() const {
536  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
537    return BT->getKind() >= BuiltinType::Float &&
538           BT->getKind() <= BuiltinType::LongDouble;
539  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
540    return CT->getElementType()->isFloatingType();
541  return false;
542}
543
544bool Type::hasFloatingRepresentation() const {
545  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
546    return VT->getElementType()->isFloatingType();
547  else
548    return isFloatingType();
549}
550
551bool Type::isRealFloatingType() const {
552  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
553    return BT->isFloatingPoint();
554  return false;
555}
556
557bool Type::isRealType() const {
558  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
559    return BT->getKind() >= BuiltinType::Bool &&
560           BT->getKind() <= BuiltinType::LongDouble;
561  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
562      return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
563  return false;
564}
565
566bool Type::isArithmeticType() const {
567  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
568    return BT->getKind() >= BuiltinType::Bool &&
569           BT->getKind() <= BuiltinType::LongDouble;
570  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
571    // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
572    // If a body isn't seen by the time we get here, return false.
573    //
574    // C++0x: Enumerations are not arithmetic types. For now, just return
575    // false for scoped enumerations since that will disable any
576    // unwanted implicit conversions.
577    return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
578  return isa<ComplexType>(CanonicalType);
579}
580
581bool Type::isScalarType() const {
582  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
583    return BT->getKind() > BuiltinType::Void &&
584           BT->getKind() <= BuiltinType::NullPtr;
585  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
586    // Enums are scalar types, but only if they are defined.  Incomplete enums
587    // are not treated as scalar types.
588    return ET->getDecl()->isComplete();
589  return isa<PointerType>(CanonicalType) ||
590         isa<BlockPointerType>(CanonicalType) ||
591         isa<MemberPointerType>(CanonicalType) ||
592         isa<ComplexType>(CanonicalType) ||
593         isa<ObjCObjectPointerType>(CanonicalType);
594}
595
596Type::ScalarTypeKind Type::getScalarTypeKind() const {
597  assert(isScalarType());
598
599  const Type *T = CanonicalType.getTypePtr();
600  if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
601    if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
602    if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
603    if (BT->isInteger()) return STK_Integral;
604    if (BT->isFloatingPoint()) return STK_Floating;
605    llvm_unreachable("unknown scalar builtin type");
606  } else if (isa<PointerType>(T) ||
607             isa<BlockPointerType>(T) ||
608             isa<ObjCObjectPointerType>(T)) {
609    return STK_Pointer;
610  } else if (isa<MemberPointerType>(T)) {
611    return STK_MemberPointer;
612  } else if (isa<EnumType>(T)) {
613    assert(cast<EnumType>(T)->getDecl()->isComplete());
614    return STK_Integral;
615  } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
616    if (CT->getElementType()->isRealFloatingType())
617      return STK_FloatingComplex;
618    return STK_IntegralComplex;
619  }
620
621  llvm_unreachable("unknown scalar type");
622  return STK_Pointer;
623}
624
625/// \brief Determines whether the type is a C++ aggregate type or C
626/// aggregate or union type.
627///
628/// An aggregate type is an array or a class type (struct, union, or
629/// class) that has no user-declared constructors, no private or
630/// protected non-static data members, no base classes, and no virtual
631/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
632/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
633/// includes union types.
634bool Type::isAggregateType() const {
635  if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
636    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
637      return ClassDecl->isAggregate();
638
639    return true;
640  }
641
642  return isa<ArrayType>(CanonicalType);
643}
644
645/// isConstantSizeType - Return true if this is not a variable sized type,
646/// according to the rules of C99 6.7.5p3.  It is not legal to call this on
647/// incomplete types or dependent types.
648bool Type::isConstantSizeType() const {
649  assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
650  assert(!isDependentType() && "This doesn't make sense for dependent types");
651  // The VAT must have a size, as it is known to be complete.
652  return !isa<VariableArrayType>(CanonicalType);
653}
654
655/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
656/// - a type that can describe objects, but which lacks information needed to
657/// determine its size.
658bool Type::isIncompleteType() const {
659  switch (CanonicalType->getTypeClass()) {
660  default: return false;
661  case Builtin:
662    // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
663    // be completed.
664    return isVoidType();
665  case Enum:
666    // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
667    if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
668        return false;
669    // Fall through.
670  case Record:
671    // A tagged type (struct/union/enum/class) is incomplete if the decl is a
672    // forward declaration, but not a full definition (C99 6.2.5p22).
673    return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
674  case ConstantArray:
675    // An array is incomplete if its element type is incomplete
676    // (C++ [dcl.array]p1).
677    // We don't handle variable arrays (they're not allowed in C++) or
678    // dependent-sized arrays (dependent types are never treated as incomplete).
679    return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
680  case IncompleteArray:
681    // An array of unknown size is an incomplete type (C99 6.2.5p22).
682    return true;
683  case ObjCObject:
684    return cast<ObjCObjectType>(CanonicalType)->getBaseType()
685                                                         ->isIncompleteType();
686  case ObjCInterface:
687    // ObjC interfaces are incomplete if they are @class, not @interface.
688    return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
689  }
690}
691
692/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
693bool Type::isPODType() const {
694  // The compiler shouldn't query this for incomplete types, but the user might.
695  // We return false for that case. Except for incomplete arrays of PODs, which
696  // are PODs according to the standard.
697  if (isIncompleteArrayType() &&
698      cast<ArrayType>(CanonicalType)->getElementType()->isPODType())
699    return true;
700  if (isIncompleteType())
701    return false;
702
703  switch (CanonicalType->getTypeClass()) {
704    // Everything not explicitly mentioned is not POD.
705  default: return false;
706  case VariableArray:
707  case ConstantArray:
708    // IncompleteArray is handled above.
709    return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
710
711  case Builtin:
712  case Complex:
713  case Pointer:
714  case MemberPointer:
715  case Vector:
716  case ExtVector:
717  case ObjCObjectPointer:
718  case BlockPointer:
719    return true;
720
721  case Enum:
722    return true;
723
724  case Record:
725    if (CXXRecordDecl *ClassDecl
726          = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
727      return ClassDecl->isPOD();
728
729    // C struct/union is POD.
730    return true;
731  }
732}
733
734bool Type::isLiteralType() const {
735  if (isIncompleteType())
736    return false;
737
738  // C++0x [basic.types]p10:
739  //   A type is a literal type if it is:
740  switch (CanonicalType->getTypeClass()) {
741    // We're whitelisting
742  default: return false;
743
744    //   -- a scalar type
745  case Builtin:
746  case Complex:
747  case Pointer:
748  case MemberPointer:
749  case Vector:
750  case ExtVector:
751  case ObjCObjectPointer:
752  case Enum:
753    return true;
754
755    //   -- a class type with ...
756  case Record:
757    // FIXME: Do the tests
758    return false;
759
760    //   -- an array of literal type
761    // Extension: variable arrays cannot be literal types, since they're
762    // runtime-sized.
763  case ConstantArray:
764    return cast<ArrayType>(CanonicalType)->getElementType()->isLiteralType();
765  }
766}
767
768bool Type::isPromotableIntegerType() const {
769  if (const BuiltinType *BT = getAs<BuiltinType>())
770    switch (BT->getKind()) {
771    case BuiltinType::Bool:
772    case BuiltinType::Char_S:
773    case BuiltinType::Char_U:
774    case BuiltinType::SChar:
775    case BuiltinType::UChar:
776    case BuiltinType::Short:
777    case BuiltinType::UShort:
778      return true;
779    default:
780      return false;
781    }
782
783  // Enumerated types are promotable to their compatible integer types
784  // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
785  if (const EnumType *ET = getAs<EnumType>()){
786    if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
787        || ET->getDecl()->isScoped())
788      return false;
789
790    const BuiltinType *BT
791      = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
792    return BT->getKind() == BuiltinType::Int
793           || BT->getKind() == BuiltinType::UInt;
794  }
795
796  return false;
797}
798
799bool Type::isNullPtrType() const {
800  if (const BuiltinType *BT = getAs<BuiltinType>())
801    return BT->getKind() == BuiltinType::NullPtr;
802  return false;
803}
804
805bool Type::isSpecifierType() const {
806  // Note that this intentionally does not use the canonical type.
807  switch (getTypeClass()) {
808  case Builtin:
809  case Record:
810  case Enum:
811  case Typedef:
812  case Complex:
813  case TypeOfExpr:
814  case TypeOf:
815  case TemplateTypeParm:
816  case SubstTemplateTypeParm:
817  case TemplateSpecialization:
818  case Elaborated:
819  case DependentName:
820  case DependentTemplateSpecialization:
821  case ObjCInterface:
822  case ObjCObject:
823  case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
824    return true;
825  default:
826    return false;
827  }
828}
829
830TypeWithKeyword::~TypeWithKeyword() {
831}
832
833ElaboratedTypeKeyword
834TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
835  switch (TypeSpec) {
836  default: return ETK_None;
837  case TST_typename: return ETK_Typename;
838  case TST_class: return ETK_Class;
839  case TST_struct: return ETK_Struct;
840  case TST_union: return ETK_Union;
841  case TST_enum: return ETK_Enum;
842  }
843}
844
845TagTypeKind
846TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
847  switch(TypeSpec) {
848  case TST_class: return TTK_Class;
849  case TST_struct: return TTK_Struct;
850  case TST_union: return TTK_Union;
851  case TST_enum: return TTK_Enum;
852  default: llvm_unreachable("Type specifier is not a tag type kind.");
853  }
854}
855
856ElaboratedTypeKeyword
857TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
858  switch (Kind) {
859  case TTK_Class: return ETK_Class;
860  case TTK_Struct: return ETK_Struct;
861  case TTK_Union: return ETK_Union;
862  case TTK_Enum: return ETK_Enum;
863  }
864  llvm_unreachable("Unknown tag type kind.");
865}
866
867TagTypeKind
868TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
869  switch (Keyword) {
870  case ETK_Class: return TTK_Class;
871  case ETK_Struct: return TTK_Struct;
872  case ETK_Union: return TTK_Union;
873  case ETK_Enum: return TTK_Enum;
874  case ETK_None: // Fall through.
875  case ETK_Typename:
876    llvm_unreachable("Elaborated type keyword is not a tag type kind.");
877  }
878  llvm_unreachable("Unknown elaborated type keyword.");
879}
880
881bool
882TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
883  switch (Keyword) {
884  case ETK_None:
885  case ETK_Typename:
886    return false;
887  case ETK_Class:
888  case ETK_Struct:
889  case ETK_Union:
890  case ETK_Enum:
891    return true;
892  }
893  llvm_unreachable("Unknown elaborated type keyword.");
894}
895
896const char*
897TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
898  switch (Keyword) {
899  default: llvm_unreachable("Unknown elaborated type keyword.");
900  case ETK_None: return "";
901  case ETK_Typename: return "typename";
902  case ETK_Class:  return "class";
903  case ETK_Struct: return "struct";
904  case ETK_Union:  return "union";
905  case ETK_Enum:   return "enum";
906  }
907}
908
909ElaboratedType::~ElaboratedType() {}
910DependentNameType::~DependentNameType() {}
911DependentTemplateSpecializationType::~DependentTemplateSpecializationType() {}
912
913DependentTemplateSpecializationType::DependentTemplateSpecializationType(
914                         ElaboratedTypeKeyword Keyword,
915                         NestedNameSpecifier *NNS, const IdentifierInfo *Name,
916                         unsigned NumArgs, const TemplateArgument *Args,
917                         QualType Canon)
918  : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true,
919                    false),
920    NNS(NNS), Name(Name), NumArgs(NumArgs) {
921  assert(NNS && NNS->isDependent() &&
922         "DependentTemplateSpecializatonType requires dependent qualifier");
923  for (unsigned I = 0; I != NumArgs; ++I)
924    new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
925}
926
927void
928DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
929                                             ASTContext &Context,
930                                             ElaboratedTypeKeyword Keyword,
931                                             NestedNameSpecifier *Qualifier,
932                                             const IdentifierInfo *Name,
933                                             unsigned NumArgs,
934                                             const TemplateArgument *Args) {
935  ID.AddInteger(Keyword);
936  ID.AddPointer(Qualifier);
937  ID.AddPointer(Name);
938  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
939    Args[Idx].Profile(ID, Context);
940}
941
942bool Type::isElaboratedTypeSpecifier() const {
943  ElaboratedTypeKeyword Keyword;
944  if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
945    Keyword = Elab->getKeyword();
946  else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
947    Keyword = DepName->getKeyword();
948  else if (const DependentTemplateSpecializationType *DepTST =
949             dyn_cast<DependentTemplateSpecializationType>(this))
950    Keyword = DepTST->getKeyword();
951  else
952    return false;
953
954  return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
955}
956
957const char *Type::getTypeClassName() const {
958  switch (TypeBits.TC) {
959  default: assert(0 && "Type class not in TypeNodes.def!");
960#define ABSTRACT_TYPE(Derived, Base)
961#define TYPE(Derived, Base) case Derived: return #Derived;
962#include "clang/AST/TypeNodes.def"
963  }
964}
965
966const char *BuiltinType::getName(const LangOptions &LO) const {
967  switch (getKind()) {
968  case Void:              return "void";
969  case Bool:              return LO.Bool ? "bool" : "_Bool";
970  case Char_S:            return "char";
971  case Char_U:            return "char";
972  case SChar:             return "signed char";
973  case Short:             return "short";
974  case Int:               return "int";
975  case Long:              return "long";
976  case LongLong:          return "long long";
977  case Int128:            return "__int128_t";
978  case UChar:             return "unsigned char";
979  case UShort:            return "unsigned short";
980  case UInt:              return "unsigned int";
981  case ULong:             return "unsigned long";
982  case ULongLong:         return "unsigned long long";
983  case UInt128:           return "__uint128_t";
984  case Float:             return "float";
985  case Double:            return "double";
986  case LongDouble:        return "long double";
987  case WChar:             return "wchar_t";
988  case Char16:            return "char16_t";
989  case Char32:            return "char32_t";
990  case NullPtr:           return "nullptr_t";
991  case Overload:          return "<overloaded function type>";
992  case Dependent:         return "<dependent type>";
993  case UndeducedAuto:     return "auto";
994  case ObjCId:            return "id";
995  case ObjCClass:         return "Class";
996  case ObjCSel:           return "SEL";
997  }
998}
999
1000void FunctionType::ANCHOR() {} // Key function for FunctionType.
1001
1002QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1003  if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1004    return RefType->getPointeeType();
1005
1006  // C++0x [basic.lval]:
1007  //   Class prvalues can have cv-qualified types; non-class prvalues always
1008  //   have cv-unqualified types.
1009  //
1010  // See also C99 6.3.2.1p2.
1011  if (!Context.getLangOptions().CPlusPlus ||
1012      (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1013    return getUnqualifiedType();
1014
1015  return *this;
1016}
1017
1018llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1019  switch (CC) {
1020  case CC_Default: llvm_unreachable("no name for default cc");
1021  default: return "";
1022
1023  case CC_C: return "cdecl";
1024  case CC_X86StdCall: return "stdcall";
1025  case CC_X86FastCall: return "fastcall";
1026  case CC_X86ThisCall: return "thiscall";
1027  case CC_X86Pascal: return "pascal";
1028  }
1029}
1030
1031FunctionProtoType::FunctionProtoType(QualType Result, const QualType *ArgArray,
1032                                     unsigned numArgs, bool isVariadic,
1033                                     unsigned typeQuals, bool hasExs,
1034                                     bool hasAnyExs, const QualType *ExArray,
1035                                     unsigned numExs, QualType Canonical,
1036                                     const ExtInfo &Info)
1037  : FunctionType(FunctionProto, Result, isVariadic, typeQuals, Canonical,
1038                 Result->isDependentType(),
1039                 Result->isVariablyModifiedType(),
1040                 Info),
1041    NumArgs(numArgs), NumExceptions(numExs), HasExceptionSpec(hasExs),
1042    AnyExceptionSpec(hasAnyExs)
1043{
1044  // Fill in the trailing argument array.
1045  QualType *ArgInfo = reinterpret_cast<QualType*>(this+1);
1046  for (unsigned i = 0; i != numArgs; ++i) {
1047    if (ArgArray[i]->isDependentType())
1048      setDependent();
1049
1050    ArgInfo[i] = ArgArray[i];
1051  }
1052
1053  // Fill in the exception array.
1054  QualType *Ex = ArgInfo + numArgs;
1055  for (unsigned i = 0; i != numExs; ++i)
1056    Ex[i] = ExArray[i];
1057}
1058
1059
1060void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1061                                arg_type_iterator ArgTys,
1062                                unsigned NumArgs, bool isVariadic,
1063                                unsigned TypeQuals, bool hasExceptionSpec,
1064                                bool anyExceptionSpec, unsigned NumExceptions,
1065                                exception_iterator Exs,
1066                                FunctionType::ExtInfo Info) {
1067  ID.AddPointer(Result.getAsOpaquePtr());
1068  for (unsigned i = 0; i != NumArgs; ++i)
1069    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1070  ID.AddInteger(isVariadic);
1071  ID.AddInteger(TypeQuals);
1072  ID.AddInteger(hasExceptionSpec);
1073  if (hasExceptionSpec) {
1074    ID.AddInteger(anyExceptionSpec);
1075    for (unsigned i = 0; i != NumExceptions; ++i)
1076      ID.AddPointer(Exs[i].getAsOpaquePtr());
1077  }
1078  Info.Profile(ID);
1079}
1080
1081void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
1082  Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(),
1083          getTypeQuals(), hasExceptionSpec(), hasAnyExceptionSpec(),
1084          getNumExceptions(), exception_begin(),
1085          getExtInfo());
1086}
1087
1088/// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1089/// potentially looking through *all* consequtive typedefs.  This returns the
1090/// sum of the type qualifiers, so if you have:
1091///   typedef const int A;
1092///   typedef volatile A B;
1093/// looking through the typedefs for B will give you "const volatile A".
1094///
1095QualType TypedefType::LookThroughTypedefs() const {
1096  // Usually, there is only a single level of typedefs, be fast in that case.
1097  QualType FirstType = getDecl()->getUnderlyingType();
1098  if (!isa<TypedefType>(FirstType))
1099    return FirstType;
1100
1101  // Otherwise, do the fully general loop.
1102  QualifierCollector Qs;
1103
1104  QualType CurType;
1105  const TypedefType *TDT = this;
1106  do {
1107    CurType = TDT->getDecl()->getUnderlyingType();
1108    TDT = dyn_cast<TypedefType>(Qs.strip(CurType));
1109  } while (TDT);
1110
1111  return Qs.apply(CurType);
1112}
1113
1114QualType TypedefType::desugar() const {
1115  return getDecl()->getUnderlyingType();
1116}
1117
1118TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1119  : Type(TypeOfExpr, can, E->isTypeDependent(),
1120         E->getType()->isVariablyModifiedType()), TOExpr(E) {
1121}
1122
1123QualType TypeOfExprType::desugar() const {
1124  return getUnderlyingExpr()->getType();
1125}
1126
1127void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1128                                      ASTContext &Context, Expr *E) {
1129  E->Profile(ID, Context, true);
1130}
1131
1132DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1133  : Type(Decltype, can, E->isTypeDependent(),
1134         E->getType()->isVariablyModifiedType()), E(E),
1135  UnderlyingType(underlyingType) {
1136}
1137
1138DependentDecltypeType::DependentDecltypeType(ASTContext &Context, Expr *E)
1139  : DecltypeType(E, Context.DependentTy), Context(Context) { }
1140
1141void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1142                                    ASTContext &Context, Expr *E) {
1143  E->Profile(ID, Context, true);
1144}
1145
1146TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1147  : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false),
1148    decl(const_cast<TagDecl*>(D)) {}
1149
1150static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1151  for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1152                                E = decl->redecls_end();
1153       I != E; ++I) {
1154    if (I->isDefinition() || I->isBeingDefined())
1155      return *I;
1156  }
1157  // If there's no definition (not even in progress), return what we have.
1158  return decl;
1159}
1160
1161TagDecl *TagType::getDecl() const {
1162  return getInterestingTagDecl(decl);
1163}
1164
1165bool TagType::isBeingDefined() const {
1166  return getDecl()->isBeingDefined();
1167}
1168
1169CXXRecordDecl *InjectedClassNameType::getDecl() const {
1170  return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1171}
1172
1173bool RecordType::classof(const TagType *TT) {
1174  return isa<RecordDecl>(TT->getDecl());
1175}
1176
1177bool EnumType::classof(const TagType *TT) {
1178  return isa<EnumDecl>(TT->getDecl());
1179}
1180
1181static bool isDependent(const TemplateArgument &Arg) {
1182  switch (Arg.getKind()) {
1183  case TemplateArgument::Null:
1184    assert(false && "Should not have a NULL template argument");
1185    return false;
1186
1187  case TemplateArgument::Type:
1188    return Arg.getAsType()->isDependentType();
1189
1190  case TemplateArgument::Template:
1191    return Arg.getAsTemplate().isDependent();
1192
1193  case TemplateArgument::Declaration:
1194    if (DeclContext *DC = dyn_cast<DeclContext>(Arg.getAsDecl()))
1195      return DC->isDependentContext();
1196    return Arg.getAsDecl()->getDeclContext()->isDependentContext();
1197
1198  case TemplateArgument::Integral:
1199    // Never dependent
1200    return false;
1201
1202  case TemplateArgument::Expression:
1203    return (Arg.getAsExpr()->isTypeDependent() ||
1204            Arg.getAsExpr()->isValueDependent());
1205
1206  case TemplateArgument::Pack:
1207    for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1208                                      PEnd = Arg.pack_end();
1209         P != PEnd; ++P) {
1210      if (isDependent(*P))
1211        return true;
1212    }
1213
1214    return false;
1215  }
1216
1217  return false;
1218}
1219
1220bool TemplateSpecializationType::
1221anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1222  return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1223}
1224
1225bool TemplateSpecializationType::
1226anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1227  for (unsigned i = 0; i != N; ++i)
1228    if (isDependent(Args[i].getArgument()))
1229      return true;
1230  return false;
1231}
1232
1233bool TemplateSpecializationType::
1234anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1235  for (unsigned i = 0; i != N; ++i)
1236    if (isDependent(Args[i]))
1237      return true;
1238  return false;
1239}
1240
1241TemplateSpecializationType::
1242TemplateSpecializationType(TemplateName T,
1243                           const TemplateArgument *Args,
1244                           unsigned NumArgs, QualType Canon)
1245  : Type(TemplateSpecialization,
1246         Canon.isNull()? QualType(this, 0) : Canon,
1247         T.isDependent(), false),
1248    Template(T), NumArgs(NumArgs)
1249{
1250  assert((!Canon.isNull() ||
1251          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1252         "No canonical type for non-dependent class template specialization");
1253
1254  TemplateArgument *TemplateArgs
1255    = reinterpret_cast<TemplateArgument *>(this + 1);
1256  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1257    // Update dependent and variably-modified bits.
1258    if (isDependent(Args[Arg]))
1259      setDependent();
1260    if (Args[Arg].getKind() == TemplateArgument::Type &&
1261        Args[Arg].getAsType()->isVariablyModifiedType())
1262      setVariablyModified();
1263
1264    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1265  }
1266}
1267
1268void
1269TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1270                                    TemplateName T,
1271                                    const TemplateArgument *Args,
1272                                    unsigned NumArgs,
1273                                    ASTContext &Context) {
1274  T.Profile(ID);
1275  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1276    Args[Idx].Profile(ID, Context);
1277}
1278
1279QualType QualifierCollector::apply(QualType QT) const {
1280  if (!hasNonFastQualifiers())
1281    return QT.withFastQualifiers(getFastQualifiers());
1282
1283  assert(Context && "extended qualifiers but no context!");
1284  return Context->getQualifiedType(QT, *this);
1285}
1286
1287QualType QualifierCollector::apply(const Type *T) const {
1288  if (!hasNonFastQualifiers())
1289    return QualType(T, getFastQualifiers());
1290
1291  assert(Context && "extended qualifiers but no context!");
1292  return Context->getQualifiedType(T, *this);
1293}
1294
1295void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1296                                 QualType BaseType,
1297                                 ObjCProtocolDecl * const *Protocols,
1298                                 unsigned NumProtocols) {
1299  ID.AddPointer(BaseType.getAsOpaquePtr());
1300  for (unsigned i = 0; i != NumProtocols; i++)
1301    ID.AddPointer(Protocols[i]);
1302}
1303
1304void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1305  Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1306}
1307
1308void Type::ensureCachedProperties() const {
1309  if (!TypeBits.isCacheValid()) {
1310    CachedProperties Result = getCachedProperties();
1311    TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1312    assert(TypeBits.isCacheValid() &&
1313           TypeBits.getVisibility() == Result.getVisibility());
1314    TypeBits.CachedLinkage = Result.getLinkage();
1315    TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1316  }
1317}
1318
1319/// \brief Determine the linkage of this type.
1320Linkage Type::getLinkage() const {
1321  if (this != CanonicalType.getTypePtr())
1322    return CanonicalType->getLinkage();
1323
1324  ensureCachedProperties();
1325  return TypeBits.getLinkage();
1326}
1327
1328/// \brief Determine the linkage of this type.
1329Visibility Type::getVisibility() const {
1330  if (this != CanonicalType.getTypePtr())
1331    return CanonicalType->getVisibility();
1332
1333  ensureCachedProperties();
1334  return TypeBits.getVisibility();
1335}
1336
1337bool Type::hasUnnamedOrLocalType() const {
1338  if (this != CanonicalType.getTypePtr())
1339    return CanonicalType->hasUnnamedOrLocalType();
1340
1341  ensureCachedProperties();
1342  return TypeBits.hasLocalOrUnnamedType();
1343}
1344
1345std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
1346  if (this != CanonicalType.getTypePtr())
1347    return CanonicalType->getLinkageAndVisibility();
1348
1349  ensureCachedProperties();
1350  return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
1351}
1352
1353
1354Type::CachedProperties Type::getCachedProperties(const Type *T) {
1355  T = T->CanonicalType.getTypePtr();
1356  T->ensureCachedProperties();
1357  return CachedProperties(T->TypeBits.getLinkage(),
1358                          T->TypeBits.getVisibility(),
1359                          T->TypeBits.hasLocalOrUnnamedType());
1360}
1361
1362void Type::ClearLinkageCache() {
1363  if (this != CanonicalType.getTypePtr())
1364    CanonicalType->ClearLinkageCache();
1365  else
1366    TypeBits.CacheValidAndVisibility = 0;
1367}
1368
1369Type::CachedProperties Type::getCachedProperties() const {
1370  // Treat dependent types as external.
1371  if (isDependentType())
1372    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1373
1374  // C++ [basic.link]p8:
1375  //   Names not covered by these rules have no linkage.
1376  return CachedProperties(NoLinkage, DefaultVisibility, false);
1377}
1378
1379Type::CachedProperties BuiltinType::getCachedProperties() const {
1380  // C++ [basic.link]p8:
1381  //   A type is said to have linkage if and only if:
1382  //     - it is a fundamental type (3.9.1); or
1383  return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1384}
1385
1386Type::CachedProperties TagType::getCachedProperties() const {
1387  // C++ [basic.link]p8:
1388  //     - it is a class or enumeration type that is named (or has a name for
1389  //       linkage purposes (7.1.3)) and the name has linkage; or
1390  //     -  it is a specialization of a class template (14); or
1391
1392  NamedDecl::LinkageInfo LV = getDecl()->getLinkageAndVisibility();
1393  bool IsLocalOrUnnamed =
1394    getDecl()->getDeclContext()->isFunctionOrMethod() ||
1395                        (!getDecl()->getIdentifier() &&
1396                         !getDecl()->getTypedefForAnonDecl());
1397  return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
1398}
1399
1400// C++ [basic.link]p8:
1401//   - it is a compound type (3.9.2) other than a class or enumeration,
1402//     compounded exclusively from types that have linkage; or
1403Type::CachedProperties ComplexType::getCachedProperties() const {
1404  return Type::getCachedProperties(ElementType);
1405}
1406
1407Type::CachedProperties PointerType::getCachedProperties() const {
1408  return Type::getCachedProperties(PointeeType);
1409}
1410
1411Type::CachedProperties BlockPointerType::getCachedProperties() const {
1412  return Type::getCachedProperties(PointeeType);
1413}
1414
1415Type::CachedProperties ReferenceType::getCachedProperties() const {
1416  return Type::getCachedProperties(PointeeType);
1417}
1418
1419Type::CachedProperties MemberPointerType::getCachedProperties() const {
1420  return merge(Type::getCachedProperties(Class),
1421               Type::getCachedProperties(PointeeType));
1422}
1423
1424Type::CachedProperties ArrayType::getCachedProperties() const {
1425  return Type::getCachedProperties(ElementType);
1426}
1427
1428Type::CachedProperties VectorType::getCachedProperties() const {
1429  return Type::getCachedProperties(ElementType);
1430}
1431
1432Type::CachedProperties FunctionNoProtoType::getCachedProperties() const {
1433  return Type::getCachedProperties(getResultType());
1434}
1435
1436Type::CachedProperties FunctionProtoType::getCachedProperties() const {
1437  CachedProperties Cached = Type::getCachedProperties(getResultType());
1438  for (arg_type_iterator A = arg_type_begin(), AEnd = arg_type_end();
1439       A != AEnd; ++A) {
1440    Cached = merge(Cached, Type::getCachedProperties(*A));
1441  }
1442  return Cached;
1443}
1444
1445Type::CachedProperties ObjCInterfaceType::getCachedProperties() const {
1446  NamedDecl::LinkageInfo LV = getDecl()->getLinkageAndVisibility();
1447  return CachedProperties(LV.linkage(), LV.visibility(), false);
1448}
1449
1450Type::CachedProperties ObjCObjectType::getCachedProperties() const {
1451  if (const ObjCInterfaceType *T = getBaseType()->getAs<ObjCInterfaceType>())
1452    return Type::getCachedProperties(T);
1453  return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1454}
1455
1456Type::CachedProperties ObjCObjectPointerType::getCachedProperties() const {
1457  return Type::getCachedProperties(PointeeType);
1458}
1459