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