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