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