1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to print types from Clang's type system.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/PrettyPrinter.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/Type.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/SaveAndRestore.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
30 /// \brief RAII object that enables printing of the ARC __strong lifetime
32 class IncludeStrongLifetimeRAII {
33 PrintingPolicy &Policy;
37 explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
38 : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
39 Policy.SuppressStrongLifetime = false;
42 ~IncludeStrongLifetimeRAII() {
43 Policy.SuppressStrongLifetime = Old;
47 class ParamPolicyRAII {
48 PrintingPolicy &Policy;
52 explicit ParamPolicyRAII(PrintingPolicy &Policy)
53 : Policy(Policy), Old(Policy.SuppressSpecifiers) {
54 Policy.SuppressSpecifiers = false;
58 Policy.SuppressSpecifiers = Old;
62 class ElaboratedTypePolicyRAII {
63 PrintingPolicy &Policy;
64 bool SuppressTagKeyword;
68 explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
69 SuppressTagKeyword = Policy.SuppressTagKeyword;
70 SuppressScope = Policy.SuppressScope;
71 Policy.SuppressTagKeyword = true;
72 Policy.SuppressScope = true;
75 ~ElaboratedTypePolicyRAII() {
76 Policy.SuppressTagKeyword = SuppressTagKeyword;
77 Policy.SuppressScope = SuppressScope;
82 PrintingPolicy Policy;
83 bool HasEmptyPlaceHolder;
86 explicit TypePrinter(const PrintingPolicy &Policy)
87 : Policy(Policy), HasEmptyPlaceHolder(false) { }
89 void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
90 StringRef PlaceHolder);
91 void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
93 static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
94 void spaceBeforePlaceHolder(raw_ostream &OS);
95 void printTypeSpec(const NamedDecl *D, raw_ostream &OS);
97 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
98 void printBefore(QualType T, raw_ostream &OS);
99 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
100 void printAfter(QualType T, raw_ostream &OS);
101 void AppendScope(DeclContext *DC, raw_ostream &OS);
102 void printTag(TagDecl *T, raw_ostream &OS);
103 #define ABSTRACT_TYPE(CLASS, PARENT)
104 #define TYPE(CLASS, PARENT) \
105 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
106 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
107 #include "clang/AST/TypeNodes.def"
111 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals) {
112 bool appendSpace = false;
113 if (TypeQuals & Qualifiers::Const) {
117 if (TypeQuals & Qualifiers::Volatile) {
118 if (appendSpace) OS << ' ';
122 if (TypeQuals & Qualifiers::Restrict) {
123 if (appendSpace) OS << ' ';
128 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
129 if (!HasEmptyPlaceHolder)
133 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
134 SplitQualType split = t.split();
135 print(split.Ty, split.Quals, OS, PlaceHolder);
138 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
139 StringRef PlaceHolder) {
145 SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
147 printBefore(T, Quals, OS);
149 printAfter(T, Quals, OS);
152 bool TypePrinter::canPrefixQualifiers(const Type *T,
153 bool &NeedARCStrongQualifier) {
154 // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
155 // so that we get "const int" instead of "int const", but we can't do this if
156 // the type is complex. For example if the type is "int*", we *must* print
157 // "int * const", printing "const int *" is different. Only do this when the
158 // type expands to a simple string.
159 bool CanPrefixQualifiers = false;
160 NeedARCStrongQualifier = false;
161 Type::TypeClass TC = T->getTypeClass();
162 if (const AutoType *AT = dyn_cast<AutoType>(T))
163 TC = AT->desugar()->getTypeClass();
164 if (const SubstTemplateTypeParmType *Subst
165 = dyn_cast<SubstTemplateTypeParmType>(T))
166 TC = Subst->getReplacementType()->getTypeClass();
171 case Type::UnresolvedUsing:
173 case Type::TypeOfExpr:
176 case Type::UnaryTransform:
179 case Type::Elaborated:
180 case Type::TemplateTypeParm:
181 case Type::SubstTemplateTypeParmPack:
182 case Type::TemplateSpecialization:
183 case Type::InjectedClassName:
184 case Type::DependentName:
185 case Type::DependentTemplateSpecialization:
186 case Type::ObjCObject:
187 case Type::ObjCInterface:
189 CanPrefixQualifiers = true;
192 case Type::ObjCObjectPointer:
193 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
194 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
197 case Type::ConstantArray:
198 case Type::IncompleteArray:
199 case Type::VariableArray:
200 case Type::DependentSizedArray:
201 NeedARCStrongQualifier = true;
205 case Type::BlockPointer:
206 case Type::LValueReference:
207 case Type::RValueReference:
208 case Type::MemberPointer:
209 case Type::DependentSizedExtVector:
211 case Type::ExtVector:
212 case Type::FunctionProto:
213 case Type::FunctionNoProto:
215 case Type::Attributed:
216 case Type::PackExpansion:
217 case Type::SubstTemplateTypeParm:
219 CanPrefixQualifiers = false;
223 return CanPrefixQualifiers;
226 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
227 SplitQualType Split = T.split();
229 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
231 Qualifiers Quals = Split.Quals;
232 if (const SubstTemplateTypeParmType *Subst =
233 dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
234 Quals -= QualType(Subst, 0).getQualifiers();
236 printBefore(Split.Ty, Quals, OS);
239 /// \brief Prints the part of the type string before an identifier, e.g. for
240 /// "int foo[10]" it prints "int ".
241 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
242 if (Policy.SuppressSpecifiers && T->isSpecifierType())
245 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
247 // Print qualifiers as appropriate.
249 bool CanPrefixQualifiers = false;
250 bool NeedARCStrongQualifier = false;
251 CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
253 if (CanPrefixQualifiers && !Quals.empty()) {
254 if (NeedARCStrongQualifier) {
255 IncludeStrongLifetimeRAII Strong(Policy);
256 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
258 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
262 bool hasAfterQuals = false;
263 if (!CanPrefixQualifiers && !Quals.empty()) {
264 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
266 HasEmptyPlaceHolder = false;
269 switch (T->getTypeClass()) {
270 #define ABSTRACT_TYPE(CLASS, PARENT)
271 #define TYPE(CLASS, PARENT) case Type::CLASS: \
272 print##CLASS##Before(cast<CLASS##Type>(T), OS); \
274 #include "clang/AST/TypeNodes.def"
278 if (NeedARCStrongQualifier) {
279 IncludeStrongLifetimeRAII Strong(Policy);
280 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
282 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
287 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
288 SplitQualType split = t.split();
289 printAfter(split.Ty, split.Quals, OS);
292 /// \brief Prints the part of the type string after an identifier, e.g. for
293 /// "int foo[10]" it prints "[10]".
294 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
295 switch (T->getTypeClass()) {
296 #define ABSTRACT_TYPE(CLASS, PARENT)
297 #define TYPE(CLASS, PARENT) case Type::CLASS: \
298 print##CLASS##After(cast<CLASS##Type>(T), OS); \
300 #include "clang/AST/TypeNodes.def"
304 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
305 OS << T->getName(Policy);
306 spaceBeforePlaceHolder(OS);
308 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) { }
310 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
312 printBefore(T->getElementType(), OS);
314 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
315 printAfter(T->getElementType(), OS);
318 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
319 IncludeStrongLifetimeRAII Strong(Policy);
320 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
321 printBefore(T->getPointeeType(), OS);
322 // Handle things like 'int (*A)[4];' correctly.
323 // FIXME: this should include vectors, but vectors use attributes I guess.
324 if (isa<ArrayType>(T->getPointeeType()))
328 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
329 IncludeStrongLifetimeRAII Strong(Policy);
330 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
331 // Handle things like 'int (*A)[4];' correctly.
332 // FIXME: this should include vectors, but vectors use attributes I guess.
333 if (isa<ArrayType>(T->getPointeeType()))
335 printAfter(T->getPointeeType(), OS);
338 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
340 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
341 printBefore(T->getPointeeType(), OS);
344 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
346 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
347 printAfter(T->getPointeeType(), OS);
350 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
352 IncludeStrongLifetimeRAII Strong(Policy);
353 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
354 printBefore(T->getPointeeTypeAsWritten(), OS);
355 // Handle things like 'int (&A)[4];' correctly.
356 // FIXME: this should include vectors, but vectors use attributes I guess.
357 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
361 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
363 IncludeStrongLifetimeRAII Strong(Policy);
364 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
365 // Handle things like 'int (&A)[4];' correctly.
366 // FIXME: this should include vectors, but vectors use attributes I guess.
367 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
369 printAfter(T->getPointeeTypeAsWritten(), OS);
372 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
374 IncludeStrongLifetimeRAII Strong(Policy);
375 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
376 printBefore(T->getPointeeTypeAsWritten(), OS);
377 // Handle things like 'int (&&A)[4];' correctly.
378 // FIXME: this should include vectors, but vectors use attributes I guess.
379 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
383 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
385 IncludeStrongLifetimeRAII Strong(Policy);
386 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
387 // Handle things like 'int (&&A)[4];' correctly.
388 // FIXME: this should include vectors, but vectors use attributes I guess.
389 if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
391 printAfter(T->getPointeeTypeAsWritten(), OS);
394 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
396 IncludeStrongLifetimeRAII Strong(Policy);
397 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
398 printBefore(T->getPointeeType(), OS);
399 // Handle things like 'int (Cls::*A)[4];' correctly.
400 // FIXME: this should include vectors, but vectors use attributes I guess.
401 if (isa<ArrayType>(T->getPointeeType()))
404 PrintingPolicy InnerPolicy(Policy);
405 InnerPolicy.SuppressTag = false;
406 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
410 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
412 IncludeStrongLifetimeRAII Strong(Policy);
413 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
414 // Handle things like 'int (Cls::*A)[4];' correctly.
415 // FIXME: this should include vectors, but vectors use attributes I guess.
416 if (isa<ArrayType>(T->getPointeeType()))
418 printAfter(T->getPointeeType(), OS);
421 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
423 IncludeStrongLifetimeRAII Strong(Policy);
424 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
425 printBefore(T->getElementType(), OS);
427 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
429 OS << '[' << T->getSize().getZExtValue() << ']';
430 printAfter(T->getElementType(), OS);
433 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
435 IncludeStrongLifetimeRAII Strong(Policy);
436 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
437 printBefore(T->getElementType(), OS);
439 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
442 printAfter(T->getElementType(), OS);
445 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
447 IncludeStrongLifetimeRAII Strong(Policy);
448 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
449 printBefore(T->getElementType(), OS);
451 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
454 if (T->getIndexTypeQualifiers().hasQualifiers()) {
455 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers());
459 if (T->getSizeModifier() == VariableArrayType::Static)
461 else if (T->getSizeModifier() == VariableArrayType::Star)
464 if (T->getSizeExpr())
465 T->getSizeExpr()->printPretty(OS, 0, Policy);
468 printAfter(T->getElementType(), OS);
471 void TypePrinter::printDependentSizedArrayBefore(
472 const DependentSizedArrayType *T,
474 IncludeStrongLifetimeRAII Strong(Policy);
475 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
476 printBefore(T->getElementType(), OS);
478 void TypePrinter::printDependentSizedArrayAfter(
479 const DependentSizedArrayType *T,
482 if (T->getSizeExpr())
483 T->getSizeExpr()->printPretty(OS, 0, Policy);
485 printAfter(T->getElementType(), OS);
488 void TypePrinter::printDependentSizedExtVectorBefore(
489 const DependentSizedExtVectorType *T,
491 printBefore(T->getElementType(), OS);
493 void TypePrinter::printDependentSizedExtVectorAfter(
494 const DependentSizedExtVectorType *T,
496 OS << " __attribute__((ext_vector_type(";
497 if (T->getSizeExpr())
498 T->getSizeExpr()->printPretty(OS, 0, Policy);
500 printAfter(T->getElementType(), OS);
503 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
504 switch (T->getVectorKind()) {
505 case VectorType::AltiVecPixel:
506 OS << "__vector __pixel ";
508 case VectorType::AltiVecBool:
509 OS << "__vector __bool ";
510 printBefore(T->getElementType(), OS);
512 case VectorType::AltiVecVector:
514 printBefore(T->getElementType(), OS);
516 case VectorType::NeonVector:
517 OS << "__attribute__((neon_vector_type("
518 << T->getNumElements() << "))) ";
519 printBefore(T->getElementType(), OS);
521 case VectorType::NeonPolyVector:
522 OS << "__attribute__((neon_polyvector_type(" <<
523 T->getNumElements() << "))) ";
524 printBefore(T->getElementType(), OS);
526 case VectorType::GenericVector: {
527 // FIXME: We prefer to print the size directly here, but have no way
528 // to get the size of the type.
529 OS << "__attribute__((__vector_size__("
530 << T->getNumElements()
532 print(T->getElementType(), OS, StringRef());
534 printBefore(T->getElementType(), OS);
539 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
540 printAfter(T->getElementType(), OS);
543 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
545 printBefore(T->getElementType(), OS);
547 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
548 printAfter(T->getElementType(), OS);
549 OS << " __attribute__((ext_vector_type(";
550 OS << T->getNumElements();
555 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
556 const PrintingPolicy &Policy)
559 if (hasDynamicExceptionSpec()) {
561 if (getExceptionSpecType() == EST_MSAny)
564 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
568 OS << getExceptionType(I).stream(Policy);
571 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
573 if (getExceptionSpecType() == EST_ComputedNoexcept) {
575 getNoexceptExpr()->printPretty(OS, 0, Policy);
581 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
583 if (T->hasTrailingReturn()) {
585 if (!HasEmptyPlaceHolder)
588 // If needed for precedence reasons, wrap the inner part in grouping parens.
589 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
590 printBefore(T->getResultType(), OS);
591 if (!PrevPHIsEmpty.get())
596 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
598 // If needed for precedence reasons, wrap the inner part in grouping parens.
599 if (!HasEmptyPlaceHolder)
601 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
605 ParamPolicyRAII ParamPolicy(Policy);
606 for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
608 print(T->getArgType(i), OS, StringRef());
612 if (T->isVariadic()) {
616 } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
617 // Do not emit int() if we have a proto, emit 'int(void)'.
623 FunctionType::ExtInfo Info = T->getExtInfo();
624 switch(Info.getCC()) {
625 case CC_Default: break;
627 OS << " __attribute__((cdecl))";
630 OS << " __attribute__((stdcall))";
633 OS << " __attribute__((fastcall))";
636 OS << " __attribute__((thiscall))";
639 OS << " __attribute__((pascal))";
642 OS << " __attribute__((pcs(\"aapcs\")))";
645 OS << " __attribute__((pcs(\"aapcs-vfp\")))";
648 OS << " __attribute__((pnaclcall))";
650 case CC_IntelOclBicc:
651 OS << " __attribute__((intel_ocl_bicc))";
654 OS << " __attribute__((ms_abi))";
657 OS << " __attribute__((sysv_abi))";
660 if (Info.getNoReturn())
661 OS << " __attribute__((noreturn))";
662 if (Info.getRegParm())
663 OS << " __attribute__((regparm ("
664 << Info.getRegParm() << ")))";
666 if (unsigned quals = T->getTypeQuals()) {
668 AppendTypeQualList(OS, quals);
671 switch (T->getRefQualifier()) {
683 T->printExceptionSpecification(OS, Policy);
685 if (T->hasTrailingReturn()) {
687 print(T->getResultType(), OS, StringRef());
689 printAfter(T->getResultType(), OS);
692 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
694 // If needed for precedence reasons, wrap the inner part in grouping parens.
695 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
696 printBefore(T->getResultType(), OS);
697 if (!PrevPHIsEmpty.get())
700 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
702 // If needed for precedence reasons, wrap the inner part in grouping parens.
703 if (!HasEmptyPlaceHolder)
705 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
708 if (T->getNoReturnAttr())
709 OS << " __attribute__((noreturn))";
710 printAfter(T->getResultType(), OS);
713 void TypePrinter::printTypeSpec(const NamedDecl *D, raw_ostream &OS) {
714 IdentifierInfo *II = D->getIdentifier();
716 spaceBeforePlaceHolder(OS);
719 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
721 printTypeSpec(T->getDecl(), OS);
723 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
726 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
727 printTypeSpec(T->getDecl(), OS);
729 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) { }
731 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
734 T->getUnderlyingExpr()->printPretty(OS, 0, Policy);
735 spaceBeforePlaceHolder(OS);
737 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
740 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
742 print(T->getUnderlyingType(), OS, StringRef());
744 spaceBeforePlaceHolder(OS);
746 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) { }
748 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
750 T->getUnderlyingExpr()->printPretty(OS, 0, Policy);
752 spaceBeforePlaceHolder(OS);
754 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) { }
756 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
758 IncludeStrongLifetimeRAII Strong(Policy);
760 switch (T->getUTTKind()) {
761 case UnaryTransformType::EnumUnderlyingType:
762 OS << "__underlying_type(";
763 print(T->getBaseType(), OS, StringRef());
765 spaceBeforePlaceHolder(OS);
769 printBefore(T->getBaseType(), OS);
771 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
773 IncludeStrongLifetimeRAII Strong(Policy);
775 switch (T->getUTTKind()) {
776 case UnaryTransformType::EnumUnderlyingType:
780 printAfter(T->getBaseType(), OS);
783 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
784 // If the type has been deduced, do not print 'auto'.
785 if (!T->getDeducedType().isNull()) {
786 printBefore(T->getDeducedType(), OS);
788 OS << (T->isDecltypeAuto() ? "decltype(auto)" : "auto");
789 spaceBeforePlaceHolder(OS);
792 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
793 // If the type has been deduced, do not print 'auto'.
794 if (!T->getDeducedType().isNull())
795 printAfter(T->getDeducedType(), OS);
798 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
799 IncludeStrongLifetimeRAII Strong(Policy);
802 print(T->getValueType(), OS, StringRef());
804 spaceBeforePlaceHolder(OS);
806 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) { }
808 /// Appends the given scope to the end of a string.
809 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
810 if (DC->isTranslationUnit()) return;
811 if (DC->isFunctionOrMethod()) return;
812 AppendScope(DC->getParent(), OS);
814 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
815 if (Policy.SuppressUnwrittenScope &&
816 (NS->isAnonymousNamespace() || NS->isInline()))
818 if (NS->getIdentifier())
819 OS << NS->getName() << "::";
821 OS << "<anonymous>::";
822 } else if (ClassTemplateSpecializationDecl *Spec
823 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
824 IncludeStrongLifetimeRAII Strong(Policy);
825 OS << Spec->getIdentifier()->getName();
826 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
827 TemplateSpecializationType::PrintTemplateArgumentList(OS,
832 } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
833 if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
834 OS << Typedef->getIdentifier()->getName() << "::";
835 else if (Tag->getIdentifier())
836 OS << Tag->getIdentifier()->getName() << "::";
842 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
843 if (Policy.SuppressTag)
846 bool HasKindDecoration = false;
848 // bool SuppressTagKeyword
849 // = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
851 // We don't print tags unless this is an elaborated type.
852 // In C, we just assume every RecordType is an elaborated type.
853 if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
854 D->getTypedefNameForAnonDecl())) {
855 HasKindDecoration = true;
856 OS << D->getKindName();
860 // Compute the full nested-name-specifier for this type.
861 // In C, this will always be empty except when the type
862 // being printed is anonymous within other Record.
863 if (!Policy.SuppressScope)
864 AppendScope(D->getDeclContext(), OS);
866 if (const IdentifierInfo *II = D->getIdentifier())
868 else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
869 assert(Typedef->getIdentifier() && "Typedef without identifier?");
870 OS << Typedef->getIdentifier()->getName();
872 // Make an unambiguous representation for anonymous types, e.g.
873 // <anonymous enum at /usr/include/string.h:120:9>
875 if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
877 HasKindDecoration = true;
882 if (Policy.AnonymousTagLocations) {
883 // Suppress the redundant tag keyword if we just printed one.
884 // We don't have to worry about ElaboratedTypes here because you can't
885 // refer to an anonymous type with one.
886 if (!HasKindDecoration)
887 OS << " " << D->getKindName();
889 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
891 if (PLoc.isValid()) {
892 OS << " at " << PLoc.getFilename()
893 << ':' << PLoc.getLine()
894 << ':' << PLoc.getColumn();
901 // If this is a class template specialization, print the template
903 if (ClassTemplateSpecializationDecl *Spec
904 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
905 const TemplateArgument *Args;
907 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
908 const TemplateSpecializationType *TST =
909 cast<TemplateSpecializationType>(TAW->getType());
910 Args = TST->getArgs();
911 NumArgs = TST->getNumArgs();
913 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
914 Args = TemplateArgs.data();
915 NumArgs = TemplateArgs.size();
917 IncludeStrongLifetimeRAII Strong(Policy);
918 TemplateSpecializationType::PrintTemplateArgumentList(OS,
923 spaceBeforePlaceHolder(OS);
926 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
927 printTag(T->getDecl(), OS);
929 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) { }
931 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
932 printTag(T->getDecl(), OS);
934 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) { }
936 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
938 if (IdentifierInfo *Id = T->getIdentifier())
941 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
942 spaceBeforePlaceHolder(OS);
944 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
947 void TypePrinter::printSubstTemplateTypeParmBefore(
948 const SubstTemplateTypeParmType *T,
950 IncludeStrongLifetimeRAII Strong(Policy);
951 printBefore(T->getReplacementType(), OS);
953 void TypePrinter::printSubstTemplateTypeParmAfter(
954 const SubstTemplateTypeParmType *T,
956 IncludeStrongLifetimeRAII Strong(Policy);
957 printAfter(T->getReplacementType(), OS);
960 void TypePrinter::printSubstTemplateTypeParmPackBefore(
961 const SubstTemplateTypeParmPackType *T,
963 IncludeStrongLifetimeRAII Strong(Policy);
964 printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
966 void TypePrinter::printSubstTemplateTypeParmPackAfter(
967 const SubstTemplateTypeParmPackType *T,
969 IncludeStrongLifetimeRAII Strong(Policy);
970 printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
973 void TypePrinter::printTemplateSpecializationBefore(
974 const TemplateSpecializationType *T,
976 IncludeStrongLifetimeRAII Strong(Policy);
977 T->getTemplateName().print(OS, Policy);
979 TemplateSpecializationType::PrintTemplateArgumentList(OS,
983 spaceBeforePlaceHolder(OS);
985 void TypePrinter::printTemplateSpecializationAfter(
986 const TemplateSpecializationType *T,
989 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
991 printTemplateSpecializationBefore(T->getInjectedTST(), OS);
993 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
996 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
998 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
999 if (T->getKeyword() != ETK_None)
1001 NestedNameSpecifier* Qualifier = T->getQualifier();
1003 Qualifier->print(OS, Policy);
1005 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1006 printBefore(T->getNamedType(), OS);
1008 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1010 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1011 printAfter(T->getNamedType(), OS);
1014 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1015 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1016 printBefore(T->getInnerType(), OS);
1019 printBefore(T->getInnerType(), OS);
1021 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1022 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1024 printAfter(T->getInnerType(), OS);
1026 printAfter(T->getInnerType(), OS);
1029 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1031 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1032 if (T->getKeyword() != ETK_None)
1035 T->getQualifier()->print(OS, Policy);
1037 OS << T->getIdentifier()->getName();
1038 spaceBeforePlaceHolder(OS);
1040 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1041 raw_ostream &OS) { }
1043 void TypePrinter::printDependentTemplateSpecializationBefore(
1044 const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1045 IncludeStrongLifetimeRAII Strong(Policy);
1047 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1048 if (T->getKeyword() != ETK_None)
1051 if (T->getQualifier())
1052 T->getQualifier()->print(OS, Policy);
1053 OS << T->getIdentifier()->getName();
1054 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1058 spaceBeforePlaceHolder(OS);
1060 void TypePrinter::printDependentTemplateSpecializationAfter(
1061 const DependentTemplateSpecializationType *T, raw_ostream &OS) { }
1063 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1065 printBefore(T->getPattern(), OS);
1067 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1069 printAfter(T->getPattern(), OS);
1073 void TypePrinter::printAttributedBefore(const AttributedType *T,
1075 // Prefer the macro forms of the GC and ownership qualifiers.
1076 if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1077 T->getAttrKind() == AttributedType::attr_objc_ownership)
1078 return printBefore(T->getEquivalentType(), OS);
1080 printBefore(T->getModifiedType(), OS);
1083 void TypePrinter::printAttributedAfter(const AttributedType *T,
1085 // Prefer the macro forms of the GC and ownership qualifiers.
1086 if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1087 T->getAttrKind() == AttributedType::attr_objc_ownership)
1088 return printAfter(T->getEquivalentType(), OS);
1090 // TODO: not all attributes are GCC-style attributes.
1091 OS << " __attribute__((";
1092 switch (T->getAttrKind()) {
1093 case AttributedType::attr_address_space:
1094 OS << "address_space(";
1095 OS << T->getEquivalentType().getAddressSpace();
1099 case AttributedType::attr_vector_size: {
1100 OS << "__vector_size__(";
1101 if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
1102 OS << vector->getNumElements();
1104 print(vector->getElementType(), OS, StringRef());
1111 case AttributedType::attr_neon_vector_type:
1112 case AttributedType::attr_neon_polyvector_type: {
1113 if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
1114 OS << "neon_vector_type(";
1116 OS << "neon_polyvector_type(";
1117 const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
1118 OS << vector->getNumElements();
1123 case AttributedType::attr_regparm: {
1125 QualType t = T->getEquivalentType();
1126 while (!t->isFunctionType())
1127 t = t->getPointeeType();
1128 OS << t->getAs<FunctionType>()->getRegParmType();
1133 case AttributedType::attr_objc_gc: {
1136 QualType tmp = T->getEquivalentType();
1137 while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
1138 QualType next = tmp->getPointeeType();
1139 if (next == tmp) break;
1143 if (tmp.isObjCGCWeak())
1151 case AttributedType::attr_objc_ownership:
1152 OS << "objc_ownership(";
1153 switch (T->getEquivalentType().getObjCLifetime()) {
1154 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
1155 case Qualifiers::OCL_ExplicitNone: OS << "none"; break;
1156 case Qualifiers::OCL_Strong: OS << "strong"; break;
1157 case Qualifiers::OCL_Weak: OS << "weak"; break;
1158 case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break;
1163 case AttributedType::attr_noreturn: OS << "noreturn"; break;
1164 case AttributedType::attr_cdecl: OS << "cdecl"; break;
1165 case AttributedType::attr_fastcall: OS << "fastcall"; break;
1166 case AttributedType::attr_stdcall: OS << "stdcall"; break;
1167 case AttributedType::attr_thiscall: OS << "thiscall"; break;
1168 case AttributedType::attr_pascal: OS << "pascal"; break;
1169 case AttributedType::attr_ms_abi: OS << "ms_abi"; break;
1170 case AttributedType::attr_sysv_abi: OS << "sysv_abi"; break;
1171 case AttributedType::attr_pcs: {
1173 QualType t = T->getEquivalentType();
1174 while (!t->isFunctionType())
1175 t = t->getPointeeType();
1176 OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1177 "\"aapcs\"" : "\"aapcs-vfp\"");
1181 case AttributedType::attr_pnaclcall: OS << "pnaclcall"; break;
1182 case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
1187 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1189 OS << T->getDecl()->getName();
1190 spaceBeforePlaceHolder(OS);
1192 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1193 raw_ostream &OS) { }
1195 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1197 if (T->qual_empty())
1198 return printBefore(T->getBaseType(), OS);
1200 print(T->getBaseType(), OS, StringRef());
1202 bool isFirst = true;
1203 for (ObjCObjectType::qual_iterator
1204 I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
1209 OS << (*I)->getName();
1212 spaceBeforePlaceHolder(OS);
1214 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1216 if (T->qual_empty())
1217 return printAfter(T->getBaseType(), OS);
1220 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1222 T->getPointeeType().getLocalQualifiers().print(OS, Policy,
1223 /*appendSpaceIfNonEmpty=*/true);
1225 if (T->isObjCIdType() || T->isObjCQualifiedIdType())
1227 else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
1229 else if (T->isObjCSelType())
1232 OS << T->getInterfaceDecl()->getName();
1234 if (!T->qual_empty()) {
1236 for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
1239 OS << (*I)->getName();
1246 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType()) {
1247 OS << " *"; // Don't forget the implicit pointer.
1249 spaceBeforePlaceHolder(OS);
1252 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1253 raw_ostream &OS) { }
1255 void TemplateSpecializationType::
1256 PrintTemplateArgumentList(raw_ostream &OS,
1257 const TemplateArgumentListInfo &Args,
1258 const PrintingPolicy &Policy) {
1259 return PrintTemplateArgumentList(OS,
1260 Args.getArgumentArray(),
1266 TemplateSpecializationType::PrintTemplateArgumentList(
1268 const TemplateArgument *Args,
1270 const PrintingPolicy &Policy,
1271 bool SkipBrackets) {
1275 bool needSpace = false;
1276 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1280 // Print the argument into a string.
1281 SmallString<128> Buf;
1282 llvm::raw_svector_ostream ArgOS(Buf);
1283 if (Args[Arg].getKind() == TemplateArgument::Pack) {
1284 PrintTemplateArgumentList(ArgOS,
1285 Args[Arg].pack_begin(),
1286 Args[Arg].pack_size(),
1289 Args[Arg].print(Policy, ArgOS);
1291 StringRef ArgString = ArgOS.str();
1293 // If this is the first argument and its string representation
1294 // begins with the global scope specifier ('::foo'), add a space
1295 // to avoid printing the diagraph '<:'.
1296 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1301 needSpace = (!ArgString.empty() && ArgString.back() == '>');
1304 // If the last character of our string is '>', add another space to
1305 // keep the two '>''s separate tokens. We don't *have* to do this in
1306 // C++0x, but it's still good hygiene.
1314 // Sadly, repeat all that with TemplateArgLoc.
1315 void TemplateSpecializationType::
1316 PrintTemplateArgumentList(raw_ostream &OS,
1317 const TemplateArgumentLoc *Args, unsigned NumArgs,
1318 const PrintingPolicy &Policy) {
1321 bool needSpace = false;
1322 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1326 // Print the argument into a string.
1327 SmallString<128> Buf;
1328 llvm::raw_svector_ostream ArgOS(Buf);
1329 if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
1330 PrintTemplateArgumentList(ArgOS,
1331 Args[Arg].getArgument().pack_begin(),
1332 Args[Arg].getArgument().pack_size(),
1335 Args[Arg].getArgument().print(Policy, ArgOS);
1337 StringRef ArgString = ArgOS.str();
1339 // If this is the first argument and its string representation
1340 // begins with the global scope specifier ('::foo'), add a space
1341 // to avoid printing the diagraph '<:'.
1342 if (!Arg && !ArgString.empty() && ArgString[0] == ':')
1347 needSpace = (!ArgString.empty() && ArgString.back() == '>');
1350 // If the last character of our string is '>', add another space to
1351 // keep the two '>''s separate tokens. We don't *have* to do this in
1352 // C++0x, but it's still good hygiene.
1359 void QualType::dump(const char *msg) const {
1361 llvm::errs() << msg << ": ";
1363 print(llvm::errs(), PrintingPolicy(LO), "identifier");
1364 llvm::errs() << '\n';
1366 void QualType::dump() const {
1370 void Type::dump() const {
1371 QualType(this, 0).dump();
1374 std::string Qualifiers::getAsString() const {
1376 return getAsString(PrintingPolicy(LO));
1379 // Appends qualifiers to the given string, separated by spaces. Will
1380 // prefix a space if the string is non-empty. Will not append a final
1382 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1383 SmallString<64> Buf;
1384 llvm::raw_svector_ostream StrOS(Buf);
1385 print(StrOS, Policy);
1389 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1390 if (getCVRQualifiers())
1393 if (getAddressSpace())
1396 if (getObjCGCAttr())
1399 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1400 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1406 // Appends qualifiers to the given string, separated by spaces. Will
1407 // prefix a space if the string is non-empty. Will not append a final
1409 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1410 bool appendSpaceIfNonEmpty) const {
1411 bool addSpace = false;
1413 unsigned quals = getCVRQualifiers();
1415 AppendTypeQualList(OS, quals);
1418 if (unsigned addrspace = getAddressSpace()) {
1422 switch (addrspace) {
1423 case LangAS::opencl_global:
1426 case LangAS::opencl_local:
1429 case LangAS::opencl_constant:
1433 OS << "__attribute__((address_space(";
1438 if (Qualifiers::GC gc = getObjCGCAttr()) {
1442 if (gc == Qualifiers::Weak)
1447 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1448 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1455 case Qualifiers::OCL_None: llvm_unreachable("none but true");
1456 case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1457 case Qualifiers::OCL_Strong:
1458 if (!Policy.SuppressStrongLifetime)
1462 case Qualifiers::OCL_Weak: OS << "__weak"; break;
1463 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1467 if (appendSpaceIfNonEmpty && addSpace)
1471 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1473 getAsStringInternal(S, Policy);
1477 std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
1479 LangOptions options;
1480 getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
1484 void QualType::print(const Type *ty, Qualifiers qs,
1485 raw_ostream &OS, const PrintingPolicy &policy,
1486 const Twine &PlaceHolder) {
1487 SmallString<128> PHBuf;
1488 StringRef PH = PlaceHolder.toStringRef(PHBuf);
1490 TypePrinter(policy).print(ty, qs, OS, PH);
1493 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1494 std::string &buffer,
1495 const PrintingPolicy &policy) {
1496 SmallString<256> Buf;
1497 llvm::raw_svector_ostream StrOS(Buf);
1498 TypePrinter(policy).print(ty, qs, StrOS, buffer);
1499 std::string str = StrOS.str();