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/DeclBase.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/TemplateName.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/AddressSpaces.h"
27 #include "clang/Basic/ExceptionSpecificationType.h"
28 #include "clang/Basic/IdentifierTable.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "clang/Basic/SourceLocation.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/Specifiers.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/SaveAndRestore.h"
42 #include "llvm/Support/raw_ostream.h"
46 using namespace clang;
50 /// RAII object that enables printing of the ARC __strong lifetime
52 class IncludeStrongLifetimeRAII {
53 PrintingPolicy &Policy;
57 explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
58 : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
59 if (!Policy.SuppressLifetimeQualifiers)
60 Policy.SuppressStrongLifetime = false;
63 ~IncludeStrongLifetimeRAII() {
64 Policy.SuppressStrongLifetime = Old;
68 class ParamPolicyRAII {
69 PrintingPolicy &Policy;
73 explicit ParamPolicyRAII(PrintingPolicy &Policy)
74 : Policy(Policy), Old(Policy.SuppressSpecifiers) {
75 Policy.SuppressSpecifiers = false;
79 Policy.SuppressSpecifiers = Old;
83 class ElaboratedTypePolicyRAII {
84 PrintingPolicy &Policy;
85 bool SuppressTagKeyword;
89 explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
90 SuppressTagKeyword = Policy.SuppressTagKeyword;
91 SuppressScope = Policy.SuppressScope;
92 Policy.SuppressTagKeyword = true;
93 Policy.SuppressScope = true;
96 ~ElaboratedTypePolicyRAII() {
97 Policy.SuppressTagKeyword = SuppressTagKeyword;
98 Policy.SuppressScope = SuppressScope;
103 PrintingPolicy Policy;
104 unsigned Indentation;
105 bool HasEmptyPlaceHolder = false;
106 bool InsideCCAttribute = false;
109 explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
110 : Policy(Policy), Indentation(Indentation) {}
112 void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
113 StringRef PlaceHolder);
114 void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
116 static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
117 void spaceBeforePlaceHolder(raw_ostream &OS);
118 void printTypeSpec(NamedDecl *D, raw_ostream &OS);
120 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
121 void printBefore(QualType T, raw_ostream &OS);
122 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
123 void printAfter(QualType T, raw_ostream &OS);
124 void AppendScope(DeclContext *DC, raw_ostream &OS);
125 void printTag(TagDecl *T, raw_ostream &OS);
126 void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
127 #define ABSTRACT_TYPE(CLASS, PARENT)
128 #define TYPE(CLASS, PARENT) \
129 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
130 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
131 #include "clang/AST/TypeNodes.def"
136 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
137 bool HasRestrictKeyword) {
138 bool appendSpace = false;
139 if (TypeQuals & Qualifiers::Const) {
143 if (TypeQuals & Qualifiers::Volatile) {
144 if (appendSpace) OS << ' ';
148 if (TypeQuals & Qualifiers::Restrict) {
149 if (appendSpace) OS << ' ';
150 if (HasRestrictKeyword) {
158 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
159 if (!HasEmptyPlaceHolder)
163 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
164 SplitQualType split = t.split();
165 print(split.Ty, split.Quals, OS, PlaceHolder);
168 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
169 StringRef PlaceHolder) {
175 SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
177 printBefore(T, Quals, OS);
179 printAfter(T, Quals, OS);
182 bool TypePrinter::canPrefixQualifiers(const Type *T,
183 bool &NeedARCStrongQualifier) {
184 // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
185 // so that we get "const int" instead of "int const", but we can't do this if
186 // the type is complex. For example if the type is "int*", we *must* print
187 // "int * const", printing "const int *" is different. Only do this when the
188 // type expands to a simple string.
189 bool CanPrefixQualifiers = false;
190 NeedARCStrongQualifier = false;
191 Type::TypeClass TC = T->getTypeClass();
192 if (const auto *AT = dyn_cast<AutoType>(T))
193 TC = AT->desugar()->getTypeClass();
194 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T))
195 TC = Subst->getReplacementType()->getTypeClass();
201 case Type::UnresolvedUsing:
203 case Type::TypeOfExpr:
206 case Type::UnaryTransform:
209 case Type::Elaborated:
210 case Type::TemplateTypeParm:
211 case Type::SubstTemplateTypeParmPack:
212 case Type::DeducedTemplateSpecialization:
213 case Type::TemplateSpecialization:
214 case Type::InjectedClassName:
215 case Type::DependentName:
216 case Type::DependentTemplateSpecialization:
217 case Type::ObjCObject:
218 case Type::ObjCTypeParam:
219 case Type::ObjCInterface:
222 CanPrefixQualifiers = true;
225 case Type::ObjCObjectPointer:
226 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
227 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
230 case Type::ConstantArray:
231 case Type::IncompleteArray:
232 case Type::VariableArray:
233 case Type::DependentSizedArray:
234 NeedARCStrongQualifier = true;
240 case Type::BlockPointer:
241 case Type::LValueReference:
242 case Type::RValueReference:
243 case Type::MemberPointer:
244 case Type::DependentAddressSpace:
245 case Type::DependentVector:
246 case Type::DependentSizedExtVector:
248 case Type::ExtVector:
249 case Type::FunctionProto:
250 case Type::FunctionNoProto:
252 case Type::Attributed:
253 case Type::PackExpansion:
254 case Type::SubstTemplateTypeParm:
255 CanPrefixQualifiers = false;
259 return CanPrefixQualifiers;
262 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
263 SplitQualType Split = T.split();
265 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
267 Qualifiers Quals = Split.Quals;
268 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
269 Quals -= QualType(Subst, 0).getQualifiers();
271 printBefore(Split.Ty, Quals, OS);
274 /// Prints the part of the type string before an identifier, e.g. for
275 /// "int foo[10]" it prints "int ".
276 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
277 if (Policy.SuppressSpecifiers && T->isSpecifierType())
280 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
282 // Print qualifiers as appropriate.
284 bool CanPrefixQualifiers = false;
285 bool NeedARCStrongQualifier = false;
286 CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
288 if (CanPrefixQualifiers && !Quals.empty()) {
289 if (NeedARCStrongQualifier) {
290 IncludeStrongLifetimeRAII Strong(Policy);
291 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
293 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
297 bool hasAfterQuals = false;
298 if (!CanPrefixQualifiers && !Quals.empty()) {
299 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
301 HasEmptyPlaceHolder = false;
304 switch (T->getTypeClass()) {
305 #define ABSTRACT_TYPE(CLASS, PARENT)
306 #define TYPE(CLASS, PARENT) case Type::CLASS: \
307 print##CLASS##Before(cast<CLASS##Type>(T), OS); \
309 #include "clang/AST/TypeNodes.def"
313 if (NeedARCStrongQualifier) {
314 IncludeStrongLifetimeRAII Strong(Policy);
315 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
317 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
322 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
323 SplitQualType split = t.split();
324 printAfter(split.Ty, split.Quals, OS);
327 /// Prints the part of the type string after an identifier, e.g. for
328 /// "int foo[10]" it prints "[10]".
329 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
330 switch (T->getTypeClass()) {
331 #define ABSTRACT_TYPE(CLASS, PARENT)
332 #define TYPE(CLASS, PARENT) case Type::CLASS: \
333 print##CLASS##After(cast<CLASS##Type>(T), OS); \
335 #include "clang/AST/TypeNodes.def"
339 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
340 OS << T->getName(Policy);
341 spaceBeforePlaceHolder(OS);
344 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {}
346 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
348 printBefore(T->getElementType(), OS);
351 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
352 printAfter(T->getElementType(), OS);
355 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
356 IncludeStrongLifetimeRAII Strong(Policy);
357 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
358 printBefore(T->getPointeeType(), OS);
359 // Handle things like 'int (*A)[4];' correctly.
360 // FIXME: this should include vectors, but vectors use attributes I guess.
361 if (isa<ArrayType>(T->getPointeeType()))
366 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
367 IncludeStrongLifetimeRAII Strong(Policy);
368 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
369 // Handle things like 'int (*A)[4];' correctly.
370 // FIXME: this should include vectors, but vectors use attributes I guess.
371 if (isa<ArrayType>(T->getPointeeType()))
373 printAfter(T->getPointeeType(), OS);
376 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
378 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
379 printBefore(T->getPointeeType(), OS);
383 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
385 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
386 printAfter(T->getPointeeType(), OS);
389 // When printing a reference, the referenced type might also be a reference.
390 // If so, we want to skip that before printing the inner type.
391 static QualType skipTopLevelReferences(QualType T) {
392 if (auto *Ref = T->getAs<ReferenceType>())
393 return skipTopLevelReferences(Ref->getPointeeTypeAsWritten());
397 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
399 IncludeStrongLifetimeRAII Strong(Policy);
400 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
401 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
402 printBefore(Inner, OS);
403 // Handle things like 'int (&A)[4];' correctly.
404 // FIXME: this should include vectors, but vectors use attributes I guess.
405 if (isa<ArrayType>(Inner))
410 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
412 IncludeStrongLifetimeRAII Strong(Policy);
413 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
414 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
415 // Handle things like 'int (&A)[4];' correctly.
416 // FIXME: this should include vectors, but vectors use attributes I guess.
417 if (isa<ArrayType>(Inner))
419 printAfter(Inner, OS);
422 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
424 IncludeStrongLifetimeRAII Strong(Policy);
425 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
426 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
427 printBefore(Inner, OS);
428 // Handle things like 'int (&&A)[4];' correctly.
429 // FIXME: this should include vectors, but vectors use attributes I guess.
430 if (isa<ArrayType>(Inner))
435 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
437 IncludeStrongLifetimeRAII Strong(Policy);
438 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
439 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
440 // Handle things like 'int (&&A)[4];' correctly.
441 // FIXME: this should include vectors, but vectors use attributes I guess.
442 if (isa<ArrayType>(Inner))
444 printAfter(Inner, OS);
447 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
449 IncludeStrongLifetimeRAII Strong(Policy);
450 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
451 printBefore(T->getPointeeType(), OS);
452 // Handle things like 'int (Cls::*A)[4];' correctly.
453 // FIXME: this should include vectors, but vectors use attributes I guess.
454 if (isa<ArrayType>(T->getPointeeType()))
457 PrintingPolicy InnerPolicy(Policy);
458 InnerPolicy.IncludeTagDefinition = false;
459 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
464 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
466 IncludeStrongLifetimeRAII Strong(Policy);
467 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
468 // Handle things like 'int (Cls::*A)[4];' correctly.
469 // FIXME: this should include vectors, but vectors use attributes I guess.
470 if (isa<ArrayType>(T->getPointeeType()))
472 printAfter(T->getPointeeType(), OS);
475 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
477 IncludeStrongLifetimeRAII Strong(Policy);
478 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
479 printBefore(T->getElementType(), OS);
482 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
485 if (T->getIndexTypeQualifiers().hasQualifiers()) {
486 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
491 if (T->getSizeModifier() == ArrayType::Static)
494 OS << T->getSize().getZExtValue() << ']';
495 printAfter(T->getElementType(), OS);
498 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
500 IncludeStrongLifetimeRAII Strong(Policy);
501 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
502 printBefore(T->getElementType(), OS);
505 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
508 printAfter(T->getElementType(), OS);
511 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
513 IncludeStrongLifetimeRAII Strong(Policy);
514 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
515 printBefore(T->getElementType(), OS);
518 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
521 if (T->getIndexTypeQualifiers().hasQualifiers()) {
522 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
526 if (T->getSizeModifier() == VariableArrayType::Static)
528 else if (T->getSizeModifier() == VariableArrayType::Star)
531 if (T->getSizeExpr())
532 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
535 printAfter(T->getElementType(), OS);
538 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
539 // Print the adjusted representation, otherwise the adjustment will be
541 printBefore(T->getAdjustedType(), OS);
544 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
545 printAfter(T->getAdjustedType(), OS);
548 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
549 // Print as though it's a pointer.
550 printAdjustedBefore(T, OS);
553 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
554 printAdjustedAfter(T, OS);
557 void TypePrinter::printDependentSizedArrayBefore(
558 const DependentSizedArrayType *T,
560 IncludeStrongLifetimeRAII Strong(Policy);
561 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
562 printBefore(T->getElementType(), OS);
565 void TypePrinter::printDependentSizedArrayAfter(
566 const DependentSizedArrayType *T,
569 if (T->getSizeExpr())
570 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
572 printAfter(T->getElementType(), OS);
575 void TypePrinter::printDependentAddressSpaceBefore(
576 const DependentAddressSpaceType *T, raw_ostream &OS) {
577 printBefore(T->getPointeeType(), OS);
580 void TypePrinter::printDependentAddressSpaceAfter(
581 const DependentAddressSpaceType *T, raw_ostream &OS) {
582 OS << " __attribute__((address_space(";
583 if (T->getAddrSpaceExpr())
584 T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy);
586 printAfter(T->getPointeeType(), OS);
589 void TypePrinter::printDependentSizedExtVectorBefore(
590 const DependentSizedExtVectorType *T,
592 printBefore(T->getElementType(), OS);
595 void TypePrinter::printDependentSizedExtVectorAfter(
596 const DependentSizedExtVectorType *T,
598 OS << " __attribute__((ext_vector_type(";
599 if (T->getSizeExpr())
600 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
602 printAfter(T->getElementType(), OS);
605 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
606 switch (T->getVectorKind()) {
607 case VectorType::AltiVecPixel:
608 OS << "__vector __pixel ";
610 case VectorType::AltiVecBool:
611 OS << "__vector __bool ";
612 printBefore(T->getElementType(), OS);
614 case VectorType::AltiVecVector:
616 printBefore(T->getElementType(), OS);
618 case VectorType::NeonVector:
619 OS << "__attribute__((neon_vector_type("
620 << T->getNumElements() << "))) ";
621 printBefore(T->getElementType(), OS);
623 case VectorType::NeonPolyVector:
624 OS << "__attribute__((neon_polyvector_type(" <<
625 T->getNumElements() << "))) ";
626 printBefore(T->getElementType(), OS);
628 case VectorType::GenericVector: {
629 // FIXME: We prefer to print the size directly here, but have no way
630 // to get the size of the type.
631 OS << "__attribute__((__vector_size__("
632 << T->getNumElements()
634 print(T->getElementType(), OS, StringRef());
636 printBefore(T->getElementType(), OS);
642 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
643 printAfter(T->getElementType(), OS);
646 void TypePrinter::printDependentVectorBefore(
647 const DependentVectorType *T, raw_ostream &OS) {
648 switch (T->getVectorKind()) {
649 case VectorType::AltiVecPixel:
650 OS << "__vector __pixel ";
652 case VectorType::AltiVecBool:
653 OS << "__vector __bool ";
654 printBefore(T->getElementType(), OS);
656 case VectorType::AltiVecVector:
658 printBefore(T->getElementType(), OS);
660 case VectorType::NeonVector:
661 OS << "__attribute__((neon_vector_type(";
662 if (T->getSizeExpr())
663 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
665 printBefore(T->getElementType(), OS);
667 case VectorType::NeonPolyVector:
668 OS << "__attribute__((neon_polyvector_type(";
669 if (T->getSizeExpr())
670 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
672 printBefore(T->getElementType(), OS);
674 case VectorType::GenericVector: {
675 // FIXME: We prefer to print the size directly here, but have no way
676 // to get the size of the type.
677 OS << "__attribute__((__vector_size__(";
678 if (T->getSizeExpr())
679 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
681 print(T->getElementType(), OS, StringRef());
683 printBefore(T->getElementType(), OS);
689 void TypePrinter::printDependentVectorAfter(
690 const DependentVectorType *T, raw_ostream &OS) {
691 printAfter(T->getElementType(), OS);
694 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
696 printBefore(T->getElementType(), OS);
699 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
700 printAfter(T->getElementType(), OS);
701 OS << " __attribute__((ext_vector_type(";
702 OS << T->getNumElements();
707 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
708 const PrintingPolicy &Policy)
710 if (hasDynamicExceptionSpec()) {
712 if (getExceptionSpecType() == EST_MSAny)
715 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
719 OS << getExceptionType(I).stream(Policy);
722 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
724 // FIXME:Is it useful to print out the expression for a non-dependent
725 // noexcept specification?
726 if (isComputedNoexcept(getExceptionSpecType())) {
728 if (getNoexceptExpr())
729 getNoexceptExpr()->printPretty(OS, nullptr, Policy);
735 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
737 if (T->hasTrailingReturn()) {
739 if (!HasEmptyPlaceHolder)
742 // If needed for precedence reasons, wrap the inner part in grouping parens.
743 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
744 printBefore(T->getReturnType(), OS);
745 if (!PrevPHIsEmpty.get())
750 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
752 case ParameterABI::Ordinary:
753 llvm_unreachable("asking for spelling of ordinary parameter ABI");
754 case ParameterABI::SwiftContext:
755 return "swift_context";
756 case ParameterABI::SwiftErrorResult:
757 return "swift_error_result";
758 case ParameterABI::SwiftIndirectResult:
759 return "swift_indirect_result";
761 llvm_unreachable("bad parameter ABI kind");
764 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
766 // If needed for precedence reasons, wrap the inner part in grouping parens.
767 if (!HasEmptyPlaceHolder)
769 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
773 ParamPolicyRAII ParamPolicy(Policy);
774 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
777 auto EPI = T->getExtParameterInfo(i);
778 if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
779 if (EPI.isNoEscape())
780 OS << "__attribute__((noescape)) ";
781 auto ABI = EPI.getABI();
782 if (ABI != ParameterABI::Ordinary)
783 OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
785 print(T->getParamType(i), OS, StringRef());
789 if (T->isVariadic()) {
790 if (T->getNumParams())
793 } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
794 // Do not emit int() if we have a proto, emit 'int(void)'.
800 FunctionType::ExtInfo Info = T->getExtInfo();
802 printFunctionAfter(Info, OS);
804 if (unsigned quals = T->getTypeQuals()) {
806 AppendTypeQualList(OS, quals, Policy.Restrict);
809 switch (T->getRefQualifier()) {
821 T->printExceptionSpecification(OS, Policy);
823 if (T->hasTrailingReturn()) {
825 print(T->getReturnType(), OS, StringRef());
827 printAfter(T->getReturnType(), OS);
830 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
832 if (!InsideCCAttribute) {
833 switch (Info.getCC()) {
835 // The C calling convention is the default on the vast majority of platforms
836 // we support. If the user wrote it explicitly, it will usually be printed
837 // while traversing the AttributedType. If the type has been desugared, let
838 // the canonical spelling be the implicit calling convention.
839 // FIXME: It would be better to be explicit in certain contexts, such as a
840 // cdecl function typedef used to declare a member function with the
841 // Microsoft C++ ABI.
844 OS << " __attribute__((stdcall))";
847 OS << " __attribute__((fastcall))";
850 OS << " __attribute__((thiscall))";
852 case CC_X86VectorCall:
853 OS << " __attribute__((vectorcall))";
856 OS << " __attribute__((pascal))";
859 OS << " __attribute__((pcs(\"aapcs\")))";
862 OS << " __attribute__((pcs(\"aapcs-vfp\")))";
864 case CC_IntelOclBicc:
865 OS << " __attribute__((intel_ocl_bicc))";
868 OS << " __attribute__((ms_abi))";
871 OS << " __attribute__((sysv_abi))";
874 OS << " __attribute__((regcall))";
876 case CC_SpirFunction:
877 case CC_OpenCLKernel:
878 // Do nothing. These CCs are not available as attributes.
881 OS << " __attribute__((swiftcall))";
883 case CC_PreserveMost:
884 OS << " __attribute__((preserve_most))";
887 OS << " __attribute__((preserve_all))";
892 if (Info.getNoReturn())
893 OS << " __attribute__((noreturn))";
894 if (Info.getProducesResult())
895 OS << " __attribute__((ns_returns_retained))";
896 if (Info.getRegParm())
897 OS << " __attribute__((regparm ("
898 << Info.getRegParm() << ")))";
899 if (Info.getNoCallerSavedRegs())
900 OS << " __attribute__((no_caller_saved_registers))";
901 if (Info.getNoCfCheck())
902 OS << " __attribute__((nocf_check))";
905 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
907 // If needed for precedence reasons, wrap the inner part in grouping parens.
908 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
909 printBefore(T->getReturnType(), OS);
910 if (!PrevPHIsEmpty.get())
914 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
916 // If needed for precedence reasons, wrap the inner part in grouping parens.
917 if (!HasEmptyPlaceHolder)
919 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
922 printFunctionAfter(T->getExtInfo(), OS);
923 printAfter(T->getReturnType(), OS);
926 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
928 // Compute the full nested-name-specifier for this type.
929 // In C, this will always be empty except when the type
930 // being printed is anonymous within other Record.
931 if (!Policy.SuppressScope)
932 AppendScope(D->getDeclContext(), OS);
934 IdentifierInfo *II = D->getIdentifier();
936 spaceBeforePlaceHolder(OS);
939 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
941 printTypeSpec(T->getDecl(), OS);
944 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
947 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
948 printTypeSpec(T->getDecl(), OS);
951 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
953 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
956 if (T->getUnderlyingExpr())
957 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
958 spaceBeforePlaceHolder(OS);
961 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
964 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
966 print(T->getUnderlyingType(), OS, StringRef());
968 spaceBeforePlaceHolder(OS);
971 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
973 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
975 if (T->getUnderlyingExpr())
976 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
978 spaceBeforePlaceHolder(OS);
981 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
983 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
985 IncludeStrongLifetimeRAII Strong(Policy);
987 switch (T->getUTTKind()) {
988 case UnaryTransformType::EnumUnderlyingType:
989 OS << "__underlying_type(";
990 print(T->getBaseType(), OS, StringRef());
992 spaceBeforePlaceHolder(OS);
996 printBefore(T->getBaseType(), OS);
999 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
1001 IncludeStrongLifetimeRAII Strong(Policy);
1003 switch (T->getUTTKind()) {
1004 case UnaryTransformType::EnumUnderlyingType:
1008 printAfter(T->getBaseType(), OS);
1011 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
1012 // If the type has been deduced, do not print 'auto'.
1013 if (!T->getDeducedType().isNull()) {
1014 printBefore(T->getDeducedType(), OS);
1016 switch (T->getKeyword()) {
1017 case AutoTypeKeyword::Auto: OS << "auto"; break;
1018 case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
1019 case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
1021 spaceBeforePlaceHolder(OS);
1025 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
1026 // If the type has been deduced, do not print 'auto'.
1027 if (!T->getDeducedType().isNull())
1028 printAfter(T->getDeducedType(), OS);
1031 void TypePrinter::printDeducedTemplateSpecializationBefore(
1032 const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1033 // If the type has been deduced, print the deduced type.
1034 if (!T->getDeducedType().isNull()) {
1035 printBefore(T->getDeducedType(), OS);
1037 IncludeStrongLifetimeRAII Strong(Policy);
1038 T->getTemplateName().print(OS, Policy);
1039 spaceBeforePlaceHolder(OS);
1043 void TypePrinter::printDeducedTemplateSpecializationAfter(
1044 const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1045 // If the type has been deduced, print the deduced type.
1046 if (!T->getDeducedType().isNull())
1047 printAfter(T->getDeducedType(), OS);
1050 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
1051 IncludeStrongLifetimeRAII Strong(Policy);
1054 print(T->getValueType(), OS, StringRef());
1056 spaceBeforePlaceHolder(OS);
1059 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
1061 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
1062 IncludeStrongLifetimeRAII Strong(Policy);
1064 if (T->isReadOnly())
1067 OS << "write_only ";
1069 print(T->getElementType(), OS, StringRef());
1070 spaceBeforePlaceHolder(OS);
1073 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
1075 /// Appends the given scope to the end of a string.
1076 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
1077 if (DC->isTranslationUnit()) return;
1078 if (DC->isFunctionOrMethod()) return;
1079 AppendScope(DC->getParent(), OS);
1081 if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
1082 if (Policy.SuppressUnwrittenScope &&
1083 (NS->isAnonymousNamespace() || NS->isInline()))
1085 if (NS->getIdentifier())
1086 OS << NS->getName() << "::";
1088 OS << "(anonymous namespace)::";
1089 } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1090 IncludeStrongLifetimeRAII Strong(Policy);
1091 OS << Spec->getIdentifier()->getName();
1092 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1093 printTemplateArgumentList(OS, TemplateArgs.asArray(), Policy);
1095 } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
1096 if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
1097 OS << Typedef->getIdentifier()->getName() << "::";
1098 else if (Tag->getIdentifier())
1099 OS << Tag->getIdentifier()->getName() << "::";
1105 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
1106 if (Policy.IncludeTagDefinition) {
1107 PrintingPolicy SubPolicy = Policy;
1108 SubPolicy.IncludeTagDefinition = false;
1109 D->print(OS, SubPolicy, Indentation);
1110 spaceBeforePlaceHolder(OS);
1114 bool HasKindDecoration = false;
1116 // We don't print tags unless this is an elaborated type.
1117 // In C, we just assume every RecordType is an elaborated type.
1118 if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
1119 HasKindDecoration = true;
1120 OS << D->getKindName();
1124 // Compute the full nested-name-specifier for this type.
1125 // In C, this will always be empty except when the type
1126 // being printed is anonymous within other Record.
1127 if (!Policy.SuppressScope)
1128 AppendScope(D->getDeclContext(), OS);
1130 if (const IdentifierInfo *II = D->getIdentifier())
1131 OS << II->getName();
1132 else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1133 assert(Typedef->getIdentifier() && "Typedef without identifier?");
1134 OS << Typedef->getIdentifier()->getName();
1136 // Make an unambiguous representation for anonymous types, e.g.
1137 // (anonymous enum at /usr/include/string.h:120:9)
1138 OS << (Policy.MSVCFormatting ? '`' : '(');
1140 if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1142 HasKindDecoration = true;
1147 if (Policy.AnonymousTagLocations) {
1148 // Suppress the redundant tag keyword if we just printed one.
1149 // We don't have to worry about ElaboratedTypes here because you can't
1150 // refer to an anonymous type with one.
1151 if (!HasKindDecoration)
1152 OS << " " << D->getKindName();
1154 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1156 if (PLoc.isValid()) {
1157 OS << " at " << PLoc.getFilename()
1158 << ':' << PLoc.getLine()
1159 << ':' << PLoc.getColumn();
1163 OS << (Policy.MSVCFormatting ? '\'' : ')');
1166 // If this is a class template specialization, print the template
1168 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1169 ArrayRef<TemplateArgument> Args;
1170 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
1171 const TemplateSpecializationType *TST =
1172 cast<TemplateSpecializationType>(TAW->getType());
1173 Args = TST->template_arguments();
1175 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1176 Args = TemplateArgs.asArray();
1178 IncludeStrongLifetimeRAII Strong(Policy);
1179 printTemplateArgumentList(OS, Args, Policy);
1182 spaceBeforePlaceHolder(OS);
1185 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1186 printTag(T->getDecl(), OS);
1189 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
1191 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1192 printTag(T->getDecl(), OS);
1195 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
1197 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1199 if (IdentifierInfo *Id = T->getIdentifier())
1200 OS << Id->getName();
1202 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1203 spaceBeforePlaceHolder(OS);
1206 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1209 void TypePrinter::printSubstTemplateTypeParmBefore(
1210 const SubstTemplateTypeParmType *T,
1212 IncludeStrongLifetimeRAII Strong(Policy);
1213 printBefore(T->getReplacementType(), OS);
1216 void TypePrinter::printSubstTemplateTypeParmAfter(
1217 const SubstTemplateTypeParmType *T,
1219 IncludeStrongLifetimeRAII Strong(Policy);
1220 printAfter(T->getReplacementType(), OS);
1223 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1224 const SubstTemplateTypeParmPackType *T,
1226 IncludeStrongLifetimeRAII Strong(Policy);
1227 printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1230 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1231 const SubstTemplateTypeParmPackType *T,
1233 IncludeStrongLifetimeRAII Strong(Policy);
1234 printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1237 void TypePrinter::printTemplateSpecializationBefore(
1238 const TemplateSpecializationType *T,
1240 IncludeStrongLifetimeRAII Strong(Policy);
1241 T->getTemplateName().print(OS, Policy);
1243 printTemplateArgumentList(OS, T->template_arguments(), Policy);
1244 spaceBeforePlaceHolder(OS);
1247 void TypePrinter::printTemplateSpecializationAfter(
1248 const TemplateSpecializationType *T,
1251 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1253 printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1256 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1259 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1261 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
1262 TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
1263 assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
1264 "OwnedTagDecl expected to be a declaration for the type");
1265 PrintingPolicy SubPolicy = Policy;
1266 SubPolicy.IncludeTagDefinition = false;
1267 OwnedTagDecl->print(OS, SubPolicy, Indentation);
1268 spaceBeforePlaceHolder(OS);
1272 // The tag definition will take care of these.
1273 if (!Policy.IncludeTagDefinition)
1275 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1276 if (T->getKeyword() != ETK_None)
1278 NestedNameSpecifier *Qualifier = T->getQualifier();
1280 Qualifier->print(OS, Policy);
1283 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1284 printBefore(T->getNamedType(), OS);
1287 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1289 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
1291 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1292 printAfter(T->getNamedType(), OS);
1295 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1296 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1297 printBefore(T->getInnerType(), OS);
1300 printBefore(T->getInnerType(), OS);
1303 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1304 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1306 printAfter(T->getInnerType(), OS);
1308 printAfter(T->getInnerType(), OS);
1311 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1313 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1314 if (T->getKeyword() != ETK_None)
1317 T->getQualifier()->print(OS, Policy);
1319 OS << T->getIdentifier()->getName();
1320 spaceBeforePlaceHolder(OS);
1323 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1326 void TypePrinter::printDependentTemplateSpecializationBefore(
1327 const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1328 IncludeStrongLifetimeRAII Strong(Policy);
1330 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1331 if (T->getKeyword() != ETK_None)
1334 if (T->getQualifier())
1335 T->getQualifier()->print(OS, Policy);
1336 OS << T->getIdentifier()->getName();
1337 printTemplateArgumentList(OS, T->template_arguments(), Policy);
1338 spaceBeforePlaceHolder(OS);
1341 void TypePrinter::printDependentTemplateSpecializationAfter(
1342 const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
1344 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1346 printBefore(T->getPattern(), OS);
1349 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1351 printAfter(T->getPattern(), OS);
1355 void TypePrinter::printAttributedBefore(const AttributedType *T,
1357 // Prefer the macro forms of the GC and ownership qualifiers.
1358 if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1359 T->getAttrKind() == AttributedType::attr_objc_ownership)
1360 return printBefore(T->getEquivalentType(), OS);
1362 if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1365 printBefore(T->getModifiedType(), OS);
1367 if (T->isMSTypeSpec()) {
1368 switch (T->getAttrKind()) {
1370 case AttributedType::attr_ptr32: OS << " __ptr32"; break;
1371 case AttributedType::attr_ptr64: OS << " __ptr64"; break;
1372 case AttributedType::attr_sptr: OS << " __sptr"; break;
1373 case AttributedType::attr_uptr: OS << " __uptr"; break;
1375 spaceBeforePlaceHolder(OS);
1378 // Print nullability type specifiers.
1379 if (T->getAttrKind() == AttributedType::attr_nonnull ||
1380 T->getAttrKind() == AttributedType::attr_nullable ||
1381 T->getAttrKind() == AttributedType::attr_null_unspecified) {
1382 if (T->getAttrKind() == AttributedType::attr_nonnull)
1384 else if (T->getAttrKind() == AttributedType::attr_nullable)
1386 else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1387 OS << " _Null_unspecified";
1389 llvm_unreachable("unhandled nullability");
1390 spaceBeforePlaceHolder(OS);
1394 void TypePrinter::printAttributedAfter(const AttributedType *T,
1396 // Prefer the macro forms of the GC and ownership qualifiers.
1397 if (T->getAttrKind() == AttributedType::attr_objc_gc ||
1398 T->getAttrKind() == AttributedType::attr_objc_ownership)
1399 return printAfter(T->getEquivalentType(), OS);
1401 if (T->getAttrKind() == AttributedType::attr_objc_kindof)
1404 // TODO: not all attributes are GCC-style attributes.
1405 if (T->isMSTypeSpec())
1408 // Nothing to print after.
1409 if (T->getAttrKind() == AttributedType::attr_nonnull ||
1410 T->getAttrKind() == AttributedType::attr_nullable ||
1411 T->getAttrKind() == AttributedType::attr_null_unspecified)
1412 return printAfter(T->getModifiedType(), OS);
1414 // If this is a calling convention attribute, don't print the implicit CC from
1415 // the modified type.
1416 SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1418 printAfter(T->getModifiedType(), OS);
1420 // Don't print the inert __unsafe_unretained attribute at all.
1421 if (T->getAttrKind() == AttributedType::attr_objc_inert_unsafe_unretained)
1424 // Don't print ns_returns_retained unless it had an effect.
1425 if (T->getAttrKind() == AttributedType::attr_ns_returns_retained &&
1426 !T->getEquivalentType()->castAs<FunctionType>()
1427 ->getExtInfo().getProducesResult())
1430 // Print nullability type specifiers that occur after
1431 if (T->getAttrKind() == AttributedType::attr_nonnull ||
1432 T->getAttrKind() == AttributedType::attr_nullable ||
1433 T->getAttrKind() == AttributedType::attr_null_unspecified) {
1434 if (T->getAttrKind() == AttributedType::attr_nonnull)
1436 else if (T->getAttrKind() == AttributedType::attr_nullable)
1438 else if (T->getAttrKind() == AttributedType::attr_null_unspecified)
1439 OS << " _Null_unspecified";
1441 llvm_unreachable("unhandled nullability");
1446 if (T->getAttrKind() == AttributedType::attr_lifetimebound) {
1447 OS << " [[clang::lifetimebound]]";
1451 OS << " __attribute__((";
1452 switch (T->getAttrKind()) {
1453 case AttributedType::attr_lifetimebound:
1454 case AttributedType::attr_nonnull:
1455 case AttributedType::attr_nullable:
1456 case AttributedType::attr_null_unspecified:
1457 case AttributedType::attr_objc_gc:
1458 case AttributedType::attr_objc_inert_unsafe_unretained:
1459 case AttributedType::attr_objc_kindof:
1460 case AttributedType::attr_objc_ownership:
1461 case AttributedType::attr_ptr32:
1462 case AttributedType::attr_ptr64:
1463 case AttributedType::attr_sptr:
1464 case AttributedType::attr_uptr:
1465 llvm_unreachable("This attribute should have been handled already");
1467 case AttributedType::attr_address_space:
1468 OS << "address_space(";
1469 // FIXME: printing the raw LangAS value is wrong. This should probably
1470 // use the same code as Qualifiers::print()
1471 OS << (unsigned)T->getEquivalentType().getAddressSpace();
1475 case AttributedType::attr_vector_size:
1476 OS << "__vector_size__(";
1477 if (const auto *vector = T->getEquivalentType()->getAs<VectorType>()) {
1478 OS << vector->getNumElements();
1480 print(vector->getElementType(), OS, StringRef());
1486 case AttributedType::attr_neon_vector_type:
1487 case AttributedType::attr_neon_polyvector_type: {
1488 if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
1489 OS << "neon_vector_type(";
1491 OS << "neon_polyvector_type(";
1492 const auto *vector = T->getEquivalentType()->getAs<VectorType>();
1493 OS << vector->getNumElements();
1498 case AttributedType::attr_regparm: {
1499 // FIXME: When Sema learns to form this AttributedType, avoid printing the
1500 // attribute again in printFunctionProtoAfter.
1502 QualType t = T->getEquivalentType();
1503 while (!t->isFunctionType())
1504 t = t->getPointeeType();
1505 OS << t->getAs<FunctionType>()->getRegParmType();
1510 case AttributedType::attr_ns_returns_retained:
1511 OS << "ns_returns_retained";
1514 // FIXME: When Sema learns to form this AttributedType, avoid printing the
1515 // attribute again in printFunctionProtoAfter.
1516 case AttributedType::attr_noreturn: OS << "noreturn"; break;
1517 case AttributedType::attr_nocf_check: OS << "nocf_check"; break;
1518 case AttributedType::attr_cdecl: OS << "cdecl"; break;
1519 case AttributedType::attr_fastcall: OS << "fastcall"; break;
1520 case AttributedType::attr_stdcall: OS << "stdcall"; break;
1521 case AttributedType::attr_thiscall: OS << "thiscall"; break;
1522 case AttributedType::attr_swiftcall: OS << "swiftcall"; break;
1523 case AttributedType::attr_vectorcall: OS << "vectorcall"; break;
1524 case AttributedType::attr_pascal: OS << "pascal"; break;
1525 case AttributedType::attr_ms_abi: OS << "ms_abi"; break;
1526 case AttributedType::attr_sysv_abi: OS << "sysv_abi"; break;
1527 case AttributedType::attr_regcall: OS << "regcall"; break;
1528 case AttributedType::attr_pcs:
1529 case AttributedType::attr_pcs_vfp: {
1531 QualType t = T->getEquivalentType();
1532 while (!t->isFunctionType())
1533 t = t->getPointeeType();
1534 OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1535 "\"aapcs\"" : "\"aapcs-vfp\"");
1540 case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break;
1541 case AttributedType::attr_preserve_most:
1542 OS << "preserve_most";
1545 case AttributedType::attr_preserve_all:
1546 OS << "preserve_all";
1552 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1554 OS << T->getDecl()->getName();
1555 spaceBeforePlaceHolder(OS);
1558 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1561 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1563 OS << T->getDecl()->getName();
1564 if (!T->qual_empty()) {
1565 bool isFirst = true;
1567 for (const auto *I : T->quals()) {
1577 spaceBeforePlaceHolder(OS);
1580 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1583 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1585 if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1586 !T->isKindOfTypeAsWritten())
1587 return printBefore(T->getBaseType(), OS);
1589 if (T->isKindOfTypeAsWritten())
1592 print(T->getBaseType(), OS, StringRef());
1594 if (T->isSpecializedAsWritten()) {
1595 bool isFirst = true;
1597 for (auto typeArg : T->getTypeArgsAsWritten()) {
1603 print(typeArg, OS, StringRef());
1608 if (!T->qual_empty()) {
1609 bool isFirst = true;
1611 for (const auto *I : T->quals()) {
1621 spaceBeforePlaceHolder(OS);
1624 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1626 if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1627 !T->isKindOfTypeAsWritten())
1628 return printAfter(T->getBaseType(), OS);
1631 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1633 printBefore(T->getPointeeType(), OS);
1635 // If we need to print the pointer, print it now.
1636 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1637 !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1638 if (HasEmptyPlaceHolder)
1644 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1648 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
1650 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
1651 return A.getArgument();
1654 template<typename TA>
1655 static void printTo(raw_ostream &OS, ArrayRef<TA> Args,
1656 const PrintingPolicy &Policy, bool SkipBrackets) {
1657 const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1661 bool NeedSpace = false;
1662 bool FirstArg = true;
1663 for (const auto &Arg : Args) {
1664 // Print the argument into a string.
1665 SmallString<128> Buf;
1666 llvm::raw_svector_ostream ArgOS(Buf);
1667 const TemplateArgument &Argument = getArgument(Arg);
1668 if (Argument.getKind() == TemplateArgument::Pack) {
1669 if (Argument.pack_size() && !FirstArg)
1671 printTo(ArgOS, Argument.getPackAsArray(), Policy, true);
1675 Argument.print(Policy, ArgOS);
1677 StringRef ArgString = ArgOS.str();
1679 // If this is the first argument and its string representation
1680 // begins with the global scope specifier ('::foo'), add a space
1681 // to avoid printing the diagraph '<:'.
1682 if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
1687 NeedSpace = (!ArgString.empty() && ArgString.back() == '>');
1691 // If the last character of our string is '>', add another space to
1692 // keep the two '>''s separate tokens. We don't *have* to do this in
1693 // C++0x, but it's still good hygiene.
1701 void clang::printTemplateArgumentList(raw_ostream &OS,
1702 const TemplateArgumentListInfo &Args,
1703 const PrintingPolicy &Policy) {
1704 return printTo(OS, Args.arguments(), Policy, false);
1707 void clang::printTemplateArgumentList(raw_ostream &OS,
1708 ArrayRef<TemplateArgument> Args,
1709 const PrintingPolicy &Policy) {
1710 printTo(OS, Args, Policy, false);
1713 void clang::printTemplateArgumentList(raw_ostream &OS,
1714 ArrayRef<TemplateArgumentLoc> Args,
1715 const PrintingPolicy &Policy) {
1716 printTo(OS, Args, Policy, false);
1719 std::string Qualifiers::getAsString() const {
1721 return getAsString(PrintingPolicy(LO));
1724 // Appends qualifiers to the given string, separated by spaces. Will
1725 // prefix a space if the string is non-empty. Will not append a final
1727 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1728 SmallString<64> Buf;
1729 llvm::raw_svector_ostream StrOS(Buf);
1730 print(StrOS, Policy);
1734 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1735 if (getCVRQualifiers())
1738 if (getAddressSpace() != LangAS::Default)
1741 if (getObjCGCAttr())
1744 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1745 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1751 // Appends qualifiers to the given string, separated by spaces. Will
1752 // prefix a space if the string is non-empty. Will not append a final
1754 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1755 bool appendSpaceIfNonEmpty) const {
1756 bool addSpace = false;
1758 unsigned quals = getCVRQualifiers();
1760 AppendTypeQualList(OS, quals, Policy.Restrict);
1763 if (hasUnaligned()) {
1766 OS << "__unaligned";
1769 LangAS addrspace = getAddressSpace();
1770 if (addrspace != LangAS::Default) {
1771 if (addrspace != LangAS::opencl_private) {
1775 switch (addrspace) {
1776 case LangAS::opencl_global:
1779 case LangAS::opencl_local:
1782 case LangAS::opencl_private:
1784 case LangAS::opencl_constant:
1785 case LangAS::cuda_constant:
1788 case LangAS::opencl_generic:
1791 case LangAS::cuda_device:
1794 case LangAS::cuda_shared:
1798 OS << "__attribute__((address_space(";
1799 OS << toTargetAddressSpace(addrspace);
1804 if (Qualifiers::GC gc = getObjCGCAttr()) {
1808 if (gc == Qualifiers::Weak)
1813 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1814 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1821 case Qualifiers::OCL_None: llvm_unreachable("none but true");
1822 case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1823 case Qualifiers::OCL_Strong:
1824 if (!Policy.SuppressStrongLifetime)
1828 case Qualifiers::OCL_Weak: OS << "__weak"; break;
1829 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1833 if (appendSpaceIfNonEmpty && addSpace)
1837 std::string QualType::getAsString() const {
1838 return getAsString(split(), LangOptions());
1841 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1843 getAsStringInternal(S, Policy);
1847 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
1848 const PrintingPolicy &Policy) {
1850 getAsStringInternal(ty, qs, buffer, Policy);
1854 void QualType::print(const Type *ty, Qualifiers qs,
1855 raw_ostream &OS, const PrintingPolicy &policy,
1856 const Twine &PlaceHolder, unsigned Indentation) {
1857 SmallString<128> PHBuf;
1858 StringRef PH = PlaceHolder.toStringRef(PHBuf);
1860 TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
1863 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1864 std::string &buffer,
1865 const PrintingPolicy &policy) {
1866 SmallString<256> Buf;
1867 llvm::raw_svector_ostream StrOS(Buf);
1868 TypePrinter(policy).print(ty, qs, StrOS, buffer);
1869 std::string str = StrOS.str();