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