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