[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / AST / TypePrinter.cpp
blobe4f5f40cd6259969c9c4615aba2c8d4879c95ee5
1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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"
45 #include <cassert>
46 #include <string>
48 using namespace clang;
50 namespace {
52 /// RAII object that enables printing of the ARC __strong lifetime
53 /// qualifier.
54 class IncludeStrongLifetimeRAII {
55 PrintingPolicy &Policy;
56 bool Old;
58 public:
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;
70 bool Old;
72 public:
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;
83 bool Old;
85 public:
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;
97 bool SuppressScope;
99 public:
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;
113 class TypePrinter {
114 PrintingPolicy Policy;
115 unsigned Indentation;
116 bool HasEmptyPlaceHolder = false;
117 bool InsideCCAttribute = false;
119 public:
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,
131 bool FullyQualify);
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"
145 private:
146 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
147 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
150 } // namespace
152 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
153 bool HasRestrictKeyword) {
154 bool appendSpace = false;
155 if (TypeQuals & Qualifiers::Const) {
156 OS << "const";
157 appendSpace = true;
159 if (TypeQuals & Qualifiers::Volatile) {
160 if (appendSpace) OS << ' ';
161 OS << "volatile";
162 appendSpace = true;
164 if (TypeQuals & Qualifiers::Restrict) {
165 if (appendSpace) OS << ' ';
166 if (HasRestrictKeyword) {
167 OS << "restrict";
168 } else {
169 OS << "__restrict";
174 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
175 if (!HasEmptyPlaceHolder)
176 OS << ' ';
179 static SplitQualType splitAccordingToPolicy(QualType QT,
180 const PrintingPolicy &Policy) {
181 if (Policy.PrintCanonicalTypes)
182 QT = QT.getCanonicalType();
183 return QT.split();
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) {
193 if (!T) {
194 OS << "NULL TYPE";
195 return;
198 SaveAndRestore PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
200 printBefore(T, Quals, OS);
201 OS << PlaceHolder;
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();
221 switch (TC) {
222 case Type::Auto:
223 case Type::Builtin:
224 case Type::Complex:
225 case Type::UnresolvedUsing:
226 case Type::Using:
227 case Type::Typedef:
228 case Type::TypeOfExpr:
229 case Type::TypeOf:
230 case Type::Decltype:
231 case Type::UnaryTransform:
232 case Type::Record:
233 case Type::Enum:
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:
245 case Type::Atomic:
246 case Type::Pipe:
247 case Type::BitInt:
248 case Type::DependentBitInt:
249 case Type::BTFTagAttributed:
250 CanPrefixQualifiers = true;
251 break;
253 case Type::ObjCObjectPointer:
254 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
255 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
256 break;
258 case Type::VariableArray:
259 case Type::DependentSizedArray:
260 NeedARCStrongQualifier = true;
261 [[fallthrough]];
263 case Type::ConstantArray:
264 case Type::IncompleteArray:
265 return canPrefixQualifiers(
266 cast<ArrayType>(UnderlyingType)->getElementType().getTypePtr(),
267 NeedARCStrongQualifier);
269 case Type::Adjusted:
270 case Type::Decayed:
271 case Type::Pointer:
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:
279 case Type::Vector:
280 case Type::ExtVector:
281 case Type::ConstantMatrix:
282 case Type::DependentSizedMatrix:
283 case Type::FunctionProto:
284 case Type::FunctionNoProto:
285 case Type::Paren:
286 case Type::PackExpansion:
287 case Type::SubstTemplateTypeParm:
288 case Type::MacroQualified:
289 CanPrefixQualifiers = false;
290 break;
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;
297 break;
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
308 // at this level.
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())
320 return;
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);
334 } else {
335 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
339 bool hasAfterQuals = false;
340 if (!CanPrefixQualifiers && !Quals.empty()) {
341 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
342 if (hasAfterQuals)
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); \
350 break;
351 #include "clang/AST/TypeNodes.inc"
354 if (hasAfterQuals) {
355 if (NeedARCStrongQualifier) {
356 IncludeStrongLifetimeRAII Strong(Policy);
357 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
358 } else {
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); \
376 break;
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) {
389 OS << "_Complex ";
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()))
404 OS << '(';
405 OS << '*';
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()))
414 OS << ')';
415 printAfter(T->getPointeeType(), OS);
418 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
419 raw_ostream &OS) {
420 SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
421 printBefore(T->getPointeeType(), OS);
422 OS << '^';
425 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
426 raw_ostream &OS) {
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());
436 return T;
439 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
440 raw_ostream &OS) {
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))
448 OS << '(';
449 OS << '&';
452 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
453 raw_ostream &OS) {
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))
460 OS << ')';
461 printAfter(Inner, OS);
464 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
465 raw_ostream &OS) {
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))
473 OS << '(';
474 OS << "&&";
477 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
478 raw_ostream &OS) {
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))
485 OS << ')';
486 printAfter(Inner, OS);
489 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
490 raw_ostream &OS) {
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()))
497 OS << '(';
499 PrintingPolicy InnerPolicy(Policy);
500 InnerPolicy.IncludeTagDefinition = false;
501 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
503 OS << "::*";
506 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
507 raw_ostream &OS) {
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()))
513 OS << ')';
514 printAfter(T->getPointeeType(), OS);
517 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
518 raw_ostream &OS) {
519 IncludeStrongLifetimeRAII Strong(Policy);
520 printBefore(T->getElementType(), OS);
523 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
524 raw_ostream &OS) {
525 OS << '[';
526 if (T->getIndexTypeQualifiers().hasQualifiers()) {
527 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
528 Policy.Restrict);
529 OS << ' ';
532 if (T->getSizeModifier() == ArraySizeModifier::Static)
533 OS << "static ";
535 OS << T->getSize().getZExtValue() << ']';
536 printAfter(T->getElementType(), OS);
539 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
540 raw_ostream &OS) {
541 IncludeStrongLifetimeRAII Strong(Policy);
542 printBefore(T->getElementType(), OS);
545 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
546 raw_ostream &OS) {
547 OS << "[]";
548 printAfter(T->getElementType(), OS);
551 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
552 raw_ostream &OS) {
553 IncludeStrongLifetimeRAII Strong(Policy);
554 printBefore(T->getElementType(), OS);
557 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
558 raw_ostream &OS) {
559 OS << '[';
560 if (T->getIndexTypeQualifiers().hasQualifiers()) {
561 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
562 OS << ' ';
565 if (T->getSizeModifier() == ArraySizeModifier::Static)
566 OS << "static ";
567 else if (T->getSizeModifier() == ArraySizeModifier::Star)
568 OS << '*';
570 if (T->getSizeExpr())
571 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
572 OS << ']';
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
579 // invisible.
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,
598 raw_ostream &OS) {
599 IncludeStrongLifetimeRAII Strong(Policy);
600 printBefore(T->getElementType(), OS);
603 void TypePrinter::printDependentSizedArrayAfter(
604 const DependentSizedArrayType *T,
605 raw_ostream &OS) {
606 OS << '[';
607 if (T->getSizeExpr())
608 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
609 OS << ']';
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);
623 OS << ")))";
624 printAfter(T->getPointeeType(), OS);
627 void TypePrinter::printDependentSizedExtVectorBefore(
628 const DependentSizedExtVectorType *T,
629 raw_ostream &OS) {
630 printBefore(T->getElementType(), OS);
633 void TypePrinter::printDependentSizedExtVectorAfter(
634 const DependentSizedExtVectorType *T,
635 raw_ostream &OS) {
636 OS << " __attribute__((ext_vector_type(";
637 if (T->getSizeExpr())
638 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
639 OS << ")))";
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 ";
647 break;
648 case VectorKind::AltiVecBool:
649 OS << "__vector __bool ";
650 printBefore(T->getElementType(), OS);
651 break;
652 case VectorKind::AltiVecVector:
653 OS << "__vector ";
654 printBefore(T->getElementType(), OS);
655 break;
656 case VectorKind::Neon:
657 OS << "__attribute__((neon_vector_type("
658 << T->getNumElements() << "))) ";
659 printBefore(T->getElementType(), OS);
660 break;
661 case VectorKind::NeonPoly:
662 OS << "__attribute__((neon_polyvector_type(" <<
663 T->getNumElements() << "))) ";
664 printBefore(T->getElementType(), OS);
665 break;
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()
671 << " * sizeof(";
672 print(T->getElementType(), OS, StringRef());
673 OS << ")))) ";
674 printBefore(T->getElementType(), OS);
675 break;
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;
687 else
688 OS << T->getNumElements();
690 OS << " * sizeof(";
691 print(T->getElementType(), OS, StringRef());
692 // Multiply by 8 for the number of bits.
693 OS << ") * 8))) ";
694 printBefore(T->getElementType(), OS);
695 break;
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();
703 OS << " * sizeof(";
704 print(T->getElementType(), OS, StringRef());
705 // Multiply by 8 for the number of bits.
706 OS << ") * 8))) ";
707 printBefore(T->getElementType(), OS);
708 break;
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 ";
721 break;
722 case VectorKind::AltiVecBool:
723 OS << "__vector __bool ";
724 printBefore(T->getElementType(), OS);
725 break;
726 case VectorKind::AltiVecVector:
727 OS << "__vector ";
728 printBefore(T->getElementType(), OS);
729 break;
730 case VectorKind::Neon:
731 OS << "__attribute__((neon_vector_type(";
732 if (T->getSizeExpr())
733 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
734 OS << "))) ";
735 printBefore(T->getElementType(), OS);
736 break;
737 case VectorKind::NeonPoly:
738 OS << "__attribute__((neon_polyvector_type(";
739 if (T->getSizeExpr())
740 T->getSizeExpr()->printPretty(OS, nullptr, Policy);
741 OS << "))) ";
742 printBefore(T->getElementType(), OS);
743 break;
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);
750 OS << " * sizeof(";
751 print(T->getElementType(), OS, StringRef());
752 OS << ")))) ";
753 printBefore(T->getElementType(), OS);
754 break;
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.
766 OS << " * 8";
767 OS << " * sizeof(";
768 print(T->getElementType(), OS, StringRef());
769 // Multiply by 8 for the number of bits.
770 OS << ") * 8";
772 OS << "))) ";
773 printBefore(T->getElementType(), OS);
774 break;
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);
781 OS << " * sizeof(";
782 print(T->getElementType(), OS, StringRef());
783 // Multiply by 8 for the number of bits.
784 OS << ") * 8";
786 OS << "))) ";
787 printBefore(T->getElementType(), OS);
788 break;
792 void TypePrinter::printDependentVectorAfter(
793 const DependentVectorType *T, raw_ostream &OS) {
794 printAfter(T->getElementType(), OS);
797 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
798 raw_ostream &OS) {
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();
806 OS << ")))";
809 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType *T,
810 raw_ostream &OS) {
811 printBefore(T->getElementType(), OS);
812 OS << " __attribute__((matrix_type(";
813 OS << T->getNumRows() << ", " << T->getNumColumns();
814 OS << ")))";
817 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType *T,
818 raw_ostream &OS) {
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);
829 OS << ", ";
830 if (T->getColumnExpr()) {
831 T->getColumnExpr()->printPretty(OS, nullptr, Policy);
833 OS << ")))";
836 void TypePrinter::printDependentSizedMatrixAfter(
837 const DependentSizedMatrixType *T, raw_ostream &OS) {
838 printAfter(T->getElementType(), OS);
841 void
842 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
843 const PrintingPolicy &Policy)
844 const {
845 if (hasDynamicExceptionSpec()) {
846 OS << " throw(";
847 if (getExceptionSpecType() == EST_MSAny)
848 OS << "...";
849 else
850 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
851 if (I)
852 OS << ", ";
854 OS << getExceptionType(I).stream(Policy);
856 OS << ')';
857 } else if (EST_NoThrow == getExceptionSpecType()) {
858 OS << " __attribute__((nothrow))";
859 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
860 OS << " noexcept";
861 // FIXME:Is it useful to print out the expression for a non-dependent
862 // noexcept specification?
863 if (isComputedNoexcept(getExceptionSpecType())) {
864 OS << '(';
865 if (getNoexceptExpr())
866 getNoexceptExpr()->printPretty(OS, nullptr, Policy);
867 OS << ')';
872 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
873 raw_ostream &OS) {
874 if (T->hasTrailingReturn()) {
875 OS << "auto ";
876 if (!HasEmptyPlaceHolder)
877 OS << '(';
878 } else {
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())
883 OS << '(';
887 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
888 switch (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,
904 raw_ostream &OS) {
905 // If needed for precedence reasons, wrap the inner part in grouping parens.
906 if (!HasEmptyPlaceHolder)
907 OS << ')';
908 SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
910 OS << '(';
912 ParamPolicyRAII ParamPolicy(Policy);
913 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
914 if (i) OS << ", ";
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())
930 OS << ", ";
931 OS << "...";
932 } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
933 // Do not emit int() if we have a proto, emit 'int(void)'.
934 OS << "void";
937 OS << ')';
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()) {
956 case RQ_None:
957 break;
959 case RQ_LValue:
960 OS << " &";
961 break;
963 case RQ_RValue:
964 OS << " &&";
965 break;
967 T->printExceptionSpecification(OS, Policy);
969 if (T->hasTrailingReturn()) {
970 OS << " -> ";
971 print(T->getReturnType(), OS, StringRef());
972 } else
973 printAfter(T->getReturnType(), OS);
976 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
977 raw_ostream &OS) {
978 if (!InsideCCAttribute) {
979 switch (Info.getCC()) {
980 case CC_C:
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.
988 break;
989 case CC_X86StdCall:
990 OS << " __attribute__((stdcall))";
991 break;
992 case CC_X86FastCall:
993 OS << " __attribute__((fastcall))";
994 break;
995 case CC_X86ThisCall:
996 OS << " __attribute__((thiscall))";
997 break;
998 case CC_X86VectorCall:
999 OS << " __attribute__((vectorcall))";
1000 break;
1001 case CC_X86Pascal:
1002 OS << " __attribute__((pascal))";
1003 break;
1004 case CC_AAPCS:
1005 OS << " __attribute__((pcs(\"aapcs\")))";
1006 break;
1007 case CC_AAPCS_VFP:
1008 OS << " __attribute__((pcs(\"aapcs-vfp\")))";
1009 break;
1010 case CC_AArch64VectorCall:
1011 OS << "__attribute__((aarch64_vector_pcs))";
1012 break;
1013 case CC_AArch64SVEPCS:
1014 OS << "__attribute__((aarch64_sve_pcs))";
1015 break;
1016 case CC_AMDGPUKernelCall:
1017 OS << "__attribute__((amdgpu_kernel))";
1018 break;
1019 case CC_IntelOclBicc:
1020 OS << " __attribute__((intel_ocl_bicc))";
1021 break;
1022 case CC_Win64:
1023 OS << " __attribute__((ms_abi))";
1024 break;
1025 case CC_X86_64SysV:
1026 OS << " __attribute__((sysv_abi))";
1027 break;
1028 case CC_X86RegCall:
1029 OS << " __attribute__((regcall))";
1030 break;
1031 case CC_SpirFunction:
1032 case CC_OpenCLKernel:
1033 // Do nothing. These CCs are not available as attributes.
1034 break;
1035 case CC_Swift:
1036 OS << " __attribute__((swiftcall))";
1037 break;
1038 case CC_SwiftAsync:
1039 OS << "__attribute__((swiftasynccall))";
1040 break;
1041 case CC_PreserveMost:
1042 OS << " __attribute__((preserve_most))";
1043 break;
1044 case CC_PreserveAll:
1045 OS << " __attribute__((preserve_all))";
1046 break;
1047 case CC_M68kRTD:
1048 OS << " __attribute__((m68k_rtd))";
1049 break;
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,
1069 raw_ostream &OS) {
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())
1074 OS << '(';
1077 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
1078 raw_ostream &OS) {
1079 // If needed for precedence reasons, wrap the inner part in grouping parens.
1080 if (!HasEmptyPlaceHolder)
1081 OS << ')';
1082 SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
1084 OS << "()";
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,
1103 raw_ostream &OS) {
1104 printTypeSpec(T->getDecl(), OS);
1107 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
1108 raw_ostream &OS) {}
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,
1130 raw_ostream &OS) {
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,
1140 raw_ostream &OS) {
1141 printAfter(T->getModifiedType(), OS);
1144 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
1146 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
1147 raw_ostream &OS) {
1148 OS << (T->getKind() == TypeOfKind::Unqualified ? "typeof_unqual "
1149 : "typeof ");
1150 if (T->getUnderlyingExpr())
1151 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1152 spaceBeforePlaceHolder(OS);
1155 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
1156 raw_ostream &OS) {}
1158 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
1159 OS << (T->getKind() == TypeOfKind::Unqualified ? "typeof_unqual("
1160 : "typeof(");
1161 print(T->getUnmodifiedType(), OS, StringRef());
1162 OS << ')';
1163 spaceBeforePlaceHolder(OS);
1166 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
1168 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
1169 OS << "decltype(";
1170 if (T->getUnderlyingExpr())
1171 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1172 OS << ')';
1173 spaceBeforePlaceHolder(OS);
1176 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
1178 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
1179 raw_ostream &OS) {
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());
1189 OS << ')';
1190 spaceBeforePlaceHolder(OS);
1193 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
1194 raw_ostream &OS) {}
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);
1200 } else {
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();
1206 if (!Args.empty())
1207 printTemplateArgumentList(
1208 OS, Args, Policy,
1209 T->getTypeConstraintConcept()->getTemplateParameters());
1210 OS << ' ';
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);
1232 } else {
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);
1249 OS << "_Atomic(";
1250 print(T->getValueType(), OS, StringRef());
1251 OS << ')';
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())
1261 OS << "read_only ";
1262 else
1263 OS << "write_only ";
1264 OS << "pipe ";
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())
1273 OS << "unsigned ";
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,
1281 raw_ostream &OS) {
1282 if (T->isUnsigned())
1283 OS << "unsigned ";
1284 OS << "_BitInt(";
1285 T->getNumBitsExpr()->printPretty(OS, nullptr, Policy);
1286 OS << ")";
1287 spaceBeforePlaceHolder(OS);
1290 void TypePrinter::printDependentBitIntAfter(const DependentBitIntType *T,
1291 raw_ostream &OS) {}
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())
1297 return;
1299 // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier,
1300 // which can also print names for function and method scopes.
1301 if (DC->isFunctionOrMethod())
1302 return;
1304 if (Policy.Callbacks && Policy.Callbacks->isScopeVisible(DC))
1305 return;
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() << "::";
1320 else
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());
1330 OS << "::";
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() << "::";
1337 else
1338 return;
1339 } else {
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);
1350 return;
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();
1360 OS << ' ';
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();
1374 } else {
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()) {
1380 OS << "lambda";
1381 HasKindDecoration = true;
1382 } else if ((isa<RecordDecl>(D) && cast<RecordDecl>(D)->isAnonymousStructOrUnion())) {
1383 OS << "anonymous";
1384 } else {
1385 OS << "unnamed";
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(
1396 D->getLocation());
1397 if (PLoc.isValid()) {
1398 OS << " at ";
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
1405 // path.
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
1421 // arguments.
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();
1429 } else {
1430 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1431 Args = TemplateArgs.asArray();
1433 IncludeStrongLifetimeRAII Strong(Policy);
1434 printTemplateArgumentList(
1435 OS, Args, Policy,
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(),
1447 T->getDecl()))
1448 continue;
1449 // Find the outermost typedef or alias template.
1450 QualType T = PNA->getTypedefType();
1451 while (true) {
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,
1473 raw_ostream &OS) {
1474 TemplateTypeParmDecl *D = T->getDecl();
1475 if (D && D->isImplicit()) {
1476 if (auto *TC = D->getTypeConstraint()) {
1477 TC->print(OS, Policy);
1478 OS << ' ';
1480 OS << "auto";
1481 } else if (IdentifierInfo *Id = T->getIdentifier())
1482 OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName()
1483 : Id->getName());
1484 else
1485 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1487 spaceBeforePlaceHolder(OS);
1490 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1491 raw_ostream &OS) {}
1493 void TypePrinter::printSubstTemplateTypeParmBefore(
1494 const SubstTemplateTypeParmType *T,
1495 raw_ostream &OS) {
1496 IncludeStrongLifetimeRAII Strong(Policy);
1497 printBefore(T->getReplacementType(), OS);
1500 void TypePrinter::printSubstTemplateTypeParmAfter(
1501 const SubstTemplateTypeParmType *T,
1502 raw_ostream &OS) {
1503 IncludeStrongLifetimeRAII Strong(Policy);
1504 printAfter(T->getReplacementType(), OS);
1507 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1508 const SubstTemplateTypeParmPackType *T,
1509 raw_ostream &OS) {
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);
1515 OS << ' ';
1517 OS << "auto";
1518 } else if (IdentifierInfo *Id = D->getIdentifier())
1519 OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName()
1520 : Id->getName());
1521 else
1522 OS << "type-parameter-" << D->getDepth() << '-' << D->getIndex();
1524 spaceBeforePlaceHolder(OS);
1528 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1529 const SubstTemplateTypeParmPackType *T,
1530 raw_ostream &OS) {
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();
1545 } else {
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,
1557 raw_ostream &OS) {
1558 printTemplateId(T, OS, Policy.FullyQualifiedName);
1561 void TypePrinter::printTemplateSpecializationAfter(
1562 const TemplateSpecializationType *T,
1563 raw_ostream &OS) {}
1565 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1566 raw_ostream &OS) {
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,
1576 raw_ostream &OS) {}
1578 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1579 raw_ostream &OS) {
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);
1588 return;
1591 if (Policy.SuppressElaboration) {
1592 printBefore(T->getNamedType(), OS);
1593 return;
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)
1601 OS << " ";
1602 NestedNameSpecifier *Qualifier = T->getQualifier();
1603 if (Qualifier)
1604 Qualifier->print(OS, Policy);
1607 ElaboratedTypePolicyRAII PolicyRAII(Policy);
1608 printBefore(T->getNamedType(), OS);
1611 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1612 raw_ostream &OS) {
1613 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
1614 return;
1616 if (Policy.SuppressElaboration) {
1617 printAfter(T->getNamedType(), OS);
1618 return;
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);
1628 OS << '(';
1629 } else
1630 printBefore(T->getInnerType(), OS);
1633 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1634 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1635 OS << ')';
1636 printAfter(T->getInnerType(), OS);
1637 } else
1638 printAfter(T->getInnerType(), OS);
1641 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1642 raw_ostream &OS) {
1643 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1644 if (T->getKeyword() != ElaboratedTypeKeyword::None)
1645 OS << " ";
1647 T->getQualifier()->print(OS, Policy);
1649 OS << T->getIdentifier()->getName();
1650 spaceBeforePlaceHolder(OS);
1653 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1654 raw_ostream &OS) {}
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)
1662 OS << " ";
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,
1675 raw_ostream &OS) {
1676 printBefore(T->getPattern(), OS);
1679 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1680 raw_ostream &OS) {
1681 printAfter(T->getPattern(), OS);
1682 OS << "...";
1685 void TypePrinter::printAttributedBefore(const AttributedType *T,
1686 raw_ostream &OS) {
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)
1695 OS << "__kindof ";
1697 if (T->getAttrKind() == attr::AddressSpace)
1698 printBefore(T->getEquivalentType(), OS);
1699 else
1700 printBefore(T->getModifiedType(), OS);
1702 if (T->isMSTypeSpec()) {
1703 switch (T->getAttrKind()) {
1704 default: return;
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())
1714 OS << "__funcref";
1716 // Print nullability type specifiers.
1717 if (T->getImmediateNullability()) {
1718 if (T->getAttrKind() == attr::TypeNonNull)
1719 OS << " _Nonnull";
1720 else if (T->getAttrKind() == attr::TypeNullable)
1721 OS << " _Nullable";
1722 else if (T->getAttrKind() == attr::TypeNullUnspecified)
1723 OS << " _Null_unspecified";
1724 else if (T->getAttrKind() == attr::TypeNullableResult)
1725 OS << " _Nullable_result";
1726 else
1727 llvm_unreachable("unhandled nullability");
1728 spaceBeforePlaceHolder(OS);
1732 void TypePrinter::printAttributedAfter(const AttributedType *T,
1733 raw_ostream &OS) {
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())
1751 return;
1753 // Don't print the inert __unsafe_unretained attribute at all.
1754 if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained)
1755 return;
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())
1761 return;
1763 if (T->getAttrKind() == attr::LifetimeBound) {
1764 OS << " [[clang::lifetimebound]]";
1765 return;
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
1770 // this twice.
1771 if (T->getAttrKind() == attr::AddressSpace)
1772 return;
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(...)]]";
1780 return;
1783 if (T->getAttrKind() == attr::ArmStreaming) {
1784 OS << "__arm_streaming";
1785 return;
1787 if (T->getAttrKind() == attr::ArmStreamingCompatible) {
1788 OS << "__arm_streaming_compatible";
1789 return;
1791 if (T->getAttrKind() == attr::ArmSharedZA) {
1792 OS << "__arm_shared_za";
1793 return;
1795 if (T->getAttrKind() == attr::ArmPreservesZA) {
1796 OS << "__arm_preserves_za";
1797 return;
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.
1821 break;
1823 case attr::LifetimeBound:
1824 case attr::TypeNonNull:
1825 case attr::TypeNullable:
1826 case attr::TypeNullableResult:
1827 case attr::TypeNullUnspecified:
1828 case attr::ObjCGC:
1829 case attr::ObjCInertUnsafeUnretained:
1830 case attr::ObjCKindOf:
1831 case attr::ObjCOwnership:
1832 case attr::Ptr32:
1833 case attr::Ptr64:
1834 case attr::SPtr:
1835 case attr::UPtr:
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";
1848 break;
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;
1864 case attr::Pcs: {
1865 OS << "pcs(";
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\"");
1871 OS << ')';
1872 break;
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";
1880 break;
1882 case attr::PreserveAll:
1883 OS << "preserve_all";
1884 break;
1885 case attr::M68kRTD:
1886 OS << "m68k_rtd";
1887 break;
1888 case attr::NoDeref:
1889 OS << "noderef";
1890 break;
1891 case attr::AcquireHandle:
1892 OS << "acquire_handle";
1893 break;
1894 case attr::ArmMveStrictPolymorphism:
1895 OS << "__clang_arm_mve_strict_polymorphism";
1896 break;
1898 OS << "))";
1901 void TypePrinter::printBTFTagAttributedBefore(const BTFTagAttributedType *T,
1902 raw_ostream &OS) {
1903 printBefore(T->getWrappedType(), OS);
1904 OS << " __attribute__((btf_type_tag(\"" << T->getAttr()->getBTFTypeTag() << "\")))";
1907 void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType *T,
1908 raw_ostream &OS) {
1909 printAfter(T->getWrappedType(), OS);
1912 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1913 raw_ostream &OS) {
1914 OS << T->getDecl()->getName();
1915 spaceBeforePlaceHolder(OS);
1918 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1919 raw_ostream &OS) {}
1921 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1922 raw_ostream &OS) {
1923 OS << T->getDecl()->getName();
1924 if (!T->qual_empty()) {
1925 bool isFirst = true;
1926 OS << '<';
1927 for (const auto *I : T->quals()) {
1928 if (isFirst)
1929 isFirst = false;
1930 else
1931 OS << ',';
1932 OS << I->getName();
1934 OS << '>';
1937 spaceBeforePlaceHolder(OS);
1940 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1941 raw_ostream &OS) {}
1943 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1944 raw_ostream &OS) {
1945 if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1946 !T->isKindOfTypeAsWritten())
1947 return printBefore(T->getBaseType(), OS);
1949 if (T->isKindOfTypeAsWritten())
1950 OS << "__kindof ";
1952 print(T->getBaseType(), OS, StringRef());
1954 if (T->isSpecializedAsWritten()) {
1955 bool isFirst = true;
1956 OS << '<';
1957 for (auto typeArg : T->getTypeArgsAsWritten()) {
1958 if (isFirst)
1959 isFirst = false;
1960 else
1961 OS << ",";
1963 print(typeArg, OS, StringRef());
1965 OS << '>';
1968 if (!T->qual_empty()) {
1969 bool isFirst = true;
1970 OS << '<';
1971 for (const auto *I : T->quals()) {
1972 if (isFirst)
1973 isFirst = false;
1974 else
1975 OS << ',';
1976 OS << I->getName();
1978 OS << '>';
1981 spaceBeforePlaceHolder(OS);
1984 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1985 raw_ostream &OS) {
1986 if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1987 !T->isKindOfTypeAsWritten())
1988 return printAfter(T->getBaseType(), OS);
1991 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1992 raw_ostream &OS) {
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)
1999 OS << ' ';
2000 OS << '*';
2004 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
2005 raw_ostream &OS) {}
2007 static
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,
2021 bool IncludeType) {
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,
2031 unsigned Depth);
2033 static bool isSubstitutedType(ASTContext &Ctx, QualType T, QualType Pattern,
2034 ArrayRef<TemplateArgument> Args, unsigned Depth) {
2035 if (Ctx.hasSameType(T, Pattern))
2036 return true;
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);
2046 return false;
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)
2056 return false;
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.
2068 if (auto *PTST =
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();
2079 } else {
2080 return false;
2083 if (!isSubstitutedTemplateArgument(Ctx, Template, PTST->getTemplateName(),
2084 Args, Depth))
2085 return false;
2086 if (TemplateArgs.size() != PTST->template_arguments().size())
2087 return false;
2088 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2089 if (!isSubstitutedTemplateArgument(
2090 Ctx, TemplateArgs[I], PTST->template_arguments()[I], Args, Depth))
2091 return false;
2092 return true;
2095 // FIXME: Handle more cases.
2096 return false;
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)
2105 return false;
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))
2111 return false;
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))
2120 return false;
2122 return llvm::APSInt::isSameValue(args_expr->EvaluateKnownConstInt(Ctx),
2123 pattern_expr->EvaluateKnownConstInt(Ctx));
2126 return false;
2129 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
2130 TemplateArgument Pattern,
2131 ArrayRef<TemplateArgument> Args,
2132 unsigned Depth) {
2133 Arg = Ctx.getCanonicalTemplateArgument(Arg);
2134 Pattern = Ctx.getCanonicalTemplateArgument(Pattern);
2135 if (Arg.structurallyEquals(Pattern))
2136 return true;
2138 if (Pattern.getKind() == TemplateArgument::Expression) {
2139 if (auto *DRE =
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))
2148 return true;
2150 if (Arg.getKind() != Pattern.getKind())
2151 return false;
2153 if (Arg.getKind() == TemplateArgument::Type)
2154 return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args,
2155 Depth);
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.
2166 return false;
2169 bool clang::isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg,
2170 const NamedDecl *Param,
2171 ArrayRef<TemplateArgument> Args,
2172 unsigned Depth) {
2173 // An empty pack is equivalent to not providing a pack argument.
2174 if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0)
2175 return true;
2177 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param)) {
2178 return TTPD->hasDefaultArgument() &&
2179 isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(),
2180 Args, Depth);
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(),
2188 Args, Depth);
2190 return false;
2193 template <typename TA>
2194 static void
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 ? "," : ", ";
2209 if (!IsPack)
2210 OS << '<';
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)
2221 OS << Comma;
2222 printTo(ArgOS, Argument.getPackAsArray(), Policy, TPL,
2223 /*IsPack*/ true, ParmIndex);
2224 } else {
2225 if (!FirstArg)
2226 OS << Comma;
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] == ':')
2238 OS << ' ';
2240 OS << ArgString;
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() == '>';
2246 FirstArg = false;
2249 // Use same template parameter for all elements of Pack
2250 if (!IsPack)
2251 ParmIndex++;
2254 if (!IsPack) {
2255 if (NeedSpace)
2256 OS << ' ';
2257 OS << '>';
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 {
2283 LangOptions LO;
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
2289 // space.
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())
2299 return false;
2301 if (getAddressSpace() != LangAS::Default)
2302 return false;
2304 if (getObjCGCAttr())
2305 return false;
2307 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
2308 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
2309 return false;
2311 return true;
2314 std::string Qualifiers::getAddrSpaceAsString(LangAS AS) {
2315 switch (AS) {
2316 case LangAS::Default:
2317 return "";
2318 case LangAS::opencl_global:
2319 case LangAS::sycl_global:
2320 return "__global";
2321 case LangAS::opencl_local:
2322 case LangAS::sycl_local:
2323 return "__local";
2324 case LangAS::opencl_private:
2325 case LangAS::sycl_private:
2326 return "__private";
2327 case LangAS::opencl_constant:
2328 return "__constant";
2329 case LangAS::opencl_generic:
2330 return "__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";
2347 case LangAS::ptr64:
2348 return "__ptr64";
2349 case LangAS::wasm_funcref:
2350 return "__funcref";
2351 case LangAS::hlsl_groupshared:
2352 return "groupshared";
2353 default:
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
2360 // space.
2361 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
2362 bool appendSpaceIfNonEmpty) const {
2363 bool addSpace = false;
2365 unsigned quals = getCVRQualifiers();
2366 if (quals) {
2367 AppendTypeQualList(OS, quals, Policy.Restrict);
2368 addSpace = true;
2370 if (hasUnaligned()) {
2371 if (addSpace)
2372 OS << ' ';
2373 OS << "__unaligned";
2374 addSpace = true;
2376 auto ASStr = getAddrSpaceAsString(getAddressSpace());
2377 if (!ASStr.empty()) {
2378 if (addSpace)
2379 OS << ' ';
2380 addSpace = true;
2381 // Wrap target address space into an attribute syntax
2382 if (isTargetAddressSpace(getAddressSpace()))
2383 OS << "__attribute__((address_space(" << ASStr << ")))";
2384 else
2385 OS << ASStr;
2388 if (Qualifiers::GC gc = getObjCGCAttr()) {
2389 if (addSpace)
2390 OS << ' ';
2391 addSpace = true;
2392 if (gc == Qualifiers::Weak)
2393 OS << "__weak";
2394 else
2395 OS << "__strong";
2397 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
2398 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
2399 if (addSpace)
2400 OS << ' ';
2401 addSpace = true;
2404 switch (lifetime) {
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)
2409 OS << "__strong";
2410 break;
2412 case Qualifiers::OCL_Weak: OS << "__weak"; break;
2413 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
2417 if (appendSpaceIfNonEmpty && addSpace)
2418 OS << ' ';
2421 std::string QualType::getAsString() const {
2422 return getAsString(split(), LangOptions());
2425 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
2426 std::string S;
2427 getAsStringInternal(S, Policy);
2428 return S;
2431 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
2432 const PrintingPolicy &Policy) {
2433 std::string buffer;
2434 getAsStringInternal(ty, qs, buffer, Policy);
2435 return buffer;
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,
2441 Indentation);
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,
2456 Policy);
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());
2466 buffer.swap(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=*/"");
2472 return OS;