Type.cpp revision 207619
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/Type.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/raw_ostream.h"
23using namespace clang;
24
25bool QualType::isConstant(QualType T, ASTContext &Ctx) {
26  if (T.isConstQualified())
27    return true;
28
29  if (const ArrayType *AT = Ctx.getAsArrayType(T))
30    return AT->getElementType().isConstant(Ctx);
31
32  return false;
33}
34
35void Type::Destroy(ASTContext& C) {
36  this->~Type();
37  C.Deallocate(this);
38}
39
40void VariableArrayType::Destroy(ASTContext& C) {
41  if (SizeExpr)
42    SizeExpr->Destroy(C);
43  this->~VariableArrayType();
44  C.Deallocate(this);
45}
46
47void DependentSizedArrayType::Destroy(ASTContext& C) {
48  // FIXME: Resource contention like in ConstantArrayWithExprType ?
49  // May crash, depending on platform or a particular build.
50  // SizeExpr->Destroy(C);
51  this->~DependentSizedArrayType();
52  C.Deallocate(this);
53}
54
55void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
56                                      ASTContext &Context,
57                                      QualType ET,
58                                      ArraySizeModifier SizeMod,
59                                      unsigned TypeQuals,
60                                      Expr *E) {
61  ID.AddPointer(ET.getAsOpaquePtr());
62  ID.AddInteger(SizeMod);
63  ID.AddInteger(TypeQuals);
64  E->Profile(ID, Context, true);
65}
66
67void
68DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
69                                     ASTContext &Context,
70                                     QualType ElementType, Expr *SizeExpr) {
71  ID.AddPointer(ElementType.getAsOpaquePtr());
72  SizeExpr->Profile(ID, Context, true);
73}
74
75void DependentSizedExtVectorType::Destroy(ASTContext& C) {
76  // FIXME: Deallocate size expression, once we're cloning properly.
77//  if (SizeExpr)
78//    SizeExpr->Destroy(C);
79  this->~DependentSizedExtVectorType();
80  C.Deallocate(this);
81}
82
83/// getArrayElementTypeNoTypeQual - If this is an array type, return the
84/// element type of the array, potentially with type qualifiers missing.
85/// This method should never be used when type qualifiers are meaningful.
86const Type *Type::getArrayElementTypeNoTypeQual() const {
87  // If this is directly an array type, return it.
88  if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
89    return ATy->getElementType().getTypePtr();
90
91  // If the canonical form of this type isn't the right kind, reject it.
92  if (!isa<ArrayType>(CanonicalType))
93    return 0;
94
95  // If this is a typedef for an array type, strip the typedef off without
96  // losing all typedef information.
97  return cast<ArrayType>(getUnqualifiedDesugaredType())
98    ->getElementType().getTypePtr();
99}
100
101/// \brief Retrieve the unqualified variant of the given type, removing as
102/// little sugar as possible.
103///
104/// This routine looks through various kinds of sugar to find the
105/// least-desuraged type that is unqualified. For example, given:
106///
107/// \code
108/// typedef int Integer;
109/// typedef const Integer CInteger;
110/// typedef CInteger DifferenceType;
111/// \endcode
112///
113/// Executing \c getUnqualifiedTypeSlow() on the type \c DifferenceType will
114/// desugar until we hit the type \c Integer, which has no qualifiers on it.
115QualType QualType::getUnqualifiedTypeSlow() const {
116  QualType Cur = *this;
117  while (true) {
118    if (!Cur.hasQualifiers())
119      return Cur;
120
121    const Type *CurTy = Cur.getTypePtr();
122    switch (CurTy->getTypeClass()) {
123#define ABSTRACT_TYPE(Class, Parent)
124#define TYPE(Class, Parent)                                  \
125    case Type::Class: {                                      \
126      const Class##Type *Ty = cast<Class##Type>(CurTy);      \
127      if (!Ty->isSugared())                                  \
128        return Cur.getLocalUnqualifiedType();                \
129      Cur = Ty->desugar();                                   \
130      break;                                                 \
131    }
132#include "clang/AST/TypeNodes.def"
133    }
134  }
135
136  return Cur.getUnqualifiedType();
137}
138
139/// getDesugaredType - Return the specified type with any "sugar" removed from
140/// the type.  This takes off typedefs, typeof's etc.  If the outer level of
141/// the type is already concrete, it returns it unmodified.  This is similar
142/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
143/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
144/// concrete.
145QualType QualType::getDesugaredType(QualType T) {
146  QualifierCollector Qs;
147
148  QualType Cur = T;
149  while (true) {
150    const Type *CurTy = Qs.strip(Cur);
151    switch (CurTy->getTypeClass()) {
152#define ABSTRACT_TYPE(Class, Parent)
153#define TYPE(Class, Parent) \
154    case Type::Class: { \
155      const Class##Type *Ty = cast<Class##Type>(CurTy); \
156      if (!Ty->isSugared()) \
157        return Qs.apply(Cur); \
158      Cur = Ty->desugar(); \
159      break; \
160    }
161#include "clang/AST/TypeNodes.def"
162    }
163  }
164}
165
166/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
167/// sugar off the given type.  This should produce an object of the
168/// same dynamic type as the canonical type.
169const Type *Type::getUnqualifiedDesugaredType() const {
170  const Type *Cur = this;
171
172  while (true) {
173    switch (Cur->getTypeClass()) {
174#define ABSTRACT_TYPE(Class, Parent)
175#define TYPE(Class, Parent) \
176    case Class: { \
177      const Class##Type *Ty = cast<Class##Type>(Cur); \
178      if (!Ty->isSugared()) return Cur; \
179      Cur = Ty->desugar().getTypePtr(); \
180      break; \
181    }
182#include "clang/AST/TypeNodes.def"
183    }
184  }
185}
186
187/// isVoidType - Helper method to determine if this is the 'void' type.
188bool Type::isVoidType() const {
189  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
190    return BT->getKind() == BuiltinType::Void;
191  return false;
192}
193
194bool Type::isObjectType() const {
195  if (isa<FunctionType>(CanonicalType) || isa<ReferenceType>(CanonicalType) ||
196      isa<IncompleteArrayType>(CanonicalType) || isVoidType())
197    return false;
198  return true;
199}
200
201bool Type::isDerivedType() const {
202  switch (CanonicalType->getTypeClass()) {
203  case Pointer:
204  case VariableArray:
205  case ConstantArray:
206  case IncompleteArray:
207  case FunctionProto:
208  case FunctionNoProto:
209  case LValueReference:
210  case RValueReference:
211  case Record:
212    return true;
213  default:
214    return false;
215  }
216}
217
218bool Type::isClassType() const {
219  if (const RecordType *RT = getAs<RecordType>())
220    return RT->getDecl()->isClass();
221  return false;
222}
223bool Type::isStructureType() const {
224  if (const RecordType *RT = getAs<RecordType>())
225    return RT->getDecl()->isStruct();
226  return false;
227}
228bool Type::isStructureOrClassType() const {
229  if (const RecordType *RT = getAs<RecordType>())
230    return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
231  return false;
232}
233bool Type::isVoidPointerType() const {
234  if (const PointerType *PT = getAs<PointerType>())
235    return PT->getPointeeType()->isVoidType();
236  return false;
237}
238
239bool Type::isUnionType() const {
240  if (const RecordType *RT = getAs<RecordType>())
241    return RT->getDecl()->isUnion();
242  return false;
243}
244
245bool Type::isComplexType() const {
246  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
247    return CT->getElementType()->isFloatingType();
248  return false;
249}
250
251bool Type::isComplexIntegerType() const {
252  // Check for GCC complex integer extension.
253  return getAsComplexIntegerType();
254}
255
256const ComplexType *Type::getAsComplexIntegerType() const {
257  if (const ComplexType *Complex = getAs<ComplexType>())
258    if (Complex->getElementType()->isIntegerType())
259      return Complex;
260  return 0;
261}
262
263QualType Type::getPointeeType() const {
264  if (const PointerType *PT = getAs<PointerType>())
265    return PT->getPointeeType();
266  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
267    return OPT->getPointeeType();
268  if (const BlockPointerType *BPT = getAs<BlockPointerType>())
269    return BPT->getPointeeType();
270  if (const ReferenceType *RT = getAs<ReferenceType>())
271    return RT->getPointeeType();
272  return QualType();
273}
274
275/// isVariablyModifiedType (C99 6.7.5p3) - Return true for variable length
276/// array types and types that contain variable array types in their
277/// declarator
278bool Type::isVariablyModifiedType() const {
279  // A VLA is a variably modified type.
280  if (isVariableArrayType())
281    return true;
282
283  // An array can contain a variably modified type
284  if (const Type *T = getArrayElementTypeNoTypeQual())
285    return T->isVariablyModifiedType();
286
287  // A pointer can point to a variably modified type.
288  // Also, C++ references and member pointers can point to a variably modified
289  // type, where VLAs appear as an extension to C++, and should be treated
290  // correctly.
291  if (const PointerType *PT = getAs<PointerType>())
292    return PT->getPointeeType()->isVariablyModifiedType();
293  if (const ReferenceType *RT = getAs<ReferenceType>())
294    return RT->getPointeeType()->isVariablyModifiedType();
295  if (const MemberPointerType *PT = getAs<MemberPointerType>())
296    return PT->getPointeeType()->isVariablyModifiedType();
297
298  // A function can return a variably modified type
299  // This one isn't completely obvious, but it follows from the
300  // definition in C99 6.7.5p3. Because of this rule, it's
301  // illegal to declare a function returning a variably modified type.
302  if (const FunctionType *FT = getAs<FunctionType>())
303    return FT->getResultType()->isVariablyModifiedType();
304
305  return false;
306}
307
308const RecordType *Type::getAsStructureType() const {
309  // If this is directly a structure type, return it.
310  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
311    if (RT->getDecl()->isStruct())
312      return RT;
313  }
314
315  // If the canonical form of this type isn't the right kind, reject it.
316  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
317    if (!RT->getDecl()->isStruct())
318      return 0;
319
320    // If this is a typedef for a structure type, strip the typedef off without
321    // losing all typedef information.
322    return cast<RecordType>(getUnqualifiedDesugaredType());
323  }
324  return 0;
325}
326
327const RecordType *Type::getAsUnionType() const {
328  // If this is directly a union type, return it.
329  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
330    if (RT->getDecl()->isUnion())
331      return RT;
332  }
333
334  // If the canonical form of this type isn't the right kind, reject it.
335  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
336    if (!RT->getDecl()->isUnion())
337      return 0;
338
339    // If this is a typedef for a union type, strip the typedef off without
340    // losing all typedef information.
341    return cast<RecordType>(getUnqualifiedDesugaredType());
342  }
343
344  return 0;
345}
346
347ObjCInterfaceType::ObjCInterfaceType(QualType Canonical,
348                                     ObjCInterfaceDecl *D,
349                                     ObjCProtocolDecl **Protos, unsigned NumP) :
350  Type(ObjCInterface, Canonical, /*Dependent=*/false),
351  Decl(D), NumProtocols(NumP)
352{
353  if (NumProtocols)
354    memcpy(reinterpret_cast<ObjCProtocolDecl**>(this + 1), Protos,
355           NumProtocols * sizeof(*Protos));
356}
357
358void ObjCInterfaceType::Destroy(ASTContext& C) {
359  this->~ObjCInterfaceType();
360  C.Deallocate(this);
361}
362
363const ObjCInterfaceType *Type::getAsObjCQualifiedInterfaceType() const {
364  // There is no sugar for ObjCInterfaceType's, just return the canonical
365  // type pointer if it is the right class.  There is no typedef information to
366  // return and these cannot be Address-space qualified.
367  if (const ObjCInterfaceType *OIT = getAs<ObjCInterfaceType>())
368    if (OIT->getNumProtocols())
369      return OIT;
370  return 0;
371}
372
373bool Type::isObjCQualifiedInterfaceType() const {
374  return getAsObjCQualifiedInterfaceType() != 0;
375}
376
377ObjCObjectPointerType::ObjCObjectPointerType(QualType Canonical, QualType T,
378                                             ObjCProtocolDecl **Protos,
379                                             unsigned NumP) :
380  Type(ObjCObjectPointer, Canonical, /*Dependent=*/false),
381  PointeeType(T), NumProtocols(NumP)
382{
383  if (NumProtocols)
384    memcpy(reinterpret_cast<ObjCProtocolDecl **>(this + 1), Protos,
385           NumProtocols * sizeof(*Protos));
386}
387
388void ObjCObjectPointerType::Destroy(ASTContext& C) {
389  this->~ObjCObjectPointerType();
390  C.Deallocate(this);
391}
392
393const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
394  // There is no sugar for ObjCQualifiedIdType's, just return the canonical
395  // type pointer if it is the right class.
396  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
397    if (OPT->isObjCQualifiedIdType())
398      return OPT;
399  }
400  return 0;
401}
402
403const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
404  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
405    if (OPT->getInterfaceType())
406      return OPT;
407  }
408  return 0;
409}
410
411const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
412  if (const PointerType *PT = getAs<PointerType>())
413    if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
414      return dyn_cast<CXXRecordDecl>(RT->getDecl());
415  return 0;
416}
417
418CXXRecordDecl *Type::getAsCXXRecordDecl() const {
419  if (const RecordType *RT = getAs<RecordType>())
420    return dyn_cast<CXXRecordDecl>(RT->getDecl());
421  else if (const InjectedClassNameType *Injected
422                                  = getAs<InjectedClassNameType>())
423    return Injected->getDecl();
424
425  return 0;
426}
427
428bool Type::isIntegerType() const {
429  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
430    return BT->getKind() >= BuiltinType::Bool &&
431           BT->getKind() <= BuiltinType::Int128;
432  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
433    // Incomplete enum types are not treated as integer types.
434    // FIXME: In C++, enum types are never integer types.
435    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
436      return true;
437  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
438    return VT->getElementType()->isIntegerType();
439  return false;
440}
441
442bool Type::isIntegralType() const {
443  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
444    return BT->getKind() >= BuiltinType::Bool &&
445    BT->getKind() <= BuiltinType::Int128;
446  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
447    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
448      return true;  // Complete enum types are integral.
449                    // FIXME: In C++, enum types are never integral.
450  return false;
451}
452
453bool Type::isEnumeralType() const {
454  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
455    return TT->getDecl()->isEnum();
456  return false;
457}
458
459bool Type::isBooleanType() const {
460  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
461    return BT->getKind() == BuiltinType::Bool;
462  return false;
463}
464
465bool Type::isCharType() const {
466  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
467    return BT->getKind() == BuiltinType::Char_U ||
468           BT->getKind() == BuiltinType::UChar ||
469           BT->getKind() == BuiltinType::Char_S ||
470           BT->getKind() == BuiltinType::SChar;
471  return false;
472}
473
474bool Type::isWideCharType() const {
475  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
476    return BT->getKind() == BuiltinType::WChar;
477  return false;
478}
479
480/// \brief Determine whether this type is any of the built-in character
481/// types.
482bool Type::isAnyCharacterType() const {
483  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
484    return (BT->getKind() >= BuiltinType::Char_U &&
485            BT->getKind() <= BuiltinType::Char32) ||
486           (BT->getKind() >= BuiltinType::Char_S &&
487            BT->getKind() <= BuiltinType::WChar);
488
489  return false;
490}
491
492/// isSignedIntegerType - Return true if this is an integer type that is
493/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
494/// an enum decl which has a signed representation, or a vector of signed
495/// integer element type.
496bool Type::isSignedIntegerType() const {
497  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
498    return BT->getKind() >= BuiltinType::Char_S &&
499           BT->getKind() <= BuiltinType::Int128;
500  }
501
502  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
503    return ET->getDecl()->getIntegerType()->isSignedIntegerType();
504
505  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
506    return VT->getElementType()->isSignedIntegerType();
507  return false;
508}
509
510/// isUnsignedIntegerType - Return true if this is an integer type that is
511/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
512/// decl which has an unsigned representation, or a vector of unsigned integer
513/// element type.
514bool Type::isUnsignedIntegerType() const {
515  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
516    return BT->getKind() >= BuiltinType::Bool &&
517           BT->getKind() <= BuiltinType::UInt128;
518  }
519
520  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
521    return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
522
523  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
524    return VT->getElementType()->isUnsignedIntegerType();
525  return false;
526}
527
528bool Type::isFloatingType() const {
529  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
530    return BT->getKind() >= BuiltinType::Float &&
531           BT->getKind() <= BuiltinType::LongDouble;
532  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
533    return CT->getElementType()->isFloatingType();
534  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
535    return VT->getElementType()->isFloatingType();
536  return false;
537}
538
539bool Type::isRealFloatingType() const {
540  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
541    return BT->isFloatingPoint();
542  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
543    return VT->getElementType()->isRealFloatingType();
544  return false;
545}
546
547bool Type::isRealType() const {
548  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
549    return BT->getKind() >= BuiltinType::Bool &&
550           BT->getKind() <= BuiltinType::LongDouble;
551  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
552    return TT->getDecl()->isEnum() && TT->getDecl()->isDefinition();
553  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
554    return VT->getElementType()->isRealType();
555  return false;
556}
557
558bool Type::isArithmeticType() const {
559  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
560    return BT->getKind() >= BuiltinType::Bool &&
561           BT->getKind() <= BuiltinType::LongDouble;
562  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
563    // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
564    // If a body isn't seen by the time we get here, return false.
565    return ET->getDecl()->isDefinition();
566  return isa<ComplexType>(CanonicalType) || isa<VectorType>(CanonicalType);
567}
568
569bool Type::isScalarType() const {
570  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
571    return BT->getKind() != BuiltinType::Void;
572  if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) {
573    // Enums are scalar types, but only if they are defined.  Incomplete enums
574    // are not treated as scalar types.
575    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
576      return true;
577    return false;
578  }
579  return isa<PointerType>(CanonicalType) ||
580         isa<BlockPointerType>(CanonicalType) ||
581         isa<MemberPointerType>(CanonicalType) ||
582         isa<ComplexType>(CanonicalType) ||
583         isa<ObjCObjectPointerType>(CanonicalType);
584}
585
586/// \brief Determines whether the type is a C++ aggregate type or C
587/// aggregate or union type.
588///
589/// An aggregate type is an array or a class type (struct, union, or
590/// class) that has no user-declared constructors, no private or
591/// protected non-static data members, no base classes, and no virtual
592/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
593/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
594/// includes union types.
595bool Type::isAggregateType() const {
596  if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
597    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
598      return ClassDecl->isAggregate();
599
600    return true;
601  }
602
603  return isa<ArrayType>(CanonicalType);
604}
605
606/// isConstantSizeType - Return true if this is not a variable sized type,
607/// according to the rules of C99 6.7.5p3.  It is not legal to call this on
608/// incomplete types or dependent types.
609bool Type::isConstantSizeType() const {
610  assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
611  assert(!isDependentType() && "This doesn't make sense for dependent types");
612  // The VAT must have a size, as it is known to be complete.
613  return !isa<VariableArrayType>(CanonicalType);
614}
615
616/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
617/// - a type that can describe objects, but which lacks information needed to
618/// determine its size.
619bool Type::isIncompleteType() const {
620  switch (CanonicalType->getTypeClass()) {
621  default: return false;
622  case Builtin:
623    // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
624    // be completed.
625    return isVoidType();
626  case Record:
627  case Enum:
628    // A tagged type (struct/union/enum/class) is incomplete if the decl is a
629    // forward declaration, but not a full definition (C99 6.2.5p22).
630    return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
631  case ConstantArray:
632    // An array is incomplete if its element type is incomplete
633    // (C++ [dcl.array]p1).
634    // We don't handle variable arrays (they're not allowed in C++) or
635    // dependent-sized arrays (dependent types are never treated as incomplete).
636    return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
637  case IncompleteArray:
638    // An array of unknown size is an incomplete type (C99 6.2.5p22).
639    return true;
640  case ObjCInterface:
641    // ObjC interfaces are incomplete if they are @class, not @interface.
642    return cast<ObjCInterfaceType>(this)->getDecl()->isForwardDecl();
643  }
644}
645
646/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
647bool Type::isPODType() const {
648  // The compiler shouldn't query this for incomplete types, but the user might.
649  // We return false for that case.
650  if (isIncompleteType())
651    return false;
652
653  switch (CanonicalType->getTypeClass()) {
654    // Everything not explicitly mentioned is not POD.
655  default: return false;
656  case VariableArray:
657  case ConstantArray:
658    // IncompleteArray is caught by isIncompleteType() above.
659    return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
660
661  case Builtin:
662  case Complex:
663  case Pointer:
664  case MemberPointer:
665  case Vector:
666  case ExtVector:
667  case ObjCObjectPointer:
668  case BlockPointer:
669    return true;
670
671  case Enum:
672    return true;
673
674  case Record:
675    if (CXXRecordDecl *ClassDecl
676          = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
677      return ClassDecl->isPOD();
678
679    // C struct/union is POD.
680    return true;
681  }
682}
683
684bool Type::isLiteralType() const {
685  if (isIncompleteType())
686    return false;
687
688  // C++0x [basic.types]p10:
689  //   A type is a literal type if it is:
690  switch (CanonicalType->getTypeClass()) {
691    // We're whitelisting
692  default: return false;
693
694    //   -- a scalar type
695  case Builtin:
696  case Complex:
697  case Pointer:
698  case MemberPointer:
699  case Vector:
700  case ExtVector:
701  case ObjCObjectPointer:
702  case Enum:
703    return true;
704
705    //   -- a class type with ...
706  case Record:
707    // FIXME: Do the tests
708    return false;
709
710    //   -- an array of literal type
711    // Extension: variable arrays cannot be literal types, since they're
712    // runtime-sized.
713  case ConstantArray:
714    return cast<ArrayType>(CanonicalType)->getElementType()->isLiteralType();
715  }
716}
717
718bool Type::isPromotableIntegerType() const {
719  if (const BuiltinType *BT = getAs<BuiltinType>())
720    switch (BT->getKind()) {
721    case BuiltinType::Bool:
722    case BuiltinType::Char_S:
723    case BuiltinType::Char_U:
724    case BuiltinType::SChar:
725    case BuiltinType::UChar:
726    case BuiltinType::Short:
727    case BuiltinType::UShort:
728      return true;
729    default:
730      return false;
731    }
732
733  // Enumerated types are promotable to their compatible integer types
734  // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
735  if (const EnumType *ET = getAs<EnumType>()){
736    if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull())
737      return false;
738
739    const BuiltinType *BT
740      = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
741    return BT->getKind() == BuiltinType::Int
742           || BT->getKind() == BuiltinType::UInt;
743  }
744
745  return false;
746}
747
748bool Type::isNullPtrType() const {
749  if (const BuiltinType *BT = getAs<BuiltinType>())
750    return BT->getKind() == BuiltinType::NullPtr;
751  return false;
752}
753
754bool Type::isSpecifierType() const {
755  // Note that this intentionally does not use the canonical type.
756  switch (getTypeClass()) {
757  case Builtin:
758  case Record:
759  case Enum:
760  case Typedef:
761  case Complex:
762  case TypeOfExpr:
763  case TypeOf:
764  case TemplateTypeParm:
765  case SubstTemplateTypeParm:
766  case TemplateSpecialization:
767  case QualifiedName:
768  case DependentName:
769  case ObjCInterface:
770  case ObjCObjectPointer:
771  case Elaborated:
772    return true;
773  default:
774    return false;
775  }
776}
777
778bool Type::isElaboratedTypeSpecifier() const {
779  if (getTypeClass() == Elaborated)
780    return true;
781
782  if (const DependentNameType *Dependent = dyn_cast<DependentNameType>(this)) {
783    switch (Dependent->getKeyword()) {
784    case ETK_None:
785    case ETK_Typename:
786      return false;
787
788    case ETK_Class:
789    case ETK_Struct:
790    case ETK_Union:
791    case ETK_Enum:
792      return true;
793    }
794  }
795
796  return false;
797}
798
799const char *Type::getTypeClassName() const {
800  switch (TC) {
801  default: assert(0 && "Type class not in TypeNodes.def!");
802#define ABSTRACT_TYPE(Derived, Base)
803#define TYPE(Derived, Base) case Derived: return #Derived;
804#include "clang/AST/TypeNodes.def"
805  }
806}
807
808const char *BuiltinType::getName(const LangOptions &LO) const {
809  switch (getKind()) {
810  default: assert(0 && "Unknown builtin type!");
811  case Void:              return "void";
812  case Bool:              return LO.Bool ? "bool" : "_Bool";
813  case Char_S:            return "char";
814  case Char_U:            return "char";
815  case SChar:             return "signed char";
816  case Short:             return "short";
817  case Int:               return "int";
818  case Long:              return "long";
819  case LongLong:          return "long long";
820  case Int128:            return "__int128_t";
821  case UChar:             return "unsigned char";
822  case UShort:            return "unsigned short";
823  case UInt:              return "unsigned int";
824  case ULong:             return "unsigned long";
825  case ULongLong:         return "unsigned long long";
826  case UInt128:           return "__uint128_t";
827  case Float:             return "float";
828  case Double:            return "double";
829  case LongDouble:        return "long double";
830  case WChar:             return "wchar_t";
831  case Char16:            return "char16_t";
832  case Char32:            return "char32_t";
833  case NullPtr:           return "nullptr_t";
834  case Overload:          return "<overloaded function type>";
835  case Dependent:         return "<dependent type>";
836  case UndeducedAuto:     return "auto";
837  case ObjCId:            return "id";
838  case ObjCClass:         return "Class";
839  case ObjCSel:         return "SEL";
840  }
841}
842
843llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
844  switch (CC) {
845  case CC_Default: llvm_unreachable("no name for default cc");
846  default: return "";
847
848  case CC_C: return "cdecl";
849  case CC_X86StdCall: return "stdcall";
850  case CC_X86FastCall: return "fastcall";
851  }
852}
853
854void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
855                                arg_type_iterator ArgTys,
856                                unsigned NumArgs, bool isVariadic,
857                                unsigned TypeQuals, bool hasExceptionSpec,
858                                bool anyExceptionSpec, unsigned NumExceptions,
859                                exception_iterator Exs,
860                                const FunctionType::ExtInfo &Info) {
861  ID.AddPointer(Result.getAsOpaquePtr());
862  for (unsigned i = 0; i != NumArgs; ++i)
863    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
864  ID.AddInteger(isVariadic);
865  ID.AddInteger(TypeQuals);
866  ID.AddInteger(hasExceptionSpec);
867  if (hasExceptionSpec) {
868    ID.AddInteger(anyExceptionSpec);
869    for (unsigned i = 0; i != NumExceptions; ++i)
870      ID.AddPointer(Exs[i].getAsOpaquePtr());
871  }
872  ID.AddInteger(Info.getNoReturn());
873  ID.AddInteger(Info.getRegParm());
874  ID.AddInteger(Info.getCC());
875}
876
877void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
878  Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(),
879          getTypeQuals(), hasExceptionSpec(), hasAnyExceptionSpec(),
880          getNumExceptions(), exception_begin(),
881          getExtInfo());
882}
883
884void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID,
885                                    QualType OIT,
886                                    ObjCProtocolDecl * const *protocols,
887                                    unsigned NumProtocols) {
888  ID.AddPointer(OIT.getAsOpaquePtr());
889  for (unsigned i = 0; i != NumProtocols; i++)
890    ID.AddPointer(protocols[i]);
891}
892
893void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID) {
894  Profile(ID, getPointeeType(), qual_begin(), getNumProtocols());
895}
896
897/// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
898/// potentially looking through *all* consequtive typedefs.  This returns the
899/// sum of the type qualifiers, so if you have:
900///   typedef const int A;
901///   typedef volatile A B;
902/// looking through the typedefs for B will give you "const volatile A".
903///
904QualType TypedefType::LookThroughTypedefs() const {
905  // Usually, there is only a single level of typedefs, be fast in that case.
906  QualType FirstType = getDecl()->getUnderlyingType();
907  if (!isa<TypedefType>(FirstType))
908    return FirstType;
909
910  // Otherwise, do the fully general loop.
911  QualifierCollector Qs;
912
913  QualType CurType;
914  const TypedefType *TDT = this;
915  do {
916    CurType = TDT->getDecl()->getUnderlyingType();
917    TDT = dyn_cast<TypedefType>(Qs.strip(CurType));
918  } while (TDT);
919
920  return Qs.apply(CurType);
921}
922
923QualType TypedefType::desugar() const {
924  return getDecl()->getUnderlyingType();
925}
926
927TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
928  : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) {
929}
930
931QualType TypeOfExprType::desugar() const {
932  return getUnderlyingExpr()->getType();
933}
934
935void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
936                                      ASTContext &Context, Expr *E) {
937  E->Profile(ID, Context, true);
938}
939
940DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
941  : Type(Decltype, can, E->isTypeDependent()), E(E),
942  UnderlyingType(underlyingType) {
943}
944
945DependentDecltypeType::DependentDecltypeType(ASTContext &Context, Expr *E)
946  : DecltypeType(E, Context.DependentTy), Context(Context) { }
947
948void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
949                                    ASTContext &Context, Expr *E) {
950  E->Profile(ID, Context, true);
951}
952
953TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
954  : Type(TC, can, D->isDependentType()),
955    decl(const_cast<TagDecl*>(D), 0) {}
956
957bool RecordType::classof(const TagType *TT) {
958  return isa<RecordDecl>(TT->getDecl());
959}
960
961bool EnumType::classof(const TagType *TT) {
962  return isa<EnumDecl>(TT->getDecl());
963}
964
965static bool isDependent(const TemplateArgument &Arg) {
966  switch (Arg.getKind()) {
967  case TemplateArgument::Null:
968    assert(false && "Should not have a NULL template argument");
969    return false;
970
971  case TemplateArgument::Type:
972    return Arg.getAsType()->isDependentType();
973
974  case TemplateArgument::Template:
975    return Arg.getAsTemplate().isDependent();
976
977  case TemplateArgument::Declaration:
978  case TemplateArgument::Integral:
979    // Never dependent
980    return false;
981
982  case TemplateArgument::Expression:
983    return (Arg.getAsExpr()->isTypeDependent() ||
984            Arg.getAsExpr()->isValueDependent());
985
986  case TemplateArgument::Pack:
987    assert(0 && "FIXME: Implement!");
988    return false;
989  }
990
991  return false;
992}
993
994bool TemplateSpecializationType::
995anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
996  return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
997}
998
999bool TemplateSpecializationType::
1000anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1001  for (unsigned i = 0; i != N; ++i)
1002    if (isDependent(Args[i].getArgument()))
1003      return true;
1004  return false;
1005}
1006
1007bool TemplateSpecializationType::
1008anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1009  for (unsigned i = 0; i != N; ++i)
1010    if (isDependent(Args[i]))
1011      return true;
1012  return false;
1013}
1014
1015TemplateSpecializationType::
1016TemplateSpecializationType(ASTContext &Context, TemplateName T,
1017                           bool IsCurrentInstantiation,
1018                           const TemplateArgument *Args,
1019                           unsigned NumArgs, QualType Canon)
1020  : Type(TemplateSpecialization,
1021         Canon.isNull()? QualType(this, 0) : Canon,
1022         T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)),
1023    ContextAndCurrentInstantiation(&Context, IsCurrentInstantiation),
1024    Template(T), NumArgs(NumArgs) {
1025  assert((!Canon.isNull() ||
1026          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1027         "No canonical type for non-dependent class template specialization");
1028
1029  TemplateArgument *TemplateArgs
1030    = reinterpret_cast<TemplateArgument *>(this + 1);
1031  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
1032    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1033}
1034
1035void TemplateSpecializationType::Destroy(ASTContext& C) {
1036  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1037    // FIXME: Not all expressions get cloned, so we can't yet perform
1038    // this destruction.
1039    //    if (Expr *E = getArg(Arg).getAsExpr())
1040    //      E->Destroy(C);
1041  }
1042}
1043
1044TemplateSpecializationType::iterator
1045TemplateSpecializationType::end() const {
1046  return begin() + getNumArgs();
1047}
1048
1049const TemplateArgument &
1050TemplateSpecializationType::getArg(unsigned Idx) const {
1051  assert(Idx < getNumArgs() && "Template argument out of range");
1052  return getArgs()[Idx];
1053}
1054
1055void
1056TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1057                                    TemplateName T,
1058                                    bool IsCurrentInstantiation,
1059                                    const TemplateArgument *Args,
1060                                    unsigned NumArgs,
1061                                    ASTContext &Context) {
1062  ID.AddBoolean(IsCurrentInstantiation);
1063  T.Profile(ID);
1064  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1065    Args[Idx].Profile(ID, Context);
1066}
1067
1068QualType QualifierCollector::apply(QualType QT) const {
1069  if (!hasNonFastQualifiers())
1070    return QT.withFastQualifiers(getFastQualifiers());
1071
1072  assert(Context && "extended qualifiers but no context!");
1073  return Context->getQualifiedType(QT, *this);
1074}
1075
1076QualType QualifierCollector::apply(const Type *T) const {
1077  if (!hasNonFastQualifiers())
1078    return QualType(T, getFastQualifiers());
1079
1080  assert(Context && "extended qualifiers but no context!");
1081  return Context->getQualifiedType(T, *this);
1082}
1083
1084void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID,
1085                                         const ObjCInterfaceDecl *Decl,
1086                                         ObjCProtocolDecl * const *protocols,
1087                                         unsigned NumProtocols) {
1088  ID.AddPointer(Decl);
1089  for (unsigned i = 0; i != NumProtocols; i++)
1090    ID.AddPointer(protocols[i]);
1091}
1092
1093void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID) {
1094  Profile(ID, getDecl(), qual_begin(), getNumProtocols());
1095}
1096
1097Linkage Type::getLinkage() const {
1098  // C++ [basic.link]p8:
1099  //   Names not covered by these rules have no linkage.
1100  if (this != CanonicalType.getTypePtr())
1101    return CanonicalType->getLinkage();
1102
1103  return NoLinkage;
1104}
1105
1106Linkage BuiltinType::getLinkage() const {
1107  // C++ [basic.link]p8:
1108  //   A type is said to have linkage if and only if:
1109  //     - it is a fundamental type (3.9.1); or
1110  return ExternalLinkage;
1111}
1112
1113Linkage TagType::getLinkage() const {
1114  // C++ [basic.link]p8:
1115  //     - it is a class or enumeration type that is named (or has a name for
1116  //       linkage purposes (7.1.3)) and the name has linkage; or
1117  //     -  it is a specialization of a class template (14); or
1118  return getDecl()->getLinkage();
1119}
1120
1121// C++ [basic.link]p8:
1122//   - it is a compound type (3.9.2) other than a class or enumeration,
1123//     compounded exclusively from types that have linkage; or
1124Linkage ComplexType::getLinkage() const {
1125  return ElementType->getLinkage();
1126}
1127
1128Linkage PointerType::getLinkage() const {
1129  return PointeeType->getLinkage();
1130}
1131
1132Linkage BlockPointerType::getLinkage() const {
1133  return PointeeType->getLinkage();
1134}
1135
1136Linkage ReferenceType::getLinkage() const {
1137  return PointeeType->getLinkage();
1138}
1139
1140Linkage MemberPointerType::getLinkage() const {
1141  return minLinkage(Class->getLinkage(), PointeeType->getLinkage());
1142}
1143
1144Linkage ArrayType::getLinkage() const {
1145  return ElementType->getLinkage();
1146}
1147
1148Linkage VectorType::getLinkage() const {
1149  return ElementType->getLinkage();
1150}
1151
1152Linkage FunctionNoProtoType::getLinkage() const {
1153  return getResultType()->getLinkage();
1154}
1155
1156Linkage FunctionProtoType::getLinkage() const {
1157  Linkage L = getResultType()->getLinkage();
1158  for (arg_type_iterator A = arg_type_begin(), AEnd = arg_type_end();
1159       A != AEnd; ++A)
1160    L = minLinkage(L, (*A)->getLinkage());
1161
1162  return L;
1163}
1164
1165Linkage ObjCInterfaceType::getLinkage() const {
1166  return ExternalLinkage;
1167}
1168
1169Linkage ObjCObjectPointerType::getLinkage() const {
1170  return ExternalLinkage;
1171}
1172