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