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/ASTContext.h"
14 #include "clang/AST/Attr.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/PrettyPrinter.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/TemplateName.h"
25 #include "clang/AST/TextNodeDumper.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/AddressSpaces.h"
28 #include "clang/Basic/ExceptionSpecificationType.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/SourceLocation.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/Specifiers.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/SaveAndRestore.h"
44 #include "llvm/Support/raw_ostream.h"
48 using namespace clang
;
52 /// RAII object that enables printing of the ARC __strong lifetime
54 class IncludeStrongLifetimeRAII
{
55 PrintingPolicy
&Policy
;
59 explicit IncludeStrongLifetimeRAII(PrintingPolicy
&Policy
)
60 : Policy(Policy
), Old(Policy
.SuppressStrongLifetime
) {
61 if (!Policy
.SuppressLifetimeQualifiers
)
62 Policy
.SuppressStrongLifetime
= false;
65 ~IncludeStrongLifetimeRAII() { Policy
.SuppressStrongLifetime
= Old
; }
68 class ParamPolicyRAII
{
69 PrintingPolicy
&Policy
;
73 explicit ParamPolicyRAII(PrintingPolicy
&Policy
)
74 : Policy(Policy
), Old(Policy
.SuppressSpecifiers
) {
75 Policy
.SuppressSpecifiers
= false;
78 ~ParamPolicyRAII() { Policy
.SuppressSpecifiers
= Old
; }
81 class DefaultTemplateArgsPolicyRAII
{
82 PrintingPolicy
&Policy
;
86 explicit DefaultTemplateArgsPolicyRAII(PrintingPolicy
&Policy
)
87 : Policy(Policy
), Old(Policy
.SuppressDefaultTemplateArgs
) {
88 Policy
.SuppressDefaultTemplateArgs
= false;
91 ~DefaultTemplateArgsPolicyRAII() { Policy
.SuppressDefaultTemplateArgs
= Old
; }
94 class ElaboratedTypePolicyRAII
{
95 PrintingPolicy
&Policy
;
96 bool SuppressTagKeyword
;
100 explicit ElaboratedTypePolicyRAII(PrintingPolicy
&Policy
) : Policy(Policy
) {
101 SuppressTagKeyword
= Policy
.SuppressTagKeyword
;
102 SuppressScope
= Policy
.SuppressScope
;
103 Policy
.SuppressTagKeyword
= true;
104 Policy
.SuppressScope
= true;
107 ~ElaboratedTypePolicyRAII() {
108 Policy
.SuppressTagKeyword
= SuppressTagKeyword
;
109 Policy
.SuppressScope
= SuppressScope
;
114 PrintingPolicy Policy
;
115 unsigned Indentation
;
116 bool HasEmptyPlaceHolder
= false;
117 bool InsideCCAttribute
= false;
120 explicit TypePrinter(const PrintingPolicy
&Policy
, unsigned Indentation
= 0)
121 : Policy(Policy
), Indentation(Indentation
) {}
123 void print(const Type
*ty
, Qualifiers qs
, raw_ostream
&OS
,
124 StringRef PlaceHolder
);
125 void print(QualType T
, raw_ostream
&OS
, StringRef PlaceHolder
);
127 static bool canPrefixQualifiers(const Type
*T
, bool &NeedARCStrongQualifier
);
128 void spaceBeforePlaceHolder(raw_ostream
&OS
);
129 void printTypeSpec(NamedDecl
*D
, raw_ostream
&OS
);
130 void printTemplateId(const TemplateSpecializationType
*T
, raw_ostream
&OS
,
133 void printBefore(QualType T
, raw_ostream
&OS
);
134 void printAfter(QualType T
, raw_ostream
&OS
);
135 void AppendScope(DeclContext
*DC
, raw_ostream
&OS
,
136 DeclarationName NameInScope
);
137 void printTag(TagDecl
*T
, raw_ostream
&OS
);
138 void printFunctionAfter(const FunctionType::ExtInfo
&Info
, raw_ostream
&OS
);
139 #define ABSTRACT_TYPE(CLASS, PARENT)
140 #define TYPE(CLASS, PARENT) \
141 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \
142 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
143 #include "clang/AST/TypeNodes.inc"
146 void printBefore(const Type
*ty
, Qualifiers qs
, raw_ostream
&OS
);
147 void printAfter(const Type
*ty
, Qualifiers qs
, raw_ostream
&OS
);
152 static void AppendTypeQualList(raw_ostream
&OS
, unsigned TypeQuals
,
153 bool HasRestrictKeyword
) {
154 bool appendSpace
= false;
155 if (TypeQuals
& Qualifiers::Const
) {
159 if (TypeQuals
& Qualifiers::Volatile
) {
160 if (appendSpace
) OS
<< ' ';
164 if (TypeQuals
& Qualifiers::Restrict
) {
165 if (appendSpace
) OS
<< ' ';
166 if (HasRestrictKeyword
) {
174 void TypePrinter::spaceBeforePlaceHolder(raw_ostream
&OS
) {
175 if (!HasEmptyPlaceHolder
)
179 static SplitQualType
splitAccordingToPolicy(QualType QT
,
180 const PrintingPolicy
&Policy
) {
181 if (Policy
.PrintCanonicalTypes
)
182 QT
= QT
.getCanonicalType();
186 void TypePrinter::print(QualType t
, raw_ostream
&OS
, StringRef PlaceHolder
) {
187 SplitQualType split
= splitAccordingToPolicy(t
, Policy
);
188 print(split
.Ty
, split
.Quals
, OS
, PlaceHolder
);
191 void TypePrinter::print(const Type
*T
, Qualifiers Quals
, raw_ostream
&OS
,
192 StringRef PlaceHolder
) {
198 SaveAndRestore
PHVal(HasEmptyPlaceHolder
, PlaceHolder
.empty());
200 printBefore(T
, Quals
, OS
);
202 printAfter(T
, Quals
, OS
);
205 bool TypePrinter::canPrefixQualifiers(const Type
*T
,
206 bool &NeedARCStrongQualifier
) {
207 // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
208 // so that we get "const int" instead of "int const", but we can't do this if
209 // the type is complex. For example if the type is "int*", we *must* print
210 // "int * const", printing "const int *" is different. Only do this when the
211 // type expands to a simple string.
212 bool CanPrefixQualifiers
= false;
213 NeedARCStrongQualifier
= false;
214 const Type
*UnderlyingType
= T
;
215 if (const auto *AT
= dyn_cast
<AutoType
>(T
))
216 UnderlyingType
= AT
->desugar().getTypePtr();
217 if (const auto *Subst
= dyn_cast
<SubstTemplateTypeParmType
>(T
))
218 UnderlyingType
= Subst
->getReplacementType().getTypePtr();
219 Type::TypeClass TC
= UnderlyingType
->getTypeClass();
225 case Type::UnresolvedUsing
:
228 case Type::TypeOfExpr
:
231 case Type::UnaryTransform
:
234 case Type::Elaborated
:
235 case Type::TemplateTypeParm
:
236 case Type::SubstTemplateTypeParmPack
:
237 case Type::DeducedTemplateSpecialization
:
238 case Type::TemplateSpecialization
:
239 case Type::InjectedClassName
:
240 case Type::DependentName
:
241 case Type::DependentTemplateSpecialization
:
242 case Type::ObjCObject
:
243 case Type::ObjCTypeParam
:
244 case Type::ObjCInterface
:
248 case Type::DependentBitInt
:
249 case Type::BTFTagAttributed
:
250 CanPrefixQualifiers
= true;
253 case Type::ObjCObjectPointer
:
254 CanPrefixQualifiers
= T
->isObjCIdType() || T
->isObjCClassType() ||
255 T
->isObjCQualifiedIdType() || T
->isObjCQualifiedClassType();
258 case Type::VariableArray
:
259 case Type::DependentSizedArray
:
260 NeedARCStrongQualifier
= true;
263 case Type::ConstantArray
:
264 case Type::IncompleteArray
:
265 return canPrefixQualifiers(
266 cast
<ArrayType
>(UnderlyingType
)->getElementType().getTypePtr(),
267 NeedARCStrongQualifier
);
272 case Type::BlockPointer
:
273 case Type::LValueReference
:
274 case Type::RValueReference
:
275 case Type::MemberPointer
:
276 case Type::DependentAddressSpace
:
277 case Type::DependentVector
:
278 case Type::DependentSizedExtVector
:
280 case Type::ExtVector
:
281 case Type::ConstantMatrix
:
282 case Type::DependentSizedMatrix
:
283 case Type::FunctionProto
:
284 case Type::FunctionNoProto
:
286 case Type::PackExpansion
:
287 case Type::SubstTemplateTypeParm
:
288 case Type::MacroQualified
:
289 CanPrefixQualifiers
= false;
292 case Type::Attributed
: {
293 // We still want to print the address_space before the type if it is an
294 // address_space attribute.
295 const auto *AttrTy
= cast
<AttributedType
>(UnderlyingType
);
296 CanPrefixQualifiers
= AttrTy
->getAttrKind() == attr::AddressSpace
;
301 return CanPrefixQualifiers
;
304 void TypePrinter::printBefore(QualType T
, raw_ostream
&OS
) {
305 SplitQualType Split
= splitAccordingToPolicy(T
, Policy
);
307 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
309 Qualifiers Quals
= Split
.Quals
;
310 if (const auto *Subst
= dyn_cast
<SubstTemplateTypeParmType
>(Split
.Ty
))
311 Quals
-= QualType(Subst
, 0).getQualifiers();
313 printBefore(Split
.Ty
, Quals
, OS
);
316 /// Prints the part of the type string before an identifier, e.g. for
317 /// "int foo[10]" it prints "int ".
318 void TypePrinter::printBefore(const Type
*T
,Qualifiers Quals
, raw_ostream
&OS
) {
319 if (Policy
.SuppressSpecifiers
&& T
->isSpecifierType())
322 SaveAndRestore
PrevPHIsEmpty(HasEmptyPlaceHolder
);
324 // Print qualifiers as appropriate.
326 bool CanPrefixQualifiers
= false;
327 bool NeedARCStrongQualifier
= false;
328 CanPrefixQualifiers
= canPrefixQualifiers(T
, NeedARCStrongQualifier
);
330 if (CanPrefixQualifiers
&& !Quals
.empty()) {
331 if (NeedARCStrongQualifier
) {
332 IncludeStrongLifetimeRAII
Strong(Policy
);
333 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/true);
335 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/true);
339 bool hasAfterQuals
= false;
340 if (!CanPrefixQualifiers
&& !Quals
.empty()) {
341 hasAfterQuals
= !Quals
.isEmptyWhenPrinted(Policy
);
343 HasEmptyPlaceHolder
= false;
346 switch (T
->getTypeClass()) {
347 #define ABSTRACT_TYPE(CLASS, PARENT)
348 #define TYPE(CLASS, PARENT) case Type::CLASS: \
349 print##CLASS##Before(cast<CLASS##Type>(T), OS); \
351 #include "clang/AST/TypeNodes.inc"
355 if (NeedARCStrongQualifier
) {
356 IncludeStrongLifetimeRAII
Strong(Policy
);
357 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty
.get());
359 Quals
.print(OS
, Policy
, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty
.get());
364 void TypePrinter::printAfter(QualType t
, raw_ostream
&OS
) {
365 SplitQualType split
= splitAccordingToPolicy(t
, Policy
);
366 printAfter(split
.Ty
, split
.Quals
, OS
);
369 /// Prints the part of the type string after an identifier, e.g. for
370 /// "int foo[10]" it prints "[10]".
371 void TypePrinter::printAfter(const Type
*T
, Qualifiers Quals
, raw_ostream
&OS
) {
372 switch (T
->getTypeClass()) {
373 #define ABSTRACT_TYPE(CLASS, PARENT)
374 #define TYPE(CLASS, PARENT) case Type::CLASS: \
375 print##CLASS##After(cast<CLASS##Type>(T), OS); \
377 #include "clang/AST/TypeNodes.inc"
381 void TypePrinter::printBuiltinBefore(const BuiltinType
*T
, raw_ostream
&OS
) {
382 OS
<< T
->getName(Policy
);
383 spaceBeforePlaceHolder(OS
);
386 void TypePrinter::printBuiltinAfter(const BuiltinType
*T
, raw_ostream
&OS
) {}
388 void TypePrinter::printComplexBefore(const ComplexType
*T
, raw_ostream
&OS
) {
390 printBefore(T
->getElementType(), OS
);
393 void TypePrinter::printComplexAfter(const ComplexType
*T
, raw_ostream
&OS
) {
394 printAfter(T
->getElementType(), OS
);
397 void TypePrinter::printPointerBefore(const PointerType
*T
, raw_ostream
&OS
) {
398 IncludeStrongLifetimeRAII
Strong(Policy
);
399 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
400 printBefore(T
->getPointeeType(), OS
);
401 // Handle things like 'int (*A)[4];' correctly.
402 // FIXME: this should include vectors, but vectors use attributes I guess.
403 if (isa
<ArrayType
>(T
->getPointeeType()))
408 void TypePrinter::printPointerAfter(const PointerType
*T
, raw_ostream
&OS
) {
409 IncludeStrongLifetimeRAII
Strong(Policy
);
410 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
411 // Handle things like 'int (*A)[4];' correctly.
412 // FIXME: this should include vectors, but vectors use attributes I guess.
413 if (isa
<ArrayType
>(T
->getPointeeType()))
415 printAfter(T
->getPointeeType(), OS
);
418 void TypePrinter::printBlockPointerBefore(const BlockPointerType
*T
,
420 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
421 printBefore(T
->getPointeeType(), OS
);
425 void TypePrinter::printBlockPointerAfter(const BlockPointerType
*T
,
427 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
428 printAfter(T
->getPointeeType(), OS
);
431 // When printing a reference, the referenced type might also be a reference.
432 // If so, we want to skip that before printing the inner type.
433 static QualType
skipTopLevelReferences(QualType T
) {
434 if (auto *Ref
= T
->getAs
<ReferenceType
>())
435 return skipTopLevelReferences(Ref
->getPointeeTypeAsWritten());
439 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType
*T
,
441 IncludeStrongLifetimeRAII
Strong(Policy
);
442 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
443 QualType Inner
= skipTopLevelReferences(T
->getPointeeTypeAsWritten());
444 printBefore(Inner
, OS
);
445 // Handle things like 'int (&A)[4];' correctly.
446 // FIXME: this should include vectors, but vectors use attributes I guess.
447 if (isa
<ArrayType
>(Inner
))
452 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType
*T
,
454 IncludeStrongLifetimeRAII
Strong(Policy
);
455 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
456 QualType Inner
= skipTopLevelReferences(T
->getPointeeTypeAsWritten());
457 // Handle things like 'int (&A)[4];' correctly.
458 // FIXME: this should include vectors, but vectors use attributes I guess.
459 if (isa
<ArrayType
>(Inner
))
461 printAfter(Inner
, OS
);
464 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType
*T
,
466 IncludeStrongLifetimeRAII
Strong(Policy
);
467 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
468 QualType Inner
= skipTopLevelReferences(T
->getPointeeTypeAsWritten());
469 printBefore(Inner
, OS
);
470 // Handle things like 'int (&&A)[4];' correctly.
471 // FIXME: this should include vectors, but vectors use attributes I guess.
472 if (isa
<ArrayType
>(Inner
))
477 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType
*T
,
479 IncludeStrongLifetimeRAII
Strong(Policy
);
480 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
481 QualType Inner
= skipTopLevelReferences(T
->getPointeeTypeAsWritten());
482 // Handle things like 'int (&&A)[4];' correctly.
483 // FIXME: this should include vectors, but vectors use attributes I guess.
484 if (isa
<ArrayType
>(Inner
))
486 printAfter(Inner
, OS
);
489 void TypePrinter::printMemberPointerBefore(const MemberPointerType
*T
,
491 IncludeStrongLifetimeRAII
Strong(Policy
);
492 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
493 printBefore(T
->getPointeeType(), OS
);
494 // Handle things like 'int (Cls::*A)[4];' correctly.
495 // FIXME: this should include vectors, but vectors use attributes I guess.
496 if (isa
<ArrayType
>(T
->getPointeeType()))
499 PrintingPolicy
InnerPolicy(Policy
);
500 InnerPolicy
.IncludeTagDefinition
= false;
501 TypePrinter(InnerPolicy
).print(QualType(T
->getClass(), 0), OS
, StringRef());
506 void TypePrinter::printMemberPointerAfter(const MemberPointerType
*T
,
508 IncludeStrongLifetimeRAII
Strong(Policy
);
509 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
510 // Handle things like 'int (Cls::*A)[4];' correctly.
511 // FIXME: this should include vectors, but vectors use attributes I guess.
512 if (isa
<ArrayType
>(T
->getPointeeType()))
514 printAfter(T
->getPointeeType(), OS
);
517 void TypePrinter::printConstantArrayBefore(const ConstantArrayType
*T
,
519 IncludeStrongLifetimeRAII
Strong(Policy
);
520 printBefore(T
->getElementType(), OS
);
523 void TypePrinter::printConstantArrayAfter(const ConstantArrayType
*T
,
526 if (T
->getIndexTypeQualifiers().hasQualifiers()) {
527 AppendTypeQualList(OS
, T
->getIndexTypeCVRQualifiers(),
532 if (T
->getSizeModifier() == ArraySizeModifier::Static
)
535 OS
<< T
->getSize().getZExtValue() << ']';
536 printAfter(T
->getElementType(), OS
);
539 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType
*T
,
541 IncludeStrongLifetimeRAII
Strong(Policy
);
542 printBefore(T
->getElementType(), OS
);
545 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType
*T
,
548 printAfter(T
->getElementType(), OS
);
551 void TypePrinter::printVariableArrayBefore(const VariableArrayType
*T
,
553 IncludeStrongLifetimeRAII
Strong(Policy
);
554 printBefore(T
->getElementType(), OS
);
557 void TypePrinter::printVariableArrayAfter(const VariableArrayType
*T
,
560 if (T
->getIndexTypeQualifiers().hasQualifiers()) {
561 AppendTypeQualList(OS
, T
->getIndexTypeCVRQualifiers(), Policy
.Restrict
);
565 if (T
->getSizeModifier() == ArraySizeModifier::Static
)
567 else if (T
->getSizeModifier() == ArraySizeModifier::Star
)
570 if (T
->getSizeExpr())
571 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
574 printAfter(T
->getElementType(), OS
);
577 void TypePrinter::printAdjustedBefore(const AdjustedType
*T
, raw_ostream
&OS
) {
578 // Print the adjusted representation, otherwise the adjustment will be
580 printBefore(T
->getAdjustedType(), OS
);
583 void TypePrinter::printAdjustedAfter(const AdjustedType
*T
, raw_ostream
&OS
) {
584 printAfter(T
->getAdjustedType(), OS
);
587 void TypePrinter::printDecayedBefore(const DecayedType
*T
, raw_ostream
&OS
) {
588 // Print as though it's a pointer.
589 printAdjustedBefore(T
, OS
);
592 void TypePrinter::printDecayedAfter(const DecayedType
*T
, raw_ostream
&OS
) {
593 printAdjustedAfter(T
, OS
);
596 void TypePrinter::printDependentSizedArrayBefore(
597 const DependentSizedArrayType
*T
,
599 IncludeStrongLifetimeRAII
Strong(Policy
);
600 printBefore(T
->getElementType(), OS
);
603 void TypePrinter::printDependentSizedArrayAfter(
604 const DependentSizedArrayType
*T
,
607 if (T
->getSizeExpr())
608 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
610 printAfter(T
->getElementType(), OS
);
613 void TypePrinter::printDependentAddressSpaceBefore(
614 const DependentAddressSpaceType
*T
, raw_ostream
&OS
) {
615 printBefore(T
->getPointeeType(), OS
);
618 void TypePrinter::printDependentAddressSpaceAfter(
619 const DependentAddressSpaceType
*T
, raw_ostream
&OS
) {
620 OS
<< " __attribute__((address_space(";
621 if (T
->getAddrSpaceExpr())
622 T
->getAddrSpaceExpr()->printPretty(OS
, nullptr, Policy
);
624 printAfter(T
->getPointeeType(), OS
);
627 void TypePrinter::printDependentSizedExtVectorBefore(
628 const DependentSizedExtVectorType
*T
,
630 printBefore(T
->getElementType(), OS
);
633 void TypePrinter::printDependentSizedExtVectorAfter(
634 const DependentSizedExtVectorType
*T
,
636 OS
<< " __attribute__((ext_vector_type(";
637 if (T
->getSizeExpr())
638 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
640 printAfter(T
->getElementType(), OS
);
643 void TypePrinter::printVectorBefore(const VectorType
*T
, raw_ostream
&OS
) {
644 switch (T
->getVectorKind()) {
645 case VectorKind::AltiVecPixel
:
646 OS
<< "__vector __pixel ";
648 case VectorKind::AltiVecBool
:
649 OS
<< "__vector __bool ";
650 printBefore(T
->getElementType(), OS
);
652 case VectorKind::AltiVecVector
:
654 printBefore(T
->getElementType(), OS
);
656 case VectorKind::Neon
:
657 OS
<< "__attribute__((neon_vector_type("
658 << T
->getNumElements() << "))) ";
659 printBefore(T
->getElementType(), OS
);
661 case VectorKind::NeonPoly
:
662 OS
<< "__attribute__((neon_polyvector_type(" <<
663 T
->getNumElements() << "))) ";
664 printBefore(T
->getElementType(), OS
);
666 case VectorKind::Generic
: {
667 // FIXME: We prefer to print the size directly here, but have no way
668 // to get the size of the type.
669 OS
<< "__attribute__((__vector_size__("
670 << T
->getNumElements()
672 print(T
->getElementType(), OS
, StringRef());
674 printBefore(T
->getElementType(), OS
);
677 case VectorKind::SveFixedLengthData
:
678 case VectorKind::SveFixedLengthPredicate
:
679 // FIXME: We prefer to print the size directly here, but have no way
680 // to get the size of the type.
681 OS
<< "__attribute__((__arm_sve_vector_bits__(";
683 if (T
->getVectorKind() == VectorKind::SveFixedLengthPredicate
)
684 // Predicates take a bit per byte of the vector size, multiply by 8 to
685 // get the number of bits passed to the attribute.
686 OS
<< T
->getNumElements() * 8;
688 OS
<< T
->getNumElements();
691 print(T
->getElementType(), OS
, StringRef());
692 // Multiply by 8 for the number of bits.
694 printBefore(T
->getElementType(), OS
);
696 case VectorKind::RVVFixedLengthData
:
697 // FIXME: We prefer to print the size directly here, but have no way
698 // to get the size of the type.
699 OS
<< "__attribute__((__riscv_rvv_vector_bits__(";
701 OS
<< T
->getNumElements();
704 print(T
->getElementType(), OS
, StringRef());
705 // Multiply by 8 for the number of bits.
707 printBefore(T
->getElementType(), OS
);
712 void TypePrinter::printVectorAfter(const VectorType
*T
, raw_ostream
&OS
) {
713 printAfter(T
->getElementType(), OS
);
716 void TypePrinter::printDependentVectorBefore(
717 const DependentVectorType
*T
, raw_ostream
&OS
) {
718 switch (T
->getVectorKind()) {
719 case VectorKind::AltiVecPixel
:
720 OS
<< "__vector __pixel ";
722 case VectorKind::AltiVecBool
:
723 OS
<< "__vector __bool ";
724 printBefore(T
->getElementType(), OS
);
726 case VectorKind::AltiVecVector
:
728 printBefore(T
->getElementType(), OS
);
730 case VectorKind::Neon
:
731 OS
<< "__attribute__((neon_vector_type(";
732 if (T
->getSizeExpr())
733 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
735 printBefore(T
->getElementType(), OS
);
737 case VectorKind::NeonPoly
:
738 OS
<< "__attribute__((neon_polyvector_type(";
739 if (T
->getSizeExpr())
740 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
742 printBefore(T
->getElementType(), OS
);
744 case VectorKind::Generic
: {
745 // FIXME: We prefer to print the size directly here, but have no way
746 // to get the size of the type.
747 OS
<< "__attribute__((__vector_size__(";
748 if (T
->getSizeExpr())
749 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
751 print(T
->getElementType(), OS
, StringRef());
753 printBefore(T
->getElementType(), OS
);
756 case VectorKind::SveFixedLengthData
:
757 case VectorKind::SveFixedLengthPredicate
:
758 // FIXME: We prefer to print the size directly here, but have no way
759 // to get the size of the type.
760 OS
<< "__attribute__((__arm_sve_vector_bits__(";
761 if (T
->getSizeExpr()) {
762 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
763 if (T
->getVectorKind() == VectorKind::SveFixedLengthPredicate
)
764 // Predicates take a bit per byte of the vector size, multiply by 8 to
765 // get the number of bits passed to the attribute.
768 print(T
->getElementType(), OS
, StringRef());
769 // Multiply by 8 for the number of bits.
773 printBefore(T
->getElementType(), OS
);
775 case VectorKind::RVVFixedLengthData
:
776 // FIXME: We prefer to print the size directly here, but have no way
777 // to get the size of the type.
778 OS
<< "__attribute__((__riscv_rvv_vector_bits__(";
779 if (T
->getSizeExpr()) {
780 T
->getSizeExpr()->printPretty(OS
, nullptr, Policy
);
782 print(T
->getElementType(), OS
, StringRef());
783 // Multiply by 8 for the number of bits.
787 printBefore(T
->getElementType(), OS
);
792 void TypePrinter::printDependentVectorAfter(
793 const DependentVectorType
*T
, raw_ostream
&OS
) {
794 printAfter(T
->getElementType(), OS
);
797 void TypePrinter::printExtVectorBefore(const ExtVectorType
*T
,
799 printBefore(T
->getElementType(), OS
);
802 void TypePrinter::printExtVectorAfter(const ExtVectorType
*T
, raw_ostream
&OS
) {
803 printAfter(T
->getElementType(), OS
);
804 OS
<< " __attribute__((ext_vector_type(";
805 OS
<< T
->getNumElements();
809 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType
*T
,
811 printBefore(T
->getElementType(), OS
);
812 OS
<< " __attribute__((matrix_type(";
813 OS
<< T
->getNumRows() << ", " << T
->getNumColumns();
817 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType
*T
,
819 printAfter(T
->getElementType(), OS
);
822 void TypePrinter::printDependentSizedMatrixBefore(
823 const DependentSizedMatrixType
*T
, raw_ostream
&OS
) {
824 printBefore(T
->getElementType(), OS
);
825 OS
<< " __attribute__((matrix_type(";
826 if (T
->getRowExpr()) {
827 T
->getRowExpr()->printPretty(OS
, nullptr, Policy
);
830 if (T
->getColumnExpr()) {
831 T
->getColumnExpr()->printPretty(OS
, nullptr, Policy
);
836 void TypePrinter::printDependentSizedMatrixAfter(
837 const DependentSizedMatrixType
*T
, raw_ostream
&OS
) {
838 printAfter(T
->getElementType(), OS
);
842 FunctionProtoType::printExceptionSpecification(raw_ostream
&OS
,
843 const PrintingPolicy
&Policy
)
845 if (hasDynamicExceptionSpec()) {
847 if (getExceptionSpecType() == EST_MSAny
)
850 for (unsigned I
= 0, N
= getNumExceptions(); I
!= N
; ++I
) {
854 OS
<< getExceptionType(I
).stream(Policy
);
857 } else if (EST_NoThrow
== getExceptionSpecType()) {
858 OS
<< " __attribute__((nothrow))";
859 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
861 // FIXME:Is it useful to print out the expression for a non-dependent
862 // noexcept specification?
863 if (isComputedNoexcept(getExceptionSpecType())) {
865 if (getNoexceptExpr())
866 getNoexceptExpr()->printPretty(OS
, nullptr, Policy
);
872 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType
*T
,
874 if (T
->hasTrailingReturn()) {
876 if (!HasEmptyPlaceHolder
)
879 // If needed for precedence reasons, wrap the inner part in grouping parens.
880 SaveAndRestore
PrevPHIsEmpty(HasEmptyPlaceHolder
, false);
881 printBefore(T
->getReturnType(), OS
);
882 if (!PrevPHIsEmpty
.get())
887 StringRef
clang::getParameterABISpelling(ParameterABI ABI
) {
889 case ParameterABI::Ordinary
:
890 llvm_unreachable("asking for spelling of ordinary parameter ABI");
891 case ParameterABI::SwiftContext
:
892 return "swift_context";
893 case ParameterABI::SwiftAsyncContext
:
894 return "swift_async_context";
895 case ParameterABI::SwiftErrorResult
:
896 return "swift_error_result";
897 case ParameterABI::SwiftIndirectResult
:
898 return "swift_indirect_result";
900 llvm_unreachable("bad parameter ABI kind");
903 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType
*T
,
905 // If needed for precedence reasons, wrap the inner part in grouping parens.
906 if (!HasEmptyPlaceHolder
)
908 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
912 ParamPolicyRAII
ParamPolicy(Policy
);
913 for (unsigned i
= 0, e
= T
->getNumParams(); i
!= e
; ++i
) {
916 auto EPI
= T
->getExtParameterInfo(i
);
917 if (EPI
.isConsumed()) OS
<< "__attribute__((ns_consumed)) ";
918 if (EPI
.isNoEscape())
919 OS
<< "__attribute__((noescape)) ";
920 auto ABI
= EPI
.getABI();
921 if (ABI
!= ParameterABI::Ordinary
)
922 OS
<< "__attribute__((" << getParameterABISpelling(ABI
) << ")) ";
924 print(T
->getParamType(i
), OS
, StringRef());
928 if (T
->isVariadic()) {
929 if (T
->getNumParams())
932 } else if (T
->getNumParams() == 0 && Policy
.UseVoidForZeroParams
) {
933 // Do not emit int() if we have a proto, emit 'int(void)'.
939 FunctionType::ExtInfo Info
= T
->getExtInfo();
941 if ((T
->getAArch64SMEAttributes() & FunctionType::SME_PStateSMCompatibleMask
))
942 OS
<< " __arm_streaming_compatible";
943 if ((T
->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask
))
944 OS
<< " __arm_streaming";
945 if ((T
->getAArch64SMEAttributes() & FunctionType::SME_PStateZASharedMask
))
946 OS
<< " __arm_shared_za";
947 if ((T
->getAArch64SMEAttributes() & FunctionType::SME_PStateZAPreservedMask
))
948 OS
<< " __arm_preserves_za";
950 printFunctionAfter(Info
, OS
);
952 if (!T
->getMethodQuals().empty())
953 OS
<< " " << T
->getMethodQuals().getAsString();
955 switch (T
->getRefQualifier()) {
967 T
->printExceptionSpecification(OS
, Policy
);
969 if (T
->hasTrailingReturn()) {
971 print(T
->getReturnType(), OS
, StringRef());
973 printAfter(T
->getReturnType(), OS
);
976 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo
&Info
,
978 if (!InsideCCAttribute
) {
979 switch (Info
.getCC()) {
981 // The C calling convention is the default on the vast majority of platforms
982 // we support. If the user wrote it explicitly, it will usually be printed
983 // while traversing the AttributedType. If the type has been desugared, let
984 // the canonical spelling be the implicit calling convention.
985 // FIXME: It would be better to be explicit in certain contexts, such as a
986 // cdecl function typedef used to declare a member function with the
987 // Microsoft C++ ABI.
990 OS
<< " __attribute__((stdcall))";
993 OS
<< " __attribute__((fastcall))";
996 OS
<< " __attribute__((thiscall))";
998 case CC_X86VectorCall
:
999 OS
<< " __attribute__((vectorcall))";
1002 OS
<< " __attribute__((pascal))";
1005 OS
<< " __attribute__((pcs(\"aapcs\")))";
1008 OS
<< " __attribute__((pcs(\"aapcs-vfp\")))";
1010 case CC_AArch64VectorCall
:
1011 OS
<< "__attribute__((aarch64_vector_pcs))";
1013 case CC_AArch64SVEPCS
:
1014 OS
<< "__attribute__((aarch64_sve_pcs))";
1016 case CC_AMDGPUKernelCall
:
1017 OS
<< "__attribute__((amdgpu_kernel))";
1019 case CC_IntelOclBicc
:
1020 OS
<< " __attribute__((intel_ocl_bicc))";
1023 OS
<< " __attribute__((ms_abi))";
1026 OS
<< " __attribute__((sysv_abi))";
1029 OS
<< " __attribute__((regcall))";
1031 case CC_SpirFunction
:
1032 case CC_OpenCLKernel
:
1033 // Do nothing. These CCs are not available as attributes.
1036 OS
<< " __attribute__((swiftcall))";
1039 OS
<< "__attribute__((swiftasynccall))";
1041 case CC_PreserveMost
:
1042 OS
<< " __attribute__((preserve_most))";
1044 case CC_PreserveAll
:
1045 OS
<< " __attribute__((preserve_all))";
1048 OS
<< " __attribute__((m68k_rtd))";
1053 if (Info
.getNoReturn())
1054 OS
<< " __attribute__((noreturn))";
1055 if (Info
.getCmseNSCall())
1056 OS
<< " __attribute__((cmse_nonsecure_call))";
1057 if (Info
.getProducesResult())
1058 OS
<< " __attribute__((ns_returns_retained))";
1059 if (Info
.getRegParm())
1060 OS
<< " __attribute__((regparm ("
1061 << Info
.getRegParm() << ")))";
1062 if (Info
.getNoCallerSavedRegs())
1063 OS
<< " __attribute__((no_caller_saved_registers))";
1064 if (Info
.getNoCfCheck())
1065 OS
<< " __attribute__((nocf_check))";
1068 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType
*T
,
1070 // If needed for precedence reasons, wrap the inner part in grouping parens.
1071 SaveAndRestore
PrevPHIsEmpty(HasEmptyPlaceHolder
, false);
1072 printBefore(T
->getReturnType(), OS
);
1073 if (!PrevPHIsEmpty
.get())
1077 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType
*T
,
1079 // If needed for precedence reasons, wrap the inner part in grouping parens.
1080 if (!HasEmptyPlaceHolder
)
1082 SaveAndRestore
NonEmptyPH(HasEmptyPlaceHolder
, false);
1085 printFunctionAfter(T
->getExtInfo(), OS
);
1086 printAfter(T
->getReturnType(), OS
);
1089 void TypePrinter::printTypeSpec(NamedDecl
*D
, raw_ostream
&OS
) {
1091 // Compute the full nested-name-specifier for this type.
1092 // In C, this will always be empty except when the type
1093 // being printed is anonymous within other Record.
1094 if (!Policy
.SuppressScope
)
1095 AppendScope(D
->getDeclContext(), OS
, D
->getDeclName());
1097 IdentifierInfo
*II
= D
->getIdentifier();
1098 OS
<< II
->getName();
1099 spaceBeforePlaceHolder(OS
);
1102 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType
*T
,
1104 printTypeSpec(T
->getDecl(), OS
);
1107 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType
*T
,
1110 void TypePrinter::printUsingBefore(const UsingType
*T
, raw_ostream
&OS
) {
1111 // After `namespace b { using a::X }`, is the type X within B a::X or b::X?
1113 // - b::X is more formally correct given the UsingType model
1114 // - b::X makes sense if "re-exporting" a symbol in a new namespace
1115 // - a::X makes sense if "importing" a symbol for convenience
1117 // The "importing" use seems much more common, so we print a::X.
1118 // This could be a policy option, but the right choice seems to rest more
1119 // with the intent of the code than the caller.
1120 printTypeSpec(T
->getFoundDecl()->getUnderlyingDecl(), OS
);
1123 void TypePrinter::printUsingAfter(const UsingType
*T
, raw_ostream
&OS
) {}
1125 void TypePrinter::printTypedefBefore(const TypedefType
*T
, raw_ostream
&OS
) {
1126 printTypeSpec(T
->getDecl(), OS
);
1129 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType
*T
,
1131 StringRef MacroName
= T
->getMacroIdentifier()->getName();
1132 OS
<< MacroName
<< " ";
1134 // Since this type is meant to print the macro instead of the whole attribute,
1135 // we trim any attributes and go directly to the original modified type.
1136 printBefore(T
->getModifiedType(), OS
);
1139 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType
*T
,
1141 printAfter(T
->getModifiedType(), OS
);
1144 void TypePrinter::printTypedefAfter(const TypedefType
*T
, raw_ostream
&OS
) {}
1146 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType
*T
,
1148 OS
<< (T
->getKind() == TypeOfKind::Unqualified
? "typeof_unqual "
1150 if (T
->getUnderlyingExpr())
1151 T
->getUnderlyingExpr()->printPretty(OS
, nullptr, Policy
);
1152 spaceBeforePlaceHolder(OS
);
1155 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType
*T
,
1158 void TypePrinter::printTypeOfBefore(const TypeOfType
*T
, raw_ostream
&OS
) {
1159 OS
<< (T
->getKind() == TypeOfKind::Unqualified
? "typeof_unqual("
1161 print(T
->getUnmodifiedType(), OS
, StringRef());
1163 spaceBeforePlaceHolder(OS
);
1166 void TypePrinter::printTypeOfAfter(const TypeOfType
*T
, raw_ostream
&OS
) {}
1168 void TypePrinter::printDecltypeBefore(const DecltypeType
*T
, raw_ostream
&OS
) {
1170 if (T
->getUnderlyingExpr())
1171 T
->getUnderlyingExpr()->printPretty(OS
, nullptr, Policy
);
1173 spaceBeforePlaceHolder(OS
);
1176 void TypePrinter::printDecltypeAfter(const DecltypeType
*T
, raw_ostream
&OS
) {}
1178 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType
*T
,
1180 IncludeStrongLifetimeRAII
Strong(Policy
);
1182 static llvm::DenseMap
<int, const char *> Transformation
= {{
1183 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1184 {UnaryTransformType::Enum, "__" #Trait},
1185 #include "clang/Basic/TransformTypeTraits.def"
1187 OS
<< Transformation
[T
->getUTTKind()] << '(';
1188 print(T
->getBaseType(), OS
, StringRef());
1190 spaceBeforePlaceHolder(OS
);
1193 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType
*T
,
1196 void TypePrinter::printAutoBefore(const AutoType
*T
, raw_ostream
&OS
) {
1197 // If the type has been deduced, do not print 'auto'.
1198 if (!T
->getDeducedType().isNull()) {
1199 printBefore(T
->getDeducedType(), OS
);
1201 if (T
->isConstrained()) {
1202 // FIXME: Track a TypeConstraint as type sugar, so that we can print the
1203 // type as it was written.
1204 T
->getTypeConstraintConcept()->getDeclName().print(OS
, Policy
);
1205 auto Args
= T
->getTypeConstraintArguments();
1207 printTemplateArgumentList(
1209 T
->getTypeConstraintConcept()->getTemplateParameters());
1212 switch (T
->getKeyword()) {
1213 case AutoTypeKeyword::Auto
: OS
<< "auto"; break;
1214 case AutoTypeKeyword::DecltypeAuto
: OS
<< "decltype(auto)"; break;
1215 case AutoTypeKeyword::GNUAutoType
: OS
<< "__auto_type"; break;
1217 spaceBeforePlaceHolder(OS
);
1221 void TypePrinter::printAutoAfter(const AutoType
*T
, raw_ostream
&OS
) {
1222 // If the type has been deduced, do not print 'auto'.
1223 if (!T
->getDeducedType().isNull())
1224 printAfter(T
->getDeducedType(), OS
);
1227 void TypePrinter::printDeducedTemplateSpecializationBefore(
1228 const DeducedTemplateSpecializationType
*T
, raw_ostream
&OS
) {
1229 // If the type has been deduced, print the deduced type.
1230 if (!T
->getDeducedType().isNull()) {
1231 printBefore(T
->getDeducedType(), OS
);
1233 IncludeStrongLifetimeRAII
Strong(Policy
);
1234 T
->getTemplateName().print(OS
, Policy
);
1235 spaceBeforePlaceHolder(OS
);
1239 void TypePrinter::printDeducedTemplateSpecializationAfter(
1240 const DeducedTemplateSpecializationType
*T
, raw_ostream
&OS
) {
1241 // If the type has been deduced, print the deduced type.
1242 if (!T
->getDeducedType().isNull())
1243 printAfter(T
->getDeducedType(), OS
);
1246 void TypePrinter::printAtomicBefore(const AtomicType
*T
, raw_ostream
&OS
) {
1247 IncludeStrongLifetimeRAII
Strong(Policy
);
1250 print(T
->getValueType(), OS
, StringRef());
1252 spaceBeforePlaceHolder(OS
);
1255 void TypePrinter::printAtomicAfter(const AtomicType
*T
, raw_ostream
&OS
) {}
1257 void TypePrinter::printPipeBefore(const PipeType
*T
, raw_ostream
&OS
) {
1258 IncludeStrongLifetimeRAII
Strong(Policy
);
1260 if (T
->isReadOnly())
1263 OS
<< "write_only ";
1265 print(T
->getElementType(), OS
, StringRef());
1266 spaceBeforePlaceHolder(OS
);
1269 void TypePrinter::printPipeAfter(const PipeType
*T
, raw_ostream
&OS
) {}
1271 void TypePrinter::printBitIntBefore(const BitIntType
*T
, raw_ostream
&OS
) {
1272 if (T
->isUnsigned())
1274 OS
<< "_BitInt(" << T
->getNumBits() << ")";
1275 spaceBeforePlaceHolder(OS
);
1278 void TypePrinter::printBitIntAfter(const BitIntType
*T
, raw_ostream
&OS
) {}
1280 void TypePrinter::printDependentBitIntBefore(const DependentBitIntType
*T
,
1282 if (T
->isUnsigned())
1285 T
->getNumBitsExpr()->printPretty(OS
, nullptr, Policy
);
1287 spaceBeforePlaceHolder(OS
);
1290 void TypePrinter::printDependentBitIntAfter(const DependentBitIntType
*T
,
1293 /// Appends the given scope to the end of a string.
1294 void TypePrinter::AppendScope(DeclContext
*DC
, raw_ostream
&OS
,
1295 DeclarationName NameInScope
) {
1296 if (DC
->isTranslationUnit())
1299 // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier,
1300 // which can also print names for function and method scopes.
1301 if (DC
->isFunctionOrMethod())
1304 if (Policy
.Callbacks
&& Policy
.Callbacks
->isScopeVisible(DC
))
1307 if (const auto *NS
= dyn_cast
<NamespaceDecl
>(DC
)) {
1308 if (Policy
.SuppressUnwrittenScope
&& NS
->isAnonymousNamespace())
1309 return AppendScope(DC
->getParent(), OS
, NameInScope
);
1311 // Only suppress an inline namespace if the name has the same lookup
1312 // results in the enclosing namespace.
1313 if (Policy
.SuppressInlineNamespace
&& NS
->isInline() && NameInScope
&&
1314 NS
->isRedundantInlineQualifierFor(NameInScope
))
1315 return AppendScope(DC
->getParent(), OS
, NameInScope
);
1317 AppendScope(DC
->getParent(), OS
, NS
->getDeclName());
1318 if (NS
->getIdentifier())
1319 OS
<< NS
->getName() << "::";
1321 OS
<< "(anonymous namespace)::";
1322 } else if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(DC
)) {
1323 AppendScope(DC
->getParent(), OS
, Spec
->getDeclName());
1324 IncludeStrongLifetimeRAII
Strong(Policy
);
1325 OS
<< Spec
->getIdentifier()->getName();
1326 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
1327 printTemplateArgumentList(
1328 OS
, TemplateArgs
.asArray(), Policy
,
1329 Spec
->getSpecializedTemplate()->getTemplateParameters());
1331 } else if (const auto *Tag
= dyn_cast
<TagDecl
>(DC
)) {
1332 AppendScope(DC
->getParent(), OS
, Tag
->getDeclName());
1333 if (TypedefNameDecl
*Typedef
= Tag
->getTypedefNameForAnonDecl())
1334 OS
<< Typedef
->getIdentifier()->getName() << "::";
1335 else if (Tag
->getIdentifier())
1336 OS
<< Tag
->getIdentifier()->getName() << "::";
1340 AppendScope(DC
->getParent(), OS
, NameInScope
);
1344 void TypePrinter::printTag(TagDecl
*D
, raw_ostream
&OS
) {
1345 if (Policy
.IncludeTagDefinition
) {
1346 PrintingPolicy SubPolicy
= Policy
;
1347 SubPolicy
.IncludeTagDefinition
= false;
1348 D
->print(OS
, SubPolicy
, Indentation
);
1349 spaceBeforePlaceHolder(OS
);
1353 bool HasKindDecoration
= false;
1355 // We don't print tags unless this is an elaborated type.
1356 // In C, we just assume every RecordType is an elaborated type.
1357 if (!Policy
.SuppressTagKeyword
&& !D
->getTypedefNameForAnonDecl()) {
1358 HasKindDecoration
= true;
1359 OS
<< D
->getKindName();
1363 // Compute the full nested-name-specifier for this type.
1364 // In C, this will always be empty except when the type
1365 // being printed is anonymous within other Record.
1366 if (!Policy
.SuppressScope
)
1367 AppendScope(D
->getDeclContext(), OS
, D
->getDeclName());
1369 if (const IdentifierInfo
*II
= D
->getIdentifier())
1370 OS
<< II
->getName();
1371 else if (TypedefNameDecl
*Typedef
= D
->getTypedefNameForAnonDecl()) {
1372 assert(Typedef
->getIdentifier() && "Typedef without identifier?");
1373 OS
<< Typedef
->getIdentifier()->getName();
1375 // Make an unambiguous representation for anonymous types, e.g.
1376 // (anonymous enum at /usr/include/string.h:120:9)
1377 OS
<< (Policy
.MSVCFormatting
? '`' : '(');
1379 if (isa
<CXXRecordDecl
>(D
) && cast
<CXXRecordDecl
>(D
)->isLambda()) {
1381 HasKindDecoration
= true;
1382 } else if ((isa
<RecordDecl
>(D
) && cast
<RecordDecl
>(D
)->isAnonymousStructOrUnion())) {
1388 if (Policy
.AnonymousTagLocations
) {
1389 // Suppress the redundant tag keyword if we just printed one.
1390 // We don't have to worry about ElaboratedTypes here because you can't
1391 // refer to an anonymous type with one.
1392 if (!HasKindDecoration
)
1393 OS
<< " " << D
->getKindName();
1395 PresumedLoc PLoc
= D
->getASTContext().getSourceManager().getPresumedLoc(
1397 if (PLoc
.isValid()) {
1399 StringRef File
= PLoc
.getFilename();
1400 llvm::SmallString
<1024> WrittenFile(File
);
1401 if (auto *Callbacks
= Policy
.Callbacks
)
1402 WrittenFile
= Callbacks
->remapPath(File
);
1403 // Fix inconsistent path separator created by
1404 // clang::DirectoryLookup::LookupFile when the file path is relative
1406 llvm::sys::path::Style Style
=
1407 llvm::sys::path::is_absolute(WrittenFile
)
1408 ? llvm::sys::path::Style::native
1409 : (Policy
.MSVCFormatting
1410 ? llvm::sys::path::Style::windows_backslash
1411 : llvm::sys::path::Style::posix
);
1412 llvm::sys::path::native(WrittenFile
, Style
);
1413 OS
<< WrittenFile
<< ':' << PLoc
.getLine() << ':' << PLoc
.getColumn();
1417 OS
<< (Policy
.MSVCFormatting
? '\'' : ')');
1420 // If this is a class template specialization, print the template
1422 if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(D
)) {
1423 ArrayRef
<TemplateArgument
> Args
;
1424 TypeSourceInfo
*TAW
= Spec
->getTypeAsWritten();
1425 if (!Policy
.PrintCanonicalTypes
&& TAW
) {
1426 const TemplateSpecializationType
*TST
=
1427 cast
<TemplateSpecializationType
>(TAW
->getType());
1428 Args
= TST
->template_arguments();
1430 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
1431 Args
= TemplateArgs
.asArray();
1433 IncludeStrongLifetimeRAII
Strong(Policy
);
1434 printTemplateArgumentList(
1436 Spec
->getSpecializedTemplate()->getTemplateParameters());
1439 spaceBeforePlaceHolder(OS
);
1442 void TypePrinter::printRecordBefore(const RecordType
*T
, raw_ostream
&OS
) {
1443 // Print the preferred name if we have one for this type.
1444 if (Policy
.UsePreferredNames
) {
1445 for (const auto *PNA
: T
->getDecl()->specific_attrs
<PreferredNameAttr
>()) {
1446 if (!declaresSameEntity(PNA
->getTypedefType()->getAsCXXRecordDecl(),
1449 // Find the outermost typedef or alias template.
1450 QualType T
= PNA
->getTypedefType();
1452 if (auto *TT
= dyn_cast
<TypedefType
>(T
))
1453 return printTypeSpec(TT
->getDecl(), OS
);
1454 if (auto *TST
= dyn_cast
<TemplateSpecializationType
>(T
))
1455 return printTemplateId(TST
, OS
, /*FullyQualify=*/true);
1456 T
= T
->getLocallyUnqualifiedSingleStepDesugaredType();
1461 printTag(T
->getDecl(), OS
);
1464 void TypePrinter::printRecordAfter(const RecordType
*T
, raw_ostream
&OS
) {}
1466 void TypePrinter::printEnumBefore(const EnumType
*T
, raw_ostream
&OS
) {
1467 printTag(T
->getDecl(), OS
);
1470 void TypePrinter::printEnumAfter(const EnumType
*T
, raw_ostream
&OS
) {}
1472 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType
*T
,
1474 TemplateTypeParmDecl
*D
= T
->getDecl();
1475 if (D
&& D
->isImplicit()) {
1476 if (auto *TC
= D
->getTypeConstraint()) {
1477 TC
->print(OS
, Policy
);
1481 } else if (IdentifierInfo
*Id
= T
->getIdentifier())
1482 OS
<< (Policy
.CleanUglifiedParameters
? Id
->deuglifiedName()
1485 OS
<< "type-parameter-" << T
->getDepth() << '-' << T
->getIndex();
1487 spaceBeforePlaceHolder(OS
);
1490 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType
*T
,
1493 void TypePrinter::printSubstTemplateTypeParmBefore(
1494 const SubstTemplateTypeParmType
*T
,
1496 IncludeStrongLifetimeRAII
Strong(Policy
);
1497 printBefore(T
->getReplacementType(), OS
);
1500 void TypePrinter::printSubstTemplateTypeParmAfter(
1501 const SubstTemplateTypeParmType
*T
,
1503 IncludeStrongLifetimeRAII
Strong(Policy
);
1504 printAfter(T
->getReplacementType(), OS
);
1507 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1508 const SubstTemplateTypeParmPackType
*T
,
1510 IncludeStrongLifetimeRAII
Strong(Policy
);
1511 if (const TemplateTypeParmDecl
*D
= T
->getReplacedParameter()) {
1512 if (D
&& D
->isImplicit()) {
1513 if (auto *TC
= D
->getTypeConstraint()) {
1514 TC
->print(OS
, Policy
);
1518 } else if (IdentifierInfo
*Id
= D
->getIdentifier())
1519 OS
<< (Policy
.CleanUglifiedParameters
? Id
->deuglifiedName()
1522 OS
<< "type-parameter-" << D
->getDepth() << '-' << D
->getIndex();
1524 spaceBeforePlaceHolder(OS
);
1528 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1529 const SubstTemplateTypeParmPackType
*T
,
1531 IncludeStrongLifetimeRAII
Strong(Policy
);
1534 void TypePrinter::printTemplateId(const TemplateSpecializationType
*T
,
1535 raw_ostream
&OS
, bool FullyQualify
) {
1536 IncludeStrongLifetimeRAII
Strong(Policy
);
1538 TemplateDecl
*TD
= T
->getTemplateName().getAsTemplateDecl();
1539 // FIXME: Null TD never excercised in test suite.
1540 if (FullyQualify
&& TD
) {
1541 if (!Policy
.SuppressScope
)
1542 AppendScope(TD
->getDeclContext(), OS
, TD
->getDeclName());
1544 OS
<< TD
->getName();
1546 T
->getTemplateName().print(OS
, Policy
);
1549 DefaultTemplateArgsPolicyRAII
TemplateArgs(Policy
);
1550 const TemplateParameterList
*TPL
= TD
? TD
->getTemplateParameters() : nullptr;
1551 printTemplateArgumentList(OS
, T
->template_arguments(), Policy
, TPL
);
1552 spaceBeforePlaceHolder(OS
);
1555 void TypePrinter::printTemplateSpecializationBefore(
1556 const TemplateSpecializationType
*T
,
1558 printTemplateId(T
, OS
, Policy
.FullyQualifiedName
);
1561 void TypePrinter::printTemplateSpecializationAfter(
1562 const TemplateSpecializationType
*T
,
1565 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType
*T
,
1567 if (Policy
.PrintInjectedClassNameWithArguments
)
1568 return printTemplateSpecializationBefore(T
->getInjectedTST(), OS
);
1570 IncludeStrongLifetimeRAII
Strong(Policy
);
1571 T
->getTemplateName().print(OS
, Policy
);
1572 spaceBeforePlaceHolder(OS
);
1575 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType
*T
,
1578 void TypePrinter::printElaboratedBefore(const ElaboratedType
*T
,
1580 if (Policy
.IncludeTagDefinition
&& T
->getOwnedTagDecl()) {
1581 TagDecl
*OwnedTagDecl
= T
->getOwnedTagDecl();
1582 assert(OwnedTagDecl
->getTypeForDecl() == T
->getNamedType().getTypePtr() &&
1583 "OwnedTagDecl expected to be a declaration for the type");
1584 PrintingPolicy SubPolicy
= Policy
;
1585 SubPolicy
.IncludeTagDefinition
= false;
1586 OwnedTagDecl
->print(OS
, SubPolicy
, Indentation
);
1587 spaceBeforePlaceHolder(OS
);
1591 if (Policy
.SuppressElaboration
) {
1592 printBefore(T
->getNamedType(), OS
);
1596 // The tag definition will take care of these.
1597 if (!Policy
.IncludeTagDefinition
)
1599 OS
<< TypeWithKeyword::getKeywordName(T
->getKeyword());
1600 if (T
->getKeyword() != ElaboratedTypeKeyword::None
)
1602 NestedNameSpecifier
*Qualifier
= T
->getQualifier();
1604 Qualifier
->print(OS
, Policy
);
1607 ElaboratedTypePolicyRAII
PolicyRAII(Policy
);
1608 printBefore(T
->getNamedType(), OS
);
1611 void TypePrinter::printElaboratedAfter(const ElaboratedType
*T
,
1613 if (Policy
.IncludeTagDefinition
&& T
->getOwnedTagDecl())
1616 if (Policy
.SuppressElaboration
) {
1617 printAfter(T
->getNamedType(), OS
);
1621 ElaboratedTypePolicyRAII
PolicyRAII(Policy
);
1622 printAfter(T
->getNamedType(), OS
);
1625 void TypePrinter::printParenBefore(const ParenType
*T
, raw_ostream
&OS
) {
1626 if (!HasEmptyPlaceHolder
&& !isa
<FunctionType
>(T
->getInnerType())) {
1627 printBefore(T
->getInnerType(), OS
);
1630 printBefore(T
->getInnerType(), OS
);
1633 void TypePrinter::printParenAfter(const ParenType
*T
, raw_ostream
&OS
) {
1634 if (!HasEmptyPlaceHolder
&& !isa
<FunctionType
>(T
->getInnerType())) {
1636 printAfter(T
->getInnerType(), OS
);
1638 printAfter(T
->getInnerType(), OS
);
1641 void TypePrinter::printDependentNameBefore(const DependentNameType
*T
,
1643 OS
<< TypeWithKeyword::getKeywordName(T
->getKeyword());
1644 if (T
->getKeyword() != ElaboratedTypeKeyword::None
)
1647 T
->getQualifier()->print(OS
, Policy
);
1649 OS
<< T
->getIdentifier()->getName();
1650 spaceBeforePlaceHolder(OS
);
1653 void TypePrinter::printDependentNameAfter(const DependentNameType
*T
,
1656 void TypePrinter::printDependentTemplateSpecializationBefore(
1657 const DependentTemplateSpecializationType
*T
, raw_ostream
&OS
) {
1658 IncludeStrongLifetimeRAII
Strong(Policy
);
1660 OS
<< TypeWithKeyword::getKeywordName(T
->getKeyword());
1661 if (T
->getKeyword() != ElaboratedTypeKeyword::None
)
1664 if (T
->getQualifier())
1665 T
->getQualifier()->print(OS
, Policy
);
1666 OS
<< "template " << T
->getIdentifier()->getName();
1667 printTemplateArgumentList(OS
, T
->template_arguments(), Policy
);
1668 spaceBeforePlaceHolder(OS
);
1671 void TypePrinter::printDependentTemplateSpecializationAfter(
1672 const DependentTemplateSpecializationType
*T
, raw_ostream
&OS
) {}
1674 void TypePrinter::printPackExpansionBefore(const PackExpansionType
*T
,
1676 printBefore(T
->getPattern(), OS
);
1679 void TypePrinter::printPackExpansionAfter(const PackExpansionType
*T
,
1681 printAfter(T
->getPattern(), OS
);
1685 void TypePrinter::printAttributedBefore(const AttributedType
*T
,
1687 // FIXME: Generate this with TableGen.
1689 // Prefer the macro forms of the GC and ownership qualifiers.
1690 if (T
->getAttrKind() == attr::ObjCGC
||
1691 T
->getAttrKind() == attr::ObjCOwnership
)
1692 return printBefore(T
->getEquivalentType(), OS
);
1694 if (T
->getAttrKind() == attr::ObjCKindOf
)
1697 if (T
->getAttrKind() == attr::AddressSpace
)
1698 printBefore(T
->getEquivalentType(), OS
);
1700 printBefore(T
->getModifiedType(), OS
);
1702 if (T
->isMSTypeSpec()) {
1703 switch (T
->getAttrKind()) {
1705 case attr::Ptr32
: OS
<< " __ptr32"; break;
1706 case attr::Ptr64
: OS
<< " __ptr64"; break;
1707 case attr::SPtr
: OS
<< " __sptr"; break;
1708 case attr::UPtr
: OS
<< " __uptr"; break;
1710 spaceBeforePlaceHolder(OS
);
1713 if (T
->isWebAssemblyFuncrefSpec())
1716 // Print nullability type specifiers.
1717 if (T
->getImmediateNullability()) {
1718 if (T
->getAttrKind() == attr::TypeNonNull
)
1720 else if (T
->getAttrKind() == attr::TypeNullable
)
1722 else if (T
->getAttrKind() == attr::TypeNullUnspecified
)
1723 OS
<< " _Null_unspecified";
1724 else if (T
->getAttrKind() == attr::TypeNullableResult
)
1725 OS
<< " _Nullable_result";
1727 llvm_unreachable("unhandled nullability");
1728 spaceBeforePlaceHolder(OS
);
1732 void TypePrinter::printAttributedAfter(const AttributedType
*T
,
1734 // FIXME: Generate this with TableGen.
1736 // Prefer the macro forms of the GC and ownership qualifiers.
1737 if (T
->getAttrKind() == attr::ObjCGC
||
1738 T
->getAttrKind() == attr::ObjCOwnership
)
1739 return printAfter(T
->getEquivalentType(), OS
);
1741 // If this is a calling convention attribute, don't print the implicit CC from
1742 // the modified type.
1743 SaveAndRestore
MaybeSuppressCC(InsideCCAttribute
, T
->isCallingConv());
1745 printAfter(T
->getModifiedType(), OS
);
1747 // Some attributes are printed as qualifiers before the type, so we have
1748 // nothing left to do.
1749 if (T
->getAttrKind() == attr::ObjCKindOf
|| T
->isMSTypeSpec() ||
1750 T
->getImmediateNullability() || T
->isWebAssemblyFuncrefSpec())
1753 // Don't print the inert __unsafe_unretained attribute at all.
1754 if (T
->getAttrKind() == attr::ObjCInertUnsafeUnretained
)
1757 // Don't print ns_returns_retained unless it had an effect.
1758 if (T
->getAttrKind() == attr::NSReturnsRetained
&&
1759 !T
->getEquivalentType()->castAs
<FunctionType
>()
1760 ->getExtInfo().getProducesResult())
1763 if (T
->getAttrKind() == attr::LifetimeBound
) {
1764 OS
<< " [[clang::lifetimebound]]";
1768 // The printing of the address_space attribute is handled by the qualifier
1769 // since it is still stored in the qualifier. Return early to prevent printing
1771 if (T
->getAttrKind() == attr::AddressSpace
)
1774 if (T
->getAttrKind() == attr::AnnotateType
) {
1775 // FIXME: Print the attribute arguments once we have a way to retrieve these
1776 // here. For the meantime, we just print `[[clang::annotate_type(...)]]`
1777 // without the arguments so that we know at least that we had _some_
1778 // annotation on the type.
1779 OS
<< " [[clang::annotate_type(...)]]";
1783 if (T
->getAttrKind() == attr::ArmStreaming
) {
1784 OS
<< "__arm_streaming";
1787 if (T
->getAttrKind() == attr::ArmStreamingCompatible
) {
1788 OS
<< "__arm_streaming_compatible";
1791 if (T
->getAttrKind() == attr::ArmSharedZA
) {
1792 OS
<< "__arm_shared_za";
1795 if (T
->getAttrKind() == attr::ArmPreservesZA
) {
1796 OS
<< "__arm_preserves_za";
1800 OS
<< " __attribute__((";
1801 switch (T
->getAttrKind()) {
1802 #define TYPE_ATTR(NAME)
1803 #define DECL_OR_TYPE_ATTR(NAME)
1804 #define ATTR(NAME) case attr::NAME:
1805 #include "clang/Basic/AttrList.inc"
1806 llvm_unreachable("non-type attribute attached to type");
1808 case attr::BTFTypeTag
:
1809 llvm_unreachable("BTFTypeTag attribute handled separately");
1811 case attr::OpenCLPrivateAddressSpace
:
1812 case attr::OpenCLGlobalAddressSpace
:
1813 case attr::OpenCLGlobalDeviceAddressSpace
:
1814 case attr::OpenCLGlobalHostAddressSpace
:
1815 case attr::OpenCLLocalAddressSpace
:
1816 case attr::OpenCLConstantAddressSpace
:
1817 case attr::OpenCLGenericAddressSpace
:
1818 case attr::HLSLGroupSharedAddressSpace
:
1819 // FIXME: Update printAttributedBefore to print these once we generate
1820 // AttributedType nodes for them.
1823 case attr::LifetimeBound
:
1824 case attr::TypeNonNull
:
1825 case attr::TypeNullable
:
1826 case attr::TypeNullableResult
:
1827 case attr::TypeNullUnspecified
:
1829 case attr::ObjCInertUnsafeUnretained
:
1830 case attr::ObjCKindOf
:
1831 case attr::ObjCOwnership
:
1836 case attr::AddressSpace
:
1837 case attr::CmseNSCall
:
1838 case attr::AnnotateType
:
1839 case attr::WebAssemblyFuncref
:
1840 case attr::ArmStreaming
:
1841 case attr::ArmStreamingCompatible
:
1842 case attr::ArmSharedZA
:
1843 case attr::ArmPreservesZA
:
1844 llvm_unreachable("This attribute should have been handled already");
1846 case attr::NSReturnsRetained
:
1847 OS
<< "ns_returns_retained";
1850 // FIXME: When Sema learns to form this AttributedType, avoid printing the
1851 // attribute again in printFunctionProtoAfter.
1852 case attr::AnyX86NoCfCheck
: OS
<< "nocf_check"; break;
1853 case attr::CDecl
: OS
<< "cdecl"; break;
1854 case attr::FastCall
: OS
<< "fastcall"; break;
1855 case attr::StdCall
: OS
<< "stdcall"; break;
1856 case attr::ThisCall
: OS
<< "thiscall"; break;
1857 case attr::SwiftCall
: OS
<< "swiftcall"; break;
1858 case attr::SwiftAsyncCall
: OS
<< "swiftasynccall"; break;
1859 case attr::VectorCall
: OS
<< "vectorcall"; break;
1860 case attr::Pascal
: OS
<< "pascal"; break;
1861 case attr::MSABI
: OS
<< "ms_abi"; break;
1862 case attr::SysVABI
: OS
<< "sysv_abi"; break;
1863 case attr::RegCall
: OS
<< "regcall"; break;
1866 QualType t
= T
->getEquivalentType();
1867 while (!t
->isFunctionType())
1868 t
= t
->getPointeeType();
1869 OS
<< (t
->castAs
<FunctionType
>()->getCallConv() == CC_AAPCS
?
1870 "\"aapcs\"" : "\"aapcs-vfp\"");
1874 case attr::AArch64VectorPcs
: OS
<< "aarch64_vector_pcs"; break;
1875 case attr::AArch64SVEPcs
: OS
<< "aarch64_sve_pcs"; break;
1876 case attr::AMDGPUKernelCall
: OS
<< "amdgpu_kernel"; break;
1877 case attr::IntelOclBicc
: OS
<< "inteloclbicc"; break;
1878 case attr::PreserveMost
:
1879 OS
<< "preserve_most";
1882 case attr::PreserveAll
:
1883 OS
<< "preserve_all";
1891 case attr::AcquireHandle
:
1892 OS
<< "acquire_handle";
1894 case attr::ArmMveStrictPolymorphism
:
1895 OS
<< "__clang_arm_mve_strict_polymorphism";
1901 void TypePrinter::printBTFTagAttributedBefore(const BTFTagAttributedType
*T
,
1903 printBefore(T
->getWrappedType(), OS
);
1904 OS
<< " __attribute__((btf_type_tag(\"" << T
->getAttr()->getBTFTypeTag() << "\")))";
1907 void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType
*T
,
1909 printAfter(T
->getWrappedType(), OS
);
1912 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType
*T
,
1914 OS
<< T
->getDecl()->getName();
1915 spaceBeforePlaceHolder(OS
);
1918 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType
*T
,
1921 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType
*T
,
1923 OS
<< T
->getDecl()->getName();
1924 if (!T
->qual_empty()) {
1925 bool isFirst
= true;
1927 for (const auto *I
: T
->quals()) {
1937 spaceBeforePlaceHolder(OS
);
1940 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType
*T
,
1943 void TypePrinter::printObjCObjectBefore(const ObjCObjectType
*T
,
1945 if (T
->qual_empty() && T
->isUnspecializedAsWritten() &&
1946 !T
->isKindOfTypeAsWritten())
1947 return printBefore(T
->getBaseType(), OS
);
1949 if (T
->isKindOfTypeAsWritten())
1952 print(T
->getBaseType(), OS
, StringRef());
1954 if (T
->isSpecializedAsWritten()) {
1955 bool isFirst
= true;
1957 for (auto typeArg
: T
->getTypeArgsAsWritten()) {
1963 print(typeArg
, OS
, StringRef());
1968 if (!T
->qual_empty()) {
1969 bool isFirst
= true;
1971 for (const auto *I
: T
->quals()) {
1981 spaceBeforePlaceHolder(OS
);
1984 void TypePrinter::printObjCObjectAfter(const ObjCObjectType
*T
,
1986 if (T
->qual_empty() && T
->isUnspecializedAsWritten() &&
1987 !T
->isKindOfTypeAsWritten())
1988 return printAfter(T
->getBaseType(), OS
);
1991 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType
*T
,
1993 printBefore(T
->getPointeeType(), OS
);
1995 // If we need to print the pointer, print it now.
1996 if (!T
->isObjCIdType() && !T
->isObjCQualifiedIdType() &&
1997 !T
->isObjCClassType() && !T
->isObjCQualifiedClassType()) {
1998 if (HasEmptyPlaceHolder
)
2004 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType
*T
,
2008 const TemplateArgument
&getArgument(const TemplateArgument
&A
) { return A
; }
2010 static const TemplateArgument
&getArgument(const TemplateArgumentLoc
&A
) {
2011 return A
.getArgument();
2014 static void printArgument(const TemplateArgument
&A
, const PrintingPolicy
&PP
,
2015 llvm::raw_ostream
&OS
, bool IncludeType
) {
2016 A
.print(PP
, OS
, IncludeType
);
2019 static void printArgument(const TemplateArgumentLoc
&A
,
2020 const PrintingPolicy
&PP
, llvm::raw_ostream
&OS
,
2022 const TemplateArgument::ArgKind
&Kind
= A
.getArgument().getKind();
2023 if (Kind
== TemplateArgument::ArgKind::Type
)
2024 return A
.getTypeSourceInfo()->getType().print(OS
, PP
);
2025 return A
.getArgument().print(PP
, OS
, IncludeType
);
2028 static bool isSubstitutedTemplateArgument(ASTContext
&Ctx
, TemplateArgument Arg
,
2029 TemplateArgument Pattern
,
2030 ArrayRef
<TemplateArgument
> Args
,
2033 static bool isSubstitutedType(ASTContext
&Ctx
, QualType T
, QualType Pattern
,
2034 ArrayRef
<TemplateArgument
> Args
, unsigned Depth
) {
2035 if (Ctx
.hasSameType(T
, Pattern
))
2038 // A type parameter matches its argument.
2039 if (auto *TTPT
= Pattern
->getAs
<TemplateTypeParmType
>()) {
2040 if (TTPT
->getDepth() == Depth
&& TTPT
->getIndex() < Args
.size() &&
2041 Args
[TTPT
->getIndex()].getKind() == TemplateArgument::Type
) {
2042 QualType SubstArg
= Ctx
.getQualifiedType(
2043 Args
[TTPT
->getIndex()].getAsType(), Pattern
.getQualifiers());
2044 return Ctx
.hasSameType(SubstArg
, T
);
2049 // FIXME: Recurse into array types.
2051 // All other cases will need the types to be identically qualified.
2052 Qualifiers TQual
, PatQual
;
2053 T
= Ctx
.getUnqualifiedArrayType(T
, TQual
);
2054 Pattern
= Ctx
.getUnqualifiedArrayType(Pattern
, PatQual
);
2055 if (TQual
!= PatQual
)
2058 // Recurse into pointer-like types.
2060 QualType TPointee
= T
->getPointeeType();
2061 QualType PPointee
= Pattern
->getPointeeType();
2062 if (!TPointee
.isNull() && !PPointee
.isNull())
2063 return T
->getTypeClass() == Pattern
->getTypeClass() &&
2064 isSubstitutedType(Ctx
, TPointee
, PPointee
, Args
, Depth
);
2067 // Recurse into template specialization types.
2069 Pattern
.getCanonicalType()->getAs
<TemplateSpecializationType
>()) {
2070 TemplateName Template
;
2071 ArrayRef
<TemplateArgument
> TemplateArgs
;
2072 if (auto *TTST
= T
->getAs
<TemplateSpecializationType
>()) {
2073 Template
= TTST
->getTemplateName();
2074 TemplateArgs
= TTST
->template_arguments();
2075 } else if (auto *CTSD
= dyn_cast_or_null
<ClassTemplateSpecializationDecl
>(
2076 T
->getAsCXXRecordDecl())) {
2077 Template
= TemplateName(CTSD
->getSpecializedTemplate());
2078 TemplateArgs
= CTSD
->getTemplateArgs().asArray();
2083 if (!isSubstitutedTemplateArgument(Ctx
, Template
, PTST
->getTemplateName(),
2086 if (TemplateArgs
.size() != PTST
->template_arguments().size())
2088 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
2089 if (!isSubstitutedTemplateArgument(
2090 Ctx
, TemplateArgs
[I
], PTST
->template_arguments()[I
], Args
, Depth
))
2095 // FIXME: Handle more cases.
2099 /// Evaluates the expression template argument 'Pattern' and returns true
2100 /// if 'Arg' evaluates to the same result.
2101 static bool templateArgumentExpressionsEqual(ASTContext
const &Ctx
,
2102 TemplateArgument
const &Pattern
,
2103 TemplateArgument
const &Arg
) {
2104 if (Pattern
.getKind() != TemplateArgument::Expression
)
2107 // Can't evaluate value-dependent expressions so bail early
2108 Expr
const *pattern_expr
= Pattern
.getAsExpr();
2109 if (pattern_expr
->isValueDependent() ||
2110 !pattern_expr
->isIntegerConstantExpr(Ctx
))
2113 if (Arg
.getKind() == TemplateArgument::Integral
)
2114 return llvm::APSInt::isSameValue(pattern_expr
->EvaluateKnownConstInt(Ctx
),
2115 Arg
.getAsIntegral());
2117 if (Arg
.getKind() == TemplateArgument::Expression
) {
2118 Expr
const *args_expr
= Arg
.getAsExpr();
2119 if (args_expr
->isValueDependent() || !args_expr
->isIntegerConstantExpr(Ctx
))
2122 return llvm::APSInt::isSameValue(args_expr
->EvaluateKnownConstInt(Ctx
),
2123 pattern_expr
->EvaluateKnownConstInt(Ctx
));
2129 static bool isSubstitutedTemplateArgument(ASTContext
&Ctx
, TemplateArgument Arg
,
2130 TemplateArgument Pattern
,
2131 ArrayRef
<TemplateArgument
> Args
,
2133 Arg
= Ctx
.getCanonicalTemplateArgument(Arg
);
2134 Pattern
= Ctx
.getCanonicalTemplateArgument(Pattern
);
2135 if (Arg
.structurallyEquals(Pattern
))
2138 if (Pattern
.getKind() == TemplateArgument::Expression
) {
2140 dyn_cast
<DeclRefExpr
>(Pattern
.getAsExpr()->IgnoreParenImpCasts())) {
2141 if (auto *NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(DRE
->getDecl()))
2142 return NTTP
->getDepth() == Depth
&& Args
.size() > NTTP
->getIndex() &&
2143 Args
[NTTP
->getIndex()].structurallyEquals(Arg
);
2147 if (templateArgumentExpressionsEqual(Ctx
, Pattern
, Arg
))
2150 if (Arg
.getKind() != Pattern
.getKind())
2153 if (Arg
.getKind() == TemplateArgument::Type
)
2154 return isSubstitutedType(Ctx
, Arg
.getAsType(), Pattern
.getAsType(), Args
,
2157 if (Arg
.getKind() == TemplateArgument::Template
) {
2158 TemplateDecl
*PatTD
= Pattern
.getAsTemplate().getAsTemplateDecl();
2159 if (auto *TTPD
= dyn_cast_or_null
<TemplateTemplateParmDecl
>(PatTD
))
2160 return TTPD
->getDepth() == Depth
&& Args
.size() > TTPD
->getIndex() &&
2161 Ctx
.getCanonicalTemplateArgument(Args
[TTPD
->getIndex()])
2162 .structurallyEquals(Arg
);
2165 // FIXME: Handle more cases.
2169 bool clang::isSubstitutedDefaultArgument(ASTContext
&Ctx
, TemplateArgument Arg
,
2170 const NamedDecl
*Param
,
2171 ArrayRef
<TemplateArgument
> Args
,
2173 // An empty pack is equivalent to not providing a pack argument.
2174 if (Arg
.getKind() == TemplateArgument::Pack
&& Arg
.pack_size() == 0)
2177 if (auto *TTPD
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
2178 return TTPD
->hasDefaultArgument() &&
2179 isSubstitutedTemplateArgument(Ctx
, Arg
, TTPD
->getDefaultArgument(),
2181 } else if (auto *TTPD
= dyn_cast
<TemplateTemplateParmDecl
>(Param
)) {
2182 return TTPD
->hasDefaultArgument() &&
2183 isSubstitutedTemplateArgument(
2184 Ctx
, Arg
, TTPD
->getDefaultArgument().getArgument(), Args
, Depth
);
2185 } else if (auto *NTTPD
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
2186 return NTTPD
->hasDefaultArgument() &&
2187 isSubstitutedTemplateArgument(Ctx
, Arg
, NTTPD
->getDefaultArgument(),
2193 template <typename TA
>
2195 printTo(raw_ostream
&OS
, ArrayRef
<TA
> Args
, const PrintingPolicy
&Policy
,
2196 const TemplateParameterList
*TPL
, bool IsPack
, unsigned ParmIndex
) {
2197 // Drop trailing template arguments that match default arguments.
2198 if (TPL
&& Policy
.SuppressDefaultTemplateArgs
&&
2199 !Policy
.PrintCanonicalTypes
&& !Args
.empty() && !IsPack
&&
2200 Args
.size() <= TPL
->size()) {
2201 llvm::SmallVector
<TemplateArgument
, 8> OrigArgs
;
2202 for (const TA
&A
: Args
)
2203 OrigArgs
.push_back(getArgument(A
));
2204 while (!Args
.empty() && getArgument(Args
.back()).getIsDefaulted())
2205 Args
= Args
.drop_back();
2208 const char *Comma
= Policy
.MSVCFormatting
? "," : ", ";
2212 bool NeedSpace
= false;
2213 bool FirstArg
= true;
2214 for (const auto &Arg
: Args
) {
2215 // Print the argument into a string.
2216 SmallString
<128> Buf
;
2217 llvm::raw_svector_ostream
ArgOS(Buf
);
2218 const TemplateArgument
&Argument
= getArgument(Arg
);
2219 if (Argument
.getKind() == TemplateArgument::Pack
) {
2220 if (Argument
.pack_size() && !FirstArg
)
2222 printTo(ArgOS
, Argument
.getPackAsArray(), Policy
, TPL
,
2223 /*IsPack*/ true, ParmIndex
);
2227 // Tries to print the argument with location info if exists.
2228 printArgument(Arg
, Policy
, ArgOS
,
2229 TemplateParameterList::shouldIncludeTypeForArgument(
2230 Policy
, TPL
, ParmIndex
));
2232 StringRef ArgString
= ArgOS
.str();
2234 // If this is the first argument and its string representation
2235 // begins with the global scope specifier ('::foo'), add a space
2236 // to avoid printing the diagraph '<:'.
2237 if (FirstArg
&& !ArgString
.empty() && ArgString
[0] == ':')
2242 // If the last character of our string is '>', add another space to
2243 // keep the two '>''s separate tokens.
2244 if (!ArgString
.empty()) {
2245 NeedSpace
= Policy
.SplitTemplateClosers
&& ArgString
.back() == '>';
2249 // Use same template parameter for all elements of Pack
2261 void clang::printTemplateArgumentList(raw_ostream
&OS
,
2262 const TemplateArgumentListInfo
&Args
,
2263 const PrintingPolicy
&Policy
,
2264 const TemplateParameterList
*TPL
) {
2265 printTemplateArgumentList(OS
, Args
.arguments(), Policy
, TPL
);
2268 void clang::printTemplateArgumentList(raw_ostream
&OS
,
2269 ArrayRef
<TemplateArgument
> Args
,
2270 const PrintingPolicy
&Policy
,
2271 const TemplateParameterList
*TPL
) {
2272 printTo(OS
, Args
, Policy
, TPL
, /*isPack*/ false, /*parmIndex*/ 0);
2275 void clang::printTemplateArgumentList(raw_ostream
&OS
,
2276 ArrayRef
<TemplateArgumentLoc
> Args
,
2277 const PrintingPolicy
&Policy
,
2278 const TemplateParameterList
*TPL
) {
2279 printTo(OS
, Args
, Policy
, TPL
, /*isPack*/ false, /*parmIndex*/ 0);
2282 std::string
Qualifiers::getAsString() const {
2284 return getAsString(PrintingPolicy(LO
));
2287 // Appends qualifiers to the given string, separated by spaces. Will
2288 // prefix a space if the string is non-empty. Will not append a final
2290 std::string
Qualifiers::getAsString(const PrintingPolicy
&Policy
) const {
2291 SmallString
<64> Buf
;
2292 llvm::raw_svector_ostream
StrOS(Buf
);
2293 print(StrOS
, Policy
);
2294 return std::string(StrOS
.str());
2297 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy
&Policy
) const {
2298 if (getCVRQualifiers())
2301 if (getAddressSpace() != LangAS::Default
)
2304 if (getObjCGCAttr())
2307 if (Qualifiers::ObjCLifetime lifetime
= getObjCLifetime())
2308 if (!(lifetime
== Qualifiers::OCL_Strong
&& Policy
.SuppressStrongLifetime
))
2314 std::string
Qualifiers::getAddrSpaceAsString(LangAS AS
) {
2316 case LangAS::Default
:
2318 case LangAS::opencl_global
:
2319 case LangAS::sycl_global
:
2321 case LangAS::opencl_local
:
2322 case LangAS::sycl_local
:
2324 case LangAS::opencl_private
:
2325 case LangAS::sycl_private
:
2327 case LangAS::opencl_constant
:
2328 return "__constant";
2329 case LangAS::opencl_generic
:
2331 case LangAS::opencl_global_device
:
2332 case LangAS::sycl_global_device
:
2333 return "__global_device";
2334 case LangAS::opencl_global_host
:
2335 case LangAS::sycl_global_host
:
2336 return "__global_host";
2337 case LangAS::cuda_device
:
2338 return "__device__";
2339 case LangAS::cuda_constant
:
2340 return "__constant__";
2341 case LangAS::cuda_shared
:
2342 return "__shared__";
2343 case LangAS::ptr32_sptr
:
2344 return "__sptr __ptr32";
2345 case LangAS::ptr32_uptr
:
2346 return "__uptr __ptr32";
2349 case LangAS::wasm_funcref
:
2351 case LangAS::hlsl_groupshared
:
2352 return "groupshared";
2354 return std::to_string(toTargetAddressSpace(AS
));
2358 // Appends qualifiers to the given string, separated by spaces. Will
2359 // prefix a space if the string is non-empty. Will not append a final
2361 void Qualifiers::print(raw_ostream
&OS
, const PrintingPolicy
& Policy
,
2362 bool appendSpaceIfNonEmpty
) const {
2363 bool addSpace
= false;
2365 unsigned quals
= getCVRQualifiers();
2367 AppendTypeQualList(OS
, quals
, Policy
.Restrict
);
2370 if (hasUnaligned()) {
2373 OS
<< "__unaligned";
2376 auto ASStr
= getAddrSpaceAsString(getAddressSpace());
2377 if (!ASStr
.empty()) {
2381 // Wrap target address space into an attribute syntax
2382 if (isTargetAddressSpace(getAddressSpace()))
2383 OS
<< "__attribute__((address_space(" << ASStr
<< ")))";
2388 if (Qualifiers::GC gc
= getObjCGCAttr()) {
2392 if (gc
== Qualifiers::Weak
)
2397 if (Qualifiers::ObjCLifetime lifetime
= getObjCLifetime()) {
2398 if (!(lifetime
== Qualifiers::OCL_Strong
&& Policy
.SuppressStrongLifetime
)){
2405 case Qualifiers::OCL_None
: llvm_unreachable("none but true");
2406 case Qualifiers::OCL_ExplicitNone
: OS
<< "__unsafe_unretained"; break;
2407 case Qualifiers::OCL_Strong
:
2408 if (!Policy
.SuppressStrongLifetime
)
2412 case Qualifiers::OCL_Weak
: OS
<< "__weak"; break;
2413 case Qualifiers::OCL_Autoreleasing
: OS
<< "__autoreleasing"; break;
2417 if (appendSpaceIfNonEmpty
&& addSpace
)
2421 std::string
QualType::getAsString() const {
2422 return getAsString(split(), LangOptions());
2425 std::string
QualType::getAsString(const PrintingPolicy
&Policy
) const {
2427 getAsStringInternal(S
, Policy
);
2431 std::string
QualType::getAsString(const Type
*ty
, Qualifiers qs
,
2432 const PrintingPolicy
&Policy
) {
2434 getAsStringInternal(ty
, qs
, buffer
, Policy
);
2438 void QualType::print(raw_ostream
&OS
, const PrintingPolicy
&Policy
,
2439 const Twine
&PlaceHolder
, unsigned Indentation
) const {
2440 print(splitAccordingToPolicy(*this, Policy
), OS
, Policy
, PlaceHolder
,
2444 void QualType::print(const Type
*ty
, Qualifiers qs
,
2445 raw_ostream
&OS
, const PrintingPolicy
&policy
,
2446 const Twine
&PlaceHolder
, unsigned Indentation
) {
2447 SmallString
<128> PHBuf
;
2448 StringRef PH
= PlaceHolder
.toStringRef(PHBuf
);
2450 TypePrinter(policy
, Indentation
).print(ty
, qs
, OS
, PH
);
2453 void QualType::getAsStringInternal(std::string
&Str
,
2454 const PrintingPolicy
&Policy
) const {
2455 return getAsStringInternal(splitAccordingToPolicy(*this, Policy
), Str
,
2459 void QualType::getAsStringInternal(const Type
*ty
, Qualifiers qs
,
2460 std::string
&buffer
,
2461 const PrintingPolicy
&policy
) {
2462 SmallString
<256> Buf
;
2463 llvm::raw_svector_ostream
StrOS(Buf
);
2464 TypePrinter(policy
).print(ty
, qs
, StrOS
, buffer
);
2465 std::string str
= std::string(StrOS
.str());
2469 raw_ostream
&clang::operator<<(raw_ostream
&OS
, QualType QT
) {
2470 SplitQualType S
= QT
.split();
2471 TypePrinter(LangOptions()).print(S
.Ty
, S
.Quals
, OS
, /*PlaceHolder=*/"");