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. 10 // 11 //===----------------------------------------------------------------------===// 12 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/Type.h" 26 #include "clang/Basic/AddressSpaces.h" 27 #include "clang/Basic/ExceptionSpecificationType.h" 28 #include "clang/Basic/IdentifierTable.h" 29 #include "clang/Basic/LLVM.h" 30 #include "clang/Basic/LangOptions.h" 31 #include "clang/Basic/SourceLocation.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/Specifiers.h" 34 #include "llvm/ADT/ArrayRef.h" 35 #include "llvm/ADT/SmallString.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/Compiler.h" 40 #include "llvm/Support/ErrorHandling.h" 41 #include "llvm/Support/SaveAndRestore.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include <cassert> 44 #include <string> 45 46 using namespace clang; 47 48 namespace { 49 50 /// RAII object that enables printing of the ARC __strong lifetime 51 /// qualifier. 52 class IncludeStrongLifetimeRAII { 53 PrintingPolicy &Policy; 54 bool Old; 55 56 public: 57 explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) 58 : Policy(Policy), Old(Policy.SuppressStrongLifetime) { 59 if (!Policy.SuppressLifetimeQualifiers) 60 Policy.SuppressStrongLifetime = false; 61 } 62 63 ~IncludeStrongLifetimeRAII() { 64 Policy.SuppressStrongLifetime = Old; 65 } 66 }; 67 68 class ParamPolicyRAII { 69 PrintingPolicy &Policy; 70 bool Old; 71 72 public: 73 explicit ParamPolicyRAII(PrintingPolicy &Policy) 74 : Policy(Policy), Old(Policy.SuppressSpecifiers) { 75 Policy.SuppressSpecifiers = false; 76 } 77 78 ~ParamPolicyRAII() { 79 Policy.SuppressSpecifiers = Old; 80 } 81 }; 82 83 class DefaultTemplateArgsPolicyRAII { 84 PrintingPolicy &Policy; 85 bool Old; 86 87 public: 88 explicit DefaultTemplateArgsPolicyRAII(PrintingPolicy &Policy) 89 : Policy(Policy), Old(Policy.SuppressDefaultTemplateArgs) { 90 Policy.SuppressDefaultTemplateArgs = false; 91 } 92 93 ~DefaultTemplateArgsPolicyRAII() { 94 Policy.SuppressDefaultTemplateArgs = Old; 95 } 96 }; 97 98 class ElaboratedTypePolicyRAII { 99 PrintingPolicy &Policy; 100 bool SuppressTagKeyword; 101 bool SuppressScope; 102 103 public: 104 explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) { 105 SuppressTagKeyword = Policy.SuppressTagKeyword; 106 SuppressScope = Policy.SuppressScope; 107 Policy.SuppressTagKeyword = true; 108 Policy.SuppressScope = true; 109 } 110 111 ~ElaboratedTypePolicyRAII() { 112 Policy.SuppressTagKeyword = SuppressTagKeyword; 113 Policy.SuppressScope = SuppressScope; 114 } 115 }; 116 117 class TypePrinter { 118 PrintingPolicy Policy; 119 unsigned Indentation; 120 bool HasEmptyPlaceHolder = false; 121 bool InsideCCAttribute = false; 122 123 public: 124 explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0) 125 : Policy(Policy), Indentation(Indentation) {} 126 127 void print(const Type *ty, Qualifiers qs, raw_ostream &OS, 128 StringRef PlaceHolder); 129 void print(QualType T, raw_ostream &OS, StringRef PlaceHolder); 130 131 static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier); 132 void spaceBeforePlaceHolder(raw_ostream &OS); 133 void printTypeSpec(NamedDecl *D, raw_ostream &OS); 134 void printTemplateId(const TemplateSpecializationType *T, raw_ostream &OS, 135 bool FullyQualify); 136 137 void printBefore(QualType T, raw_ostream &OS); 138 void printAfter(QualType T, raw_ostream &OS); 139 void AppendScope(DeclContext *DC, raw_ostream &OS, 140 DeclarationName NameInScope); 141 void printTag(TagDecl *T, raw_ostream &OS); 142 void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS); 143 #define ABSTRACT_TYPE(CLASS, PARENT) 144 #define TYPE(CLASS, PARENT) \ 145 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \ 146 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS); 147 #include "clang/AST/TypeNodes.inc" 148 149 private: 150 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS); 151 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS); 152 }; 153 154 } // namespace 155 156 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals, 157 bool HasRestrictKeyword) { 158 bool appendSpace = false; 159 if (TypeQuals & Qualifiers::Const) { 160 OS << "const"; 161 appendSpace = true; 162 } 163 if (TypeQuals & Qualifiers::Volatile) { 164 if (appendSpace) OS << ' '; 165 OS << "volatile"; 166 appendSpace = true; 167 } 168 if (TypeQuals & Qualifiers::Restrict) { 169 if (appendSpace) OS << ' '; 170 if (HasRestrictKeyword) { 171 OS << "restrict"; 172 } else { 173 OS << "__restrict"; 174 } 175 } 176 } 177 178 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) { 179 if (!HasEmptyPlaceHolder) 180 OS << ' '; 181 } 182 183 static SplitQualType splitAccordingToPolicy(QualType QT, 184 const PrintingPolicy &Policy) { 185 if (Policy.PrintCanonicalTypes) 186 QT = QT.getCanonicalType(); 187 return QT.split(); 188 } 189 190 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) { 191 SplitQualType split = splitAccordingToPolicy(t, Policy); 192 print(split.Ty, split.Quals, OS, PlaceHolder); 193 } 194 195 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS, 196 StringRef PlaceHolder) { 197 if (!T) { 198 OS << "NULL TYPE"; 199 return; 200 } 201 202 SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty()); 203 204 printBefore(T, Quals, OS); 205 OS << PlaceHolder; 206 printAfter(T, Quals, OS); 207 } 208 209 bool TypePrinter::canPrefixQualifiers(const Type *T, 210 bool &NeedARCStrongQualifier) { 211 // CanPrefixQualifiers - We prefer to print type qualifiers before the type, 212 // so that we get "const int" instead of "int const", but we can't do this if 213 // the type is complex. For example if the type is "int*", we *must* print 214 // "int * const", printing "const int *" is different. Only do this when the 215 // type expands to a simple string. 216 bool CanPrefixQualifiers = false; 217 NeedARCStrongQualifier = false; 218 const Type *UnderlyingType = T; 219 if (const auto *AT = dyn_cast<AutoType>(T)) 220 UnderlyingType = AT->desugar().getTypePtr(); 221 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T)) 222 UnderlyingType = Subst->getReplacementType().getTypePtr(); 223 Type::TypeClass TC = UnderlyingType->getTypeClass(); 224 225 switch (TC) { 226 case Type::Auto: 227 case Type::Builtin: 228 case Type::Complex: 229 case Type::UnresolvedUsing: 230 case Type::Using: 231 case Type::Typedef: 232 case Type::TypeOfExpr: 233 case Type::TypeOf: 234 case Type::Decltype: 235 case Type::UnaryTransform: 236 case Type::Record: 237 case Type::Enum: 238 case Type::Elaborated: 239 case Type::TemplateTypeParm: 240 case Type::SubstTemplateTypeParmPack: 241 case Type::DeducedTemplateSpecialization: 242 case Type::TemplateSpecialization: 243 case Type::InjectedClassName: 244 case Type::DependentName: 245 case Type::DependentTemplateSpecialization: 246 case Type::ObjCObject: 247 case Type::ObjCTypeParam: 248 case Type::ObjCInterface: 249 case Type::Atomic: 250 case Type::Pipe: 251 case Type::BitInt: 252 case Type::DependentBitInt: 253 case Type::BTFTagAttributed: 254 CanPrefixQualifiers = true; 255 break; 256 257 case Type::ObjCObjectPointer: 258 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() || 259 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType(); 260 break; 261 262 case Type::VariableArray: 263 case Type::DependentSizedArray: 264 NeedARCStrongQualifier = true; 265 LLVM_FALLTHROUGH; 266 267 case Type::ConstantArray: 268 case Type::IncompleteArray: 269 return canPrefixQualifiers( 270 cast<ArrayType>(UnderlyingType)->getElementType().getTypePtr(), 271 NeedARCStrongQualifier); 272 273 case Type::Adjusted: 274 case Type::Decayed: 275 case Type::Pointer: 276 case Type::BlockPointer: 277 case Type::LValueReference: 278 case Type::RValueReference: 279 case Type::MemberPointer: 280 case Type::DependentAddressSpace: 281 case Type::DependentVector: 282 case Type::DependentSizedExtVector: 283 case Type::Vector: 284 case Type::ExtVector: 285 case Type::ConstantMatrix: 286 case Type::DependentSizedMatrix: 287 case Type::FunctionProto: 288 case Type::FunctionNoProto: 289 case Type::Paren: 290 case Type::PackExpansion: 291 case Type::SubstTemplateTypeParm: 292 case Type::MacroQualified: 293 CanPrefixQualifiers = false; 294 break; 295 296 case Type::Attributed: { 297 // We still want to print the address_space before the type if it is an 298 // address_space attribute. 299 const auto *AttrTy = cast<AttributedType>(UnderlyingType); 300 CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace; 301 break; 302 } 303 } 304 305 return CanPrefixQualifiers; 306 } 307 308 void TypePrinter::printBefore(QualType T, raw_ostream &OS) { 309 SplitQualType Split = splitAccordingToPolicy(T, Policy); 310 311 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2 312 // at this level. 313 Qualifiers Quals = Split.Quals; 314 if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty)) 315 Quals -= QualType(Subst, 0).getQualifiers(); 316 317 printBefore(Split.Ty, Quals, OS); 318 } 319 320 /// Prints the part of the type string before an identifier, e.g. for 321 /// "int foo[10]" it prints "int ". 322 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) { 323 if (Policy.SuppressSpecifiers && T->isSpecifierType()) 324 return; 325 326 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder); 327 328 // Print qualifiers as appropriate. 329 330 bool CanPrefixQualifiers = false; 331 bool NeedARCStrongQualifier = false; 332 CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier); 333 334 if (CanPrefixQualifiers && !Quals.empty()) { 335 if (NeedARCStrongQualifier) { 336 IncludeStrongLifetimeRAII Strong(Policy); 337 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true); 338 } else { 339 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true); 340 } 341 } 342 343 bool hasAfterQuals = false; 344 if (!CanPrefixQualifiers && !Quals.empty()) { 345 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy); 346 if (hasAfterQuals) 347 HasEmptyPlaceHolder = false; 348 } 349 350 switch (T->getTypeClass()) { 351 #define ABSTRACT_TYPE(CLASS, PARENT) 352 #define TYPE(CLASS, PARENT) case Type::CLASS: \ 353 print##CLASS##Before(cast<CLASS##Type>(T), OS); \ 354 break; 355 #include "clang/AST/TypeNodes.inc" 356 } 357 358 if (hasAfterQuals) { 359 if (NeedARCStrongQualifier) { 360 IncludeStrongLifetimeRAII Strong(Policy); 361 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get()); 362 } else { 363 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get()); 364 } 365 } 366 } 367 368 void TypePrinter::printAfter(QualType t, raw_ostream &OS) { 369 SplitQualType split = splitAccordingToPolicy(t, Policy); 370 printAfter(split.Ty, split.Quals, OS); 371 } 372 373 /// Prints the part of the type string after an identifier, e.g. for 374 /// "int foo[10]" it prints "[10]". 375 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) { 376 switch (T->getTypeClass()) { 377 #define ABSTRACT_TYPE(CLASS, PARENT) 378 #define TYPE(CLASS, PARENT) case Type::CLASS: \ 379 print##CLASS##After(cast<CLASS##Type>(T), OS); \ 380 break; 381 #include "clang/AST/TypeNodes.inc" 382 } 383 } 384 385 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) { 386 OS << T->getName(Policy); 387 spaceBeforePlaceHolder(OS); 388 } 389 390 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {} 391 392 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) { 393 OS << "_Complex "; 394 printBefore(T->getElementType(), OS); 395 } 396 397 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) { 398 printAfter(T->getElementType(), OS); 399 } 400 401 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) { 402 IncludeStrongLifetimeRAII Strong(Policy); 403 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 404 printBefore(T->getPointeeType(), OS); 405 // Handle things like 'int (*A)[4];' correctly. 406 // FIXME: this should include vectors, but vectors use attributes I guess. 407 if (isa<ArrayType>(T->getPointeeType())) 408 OS << '('; 409 OS << '*'; 410 } 411 412 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) { 413 IncludeStrongLifetimeRAII Strong(Policy); 414 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 415 // Handle things like 'int (*A)[4];' correctly. 416 // FIXME: this should include vectors, but vectors use attributes I guess. 417 if (isa<ArrayType>(T->getPointeeType())) 418 OS << ')'; 419 printAfter(T->getPointeeType(), OS); 420 } 421 422 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T, 423 raw_ostream &OS) { 424 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 425 printBefore(T->getPointeeType(), OS); 426 OS << '^'; 427 } 428 429 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T, 430 raw_ostream &OS) { 431 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 432 printAfter(T->getPointeeType(), OS); 433 } 434 435 // When printing a reference, the referenced type might also be a reference. 436 // If so, we want to skip that before printing the inner type. 437 static QualType skipTopLevelReferences(QualType T) { 438 if (auto *Ref = T->getAs<ReferenceType>()) 439 return skipTopLevelReferences(Ref->getPointeeTypeAsWritten()); 440 return T; 441 } 442 443 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T, 444 raw_ostream &OS) { 445 IncludeStrongLifetimeRAII Strong(Policy); 446 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 447 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 448 printBefore(Inner, OS); 449 // Handle things like 'int (&A)[4];' correctly. 450 // FIXME: this should include vectors, but vectors use attributes I guess. 451 if (isa<ArrayType>(Inner)) 452 OS << '('; 453 OS << '&'; 454 } 455 456 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T, 457 raw_ostream &OS) { 458 IncludeStrongLifetimeRAII Strong(Policy); 459 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 460 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 461 // Handle things like 'int (&A)[4];' correctly. 462 // FIXME: this should include vectors, but vectors use attributes I guess. 463 if (isa<ArrayType>(Inner)) 464 OS << ')'; 465 printAfter(Inner, OS); 466 } 467 468 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T, 469 raw_ostream &OS) { 470 IncludeStrongLifetimeRAII Strong(Policy); 471 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 472 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 473 printBefore(Inner, OS); 474 // Handle things like 'int (&&A)[4];' correctly. 475 // FIXME: this should include vectors, but vectors use attributes I guess. 476 if (isa<ArrayType>(Inner)) 477 OS << '('; 478 OS << "&&"; 479 } 480 481 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T, 482 raw_ostream &OS) { 483 IncludeStrongLifetimeRAII Strong(Policy); 484 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 485 QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten()); 486 // Handle things like 'int (&&A)[4];' correctly. 487 // FIXME: this should include vectors, but vectors use attributes I guess. 488 if (isa<ArrayType>(Inner)) 489 OS << ')'; 490 printAfter(Inner, OS); 491 } 492 493 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, 494 raw_ostream &OS) { 495 IncludeStrongLifetimeRAII Strong(Policy); 496 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 497 printBefore(T->getPointeeType(), OS); 498 // Handle things like 'int (Cls::*A)[4];' correctly. 499 // FIXME: this should include vectors, but vectors use attributes I guess. 500 if (isa<ArrayType>(T->getPointeeType())) 501 OS << '('; 502 503 PrintingPolicy InnerPolicy(Policy); 504 InnerPolicy.IncludeTagDefinition = false; 505 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef()); 506 507 OS << "::*"; 508 } 509 510 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, 511 raw_ostream &OS) { 512 IncludeStrongLifetimeRAII Strong(Policy); 513 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 514 // Handle things like 'int (Cls::*A)[4];' correctly. 515 // FIXME: this should include vectors, but vectors use attributes I guess. 516 if (isa<ArrayType>(T->getPointeeType())) 517 OS << ')'; 518 printAfter(T->getPointeeType(), OS); 519 } 520 521 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, 522 raw_ostream &OS) { 523 IncludeStrongLifetimeRAII Strong(Policy); 524 printBefore(T->getElementType(), OS); 525 } 526 527 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, 528 raw_ostream &OS) { 529 OS << '['; 530 if (T->getIndexTypeQualifiers().hasQualifiers()) { 531 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), 532 Policy.Restrict); 533 OS << ' '; 534 } 535 536 if (T->getSizeModifier() == ArrayType::Static) 537 OS << "static "; 538 539 OS << T->getSize().getZExtValue() << ']'; 540 printAfter(T->getElementType(), OS); 541 } 542 543 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, 544 raw_ostream &OS) { 545 IncludeStrongLifetimeRAII Strong(Policy); 546 printBefore(T->getElementType(), OS); 547 } 548 549 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, 550 raw_ostream &OS) { 551 OS << "[]"; 552 printAfter(T->getElementType(), OS); 553 } 554 555 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, 556 raw_ostream &OS) { 557 IncludeStrongLifetimeRAII Strong(Policy); 558 printBefore(T->getElementType(), OS); 559 } 560 561 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, 562 raw_ostream &OS) { 563 OS << '['; 564 if (T->getIndexTypeQualifiers().hasQualifiers()) { 565 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict); 566 OS << ' '; 567 } 568 569 if (T->getSizeModifier() == VariableArrayType::Static) 570 OS << "static "; 571 else if (T->getSizeModifier() == VariableArrayType::Star) 572 OS << '*'; 573 574 if (T->getSizeExpr()) 575 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 576 OS << ']'; 577 578 printAfter(T->getElementType(), OS); 579 } 580 581 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) { 582 // Print the adjusted representation, otherwise the adjustment will be 583 // invisible. 584 printBefore(T->getAdjustedType(), OS); 585 } 586 587 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) { 588 printAfter(T->getAdjustedType(), OS); 589 } 590 591 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) { 592 // Print as though it's a pointer. 593 printAdjustedBefore(T, OS); 594 } 595 596 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) { 597 printAdjustedAfter(T, OS); 598 } 599 600 void TypePrinter::printDependentSizedArrayBefore( 601 const DependentSizedArrayType *T, 602 raw_ostream &OS) { 603 IncludeStrongLifetimeRAII Strong(Policy); 604 printBefore(T->getElementType(), OS); 605 } 606 607 void TypePrinter::printDependentSizedArrayAfter( 608 const DependentSizedArrayType *T, 609 raw_ostream &OS) { 610 OS << '['; 611 if (T->getSizeExpr()) 612 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 613 OS << ']'; 614 printAfter(T->getElementType(), OS); 615 } 616 617 void TypePrinter::printDependentAddressSpaceBefore( 618 const DependentAddressSpaceType *T, raw_ostream &OS) { 619 printBefore(T->getPointeeType(), OS); 620 } 621 622 void TypePrinter::printDependentAddressSpaceAfter( 623 const DependentAddressSpaceType *T, raw_ostream &OS) { 624 OS << " __attribute__((address_space("; 625 if (T->getAddrSpaceExpr()) 626 T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy); 627 OS << ")))"; 628 printAfter(T->getPointeeType(), OS); 629 } 630 631 void TypePrinter::printDependentSizedExtVectorBefore( 632 const DependentSizedExtVectorType *T, 633 raw_ostream &OS) { 634 printBefore(T->getElementType(), OS); 635 } 636 637 void TypePrinter::printDependentSizedExtVectorAfter( 638 const DependentSizedExtVectorType *T, 639 raw_ostream &OS) { 640 OS << " __attribute__((ext_vector_type("; 641 if (T->getSizeExpr()) 642 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 643 OS << ")))"; 644 printAfter(T->getElementType(), OS); 645 } 646 647 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { 648 switch (T->getVectorKind()) { 649 case VectorType::AltiVecPixel: 650 OS << "__vector __pixel "; 651 break; 652 case VectorType::AltiVecBool: 653 OS << "__vector __bool "; 654 printBefore(T->getElementType(), OS); 655 break; 656 case VectorType::AltiVecVector: 657 OS << "__vector "; 658 printBefore(T->getElementType(), OS); 659 break; 660 case VectorType::NeonVector: 661 OS << "__attribute__((neon_vector_type(" 662 << T->getNumElements() << "))) "; 663 printBefore(T->getElementType(), OS); 664 break; 665 case VectorType::NeonPolyVector: 666 OS << "__attribute__((neon_polyvector_type(" << 667 T->getNumElements() << "))) "; 668 printBefore(T->getElementType(), OS); 669 break; 670 case VectorType::GenericVector: { 671 // FIXME: We prefer to print the size directly here, but have no way 672 // to get the size of the type. 673 OS << "__attribute__((__vector_size__(" 674 << T->getNumElements() 675 << " * sizeof("; 676 print(T->getElementType(), OS, StringRef()); 677 OS << ")))) "; 678 printBefore(T->getElementType(), OS); 679 break; 680 } 681 case VectorType::SveFixedLengthDataVector: 682 case VectorType::SveFixedLengthPredicateVector: 683 // FIXME: We prefer to print the size directly here, but have no way 684 // to get the size of the type. 685 OS << "__attribute__((__arm_sve_vector_bits__("; 686 687 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 688 // Predicates take a bit per byte of the vector size, multiply by 8 to 689 // get the number of bits passed to the attribute. 690 OS << T->getNumElements() * 8; 691 else 692 OS << T->getNumElements(); 693 694 OS << " * sizeof("; 695 print(T->getElementType(), OS, StringRef()); 696 // Multiply by 8 for the number of bits. 697 OS << ") * 8))) "; 698 printBefore(T->getElementType(), OS); 699 } 700 } 701 702 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) { 703 printAfter(T->getElementType(), OS); 704 } 705 706 void TypePrinter::printDependentVectorBefore( 707 const DependentVectorType *T, raw_ostream &OS) { 708 switch (T->getVectorKind()) { 709 case VectorType::AltiVecPixel: 710 OS << "__vector __pixel "; 711 break; 712 case VectorType::AltiVecBool: 713 OS << "__vector __bool "; 714 printBefore(T->getElementType(), OS); 715 break; 716 case VectorType::AltiVecVector: 717 OS << "__vector "; 718 printBefore(T->getElementType(), OS); 719 break; 720 case VectorType::NeonVector: 721 OS << "__attribute__((neon_vector_type("; 722 if (T->getSizeExpr()) 723 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 724 OS << "))) "; 725 printBefore(T->getElementType(), OS); 726 break; 727 case VectorType::NeonPolyVector: 728 OS << "__attribute__((neon_polyvector_type("; 729 if (T->getSizeExpr()) 730 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 731 OS << "))) "; 732 printBefore(T->getElementType(), OS); 733 break; 734 case VectorType::GenericVector: { 735 // FIXME: We prefer to print the size directly here, but have no way 736 // to get the size of the type. 737 OS << "__attribute__((__vector_size__("; 738 if (T->getSizeExpr()) 739 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 740 OS << " * sizeof("; 741 print(T->getElementType(), OS, StringRef()); 742 OS << ")))) "; 743 printBefore(T->getElementType(), OS); 744 break; 745 } 746 case VectorType::SveFixedLengthDataVector: 747 case VectorType::SveFixedLengthPredicateVector: 748 // FIXME: We prefer to print the size directly here, but have no way 749 // to get the size of the type. 750 OS << "__attribute__((__arm_sve_vector_bits__("; 751 if (T->getSizeExpr()) { 752 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 753 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 754 // Predicates take a bit per byte of the vector size, multiply by 8 to 755 // get the number of bits passed to the attribute. 756 OS << " * 8"; 757 OS << " * sizeof("; 758 print(T->getElementType(), OS, StringRef()); 759 // Multiply by 8 for the number of bits. 760 OS << ") * 8"; 761 } 762 OS << "))) "; 763 printBefore(T->getElementType(), OS); 764 } 765 } 766 767 void TypePrinter::printDependentVectorAfter( 768 const DependentVectorType *T, raw_ostream &OS) { 769 printAfter(T->getElementType(), OS); 770 } 771 772 void TypePrinter::printExtVectorBefore(const ExtVectorType *T, 773 raw_ostream &OS) { 774 printBefore(T->getElementType(), OS); 775 } 776 777 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { 778 printAfter(T->getElementType(), OS); 779 OS << " __attribute__((ext_vector_type("; 780 OS << T->getNumElements(); 781 OS << ")))"; 782 } 783 784 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType *T, 785 raw_ostream &OS) { 786 printBefore(T->getElementType(), OS); 787 OS << " __attribute__((matrix_type("; 788 OS << T->getNumRows() << ", " << T->getNumColumns(); 789 OS << ")))"; 790 } 791 792 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType *T, 793 raw_ostream &OS) { 794 printAfter(T->getElementType(), OS); 795 } 796 797 void TypePrinter::printDependentSizedMatrixBefore( 798 const DependentSizedMatrixType *T, raw_ostream &OS) { 799 printBefore(T->getElementType(), OS); 800 OS << " __attribute__((matrix_type("; 801 if (T->getRowExpr()) { 802 T->getRowExpr()->printPretty(OS, nullptr, Policy); 803 } 804 OS << ", "; 805 if (T->getColumnExpr()) { 806 T->getColumnExpr()->printPretty(OS, nullptr, Policy); 807 } 808 OS << ")))"; 809 } 810 811 void TypePrinter::printDependentSizedMatrixAfter( 812 const DependentSizedMatrixType *T, raw_ostream &OS) { 813 printAfter(T->getElementType(), OS); 814 } 815 816 void 817 FunctionProtoType::printExceptionSpecification(raw_ostream &OS, 818 const PrintingPolicy &Policy) 819 const { 820 if (hasDynamicExceptionSpec()) { 821 OS << " throw("; 822 if (getExceptionSpecType() == EST_MSAny) 823 OS << "..."; 824 else 825 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) { 826 if (I) 827 OS << ", "; 828 829 OS << getExceptionType(I).stream(Policy); 830 } 831 OS << ')'; 832 } else if (EST_NoThrow == getExceptionSpecType()) { 833 OS << " __attribute__((nothrow))"; 834 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) { 835 OS << " noexcept"; 836 // FIXME:Is it useful to print out the expression for a non-dependent 837 // noexcept specification? 838 if (isComputedNoexcept(getExceptionSpecType())) { 839 OS << '('; 840 if (getNoexceptExpr()) 841 getNoexceptExpr()->printPretty(OS, nullptr, Policy); 842 OS << ')'; 843 } 844 } 845 } 846 847 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, 848 raw_ostream &OS) { 849 if (T->hasTrailingReturn()) { 850 OS << "auto "; 851 if (!HasEmptyPlaceHolder) 852 OS << '('; 853 } else { 854 // If needed for precedence reasons, wrap the inner part in grouping parens. 855 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); 856 printBefore(T->getReturnType(), OS); 857 if (!PrevPHIsEmpty.get()) 858 OS << '('; 859 } 860 } 861 862 StringRef clang::getParameterABISpelling(ParameterABI ABI) { 863 switch (ABI) { 864 case ParameterABI::Ordinary: 865 llvm_unreachable("asking for spelling of ordinary parameter ABI"); 866 case ParameterABI::SwiftContext: 867 return "swift_context"; 868 case ParameterABI::SwiftAsyncContext: 869 return "swift_async_context"; 870 case ParameterABI::SwiftErrorResult: 871 return "swift_error_result"; 872 case ParameterABI::SwiftIndirectResult: 873 return "swift_indirect_result"; 874 } 875 llvm_unreachable("bad parameter ABI kind"); 876 } 877 878 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, 879 raw_ostream &OS) { 880 // If needed for precedence reasons, wrap the inner part in grouping parens. 881 if (!HasEmptyPlaceHolder) 882 OS << ')'; 883 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 884 885 OS << '('; 886 { 887 ParamPolicyRAII ParamPolicy(Policy); 888 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) { 889 if (i) OS << ", "; 890 891 auto EPI = T->getExtParameterInfo(i); 892 if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) "; 893 if (EPI.isNoEscape()) 894 OS << "__attribute__((noescape)) "; 895 auto ABI = EPI.getABI(); 896 if (ABI != ParameterABI::Ordinary) 897 OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) "; 898 899 print(T->getParamType(i), OS, StringRef()); 900 } 901 } 902 903 if (T->isVariadic()) { 904 if (T->getNumParams()) 905 OS << ", "; 906 OS << "..."; 907 } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) { 908 // Do not emit int() if we have a proto, emit 'int(void)'. 909 OS << "void"; 910 } 911 912 OS << ')'; 913 914 FunctionType::ExtInfo Info = T->getExtInfo(); 915 916 printFunctionAfter(Info, OS); 917 918 if (!T->getMethodQuals().empty()) 919 OS << " " << T->getMethodQuals().getAsString(); 920 921 switch (T->getRefQualifier()) { 922 case RQ_None: 923 break; 924 925 case RQ_LValue: 926 OS << " &"; 927 break; 928 929 case RQ_RValue: 930 OS << " &&"; 931 break; 932 } 933 T->printExceptionSpecification(OS, Policy); 934 935 if (T->hasTrailingReturn()) { 936 OS << " -> "; 937 print(T->getReturnType(), OS, StringRef()); 938 } else 939 printAfter(T->getReturnType(), OS); 940 } 941 942 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info, 943 raw_ostream &OS) { 944 if (!InsideCCAttribute) { 945 switch (Info.getCC()) { 946 case CC_C: 947 // The C calling convention is the default on the vast majority of platforms 948 // we support. If the user wrote it explicitly, it will usually be printed 949 // while traversing the AttributedType. If the type has been desugared, let 950 // the canonical spelling be the implicit calling convention. 951 // FIXME: It would be better to be explicit in certain contexts, such as a 952 // cdecl function typedef used to declare a member function with the 953 // Microsoft C++ ABI. 954 break; 955 case CC_X86StdCall: 956 OS << " __attribute__((stdcall))"; 957 break; 958 case CC_X86FastCall: 959 OS << " __attribute__((fastcall))"; 960 break; 961 case CC_X86ThisCall: 962 OS << " __attribute__((thiscall))"; 963 break; 964 case CC_X86VectorCall: 965 OS << " __attribute__((vectorcall))"; 966 break; 967 case CC_X86Pascal: 968 OS << " __attribute__((pascal))"; 969 break; 970 case CC_AAPCS: 971 OS << " __attribute__((pcs(\"aapcs\")))"; 972 break; 973 case CC_AAPCS_VFP: 974 OS << " __attribute__((pcs(\"aapcs-vfp\")))"; 975 break; 976 case CC_AArch64VectorCall: 977 OS << "__attribute__((aarch64_vector_pcs))"; 978 break; 979 case CC_AArch64SVEPCS: 980 OS << "__attribute__((aarch64_sve_pcs))"; 981 break; 982 case CC_AMDGPUKernelCall: 983 OS << "__attribute__((amdgpu_kernel))"; 984 break; 985 case CC_IntelOclBicc: 986 OS << " __attribute__((intel_ocl_bicc))"; 987 break; 988 case CC_Win64: 989 OS << " __attribute__((ms_abi))"; 990 break; 991 case CC_X86_64SysV: 992 OS << " __attribute__((sysv_abi))"; 993 break; 994 case CC_X86RegCall: 995 OS << " __attribute__((regcall))"; 996 break; 997 case CC_SpirFunction: 998 case CC_OpenCLKernel: 999 // Do nothing. These CCs are not available as attributes. 1000 break; 1001 case CC_Swift: 1002 OS << " __attribute__((swiftcall))"; 1003 break; 1004 case CC_SwiftAsync: 1005 OS << "__attribute__((swiftasynccall))"; 1006 break; 1007 case CC_PreserveMost: 1008 OS << " __attribute__((preserve_most))"; 1009 break; 1010 case CC_PreserveAll: 1011 OS << " __attribute__((preserve_all))"; 1012 break; 1013 } 1014 } 1015 1016 if (Info.getNoReturn()) 1017 OS << " __attribute__((noreturn))"; 1018 if (Info.getCmseNSCall()) 1019 OS << " __attribute__((cmse_nonsecure_call))"; 1020 if (Info.getProducesResult()) 1021 OS << " __attribute__((ns_returns_retained))"; 1022 if (Info.getRegParm()) 1023 OS << " __attribute__((regparm (" 1024 << Info.getRegParm() << ")))"; 1025 if (Info.getNoCallerSavedRegs()) 1026 OS << " __attribute__((no_caller_saved_registers))"; 1027 if (Info.getNoCfCheck()) 1028 OS << " __attribute__((nocf_check))"; 1029 } 1030 1031 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, 1032 raw_ostream &OS) { 1033 // If needed for precedence reasons, wrap the inner part in grouping parens. 1034 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); 1035 printBefore(T->getReturnType(), OS); 1036 if (!PrevPHIsEmpty.get()) 1037 OS << '('; 1038 } 1039 1040 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, 1041 raw_ostream &OS) { 1042 // If needed for precedence reasons, wrap the inner part in grouping parens. 1043 if (!HasEmptyPlaceHolder) 1044 OS << ')'; 1045 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 1046 1047 OS << "()"; 1048 printFunctionAfter(T->getExtInfo(), OS); 1049 printAfter(T->getReturnType(), OS); 1050 } 1051 1052 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) { 1053 1054 // Compute the full nested-name-specifier for this type. 1055 // In C, this will always be empty except when the type 1056 // being printed is anonymous within other Record. 1057 if (!Policy.SuppressScope) 1058 AppendScope(D->getDeclContext(), OS, D->getDeclName()); 1059 1060 IdentifierInfo *II = D->getIdentifier(); 1061 OS << II->getName(); 1062 spaceBeforePlaceHolder(OS); 1063 } 1064 1065 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T, 1066 raw_ostream &OS) { 1067 printTypeSpec(T->getDecl(), OS); 1068 } 1069 1070 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T, 1071 raw_ostream &OS) {} 1072 1073 void TypePrinter::printUsingBefore(const UsingType *T, raw_ostream &OS) { 1074 // After `namespace b { using a::X }`, is the type X within B a::X or b::X? 1075 // 1076 // - b::X is more formally correct given the UsingType model 1077 // - b::X makes sense if "re-exporting" a symbol in a new namespace 1078 // - a::X makes sense if "importing" a symbol for convenience 1079 // 1080 // The "importing" use seems much more common, so we print a::X. 1081 // This could be a policy option, but the right choice seems to rest more 1082 // with the intent of the code than the caller. 1083 printTypeSpec(T->getFoundDecl()->getUnderlyingDecl(), OS); 1084 } 1085 1086 void TypePrinter::printUsingAfter(const UsingType *T, raw_ostream &OS) {} 1087 1088 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { 1089 printTypeSpec(T->getDecl(), OS); 1090 } 1091 1092 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType *T, 1093 raw_ostream &OS) { 1094 StringRef MacroName = T->getMacroIdentifier()->getName(); 1095 OS << MacroName << " "; 1096 1097 // Since this type is meant to print the macro instead of the whole attribute, 1098 // we trim any attributes and go directly to the original modified type. 1099 printBefore(T->getModifiedType(), OS); 1100 } 1101 1102 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType *T, 1103 raw_ostream &OS) { 1104 printAfter(T->getModifiedType(), OS); 1105 } 1106 1107 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {} 1108 1109 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T, 1110 raw_ostream &OS) { 1111 OS << "typeof "; 1112 if (T->getUnderlyingExpr()) 1113 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); 1114 spaceBeforePlaceHolder(OS); 1115 } 1116 1117 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T, 1118 raw_ostream &OS) {} 1119 1120 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { 1121 OS << "typeof("; 1122 print(T->getUnderlyingType(), OS, StringRef()); 1123 OS << ')'; 1124 spaceBeforePlaceHolder(OS); 1125 } 1126 1127 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {} 1128 1129 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { 1130 OS << "decltype("; 1131 if (T->getUnderlyingExpr()) 1132 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); 1133 OS << ')'; 1134 spaceBeforePlaceHolder(OS); 1135 } 1136 1137 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {} 1138 1139 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T, 1140 raw_ostream &OS) { 1141 IncludeStrongLifetimeRAII Strong(Policy); 1142 1143 switch (T->getUTTKind()) { 1144 case UnaryTransformType::EnumUnderlyingType: 1145 OS << "__underlying_type("; 1146 print(T->getBaseType(), OS, StringRef()); 1147 OS << ')'; 1148 spaceBeforePlaceHolder(OS); 1149 return; 1150 } 1151 1152 printBefore(T->getBaseType(), OS); 1153 } 1154 1155 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T, 1156 raw_ostream &OS) { 1157 IncludeStrongLifetimeRAII Strong(Policy); 1158 1159 switch (T->getUTTKind()) { 1160 case UnaryTransformType::EnumUnderlyingType: 1161 return; 1162 } 1163 1164 printAfter(T->getBaseType(), OS); 1165 } 1166 1167 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { 1168 // If the type has been deduced, do not print 'auto'. 1169 if (!T->getDeducedType().isNull()) { 1170 printBefore(T->getDeducedType(), OS); 1171 } else { 1172 if (T->isConstrained()) { 1173 // FIXME: Track a TypeConstraint as type sugar, so that we can print the 1174 // type as it was written. 1175 T->getTypeConstraintConcept()->getDeclName().print(OS, Policy); 1176 auto Args = T->getTypeConstraintArguments(); 1177 if (!Args.empty()) 1178 printTemplateArgumentList( 1179 OS, Args, Policy, 1180 T->getTypeConstraintConcept()->getTemplateParameters()); 1181 OS << ' '; 1182 } 1183 switch (T->getKeyword()) { 1184 case AutoTypeKeyword::Auto: OS << "auto"; break; 1185 case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break; 1186 case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break; 1187 } 1188 spaceBeforePlaceHolder(OS); 1189 } 1190 } 1191 1192 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { 1193 // If the type has been deduced, do not print 'auto'. 1194 if (!T->getDeducedType().isNull()) 1195 printAfter(T->getDeducedType(), OS); 1196 } 1197 1198 void TypePrinter::printDeducedTemplateSpecializationBefore( 1199 const DeducedTemplateSpecializationType *T, raw_ostream &OS) { 1200 // If the type has been deduced, print the deduced type. 1201 if (!T->getDeducedType().isNull()) { 1202 printBefore(T->getDeducedType(), OS); 1203 } else { 1204 IncludeStrongLifetimeRAII Strong(Policy); 1205 T->getTemplateName().print(OS, Policy); 1206 spaceBeforePlaceHolder(OS); 1207 } 1208 } 1209 1210 void TypePrinter::printDeducedTemplateSpecializationAfter( 1211 const DeducedTemplateSpecializationType *T, raw_ostream &OS) { 1212 // If the type has been deduced, print the deduced type. 1213 if (!T->getDeducedType().isNull()) 1214 printAfter(T->getDeducedType(), OS); 1215 } 1216 1217 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) { 1218 IncludeStrongLifetimeRAII Strong(Policy); 1219 1220 OS << "_Atomic("; 1221 print(T->getValueType(), OS, StringRef()); 1222 OS << ')'; 1223 spaceBeforePlaceHolder(OS); 1224 } 1225 1226 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {} 1227 1228 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) { 1229 IncludeStrongLifetimeRAII Strong(Policy); 1230 1231 if (T->isReadOnly()) 1232 OS << "read_only "; 1233 else 1234 OS << "write_only "; 1235 OS << "pipe "; 1236 print(T->getElementType(), OS, StringRef()); 1237 spaceBeforePlaceHolder(OS); 1238 } 1239 1240 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {} 1241 1242 void TypePrinter::printBitIntBefore(const BitIntType *T, raw_ostream &OS) { 1243 if (T->isUnsigned()) 1244 OS << "unsigned "; 1245 OS << "_BitInt(" << T->getNumBits() << ")"; 1246 spaceBeforePlaceHolder(OS); 1247 } 1248 1249 void TypePrinter::printBitIntAfter(const BitIntType *T, raw_ostream &OS) {} 1250 1251 void TypePrinter::printDependentBitIntBefore(const DependentBitIntType *T, 1252 raw_ostream &OS) { 1253 if (T->isUnsigned()) 1254 OS << "unsigned "; 1255 OS << "_BitInt("; 1256 T->getNumBitsExpr()->printPretty(OS, nullptr, Policy); 1257 OS << ")"; 1258 spaceBeforePlaceHolder(OS); 1259 } 1260 1261 void TypePrinter::printDependentBitIntAfter(const DependentBitIntType *T, 1262 raw_ostream &OS) {} 1263 1264 /// Appends the given scope to the end of a string. 1265 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS, 1266 DeclarationName NameInScope) { 1267 if (DC->isTranslationUnit()) 1268 return; 1269 1270 // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier, 1271 // which can also print names for function and method scopes. 1272 if (DC->isFunctionOrMethod()) 1273 return; 1274 1275 if (Policy.Callbacks && Policy.Callbacks->isScopeVisible(DC)) 1276 return; 1277 1278 if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) { 1279 if (Policy.SuppressUnwrittenScope && NS->isAnonymousNamespace()) 1280 return AppendScope(DC->getParent(), OS, NameInScope); 1281 1282 // Only suppress an inline namespace if the name has the same lookup 1283 // results in the enclosing namespace. 1284 if (Policy.SuppressInlineNamespace && NS->isInline() && NameInScope && 1285 NS->isRedundantInlineQualifierFor(NameInScope)) 1286 return AppendScope(DC->getParent(), OS, NameInScope); 1287 1288 AppendScope(DC->getParent(), OS, NS->getDeclName()); 1289 if (NS->getIdentifier()) 1290 OS << NS->getName() << "::"; 1291 else 1292 OS << "(anonymous namespace)::"; 1293 } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 1294 AppendScope(DC->getParent(), OS, Spec->getDeclName()); 1295 IncludeStrongLifetimeRAII Strong(Policy); 1296 OS << Spec->getIdentifier()->getName(); 1297 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1298 printTemplateArgumentList( 1299 OS, TemplateArgs.asArray(), Policy, 1300 Spec->getSpecializedTemplate()->getTemplateParameters()); 1301 OS << "::"; 1302 } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) { 1303 AppendScope(DC->getParent(), OS, Tag->getDeclName()); 1304 if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl()) 1305 OS << Typedef->getIdentifier()->getName() << "::"; 1306 else if (Tag->getIdentifier()) 1307 OS << Tag->getIdentifier()->getName() << "::"; 1308 else 1309 return; 1310 } else { 1311 AppendScope(DC->getParent(), OS, NameInScope); 1312 } 1313 } 1314 1315 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { 1316 if (Policy.IncludeTagDefinition) { 1317 PrintingPolicy SubPolicy = Policy; 1318 SubPolicy.IncludeTagDefinition = false; 1319 D->print(OS, SubPolicy, Indentation); 1320 spaceBeforePlaceHolder(OS); 1321 return; 1322 } 1323 1324 bool HasKindDecoration = false; 1325 1326 // We don't print tags unless this is an elaborated type. 1327 // In C, we just assume every RecordType is an elaborated type. 1328 if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) { 1329 HasKindDecoration = true; 1330 OS << D->getKindName(); 1331 OS << ' '; 1332 } 1333 1334 // Compute the full nested-name-specifier for this type. 1335 // In C, this will always be empty except when the type 1336 // being printed is anonymous within other Record. 1337 if (!Policy.SuppressScope) 1338 AppendScope(D->getDeclContext(), OS, D->getDeclName()); 1339 1340 if (const IdentifierInfo *II = D->getIdentifier()) 1341 OS << II->getName(); 1342 else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) { 1343 assert(Typedef->getIdentifier() && "Typedef without identifier?"); 1344 OS << Typedef->getIdentifier()->getName(); 1345 } else { 1346 // Make an unambiguous representation for anonymous types, e.g. 1347 // (anonymous enum at /usr/include/string.h:120:9) 1348 OS << (Policy.MSVCFormatting ? '`' : '('); 1349 1350 if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) { 1351 OS << "lambda"; 1352 HasKindDecoration = true; 1353 } else if ((isa<RecordDecl>(D) && cast<RecordDecl>(D)->isAnonymousStructOrUnion())) { 1354 OS << "anonymous"; 1355 } else { 1356 OS << "unnamed"; 1357 } 1358 1359 if (Policy.AnonymousTagLocations) { 1360 // Suppress the redundant tag keyword if we just printed one. 1361 // We don't have to worry about ElaboratedTypes here because you can't 1362 // refer to an anonymous type with one. 1363 if (!HasKindDecoration) 1364 OS << " " << D->getKindName(); 1365 1366 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc( 1367 D->getLocation()); 1368 if (PLoc.isValid()) { 1369 OS << " at "; 1370 StringRef File = PLoc.getFilename(); 1371 if (auto *Callbacks = Policy.Callbacks) 1372 OS << Callbacks->remapPath(File); 1373 else 1374 OS << File; 1375 OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn(); 1376 } 1377 } 1378 1379 OS << (Policy.MSVCFormatting ? '\'' : ')'); 1380 } 1381 1382 // If this is a class template specialization, print the template 1383 // arguments. 1384 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 1385 ArrayRef<TemplateArgument> Args; 1386 TypeSourceInfo *TAW = Spec->getTypeAsWritten(); 1387 if (!Policy.PrintCanonicalTypes && TAW) { 1388 const TemplateSpecializationType *TST = 1389 cast<TemplateSpecializationType>(TAW->getType()); 1390 Args = TST->template_arguments(); 1391 } else { 1392 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1393 Args = TemplateArgs.asArray(); 1394 } 1395 IncludeStrongLifetimeRAII Strong(Policy); 1396 printTemplateArgumentList( 1397 OS, Args, Policy, 1398 Spec->getSpecializedTemplate()->getTemplateParameters()); 1399 } 1400 1401 spaceBeforePlaceHolder(OS); 1402 } 1403 1404 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) { 1405 // Print the preferred name if we have one for this type. 1406 if (Policy.UsePreferredNames) { 1407 for (const auto *PNA : T->getDecl()->specific_attrs<PreferredNameAttr>()) { 1408 if (!declaresSameEntity(PNA->getTypedefType()->getAsCXXRecordDecl(), 1409 T->getDecl())) 1410 continue; 1411 // Find the outermost typedef or alias template. 1412 QualType T = PNA->getTypedefType(); 1413 while (true) { 1414 if (auto *TT = dyn_cast<TypedefType>(T)) 1415 return printTypeSpec(TT->getDecl(), OS); 1416 if (auto *TST = dyn_cast<TemplateSpecializationType>(T)) 1417 return printTemplateId(TST, OS, /*FullyQualify=*/true); 1418 T = T->getLocallyUnqualifiedSingleStepDesugaredType(); 1419 } 1420 } 1421 } 1422 1423 printTag(T->getDecl(), OS); 1424 } 1425 1426 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {} 1427 1428 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { 1429 printTag(T->getDecl(), OS); 1430 } 1431 1432 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {} 1433 1434 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, 1435 raw_ostream &OS) { 1436 TemplateTypeParmDecl *D = T->getDecl(); 1437 if (D && D->isImplicit()) { 1438 if (auto *TC = D->getTypeConstraint()) { 1439 TC->print(OS, Policy); 1440 OS << ' '; 1441 } 1442 OS << "auto"; 1443 } else if (IdentifierInfo *Id = T->getIdentifier()) 1444 OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName() 1445 : Id->getName()); 1446 else 1447 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex(); 1448 1449 spaceBeforePlaceHolder(OS); 1450 } 1451 1452 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, 1453 raw_ostream &OS) {} 1454 1455 void TypePrinter::printSubstTemplateTypeParmBefore( 1456 const SubstTemplateTypeParmType *T, 1457 raw_ostream &OS) { 1458 IncludeStrongLifetimeRAII Strong(Policy); 1459 printBefore(T->getReplacementType(), OS); 1460 } 1461 1462 void TypePrinter::printSubstTemplateTypeParmAfter( 1463 const SubstTemplateTypeParmType *T, 1464 raw_ostream &OS) { 1465 IncludeStrongLifetimeRAII Strong(Policy); 1466 printAfter(T->getReplacementType(), OS); 1467 } 1468 1469 void TypePrinter::printSubstTemplateTypeParmPackBefore( 1470 const SubstTemplateTypeParmPackType *T, 1471 raw_ostream &OS) { 1472 IncludeStrongLifetimeRAII Strong(Policy); 1473 printTemplateTypeParmBefore(T->getReplacedParameter(), OS); 1474 } 1475 1476 void TypePrinter::printSubstTemplateTypeParmPackAfter( 1477 const SubstTemplateTypeParmPackType *T, 1478 raw_ostream &OS) { 1479 IncludeStrongLifetimeRAII Strong(Policy); 1480 printTemplateTypeParmAfter(T->getReplacedParameter(), OS); 1481 } 1482 1483 void TypePrinter::printTemplateId(const TemplateSpecializationType *T, 1484 raw_ostream &OS, bool FullyQualify) { 1485 IncludeStrongLifetimeRAII Strong(Policy); 1486 1487 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl(); 1488 // FIXME: Null TD never excercised in test suite. 1489 if (FullyQualify && TD) { 1490 if (!Policy.SuppressScope) 1491 AppendScope(TD->getDeclContext(), OS, TD->getDeclName()); 1492 1493 OS << TD->getName(); 1494 } else { 1495 T->getTemplateName().print(OS, Policy); 1496 } 1497 1498 DefaultTemplateArgsPolicyRAII TemplateArgs(Policy); 1499 const TemplateParameterList *TPL = TD ? TD->getTemplateParameters() : nullptr; 1500 printTemplateArgumentList(OS, T->template_arguments(), Policy, TPL); 1501 spaceBeforePlaceHolder(OS); 1502 } 1503 1504 void TypePrinter::printTemplateSpecializationBefore( 1505 const TemplateSpecializationType *T, 1506 raw_ostream &OS) { 1507 printTemplateId(T, OS, Policy.FullyQualifiedName); 1508 } 1509 1510 void TypePrinter::printTemplateSpecializationAfter( 1511 const TemplateSpecializationType *T, 1512 raw_ostream &OS) {} 1513 1514 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T, 1515 raw_ostream &OS) { 1516 if (Policy.PrintInjectedClassNameWithArguments) 1517 return printTemplateSpecializationBefore(T->getInjectedTST(), OS); 1518 1519 IncludeStrongLifetimeRAII Strong(Policy); 1520 T->getTemplateName().print(OS, Policy); 1521 spaceBeforePlaceHolder(OS); 1522 } 1523 1524 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T, 1525 raw_ostream &OS) {} 1526 1527 void TypePrinter::printElaboratedBefore(const ElaboratedType *T, 1528 raw_ostream &OS) { 1529 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) { 1530 TagDecl *OwnedTagDecl = T->getOwnedTagDecl(); 1531 assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() && 1532 "OwnedTagDecl expected to be a declaration for the type"); 1533 PrintingPolicy SubPolicy = Policy; 1534 SubPolicy.IncludeTagDefinition = false; 1535 OwnedTagDecl->print(OS, SubPolicy, Indentation); 1536 spaceBeforePlaceHolder(OS); 1537 return; 1538 } 1539 1540 // The tag definition will take care of these. 1541 if (!Policy.IncludeTagDefinition) 1542 { 1543 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1544 if (T->getKeyword() != ETK_None) 1545 OS << " "; 1546 NestedNameSpecifier *Qualifier = T->getQualifier(); 1547 if (Qualifier) 1548 Qualifier->print(OS, Policy); 1549 } 1550 1551 ElaboratedTypePolicyRAII PolicyRAII(Policy); 1552 printBefore(T->getNamedType(), OS); 1553 } 1554 1555 void TypePrinter::printElaboratedAfter(const ElaboratedType *T, 1556 raw_ostream &OS) { 1557 if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) 1558 return; 1559 ElaboratedTypePolicyRAII PolicyRAII(Policy); 1560 printAfter(T->getNamedType(), OS); 1561 } 1562 1563 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) { 1564 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) { 1565 printBefore(T->getInnerType(), OS); 1566 OS << '('; 1567 } else 1568 printBefore(T->getInnerType(), OS); 1569 } 1570 1571 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) { 1572 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) { 1573 OS << ')'; 1574 printAfter(T->getInnerType(), OS); 1575 } else 1576 printAfter(T->getInnerType(), OS); 1577 } 1578 1579 void TypePrinter::printDependentNameBefore(const DependentNameType *T, 1580 raw_ostream &OS) { 1581 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1582 if (T->getKeyword() != ETK_None) 1583 OS << " "; 1584 1585 T->getQualifier()->print(OS, Policy); 1586 1587 OS << T->getIdentifier()->getName(); 1588 spaceBeforePlaceHolder(OS); 1589 } 1590 1591 void TypePrinter::printDependentNameAfter(const DependentNameType *T, 1592 raw_ostream &OS) {} 1593 1594 void TypePrinter::printDependentTemplateSpecializationBefore( 1595 const DependentTemplateSpecializationType *T, raw_ostream &OS) { 1596 IncludeStrongLifetimeRAII Strong(Policy); 1597 1598 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1599 if (T->getKeyword() != ETK_None) 1600 OS << " "; 1601 1602 if (T->getQualifier()) 1603 T->getQualifier()->print(OS, Policy); 1604 OS << "template " << T->getIdentifier()->getName(); 1605 printTemplateArgumentList(OS, T->template_arguments(), Policy); 1606 spaceBeforePlaceHolder(OS); 1607 } 1608 1609 void TypePrinter::printDependentTemplateSpecializationAfter( 1610 const DependentTemplateSpecializationType *T, raw_ostream &OS) {} 1611 1612 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, 1613 raw_ostream &OS) { 1614 printBefore(T->getPattern(), OS); 1615 } 1616 1617 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, 1618 raw_ostream &OS) { 1619 printAfter(T->getPattern(), OS); 1620 OS << "..."; 1621 } 1622 1623 void TypePrinter::printAttributedBefore(const AttributedType *T, 1624 raw_ostream &OS) { 1625 // FIXME: Generate this with TableGen. 1626 1627 // Prefer the macro forms of the GC and ownership qualifiers. 1628 if (T->getAttrKind() == attr::ObjCGC || 1629 T->getAttrKind() == attr::ObjCOwnership) 1630 return printBefore(T->getEquivalentType(), OS); 1631 1632 if (T->getAttrKind() == attr::ObjCKindOf) 1633 OS << "__kindof "; 1634 1635 if (T->getAttrKind() == attr::AddressSpace) 1636 printBefore(T->getEquivalentType(), OS); 1637 else 1638 printBefore(T->getModifiedType(), OS); 1639 1640 if (T->isMSTypeSpec()) { 1641 switch (T->getAttrKind()) { 1642 default: return; 1643 case attr::Ptr32: OS << " __ptr32"; break; 1644 case attr::Ptr64: OS << " __ptr64"; break; 1645 case attr::SPtr: OS << " __sptr"; break; 1646 case attr::UPtr: OS << " __uptr"; break; 1647 } 1648 spaceBeforePlaceHolder(OS); 1649 } 1650 1651 // Print nullability type specifiers. 1652 if (T->getImmediateNullability()) { 1653 if (T->getAttrKind() == attr::TypeNonNull) 1654 OS << " _Nonnull"; 1655 else if (T->getAttrKind() == attr::TypeNullable) 1656 OS << " _Nullable"; 1657 else if (T->getAttrKind() == attr::TypeNullUnspecified) 1658 OS << " _Null_unspecified"; 1659 else if (T->getAttrKind() == attr::TypeNullableResult) 1660 OS << " _Nullable_result"; 1661 else 1662 llvm_unreachable("unhandled nullability"); 1663 spaceBeforePlaceHolder(OS); 1664 } 1665 } 1666 1667 void TypePrinter::printAttributedAfter(const AttributedType *T, 1668 raw_ostream &OS) { 1669 // FIXME: Generate this with TableGen. 1670 1671 // Prefer the macro forms of the GC and ownership qualifiers. 1672 if (T->getAttrKind() == attr::ObjCGC || 1673 T->getAttrKind() == attr::ObjCOwnership) 1674 return printAfter(T->getEquivalentType(), OS); 1675 1676 // If this is a calling convention attribute, don't print the implicit CC from 1677 // the modified type. 1678 SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv()); 1679 1680 printAfter(T->getModifiedType(), OS); 1681 1682 // Some attributes are printed as qualifiers before the type, so we have 1683 // nothing left to do. 1684 if (T->getAttrKind() == attr::ObjCKindOf || 1685 T->isMSTypeSpec() || T->getImmediateNullability()) 1686 return; 1687 1688 // Don't print the inert __unsafe_unretained attribute at all. 1689 if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained) 1690 return; 1691 1692 // Don't print ns_returns_retained unless it had an effect. 1693 if (T->getAttrKind() == attr::NSReturnsRetained && 1694 !T->getEquivalentType()->castAs<FunctionType>() 1695 ->getExtInfo().getProducesResult()) 1696 return; 1697 1698 if (T->getAttrKind() == attr::LifetimeBound) { 1699 OS << " [[clang::lifetimebound]]"; 1700 return; 1701 } 1702 1703 // The printing of the address_space attribute is handled by the qualifier 1704 // since it is still stored in the qualifier. Return early to prevent printing 1705 // this twice. 1706 if (T->getAttrKind() == attr::AddressSpace) 1707 return; 1708 1709 if (T->getAttrKind() == attr::AnnotateType) { 1710 // FIXME: Print the attribute arguments once we have a way to retrieve these 1711 // here. For the meantime, we just print `[[clang::annotate_type(...)]]` 1712 // without the arguments so that we know at least that we had _some_ 1713 // annotation on the type. 1714 OS << " [[clang::annotate_type(...)]]"; 1715 return; 1716 } 1717 1718 OS << " __attribute__(("; 1719 switch (T->getAttrKind()) { 1720 #define TYPE_ATTR(NAME) 1721 #define DECL_OR_TYPE_ATTR(NAME) 1722 #define ATTR(NAME) case attr::NAME: 1723 #include "clang/Basic/AttrList.inc" 1724 llvm_unreachable("non-type attribute attached to type"); 1725 1726 case attr::BTFTypeTag: 1727 llvm_unreachable("BTFTypeTag attribute handled separately"); 1728 1729 case attr::OpenCLPrivateAddressSpace: 1730 case attr::OpenCLGlobalAddressSpace: 1731 case attr::OpenCLGlobalDeviceAddressSpace: 1732 case attr::OpenCLGlobalHostAddressSpace: 1733 case attr::OpenCLLocalAddressSpace: 1734 case attr::OpenCLConstantAddressSpace: 1735 case attr::OpenCLGenericAddressSpace: 1736 // FIXME: Update printAttributedBefore to print these once we generate 1737 // AttributedType nodes for them. 1738 break; 1739 1740 case attr::LifetimeBound: 1741 case attr::TypeNonNull: 1742 case attr::TypeNullable: 1743 case attr::TypeNullableResult: 1744 case attr::TypeNullUnspecified: 1745 case attr::ObjCGC: 1746 case attr::ObjCInertUnsafeUnretained: 1747 case attr::ObjCKindOf: 1748 case attr::ObjCOwnership: 1749 case attr::Ptr32: 1750 case attr::Ptr64: 1751 case attr::SPtr: 1752 case attr::UPtr: 1753 case attr::AddressSpace: 1754 case attr::CmseNSCall: 1755 case attr::AnnotateType: 1756 llvm_unreachable("This attribute should have been handled already"); 1757 1758 case attr::NSReturnsRetained: 1759 OS << "ns_returns_retained"; 1760 break; 1761 1762 // FIXME: When Sema learns to form this AttributedType, avoid printing the 1763 // attribute again in printFunctionProtoAfter. 1764 case attr::AnyX86NoCfCheck: OS << "nocf_check"; break; 1765 case attr::CDecl: OS << "cdecl"; break; 1766 case attr::FastCall: OS << "fastcall"; break; 1767 case attr::StdCall: OS << "stdcall"; break; 1768 case attr::ThisCall: OS << "thiscall"; break; 1769 case attr::SwiftCall: OS << "swiftcall"; break; 1770 case attr::SwiftAsyncCall: OS << "swiftasynccall"; break; 1771 case attr::VectorCall: OS << "vectorcall"; break; 1772 case attr::Pascal: OS << "pascal"; break; 1773 case attr::MSABI: OS << "ms_abi"; break; 1774 case attr::SysVABI: OS << "sysv_abi"; break; 1775 case attr::RegCall: OS << "regcall"; break; 1776 case attr::Pcs: { 1777 OS << "pcs("; 1778 QualType t = T->getEquivalentType(); 1779 while (!t->isFunctionType()) 1780 t = t->getPointeeType(); 1781 OS << (t->castAs<FunctionType>()->getCallConv() == CC_AAPCS ? 1782 "\"aapcs\"" : "\"aapcs-vfp\""); 1783 OS << ')'; 1784 break; 1785 } 1786 case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break; 1787 case attr::AArch64SVEPcs: OS << "aarch64_sve_pcs"; break; 1788 case attr::AMDGPUKernelCall: OS << "amdgpu_kernel"; break; 1789 case attr::IntelOclBicc: OS << "inteloclbicc"; break; 1790 case attr::PreserveMost: 1791 OS << "preserve_most"; 1792 break; 1793 1794 case attr::PreserveAll: 1795 OS << "preserve_all"; 1796 break; 1797 case attr::NoDeref: 1798 OS << "noderef"; 1799 break; 1800 case attr::AcquireHandle: 1801 OS << "acquire_handle"; 1802 break; 1803 case attr::ArmMveStrictPolymorphism: 1804 OS << "__clang_arm_mve_strict_polymorphism"; 1805 break; 1806 } 1807 OS << "))"; 1808 } 1809 1810 void TypePrinter::printBTFTagAttributedBefore(const BTFTagAttributedType *T, 1811 raw_ostream &OS) { 1812 printBefore(T->getWrappedType(), OS); 1813 OS << " btf_type_tag(" << T->getAttr()->getBTFTypeTag() << ")"; 1814 } 1815 1816 void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType *T, 1817 raw_ostream &OS) { 1818 printAfter(T->getWrappedType(), OS); 1819 } 1820 1821 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, 1822 raw_ostream &OS) { 1823 OS << T->getDecl()->getName(); 1824 spaceBeforePlaceHolder(OS); 1825 } 1826 1827 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, 1828 raw_ostream &OS) {} 1829 1830 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T, 1831 raw_ostream &OS) { 1832 OS << T->getDecl()->getName(); 1833 if (!T->qual_empty()) { 1834 bool isFirst = true; 1835 OS << '<'; 1836 for (const auto *I : T->quals()) { 1837 if (isFirst) 1838 isFirst = false; 1839 else 1840 OS << ','; 1841 OS << I->getName(); 1842 } 1843 OS << '>'; 1844 } 1845 1846 spaceBeforePlaceHolder(OS); 1847 } 1848 1849 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T, 1850 raw_ostream &OS) {} 1851 1852 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T, 1853 raw_ostream &OS) { 1854 if (T->qual_empty() && T->isUnspecializedAsWritten() && 1855 !T->isKindOfTypeAsWritten()) 1856 return printBefore(T->getBaseType(), OS); 1857 1858 if (T->isKindOfTypeAsWritten()) 1859 OS << "__kindof "; 1860 1861 print(T->getBaseType(), OS, StringRef()); 1862 1863 if (T->isSpecializedAsWritten()) { 1864 bool isFirst = true; 1865 OS << '<'; 1866 for (auto typeArg : T->getTypeArgsAsWritten()) { 1867 if (isFirst) 1868 isFirst = false; 1869 else 1870 OS << ","; 1871 1872 print(typeArg, OS, StringRef()); 1873 } 1874 OS << '>'; 1875 } 1876 1877 if (!T->qual_empty()) { 1878 bool isFirst = true; 1879 OS << '<'; 1880 for (const auto *I : T->quals()) { 1881 if (isFirst) 1882 isFirst = false; 1883 else 1884 OS << ','; 1885 OS << I->getName(); 1886 } 1887 OS << '>'; 1888 } 1889 1890 spaceBeforePlaceHolder(OS); 1891 } 1892 1893 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T, 1894 raw_ostream &OS) { 1895 if (T->qual_empty() && T->isUnspecializedAsWritten() && 1896 !T->isKindOfTypeAsWritten()) 1897 return printAfter(T->getBaseType(), OS); 1898 } 1899 1900 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, 1901 raw_ostream &OS) { 1902 printBefore(T->getPointeeType(), OS); 1903 1904 // If we need to print the pointer, print it now. 1905 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() && 1906 !T->isObjCClassType() && !T->isObjCQualifiedClassType()) { 1907 if (HasEmptyPlaceHolder) 1908 OS << ' '; 1909 OS << '*'; 1910 } 1911 } 1912 1913 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, 1914 raw_ostream &OS) {} 1915 1916 static 1917 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; } 1918 1919 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) { 1920 return A.getArgument(); 1921 } 1922 1923 static void printArgument(const TemplateArgument &A, const PrintingPolicy &PP, 1924 llvm::raw_ostream &OS, bool IncludeType) { 1925 A.print(PP, OS, IncludeType); 1926 } 1927 1928 static void printArgument(const TemplateArgumentLoc &A, 1929 const PrintingPolicy &PP, llvm::raw_ostream &OS, 1930 bool IncludeType) { 1931 const TemplateArgument::ArgKind &Kind = A.getArgument().getKind(); 1932 if (Kind == TemplateArgument::ArgKind::Type) 1933 return A.getTypeSourceInfo()->getType().print(OS, PP); 1934 return A.getArgument().print(PP, OS, IncludeType); 1935 } 1936 1937 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg, 1938 TemplateArgument Pattern, 1939 ArrayRef<TemplateArgument> Args, 1940 unsigned Depth); 1941 1942 static bool isSubstitutedType(ASTContext &Ctx, QualType T, QualType Pattern, 1943 ArrayRef<TemplateArgument> Args, unsigned Depth) { 1944 if (Ctx.hasSameType(T, Pattern)) 1945 return true; 1946 1947 // A type parameter matches its argument. 1948 if (auto *TTPT = Pattern->getAs<TemplateTypeParmType>()) { 1949 if (TTPT->getDepth() == Depth && TTPT->getIndex() < Args.size() && 1950 Args[TTPT->getIndex()].getKind() == TemplateArgument::Type) { 1951 QualType SubstArg = Ctx.getQualifiedType( 1952 Args[TTPT->getIndex()].getAsType(), Pattern.getQualifiers()); 1953 return Ctx.hasSameType(SubstArg, T); 1954 } 1955 return false; 1956 } 1957 1958 // FIXME: Recurse into array types. 1959 1960 // All other cases will need the types to be identically qualified. 1961 Qualifiers TQual, PatQual; 1962 T = Ctx.getUnqualifiedArrayType(T, TQual); 1963 Pattern = Ctx.getUnqualifiedArrayType(Pattern, PatQual); 1964 if (TQual != PatQual) 1965 return false; 1966 1967 // Recurse into pointer-like types. 1968 { 1969 QualType TPointee = T->getPointeeType(); 1970 QualType PPointee = Pattern->getPointeeType(); 1971 if (!TPointee.isNull() && !PPointee.isNull()) 1972 return T->getTypeClass() == Pattern->getTypeClass() && 1973 isSubstitutedType(Ctx, TPointee, PPointee, Args, Depth); 1974 } 1975 1976 // Recurse into template specialization types. 1977 if (auto *PTST = 1978 Pattern.getCanonicalType()->getAs<TemplateSpecializationType>()) { 1979 TemplateName Template; 1980 ArrayRef<TemplateArgument> TemplateArgs; 1981 if (auto *TTST = T->getAs<TemplateSpecializationType>()) { 1982 Template = TTST->getTemplateName(); 1983 TemplateArgs = TTST->template_arguments(); 1984 } else if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1985 T->getAsCXXRecordDecl())) { 1986 Template = TemplateName(CTSD->getSpecializedTemplate()); 1987 TemplateArgs = CTSD->getTemplateArgs().asArray(); 1988 } else { 1989 return false; 1990 } 1991 1992 if (!isSubstitutedTemplateArgument(Ctx, Template, PTST->getTemplateName(), 1993 Args, Depth)) 1994 return false; 1995 if (TemplateArgs.size() != PTST->getNumArgs()) 1996 return false; 1997 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 1998 if (!isSubstitutedTemplateArgument(Ctx, TemplateArgs[I], PTST->getArg(I), 1999 Args, Depth)) 2000 return false; 2001 return true; 2002 } 2003 2004 // FIXME: Handle more cases. 2005 return false; 2006 } 2007 2008 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg, 2009 TemplateArgument Pattern, 2010 ArrayRef<TemplateArgument> Args, 2011 unsigned Depth) { 2012 Arg = Ctx.getCanonicalTemplateArgument(Arg); 2013 Pattern = Ctx.getCanonicalTemplateArgument(Pattern); 2014 if (Arg.structurallyEquals(Pattern)) 2015 return true; 2016 2017 if (Pattern.getKind() == TemplateArgument::Expression) { 2018 if (auto *DRE = 2019 dyn_cast<DeclRefExpr>(Pattern.getAsExpr()->IgnoreParenImpCasts())) { 2020 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) 2021 return NTTP->getDepth() == Depth && Args.size() > NTTP->getIndex() && 2022 Args[NTTP->getIndex()].structurallyEquals(Arg); 2023 } 2024 } 2025 2026 if (Arg.getKind() != Pattern.getKind()) 2027 return false; 2028 2029 if (Arg.getKind() == TemplateArgument::Type) 2030 return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args, 2031 Depth); 2032 2033 if (Arg.getKind() == TemplateArgument::Template) { 2034 TemplateDecl *PatTD = Pattern.getAsTemplate().getAsTemplateDecl(); 2035 if (auto *TTPD = dyn_cast_or_null<TemplateTemplateParmDecl>(PatTD)) 2036 return TTPD->getDepth() == Depth && Args.size() > TTPD->getIndex() && 2037 Ctx.getCanonicalTemplateArgument(Args[TTPD->getIndex()]) 2038 .structurallyEquals(Arg); 2039 } 2040 2041 // FIXME: Handle more cases. 2042 return false; 2043 } 2044 2045 /// Make a best-effort determination of whether the type T can be produced by 2046 /// substituting Args into the default argument of Param. 2047 static bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, 2048 const NamedDecl *Param, 2049 ArrayRef<TemplateArgument> Args, 2050 unsigned Depth) { 2051 // An empty pack is equivalent to not providing a pack argument. 2052 if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0) 2053 return true; 2054 2055 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param)) { 2056 return TTPD->hasDefaultArgument() && 2057 isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(), 2058 Args, Depth); 2059 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) { 2060 return TTPD->hasDefaultArgument() && 2061 isSubstitutedTemplateArgument( 2062 Ctx, Arg, TTPD->getDefaultArgument().getArgument(), Args, Depth); 2063 } else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2064 return NTTPD->hasDefaultArgument() && 2065 isSubstitutedTemplateArgument(Ctx, Arg, NTTPD->getDefaultArgument(), 2066 Args, Depth); 2067 } 2068 return false; 2069 } 2070 2071 template <typename TA> 2072 static void 2073 printTo(raw_ostream &OS, ArrayRef<TA> Args, const PrintingPolicy &Policy, 2074 const TemplateParameterList *TPL, bool IsPack, unsigned ParmIndex) { 2075 // Drop trailing template arguments that match default arguments. 2076 if (TPL && Policy.SuppressDefaultTemplateArgs && 2077 !Policy.PrintCanonicalTypes && !Args.empty() && !IsPack && 2078 Args.size() <= TPL->size()) { 2079 ASTContext &Ctx = TPL->getParam(0)->getASTContext(); 2080 llvm::SmallVector<TemplateArgument, 8> OrigArgs; 2081 for (const TA &A : Args) 2082 OrigArgs.push_back(getArgument(A)); 2083 while (!Args.empty() && 2084 isSubstitutedDefaultArgument(Ctx, getArgument(Args.back()), 2085 TPL->getParam(Args.size() - 1), 2086 OrigArgs, TPL->getDepth())) 2087 Args = Args.drop_back(); 2088 } 2089 2090 const char *Comma = Policy.MSVCFormatting ? "," : ", "; 2091 if (!IsPack) 2092 OS << '<'; 2093 2094 bool NeedSpace = false; 2095 bool FirstArg = true; 2096 for (const auto &Arg : Args) { 2097 // Print the argument into a string. 2098 SmallString<128> Buf; 2099 llvm::raw_svector_ostream ArgOS(Buf); 2100 const TemplateArgument &Argument = getArgument(Arg); 2101 if (Argument.getKind() == TemplateArgument::Pack) { 2102 if (Argument.pack_size() && !FirstArg) 2103 OS << Comma; 2104 printTo(ArgOS, Argument.getPackAsArray(), Policy, TPL, 2105 /*IsPack*/ true, ParmIndex); 2106 } else { 2107 if (!FirstArg) 2108 OS << Comma; 2109 // Tries to print the argument with location info if exists. 2110 printArgument(Arg, Policy, ArgOS, 2111 TemplateParameterList::shouldIncludeTypeForArgument( 2112 Policy, TPL, ParmIndex)); 2113 } 2114 StringRef ArgString = ArgOS.str(); 2115 2116 // If this is the first argument and its string representation 2117 // begins with the global scope specifier ('::foo'), add a space 2118 // to avoid printing the diagraph '<:'. 2119 if (FirstArg && !ArgString.empty() && ArgString[0] == ':') 2120 OS << ' '; 2121 2122 OS << ArgString; 2123 2124 // If the last character of our string is '>', add another space to 2125 // keep the two '>''s separate tokens. 2126 if (!ArgString.empty()) { 2127 NeedSpace = Policy.SplitTemplateClosers && ArgString.back() == '>'; 2128 FirstArg = false; 2129 } 2130 2131 // Use same template parameter for all elements of Pack 2132 if (!IsPack) 2133 ParmIndex++; 2134 } 2135 2136 if (!IsPack) { 2137 if (NeedSpace) 2138 OS << ' '; 2139 OS << '>'; 2140 } 2141 } 2142 2143 void clang::printTemplateArgumentList(raw_ostream &OS, 2144 const TemplateArgumentListInfo &Args, 2145 const PrintingPolicy &Policy, 2146 const TemplateParameterList *TPL) { 2147 printTemplateArgumentList(OS, Args.arguments(), Policy, TPL); 2148 } 2149 2150 void clang::printTemplateArgumentList(raw_ostream &OS, 2151 ArrayRef<TemplateArgument> Args, 2152 const PrintingPolicy &Policy, 2153 const TemplateParameterList *TPL) { 2154 printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0); 2155 } 2156 2157 void clang::printTemplateArgumentList(raw_ostream &OS, 2158 ArrayRef<TemplateArgumentLoc> Args, 2159 const PrintingPolicy &Policy, 2160 const TemplateParameterList *TPL) { 2161 printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0); 2162 } 2163 2164 std::string Qualifiers::getAsString() const { 2165 LangOptions LO; 2166 return getAsString(PrintingPolicy(LO)); 2167 } 2168 2169 // Appends qualifiers to the given string, separated by spaces. Will 2170 // prefix a space if the string is non-empty. Will not append a final 2171 // space. 2172 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const { 2173 SmallString<64> Buf; 2174 llvm::raw_svector_ostream StrOS(Buf); 2175 print(StrOS, Policy); 2176 return std::string(StrOS.str()); 2177 } 2178 2179 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const { 2180 if (getCVRQualifiers()) 2181 return false; 2182 2183 if (getAddressSpace() != LangAS::Default) 2184 return false; 2185 2186 if (getObjCGCAttr()) 2187 return false; 2188 2189 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) 2190 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)) 2191 return false; 2192 2193 return true; 2194 } 2195 2196 std::string Qualifiers::getAddrSpaceAsString(LangAS AS) { 2197 switch (AS) { 2198 case LangAS::Default: 2199 return ""; 2200 case LangAS::opencl_global: 2201 case LangAS::sycl_global: 2202 return "__global"; 2203 case LangAS::opencl_local: 2204 case LangAS::sycl_local: 2205 return "__local"; 2206 case LangAS::opencl_private: 2207 case LangAS::sycl_private: 2208 return "__private"; 2209 case LangAS::opencl_constant: 2210 return "__constant"; 2211 case LangAS::opencl_generic: 2212 return "__generic"; 2213 case LangAS::opencl_global_device: 2214 case LangAS::sycl_global_device: 2215 return "__global_device"; 2216 case LangAS::opencl_global_host: 2217 case LangAS::sycl_global_host: 2218 return "__global_host"; 2219 case LangAS::cuda_device: 2220 return "__device__"; 2221 case LangAS::cuda_constant: 2222 return "__constant__"; 2223 case LangAS::cuda_shared: 2224 return "__shared__"; 2225 case LangAS::ptr32_sptr: 2226 return "__sptr __ptr32"; 2227 case LangAS::ptr32_uptr: 2228 return "__uptr __ptr32"; 2229 case LangAS::ptr64: 2230 return "__ptr64"; 2231 default: 2232 return std::to_string(toTargetAddressSpace(AS)); 2233 } 2234 } 2235 2236 // Appends qualifiers to the given string, separated by spaces. Will 2237 // prefix a space if the string is non-empty. Will not append a final 2238 // space. 2239 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy, 2240 bool appendSpaceIfNonEmpty) const { 2241 bool addSpace = false; 2242 2243 unsigned quals = getCVRQualifiers(); 2244 if (quals) { 2245 AppendTypeQualList(OS, quals, Policy.Restrict); 2246 addSpace = true; 2247 } 2248 if (hasUnaligned()) { 2249 if (addSpace) 2250 OS << ' '; 2251 OS << "__unaligned"; 2252 addSpace = true; 2253 } 2254 auto ASStr = getAddrSpaceAsString(getAddressSpace()); 2255 if (!ASStr.empty()) { 2256 if (addSpace) 2257 OS << ' '; 2258 addSpace = true; 2259 // Wrap target address space into an attribute syntax 2260 if (isTargetAddressSpace(getAddressSpace())) 2261 OS << "__attribute__((address_space(" << ASStr << ")))"; 2262 else 2263 OS << ASStr; 2264 } 2265 2266 if (Qualifiers::GC gc = getObjCGCAttr()) { 2267 if (addSpace) 2268 OS << ' '; 2269 addSpace = true; 2270 if (gc == Qualifiers::Weak) 2271 OS << "__weak"; 2272 else 2273 OS << "__strong"; 2274 } 2275 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) { 2276 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){ 2277 if (addSpace) 2278 OS << ' '; 2279 addSpace = true; 2280 } 2281 2282 switch (lifetime) { 2283 case Qualifiers::OCL_None: llvm_unreachable("none but true"); 2284 case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break; 2285 case Qualifiers::OCL_Strong: 2286 if (!Policy.SuppressStrongLifetime) 2287 OS << "__strong"; 2288 break; 2289 2290 case Qualifiers::OCL_Weak: OS << "__weak"; break; 2291 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break; 2292 } 2293 } 2294 2295 if (appendSpaceIfNonEmpty && addSpace) 2296 OS << ' '; 2297 } 2298 2299 std::string QualType::getAsString() const { 2300 return getAsString(split(), LangOptions()); 2301 } 2302 2303 std::string QualType::getAsString(const PrintingPolicy &Policy) const { 2304 std::string S; 2305 getAsStringInternal(S, Policy); 2306 return S; 2307 } 2308 2309 std::string QualType::getAsString(const Type *ty, Qualifiers qs, 2310 const PrintingPolicy &Policy) { 2311 std::string buffer; 2312 getAsStringInternal(ty, qs, buffer, Policy); 2313 return buffer; 2314 } 2315 2316 void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy, 2317 const Twine &PlaceHolder, unsigned Indentation) const { 2318 print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder, 2319 Indentation); 2320 } 2321 2322 void QualType::print(const Type *ty, Qualifiers qs, 2323 raw_ostream &OS, const PrintingPolicy &policy, 2324 const Twine &PlaceHolder, unsigned Indentation) { 2325 SmallString<128> PHBuf; 2326 StringRef PH = PlaceHolder.toStringRef(PHBuf); 2327 2328 TypePrinter(policy, Indentation).print(ty, qs, OS, PH); 2329 } 2330 2331 void QualType::getAsStringInternal(std::string &Str, 2332 const PrintingPolicy &Policy) const { 2333 return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str, 2334 Policy); 2335 } 2336 2337 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs, 2338 std::string &buffer, 2339 const PrintingPolicy &policy) { 2340 SmallString<256> Buf; 2341 llvm::raw_svector_ostream StrOS(Buf); 2342 TypePrinter(policy).print(ty, qs, StrOS, buffer); 2343 std::string str = std::string(StrOS.str()); 2344 buffer.swap(str); 2345 } 2346 2347 raw_ostream &clang::operator<<(raw_ostream &OS, QualType QT) { 2348 SplitQualType S = QT.split(); 2349 TypePrinter(LangOptions()).print(S.Ty, S.Quals, OS, /*PlaceHolder=*/""); 2350 return OS; 2351 } 2352