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