1 //===------------------------- ItaniumDemangle.cpp ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // FIXME: (possibly) incomplete list of features that clang mangles that this 11 // file does not yet support: 12 // - C++ modules TS 13 // - All C++14 and C++17 features 14 15 #include "llvm/Demangle/Demangle.h" 16 17 #include "llvm/Demangle/Compiler.h" 18 19 #include <algorithm> 20 #include <cassert> 21 #include <cctype> 22 #include <cstdio> 23 #include <cstdlib> 24 #include <cstring> 25 #include <numeric> 26 #include <vector> 27 28 #ifdef _MSC_VER 29 // snprintf is implemented in VS 2015 30 #if _MSC_VER < 1900 31 #define snprintf _snprintf_s 32 #endif 33 #endif 34 35 namespace { 36 37 class StringView { 38 const char *First; 39 const char *Last; 40 41 public: 42 template <size_t N> 43 StringView(const char (&Str)[N]) : First(Str), Last(Str + N - 1) {} 44 StringView(const char *First_, const char *Last_) : First(First_), Last(Last_) {} 45 StringView() : First(nullptr), Last(nullptr) {} 46 47 StringView substr(size_t From, size_t To) { 48 if (To >= size()) 49 To = size() - 1; 50 if (From >= size()) 51 From = size() - 1; 52 return StringView(First + From, First + To); 53 } 54 55 StringView dropFront(size_t N) const { 56 if (N >= size()) 57 N = size() - 1; 58 return StringView(First + N, Last); 59 } 60 61 bool startsWith(StringView Str) const { 62 if (Str.size() > size()) 63 return false; 64 return std::equal(Str.begin(), Str.end(), begin()); 65 } 66 67 const char &operator[](size_t Idx) const { return *(begin() + Idx); } 68 69 const char *begin() const { return First; } 70 const char *end() const { return Last; } 71 size_t size() const { return static_cast<size_t>(Last - First); } 72 bool empty() const { return First == Last; } 73 }; 74 75 bool operator==(const StringView &LHS, const StringView &RHS) { 76 return LHS.size() == RHS.size() && 77 std::equal(LHS.begin(), LHS.end(), RHS.begin()); 78 } 79 80 // Stream that AST nodes write their string representation into after the AST 81 // has been parsed. 82 class OutputStream { 83 char *Buffer; 84 size_t CurrentPosition; 85 size_t BufferCapacity; 86 87 // Ensure there is at least n more positions in buffer. 88 void grow(size_t N) { 89 if (N + CurrentPosition >= BufferCapacity) { 90 BufferCapacity *= 2; 91 if (BufferCapacity < N + CurrentPosition) 92 BufferCapacity = N + CurrentPosition; 93 Buffer = static_cast<char *>(std::realloc(Buffer, BufferCapacity)); 94 } 95 } 96 97 public: 98 OutputStream(char *StartBuf, size_t Size) 99 : Buffer(StartBuf), CurrentPosition(0), BufferCapacity(Size) {} 100 101 /// If a ParameterPackExpansion (or similar type) is encountered, the offset 102 /// into the pack that we're currently printing. 103 unsigned CurrentPackIndex = std::numeric_limits<unsigned>::max(); 104 unsigned CurrentPackMax = std::numeric_limits<unsigned>::max(); 105 106 OutputStream &operator+=(StringView R) { 107 size_t Size = R.size(); 108 if (Size == 0) 109 return *this; 110 grow(Size); 111 memmove(Buffer + CurrentPosition, R.begin(), Size); 112 CurrentPosition += Size; 113 return *this; 114 } 115 116 OutputStream &operator+=(char C) { 117 grow(1); 118 Buffer[CurrentPosition++] = C; 119 return *this; 120 } 121 122 size_t getCurrentPosition() const { return CurrentPosition; } 123 void setCurrentPosition(size_t NewPos) { CurrentPosition = NewPos; } 124 125 char back() const { 126 return CurrentPosition ? Buffer[CurrentPosition - 1] : '\0'; 127 } 128 129 bool empty() const { return CurrentPosition == 0; } 130 131 char *getBuffer() { return Buffer; } 132 char *getBufferEnd() { return Buffer + CurrentPosition - 1; } 133 size_t getBufferCapacity() { return BufferCapacity; } 134 }; 135 136 template <class T> 137 class SwapAndRestore { 138 T &Restore; 139 T OriginalValue; 140 public: 141 SwapAndRestore(T& Restore_, T NewVal) 142 : Restore(Restore_), OriginalValue(Restore) { 143 Restore = std::move(NewVal); 144 } 145 ~SwapAndRestore() { Restore = std::move(OriginalValue); } 146 147 SwapAndRestore(const SwapAndRestore &) = delete; 148 SwapAndRestore &operator=(const SwapAndRestore &) = delete; 149 }; 150 151 // Base class of all AST nodes. The AST is built by the parser, then is 152 // traversed by the printLeft/Right functions to produce a demangled string. 153 class Node { 154 public: 155 enum Kind : unsigned char { 156 KDotSuffix, 157 KVendorExtQualType, 158 KQualType, 159 KConversionOperatorType, 160 KPostfixQualifiedType, 161 KElaboratedTypeSpefType, 162 KNameType, 163 KAbiTagAttr, 164 KEnableIfAttr, 165 KObjCProtoName, 166 KPointerType, 167 KLValueReferenceType, 168 KRValueReferenceType, 169 KPointerToMemberType, 170 KArrayType, 171 KFunctionType, 172 KNoexceptSpec, 173 KDynamicExceptionSpec, 174 KFunctionEncoding, 175 KLiteralOperator, 176 KSpecialName, 177 KCtorVtableSpecialName, 178 KQualifiedName, 179 KEmptyName, 180 KVectorType, 181 KParameterPack, 182 KTemplateArgumentPack, 183 KParameterPackExpansion, 184 KTemplateArgs, 185 KForwardTemplateReference, 186 KNameWithTemplateArgs, 187 KGlobalQualifiedName, 188 KStdQualifiedName, 189 KExpandedSpecialSubstitution, 190 KSpecialSubstitution, 191 KCtorDtorName, 192 KDtorName, 193 KUnnamedTypeName, 194 KClosureTypeName, 195 KStructuredBindingName, 196 KExpr, 197 KBracedExpr, 198 KBracedRangeExpr, 199 }; 200 201 Kind K; 202 203 /// Three-way bool to track a cached value. Unknown is possible if this node 204 /// has an unexpanded parameter pack below it that may affect this cache. 205 enum class Cache : unsigned char { Yes, No, Unknown, }; 206 207 /// Tracks if this node has a component on its right side, in which case we 208 /// need to call printRight. 209 Cache RHSComponentCache; 210 211 /// Track if this node is a (possibly qualified) array type. This can affect 212 /// how we format the output string. 213 Cache ArrayCache; 214 215 /// Track if this node is a (possibly qualified) function type. This can 216 /// affect how we format the output string. 217 Cache FunctionCache; 218 219 Node(Kind K_, Cache RHSComponentCache_ = Cache::No, 220 Cache ArrayCache_ = Cache::No, Cache FunctionCache_ = Cache::No) 221 : K(K_), RHSComponentCache(RHSComponentCache_), ArrayCache(ArrayCache_), 222 FunctionCache(FunctionCache_) {} 223 224 bool hasRHSComponent(OutputStream &S) const { 225 if (RHSComponentCache != Cache::Unknown) 226 return RHSComponentCache == Cache::Yes; 227 return hasRHSComponentSlow(S); 228 } 229 230 bool hasArray(OutputStream &S) const { 231 if (ArrayCache != Cache::Unknown) 232 return ArrayCache == Cache::Yes; 233 return hasArraySlow(S); 234 } 235 236 bool hasFunction(OutputStream &S) const { 237 if (FunctionCache != Cache::Unknown) 238 return FunctionCache == Cache::Yes; 239 return hasFunctionSlow(S); 240 } 241 242 Kind getKind() const { return K; } 243 244 virtual bool hasRHSComponentSlow(OutputStream &) const { return false; } 245 virtual bool hasArraySlow(OutputStream &) const { return false; } 246 virtual bool hasFunctionSlow(OutputStream &) const { return false; } 247 248 void print(OutputStream &S) const { 249 printLeft(S); 250 if (RHSComponentCache != Cache::No) 251 printRight(S); 252 } 253 254 // Print the "left" side of this Node into OutputStream. 255 virtual void printLeft(OutputStream &) const = 0; 256 257 // Print the "right". This distinction is necessary to represent C++ types 258 // that appear on the RHS of their subtype, such as arrays or functions. 259 // Since most types don't have such a component, provide a default 260 // implemenation. 261 virtual void printRight(OutputStream &) const {} 262 263 virtual StringView getBaseName() const { return StringView(); } 264 265 // Silence compiler warnings, this dtor will never be called. 266 virtual ~Node() = default; 267 268 #ifndef NDEBUG 269 LLVM_DUMP_METHOD void dump() const { 270 char *Buffer = static_cast<char*>(std::malloc(1024)); 271 OutputStream S(Buffer, 1024); 272 print(S); 273 S += '\0'; 274 printf("Symbol dump for %p: %s\n", (const void*)this, S.getBuffer()); 275 std::free(S.getBuffer()); 276 } 277 #endif 278 }; 279 280 class NodeArray { 281 Node **Elements; 282 size_t NumElements; 283 284 public: 285 NodeArray() : Elements(nullptr), NumElements(0) {} 286 NodeArray(Node **Elements_, size_t NumElements_) 287 : Elements(Elements_), NumElements(NumElements_) {} 288 289 bool empty() const { return NumElements == 0; } 290 size_t size() const { return NumElements; } 291 292 Node **begin() const { return Elements; } 293 Node **end() const { return Elements + NumElements; } 294 295 Node *operator[](size_t Idx) const { return Elements[Idx]; } 296 297 void printWithComma(OutputStream &S) const { 298 bool FirstElement = true; 299 for (size_t Idx = 0; Idx != NumElements; ++Idx) { 300 size_t BeforeComma = S.getCurrentPosition(); 301 if (!FirstElement) 302 S += ", "; 303 size_t AfterComma = S.getCurrentPosition(); 304 Elements[Idx]->print(S); 305 306 // Elements[Idx] is an empty parameter pack expansion, we should erase the 307 // comma we just printed. 308 if (AfterComma == S.getCurrentPosition()) { 309 S.setCurrentPosition(BeforeComma); 310 continue; 311 } 312 313 FirstElement = false; 314 } 315 } 316 }; 317 318 class DotSuffix final : public Node { 319 const Node *Prefix; 320 const StringView Suffix; 321 322 public: 323 DotSuffix(Node *Prefix_, StringView Suffix_) 324 : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {} 325 326 void printLeft(OutputStream &s) const override { 327 Prefix->print(s); 328 s += " ("; 329 s += Suffix; 330 s += ")"; 331 } 332 }; 333 334 class VendorExtQualType final : public Node { 335 const Node *Ty; 336 StringView Ext; 337 338 public: 339 VendorExtQualType(Node *Ty_, StringView Ext_) 340 : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_) {} 341 342 void printLeft(OutputStream &S) const override { 343 Ty->print(S); 344 S += " "; 345 S += Ext; 346 } 347 }; 348 349 enum FunctionRefQual : unsigned char { 350 FrefQualNone, 351 FrefQualLValue, 352 FrefQualRValue, 353 }; 354 355 enum Qualifiers { 356 QualNone = 0, 357 QualConst = 0x1, 358 QualVolatile = 0x2, 359 QualRestrict = 0x4, 360 }; 361 362 void addQualifiers(Qualifiers &Q1, Qualifiers Q2) { 363 Q1 = static_cast<Qualifiers>(Q1 | Q2); 364 } 365 366 class QualType : public Node { 367 protected: 368 const Qualifiers Quals; 369 const Node *Child; 370 371 void printQuals(OutputStream &S) const { 372 if (Quals & QualConst) 373 S += " const"; 374 if (Quals & QualVolatile) 375 S += " volatile"; 376 if (Quals & QualRestrict) 377 S += " restrict"; 378 } 379 380 public: 381 QualType(Node *Child_, Qualifiers Quals_) 382 : Node(KQualType, Child_->RHSComponentCache, 383 Child_->ArrayCache, Child_->FunctionCache), 384 Quals(Quals_), Child(Child_) {} 385 386 bool hasRHSComponentSlow(OutputStream &S) const override { 387 return Child->hasRHSComponent(S); 388 } 389 bool hasArraySlow(OutputStream &S) const override { 390 return Child->hasArray(S); 391 } 392 bool hasFunctionSlow(OutputStream &S) const override { 393 return Child->hasFunction(S); 394 } 395 396 void printLeft(OutputStream &S) const override { 397 Child->printLeft(S); 398 printQuals(S); 399 } 400 401 void printRight(OutputStream &S) const override { Child->printRight(S); } 402 }; 403 404 class ConversionOperatorType final : public Node { 405 const Node *Ty; 406 407 public: 408 ConversionOperatorType(Node *Ty_) 409 : Node(KConversionOperatorType), Ty(Ty_) {} 410 411 void printLeft(OutputStream &S) const override { 412 S += "operator "; 413 Ty->print(S); 414 } 415 }; 416 417 class PostfixQualifiedType final : public Node { 418 const Node *Ty; 419 const StringView Postfix; 420 421 public: 422 PostfixQualifiedType(Node *Ty_, StringView Postfix_) 423 : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {} 424 425 void printLeft(OutputStream &s) const override { 426 Ty->printLeft(s); 427 s += Postfix; 428 } 429 }; 430 431 class NameType final : public Node { 432 const StringView Name; 433 434 public: 435 NameType(StringView Name_) : Node(KNameType), Name(Name_) {} 436 437 StringView getName() const { return Name; } 438 StringView getBaseName() const override { return Name; } 439 440 void printLeft(OutputStream &s) const override { s += Name; } 441 }; 442 443 class ElaboratedTypeSpefType : public Node { 444 StringView Kind; 445 Node *Child; 446 public: 447 ElaboratedTypeSpefType(StringView Kind_, Node *Child_) 448 : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {} 449 450 void printLeft(OutputStream &S) const override { 451 S += Kind; 452 S += ' '; 453 Child->print(S); 454 } 455 }; 456 457 class AbiTagAttr final : public Node { 458 const Node* Base; 459 StringView Tag; 460 public: 461 AbiTagAttr(const Node* Base_, StringView Tag_) 462 : Node(KAbiTagAttr, Base_->RHSComponentCache, 463 Base_->ArrayCache, Base_->FunctionCache), 464 Base(Base_), Tag(Tag_) {} 465 466 void printLeft(OutputStream &S) const override { 467 Base->printLeft(S); 468 S += "[abi:"; 469 S += Tag; 470 S += "]"; 471 } 472 }; 473 474 class EnableIfAttr : public Node { 475 NodeArray Conditions; 476 public: 477 EnableIfAttr(NodeArray Conditions_) 478 : Node(KEnableIfAttr), Conditions(Conditions_) {} 479 480 void printLeft(OutputStream &S) const override { 481 S += " [enable_if:"; 482 Conditions.printWithComma(S); 483 S += ']'; 484 } 485 }; 486 487 class ObjCProtoName : public Node { 488 Node *Ty; 489 StringView Protocol; 490 491 friend class PointerType; 492 493 public: 494 ObjCProtoName(Node *Ty_, StringView Protocol_) 495 : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {} 496 497 bool isObjCObject() const { 498 return Ty->getKind() == KNameType && 499 static_cast<NameType *>(Ty)->getName() == "objc_object"; 500 } 501 502 void printLeft(OutputStream &S) const override { 503 Ty->print(S); 504 S += "<"; 505 S += Protocol; 506 S += ">"; 507 } 508 }; 509 510 class PointerType final : public Node { 511 const Node *Pointee; 512 513 public: 514 PointerType(Node *Pointee_) 515 : Node(KPointerType, Pointee_->RHSComponentCache), 516 Pointee(Pointee_) {} 517 518 bool hasRHSComponentSlow(OutputStream &S) const override { 519 return Pointee->hasRHSComponent(S); 520 } 521 522 void printLeft(OutputStream &s) const override { 523 // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>. 524 if (Pointee->getKind() != KObjCProtoName || 525 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) { 526 Pointee->printLeft(s); 527 if (Pointee->hasArray(s)) 528 s += " "; 529 if (Pointee->hasArray(s) || Pointee->hasFunction(s)) 530 s += "("; 531 s += "*"; 532 } else { 533 const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee); 534 s += "id<"; 535 s += objcProto->Protocol; 536 s += ">"; 537 } 538 } 539 540 void printRight(OutputStream &s) const override { 541 if (Pointee->getKind() != KObjCProtoName || 542 !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) { 543 if (Pointee->hasArray(s) || Pointee->hasFunction(s)) 544 s += ")"; 545 Pointee->printRight(s); 546 } 547 } 548 }; 549 550 class LValueReferenceType final : public Node { 551 const Node *Pointee; 552 553 public: 554 LValueReferenceType(Node *Pointee_) 555 : Node(KLValueReferenceType, Pointee_->RHSComponentCache), 556 Pointee(Pointee_) {} 557 558 bool hasRHSComponentSlow(OutputStream &S) const override { 559 return Pointee->hasRHSComponent(S); 560 } 561 562 void printLeft(OutputStream &s) const override { 563 Pointee->printLeft(s); 564 if (Pointee->hasArray(s)) 565 s += " "; 566 if (Pointee->hasArray(s) || Pointee->hasFunction(s)) 567 s += "(&"; 568 else 569 s += "&"; 570 } 571 void printRight(OutputStream &s) const override { 572 if (Pointee->hasArray(s) || Pointee->hasFunction(s)) 573 s += ")"; 574 Pointee->printRight(s); 575 } 576 }; 577 578 class RValueReferenceType final : public Node { 579 const Node *Pointee; 580 581 public: 582 RValueReferenceType(Node *Pointee_) 583 : Node(KRValueReferenceType, Pointee_->RHSComponentCache), 584 Pointee(Pointee_) {} 585 586 bool hasRHSComponentSlow(OutputStream &S) const override { 587 return Pointee->hasRHSComponent(S); 588 } 589 590 void printLeft(OutputStream &s) const override { 591 Pointee->printLeft(s); 592 if (Pointee->hasArray(s)) 593 s += " "; 594 if (Pointee->hasArray(s) || Pointee->hasFunction(s)) 595 s += "(&&"; 596 else 597 s += "&&"; 598 } 599 600 void printRight(OutputStream &s) const override { 601 if (Pointee->hasArray(s) || Pointee->hasFunction(s)) 602 s += ")"; 603 Pointee->printRight(s); 604 } 605 }; 606 607 class PointerToMemberType final : public Node { 608 const Node *ClassType; 609 const Node *MemberType; 610 611 public: 612 PointerToMemberType(Node *ClassType_, Node *MemberType_) 613 : Node(KPointerToMemberType, MemberType_->RHSComponentCache), 614 ClassType(ClassType_), MemberType(MemberType_) {} 615 616 bool hasRHSComponentSlow(OutputStream &S) const override { 617 return MemberType->hasRHSComponent(S); 618 } 619 620 void printLeft(OutputStream &s) const override { 621 MemberType->printLeft(s); 622 if (MemberType->hasArray(s) || MemberType->hasFunction(s)) 623 s += "("; 624 else 625 s += " "; 626 ClassType->print(s); 627 s += "::*"; 628 } 629 630 void printRight(OutputStream &s) const override { 631 if (MemberType->hasArray(s) || MemberType->hasFunction(s)) 632 s += ")"; 633 MemberType->printRight(s); 634 } 635 }; 636 637 class NodeOrString { 638 const void *First; 639 const void *Second; 640 641 public: 642 /* implicit */ NodeOrString(StringView Str) { 643 const char *FirstChar = Str.begin(); 644 const char *SecondChar = Str.end(); 645 if (SecondChar == nullptr) { 646 assert(FirstChar == SecondChar); 647 ++FirstChar, ++SecondChar; 648 } 649 First = static_cast<const void *>(FirstChar); 650 Second = static_cast<const void *>(SecondChar); 651 } 652 653 /* implicit */ NodeOrString(Node *N) 654 : First(static_cast<const void *>(N)), Second(nullptr) {} 655 NodeOrString() : First(nullptr), Second(nullptr) {} 656 657 bool isString() const { return Second && First; } 658 bool isNode() const { return First && !Second; } 659 bool isEmpty() const { return !First && !Second; } 660 661 StringView asString() const { 662 assert(isString()); 663 return StringView(static_cast<const char *>(First), 664 static_cast<const char *>(Second)); 665 } 666 667 const Node *asNode() const { 668 assert(isNode()); 669 return static_cast<const Node *>(First); 670 } 671 }; 672 673 class ArrayType final : public Node { 674 Node *Base; 675 NodeOrString Dimension; 676 677 public: 678 ArrayType(Node *Base_, NodeOrString Dimension_) 679 : Node(KArrayType, 680 /*RHSComponentCache=*/Cache::Yes, 681 /*ArrayCache=*/Cache::Yes), 682 Base(Base_), Dimension(Dimension_) {} 683 684 // Incomplete array type. 685 ArrayType(Node *Base_) 686 : Node(KArrayType, 687 /*RHSComponentCache=*/Cache::Yes, 688 /*ArrayCache=*/Cache::Yes), 689 Base(Base_) {} 690 691 bool hasRHSComponentSlow(OutputStream &) const override { return true; } 692 bool hasArraySlow(OutputStream &) const override { return true; } 693 694 void printLeft(OutputStream &S) const override { Base->printLeft(S); } 695 696 void printRight(OutputStream &S) const override { 697 if (S.back() != ']') 698 S += " "; 699 S += "["; 700 if (Dimension.isString()) 701 S += Dimension.asString(); 702 else if (Dimension.isNode()) 703 Dimension.asNode()->print(S); 704 S += "]"; 705 Base->printRight(S); 706 } 707 }; 708 709 class FunctionType final : public Node { 710 Node *Ret; 711 NodeArray Params; 712 Qualifiers CVQuals; 713 FunctionRefQual RefQual; 714 Node *ExceptionSpec; 715 716 public: 717 FunctionType(Node *Ret_, NodeArray Params_, Qualifiers CVQuals_, 718 FunctionRefQual RefQual_, Node *ExceptionSpec_) 719 : Node(KFunctionType, 720 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No, 721 /*FunctionCache=*/Cache::Yes), 722 Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_), 723 ExceptionSpec(ExceptionSpec_) {} 724 725 bool hasRHSComponentSlow(OutputStream &) const override { return true; } 726 bool hasFunctionSlow(OutputStream &) const override { return true; } 727 728 // Handle C++'s ... quirky decl grammer by using the left & right 729 // distinction. Consider: 730 // int (*f(float))(char) {} 731 // f is a function that takes a float and returns a pointer to a function 732 // that takes a char and returns an int. If we're trying to print f, start 733 // by printing out the return types's left, then print our parameters, then 734 // finally print right of the return type. 735 void printLeft(OutputStream &S) const override { 736 Ret->printLeft(S); 737 S += " "; 738 } 739 740 void printRight(OutputStream &S) const override { 741 S += "("; 742 Params.printWithComma(S); 743 S += ")"; 744 Ret->printRight(S); 745 746 if (CVQuals & QualConst) 747 S += " const"; 748 if (CVQuals & QualVolatile) 749 S += " volatile"; 750 if (CVQuals & QualRestrict) 751 S += " restrict"; 752 753 if (RefQual == FrefQualLValue) 754 S += " &"; 755 else if (RefQual == FrefQualRValue) 756 S += " &&"; 757 758 if (ExceptionSpec != nullptr) { 759 S += ' '; 760 ExceptionSpec->print(S); 761 } 762 } 763 }; 764 765 class NoexceptSpec : public Node { 766 Node *E; 767 public: 768 NoexceptSpec(Node *E_) : Node(KNoexceptSpec), E(E_) {} 769 770 void printLeft(OutputStream &S) const override { 771 S += "noexcept("; 772 E->print(S); 773 S += ")"; 774 } 775 }; 776 777 class DynamicExceptionSpec : public Node { 778 NodeArray Types; 779 public: 780 DynamicExceptionSpec(NodeArray Types_) 781 : Node(KDynamicExceptionSpec), Types(Types_) {} 782 783 void printLeft(OutputStream &S) const override { 784 S += "throw("; 785 Types.printWithComma(S); 786 S += ')'; 787 } 788 }; 789 790 class FunctionEncoding final : public Node { 791 const Node *Ret; 792 const Node *Name; 793 NodeArray Params; 794 Node *Attrs; 795 Qualifiers CVQuals; 796 FunctionRefQual RefQual; 797 798 public: 799 FunctionEncoding(Node *Ret_, Node *Name_, NodeArray Params_, 800 Node *Attrs_, Qualifiers CVQuals_, FunctionRefQual RefQual_) 801 : Node(KFunctionEncoding, 802 /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No, 803 /*FunctionCache=*/Cache::Yes), 804 Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_), 805 CVQuals(CVQuals_), RefQual(RefQual_) {} 806 807 bool hasRHSComponentSlow(OutputStream &) const override { return true; } 808 bool hasFunctionSlow(OutputStream &) const override { return true; } 809 810 Node *getName() { return const_cast<Node *>(Name); } 811 812 void printLeft(OutputStream &S) const override { 813 if (Ret) { 814 Ret->printLeft(S); 815 if (!Ret->hasRHSComponent(S)) 816 S += " "; 817 } 818 Name->print(S); 819 } 820 821 void printRight(OutputStream &S) const override { 822 S += "("; 823 Params.printWithComma(S); 824 S += ")"; 825 if (Ret) 826 Ret->printRight(S); 827 828 if (CVQuals & QualConst) 829 S += " const"; 830 if (CVQuals & QualVolatile) 831 S += " volatile"; 832 if (CVQuals & QualRestrict) 833 S += " restrict"; 834 835 if (RefQual == FrefQualLValue) 836 S += " &"; 837 else if (RefQual == FrefQualRValue) 838 S += " &&"; 839 840 if (Attrs != nullptr) 841 Attrs->print(S); 842 } 843 }; 844 845 class LiteralOperator : public Node { 846 const Node *OpName; 847 848 public: 849 LiteralOperator(Node *OpName_) : Node(KLiteralOperator), OpName(OpName_) {} 850 851 void printLeft(OutputStream &S) const override { 852 S += "operator\"\" "; 853 OpName->print(S); 854 } 855 }; 856 857 class SpecialName final : public Node { 858 const StringView Special; 859 const Node *Child; 860 861 public: 862 SpecialName(StringView Special_, Node* Child_) 863 : Node(KSpecialName), Special(Special_), Child(Child_) {} 864 865 void printLeft(OutputStream &S) const override { 866 S += Special; 867 Child->print(S); 868 } 869 }; 870 871 class CtorVtableSpecialName final : public Node { 872 const Node *FirstType; 873 const Node *SecondType; 874 875 public: 876 CtorVtableSpecialName(Node *FirstType_, Node *SecondType_) 877 : Node(KCtorVtableSpecialName), 878 FirstType(FirstType_), SecondType(SecondType_) {} 879 880 void printLeft(OutputStream &S) const override { 881 S += "construction vtable for "; 882 FirstType->print(S); 883 S += "-in-"; 884 SecondType->print(S); 885 } 886 }; 887 888 class QualifiedName final : public Node { 889 // qualifier::name 890 const Node *Qualifier; 891 const Node *Name; 892 893 public: 894 QualifiedName(Node* Qualifier_, Node* Name_) 895 : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {} 896 897 StringView getBaseName() const override { return Name->getBaseName(); } 898 899 void printLeft(OutputStream &S) const override { 900 Qualifier->print(S); 901 S += "::"; 902 Name->print(S); 903 } 904 }; 905 906 class EmptyName : public Node { 907 public: 908 EmptyName() : Node(KEmptyName) {} 909 void printLeft(OutputStream &) const override {} 910 }; 911 912 class VectorType final : public Node { 913 const Node *BaseType; 914 const NodeOrString Dimension; 915 const bool IsPixel; 916 917 public: 918 VectorType(NodeOrString Dimension_) 919 : Node(KVectorType), BaseType(nullptr), Dimension(Dimension_), 920 IsPixel(true) {} 921 VectorType(Node *BaseType_, NodeOrString Dimension_) 922 : Node(KVectorType), BaseType(BaseType_), 923 Dimension(Dimension_), IsPixel(false) {} 924 925 void printLeft(OutputStream &S) const override { 926 if (IsPixel) { 927 S += "pixel vector["; 928 S += Dimension.asString(); 929 S += "]"; 930 } else { 931 BaseType->print(S); 932 S += " vector["; 933 if (Dimension.isNode()) 934 Dimension.asNode()->print(S); 935 else if (Dimension.isString()) 936 S += Dimension.asString(); 937 S += "]"; 938 } 939 } 940 }; 941 942 /// An unexpanded parameter pack (either in the expression or type context). If 943 /// this AST is correct, this node will have a ParameterPackExpansion node above 944 /// it. 945 /// 946 /// This node is created when some <template-args> are found that apply to an 947 /// <encoding>, and is stored in the TemplateParams table. In order for this to 948 /// appear in the final AST, it has to referenced via a <template-param> (ie, 949 /// T_). 950 class ParameterPack final : public Node { 951 NodeArray Data; 952 953 // Setup OutputStream for a pack expansion unless we're already expanding one. 954 void initializePackExpansion(OutputStream &S) const { 955 if (S.CurrentPackMax == std::numeric_limits<unsigned>::max()) { 956 S.CurrentPackMax = static_cast<unsigned>(Data.size()); 957 S.CurrentPackIndex = 0; 958 } 959 } 960 961 public: 962 ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) { 963 ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown; 964 if (std::all_of(Data.begin(), Data.end(), [](Node* P) { 965 return P->ArrayCache == Cache::No; 966 })) 967 ArrayCache = Cache::No; 968 if (std::all_of(Data.begin(), Data.end(), [](Node* P) { 969 return P->FunctionCache == Cache::No; 970 })) 971 FunctionCache = Cache::No; 972 if (std::all_of(Data.begin(), Data.end(), [](Node* P) { 973 return P->RHSComponentCache == Cache::No; 974 })) 975 RHSComponentCache = Cache::No; 976 } 977 978 bool hasRHSComponentSlow(OutputStream &S) const override { 979 initializePackExpansion(S); 980 size_t Idx = S.CurrentPackIndex; 981 return Idx < Data.size() && Data[Idx]->hasRHSComponent(S); 982 } 983 bool hasArraySlow(OutputStream &S) const override { 984 initializePackExpansion(S); 985 size_t Idx = S.CurrentPackIndex; 986 return Idx < Data.size() && Data[Idx]->hasArray(S); 987 } 988 bool hasFunctionSlow(OutputStream &S) const override { 989 initializePackExpansion(S); 990 size_t Idx = S.CurrentPackIndex; 991 return Idx < Data.size() && Data[Idx]->hasFunction(S); 992 } 993 994 void printLeft(OutputStream &S) const override { 995 initializePackExpansion(S); 996 size_t Idx = S.CurrentPackIndex; 997 if (Idx < Data.size()) 998 Data[Idx]->printLeft(S); 999 } 1000 void printRight(OutputStream &S) const override { 1001 initializePackExpansion(S); 1002 size_t Idx = S.CurrentPackIndex; 1003 if (Idx < Data.size()) 1004 Data[Idx]->printRight(S); 1005 } 1006 }; 1007 1008 /// A variadic template argument. This node represents an occurance of 1009 /// J<something>E in some <template-args>. It isn't itself unexpanded, unless 1010 /// one of it's Elements is. The parser inserts a ParameterPack into the 1011 /// TemplateParams table if the <template-args> this pack belongs to apply to an 1012 /// <encoding>. 1013 class TemplateArgumentPack final : public Node { 1014 NodeArray Elements; 1015 public: 1016 TemplateArgumentPack(NodeArray Elements_) 1017 : Node(KTemplateArgumentPack), Elements(Elements_) {} 1018 1019 NodeArray getElements() const { return Elements; } 1020 1021 void printLeft(OutputStream &S) const override { 1022 Elements.printWithComma(S); 1023 } 1024 }; 1025 1026 /// A pack expansion. Below this node, there are some unexpanded ParameterPacks 1027 /// which each have Child->ParameterPackSize elements. 1028 class ParameterPackExpansion final : public Node { 1029 const Node *Child; 1030 1031 public: 1032 ParameterPackExpansion(Node* Child_) 1033 : Node(KParameterPackExpansion), Child(Child_) {} 1034 1035 const Node *getChild() const { return Child; } 1036 1037 void printLeft(OutputStream &S) const override { 1038 constexpr unsigned Max = std::numeric_limits<unsigned>::max(); 1039 SwapAndRestore<unsigned> SavePackIdx(S.CurrentPackIndex, Max); 1040 SwapAndRestore<unsigned> SavePackMax(S.CurrentPackMax, Max); 1041 size_t StreamPos = S.getCurrentPosition(); 1042 1043 // Print the first element in the pack. If Child contains a ParameterPack, 1044 // it will set up S.CurrentPackMax and print the first element. 1045 Child->print(S); 1046 1047 // No ParameterPack was found in Child. This can occur if we've found a pack 1048 // expansion on a <function-param>. 1049 if (S.CurrentPackMax == Max) { 1050 S += "..."; 1051 return; 1052 } 1053 1054 // We found a ParameterPack, but it has no elements. Erase whatever we may 1055 // of printed. 1056 if (S.CurrentPackMax == 0) { 1057 S.setCurrentPosition(StreamPos); 1058 return; 1059 } 1060 1061 // Else, iterate through the rest of the elements in the pack. 1062 for (unsigned I = 1, E = S.CurrentPackMax; I < E; ++I) { 1063 S += ", "; 1064 S.CurrentPackIndex = I; 1065 Child->print(S); 1066 } 1067 } 1068 }; 1069 1070 class TemplateArgs final : public Node { 1071 NodeArray Params; 1072 1073 public: 1074 TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {} 1075 1076 NodeArray getParams() { return Params; } 1077 1078 void printLeft(OutputStream &S) const override { 1079 S += "<"; 1080 Params.printWithComma(S); 1081 if (S.back() == '>') 1082 S += " "; 1083 S += ">"; 1084 } 1085 }; 1086 1087 struct ForwardTemplateReference : Node { 1088 size_t Index; 1089 Node *Ref = nullptr; 1090 1091 ForwardTemplateReference(size_t Index_) 1092 : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown, 1093 Cache::Unknown), 1094 Index(Index_) {} 1095 1096 bool hasRHSComponentSlow(OutputStream &S) const override { 1097 return Ref->hasRHSComponent(S); 1098 } 1099 bool hasArraySlow(OutputStream &S) const override { 1100 return Ref->hasArray(S); 1101 } 1102 bool hasFunctionSlow(OutputStream &S) const override { 1103 return Ref->hasFunction(S); 1104 } 1105 1106 void printLeft(OutputStream &S) const override { Ref->printLeft(S); } 1107 void printRight(OutputStream &S) const override { Ref->printRight(S); } 1108 }; 1109 1110 class NameWithTemplateArgs final : public Node { 1111 // name<template_args> 1112 Node *Name; 1113 Node *TemplateArgs; 1114 1115 public: 1116 NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_) 1117 : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {} 1118 1119 StringView getBaseName() const override { return Name->getBaseName(); } 1120 1121 void printLeft(OutputStream &S) const override { 1122 Name->print(S); 1123 TemplateArgs->print(S); 1124 } 1125 }; 1126 1127 class GlobalQualifiedName final : public Node { 1128 Node *Child; 1129 1130 public: 1131 GlobalQualifiedName(Node* Child_) 1132 : Node(KGlobalQualifiedName), Child(Child_) {} 1133 1134 StringView getBaseName() const override { return Child->getBaseName(); } 1135 1136 void printLeft(OutputStream &S) const override { 1137 S += "::"; 1138 Child->print(S); 1139 } 1140 }; 1141 1142 class StdQualifiedName final : public Node { 1143 Node *Child; 1144 1145 public: 1146 StdQualifiedName(Node *Child_) : Node(KStdQualifiedName), Child(Child_) {} 1147 1148 StringView getBaseName() const override { return Child->getBaseName(); } 1149 1150 void printLeft(OutputStream &S) const override { 1151 S += "std::"; 1152 Child->print(S); 1153 } 1154 }; 1155 1156 enum class SpecialSubKind { 1157 allocator, 1158 basic_string, 1159 string, 1160 istream, 1161 ostream, 1162 iostream, 1163 }; 1164 1165 class ExpandedSpecialSubstitution final : public Node { 1166 SpecialSubKind SSK; 1167 1168 public: 1169 ExpandedSpecialSubstitution(SpecialSubKind SSK_) 1170 : Node(KExpandedSpecialSubstitution), SSK(SSK_) {} 1171 1172 StringView getBaseName() const override { 1173 switch (SSK) { 1174 case SpecialSubKind::allocator: 1175 return StringView("allocator"); 1176 case SpecialSubKind::basic_string: 1177 return StringView("basic_string"); 1178 case SpecialSubKind::string: 1179 return StringView("basic_string"); 1180 case SpecialSubKind::istream: 1181 return StringView("basic_istream"); 1182 case SpecialSubKind::ostream: 1183 return StringView("basic_ostream"); 1184 case SpecialSubKind::iostream: 1185 return StringView("basic_iostream"); 1186 } 1187 LLVM_BUILTIN_UNREACHABLE; 1188 } 1189 1190 void printLeft(OutputStream &S) const override { 1191 switch (SSK) { 1192 case SpecialSubKind::allocator: 1193 S += "std::basic_string<char, std::char_traits<char>, " 1194 "std::allocator<char> >"; 1195 break; 1196 case SpecialSubKind::basic_string: 1197 case SpecialSubKind::string: 1198 S += "std::basic_string<char, std::char_traits<char>, " 1199 "std::allocator<char> >"; 1200 break; 1201 case SpecialSubKind::istream: 1202 S += "std::basic_istream<char, std::char_traits<char> >"; 1203 break; 1204 case SpecialSubKind::ostream: 1205 S += "std::basic_ostream<char, std::char_traits<char> >"; 1206 break; 1207 case SpecialSubKind::iostream: 1208 S += "std::basic_iostream<char, std::char_traits<char> >"; 1209 break; 1210 } 1211 } 1212 }; 1213 1214 class SpecialSubstitution final : public Node { 1215 public: 1216 SpecialSubKind SSK; 1217 1218 SpecialSubstitution(SpecialSubKind SSK_) 1219 : Node(KSpecialSubstitution), SSK(SSK_) {} 1220 1221 StringView getBaseName() const override { 1222 switch (SSK) { 1223 case SpecialSubKind::allocator: 1224 return StringView("allocator"); 1225 case SpecialSubKind::basic_string: 1226 return StringView("basic_string"); 1227 case SpecialSubKind::string: 1228 return StringView("string"); 1229 case SpecialSubKind::istream: 1230 return StringView("istream"); 1231 case SpecialSubKind::ostream: 1232 return StringView("ostream"); 1233 case SpecialSubKind::iostream: 1234 return StringView("iostream"); 1235 } 1236 LLVM_BUILTIN_UNREACHABLE; 1237 } 1238 1239 void printLeft(OutputStream &S) const override { 1240 switch (SSK) { 1241 case SpecialSubKind::allocator: 1242 S += "std::allocator"; 1243 break; 1244 case SpecialSubKind::basic_string: 1245 S += "std::basic_string"; 1246 break; 1247 case SpecialSubKind::string: 1248 S += "std::string"; 1249 break; 1250 case SpecialSubKind::istream: 1251 S += "std::istream"; 1252 break; 1253 case SpecialSubKind::ostream: 1254 S += "std::ostream"; 1255 break; 1256 case SpecialSubKind::iostream: 1257 S += "std::iostream"; 1258 break; 1259 } 1260 } 1261 }; 1262 1263 class CtorDtorName final : public Node { 1264 const Node *Basename; 1265 const bool IsDtor; 1266 1267 public: 1268 CtorDtorName(Node *Basename_, bool IsDtor_) 1269 : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_) {} 1270 1271 void printLeft(OutputStream &S) const override { 1272 if (IsDtor) 1273 S += "~"; 1274 S += Basename->getBaseName(); 1275 } 1276 }; 1277 1278 class DtorName : public Node { 1279 const Node *Base; 1280 1281 public: 1282 DtorName(Node *Base_) : Node(KDtorName), Base(Base_) {} 1283 1284 void printLeft(OutputStream &S) const override { 1285 S += "~"; 1286 Base->printLeft(S); 1287 } 1288 }; 1289 1290 class UnnamedTypeName : public Node { 1291 const StringView Count; 1292 1293 public: 1294 UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {} 1295 1296 void printLeft(OutputStream &S) const override { 1297 S += "'unnamed"; 1298 S += Count; 1299 S += "\'"; 1300 } 1301 }; 1302 1303 class ClosureTypeName : public Node { 1304 NodeArray Params; 1305 StringView Count; 1306 1307 public: 1308 ClosureTypeName(NodeArray Params_, StringView Count_) 1309 : Node(KClosureTypeName), Params(Params_), Count(Count_) {} 1310 1311 void printLeft(OutputStream &S) const override { 1312 S += "\'lambda"; 1313 S += Count; 1314 S += "\'("; 1315 Params.printWithComma(S); 1316 S += ")"; 1317 } 1318 }; 1319 1320 class StructuredBindingName : public Node { 1321 NodeArray Bindings; 1322 public: 1323 StructuredBindingName(NodeArray Bindings_) 1324 : Node(KStructuredBindingName), Bindings(Bindings_) {} 1325 1326 void printLeft(OutputStream &S) const override { 1327 S += '['; 1328 Bindings.printWithComma(S); 1329 S += ']'; 1330 } 1331 }; 1332 1333 // -- Expression Nodes -- 1334 1335 struct Expr : public Node { 1336 Expr(Kind K = KExpr) : Node(K) {} 1337 }; 1338 1339 class BinaryExpr : public Expr { 1340 const Node *LHS; 1341 const StringView InfixOperator; 1342 const Node *RHS; 1343 1344 public: 1345 BinaryExpr(Node *LHS_, StringView InfixOperator_, Node *RHS_) 1346 : LHS(LHS_), InfixOperator(InfixOperator_), RHS(RHS_) {} 1347 1348 void printLeft(OutputStream &S) const override { 1349 // might be a template argument expression, then we need to disambiguate 1350 // with parens. 1351 if (InfixOperator == ">") 1352 S += "("; 1353 1354 S += "("; 1355 LHS->print(S); 1356 S += ") "; 1357 S += InfixOperator; 1358 S += " ("; 1359 RHS->print(S); 1360 S += ")"; 1361 1362 if (InfixOperator == ">") 1363 S += ")"; 1364 } 1365 }; 1366 1367 class ArraySubscriptExpr : public Expr { 1368 const Node *Op1; 1369 const Node *Op2; 1370 1371 public: 1372 ArraySubscriptExpr(Node *Op1_, Node *Op2_) : Op1(Op1_), Op2(Op2_) {} 1373 1374 void printLeft(OutputStream &S) const override { 1375 S += "("; 1376 Op1->print(S); 1377 S += ")["; 1378 Op2->print(S); 1379 S += "]"; 1380 } 1381 }; 1382 1383 class PostfixExpr : public Expr { 1384 const Node *Child; 1385 const StringView Operand; 1386 1387 public: 1388 PostfixExpr(Node *Child_, StringView Operand_) 1389 : Child(Child_), Operand(Operand_) {} 1390 1391 void printLeft(OutputStream &S) const override { 1392 S += "("; 1393 Child->print(S); 1394 S += ")"; 1395 S += Operand; 1396 } 1397 }; 1398 1399 class ConditionalExpr : public Expr { 1400 const Node *Cond; 1401 const Node *Then; 1402 const Node *Else; 1403 1404 public: 1405 ConditionalExpr(Node *Cond_, Node *Then_, Node *Else_) 1406 : Cond(Cond_), Then(Then_), Else(Else_) {} 1407 1408 void printLeft(OutputStream &S) const override { 1409 S += "("; 1410 Cond->print(S); 1411 S += ") ? ("; 1412 Then->print(S); 1413 S += ") : ("; 1414 Else->print(S); 1415 S += ")"; 1416 } 1417 }; 1418 1419 class MemberExpr : public Expr { 1420 const Node *LHS; 1421 const StringView Kind; 1422 const Node *RHS; 1423 1424 public: 1425 MemberExpr(Node *LHS_, StringView Kind_, Node *RHS_) 1426 : LHS(LHS_), Kind(Kind_), RHS(RHS_) {} 1427 1428 void printLeft(OutputStream &S) const override { 1429 LHS->print(S); 1430 S += Kind; 1431 RHS->print(S); 1432 } 1433 }; 1434 1435 class EnclosingExpr : public Expr { 1436 const StringView Prefix; 1437 const Node *Infix; 1438 const StringView Postfix; 1439 1440 public: 1441 EnclosingExpr(StringView Prefix_, Node *Infix_, StringView Postfix_) 1442 : Prefix(Prefix_), Infix(Infix_), Postfix(Postfix_) {} 1443 1444 void printLeft(OutputStream &S) const override { 1445 S += Prefix; 1446 Infix->print(S); 1447 S += Postfix; 1448 } 1449 }; 1450 1451 class CastExpr : public Expr { 1452 // cast_kind<to>(from) 1453 const StringView CastKind; 1454 const Node *To; 1455 const Node *From; 1456 1457 public: 1458 CastExpr(StringView CastKind_, Node *To_, Node *From_) 1459 : CastKind(CastKind_), To(To_), From(From_) {} 1460 1461 void printLeft(OutputStream &S) const override { 1462 S += CastKind; 1463 S += "<"; 1464 To->printLeft(S); 1465 S += ">("; 1466 From->printLeft(S); 1467 S += ")"; 1468 } 1469 }; 1470 1471 class SizeofParamPackExpr : public Expr { 1472 Node *Pack; 1473 1474 public: 1475 SizeofParamPackExpr(Node *Pack_) : Pack(Pack_) {} 1476 1477 void printLeft(OutputStream &S) const override { 1478 S += "sizeof...("; 1479 ParameterPackExpansion PPE(Pack); 1480 PPE.printLeft(S); 1481 S += ")"; 1482 } 1483 }; 1484 1485 class CallExpr : public Expr { 1486 const Node *Callee; 1487 NodeArray Args; 1488 1489 public: 1490 CallExpr(Node *Callee_, NodeArray Args_) : Callee(Callee_), Args(Args_) {} 1491 1492 void printLeft(OutputStream &S) const override { 1493 Callee->print(S); 1494 S += "("; 1495 Args.printWithComma(S); 1496 S += ")"; 1497 } 1498 }; 1499 1500 class NewExpr : public Expr { 1501 // new (expr_list) type(init_list) 1502 NodeArray ExprList; 1503 Node *Type; 1504 NodeArray InitList; 1505 bool IsGlobal; // ::operator new ? 1506 bool IsArray; // new[] ? 1507 public: 1508 NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_, 1509 bool IsArray_) 1510 : ExprList(ExprList_), Type(Type_), InitList(InitList_), 1511 IsGlobal(IsGlobal_), IsArray(IsArray_) {} 1512 1513 void printLeft(OutputStream &S) const override { 1514 if (IsGlobal) 1515 S += "::operator "; 1516 S += "new"; 1517 if (IsArray) 1518 S += "[]"; 1519 S += ' '; 1520 if (!ExprList.empty()) { 1521 S += "("; 1522 ExprList.printWithComma(S); 1523 S += ")"; 1524 } 1525 Type->print(S); 1526 if (!InitList.empty()) { 1527 S += "("; 1528 InitList.printWithComma(S); 1529 S += ")"; 1530 } 1531 1532 } 1533 }; 1534 1535 class DeleteExpr : public Expr { 1536 Node *Op; 1537 bool IsGlobal; 1538 bool IsArray; 1539 1540 public: 1541 DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_) 1542 : Op(Op_), IsGlobal(IsGlobal_), IsArray(IsArray_) {} 1543 1544 void printLeft(OutputStream &S) const override { 1545 if (IsGlobal) 1546 S += "::"; 1547 S += "delete"; 1548 if (IsArray) 1549 S += "[] "; 1550 Op->print(S); 1551 } 1552 }; 1553 1554 class PrefixExpr : public Expr { 1555 StringView Prefix; 1556 Node *Child; 1557 1558 public: 1559 PrefixExpr(StringView Prefix_, Node *Child_) : Prefix(Prefix_), Child(Child_) {} 1560 1561 void printLeft(OutputStream &S) const override { 1562 S += Prefix; 1563 S += "("; 1564 Child->print(S); 1565 S += ")"; 1566 } 1567 }; 1568 1569 class FunctionParam : public Expr { 1570 StringView Number; 1571 1572 public: 1573 FunctionParam(StringView Number_) : Number(Number_) {} 1574 1575 void printLeft(OutputStream &S) const override { 1576 S += "fp"; 1577 S += Number; 1578 } 1579 }; 1580 1581 class ConversionExpr : public Expr { 1582 const Node *Type; 1583 NodeArray Expressions; 1584 1585 public: 1586 ConversionExpr(const Node *Type_, NodeArray Expressions_) 1587 : Type(Type_), Expressions(Expressions_) {} 1588 1589 void printLeft(OutputStream &S) const override { 1590 S += "("; 1591 Type->print(S); 1592 S += ")("; 1593 Expressions.printWithComma(S); 1594 S += ")"; 1595 } 1596 }; 1597 1598 class InitListExpr : public Expr { 1599 Node *Ty; 1600 NodeArray Inits; 1601 public: 1602 InitListExpr(Node *Ty_, NodeArray Inits_) : Ty(Ty_), Inits(Inits_) {} 1603 1604 void printLeft(OutputStream &S) const override { 1605 if (Ty) 1606 Ty->print(S); 1607 S += '{'; 1608 Inits.printWithComma(S); 1609 S += '}'; 1610 } 1611 }; 1612 1613 class BracedExpr : public Expr { 1614 Node *Elem; 1615 Node *Init; 1616 bool IsArray; 1617 public: 1618 BracedExpr(Node *Elem_, Node *Init_, bool IsArray_) 1619 : Expr(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {} 1620 1621 void printLeft(OutputStream &S) const override { 1622 if (IsArray) { 1623 S += '['; 1624 Elem->print(S); 1625 S += ']'; 1626 } else { 1627 S += '.'; 1628 Elem->print(S); 1629 } 1630 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr) 1631 S += " = "; 1632 Init->print(S); 1633 } 1634 }; 1635 1636 class BracedRangeExpr : public Expr { 1637 Node *First; 1638 Node *Last; 1639 Node *Init; 1640 public: 1641 BracedRangeExpr(Node *First_, Node *Last_, Node *Init_) 1642 : Expr(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {} 1643 1644 void printLeft(OutputStream &S) const override { 1645 S += '['; 1646 First->print(S); 1647 S += " ... "; 1648 Last->print(S); 1649 S += ']'; 1650 if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr) 1651 S += " = "; 1652 Init->print(S); 1653 } 1654 }; 1655 1656 class ThrowExpr : public Expr { 1657 const Node *Op; 1658 1659 public: 1660 ThrowExpr(Node *Op_) : Op(Op_) {} 1661 1662 void printLeft(OutputStream &S) const override { 1663 S += "throw "; 1664 Op->print(S); 1665 } 1666 }; 1667 1668 class BoolExpr : public Expr { 1669 bool Value; 1670 1671 public: 1672 BoolExpr(bool Value_) : Value(Value_) {} 1673 1674 void printLeft(OutputStream &S) const override { 1675 S += Value ? StringView("true") : StringView("false"); 1676 } 1677 }; 1678 1679 class IntegerCastExpr : public Expr { 1680 // ty(integer) 1681 Node *Ty; 1682 StringView Integer; 1683 1684 public: 1685 IntegerCastExpr(Node *Ty_, StringView Integer_) 1686 : Ty(Ty_), Integer(Integer_) {} 1687 1688 void printLeft(OutputStream &S) const override { 1689 S += "("; 1690 Ty->print(S); 1691 S += ")"; 1692 S += Integer; 1693 } 1694 }; 1695 1696 class IntegerExpr : public Expr { 1697 StringView Type; 1698 StringView Value; 1699 1700 public: 1701 IntegerExpr(StringView Type_, StringView Value_) : Type(Type_), Value(Value_) {} 1702 1703 void printLeft(OutputStream &S) const override { 1704 if (Type.size() > 3) { 1705 S += "("; 1706 S += Type; 1707 S += ")"; 1708 } 1709 1710 if (Value[0] == 'n') { 1711 S += "-"; 1712 S += Value.dropFront(1); 1713 } else 1714 S += Value; 1715 1716 if (Type.size() <= 3) 1717 S += Type; 1718 } 1719 }; 1720 1721 template <class Float> struct FloatData; 1722 1723 template <class Float> class FloatExpr : public Expr { 1724 const StringView Contents; 1725 1726 public: 1727 FloatExpr(StringView Contents_) : Contents(Contents_) {} 1728 1729 void printLeft(OutputStream &s) const override { 1730 const char *first = Contents.begin(); 1731 const char *last = Contents.end() + 1; 1732 1733 const size_t N = FloatData<Float>::mangled_size; 1734 if (static_cast<std::size_t>(last - first) > N) { 1735 last = first + N; 1736 union { 1737 Float value; 1738 char buf[sizeof(Float)]; 1739 }; 1740 const char *t = first; 1741 char *e = buf; 1742 for (; t != last; ++t, ++e) { 1743 unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0') 1744 : static_cast<unsigned>(*t - 'a' + 10); 1745 ++t; 1746 unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0') 1747 : static_cast<unsigned>(*t - 'a' + 10); 1748 *e = static_cast<char>((d1 << 4) + d0); 1749 } 1750 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ 1751 std::reverse(buf, e); 1752 #endif 1753 char num[FloatData<Float>::max_demangled_size] = {0}; 1754 int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value); 1755 s += StringView(num, num + n); 1756 } 1757 } 1758 }; 1759 1760 class BumpPointerAllocator { 1761 struct BlockMeta { 1762 BlockMeta* Next; 1763 size_t Current; 1764 }; 1765 1766 static constexpr size_t AllocSize = 4096; 1767 static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta); 1768 1769 alignas(16) char InitialBuffer[AllocSize]; 1770 BlockMeta* BlockList = nullptr; 1771 1772 void grow() { 1773 char* NewMeta = new char[AllocSize]; 1774 BlockList = new (NewMeta) BlockMeta{BlockList, 0}; 1775 } 1776 1777 void* allocateMassive(size_t NBytes) { 1778 NBytes += sizeof(BlockMeta); 1779 BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(new char[NBytes]); 1780 BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0}; 1781 return static_cast<void*>(NewMeta + 1); 1782 } 1783 1784 public: 1785 BumpPointerAllocator() 1786 : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {} 1787 1788 void* allocate(size_t N) { 1789 N = (N + 15u) & ~15u; 1790 if (N + BlockList->Current >= UsableAllocSize) { 1791 if (N > UsableAllocSize) 1792 return allocateMassive(N); 1793 grow(); 1794 } 1795 BlockList->Current += N; 1796 return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) + 1797 BlockList->Current - N); 1798 } 1799 1800 ~BumpPointerAllocator() { 1801 while (BlockList) { 1802 BlockMeta* Tmp = BlockList; 1803 BlockList = BlockList->Next; 1804 if (reinterpret_cast<char*>(Tmp) != InitialBuffer) 1805 delete[] reinterpret_cast<char*>(Tmp); 1806 } 1807 } 1808 }; 1809 1810 template <class T, size_t N> 1811 class PODSmallVector { 1812 static_assert(std::is_pod<T>::value, 1813 "T is required to be a plain old data type"); 1814 1815 T* First; 1816 T* Last; 1817 T* Cap; 1818 T Inline[N]; 1819 1820 bool isInline() const { return First == Inline; } 1821 1822 void clearInline() { 1823 First = Inline; 1824 Last = Inline; 1825 Cap = Inline + N; 1826 } 1827 1828 void reserve(size_t NewCap) { 1829 size_t S = size(); 1830 if (isInline()) { 1831 auto* Tmp = static_cast<T*>(std::malloc(NewCap * sizeof(T))); 1832 std::copy(First, Last, Tmp); 1833 First = Tmp; 1834 } else 1835 First = static_cast<T*>(std::realloc(First, NewCap * sizeof(T))); 1836 Last = First + S; 1837 Cap = First + NewCap; 1838 } 1839 1840 public: 1841 PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {} 1842 1843 PODSmallVector(const PODSmallVector&) = delete; 1844 PODSmallVector& operator=(const PODSmallVector&) = delete; 1845 1846 PODSmallVector(PODSmallVector&& Other) : PODSmallVector() { 1847 if (Other.isInline()) { 1848 std::copy(Other.begin(), Other.end(), First); 1849 Last = First + Other.size(); 1850 Other.clear(); 1851 return; 1852 } 1853 1854 First = Other.First; 1855 Last = Other.Last; 1856 Cap = Other.Cap; 1857 Other.clearInline(); 1858 } 1859 1860 PODSmallVector& operator=(PODSmallVector&& Other) { 1861 if (Other.isInline()) { 1862 if (!isInline()) { 1863 std::free(First); 1864 clearInline(); 1865 } 1866 std::copy(Other.begin(), Other.end(), First); 1867 Last = First + Other.size(); 1868 Other.clear(); 1869 return *this; 1870 } 1871 1872 if (isInline()) { 1873 First = Other.First; 1874 Last = Other.Last; 1875 Cap = Other.Cap; 1876 Other.clearInline(); 1877 return *this; 1878 } 1879 1880 std::swap(First, Other.First); 1881 std::swap(Last, Other.Last); 1882 std::swap(Cap, Other.Cap); 1883 Other.clear(); 1884 return *this; 1885 } 1886 1887 void push_back(const T& Elem) { 1888 if (Last == Cap) 1889 reserve(size() * 2); 1890 *Last++ = Elem; 1891 } 1892 1893 void pop_back() { 1894 assert(Last != First && "Popping empty vector!"); 1895 --Last; 1896 } 1897 1898 void dropBack(size_t Index) { 1899 assert(Index <= size() && "dropBack() can't expand!"); 1900 Last = First + Index; 1901 } 1902 1903 T* begin() { return First; } 1904 T* end() { return Last; } 1905 1906 bool empty() const { return First == Last; } 1907 size_t size() const { return static_cast<size_t>(Last - First); } 1908 T& back() { 1909 assert(Last != First && "Calling back() on empty vector!"); 1910 return *(Last - 1); 1911 } 1912 T& operator[](size_t Index) { 1913 assert(Index < size() && "Invalid access!"); 1914 return *(begin() + Index); 1915 } 1916 void clear() { Last = First; } 1917 1918 ~PODSmallVector() { 1919 if (!isInline()) 1920 std::free(First); 1921 } 1922 }; 1923 1924 struct Db { 1925 const char *First; 1926 const char *Last; 1927 1928 // Name stack, this is used by the parser to hold temporary names that were 1929 // parsed. The parser colapses multiple names into new nodes to construct 1930 // the AST. Once the parser is finished, names.size() == 1. 1931 PODSmallVector<Node *, 32> Names; 1932 1933 // Substitution table. Itanium supports name substitutions as a means of 1934 // compression. The string "S42_" refers to the 44nd entry (base-36) in this 1935 // table. 1936 PODSmallVector<Node *, 32> Subs; 1937 1938 // Template parameter table. Like the above, but referenced like "T42_". 1939 // This has a smaller size compared to Subs and Names because it can be 1940 // stored on the stack. 1941 PODSmallVector<Node *, 8> TemplateParams; 1942 1943 // Set of unresolved forward <template-param> references. These can occur in a 1944 // conversion operator's type, and are resolved in the enclosing <encoding>. 1945 PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs; 1946 1947 bool TryToParseTemplateArgs = true; 1948 bool PermitForwardTemplateReferences = false; 1949 bool ParsingLambdaParams = false; 1950 1951 BumpPointerAllocator ASTAllocator; 1952 1953 Db(const char *First_, const char *Last_) : First(First_), Last(Last_) {} 1954 1955 template <class T, class... Args> T *make(Args &&... args) { 1956 return new (ASTAllocator.allocate(sizeof(T))) 1957 T(std::forward<Args>(args)...); 1958 } 1959 1960 template <class It> NodeArray makeNodeArray(It begin, It end) { 1961 size_t sz = static_cast<size_t>(end - begin); 1962 void *mem = ASTAllocator.allocate(sizeof(Node *) * sz); 1963 Node **data = new (mem) Node *[sz]; 1964 std::copy(begin, end, data); 1965 return NodeArray(data, sz); 1966 } 1967 1968 NodeArray popTrailingNodeArray(size_t FromPosition) { 1969 assert(FromPosition <= Names.size()); 1970 NodeArray res = 1971 makeNodeArray(Names.begin() + (long)FromPosition, Names.end()); 1972 Names.dropBack(FromPosition); 1973 return res; 1974 } 1975 1976 bool consumeIf(StringView S) { 1977 if (StringView(First, Last).startsWith(S)) { 1978 First += S.size(); 1979 return true; 1980 } 1981 return false; 1982 } 1983 1984 bool consumeIf(char C) { 1985 if (First != Last && *First == C) { 1986 ++First; 1987 return true; 1988 } 1989 return false; 1990 } 1991 1992 char consume() { return First != Last ? *First++ : '\0'; } 1993 1994 char look(unsigned Lookahead = 0) { 1995 if (static_cast<size_t>(Last - First) <= Lookahead) 1996 return '\0'; 1997 return First[Lookahead]; 1998 } 1999 2000 size_t numLeft() const { return static_cast<size_t>(Last - First); } 2001 2002 StringView parseNumber(bool AllowNegative = false); 2003 Qualifiers parseCVQualifiers(); 2004 bool parsePositiveInteger(size_t *Out); 2005 StringView parseBareSourceName(); 2006 2007 bool parseSeqId(size_t *Out); 2008 Node *parseSubstitution(); 2009 Node *parseTemplateParam(); 2010 Node *parseTemplateArgs(bool TagTemplates = false); 2011 Node *parseTemplateArg(); 2012 2013 /// Parse the <expr> production. 2014 Node *parseExpr(); 2015 Node *parsePrefixExpr(StringView Kind); 2016 Node *parseBinaryExpr(StringView Kind); 2017 Node *parseIntegerLiteral(StringView Lit); 2018 Node *parseExprPrimary(); 2019 template <class Float> Node *parseFloatingLiteral(); 2020 Node *parseFunctionParam(); 2021 Node *parseNewExpr(); 2022 Node *parseConversionExpr(); 2023 Node *parseBracedExpr(); 2024 2025 /// Parse the <type> production. 2026 Node *parseType(); 2027 Node *parseFunctionType(); 2028 Node *parseVectorType(); 2029 Node *parseDecltype(); 2030 Node *parseArrayType(); 2031 Node *parsePointerToMemberType(); 2032 Node *parseClassEnumType(); 2033 Node *parseQualifiedType(); 2034 2035 Node *parseEncoding(); 2036 bool parseCallOffset(); 2037 Node *parseSpecialName(); 2038 2039 /// Holds some extra information about a <name> that is being parsed. This 2040 /// information is only pertinent if the <name> refers to an <encoding>. 2041 struct NameState { 2042 bool CtorDtorConversion = false; 2043 bool EndsWithTemplateArgs = false; 2044 Qualifiers CVQualifiers = QualNone; 2045 FunctionRefQual ReferenceQualifier = FrefQualNone; 2046 size_t ForwardTemplateRefsBegin; 2047 2048 NameState(Db *Enclosing) 2049 : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {} 2050 }; 2051 2052 bool resolveForwardTemplateRefs(NameState &State) { 2053 size_t I = State.ForwardTemplateRefsBegin; 2054 size_t E = ForwardTemplateRefs.size(); 2055 for (; I < E; ++I) { 2056 size_t Idx = ForwardTemplateRefs[I]->Index; 2057 if (Idx >= TemplateParams.size()) 2058 return true; 2059 ForwardTemplateRefs[I]->Ref = TemplateParams[Idx]; 2060 } 2061 ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin); 2062 return false; 2063 } 2064 2065 /// Parse the <name> production> 2066 Node *parseName(NameState *State = nullptr); 2067 Node *parseLocalName(NameState *State); 2068 Node *parseOperatorName(NameState *State); 2069 Node *parseUnqualifiedName(NameState *State); 2070 Node *parseUnnamedTypeName(NameState *State); 2071 Node *parseSourceName(NameState *State); 2072 Node *parseUnscopedName(NameState *State); 2073 Node *parseNestedName(NameState *State); 2074 Node *parseCtorDtorName(Node *&SoFar, NameState *State); 2075 2076 Node *parseAbiTags(Node *N); 2077 2078 /// Parse the <unresolved-name> production. 2079 Node *parseUnresolvedName(); 2080 Node *parseSimpleId(); 2081 Node *parseBaseUnresolvedName(); 2082 Node *parseUnresolvedType(); 2083 Node *parseDestructorName(); 2084 2085 /// Top-level entry point into the parser. 2086 Node *parse(); 2087 }; 2088 2089 const char* parse_discriminator(const char* first, const char* last); 2090 2091 // <name> ::= <nested-name> // N 2092 // ::= <local-name> # See Scope Encoding below // Z 2093 // ::= <unscoped-template-name> <template-args> 2094 // ::= <unscoped-name> 2095 // 2096 // <unscoped-template-name> ::= <unscoped-name> 2097 // ::= <substitution> 2098 Node *Db::parseName(NameState *State) { 2099 consumeIf('L'); // extension 2100 2101 if (look() == 'N') 2102 return parseNestedName(State); 2103 if (look() == 'Z') 2104 return parseLocalName(State); 2105 2106 // ::= <unscoped-template-name> <template-args> 2107 if (look() == 'S' && look(1) != 't') { 2108 Node *S = parseSubstitution(); 2109 if (S == nullptr) 2110 return nullptr; 2111 if (look() != 'I') 2112 return nullptr; 2113 Node *TA = parseTemplateArgs(State != nullptr); 2114 if (TA == nullptr) 2115 return nullptr; 2116 if (State) State->EndsWithTemplateArgs = true; 2117 return make<NameWithTemplateArgs>(S, TA); 2118 } 2119 2120 Node *N = parseUnscopedName(State); 2121 if (N == nullptr) 2122 return nullptr; 2123 // ::= <unscoped-template-name> <template-args> 2124 if (look() == 'I') { 2125 Subs.push_back(N); 2126 Node *TA = parseTemplateArgs(State != nullptr); 2127 if (TA == nullptr) 2128 return nullptr; 2129 if (State) State->EndsWithTemplateArgs = true; 2130 return make<NameWithTemplateArgs>(N, TA); 2131 } 2132 // ::= <unscoped-name> 2133 return N; 2134 } 2135 2136 // <local-name> := Z <function encoding> E <entity name> [<discriminator>] 2137 // := Z <function encoding> E s [<discriminator>] 2138 // := Z <function encoding> Ed [ <parameter number> ] _ <entity name> 2139 Node *Db::parseLocalName(NameState *State) { 2140 if (!consumeIf('Z')) 2141 return nullptr; 2142 Node *Encoding = parseEncoding(); 2143 if (Encoding == nullptr || !consumeIf('E')) 2144 return nullptr; 2145 2146 if (consumeIf('s')) { 2147 First = parse_discriminator(First, Last); 2148 return make<QualifiedName>(Encoding, make<NameType>("string literal")); 2149 } 2150 2151 if (consumeIf('d')) { 2152 parseNumber(true); 2153 if (!consumeIf('_')) 2154 return nullptr; 2155 Node *N = parseName(State); 2156 if (N == nullptr) 2157 return nullptr; 2158 return make<QualifiedName>(Encoding, N); 2159 } 2160 2161 Node *Entity = parseName(State); 2162 if (Entity == nullptr) 2163 return nullptr; 2164 First = parse_discriminator(First, Last); 2165 return make<QualifiedName>(Encoding, Entity); 2166 } 2167 2168 // <unscoped-name> ::= <unqualified-name> 2169 // ::= St <unqualified-name> # ::std:: 2170 // extension ::= StL<unqualified-name> 2171 Node *Db::parseUnscopedName(NameState *State) { 2172 if (consumeIf("StL") || consumeIf("St")) { 2173 Node *R = parseUnqualifiedName(State); 2174 if (R == nullptr) 2175 return nullptr; 2176 return make<StdQualifiedName>(R); 2177 } 2178 return parseUnqualifiedName(State); 2179 } 2180 2181 // <unqualified-name> ::= <operator-name> [abi-tags] 2182 // ::= <ctor-dtor-name> 2183 // ::= <source-name> 2184 // ::= <unnamed-type-name> 2185 // ::= DC <source-name>+ E # structured binding declaration 2186 Node *Db::parseUnqualifiedName(NameState *State) { 2187 // <ctor-dtor-name>s are special-cased in parseNestedName(). 2188 Node *Result; 2189 if (look() == 'U') 2190 Result = parseUnnamedTypeName(State); 2191 else if (look() >= '1' && look() <= '9') 2192 Result = parseSourceName(State); 2193 else if (consumeIf("DC")) { 2194 size_t BindingsBegin = Names.size(); 2195 do { 2196 Node *Binding = parseSourceName(State); 2197 if (Binding == nullptr) 2198 return nullptr; 2199 Names.push_back(Binding); 2200 } while (!consumeIf('E')); 2201 Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin)); 2202 } else 2203 Result = parseOperatorName(State); 2204 if (Result != nullptr) 2205 Result = parseAbiTags(Result); 2206 return Result; 2207 } 2208 2209 // <unnamed-type-name> ::= Ut [<nonnegative number>] _ 2210 // ::= <closure-type-name> 2211 // 2212 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ 2213 // 2214 // <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters 2215 Node *Db::parseUnnamedTypeName(NameState *) { 2216 if (consumeIf("Ut")) { 2217 StringView Count = parseNumber(); 2218 if (!consumeIf('_')) 2219 return nullptr; 2220 return make<UnnamedTypeName>(Count); 2221 } 2222 if (consumeIf("Ul")) { 2223 NodeArray Params; 2224 SwapAndRestore<bool> SwapParams(ParsingLambdaParams, true); 2225 if (!consumeIf("vE")) { 2226 size_t ParamsBegin = Names.size(); 2227 do { 2228 Node *P = parseType(); 2229 if (P == nullptr) 2230 return nullptr; 2231 Names.push_back(P); 2232 } while (!consumeIf('E')); 2233 Params = popTrailingNodeArray(ParamsBegin); 2234 } 2235 StringView Count = parseNumber(); 2236 if (!consumeIf('_')) 2237 return nullptr; 2238 return make<ClosureTypeName>(Params, Count); 2239 } 2240 return nullptr; 2241 } 2242 2243 // <source-name> ::= <positive length number> <identifier> 2244 Node *Db::parseSourceName(NameState *) { 2245 size_t Length = 0; 2246 if (parsePositiveInteger(&Length)) 2247 return nullptr; 2248 if (numLeft() < Length || Length == 0) 2249 return nullptr; 2250 StringView Name(First, First + Length); 2251 First += Length; 2252 if (Name.startsWith("_GLOBAL__N")) 2253 return make<NameType>("(anonymous namespace)"); 2254 return make<NameType>(Name); 2255 } 2256 2257 // <operator-name> ::= aa # && 2258 // ::= ad # & (unary) 2259 // ::= an # & 2260 // ::= aN # &= 2261 // ::= aS # = 2262 // ::= cl # () 2263 // ::= cm # , 2264 // ::= co # ~ 2265 // ::= cv <type> # (cast) 2266 // ::= da # delete[] 2267 // ::= de # * (unary) 2268 // ::= dl # delete 2269 // ::= dv # / 2270 // ::= dV # /= 2271 // ::= eo # ^ 2272 // ::= eO # ^= 2273 // ::= eq # == 2274 // ::= ge # >= 2275 // ::= gt # > 2276 // ::= ix # [] 2277 // ::= le # <= 2278 // ::= li <source-name> # operator "" 2279 // ::= ls # << 2280 // ::= lS # <<= 2281 // ::= lt # < 2282 // ::= mi # - 2283 // ::= mI # -= 2284 // ::= ml # * 2285 // ::= mL # *= 2286 // ::= mm # -- (postfix in <expression> context) 2287 // ::= na # new[] 2288 // ::= ne # != 2289 // ::= ng # - (unary) 2290 // ::= nt # ! 2291 // ::= nw # new 2292 // ::= oo # || 2293 // ::= or # | 2294 // ::= oR # |= 2295 // ::= pm # ->* 2296 // ::= pl # + 2297 // ::= pL # += 2298 // ::= pp # ++ (postfix in <expression> context) 2299 // ::= ps # + (unary) 2300 // ::= pt # -> 2301 // ::= qu # ? 2302 // ::= rm # % 2303 // ::= rM # %= 2304 // ::= rs # >> 2305 // ::= rS # >>= 2306 // ::= ss # <=> C++2a 2307 // ::= v <digit> <source-name> # vendor extended operator 2308 Node *Db::parseOperatorName(NameState *State) { 2309 switch (look()) { 2310 case 'a': 2311 switch (look(1)) { 2312 case 'a': 2313 First += 2; 2314 return make<NameType>("operator&&"); 2315 case 'd': 2316 case 'n': 2317 First += 2; 2318 return make<NameType>("operator&"); 2319 case 'N': 2320 First += 2; 2321 return make<NameType>("operator&="); 2322 case 'S': 2323 First += 2; 2324 return make<NameType>("operator="); 2325 } 2326 return nullptr; 2327 case 'c': 2328 switch (look(1)) { 2329 case 'l': 2330 First += 2; 2331 return make<NameType>("operator()"); 2332 case 'm': 2333 First += 2; 2334 return make<NameType>("operator,"); 2335 case 'o': 2336 First += 2; 2337 return make<NameType>("operator~"); 2338 // ::= cv <type> # (cast) 2339 case 'v': { 2340 First += 2; 2341 SwapAndRestore<bool> SaveTemplate(TryToParseTemplateArgs, false); 2342 // If we're parsing an encoding, State != nullptr and the conversion 2343 // operators' <type> could have a <template-param> that refers to some 2344 // <template-arg>s further ahead in the mangled name. 2345 SwapAndRestore<bool> SavePermit(PermitForwardTemplateReferences, 2346 PermitForwardTemplateReferences || 2347 State != nullptr); 2348 Node* Ty = parseType(); 2349 if (Ty == nullptr) 2350 return nullptr; 2351 if (State) State->CtorDtorConversion = true; 2352 return make<ConversionOperatorType>(Ty); 2353 } 2354 } 2355 return nullptr; 2356 case 'd': 2357 switch (look(1)) { 2358 case 'a': 2359 First += 2; 2360 return make<NameType>("operator delete[]"); 2361 case 'e': 2362 First += 2; 2363 return make<NameType>("operator*"); 2364 case 'l': 2365 First += 2; 2366 return make<NameType>("operator delete"); 2367 case 'v': 2368 First += 2; 2369 return make<NameType>("operator/"); 2370 case 'V': 2371 First += 2; 2372 return make<NameType>("operator/="); 2373 } 2374 return nullptr; 2375 case 'e': 2376 switch (look(1)) { 2377 case 'o': 2378 First += 2; 2379 return make<NameType>("operator^"); 2380 case 'O': 2381 First += 2; 2382 return make<NameType>("operator^="); 2383 case 'q': 2384 First += 2; 2385 return make<NameType>("operator=="); 2386 } 2387 return nullptr; 2388 case 'g': 2389 switch (look(1)) { 2390 case 'e': 2391 First += 2; 2392 return make<NameType>("operator>="); 2393 case 't': 2394 First += 2; 2395 return make<NameType>("operator>"); 2396 } 2397 return nullptr; 2398 case 'i': 2399 if (look(1) == 'x') { 2400 First += 2; 2401 return make<NameType>("operator[]"); 2402 } 2403 return nullptr; 2404 case 'l': 2405 switch (look(1)) { 2406 case 'e': 2407 First += 2; 2408 return make<NameType>("operator<="); 2409 // ::= li <source-name> # operator "" 2410 case 'i': { 2411 First += 2; 2412 Node *SN = parseSourceName(State); 2413 if (SN == nullptr) 2414 return nullptr; 2415 return make<LiteralOperator>(SN); 2416 } 2417 case 's': 2418 First += 2; 2419 return make<NameType>("operator<<"); 2420 case 'S': 2421 First += 2; 2422 return make<NameType>("operator<<="); 2423 case 't': 2424 First += 2; 2425 return make<NameType>("operator<"); 2426 } 2427 return nullptr; 2428 case 'm': 2429 switch (look(1)) { 2430 case 'i': 2431 First += 2; 2432 return make<NameType>("operator-"); 2433 case 'I': 2434 First += 2; 2435 return make<NameType>("operator-="); 2436 case 'l': 2437 First += 2; 2438 return make<NameType>("operator*"); 2439 case 'L': 2440 First += 2; 2441 return make<NameType>("operator*="); 2442 case 'm': 2443 First += 2; 2444 return make<NameType>("operator--"); 2445 } 2446 return nullptr; 2447 case 'n': 2448 switch (look(1)) { 2449 case 'a': 2450 First += 2; 2451 return make<NameType>("operator new[]"); 2452 case 'e': 2453 First += 2; 2454 return make<NameType>("operator!="); 2455 case 'g': 2456 First += 2; 2457 return make<NameType>("operator-"); 2458 case 't': 2459 First += 2; 2460 return make<NameType>("operator!"); 2461 case 'w': 2462 First += 2; 2463 return make<NameType>("operator new"); 2464 } 2465 return nullptr; 2466 case 'o': 2467 switch (look(1)) { 2468 case 'o': 2469 First += 2; 2470 return make<NameType>("operator||"); 2471 case 'r': 2472 First += 2; 2473 return make<NameType>("operator|"); 2474 case 'R': 2475 First += 2; 2476 return make<NameType>("operator|="); 2477 } 2478 return nullptr; 2479 case 'p': 2480 switch (look(1)) { 2481 case 'm': 2482 First += 2; 2483 return make<NameType>("operator->*"); 2484 case 'l': 2485 First += 2; 2486 return make<NameType>("operator+"); 2487 case 'L': 2488 First += 2; 2489 return make<NameType>("operator+="); 2490 case 'p': 2491 First += 2; 2492 return make<NameType>("operator++"); 2493 case 's': 2494 First += 2; 2495 return make<NameType>("operator+"); 2496 case 't': 2497 First += 2; 2498 return make<NameType>("operator->"); 2499 } 2500 return nullptr; 2501 case 'q': 2502 if (look(1) == 'u') { 2503 First += 2; 2504 return make<NameType>("operator?"); 2505 } 2506 return nullptr; 2507 case 'r': 2508 switch (look(1)) { 2509 case 'm': 2510 First += 2; 2511 return make<NameType>("operator%"); 2512 case 'M': 2513 First += 2; 2514 return make<NameType>("operator%="); 2515 case 's': 2516 First += 2; 2517 return make<NameType>("operator>>"); 2518 case 'S': 2519 First += 2; 2520 return make<NameType>("operator>>="); 2521 } 2522 return nullptr; 2523 case 's': 2524 if (look(1) == 's') { 2525 First += 2; 2526 return make<NameType>("operator<=>"); 2527 } 2528 return nullptr; 2529 // ::= v <digit> <source-name> # vendor extended operator 2530 case 'v': 2531 if (std::isdigit(look(1))) { 2532 First += 2; 2533 Node *SN = parseSourceName(State); 2534 if (SN == nullptr) 2535 return nullptr; 2536 return make<ConversionOperatorType>(SN); 2537 } 2538 return nullptr; 2539 } 2540 return nullptr; 2541 } 2542 2543 // <ctor-dtor-name> ::= C1 # complete object constructor 2544 // ::= C2 # base object constructor 2545 // ::= C3 # complete object allocating constructor 2546 // extension ::= C5 # ? 2547 // ::= D0 # deleting destructor 2548 // ::= D1 # complete object destructor 2549 // ::= D2 # base object destructor 2550 // extension ::= D5 # ? 2551 Node *Db::parseCtorDtorName(Node *&SoFar, NameState *State) { 2552 if (SoFar->K == Node::KSpecialSubstitution) { 2553 auto SSK = static_cast<SpecialSubstitution *>(SoFar)->SSK; 2554 switch (SSK) { 2555 case SpecialSubKind::string: 2556 case SpecialSubKind::istream: 2557 case SpecialSubKind::ostream: 2558 case SpecialSubKind::iostream: 2559 SoFar = make<ExpandedSpecialSubstitution>(SSK); 2560 default: 2561 break; 2562 } 2563 } 2564 2565 if (consumeIf('C')) { 2566 bool IsInherited = consumeIf('I'); 2567 if (look() != '1' && look() != '2' && look() != '3' && look() != '5') 2568 return nullptr; 2569 ++First; 2570 if (State) State->CtorDtorConversion = true; 2571 if (IsInherited) { 2572 if (parseName(State) == nullptr) 2573 return nullptr; 2574 } 2575 return make<CtorDtorName>(SoFar, false); 2576 } 2577 2578 if (look() == 'D' && 2579 (look(1) == '0' || look(1) == '1' || look(1) == '2' || look(1) == '5')) { 2580 First += 2; 2581 if (State) State->CtorDtorConversion = true; 2582 return make<CtorDtorName>(SoFar, true); 2583 } 2584 2585 return nullptr; 2586 } 2587 2588 // <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E 2589 // ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E 2590 // 2591 // <prefix> ::= <prefix> <unqualified-name> 2592 // ::= <template-prefix> <template-args> 2593 // ::= <template-param> 2594 // ::= <decltype> 2595 // ::= # empty 2596 // ::= <substitution> 2597 // ::= <prefix> <data-member-prefix> 2598 // extension ::= L 2599 // 2600 // <template-prefix> ::= <prefix> <template unqualified-name> 2601 // ::= <template-param> 2602 // ::= <substitution> 2603 Node *Db::parseNestedName(NameState *State) { 2604 if (!consumeIf('N')) 2605 return nullptr; 2606 2607 Qualifiers CVTmp = parseCVQualifiers(); 2608 if (State) State->CVQualifiers = CVTmp; 2609 2610 if (consumeIf('O')) { 2611 if (State) State->ReferenceQualifier = FrefQualRValue; 2612 } else if (consumeIf('R')) { 2613 if (State) State->ReferenceQualifier = FrefQualLValue; 2614 } else 2615 if (State) State->ReferenceQualifier = FrefQualNone; 2616 2617 Node *SoFar = nullptr; 2618 auto PushComponent = [&](Node *Comp) { 2619 if (SoFar) SoFar = make<QualifiedName>(SoFar, Comp); 2620 else SoFar = Comp; 2621 if (State) State->EndsWithTemplateArgs = false; 2622 }; 2623 2624 if (consumeIf("St")) 2625 SoFar = make<NameType>("std"); 2626 2627 while (!consumeIf('E')) { 2628 consumeIf('L'); // extension 2629 2630 // ::= <template-param> 2631 if (look() == 'T') { 2632 Node *TP = parseTemplateParam(); 2633 if (TP == nullptr) 2634 return nullptr; 2635 PushComponent(TP); 2636 Subs.push_back(SoFar); 2637 continue; 2638 } 2639 2640 // ::= <template-prefix> <template-args> 2641 if (look() == 'I') { 2642 Node *TA = parseTemplateArgs(State != nullptr); 2643 if (TA == nullptr || SoFar == nullptr) 2644 return nullptr; 2645 SoFar = make<NameWithTemplateArgs>(SoFar, TA); 2646 if (State) State->EndsWithTemplateArgs = true; 2647 Subs.push_back(SoFar); 2648 continue; 2649 } 2650 2651 // ::= <decltype> 2652 if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) { 2653 Node *DT = parseDecltype(); 2654 if (DT == nullptr) 2655 return nullptr; 2656 PushComponent(DT); 2657 Subs.push_back(SoFar); 2658 continue; 2659 } 2660 2661 // ::= <substitution> 2662 if (look() == 'S' && look(1) != 't') { 2663 Node *S = parseSubstitution(); 2664 if (S == nullptr) 2665 return nullptr; 2666 PushComponent(S); 2667 if (SoFar != S) 2668 Subs.push_back(S); 2669 continue; 2670 } 2671 2672 // Parse an <unqualified-name> thats actually a <ctor-dtor-name>. 2673 if (look() == 'C' || (look() == 'D' && look(1) != 'C')) { 2674 if (SoFar == nullptr) 2675 return nullptr; 2676 Node *CtorDtor = parseCtorDtorName(SoFar, State); 2677 if (CtorDtor == nullptr) 2678 return nullptr; 2679 PushComponent(CtorDtor); 2680 SoFar = parseAbiTags(SoFar); 2681 if (SoFar == nullptr) 2682 return nullptr; 2683 Subs.push_back(SoFar); 2684 continue; 2685 } 2686 2687 // ::= <prefix> <unqualified-name> 2688 Node *N = parseUnqualifiedName(State); 2689 if (N == nullptr) 2690 return nullptr; 2691 PushComponent(N); 2692 Subs.push_back(SoFar); 2693 } 2694 2695 if (SoFar == nullptr || Subs.empty()) 2696 return nullptr; 2697 2698 Subs.pop_back(); 2699 return SoFar; 2700 } 2701 2702 // <simple-id> ::= <source-name> [ <template-args> ] 2703 Node *Db::parseSimpleId() { 2704 Node *SN = parseSourceName(/*NameState=*/nullptr); 2705 if (SN == nullptr) 2706 return nullptr; 2707 if (look() == 'I') { 2708 Node *TA = parseTemplateArgs(); 2709 if (TA == nullptr) 2710 return nullptr; 2711 return make<NameWithTemplateArgs>(SN, TA); 2712 } 2713 return SN; 2714 } 2715 2716 // <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f()) 2717 // ::= <simple-id> # e.g., ~A<2*N> 2718 Node *Db::parseDestructorName() { 2719 Node *Result; 2720 if (std::isdigit(look())) 2721 Result = parseSimpleId(); 2722 else 2723 Result = parseUnresolvedType(); 2724 if (Result == nullptr) 2725 return nullptr; 2726 return make<DtorName>(Result); 2727 } 2728 2729 // <unresolved-type> ::= <template-param> 2730 // ::= <decltype> 2731 // ::= <substitution> 2732 Node *Db::parseUnresolvedType() { 2733 if (look() == 'T') { 2734 Node *TP = parseTemplateParam(); 2735 if (TP == nullptr) 2736 return nullptr; 2737 Subs.push_back(TP); 2738 return TP; 2739 } 2740 if (look() == 'D') { 2741 Node *DT = parseDecltype(); 2742 if (DT == nullptr) 2743 return nullptr; 2744 Subs.push_back(DT); 2745 return DT; 2746 } 2747 return parseSubstitution(); 2748 } 2749 2750 // <base-unresolved-name> ::= <simple-id> # unresolved name 2751 // extension ::= <operator-name> # unresolved operator-function-id 2752 // extension ::= <operator-name> <template-args> # unresolved operator template-id 2753 // ::= on <operator-name> # unresolved operator-function-id 2754 // ::= on <operator-name> <template-args> # unresolved operator template-id 2755 // ::= dn <destructor-name> # destructor or pseudo-destructor; 2756 // # e.g. ~X or ~X<N-1> 2757 Node *Db::parseBaseUnresolvedName() { 2758 if (std::isdigit(look())) 2759 return parseSimpleId(); 2760 2761 if (consumeIf("dn")) 2762 return parseDestructorName(); 2763 2764 consumeIf("on"); 2765 2766 Node *Oper = parseOperatorName(/*NameState=*/nullptr); 2767 if (Oper == nullptr) 2768 return nullptr; 2769 if (look() == 'I') { 2770 Node *TA = parseTemplateArgs(); 2771 if (TA == nullptr) 2772 return nullptr; 2773 return make<NameWithTemplateArgs>(Oper, TA); 2774 } 2775 return Oper; 2776 } 2777 2778 // <unresolved-name> 2779 // extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name> 2780 // ::= [gs] <base-unresolved-name> # x or (with "gs") ::x 2781 // ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name> 2782 // # A::x, N::y, A<T>::z; "gs" means leading "::" 2783 // ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x 2784 // extension ::= sr <unresolved-type> <template-args> <base-unresolved-name> 2785 // # T::N::x /decltype(p)::N::x 2786 // (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name> 2787 // 2788 // <unresolved-qualifier-level> ::= <simple-id> 2789 Node *Db::parseUnresolvedName() { 2790 Node *SoFar = nullptr; 2791 2792 // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name> 2793 // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name> 2794 if (consumeIf("srN")) { 2795 SoFar = parseUnresolvedType(); 2796 if (SoFar == nullptr) 2797 return nullptr; 2798 2799 if (look() == 'I') { 2800 Node *TA = parseTemplateArgs(); 2801 if (TA == nullptr) 2802 return nullptr; 2803 SoFar = make<NameWithTemplateArgs>(SoFar, TA); 2804 } 2805 2806 while (!consumeIf('E')) { 2807 Node *Qual = parseSimpleId(); 2808 if (Qual == nullptr) 2809 return nullptr; 2810 SoFar = make<QualifiedName>(SoFar, Qual); 2811 } 2812 2813 Node *Base = parseBaseUnresolvedName(); 2814 if (Base == nullptr) 2815 return nullptr; 2816 return make<QualifiedName>(SoFar, Base); 2817 } 2818 2819 bool Global = consumeIf("gs"); 2820 2821 // [gs] <base-unresolved-name> # x or (with "gs") ::x 2822 if (!consumeIf("sr")) { 2823 SoFar = parseBaseUnresolvedName(); 2824 if (SoFar == nullptr) 2825 return nullptr; 2826 if (Global) 2827 SoFar = make<GlobalQualifiedName>(SoFar); 2828 return SoFar; 2829 } 2830 2831 // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name> 2832 if (std::isdigit(look())) { 2833 do { 2834 Node *Qual = parseSimpleId(); 2835 if (Qual == nullptr) 2836 return nullptr; 2837 if (SoFar) 2838 SoFar = make<QualifiedName>(SoFar, Qual); 2839 else if (Global) 2840 SoFar = make<GlobalQualifiedName>(Qual); 2841 else 2842 SoFar = Qual; 2843 } while (!consumeIf('E')); 2844 } 2845 // sr <unresolved-type> <base-unresolved-name> 2846 // sr <unresolved-type> <template-args> <base-unresolved-name> 2847 else { 2848 SoFar = parseUnresolvedType(); 2849 if (SoFar == nullptr) 2850 return nullptr; 2851 2852 if (look() == 'I') { 2853 Node *TA = parseTemplateArgs(); 2854 if (TA == nullptr) 2855 return nullptr; 2856 SoFar = make<NameWithTemplateArgs>(SoFar, TA); 2857 } 2858 } 2859 2860 assert(SoFar != nullptr); 2861 2862 Node *Base = parseBaseUnresolvedName(); 2863 if (Base == nullptr) 2864 return nullptr; 2865 return make<QualifiedName>(SoFar, Base); 2866 } 2867 2868 // <abi-tags> ::= <abi-tag> [<abi-tags>] 2869 // <abi-tag> ::= B <source-name> 2870 Node *Db::parseAbiTags(Node *N) { 2871 while (consumeIf('B')) { 2872 StringView SN = parseBareSourceName(); 2873 if (SN.empty()) 2874 return nullptr; 2875 N = make<AbiTagAttr>(N, SN); 2876 } 2877 return N; 2878 } 2879 2880 // <number> ::= [n] <non-negative decimal integer> 2881 StringView Db::parseNumber(bool AllowNegative) { 2882 const char *Tmp = First; 2883 if (AllowNegative) 2884 consumeIf('n'); 2885 if (numLeft() == 0 || !std::isdigit(*First)) 2886 return StringView(); 2887 while (numLeft() != 0 && std::isdigit(*First)) 2888 ++First; 2889 return StringView(Tmp, First); 2890 } 2891 2892 // <positive length number> ::= [0-9]* 2893 bool Db::parsePositiveInteger(size_t *Out) { 2894 *Out = 0; 2895 if (look() < '0' || look() > '9') 2896 return true; 2897 while (look() >= '0' && look() <= '9') { 2898 *Out *= 10; 2899 *Out += static_cast<size_t>(consume() - '0'); 2900 } 2901 return false; 2902 } 2903 2904 StringView Db::parseBareSourceName() { 2905 size_t Int = 0; 2906 if (parsePositiveInteger(&Int) || numLeft() < Int) 2907 return StringView(); 2908 StringView R(First, First + Int); 2909 First += Int; 2910 return R; 2911 } 2912 2913 // <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E 2914 // 2915 // <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw()) 2916 // ::= DO <expression> E # computed (instantiation-dependent) noexcept 2917 // ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types 2918 // 2919 // <ref-qualifier> ::= R # & ref-qualifier 2920 // <ref-qualifier> ::= O # && ref-qualifier 2921 Node *Db::parseFunctionType() { 2922 Qualifiers CVQuals = parseCVQualifiers(); 2923 2924 Node *ExceptionSpec = nullptr; 2925 if (consumeIf("Do")) { 2926 ExceptionSpec = make<NameType>("noexcept"); 2927 } else if (consumeIf("DO")) { 2928 Node *E = parseExpr(); 2929 if (E == nullptr || !consumeIf('E')) 2930 return nullptr; 2931 ExceptionSpec = make<NoexceptSpec>(E); 2932 } else if (consumeIf("Dw")) { 2933 size_t SpecsBegin = Names.size(); 2934 while (!consumeIf('E')) { 2935 Node *T = parseType(); 2936 if (T == nullptr) 2937 return nullptr; 2938 Names.push_back(T); 2939 } 2940 ExceptionSpec = 2941 make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin)); 2942 } 2943 2944 consumeIf("Dx"); // transaction safe 2945 2946 if (!consumeIf('F')) 2947 return nullptr; 2948 consumeIf('Y'); // extern "C" 2949 Node *ReturnType = parseType(); 2950 if (ReturnType == nullptr) 2951 return nullptr; 2952 2953 FunctionRefQual ReferenceQualifier = FrefQualNone; 2954 size_t ParamsBegin = Names.size(); 2955 while (true) { 2956 if (consumeIf('E')) 2957 break; 2958 if (consumeIf('v')) 2959 continue; 2960 if (consumeIf("RE")) { 2961 ReferenceQualifier = FrefQualLValue; 2962 break; 2963 } 2964 if (consumeIf("OE")) { 2965 ReferenceQualifier = FrefQualRValue; 2966 break; 2967 } 2968 Node *T = parseType(); 2969 if (T == nullptr) 2970 return nullptr; 2971 Names.push_back(T); 2972 } 2973 2974 NodeArray Params = popTrailingNodeArray(ParamsBegin); 2975 return make<FunctionType>(ReturnType, Params, CVQuals, 2976 ReferenceQualifier, ExceptionSpec); 2977 } 2978 2979 // extension: 2980 // <vector-type> ::= Dv <positive dimension number> _ <extended element type> 2981 // ::= Dv [<dimension expression>] _ <element type> 2982 // <extended element type> ::= <element type> 2983 // ::= p # AltiVec vector pixel 2984 Node *Db::parseVectorType() { 2985 if (!consumeIf("Dv")) 2986 return nullptr; 2987 if (look() >= '1' && look() <= '9') { 2988 StringView DimensionNumber = parseNumber(); 2989 if (!consumeIf('_')) 2990 return nullptr; 2991 if (consumeIf('p')) 2992 return make<VectorType>(DimensionNumber); 2993 Node *ElemType = parseType(); 2994 if (ElemType == nullptr) 2995 return nullptr; 2996 return make<VectorType>(ElemType, DimensionNumber); 2997 } 2998 2999 if (!consumeIf('_')) { 3000 Node *DimExpr = parseExpr(); 3001 if (!DimExpr) 3002 return nullptr; 3003 if (!consumeIf('_')) 3004 return nullptr; 3005 Node *ElemType = parseType(); 3006 if (!ElemType) 3007 return nullptr; 3008 return make<VectorType>(ElemType, DimExpr); 3009 } 3010 Node *ElemType = parseType(); 3011 if (!ElemType) 3012 return nullptr; 3013 return make<VectorType>(ElemType, StringView()); 3014 } 3015 3016 // <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x) 3017 // ::= DT <expression> E # decltype of an expression (C++0x) 3018 Node *Db::parseDecltype() { 3019 if (!consumeIf('D')) 3020 return nullptr; 3021 if (!consumeIf('t') && !consumeIf('T')) 3022 return nullptr; 3023 Node *E = parseExpr(); 3024 if (E == nullptr) 3025 return nullptr; 3026 if (!consumeIf('E')) 3027 return nullptr; 3028 return make<EnclosingExpr>("decltype(", E, ")"); 3029 } 3030 3031 // <array-type> ::= A <positive dimension number> _ <element type> 3032 // ::= A [<dimension expression>] _ <element type> 3033 Node *Db::parseArrayType() { 3034 if (!consumeIf('A')) 3035 return nullptr; 3036 3037 if (std::isdigit(look())) { 3038 StringView Dimension = parseNumber(); 3039 if (!consumeIf('_')) 3040 return nullptr; 3041 Node *Ty = parseType(); 3042 if (Ty == nullptr) 3043 return nullptr; 3044 return make<ArrayType>(Ty, Dimension); 3045 } 3046 3047 if (!consumeIf('_')) { 3048 Node *DimExpr = parseExpr(); 3049 if (DimExpr == nullptr) 3050 return nullptr; 3051 if (!consumeIf('_')) 3052 return nullptr; 3053 Node *ElementType = parseType(); 3054 if (ElementType == nullptr) 3055 return nullptr; 3056 return make<ArrayType>(ElementType, DimExpr); 3057 } 3058 3059 Node *Ty = parseType(); 3060 if (Ty == nullptr) 3061 return nullptr; 3062 return make<ArrayType>(Ty); 3063 } 3064 3065 // <pointer-to-member-type> ::= M <class type> <member type> 3066 Node *Db::parsePointerToMemberType() { 3067 if (!consumeIf('M')) 3068 return nullptr; 3069 Node *ClassType = parseType(); 3070 if (ClassType == nullptr) 3071 return nullptr; 3072 Node *MemberType = parseType(); 3073 if (MemberType == nullptr) 3074 return nullptr; 3075 return make<PointerToMemberType>(ClassType, MemberType); 3076 } 3077 3078 // <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier 3079 // ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class' 3080 // ::= Tu <name> # dependent elaborated type specifier using 'union' 3081 // ::= Te <name> # dependent elaborated type specifier using 'enum' 3082 Node *Db::parseClassEnumType() { 3083 StringView ElabSpef; 3084 if (consumeIf("Ts")) 3085 ElabSpef = "struct"; 3086 else if (consumeIf("Tu")) 3087 ElabSpef = "union"; 3088 else if (consumeIf("Te")) 3089 ElabSpef = "enum"; 3090 3091 Node *Name = parseName(); 3092 if (Name == nullptr) 3093 return nullptr; 3094 3095 if (!ElabSpef.empty()) 3096 return make<ElaboratedTypeSpefType>(ElabSpef, Name); 3097 3098 return Name; 3099 } 3100 3101 // <qualified-type> ::= <qualifiers> <type> 3102 // <qualifiers> ::= <extended-qualifier>* <CV-qualifiers> 3103 // <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier 3104 Node *Db::parseQualifiedType() { 3105 if (consumeIf('U')) { 3106 StringView Qual = parseBareSourceName(); 3107 if (Qual.empty()) 3108 return nullptr; 3109 3110 // FIXME parse the optional <template-args> here! 3111 3112 // extension ::= U <objc-name> <objc-type> # objc-type<identifier> 3113 if (Qual.startsWith("objcproto")) { 3114 StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto")); 3115 StringView Proto; 3116 { 3117 SwapAndRestore<const char *> SaveFirst(First, ProtoSourceName.begin()), 3118 SaveLast(Last, ProtoSourceName.end()); 3119 Proto = parseBareSourceName(); 3120 } 3121 if (Proto.empty()) 3122 return nullptr; 3123 Node *Child = parseQualifiedType(); 3124 if (Child == nullptr) 3125 return nullptr; 3126 return make<ObjCProtoName>(Child, Proto); 3127 } 3128 3129 Node *Child = parseQualifiedType(); 3130 if (Child == nullptr) 3131 return nullptr; 3132 return make<VendorExtQualType>(Child, Qual); 3133 } 3134 3135 Qualifiers Quals = parseCVQualifiers(); 3136 Node *Ty = parseType(); 3137 if (Ty == nullptr) 3138 return nullptr; 3139 if (Quals != QualNone) 3140 Ty = make<QualType>(Ty, Quals); 3141 return Ty; 3142 } 3143 3144 // <type> ::= <builtin-type> 3145 // ::= <qualified-type> 3146 // ::= <function-type> 3147 // ::= <class-enum-type> 3148 // ::= <array-type> 3149 // ::= <pointer-to-member-type> 3150 // ::= <template-param> 3151 // ::= <template-template-param> <template-args> 3152 // ::= <decltype> 3153 // ::= P <type> # pointer 3154 // ::= R <type> # l-value reference 3155 // ::= O <type> # r-value reference (C++11) 3156 // ::= C <type> # complex pair (C99) 3157 // ::= G <type> # imaginary (C99) 3158 // ::= <substitution> # See Compression below 3159 // extension ::= U <objc-name> <objc-type> # objc-type<identifier> 3160 // extension ::= <vector-type> # <vector-type> starts with Dv 3161 // 3162 // <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1 3163 // <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name> 3164 Node *Db::parseType() { 3165 Node *Result = nullptr; 3166 3167 switch (look()) { 3168 // ::= <qualified-type> 3169 case 'r': 3170 case 'V': 3171 case 'K': { 3172 unsigned AfterQuals = 0; 3173 if (look(AfterQuals) == 'r') ++AfterQuals; 3174 if (look(AfterQuals) == 'V') ++AfterQuals; 3175 if (look(AfterQuals) == 'K') ++AfterQuals; 3176 3177 if (look(AfterQuals) == 'F' || 3178 (look(AfterQuals) == 'D' && 3179 (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' || 3180 look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) { 3181 Result = parseFunctionType(); 3182 break; 3183 } 3184 LLVM_FALLTHROUGH; 3185 } 3186 case 'U': { 3187 Result = parseQualifiedType(); 3188 break; 3189 } 3190 // <builtin-type> ::= v # void 3191 case 'v': 3192 ++First; 3193 return make<NameType>("void"); 3194 // ::= w # wchar_t 3195 case 'w': 3196 ++First; 3197 return make<NameType>("wchar_t"); 3198 // ::= b # bool 3199 case 'b': 3200 ++First; 3201 return make<NameType>("bool"); 3202 // ::= c # char 3203 case 'c': 3204 ++First; 3205 return make<NameType>("char"); 3206 // ::= a # signed char 3207 case 'a': 3208 ++First; 3209 return make<NameType>("signed char"); 3210 // ::= h # unsigned char 3211 case 'h': 3212 ++First; 3213 return make<NameType>("unsigned char"); 3214 // ::= s # short 3215 case 's': 3216 ++First; 3217 return make<NameType>("short"); 3218 // ::= t # unsigned short 3219 case 't': 3220 ++First; 3221 return make<NameType>("unsigned short"); 3222 // ::= i # int 3223 case 'i': 3224 ++First; 3225 return make<NameType>("int"); 3226 // ::= j # unsigned int 3227 case 'j': 3228 ++First; 3229 return make<NameType>("unsigned int"); 3230 // ::= l # long 3231 case 'l': 3232 ++First; 3233 return make<NameType>("long"); 3234 // ::= m # unsigned long 3235 case 'm': 3236 ++First; 3237 return make<NameType>("unsigned long"); 3238 // ::= x # long long, __int64 3239 case 'x': 3240 ++First; 3241 return make<NameType>("long long"); 3242 // ::= y # unsigned long long, __int64 3243 case 'y': 3244 ++First; 3245 return make<NameType>("unsigned long long"); 3246 // ::= n # __int128 3247 case 'n': 3248 ++First; 3249 return make<NameType>("__int128"); 3250 // ::= o # unsigned __int128 3251 case 'o': 3252 ++First; 3253 return make<NameType>("unsigned __int128"); 3254 // ::= f # float 3255 case 'f': 3256 ++First; 3257 return make<NameType>("float"); 3258 // ::= d # double 3259 case 'd': 3260 ++First; 3261 return make<NameType>("double"); 3262 // ::= e # long double, __float80 3263 case 'e': 3264 ++First; 3265 return make<NameType>("long double"); 3266 // ::= g # __float128 3267 case 'g': 3268 ++First; 3269 return make<NameType>("__float128"); 3270 // ::= z # ellipsis 3271 case 'z': 3272 ++First; 3273 return make<NameType>("..."); 3274 3275 // <builtin-type> ::= u <source-name> # vendor extended type 3276 case 'u': { 3277 ++First; 3278 StringView Res = parseBareSourceName(); 3279 if (Res.empty()) 3280 return nullptr; 3281 return make<NameType>(Res); 3282 } 3283 case 'D': 3284 switch (look(1)) { 3285 // ::= Dd # IEEE 754r decimal floating point (64 bits) 3286 case 'd': 3287 First += 2; 3288 return make<NameType>("decimal64"); 3289 // ::= De # IEEE 754r decimal floating point (128 bits) 3290 case 'e': 3291 First += 2; 3292 return make<NameType>("decimal128"); 3293 // ::= Df # IEEE 754r decimal floating point (32 bits) 3294 case 'f': 3295 First += 2; 3296 return make<NameType>("decimal32"); 3297 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 3298 case 'h': 3299 First += 2; 3300 return make<NameType>("decimal16"); 3301 // ::= Di # char32_t 3302 case 'i': 3303 First += 2; 3304 return make<NameType>("char32_t"); 3305 // ::= Ds # char16_t 3306 case 's': 3307 First += 2; 3308 return make<NameType>("char16_t"); 3309 // ::= Da # auto (in dependent new-expressions) 3310 case 'a': 3311 First += 2; 3312 return make<NameType>("auto"); 3313 // ::= Dc # decltype(auto) 3314 case 'c': 3315 First += 2; 3316 return make<NameType>("decltype(auto)"); 3317 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 3318 case 'n': 3319 First += 2; 3320 return make<NameType>("std::nullptr_t"); 3321 3322 // ::= <decltype> 3323 case 't': 3324 case 'T': { 3325 Result = parseDecltype(); 3326 break; 3327 } 3328 // extension ::= <vector-type> # <vector-type> starts with Dv 3329 case 'v': { 3330 Result = parseVectorType(); 3331 break; 3332 } 3333 // ::= Dp <type> # pack expansion (C++0x) 3334 case 'p': { 3335 First += 2; 3336 Node *Child = parseType(); 3337 if (!Child) 3338 return nullptr; 3339 Result = make<ParameterPackExpansion>(Child); 3340 break; 3341 } 3342 // Exception specifier on a function type. 3343 case 'o': 3344 case 'O': 3345 case 'w': 3346 // Transaction safe function type. 3347 case 'x': 3348 Result = parseFunctionType(); 3349 break; 3350 } 3351 break; 3352 // ::= <function-type> 3353 case 'F': { 3354 Result = parseFunctionType(); 3355 break; 3356 } 3357 // ::= <array-type> 3358 case 'A': { 3359 Result = parseArrayType(); 3360 break; 3361 } 3362 // ::= <pointer-to-member-type> 3363 case 'M': { 3364 Result = parsePointerToMemberType(); 3365 break; 3366 } 3367 // ::= <template-param> 3368 case 'T': { 3369 // This could be an elaborate type specifier on a <class-enum-type>. 3370 if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') { 3371 Result = parseClassEnumType(); 3372 break; 3373 } 3374 3375 Result = parseTemplateParam(); 3376 if (Result == nullptr) 3377 return nullptr; 3378 3379 // Result could be either of: 3380 // <type> ::= <template-param> 3381 // <type> ::= <template-template-param> <template-args> 3382 // 3383 // <template-template-param> ::= <template-param> 3384 // ::= <substitution> 3385 // 3386 // If this is followed by some <template-args>, and we're permitted to 3387 // parse them, take the second production. 3388 3389 if (TryToParseTemplateArgs && look() == 'I') { 3390 Node *TA = parseTemplateArgs(); 3391 if (TA == nullptr) 3392 return nullptr; 3393 Result = make<NameWithTemplateArgs>(Result, TA); 3394 } 3395 break; 3396 } 3397 // ::= P <type> # pointer 3398 case 'P': { 3399 ++First; 3400 Node *Ptr = parseType(); 3401 if (Ptr == nullptr) 3402 return nullptr; 3403 Result = make<PointerType>(Ptr); 3404 break; 3405 } 3406 // ::= R <type> # l-value reference 3407 case 'R': { 3408 ++First; 3409 Node *Ref = parseType(); 3410 if (Ref == nullptr) 3411 return nullptr; 3412 Result = make<LValueReferenceType>(Ref); 3413 break; 3414 } 3415 // ::= O <type> # r-value reference (C++11) 3416 case 'O': { 3417 ++First; 3418 Node *Ref = parseType(); 3419 if (Ref == nullptr) 3420 return nullptr; 3421 Result = make<RValueReferenceType>(Ref); 3422 break; 3423 } 3424 // ::= C <type> # complex pair (C99) 3425 case 'C': { 3426 ++First; 3427 Node *P = parseType(); 3428 if (P == nullptr) 3429 return nullptr; 3430 Result = make<PostfixQualifiedType>(P, " complex"); 3431 break; 3432 } 3433 // ::= G <type> # imaginary (C99) 3434 case 'G': { 3435 ++First; 3436 Node *P = parseType(); 3437 if (P == nullptr) 3438 return P; 3439 Result = make<PostfixQualifiedType>(P, " imaginary"); 3440 break; 3441 } 3442 // ::= <substitution> # See Compression below 3443 case 'S': { 3444 if (look(1) && look(1) != 't') { 3445 Node *Sub = parseSubstitution(); 3446 if (Sub == nullptr) 3447 return nullptr; 3448 3449 // Sub could be either of: 3450 // <type> ::= <substitution> 3451 // <type> ::= <template-template-param> <template-args> 3452 // 3453 // <template-template-param> ::= <template-param> 3454 // ::= <substitution> 3455 // 3456 // If this is followed by some <template-args>, and we're permitted to 3457 // parse them, take the second production. 3458 3459 if (TryToParseTemplateArgs && look() == 'I') { 3460 Node *TA = parseTemplateArgs(); 3461 if (TA == nullptr) 3462 return nullptr; 3463 Result = make<NameWithTemplateArgs>(Sub, TA); 3464 break; 3465 } 3466 3467 // If all we parsed was a substitution, don't re-insert into the 3468 // substitution table. 3469 return Sub; 3470 } 3471 LLVM_FALLTHROUGH; 3472 } 3473 // ::= <class-enum-type> 3474 default: { 3475 Result = parseClassEnumType(); 3476 break; 3477 } 3478 } 3479 3480 // If we parsed a type, insert it into the substitution table. Note that all 3481 // <builtin-type>s and <substitution>s have already bailed out, because they 3482 // don't get substitutions. 3483 if (Result != nullptr) 3484 Subs.push_back(Result); 3485 return Result; 3486 } 3487 3488 Node *Db::parsePrefixExpr(StringView Kind) { 3489 Node *E = parseExpr(); 3490 if (E == nullptr) 3491 return nullptr; 3492 return make<PrefixExpr>(Kind, E); 3493 } 3494 3495 Node *Db::parseBinaryExpr(StringView Kind) { 3496 Node *LHS = parseExpr(); 3497 if (LHS == nullptr) 3498 return nullptr; 3499 Node *RHS = parseExpr(); 3500 if (RHS == nullptr) 3501 return nullptr; 3502 return make<BinaryExpr>(LHS, Kind, RHS); 3503 } 3504 3505 Node *Db::parseIntegerLiteral(StringView Lit) { 3506 StringView Tmp = parseNumber(true); 3507 if (!Tmp.empty() && consumeIf('E')) 3508 return make<IntegerExpr>(Lit, Tmp); 3509 return nullptr; 3510 } 3511 3512 // <CV-Qualifiers> ::= [r] [V] [K] 3513 Qualifiers Db::parseCVQualifiers() { 3514 Qualifiers CVR = QualNone; 3515 if (consumeIf('r')) 3516 addQualifiers(CVR, QualRestrict); 3517 if (consumeIf('V')) 3518 addQualifiers(CVR, QualVolatile); 3519 if (consumeIf('K')) 3520 addQualifiers(CVR, QualConst); 3521 return CVR; 3522 } 3523 3524 // <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter 3525 // ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters 3526 // ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter 3527 // ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters 3528 Node *Db::parseFunctionParam() { 3529 if (consumeIf("fp")) { 3530 parseCVQualifiers(); 3531 StringView Num = parseNumber(); 3532 if (!consumeIf('_')) 3533 return nullptr; 3534 return make<FunctionParam>(Num); 3535 } 3536 if (consumeIf("fL")) { 3537 if (parseNumber().empty()) 3538 return nullptr; 3539 if (!consumeIf('p')) 3540 return nullptr; 3541 parseCVQualifiers(); 3542 StringView Num = parseNumber(); 3543 if (!consumeIf('_')) 3544 return nullptr; 3545 return make<FunctionParam>(Num); 3546 } 3547 return nullptr; 3548 } 3549 3550 // [gs] nw <expression>* _ <type> E # new (expr-list) type 3551 // [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init) 3552 // [gs] na <expression>* _ <type> E # new[] (expr-list) type 3553 // [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init) 3554 // <initializer> ::= pi <expression>* E # parenthesized initialization 3555 Node *Db::parseNewExpr() { 3556 bool Global = consumeIf("gs"); 3557 bool IsArray = look(1) == 'a'; 3558 if (!consumeIf("nw") && !consumeIf("na")) 3559 return nullptr; 3560 size_t Exprs = Names.size(); 3561 while (!consumeIf('_')) { 3562 Node *Ex = parseExpr(); 3563 if (Ex == nullptr) 3564 return nullptr; 3565 Names.push_back(Ex); 3566 } 3567 NodeArray ExprList = popTrailingNodeArray(Exprs); 3568 Node *Ty = parseType(); 3569 if (Ty == nullptr) 3570 return Ty; 3571 if (consumeIf("pi")) { 3572 size_t InitsBegin = Names.size(); 3573 while (!consumeIf('E')) { 3574 Node *Init = parseExpr(); 3575 if (Init == nullptr) 3576 return Init; 3577 Names.push_back(Init); 3578 } 3579 NodeArray Inits = popTrailingNodeArray(InitsBegin); 3580 return make<NewExpr>(ExprList, Ty, Inits, Global, IsArray); 3581 } else if (!consumeIf('E')) 3582 return nullptr; 3583 return make<NewExpr>(ExprList, Ty, NodeArray(), Global, IsArray); 3584 } 3585 3586 // cv <type> <expression> # conversion with one argument 3587 // cv <type> _ <expression>* E # conversion with a different number of arguments 3588 Node *Db::parseConversionExpr() { 3589 if (!consumeIf("cv")) 3590 return nullptr; 3591 Node *Ty; 3592 { 3593 SwapAndRestore<bool> SaveTemp(TryToParseTemplateArgs, false); 3594 Ty = parseType(); 3595 } 3596 3597 if (Ty == nullptr) 3598 return nullptr; 3599 3600 if (consumeIf('_')) { 3601 size_t ExprsBegin = Names.size(); 3602 while (!consumeIf('E')) { 3603 Node *E = parseExpr(); 3604 if (E == nullptr) 3605 return E; 3606 Names.push_back(E); 3607 } 3608 NodeArray Exprs = popTrailingNodeArray(ExprsBegin); 3609 return make<ConversionExpr>(Ty, Exprs); 3610 } 3611 3612 Node *E[1] = {parseExpr()}; 3613 if (E[0] == nullptr) 3614 return nullptr; 3615 return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1)); 3616 } 3617 3618 // <expr-primary> ::= L <type> <value number> E # integer literal 3619 // ::= L <type> <value float> E # floating literal 3620 // ::= L <string type> E # string literal 3621 // ::= L <nullptr type> E # nullptr literal (i.e., "LDnE") 3622 // FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000) 3623 // ::= L <mangled-name> E # external name 3624 Node *Db::parseExprPrimary() { 3625 if (!consumeIf('L')) 3626 return nullptr; 3627 switch (look()) { 3628 case 'w': 3629 ++First; 3630 return parseIntegerLiteral("wchar_t"); 3631 case 'b': 3632 if (consumeIf("b0E")) 3633 return make<BoolExpr>(0); 3634 if (consumeIf("b1E")) 3635 return make<BoolExpr>(1); 3636 return nullptr; 3637 case 'c': 3638 ++First; 3639 return parseIntegerLiteral("char"); 3640 case 'a': 3641 ++First; 3642 return parseIntegerLiteral("signed char"); 3643 case 'h': 3644 ++First; 3645 return parseIntegerLiteral("unsigned char"); 3646 case 's': 3647 ++First; 3648 return parseIntegerLiteral("short"); 3649 case 't': 3650 ++First; 3651 return parseIntegerLiteral("unsigned short"); 3652 case 'i': 3653 ++First; 3654 return parseIntegerLiteral(""); 3655 case 'j': 3656 ++First; 3657 return parseIntegerLiteral("u"); 3658 case 'l': 3659 ++First; 3660 return parseIntegerLiteral("l"); 3661 case 'm': 3662 ++First; 3663 return parseIntegerLiteral("ul"); 3664 case 'x': 3665 ++First; 3666 return parseIntegerLiteral("ll"); 3667 case 'y': 3668 ++First; 3669 return parseIntegerLiteral("ull"); 3670 case 'n': 3671 ++First; 3672 return parseIntegerLiteral("__int128"); 3673 case 'o': 3674 ++First; 3675 return parseIntegerLiteral("unsigned __int128"); 3676 case 'f': 3677 ++First; 3678 return parseFloatingLiteral<float>(); 3679 case 'd': 3680 ++First; 3681 return parseFloatingLiteral<double>(); 3682 case 'e': 3683 ++First; 3684 return parseFloatingLiteral<long double>(); 3685 case '_': 3686 if (consumeIf("_Z")) { 3687 Node *R = parseEncoding(); 3688 if (R != nullptr && consumeIf('E')) 3689 return R; 3690 } 3691 return nullptr; 3692 case 'T': 3693 // Invalid mangled name per 3694 // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html 3695 return nullptr; 3696 default: { 3697 // might be named type 3698 Node *T = parseType(); 3699 if (T == nullptr) 3700 return nullptr; 3701 StringView N = parseNumber(); 3702 if (!N.empty()) { 3703 if (!consumeIf('E')) 3704 return nullptr; 3705 return make<IntegerCastExpr>(T, N); 3706 } 3707 if (consumeIf('E')) 3708 return T; 3709 return nullptr; 3710 } 3711 } 3712 } 3713 3714 // <braced-expression> ::= <expression> 3715 // ::= di <field source-name> <braced-expression> # .name = expr 3716 // ::= dx <index expression> <braced-expression> # [expr] = expr 3717 // ::= dX <range begin expression> <range end expression> <braced-expression> 3718 Node *Db::parseBracedExpr() { 3719 if (look() == 'd') { 3720 switch (look(1)) { 3721 case 'i': { 3722 First += 2; 3723 Node *Field = parseSourceName(/*NameState=*/nullptr); 3724 if (Field == nullptr) 3725 return nullptr; 3726 Node *Init = parseBracedExpr(); 3727 if (Init == nullptr) 3728 return nullptr; 3729 return make<BracedExpr>(Field, Init, /*isArray=*/false); 3730 } 3731 case 'x': { 3732 First += 2; 3733 Node *Index = parseExpr(); 3734 if (Index == nullptr) 3735 return nullptr; 3736 Node *Init = parseBracedExpr(); 3737 if (Init == nullptr) 3738 return nullptr; 3739 return make<BracedExpr>(Index, Init, /*isArray=*/true); 3740 } 3741 case 'X': { 3742 First += 2; 3743 Node *RangeBegin = parseExpr(); 3744 if (RangeBegin == nullptr) 3745 return nullptr; 3746 Node *RangeEnd = parseExpr(); 3747 if (RangeEnd == nullptr) 3748 return nullptr; 3749 Node *Init = parseBracedExpr(); 3750 if (Init == nullptr) 3751 return nullptr; 3752 return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init); 3753 } 3754 } 3755 } 3756 return parseExpr(); 3757 } 3758 3759 // <expression> ::= <unary operator-name> <expression> 3760 // ::= <binary operator-name> <expression> <expression> 3761 // ::= <ternary operator-name> <expression> <expression> <expression> 3762 // ::= cl <expression>+ E # call 3763 // ::= cv <type> <expression> # conversion with one argument 3764 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 3765 // ::= [gs] nw <expression>* _ <type> E # new (expr-list) type 3766 // ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init) 3767 // ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type 3768 // ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init) 3769 // ::= [gs] dl <expression> # delete expression 3770 // ::= [gs] da <expression> # delete[] expression 3771 // ::= pp_ <expression> # prefix ++ 3772 // ::= mm_ <expression> # prefix -- 3773 // ::= ti <type> # typeid (type) 3774 // ::= te <expression> # typeid (expression) 3775 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 3776 // ::= sc <type> <expression> # static_cast<type> (expression) 3777 // ::= cc <type> <expression> # const_cast<type> (expression) 3778 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 3779 // ::= st <type> # sizeof (a type) 3780 // ::= sz <expression> # sizeof (an expression) 3781 // ::= at <type> # alignof (a type) 3782 // ::= az <expression> # alignof (an expression) 3783 // ::= nx <expression> # noexcept (expression) 3784 // ::= <template-param> 3785 // ::= <function-param> 3786 // ::= dt <expression> <unresolved-name> # expr.name 3787 // ::= pt <expression> <unresolved-name> # expr->name 3788 // ::= ds <expression> <expression> # expr.*expr 3789 // ::= sZ <template-param> # size of a parameter pack 3790 // ::= sZ <function-param> # size of a function parameter pack 3791 // ::= sp <expression> # pack expansion 3792 // ::= tw <expression> # throw expression 3793 // ::= tr # throw with no operand (rethrow) 3794 // ::= <unresolved-name> # f(p), N::f(p), ::f(p), 3795 // # freestanding dependent name (e.g., T::x), 3796 // # objectless nonstatic member reference 3797 // ::= fL <binary-operator-name> <expression> <expression> 3798 // ::= fR <binary-operator-name> <expression> <expression> 3799 // ::= fl <binary-operator-name> <expression> 3800 // ::= fr <binary-operator-name> <expression> 3801 // ::= <expr-primary> 3802 Node *Db::parseExpr() { 3803 bool Global = consumeIf("gs"); 3804 if (numLeft() < 2) 3805 return nullptr; 3806 3807 switch (*First) { 3808 case 'L': 3809 return parseExprPrimary(); 3810 case 'T': 3811 return parseTemplateParam(); 3812 case 'f': 3813 return parseFunctionParam(); 3814 case 'a': 3815 switch (First[1]) { 3816 case 'a': 3817 First += 2; 3818 return parseBinaryExpr("&&"); 3819 case 'd': 3820 First += 2; 3821 return parsePrefixExpr("&"); 3822 case 'n': 3823 First += 2; 3824 return parseBinaryExpr("&"); 3825 case 'N': 3826 First += 2; 3827 return parseBinaryExpr("&="); 3828 case 'S': 3829 First += 2; 3830 return parseBinaryExpr("="); 3831 case 't': { 3832 First += 2; 3833 Node *Ty = parseType(); 3834 if (Ty == nullptr) 3835 return nullptr; 3836 return make<EnclosingExpr>("alignof (", Ty, ")"); 3837 } 3838 case 'z': { 3839 First += 2; 3840 Node *Ty = parseExpr(); 3841 if (Ty == nullptr) 3842 return nullptr; 3843 return make<EnclosingExpr>("alignof (", Ty, ")"); 3844 } 3845 } 3846 return nullptr; 3847 case 'c': 3848 switch (First[1]) { 3849 // cc <type> <expression> # const_cast<type>(expression) 3850 case 'c': { 3851 First += 2; 3852 Node *Ty = parseType(); 3853 if (Ty == nullptr) 3854 return Ty; 3855 Node *Ex = parseExpr(); 3856 if (Ex == nullptr) 3857 return Ex; 3858 return make<CastExpr>("const_cast", Ty, Ex); 3859 } 3860 // cl <expression>+ E # call 3861 case 'l': { 3862 First += 2; 3863 Node *Callee = parseExpr(); 3864 if (Callee == nullptr) 3865 return Callee; 3866 size_t ExprsBegin = Names.size(); 3867 while (!consumeIf('E')) { 3868 Node *E = parseExpr(); 3869 if (E == nullptr) 3870 return E; 3871 Names.push_back(E); 3872 } 3873 return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin)); 3874 } 3875 case 'm': 3876 First += 2; 3877 return parseBinaryExpr(","); 3878 case 'o': 3879 First += 2; 3880 return parsePrefixExpr("~"); 3881 case 'v': 3882 return parseConversionExpr(); 3883 } 3884 return nullptr; 3885 case 'd': 3886 switch (First[1]) { 3887 case 'a': { 3888 First += 2; 3889 Node *Ex = parseExpr(); 3890 if (Ex == nullptr) 3891 return Ex; 3892 return make<DeleteExpr>(Ex, Global, /*is_array=*/true); 3893 } 3894 case 'c': { 3895 First += 2; 3896 Node *T = parseType(); 3897 if (T == nullptr) 3898 return T; 3899 Node *Ex = parseExpr(); 3900 if (Ex == nullptr) 3901 return Ex; 3902 return make<CastExpr>("dynamic_cast", T, Ex); 3903 } 3904 case 'e': 3905 First += 2; 3906 return parsePrefixExpr("*"); 3907 case 'l': { 3908 First += 2; 3909 Node *E = parseExpr(); 3910 if (E == nullptr) 3911 return E; 3912 return make<DeleteExpr>(E, Global, /*is_array=*/false); 3913 } 3914 case 'n': 3915 return parseUnresolvedName(); 3916 case 's': { 3917 First += 2; 3918 Node *LHS = parseExpr(); 3919 if (LHS == nullptr) 3920 return nullptr; 3921 Node *RHS = parseExpr(); 3922 if (RHS == nullptr) 3923 return nullptr; 3924 return make<MemberExpr>(LHS, ".*", RHS); 3925 } 3926 case 't': { 3927 First += 2; 3928 Node *LHS = parseExpr(); 3929 if (LHS == nullptr) 3930 return LHS; 3931 Node *RHS = parseExpr(); 3932 if (RHS == nullptr) 3933 return nullptr; 3934 return make<MemberExpr>(LHS, ".", RHS); 3935 } 3936 case 'v': 3937 First += 2; 3938 return parseBinaryExpr("/"); 3939 case 'V': 3940 First += 2; 3941 return parseBinaryExpr("/="); 3942 } 3943 return nullptr; 3944 case 'e': 3945 switch (First[1]) { 3946 case 'o': 3947 First += 2; 3948 return parseBinaryExpr("^"); 3949 case 'O': 3950 First += 2; 3951 return parseBinaryExpr("^="); 3952 case 'q': 3953 First += 2; 3954 return parseBinaryExpr("=="); 3955 } 3956 return nullptr; 3957 case 'g': 3958 switch (First[1]) { 3959 case 'e': 3960 First += 2; 3961 return parseBinaryExpr(">="); 3962 case 't': 3963 First += 2; 3964 return parseBinaryExpr(">"); 3965 } 3966 return nullptr; 3967 case 'i': 3968 switch (First[1]) { 3969 case 'x': { 3970 First += 2; 3971 Node *Base = parseExpr(); 3972 if (Base == nullptr) 3973 return nullptr; 3974 Node *Index = parseExpr(); 3975 if (Index == nullptr) 3976 return Index; 3977 return make<ArraySubscriptExpr>(Base, Index); 3978 } 3979 case 'l': { 3980 First += 2; 3981 size_t InitsBegin = Names.size(); 3982 while (!consumeIf('E')) { 3983 Node *E = parseBracedExpr(); 3984 if (E == nullptr) 3985 return nullptr; 3986 Names.push_back(E); 3987 } 3988 return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin)); 3989 } 3990 } 3991 return nullptr; 3992 case 'l': 3993 switch (First[1]) { 3994 case 'e': 3995 First += 2; 3996 return parseBinaryExpr("<="); 3997 case 's': 3998 First += 2; 3999 return parseBinaryExpr("<<"); 4000 case 'S': 4001 First += 2; 4002 return parseBinaryExpr("<<="); 4003 case 't': 4004 First += 2; 4005 return parseBinaryExpr("<"); 4006 } 4007 return nullptr; 4008 case 'm': 4009 switch (First[1]) { 4010 case 'i': 4011 First += 2; 4012 return parseBinaryExpr("-"); 4013 case 'I': 4014 First += 2; 4015 return parseBinaryExpr("-="); 4016 case 'l': 4017 First += 2; 4018 return parseBinaryExpr("*"); 4019 case 'L': 4020 First += 2; 4021 return parseBinaryExpr("*="); 4022 case 'm': 4023 First += 2; 4024 if (consumeIf('_')) 4025 return parsePrefixExpr("--"); 4026 Node *Ex = parseExpr(); 4027 if (Ex == nullptr) 4028 return nullptr; 4029 return make<PostfixExpr>(Ex, "--"); 4030 } 4031 return nullptr; 4032 case 'n': 4033 switch (First[1]) { 4034 case 'a': 4035 case 'w': 4036 return parseNewExpr(); 4037 case 'e': 4038 First += 2; 4039 return parseBinaryExpr("!="); 4040 case 'g': 4041 First += 2; 4042 return parsePrefixExpr("-"); 4043 case 't': 4044 First += 2; 4045 return parsePrefixExpr("!"); 4046 case 'x': 4047 First += 2; 4048 Node *Ex = parseExpr(); 4049 if (Ex == nullptr) 4050 return Ex; 4051 return make<EnclosingExpr>("noexcept (", Ex, ")"); 4052 } 4053 return nullptr; 4054 case 'o': 4055 switch (First[1]) { 4056 case 'n': 4057 return parseUnresolvedName(); 4058 case 'o': 4059 First += 2; 4060 return parseBinaryExpr("||"); 4061 case 'r': 4062 First += 2; 4063 return parseBinaryExpr("|"); 4064 case 'R': 4065 First += 2; 4066 return parseBinaryExpr("|="); 4067 } 4068 return nullptr; 4069 case 'p': 4070 switch (First[1]) { 4071 case 'm': 4072 First += 2; 4073 return parseBinaryExpr("->*"); 4074 case 'l': 4075 First += 2; 4076 return parseBinaryExpr("+"); 4077 case 'L': 4078 First += 2; 4079 return parseBinaryExpr("+="); 4080 case 'p': { 4081 First += 2; 4082 if (consumeIf('_')) 4083 return parsePrefixExpr("++"); 4084 Node *Ex = parseExpr(); 4085 if (Ex == nullptr) 4086 return Ex; 4087 return make<PostfixExpr>(Ex, "++"); 4088 } 4089 case 's': 4090 First += 2; 4091 return parsePrefixExpr("+"); 4092 case 't': { 4093 First += 2; 4094 Node *L = parseExpr(); 4095 if (L == nullptr) 4096 return nullptr; 4097 Node *R = parseExpr(); 4098 if (R == nullptr) 4099 return nullptr; 4100 return make<MemberExpr>(L, "->", R); 4101 } 4102 } 4103 return nullptr; 4104 case 'q': 4105 if (First[1] == 'u') { 4106 First += 2; 4107 Node *Cond = parseExpr(); 4108 if (Cond == nullptr) 4109 return nullptr; 4110 Node *LHS = parseExpr(); 4111 if (LHS == nullptr) 4112 return nullptr; 4113 Node *RHS = parseExpr(); 4114 if (RHS == nullptr) 4115 return nullptr; 4116 return make<ConditionalExpr>(Cond, LHS, RHS); 4117 } 4118 return nullptr; 4119 case 'r': 4120 switch (First[1]) { 4121 case 'c': { 4122 First += 2; 4123 Node *T = parseType(); 4124 if (T == nullptr) 4125 return T; 4126 Node *Ex = parseExpr(); 4127 if (Ex == nullptr) 4128 return Ex; 4129 return make<CastExpr>("reinterpret_cast", T, Ex); 4130 } 4131 case 'm': 4132 First += 2; 4133 return parseBinaryExpr("%"); 4134 case 'M': 4135 First += 2; 4136 return parseBinaryExpr("%="); 4137 case 's': 4138 First += 2; 4139 return parseBinaryExpr(">>"); 4140 case 'S': 4141 First += 2; 4142 return parseBinaryExpr(">>="); 4143 } 4144 return nullptr; 4145 case 's': 4146 switch (First[1]) { 4147 case 'c': { 4148 First += 2; 4149 Node *T = parseType(); 4150 if (T == nullptr) 4151 return T; 4152 Node *Ex = parseExpr(); 4153 if (Ex == nullptr) 4154 return Ex; 4155 return make<CastExpr>("static_cast", T, Ex); 4156 } 4157 case 'p': { 4158 First += 2; 4159 Node *Child = parseExpr(); 4160 if (Child == nullptr) 4161 return nullptr; 4162 return make<ParameterPackExpansion>(Child); 4163 } 4164 case 'r': 4165 return parseUnresolvedName(); 4166 case 't': { 4167 First += 2; 4168 Node *Ty = parseType(); 4169 if (Ty == nullptr) 4170 return Ty; 4171 return make<EnclosingExpr>("sizeof (", Ty, ")"); 4172 } 4173 case 'z': { 4174 First += 2; 4175 Node *Ex = parseExpr(); 4176 if (Ex == nullptr) 4177 return Ex; 4178 return make<EnclosingExpr>("sizeof (", Ex, ")"); 4179 } 4180 case 'Z': 4181 First += 2; 4182 if (look() == 'T') { 4183 Node *R = parseTemplateParam(); 4184 if (R == nullptr) 4185 return nullptr; 4186 return make<SizeofParamPackExpr>(R); 4187 } else if (look() == 'f') { 4188 Node *FP = parseFunctionParam(); 4189 if (FP == nullptr) 4190 return nullptr; 4191 return make<EnclosingExpr>("sizeof...", FP, ")"); 4192 } 4193 return nullptr; 4194 } 4195 return nullptr; 4196 case 't': 4197 switch (First[1]) { 4198 case 'e': { 4199 First += 2; 4200 Node *Ex = parseExpr(); 4201 if (Ex == nullptr) 4202 return Ex; 4203 return make<EnclosingExpr>("typeid (", Ex, ")"); 4204 } 4205 case 'i': { 4206 First += 2; 4207 Node *Ty = parseType(); 4208 if (Ty == nullptr) 4209 return Ty; 4210 return make<EnclosingExpr>("typeid (", Ty, ")"); 4211 } 4212 case 'l': { 4213 First += 2; 4214 Node *Ty = parseType(); 4215 if (Ty == nullptr) 4216 return nullptr; 4217 size_t InitsBegin = Names.size(); 4218 while (!consumeIf('E')) { 4219 Node *E = parseBracedExpr(); 4220 if (E == nullptr) 4221 return nullptr; 4222 Names.push_back(E); 4223 } 4224 return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin)); 4225 } 4226 case 'r': 4227 First += 2; 4228 return make<NameType>("throw"); 4229 case 'w': { 4230 First += 2; 4231 Node *Ex = parseExpr(); 4232 if (Ex == nullptr) 4233 return nullptr; 4234 return make<ThrowExpr>(Ex); 4235 } 4236 } 4237 return nullptr; 4238 case '1': 4239 case '2': 4240 case '3': 4241 case '4': 4242 case '5': 4243 case '6': 4244 case '7': 4245 case '8': 4246 case '9': 4247 return parseUnresolvedName(); 4248 } 4249 return nullptr; 4250 } 4251 4252 // <call-offset> ::= h <nv-offset> _ 4253 // ::= v <v-offset> _ 4254 // 4255 // <nv-offset> ::= <offset number> 4256 // # non-virtual base override 4257 // 4258 // <v-offset> ::= <offset number> _ <virtual offset number> 4259 // # virtual base override, with vcall offset 4260 bool Db::parseCallOffset() { 4261 // Just scan through the call offset, we never add this information into the 4262 // output. 4263 if (consumeIf('h')) 4264 return parseNumber(true).empty() || !consumeIf('_'); 4265 if (consumeIf('v')) 4266 return parseNumber(true).empty() || !consumeIf('_') || 4267 parseNumber(true).empty() || !consumeIf('_'); 4268 return true; 4269 } 4270 4271 // <special-name> ::= TV <type> # virtual table 4272 // ::= TT <type> # VTT structure (construction vtable index) 4273 // ::= TI <type> # typeinfo structure 4274 // ::= TS <type> # typeinfo name (null-terminated byte string) 4275 // ::= Tc <call-offset> <call-offset> <base encoding> 4276 // # base is the nominal target function of thunk 4277 // # first call-offset is 'this' adjustment 4278 // # second call-offset is result adjustment 4279 // ::= T <call-offset> <base encoding> 4280 // # base is the nominal target function of thunk 4281 // ::= GV <object name> # Guard variable for one-time initialization 4282 // # No <type> 4283 // ::= TW <object name> # Thread-local wrapper 4284 // ::= TH <object name> # Thread-local initialization 4285 // ::= GR <object name> _ # First temporary 4286 // ::= GR <object name> <seq-id> _ # Subsequent temporaries 4287 // extension ::= TC <first type> <number> _ <second type> # construction vtable for second-in-first 4288 // extension ::= GR <object name> # reference temporary for object 4289 Node *Db::parseSpecialName() { 4290 switch (look()) { 4291 case 'T': 4292 switch (look(1)) { 4293 // TV <type> # virtual table 4294 case 'V': { 4295 First += 2; 4296 Node *Ty = parseType(); 4297 if (Ty == nullptr) 4298 return nullptr; 4299 return make<SpecialName>("vtable for ", Ty); 4300 } 4301 // TT <type> # VTT structure (construction vtable index) 4302 case 'T': { 4303 First += 2; 4304 Node *Ty = parseType(); 4305 if (Ty == nullptr) 4306 return nullptr; 4307 return make<SpecialName>("VTT for ", Ty); 4308 } 4309 // TI <type> # typeinfo structure 4310 case 'I': { 4311 First += 2; 4312 Node *Ty = parseType(); 4313 if (Ty == nullptr) 4314 return nullptr; 4315 return make<SpecialName>("typeinfo for ", Ty); 4316 } 4317 // TS <type> # typeinfo name (null-terminated byte string) 4318 case 'S': { 4319 First += 2; 4320 Node *Ty = parseType(); 4321 if (Ty == nullptr) 4322 return nullptr; 4323 return make<SpecialName>("typeinfo name for ", Ty); 4324 } 4325 // Tc <call-offset> <call-offset> <base encoding> 4326 case 'c': { 4327 First += 2; 4328 if (parseCallOffset() || parseCallOffset()) 4329 return nullptr; 4330 Node *Encoding = parseEncoding(); 4331 if (Encoding == nullptr) 4332 return nullptr; 4333 return make<SpecialName>("covariant return thunk to ", Encoding); 4334 } 4335 // extension ::= TC <first type> <number> _ <second type> 4336 // # construction vtable for second-in-first 4337 case 'C': { 4338 First += 2; 4339 Node *FirstType = parseType(); 4340 if (FirstType == nullptr) 4341 return nullptr; 4342 if (parseNumber(true).empty() || !consumeIf('_')) 4343 return nullptr; 4344 Node *SecondType = parseType(); 4345 if (SecondType == nullptr) 4346 return nullptr; 4347 return make<CtorVtableSpecialName>(SecondType, FirstType); 4348 } 4349 // TW <object name> # Thread-local wrapper 4350 case 'W': { 4351 First += 2; 4352 Node *Name = parseName(); 4353 if (Name == nullptr) 4354 return nullptr; 4355 return make<SpecialName>("thread-local wrapper routine for ", Name); 4356 } 4357 // TH <object name> # Thread-local initialization 4358 case 'H': { 4359 First += 2; 4360 Node *Name = parseName(); 4361 if (Name == nullptr) 4362 return nullptr; 4363 return make<SpecialName>("thread-local initialization routine for ", Name); 4364 } 4365 // T <call-offset> <base encoding> 4366 default: { 4367 ++First; 4368 bool IsVirt = look() == 'v'; 4369 if (parseCallOffset()) 4370 return nullptr; 4371 Node *BaseEncoding = parseEncoding(); 4372 if (BaseEncoding == nullptr) 4373 return nullptr; 4374 if (IsVirt) 4375 return make<SpecialName>("virtual thunk to ", BaseEncoding); 4376 else 4377 return make<SpecialName>("non-virtual thunk to ", BaseEncoding); 4378 } 4379 } 4380 case 'G': 4381 switch (look(1)) { 4382 // GV <object name> # Guard variable for one-time initialization 4383 case 'V': { 4384 First += 2; 4385 Node *Name = parseName(); 4386 if (Name == nullptr) 4387 return nullptr; 4388 return make<SpecialName>("guard variable for ", Name); 4389 } 4390 // GR <object name> # reference temporary for object 4391 // GR <object name> _ # First temporary 4392 // GR <object name> <seq-id> _ # Subsequent temporaries 4393 case 'R': { 4394 First += 2; 4395 Node *Name = parseName(); 4396 if (Name == nullptr) 4397 return nullptr; 4398 size_t Count; 4399 bool ParsedSeqId = !parseSeqId(&Count); 4400 if (!consumeIf('_') && ParsedSeqId) 4401 return nullptr; 4402 return make<SpecialName>("reference temporary for ", Name); 4403 } 4404 } 4405 } 4406 return nullptr; 4407 } 4408 4409 // <encoding> ::= <function name> <bare-function-type> 4410 // ::= <data name> 4411 // ::= <special-name> 4412 Node *Db::parseEncoding() { 4413 if (look() == 'G' || look() == 'T') 4414 return parseSpecialName(); 4415 4416 auto IsEndOfEncoding = [&] { 4417 // The set of chars that can potentially follow an <encoding> (none of which 4418 // can start a <type>). Enumerating these allows us to avoid speculative 4419 // parsing. 4420 return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_'; 4421 }; 4422 4423 NameState NameInfo(this); 4424 Node *Name = parseName(&NameInfo); 4425 if (Name == nullptr) 4426 return nullptr; 4427 4428 if (resolveForwardTemplateRefs(NameInfo)) 4429 return nullptr; 4430 4431 if (IsEndOfEncoding()) 4432 return Name; 4433 4434 Node *Attrs = nullptr; 4435 if (consumeIf("Ua9enable_ifI")) { 4436 size_t BeforeArgs = Names.size(); 4437 while (!consumeIf('E')) { 4438 Node *Arg = parseTemplateArg(); 4439 if (Arg == nullptr) 4440 return nullptr; 4441 Names.push_back(Arg); 4442 } 4443 Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs)); 4444 } 4445 4446 Node *ReturnType = nullptr; 4447 if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) { 4448 ReturnType = parseType(); 4449 if (ReturnType == nullptr) 4450 return nullptr; 4451 } 4452 4453 if (consumeIf('v')) 4454 return make<FunctionEncoding>(ReturnType, Name, NodeArray(), 4455 Attrs, NameInfo.CVQualifiers, 4456 NameInfo.ReferenceQualifier); 4457 4458 size_t ParamsBegin = Names.size(); 4459 do { 4460 Node *Ty = parseType(); 4461 if (Ty == nullptr) 4462 return nullptr; 4463 Names.push_back(Ty); 4464 } while (!IsEndOfEncoding()); 4465 4466 return make<FunctionEncoding>(ReturnType, Name, 4467 popTrailingNodeArray(ParamsBegin), 4468 Attrs, NameInfo.CVQualifiers, 4469 NameInfo.ReferenceQualifier); 4470 } 4471 4472 template <class Float> 4473 struct FloatData; 4474 4475 template <> 4476 struct FloatData<float> 4477 { 4478 static const size_t mangled_size = 8; 4479 static const size_t max_demangled_size = 24; 4480 static constexpr const char* spec = "%af"; 4481 }; 4482 4483 constexpr const char* FloatData<float>::spec; 4484 4485 template <> 4486 struct FloatData<double> 4487 { 4488 static const size_t mangled_size = 16; 4489 static const size_t max_demangled_size = 32; 4490 static constexpr const char* spec = "%a"; 4491 }; 4492 4493 constexpr const char* FloatData<double>::spec; 4494 4495 template <> 4496 struct FloatData<long double> 4497 { 4498 #if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \ 4499 defined(__wasm__) 4500 static const size_t mangled_size = 32; 4501 #elif defined(__arm__) || defined(__mips__) || defined(__hexagon__) 4502 static const size_t mangled_size = 16; 4503 #else 4504 static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms 4505 #endif 4506 static const size_t max_demangled_size = 40; 4507 static constexpr const char *spec = "%LaL"; 4508 }; 4509 4510 constexpr const char *FloatData<long double>::spec; 4511 4512 template <class Float> Node *Db::parseFloatingLiteral() { 4513 const size_t N = FloatData<Float>::mangled_size; 4514 if (numLeft() <= N) 4515 return nullptr; 4516 StringView Data(First, First + N); 4517 for (char C : Data) 4518 if (!std::isxdigit(C)) 4519 return nullptr; 4520 First += N; 4521 if (!consumeIf('E')) 4522 return nullptr; 4523 return make<FloatExpr<Float>>(Data); 4524 } 4525 4526 // <seq-id> ::= <0-9A-Z>+ 4527 bool Db::parseSeqId(size_t *Out) { 4528 if (!(look() >= '0' && look() <= '9') && 4529 !(look() >= 'A' && look() <= 'Z')) 4530 return true; 4531 4532 size_t Id = 0; 4533 while (true) { 4534 if (look() >= '0' && look() <= '9') { 4535 Id *= 36; 4536 Id += static_cast<size_t>(look() - '0'); 4537 } else if (look() >= 'A' && look() <= 'Z') { 4538 Id *= 36; 4539 Id += static_cast<size_t>(look() - 'A') + 10; 4540 } else { 4541 *Out = Id; 4542 return false; 4543 } 4544 ++First; 4545 } 4546 } 4547 4548 // <substitution> ::= S <seq-id> _ 4549 // ::= S_ 4550 // <substitution> ::= Sa # ::std::allocator 4551 // <substitution> ::= Sb # ::std::basic_string 4552 // <substitution> ::= Ss # ::std::basic_string < char, 4553 // ::std::char_traits<char>, 4554 // ::std::allocator<char> > 4555 // <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> > 4556 // <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> > 4557 // <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> > 4558 Node *Db::parseSubstitution() { 4559 if (!consumeIf('S')) 4560 return nullptr; 4561 4562 if (std::islower(look())) { 4563 Node *SpecialSub; 4564 switch (look()) { 4565 case 'a': 4566 ++First; 4567 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::allocator); 4568 break; 4569 case 'b': 4570 ++First; 4571 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::basic_string); 4572 break; 4573 case 's': 4574 ++First; 4575 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::string); 4576 break; 4577 case 'i': 4578 ++First; 4579 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::istream); 4580 break; 4581 case 'o': 4582 ++First; 4583 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::ostream); 4584 break; 4585 case 'd': 4586 ++First; 4587 SpecialSub = make<SpecialSubstitution>(SpecialSubKind::iostream); 4588 break; 4589 default: 4590 return nullptr; 4591 } 4592 // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution> 4593 // has ABI tags, the tags are appended to the substitution; the result is a 4594 // substitutable component. 4595 Node *WithTags = parseAbiTags(SpecialSub); 4596 if (WithTags != SpecialSub) { 4597 Subs.push_back(WithTags); 4598 SpecialSub = WithTags; 4599 } 4600 return SpecialSub; 4601 } 4602 4603 // ::= S_ 4604 if (consumeIf('_')) { 4605 if (Subs.empty()) 4606 return nullptr; 4607 return Subs[0]; 4608 } 4609 4610 // ::= S <seq-id> _ 4611 size_t Index = 0; 4612 if (parseSeqId(&Index)) 4613 return nullptr; 4614 ++Index; 4615 if (!consumeIf('_') || Index >= Subs.size()) 4616 return nullptr; 4617 return Subs[Index]; 4618 } 4619 4620 // <template-param> ::= T_ # first template parameter 4621 // ::= T <parameter-2 non-negative number> _ 4622 Node *Db::parseTemplateParam() { 4623 if (!consumeIf('T')) 4624 return nullptr; 4625 4626 size_t Index = 0; 4627 if (!consumeIf('_')) { 4628 if (parsePositiveInteger(&Index)) 4629 return nullptr; 4630 ++Index; 4631 if (!consumeIf('_')) 4632 return nullptr; 4633 } 4634 4635 // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter list 4636 // are mangled as the corresponding artificial template type parameter. 4637 if (ParsingLambdaParams) 4638 return make<NameType>("auto"); 4639 4640 // If we're in a context where this <template-param> refers to a 4641 // <template-arg> further ahead in the mangled name (currently just conversion 4642 // operator types), then we should only look it up in the right context. 4643 if (PermitForwardTemplateReferences) { 4644 ForwardTemplateRefs.push_back(make<ForwardTemplateReference>(Index)); 4645 return ForwardTemplateRefs.back(); 4646 } 4647 4648 if (Index >= TemplateParams.size()) 4649 return nullptr; 4650 return TemplateParams[Index]; 4651 } 4652 4653 // <template-arg> ::= <type> # type or template 4654 // ::= X <expression> E # expression 4655 // ::= <expr-primary> # simple expressions 4656 // ::= J <template-arg>* E # argument pack 4657 // ::= LZ <encoding> E # extension 4658 Node *Db::parseTemplateArg() { 4659 switch (look()) { 4660 case 'X': { 4661 ++First; 4662 Node *Arg = parseExpr(); 4663 if (Arg == nullptr || !consumeIf('E')) 4664 return nullptr; 4665 return Arg; 4666 } 4667 case 'J': { 4668 ++First; 4669 size_t ArgsBegin = Names.size(); 4670 while (!consumeIf('E')) { 4671 Node *Arg = parseTemplateArg(); 4672 if (Arg == nullptr) 4673 return nullptr; 4674 Names.push_back(Arg); 4675 } 4676 NodeArray Args = popTrailingNodeArray(ArgsBegin); 4677 return make<TemplateArgumentPack>(Args); 4678 } 4679 case 'L': { 4680 // ::= LZ <encoding> E # extension 4681 if (look(1) == 'Z') { 4682 First += 2; 4683 Node *Arg = parseEncoding(); 4684 if (Arg == nullptr || !consumeIf('E')) 4685 return nullptr; 4686 return Arg; 4687 } 4688 // ::= <expr-primary> # simple expressions 4689 return parseExprPrimary(); 4690 } 4691 default: 4692 return parseType(); 4693 } 4694 } 4695 4696 // <template-args> ::= I <template-arg>* E 4697 // extension, the abi says <template-arg>+ 4698 Node *Db::parseTemplateArgs(bool TagTemplates) { 4699 if (!consumeIf('I')) 4700 return nullptr; 4701 4702 // <template-params> refer to the innermost <template-args>. Clear out any 4703 // outer args that we may have inserted into TemplateParams. 4704 if (TagTemplates) 4705 TemplateParams.clear(); 4706 4707 size_t ArgsBegin = Names.size(); 4708 while (!consumeIf('E')) { 4709 if (TagTemplates) { 4710 auto OldParams = std::move(TemplateParams); 4711 Node *Arg = parseTemplateArg(); 4712 TemplateParams = std::move(OldParams); 4713 if (Arg == nullptr) 4714 return nullptr; 4715 Names.push_back(Arg); 4716 Node *TableEntry = Arg; 4717 if (Arg->getKind() == Node::KTemplateArgumentPack) { 4718 TableEntry = make<ParameterPack>( 4719 static_cast<TemplateArgumentPack*>(TableEntry)->getElements()); 4720 } 4721 TemplateParams.push_back(TableEntry); 4722 } else { 4723 Node *Arg = parseTemplateArg(); 4724 if (Arg == nullptr) 4725 return nullptr; 4726 Names.push_back(Arg); 4727 } 4728 } 4729 return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin)); 4730 } 4731 4732 // <discriminator> := _ <non-negative number> # when number < 10 4733 // := __ <non-negative number> _ # when number >= 10 4734 // extension := decimal-digit+ # at the end of string 4735 4736 const char* 4737 parse_discriminator(const char* first, const char* last) 4738 { 4739 // parse but ignore discriminator 4740 if (first != last) 4741 { 4742 if (*first == '_') 4743 { 4744 const char* t1 = first+1; 4745 if (t1 != last) 4746 { 4747 if (std::isdigit(*t1)) 4748 first = t1+1; 4749 else if (*t1 == '_') 4750 { 4751 for (++t1; t1 != last && std::isdigit(*t1); ++t1) 4752 ; 4753 if (t1 != last && *t1 == '_') 4754 first = t1 + 1; 4755 } 4756 } 4757 } 4758 else if (std::isdigit(*first)) 4759 { 4760 const char* t1 = first+1; 4761 for (; t1 != last && std::isdigit(*t1); ++t1) 4762 ; 4763 if (t1 == last) 4764 first = last; 4765 } 4766 } 4767 return first; 4768 } 4769 4770 // <mangled-name> ::= _Z <encoding> 4771 // ::= <type> 4772 // extension ::= ___Z <encoding> _block_invoke 4773 // extension ::= ___Z <encoding> _block_invoke<decimal-digit>+ 4774 // extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+ 4775 Node *Db::parse() { 4776 if (consumeIf("_Z")) { 4777 Node *Encoding = parseEncoding(); 4778 if (Encoding == nullptr) 4779 return nullptr; 4780 if (look() == '.') { 4781 Encoding = make<DotSuffix>(Encoding, StringView(First, Last)); 4782 First = Last; 4783 } 4784 if (numLeft() != 0) 4785 return nullptr; 4786 return Encoding; 4787 } 4788 4789 if (consumeIf("___Z")) { 4790 Node *Encoding = parseEncoding(); 4791 if (Encoding == nullptr || !consumeIf("_block_invoke")) 4792 return nullptr; 4793 bool RequireNumber = consumeIf('_'); 4794 if (parseNumber().empty() && RequireNumber) 4795 return nullptr; 4796 if (numLeft() != 0) 4797 return nullptr; 4798 return make<SpecialName>("invocation function for block in ", Encoding); 4799 } 4800 4801 Node *Ty = parseType(); 4802 if (numLeft() != 0) 4803 return nullptr; 4804 return Ty; 4805 } 4806 } // unnamed namespace 4807 4808 enum { 4809 unknown_error = -4, 4810 invalid_args = -3, 4811 invalid_mangled_name = -2, 4812 memory_alloc_failure = -1, 4813 success = 0, 4814 }; 4815 4816 char *llvm::itaniumDemangle(const char *MangledName, char *Buf, 4817 size_t *N, int *Status) { 4818 if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) { 4819 if (Status) 4820 *Status = invalid_args; 4821 return nullptr; 4822 } 4823 4824 size_t BufSize = Buf != nullptr ? *N : 0; 4825 int InternalStatus = success; 4826 size_t MangledNameLength = std::strlen(MangledName); 4827 4828 Db Parser(MangledName, MangledName + MangledNameLength); 4829 Node *AST = Parser.parse(); 4830 4831 if (AST == nullptr) 4832 InternalStatus = invalid_mangled_name; 4833 4834 if (InternalStatus == success) { 4835 assert(Parser.ForwardTemplateRefs.empty()); 4836 4837 if (Buf == nullptr) { 4838 BufSize = 1024; 4839 Buf = static_cast<char*>(std::malloc(BufSize)); 4840 } 4841 4842 if (Buf) { 4843 OutputStream Stream(Buf, BufSize); 4844 AST->print(Stream); 4845 Stream += '\0'; 4846 if (N != nullptr) 4847 *N = Stream.getCurrentPosition(); 4848 Buf = Stream.getBuffer(); 4849 } else 4850 InternalStatus = memory_alloc_failure; 4851 } 4852 4853 if (Status) 4854 *Status = InternalStatus; 4855 return InternalStatus == success ? Buf : nullptr; 4856 } 4857