1 //===- MicrosoftDemangle.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 // This file defines a demangler for MSVC-style mangled symbols.
11 //
12 // This file has no dependencies on the rest of LLVM so that it can be
13 // easily reused in other programs such as libcxxabi.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Demangle/Demangle.h"
18 
19 #include "Compiler.h"
20 #include "StringView.h"
21 #include "Utility.h"
22 
23 #include <cctype>
24 #include <cstdio>
25 #include <tuple>
26 
27 // This memory allocator is extremely fast, but it doesn't call dtors
28 // for allocated objects. That means you can't use STL containers
29 // (such as std::vector) with this allocator. But it pays off --
30 // the demangler is 3x faster with this allocator compared to one with
31 // STL containers.
32 namespace {
33   constexpr size_t AllocUnit = 4096;
34 
35 class ArenaAllocator {
36   struct AllocatorNode {
37     uint8_t *Buf = nullptr;
38     size_t Used = 0;
39     size_t Capacity = 0;
40     AllocatorNode *Next = nullptr;
41   };
42 
43   void addNode(size_t Capacity) {
44     AllocatorNode *NewHead = new AllocatorNode;
45     NewHead->Buf = new uint8_t[Capacity];
46     NewHead->Next = Head;
47     NewHead->Capacity = Capacity;
48     Head = NewHead;
49     NewHead->Used = 0;
50   }
51 
52 public:
53   ArenaAllocator() { addNode(AllocUnit); }
54 
55   ~ArenaAllocator() {
56     while (Head) {
57       assert(Head->Buf);
58       delete[] Head->Buf;
59       AllocatorNode *Next = Head->Next;
60       delete Head;
61       Head = Next;
62     }
63   }
64 
65   char *allocUnalignedBuffer(size_t Length) {
66     uint8_t *Buf = Head->Buf + Head->Used;
67 
68     Head->Used += Length;
69     if (Head->Used > Head->Capacity) {
70       // It's possible we need a buffer which is larger than our default unit
71       // size, so we need to be careful to add a node with capacity that is at
72       // least as large as what we need.
73       addNode(std::max(AllocUnit, Length));
74       Head->Used = Length;
75       Buf = Head->Buf;
76     }
77 
78     return reinterpret_cast<char *>(Buf);
79   }
80 
81   template <typename T, typename... Args> T *alloc(Args &&... ConstructorArgs) {
82 
83     size_t Size = sizeof(T);
84     assert(Head && Head->Buf);
85 
86     size_t P = (size_t)Head->Buf + Head->Used;
87     uintptr_t AlignedP =
88         (((size_t)P + alignof(T) - 1) & ~(size_t)(alignof(T) - 1));
89     uint8_t *PP = (uint8_t *)AlignedP;
90     size_t Adjustment = AlignedP - P;
91 
92     Head->Used += Size + Adjustment;
93     if (Head->Used < Head->Capacity)
94       return new (PP) T(std::forward<Args>(ConstructorArgs)...);
95 
96     addNode(AllocUnit);
97     Head->Used = Size;
98     return new (Head->Buf) T(std::forward<Args>(ConstructorArgs)...);
99   }
100 
101 private:
102   AllocatorNode *Head = nullptr;
103 };
104 } // namespace
105 
106 static bool startsWithDigit(StringView S) {
107   return !S.empty() && std::isdigit(S.front());
108 }
109 
110 // Writes a space if the last token does not end with a punctuation.
111 static void outputSpaceIfNecessary(OutputStream &OS) {
112   if (OS.empty())
113     return;
114 
115   char C = OS.back();
116   if (isalnum(C) || C == '>')
117     OS << " ";
118 }
119 
120 // Storage classes
121 enum Qualifiers : uint8_t {
122   Q_None = 0,
123   Q_Const = 1 << 0,
124   Q_Volatile = 1 << 1,
125   Q_Far = 1 << 2,
126   Q_Huge = 1 << 3,
127   Q_Unaligned = 1 << 4,
128   Q_Restrict = 1 << 5,
129   Q_Pointer64 = 1 << 6
130 };
131 
132 enum class StorageClass : uint8_t {
133   None,
134   PrivateStatic,
135   ProtectedStatic,
136   PublicStatic,
137   Global,
138   FunctionLocalStatic
139 };
140 
141 enum class QualifierMangleMode { Drop, Mangle, Result };
142 
143 enum class PointerAffinity { Pointer, Reference, RValueReference };
144 
145 // Calling conventions
146 enum class CallingConv : uint8_t {
147   None,
148   Cdecl,
149   Pascal,
150   Thiscall,
151   Stdcall,
152   Fastcall,
153   Clrcall,
154   Eabi,
155   Vectorcall,
156   Regcall,
157 };
158 
159 enum class ReferenceKind : uint8_t { None, LValueRef, RValueRef };
160 
161 // Types
162 enum class PrimTy : uint8_t {
163   Unknown,
164   None,
165   Function,
166   Ptr,
167   MemberPtr,
168   Array,
169 
170   Struct,
171   Union,
172   Class,
173   Enum,
174 
175   Void,
176   Bool,
177   Char,
178   Schar,
179   Uchar,
180   Char16,
181   Char32,
182   Short,
183   Ushort,
184   Int,
185   Uint,
186   Long,
187   Ulong,
188   Int64,
189   Uint64,
190   Wchar,
191   Float,
192   Double,
193   Ldouble,
194   Nullptr
195 };
196 
197 // Function classes
198 enum FuncClass : uint16_t {
199   Public = 1 << 0,
200   Protected = 1 << 1,
201   Private = 1 << 2,
202   Global = 1 << 3,
203   Static = 1 << 4,
204   Virtual = 1 << 5,
205   Far = 1 << 6,
206   ExternC = 1 << 7,
207   NoPrototype = 1 << 8,
208 };
209 
210 enum NameBackrefBehavior : uint8_t {
211   NBB_None = 0,          // don't save any names as backrefs.
212   NBB_Template = 1 << 0, // save template instanations.
213   NBB_Simple = 1 << 1,   // save simple names.
214 };
215 
216 enum class SymbolCategory { Function, Variable };
217 
218 namespace {
219 
220 struct NameResolver {
221   virtual ~NameResolver() = default;
222   virtual StringView resolve(StringView S) = 0;
223 };
224 
225 struct Type;
226 struct Name;
227 
228 struct FunctionParams {
229   bool IsVariadic = false;
230 
231   Type *Current = nullptr;
232 
233   FunctionParams *Next = nullptr;
234 };
235 
236 struct TemplateParams {
237   bool IsTemplateTemplate = false;
238   bool IsAliasTemplate = false;
239   bool IsIntegerLiteral = false;
240   bool IntegerLiteralIsNegative = false;
241   bool IsEmptyParameterPack = false;
242   bool PointerToSymbol = false;
243   bool ReferenceToSymbol = false;
244 
245   // If IsIntegerLiteral is true, this is a non-type template parameter
246   // whose value is contained in this field.
247   uint64_t IntegralValue = 0;
248 
249   // Type can be null if this is a template template parameter.  In that case
250   // only Name will be valid.
251   Type *ParamType = nullptr;
252 
253   // Name can be valid if this is a template template parameter (see above) or
254   // this is a function declaration (e.g. foo<&SomeFunc>).  In the latter case
255   // Name contains the name of the function and Type contains the signature.
256   Name *ParamName = nullptr;
257 
258   TemplateParams *Next = nullptr;
259 };
260 
261 // The type class. Mangled symbols are first parsed and converted to
262 // this type and then converted to string.
263 struct Type {
264   virtual ~Type() {}
265 
266   virtual Type *clone(ArenaAllocator &Arena) const;
267 
268   // Write the "first half" of a given type.  This is a static functions to
269   // give the code a chance to do processing that is common to a subset of
270   // subclasses
271   static void outputPre(OutputStream &OS, Type &Ty, NameResolver &Resolver);
272 
273   // Write the "second half" of a given type.  This is a static functions to
274   // give the code a chance to do processing that is common to a subset of
275   // subclasses
276   static void outputPost(OutputStream &OS, Type &Ty, NameResolver &Resolver);
277 
278   virtual void outputPre(OutputStream &OS, NameResolver &Resolver);
279   virtual void outputPost(OutputStream &OS, NameResolver &Resolver);
280 
281   // Primitive type such as Int.
282   PrimTy Prim = PrimTy::Unknown;
283 
284   Qualifiers Quals = Q_None;
285   StorageClass Storage = StorageClass::None; // storage class
286 };
287 
288 // Represents an identifier which may be a template.
289 struct Name {
290   bool IsTemplateInstantiation = false;
291   bool IsOperator = false;
292   bool IsBackReference = false;
293   bool IsConversionOperator = false;
294 
295   // Name read from an MangledName string.
296   StringView Str;
297 
298   // Template parameters. Only valid if Flags contains NF_TemplateInstantiation.
299   TemplateParams *TParams = nullptr;
300 
301   // Nested BackReferences (e.g. "A::B::C") are represented as a linked list.
302   Name *Next = nullptr;
303 };
304 
305 struct PointerType : public Type {
306   Type *clone(ArenaAllocator &Arena) const override;
307   void outputPre(OutputStream &OS, NameResolver &Resolver) override;
308   void outputPost(OutputStream &OS, NameResolver &Resolver) override;
309 
310   PointerAffinity Affinity;
311 
312   // Represents a type X in "a pointer to X", "a reference to X",
313   // "an array of X", or "a function returning X".
314   Type *Pointee = nullptr;
315 };
316 
317 struct MemberPointerType : public Type {
318   Type *clone(ArenaAllocator &Arena) const override;
319   void outputPre(OutputStream &OS, NameResolver &Resolver) override;
320   void outputPost(OutputStream &OS, NameResolver &Resolver) override;
321 
322   Name *MemberName = nullptr;
323 
324   // Represents a type X in "a pointer to X", "a reference to X",
325   // "an array of X", or "a function returning X".
326   Type *Pointee = nullptr;
327 };
328 
329 struct FunctionType : public Type {
330   Type *clone(ArenaAllocator &Arena) const override;
331   void outputPre(OutputStream &OS, NameResolver &Resolver) override;
332   void outputPost(OutputStream &OS, NameResolver &Resolver) override;
333 
334   // True if this FunctionType instance is the Pointee of a PointerType or
335   // MemberPointerType.
336   bool IsFunctionPointer = false;
337 
338   Type *ReturnType = nullptr;
339   // If this is a reference, the type of reference.
340   ReferenceKind RefKind;
341 
342   CallingConv CallConvention;
343   FuncClass FunctionClass;
344 
345   FunctionParams Params;
346 };
347 
348 struct UdtType : public Type {
349   Type *clone(ArenaAllocator &Arena) const override;
350   void outputPre(OutputStream &OS, NameResolver &Resolver) override;
351 
352   Name *UdtName = nullptr;
353 };
354 
355 struct ArrayDimension {
356   uint64_t Dim = 0;
357   ArrayDimension *Next = nullptr;
358 };
359 
360 struct ArrayType : public Type {
361   Type *clone(ArenaAllocator &Arena) const override;
362   void outputPre(OutputStream &OS, NameResolver &Resolver) override;
363   void outputPost(OutputStream &OS, NameResolver &Resolver) override;
364 
365   // Either NextDimension or ElementType will be valid.
366   ArrayDimension *Dims = nullptr;
367 
368   Type *ElementType = nullptr;
369 };
370 
371 } // namespace
372 
373 static bool isMemberPointer(StringView MangledName) {
374   switch (MangledName.popFront()) {
375   case '$':
376     // This is probably an rvalue reference (e.g. $$Q), and you cannot have an
377     // rvalue reference to a member.
378     return false;
379   case 'A':
380     // 'A' indicates a reference, and you cannot have a reference to a member
381     // function or member.
382     return false;
383   case 'P':
384   case 'Q':
385   case 'R':
386   case 'S':
387     // These 4 values indicate some kind of pointer, but we still don't know
388     // what.
389     break;
390   default:
391     assert(false && "Ty is not a pointer type!");
392   }
393 
394   // If it starts with a number, then 6 indicates a non-member function
395   // pointer, and 8 indicates a member function pointer.
396   if (startsWithDigit(MangledName)) {
397     assert(MangledName[0] == '6' || MangledName[0] == '8');
398     return (MangledName[0] == '8');
399   }
400 
401   // Remove ext qualifiers since those can appear on either type and are
402   // therefore not indicative.
403   MangledName.consumeFront('E'); // 64-bit
404   MangledName.consumeFront('I'); // restrict
405   MangledName.consumeFront('F'); // unaligned
406 
407   assert(!MangledName.empty());
408 
409   // The next value should be either ABCD (non-member) or QRST (member).
410   switch (MangledName.front()) {
411   case 'A':
412   case 'B':
413   case 'C':
414   case 'D':
415     return false;
416   case 'Q':
417   case 'R':
418   case 'S':
419   case 'T':
420     return true;
421   default:
422     assert(false);
423   }
424   return false;
425 }
426 
427 static void outputCallingConvention(OutputStream &OS, CallingConv CC) {
428   outputSpaceIfNecessary(OS);
429 
430   switch (CC) {
431   case CallingConv::Cdecl:
432     OS << "__cdecl";
433     break;
434   case CallingConv::Fastcall:
435     OS << "__fastcall";
436     break;
437   case CallingConv::Pascal:
438     OS << "__pascal";
439     break;
440   case CallingConv::Regcall:
441     OS << "__regcall";
442     break;
443   case CallingConv::Stdcall:
444     OS << "__stdcall";
445     break;
446   case CallingConv::Thiscall:
447     OS << "__thiscall";
448     break;
449   case CallingConv::Eabi:
450     OS << "__eabi";
451     break;
452   case CallingConv::Vectorcall:
453     OS << "__vectorcall";
454     break;
455   case CallingConv::Clrcall:
456     OS << "__clrcall";
457     break;
458   default:
459     break;
460   }
461 }
462 
463 static bool startsWithLocalScopePattern(StringView S) {
464   if (!S.consumeFront('?'))
465     return false;
466   if (S.size() < 2)
467     return false;
468 
469   size_t End = S.find('?');
470   if (End == StringView::npos)
471     return false;
472   StringView Candidate = S.substr(0, End);
473   if (Candidate.empty())
474     return false;
475 
476   // \?[0-9]\?
477   // ?@? is the discriminator 0.
478   if (Candidate.size() == 1)
479     return Candidate[0] == '@' || (Candidate[0] >= '0' && Candidate[0] <= '9');
480 
481   // If it's not 0-9, then it's an encoded number terminated with an @
482   if (Candidate.back() != '@')
483     return false;
484   Candidate = Candidate.dropBack();
485 
486   // An encoded number starts with B-P and all subsequent digits are in A-P.
487   // Note that the reason the first digit cannot be A is two fold.  First, it
488   // would create an ambiguity with ?A which delimits the beginning of an
489   // anonymous namespace.  Second, A represents 0, and you don't start a multi
490   // digit number with a leading 0.  Presumably the anonymous namespace
491   // ambiguity is also why single digit encoded numbers use 0-9 rather than A-J.
492   if (Candidate[0] < 'B' || Candidate[0] > 'P')
493     return false;
494   Candidate = Candidate.dropFront();
495   while (!Candidate.empty()) {
496     if (Candidate[0] < 'A' || Candidate[0] > 'P')
497       return false;
498     Candidate = Candidate.dropFront();
499   }
500 
501   return true;
502 }
503 
504 // Write a function or template parameter list.
505 static void outputParameterList(OutputStream &OS, const FunctionParams &Params,
506                                 NameResolver &Resolver) {
507   if (!Params.Current) {
508     OS << "void";
509     return;
510   }
511 
512   const FunctionParams *Head = &Params;
513   while (Head) {
514     Type::outputPre(OS, *Head->Current, Resolver);
515     Type::outputPost(OS, *Head->Current, Resolver);
516 
517     Head = Head->Next;
518 
519     if (Head)
520       OS << ", ";
521   }
522 }
523 
524 static void outputName(OutputStream &OS, const Name *TheName, const Type *Ty,
525                        NameResolver &Resolver);
526 
527 static void outputParameterList(OutputStream &OS, const TemplateParams &Params,
528                                 NameResolver &Resolver) {
529   if (Params.IsEmptyParameterPack) {
530     OS << "<>";
531     return;
532   }
533 
534   OS << "<";
535   const TemplateParams *Head = &Params;
536   while (Head) {
537     // Type can be null if this is a template template parameter,
538     // and Name can be null if this is a simple type.
539 
540     if (Head->IsIntegerLiteral) {
541       if (Head->IntegerLiteralIsNegative)
542         OS << '-';
543       OS << Head->IntegralValue;
544     } else if (Head->PointerToSymbol || Head->ReferenceToSymbol) {
545       if (Head->PointerToSymbol)
546         OS << "&";
547       Type::outputPre(OS, *Head->ParamType, Resolver);
548       outputName(OS, Head->ParamName, Head->ParamType, Resolver);
549       Type::outputPost(OS, *Head->ParamType, Resolver);
550     } else if (Head->ParamType) {
551       // simple type.
552       Type::outputPre(OS, *Head->ParamType, Resolver);
553       Type::outputPost(OS, *Head->ParamType, Resolver);
554     } else {
555       // Template alias.
556       outputName(OS, Head->ParamName, Head->ParamType, Resolver);
557     }
558 
559     Head = Head->Next;
560 
561     if (Head)
562       OS << ", ";
563   }
564   OS << ">";
565 }
566 
567 static void outputNameComponent(OutputStream &OS, const Name &N,
568                                 NameResolver &Resolver) {
569   if (N.IsConversionOperator) {
570     OS << " conv";
571   } else {
572     StringView S = N.Str;
573 
574     if (N.IsBackReference)
575       S = Resolver.resolve(N.Str);
576     OS << S;
577   }
578 
579   if (N.IsTemplateInstantiation && N.TParams)
580     outputParameterList(OS, *N.TParams, Resolver);
581 }
582 
583 static void outputName(OutputStream &OS, const Name *TheName, const Type *Ty,
584                        NameResolver &Resolver) {
585   if (!TheName)
586     return;
587 
588   outputSpaceIfNecessary(OS);
589 
590   const Name *Previous = nullptr;
591   // Print out namespaces or outer class BackReferences.
592   for (; TheName->Next; TheName = TheName->Next) {
593     Previous = TheName;
594     outputNameComponent(OS, *TheName, Resolver);
595     OS << "::";
596   }
597 
598   // Print out a regular name.
599   if (!TheName->IsOperator) {
600     outputNameComponent(OS, *TheName, Resolver);
601     return;
602   }
603 
604   // Print out ctor or dtor.
605   if (TheName->Str == "dtor")
606     OS << "~";
607 
608   if (TheName->Str == "ctor" || TheName->Str == "dtor") {
609     outputNameComponent(OS, *Previous, Resolver);
610     return;
611   }
612 
613   if (TheName->IsConversionOperator) {
614     OS << "operator";
615     if (TheName->IsTemplateInstantiation && TheName->TParams)
616       outputParameterList(OS, *TheName->TParams, Resolver);
617     OS << " ";
618     if (Ty) {
619       const FunctionType *FTy = static_cast<const FunctionType *>(Ty);
620       Type::outputPre(OS, *FTy->ReturnType, Resolver);
621       Type::outputPost(OS, *FTy->ReturnType, Resolver);
622     } else {
623       OS << "<conversion>";
624     }
625   } else {
626     // Print out an overloaded operator.
627     OS << "operator";
628     outputNameComponent(OS, *TheName, Resolver);
629   }
630 }
631 
632 namespace {
633 
634 Type *Type::clone(ArenaAllocator &Arena) const {
635   return Arena.alloc<Type>(*this);
636 }
637 
638 // Write the "first half" of a given type.
639 void Type::outputPre(OutputStream &OS, Type &Ty, NameResolver &Resolver) {
640   // Function types require custom handling of const and static so we
641   // handle them separately.  All other types use the same decoration
642   // for these modifiers, so handle them here in common code.
643   if (Ty.Prim == PrimTy::Function) {
644     Ty.outputPre(OS, Resolver);
645     return;
646   }
647 
648   switch (Ty.Storage) {
649   case StorageClass::PrivateStatic:
650   case StorageClass::PublicStatic:
651   case StorageClass::ProtectedStatic:
652     OS << "static ";
653   default:
654     break;
655   }
656   Ty.outputPre(OS, Resolver);
657 
658   if (Ty.Quals & Q_Const) {
659     outputSpaceIfNecessary(OS);
660     OS << "const";
661   }
662 
663   if (Ty.Quals & Q_Volatile) {
664     outputSpaceIfNecessary(OS);
665     OS << "volatile";
666   }
667 
668   if (Ty.Quals & Q_Restrict) {
669     outputSpaceIfNecessary(OS);
670     OS << "__restrict";
671   }
672 }
673 
674 // Write the "second half" of a given type.
675 void Type::outputPost(OutputStream &OS, Type &Ty, NameResolver &Resolver) {
676   Ty.outputPost(OS, Resolver);
677 }
678 
679 void Type::outputPre(OutputStream &OS, NameResolver &Resolver) {
680   switch (Prim) {
681   case PrimTy::Void:
682     OS << "void";
683     break;
684   case PrimTy::Bool:
685     OS << "bool";
686     break;
687   case PrimTy::Char:
688     OS << "char";
689     break;
690   case PrimTy::Schar:
691     OS << "signed char";
692     break;
693   case PrimTy::Uchar:
694     OS << "unsigned char";
695     break;
696   case PrimTy::Char16:
697     OS << "char16_t";
698     break;
699   case PrimTy::Char32:
700     OS << "char32_t";
701     break;
702   case PrimTy::Short:
703     OS << "short";
704     break;
705   case PrimTy::Ushort:
706     OS << "unsigned short";
707     break;
708   case PrimTy::Int:
709     OS << "int";
710     break;
711   case PrimTy::Uint:
712     OS << "unsigned int";
713     break;
714   case PrimTy::Long:
715     OS << "long";
716     break;
717   case PrimTy::Ulong:
718     OS << "unsigned long";
719     break;
720   case PrimTy::Int64:
721     OS << "__int64";
722     break;
723   case PrimTy::Uint64:
724     OS << "unsigned __int64";
725     break;
726   case PrimTy::Wchar:
727     OS << "wchar_t";
728     break;
729   case PrimTy::Float:
730     OS << "float";
731     break;
732   case PrimTy::Double:
733     OS << "double";
734     break;
735   case PrimTy::Ldouble:
736     OS << "long double";
737     break;
738   case PrimTy::Nullptr:
739     OS << "std::nullptr_t";
740     break;
741   default:
742     assert(false && "Invalid primitive type!");
743   }
744 }
745 void Type::outputPost(OutputStream &OS, NameResolver &Resolver) {}
746 
747 Type *PointerType::clone(ArenaAllocator &Arena) const {
748   return Arena.alloc<PointerType>(*this);
749 }
750 
751 static void outputPointerIndicator(OutputStream &OS, PointerAffinity Affinity,
752                                    const Name *MemberName, const Type *Pointee,
753                                    NameResolver &Resolver) {
754   // "[]" and "()" (for function parameters) take precedence over "*",
755   // so "int *x(int)" means "x is a function returning int *". We need
756   // parentheses to supercede the default precedence. (e.g. we want to
757   // emit something like "int (*x)(int)".)
758   if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array) {
759     OS << "(";
760     if (Pointee->Prim == PrimTy::Function) {
761       const FunctionType *FTy = static_cast<const FunctionType *>(Pointee);
762       assert(FTy->IsFunctionPointer);
763       outputCallingConvention(OS, FTy->CallConvention);
764       OS << " ";
765     }
766   }
767 
768   if (MemberName) {
769     outputName(OS, MemberName, Pointee, Resolver);
770     OS << "::";
771   }
772 
773   if (Affinity == PointerAffinity::Pointer)
774     OS << "*";
775   else if (Affinity == PointerAffinity::Reference)
776     OS << "&";
777   else
778     OS << "&&";
779 }
780 
781 void PointerType::outputPre(OutputStream &OS, NameResolver &Resolver) {
782   Type::outputPre(OS, *Pointee, Resolver);
783 
784   outputSpaceIfNecessary(OS);
785 
786   if (Quals & Q_Unaligned)
787     OS << "__unaligned ";
788 
789   outputPointerIndicator(OS, Affinity, nullptr, Pointee, Resolver);
790 
791   // FIXME: We should output this, but it requires updating lots of tests.
792   // if (Ty.Quals & Q_Pointer64)
793   //  OS << " __ptr64";
794 }
795 
796 void PointerType::outputPost(OutputStream &OS, NameResolver &Resolver) {
797   if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array)
798     OS << ")";
799 
800   Type::outputPost(OS, *Pointee, Resolver);
801 }
802 
803 Type *MemberPointerType::clone(ArenaAllocator &Arena) const {
804   return Arena.alloc<MemberPointerType>(*this);
805 }
806 
807 void MemberPointerType::outputPre(OutputStream &OS, NameResolver &Resolver) {
808   Type::outputPre(OS, *Pointee, Resolver);
809 
810   outputSpaceIfNecessary(OS);
811 
812   outputPointerIndicator(OS, PointerAffinity::Pointer, MemberName, Pointee,
813                          Resolver);
814 
815   // FIXME: We should output this, but it requires updating lots of tests.
816   // if (Ty.Quals & Q_Pointer64)
817   //  OS << " __ptr64";
818 }
819 
820 void MemberPointerType::outputPost(OutputStream &OS, NameResolver &Resolver) {
821   if (Pointee->Prim == PrimTy::Function || Pointee->Prim == PrimTy::Array)
822     OS << ")";
823 
824   Type::outputPost(OS, *Pointee, Resolver);
825 }
826 
827 Type *FunctionType::clone(ArenaAllocator &Arena) const {
828   return Arena.alloc<FunctionType>(*this);
829 }
830 
831 void FunctionType::outputPre(OutputStream &OS, NameResolver &Resolver) {
832   if (!(FunctionClass & Global)) {
833     if (FunctionClass & Static)
834       OS << "static ";
835   }
836   if (FunctionClass & ExternC) {
837     OS << "extern \"C\" ";
838   }
839 
840   if (ReturnType) {
841     Type::outputPre(OS, *ReturnType, Resolver);
842     OS << " ";
843   }
844 
845   // Function pointers print the calling convention as void (__cdecl *)(params)
846   // rather than void __cdecl (*)(params).  So we need to let the PointerType
847   // class handle this.
848   if (!IsFunctionPointer)
849     outputCallingConvention(OS, CallConvention);
850 }
851 
852 void FunctionType::outputPost(OutputStream &OS, NameResolver &Resolver) {
853   // extern "C" functions don't have a prototype.
854   if (FunctionClass & NoPrototype)
855     return;
856 
857   OS << "(";
858   outputParameterList(OS, Params, Resolver);
859   OS << ")";
860   if (Quals & Q_Const)
861     OS << " const";
862   if (Quals & Q_Volatile)
863     OS << " volatile";
864   if (Quals & Q_Restrict)
865     OS << " __restrict";
866   if (Quals & Q_Unaligned)
867     OS << " __unaligned";
868 
869   if (RefKind == ReferenceKind::LValueRef)
870     OS << " &";
871   else if (RefKind == ReferenceKind::RValueRef)
872     OS << " &&";
873 
874   if (ReturnType)
875     Type::outputPost(OS, *ReturnType, Resolver);
876   return;
877 }
878 
879 Type *UdtType::clone(ArenaAllocator &Arena) const {
880   return Arena.alloc<UdtType>(*this);
881 }
882 
883 void UdtType::outputPre(OutputStream &OS, NameResolver &Resolver) {
884   switch (Prim) {
885   case PrimTy::Class:
886     OS << "class ";
887     break;
888   case PrimTy::Struct:
889     OS << "struct ";
890     break;
891   case PrimTy::Union:
892     OS << "union ";
893     break;
894   case PrimTy::Enum:
895     OS << "enum ";
896     break;
897   default:
898     assert(false && "Not a udt type!");
899   }
900 
901   outputName(OS, UdtName, this, Resolver);
902 }
903 
904 Type *ArrayType::clone(ArenaAllocator &Arena) const {
905   return Arena.alloc<ArrayType>(*this);
906 }
907 
908 void ArrayType::outputPre(OutputStream &OS, NameResolver &Resolver) {
909   Type::outputPre(OS, *ElementType, Resolver);
910 }
911 
912 void ArrayType::outputPost(OutputStream &OS, NameResolver &Resolver) {
913   ArrayDimension *D = Dims;
914   while (D) {
915     OS << "[";
916     if (D->Dim > 0)
917       OS << D->Dim;
918     OS << "]";
919     D = D->Next;
920   }
921 
922   Type::outputPost(OS, *ElementType, Resolver);
923 }
924 
925 struct Symbol {
926   SymbolCategory Category;
927 
928   Name *SymbolName = nullptr;
929   Type *SymbolType = nullptr;
930 };
931 
932 } // namespace
933 
934 namespace {
935 
936 struct BackrefContext {
937   static constexpr size_t Max = 10;
938 
939   Type *FunctionParams[Max];
940   size_t FunctionParamCount = 0;
941 
942   // The first 10 BackReferences in a mangled name can be back-referenced by
943   // special name @[0-9]. This is a storage for the first 10 BackReferences.
944   StringView Names[Max];
945   size_t NamesCount = 0;
946 };
947 
948 // Demangler class takes the main role in demangling symbols.
949 // It has a set of functions to parse mangled symbols into Type instances.
950 // It also has a set of functions to cnovert Type instances to strings.
951 class Demangler : public NameResolver {
952 public:
953   Demangler() = default;
954   virtual ~Demangler() = default;
955 
956   // You are supposed to call parse() first and then check if error is true.  If
957   // it is false, call output() to write the formatted name to the given stream.
958   Symbol *parse(StringView &MangledName);
959   void output(const Symbol *S, OutputStream &OS);
960 
961   StringView resolve(StringView N) override;
962 
963   // True if an error occurred.
964   bool Error = false;
965 
966   void dumpBackReferences();
967 
968 private:
969   Type *demangleVariableEncoding(StringView &MangledName);
970   Type *demangleFunctionEncoding(StringView &MangledName);
971 
972   Qualifiers demanglePointerExtQualifiers(StringView &MangledName);
973 
974   // Parser functions. This is a recursive-descent parser.
975   Type *demangleType(StringView &MangledName, QualifierMangleMode QMM);
976   Type *demangleBasicType(StringView &MangledName);
977   UdtType *demangleClassType(StringView &MangledName);
978   PointerType *demanglePointerType(StringView &MangledName);
979   MemberPointerType *demangleMemberPointerType(StringView &MangledName);
980   FunctionType *demangleFunctionType(StringView &MangledName, bool HasThisQuals,
981                                      bool IsFunctionPointer);
982 
983   ArrayType *demangleArrayType(StringView &MangledName);
984 
985   TemplateParams *demangleTemplateParameterList(StringView &MangledName);
986   FunctionParams demangleFunctionParameterList(StringView &MangledName);
987 
988   std::pair<uint64_t, bool> demangleNumber(StringView &MangledName);
989 
990   void memorizeString(StringView s);
991 
992   /// Allocate a copy of \p Borrowed into memory that we own.
993   StringView copyString(StringView Borrowed);
994 
995   Name *demangleFullyQualifiedTypeName(StringView &MangledName);
996   Name *demangleFullyQualifiedSymbolName(StringView &MangledName);
997 
998   Name *demangleUnqualifiedTypeName(StringView &MangledName, bool Memorize);
999   Name *demangleUnqualifiedSymbolName(StringView &MangledName,
1000                                       NameBackrefBehavior NBB);
1001 
1002   Name *demangleNameScopeChain(StringView &MangledName, Name *UnqualifiedName);
1003   Name *demangleNameScopePiece(StringView &MangledName);
1004 
1005   Name *demangleBackRefName(StringView &MangledName);
1006   Name *demangleTemplateInstantiationName(StringView &MangledName,
1007                                           NameBackrefBehavior NBB);
1008   Name *demangleOperatorName(StringView &MangledName);
1009   Name *demangleSimpleName(StringView &MangledName, bool Memorize);
1010   Name *demangleAnonymousNamespaceName(StringView &MangledName);
1011   Name *demangleLocallyScopedNamePiece(StringView &MangledName);
1012 
1013   StringView demangleSimpleString(StringView &MangledName, bool Memorize);
1014 
1015   FuncClass demangleFunctionClass(StringView &MangledName);
1016   CallingConv demangleCallingConvention(StringView &MangledName);
1017   StorageClass demangleVariableStorageClass(StringView &MangledName);
1018   ReferenceKind demangleReferenceKind(StringView &MangledName);
1019   void demangleThrowSpecification(StringView &MangledName);
1020 
1021   std::pair<Qualifiers, bool> demangleQualifiers(StringView &MangledName);
1022 
1023   // Memory allocator.
1024   ArenaAllocator Arena;
1025 
1026   // A single type uses one global back-ref table for all function params.
1027   // This means back-refs can even go "into" other types.  Examples:
1028   //
1029   //  // Second int* is a back-ref to first.
1030   //  void foo(int *, int*);
1031   //
1032   //  // Second int* is not a back-ref to first (first is not a function param).
1033   //  int* foo(int*);
1034   //
1035   //  // Second int* is a back-ref to first (ALL function types share the same
1036   //  // back-ref map.
1037   //  using F = void(*)(int*);
1038   //  F G(int *);
1039   BackrefContext Backrefs;
1040 };
1041 } // namespace
1042 
1043 StringView Demangler::copyString(StringView Borrowed) {
1044   char *Stable = Arena.allocUnalignedBuffer(Borrowed.size() + 1);
1045   std::strcpy(Stable, Borrowed.begin());
1046 
1047   return {Stable, Borrowed.size()};
1048 }
1049 
1050 // Parser entry point.
1051 Symbol *Demangler::parse(StringView &MangledName) {
1052   Symbol *S = Arena.alloc<Symbol>();
1053 
1054   // MSVC-style mangled symbols must start with '?'.
1055   if (!MangledName.consumeFront("?")) {
1056     S->SymbolName = Arena.alloc<Name>();
1057     S->SymbolName->Str = MangledName;
1058     S->SymbolType = Arena.alloc<Type>();
1059     S->SymbolType->Prim = PrimTy::Unknown;
1060     return S;
1061   }
1062 
1063   // What follows is a main symbol name. This may include
1064   // namespaces or class BackReferences.
1065   S->SymbolName = demangleFullyQualifiedSymbolName(MangledName);
1066   if (Error)
1067     return nullptr;
1068   // Read a variable.
1069   if (startsWithDigit(MangledName) && !MangledName.startsWith('9')) {
1070     // 9 is a special marker for an extern "C" function with
1071     // no prototype.
1072     S->Category = SymbolCategory::Variable;
1073     S->SymbolType = demangleVariableEncoding(MangledName);
1074   } else {
1075     S->Category = SymbolCategory::Function;
1076     S->SymbolType = demangleFunctionEncoding(MangledName);
1077   }
1078 
1079   if (Error)
1080     return nullptr;
1081 
1082   return S;
1083 }
1084 
1085 // <type-encoding> ::= <storage-class> <variable-type>
1086 // <storage-class> ::= 0  # private static member
1087 //                 ::= 1  # protected static member
1088 //                 ::= 2  # public static member
1089 //                 ::= 3  # global
1090 //                 ::= 4  # static local
1091 
1092 Type *Demangler::demangleVariableEncoding(StringView &MangledName) {
1093   StorageClass SC = demangleVariableStorageClass(MangledName);
1094 
1095   Type *Ty = demangleType(MangledName, QualifierMangleMode::Drop);
1096 
1097   Ty->Storage = SC;
1098 
1099   // <variable-type> ::= <type> <cvr-qualifiers>
1100   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
1101   switch (Ty->Prim) {
1102   case PrimTy::Ptr:
1103   case PrimTy::MemberPtr: {
1104     Qualifiers ExtraChildQuals = Q_None;
1105     Ty->Quals =
1106         Qualifiers(Ty->Quals | demanglePointerExtQualifiers(MangledName));
1107 
1108     bool IsMember = false;
1109     std::tie(ExtraChildQuals, IsMember) = demangleQualifiers(MangledName);
1110 
1111     if (Ty->Prim == PrimTy::MemberPtr) {
1112       assert(IsMember);
1113       Name *BackRefName = demangleFullyQualifiedTypeName(MangledName);
1114       (void)BackRefName;
1115       MemberPointerType *MPTy = static_cast<MemberPointerType *>(Ty);
1116       MPTy->Pointee->Quals = Qualifiers(MPTy->Pointee->Quals | ExtraChildQuals);
1117     } else {
1118       PointerType *PTy = static_cast<PointerType *>(Ty);
1119       PTy->Pointee->Quals = Qualifiers(PTy->Pointee->Quals | ExtraChildQuals);
1120     }
1121 
1122     break;
1123   }
1124   default:
1125     Ty->Quals = demangleQualifiers(MangledName).first;
1126     break;
1127   }
1128 
1129   return Ty;
1130 }
1131 
1132 // Sometimes numbers are encoded in mangled symbols. For example,
1133 // "int (*x)[20]" is a valid C type (x is a pointer to an array of
1134 // length 20), so we need some way to embed numbers as part of symbols.
1135 // This function parses it.
1136 //
1137 // <number>               ::= [?] <non-negative integer>
1138 //
1139 // <non-negative integer> ::= <decimal digit> # when 1 <= Number <= 10
1140 //                        ::= <hex digit>+ @  # when Numbrer == 0 or >= 10
1141 //
1142 // <hex-digit>            ::= [A-P]           # A = 0, B = 1, ...
1143 std::pair<uint64_t, bool> Demangler::demangleNumber(StringView &MangledName) {
1144   bool IsNegative = MangledName.consumeFront('?');
1145 
1146   if (startsWithDigit(MangledName)) {
1147     uint64_t Ret = MangledName[0] - '0' + 1;
1148     MangledName = MangledName.dropFront(1);
1149     return {Ret, IsNegative};
1150   }
1151 
1152   uint64_t Ret = 0;
1153   for (size_t i = 0; i < MangledName.size(); ++i) {
1154     char C = MangledName[i];
1155     if (C == '@') {
1156       MangledName = MangledName.dropFront(i + 1);
1157       return {Ret, IsNegative};
1158     }
1159     if ('A' <= C && C <= 'P') {
1160       Ret = (Ret << 4) + (C - 'A');
1161       continue;
1162     }
1163     break;
1164   }
1165 
1166   Error = true;
1167   return {0ULL, false};
1168 }
1169 
1170 // First 10 strings can be referenced by special BackReferences ?0, ?1, ..., ?9.
1171 // Memorize it.
1172 void Demangler::memorizeString(StringView S) {
1173   if (Backrefs.NamesCount >= BackrefContext::Max)
1174     return;
1175   for (size_t i = 0; i < Backrefs.NamesCount; ++i)
1176     if (S == Backrefs.Names[i])
1177       return;
1178   Backrefs.Names[Backrefs.NamesCount++] = S;
1179 }
1180 
1181 Name *Demangler::demangleBackRefName(StringView &MangledName) {
1182   assert(startsWithDigit(MangledName));
1183   Name *Node = Arena.alloc<Name>();
1184   Node->IsBackReference = true;
1185   Node->Str = {MangledName.begin(), 1};
1186   MangledName = MangledName.dropFront();
1187   return Node;
1188 }
1189 
1190 Name *Demangler::demangleTemplateInstantiationName(StringView &MangledName,
1191                                                    NameBackrefBehavior NBB) {
1192   assert(MangledName.startsWith("?$"));
1193   MangledName.consumeFront("?$");
1194 
1195   BackrefContext OuterContext;
1196   std::swap(OuterContext, Backrefs);
1197 
1198   Name *Node = demangleUnqualifiedSymbolName(MangledName, NBB_None);
1199   if (!Error)
1200     Node->TParams = demangleTemplateParameterList(MangledName);
1201 
1202   std::swap(OuterContext, Backrefs);
1203   if (Error)
1204     return nullptr;
1205 
1206   Node->IsTemplateInstantiation = true;
1207 
1208   if (NBB & NBB_Template) {
1209     // Render this class template name into a string buffer so that we can
1210     // memorize it for the purpose of back-referencing.
1211     OutputStream OS = OutputStream::create(nullptr, nullptr, 1024);
1212     outputName(OS, Node, nullptr, *this);
1213     OS << '\0';
1214     char *Name = OS.getBuffer();
1215 
1216     StringView Owned = copyString(Name);
1217     memorizeString(Owned);
1218     std::free(Name);
1219   }
1220 
1221   return Node;
1222 }
1223 
1224 Name *Demangler::demangleOperatorName(StringView &MangledName) {
1225   assert(MangledName.startsWith('?'));
1226   MangledName.consumeFront('?');
1227 
1228   auto NameString = [this, &MangledName]() -> StringView {
1229     switch (MangledName.popFront()) {
1230     case '0':
1231       return "ctor";
1232     case '1':
1233       return "dtor";
1234     case '2':
1235       return " new";
1236     case '3':
1237       return " delete";
1238     case '4':
1239       return "=";
1240     case '5':
1241       return ">>";
1242     case '6':
1243       return "<<";
1244     case '7':
1245       return "!";
1246     case '8':
1247       return "==";
1248     case '9':
1249       return "!=";
1250     case 'A':
1251       return "[]";
1252     case 'C':
1253       return "->";
1254     case 'D':
1255       return "*";
1256     case 'E':
1257       return "++";
1258     case 'F':
1259       return "--";
1260     case 'G':
1261       return "-";
1262     case 'H':
1263       return "+";
1264     case 'I':
1265       return "&";
1266     case 'J':
1267       return "->*";
1268     case 'K':
1269       return "/";
1270     case 'L':
1271       return "%";
1272     case 'M':
1273       return "<";
1274     case 'N':
1275       return "<=";
1276     case 'O':
1277       return ">";
1278     case 'P':
1279       return ">=";
1280     case 'Q':
1281       return ",";
1282     case 'R':
1283       return "()";
1284     case 'S':
1285       return "~";
1286     case 'T':
1287       return "^";
1288     case 'U':
1289       return "|";
1290     case 'V':
1291       return "&&";
1292     case 'W':
1293       return "||";
1294     case 'X':
1295       return "*=";
1296     case 'Y':
1297       return "+=";
1298     case 'Z':
1299       return "-=";
1300     case '_': {
1301       if (MangledName.empty())
1302         break;
1303 
1304       switch (MangledName.popFront()) {
1305       case '0':
1306         return "/=";
1307       case '1':
1308         return "%=";
1309       case '2':
1310         return ">>=";
1311       case '3':
1312         return "<<=";
1313       case '4':
1314         return "&=";
1315       case '5':
1316         return "|=";
1317       case '6':
1318         return "^=";
1319       case 'U':
1320         return " new[]";
1321       case 'V':
1322         return " delete[]";
1323       case '_':
1324         if (MangledName.consumeFront("L"))
1325           return " co_await";
1326         if (MangledName.consumeFront("K")) {
1327           size_t EndPos = MangledName.find('@');
1328           if (EndPos == StringView::npos)
1329             break;
1330           StringView OpName = demangleSimpleString(MangledName, false);
1331           size_t FullSize = OpName.size() + 3; // <space>""OpName
1332           char *Buffer = Arena.allocUnalignedBuffer(FullSize);
1333           Buffer[0] = ' ';
1334           Buffer[1] = '"';
1335           Buffer[2] = '"';
1336           std::memcpy(Buffer + 3, OpName.begin(), OpName.size());
1337           return {Buffer, FullSize};
1338         }
1339       }
1340     }
1341     }
1342     Error = true;
1343     return "";
1344   };
1345 
1346   Name *Node = Arena.alloc<Name>();
1347   if (MangledName.consumeFront('B')) {
1348     // Handle conversion operator specially.
1349     Node->IsConversionOperator = true;
1350   } else {
1351     Node->Str = NameString();
1352   }
1353   Node->IsOperator = true;
1354   return Node;
1355 }
1356 
1357 Name *Demangler::demangleSimpleName(StringView &MangledName, bool Memorize) {
1358   StringView S = demangleSimpleString(MangledName, Memorize);
1359   if (Error)
1360     return nullptr;
1361 
1362   Name *Node = Arena.alloc<Name>();
1363   Node->Str = S;
1364   return Node;
1365 }
1366 
1367 StringView Demangler::demangleSimpleString(StringView &MangledName,
1368                                            bool Memorize) {
1369   StringView S;
1370   for (size_t i = 0; i < MangledName.size(); ++i) {
1371     if (MangledName[i] != '@')
1372       continue;
1373     S = MangledName.substr(0, i);
1374     MangledName = MangledName.dropFront(i + 1);
1375 
1376     if (Memorize)
1377       memorizeString(S);
1378     return S;
1379   }
1380 
1381   Error = true;
1382   return {};
1383 }
1384 
1385 Name *Demangler::demangleAnonymousNamespaceName(StringView &MangledName) {
1386   assert(MangledName.startsWith("?A"));
1387   MangledName.consumeFront("?A");
1388 
1389   Name *Node = Arena.alloc<Name>();
1390   Node->Str = "`anonymous namespace'";
1391   if (MangledName.consumeFront('@'))
1392     return Node;
1393 
1394   Error = true;
1395   return nullptr;
1396 }
1397 
1398 Name *Demangler::demangleLocallyScopedNamePiece(StringView &MangledName) {
1399   assert(startsWithLocalScopePattern(MangledName));
1400 
1401   Name *Node = Arena.alloc<Name>();
1402   MangledName.consumeFront('?');
1403   auto Number = demangleNumber(MangledName);
1404   assert(!Number.second);
1405 
1406   // One ? to terminate the number
1407   MangledName.consumeFront('?');
1408 
1409   assert(!Error);
1410   Symbol *Scope = parse(MangledName);
1411   if (Error)
1412     return nullptr;
1413 
1414   // Render the parent symbol's name into a buffer.
1415   OutputStream OS = OutputStream::create(nullptr, nullptr, 1024);
1416   OS << '`';
1417   output(Scope, OS);
1418   OS << '\'';
1419   OS << "::`" << Number.first << "'";
1420   OS << '\0';
1421   char *Result = OS.getBuffer();
1422   Node->Str = copyString(Result);
1423   std::free(Result);
1424   return Node;
1425 }
1426 
1427 // Parses a type name in the form of A@B@C@@ which represents C::B::A.
1428 Name *Demangler::demangleFullyQualifiedTypeName(StringView &MangledName) {
1429   Name *TypeName = demangleUnqualifiedTypeName(MangledName, true);
1430   if (Error)
1431     return nullptr;
1432   assert(TypeName);
1433 
1434   Name *QualName = demangleNameScopeChain(MangledName, TypeName);
1435   if (Error)
1436     return nullptr;
1437   assert(QualName);
1438   return QualName;
1439 }
1440 
1441 // Parses a symbol name in the form of A@B@C@@ which represents C::B::A.
1442 // Symbol names have slightly different rules regarding what can appear
1443 // so we separate out the implementations for flexibility.
1444 Name *Demangler::demangleFullyQualifiedSymbolName(StringView &MangledName) {
1445   // This is the final component of a symbol name (i.e. the leftmost component
1446   // of a mangled name.  Since the only possible template instantiation that
1447   // can appear in this context is a function template, and since those are
1448   // not saved for the purposes of name backreferences, only backref simple
1449   // names.
1450   Name *SymbolName = demangleUnqualifiedSymbolName(MangledName, NBB_Simple);
1451   if (Error)
1452     return nullptr;
1453   assert(SymbolName);
1454 
1455   Name *QualName = demangleNameScopeChain(MangledName, SymbolName);
1456   if (Error)
1457     return nullptr;
1458   assert(QualName);
1459   return QualName;
1460 }
1461 
1462 Name *Demangler::demangleUnqualifiedTypeName(StringView &MangledName,
1463                                              bool Memorize) {
1464   // An inner-most name can be a back-reference, because a fully-qualified name
1465   // (e.g. Scope + Inner) can contain other fully qualified names inside of
1466   // them (for example template parameters), and these nested parameters can
1467   // refer to previously mangled types.
1468   if (startsWithDigit(MangledName))
1469     return demangleBackRefName(MangledName);
1470 
1471   if (MangledName.startsWith("?$"))
1472     return demangleTemplateInstantiationName(MangledName, NBB_Template);
1473 
1474   return demangleSimpleName(MangledName, Memorize);
1475 }
1476 
1477 Name *Demangler::demangleUnqualifiedSymbolName(StringView &MangledName,
1478                                                NameBackrefBehavior NBB) {
1479   if (startsWithDigit(MangledName))
1480     return demangleBackRefName(MangledName);
1481   if (MangledName.startsWith("?$"))
1482     return demangleTemplateInstantiationName(MangledName, NBB);
1483   if (MangledName.startsWith('?'))
1484     return demangleOperatorName(MangledName);
1485   return demangleSimpleName(MangledName, (NBB & NBB_Simple) != 0);
1486 }
1487 
1488 Name *Demangler::demangleNameScopePiece(StringView &MangledName) {
1489   if (startsWithDigit(MangledName))
1490     return demangleBackRefName(MangledName);
1491 
1492   if (MangledName.startsWith("?$"))
1493     return demangleTemplateInstantiationName(MangledName, NBB_Template);
1494 
1495   if (MangledName.startsWith("?A"))
1496     return demangleAnonymousNamespaceName(MangledName);
1497 
1498   if (startsWithLocalScopePattern(MangledName))
1499     return demangleLocallyScopedNamePiece(MangledName);
1500 
1501   return demangleSimpleName(MangledName, true);
1502 }
1503 
1504 Name *Demangler::demangleNameScopeChain(StringView &MangledName,
1505                                         Name *UnqualifiedName) {
1506   Name *Head = UnqualifiedName;
1507 
1508   while (!MangledName.consumeFront("@")) {
1509     if (MangledName.empty()) {
1510       Error = true;
1511       return nullptr;
1512     }
1513 
1514     assert(!Error);
1515     Name *Elem = demangleNameScopePiece(MangledName);
1516     if (Error)
1517       return nullptr;
1518 
1519     Elem->Next = Head;
1520     Head = Elem;
1521   }
1522   return Head;
1523 }
1524 
1525 FuncClass Demangler::demangleFunctionClass(StringView &MangledName) {
1526   SwapAndRestore<StringView> RestoreOnError(MangledName, MangledName);
1527   RestoreOnError.shouldRestore(false);
1528 
1529   FuncClass TempFlags = FuncClass(0);
1530   if (MangledName.consumeFront("$$J0"))
1531     TempFlags = ExternC;
1532 
1533   switch (MangledName.popFront()) {
1534   case '9':
1535     return FuncClass(TempFlags | ExternC | NoPrototype);
1536   case 'A':
1537     return Private;
1538   case 'B':
1539     return FuncClass(TempFlags | Private | Far);
1540   case 'C':
1541     return FuncClass(TempFlags | Private | Static);
1542   case 'D':
1543     return FuncClass(TempFlags | Private | Static);
1544   case 'E':
1545     return FuncClass(TempFlags | Private | Virtual);
1546   case 'F':
1547     return FuncClass(TempFlags | Private | Virtual);
1548   case 'I':
1549     return FuncClass(TempFlags | Protected);
1550   case 'J':
1551     return FuncClass(TempFlags | Protected | Far);
1552   case 'K':
1553     return FuncClass(TempFlags | Protected | Static);
1554   case 'L':
1555     return FuncClass(TempFlags | Protected | Static | Far);
1556   case 'M':
1557     return FuncClass(TempFlags | Protected | Virtual);
1558   case 'N':
1559     return FuncClass(TempFlags | Protected | Virtual | Far);
1560   case 'Q':
1561     return FuncClass(TempFlags | Public);
1562   case 'R':
1563     return FuncClass(TempFlags | Public | Far);
1564   case 'S':
1565     return FuncClass(TempFlags | Public | Static);
1566   case 'T':
1567     return FuncClass(TempFlags | Public | Static | Far);
1568   case 'U':
1569     return FuncClass(TempFlags | Public | Virtual);
1570   case 'V':
1571     return FuncClass(TempFlags | Public | Virtual | Far);
1572   case 'Y':
1573     return FuncClass(TempFlags | Global);
1574   case 'Z':
1575     return FuncClass(TempFlags | Global | Far);
1576   }
1577 
1578   Error = true;
1579   RestoreOnError.shouldRestore(true);
1580   return Public;
1581 }
1582 
1583 CallingConv Demangler::demangleCallingConvention(StringView &MangledName) {
1584   switch (MangledName.popFront()) {
1585   case 'A':
1586   case 'B':
1587     return CallingConv::Cdecl;
1588   case 'C':
1589   case 'D':
1590     return CallingConv::Pascal;
1591   case 'E':
1592   case 'F':
1593     return CallingConv::Thiscall;
1594   case 'G':
1595   case 'H':
1596     return CallingConv::Stdcall;
1597   case 'I':
1598   case 'J':
1599     return CallingConv::Fastcall;
1600   case 'M':
1601   case 'N':
1602     return CallingConv::Clrcall;
1603   case 'O':
1604   case 'P':
1605     return CallingConv::Eabi;
1606   case 'Q':
1607     return CallingConv::Vectorcall;
1608   }
1609 
1610   return CallingConv::None;
1611 }
1612 
1613 StorageClass Demangler::demangleVariableStorageClass(StringView &MangledName) {
1614   assert(std::isdigit(MangledName.front()));
1615 
1616   switch (MangledName.popFront()) {
1617   case '0':
1618     return StorageClass::PrivateStatic;
1619   case '1':
1620     return StorageClass::ProtectedStatic;
1621   case '2':
1622     return StorageClass::PublicStatic;
1623   case '3':
1624     return StorageClass::Global;
1625   case '4':
1626     return StorageClass::FunctionLocalStatic;
1627   }
1628   Error = true;
1629   return StorageClass::None;
1630 }
1631 
1632 std::pair<Qualifiers, bool>
1633 Demangler::demangleQualifiers(StringView &MangledName) {
1634 
1635   switch (MangledName.popFront()) {
1636   // Member qualifiers
1637   case 'Q':
1638     return std::make_pair(Q_None, true);
1639   case 'R':
1640     return std::make_pair(Q_Const, true);
1641   case 'S':
1642     return std::make_pair(Q_Volatile, true);
1643   case 'T':
1644     return std::make_pair(Qualifiers(Q_Const | Q_Volatile), true);
1645   // Non-Member qualifiers
1646   case 'A':
1647     return std::make_pair(Q_None, false);
1648   case 'B':
1649     return std::make_pair(Q_Const, false);
1650   case 'C':
1651     return std::make_pair(Q_Volatile, false);
1652   case 'D':
1653     return std::make_pair(Qualifiers(Q_Const | Q_Volatile), false);
1654   }
1655   Error = true;
1656   return std::make_pair(Q_None, false);
1657 }
1658 
1659 static bool isTagType(StringView S) {
1660   switch (S.front()) {
1661   case 'T': // union
1662   case 'U': // struct
1663   case 'V': // class
1664   case 'W': // enum
1665     return true;
1666   }
1667   return false;
1668 }
1669 
1670 static bool isPointerType(StringView S) {
1671   if (S.startsWith("$$Q")) // foo &&
1672     return true;
1673 
1674   switch (S.front()) {
1675   case 'A': // foo &
1676   case 'P': // foo *
1677   case 'Q': // foo *const
1678   case 'R': // foo *volatile
1679   case 'S': // foo *const volatile
1680     return true;
1681   }
1682   return false;
1683 }
1684 
1685 static bool isArrayType(StringView S) { return S[0] == 'Y'; }
1686 
1687 static bool isFunctionType(StringView S) {
1688   return S.startsWith("$$A8@@") || S.startsWith("$$A6");
1689 }
1690 
1691 // <variable-type> ::= <type> <cvr-qualifiers>
1692 //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
1693 Type *Demangler::demangleType(StringView &MangledName,
1694                               QualifierMangleMode QMM) {
1695   Qualifiers Quals = Q_None;
1696   bool IsMember = false;
1697   bool IsMemberKnown = false;
1698   if (QMM == QualifierMangleMode::Mangle) {
1699     std::tie(Quals, IsMember) = demangleQualifiers(MangledName);
1700     IsMemberKnown = true;
1701   } else if (QMM == QualifierMangleMode::Result) {
1702     if (MangledName.consumeFront('?')) {
1703       std::tie(Quals, IsMember) = demangleQualifiers(MangledName);
1704       IsMemberKnown = true;
1705     }
1706   }
1707 
1708   Type *Ty = nullptr;
1709   if (isTagType(MangledName))
1710     Ty = demangleClassType(MangledName);
1711   else if (isPointerType(MangledName)) {
1712     if (!IsMemberKnown)
1713       IsMember = isMemberPointer(MangledName);
1714 
1715     if (IsMember)
1716       Ty = demangleMemberPointerType(MangledName);
1717     else
1718       Ty = demanglePointerType(MangledName);
1719   } else if (isArrayType(MangledName))
1720     Ty = demangleArrayType(MangledName);
1721   else if (isFunctionType(MangledName)) {
1722     if (MangledName.consumeFront("$$A8@@"))
1723       Ty = demangleFunctionType(MangledName, true, false);
1724     else {
1725       assert(MangledName.startsWith("$$A6"));
1726       MangledName.consumeFront("$$A6");
1727       Ty = demangleFunctionType(MangledName, false, false);
1728     }
1729   } else {
1730     Ty = demangleBasicType(MangledName);
1731     assert(Ty && !Error);
1732     if (!Ty || Error)
1733       return Ty;
1734   }
1735 
1736   Ty->Quals = Qualifiers(Ty->Quals | Quals);
1737   return Ty;
1738 }
1739 
1740 ReferenceKind Demangler::demangleReferenceKind(StringView &MangledName) {
1741   if (MangledName.consumeFront('G'))
1742     return ReferenceKind::LValueRef;
1743   else if (MangledName.consumeFront('H'))
1744     return ReferenceKind::RValueRef;
1745   return ReferenceKind::None;
1746 }
1747 
1748 void Demangler::demangleThrowSpecification(StringView &MangledName) {
1749   if (MangledName.consumeFront('Z'))
1750     return;
1751 
1752   Error = true;
1753 }
1754 
1755 FunctionType *Demangler::demangleFunctionType(StringView &MangledName,
1756                                               bool HasThisQuals,
1757                                               bool IsFunctionPointer) {
1758   FunctionType *FTy = Arena.alloc<FunctionType>();
1759   FTy->Prim = PrimTy::Function;
1760   FTy->IsFunctionPointer = IsFunctionPointer;
1761 
1762   if (HasThisQuals) {
1763     FTy->Quals = demanglePointerExtQualifiers(MangledName);
1764     FTy->RefKind = demangleReferenceKind(MangledName);
1765     FTy->Quals = Qualifiers(FTy->Quals | demangleQualifiers(MangledName).first);
1766   }
1767 
1768   // Fields that appear on both member and non-member functions.
1769   FTy->CallConvention = demangleCallingConvention(MangledName);
1770 
1771   // <return-type> ::= <type>
1772   //               ::= @ # structors (they have no declared return type)
1773   bool IsStructor = MangledName.consumeFront('@');
1774   if (!IsStructor)
1775     FTy->ReturnType = demangleType(MangledName, QualifierMangleMode::Result);
1776 
1777   FTy->Params = demangleFunctionParameterList(MangledName);
1778 
1779   demangleThrowSpecification(MangledName);
1780 
1781   return FTy;
1782 }
1783 
1784 Type *Demangler::demangleFunctionEncoding(StringView &MangledName) {
1785   FuncClass FC = demangleFunctionClass(MangledName);
1786   FunctionType *FTy = nullptr;
1787   if (FC & NoPrototype) {
1788     // This is an extern "C" function whose full signature hasn't been mangled.
1789     // This happens when we need to mangle a local symbol inside of an extern
1790     // "C" function.
1791     FTy = Arena.alloc<FunctionType>();
1792   } else {
1793     bool HasThisQuals = !(FC & (Global | Static));
1794     FTy = demangleFunctionType(MangledName, HasThisQuals, false);
1795   }
1796   FTy->FunctionClass = FC;
1797 
1798   return FTy;
1799 }
1800 
1801 // Reads a primitive type.
1802 Type *Demangler::demangleBasicType(StringView &MangledName) {
1803   Type *Ty = Arena.alloc<Type>();
1804 
1805   if (MangledName.consumeFront("$$T")) {
1806     Ty->Prim = PrimTy::Nullptr;
1807     return Ty;
1808   }
1809 
1810   switch (MangledName.popFront()) {
1811   case 'X':
1812     Ty->Prim = PrimTy::Void;
1813     break;
1814   case 'D':
1815     Ty->Prim = PrimTy::Char;
1816     break;
1817   case 'C':
1818     Ty->Prim = PrimTy::Schar;
1819     break;
1820   case 'E':
1821     Ty->Prim = PrimTy::Uchar;
1822     break;
1823   case 'F':
1824     Ty->Prim = PrimTy::Short;
1825     break;
1826   case 'G':
1827     Ty->Prim = PrimTy::Ushort;
1828     break;
1829   case 'H':
1830     Ty->Prim = PrimTy::Int;
1831     break;
1832   case 'I':
1833     Ty->Prim = PrimTy::Uint;
1834     break;
1835   case 'J':
1836     Ty->Prim = PrimTy::Long;
1837     break;
1838   case 'K':
1839     Ty->Prim = PrimTy::Ulong;
1840     break;
1841   case 'M':
1842     Ty->Prim = PrimTy::Float;
1843     break;
1844   case 'N':
1845     Ty->Prim = PrimTy::Double;
1846     break;
1847   case 'O':
1848     Ty->Prim = PrimTy::Ldouble;
1849     break;
1850   case '_': {
1851     if (MangledName.empty()) {
1852       Error = true;
1853       return nullptr;
1854     }
1855     switch (MangledName.popFront()) {
1856     case 'N':
1857       Ty->Prim = PrimTy::Bool;
1858       break;
1859     case 'J':
1860       Ty->Prim = PrimTy::Int64;
1861       break;
1862     case 'K':
1863       Ty->Prim = PrimTy::Uint64;
1864       break;
1865     case 'W':
1866       Ty->Prim = PrimTy::Wchar;
1867       break;
1868     case 'S':
1869       Ty->Prim = PrimTy::Char16;
1870       break;
1871     case 'U':
1872       Ty->Prim = PrimTy::Char32;
1873       break;
1874     default:
1875       Error = true;
1876       return nullptr;
1877     }
1878     break;
1879   }
1880   default:
1881     Error = true;
1882     return nullptr;
1883   }
1884   return Ty;
1885 }
1886 
1887 UdtType *Demangler::demangleClassType(StringView &MangledName) {
1888   UdtType *UTy = Arena.alloc<UdtType>();
1889 
1890   switch (MangledName.popFront()) {
1891   case 'T':
1892     UTy->Prim = PrimTy::Union;
1893     break;
1894   case 'U':
1895     UTy->Prim = PrimTy::Struct;
1896     break;
1897   case 'V':
1898     UTy->Prim = PrimTy::Class;
1899     break;
1900   case 'W':
1901     if (MangledName.popFront() != '4') {
1902       Error = true;
1903       return nullptr;
1904     }
1905     UTy->Prim = PrimTy::Enum;
1906     break;
1907   default:
1908     assert(false);
1909   }
1910 
1911   UTy->UdtName = demangleFullyQualifiedTypeName(MangledName);
1912   return UTy;
1913 }
1914 
1915 static std::pair<Qualifiers, PointerAffinity>
1916 demanglePointerCVQualifiers(StringView &MangledName) {
1917   if (MangledName.consumeFront("$$Q"))
1918     return std::make_pair(Q_None, PointerAffinity::RValueReference);
1919 
1920   switch (MangledName.popFront()) {
1921   case 'A':
1922     return std::make_pair(Q_None, PointerAffinity::Reference);
1923   case 'P':
1924     return std::make_pair(Q_None, PointerAffinity::Pointer);
1925   case 'Q':
1926     return std::make_pair(Q_Const, PointerAffinity::Pointer);
1927   case 'R':
1928     return std::make_pair(Q_Volatile, PointerAffinity::Pointer);
1929   case 'S':
1930     return std::make_pair(Qualifiers(Q_Const | Q_Volatile),
1931                           PointerAffinity::Pointer);
1932   default:
1933     assert(false && "Ty is not a pointer type!");
1934   }
1935   return std::make_pair(Q_None, PointerAffinity::Pointer);
1936 }
1937 
1938 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <ext-qualifiers> <type>
1939 //                       # the E is required for 64-bit non-static pointers
1940 PointerType *Demangler::demanglePointerType(StringView &MangledName) {
1941   PointerType *Pointer = Arena.alloc<PointerType>();
1942 
1943   std::tie(Pointer->Quals, Pointer->Affinity) =
1944       demanglePointerCVQualifiers(MangledName);
1945 
1946   Pointer->Prim = PrimTy::Ptr;
1947   if (MangledName.consumeFront("6")) {
1948     Pointer->Pointee = demangleFunctionType(MangledName, false, true);
1949     return Pointer;
1950   }
1951 
1952   Qualifiers ExtQuals = demanglePointerExtQualifiers(MangledName);
1953   Pointer->Quals = Qualifiers(Pointer->Quals | ExtQuals);
1954 
1955   Pointer->Pointee = demangleType(MangledName, QualifierMangleMode::Mangle);
1956   return Pointer;
1957 }
1958 
1959 MemberPointerType *
1960 Demangler::demangleMemberPointerType(StringView &MangledName) {
1961   MemberPointerType *Pointer = Arena.alloc<MemberPointerType>();
1962   Pointer->Prim = PrimTy::MemberPtr;
1963 
1964   PointerAffinity Affinity;
1965   std::tie(Pointer->Quals, Affinity) = demanglePointerCVQualifiers(MangledName);
1966   assert(Affinity == PointerAffinity::Pointer);
1967 
1968   Qualifiers ExtQuals = demanglePointerExtQualifiers(MangledName);
1969   Pointer->Quals = Qualifiers(Pointer->Quals | ExtQuals);
1970 
1971   if (MangledName.consumeFront("8")) {
1972     Pointer->MemberName = demangleFullyQualifiedSymbolName(MangledName);
1973     Pointer->Pointee = demangleFunctionType(MangledName, true, true);
1974   } else {
1975     Qualifiers PointeeQuals = Q_None;
1976     bool IsMember = false;
1977     std::tie(PointeeQuals, IsMember) = demangleQualifiers(MangledName);
1978     assert(IsMember);
1979     Pointer->MemberName = demangleFullyQualifiedSymbolName(MangledName);
1980 
1981     Pointer->Pointee = demangleType(MangledName, QualifierMangleMode::Drop);
1982     Pointer->Pointee->Quals = PointeeQuals;
1983   }
1984 
1985   return Pointer;
1986 }
1987 
1988 Qualifiers Demangler::demanglePointerExtQualifiers(StringView &MangledName) {
1989   Qualifiers Quals = Q_None;
1990   if (MangledName.consumeFront('E'))
1991     Quals = Qualifiers(Quals | Q_Pointer64);
1992   if (MangledName.consumeFront('I'))
1993     Quals = Qualifiers(Quals | Q_Restrict);
1994   if (MangledName.consumeFront('F'))
1995     Quals = Qualifiers(Quals | Q_Unaligned);
1996 
1997   return Quals;
1998 }
1999 
2000 ArrayType *Demangler::demangleArrayType(StringView &MangledName) {
2001   assert(MangledName.front() == 'Y');
2002   MangledName.popFront();
2003 
2004   uint64_t Rank = 0;
2005   bool IsNegative = false;
2006   std::tie(Rank, IsNegative) = demangleNumber(MangledName);
2007   if (IsNegative || Rank == 0) {
2008     Error = true;
2009     return nullptr;
2010   }
2011 
2012   ArrayType *ATy = Arena.alloc<ArrayType>();
2013   ATy->Prim = PrimTy::Array;
2014   ATy->Dims = Arena.alloc<ArrayDimension>();
2015   ArrayDimension *Dim = ATy->Dims;
2016   for (uint64_t I = 0; I < Rank; ++I) {
2017     std::tie(Dim->Dim, IsNegative) = demangleNumber(MangledName);
2018     if (IsNegative) {
2019       Error = true;
2020       return nullptr;
2021     }
2022     if (I + 1 < Rank) {
2023       Dim->Next = Arena.alloc<ArrayDimension>();
2024       Dim = Dim->Next;
2025     }
2026   }
2027 
2028   if (MangledName.consumeFront("$$C")) {
2029     bool IsMember = false;
2030     std::tie(ATy->Quals, IsMember) = demangleQualifiers(MangledName);
2031     if (IsMember) {
2032       Error = true;
2033       return nullptr;
2034     }
2035   }
2036 
2037   ATy->ElementType = demangleType(MangledName, QualifierMangleMode::Drop);
2038   return ATy;
2039 }
2040 
2041 // Reads a function or a template parameters.
2042 FunctionParams
2043 Demangler::demangleFunctionParameterList(StringView &MangledName) {
2044   // Empty parameter list.
2045   if (MangledName.consumeFront('X'))
2046     return {};
2047 
2048   FunctionParams *Head;
2049   FunctionParams **Current = &Head;
2050   while (!Error && !MangledName.startsWith('@') &&
2051          !MangledName.startsWith('Z')) {
2052 
2053     if (startsWithDigit(MangledName)) {
2054       size_t N = MangledName[0] - '0';
2055       if (N >= Backrefs.FunctionParamCount) {
2056         Error = true;
2057         return {};
2058       }
2059       MangledName = MangledName.dropFront();
2060 
2061       *Current = Arena.alloc<FunctionParams>();
2062       (*Current)->Current = Backrefs.FunctionParams[N]->clone(Arena);
2063       Current = &(*Current)->Next;
2064       continue;
2065     }
2066 
2067     size_t OldSize = MangledName.size();
2068 
2069     *Current = Arena.alloc<FunctionParams>();
2070     (*Current)->Current = demangleType(MangledName, QualifierMangleMode::Drop);
2071 
2072     size_t CharsConsumed = OldSize - MangledName.size();
2073     assert(CharsConsumed != 0);
2074 
2075     // Single-letter types are ignored for backreferences because memorizing
2076     // them doesn't save anything.
2077     if (Backrefs.FunctionParamCount <= 9 && CharsConsumed > 1)
2078       Backrefs.FunctionParams[Backrefs.FunctionParamCount++] =
2079           (*Current)->Current;
2080 
2081     Current = &(*Current)->Next;
2082   }
2083 
2084   if (Error)
2085     return {};
2086 
2087   // A non-empty parameter list is terminated by either 'Z' (variadic) parameter
2088   // list or '@' (non variadic).  Careful not to consume "@Z", as in that case
2089   // the following Z could be a throw specifier.
2090   if (MangledName.consumeFront('@'))
2091     return *Head;
2092 
2093   if (MangledName.consumeFront('Z')) {
2094     Head->IsVariadic = true;
2095     return *Head;
2096   }
2097 
2098   Error = true;
2099   return {};
2100 }
2101 
2102 TemplateParams *
2103 Demangler::demangleTemplateParameterList(StringView &MangledName) {
2104   TemplateParams *Head;
2105   TemplateParams **Current = &Head;
2106   while (!Error && !MangledName.startsWith('@')) {
2107     // Template parameter lists don't participate in back-referencing.
2108     *Current = Arena.alloc<TemplateParams>();
2109 
2110     // Empty parameter pack.
2111     if (MangledName.consumeFront("$S") || MangledName.consumeFront("$$V") ||
2112         MangledName.consumeFront("$$$V")) {
2113       (*Current)->IsEmptyParameterPack = true;
2114       break;
2115     }
2116 
2117     if (MangledName.consumeFront("$$Y")) {
2118       // Template alias
2119       (*Current)->IsTemplateTemplate = true;
2120       (*Current)->IsAliasTemplate = true;
2121       (*Current)->ParamName = demangleFullyQualifiedTypeName(MangledName);
2122     } else if (MangledName.consumeFront("$$B")) {
2123       // Array
2124       (*Current)->ParamType =
2125           demangleType(MangledName, QualifierMangleMode::Drop);
2126     } else if (MangledName.consumeFront("$$C")) {
2127       // Type has qualifiers.
2128       (*Current)->ParamType =
2129           demangleType(MangledName, QualifierMangleMode::Mangle);
2130     } else if (MangledName.startsWith("$1?")) {
2131       MangledName.consumeFront("$1");
2132       // Pointer to symbol
2133       Symbol *S = parse(MangledName);
2134       (*Current)->ParamName = S->SymbolName;
2135       (*Current)->ParamType = S->SymbolType;
2136       (*Current)->PointerToSymbol = true;
2137     } else if (MangledName.startsWith("$E?")) {
2138       MangledName.consumeFront("$E");
2139       // Reference to symbol
2140       Symbol *S = parse(MangledName);
2141       (*Current)->ParamName = S->SymbolName;
2142       (*Current)->ParamType = S->SymbolType;
2143       (*Current)->ReferenceToSymbol = true;
2144     } else if (MangledName.consumeFront("$0")) {
2145       // Integral non-type template parameter
2146       bool IsNegative = false;
2147       uint64_t Value = 0;
2148       std::tie(Value, IsNegative) = demangleNumber(MangledName);
2149 
2150       (*Current)->IsIntegerLiteral = true;
2151       (*Current)->IntegerLiteralIsNegative = IsNegative;
2152       (*Current)->IntegralValue = Value;
2153     } else {
2154       (*Current)->ParamType =
2155           demangleType(MangledName, QualifierMangleMode::Drop);
2156     }
2157     if (Error)
2158       return nullptr;
2159 
2160     Current = &(*Current)->Next;
2161   }
2162 
2163   if (Error)
2164     return nullptr;
2165 
2166   // Template parameter lists cannot be variadic, so it can only be terminated
2167   // by @.
2168   if (MangledName.consumeFront('@'))
2169     return Head;
2170   Error = true;
2171   return nullptr;
2172 }
2173 
2174 StringView Demangler::resolve(StringView N) {
2175   assert(N.size() == 1 && isdigit(N[0]));
2176   size_t Digit = N[0] - '0';
2177   if (Digit >= Backrefs.NamesCount)
2178     return N;
2179   return Backrefs.Names[Digit];
2180 }
2181 
2182 void Demangler::output(const Symbol *S, OutputStream &OS) {
2183   // Converts an AST to a string.
2184   //
2185   // Converting an AST representing a C++ type to a string is tricky due
2186   // to the bad grammar of the C++ declaration inherited from C. You have
2187   // to construct a string from inside to outside. For example, if a type
2188   // X is a pointer to a function returning int, the order you create a
2189   // string becomes something like this:
2190   //
2191   //   (1) X is a pointer: *X
2192   //   (2) (1) is a function returning int: int (*X)()
2193   //
2194   // So you cannot construct a result just by appending strings to a result.
2195   //
2196   // To deal with this, we split the function into two. outputPre() writes
2197   // the "first half" of type declaration, and outputPost() writes the
2198   // "second half". For example, outputPre() writes a return type for a
2199   // function and outputPost() writes an parameter list.
2200   Type::outputPre(OS, *S->SymbolType, *this);
2201   outputName(OS, S->SymbolName, S->SymbolType, *this);
2202   Type::outputPost(OS, *S->SymbolType, *this);
2203 }
2204 
2205 void Demangler::dumpBackReferences() {
2206   std::printf("%d function parameter backreferences\n",
2207               (int)Backrefs.FunctionParamCount);
2208 
2209   // Create an output stream so we can render each type.
2210   OutputStream OS = OutputStream::create(nullptr, 0, 1024);
2211   for (size_t I = 0; I < Backrefs.FunctionParamCount; ++I) {
2212     OS.setCurrentPosition(0);
2213 
2214     Type *T = Backrefs.FunctionParams[I];
2215     Type::outputPre(OS, *T, *this);
2216     Type::outputPost(OS, *T, *this);
2217 
2218     std::printf("  [%d] - %.*s\n", (int)I, (int)OS.getCurrentPosition(),
2219                 OS.getBuffer());
2220   }
2221   std::free(OS.getBuffer());
2222 
2223   if (Backrefs.FunctionParamCount > 0)
2224     std::printf("\n");
2225   std::printf("%d name backreferences\n", (int)Backrefs.NamesCount);
2226   for (size_t I = 0; I < Backrefs.NamesCount; ++I) {
2227     std::printf("  [%d] - %.*s\n", (int)I, (int)Backrefs.Names[I].size(),
2228                 Backrefs.Names[I].begin());
2229   }
2230   if (Backrefs.NamesCount > 0)
2231     std::printf("\n");
2232 }
2233 
2234 char *llvm::microsoftDemangle(const char *MangledName, char *Buf, size_t *N,
2235                               int *Status, MSDemangleFlags Flags) {
2236   Demangler D;
2237   StringView Name{MangledName};
2238   Symbol *S = D.parse(Name);
2239 
2240   if (Flags & MSDF_DumpBackrefs)
2241     D.dumpBackReferences();
2242   OutputStream OS = OutputStream::create(Buf, N, 1024);
2243   if (D.Error) {
2244     OS << MangledName;
2245     *Status = llvm::demangle_invalid_mangled_name;
2246   } else {
2247     D.output(S, OS);
2248     *Status = llvm::demangle_success;
2249   }
2250 
2251   OS << '\0';
2252   return OS.getBuffer();
2253 }
2254