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