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