1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This contains code to print types from Clang's type system.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/PrettyPrinter.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/TemplateBase.h"
23 #include "clang/AST/TemplateName.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/AddressSpaces.h"
26 #include "clang/Basic/ExceptionSpecificationType.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/LLVM.h"
29 #include "clang/Basic/LangOptions.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/Specifiers.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/SaveAndRestore.h"
41 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
49 /// RAII object that enables printing of the ARC __strong lifetime
51 class IncludeStrongLifetimeRAII {
52 PrintingPolicy &Policy;
56 explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
57 : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
58 if (!Policy.SuppressLifetimeQualifiers)
59 Policy.SuppressStrongLifetime = false;
62 ~IncludeStrongLifetimeRAII() {
63 Policy.SuppressStrongLifetime = Old;
67 class ParamPolicyRAII {
68 PrintingPolicy &Policy;
72 explicit ParamPolicyRAII(PrintingPolicy &Policy)
73 : Policy(Policy), Old(Policy.SuppressSpecifiers) {
74 Policy.SuppressSpecifiers = false;
78 Policy.SuppressSpecifiers = Old;
82 class ElaboratedTypePolicyRAII {
83 PrintingPolicy &Policy;
84 bool SuppressTagKeyword;
88 explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
89 SuppressTagKeyword = Policy.SuppressTagKeyword;
90 SuppressScope = Policy.SuppressScope;
91 Policy.SuppressTagKeyword = true;
92 Policy.SuppressScope = true;
95 ~ElaboratedTypePolicyRAII() {
96 Policy.SuppressTagKeyword = SuppressTagKeyword;
97 Policy.SuppressScope = SuppressScope;
102 PrintingPolicy Policy;
103 unsigned Indentation;
104 bool HasEmptyPlaceHolder = false;
105 bool InsideCCAttribute = false;
108 explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
109 : Policy(Policy), Indentation(Indentation) {}
111 void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
112 StringRef PlaceHolder);
113 void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
115 static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
116 void spaceBeforePlaceHolder(raw_ostream &OS);
117 void printTypeSpec(NamedDecl *D, raw_ostream &OS);
119 void printBefore(QualType T, raw_ostream &OS);
120 void printAfter(QualType T, raw_ostream &OS);
121 void AppendScope(DeclContext *DC, raw_ostream &OS);
122 void printTag(TagDecl *T, raw_ostream &OS);
123 void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
124 #define ABSTRACT_TYPE(CLASS, PARENT)
125 #define TYPE(CLASS, PARENT) \
126 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
127 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
128 #include "clang/AST/TypeNodes.inc"
131 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
132 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
137 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
138 bool HasRestrictKeyword) {
139 bool appendSpace = false;
140 if (TypeQuals & Qualifiers::Const) {
144 if (TypeQuals & Qualifiers::Volatile) {
145 if (appendSpace) OS << ' ';
149 if (TypeQuals & Qualifiers::Restrict) {
150 if (appendSpace) OS << ' ';
151 if (HasRestrictKeyword) {
159 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
160 if (!HasEmptyPlaceHolder)
164 static SplitQualType splitAccordingToPolicy(QualType QT,
165 const PrintingPolicy &Policy) {
166 if (Policy.PrintCanonicalTypes)
167 QT = QT.getCanonicalType();
171 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
172 SplitQualType split = splitAccordingToPolicy(t, Policy);
173 print(split.Ty, split.Quals, OS, PlaceHolder);
176 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
177 StringRef PlaceHolder) {
183 SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
185 printBefore(T, Quals, OS);
187 printAfter(T, Quals, OS);
190 bool TypePrinter::canPrefixQualifiers(const Type *T,
191 bool &NeedARCStrongQualifier) {
192 // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
193 // so that we get "const int" instead of "int const", but we can't do this if
194 // the type is complex. For example if the type is "int*", we *must* print
195 // "int * const", printing "const int *" is different. Only do this when the
196 // type expands to a simple string.
197 bool CanPrefixQualifiers = false;
198 NeedARCStrongQualifier = false;
199 Type::TypeClass TC = T->getTypeClass();
200 if (const auto *AT = dyn_cast<AutoType>(T))
201 TC = AT->desugar()->getTypeClass();
202 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T))
203 TC = Subst->getReplacementType()->getTypeClass();
209 case Type::UnresolvedUsing:
211 case Type::TypeOfExpr:
214 case Type::UnaryTransform:
217 case Type::Elaborated:
218 case Type::TemplateTypeParm:
219 case Type::SubstTemplateTypeParmPack:
220 case Type::DeducedTemplateSpecialization:
221 case Type::TemplateSpecialization:
222 case Type::InjectedClassName:
223 case Type::DependentName:
224 case Type::DependentTemplateSpecialization:
225 case Type::ObjCObject:
226 case Type::ObjCTypeParam:
227 case Type::ObjCInterface:
230 CanPrefixQualifiers = true;
233 case Type::ObjCObjectPointer:
234 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
235 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
238 case Type::ConstantArray:
239 case Type::IncompleteArray:
240 case Type::VariableArray:
241 case Type::DependentSizedArray:
242 NeedARCStrongQualifier = true;
248 case Type::BlockPointer:
249 case Type::LValueReference:
250 case Type::RValueReference:
251 case Type::MemberPointer:
252 case Type::DependentAddressSpace:
253 case Type::DependentVector:
254 case Type::DependentSizedExtVector:
256 case Type::ExtVector:
257 case Type::FunctionProto:
258 case Type::FunctionNoProto:
260 case Type::PackExpansion:
261 case Type::SubstTemplateTypeParm:
262 case Type::MacroQualified:
263 CanPrefixQualifiers = false;
266 case Type::Attributed: {
267 // We still want to print the address_space before the type if it is an
268 // address_space attribute.
269 const auto *AttrTy = cast<AttributedType>(T);
270 CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace;
274 return CanPrefixQualifiers;
277 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
278 SplitQualType Split = splitAccordingToPolicy(T, Policy);
280 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
282 Qualifiers Quals = Split.Quals;
283 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
284 Quals -= QualType(Subst, 0).getQualifiers();
286 printBefore(Split.Ty, Quals, OS);
289 /// Prints the part of the type string before an identifier, e.g. for
290 /// "int foo[10]" it prints "int ".
291 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
292 if (Policy.SuppressSpecifiers && T->isSpecifierType())
295 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder);
297 // Print qualifiers as appropriate.
299 bool CanPrefixQualifiers = false;
300 bool NeedARCStrongQualifier = false;
301 CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
303 if (CanPrefixQualifiers && !Quals.empty()) {
304 if (NeedARCStrongQualifier) {
305 IncludeStrongLifetimeRAII Strong(Policy);
306 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
308 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
312 bool hasAfterQuals = false;
313 if (!CanPrefixQualifiers && !Quals.empty()) {
314 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
316 HasEmptyPlaceHolder = false;
319 switch (T->getTypeClass()) {
320 #define ABSTRACT_TYPE(CLASS, PARENT)
321 #define TYPE(CLASS, PARENT) case Type::CLASS: \
322 print##CLASS##Before(cast<CLASS##Type>(T), OS); \
324 #include "clang/AST/TypeNodes.inc"
328 if (NeedARCStrongQualifier) {
329 IncludeStrongLifetimeRAII Strong(Policy);
330 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
332 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
337 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
338 SplitQualType split = splitAccordingToPolicy(t, Policy);
339 printAfter(split.Ty, split.Quals, OS);
342 /// Prints the part of the type string after an identifier, e.g. for
343 /// "int foo[10]" it prints "[10]".
344 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
345 switch (T->getTypeClass()) {
346 #define ABSTRACT_TYPE(CLASS, PARENT)
347 #define TYPE(CLASS, PARENT) case Type::CLASS: \
348 print##CLASS##After(cast<CLASS##Type>(T), OS); \
350 #include "clang/AST/TypeNodes.inc"
354 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
355 OS << T->getName(Policy);
356 spaceBeforePlaceHolder(OS);
359 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {}
361 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
363 printBefore(T->getElementType(), OS);
366 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
367 printAfter(T->getElementType(), OS);
370 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
371 IncludeStrongLifetimeRAII Strong(Policy);
372 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
373 printBefore(T->getPointeeType(), OS);
374 // Handle things like 'int (*A)[4];' correctly.
375 // FIXME: this should include vectors, but vectors use attributes I guess.
376 if (isa<ArrayType>(T->getPointeeType()))
381 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
382 IncludeStrongLifetimeRAII Strong(Policy);
383 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
384 // Handle things like 'int (*A)[4];' correctly.
385 // FIXME: this should include vectors, but vectors use attributes I guess.
386 if (isa<ArrayType>(T->getPointeeType()))
388 printAfter(T->getPointeeType(), OS);
391 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
393 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
394 printBefore(T->getPointeeType(), OS);
398 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
400 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
401 printAfter(T->getPointeeType(), OS);
404 // When printing a reference, the referenced type might also be a reference.
405 // If so, we want to skip that before printing the inner type.
406 static QualType skipTopLevelReferences(QualType T) {
407 if (auto *Ref = T->getAs<ReferenceType>())
408 return skipTopLevelReferences(Ref->getPointeeTypeAsWritten());
412 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
414 IncludeStrongLifetimeRAII Strong(Policy);
415 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
416 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
417 printBefore(Inner, OS);
418 // Handle things like 'int (&A)[4];' correctly.
419 // FIXME: this should include vectors, but vectors use attributes I guess.
420 if (isa<ArrayType>(Inner))
425 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
427 IncludeStrongLifetimeRAII Strong(Policy);
428 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
429 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
430 // Handle things like 'int (&A)[4];' correctly.
431 // FIXME: this should include vectors, but vectors use attributes I guess.
432 if (isa<ArrayType>(Inner))
434 printAfter(Inner, OS);
437 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
439 IncludeStrongLifetimeRAII Strong(Policy);
440 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
441 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
442 printBefore(Inner, OS);
443 // Handle things like 'int (&&A)[4];' correctly.
444 // FIXME: this should include vectors, but vectors use attributes I guess.
445 if (isa<ArrayType>(Inner))
450 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
452 IncludeStrongLifetimeRAII Strong(Policy);
453 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
454 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
455 // Handle things like 'int (&&A)[4];' correctly.
456 // FIXME: this should include vectors, but vectors use attributes I guess.
457 if (isa<ArrayType>(Inner))
459 printAfter(Inner, OS);
462 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
464 IncludeStrongLifetimeRAII Strong(Policy);
465 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
466 printBefore(T->getPointeeType(), OS);
467 // Handle things like 'int (Cls::*A)[4];' correctly.
468 // FIXME: this should include vectors, but vectors use attributes I guess.
469 if (isa<ArrayType>(T->getPointeeType()))
472 PrintingPolicy InnerPolicy(Policy);
473 InnerPolicy.IncludeTagDefinition = false;
474 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
479 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
481 IncludeStrongLifetimeRAII Strong(Policy);
482 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
483 // Handle things like 'int (Cls::*A)[4];' correctly.
484 // FIXME: this should include vectors, but vectors use attributes I guess.
485 if (isa<ArrayType>(T->getPointeeType()))
487 printAfter(T->getPointeeType(), OS);
490 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
492 IncludeStrongLifetimeRAII Strong(Policy);
493 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
494 printBefore(T->getElementType(), OS);
497 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
500 if (T->getIndexTypeQualifiers().hasQualifiers()) {
501 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
506 if (T->getSizeModifier() == ArrayType::Static)
509 OS << T->getSize().getZExtValue() << ']';
510 printAfter(T->getElementType(), OS);
513 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
515 IncludeStrongLifetimeRAII Strong(Policy);
516 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
517 printBefore(T->getElementType(), OS);
520 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
523 printAfter(T->getElementType(), OS);
526 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
528 IncludeStrongLifetimeRAII Strong(Policy);
529 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
530 printBefore(T->getElementType(), OS);
533 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
536 if (T->getIndexTypeQualifiers().hasQualifiers()) {
537 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
541 if (T->getSizeModifier() == VariableArrayType::Static)
543 else if (T->getSizeModifier() == VariableArrayType::Star)
546 if (T->getSizeExpr())
547 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
550 printAfter(T->getElementType(), OS);
553 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
554 // Print the adjusted representation, otherwise the adjustment will be
556 printBefore(T->getAdjustedType(), OS);
559 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
560 printAfter(T->getAdjustedType(), OS);
563 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
564 // Print as though it's a pointer.
565 printAdjustedBefore(T, OS);
568 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
569 printAdjustedAfter(T, OS);
572 void TypePrinter::printDependentSizedArrayBefore(
573 const DependentSizedArrayType *T,
575 IncludeStrongLifetimeRAII Strong(Policy);
576 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
577 printBefore(T->getElementType(), OS);
580 void TypePrinter::printDependentSizedArrayAfter(
581 const DependentSizedArrayType *T,
584 if (T->getSizeExpr())
585 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
587 printAfter(T->getElementType(), OS);
590 void TypePrinter::printDependentAddressSpaceBefore(
591 const DependentAddressSpaceType *T, raw_ostream &OS) {
592 printBefore(T->getPointeeType(), OS);
595 void TypePrinter::printDependentAddressSpaceAfter(
596 const DependentAddressSpaceType *T, raw_ostream &OS) {
597 OS << " __attribute__((address_space(";
598 if (T->getAddrSpaceExpr())
599 T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy);
601 printAfter(T->getPointeeType(), OS);
604 void TypePrinter::printDependentSizedExtVectorBefore(
605 const DependentSizedExtVectorType *T,
607 printBefore(T->getElementType(), OS);
610 void TypePrinter::printDependentSizedExtVectorAfter(
611 const DependentSizedExtVectorType *T,
613 OS << " __attribute__((ext_vector_type(";
614 if (T->getSizeExpr())
615 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
617 printAfter(T->getElementType(), OS);
620 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
621 switch (T->getVectorKind()) {
622 case VectorType::AltiVecPixel:
623 OS << "__vector __pixel ";
625 case VectorType::AltiVecBool:
626 OS << "__vector __bool ";
627 printBefore(T->getElementType(), OS);
629 case VectorType::AltiVecVector:
631 printBefore(T->getElementType(), OS);
633 case VectorType::NeonVector:
634 OS << "__attribute__((neon_vector_type("
635 << T->getNumElements() << "))) ";
636 printBefore(T->getElementType(), OS);
638 case VectorType::NeonPolyVector:
639 OS << "__attribute__((neon_polyvector_type(" <<
640 T->getNumElements() << "))) ";
641 printBefore(T->getElementType(), OS);
643 case VectorType::GenericVector: {
644 // FIXME: We prefer to print the size directly here, but have no way
645 // to get the size of the type.
646 OS << "__attribute__((__vector_size__("
647 << T->getNumElements()
649 print(T->getElementType(), OS, StringRef());
651 printBefore(T->getElementType(), OS);
657 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
658 printAfter(T->getElementType(), OS);
661 void TypePrinter::printDependentVectorBefore(
662 const DependentVectorType *T, raw_ostream &OS) {
663 switch (T->getVectorKind()) {
664 case VectorType::AltiVecPixel:
665 OS << "__vector __pixel ";
667 case VectorType::AltiVecBool:
668 OS << "__vector __bool ";
669 printBefore(T->getElementType(), OS);
671 case VectorType::AltiVecVector:
673 printBefore(T->getElementType(), OS);
675 case VectorType::NeonVector:
676 OS << "__attribute__((neon_vector_type(";
677 if (T->getSizeExpr())
678 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
680 printBefore(T->getElementType(), OS);
682 case VectorType::NeonPolyVector:
683 OS << "__attribute__((neon_polyvector_type(";
684 if (T->getSizeExpr())
685 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
687 printBefore(T->getElementType(), OS);
689 case VectorType::GenericVector: {
690 // FIXME: We prefer to print the size directly here, but have no way
691 // to get the size of the type.
692 OS << "__attribute__((__vector_size__(";
693 if (T->getSizeExpr())
694 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
696 print(T->getElementType(), OS, StringRef());
698 printBefore(T->getElementType(), OS);
704 void TypePrinter::printDependentVectorAfter(
705 const DependentVectorType *T, raw_ostream &OS) {
706 printAfter(T->getElementType(), OS);
709 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
711 printBefore(T->getElementType(), OS);
714 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
715 printAfter(T->getElementType(), OS);
716 OS << " __attribute__((ext_vector_type(";
717 OS << T->getNumElements();
722 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
723 const PrintingPolicy &Policy)
725 if (hasDynamicExceptionSpec()) {
727 if (getExceptionSpecType() == EST_MSAny)
730 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
734 OS << getExceptionType(I).stream(Policy);
737 } else if (EST_NoThrow == getExceptionSpecType()) {
738 OS << " __attribute__((nothrow))";
739 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
741 // FIXME:Is it useful to print out the expression for a non-dependent
742 // noexcept specification?
743 if (isComputedNoexcept(getExceptionSpecType())) {
745 if (getNoexceptExpr())
746 getNoexceptExpr()->printPretty(OS, nullptr, Policy);
752 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
754 if (T->hasTrailingReturn()) {
756 if (!HasEmptyPlaceHolder)
759 // If needed for precedence reasons, wrap the inner part in grouping parens.
760 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
761 printBefore(T->getReturnType(), OS);
762 if (!PrevPHIsEmpty.get())
767 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
769 case ParameterABI::Ordinary:
770 llvm_unreachable("asking for spelling of ordinary parameter ABI");
771 case ParameterABI::SwiftContext:
772 return "swift_context";
773 case ParameterABI::SwiftErrorResult:
774 return "swift_error_result";
775 case ParameterABI::SwiftIndirectResult:
776 return "swift_indirect_result";
778 llvm_unreachable("bad parameter ABI kind");
781 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
783 // If needed for precedence reasons, wrap the inner part in grouping parens.
784 if (!HasEmptyPlaceHolder)
786 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
790 ParamPolicyRAII ParamPolicy(Policy);
791 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
794 auto EPI = T->getExtParameterInfo(i);
795 if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
796 if (EPI.isNoEscape())
797 OS << "__attribute__((noescape)) ";
798 auto ABI = EPI.getABI();
799 if (ABI != ParameterABI::Ordinary)
800 OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
802 print(T->getParamType(i), OS, StringRef());
806 if (T->isVariadic()) {
807 if (T->getNumParams())
810 } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
811 // Do not emit int() if we have a proto, emit 'int(void)'.
817 FunctionType::ExtInfo Info = T->getExtInfo();
819 printFunctionAfter(Info, OS);
821 if (!T->getMethodQuals().empty())
822 OS << " " << T->getMethodQuals().getAsString();
824 switch (T->getRefQualifier()) {
836 T->printExceptionSpecification(OS, Policy);
838 if (T->hasTrailingReturn()) {
840 print(T->getReturnType(), OS, StringRef());
842 printAfter(T->getReturnType(), OS);
845 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
847 if (!InsideCCAttribute) {
848 switch (Info.getCC()) {
850 // The C calling convention is the default on the vast majority of platforms
851 // we support. If the user wrote it explicitly, it will usually be printed
852 // while traversing the AttributedType. If the type has been desugared, let
853 // the canonical spelling be the implicit calling convention.
854 // FIXME: It would be better to be explicit in certain contexts, such as a
855 // cdecl function typedef used to declare a member function with the
856 // Microsoft C++ ABI.
859 OS << " __attribute__((stdcall))";
862 OS << " __attribute__((fastcall))";
865 OS << " __attribute__((thiscall))";
867 case CC_X86VectorCall:
868 OS << " __attribute__((vectorcall))";
871 OS << " __attribute__((pascal))";
874 OS << " __attribute__((pcs(\"aapcs\")))";
877 OS << " __attribute__((pcs(\"aapcs-vfp\")))";
879 case CC_AArch64VectorCall:
880 OS << "__attribute__((aarch64_vector_pcs))";
882 case CC_IntelOclBicc:
883 OS << " __attribute__((intel_ocl_bicc))";
886 OS << " __attribute__((ms_abi))";
889 OS << " __attribute__((sysv_abi))";
892 OS << " __attribute__((regcall))";
894 case CC_SpirFunction:
895 case CC_OpenCLKernel:
896 // Do nothing. These CCs are not available as attributes.
899 OS << " __attribute__((swiftcall))";
901 case CC_PreserveMost:
902 OS << " __attribute__((preserve_most))";
905 OS << " __attribute__((preserve_all))";
910 if (Info.getNoReturn())
911 OS << " __attribute__((noreturn))";
912 if (Info.getProducesResult())
913 OS << " __attribute__((ns_returns_retained))";
914 if (Info.getRegParm())
915 OS << " __attribute__((regparm ("
916 << Info.getRegParm() << ")))";
917 if (Info.getNoCallerSavedRegs())
918 OS << " __attribute__((no_caller_saved_registers))";
919 if (Info.getNoCfCheck())
920 OS << " __attribute__((nocf_check))";
923 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
925 // If needed for precedence reasons, wrap the inner part in grouping parens.
926 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false);
927 printBefore(T->getReturnType(), OS);
928 if (!PrevPHIsEmpty.get())
932 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
934 // If needed for precedence reasons, wrap the inner part in grouping parens.
935 if (!HasEmptyPlaceHolder)
937 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false);
940 printFunctionAfter(T->getExtInfo(), OS);
941 printAfter(T->getReturnType(), OS);
944 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
946 // Compute the full nested-name-specifier for this type.
947 // In C, this will always be empty except when the type
948 // being printed is anonymous within other Record.
949 if (!Policy.SuppressScope)
950 AppendScope(D->getDeclContext(), OS);
952 IdentifierInfo *II = D->getIdentifier();
954 spaceBeforePlaceHolder(OS);
957 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
959 printTypeSpec(T->getDecl(), OS);
962 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
965 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
966 printTypeSpec(T->getDecl(), OS);
969 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType *T,
971 StringRef MacroName = T->getMacroIdentifier()->getName();
972 OS << MacroName << " ";
974 // Since this type is meant to print the macro instead of the whole attribute,
975 // we trim any attributes and go directly to the original modified type.
976 printBefore(T->getModifiedType(), OS);
979 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType *T,
981 printAfter(T->getModifiedType(), OS);
984 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
986 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
989 if (T->getUnderlyingExpr())
990 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
991 spaceBeforePlaceHolder(OS);
994 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
997 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
999 print(T->getUnderlyingType(), OS, StringRef());
1001 spaceBeforePlaceHolder(OS);
1004 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
1006 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
1008 if (T->getUnderlyingExpr())
1009 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1011 spaceBeforePlaceHolder(OS);
1014 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
1016 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
1018 IncludeStrongLifetimeRAII Strong(Policy);
1020 switch (T->getUTTKind()) {
1021 case UnaryTransformType::EnumUnderlyingType:
1022 OS << "__underlying_type(";
1023 print(T->getBaseType(), OS, StringRef());
1025 spaceBeforePlaceHolder(OS);
1029 printBefore(T->getBaseType(), OS);
1032 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
1034 IncludeStrongLifetimeRAII Strong(Policy);
1036 switch (T->getUTTKind()) {
1037 case UnaryTransformType::EnumUnderlyingType:
1041 printAfter(T->getBaseType(), OS);
1044 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
1045 // If the type has been deduced, do not print 'auto'.
1046 if (!T->getDeducedType().isNull()) {
1047 printBefore(T->getDeducedType(), OS);
1049 switch (T->getKeyword()) {
1050 case AutoTypeKeyword::Auto: OS << "auto"; break;
1051 case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
1052 case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
1054 spaceBeforePlaceHolder(OS);
1058 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
1059 // If the type has been deduced, do not print 'auto'.
1060 if (!T->getDeducedType().isNull())
1061 printAfter(T->getDeducedType(), OS);
1064 void TypePrinter::printDeducedTemplateSpecializationBefore(
1065 const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1066 // If the type has been deduced, print the deduced type.
1067 if (!T->getDeducedType().isNull()) {
1068 printBefore(T->getDeducedType(), OS);
1070 IncludeStrongLifetimeRAII Strong(Policy);
1071 T->getTemplateName().print(OS, Policy);
1072 spaceBeforePlaceHolder(OS);
1076 void TypePrinter::printDeducedTemplateSpecializationAfter(
1077 const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1078 // If the type has been deduced, print the deduced type.
1079 if (!T->getDeducedType().isNull())
1080 printAfter(T->getDeducedType(), OS);
1083 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
1084 IncludeStrongLifetimeRAII Strong(Policy);
1087 print(T->getValueType(), OS, StringRef());
1089 spaceBeforePlaceHolder(OS);
1092 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
1094 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
1095 IncludeStrongLifetimeRAII Strong(Policy);
1097 if (T->isReadOnly())
1100 OS << "write_only ";
1102 print(T->getElementType(), OS, StringRef());
1103 spaceBeforePlaceHolder(OS);
1106 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
1108 /// Appends the given scope to the end of a string.
1109 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) {
1110 if (DC->isTranslationUnit()) return;
1111 if (DC->isFunctionOrMethod()) return;
1112 AppendScope(DC->getParent(), OS);
1114 if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
1115 if (Policy.SuppressUnwrittenScope &&
1116 (NS->isAnonymousNamespace() || NS->isInline()))
1118 if (NS->getIdentifier())
1119 OS << NS->getName() << "::";
1121 OS << "(anonymous namespace)::";
1122 } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1123 IncludeStrongLifetimeRAII Strong(Policy);
1124 OS << Spec->getIdentifier()->getName();
1125 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1126 printTemplateArgumentList(OS, TemplateArgs.asArray(), Policy);
1128 } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
1129 if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
1130 OS << Typedef->getIdentifier()->getName() << "::";
1131 else if (Tag->getIdentifier())
1132 OS << Tag->getIdentifier()->getName() << "::";
1138 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
1139 if (Policy.IncludeTagDefinition) {
1140 PrintingPolicy SubPolicy = Policy;
1141 SubPolicy.IncludeTagDefinition = false;
1142 D->print(OS, SubPolicy, Indentation);
1143 spaceBeforePlaceHolder(OS);
1147 bool HasKindDecoration = false;
1149 // We don't print tags unless this is an elaborated type.
1150 // In C, we just assume every RecordType is an elaborated type.
1151 if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
1152 HasKindDecoration = true;
1153 OS << D->getKindName();
1157 // Compute the full nested-name-specifier for this type.
1158 // In C, this will always be empty except when the type
1159 // being printed is anonymous within other Record.
1160 if (!Policy.SuppressScope)
1161 AppendScope(D->getDeclContext(), OS);
1163 if (const IdentifierInfo *II = D->getIdentifier())
1164 OS << II->getName();
1165 else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1166 assert(Typedef->getIdentifier() && "Typedef without identifier?");
1167 OS << Typedef->getIdentifier()->getName();
1169 // Make an unambiguous representation for anonymous types, e.g.
1170 // (anonymous enum at /usr/include/string.h:120:9)
1171 OS << (Policy.MSVCFormatting ? '`' : '(');
1173 if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1175 HasKindDecoration = true;
1180 if (Policy.AnonymousTagLocations) {
1181 // Suppress the redundant tag keyword if we just printed one.
1182 // We don't have to worry about ElaboratedTypes here because you can't
1183 // refer to an anonymous type with one.
1184 if (!HasKindDecoration)
1185 OS << " " << D->getKindName();
1187 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1189 if (PLoc.isValid()) {
1191 StringRef File = PLoc.getFilename();
1192 if (Policy.RemapFilePaths)
1193 OS << Policy.remapPath(File);
1196 OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
1200 OS << (Policy.MSVCFormatting ? '\'' : ')');
1203 // If this is a class template specialization, print the template
1205 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1206 ArrayRef<TemplateArgument> Args;
1207 TypeSourceInfo *TAW = Spec->getTypeAsWritten();
1208 if (!Policy.PrintCanonicalTypes && TAW) {
1209 const TemplateSpecializationType *TST =
1210 cast<TemplateSpecializationType>(TAW->getType());
1211 Args = TST->template_arguments();
1213 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1214 Args = TemplateArgs.asArray();
1216 IncludeStrongLifetimeRAII Strong(Policy);
1217 printTemplateArgumentList(OS, Args, Policy);
1220 spaceBeforePlaceHolder(OS);
1223 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1224 printTag(T->getDecl(), OS);
1227 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
1229 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1230 printTag(T->getDecl(), OS);
1233 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
1235 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1237 if (IdentifierInfo *Id = T->getIdentifier())
1238 OS << Id->getName();
1240 bool IsLambdaAutoParam = false;
1241 if (auto D = T->getDecl()) {
1242 if (auto M = dyn_cast_or_null<CXXMethodDecl>(D->getDeclContext()))
1243 IsLambdaAutoParam = D->isImplicit() && M->getParent()->isLambda();
1246 if (IsLambdaAutoParam)
1249 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1251 spaceBeforePlaceHolder(OS);
1254 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1257 void TypePrinter::printSubstTemplateTypeParmBefore(
1258 const SubstTemplateTypeParmType *T,
1260 IncludeStrongLifetimeRAII Strong(Policy);
1261 printBefore(T->getReplacementType(), OS);
1264 void TypePrinter::printSubstTemplateTypeParmAfter(
1265 const SubstTemplateTypeParmType *T,
1267 IncludeStrongLifetimeRAII Strong(Policy);
1268 printAfter(T->getReplacementType(), OS);
1271 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1272 const SubstTemplateTypeParmPackType *T,
1274 IncludeStrongLifetimeRAII Strong(Policy);
1275 printTemplateTypeParmBefore(T->getReplacedParameter(), OS);
1278 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1279 const SubstTemplateTypeParmPackType *T,
1281 IncludeStrongLifetimeRAII Strong(Policy);
1282 printTemplateTypeParmAfter(T->getReplacedParameter(), OS);
1285 void TypePrinter::printTemplateSpecializationBefore(
1286 const TemplateSpecializationType *T,
1288 IncludeStrongLifetimeRAII Strong(Policy);
1289 T->getTemplateName().print(OS, Policy);
1291 printTemplateArgumentList(OS, T->template_arguments(), Policy);
1292 spaceBeforePlaceHolder(OS);
1295 void TypePrinter::printTemplateSpecializationAfter(
1296 const TemplateSpecializationType *T,
1299 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1301 printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1304 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1307 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1309 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
1310 TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
1311 assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
1312 "OwnedTagDecl expected to be a declaration for the type");
1313 PrintingPolicy SubPolicy = Policy;
1314 SubPolicy.IncludeTagDefinition = false;
1315 OwnedTagDecl->print(OS, SubPolicy, Indentation);
1316 spaceBeforePlaceHolder(OS);
1320 // The tag definition will take care of these.
1321 if (!Policy.IncludeTagDefinition)
1323 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1324 if (T->getKeyword() != ETK_None)
1326 NestedNameSpecifier *Qualifier = T->getQualifier();
1328 Qualifier->print(OS, Policy);
1331 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1332 printBefore(T->getNamedType(), OS);
1335 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1337 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
1339 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1340 printAfter(T->getNamedType(), OS);
1343 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1344 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1345 printBefore(T->getInnerType(), OS);
1348 printBefore(T->getInnerType(), OS);
1351 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1352 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1354 printAfter(T->getInnerType(), OS);
1356 printAfter(T->getInnerType(), OS);
1359 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1361 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1362 if (T->getKeyword() != ETK_None)
1365 T->getQualifier()->print(OS, Policy);
1367 OS << T->getIdentifier()->getName();
1368 spaceBeforePlaceHolder(OS);
1371 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1374 void TypePrinter::printDependentTemplateSpecializationBefore(
1375 const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1376 IncludeStrongLifetimeRAII Strong(Policy);
1378 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1379 if (T->getKeyword() != ETK_None)
1382 if (T->getQualifier())
1383 T->getQualifier()->print(OS, Policy);
1384 OS << T->getIdentifier()->getName();
1385 printTemplateArgumentList(OS, T->template_arguments(), Policy);
1386 spaceBeforePlaceHolder(OS);
1389 void TypePrinter::printDependentTemplateSpecializationAfter(
1390 const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
1392 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1394 printBefore(T->getPattern(), OS);
1397 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1399 printAfter(T->getPattern(), OS);
1403 void TypePrinter::printAttributedBefore(const AttributedType *T,
1405 // FIXME: Generate this with TableGen.
1407 // Prefer the macro forms of the GC and ownership qualifiers.
1408 if (T->getAttrKind() == attr::ObjCGC ||
1409 T->getAttrKind() == attr::ObjCOwnership)
1410 return printBefore(T->getEquivalentType(), OS);
1412 if (T->getAttrKind() == attr::ObjCKindOf)
1415 if (T->getAttrKind() == attr::AddressSpace)
1416 printBefore(T->getEquivalentType(), OS);
1418 printBefore(T->getModifiedType(), OS);
1420 if (T->isMSTypeSpec()) {
1421 switch (T->getAttrKind()) {
1423 case attr::Ptr32: OS << " __ptr32"; break;
1424 case attr::Ptr64: OS << " __ptr64"; break;
1425 case attr::SPtr: OS << " __sptr"; break;
1426 case attr::UPtr: OS << " __uptr"; break;
1428 spaceBeforePlaceHolder(OS);
1431 // Print nullability type specifiers.
1432 if (T->getImmediateNullability()) {
1433 if (T->getAttrKind() == attr::TypeNonNull)
1435 else if (T->getAttrKind() == attr::TypeNullable)
1437 else if (T->getAttrKind() == attr::TypeNullUnspecified)
1438 OS << " _Null_unspecified";
1440 llvm_unreachable("unhandled nullability");
1441 spaceBeforePlaceHolder(OS);
1445 void TypePrinter::printAttributedAfter(const AttributedType *T,
1447 // FIXME: Generate this with TableGen.
1449 // Prefer the macro forms of the GC and ownership qualifiers.
1450 if (T->getAttrKind() == attr::ObjCGC ||
1451 T->getAttrKind() == attr::ObjCOwnership)
1452 return printAfter(T->getEquivalentType(), OS);
1454 // If this is a calling convention attribute, don't print the implicit CC from
1455 // the modified type.
1456 SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1458 printAfter(T->getModifiedType(), OS);
1460 // Some attributes are printed as qualifiers before the type, so we have
1461 // nothing left to do.
1462 if (T->getAttrKind() == attr::ObjCKindOf ||
1463 T->isMSTypeSpec() || T->getImmediateNullability())
1466 // Don't print the inert __unsafe_unretained attribute at all.
1467 if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained)
1470 // Don't print ns_returns_retained unless it had an effect.
1471 if (T->getAttrKind() == attr::NSReturnsRetained &&
1472 !T->getEquivalentType()->castAs<FunctionType>()
1473 ->getExtInfo().getProducesResult())
1476 if (T->getAttrKind() == attr::LifetimeBound) {
1477 OS << " [[clang::lifetimebound]]";
1481 // The printing of the address_space attribute is handled by the qualifier
1482 // since it is still stored in the qualifier. Return early to prevent printing
1484 if (T->getAttrKind() == attr::AddressSpace)
1487 OS << " __attribute__((";
1488 switch (T->getAttrKind()) {
1489 #define TYPE_ATTR(NAME)
1490 #define DECL_OR_TYPE_ATTR(NAME)
1491 #define ATTR(NAME) case attr::NAME:
1492 #include "clang/Basic/AttrList.inc"
1493 llvm_unreachable("non-type attribute attached to type");
1495 case attr::OpenCLPrivateAddressSpace:
1496 case attr::OpenCLGlobalAddressSpace:
1497 case attr::OpenCLLocalAddressSpace:
1498 case attr::OpenCLConstantAddressSpace:
1499 case attr::OpenCLGenericAddressSpace:
1500 // FIXME: Update printAttributedBefore to print these once we generate
1501 // AttributedType nodes for them.
1504 case attr::LifetimeBound:
1505 case attr::TypeNonNull:
1506 case attr::TypeNullable:
1507 case attr::TypeNullUnspecified:
1509 case attr::ObjCInertUnsafeUnretained:
1510 case attr::ObjCKindOf:
1511 case attr::ObjCOwnership:
1516 case attr::AddressSpace:
1517 llvm_unreachable("This attribute should have been handled already");
1519 case attr::NSReturnsRetained:
1520 OS << "ns_returns_retained";
1523 // FIXME: When Sema learns to form this AttributedType, avoid printing the
1524 // attribute again in printFunctionProtoAfter.
1525 case attr::AnyX86NoCfCheck: OS << "nocf_check"; break;
1526 case attr::CDecl: OS << "cdecl"; break;
1527 case attr::FastCall: OS << "fastcall"; break;
1528 case attr::StdCall: OS << "stdcall"; break;
1529 case attr::ThisCall: OS << "thiscall"; break;
1530 case attr::SwiftCall: OS << "swiftcall"; break;
1531 case attr::VectorCall: OS << "vectorcall"; break;
1532 case attr::Pascal: OS << "pascal"; break;
1533 case attr::MSABI: OS << "ms_abi"; break;
1534 case attr::SysVABI: OS << "sysv_abi"; break;
1535 case attr::RegCall: OS << "regcall"; break;
1538 QualType t = T->getEquivalentType();
1539 while (!t->isFunctionType())
1540 t = t->getPointeeType();
1541 OS << (t->castAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1542 "\"aapcs\"" : "\"aapcs-vfp\"");
1546 case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break;
1547 case attr::IntelOclBicc: OS << "inteloclbicc"; break;
1548 case attr::PreserveMost:
1549 OS << "preserve_most";
1552 case attr::PreserveAll:
1553 OS << "preserve_all";
1562 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1564 OS << T->getDecl()->getName();
1565 spaceBeforePlaceHolder(OS);
1568 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1571 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1573 OS << T->getDecl()->getName();
1574 if (!T->qual_empty()) {
1575 bool isFirst = true;
1577 for (const auto *I : T->quals()) {
1587 spaceBeforePlaceHolder(OS);
1590 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1593 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1595 if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1596 !T->isKindOfTypeAsWritten())
1597 return printBefore(T->getBaseType(), OS);
1599 if (T->isKindOfTypeAsWritten())
1602 print(T->getBaseType(), OS, StringRef());
1604 if (T->isSpecializedAsWritten()) {
1605 bool isFirst = true;
1607 for (auto typeArg : T->getTypeArgsAsWritten()) {
1613 print(typeArg, OS, StringRef());
1618 if (!T->qual_empty()) {
1619 bool isFirst = true;
1621 for (const auto *I : T->quals()) {
1631 spaceBeforePlaceHolder(OS);
1634 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1636 if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1637 !T->isKindOfTypeAsWritten())
1638 return printAfter(T->getBaseType(), OS);
1641 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1643 printBefore(T->getPointeeType(), OS);
1645 // If we need to print the pointer, print it now.
1646 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1647 !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1648 if (HasEmptyPlaceHolder)
1654 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1658 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
1660 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
1661 return A.getArgument();
1664 static void printArgument(const TemplateArgument &A, const PrintingPolicy &PP,
1665 llvm::raw_ostream &OS) {
1669 static void printArgument(const TemplateArgumentLoc &A,
1670 const PrintingPolicy &PP, llvm::raw_ostream &OS) {
1671 const TemplateArgument::ArgKind &Kind = A.getArgument().getKind();
1672 if (Kind == TemplateArgument::ArgKind::Type)
1673 return A.getTypeSourceInfo()->getType().print(OS, PP);
1674 return A.getArgument().print(PP, OS);
1677 template<typename TA>
1678 static void printTo(raw_ostream &OS, ArrayRef<TA> Args,
1679 const PrintingPolicy &Policy, bool SkipBrackets) {
1680 const char *Comma = Policy.MSVCFormatting ? "," : ", ";
1684 bool NeedSpace = false;
1685 bool FirstArg = true;
1686 for (const auto &Arg : Args) {
1687 // Print the argument into a string.
1688 SmallString<128> Buf;
1689 llvm::raw_svector_ostream ArgOS(Buf);
1690 const TemplateArgument &Argument = getArgument(Arg);
1691 if (Argument.getKind() == TemplateArgument::Pack) {
1692 if (Argument.pack_size() && !FirstArg)
1694 printTo(ArgOS, Argument.getPackAsArray(), Policy, true);
1698 // Tries to print the argument with location info if exists.
1699 printArgument(Arg, Policy, ArgOS);
1701 StringRef ArgString = ArgOS.str();
1703 // If this is the first argument and its string representation
1704 // begins with the global scope specifier ('::foo'), add a space
1705 // to avoid printing the diagraph '<:'.
1706 if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
1711 NeedSpace = (!ArgString.empty() && ArgString.back() == '>');
1715 // If the last character of our string is '>', add another space to
1716 // keep the two '>''s separate tokens. We don't *have* to do this in
1717 // C++0x, but it's still good hygiene.
1725 void clang::printTemplateArgumentList(raw_ostream &OS,
1726 const TemplateArgumentListInfo &Args,
1727 const PrintingPolicy &Policy) {
1728 return printTo(OS, Args.arguments(), Policy, false);
1731 void clang::printTemplateArgumentList(raw_ostream &OS,
1732 ArrayRef<TemplateArgument> Args,
1733 const PrintingPolicy &Policy) {
1734 printTo(OS, Args, Policy, false);
1737 void clang::printTemplateArgumentList(raw_ostream &OS,
1738 ArrayRef<TemplateArgumentLoc> Args,
1739 const PrintingPolicy &Policy) {
1740 printTo(OS, Args, Policy, false);
1743 std::string Qualifiers::getAsString() const {
1745 return getAsString(PrintingPolicy(LO));
1748 // Appends qualifiers to the given string, separated by spaces. Will
1749 // prefix a space if the string is non-empty. Will not append a final
1751 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
1752 SmallString<64> Buf;
1753 llvm::raw_svector_ostream StrOS(Buf);
1754 print(StrOS, Policy);
1758 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
1759 if (getCVRQualifiers())
1762 if (getAddressSpace() != LangAS::Default)
1765 if (getObjCGCAttr())
1768 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
1769 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
1775 // Appends qualifiers to the given string, separated by spaces. Will
1776 // prefix a space if the string is non-empty. Will not append a final
1778 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
1779 bool appendSpaceIfNonEmpty) const {
1780 bool addSpace = false;
1782 unsigned quals = getCVRQualifiers();
1784 AppendTypeQualList(OS, quals, Policy.Restrict);
1787 if (hasUnaligned()) {
1790 OS << "__unaligned";
1793 LangAS addrspace = getAddressSpace();
1794 if (addrspace != LangAS::Default) {
1795 if (addrspace != LangAS::opencl_private) {
1799 switch (addrspace) {
1800 case LangAS::opencl_global:
1803 case LangAS::opencl_local:
1806 case LangAS::opencl_private:
1808 case LangAS::opencl_constant:
1811 case LangAS::opencl_generic:
1814 case LangAS::cuda_device:
1817 case LangAS::cuda_constant:
1818 OS << "__constant__";
1820 case LangAS::cuda_shared:
1824 OS << "__attribute__((address_space(";
1825 OS << toTargetAddressSpace(addrspace);
1830 if (Qualifiers::GC gc = getObjCGCAttr()) {
1834 if (gc == Qualifiers::Weak)
1839 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
1840 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
1847 case Qualifiers::OCL_None: llvm_unreachable("none but true");
1848 case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
1849 case Qualifiers::OCL_Strong:
1850 if (!Policy.SuppressStrongLifetime)
1854 case Qualifiers::OCL_Weak: OS << "__weak"; break;
1855 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
1859 if (appendSpaceIfNonEmpty && addSpace)
1863 std::string QualType::getAsString() const {
1864 return getAsString(split(), LangOptions());
1867 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
1869 getAsStringInternal(S, Policy);
1873 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
1874 const PrintingPolicy &Policy) {
1876 getAsStringInternal(ty, qs, buffer, Policy);
1880 void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy,
1881 const Twine &PlaceHolder, unsigned Indentation) const {
1882 print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder,
1886 void QualType::print(const Type *ty, Qualifiers qs,
1887 raw_ostream &OS, const PrintingPolicy &policy,
1888 const Twine &PlaceHolder, unsigned Indentation) {
1889 SmallString<128> PHBuf;
1890 StringRef PH = PlaceHolder.toStringRef(PHBuf);
1892 TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
1895 void QualType::getAsStringInternal(std::string &Str,
1896 const PrintingPolicy &Policy) const {
1897 return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str,
1901 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
1902 std::string &buffer,
1903 const PrintingPolicy &policy) {
1904 SmallString<256> Buf;
1905 llvm::raw_svector_ostream StrOS(Buf);
1906 TypePrinter(policy).print(ty, qs, StrOS, buffer);
1907 std::string str = StrOS.str();