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