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