1 //===--- TypePrinter.cpp - Pretty-Print Clang Types -----------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to print types from Clang's type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/PrettyPrinter.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/Type.h" 21 #include "clang/Basic/LangOptions.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/ADT/StringExtras.h" 25 #include "llvm/Support/SaveAndRestore.h" 26 #include "llvm/Support/raw_ostream.h" 27 using namespace clang; 28 29 namespace { 30 /// \brief RAII object that enables printing of the ARC __strong lifetime 31 /// qualifier. 32 class IncludeStrongLifetimeRAII { 33 PrintingPolicy &Policy; 34 bool Old; 35 36 public: 37 explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy) 38 : Policy(Policy), Old(Policy.SuppressStrongLifetime) { 39 if (!Policy.SuppressLifetimeQualifiers) 40 Policy.SuppressStrongLifetime = false; 41 } 42 43 ~IncludeStrongLifetimeRAII() { 44 Policy.SuppressStrongLifetime = Old; 45 } 46 }; 47 48 class ParamPolicyRAII { 49 PrintingPolicy &Policy; 50 bool Old; 51 52 public: 53 explicit ParamPolicyRAII(PrintingPolicy &Policy) 54 : Policy(Policy), Old(Policy.SuppressSpecifiers) { 55 Policy.SuppressSpecifiers = false; 56 } 57 58 ~ParamPolicyRAII() { 59 Policy.SuppressSpecifiers = Old; 60 } 61 }; 62 63 class ElaboratedTypePolicyRAII { 64 PrintingPolicy &Policy; 65 bool SuppressTagKeyword; 66 bool SuppressScope; 67 68 public: 69 explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) { 70 SuppressTagKeyword = Policy.SuppressTagKeyword; 71 SuppressScope = Policy.SuppressScope; 72 Policy.SuppressTagKeyword = true; 73 Policy.SuppressScope = true; 74 } 75 76 ~ElaboratedTypePolicyRAII() { 77 Policy.SuppressTagKeyword = SuppressTagKeyword; 78 Policy.SuppressScope = SuppressScope; 79 } 80 }; 81 82 class TypePrinter { 83 PrintingPolicy Policy; 84 unsigned Indentation; 85 bool HasEmptyPlaceHolder; 86 bool InsideCCAttribute; 87 88 public: 89 explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0) 90 : Policy(Policy), Indentation(Indentation), 91 HasEmptyPlaceHolder(false), InsideCCAttribute(false) { } 92 93 void print(const Type *ty, Qualifiers qs, raw_ostream &OS, 94 StringRef PlaceHolder); 95 void print(QualType T, raw_ostream &OS, StringRef PlaceHolder); 96 97 static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier); 98 void spaceBeforePlaceHolder(raw_ostream &OS); 99 void printTypeSpec(NamedDecl *D, raw_ostream &OS); 100 101 void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS); 102 void printBefore(QualType T, raw_ostream &OS); 103 void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS); 104 void printAfter(QualType T, raw_ostream &OS); 105 void AppendScope(DeclContext *DC, raw_ostream &OS); 106 void printTag(TagDecl *T, raw_ostream &OS); 107 #define ABSTRACT_TYPE(CLASS, PARENT) 108 #define TYPE(CLASS, PARENT) \ 109 void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS); \ 110 void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS); 111 #include "clang/AST/TypeNodes.def" 112 }; 113 } 114 115 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals, 116 bool HasRestrictKeyword) { 117 bool appendSpace = false; 118 if (TypeQuals & Qualifiers::Const) { 119 OS << "const"; 120 appendSpace = true; 121 } 122 if (TypeQuals & Qualifiers::Volatile) { 123 if (appendSpace) OS << ' '; 124 OS << "volatile"; 125 appendSpace = true; 126 } 127 if (TypeQuals & Qualifiers::Restrict) { 128 if (appendSpace) OS << ' '; 129 if (HasRestrictKeyword) { 130 OS << "restrict"; 131 } else { 132 OS << "__restrict"; 133 } 134 } 135 } 136 137 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) { 138 if (!HasEmptyPlaceHolder) 139 OS << ' '; 140 } 141 142 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) { 143 SplitQualType split = t.split(); 144 print(split.Ty, split.Quals, OS, PlaceHolder); 145 } 146 147 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS, 148 StringRef PlaceHolder) { 149 if (!T) { 150 OS << "NULL TYPE"; 151 return; 152 } 153 154 SaveAndRestore<bool> PHVal(HasEmptyPlaceHolder, PlaceHolder.empty()); 155 156 printBefore(T, Quals, OS); 157 OS << PlaceHolder; 158 printAfter(T, Quals, OS); 159 } 160 161 bool TypePrinter::canPrefixQualifiers(const Type *T, 162 bool &NeedARCStrongQualifier) { 163 // CanPrefixQualifiers - We prefer to print type qualifiers before the type, 164 // so that we get "const int" instead of "int const", but we can't do this if 165 // the type is complex. For example if the type is "int*", we *must* print 166 // "int * const", printing "const int *" is different. Only do this when the 167 // type expands to a simple string. 168 bool CanPrefixQualifiers = false; 169 NeedARCStrongQualifier = false; 170 Type::TypeClass TC = T->getTypeClass(); 171 if (const AutoType *AT = dyn_cast<AutoType>(T)) 172 TC = AT->desugar()->getTypeClass(); 173 if (const SubstTemplateTypeParmType *Subst 174 = dyn_cast<SubstTemplateTypeParmType>(T)) 175 TC = Subst->getReplacementType()->getTypeClass(); 176 177 switch (TC) { 178 case Type::Auto: 179 case Type::Builtin: 180 case Type::Complex: 181 case Type::UnresolvedUsing: 182 case Type::Typedef: 183 case Type::TypeOfExpr: 184 case Type::TypeOf: 185 case Type::Decltype: 186 case Type::UnaryTransform: 187 case Type::Record: 188 case Type::Enum: 189 case Type::Elaborated: 190 case Type::TemplateTypeParm: 191 case Type::SubstTemplateTypeParmPack: 192 case Type::DeducedTemplateSpecialization: 193 case Type::TemplateSpecialization: 194 case Type::InjectedClassName: 195 case Type::DependentName: 196 case Type::DependentTemplateSpecialization: 197 case Type::ObjCObject: 198 case Type::ObjCTypeParam: 199 case Type::ObjCInterface: 200 case Type::Atomic: 201 case Type::Pipe: 202 CanPrefixQualifiers = true; 203 break; 204 205 case Type::ObjCObjectPointer: 206 CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() || 207 T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType(); 208 break; 209 210 case Type::ConstantArray: 211 case Type::IncompleteArray: 212 case Type::VariableArray: 213 case Type::DependentSizedArray: 214 NeedARCStrongQualifier = true; 215 // Fall through 216 217 case Type::Adjusted: 218 case Type::Decayed: 219 case Type::Pointer: 220 case Type::BlockPointer: 221 case Type::LValueReference: 222 case Type::RValueReference: 223 case Type::MemberPointer: 224 case Type::DependentSizedExtVector: 225 case Type::Vector: 226 case Type::ExtVector: 227 case Type::FunctionProto: 228 case Type::FunctionNoProto: 229 case Type::Paren: 230 case Type::Attributed: 231 case Type::PackExpansion: 232 case Type::SubstTemplateTypeParm: 233 CanPrefixQualifiers = false; 234 break; 235 } 236 237 return CanPrefixQualifiers; 238 } 239 240 void TypePrinter::printBefore(QualType T, raw_ostream &OS) { 241 SplitQualType Split = T.split(); 242 243 // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2 244 // at this level. 245 Qualifiers Quals = Split.Quals; 246 if (const SubstTemplateTypeParmType *Subst = 247 dyn_cast<SubstTemplateTypeParmType>(Split.Ty)) 248 Quals -= QualType(Subst, 0).getQualifiers(); 249 250 printBefore(Split.Ty, Quals, OS); 251 } 252 253 /// \brief Prints the part of the type string before an identifier, e.g. for 254 /// "int foo[10]" it prints "int ". 255 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) { 256 if (Policy.SuppressSpecifiers && T->isSpecifierType()) 257 return; 258 259 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder); 260 261 // Print qualifiers as appropriate. 262 263 bool CanPrefixQualifiers = false; 264 bool NeedARCStrongQualifier = false; 265 CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier); 266 267 if (CanPrefixQualifiers && !Quals.empty()) { 268 if (NeedARCStrongQualifier) { 269 IncludeStrongLifetimeRAII Strong(Policy); 270 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true); 271 } else { 272 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true); 273 } 274 } 275 276 bool hasAfterQuals = false; 277 if (!CanPrefixQualifiers && !Quals.empty()) { 278 hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy); 279 if (hasAfterQuals) 280 HasEmptyPlaceHolder = false; 281 } 282 283 switch (T->getTypeClass()) { 284 #define ABSTRACT_TYPE(CLASS, PARENT) 285 #define TYPE(CLASS, PARENT) case Type::CLASS: \ 286 print##CLASS##Before(cast<CLASS##Type>(T), OS); \ 287 break; 288 #include "clang/AST/TypeNodes.def" 289 } 290 291 if (hasAfterQuals) { 292 if (NeedARCStrongQualifier) { 293 IncludeStrongLifetimeRAII Strong(Policy); 294 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get()); 295 } else { 296 Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get()); 297 } 298 } 299 } 300 301 void TypePrinter::printAfter(QualType t, raw_ostream &OS) { 302 SplitQualType split = t.split(); 303 printAfter(split.Ty, split.Quals, OS); 304 } 305 306 /// \brief Prints the part of the type string after an identifier, e.g. for 307 /// "int foo[10]" it prints "[10]". 308 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) { 309 switch (T->getTypeClass()) { 310 #define ABSTRACT_TYPE(CLASS, PARENT) 311 #define TYPE(CLASS, PARENT) case Type::CLASS: \ 312 print##CLASS##After(cast<CLASS##Type>(T), OS); \ 313 break; 314 #include "clang/AST/TypeNodes.def" 315 } 316 } 317 318 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) { 319 OS << T->getName(Policy); 320 spaceBeforePlaceHolder(OS); 321 } 322 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) { } 323 324 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) { 325 OS << "_Complex "; 326 printBefore(T->getElementType(), OS); 327 } 328 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) { 329 printAfter(T->getElementType(), OS); 330 } 331 332 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) { 333 IncludeStrongLifetimeRAII Strong(Policy); 334 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 335 printBefore(T->getPointeeType(), OS); 336 // Handle things like 'int (*A)[4];' correctly. 337 // FIXME: this should include vectors, but vectors use attributes I guess. 338 if (isa<ArrayType>(T->getPointeeType())) 339 OS << '('; 340 OS << '*'; 341 } 342 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) { 343 IncludeStrongLifetimeRAII Strong(Policy); 344 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 345 // Handle things like 'int (*A)[4];' correctly. 346 // FIXME: this should include vectors, but vectors use attributes I guess. 347 if (isa<ArrayType>(T->getPointeeType())) 348 OS << ')'; 349 printAfter(T->getPointeeType(), OS); 350 } 351 352 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T, 353 raw_ostream &OS) { 354 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 355 printBefore(T->getPointeeType(), OS); 356 OS << '^'; 357 } 358 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T, 359 raw_ostream &OS) { 360 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 361 printAfter(T->getPointeeType(), OS); 362 } 363 364 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T, 365 raw_ostream &OS) { 366 IncludeStrongLifetimeRAII Strong(Policy); 367 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 368 printBefore(T->getPointeeTypeAsWritten(), OS); 369 // Handle things like 'int (&A)[4];' correctly. 370 // FIXME: this should include vectors, but vectors use attributes I guess. 371 if (isa<ArrayType>(T->getPointeeTypeAsWritten())) 372 OS << '('; 373 OS << '&'; 374 } 375 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T, 376 raw_ostream &OS) { 377 IncludeStrongLifetimeRAII Strong(Policy); 378 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 379 // Handle things like 'int (&A)[4];' correctly. 380 // FIXME: this should include vectors, but vectors use attributes I guess. 381 if (isa<ArrayType>(T->getPointeeTypeAsWritten())) 382 OS << ')'; 383 printAfter(T->getPointeeTypeAsWritten(), OS); 384 } 385 386 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T, 387 raw_ostream &OS) { 388 IncludeStrongLifetimeRAII Strong(Policy); 389 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 390 printBefore(T->getPointeeTypeAsWritten(), OS); 391 // Handle things like 'int (&&A)[4];' correctly. 392 // FIXME: this should include vectors, but vectors use attributes I guess. 393 if (isa<ArrayType>(T->getPointeeTypeAsWritten())) 394 OS << '('; 395 OS << "&&"; 396 } 397 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T, 398 raw_ostream &OS) { 399 IncludeStrongLifetimeRAII Strong(Policy); 400 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 401 // Handle things like 'int (&&A)[4];' correctly. 402 // FIXME: this should include vectors, but vectors use attributes I guess. 403 if (isa<ArrayType>(T->getPointeeTypeAsWritten())) 404 OS << ')'; 405 printAfter(T->getPointeeTypeAsWritten(), OS); 406 } 407 408 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T, 409 raw_ostream &OS) { 410 IncludeStrongLifetimeRAII Strong(Policy); 411 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 412 printBefore(T->getPointeeType(), OS); 413 // Handle things like 'int (Cls::*A)[4];' correctly. 414 // FIXME: this should include vectors, but vectors use attributes I guess. 415 if (isa<ArrayType>(T->getPointeeType())) 416 OS << '('; 417 418 PrintingPolicy InnerPolicy(Policy); 419 InnerPolicy.IncludeTagDefinition = false; 420 TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef()); 421 422 OS << "::*"; 423 } 424 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T, 425 raw_ostream &OS) { 426 IncludeStrongLifetimeRAII Strong(Policy); 427 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 428 // Handle things like 'int (Cls::*A)[4];' correctly. 429 // FIXME: this should include vectors, but vectors use attributes I guess. 430 if (isa<ArrayType>(T->getPointeeType())) 431 OS << ')'; 432 printAfter(T->getPointeeType(), OS); 433 } 434 435 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T, 436 raw_ostream &OS) { 437 IncludeStrongLifetimeRAII Strong(Policy); 438 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 439 printBefore(T->getElementType(), OS); 440 } 441 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T, 442 raw_ostream &OS) { 443 OS << '['; 444 if (T->getIndexTypeQualifiers().hasQualifiers()) { 445 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), 446 Policy.Restrict); 447 OS << ' '; 448 } 449 450 if (T->getSizeModifier() == ArrayType::Static) 451 OS << "static "; 452 453 OS << T->getSize().getZExtValue() << ']'; 454 printAfter(T->getElementType(), OS); 455 } 456 457 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T, 458 raw_ostream &OS) { 459 IncludeStrongLifetimeRAII Strong(Policy); 460 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 461 printBefore(T->getElementType(), OS); 462 } 463 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T, 464 raw_ostream &OS) { 465 OS << "[]"; 466 printAfter(T->getElementType(), OS); 467 } 468 469 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T, 470 raw_ostream &OS) { 471 IncludeStrongLifetimeRAII Strong(Policy); 472 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 473 printBefore(T->getElementType(), OS); 474 } 475 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T, 476 raw_ostream &OS) { 477 OS << '['; 478 if (T->getIndexTypeQualifiers().hasQualifiers()) { 479 AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict); 480 OS << ' '; 481 } 482 483 if (T->getSizeModifier() == VariableArrayType::Static) 484 OS << "static "; 485 else if (T->getSizeModifier() == VariableArrayType::Star) 486 OS << '*'; 487 488 if (T->getSizeExpr()) 489 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 490 OS << ']'; 491 492 printAfter(T->getElementType(), OS); 493 } 494 495 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) { 496 // Print the adjusted representation, otherwise the adjustment will be 497 // invisible. 498 printBefore(T->getAdjustedType(), OS); 499 } 500 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) { 501 printAfter(T->getAdjustedType(), OS); 502 } 503 504 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) { 505 // Print as though it's a pointer. 506 printAdjustedBefore(T, OS); 507 } 508 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) { 509 printAdjustedAfter(T, OS); 510 } 511 512 void TypePrinter::printDependentSizedArrayBefore( 513 const DependentSizedArrayType *T, 514 raw_ostream &OS) { 515 IncludeStrongLifetimeRAII Strong(Policy); 516 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 517 printBefore(T->getElementType(), OS); 518 } 519 void TypePrinter::printDependentSizedArrayAfter( 520 const DependentSizedArrayType *T, 521 raw_ostream &OS) { 522 OS << '['; 523 if (T->getSizeExpr()) 524 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 525 OS << ']'; 526 printAfter(T->getElementType(), OS); 527 } 528 529 void TypePrinter::printDependentSizedExtVectorBefore( 530 const DependentSizedExtVectorType *T, 531 raw_ostream &OS) { 532 printBefore(T->getElementType(), OS); 533 } 534 void TypePrinter::printDependentSizedExtVectorAfter( 535 const DependentSizedExtVectorType *T, 536 raw_ostream &OS) { 537 OS << " __attribute__((ext_vector_type("; 538 if (T->getSizeExpr()) 539 T->getSizeExpr()->printPretty(OS, nullptr, Policy); 540 OS << ")))"; 541 printAfter(T->getElementType(), OS); 542 } 543 544 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) { 545 switch (T->getVectorKind()) { 546 case VectorType::AltiVecPixel: 547 OS << "__vector __pixel "; 548 break; 549 case VectorType::AltiVecBool: 550 OS << "__vector __bool "; 551 printBefore(T->getElementType(), OS); 552 break; 553 case VectorType::AltiVecVector: 554 OS << "__vector "; 555 printBefore(T->getElementType(), OS); 556 break; 557 case VectorType::NeonVector: 558 OS << "__attribute__((neon_vector_type(" 559 << T->getNumElements() << "))) "; 560 printBefore(T->getElementType(), OS); 561 break; 562 case VectorType::NeonPolyVector: 563 OS << "__attribute__((neon_polyvector_type(" << 564 T->getNumElements() << "))) "; 565 printBefore(T->getElementType(), OS); 566 break; 567 case VectorType::GenericVector: { 568 // FIXME: We prefer to print the size directly here, but have no way 569 // to get the size of the type. 570 OS << "__attribute__((__vector_size__(" 571 << T->getNumElements() 572 << " * sizeof("; 573 print(T->getElementType(), OS, StringRef()); 574 OS << ")))) "; 575 printBefore(T->getElementType(), OS); 576 break; 577 } 578 } 579 } 580 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) { 581 printAfter(T->getElementType(), OS); 582 } 583 584 void TypePrinter::printExtVectorBefore(const ExtVectorType *T, 585 raw_ostream &OS) { 586 printBefore(T->getElementType(), OS); 587 } 588 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) { 589 printAfter(T->getElementType(), OS); 590 OS << " __attribute__((ext_vector_type("; 591 OS << T->getNumElements(); 592 OS << ")))"; 593 } 594 595 void 596 FunctionProtoType::printExceptionSpecification(raw_ostream &OS, 597 const PrintingPolicy &Policy) 598 const { 599 600 if (hasDynamicExceptionSpec()) { 601 OS << " throw("; 602 if (getExceptionSpecType() == EST_MSAny) 603 OS << "..."; 604 else 605 for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) { 606 if (I) 607 OS << ", "; 608 609 OS << getExceptionType(I).stream(Policy); 610 } 611 OS << ')'; 612 } else if (isNoexceptExceptionSpec(getExceptionSpecType())) { 613 OS << " noexcept"; 614 if (getExceptionSpecType() == EST_ComputedNoexcept) { 615 OS << '('; 616 if (getNoexceptExpr()) 617 getNoexceptExpr()->printPretty(OS, nullptr, Policy); 618 OS << ')'; 619 } 620 } 621 } 622 623 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T, 624 raw_ostream &OS) { 625 if (T->hasTrailingReturn()) { 626 OS << "auto "; 627 if (!HasEmptyPlaceHolder) 628 OS << '('; 629 } else { 630 // If needed for precedence reasons, wrap the inner part in grouping parens. 631 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); 632 printBefore(T->getReturnType(), OS); 633 if (!PrevPHIsEmpty.get()) 634 OS << '('; 635 } 636 } 637 638 llvm::StringRef clang::getParameterABISpelling(ParameterABI ABI) { 639 switch (ABI) { 640 case ParameterABI::Ordinary: 641 llvm_unreachable("asking for spelling of ordinary parameter ABI"); 642 case ParameterABI::SwiftContext: 643 return "swift_context"; 644 case ParameterABI::SwiftErrorResult: 645 return "swift_error_result"; 646 case ParameterABI::SwiftIndirectResult: 647 return "swift_indirect_result"; 648 } 649 llvm_unreachable("bad parameter ABI kind"); 650 } 651 652 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T, 653 raw_ostream &OS) { 654 // If needed for precedence reasons, wrap the inner part in grouping parens. 655 if (!HasEmptyPlaceHolder) 656 OS << ')'; 657 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 658 659 OS << '('; 660 { 661 ParamPolicyRAII ParamPolicy(Policy); 662 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) { 663 if (i) OS << ", "; 664 665 auto EPI = T->getExtParameterInfo(i); 666 if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) "; 667 auto ABI = EPI.getABI(); 668 if (ABI != ParameterABI::Ordinary) 669 OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) "; 670 671 print(T->getParamType(i), OS, StringRef()); 672 } 673 } 674 675 if (T->isVariadic()) { 676 if (T->getNumParams()) 677 OS << ", "; 678 OS << "..."; 679 } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) { 680 // Do not emit int() if we have a proto, emit 'int(void)'. 681 OS << "void"; 682 } 683 684 OS << ')'; 685 686 FunctionType::ExtInfo Info = T->getExtInfo(); 687 688 if (!InsideCCAttribute) { 689 switch (Info.getCC()) { 690 case CC_C: 691 // The C calling convention is the default on the vast majority of platforms 692 // we support. If the user wrote it explicitly, it will usually be printed 693 // while traversing the AttributedType. If the type has been desugared, let 694 // the canonical spelling be the implicit calling convention. 695 // FIXME: It would be better to be explicit in certain contexts, such as a 696 // cdecl function typedef used to declare a member function with the 697 // Microsoft C++ ABI. 698 break; 699 case CC_X86StdCall: 700 OS << " __attribute__((stdcall))"; 701 break; 702 case CC_X86FastCall: 703 OS << " __attribute__((fastcall))"; 704 break; 705 case CC_X86ThisCall: 706 OS << " __attribute__((thiscall))"; 707 break; 708 case CC_X86VectorCall: 709 OS << " __attribute__((vectorcall))"; 710 break; 711 case CC_X86Pascal: 712 OS << " __attribute__((pascal))"; 713 break; 714 case CC_AAPCS: 715 OS << " __attribute__((pcs(\"aapcs\")))"; 716 break; 717 case CC_AAPCS_VFP: 718 OS << " __attribute__((pcs(\"aapcs-vfp\")))"; 719 break; 720 case CC_IntelOclBicc: 721 OS << " __attribute__((intel_ocl_bicc))"; 722 break; 723 case CC_X86_64Win64: 724 OS << " __attribute__((ms_abi))"; 725 break; 726 case CC_X86_64SysV: 727 OS << " __attribute__((sysv_abi))"; 728 break; 729 case CC_X86RegCall: 730 OS << " __attribute__((regcall))"; 731 break; 732 case CC_SpirFunction: 733 case CC_OpenCLKernel: 734 // Do nothing. These CCs are not available as attributes. 735 break; 736 case CC_Swift: 737 OS << " __attribute__((swiftcall))"; 738 break; 739 case CC_PreserveMost: 740 OS << " __attribute__((preserve_most))"; 741 break; 742 case CC_PreserveAll: 743 OS << " __attribute__((preserve_all))"; 744 break; 745 } 746 } 747 748 if (Info.getNoReturn()) 749 OS << " __attribute__((noreturn))"; 750 if (Info.getRegParm()) 751 OS << " __attribute__((regparm (" 752 << Info.getRegParm() << ")))"; 753 754 if (unsigned quals = T->getTypeQuals()) { 755 OS << ' '; 756 AppendTypeQualList(OS, quals, Policy.Restrict); 757 } 758 759 switch (T->getRefQualifier()) { 760 case RQ_None: 761 break; 762 763 case RQ_LValue: 764 OS << " &"; 765 break; 766 767 case RQ_RValue: 768 OS << " &&"; 769 break; 770 } 771 T->printExceptionSpecification(OS, Policy); 772 773 if (T->hasTrailingReturn()) { 774 OS << " -> "; 775 print(T->getReturnType(), OS, StringRef()); 776 } else 777 printAfter(T->getReturnType(), OS); 778 } 779 780 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T, 781 raw_ostream &OS) { 782 // If needed for precedence reasons, wrap the inner part in grouping parens. 783 SaveAndRestore<bool> PrevPHIsEmpty(HasEmptyPlaceHolder, false); 784 printBefore(T->getReturnType(), OS); 785 if (!PrevPHIsEmpty.get()) 786 OS << '('; 787 } 788 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T, 789 raw_ostream &OS) { 790 // If needed for precedence reasons, wrap the inner part in grouping parens. 791 if (!HasEmptyPlaceHolder) 792 OS << ')'; 793 SaveAndRestore<bool> NonEmptyPH(HasEmptyPlaceHolder, false); 794 795 OS << "()"; 796 if (T->getNoReturnAttr()) 797 OS << " __attribute__((noreturn))"; 798 printAfter(T->getReturnType(), OS); 799 } 800 801 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) { 802 803 // Compute the full nested-name-specifier for this type. 804 // In C, this will always be empty except when the type 805 // being printed is anonymous within other Record. 806 if (!Policy.SuppressScope) 807 AppendScope(D->getDeclContext(), OS); 808 809 IdentifierInfo *II = D->getIdentifier(); 810 OS << II->getName(); 811 spaceBeforePlaceHolder(OS); 812 } 813 814 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T, 815 raw_ostream &OS) { 816 printTypeSpec(T->getDecl(), OS); 817 } 818 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T, 819 raw_ostream &OS) { } 820 821 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) { 822 printTypeSpec(T->getDecl(), OS); 823 } 824 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) { } 825 826 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T, 827 raw_ostream &OS) { 828 OS << "typeof "; 829 if (T->getUnderlyingExpr()) 830 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); 831 spaceBeforePlaceHolder(OS); 832 } 833 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T, 834 raw_ostream &OS) { } 835 836 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) { 837 OS << "typeof("; 838 print(T->getUnderlyingType(), OS, StringRef()); 839 OS << ')'; 840 spaceBeforePlaceHolder(OS); 841 } 842 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) { } 843 844 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) { 845 OS << "decltype("; 846 if (T->getUnderlyingExpr()) 847 T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy); 848 OS << ')'; 849 spaceBeforePlaceHolder(OS); 850 } 851 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) { } 852 853 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T, 854 raw_ostream &OS) { 855 IncludeStrongLifetimeRAII Strong(Policy); 856 857 switch (T->getUTTKind()) { 858 case UnaryTransformType::EnumUnderlyingType: 859 OS << "__underlying_type("; 860 print(T->getBaseType(), OS, StringRef()); 861 OS << ')'; 862 spaceBeforePlaceHolder(OS); 863 return; 864 } 865 866 printBefore(T->getBaseType(), OS); 867 } 868 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T, 869 raw_ostream &OS) { 870 IncludeStrongLifetimeRAII Strong(Policy); 871 872 switch (T->getUTTKind()) { 873 case UnaryTransformType::EnumUnderlyingType: 874 return; 875 } 876 877 printAfter(T->getBaseType(), OS); 878 } 879 880 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) { 881 // If the type has been deduced, do not print 'auto'. 882 if (!T->getDeducedType().isNull()) { 883 printBefore(T->getDeducedType(), OS); 884 } else { 885 switch (T->getKeyword()) { 886 case AutoTypeKeyword::Auto: OS << "auto"; break; 887 case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break; 888 case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break; 889 } 890 spaceBeforePlaceHolder(OS); 891 } 892 } 893 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) { 894 // If the type has been deduced, do not print 'auto'. 895 if (!T->getDeducedType().isNull()) 896 printAfter(T->getDeducedType(), OS); 897 } 898 899 void TypePrinter::printDeducedTemplateSpecializationBefore( 900 const DeducedTemplateSpecializationType *T, raw_ostream &OS) { 901 // If the type has been deduced, print the deduced type. 902 if (!T->getDeducedType().isNull()) { 903 printBefore(T->getDeducedType(), OS); 904 } else { 905 IncludeStrongLifetimeRAII Strong(Policy); 906 T->getTemplateName().print(OS, Policy); 907 spaceBeforePlaceHolder(OS); 908 } 909 } 910 void TypePrinter::printDeducedTemplateSpecializationAfter( 911 const DeducedTemplateSpecializationType *T, raw_ostream &OS) { 912 // If the type has been deduced, print the deduced type. 913 if (!T->getDeducedType().isNull()) 914 printAfter(T->getDeducedType(), OS); 915 } 916 917 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) { 918 IncludeStrongLifetimeRAII Strong(Policy); 919 920 OS << "_Atomic("; 921 print(T->getValueType(), OS, StringRef()); 922 OS << ')'; 923 spaceBeforePlaceHolder(OS); 924 } 925 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) { } 926 927 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) { 928 IncludeStrongLifetimeRAII Strong(Policy); 929 930 if (T->isReadOnly()) 931 OS << "read_only "; 932 else 933 OS << "write_only "; 934 OS << "pipe "; 935 print(T->getElementType(), OS, StringRef()); 936 spaceBeforePlaceHolder(OS); 937 } 938 939 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) { 940 } 941 /// Appends the given scope to the end of a string. 942 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS) { 943 if (DC->isTranslationUnit()) return; 944 if (DC->isFunctionOrMethod()) return; 945 AppendScope(DC->getParent(), OS); 946 947 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) { 948 if (Policy.SuppressUnwrittenScope && 949 (NS->isAnonymousNamespace() || NS->isInline())) 950 return; 951 if (NS->getIdentifier()) 952 OS << NS->getName() << "::"; 953 else 954 OS << "(anonymous namespace)::"; 955 } else if (ClassTemplateSpecializationDecl *Spec 956 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 957 IncludeStrongLifetimeRAII Strong(Policy); 958 OS << Spec->getIdentifier()->getName(); 959 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 960 TemplateSpecializationType::PrintTemplateArgumentList( 961 OS, TemplateArgs.asArray(), Policy); 962 OS << "::"; 963 } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) { 964 if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl()) 965 OS << Typedef->getIdentifier()->getName() << "::"; 966 else if (Tag->getIdentifier()) 967 OS << Tag->getIdentifier()->getName() << "::"; 968 else 969 return; 970 } 971 } 972 973 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) { 974 if (Policy.IncludeTagDefinition) { 975 PrintingPolicy SubPolicy = Policy; 976 SubPolicy.IncludeTagDefinition = false; 977 D->print(OS, SubPolicy, Indentation); 978 spaceBeforePlaceHolder(OS); 979 return; 980 } 981 982 bool HasKindDecoration = false; 983 984 // We don't print tags unless this is an elaborated type. 985 // In C, we just assume every RecordType is an elaborated type. 986 if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) { 987 HasKindDecoration = true; 988 OS << D->getKindName(); 989 OS << ' '; 990 } 991 992 // Compute the full nested-name-specifier for this type. 993 // In C, this will always be empty except when the type 994 // being printed is anonymous within other Record. 995 if (!Policy.SuppressScope) 996 AppendScope(D->getDeclContext(), OS); 997 998 if (const IdentifierInfo *II = D->getIdentifier()) 999 OS << II->getName(); 1000 else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) { 1001 assert(Typedef->getIdentifier() && "Typedef without identifier?"); 1002 OS << Typedef->getIdentifier()->getName(); 1003 } else { 1004 // Make an unambiguous representation for anonymous types, e.g. 1005 // (anonymous enum at /usr/include/string.h:120:9) 1006 OS << (Policy.MSVCFormatting ? '`' : '('); 1007 1008 if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) { 1009 OS << "lambda"; 1010 HasKindDecoration = true; 1011 } else { 1012 OS << "anonymous"; 1013 } 1014 1015 if (Policy.AnonymousTagLocations) { 1016 // Suppress the redundant tag keyword if we just printed one. 1017 // We don't have to worry about ElaboratedTypes here because you can't 1018 // refer to an anonymous type with one. 1019 if (!HasKindDecoration) 1020 OS << " " << D->getKindName(); 1021 1022 PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc( 1023 D->getLocation()); 1024 if (PLoc.isValid()) { 1025 OS << " at " << PLoc.getFilename() 1026 << ':' << PLoc.getLine() 1027 << ':' << PLoc.getColumn(); 1028 } 1029 } 1030 1031 OS << (Policy.MSVCFormatting ? '\'' : ')'); 1032 } 1033 1034 // If this is a class template specialization, print the template 1035 // arguments. 1036 if (ClassTemplateSpecializationDecl *Spec 1037 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 1038 ArrayRef<TemplateArgument> Args; 1039 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) { 1040 const TemplateSpecializationType *TST = 1041 cast<TemplateSpecializationType>(TAW->getType()); 1042 Args = TST->template_arguments(); 1043 } else { 1044 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1045 Args = TemplateArgs.asArray(); 1046 } 1047 IncludeStrongLifetimeRAII Strong(Policy); 1048 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, Policy); 1049 } 1050 1051 spaceBeforePlaceHolder(OS); 1052 } 1053 1054 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) { 1055 printTag(T->getDecl(), OS); 1056 } 1057 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) { } 1058 1059 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) { 1060 printTag(T->getDecl(), OS); 1061 } 1062 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) { } 1063 1064 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T, 1065 raw_ostream &OS) { 1066 if (IdentifierInfo *Id = T->getIdentifier()) 1067 OS << Id->getName(); 1068 else 1069 OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex(); 1070 spaceBeforePlaceHolder(OS); 1071 } 1072 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T, 1073 raw_ostream &OS) { } 1074 1075 void TypePrinter::printSubstTemplateTypeParmBefore( 1076 const SubstTemplateTypeParmType *T, 1077 raw_ostream &OS) { 1078 IncludeStrongLifetimeRAII Strong(Policy); 1079 printBefore(T->getReplacementType(), OS); 1080 } 1081 void TypePrinter::printSubstTemplateTypeParmAfter( 1082 const SubstTemplateTypeParmType *T, 1083 raw_ostream &OS) { 1084 IncludeStrongLifetimeRAII Strong(Policy); 1085 printAfter(T->getReplacementType(), OS); 1086 } 1087 1088 void TypePrinter::printSubstTemplateTypeParmPackBefore( 1089 const SubstTemplateTypeParmPackType *T, 1090 raw_ostream &OS) { 1091 IncludeStrongLifetimeRAII Strong(Policy); 1092 printTemplateTypeParmBefore(T->getReplacedParameter(), OS); 1093 } 1094 void TypePrinter::printSubstTemplateTypeParmPackAfter( 1095 const SubstTemplateTypeParmPackType *T, 1096 raw_ostream &OS) { 1097 IncludeStrongLifetimeRAII Strong(Policy); 1098 printTemplateTypeParmAfter(T->getReplacedParameter(), OS); 1099 } 1100 1101 void TypePrinter::printTemplateSpecializationBefore( 1102 const TemplateSpecializationType *T, 1103 raw_ostream &OS) { 1104 IncludeStrongLifetimeRAII Strong(Policy); 1105 T->getTemplateName().print(OS, Policy); 1106 1107 TemplateSpecializationType::PrintTemplateArgumentList( 1108 OS, T->template_arguments(), Policy); 1109 spaceBeforePlaceHolder(OS); 1110 } 1111 void TypePrinter::printTemplateSpecializationAfter( 1112 const TemplateSpecializationType *T, 1113 raw_ostream &OS) { } 1114 1115 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T, 1116 raw_ostream &OS) { 1117 printTemplateSpecializationBefore(T->getInjectedTST(), OS); 1118 } 1119 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T, 1120 raw_ostream &OS) { } 1121 1122 void TypePrinter::printElaboratedBefore(const ElaboratedType *T, 1123 raw_ostream &OS) { 1124 // The tag definition will take care of these. 1125 if (!Policy.IncludeTagDefinition) 1126 { 1127 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1128 if (T->getKeyword() != ETK_None) 1129 OS << " "; 1130 NestedNameSpecifier* Qualifier = T->getQualifier(); 1131 if (Qualifier) 1132 Qualifier->print(OS, Policy); 1133 } 1134 1135 ElaboratedTypePolicyRAII PolicyRAII(Policy); 1136 printBefore(T->getNamedType(), OS); 1137 } 1138 void TypePrinter::printElaboratedAfter(const ElaboratedType *T, 1139 raw_ostream &OS) { 1140 ElaboratedTypePolicyRAII PolicyRAII(Policy); 1141 printAfter(T->getNamedType(), OS); 1142 } 1143 1144 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) { 1145 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) { 1146 printBefore(T->getInnerType(), OS); 1147 OS << '('; 1148 } else 1149 printBefore(T->getInnerType(), OS); 1150 } 1151 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) { 1152 if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) { 1153 OS << ')'; 1154 printAfter(T->getInnerType(), OS); 1155 } else 1156 printAfter(T->getInnerType(), OS); 1157 } 1158 1159 void TypePrinter::printDependentNameBefore(const DependentNameType *T, 1160 raw_ostream &OS) { 1161 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1162 if (T->getKeyword() != ETK_None) 1163 OS << " "; 1164 1165 T->getQualifier()->print(OS, Policy); 1166 1167 OS << T->getIdentifier()->getName(); 1168 spaceBeforePlaceHolder(OS); 1169 } 1170 void TypePrinter::printDependentNameAfter(const DependentNameType *T, 1171 raw_ostream &OS) { } 1172 1173 void TypePrinter::printDependentTemplateSpecializationBefore( 1174 const DependentTemplateSpecializationType *T, raw_ostream &OS) { 1175 IncludeStrongLifetimeRAII Strong(Policy); 1176 1177 OS << TypeWithKeyword::getKeywordName(T->getKeyword()); 1178 if (T->getKeyword() != ETK_None) 1179 OS << " "; 1180 1181 if (T->getQualifier()) 1182 T->getQualifier()->print(OS, Policy); 1183 OS << T->getIdentifier()->getName(); 1184 TemplateSpecializationType::PrintTemplateArgumentList(OS, 1185 T->template_arguments(), 1186 Policy); 1187 spaceBeforePlaceHolder(OS); 1188 } 1189 void TypePrinter::printDependentTemplateSpecializationAfter( 1190 const DependentTemplateSpecializationType *T, raw_ostream &OS) { } 1191 1192 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T, 1193 raw_ostream &OS) { 1194 printBefore(T->getPattern(), OS); 1195 } 1196 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T, 1197 raw_ostream &OS) { 1198 printAfter(T->getPattern(), OS); 1199 OS << "..."; 1200 } 1201 1202 void TypePrinter::printAttributedBefore(const AttributedType *T, 1203 raw_ostream &OS) { 1204 // Prefer the macro forms of the GC and ownership qualifiers. 1205 if (T->getAttrKind() == AttributedType::attr_objc_gc || 1206 T->getAttrKind() == AttributedType::attr_objc_ownership) 1207 return printBefore(T->getEquivalentType(), OS); 1208 1209 if (T->getAttrKind() == AttributedType::attr_objc_kindof) 1210 OS << "__kindof "; 1211 1212 printBefore(T->getModifiedType(), OS); 1213 1214 if (T->isMSTypeSpec()) { 1215 switch (T->getAttrKind()) { 1216 default: return; 1217 case AttributedType::attr_ptr32: OS << " __ptr32"; break; 1218 case AttributedType::attr_ptr64: OS << " __ptr64"; break; 1219 case AttributedType::attr_sptr: OS << " __sptr"; break; 1220 case AttributedType::attr_uptr: OS << " __uptr"; break; 1221 } 1222 spaceBeforePlaceHolder(OS); 1223 } 1224 1225 // Print nullability type specifiers. 1226 if (T->getAttrKind() == AttributedType::attr_nonnull || 1227 T->getAttrKind() == AttributedType::attr_nullable || 1228 T->getAttrKind() == AttributedType::attr_null_unspecified) { 1229 if (T->getAttrKind() == AttributedType::attr_nonnull) 1230 OS << " _Nonnull"; 1231 else if (T->getAttrKind() == AttributedType::attr_nullable) 1232 OS << " _Nullable"; 1233 else if (T->getAttrKind() == AttributedType::attr_null_unspecified) 1234 OS << " _Null_unspecified"; 1235 else 1236 llvm_unreachable("unhandled nullability"); 1237 spaceBeforePlaceHolder(OS); 1238 } 1239 } 1240 1241 void TypePrinter::printAttributedAfter(const AttributedType *T, 1242 raw_ostream &OS) { 1243 // Prefer the macro forms of the GC and ownership qualifiers. 1244 if (T->getAttrKind() == AttributedType::attr_objc_gc || 1245 T->getAttrKind() == AttributedType::attr_objc_ownership) 1246 return printAfter(T->getEquivalentType(), OS); 1247 1248 if (T->getAttrKind() == AttributedType::attr_objc_kindof) 1249 return; 1250 1251 // TODO: not all attributes are GCC-style attributes. 1252 if (T->isMSTypeSpec()) 1253 return; 1254 1255 // Nothing to print after. 1256 if (T->getAttrKind() == AttributedType::attr_nonnull || 1257 T->getAttrKind() == AttributedType::attr_nullable || 1258 T->getAttrKind() == AttributedType::attr_null_unspecified) 1259 return printAfter(T->getModifiedType(), OS); 1260 1261 // If this is a calling convention attribute, don't print the implicit CC from 1262 // the modified type. 1263 SaveAndRestore<bool> MaybeSuppressCC(InsideCCAttribute, T->isCallingConv()); 1264 1265 printAfter(T->getModifiedType(), OS); 1266 1267 // Don't print the inert __unsafe_unretained attribute at all. 1268 if (T->getAttrKind() == AttributedType::attr_objc_inert_unsafe_unretained) 1269 return; 1270 1271 // Print nullability type specifiers that occur after 1272 if (T->getAttrKind() == AttributedType::attr_nonnull || 1273 T->getAttrKind() == AttributedType::attr_nullable || 1274 T->getAttrKind() == AttributedType::attr_null_unspecified) { 1275 if (T->getAttrKind() == AttributedType::attr_nonnull) 1276 OS << " _Nonnull"; 1277 else if (T->getAttrKind() == AttributedType::attr_nullable) 1278 OS << " _Nullable"; 1279 else if (T->getAttrKind() == AttributedType::attr_null_unspecified) 1280 OS << " _Null_unspecified"; 1281 else 1282 llvm_unreachable("unhandled nullability"); 1283 1284 return; 1285 } 1286 1287 OS << " __attribute__(("; 1288 switch (T->getAttrKind()) { 1289 default: llvm_unreachable("This attribute should have been handled already"); 1290 case AttributedType::attr_address_space: 1291 OS << "address_space("; 1292 OS << T->getEquivalentType().getAddressSpace(); 1293 OS << ')'; 1294 break; 1295 1296 case AttributedType::attr_vector_size: { 1297 OS << "__vector_size__("; 1298 if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) { 1299 OS << vector->getNumElements(); 1300 OS << " * sizeof("; 1301 print(vector->getElementType(), OS, StringRef()); 1302 OS << ')'; 1303 } 1304 OS << ')'; 1305 break; 1306 } 1307 1308 case AttributedType::attr_neon_vector_type: 1309 case AttributedType::attr_neon_polyvector_type: { 1310 if (T->getAttrKind() == AttributedType::attr_neon_vector_type) 1311 OS << "neon_vector_type("; 1312 else 1313 OS << "neon_polyvector_type("; 1314 const VectorType *vector = T->getEquivalentType()->getAs<VectorType>(); 1315 OS << vector->getNumElements(); 1316 OS << ')'; 1317 break; 1318 } 1319 1320 case AttributedType::attr_regparm: { 1321 // FIXME: When Sema learns to form this AttributedType, avoid printing the 1322 // attribute again in printFunctionProtoAfter. 1323 OS << "regparm("; 1324 QualType t = T->getEquivalentType(); 1325 while (!t->isFunctionType()) 1326 t = t->getPointeeType(); 1327 OS << t->getAs<FunctionType>()->getRegParmType(); 1328 OS << ')'; 1329 break; 1330 } 1331 1332 case AttributedType::attr_objc_gc: { 1333 OS << "objc_gc("; 1334 1335 QualType tmp = T->getEquivalentType(); 1336 while (tmp.getObjCGCAttr() == Qualifiers::GCNone) { 1337 QualType next = tmp->getPointeeType(); 1338 if (next == tmp) break; 1339 tmp = next; 1340 } 1341 1342 if (tmp.isObjCGCWeak()) 1343 OS << "weak"; 1344 else 1345 OS << "strong"; 1346 OS << ')'; 1347 break; 1348 } 1349 1350 case AttributedType::attr_objc_ownership: 1351 OS << "objc_ownership("; 1352 switch (T->getEquivalentType().getObjCLifetime()) { 1353 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); 1354 case Qualifiers::OCL_ExplicitNone: OS << "none"; break; 1355 case Qualifiers::OCL_Strong: OS << "strong"; break; 1356 case Qualifiers::OCL_Weak: OS << "weak"; break; 1357 case Qualifiers::OCL_Autoreleasing: OS << "autoreleasing"; break; 1358 } 1359 OS << ')'; 1360 break; 1361 1362 // FIXME: When Sema learns to form this AttributedType, avoid printing the 1363 // attribute again in printFunctionProtoAfter. 1364 case AttributedType::attr_noreturn: OS << "noreturn"; break; 1365 1366 case AttributedType::attr_cdecl: OS << "cdecl"; break; 1367 case AttributedType::attr_fastcall: OS << "fastcall"; break; 1368 case AttributedType::attr_stdcall: OS << "stdcall"; break; 1369 case AttributedType::attr_thiscall: OS << "thiscall"; break; 1370 case AttributedType::attr_swiftcall: OS << "swiftcall"; break; 1371 case AttributedType::attr_vectorcall: OS << "vectorcall"; break; 1372 case AttributedType::attr_pascal: OS << "pascal"; break; 1373 case AttributedType::attr_ms_abi: OS << "ms_abi"; break; 1374 case AttributedType::attr_sysv_abi: OS << "sysv_abi"; break; 1375 case AttributedType::attr_regcall: OS << "regcall"; break; 1376 case AttributedType::attr_pcs: 1377 case AttributedType::attr_pcs_vfp: { 1378 OS << "pcs("; 1379 QualType t = T->getEquivalentType(); 1380 while (!t->isFunctionType()) 1381 t = t->getPointeeType(); 1382 OS << (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ? 1383 "\"aapcs\"" : "\"aapcs-vfp\""); 1384 OS << ')'; 1385 break; 1386 } 1387 case AttributedType::attr_inteloclbicc: OS << "inteloclbicc"; break; 1388 case AttributedType::attr_preserve_most: 1389 OS << "preserve_most"; 1390 break; 1391 case AttributedType::attr_preserve_all: 1392 OS << "preserve_all"; 1393 break; 1394 } 1395 OS << "))"; 1396 } 1397 1398 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T, 1399 raw_ostream &OS) { 1400 OS << T->getDecl()->getName(); 1401 spaceBeforePlaceHolder(OS); 1402 } 1403 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T, 1404 raw_ostream &OS) { } 1405 1406 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T, 1407 raw_ostream &OS) { 1408 OS << T->getDecl()->getName(); 1409 if (!T->qual_empty()) { 1410 bool isFirst = true; 1411 OS << '<'; 1412 for (const auto *I : T->quals()) { 1413 if (isFirst) 1414 isFirst = false; 1415 else 1416 OS << ','; 1417 OS << I->getName(); 1418 } 1419 OS << '>'; 1420 } 1421 1422 spaceBeforePlaceHolder(OS); 1423 } 1424 1425 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T, 1426 raw_ostream &OS) { } 1427 1428 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T, 1429 raw_ostream &OS) { 1430 if (T->qual_empty() && T->isUnspecializedAsWritten() && 1431 !T->isKindOfTypeAsWritten()) 1432 return printBefore(T->getBaseType(), OS); 1433 1434 if (T->isKindOfTypeAsWritten()) 1435 OS << "__kindof "; 1436 1437 print(T->getBaseType(), OS, StringRef()); 1438 1439 if (T->isSpecializedAsWritten()) { 1440 bool isFirst = true; 1441 OS << '<'; 1442 for (auto typeArg : T->getTypeArgsAsWritten()) { 1443 if (isFirst) 1444 isFirst = false; 1445 else 1446 OS << ","; 1447 1448 print(typeArg, OS, StringRef()); 1449 } 1450 OS << '>'; 1451 } 1452 1453 if (!T->qual_empty()) { 1454 bool isFirst = true; 1455 OS << '<'; 1456 for (const auto *I : T->quals()) { 1457 if (isFirst) 1458 isFirst = false; 1459 else 1460 OS << ','; 1461 OS << I->getName(); 1462 } 1463 OS << '>'; 1464 } 1465 1466 spaceBeforePlaceHolder(OS); 1467 } 1468 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T, 1469 raw_ostream &OS) { 1470 if (T->qual_empty() && T->isUnspecializedAsWritten() && 1471 !T->isKindOfTypeAsWritten()) 1472 return printAfter(T->getBaseType(), OS); 1473 } 1474 1475 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T, 1476 raw_ostream &OS) { 1477 printBefore(T->getPointeeType(), OS); 1478 1479 // If we need to print the pointer, print it now. 1480 if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() && 1481 !T->isObjCClassType() && !T->isObjCQualifiedClassType()) { 1482 if (HasEmptyPlaceHolder) 1483 OS << ' '; 1484 OS << '*'; 1485 } 1486 } 1487 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T, 1488 raw_ostream &OS) { } 1489 1490 void TemplateSpecializationType:: 1491 PrintTemplateArgumentList(raw_ostream &OS, 1492 const TemplateArgumentListInfo &Args, 1493 const PrintingPolicy &Policy) { 1494 return PrintTemplateArgumentList(OS, 1495 Args.arguments(), 1496 Policy); 1497 } 1498 1499 void TemplateSpecializationType::PrintTemplateArgumentList( 1500 raw_ostream &OS, ArrayRef<TemplateArgument> Args, 1501 const PrintingPolicy &Policy, bool SkipBrackets) { 1502 const char *Comma = Policy.MSVCFormatting ? "," : ", "; 1503 if (!SkipBrackets) 1504 OS << '<'; 1505 1506 bool needSpace = false; 1507 bool FirstArg = true; 1508 for (const TemplateArgument &Arg : Args) { 1509 // Print the argument into a string. 1510 SmallString<128> Buf; 1511 llvm::raw_svector_ostream ArgOS(Buf); 1512 if (Arg.getKind() == TemplateArgument::Pack) { 1513 if (Arg.pack_size() && !FirstArg) 1514 OS << Comma; 1515 PrintTemplateArgumentList(ArgOS, 1516 Arg.getPackAsArray(), 1517 Policy, true); 1518 } else { 1519 if (!FirstArg) 1520 OS << Comma; 1521 Arg.print(Policy, ArgOS); 1522 } 1523 StringRef ArgString = ArgOS.str(); 1524 1525 // If this is the first argument and its string representation 1526 // begins with the global scope specifier ('::foo'), add a space 1527 // to avoid printing the diagraph '<:'. 1528 if (FirstArg && !ArgString.empty() && ArgString[0] == ':') 1529 OS << ' '; 1530 1531 OS << ArgString; 1532 1533 needSpace = (!ArgString.empty() && ArgString.back() == '>'); 1534 FirstArg = false; 1535 } 1536 1537 // If the last character of our string is '>', add another space to 1538 // keep the two '>''s separate tokens. We don't *have* to do this in 1539 // C++0x, but it's still good hygiene. 1540 if (needSpace) 1541 OS << ' '; 1542 1543 if (!SkipBrackets) 1544 OS << '>'; 1545 } 1546 1547 // Sadly, repeat all that with TemplateArgLoc. 1548 void TemplateSpecializationType:: 1549 PrintTemplateArgumentList(raw_ostream &OS, 1550 ArrayRef<TemplateArgumentLoc> Args, 1551 const PrintingPolicy &Policy) { 1552 OS << '<'; 1553 const char *Comma = Policy.MSVCFormatting ? "," : ", "; 1554 1555 bool needSpace = false; 1556 bool FirstArg = true; 1557 for (const TemplateArgumentLoc &Arg : Args) { 1558 if (!FirstArg) 1559 OS << Comma; 1560 1561 // Print the argument into a string. 1562 SmallString<128> Buf; 1563 llvm::raw_svector_ostream ArgOS(Buf); 1564 if (Arg.getArgument().getKind() == TemplateArgument::Pack) { 1565 PrintTemplateArgumentList(ArgOS, 1566 Arg.getArgument().getPackAsArray(), 1567 Policy, true); 1568 } else { 1569 Arg.getArgument().print(Policy, ArgOS); 1570 } 1571 StringRef ArgString = ArgOS.str(); 1572 1573 // If this is the first argument and its string representation 1574 // begins with the global scope specifier ('::foo'), add a space 1575 // to avoid printing the diagraph '<:'. 1576 if (FirstArg && !ArgString.empty() && ArgString[0] == ':') 1577 OS << ' '; 1578 1579 OS << ArgString; 1580 1581 needSpace = (!ArgString.empty() && ArgString.back() == '>'); 1582 FirstArg = false; 1583 } 1584 1585 // If the last character of our string is '>', add another space to 1586 // keep the two '>''s separate tokens. We don't *have* to do this in 1587 // C++0x, but it's still good hygiene. 1588 if (needSpace) 1589 OS << ' '; 1590 1591 OS << '>'; 1592 } 1593 1594 std::string Qualifiers::getAsString() const { 1595 LangOptions LO; 1596 return getAsString(PrintingPolicy(LO)); 1597 } 1598 1599 // Appends qualifiers to the given string, separated by spaces. Will 1600 // prefix a space if the string is non-empty. Will not append a final 1601 // space. 1602 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const { 1603 SmallString<64> Buf; 1604 llvm::raw_svector_ostream StrOS(Buf); 1605 print(StrOS, Policy); 1606 return StrOS.str(); 1607 } 1608 1609 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const { 1610 if (getCVRQualifiers()) 1611 return false; 1612 1613 if (getAddressSpace()) 1614 return false; 1615 1616 if (getObjCGCAttr()) 1617 return false; 1618 1619 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) 1620 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)) 1621 return false; 1622 1623 return true; 1624 } 1625 1626 // Appends qualifiers to the given string, separated by spaces. Will 1627 // prefix a space if the string is non-empty. Will not append a final 1628 // space. 1629 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy, 1630 bool appendSpaceIfNonEmpty) const { 1631 bool addSpace = false; 1632 1633 unsigned quals = getCVRQualifiers(); 1634 if (quals) { 1635 AppendTypeQualList(OS, quals, Policy.Restrict); 1636 addSpace = true; 1637 } 1638 if (hasUnaligned()) { 1639 if (addSpace) 1640 OS << ' '; 1641 OS << "__unaligned"; 1642 addSpace = true; 1643 } 1644 if (unsigned addrspace = getAddressSpace()) { 1645 if (addSpace) 1646 OS << ' '; 1647 addSpace = true; 1648 switch (addrspace) { 1649 case LangAS::opencl_global: 1650 OS << "__global"; 1651 break; 1652 case LangAS::opencl_local: 1653 OS << "__local"; 1654 break; 1655 case LangAS::opencl_constant: 1656 case LangAS::cuda_constant: 1657 OS << "__constant"; 1658 break; 1659 case LangAS::opencl_generic: 1660 OS << "__generic"; 1661 break; 1662 case LangAS::cuda_device: 1663 OS << "__device"; 1664 break; 1665 case LangAS::cuda_shared: 1666 OS << "__shared"; 1667 break; 1668 default: 1669 assert(addrspace >= LangAS::Count); 1670 OS << "__attribute__((address_space("; 1671 OS << addrspace - LangAS::Count; 1672 OS << ")))"; 1673 } 1674 } 1675 if (Qualifiers::GC gc = getObjCGCAttr()) { 1676 if (addSpace) 1677 OS << ' '; 1678 addSpace = true; 1679 if (gc == Qualifiers::Weak) 1680 OS << "__weak"; 1681 else 1682 OS << "__strong"; 1683 } 1684 if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) { 1685 if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){ 1686 if (addSpace) 1687 OS << ' '; 1688 addSpace = true; 1689 } 1690 1691 switch (lifetime) { 1692 case Qualifiers::OCL_None: llvm_unreachable("none but true"); 1693 case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break; 1694 case Qualifiers::OCL_Strong: 1695 if (!Policy.SuppressStrongLifetime) 1696 OS << "__strong"; 1697 break; 1698 1699 case Qualifiers::OCL_Weak: OS << "__weak"; break; 1700 case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break; 1701 } 1702 } 1703 1704 if (appendSpaceIfNonEmpty && addSpace) 1705 OS << ' '; 1706 } 1707 1708 std::string QualType::getAsString(const PrintingPolicy &Policy) const { 1709 std::string S; 1710 getAsStringInternal(S, Policy); 1711 return S; 1712 } 1713 1714 std::string QualType::getAsString(const Type *ty, Qualifiers qs) { 1715 std::string buffer; 1716 LangOptions options; 1717 getAsStringInternal(ty, qs, buffer, PrintingPolicy(options)); 1718 return buffer; 1719 } 1720 1721 void QualType::print(const Type *ty, Qualifiers qs, 1722 raw_ostream &OS, const PrintingPolicy &policy, 1723 const Twine &PlaceHolder, unsigned Indentation) { 1724 SmallString<128> PHBuf; 1725 StringRef PH = PlaceHolder.toStringRef(PHBuf); 1726 1727 TypePrinter(policy, Indentation).print(ty, qs, OS, PH); 1728 } 1729 1730 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs, 1731 std::string &buffer, 1732 const PrintingPolicy &policy) { 1733 SmallString<256> Buf; 1734 llvm::raw_svector_ostream StrOS(Buf); 1735 TypePrinter(policy).print(ty, qs, StrOS, buffer); 1736 std::string str = StrOS.str(); 1737 buffer.swap(str); 1738 } 1739