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