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