Type.cpp revision c15cb2af27514ecc879daba9aa01389c5203685d
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(ASTContext &Ctx) const {
26  if (isConstQualified())
27    return true;
28
29  if (getTypePtr()->isArrayType())
30    return Ctx.getAsArrayType(*this)->getElementType().isConstant(Ctx);
31
32  return false;
33}
34
35void Type::Destroy(ASTContext& C) {
36  this->~Type();
37  C.Deallocate(this);
38}
39
40void ConstantArrayWithExprType::Destroy(ASTContext& C) {
41  // FIXME: destruction of SizeExpr commented out due to resource contention.
42  // SizeExpr->Destroy(C);
43  // See FIXME in SemaDecl.cpp:1536: if we were able to either steal
44  // or clone the SizeExpr there, then here we could freely delete it.
45  // Since we do not know how to steal or clone, we keep a pointer to
46  // a shared resource, but we cannot free it.
47  // (There probably is a trivial solution ... for people knowing clang!).
48  this->~ConstantArrayWithExprType();
49  C.Deallocate(this);
50}
51
52void VariableArrayType::Destroy(ASTContext& C) {
53  if (SizeExpr)
54    SizeExpr->Destroy(C);
55  this->~VariableArrayType();
56  C.Deallocate(this);
57}
58
59void DependentSizedArrayType::Destroy(ASTContext& C) {
60  SizeExpr->Destroy(C);
61  this->~DependentSizedArrayType();
62  C.Deallocate(this);
63}
64
65void DependentSizedExtVectorType::Destroy(ASTContext& C) {
66  if (SizeExpr)
67    SizeExpr->Destroy(C);
68  this->~DependentSizedExtVectorType();
69  C.Deallocate(this);
70}
71
72/// getArrayElementTypeNoTypeQual - If this is an array type, return the
73/// element type of the array, potentially with type qualifiers missing.
74/// This method should never be used when type qualifiers are meaningful.
75const Type *Type::getArrayElementTypeNoTypeQual() const {
76  // If this is directly an array type, return it.
77  if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
78    return ATy->getElementType().getTypePtr();
79
80  // If the canonical form of this type isn't the right kind, reject it.
81  if (!isa<ArrayType>(CanonicalType)) {
82    // Look through type qualifiers
83    if (ArrayType *AT = dyn_cast<ArrayType>(CanonicalType.getUnqualifiedType()))
84      return AT->getElementType().getTypePtr();
85    return 0;
86  }
87
88  // If this is a typedef for an array type, strip the typedef off without
89  // losing all typedef information.
90  return cast<ArrayType>(getDesugaredType())->getElementType().getTypePtr();
91}
92
93/// getDesugaredType - Return the specified type with any "sugar" removed from
94/// the type.  This takes off typedefs, typeof's etc.  If the outer level of
95/// the type is already concrete, it returns it unmodified.  This is similar
96/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
97/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
98/// concrete.
99///
100/// \param ForDisplay When true, the desugaring is provided for
101/// display purposes only. In this case, we apply more heuristics to
102/// decide whether it is worth providing a desugared form of the type
103/// or not.
104QualType QualType::getDesugaredType(bool ForDisplay) const {
105  return getTypePtr()->getDesugaredType(ForDisplay)
106     .getWithAdditionalQualifiers(getCVRQualifiers());
107}
108
109/// getDesugaredType - Return the specified type with any "sugar" removed from
110/// type type.  This takes off typedefs, typeof's etc.  If the outer level of
111/// the type is already concrete, it returns it unmodified.  This is similar
112/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
113/// example, it return "T*" as "T*", (not as "int*"), because the pointer is
114/// concrete.
115///
116/// \param ForDisplay When true, the desugaring is provided for
117/// display purposes only. In this case, we apply more heuristics to
118/// decide whether it is worth providing a desugared form of the type
119/// or not.
120QualType Type::getDesugaredType(bool ForDisplay) const {
121  if (const TypedefType *TDT = dyn_cast<TypedefType>(this))
122    return TDT->LookThroughTypedefs().getDesugaredType();
123  if (const TypeOfExprType *TOE = dyn_cast<TypeOfExprType>(this))
124    return TOE->getUnderlyingExpr()->getType().getDesugaredType();
125  if (const TypeOfType *TOT = dyn_cast<TypeOfType>(this))
126    return TOT->getUnderlyingType().getDesugaredType();
127  if (const DecltypeType *DTT = dyn_cast<DecltypeType>(this)) {
128    if (!DTT->getUnderlyingType()->isDependentType())
129      return DTT->getUnderlyingType().getDesugaredType();
130  }
131  if (const TemplateSpecializationType *Spec
132        = dyn_cast<TemplateSpecializationType>(this)) {
133    if (ForDisplay)
134      return QualType(this, 0);
135
136    QualType Canon = Spec->getCanonicalTypeInternal();
137    if (Canon->getAsTemplateSpecializationType())
138      return QualType(this, 0);
139    return Canon->getDesugaredType();
140  }
141  if (const QualifiedNameType *QualName  = dyn_cast<QualifiedNameType>(this)) {
142    if (ForDisplay) {
143      // If desugaring the type that the qualified name is referring to
144      // produces something interesting, that's our desugared type.
145      QualType NamedType = QualName->getNamedType().getDesugaredType();
146      if (NamedType != QualName->getNamedType())
147        return NamedType;
148    } else
149      return QualName->getNamedType().getDesugaredType();
150  }
151
152  return QualType(this, 0);
153}
154
155/// isVoidType - Helper method to determine if this is the 'void' type.
156bool Type::isVoidType() const {
157  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
158    return BT->getKind() == BuiltinType::Void;
159  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
160    return AS->getBaseType()->isVoidType();
161  return false;
162}
163
164bool Type::isObjectType() const {
165  if (isa<FunctionType>(CanonicalType) || isa<ReferenceType>(CanonicalType) ||
166      isa<IncompleteArrayType>(CanonicalType) || isVoidType())
167    return false;
168  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
169    return AS->getBaseType()->isObjectType();
170  return true;
171}
172
173bool Type::isDerivedType() const {
174  switch (CanonicalType->getTypeClass()) {
175  case ExtQual:
176    return cast<ExtQualType>(CanonicalType)->getBaseType()->isDerivedType();
177  case Pointer:
178  case VariableArray:
179  case ConstantArray:
180  case ConstantArrayWithExpr:
181  case ConstantArrayWithoutExpr:
182  case IncompleteArray:
183  case FunctionProto:
184  case FunctionNoProto:
185  case LValueReference:
186  case RValueReference:
187  case Record:
188    return true;
189  default:
190    return false;
191  }
192}
193
194bool Type::isClassType() const {
195  if (const RecordType *RT = getAsRecordType())
196    return RT->getDecl()->isClass();
197  return false;
198}
199bool Type::isStructureType() const {
200  if (const RecordType *RT = getAsRecordType())
201    return RT->getDecl()->isStruct();
202  return false;
203}
204bool Type::isVoidPointerType() const {
205  if (const PointerType *PT = getAsPointerType())
206    return PT->getPointeeType()->isVoidType();
207  return false;
208}
209
210bool Type::isUnionType() const {
211  if (const RecordType *RT = getAsRecordType())
212    return RT->getDecl()->isUnion();
213  return false;
214}
215
216bool Type::isComplexType() const {
217  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
218    return CT->getElementType()->isFloatingType();
219  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
220    return AS->getBaseType()->isComplexType();
221  return false;
222}
223
224bool Type::isComplexIntegerType() const {
225  // Check for GCC complex integer extension.
226  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
227    return CT->getElementType()->isIntegerType();
228  if (const ExtQualType *AS = dyn_cast<ExtQualType>(CanonicalType))
229    return AS->getBaseType()->isComplexIntegerType();
230  return false;
231}
232
233const ComplexType *Type::getAsComplexIntegerType() const {
234  // Are we directly a complex type?
235  if (const ComplexType *CTy = dyn_cast<ComplexType>(this)) {
236    if (CTy->getElementType()->isIntegerType())
237      return CTy;
238    return 0;
239  }
240
241  // If the canonical form of this type isn't what we want, reject it.
242  if (!isa<ComplexType>(CanonicalType)) {
243    // Look through type qualifiers (e.g. ExtQualType's).
244    if (isa<ComplexType>(CanonicalType.getUnqualifiedType()))
245      return CanonicalType.getUnqualifiedType()->getAsComplexIntegerType();
246    return 0;
247  }
248
249  // If this is a typedef for a complex type, strip the typedef off without
250  // losing all typedef information.
251  return cast<ComplexType>(getDesugaredType());
252}
253
254const BuiltinType *Type::getAsBuiltinType() const {
255  // If this is directly a builtin type, return it.
256  if (const BuiltinType *BTy = dyn_cast<BuiltinType>(this))
257    return BTy;
258
259  // If the canonical form of this type isn't a builtin type, reject it.
260  if (!isa<BuiltinType>(CanonicalType)) {
261    // Look through type qualifiers (e.g. ExtQualType's).
262    if (isa<BuiltinType>(CanonicalType.getUnqualifiedType()))
263      return CanonicalType.getUnqualifiedType()->getAsBuiltinType();
264    return 0;
265  }
266
267  // If this is a typedef for a builtin type, strip the typedef off without
268  // losing all typedef information.
269  return cast<BuiltinType>(getDesugaredType());
270}
271
272const FunctionType *Type::getAsFunctionType() const {
273  // If this is directly a function type, return it.
274  if (const FunctionType *FTy = dyn_cast<FunctionType>(this))
275    return FTy;
276
277  // If the canonical form of this type isn't the right kind, reject it.
278  if (!isa<FunctionType>(CanonicalType)) {
279    // Look through type qualifiers
280    if (isa<FunctionType>(CanonicalType.getUnqualifiedType()))
281      return CanonicalType.getUnqualifiedType()->getAsFunctionType();
282    return 0;
283  }
284
285  // If this is a typedef for a function type, strip the typedef off without
286  // losing all typedef information.
287  return cast<FunctionType>(getDesugaredType());
288}
289
290const FunctionNoProtoType *Type::getAsFunctionNoProtoType() const {
291  return dyn_cast_or_null<FunctionNoProtoType>(getAsFunctionType());
292}
293
294const FunctionProtoType *Type::getAsFunctionProtoType() const {
295  return dyn_cast_or_null<FunctionProtoType>(getAsFunctionType());
296}
297
298QualType Type::getPointeeType() const {
299  if (const PointerType *PT = getAsPointerType())
300    return PT->getPointeeType();
301  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType())
302    return OPT->getPointeeType();
303  if (const BlockPointerType *BPT = getAsBlockPointerType())
304    return BPT->getPointeeType();
305  return QualType();
306}
307
308/// isVariablyModifiedType (C99 6.7.5p3) - Return true for variable length
309/// array types and types that contain variable array types in their
310/// declarator
311bool Type::isVariablyModifiedType() const {
312  // A VLA is a variably modified type.
313  if (isVariableArrayType())
314    return true;
315
316  // An array can contain a variably modified type
317  if (const Type *T = getArrayElementTypeNoTypeQual())
318    return T->isVariablyModifiedType();
319
320  // A pointer can point to a variably modified type.
321  // Also, C++ references and member pointers can point to a variably modified
322  // type, where VLAs appear as an extension to C++, and should be treated
323  // correctly.
324  if (const PointerType *PT = getAsPointerType())
325    return PT->getPointeeType()->isVariablyModifiedType();
326  if (const ReferenceType *RT = getAsReferenceType())
327    return RT->getPointeeType()->isVariablyModifiedType();
328  if (const MemberPointerType *PT = getAsMemberPointerType())
329    return PT->getPointeeType()->isVariablyModifiedType();
330
331  // A function can return a variably modified type
332  // This one isn't completely obvious, but it follows from the
333  // definition in C99 6.7.5p3. Because of this rule, it's
334  // illegal to declare a function returning a variably modified type.
335  if (const FunctionType *FT = getAsFunctionType())
336    return FT->getResultType()->isVariablyModifiedType();
337
338  return false;
339}
340
341const PointerType *Type::getAsPointerType() const {
342  return getAs<PointerType>();
343}
344const BlockPointerType *Type::getAsBlockPointerType() const {
345  return getAs<BlockPointerType>();
346}
347const ReferenceType *Type::getAsReferenceType() const {
348  return getAs<ReferenceType>();
349}
350const LValueReferenceType *Type::getAsLValueReferenceType() const {
351  return getAs<LValueReferenceType>();
352}
353const RValueReferenceType *Type::getAsRValueReferenceType() const {
354  return getAs<RValueReferenceType>();
355}
356const MemberPointerType *Type::getAsMemberPointerType() const {
357  return getAs<MemberPointerType>();
358}
359const TagType *Type::getAsTagType() const {
360  return getAs<TagType>();
361}
362const RecordType *Type::getAsRecordType() const {
363  return getAs<RecordType>();
364}
365const RecordType *Type::getAsStructureType() const {
366  // If this is directly a structure type, return it.
367  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
368    if (RT->getDecl()->isStruct())
369      return RT;
370  }
371
372  // If the canonical form of this type isn't the right kind, reject it.
373  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
374    if (!RT->getDecl()->isStruct())
375      return 0;
376
377    // If this is a typedef for a structure type, strip the typedef off without
378    // losing all typedef information.
379    return cast<RecordType>(getDesugaredType());
380  }
381  // Look through type qualifiers
382  if (isa<RecordType>(CanonicalType.getUnqualifiedType()))
383    return CanonicalType.getUnqualifiedType()->getAsStructureType();
384  return 0;
385}
386
387const RecordType *Type::getAsUnionType() const {
388  // If this is directly a union type, return it.
389  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
390    if (RT->getDecl()->isUnion())
391      return RT;
392  }
393
394  // If the canonical form of this type isn't the right kind, reject it.
395  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
396    if (!RT->getDecl()->isUnion())
397      return 0;
398
399    // If this is a typedef for a union type, strip the typedef off without
400    // losing all typedef information.
401    return cast<RecordType>(getDesugaredType());
402  }
403
404  // Look through type qualifiers
405  if (isa<RecordType>(CanonicalType.getUnqualifiedType()))
406    return CanonicalType.getUnqualifiedType()->getAsUnionType();
407  return 0;
408}
409
410const EnumType *Type::getAsEnumType() const {
411  // Check the canonicalized unqualified type directly; the more complex
412  // version is unnecessary because there isn't any typedef information
413  // to preserve.
414  return dyn_cast<EnumType>(CanonicalType.getUnqualifiedType());
415}
416
417const ComplexType *Type::getAsComplexType() const {
418  // Are we directly a complex type?
419  if (const ComplexType *CTy = dyn_cast<ComplexType>(this))
420    return CTy;
421
422  // If the canonical form of this type isn't the right kind, reject it.
423  if (!isa<ComplexType>(CanonicalType)) {
424    // Look through type qualifiers
425    if (isa<ComplexType>(CanonicalType.getUnqualifiedType()))
426      return CanonicalType.getUnqualifiedType()->getAsComplexType();
427    return 0;
428  }
429
430  // If this is a typedef for a complex type, strip the typedef off without
431  // losing all typedef information.
432  return cast<ComplexType>(getDesugaredType());
433}
434
435const VectorType *Type::getAsVectorType() const {
436  // Are we directly a vector type?
437  if (const VectorType *VTy = dyn_cast<VectorType>(this))
438    return VTy;
439
440  // If the canonical form of this type isn't the right kind, reject it.
441  if (!isa<VectorType>(CanonicalType)) {
442    // Look through type qualifiers
443    if (isa<VectorType>(CanonicalType.getUnqualifiedType()))
444      return CanonicalType.getUnqualifiedType()->getAsVectorType();
445    return 0;
446  }
447
448  // If this is a typedef for a vector type, strip the typedef off without
449  // losing all typedef information.
450  return cast<VectorType>(getDesugaredType());
451}
452
453const ExtVectorType *Type::getAsExtVectorType() const {
454  // Are we directly an OpenCU vector type?
455  if (const ExtVectorType *VTy = dyn_cast<ExtVectorType>(this))
456    return VTy;
457
458  // If the canonical form of this type isn't the right kind, reject it.
459  if (!isa<ExtVectorType>(CanonicalType)) {
460    // Look through type qualifiers
461    if (isa<ExtVectorType>(CanonicalType.getUnqualifiedType()))
462      return CanonicalType.getUnqualifiedType()->getAsExtVectorType();
463    return 0;
464  }
465
466  // If this is a typedef for an extended vector type, strip the typedef off
467  // without losing all typedef information.
468  return cast<ExtVectorType>(getDesugaredType());
469}
470
471const ObjCInterfaceType *Type::getAsObjCInterfaceType() const {
472  // There is no sugar for ObjCInterfaceType's, just return the canonical
473  // type pointer if it is the right class.  There is no typedef information to
474  // return and these cannot be Address-space qualified.
475  return dyn_cast<ObjCInterfaceType>(CanonicalType.getUnqualifiedType());
476}
477
478const ObjCInterfaceType *Type::getAsObjCQualifiedInterfaceType() const {
479  // There is no sugar for ObjCInterfaceType's, just return the canonical
480  // type pointer if it is the right class.  There is no typedef information to
481  // return and these cannot be Address-space qualified.
482  if (const ObjCInterfaceType *OIT = getAsObjCInterfaceType())
483    if (OIT->getNumProtocols())
484      return OIT;
485  return 0;
486}
487
488bool Type::isObjCQualifiedInterfaceType() const {
489  return getAsObjCQualifiedIdType() != 0;
490}
491
492const ObjCObjectPointerType *Type::getAsObjCObjectPointerType() const {
493  // There is no sugar for ObjCObjectPointerType's, just return the
494  // canonical type pointer if it is the right class.
495  return dyn_cast<ObjCObjectPointerType>(CanonicalType.getUnqualifiedType());
496}
497
498const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
499  // There is no sugar for ObjCQualifiedIdType's, just return the canonical
500  // type pointer if it is the right class.
501  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType()) {
502    if (OPT->isObjCQualifiedIdType())
503      return OPT;
504  }
505  return 0;
506}
507
508const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
509  if (const ObjCObjectPointerType *OPT = getAsObjCObjectPointerType()) {
510    if (OPT->getInterfaceType())
511      return OPT;
512  }
513  return 0;
514}
515
516const TemplateTypeParmType *Type::getAsTemplateTypeParmType() const {
517  // There is no sugar for template type parameters, so just return
518  // the canonical type pointer if it is the right class.
519  // FIXME: can these be address-space qualified?
520  return dyn_cast<TemplateTypeParmType>(CanonicalType);
521}
522
523const TemplateSpecializationType *
524Type::getAsTemplateSpecializationType() const {
525  // There is no sugar for class template specialization types, so
526  // just return the canonical type pointer if it is the right class.
527  return dyn_cast<TemplateSpecializationType>(CanonicalType);
528}
529
530bool Type::isIntegerType() const {
531  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
532    return BT->getKind() >= BuiltinType::Bool &&
533           BT->getKind() <= BuiltinType::Int128;
534  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
535    // Incomplete enum types are not treated as integer types.
536    // FIXME: In C++, enum types are never integer types.
537    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
538      return true;
539  if (isa<FixedWidthIntType>(CanonicalType))
540    return true;
541  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
542    return VT->getElementType()->isIntegerType();
543  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
544    return EXTQT->getBaseType()->isIntegerType();
545  return false;
546}
547
548bool Type::isIntegralType() const {
549  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
550    return BT->getKind() >= BuiltinType::Bool &&
551    BT->getKind() <= BuiltinType::LongLong;
552  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
553    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
554      return true;  // Complete enum types are integral.
555                    // FIXME: In C++, enum types are never integral.
556  if (isa<FixedWidthIntType>(CanonicalType))
557    return true;
558  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
559    return EXTQT->getBaseType()->isIntegralType();
560  return false;
561}
562
563bool Type::isEnumeralType() const {
564  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
565    return TT->getDecl()->isEnum();
566  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
567    return EXTQT->getBaseType()->isEnumeralType();
568  return false;
569}
570
571bool Type::isBooleanType() const {
572  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
573    return BT->getKind() == BuiltinType::Bool;
574  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
575    return EXTQT->getBaseType()->isBooleanType();
576  return false;
577}
578
579bool Type::isCharType() const {
580  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
581    return BT->getKind() == BuiltinType::Char_U ||
582           BT->getKind() == BuiltinType::UChar ||
583           BT->getKind() == BuiltinType::Char_S ||
584           BT->getKind() == BuiltinType::SChar;
585  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
586    return EXTQT->getBaseType()->isCharType();
587  return false;
588}
589
590bool Type::isWideCharType() const {
591  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
592    return BT->getKind() == BuiltinType::WChar;
593  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
594    return EXTQT->getBaseType()->isWideCharType();
595  return false;
596}
597
598/// isSignedIntegerType - Return true if this is an integer type that is
599/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
600/// an enum decl which has a signed representation, or a vector of signed
601/// integer element type.
602bool Type::isSignedIntegerType() const {
603  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
604    return BT->getKind() >= BuiltinType::Char_S &&
605           BT->getKind() <= BuiltinType::LongLong;
606  }
607
608  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
609    return ET->getDecl()->getIntegerType()->isSignedIntegerType();
610
611  if (const FixedWidthIntType *FWIT =
612          dyn_cast<FixedWidthIntType>(CanonicalType))
613    return FWIT->isSigned();
614
615  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
616    return VT->getElementType()->isSignedIntegerType();
617  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
618    return EXTQT->getBaseType()->isSignedIntegerType();
619  return false;
620}
621
622/// isUnsignedIntegerType - Return true if this is an integer type that is
623/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
624/// decl which has an unsigned representation, or a vector of unsigned integer
625/// element type.
626bool Type::isUnsignedIntegerType() const {
627  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
628    return BT->getKind() >= BuiltinType::Bool &&
629           BT->getKind() <= BuiltinType::ULongLong;
630  }
631
632  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
633    return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
634
635  if (const FixedWidthIntType *FWIT =
636          dyn_cast<FixedWidthIntType>(CanonicalType))
637    return !FWIT->isSigned();
638
639  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
640    return VT->getElementType()->isUnsignedIntegerType();
641  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
642    return EXTQT->getBaseType()->isUnsignedIntegerType();
643  return false;
644}
645
646bool Type::isFloatingType() const {
647  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
648    return BT->getKind() >= BuiltinType::Float &&
649           BT->getKind() <= BuiltinType::LongDouble;
650  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
651    return CT->getElementType()->isFloatingType();
652  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
653    return VT->getElementType()->isFloatingType();
654  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
655    return EXTQT->getBaseType()->isFloatingType();
656  return false;
657}
658
659bool Type::isRealFloatingType() const {
660  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
661    return BT->getKind() >= BuiltinType::Float &&
662           BT->getKind() <= BuiltinType::LongDouble;
663  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
664    return VT->getElementType()->isRealFloatingType();
665  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
666    return EXTQT->getBaseType()->isRealFloatingType();
667  return false;
668}
669
670bool Type::isRealType() const {
671  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
672    return BT->getKind() >= BuiltinType::Bool &&
673           BT->getKind() <= BuiltinType::LongDouble;
674  if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
675    return TT->getDecl()->isEnum() && TT->getDecl()->isDefinition();
676  if (isa<FixedWidthIntType>(CanonicalType))
677    return true;
678  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
679    return VT->getElementType()->isRealType();
680  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
681    return EXTQT->getBaseType()->isRealType();
682  return false;
683}
684
685bool Type::isArithmeticType() const {
686  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
687    return BT->getKind() >= BuiltinType::Bool &&
688           BT->getKind() <= BuiltinType::LongDouble;
689  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
690    // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
691    // If a body isn't seen by the time we get here, return false.
692    return ET->getDecl()->isDefinition();
693  if (isa<FixedWidthIntType>(CanonicalType))
694    return true;
695  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
696    return EXTQT->getBaseType()->isArithmeticType();
697  return isa<ComplexType>(CanonicalType) || isa<VectorType>(CanonicalType);
698}
699
700bool Type::isScalarType() const {
701  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
702    return BT->getKind() != BuiltinType::Void;
703  if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) {
704    // Enums are scalar types, but only if they are defined.  Incomplete enums
705    // are not treated as scalar types.
706    if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
707      return true;
708    return false;
709  }
710  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
711    return EXTQT->getBaseType()->isScalarType();
712  if (isa<FixedWidthIntType>(CanonicalType))
713    return true;
714  return isa<PointerType>(CanonicalType) ||
715         isa<BlockPointerType>(CanonicalType) ||
716         isa<MemberPointerType>(CanonicalType) ||
717         isa<ComplexType>(CanonicalType) ||
718         isa<ObjCObjectPointerType>(CanonicalType);
719}
720
721/// \brief Determines whether the type is a C++ aggregate type or C
722/// aggregate or union type.
723///
724/// An aggregate type is an array or a class type (struct, union, or
725/// class) that has no user-declared constructors, no private or
726/// protected non-static data members, no base classes, and no virtual
727/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
728/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
729/// includes union types.
730bool Type::isAggregateType() const {
731  if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
732    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
733      return ClassDecl->isAggregate();
734
735    return true;
736  }
737
738  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
739    return EXTQT->getBaseType()->isAggregateType();
740  return isa<ArrayType>(CanonicalType);
741}
742
743/// isConstantSizeType - Return true if this is not a variable sized type,
744/// according to the rules of C99 6.7.5p3.  It is not legal to call this on
745/// incomplete types or dependent types.
746bool Type::isConstantSizeType() const {
747  if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(CanonicalType))
748    return EXTQT->getBaseType()->isConstantSizeType();
749  assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
750  assert(!isDependentType() && "This doesn't make sense for dependent types");
751  // The VAT must have a size, as it is known to be complete.
752  return !isa<VariableArrayType>(CanonicalType);
753}
754
755/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
756/// - a type that can describe objects, but which lacks information needed to
757/// determine its size.
758bool Type::isIncompleteType() const {
759  switch (CanonicalType->getTypeClass()) {
760  default: return false;
761  case ExtQual:
762    return cast<ExtQualType>(CanonicalType)->getBaseType()->isIncompleteType();
763  case Builtin:
764    // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
765    // be completed.
766    return isVoidType();
767  case Record:
768  case Enum:
769    // A tagged type (struct/union/enum/class) is incomplete if the decl is a
770    // forward declaration, but not a full definition (C99 6.2.5p22).
771    return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
772  case IncompleteArray:
773    // An array of unknown size is an incomplete type (C99 6.2.5p22).
774    return true;
775  case ObjCInterface:
776    // ObjC interfaces are incomplete if they are @class, not @interface.
777    return cast<ObjCInterfaceType>(this)->getDecl()->isForwardDecl();
778  }
779}
780
781/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
782bool Type::isPODType() const {
783  // The compiler shouldn't query this for incomplete types, but the user might.
784  // We return false for that case.
785  if (isIncompleteType())
786    return false;
787
788  switch (CanonicalType->getTypeClass()) {
789    // Everything not explicitly mentioned is not POD.
790  default: return false;
791  case ExtQual:
792    return cast<ExtQualType>(CanonicalType)->getBaseType()->isPODType();
793  case VariableArray:
794  case ConstantArray:
795    // IncompleteArray is caught by isIncompleteType() above.
796    return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
797
798  case Builtin:
799  case Complex:
800  case Pointer:
801  case MemberPointer:
802  case Vector:
803  case ExtVector:
804  case ObjCObjectPointer:
805    return true;
806
807  case Enum:
808    return true;
809
810  case Record:
811    if (CXXRecordDecl *ClassDecl
812          = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
813      return ClassDecl->isPOD();
814
815    // C struct/union is POD.
816    return true;
817  }
818}
819
820bool Type::isPromotableIntegerType() const {
821  if (const BuiltinType *BT = getAsBuiltinType())
822    switch (BT->getKind()) {
823    case BuiltinType::Bool:
824    case BuiltinType::Char_S:
825    case BuiltinType::Char_U:
826    case BuiltinType::SChar:
827    case BuiltinType::UChar:
828    case BuiltinType::Short:
829    case BuiltinType::UShort:
830      return true;
831    default:
832      return false;
833    }
834  return false;
835}
836
837bool Type::isNullPtrType() const {
838  if (const BuiltinType *BT = getAsBuiltinType())
839    return BT->getKind() == BuiltinType::NullPtr;
840  return false;
841}
842
843bool Type::isSpecifierType() const {
844  // Note that this intentionally does not use the canonical type.
845  switch (getTypeClass()) {
846  case Builtin:
847  case Record:
848  case Enum:
849  case Typedef:
850  case Complex:
851  case TypeOfExpr:
852  case TypeOf:
853  case TemplateTypeParm:
854  case TemplateSpecialization:
855  case QualifiedName:
856  case Typename:
857  case ObjCInterface:
858  case ObjCObjectPointer:
859    return true;
860  default:
861    return false;
862  }
863}
864
865const char *BuiltinType::getName(const LangOptions &LO) const {
866  switch (getKind()) {
867  default: assert(0 && "Unknown builtin type!");
868  case Void:              return "void";
869  case Bool:              return LO.Bool ? "bool" : "_Bool";
870  case Char_S:            return "char";
871  case Char_U:            return "char";
872  case SChar:             return "signed char";
873  case Short:             return "short";
874  case Int:               return "int";
875  case Long:              return "long";
876  case LongLong:          return "long long";
877  case Int128:            return "__int128_t";
878  case UChar:             return "unsigned char";
879  case UShort:            return "unsigned short";
880  case UInt:              return "unsigned int";
881  case ULong:             return "unsigned long";
882  case ULongLong:         return "unsigned long long";
883  case UInt128:           return "__uint128_t";
884  case Float:             return "float";
885  case Double:            return "double";
886  case LongDouble:        return "long double";
887  case WChar:             return "wchar_t";
888  case Char16:            return "char16_t";
889  case Char32:            return "char32_t";
890  case NullPtr:           return "nullptr_t";
891  case Overload:          return "<overloaded function type>";
892  case Dependent:         return "<dependent type>";
893  case UndeducedAuto:     return "auto";
894  case ObjCId:            return "id";
895  case ObjCClass:         return "Class";
896  }
897}
898
899void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
900                                arg_type_iterator ArgTys,
901                                unsigned NumArgs, bool isVariadic,
902                                unsigned TypeQuals, bool hasExceptionSpec,
903                                bool anyExceptionSpec, unsigned NumExceptions,
904                                exception_iterator Exs) {
905  ID.AddPointer(Result.getAsOpaquePtr());
906  for (unsigned i = 0; i != NumArgs; ++i)
907    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
908  ID.AddInteger(isVariadic);
909  ID.AddInteger(TypeQuals);
910  ID.AddInteger(hasExceptionSpec);
911  if (hasExceptionSpec) {
912    ID.AddInteger(anyExceptionSpec);
913    for(unsigned i = 0; i != NumExceptions; ++i)
914      ID.AddPointer(Exs[i].getAsOpaquePtr());
915  }
916}
917
918void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
919  Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(),
920          getTypeQuals(), hasExceptionSpec(), hasAnyExceptionSpec(),
921          getNumExceptions(), exception_begin());
922}
923
924void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID,
925                                    QualType OIT, ObjCProtocolDecl **protocols,
926                                    unsigned NumProtocols) {
927  ID.AddPointer(OIT.getAsOpaquePtr());
928  for (unsigned i = 0; i != NumProtocols; i++)
929    ID.AddPointer(protocols[i]);
930}
931
932void ObjCObjectPointerType::Profile(llvm::FoldingSetNodeID &ID) {
933  if (getNumProtocols())
934    Profile(ID, getPointeeType(), &Protocols[0], getNumProtocols());
935  else
936    Profile(ID, getPointeeType(), 0, 0);
937}
938
939/// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
940/// potentially looking through *all* consequtive typedefs.  This returns the
941/// sum of the type qualifiers, so if you have:
942///   typedef const int A;
943///   typedef volatile A B;
944/// looking through the typedefs for B will give you "const volatile A".
945///
946QualType TypedefType::LookThroughTypedefs() const {
947  // Usually, there is only a single level of typedefs, be fast in that case.
948  QualType FirstType = getDecl()->getUnderlyingType();
949  if (!isa<TypedefType>(FirstType))
950    return FirstType;
951
952  // Otherwise, do the fully general loop.
953  unsigned TypeQuals = 0;
954  const TypedefType *TDT = this;
955  while (1) {
956    QualType CurType = TDT->getDecl()->getUnderlyingType();
957
958
959    /// FIXME:
960    /// FIXME: This is incorrect for ExtQuals!
961    /// FIXME:
962    TypeQuals |= CurType.getCVRQualifiers();
963
964    TDT = dyn_cast<TypedefType>(CurType);
965    if (TDT == 0)
966      return QualType(CurType.getTypePtr(), TypeQuals);
967  }
968}
969
970TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
971  : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) {
972}
973
974DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
975  : Type(Decltype, can, E->isTypeDependent()), E(E),
976  UnderlyingType(underlyingType) {
977}
978
979TagType::TagType(TypeClass TC, TagDecl *D, QualType can)
980  : Type(TC, can, D->isDependentType()), decl(D, 0) {}
981
982bool RecordType::classof(const TagType *TT) {
983  return isa<RecordDecl>(TT->getDecl());
984}
985
986bool EnumType::classof(const TagType *TT) {
987  return isa<EnumDecl>(TT->getDecl());
988}
989
990bool
991TemplateSpecializationType::
992anyDependentTemplateArguments(const TemplateArgument *Args, unsigned NumArgs) {
993  for (unsigned Idx = 0; Idx < NumArgs; ++Idx) {
994    switch (Args[Idx].getKind()) {
995    case TemplateArgument::Null:
996      assert(false && "Should not have a NULL template argument");
997      break;
998
999    case TemplateArgument::Type:
1000      if (Args[Idx].getAsType()->isDependentType())
1001        return true;
1002      break;
1003
1004    case TemplateArgument::Declaration:
1005    case TemplateArgument::Integral:
1006      // Never dependent
1007      break;
1008
1009    case TemplateArgument::Expression:
1010      if (Args[Idx].getAsExpr()->isTypeDependent() ||
1011          Args[Idx].getAsExpr()->isValueDependent())
1012        return true;
1013      break;
1014
1015    case TemplateArgument::Pack:
1016      assert(0 && "FIXME: Implement!");
1017      break;
1018    }
1019  }
1020
1021  return false;
1022}
1023
1024TemplateSpecializationType::
1025TemplateSpecializationType(TemplateName T, const TemplateArgument *Args,
1026                           unsigned NumArgs, QualType Canon)
1027  : Type(TemplateSpecialization,
1028         Canon.isNull()? QualType(this, 0) : Canon,
1029         T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)),
1030    Template(T), NumArgs(NumArgs)
1031{
1032  assert((!Canon.isNull() ||
1033          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1034         "No canonical type for non-dependent class template specialization");
1035
1036  TemplateArgument *TemplateArgs
1037    = reinterpret_cast<TemplateArgument *>(this + 1);
1038  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
1039    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1040}
1041
1042void TemplateSpecializationType::Destroy(ASTContext& C) {
1043  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1044    // FIXME: Not all expressions get cloned, so we can't yet perform
1045    // this destruction.
1046    //    if (Expr *E = getArg(Arg).getAsExpr())
1047    //      E->Destroy(C);
1048  }
1049}
1050
1051TemplateSpecializationType::iterator
1052TemplateSpecializationType::end() const {
1053  return begin() + getNumArgs();
1054}
1055
1056const TemplateArgument &
1057TemplateSpecializationType::getArg(unsigned Idx) const {
1058  assert(Idx < getNumArgs() && "Template argument out of range");
1059  return getArgs()[Idx];
1060}
1061
1062void
1063TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1064                                    TemplateName T,
1065                                    const TemplateArgument *Args,
1066                                    unsigned NumArgs) {
1067  T.Profile(ID);
1068  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1069    Args[Idx].Profile(ID);
1070}
1071
1072//===----------------------------------------------------------------------===//
1073// Type Printing
1074//===----------------------------------------------------------------------===//
1075
1076void QualType::dump(const char *msg) const {
1077  std::string R = "identifier";
1078  LangOptions LO;
1079  getAsStringInternal(R, PrintingPolicy(LO));
1080  if (msg)
1081    fprintf(stderr, "%s: %s\n", msg, R.c_str());
1082  else
1083    fprintf(stderr, "%s\n", R.c_str());
1084}
1085void QualType::dump() const {
1086  dump("");
1087}
1088
1089void Type::dump() const {
1090  std::string S = "identifier";
1091  LangOptions LO;
1092  getAsStringInternal(S, PrintingPolicy(LO));
1093  fprintf(stderr, "%s\n", S.c_str());
1094}
1095
1096
1097
1098static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
1099  // Note: funkiness to ensure we get a space only between quals.
1100  bool NonePrinted = true;
1101  if (TypeQuals & QualType::Const)
1102    S += "const", NonePrinted = false;
1103  if (TypeQuals & QualType::Volatile)
1104    S += (NonePrinted+" volatile"), NonePrinted = false;
1105  if (TypeQuals & QualType::Restrict)
1106    S += (NonePrinted+" restrict"), NonePrinted = false;
1107}
1108
1109std::string QualType::getAsString() const {
1110  std::string S;
1111  LangOptions LO;
1112  getAsStringInternal(S, PrintingPolicy(LO));
1113  return S;
1114}
1115
1116void
1117QualType::getAsStringInternal(std::string &S,
1118                              const PrintingPolicy &Policy) const {
1119  if (isNull()) {
1120    S += "NULL TYPE";
1121    return;
1122  }
1123
1124  if (Policy.SuppressSpecifiers && getTypePtr()->isSpecifierType())
1125    return;
1126
1127  // Print qualifiers as appropriate.
1128  if (unsigned Tq = getCVRQualifiers()) {
1129    std::string TQS;
1130    AppendTypeQualList(TQS, Tq);
1131    if (!S.empty())
1132      S = TQS + ' ' + S;
1133    else
1134      S = TQS;
1135  }
1136
1137  getTypePtr()->getAsStringInternal(S, Policy);
1138}
1139
1140void BuiltinType::getAsStringInternal(std::string &S,
1141                                      const PrintingPolicy &Policy) const {
1142  if (S.empty()) {
1143    S = getName(Policy.LangOpts);
1144  } else {
1145    // Prefix the basic type, e.g. 'int X'.
1146    S = ' ' + S;
1147    S = getName(Policy.LangOpts) + S;
1148  }
1149}
1150
1151void FixedWidthIntType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1152  // FIXME: Once we get bitwidth attribute, write as
1153  // "int __attribute__((bitwidth(x)))".
1154  std::string prefix = "__clang_fixedwidth";
1155  prefix += llvm::utostr_32(Width);
1156  prefix += (char)(Signed ? 'S' : 'U');
1157  if (S.empty()) {
1158    S = prefix;
1159  } else {
1160    // Prefix the basic type, e.g. 'int X'.
1161    S = prefix + S;
1162  }
1163}
1164
1165
1166void ComplexType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1167  ElementType->getAsStringInternal(S, Policy);
1168  S = "_Complex " + S;
1169}
1170
1171void ExtQualType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1172  bool NeedsSpace = false;
1173  if (AddressSpace) {
1174    S = "__attribute__((address_space("+llvm::utostr_32(AddressSpace)+")))" + S;
1175    NeedsSpace = true;
1176  }
1177  if (GCAttrType != QualType::GCNone) {
1178    if (NeedsSpace)
1179      S += ' ';
1180    S += "__attribute__((objc_gc(";
1181    if (GCAttrType == QualType::Weak)
1182      S += "weak";
1183    else
1184      S += "strong";
1185    S += ")))";
1186  }
1187  BaseType->getAsStringInternal(S, Policy);
1188}
1189
1190void PointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1191  S = '*' + S;
1192
1193  // Handle things like 'int (*A)[4];' correctly.
1194  // FIXME: this should include vectors, but vectors use attributes I guess.
1195  if (isa<ArrayType>(getPointeeType()))
1196    S = '(' + S + ')';
1197
1198  getPointeeType().getAsStringInternal(S, Policy);
1199}
1200
1201void BlockPointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1202  S = '^' + S;
1203  PointeeType.getAsStringInternal(S, Policy);
1204}
1205
1206void LValueReferenceType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1207  S = '&' + S;
1208
1209  // Handle things like 'int (&A)[4];' correctly.
1210  // FIXME: this should include vectors, but vectors use attributes I guess.
1211  if (isa<ArrayType>(getPointeeType()))
1212    S = '(' + S + ')';
1213
1214  getPointeeType().getAsStringInternal(S, Policy);
1215}
1216
1217void RValueReferenceType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1218  S = "&&" + S;
1219
1220  // Handle things like 'int (&&A)[4];' correctly.
1221  // FIXME: this should include vectors, but vectors use attributes I guess.
1222  if (isa<ArrayType>(getPointeeType()))
1223    S = '(' + S + ')';
1224
1225  getPointeeType().getAsStringInternal(S, Policy);
1226}
1227
1228void MemberPointerType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1229  std::string C;
1230  Class->getAsStringInternal(C, Policy);
1231  C += "::*";
1232  S = C + S;
1233
1234  // Handle things like 'int (Cls::*A)[4];' correctly.
1235  // FIXME: this should include vectors, but vectors use attributes I guess.
1236  if (isa<ArrayType>(getPointeeType()))
1237    S = '(' + S + ')';
1238
1239  getPointeeType().getAsStringInternal(S, Policy);
1240}
1241
1242void ConstantArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1243  S += '[';
1244  S += llvm::utostr(getSize().getZExtValue());
1245  S += ']';
1246
1247  getElementType().getAsStringInternal(S, Policy);
1248}
1249
1250void ConstantArrayWithExprType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1251  if (Policy.ConstantArraySizeAsWritten) {
1252    std::string SStr;
1253    llvm::raw_string_ostream s(SStr);
1254    getSizeExpr()->printPretty(s, 0, Policy);
1255    S += '[';
1256    S += s.str();
1257    S += ']';
1258    getElementType().getAsStringInternal(S, Policy);
1259  }
1260  else
1261    ConstantArrayType::getAsStringInternal(S, Policy);
1262}
1263
1264void ConstantArrayWithoutExprType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1265  if (Policy.ConstantArraySizeAsWritten) {
1266    S += "[]";
1267    getElementType().getAsStringInternal(S, Policy);
1268  }
1269  else
1270    ConstantArrayType::getAsStringInternal(S, Policy);
1271}
1272
1273void IncompleteArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1274  S += "[]";
1275
1276  getElementType().getAsStringInternal(S, Policy);
1277}
1278
1279void VariableArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1280  S += '[';
1281
1282  if (getIndexTypeQualifier()) {
1283    AppendTypeQualList(S, getIndexTypeQualifier());
1284    S += ' ';
1285  }
1286
1287  if (getSizeModifier() == Static)
1288    S += "static";
1289  else if (getSizeModifier() == Star)
1290    S += '*';
1291
1292  if (getSizeExpr()) {
1293    std::string SStr;
1294    llvm::raw_string_ostream s(SStr);
1295    getSizeExpr()->printPretty(s, 0, Policy);
1296    S += s.str();
1297  }
1298  S += ']';
1299
1300  getElementType().getAsStringInternal(S, Policy);
1301}
1302
1303void DependentSizedArrayType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1304  S += '[';
1305
1306  if (getIndexTypeQualifier()) {
1307    AppendTypeQualList(S, getIndexTypeQualifier());
1308    S += ' ';
1309  }
1310
1311  if (getSizeModifier() == Static)
1312    S += "static";
1313  else if (getSizeModifier() == Star)
1314    S += '*';
1315
1316  if (getSizeExpr()) {
1317    std::string SStr;
1318    llvm::raw_string_ostream s(SStr);
1319    getSizeExpr()->printPretty(s, 0, Policy);
1320    S += s.str();
1321  }
1322  S += ']';
1323
1324  getElementType().getAsStringInternal(S, Policy);
1325}
1326
1327void DependentSizedExtVectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1328  getElementType().getAsStringInternal(S, Policy);
1329
1330  S += " __attribute__((ext_vector_type(";
1331  if (getSizeExpr()) {
1332    std::string SStr;
1333    llvm::raw_string_ostream s(SStr);
1334    getSizeExpr()->printPretty(s, 0, Policy);
1335    S += s.str();
1336  }
1337  S += ")))";
1338}
1339
1340void VectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1341  // FIXME: We prefer to print the size directly here, but have no way
1342  // to get the size of the type.
1343  S += " __attribute__((__vector_size__(";
1344  S += llvm::utostr_32(NumElements); // convert back to bytes.
1345  S += " * sizeof(" + ElementType.getAsString() + "))))";
1346  ElementType.getAsStringInternal(S, Policy);
1347}
1348
1349void ExtVectorType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1350  S += " __attribute__((ext_vector_type(";
1351  S += llvm::utostr_32(NumElements);
1352  S += ")))";
1353  ElementType.getAsStringInternal(S, Policy);
1354}
1355
1356void TypeOfExprType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1357  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typeof(e) X'.
1358    InnerString = ' ' + InnerString;
1359  std::string Str;
1360  llvm::raw_string_ostream s(Str);
1361  getUnderlyingExpr()->printPretty(s, 0, Policy);
1362  InnerString = "typeof " + s.str() + InnerString;
1363}
1364
1365void TypeOfType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1366  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typeof(t) X'.
1367    InnerString = ' ' + InnerString;
1368  std::string Tmp;
1369  getUnderlyingType().getAsStringInternal(Tmp, Policy);
1370  InnerString = "typeof(" + Tmp + ")" + InnerString;
1371}
1372
1373void DecltypeType::getAsStringInternal(std::string &InnerString,
1374                                       const PrintingPolicy &Policy) const {
1375  if (!InnerString.empty())    // Prefix the basic type, e.g. 'decltype(t) X'.
1376    InnerString = ' ' + InnerString;
1377  std::string Str;
1378  llvm::raw_string_ostream s(Str);
1379  getUnderlyingExpr()->printPretty(s, 0, Policy);
1380  InnerString = "decltype(" + s.str() + ")" + InnerString;
1381}
1382
1383void FunctionNoProtoType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1384  // If needed for precedence reasons, wrap the inner part in grouping parens.
1385  if (!S.empty())
1386    S = "(" + S + ")";
1387
1388  S += "()";
1389  getResultType().getAsStringInternal(S, Policy);
1390}
1391
1392void FunctionProtoType::getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const {
1393  // If needed for precedence reasons, wrap the inner part in grouping parens.
1394  if (!S.empty())
1395    S = "(" + S + ")";
1396
1397  S += "(";
1398  std::string Tmp;
1399  PrintingPolicy ParamPolicy(Policy);
1400  ParamPolicy.SuppressSpecifiers = false;
1401  for (unsigned i = 0, e = getNumArgs(); i != e; ++i) {
1402    if (i) S += ", ";
1403    getArgType(i).getAsStringInternal(Tmp, ParamPolicy);
1404    S += Tmp;
1405    Tmp.clear();
1406  }
1407
1408  if (isVariadic()) {
1409    if (getNumArgs())
1410      S += ", ";
1411    S += "...";
1412  } else if (getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
1413    // Do not emit int() if we have a proto, emit 'int(void)'.
1414    S += "void";
1415  }
1416
1417  S += ")";
1418  getResultType().getAsStringInternal(S, Policy);
1419}
1420
1421
1422void TypedefType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1423  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1424    InnerString = ' ' + InnerString;
1425  InnerString = getDecl()->getIdentifier()->getName() + InnerString;
1426}
1427
1428void TemplateTypeParmType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1429  if (!InnerString.empty())    // Prefix the basic type, e.g. 'parmname X'.
1430    InnerString = ' ' + InnerString;
1431
1432  if (!Name)
1433    InnerString = "type-parameter-" + llvm::utostr_32(Depth) + '-' +
1434      llvm::utostr_32(Index) + InnerString;
1435  else
1436    InnerString = Name->getName() + InnerString;
1437}
1438
1439std::string
1440TemplateSpecializationType::PrintTemplateArgumentList(
1441                                                  const TemplateArgument *Args,
1442                                                  unsigned NumArgs,
1443                                                  const PrintingPolicy &Policy) {
1444  std::string SpecString;
1445  SpecString += '<';
1446  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1447    if (Arg)
1448      SpecString += ", ";
1449
1450    // Print the argument into a string.
1451    std::string ArgString;
1452    switch (Args[Arg].getKind()) {
1453    case TemplateArgument::Null:
1454      assert(false && "Null template argument");
1455      break;
1456
1457    case TemplateArgument::Type:
1458      Args[Arg].getAsType().getAsStringInternal(ArgString, Policy);
1459      break;
1460
1461    case TemplateArgument::Declaration:
1462      ArgString = cast<NamedDecl>(Args[Arg].getAsDecl())->getNameAsString();
1463      break;
1464
1465    case TemplateArgument::Integral:
1466      ArgString = Args[Arg].getAsIntegral()->toString(10, true);
1467      break;
1468
1469    case TemplateArgument::Expression: {
1470      llvm::raw_string_ostream s(ArgString);
1471      Args[Arg].getAsExpr()->printPretty(s, 0, Policy);
1472      break;
1473    }
1474    case TemplateArgument::Pack:
1475      assert(0 && "FIXME: Implement!");
1476      break;
1477    }
1478
1479    // If this is the first argument and its string representation
1480    // begins with the global scope specifier ('::foo'), add a space
1481    // to avoid printing the diagraph '<:'.
1482    if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1483      SpecString += ' ';
1484
1485    SpecString += ArgString;
1486  }
1487
1488  // If the last character of our string is '>', add another space to
1489  // keep the two '>''s separate tokens. We don't *have* to do this in
1490  // C++0x, but it's still good hygiene.
1491  if (SpecString[SpecString.size() - 1] == '>')
1492    SpecString += ' ';
1493
1494  SpecString += '>';
1495
1496  return SpecString;
1497}
1498
1499void
1500TemplateSpecializationType::
1501getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1502  std::string SpecString;
1503
1504  {
1505    llvm::raw_string_ostream OS(SpecString);
1506    Template.print(OS, Policy);
1507  }
1508
1509  SpecString += PrintTemplateArgumentList(getArgs(), getNumArgs(), Policy);
1510  if (InnerString.empty())
1511    InnerString.swap(SpecString);
1512  else
1513    InnerString = SpecString + ' ' + InnerString;
1514}
1515
1516void QualifiedNameType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1517  std::string MyString;
1518
1519  {
1520    llvm::raw_string_ostream OS(MyString);
1521    NNS->print(OS, Policy);
1522  }
1523
1524  std::string TypeStr;
1525  PrintingPolicy InnerPolicy(Policy);
1526  InnerPolicy.SuppressTagKind = true;
1527  NamedType.getAsStringInternal(TypeStr, InnerPolicy);
1528
1529  MyString += TypeStr;
1530  if (InnerString.empty())
1531    InnerString.swap(MyString);
1532  else
1533    InnerString = MyString + ' ' + InnerString;
1534}
1535
1536void TypenameType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1537  std::string MyString;
1538
1539  {
1540    llvm::raw_string_ostream OS(MyString);
1541    OS << "typename ";
1542    NNS->print(OS, Policy);
1543
1544    if (const IdentifierInfo *Ident = getIdentifier())
1545      OS << Ident->getName();
1546    else if (const TemplateSpecializationType *Spec = getTemplateId()) {
1547      Spec->getTemplateName().print(OS, Policy, true);
1548      OS << TemplateSpecializationType::PrintTemplateArgumentList(
1549                                                               Spec->getArgs(),
1550                                                            Spec->getNumArgs(),
1551                                                               Policy);
1552    }
1553  }
1554
1555  if (InnerString.empty())
1556    InnerString.swap(MyString);
1557  else
1558    InnerString = MyString + ' ' + InnerString;
1559}
1560
1561void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID,
1562                                         const ObjCInterfaceDecl *Decl,
1563                                         ObjCProtocolDecl **protocols,
1564                                         unsigned NumProtocols) {
1565  ID.AddPointer(Decl);
1566  for (unsigned i = 0; i != NumProtocols; i++)
1567    ID.AddPointer(protocols[i]);
1568}
1569
1570void ObjCInterfaceType::Profile(llvm::FoldingSetNodeID &ID) {
1571  if (getNumProtocols())
1572    Profile(ID, getDecl(), &Protocols[0], getNumProtocols());
1573  else
1574    Profile(ID, getDecl(), 0, 0);
1575}
1576
1577void ObjCInterfaceType::getAsStringInternal(std::string &InnerString,
1578                                           const PrintingPolicy &Policy) const {
1579  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1580    InnerString = ' ' + InnerString;
1581
1582  std::string ObjCQIString = getDecl()->getNameAsString();
1583  if (getNumProtocols()) {
1584    ObjCQIString += '<';
1585    bool isFirst = true;
1586    for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) {
1587      if (isFirst)
1588        isFirst = false;
1589      else
1590        ObjCQIString += ',';
1591      ObjCQIString += (*I)->getNameAsString();
1592    }
1593    ObjCQIString += '>';
1594  }
1595  InnerString = ObjCQIString + InnerString;
1596}
1597
1598void ObjCObjectPointerType::getAsStringInternal(std::string &InnerString,
1599                                                const PrintingPolicy &Policy) const {
1600  std::string ObjCQIString;
1601
1602  if (isObjCIdType() || isObjCQualifiedIdType())
1603    ObjCQIString = "id";
1604  else if (isObjCClassType())
1605    ObjCQIString = "Class";
1606  else
1607    ObjCQIString = getInterfaceDecl()->getNameAsString();
1608
1609  if (!qual_empty()) {
1610    ObjCQIString += '<';
1611    for (qual_iterator I = qual_begin(), E = qual_end(); I != E; ++I) {
1612      ObjCQIString += (*I)->getNameAsString();
1613      if (I+1 != E)
1614        ObjCQIString += ',';
1615    }
1616    ObjCQIString += '>';
1617  }
1618  if (!isObjCIdType() && !isObjCQualifiedIdType())
1619    ObjCQIString += " *"; // Don't forget the implicit pointer.
1620  else if (!InnerString.empty()) // Prefix the basic type, e.g. 'typedefname X'.
1621    InnerString = ' ' + InnerString;
1622
1623  InnerString = ObjCQIString + InnerString;
1624}
1625
1626void TagType::getAsStringInternal(std::string &InnerString, const PrintingPolicy &Policy) const {
1627  if (Policy.SuppressTag)
1628    return;
1629
1630  if (!InnerString.empty())    // Prefix the basic type, e.g. 'typedefname X'.
1631    InnerString = ' ' + InnerString;
1632
1633  const char *Kind = Policy.SuppressTagKind? 0 : getDecl()->getKindName();
1634  const char *ID;
1635  if (const IdentifierInfo *II = getDecl()->getIdentifier())
1636    ID = II->getName();
1637  else if (TypedefDecl *Typedef = getDecl()->getTypedefForAnonDecl()) {
1638    Kind = 0;
1639    assert(Typedef->getIdentifier() && "Typedef without identifier?");
1640    ID = Typedef->getIdentifier()->getName();
1641  } else
1642    ID = "<anonymous>";
1643
1644  // If this is a class template specialization, print the template
1645  // arguments.
1646  if (ClassTemplateSpecializationDecl *Spec
1647        = dyn_cast<ClassTemplateSpecializationDecl>(getDecl())) {
1648    const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1649    std::string TemplateArgsStr
1650      = TemplateSpecializationType::PrintTemplateArgumentList(
1651                                            TemplateArgs.getFlatArgumentList(),
1652                                            TemplateArgs.flat_size(),
1653                                                              Policy);
1654    InnerString = TemplateArgsStr + InnerString;
1655  }
1656
1657  if (Kind) {
1658    // Compute the full nested-name-specifier for this type. In C,
1659    // this will always be empty.
1660    std::string ContextStr;
1661    for (DeclContext *DC = getDecl()->getDeclContext();
1662         !DC->isTranslationUnit(); DC = DC->getParent()) {
1663      std::string MyPart;
1664      if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
1665        if (NS->getIdentifier())
1666          MyPart = NS->getNameAsString();
1667      } else if (ClassTemplateSpecializationDecl *Spec
1668                   = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1669        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1670        std::string TemplateArgsStr
1671          = TemplateSpecializationType::PrintTemplateArgumentList(
1672                                           TemplateArgs.getFlatArgumentList(),
1673                                           TemplateArgs.flat_size(),
1674                                           Policy);
1675        MyPart = Spec->getIdentifier()->getName() + TemplateArgsStr;
1676      } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
1677        if (TypedefDecl *Typedef = Tag->getTypedefForAnonDecl())
1678          MyPart = Typedef->getIdentifier()->getName();
1679        else if (Tag->getIdentifier())
1680          MyPart = Tag->getIdentifier()->getName();
1681      }
1682
1683      if (!MyPart.empty())
1684        ContextStr = MyPart + "::" + ContextStr;
1685    }
1686
1687    InnerString = std::string(Kind) + " " + ContextStr + ID + InnerString;
1688  } else
1689    InnerString = ID + InnerString;
1690}
1691