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