1 //===--- Demangler.cpp - String to Node-Tree Demangling -------------------===//
2 //
3 // This source file is part of the Swift.org open source project
4 //
5 // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
6 // Licensed under Apache License v2.0 with Runtime Library Exception
7 //
8 // See https://swift.org/LICENSE.txt for license information
9 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 //  This file implements new Swift de-mangler.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "swift/Demangling/Demangler.h"
18 #include "swift/Demangling/ManglingUtils.h"
19 #include "swift/Demangling/ManglingMacros.h"
20 #include "swift/Demangling/Punycode.h"
21 #include "swift/Strings.h"
22 
23 using namespace swift;
24 using namespace Mangle;
25 using swift::Demangle::FunctionSigSpecializationParamKind;
26 
27 //////////////////////////////////
28 // Private utility functions    //
29 //////////////////////////////////
30 
31 namespace {
32 
isDeclName(Node::Kind kind)33 static bool isDeclName(Node::Kind kind) {
34   switch (kind) {
35     case Node::Kind::Identifier:
36     case Node::Kind::LocalDeclName:
37     case Node::Kind::PrivateDeclName:
38     case Node::Kind::RelatedEntityDeclName:
39     case Node::Kind::PrefixOperator:
40     case Node::Kind::PostfixOperator:
41     case Node::Kind::InfixOperator:
42     case Node::Kind::TypeSymbolicReference:
43     case Node::Kind::ProtocolSymbolicReference:
44       return true;
45     default:
46       return false;
47   }
48 }
49 
isAnyGeneric(Node::Kind kind)50 static bool isAnyGeneric(Node::Kind kind) {
51   switch (kind) {
52     case Node::Kind::Structure:
53     case Node::Kind::Class:
54     case Node::Kind::Enum:
55     case Node::Kind::Protocol:
56     case Node::Kind::ProtocolSymbolicReference:
57     case Node::Kind::OtherNominalType:
58     case Node::Kind::TypeAlias:
59     case Node::Kind::TypeSymbolicReference:
60       return true;
61     default:
62       return false;
63   }
64 }
65 
isEntity(Node::Kind kind)66 static bool isEntity(Node::Kind kind) {
67   // Also accepts some kind which are not entities.
68   if (kind == Node::Kind::Type)
69     return true;
70   return isContext(kind);
71 }
72 
isRequirement(Node::Kind kind)73 static bool isRequirement(Node::Kind kind) {
74   switch (kind) {
75     case Node::Kind::DependentGenericSameTypeRequirement:
76     case Node::Kind::DependentGenericLayoutRequirement:
77     case Node::Kind::DependentGenericConformanceRequirement:
78       return true;
79     default:
80       return false;
81   }
82 }
83 
84 } // anonymous namespace
85 
86 //////////////////////////////////
87 // Public utility functions    //
88 //////////////////////////////////
89 
isContext(Node::Kind kind)90 bool swift::Demangle::isContext(Node::Kind kind) {
91   switch (kind) {
92 #define NODE(ID)
93 #define CONTEXT_NODE(ID)                                                \
94     case Node::Kind::ID:
95 #include "swift/Demangling/DemangleNodes.def"
96       return true;
97     default:
98       return false;
99   }
100 }
101 
isFunctionAttr(Node::Kind kind)102 bool swift::Demangle::isFunctionAttr(Node::Kind kind) {
103   switch (kind) {
104     case Node::Kind::FunctionSignatureSpecialization:
105     case Node::Kind::GenericSpecialization:
106     case Node::Kind::InlinedGenericFunction:
107     case Node::Kind::GenericSpecializationNotReAbstracted:
108     case Node::Kind::GenericPartialSpecialization:
109     case Node::Kind::GenericPartialSpecializationNotReAbstracted:
110     case Node::Kind::ObjCAttribute:
111     case Node::Kind::NonObjCAttribute:
112     case Node::Kind::DynamicAttribute:
113     case Node::Kind::DirectMethodReferenceAttribute:
114     case Node::Kind::VTableAttribute:
115     case Node::Kind::PartialApplyForwarder:
116     case Node::Kind::PartialApplyObjCForwarder:
117     case Node::Kind::OutlinedVariable:
118     case Node::Kind::OutlinedBridgedMethod:
119     case Node::Kind::MergedFunction:
120     case Node::Kind::DynamicallyReplaceableFunctionImpl:
121     case Node::Kind::DynamicallyReplaceableFunctionKey:
122     case Node::Kind::DynamicallyReplaceableFunctionVar:
123       return true;
124     default:
125       return false;
126   }
127 }
128 
129 llvm::StringRef
makeSymbolicMangledNameStringRef(const char * base)130 swift::Demangle::makeSymbolicMangledNameStringRef(const char *base) {
131   if (!base)
132     return {};
133 
134   auto end = base;
135   while (*end != '\0') {
136     // Skip over symbolic references.
137     if (*end >= '\x01' && *end <= '\x17')
138       end += sizeof(uint32_t);
139     else if (*end >= '\x18' && *end <= '\x1F')
140       end += sizeof(void*);
141     ++end;
142   }
143   return StringRef(base, end - base);
144 }
145 
getManglingPrefixLength(llvm::StringRef mangledName)146 int swift::Demangle::getManglingPrefixLength(llvm::StringRef mangledName) {
147   if (mangledName.empty()) return 0;
148 
149   llvm::StringRef prefixes[] = {
150     /*Swift 4*/   "_T0",
151     /*Swift 4.x*/ "$S", "_$S",
152     /*Swift 5+*/  "$s", "_$s"};
153 
154   // Look for any of the known prefixes
155   for (auto prefix : prefixes) {
156     if (mangledName.startswith(prefix))
157       return prefix.size();
158   }
159 
160   return 0;
161 }
162 
isSwiftSymbol(llvm::StringRef mangledName)163 bool swift::Demangle::isSwiftSymbol(llvm::StringRef mangledName) {
164   if (isOldFunctionTypeMangling(mangledName))
165     return true;
166 
167   return getManglingPrefixLength(mangledName) != 0;
168 }
169 
isSwiftSymbol(const char * mangledName)170 bool swift::Demangle::isSwiftSymbol(const char *mangledName) {
171   StringRef mangledNameRef(mangledName);
172   return isSwiftSymbol(mangledNameRef);
173 }
174 
isObjCSymbol(llvm::StringRef mangledName)175 bool swift::Demangle::isObjCSymbol(llvm::StringRef mangledName) {
176   StringRef nameWithoutPrefix = dropSwiftManglingPrefix(mangledName);
177   return nameWithoutPrefix.startswith("So") ||
178          nameWithoutPrefix.startswith("SC");
179 }
180 
isOldFunctionTypeMangling(llvm::StringRef mangledName)181 bool swift::Demangle::isOldFunctionTypeMangling(llvm::StringRef mangledName) {
182   return mangledName.startswith("_T");
183 }
184 
dropSwiftManglingPrefix(StringRef mangledName)185 llvm::StringRef swift::Demangle::dropSwiftManglingPrefix(StringRef mangledName){
186   return mangledName.drop_front(getManglingPrefixLength(mangledName));
187 }
188 
isAliasNode(Demangle::NodePointer Node)189 static bool isAliasNode(Demangle::NodePointer Node) {
190   switch (Node->getKind()) {
191   case Demangle::Node::Kind::Type:
192     return isAliasNode(Node->getChild(0));
193   case Demangle::Node::Kind::TypeAlias:
194     return true;
195   default:
196     return false;
197   }
198   assert(0 && "unknown node kind");
199 }
200 
isAlias(llvm::StringRef mangledName)201 bool swift::Demangle::isAlias(llvm::StringRef mangledName) {
202   Demangle::Demangler Dem;
203   return isAliasNode(Dem.demangleType(mangledName));
204 }
205 
isClassNode(Demangle::NodePointer Node)206 static bool isClassNode(Demangle::NodePointer Node) {
207   switch (Node->getKind()) {
208   case Demangle::Node::Kind::Type:
209     return isClassNode(Node->getChild(0));
210   case Demangle::Node::Kind::Class:
211   case Demangle::Node::Kind::BoundGenericClass:
212     return true;
213   default:
214     return false;
215   }
216   assert(0 && "unknown node kind");
217 }
218 
isClass(llvm::StringRef mangledName)219 bool swift::Demangle::isClass(llvm::StringRef mangledName) {
220   Demangle::Demangler Dem;
221   return isClassNode(Dem.demangleType(mangledName));
222 }
223 
isEnumNode(Demangle::NodePointer Node)224 static bool isEnumNode(Demangle::NodePointer Node) {
225   switch (Node->getKind()) {
226   case Demangle::Node::Kind::Type:
227     return isEnumNode(Node->getChild(0));
228   case Demangle::Node::Kind::Enum:
229   case Demangle::Node::Kind::BoundGenericEnum:
230     return true;
231   default:
232     return false;
233   }
234   assert(0 && "unknown node kind");
235 }
236 
isEnum(llvm::StringRef mangledName)237 bool swift::Demangle::isEnum(llvm::StringRef mangledName) {
238   Demangle::Demangler Dem;
239   return isEnumNode(Dem.demangleType(mangledName));
240 }
241 
isProtocolNode(Demangle::NodePointer Node)242 static bool isProtocolNode(Demangle::NodePointer Node) {
243   switch (Node->getKind()) {
244   case Demangle::Node::Kind::Type:
245     return isProtocolNode(Node->getChild(0));
246   case Demangle::Node::Kind::Protocol:
247   case Demangle::Node::Kind::ProtocolSymbolicReference:
248     return true;
249   default:
250     return false;
251   }
252   assert(0 && "unknown node kind");
253 }
254 
isProtocol(llvm::StringRef mangledName)255 bool swift::Demangle::isProtocol(llvm::StringRef mangledName) {
256   Demangle::Demangler Dem;
257   return isProtocolNode(Dem.demangleType(dropSwiftManglingPrefix(mangledName)));
258 }
259 
isStructNode(Demangle::NodePointer Node)260 static bool isStructNode(Demangle::NodePointer Node) {
261   switch (Node->getKind()) {
262   case Demangle::Node::Kind::Type:
263     return isStructNode(Node->getChild(0));
264   case Demangle::Node::Kind::Structure:
265   case Demangle::Node::Kind::BoundGenericStructure:
266     return true;
267   default:
268     return false;
269   }
270   assert(0 && "unknown node kind");
271 }
272 
isStruct(llvm::StringRef mangledName)273 bool swift::Demangle::isStruct(llvm::StringRef mangledName) {
274   Demangle::Demangler Dem;
275   return isStructNode(Dem.demangleType(mangledName));
276 }
277 
278 using namespace swift;
279 using namespace Demangle;
280 
281 //////////////////////////////////
282 // Node member functions        //
283 //////////////////////////////////
284 
getNumChildren() const285 size_t Node::getNumChildren() const {
286   switch (NodePayloadKind) {
287     case PayloadKind::OneChild: return 1;
288     case PayloadKind::TwoChildren: return 2;
289     case PayloadKind::ManyChildren: return Children.Number;
290     default: return 0;
291   }
292 }
293 
begin() const294 Node::iterator Node::begin() const {
295   switch (NodePayloadKind) {
296     case PayloadKind::OneChild:
297     case PayloadKind::TwoChildren:
298       return &InlineChildren[0];
299     case PayloadKind::ManyChildren:
300       return Children.Nodes;
301     default:
302       return nullptr;
303   }
304 }
305 
end() const306 Node::iterator Node::end() const {
307   switch (NodePayloadKind) {
308     case PayloadKind::OneChild:
309       return &InlineChildren[1];
310     case PayloadKind::TwoChildren:
311       return &InlineChildren[2];
312     case PayloadKind::ManyChildren:
313       return Children.Nodes + Children.Number;
314     default:
315       return nullptr;
316   }
317 }
318 
addChild(NodePointer Child,NodeFactory & Factory)319 void Node::addChild(NodePointer Child, NodeFactory &Factory) {
320   assert(Child);
321   switch (NodePayloadKind) {
322     case PayloadKind::None:
323       InlineChildren[0] = Child;
324       InlineChildren[1] = nullptr;
325       NodePayloadKind = PayloadKind::OneChild;
326       break;
327     case PayloadKind::OneChild:
328       assert(!InlineChildren[1]);
329       InlineChildren[1] = Child;
330       NodePayloadKind = PayloadKind::TwoChildren;
331       break;
332     case PayloadKind::TwoChildren: {
333       NodePointer Child0 = InlineChildren[0];
334       NodePointer Child1 = InlineChildren[1];
335       Children.Nodes = nullptr;
336       Children.Number = 0;
337       Children.Capacity = 0;
338       Factory.Reallocate(Children.Nodes, Children.Capacity, 3);
339       assert(Children.Capacity >= 3);
340       Children.Nodes[0] = Child0;
341       Children.Nodes[1] = Child1;
342       Children.Nodes[2] = Child;
343       Children.Number = 3;
344       NodePayloadKind = PayloadKind::ManyChildren;
345       break;
346     }
347     case PayloadKind::ManyChildren:
348       if (Children.Number >= Children.Capacity) {
349         Factory.Reallocate(Children.Nodes, Children.Capacity, 1);
350       }
351       assert(Children.Number < Children.Capacity);
352       Children.Nodes[Children.Number++] = Child;
353       break;
354     default:
355       assert(false && "cannot add child");
356   }
357 }
358 
removeChildAt(unsigned Pos)359 void Node::removeChildAt(unsigned Pos) {
360   switch (NodePayloadKind) {
361     case PayloadKind::OneChild:
362       assert(Pos == 0);
363       NodePayloadKind = PayloadKind::None;
364       break;
365     case PayloadKind::TwoChildren: {
366       assert(Pos < 2);
367       if (Pos == 0)
368         InlineChildren[0] = InlineChildren[1];
369       NodePayloadKind = PayloadKind::OneChild;
370       break;
371     }
372     case PayloadKind::ManyChildren:
373       for (unsigned i = Pos, n = Children.Number - 1; i != n; ++i) {
374         Children.Nodes[i] = Children.Nodes[i + 1];
375       }
376       Children.Number--;
377       break;
378     default:
379       assert(false && "cannot remove child");
380   }
381 }
382 
reverseChildren(size_t StartingAt)383 void Node::reverseChildren(size_t StartingAt) {
384   assert(StartingAt <= getNumChildren());
385   switch (NodePayloadKind) {
386     case PayloadKind::TwoChildren:
387       if (StartingAt == 0)
388         std::swap(InlineChildren[0], InlineChildren[1]);
389       break;
390     case PayloadKind::ManyChildren:
391       std::reverse(Children.Nodes + StartingAt,
392                    Children.Nodes + Children.Number);
393       break;
394     default:
395       break;
396   }
397 }
398 
399 //////////////////////////////////
400 // NodeFactory member functions //
401 //////////////////////////////////
402 
freeSlabs(Slab * slab)403 void NodeFactory::freeSlabs(Slab *slab) {
404   while (slab) {
405     Slab *prev = slab->Previous;
406     free(slab);
407     slab = prev;
408   }
409 }
410 
clear()411 void NodeFactory::clear() {
412   assert(!isBorrowed);
413   if (CurrentSlab) {
414 #ifdef NODE_FACTORY_DEBUGGING
415     fprintf(stderr, "%s## clear: allocated memory = %zu\n", indent().c_str(), allocatedMemory);
416 #endif
417 
418     freeSlabs(CurrentSlab->Previous);
419 
420     // Recycle the last allocated slab.
421     // Note that the size of the last slab is at least as big as all previous
422     // slabs combined. Therefore it's not worth the effort of reusing all slabs.
423     // The slab size also stays the same. So at some point the demangling
424     // process converges to a single large slab across repeated demangle-clear
425     // cycles.
426     CurrentSlab->Previous = nullptr;
427     CurPtr = (char *)(CurrentSlab + 1);
428     assert(End == CurPtr + SlabSize);
429 #ifdef NODE_FACTORY_DEBUGGING
430     allocatedMemory = 0;
431 #endif
432   }
433 }
434 
createNode(Node::Kind K)435 NodePointer NodeFactory::createNode(Node::Kind K) {
436   return new (Allocate<Node>()) Node(K);
437 }
createNode(Node::Kind K,Node::IndexType Index)438 NodePointer NodeFactory::createNode(Node::Kind K, Node::IndexType Index) {
439   return new (Allocate<Node>()) Node(K, Index);
440 }
createNodeWithAllocatedText(Node::Kind K,llvm::StringRef Text)441 NodePointer NodeFactory::createNodeWithAllocatedText(Node::Kind K,
442                                                      llvm::StringRef Text) {
443   return new (Allocate<Node>()) Node(K, Text);
444 }
createNode(Node::Kind K,const CharVector & Text)445 NodePointer NodeFactory::createNode(Node::Kind K, const CharVector &Text) {
446   return createNodeWithAllocatedText(K, Text.str());
447 }
createNode(Node::Kind K,const char * Text)448 NodePointer NodeFactory::createNode(Node::Kind K, const char *Text) {
449   return new (Allocate<Node>()) Node(K, llvm::StringRef(Text));
450 }
451 
452 #ifdef NODE_FACTORY_DEBUGGING
453 int NodeFactory::nestingLevel = 0;
454 #endif
455 
456 //////////////////////////////////
457 // CharVector member functions  //
458 //////////////////////////////////
459 
append(StringRef Rhs,NodeFactory & Factory)460 void CharVector::append(StringRef Rhs, NodeFactory &Factory) {
461   if (NumElems + Rhs.size() > Capacity)
462     Factory.Reallocate(Elems, Capacity, /*Growth*/ Rhs.size());
463   memcpy(Elems + NumElems, Rhs.data(), Rhs.size());
464   NumElems += Rhs.size();
465   assert(NumElems <= Capacity);
466 }
467 
append(int Number,NodeFactory & Factory)468 void CharVector::append(int Number, NodeFactory &Factory) {
469   const int MaxIntPrintSize = 11;
470   if (NumElems + MaxIntPrintSize > Capacity)
471     Factory.Reallocate(Elems, Capacity, /*Growth*/ MaxIntPrintSize);
472   int Length = snprintf(Elems + NumElems, MaxIntPrintSize, "%d", Number);
473   assert(Length > 0 && Length < MaxIntPrintSize);
474   NumElems += Length;
475 }
476 
append(unsigned long long Number,NodeFactory & Factory)477 void CharVector::append(unsigned long long Number, NodeFactory &Factory) {
478   const int MaxPrintSize = 21;
479   if (NumElems + MaxPrintSize > Capacity)
480     Factory.Reallocate(Elems, Capacity, /*Growth*/ MaxPrintSize);
481   int Length = snprintf(Elems + NumElems, MaxPrintSize, "%llu", Number);
482   assert(Length > 0 && Length < MaxPrintSize);
483   NumElems += Length;
484 }
485 
486 //////////////////////////////////
487 // Demangler member functions   //
488 //////////////////////////////////
489 
clear()490 void Demangler::clear() {
491   NodeStack.free();
492   Substitutions.free();
493   NodeFactory::clear();
494 }
495 
DemangleInitRAII(Demangler & Dem,StringRef MangledName,std::function<SymbolicReferenceResolver_t> TheSymbolicReferenceResolver)496 Demangler::DemangleInitRAII::DemangleInitRAII(Demangler &Dem,
497         StringRef MangledName,
498         std::function<SymbolicReferenceResolver_t> TheSymbolicReferenceResolver)
499 // Save the current demangler state so we can restore it.
500   : Dem(Dem),
501     NodeStack(Dem.NodeStack), Substitutions(Dem.Substitutions),
502     NumWords(Dem.NumWords), Text(Dem.Text), Pos(Dem.Pos),
503     SymbolicReferenceResolver(std::move(Dem.SymbolicReferenceResolver))
504 {
505   // Reset the demangler state for a nested job.
506   Dem.NodeStack.init(Dem, 16);
507   Dem.Substitutions.init(Dem, 16);
508   Dem.NumWords = 0;
509   Dem.Text = MangledName;
510   Dem.Pos = 0;
511   Dem.SymbolicReferenceResolver = std::move(TheSymbolicReferenceResolver);
512 }
513 
~DemangleInitRAII()514 Demangler::DemangleInitRAII::~DemangleInitRAII() {
515   // Restore the saved state.
516   Dem.NodeStack = NodeStack;
517   Dem.Substitutions = Substitutions;
518   Dem.NumWords = NumWords;
519   Dem.Text = Text;
520   Dem.Pos = Pos;
521   Dem.SymbolicReferenceResolver = std::move(SymbolicReferenceResolver);
522 }
523 
demangleSymbol(StringRef MangledName,std::function<SymbolicReferenceResolver_t> SymbolicReferenceResolver)524 NodePointer Demangler::demangleSymbol(StringRef MangledName,
525         std::function<SymbolicReferenceResolver_t> SymbolicReferenceResolver) {
526   DemangleInitRAII state(*this, MangledName,
527                          std::move(SymbolicReferenceResolver));
528 
529   // Demangle old-style class and protocol names, which are still used in the
530   // ObjC metadata.
531   if (nextIf("_Tt"))
532     return demangleOldSymbolAsNode(Text, *this);
533 
534   unsigned PrefixLength = getManglingPrefixLength(MangledName);
535   if (PrefixLength == 0)
536     return nullptr;
537 
538   IsOldFunctionTypeMangling = isOldFunctionTypeMangling(MangledName);
539   Pos += PrefixLength;
540 
541   // If any other prefixes are accepted, please update Mangler::verify.
542 
543   if (!parseAndPushNodes())
544     return nullptr;
545 
546   NodePointer topLevel = createNode(Node::Kind::Global);
547 
548   NodePointer Parent = topLevel;
549   while (NodePointer FuncAttr = popNode(isFunctionAttr)) {
550     Parent->addChild(FuncAttr, *this);
551     if (FuncAttr->getKind() == Node::Kind::PartialApplyForwarder ||
552         FuncAttr->getKind() == Node::Kind::PartialApplyObjCForwarder)
553       Parent = FuncAttr;
554   }
555   for (Node *Nd : NodeStack) {
556     switch (Nd->getKind()) {
557       case Node::Kind::Type:
558         Parent->addChild(Nd->getFirstChild(), *this);
559         break;
560       default:
561         Parent->addChild(Nd, *this);
562         break;
563     }
564   }
565   if (topLevel->getNumChildren() == 0)
566     return nullptr;
567 
568   return topLevel;
569 }
570 
demangleType(StringRef MangledName,std::function<SymbolicReferenceResolver_t> SymbolicReferenceResolver)571 NodePointer Demangler::demangleType(StringRef MangledName,
572         std::function<SymbolicReferenceResolver_t> SymbolicReferenceResolver) {
573   DemangleInitRAII state(*this, MangledName,
574                          std::move(SymbolicReferenceResolver));
575 
576   parseAndPushNodes();
577 
578   if (NodePointer Result = popNode())
579     return Result;
580 
581   return createNode(Node::Kind::Suffix, Text);
582 }
583 
parseAndPushNodes()584 bool Demangler::parseAndPushNodes() {
585   int Idx = 0;
586   while (Pos < Text.size()) {
587     NodePointer Node = demangleOperator();
588     if (!Node)
589       return false;
590     pushNode(Node);
591     Idx++;
592   }
593   return true;
594 }
595 
addChild(NodePointer Parent,NodePointer Child)596 NodePointer Demangler::addChild(NodePointer Parent, NodePointer Child) {
597   if (!Parent || !Child)
598     return nullptr;
599   Parent->addChild(Child, *this);
600   return Parent;
601 }
602 
createWithChild(Node::Kind kind,NodePointer Child)603 NodePointer Demangler::createWithChild(Node::Kind kind,
604                                             NodePointer Child) {
605   if (!Child)
606     return nullptr;
607   NodePointer Nd = createNode(kind);
608   Nd->addChild(Child, *this);
609   return Nd;
610 }
611 
createType(NodePointer Child)612 NodePointer Demangler::createType(NodePointer Child) {
613   return createWithChild(Node::Kind::Type, Child);
614 }
615 
createWithChildren(Node::Kind kind,NodePointer Child1,NodePointer Child2)616 NodePointer Demangler::Demangler::createWithChildren(Node::Kind kind,
617                                        NodePointer Child1, NodePointer Child2) {
618   if (!Child1 || !Child2)
619     return nullptr;
620   NodePointer Nd = createNode(kind);
621   Nd->addChild(Child1, *this);
622   Nd->addChild(Child2, *this);
623   return Nd;
624 }
625 
createWithChildren(Node::Kind kind,NodePointer Child1,NodePointer Child2,NodePointer Child3)626 NodePointer Demangler::createWithChildren(Node::Kind kind,
627                                                NodePointer Child1,
628                                                NodePointer Child2,
629                                                NodePointer Child3) {
630   if (!Child1 || !Child2 || !Child3)
631     return nullptr;
632   NodePointer Nd = createNode(kind);
633   Nd->addChild(Child1, *this);
634   Nd->addChild(Child2, *this);
635   Nd->addChild(Child3, *this);
636   return Nd;
637 }
638 
createWithChildren(Node::Kind kind,NodePointer Child1,NodePointer Child2,NodePointer Child3,NodePointer Child4)639 NodePointer Demangler::createWithChildren(Node::Kind kind, NodePointer Child1,
640                                           NodePointer Child2,
641                                           NodePointer Child3,
642                                           NodePointer Child4) {
643   if (!Child1 || !Child2 || !Child3 || !Child4)
644     return nullptr;
645   NodePointer Nd = createNode(kind);
646   Nd->addChild(Child1, *this);
647   Nd->addChild(Child2, *this);
648   Nd->addChild(Child3, *this);
649   Nd->addChild(Child4, *this);
650   return Nd;
651 }
652 
changeKind(NodePointer Node,Node::Kind NewKind)653 NodePointer Demangler::changeKind(NodePointer Node, Node::Kind NewKind) {
654   if (!Node)
655     return nullptr;
656   NodePointer NewNode = nullptr;
657   if (Node->hasText()) {
658     NewNode = createNodeWithAllocatedText(NewKind, Node->getText());
659   } else if (Node->hasIndex()) {
660     NewNode = createNode(NewKind, Node->getIndex());
661   } else {
662     NewNode = createNode(NewKind);
663   }
664   for (NodePointer Child : *Node) {
665     NewNode->addChild(Child, *this);
666   }
667   return NewNode;
668 }
669 
demangleTypeMangling()670 NodePointer Demangler::demangleTypeMangling() {
671   auto Type = popNode(Node::Kind::Type);
672   auto LabelList = popFunctionParamLabels(Type);
673   auto TypeMangling = createNode(Node::Kind::TypeMangling);
674 
675   addChild(TypeMangling, LabelList);
676   TypeMangling = addChild(TypeMangling, Type);
677   return TypeMangling;
678 }
679 
demangleSymbolicReference(unsigned char rawKind)680 NodePointer Demangler::demangleSymbolicReference(unsigned char rawKind) {
681   // The symbolic reference is a 4-byte machine integer encoded in the following
682   // four bytes.
683   if (Pos + 4 > Text.size())
684     return nullptr;
685   const void *at = Text.data() + Pos;
686   int32_t value;
687   memcpy(&value, at, 4);
688   Pos += 4;
689 
690   // Map the encoded kind to a specific kind and directness.
691   SymbolicReferenceKind kind;
692   Directness direct;
693   switch (rawKind) {
694   case 1:
695     kind = SymbolicReferenceKind::Context;
696     direct = Directness::Direct;
697     break;
698   case 2:
699     kind = SymbolicReferenceKind::Context;
700     direct = Directness::Indirect;
701     break;
702   case 9:
703     kind = SymbolicReferenceKind::AccessorFunctionReference;
704     direct = Directness::Direct;
705     break;
706   default:
707     return nullptr;
708   }
709 
710   // Use the resolver, if any, to produce the demangling tree the symbolic
711   // reference represents.
712   NodePointer resolved = nullptr;
713   if (SymbolicReferenceResolver)
714     resolved = SymbolicReferenceResolver(kind, direct, value, at);
715 
716   // With no resolver, or a resolver that failed, refuse to demangle further.
717   if (!resolved)
718     return nullptr;
719 
720   // Types register as substitutions even when symbolically referenced.
721   // OOPS: Except for opaque type references!
722   if (kind == SymbolicReferenceKind::Context &&
723       resolved->getKind() != Node::Kind::OpaqueTypeDescriptorSymbolicReference &&
724       resolved->getKind() != Node::Kind::OpaqueReturnTypeOf)
725     addSubstitution(resolved);
726   return resolved;
727 }
728 
demangleOperator()729 NodePointer Demangler::demangleOperator() {
730 recur:
731   switch (unsigned char c = nextChar()) {
732     case 0xFF:
733       // A 0xFF byte is used as alignment padding for symbolic references
734       // when the platform toolchain has alignment restrictions for the
735       // relocations that form the reference value. It can be skipped.
736       goto recur;
737     case 1: case 2:   case 3:   case 4:   case 5: case 6: case 7: case 8:
738     case 9: case 0xA: case 0xB: case 0xC:
739       return demangleSymbolicReference((unsigned char)c);
740     case 'A': return demangleMultiSubstitutions();
741     case 'B': return demangleBuiltinType();
742     case 'C': return demangleAnyGenericType(Node::Kind::Class);
743     case 'D': return demangleTypeMangling();
744     case 'E': return demangleExtensionContext();
745     case 'F': return demanglePlainFunction();
746     case 'G': return demangleBoundGenericType();
747     case 'H':
748       switch (char c2 = nextChar()) {
749       case 'A': return demangleDependentProtocolConformanceAssociated();
750       case 'C': return demangleConcreteProtocolConformance();
751       case 'D': return demangleDependentProtocolConformanceRoot();
752       case 'I': return demangleDependentProtocolConformanceInherited();
753       case 'P':
754         return createWithChild(
755             Node::Kind::ProtocolConformanceRefInTypeModule, popProtocol());
756       case 'p':
757         return createWithChild(
758             Node::Kind::ProtocolConformanceRefInProtocolModule, popProtocol());
759       default:
760         pushBack();
761         pushBack();
762         return demangleIdentifier();
763       }
764 
765     case 'I': return demangleImplFunctionType();
766     case 'K': return createNode(Node::Kind::ThrowsAnnotation);
767     case 'L': return demangleLocalIdentifier();
768     case 'M': return demangleMetatype();
769     case 'N': return createWithChild(Node::Kind::TypeMetadata,
770                                      popNode(Node::Kind::Type));
771     case 'O': return demangleAnyGenericType(Node::Kind::Enum);
772     case 'P': return demangleAnyGenericType(Node::Kind::Protocol);
773     case 'Q': return demangleArchetype();
774     case 'R': return demangleGenericRequirement();
775     case 'S': return demangleStandardSubstitution();
776     case 'T': return demangleThunkOrSpecialization();
777     case 'V': return demangleAnyGenericType(Node::Kind::Structure);
778     case 'W': return demangleWitness();
779     case 'X': return demangleSpecialType();
780     case 'Z': return createWithChild(Node::Kind::Static, popNode(isEntity));
781     case 'a': return demangleAnyGenericType(Node::Kind::TypeAlias);
782     case 'c': return popFunctionType(Node::Kind::FunctionType);
783     case 'd': return createNode(Node::Kind::VariadicMarker);
784     case 'f': return demangleFunctionEntity();
785     case 'g': return demangleRetroactiveConformance();
786     case 'h': return createType(createWithChild(Node::Kind::Shared,
787                                                 popTypeAndGetChild()));
788     case 'i': return demangleSubscript();
789     case 'l': return demangleGenericSignature(/*hasParamCounts*/ false);
790     case 'm': return createType(createWithChild(Node::Kind::Metatype,
791                                                 popNode(Node::Kind::Type)));
792     case 'n':
793       return createType(
794           createWithChild(Node::Kind::Owned, popTypeAndGetChild()));
795     case 'o': return demangleOperatorIdentifier();
796     case 'p': return demangleProtocolListType();
797     case 'q': return createType(demangleGenericParamIndex());
798     case 'r': return demangleGenericSignature(/*hasParamCounts*/ true);
799     case 's': return createNode(Node::Kind::Module, STDLIB_NAME);
800     case 't': return popTuple();
801     case 'u': return demangleGenericType();
802     case 'v': return demangleVariable();
803     case 'w': return demangleValueWitness();
804     case 'x': return createType(getDependentGenericParamType(0, 0));
805     case 'y': return createNode(Node::Kind::EmptyList);
806     case 'z': return createType(createWithChild(Node::Kind::InOut,
807                                                 popTypeAndGetChild()));
808     case '_': return createNode(Node::Kind::FirstElementMarker);
809     case '.':
810       // IRGen still uses '.<n>' to disambiguate partial apply thunks and
811       // outlined copy functions. We treat such a suffix as "unmangled suffix".
812       pushBack();
813       return createNode(Node::Kind::Suffix, consumeAll());
814     default:
815       pushBack();
816       return demangleIdentifier();
817   }
818 }
819 
demangleNatural()820 int Demangler::demangleNatural() {
821   if (!isDigit(peekChar()))
822     return -1000;
823   int num = 0;
824   while (true) {
825     char c = peekChar();
826     if (!isDigit(c))
827       return num;
828     int newNum = (10 * num) + (c - '0');
829     if (newNum < num)
830       return -1000;
831     num = newNum;
832     nextChar();
833   }
834 }
835 
demangleIndex()836 int Demangler::demangleIndex() {
837   if (nextIf('_'))
838     return 0;
839   int num = demangleNatural();
840   if (num >= 0 && nextIf('_'))
841     return num + 1;
842   return -1000;
843 }
844 
demangleIndexAsNode()845 NodePointer Demangler::demangleIndexAsNode() {
846   int Idx = demangleIndex();
847   if (Idx >= 0)
848     return createNode(Node::Kind::Number, Idx);
849   return nullptr;
850 }
851 
demangleMultiSubstitutions()852 NodePointer Demangler::demangleMultiSubstitutions() {
853   int RepeatCount = -1;
854   while (true) {
855     char c = nextChar();
856     if (c == 0) {
857       // End of text.
858       return nullptr;
859     }
860     if (isLowerLetter(c)) {
861       // It's a substitution with an index < 26.
862       NodePointer Nd = pushMultiSubstitutions(RepeatCount, c - 'a');
863       if (!Nd)
864         return nullptr;
865       pushNode(Nd);
866       RepeatCount = -1;
867       // A lowercase letter indicates that there are more substitutions to
868       // follow.
869       continue;
870     }
871     if (isUpperLetter(c)) {
872       // The last substitution.
873       return pushMultiSubstitutions(RepeatCount, c - 'A');
874     }
875     if (c == '_') {
876       // The previously demangled number is actually not a repeat count but
877       // the large (> 26) index of a substitution. Because it's an index we
878       // have to add 27 and not 26.
879       unsigned Idx = RepeatCount + 27;
880       if (Idx >= Substitutions.size())
881         return nullptr;
882       return Substitutions[Idx];
883     }
884     pushBack();
885     // Not a letter? Then it can only be a natural number which might be the
886     // repeat count or a large (> 26) substitution index.
887     RepeatCount = demangleNatural();
888     if (RepeatCount < 0)
889       return nullptr;
890   }
891 }
892 
pushMultiSubstitutions(int RepeatCount,size_t SubstIdx)893 NodePointer Demangler::pushMultiSubstitutions(int RepeatCount,
894                                               size_t SubstIdx) {
895   if (SubstIdx >= Substitutions.size())
896     return nullptr;
897   if (RepeatCount > SubstitutionMerging::MaxRepeatCount)
898     return nullptr;
899   NodePointer Nd = Substitutions[SubstIdx];
900   while (RepeatCount-- > 1) {
901     pushNode(Nd);
902   }
903   return Nd;
904 }
905 
createSwiftType(Node::Kind typeKind,const char * name)906 NodePointer Demangler::createSwiftType(Node::Kind typeKind, const char *name) {
907   return createType(createWithChildren(typeKind,
908     createNode(Node::Kind::Module, STDLIB_NAME),
909     createNode(Node::Kind::Identifier, name)));
910 }
911 
demangleStandardSubstitution()912 NodePointer Demangler::demangleStandardSubstitution() {
913   switch (char c = nextChar()) {
914     case 'o':
915       return createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
916     case 'C':
917       return createNode(Node::Kind::Module, MANGLING_MODULE_CLANG_IMPORTER);
918     case 'g': {
919       NodePointer OptionalTy =
920         createType(createWithChildren(Node::Kind::BoundGenericEnum,
921           createSwiftType(Node::Kind::Enum, "Optional"),
922           createWithChild(Node::Kind::TypeList, popNode(Node::Kind::Type))));
923       addSubstitution(OptionalTy);
924       return OptionalTy;
925     }
926     default: {
927       pushBack();
928       int RepeatCount = demangleNatural();
929       if (RepeatCount > SubstitutionMerging::MaxRepeatCount)
930         return nullptr;
931       if (NodePointer Nd = createStandardSubstitution(nextChar())) {
932         while (RepeatCount-- > 1) {
933           pushNode(Nd);
934         }
935         return Nd;
936       }
937       return nullptr;
938     }
939   }
940 }
941 
createStandardSubstitution(char Subst)942 NodePointer Demangler::createStandardSubstitution(char Subst) {
943 #define STANDARD_TYPE(KIND, MANGLING, TYPENAME)                   \
944   if (Subst == #MANGLING[0]) {                                    \
945     return createSwiftType(Node::Kind::KIND, #TYPENAME);      \
946   }
947 
948 #include "swift/Demangling/StandardTypesMangling.def"
949   return nullptr;
950 }
951 
demangleIdentifier()952 NodePointer Demangler::demangleIdentifier() {
953   bool hasWordSubsts = false;
954   bool isPunycoded = false;
955   char c = peekChar();
956   if (!isDigit(c))
957     return nullptr;
958   if (c == '0') {
959     nextChar();
960     if (peekChar() == '0') {
961       nextChar();
962       isPunycoded = true;
963     } else {
964       hasWordSubsts = true;
965     }
966   }
967   CharVector Identifier;
968   do {
969     while (hasWordSubsts && isLetter(peekChar())) {
970       char c = nextChar();
971       int WordIdx = 0;
972       if (isLowerLetter(c)) {
973         WordIdx = c - 'a';
974       } else {
975         assert(isUpperLetter(c));
976         WordIdx = c - 'A';
977         hasWordSubsts = false;
978       }
979       if (WordIdx >= NumWords)
980         return nullptr;
981       assert(WordIdx < MaxNumWords);
982       StringRef Slice = Words[WordIdx];
983       Identifier.append(Slice, *this);
984     }
985     if (nextIf('0'))
986       break;
987     int numChars = demangleNatural();
988     if (numChars <= 0)
989       return nullptr;
990     if (isPunycoded)
991       nextIf('_');
992     if (Pos + numChars > Text.size())
993       return nullptr;
994     StringRef Slice = StringRef(Text.data() + Pos, numChars);
995     if (isPunycoded) {
996       std::string PunycodedString;
997       if (!Punycode::decodePunycodeUTF8(Slice, PunycodedString))
998         return nullptr;
999       Identifier.append(StringRef(PunycodedString), *this);
1000     } else {
1001       Identifier.append(Slice, *this);
1002       int wordStartPos = -1;
1003       for (int Idx = 0, End = (int)Slice.size(); Idx <= End; ++Idx) {
1004         char c = (Idx < End ? Slice[Idx] : 0);
1005         if (wordStartPos >= 0 && isWordEnd(c, Slice[Idx - 1])) {
1006           if (Idx - wordStartPos >= 2 && NumWords < MaxNumWords) {
1007             StringRef word(Slice.begin() + wordStartPos, Idx - wordStartPos);
1008             Words[NumWords++] = word;
1009           }
1010           wordStartPos = -1;
1011         }
1012         if (wordStartPos < 0 && isWordStart(c)) {
1013           wordStartPos = Idx;
1014         }
1015       }
1016     }
1017     Pos += numChars;
1018   } while (hasWordSubsts);
1019 
1020   if (Identifier.empty())
1021     return nullptr;
1022   NodePointer Ident = createNode(Node::Kind::Identifier, Identifier);
1023   addSubstitution(Ident);
1024   return Ident;
1025 }
1026 
demangleOperatorIdentifier()1027 NodePointer Demangler::demangleOperatorIdentifier() {
1028   NodePointer Ident = popNode(Node::Kind::Identifier);
1029   if (!Ident)
1030     return nullptr;
1031 
1032   static const char op_char_table[] = "& @/= >    <*!|+?%-~   ^ .";
1033 
1034   CharVector OpStr;
1035   for (signed char c : Ident->getText()) {
1036     if (c < 0) {
1037       // Pass through Unicode characters.
1038       OpStr.push_back(c, *this);
1039       continue;
1040     }
1041     if (!isLowerLetter(c))
1042       return nullptr;
1043     char o = op_char_table[c - 'a'];
1044     if (o == ' ')
1045       return nullptr;
1046     OpStr.push_back(o, *this);
1047   }
1048   switch (nextChar()) {
1049     case 'i': return createNode(Node::Kind::InfixOperator, OpStr);
1050     case 'p': return createNode(Node::Kind::PrefixOperator, OpStr);
1051     case 'P': return createNode(Node::Kind::PostfixOperator, OpStr);
1052     default: return nullptr;
1053   }
1054 }
1055 
demangleLocalIdentifier()1056 NodePointer Demangler::demangleLocalIdentifier() {
1057   if (nextIf('L')) {
1058     NodePointer discriminator = popNode(Node::Kind::Identifier);
1059     NodePointer name = popNode(isDeclName);
1060     return createWithChildren(Node::Kind::PrivateDeclName, discriminator, name);
1061   }
1062   if (nextIf('l')) {
1063     NodePointer discriminator = popNode(Node::Kind::Identifier);
1064     return createWithChild(Node::Kind::PrivateDeclName, discriminator);
1065   }
1066   if ((peekChar() >= 'a' && peekChar() <= 'j') ||
1067       (peekChar() >= 'A' && peekChar() <= 'J')) {
1068     char relatedEntityKind = nextChar();
1069     NodePointer kindNd = createNode(Node::Kind::Identifier,
1070                                     StringRef(&relatedEntityKind, 1));
1071     NodePointer name = popNode();
1072     NodePointer result = createNode(Node::Kind::RelatedEntityDeclName);
1073     addChild(result, kindNd);
1074     return addChild(result, name);
1075   }
1076   NodePointer discriminator = demangleIndexAsNode();
1077   NodePointer name = popNode(isDeclName);
1078   return createWithChildren(Node::Kind::LocalDeclName, discriminator, name);
1079 }
1080 
popModule()1081 NodePointer Demangler::popModule() {
1082   if (NodePointer Ident = popNode(Node::Kind::Identifier))
1083     return changeKind(Ident, Node::Kind::Module);
1084   return popNode(Node::Kind::Module);
1085 }
1086 
popContext()1087 NodePointer Demangler::popContext() {
1088   if (NodePointer Mod = popModule())
1089     return Mod;
1090 
1091   if (NodePointer Ty = popNode(Node::Kind::Type)) {
1092     if (Ty->getNumChildren() != 1)
1093       return nullptr;
1094     NodePointer Child = Ty->getFirstChild();
1095     if (!isContext(Child->getKind()))
1096       return nullptr;
1097     return Child;
1098   }
1099   return popNode(isContext);
1100 }
1101 
popTypeAndGetChild()1102 NodePointer Demangler::popTypeAndGetChild() {
1103   NodePointer Ty = popNode(Node::Kind::Type);
1104   if (!Ty || Ty->getNumChildren() != 1)
1105     return nullptr;
1106   return Ty->getFirstChild();
1107 }
1108 
popTypeAndGetAnyGeneric()1109 NodePointer Demangler::popTypeAndGetAnyGeneric() {
1110   NodePointer Child = popTypeAndGetChild();
1111   if (Child && isAnyGeneric(Child->getKind()))
1112     return Child;
1113   return nullptr;
1114 }
1115 
demangleBuiltinType()1116 NodePointer Demangler::demangleBuiltinType() {
1117   NodePointer Ty = nullptr;
1118   const int maxTypeSize = 4096; // a very conservative upper bound
1119   switch (nextChar()) {
1120     case 'b':
1121       Ty = createNode(Node::Kind::BuiltinTypeName,
1122                                BUILTIN_TYPE_NAME_BRIDGEOBJECT);
1123       break;
1124     case 'B':
1125       Ty = createNode(Node::Kind::BuiltinTypeName,
1126                               BUILTIN_TYPE_NAME_UNSAFEVALUEBUFFER);
1127       break;
1128     case 'f': {
1129       int size = demangleIndex() - 1;
1130       if (size <= 0 || size > maxTypeSize)
1131         return nullptr;
1132       CharVector name;
1133       name.append(BUILTIN_TYPE_NAME_FLOAT, *this);
1134       name.append(size, *this);
1135       Ty = createNode(Node::Kind::BuiltinTypeName, name);
1136       break;
1137     }
1138     case 'i': {
1139       int size = demangleIndex() - 1;
1140       if (size <= 0 || size > maxTypeSize)
1141         return nullptr;
1142       CharVector name;
1143       name.append(BUILTIN_TYPE_NAME_INT, *this);
1144       name.append(size, *this);
1145       Ty = createNode(Node::Kind::BuiltinTypeName, name);
1146       break;
1147     }
1148     case 'I':
1149       Ty = createNode(Node::Kind::BuiltinTypeName,
1150                       BUILTIN_TYPE_NAME_INTLITERAL);
1151       break;
1152     case 'v': {
1153       int elts = demangleIndex() - 1;
1154       if (elts <= 0 || elts > maxTypeSize)
1155         return nullptr;
1156       NodePointer EltType = popTypeAndGetChild();
1157       if (!EltType || EltType->getKind() != Node::Kind::BuiltinTypeName ||
1158           !EltType->getText().startswith(BUILTIN_TYPE_NAME_PREFIX))
1159         return nullptr;
1160       CharVector name;
1161       name.append(BUILTIN_TYPE_NAME_VEC, *this);
1162       name.append(elts, *this);
1163       name.push_back('x', *this);
1164       name.append(EltType->getText().substr(BUILTIN_TYPE_NAME_PREFIX.size()),
1165                   *this);
1166       Ty = createNode(Node::Kind::BuiltinTypeName, name);
1167       break;
1168     }
1169     case 'O':
1170       Ty = createNode(Node::Kind::BuiltinTypeName,
1171                                BUILTIN_TYPE_NAME_UNKNOWNOBJECT);
1172       break;
1173     case 'o':
1174       Ty = createNode(Node::Kind::BuiltinTypeName,
1175                                BUILTIN_TYPE_NAME_NATIVEOBJECT);
1176       break;
1177     case 'p':
1178       Ty = createNode(Node::Kind::BuiltinTypeName,
1179                                BUILTIN_TYPE_NAME_RAWPOINTER);
1180       break;
1181     case 't':
1182       Ty = createNode(Node::Kind::BuiltinTypeName, BUILTIN_TYPE_NAME_SILTOKEN);
1183       break;
1184     case 'w':
1185       Ty = createNode(Node::Kind::BuiltinTypeName,
1186                                BUILTIN_TYPE_NAME_WORD);
1187       break;
1188     default:
1189       return nullptr;
1190   }
1191   return createType(Ty);
1192 }
1193 
demangleAnyGenericType(Node::Kind kind)1194 NodePointer Demangler::demangleAnyGenericType(Node::Kind kind) {
1195   NodePointer Name = popNode(isDeclName);
1196   NodePointer Ctx = popContext();
1197   NodePointer NTy = createType(createWithChildren(kind, Ctx, Name));
1198   addSubstitution(NTy);
1199   return NTy;
1200 }
1201 
demangleExtensionContext()1202 NodePointer Demangler::demangleExtensionContext() {
1203   NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
1204   NodePointer Module = popModule();
1205   NodePointer Type = popTypeAndGetAnyGeneric();
1206   NodePointer Ext = createWithChildren(Node::Kind::Extension, Module, Type);
1207   if (GenSig)
1208     Ext = addChild(Ext, GenSig);
1209   return Ext;
1210 }
1211 
demanglePlainFunction()1212 NodePointer Demangler::demanglePlainFunction() {
1213   NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
1214   NodePointer Type = popFunctionType(Node::Kind::FunctionType);
1215   NodePointer LabelList = popFunctionParamLabels(Type);
1216 
1217   if (GenSig) {
1218     Type = createType(createWithChildren(Node::Kind::DependentGenericType,
1219                                          GenSig, Type));
1220   }
1221 
1222   auto Name = popNode(isDeclName);
1223   auto Ctx = popContext();
1224 
1225   if (LabelList)
1226     return createWithChildren(Node::Kind::Function, Ctx, Name, LabelList, Type);
1227 
1228   return createWithChildren(Node::Kind::Function, Ctx, Name, Type);
1229 }
1230 
popFunctionType(Node::Kind kind)1231 NodePointer Demangler::popFunctionType(Node::Kind kind) {
1232   NodePointer FuncType = createNode(kind);
1233   addChild(FuncType, popNode(Node::Kind::ThrowsAnnotation));
1234 
1235   FuncType = addChild(FuncType, popFunctionParams(Node::Kind::ArgumentTuple));
1236   FuncType = addChild(FuncType, popFunctionParams(Node::Kind::ReturnType));
1237   return createType(FuncType);
1238 }
1239 
popFunctionParams(Node::Kind kind)1240 NodePointer Demangler::popFunctionParams(Node::Kind kind) {
1241   NodePointer ParamsType = nullptr;
1242   if (popNode(Node::Kind::EmptyList)) {
1243     ParamsType = createType(createNode(Node::Kind::Tuple));
1244   } else {
1245     ParamsType = popNode(Node::Kind::Type);
1246   }
1247   return createWithChild(kind, ParamsType);
1248 }
1249 
popFunctionParamLabels(NodePointer Type)1250 NodePointer Demangler::popFunctionParamLabels(NodePointer Type) {
1251   if (!IsOldFunctionTypeMangling && popNode(Node::Kind::EmptyList))
1252     return createNode(Node::Kind::LabelList);
1253 
1254   if (!Type || Type->getKind() != Node::Kind::Type)
1255     return nullptr;
1256 
1257   auto FuncType = Type->getFirstChild();
1258   if (FuncType->getKind() == Node::Kind::DependentGenericType)
1259     FuncType = FuncType->getChild(1)->getFirstChild();
1260 
1261   if (FuncType->getKind() != Node::Kind::FunctionType &&
1262       FuncType->getKind() != Node::Kind::NoEscapeFunctionType)
1263     return nullptr;
1264 
1265   auto ParameterType = FuncType->getFirstChild();
1266   if (ParameterType->getKind() == Node::Kind::ThrowsAnnotation)
1267     ParameterType = FuncType->getChild(1);
1268 
1269   assert(ParameterType->getKind() == Node::Kind::ArgumentTuple);
1270 
1271   NodePointer ParamsType = ParameterType->getFirstChild();
1272   assert(ParamsType->getKind() == Node::Kind::Type);
1273   auto Params = ParamsType->getFirstChild();
1274   unsigned NumParams =
1275     Params->getKind() == Node::Kind::Tuple ? Params->getNumChildren() : 1;
1276 
1277   if (NumParams == 0)
1278     return nullptr;
1279 
1280   auto getChildIf =
1281       [](NodePointer Node,
1282          Node::Kind filterBy) -> std::pair<NodePointer, unsigned> {
1283     for (unsigned i = 0, n = Node->getNumChildren(); i != n; ++i) {
1284       auto Child = Node->getChild(i);
1285       if (Child->getKind() == filterBy)
1286         return {Child, i};
1287     }
1288     return {nullptr, 0};
1289   };
1290 
1291   auto getLabel = [&](NodePointer Params, unsigned Idx) -> NodePointer {
1292     // Old-style function type mangling has labels as part of the argument.
1293     if (IsOldFunctionTypeMangling) {
1294       auto Param = Params->getChild(Idx);
1295       auto Label = getChildIf(Param, Node::Kind::TupleElementName);
1296 
1297       if (Label.first) {
1298         Param->removeChildAt(Label.second);
1299         return createNodeWithAllocatedText(Node::Kind::Identifier,
1300                                            Label.first->getText());
1301       }
1302 
1303       return createNode(Node::Kind::FirstElementMarker);
1304     }
1305 
1306     return popNode();
1307   };
1308 
1309   auto LabelList = createNode(Node::Kind::LabelList);
1310   auto Tuple = ParameterType->getFirstChild()->getFirstChild();
1311 
1312   if (IsOldFunctionTypeMangling &&
1313       (!Tuple || Tuple->getKind() != Node::Kind::Tuple))
1314     return LabelList;
1315 
1316   bool hasLabels = false;
1317   for (unsigned i = 0; i != NumParams; ++i) {
1318     auto Label = getLabel(Tuple, i);
1319 
1320     if (!Label)
1321       return nullptr;
1322 
1323     if (Label->getKind() != Node::Kind::Identifier &&
1324         Label->getKind() != Node::Kind::FirstElementMarker)
1325       return nullptr;
1326 
1327     LabelList->addChild(Label, *this);
1328     hasLabels |= Label->getKind() != Node::Kind::FirstElementMarker;
1329   }
1330 
1331   // Old style label mangling can produce label list without
1332   // actual labels, we need to support that case specifically.
1333   if (!hasLabels)
1334     return createNode(Node::Kind::LabelList);
1335 
1336   if (!IsOldFunctionTypeMangling)
1337     LabelList->reverseChildren();
1338 
1339   return LabelList;
1340 }
1341 
popTuple()1342 NodePointer Demangler::popTuple() {
1343   NodePointer Root = createNode(Node::Kind::Tuple);
1344 
1345   if (!popNode(Node::Kind::EmptyList)) {
1346     bool firstElem = false;
1347     do {
1348       firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
1349       NodePointer TupleElmt = createNode(Node::Kind::TupleElement);
1350       addChild(TupleElmt, popNode(Node::Kind::VariadicMarker));
1351       if (NodePointer Ident = popNode(Node::Kind::Identifier)) {
1352         TupleElmt->addChild(createNodeWithAllocatedText(
1353                               Node::Kind::TupleElementName, Ident->getText()),
1354                             *this);
1355       }
1356       NodePointer Ty = popNode(Node::Kind::Type);
1357       if (!Ty)
1358         return nullptr;
1359       TupleElmt->addChild(Ty, *this);
1360       Root->addChild(TupleElmt, *this);
1361     } while (!firstElem);
1362 
1363     Root->reverseChildren();
1364   }
1365   return createType(Root);
1366 }
1367 
popTypeList()1368 NodePointer Demangler::popTypeList() {
1369   NodePointer Root = createNode(Node::Kind::TypeList);
1370 
1371   if (!popNode(Node::Kind::EmptyList)) {
1372     bool firstElem = false;
1373     do {
1374       firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
1375       NodePointer Ty = popNode(Node::Kind::Type);
1376       if (!Ty)
1377         return nullptr;
1378       Root->addChild(Ty, *this);
1379     } while (!firstElem);
1380 
1381     Root->reverseChildren();
1382   }
1383   return Root;
1384 }
1385 
popProtocol()1386 NodePointer Demangler::popProtocol() {
1387   if (NodePointer Type = popNode(Node::Kind::Type)) {
1388     if (Type->getNumChildren() < 1)
1389       return nullptr;
1390 
1391     if (!isProtocolNode(Type))
1392       return nullptr;
1393 
1394     return Type;
1395   }
1396 
1397   if (NodePointer SymbolicRef = popNode(Node::Kind::ProtocolSymbolicReference)){
1398     return SymbolicRef;
1399   }
1400 
1401   NodePointer Name = popNode(isDeclName);
1402   NodePointer Ctx = popContext();
1403   NodePointer Proto = createWithChildren(Node::Kind::Protocol, Ctx, Name);
1404   return createType(Proto);
1405 }
1406 
popAnyProtocolConformanceList()1407 NodePointer Demangler::popAnyProtocolConformanceList() {
1408   NodePointer conformanceList
1409     = createNode(Node::Kind::AnyProtocolConformanceList);
1410   if (!popNode(Node::Kind::EmptyList)) {
1411     bool firstElem = false;
1412     do {
1413       firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
1414       NodePointer anyConformance = popAnyProtocolConformance();
1415       if (!anyConformance)
1416         return nullptr;
1417       conformanceList->addChild(anyConformance, *this);
1418     } while (!firstElem);
1419 
1420     conformanceList->reverseChildren();
1421   }
1422   return conformanceList;
1423 }
1424 
popAnyProtocolConformance()1425 NodePointer Demangler::popAnyProtocolConformance() {
1426   return popNode([](Node::Kind kind) {
1427     switch (kind) {
1428     case Node::Kind::ConcreteProtocolConformance:
1429     case Node::Kind::DependentProtocolConformanceRoot:
1430     case Node::Kind::DependentProtocolConformanceInherited:
1431     case Node::Kind::DependentProtocolConformanceAssociated:
1432       return true;
1433 
1434     default:
1435       return false;
1436     }
1437   });
1438 }
1439 
demangleRetroactiveProtocolConformanceRef()1440 NodePointer Demangler::demangleRetroactiveProtocolConformanceRef() {
1441   NodePointer module = popModule();
1442   NodePointer proto = popProtocol();
1443   auto protocolConformanceRef =
1444       createWithChildren(Node::Kind::ProtocolConformanceRefInOtherModule,
1445                          proto, module);
1446   return protocolConformanceRef;
1447 }
1448 
demangleConcreteProtocolConformance()1449 NodePointer Demangler::demangleConcreteProtocolConformance() {
1450   NodePointer conditionalConformanceList = popAnyProtocolConformanceList();
1451 
1452   NodePointer conformanceRef =
1453       popNode(Node::Kind::ProtocolConformanceRefInTypeModule);
1454   if (!conformanceRef) {
1455     conformanceRef =
1456         popNode(Node::Kind::ProtocolConformanceRefInProtocolModule);
1457   }
1458   if (!conformanceRef)
1459     conformanceRef = demangleRetroactiveProtocolConformanceRef();
1460 
1461   NodePointer type = popNode(Node::Kind::Type);
1462   return createWithChildren(Node::Kind::ConcreteProtocolConformance,
1463                             type, conformanceRef, conditionalConformanceList);
1464 }
1465 
popDependentProtocolConformance()1466 NodePointer Demangler::popDependentProtocolConformance() {
1467   return popNode([](Node::Kind kind) {
1468     switch (kind) {
1469     case Node::Kind::DependentProtocolConformanceRoot:
1470     case Node::Kind::DependentProtocolConformanceInherited:
1471     case Node::Kind::DependentProtocolConformanceAssociated:
1472       return true;
1473 
1474     default:
1475       return false;
1476     }
1477   });
1478 }
1479 
demangleDependentProtocolConformanceRoot()1480 NodePointer Demangler::demangleDependentProtocolConformanceRoot() {
1481   NodePointer index = demangleDependentConformanceIndex();
1482   NodePointer protocol = popProtocol();
1483   NodePointer dependentType = popNode(Node::Kind::Type);
1484   return createWithChildren(Node::Kind::DependentProtocolConformanceRoot,
1485                             dependentType, protocol, index);
1486 }
1487 
demangleDependentProtocolConformanceInherited()1488 NodePointer Demangler::demangleDependentProtocolConformanceInherited() {
1489   NodePointer index = demangleDependentConformanceIndex();
1490   NodePointer protocol = popProtocol();
1491   NodePointer nested = popDependentProtocolConformance();
1492   return createWithChildren(Node::Kind::DependentProtocolConformanceInherited,
1493                             nested, protocol, index);
1494 }
1495 
popDependentAssociatedConformance()1496 NodePointer Demangler::popDependentAssociatedConformance() {
1497   NodePointer protocol = popProtocol();
1498   NodePointer dependentType = popNode(Node::Kind::Type);
1499   return createWithChildren(Node::Kind::DependentAssociatedConformance,
1500                             dependentType, protocol);
1501 }
1502 
demangleDependentProtocolConformanceAssociated()1503 NodePointer Demangler::demangleDependentProtocolConformanceAssociated() {
1504   NodePointer index = demangleDependentConformanceIndex();
1505   NodePointer associatedConformance = popDependentAssociatedConformance();
1506   NodePointer nested = popDependentProtocolConformance();
1507   return createWithChildren(Node::Kind::DependentProtocolConformanceAssociated,
1508                             nested, associatedConformance, index);
1509 }
1510 
demangleDependentConformanceIndex()1511 NodePointer Demangler::demangleDependentConformanceIndex() {
1512   int index = demangleIndex();
1513   // index < 0 indicates a demangling error.
1514   // index == 0 is ill-formed by the (originally buggy) use of this production.
1515   if (index <= 0) return nullptr;
1516 
1517   // index == 1 indicates an unknown index.
1518   if (index == 1) return createNode(Node::Kind::UnknownIndex);
1519 
1520   // Remove the index adjustment.
1521   return createNode(Node::Kind::Index, unsigned(index) - 2);
1522 }
1523 
demangleRetroactiveConformance()1524 NodePointer Demangler::demangleRetroactiveConformance() {
1525   NodePointer index = demangleIndexAsNode();
1526   NodePointer conformance = popAnyProtocolConformance();
1527   return createWithChildren(Node::Kind::RetroactiveConformance, index, conformance);
1528 }
1529 
demangleBoundGenerics(Vector<NodePointer> & TypeListList,NodePointer & RetroactiveConformances)1530 bool Demangler::demangleBoundGenerics(Vector<NodePointer> &TypeListList,
1531                                       NodePointer &RetroactiveConformances) {
1532   RetroactiveConformances = nullptr;
1533   while (auto RetroactiveConformance =
1534          popNode(Node::Kind::RetroactiveConformance)) {
1535     if (!RetroactiveConformances)
1536       RetroactiveConformances = createNode(Node::Kind::TypeList);
1537     RetroactiveConformances->addChild(RetroactiveConformance, *this);
1538   }
1539   if (RetroactiveConformances)
1540     RetroactiveConformances->reverseChildren();
1541 
1542   for (;;) {
1543     NodePointer TList = createNode(Node::Kind::TypeList);
1544     TypeListList.push_back(TList, *this);
1545     while (NodePointer Ty = popNode(Node::Kind::Type)) {
1546       TList->addChild(Ty, *this);
1547     }
1548     TList->reverseChildren();
1549 
1550     if (popNode(Node::Kind::EmptyList))
1551       break;
1552     if (!popNode(Node::Kind::FirstElementMarker))
1553       return false;
1554   }
1555   return true;
1556 }
1557 
demangleBoundGenericType()1558 NodePointer Demangler::demangleBoundGenericType() {
1559   NodePointer RetroactiveConformances;
1560   Vector<NodePointer> TypeListList(*this, 4);
1561 
1562   if (!demangleBoundGenerics(TypeListList, RetroactiveConformances))
1563     return nullptr;
1564 
1565   NodePointer Nominal = popTypeAndGetAnyGeneric();
1566   if (!Nominal)
1567     return nullptr;
1568   NodePointer BoundNode = demangleBoundGenericArgs(Nominal, TypeListList, 0);
1569   if (!BoundNode)
1570     return nullptr;
1571   addChild(BoundNode, RetroactiveConformances);
1572   NodePointer NTy = createType(BoundNode);
1573   addSubstitution(NTy);
1574   return NTy;
1575 }
1576 
nodeConsumesGenericArgs(Node * node)1577 bool Demangle::nodeConsumesGenericArgs(Node *node) {
1578   switch (node->getKind()) {
1579     case Node::Kind::Variable:
1580     case Node::Kind::Subscript:
1581     case Node::Kind::ImplicitClosure:
1582     case Node::Kind::ExplicitClosure:
1583     case Node::Kind::DefaultArgumentInitializer:
1584     case Node::Kind::Initializer:
1585     case Node::Kind::PropertyWrapperBackingInitializer:
1586       return false;
1587     default:
1588       return true;
1589   }
1590 }
1591 
demangleBoundGenericArgs(NodePointer Nominal,const Vector<NodePointer> & TypeLists,size_t TypeListIdx)1592 NodePointer Demangler::demangleBoundGenericArgs(NodePointer Nominal,
1593                                     const Vector<NodePointer> &TypeLists,
1594                                     size_t TypeListIdx) {
1595   // TODO: This would be a lot easier if we represented bound generic args
1596   // flatly in the demangling tree, since that's how they're mangled and also
1597   // how the runtime generally wants to consume them.
1598 
1599   if (!Nominal)
1600     return nullptr;
1601 
1602   if (TypeListIdx >= TypeLists.size())
1603     return nullptr;
1604 
1605   // Associate a context symbolic reference with all remaining generic
1606   // arguments.
1607   if (Nominal->getKind() == Node::Kind::TypeSymbolicReference
1608       || Nominal->getKind() == Node::Kind::ProtocolSymbolicReference) {
1609     auto remainingTypeList = createNode(Node::Kind::TypeList);
1610     for (unsigned i = TypeLists.size() - 1;
1611          i >= TypeListIdx && i < TypeLists.size();
1612          --i) {
1613       auto list = TypeLists[i];
1614       for (auto child : *list) {
1615         remainingTypeList->addChild(child, *this);
1616       }
1617     }
1618     return createWithChildren(Node::Kind::BoundGenericOtherNominalType,
1619                               createType(Nominal), remainingTypeList);
1620   }
1621 
1622   // Generic arguments for the outermost type come first.
1623   if (Nominal->getNumChildren() == 0)
1624     return nullptr;
1625   NodePointer Context = Nominal->getFirstChild();
1626 
1627   bool consumesGenericArgs = nodeConsumesGenericArgs(Nominal);
1628 
1629   NodePointer args = TypeLists[TypeListIdx];
1630 
1631   if (consumesGenericArgs)
1632     ++TypeListIdx;
1633 
1634   if (TypeListIdx < TypeLists.size()) {
1635     NodePointer BoundParent = nullptr;
1636     if (Context->getKind() == Node::Kind::Extension) {
1637       BoundParent = demangleBoundGenericArgs(Context->getChild(1), TypeLists,
1638                                              TypeListIdx);
1639       BoundParent = createWithChildren(Node::Kind::Extension,
1640                                        Context->getFirstChild(),
1641                                        BoundParent);
1642       if (Context->getNumChildren() == 3) {
1643         // Add the generic signature of the extension context.
1644         addChild(BoundParent, Context->getChild(2));
1645       }
1646     } else {
1647       BoundParent = demangleBoundGenericArgs(Context, TypeLists, TypeListIdx);
1648     }
1649     // Rebuild this type with the new parent type, which may have
1650     // had its generic arguments applied.
1651     NodePointer NewNominal = createWithChild(Nominal->getKind(), BoundParent);
1652     if (!NewNominal)
1653       return nullptr;
1654 
1655     // Append remaining children of the origin nominal.
1656     for (unsigned Idx = 1; Idx < Nominal->getNumChildren(); ++Idx) {
1657       addChild(NewNominal, Nominal->getChild(Idx));
1658     }
1659     Nominal = NewNominal;
1660   }
1661   if (!consumesGenericArgs)
1662     return Nominal;
1663 
1664   // If there were no arguments at this level there is nothing left
1665   // to do.
1666   if (args->getNumChildren() == 0)
1667     return Nominal;
1668 
1669   Node::Kind kind;
1670   switch (Nominal->getKind()) {
1671   case Node::Kind::Class:
1672     kind = Node::Kind::BoundGenericClass;
1673     break;
1674   case Node::Kind::Structure:
1675     kind = Node::Kind::BoundGenericStructure;
1676     break;
1677   case Node::Kind::Enum:
1678     kind = Node::Kind::BoundGenericEnum;
1679     break;
1680   case Node::Kind::Protocol:
1681     kind = Node::Kind::BoundGenericProtocol;
1682     break;
1683   case Node::Kind::OtherNominalType:
1684     kind = Node::Kind::BoundGenericOtherNominalType;
1685     break;
1686   case Node::Kind::TypeAlias:
1687     kind = Node::Kind::BoundGenericTypeAlias;
1688     break;
1689   case Node::Kind::Function:
1690   case Node::Kind::Constructor:
1691     // Well, not really a nominal type.
1692     return createWithChildren(Node::Kind::BoundGenericFunction, Nominal, args);
1693   default:
1694     return nullptr;
1695   }
1696   return createWithChildren(kind, createType(Nominal), args);
1697 }
1698 
demangleImplParamConvention(Node::Kind ConvKind)1699 NodePointer Demangler::demangleImplParamConvention(Node::Kind ConvKind) {
1700   const char *attr = nullptr;
1701   switch (nextChar()) {
1702     case 'i': attr = "@in"; break;
1703     case 'c':
1704       attr = "@in_constant";
1705       break;
1706     case 'l': attr = "@inout"; break;
1707     case 'b': attr = "@inout_aliasable"; break;
1708     case 'n': attr = "@in_guaranteed"; break;
1709     case 'x': attr = "@owned"; break;
1710     case 'g': attr = "@guaranteed"; break;
1711     case 'e': attr = "@deallocating"; break;
1712     case 'y': attr = "@unowned"; break;
1713     default:
1714       pushBack();
1715       return nullptr;
1716   }
1717   return createWithChild(ConvKind,
1718                          createNode(Node::Kind::ImplConvention, attr));
1719 }
1720 
demangleImplResultConvention(Node::Kind ConvKind)1721 NodePointer Demangler::demangleImplResultConvention(Node::Kind ConvKind) {
1722   const char *attr = nullptr;
1723   switch (nextChar()) {
1724     case 'r': attr = "@out"; break;
1725     case 'o': attr = "@owned"; break;
1726     case 'd': attr = "@unowned"; break;
1727     case 'u': attr = "@unowned_inner_pointer"; break;
1728     case 'a': attr = "@autoreleased"; break;
1729     default:
1730       pushBack();
1731       return nullptr;
1732   }
1733   return createWithChild(ConvKind,
1734                          createNode(Node::Kind::ImplConvention, attr));
1735 }
1736 
demangleImplFunctionType()1737 NodePointer Demangler::demangleImplFunctionType() {
1738   NodePointer type = createNode(Node::Kind::ImplFunctionType);
1739 
1740   if (nextIf('s')) {
1741     Vector<NodePointer> Substitutions;
1742     NodePointer SubstitutionRetroConformances;
1743     if (!demangleBoundGenerics(Substitutions, SubstitutionRetroConformances))
1744       return nullptr;
1745 
1746     NodePointer sig = popNode(Node::Kind::DependentGenericSignature);
1747     if (!sig)
1748       return nullptr;
1749 
1750     auto subsNode = createNode(Node::Kind::ImplPatternSubstitutions);
1751     subsNode->addChild(sig, *this);
1752     assert(Substitutions.size() == 1);
1753     subsNode->addChild(Substitutions[0], *this);
1754     if (SubstitutionRetroConformances)
1755       subsNode->addChild(SubstitutionRetroConformances, *this);
1756     type->addChild(subsNode, *this);
1757   }
1758 
1759   if (nextIf('I')) {
1760     Vector<NodePointer> Substitutions;
1761     NodePointer SubstitutionRetroConformances;
1762     if (!demangleBoundGenerics(Substitutions, SubstitutionRetroConformances))
1763       return nullptr;
1764 
1765     auto subsNode = createNode(Node::Kind::ImplInvocationSubstitutions);
1766     assert(Substitutions.size() == 1);
1767     subsNode->addChild(Substitutions[0], *this);
1768     if (SubstitutionRetroConformances)
1769       subsNode->addChild(SubstitutionRetroConformances, *this);
1770     type->addChild(subsNode, *this);
1771   }
1772 
1773   NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
1774   if (GenSig && nextIf('P'))
1775     GenSig = changeKind(GenSig, Node::Kind::DependentPseudogenericSignature);
1776 
1777   if (nextIf('e'))
1778     type->addChild(createNode(Node::Kind::ImplEscaping), *this);
1779 
1780   if (nextIf('d'))
1781     type->addChild(createNode(Node::Kind::ImplDifferentiable), *this);
1782   if (nextIf('l'))
1783     type->addChild(createNode(Node::Kind::ImplLinear), *this);
1784 
1785   const char *CAttr = nullptr;
1786   switch (nextChar()) {
1787     case 'y': CAttr = "@callee_unowned"; break;
1788     case 'g': CAttr = "@callee_guaranteed"; break;
1789     case 'x': CAttr = "@callee_owned"; break;
1790     case 't': CAttr = "@convention(thin)"; break;
1791     default: return nullptr;
1792   }
1793   type->addChild(createNode(Node::Kind::ImplConvention, CAttr), *this);
1794 
1795   const char *FAttr = nullptr;
1796   switch (nextChar()) {
1797     case 'B': FAttr = "@convention(block)"; break;
1798     case 'C': FAttr = "@convention(c)"; break;
1799     case 'M': FAttr = "@convention(method)"; break;
1800     case 'O': FAttr = "@convention(objc_method)"; break;
1801     case 'K': FAttr = "@convention(closure)"; break;
1802     case 'W': FAttr = "@convention(witness_method)"; break;
1803     default:
1804       pushBack();
1805       break;
1806   }
1807   if (FAttr)
1808     type->addChild(createNode(Node::Kind::ImplFunctionAttribute, FAttr), *this);
1809 
1810   const char *CoroAttr = nullptr;
1811   if (nextIf('A'))
1812     CoroAttr = "@yield_once";
1813   else if (nextIf('G'))
1814     CoroAttr = "@yield_many";
1815   if (CoroAttr)
1816     type->addChild(createNode(Node::Kind::ImplFunctionAttribute, CoroAttr), *this);
1817 
1818   addChild(type, GenSig);
1819 
1820   int NumTypesToAdd = 0;
1821   while (NodePointer Param =
1822            demangleImplParamConvention(Node::Kind::ImplParameter)) {
1823     type = addChild(type, Param);
1824     NumTypesToAdd++;
1825   }
1826   while (NodePointer Result = demangleImplResultConvention(
1827                                                     Node::Kind::ImplResult)) {
1828     type = addChild(type, Result);
1829     NumTypesToAdd++;
1830   }
1831   while (nextIf('Y')) {
1832     NodePointer YieldResult =
1833       demangleImplParamConvention(Node::Kind::ImplYield);
1834     if (!YieldResult)
1835       return nullptr;
1836     type = addChild(type, YieldResult);
1837     NumTypesToAdd++;
1838   }
1839   if (nextIf('z')) {
1840     NodePointer ErrorResult = demangleImplResultConvention(
1841                                                   Node::Kind::ImplErrorResult);
1842     if (!ErrorResult)
1843       return nullptr;
1844     type = addChild(type, ErrorResult);
1845     NumTypesToAdd++;
1846   }
1847   if (!nextIf('_'))
1848     return nullptr;
1849 
1850   for (int Idx = 0; Idx < NumTypesToAdd; ++Idx) {
1851     NodePointer ConvTy = popNode(Node::Kind::Type);
1852     if (!ConvTy)
1853       return nullptr;
1854     type->getChild(type->getNumChildren() - Idx - 1)->addChild(ConvTy, *this);
1855   }
1856 
1857   return createType(type);
1858 }
1859 
demangleMetatype()1860 NodePointer Demangler::demangleMetatype() {
1861   switch (nextChar()) {
1862     case 'a':
1863       return createWithPoppedType(Node::Kind::TypeMetadataAccessFunction);
1864     case 'A':
1865       return createWithChild(Node::Kind::ReflectionMetadataAssocTypeDescriptor,
1866                              popProtocolConformance());
1867     case 'B':
1868       return createWithChild(Node::Kind::ReflectionMetadataBuiltinDescriptor,
1869                                popNode(Node::Kind::Type));
1870     case 'c':
1871       return createWithChild(Node::Kind::ProtocolConformanceDescriptor,
1872                              popProtocolConformance());
1873     case 'C': {
1874       NodePointer Ty = popNode(Node::Kind::Type);
1875       if (!Ty || !isAnyGeneric(Ty->getChild(0)->getKind()))
1876         return nullptr;
1877       return createWithChild(Node::Kind::ReflectionMetadataSuperclassDescriptor,
1878                              Ty->getChild(0));
1879     }
1880     case 'D':
1881       return createWithPoppedType(Node::Kind::TypeMetadataDemanglingCache);
1882     case 'f':
1883       return createWithPoppedType(Node::Kind::FullTypeMetadata);
1884     case 'F':
1885       return createWithChild(Node::Kind::ReflectionMetadataFieldDescriptor,
1886                              popNode(Node::Kind::Type));
1887     case 'g':
1888       return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessor,
1889                              popNode());
1890     case 'h':
1891       return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessorImpl,
1892                              popNode());
1893     case 'i':
1894       return createWithPoppedType(Node::Kind::TypeMetadataInstantiationFunction);
1895     case 'I':
1896       return createWithPoppedType(Node::Kind::TypeMetadataInstantiationCache);
1897     case 'j':
1898       return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessorKey,
1899                              popNode());
1900     case 'K':
1901       return createWithChild(Node::Kind::MetadataInstantiationCache,
1902                              popNode());
1903     case 'k':
1904       return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessorVar,
1905                              popNode());
1906     case 'l':
1907       return createWithPoppedType(
1908                           Node::Kind::TypeMetadataSingletonInitializationCache);
1909     case 'L':
1910       return createWithPoppedType(Node::Kind::TypeMetadataLazyCache);
1911     case 'm':
1912       return createWithPoppedType(Node::Kind::Metaclass);
1913     case 'n':
1914       return createWithPoppedType(Node::Kind::NominalTypeDescriptor);
1915     case 'o':
1916       return createWithPoppedType(Node::Kind::ClassMetadataBaseOffset);
1917     case 'p':
1918       return createWithChild(Node::Kind::ProtocolDescriptor, popProtocol());
1919     case 'P':
1920       return createWithPoppedType(Node::Kind::GenericTypeMetadataPattern);
1921     case 'Q':
1922       return createWithChild(Node::Kind::OpaqueTypeDescriptor, popNode());
1923     case 'r':
1924       return createWithPoppedType(Node::Kind::TypeMetadataCompletionFunction);
1925     case 's':
1926       return createWithPoppedType(Node::Kind::ObjCResilientClassStub);
1927     case 'S':
1928       return createWithChild(Node::Kind::ProtocolSelfConformanceDescriptor,
1929                              popProtocol());
1930     case 't':
1931       return createWithPoppedType(Node::Kind::FullObjCResilientClassStub);
1932     case 'u':
1933       return createWithPoppedType(Node::Kind::MethodLookupFunction);
1934     case 'U':
1935       return createWithPoppedType(Node::Kind::ObjCMetadataUpdateFunction);
1936     case 'V':
1937       return createWithChild(Node::Kind::PropertyDescriptor,
1938                              popNode(isEntity));
1939     case 'X':
1940       return demanglePrivateContextDescriptor();
1941     default:
1942       return nullptr;
1943   }
1944 }
1945 
demanglePrivateContextDescriptor()1946 NodePointer Demangler::demanglePrivateContextDescriptor() {
1947   switch (nextChar()) {
1948   case 'E': {
1949     auto Extension = popContext();
1950     if (!Extension)
1951       return nullptr;
1952     return createWithChild(Node::Kind::ExtensionDescriptor, Extension);
1953   }
1954   case 'M': {
1955     auto Module = popModule();
1956     if (!Module)
1957       return nullptr;
1958     return createWithChild(Node::Kind::ModuleDescriptor, Module);
1959   }
1960   case 'Y': {
1961     auto Discriminator = popNode();
1962     if (!Discriminator)
1963       return nullptr;
1964     auto Context = popContext();
1965     if (!Context)
1966       return nullptr;
1967 
1968     auto node = createNode(Node::Kind::AnonymousDescriptor);
1969     node->addChild(Context, *this);
1970     node->addChild(Discriminator, *this);
1971     return node;
1972   }
1973   case 'X': {
1974     auto Context = popContext();
1975     if (!Context)
1976       return nullptr;
1977     return createWithChild(Node::Kind::AnonymousDescriptor, Context);
1978   }
1979   case 'A': {
1980     auto path = popAssocTypePath();
1981     if (!path)
1982       return nullptr;
1983     auto base = popNode(Node::Kind::Type);
1984     if (!base)
1985       return nullptr;
1986     return createWithChildren(Node::Kind::AssociatedTypeGenericParamRef,
1987                               base, path);
1988   }
1989   default:
1990     return nullptr;
1991   }
1992 }
1993 
demangleArchetype()1994 NodePointer Demangler::demangleArchetype() {
1995   switch (nextChar()) {
1996   case 'a': {
1997     NodePointer Ident = popNode(Node::Kind::Identifier);
1998     NodePointer ArcheTy = popTypeAndGetChild();
1999     NodePointer AssocTy = createType(
2000           createWithChildren(Node::Kind::AssociatedTypeRef, ArcheTy, Ident));
2001     addSubstitution(AssocTy);
2002     return AssocTy;
2003   }
2004   case 'O': {
2005     auto definingContext = popContext();
2006     return createWithChild(Node::Kind::OpaqueReturnTypeOf, definingContext);
2007   }
2008   case 'o': {
2009     auto index = demangleIndex();
2010     Vector<NodePointer> boundGenericArgs;
2011     NodePointer retroactiveConformances;
2012     if (!demangleBoundGenerics(boundGenericArgs, retroactiveConformances))
2013       return nullptr;
2014     auto Name = popNode();
2015     if (!Name)
2016       return nullptr;
2017     auto opaque = createWithChildren(Node::Kind::OpaqueType, Name,
2018                                    createNode(Node::Kind::Index, index));
2019     auto boundGenerics = createNode(Node::Kind::TypeList);
2020     for (unsigned i = boundGenericArgs.size(); i-- > 0;)
2021       boundGenerics->addChild(boundGenericArgs[i], *this);
2022     opaque->addChild(boundGenerics, *this);
2023     if (retroactiveConformances)
2024       opaque->addChild(retroactiveConformances, *this);
2025 
2026     auto opaqueTy = createType(opaque);
2027     addSubstitution(opaqueTy);
2028     return opaqueTy;
2029   }
2030   case 'r': {
2031     return createType(createNode(Node::Kind::OpaqueReturnType));
2032   }
2033 
2034   case 'x': {
2035     NodePointer T = demangleAssociatedTypeSimple(nullptr);
2036     addSubstitution(T);
2037     return T;
2038   }
2039 
2040   case 'X': {
2041     NodePointer T = demangleAssociatedTypeCompound(nullptr);
2042     addSubstitution(T);
2043     return T;
2044   }
2045 
2046   case 'y': {
2047     NodePointer T = demangleAssociatedTypeSimple(demangleGenericParamIndex());
2048     addSubstitution(T);
2049     return T;
2050   }
2051   case 'Y': {
2052     NodePointer T = demangleAssociatedTypeCompound(
2053                                                  demangleGenericParamIndex());
2054     addSubstitution(T);
2055     return T;
2056   }
2057 
2058   case 'z': {
2059     NodePointer T = demangleAssociatedTypeSimple(
2060                                           getDependentGenericParamType(0, 0));
2061     addSubstitution(T);
2062     return T;
2063   }
2064   case 'Z': {
2065     NodePointer T = demangleAssociatedTypeCompound(
2066                                           getDependentGenericParamType(0, 0));
2067     addSubstitution(T);
2068     return T;
2069   }
2070   default:
2071     return nullptr;
2072   }
2073 }
2074 
demangleAssociatedTypeSimple(NodePointer Base)2075 NodePointer Demangler::demangleAssociatedTypeSimple(NodePointer Base) {
2076   NodePointer ATName = popAssocTypeName();
2077   NodePointer BaseTy;
2078   if (Base) {
2079     BaseTy = createType(Base);
2080   } else {
2081     BaseTy = popNode(Node::Kind::Type);
2082   }
2083   return createType(createWithChildren(Node::Kind::DependentMemberType,
2084                                        BaseTy, ATName));
2085 }
2086 
demangleAssociatedTypeCompound(NodePointer Base)2087 NodePointer Demangler::demangleAssociatedTypeCompound(NodePointer Base) {
2088   Vector<NodePointer> AssocTyNames(*this, 4);
2089   bool firstElem = false;
2090   do {
2091     firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
2092     NodePointer AssocTyName = popAssocTypeName();
2093     if (!AssocTyName)
2094       return nullptr;
2095     AssocTyNames.push_back(AssocTyName, *this);
2096   } while (!firstElem);
2097 
2098   NodePointer BaseTy;
2099   if (Base)
2100     BaseTy = createType(Base);
2101   else
2102     BaseTy = popNode(Node::Kind::Type);
2103 
2104   while (NodePointer AssocTy = AssocTyNames.pop_back_val()) {
2105     NodePointer depTy = createNode(Node::Kind::DependentMemberType);
2106     depTy = addChild(depTy, BaseTy);
2107     BaseTy = createType(addChild(depTy, AssocTy));
2108   }
2109   return BaseTy;
2110 }
2111 
popAssocTypeName()2112 NodePointer Demangler::popAssocTypeName() {
2113   NodePointer Proto = popNode(Node::Kind::Type);
2114   if (Proto && !isProtocolNode(Proto))
2115     return nullptr;
2116 
2117   // If we haven't seen a protocol, check for a symbolic reference.
2118   if (!Proto)
2119     Proto = popNode(Node::Kind::ProtocolSymbolicReference);
2120 
2121   NodePointer Id = popNode(Node::Kind::Identifier);
2122   NodePointer AssocTy = createWithChild(Node::Kind::DependentAssociatedTypeRef, Id);
2123   addChild(AssocTy, Proto);
2124   return AssocTy;
2125 }
2126 
popAssocTypePath()2127 NodePointer Demangler::popAssocTypePath() {
2128   NodePointer AssocTypePath = createNode(Node::Kind::AssocTypePath);
2129   bool firstElem = false;
2130   do {
2131     firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
2132     NodePointer AssocTy = popAssocTypeName();
2133     if (!AssocTy)
2134       return nullptr;
2135     AssocTypePath->addChild(AssocTy, *this);
2136   } while (!firstElem);
2137   AssocTypePath->reverseChildren();
2138   return AssocTypePath;
2139 }
2140 
getDependentGenericParamType(int depth,int index)2141 NodePointer Demangler::getDependentGenericParamType(int depth, int index) {
2142   if (depth < 0 || index < 0)
2143     return nullptr;
2144 
2145   auto paramTy = createNode(Node::Kind::DependentGenericParamType);
2146   paramTy->addChild(createNode(Node::Kind::Index, depth), *this);
2147   paramTy->addChild(createNode(Node::Kind::Index, index), *this);
2148   return paramTy;
2149 }
2150 
demangleGenericParamIndex()2151 NodePointer Demangler::demangleGenericParamIndex() {
2152   if (nextIf('d')) {
2153     int depth = demangleIndex() + 1;
2154     int index = demangleIndex();
2155     return getDependentGenericParamType(depth, index);
2156   }
2157   if (nextIf('z')) {
2158     return getDependentGenericParamType(0, 0);
2159   }
2160   return getDependentGenericParamType(0, demangleIndex() + 1);
2161 }
2162 
popProtocolConformance()2163 NodePointer Demangler::popProtocolConformance() {
2164   NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
2165   NodePointer Module = popModule();
2166   NodePointer Proto = popProtocol();
2167   NodePointer Type = popNode(Node::Kind::Type);
2168   NodePointer Ident = nullptr;
2169   if (!Type) {
2170     // Property behavior conformance
2171     Ident = popNode(Node::Kind::Identifier);
2172     Type = popNode(Node::Kind::Type);
2173   }
2174   if (GenSig) {
2175     Type = createType(createWithChildren(Node::Kind::DependentGenericType,
2176                                          GenSig, Type));
2177   }
2178   NodePointer Conf = createWithChildren(Node::Kind::ProtocolConformance,
2179                                         Type, Proto, Module);
2180   addChild(Conf, Ident);
2181   return Conf;
2182 }
2183 
demangleThunkOrSpecialization()2184 NodePointer Demangler::demangleThunkOrSpecialization() {
2185   switch (char c = nextChar()) {
2186     case 'c': return createWithChild(Node::Kind::CurryThunk, popNode(isEntity));
2187     case 'j': return createWithChild(Node::Kind::DispatchThunk, popNode(isEntity));
2188     case 'q': return createWithChild(Node::Kind::MethodDescriptor, popNode(isEntity));
2189     case 'o': return createNode(Node::Kind::ObjCAttribute);
2190     case 'O': return createNode(Node::Kind::NonObjCAttribute);
2191     case 'D': return createNode(Node::Kind::DynamicAttribute);
2192     case 'd': return createNode(Node::Kind::DirectMethodReferenceAttribute);
2193     case 'a': return createNode(Node::Kind::PartialApplyObjCForwarder);
2194     case 'A': return createNode(Node::Kind::PartialApplyForwarder);
2195     case 'm': return createNode(Node::Kind::MergedFunction);
2196     case 'X': return createNode(Node::Kind::DynamicallyReplaceableFunctionVar);
2197     case 'x': return createNode(Node::Kind::DynamicallyReplaceableFunctionKey);
2198     case 'I': return createNode(Node::Kind::DynamicallyReplaceableFunctionImpl);
2199     case 'C': {
2200       NodePointer type = popNode(Node::Kind::Type);
2201       return createWithChild(Node::Kind::CoroutineContinuationPrototype, type);
2202     }
2203     case 'V': {
2204       NodePointer Base = popNode(isEntity);
2205       NodePointer Derived = popNode(isEntity);
2206       return createWithChildren(Node::Kind::VTableThunk, Derived, Base);
2207     }
2208     case 'W': {
2209       NodePointer Entity = popNode(isEntity);
2210       NodePointer Conf = popProtocolConformance();
2211       return createWithChildren(Node::Kind::ProtocolWitness, Conf, Entity);
2212     }
2213     case 'S':
2214       return createWithChild(Node::Kind::ProtocolSelfConformanceWitness,
2215                              popNode(isEntity));
2216     case 'R':
2217     case 'r':
2218     case 'y': {
2219       Node::Kind kind;
2220       if (c == 'R') kind = Node::Kind::ReabstractionThunkHelper;
2221       else if (c == 'y') kind = Node::Kind::ReabstractionThunkHelperWithSelf;
2222       else kind = Node::Kind::ReabstractionThunk;
2223       NodePointer Thunk = createNode(kind);
2224       if (NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature))
2225         addChild(Thunk, GenSig);
2226       if (kind == Node::Kind::ReabstractionThunkHelperWithSelf)
2227         addChild(Thunk, popNode(Node::Kind::Type));
2228       addChild(Thunk, popNode(Node::Kind::Type));
2229       addChild(Thunk, popNode(Node::Kind::Type));
2230       return Thunk;
2231     }
2232     case 'g':
2233       return demangleGenericSpecialization(Node::Kind::GenericSpecialization);
2234     case 'G':
2235       return demangleGenericSpecialization(Node::Kind::
2236                                           GenericSpecializationNotReAbstracted);
2237     case 'i':
2238       return demangleGenericSpecialization(Node::Kind::InlinedGenericFunction);
2239     case'p': {
2240       NodePointer Spec = demangleSpecAttributes(Node::Kind::
2241                                                 GenericPartialSpecialization);
2242       NodePointer Param = createWithChild(Node::Kind::GenericSpecializationParam,
2243                                           popNode(Node::Kind::Type));
2244       return addChild(Spec, Param);
2245     }
2246     case'P': {
2247       NodePointer Spec = demangleSpecAttributes(Node::Kind::
2248                                   GenericPartialSpecializationNotReAbstracted);
2249       NodePointer Param = createWithChild(Node::Kind::GenericSpecializationParam,
2250                                           popNode(Node::Kind::Type));
2251       return addChild(Spec, Param);
2252     }
2253     case'f':
2254       return demangleFunctionSpecialization();
2255     case 'K':
2256     case 'k': {
2257       auto nodeKind = c == 'K' ? Node::Kind::KeyPathGetterThunkHelper
2258                                : Node::Kind::KeyPathSetterThunkHelper;
2259 
2260       bool isSerialized = nextIf('q');
2261 
2262       std::vector<NodePointer> types;
2263       auto node = popNode();
2264       if (!node || node->getKind() != Node::Kind::Type)
2265         return nullptr;
2266       do {
2267         types.push_back(node);
2268         node = popNode();
2269       } while (node && node->getKind() == Node::Kind::Type);
2270 
2271       NodePointer result;
2272       if (node) {
2273         if (node->getKind() == Node::Kind::DependentGenericSignature) {
2274           auto decl = popNode();
2275           if (!decl)
2276             return nullptr;
2277           result = createWithChildren(nodeKind, decl, /*sig*/ node);
2278         } else {
2279           result = createWithChild(nodeKind, /*decl*/ node);
2280         }
2281       } else {
2282         return nullptr;
2283       }
2284       for (auto i = types.rbegin(), e = types.rend(); i != e; ++i) {
2285         result->addChild(*i, *this);
2286       }
2287 
2288       if (isSerialized)
2289         result->addChild(createNode(Node::Kind::IsSerialized), *this);
2290 
2291       return result;
2292     }
2293     case 'l': {
2294       auto assocTypeName = popAssocTypeName();
2295       if (!assocTypeName)
2296         return nullptr;
2297 
2298       return createWithChild(Node::Kind::AssociatedTypeDescriptor,
2299                              assocTypeName);
2300     }
2301     case 'L':
2302       return createWithChild(Node::Kind::ProtocolRequirementsBaseDescriptor,
2303                              popProtocol());
2304     case 'M':
2305       return createWithChild(Node::Kind::DefaultAssociatedTypeMetadataAccessor,
2306                              popAssocTypeName());
2307 
2308     case 'n': {
2309       NodePointer requirementTy = popProtocol();
2310       NodePointer conformingType = popAssocTypePath();
2311       NodePointer protoTy = popNode(Node::Kind::Type);
2312       return createWithChildren(Node::Kind::AssociatedConformanceDescriptor,
2313                                 protoTy, conformingType, requirementTy);
2314     }
2315 
2316     case 'N': {
2317       NodePointer requirementTy = popProtocol();
2318       auto assocTypePath = popAssocTypePath();
2319       NodePointer protoTy = popNode(Node::Kind::Type);
2320       return createWithChildren(
2321                             Node::Kind::DefaultAssociatedConformanceAccessor,
2322                             protoTy, assocTypePath, requirementTy);
2323     }
2324 
2325     case 'b': {
2326       NodePointer requirementTy = popProtocol();
2327       NodePointer protoTy = popNode(Node::Kind::Type);
2328       return createWithChildren(Node::Kind::BaseConformanceDescriptor,
2329                                 protoTy, requirementTy);
2330     }
2331 
2332     case 'H':
2333     case 'h': {
2334       auto nodeKind = c == 'H' ? Node::Kind::KeyPathEqualsThunkHelper
2335                                : Node::Kind::KeyPathHashThunkHelper;
2336 
2337       bool isSerialized = nextIf('q');
2338 
2339       NodePointer genericSig = nullptr;
2340       std::vector<NodePointer> types;
2341 
2342       auto node = popNode();
2343       if (node) {
2344         if (node->getKind() == Node::Kind::DependentGenericSignature) {
2345           genericSig = node;
2346         } else if (node->getKind() == Node::Kind::Type) {
2347           types.push_back(node);
2348         } else {
2349           return nullptr;
2350         }
2351       } else {
2352         return nullptr;
2353       }
2354 
2355       while (auto node = popNode()) {
2356         if (node->getKind() != Node::Kind::Type) {
2357           return nullptr;
2358         }
2359         types.push_back(node);
2360       }
2361 
2362       NodePointer result = createNode(nodeKind);
2363       for (auto i = types.rbegin(), e = types.rend(); i != e; ++i) {
2364         result->addChild(*i, *this);
2365       }
2366       if (genericSig)
2367         result->addChild(genericSig, *this);
2368 
2369       if (isSerialized)
2370         result->addChild(createNode(Node::Kind::IsSerialized), *this);
2371 
2372       return result;
2373     }
2374     case 'v': {
2375       int Idx = demangleIndex();
2376       if (Idx < 0)
2377         return nullptr;
2378       return createNode(Node::Kind::OutlinedVariable, Idx);
2379     }
2380     case 'e': {
2381       std::string Params = demangleBridgedMethodParams();
2382       if (Params.empty())
2383         return nullptr;
2384       return createNode(Node::Kind::OutlinedBridgedMethod, Params);
2385     }
2386     default:
2387       return nullptr;
2388   }
2389 }
2390 
2391 std::string Demangler::demangleBridgedMethodParams() {
2392   if (nextIf('_'))
2393     return std::string();
2394 
2395   std::string Str;
2396 
2397   auto kind = nextChar();
2398   switch (kind) {
2399   default:
2400     return std::string();
2401   case 'p': case 'a': case 'm':
2402     Str.push_back(kind);
2403   }
2404 
2405   while (!nextIf('_')) {
2406     auto c = nextChar();
2407     if (c != 'n' && c != 'b' && c != 'g')
2408       return std::string();
2409     Str.push_back(c);
2410   }
2411   return Str;
2412 }
2413 
2414 NodePointer Demangler::demangleGenericSpecialization(Node::Kind SpecKind) {
2415   NodePointer Spec = demangleSpecAttributes(SpecKind);
2416   if (!Spec)
2417     return nullptr;
2418   NodePointer TyList = popTypeList();
2419   if (!TyList)
2420     return nullptr;
2421   for (NodePointer Ty : *TyList) {
2422     Spec->addChild(createWithChild(Node::Kind::GenericSpecializationParam, Ty),
2423                    *this);
2424   }
2425   return Spec;
2426 }
2427 
2428 NodePointer Demangler::demangleFunctionSpecialization() {
2429   NodePointer Spec = demangleSpecAttributes(
2430         Node::Kind::FunctionSignatureSpecialization);
2431   while (Spec && !nextIf('_')) {
2432     Spec = addChild(Spec, demangleFuncSpecParam(Node::Kind::FunctionSignatureSpecializationParam));
2433   }
2434   if (!nextIf('n'))
2435     Spec = addChild(Spec, demangleFuncSpecParam(Node::Kind::FunctionSignatureSpecializationReturn));
2436 
2437   if (!Spec)
2438     return nullptr;
2439 
2440   // Add the required parameters in reverse order.
2441   for (size_t Idx = 0, Num = Spec->getNumChildren(); Idx < Num; ++Idx) {
2442     NodePointer Param = Spec->getChild(Num - Idx - 1);
2443     if (Param->getKind() != Node::Kind::FunctionSignatureSpecializationParam)
2444       continue;
2445 
2446     if (Param->getNumChildren() == 0)
2447       continue;
2448     NodePointer KindNd = Param->getFirstChild();
2449     assert(KindNd->getKind() ==
2450              Node::Kind::FunctionSignatureSpecializationParamKind);
2451     auto ParamKind = (FunctionSigSpecializationParamKind)KindNd->getIndex();
2452     switch (ParamKind) {
2453       case FunctionSigSpecializationParamKind::ConstantPropFunction:
2454       case FunctionSigSpecializationParamKind::ConstantPropGlobal:
2455       case FunctionSigSpecializationParamKind::ConstantPropString:
2456       case FunctionSigSpecializationParamKind::ClosureProp: {
2457         size_t FixedChildren = Param->getNumChildren();
2458         while (NodePointer Ty = popNode(Node::Kind::Type)) {
2459           if (ParamKind != FunctionSigSpecializationParamKind::ClosureProp)
2460             return nullptr;
2461           Param = addChild(Param, Ty);
2462         }
2463         NodePointer Name = popNode(Node::Kind::Identifier);
2464         if (!Name)
2465           return nullptr;
2466         StringRef Text = Name->getText();
2467         if (ParamKind ==
2468                 FunctionSigSpecializationParamKind::ConstantPropString &&
2469             !Text.empty() && Text[0] == '_') {
2470           // A '_' escapes a leading digit or '_' of a string constant.
2471           Text = Text.drop_front(1);
2472         }
2473         addChild(Param, createNodeWithAllocatedText(
2474           Node::Kind::FunctionSignatureSpecializationParamPayload, Text));
2475         Param->reverseChildren(FixedChildren);
2476         break;
2477       }
2478       default:
2479         break;
2480     }
2481   }
2482   return Spec;
2483 }
2484 
2485 NodePointer Demangler::demangleFuncSpecParam(Node::Kind Kind) {
2486   assert(Kind == Node::Kind::FunctionSignatureSpecializationParam ||
2487          Kind == Node::Kind::FunctionSignatureSpecializationReturn);
2488   NodePointer Param = createNode(Kind);
2489   switch (nextChar()) {
2490     case 'n':
2491       return Param;
2492     case 'c':
2493       // Consumes an identifier and multiple type parameters.
2494       // The parameters will be added later.
2495       return addChild(Param, createNode(
2496         Node::Kind::FunctionSignatureSpecializationParamKind,
2497         uint64_t(FunctionSigSpecializationParamKind::ClosureProp)));
2498     case 'p': {
2499       switch (nextChar()) {
2500         case 'f':
2501           // Consumes an identifier parameter, which will be added later.
2502           return addChild(
2503               Param,
2504               createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
2505                          Node::IndexType(FunctionSigSpecializationParamKind::
2506                                              ConstantPropFunction)));
2507         case 'g':
2508           // Consumes an identifier parameter, which will be added later.
2509           return addChild(
2510               Param,
2511               createNode(
2512                   Node::Kind::FunctionSignatureSpecializationParamKind,
2513                   Node::IndexType(
2514                       FunctionSigSpecializationParamKind::ConstantPropGlobal)));
2515         case 'i':
2516           return addFuncSpecParamNumber(Param,
2517                     FunctionSigSpecializationParamKind::ConstantPropInteger);
2518         case 'd':
2519           return addFuncSpecParamNumber(Param,
2520                       FunctionSigSpecializationParamKind::ConstantPropFloat);
2521         case 's': {
2522           // Consumes an identifier parameter (the string constant),
2523           // which will be added later.
2524           const char *Encoding = nullptr;
2525           switch (nextChar()) {
2526             case 'b': Encoding = "u8"; break;
2527             case 'w': Encoding = "u16"; break;
2528             case 'c': Encoding = "objc"; break;
2529             default: return nullptr;
2530           }
2531           addChild(Param,
2532                    createNode(
2533                        Node::Kind::FunctionSignatureSpecializationParamKind,
2534                        Node::IndexType(
2535                            swift::Demangle::FunctionSigSpecializationParamKind::
2536                                ConstantPropString)));
2537           return addChild(Param, createNode(
2538                   Node::Kind::FunctionSignatureSpecializationParamPayload,
2539                   Encoding));
2540         }
2541         default:
2542           return nullptr;
2543       }
2544     }
2545     case 'e': {
2546       unsigned Value =
2547           unsigned(FunctionSigSpecializationParamKind::ExistentialToGeneric);
2548       if (nextIf('D'))
2549         Value |= unsigned(FunctionSigSpecializationParamKind::Dead);
2550       if (nextIf('G'))
2551         Value |=
2552             unsigned(FunctionSigSpecializationParamKind::OwnedToGuaranteed);
2553       if (nextIf('O'))
2554         Value |=
2555             unsigned(FunctionSigSpecializationParamKind::GuaranteedToOwned);
2556       if (nextIf('X'))
2557         Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
2558       return addChild(
2559           Param,
2560           createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
2561                      Value));
2562     }
2563     case 'd': {
2564       unsigned Value = unsigned(FunctionSigSpecializationParamKind::Dead);
2565       if (nextIf('G'))
2566         Value |= unsigned(FunctionSigSpecializationParamKind::OwnedToGuaranteed);
2567       if (nextIf('O'))
2568         Value |=
2569             unsigned(FunctionSigSpecializationParamKind::GuaranteedToOwned);
2570       if (nextIf('X'))
2571         Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
2572       return addChild(Param, createNode(
2573                   Node::Kind::FunctionSignatureSpecializationParamKind, Value));
2574     }
2575     case 'g': {
2576       unsigned Value = unsigned(FunctionSigSpecializationParamKind::
2577                                 OwnedToGuaranteed);
2578       if (nextIf('X'))
2579         Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
2580       return addChild(Param, createNode(
2581                   Node::Kind::FunctionSignatureSpecializationParamKind, Value));
2582     }
2583     case 'o': {
2584       unsigned Value =
2585           unsigned(FunctionSigSpecializationParamKind::GuaranteedToOwned);
2586       if (nextIf('X'))
2587         Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
2588       return addChild(
2589           Param,
2590           createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
2591                      Value));
2592     }
2593     case 'x':
2594       return addChild(Param, createNode(
2595                 Node::Kind::FunctionSignatureSpecializationParamKind,
2596                 unsigned(FunctionSigSpecializationParamKind::SROA)));
2597     case 'i':
2598       return addChild(Param, createNode(
2599                 Node::Kind::FunctionSignatureSpecializationParamKind,
2600                 unsigned(FunctionSigSpecializationParamKind::BoxToValue)));
2601     case 's':
2602       return addChild(Param, createNode(
2603                 Node::Kind::FunctionSignatureSpecializationParamKind,
2604                 unsigned(FunctionSigSpecializationParamKind::BoxToStack)));
2605     default:
2606       return nullptr;
2607   }
2608 }
2609 
2610 NodePointer Demangler::addFuncSpecParamNumber(NodePointer Param,
2611                                     FunctionSigSpecializationParamKind Kind) {
2612   Param->addChild(createNode(
2613         Node::Kind::FunctionSignatureSpecializationParamKind, unsigned(Kind)),
2614         *this);
2615   CharVector Str;
2616   while (isDigit(peekChar())) {
2617     Str.push_back(nextChar(), *this);
2618   }
2619   if (Str.empty())
2620     return nullptr;
2621   return addChild(Param, createNode(
2622      Node::Kind::FunctionSignatureSpecializationParamPayload, Str));
2623 }
2624 
2625 NodePointer Demangler::demangleSpecAttributes(Node::Kind SpecKind) {
2626   bool isSerialized = nextIf('q');
2627 
2628   int PassID = (int)nextChar() - '0';
2629   if (PassID < 0 || PassID > 9)
2630     return nullptr;
2631 
2632   NodePointer SpecNd = createNode(SpecKind);
2633   if (isSerialized)
2634     SpecNd->addChild(createNode(Node::Kind::IsSerialized),
2635                      *this);
2636 
2637   SpecNd->addChild(createNode(Node::Kind::SpecializationPassID, PassID),
2638                    *this);
2639   return SpecNd;
2640 }
2641 
2642 NodePointer Demangler::demangleWitness() {
2643   switch (nextChar()) {
2644     case 'C':
2645       return createWithChild(Node::Kind::EnumCase,
2646                              popNode(isEntity));
2647     case 'V':
2648       return createWithChild(Node::Kind::ValueWitnessTable,
2649                              popNode(Node::Kind::Type));
2650     case 'v': {
2651       unsigned Directness;
2652       switch (nextChar()) {
2653         case 'd': Directness = unsigned(Directness::Direct); break;
2654         case 'i': Directness = unsigned(Directness::Indirect); break;
2655         default: return nullptr;
2656       }
2657       return createWithChildren(Node::Kind::FieldOffset,
2658                         createNode(Node::Kind::Directness, Directness),
2659                         popNode(isEntity));
2660     }
2661     case 'S':
2662       return createWithChild(Node::Kind::ProtocolSelfConformanceWitnessTable,
2663                              popProtocol());
2664     case 'P':
2665       return createWithChild(Node::Kind::ProtocolWitnessTable,
2666                              popProtocolConformance());
2667     case 'p':
2668       return createWithChild(Node::Kind::ProtocolWitnessTablePattern,
2669                              popProtocolConformance());
2670     case 'G':
2671       return createWithChild(Node::Kind::GenericProtocolWitnessTable,
2672                              popProtocolConformance());
2673     case 'I':
2674       return createWithChild(
2675                   Node::Kind::GenericProtocolWitnessTableInstantiationFunction,
2676                   popProtocolConformance());
2677 
2678     case 'r':
2679       return createWithChild(Node::Kind::ResilientProtocolWitnessTable,
2680                              popProtocolConformance());
2681 
2682     case 'l': {
2683       NodePointer Conf = popProtocolConformance();
2684       NodePointer Type = popNode(Node::Kind::Type);
2685       return createWithChildren(Node::Kind::LazyProtocolWitnessTableAccessor,
2686                                 Type, Conf);
2687     }
2688     case 'L': {
2689       NodePointer Conf = popProtocolConformance();
2690       NodePointer Type = popNode(Node::Kind::Type);
2691       return createWithChildren(
2692                Node::Kind::LazyProtocolWitnessTableCacheVariable, Type, Conf);
2693     }
2694     case 'a':
2695       return createWithChild(Node::Kind::ProtocolWitnessTableAccessor,
2696                              popProtocolConformance());
2697     case 't': {
2698       NodePointer Name = popNode(isDeclName);
2699       NodePointer Conf = popProtocolConformance();
2700       return createWithChildren(Node::Kind::AssociatedTypeMetadataAccessor,
2701                                 Conf, Name);
2702     }
2703     case 'T': {
2704       NodePointer ProtoTy = popNode(Node::Kind::Type);
2705       NodePointer ConformingType = popAssocTypePath();
2706       NodePointer Conf = popProtocolConformance();
2707       return createWithChildren(Node::Kind::AssociatedTypeWitnessTableAccessor,
2708                                 Conf, ConformingType, ProtoTy);
2709     }
2710     case 'b': {
2711       NodePointer ProtoTy = popNode(Node::Kind::Type);
2712       NodePointer Conf = popProtocolConformance();
2713       return createWithChildren(Node::Kind::BaseWitnessTableAccessor,
2714                                 Conf, ProtoTy);
2715     }
2716     case 'O': {
2717       switch (nextChar()) {
2718       case 'y': {
2719         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2720           return createWithChildren(Node::Kind::OutlinedCopy,
2721                                     popNode(Node::Kind::Type), sig);
2722         return createWithChild(Node::Kind::OutlinedCopy,
2723                                popNode(Node::Kind::Type));
2724       }
2725       case 'e': {
2726         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2727           return createWithChildren(Node::Kind::OutlinedConsume,
2728                                     popNode(Node::Kind::Type), sig);
2729         return createWithChild(Node::Kind::OutlinedConsume,
2730                                popNode(Node::Kind::Type));
2731       }
2732       case 'r': {
2733         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2734           return createWithChildren(Node::Kind::OutlinedRetain,
2735                                     popNode(Node::Kind::Type), sig);
2736         return createWithChild(Node::Kind::OutlinedRetain,
2737                                popNode(Node::Kind::Type));
2738       }
2739       case 's': {
2740         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2741           return createWithChildren(Node::Kind::OutlinedRelease,
2742                                     popNode(Node::Kind::Type), sig);
2743         return createWithChild(Node::Kind::OutlinedRelease,
2744                                popNode(Node::Kind::Type));
2745       }
2746       case 'b': {
2747         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2748           return createWithChildren(Node::Kind::OutlinedInitializeWithTake,
2749                                     popNode(Node::Kind::Type), sig);
2750         return createWithChild(Node::Kind::OutlinedInitializeWithTake,
2751                                popNode(Node::Kind::Type));
2752       }
2753       case 'c': {
2754         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2755           return createWithChildren(Node::Kind::OutlinedInitializeWithCopy,
2756                                     popNode(Node::Kind::Type), sig);
2757         return createWithChild(Node::Kind::OutlinedInitializeWithCopy,
2758                                popNode(Node::Kind::Type));
2759       }
2760       case 'd': {
2761         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2762           return createWithChildren(Node::Kind::OutlinedAssignWithTake,
2763                                     popNode(Node::Kind::Type), sig);
2764         return createWithChild(Node::Kind::OutlinedAssignWithTake,
2765                                popNode(Node::Kind::Type));
2766       }
2767       case 'f': {
2768         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2769           return createWithChildren(Node::Kind::OutlinedAssignWithCopy,
2770                                     popNode(Node::Kind::Type), sig);
2771         return createWithChild(Node::Kind::OutlinedAssignWithCopy,
2772                                popNode(Node::Kind::Type));
2773       }
2774       case 'h': {
2775         if (auto sig = popNode(Node::Kind::DependentGenericSignature))
2776           return createWithChildren(Node::Kind::OutlinedDestroy,
2777                                     popNode(Node::Kind::Type), sig);
2778         return createWithChild(Node::Kind::OutlinedDestroy,
2779                                popNode(Node::Kind::Type));
2780       }
2781       default:
2782         return nullptr;
2783       }
2784     }
2785     default:
2786       return nullptr;
2787   }
2788 }
2789 
2790 NodePointer Demangler::demangleSpecialType() {
2791   switch (auto specialChar = nextChar()) {
2792     case 'E':
2793       return popFunctionType(Node::Kind::NoEscapeFunctionType);
2794     case 'A':
2795       return popFunctionType(Node::Kind::EscapingAutoClosureType);
2796     case 'f':
2797       return popFunctionType(Node::Kind::ThinFunctionType);
2798     case 'K':
2799       return popFunctionType(Node::Kind::AutoClosureType);
2800     case 'U':
2801       return popFunctionType(Node::Kind::UncurriedFunctionType);
2802     case 'L':
2803       return popFunctionType(Node::Kind::EscapingObjCBlock);
2804     case 'B':
2805       return popFunctionType(Node::Kind::ObjCBlock);
2806     case 'C':
2807       return popFunctionType(Node::Kind::CFunctionPointer);
2808     case 'F':
2809       return popFunctionType(Node::Kind::DifferentiableFunctionType);
2810     case 'G':
2811       return popFunctionType(Node::Kind::EscapingDifferentiableFunctionType);
2812     case 'H':
2813       return popFunctionType(Node::Kind::LinearFunctionType);
2814     case 'I':
2815       return popFunctionType(Node::Kind::EscapingLinearFunctionType);
2816     case 'o':
2817       return createType(createWithChild(Node::Kind::Unowned,
2818                                         popNode(Node::Kind::Type)));
2819     case 'u':
2820       return createType(createWithChild(Node::Kind::Unmanaged,
2821                                         popNode(Node::Kind::Type)));
2822     case 'w':
2823       return createType(createWithChild(Node::Kind::Weak,
2824                                         popNode(Node::Kind::Type)));
2825     case 'b':
2826       return createType(createWithChild(Node::Kind::SILBoxType,
2827                                         popNode(Node::Kind::Type)));
2828     case 'D':
2829       return createType(createWithChild(Node::Kind::DynamicSelf,
2830                                         popNode(Node::Kind::Type)));
2831     case 'M': {
2832       NodePointer MTR = demangleMetatypeRepresentation();
2833       NodePointer Type = popNode(Node::Kind::Type);
2834       return createType(createWithChildren(Node::Kind::Metatype, MTR, Type));
2835     }
2836     case 'm': {
2837       NodePointer MTR = demangleMetatypeRepresentation();
2838       NodePointer Type = popNode(Node::Kind::Type);
2839       return createType(createWithChildren(Node::Kind::ExistentialMetatype,
2840                                            MTR, Type));
2841     }
2842     case 'p':
2843       return createType(createWithChild(Node::Kind::ExistentialMetatype,
2844                                         popNode(Node::Kind::Type)));
2845     case 'c': {
2846       NodePointer Superclass = popNode(Node::Kind::Type);
2847       NodePointer Protocols = demangleProtocolList();
2848       return createType(createWithChildren(Node::Kind::ProtocolListWithClass,
2849                                            Protocols, Superclass));
2850     }
2851     case 'l': {
2852       NodePointer Protocols = demangleProtocolList();
2853       return createType(createWithChild(Node::Kind::ProtocolListWithAnyObject,
2854                                         Protocols));
2855     }
2856     case 'X':
2857     case 'x': {
2858       // SIL box types.
2859       NodePointer signature = nullptr, genericArgs = nullptr;
2860       if (specialChar == 'X') {
2861         signature = popNode(Node::Kind::DependentGenericSignature);
2862         if (!signature)
2863           return nullptr;
2864         genericArgs = popTypeList();
2865         if (!genericArgs)
2866           return nullptr;
2867       }
2868 
2869       auto fieldTypes = popTypeList();
2870       if (!fieldTypes)
2871         return nullptr;
2872       // Build layout.
2873       auto layout = createNode(Node::Kind::SILBoxLayout);
2874       for (unsigned i = 0, e = fieldTypes->getNumChildren(); i < e; ++i) {
2875         auto fieldType = fieldTypes->getChild(i);
2876         assert(fieldType->getKind() == Node::Kind::Type);
2877         bool isMutable = false;
2878         // 'inout' typelist mangling is used to represent mutable fields.
2879         if (fieldType->getChild(0)->getKind() == Node::Kind::InOut) {
2880           isMutable = true;
2881           fieldType = createType(fieldType->getChild(0)->getChild(0));
2882         }
2883         auto field = createNode(isMutable
2884                                          ? Node::Kind::SILBoxMutableField
2885                                          : Node::Kind::SILBoxImmutableField);
2886         field->addChild(fieldType, *this);
2887         layout->addChild(field, *this);
2888       }
2889       auto boxTy = createNode(Node::Kind::SILBoxTypeWithLayout);
2890       boxTy->addChild(layout, *this);
2891       if (signature) {
2892         boxTy->addChild(signature, *this);
2893         assert(genericArgs);
2894         boxTy->addChild(genericArgs, *this);
2895       }
2896       return createType(boxTy);
2897     }
2898     case 'Y':
2899       return demangleAnyGenericType(Node::Kind::OtherNominalType);
2900     case 'Z': {
2901       auto types = popTypeList();
2902       auto name = popNode(Node::Kind::Identifier);
2903       auto parent = popContext();
2904       auto anon = createNode(Node::Kind::AnonymousContext);
2905       anon = addChild(anon, name);
2906       anon = addChild(anon, parent);
2907       anon = addChild(anon, types);
2908       return anon;
2909     }
2910     case 'e':
2911       return createType(createNode(Node::Kind::ErrorType));
2912     case 'S':
2913       // Sugared type for debugger.
2914       switch (nextChar()) {
2915       case 'q':
2916         return createType(createWithChild(Node::Kind::SugaredOptional,
2917                                           popNode(Node::Kind::Type)));
2918       case 'a':
2919         return createType(createWithChild(Node::Kind::SugaredArray,
2920                                           popNode(Node::Kind::Type)));
2921       case 'D': {
2922         NodePointer value = popNode(Node::Kind::Type);
2923         NodePointer key = popNode(Node::Kind::Type);
2924         return createType(createWithChildren(Node::Kind::SugaredDictionary,
2925                                              key, value));
2926       }
2927       case 'p':
2928         return createType(createWithChild(Node::Kind::SugaredParen,
2929                                           popNode(Node::Kind::Type)));
2930       default:
2931         return nullptr;
2932       }
2933     default:
2934       return nullptr;
2935   }
2936 }
2937 
2938 NodePointer Demangler::demangleMetatypeRepresentation() {
2939   switch (nextChar()) {
2940     case 't':
2941       return createNode(Node::Kind::MetatypeRepresentation, "@thin");
2942     case 'T':
2943       return createNode(Node::Kind::MetatypeRepresentation, "@thick");
2944     case 'o':
2945       return createNode(Node::Kind::MetatypeRepresentation,
2946                                  "@objc_metatype");
2947     default:
2948       return nullptr;
2949   }
2950 }
2951 
2952 NodePointer Demangler::demangleAccessor(NodePointer ChildNode) {
2953   Node::Kind Kind;
2954   switch (nextChar()) {
2955     case 'm': Kind = Node::Kind::MaterializeForSet; break;
2956     case 's': Kind = Node::Kind::Setter; break;
2957     case 'g': Kind = Node::Kind::Getter; break;
2958     case 'G': Kind = Node::Kind::GlobalGetter; break;
2959     case 'w': Kind = Node::Kind::WillSet; break;
2960     case 'W': Kind = Node::Kind::DidSet; break;
2961     case 'r': Kind = Node::Kind::ReadAccessor; break;
2962     case 'M': Kind = Node::Kind::ModifyAccessor; break;
2963     case 'a':
2964       switch (nextChar()) {
2965         case 'O': Kind = Node::Kind::OwningMutableAddressor; break;
2966         case 'o': Kind = Node::Kind::NativeOwningMutableAddressor; break;
2967         case 'P': Kind = Node::Kind::NativePinningMutableAddressor; break;
2968         case 'u': Kind = Node::Kind::UnsafeMutableAddressor; break;
2969         default: return nullptr;
2970       }
2971       break;
2972     case 'l':
2973       switch (nextChar()) {
2974         case 'O': Kind = Node::Kind::OwningAddressor; break;
2975         case 'o': Kind = Node::Kind::NativeOwningAddressor; break;
2976         case 'p': Kind = Node::Kind::NativePinningAddressor; break;
2977         case 'u': Kind = Node::Kind::UnsafeAddressor; break;
2978         default: return nullptr;
2979       }
2980       break;
2981     case 'p': // Pseudo-accessor referring to the variable/subscript itself
2982       return ChildNode;
2983     default: return nullptr;
2984   }
2985   NodePointer Entity = createWithChild(Kind, ChildNode);
2986   return Entity;
2987 }
2988 
2989 NodePointer Demangler::demangleFunctionEntity() {
2990   enum {
2991     None,
2992     TypeAndMaybePrivateName,
2993     TypeAndIndex,
2994     Index
2995   } Args;
2996 
2997   Node::Kind Kind = Node::Kind::EmptyList;
2998   switch (nextChar()) {
2999     case 'D': Args = None; Kind = Node::Kind::Deallocator; break;
3000     case 'd': Args = None; Kind = Node::Kind::Destructor; break;
3001     case 'E': Args = None; Kind = Node::Kind::IVarDestroyer; break;
3002     case 'e': Args = None; Kind = Node::Kind::IVarInitializer; break;
3003     case 'i': Args = None; Kind = Node::Kind::Initializer; break;
3004     case 'C':
3005       Args = TypeAndMaybePrivateName; Kind = Node::Kind::Allocator; break;
3006     case 'c':
3007       Args = TypeAndMaybePrivateName; Kind = Node::Kind::Constructor; break;
3008     case 'U': Args = TypeAndIndex; Kind = Node::Kind::ExplicitClosure; break;
3009     case 'u': Args = TypeAndIndex; Kind = Node::Kind::ImplicitClosure; break;
3010     case 'A': Args = Index; Kind = Node::Kind::DefaultArgumentInitializer; break;
3011     case 'p': return demangleEntity(Node::Kind::GenericTypeParamDecl);
3012     case 'P':
3013       Args = None;
3014       Kind = Node::Kind::PropertyWrapperBackingInitializer;
3015       break;
3016     default: return nullptr;
3017   }
3018 
3019   NodePointer NameOrIndex = nullptr, ParamType = nullptr, LabelList = nullptr;
3020   switch (Args) {
3021     case None:
3022       break;
3023     case TypeAndMaybePrivateName:
3024       NameOrIndex = popNode(Node::Kind::PrivateDeclName);
3025       ParamType = popNode(Node::Kind::Type);
3026       LabelList = popFunctionParamLabels(ParamType);
3027       break;
3028     case TypeAndIndex:
3029       NameOrIndex = demangleIndexAsNode();
3030       ParamType = popNode(Node::Kind::Type);
3031       break;
3032     case Index:
3033       NameOrIndex = demangleIndexAsNode();
3034       break;
3035   }
3036   NodePointer Entity = createWithChild(Kind, popContext());
3037   switch (Args) {
3038     case None:
3039       break;
3040     case Index:
3041       Entity = addChild(Entity, NameOrIndex);
3042       break;
3043     case TypeAndMaybePrivateName:
3044       addChild(Entity, LabelList);
3045       Entity = addChild(Entity, ParamType);
3046       addChild(Entity, NameOrIndex);
3047       break;
3048     case TypeAndIndex:
3049       Entity = addChild(Entity, NameOrIndex);
3050       Entity = addChild(Entity, ParamType);
3051       break;
3052   }
3053   return Entity;
3054 }
3055 
3056 NodePointer Demangler::demangleEntity(Node::Kind Kind) {
3057   NodePointer Type = popNode(Node::Kind::Type);
3058   NodePointer LabelList = popFunctionParamLabels(Type);
3059   NodePointer Name = popNode(isDeclName);
3060   NodePointer Context = popContext();
3061   return LabelList ? createWithChildren(Kind, Context, Name, LabelList, Type)
3062                    : createWithChildren(Kind, Context, Name, Type);
3063 }
3064 
3065 NodePointer Demangler::demangleVariable() {
3066   NodePointer Variable = demangleEntity(Node::Kind::Variable);
3067   return demangleAccessor(Variable);
3068 }
3069 
3070 NodePointer Demangler::demangleSubscript() {
3071   NodePointer PrivateName = popNode(Node::Kind::PrivateDeclName);
3072   NodePointer Type = popNode(Node::Kind::Type);
3073   NodePointer LabelList = popFunctionParamLabels(Type);
3074   NodePointer Context = popContext();
3075 
3076   NodePointer Subscript = createNode(Node::Kind::Subscript);
3077   Subscript = addChild(Subscript, Context);
3078   addChild(Subscript, LabelList);
3079   Subscript = addChild(Subscript, Type);
3080   addChild(Subscript, PrivateName);
3081 
3082   return demangleAccessor(Subscript);
3083 }
3084 
3085 NodePointer Demangler::demangleProtocolList() {
3086   NodePointer TypeList = createNode(Node::Kind::TypeList);
3087   NodePointer ProtoList = createWithChild(Node::Kind::ProtocolList, TypeList);
3088   if (!popNode(Node::Kind::EmptyList)) {
3089     bool firstElem = false;
3090     do {
3091       firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
3092       NodePointer Proto = popProtocol();
3093       if (!Proto)
3094         return nullptr;
3095       TypeList->addChild(Proto, *this);
3096     } while (!firstElem);
3097 
3098     TypeList->reverseChildren();
3099   }
3100   return ProtoList;
3101 }
3102 
3103 NodePointer Demangler::demangleProtocolListType() {
3104   NodePointer ProtoList = demangleProtocolList();
3105   return createType(ProtoList);
3106 }
3107 
3108 NodePointer Demangler::demangleGenericSignature(bool hasParamCounts) {
3109   NodePointer Sig = createNode(Node::Kind::DependentGenericSignature);
3110   if (hasParamCounts) {
3111     while (!nextIf('l')) {
3112       int count = 0;
3113       if (!nextIf('z'))
3114         count = demangleIndex() + 1;
3115       if (count < 0)
3116         return nullptr;
3117       Sig->addChild(createNode(Node::Kind::DependentGenericParamCount,
3118                                         count), *this);
3119     }
3120   } else {
3121     Sig->addChild(createNode(Node::Kind::DependentGenericParamCount, 1),
3122                   *this);
3123   }
3124   size_t NumCounts = Sig->getNumChildren();
3125   while (NodePointer Req = popNode(isRequirement)) {
3126     Sig->addChild(Req, *this);
3127   }
3128   Sig->reverseChildren(NumCounts);
3129   return Sig;
3130 }
3131 
3132 NodePointer Demangler::demangleGenericRequirement() {
3133 
3134   enum { Generic, Assoc, CompoundAssoc, Substitution } TypeKind;
3135   enum { Protocol, BaseClass, SameType, Layout } ConstraintKind;
3136 
3137   switch (nextChar()) {
3138     case 'c': ConstraintKind = BaseClass; TypeKind = Assoc; break;
3139     case 'C': ConstraintKind = BaseClass; TypeKind = CompoundAssoc; break;
3140     case 'b': ConstraintKind = BaseClass; TypeKind = Generic; break;
3141     case 'B': ConstraintKind = BaseClass; TypeKind = Substitution; break;
3142     case 't': ConstraintKind = SameType; TypeKind = Assoc; break;
3143     case 'T': ConstraintKind = SameType; TypeKind = CompoundAssoc; break;
3144     case 's': ConstraintKind = SameType; TypeKind = Generic; break;
3145     case 'S': ConstraintKind = SameType; TypeKind = Substitution; break;
3146     case 'm': ConstraintKind = Layout; TypeKind = Assoc; break;
3147     case 'M': ConstraintKind = Layout; TypeKind = CompoundAssoc; break;
3148     case 'l': ConstraintKind = Layout; TypeKind = Generic; break;
3149     case 'L': ConstraintKind = Layout; TypeKind = Substitution; break;
3150     case 'p': ConstraintKind = Protocol; TypeKind = Assoc; break;
3151     case 'P': ConstraintKind = Protocol; TypeKind = CompoundAssoc; break;
3152     case 'Q': ConstraintKind = Protocol; TypeKind = Substitution; break;
3153     default:  ConstraintKind = Protocol; TypeKind = Generic; pushBack(); break;
3154   }
3155 
3156   NodePointer ConstrTy = nullptr;
3157 
3158   switch (TypeKind) {
3159   case Generic:
3160     ConstrTy = createType(demangleGenericParamIndex());
3161     break;
3162   case Assoc:
3163     ConstrTy = demangleAssociatedTypeSimple(demangleGenericParamIndex());
3164     addSubstitution(ConstrTy);
3165     break;
3166   case CompoundAssoc:
3167     ConstrTy = demangleAssociatedTypeCompound(demangleGenericParamIndex());
3168     addSubstitution(ConstrTy);
3169     break;
3170   case Substitution:
3171     ConstrTy = popNode(Node::Kind::Type);
3172     break;
3173   }
3174 
3175   switch (ConstraintKind) {
3176   case Protocol:
3177     return createWithChildren(
3178         Node::Kind::DependentGenericConformanceRequirement, ConstrTy,
3179         popProtocol());
3180   case BaseClass:
3181     return createWithChildren(
3182         Node::Kind::DependentGenericConformanceRequirement, ConstrTy,
3183         popNode(Node::Kind::Type));
3184   case SameType:
3185     return createWithChildren(Node::Kind::DependentGenericSameTypeRequirement,
3186                               ConstrTy, popNode(Node::Kind::Type));
3187   case Layout: {
3188     auto c = nextChar();
3189     NodePointer size = nullptr;
3190     NodePointer alignment = nullptr;
3191     const char *name = nullptr;
3192     if (c == 'U') {
3193       name = "U";
3194     } else if (c == 'R') {
3195       name = "R";
3196     } else if (c == 'N') {
3197       name = "N";
3198     } else if (c == 'C') {
3199       name = "C";
3200     } else if (c == 'D') {
3201       name = "D";
3202     } else if (c == 'T') {
3203       name = "T";
3204     } else if (c == 'E') {
3205       size = demangleIndexAsNode();
3206       if (!size)
3207         return nullptr;
3208       alignment = demangleIndexAsNode();
3209       name = "E";
3210     } else if (c == 'e') {
3211       size = demangleIndexAsNode();
3212       if (!size)
3213         return nullptr;
3214       name = "e";
3215     } else if (c == 'M') {
3216       size = demangleIndexAsNode();
3217       if (!size)
3218         return nullptr;
3219       alignment = demangleIndexAsNode();
3220       name = "M";
3221     } else if (c == 'm') {
3222       size = demangleIndexAsNode();
3223       if (!size)
3224         return nullptr;
3225       name = "m";
3226     } else {
3227       // Unknown layout constraint.
3228       return nullptr;
3229     }
3230 
3231     auto NameNode = createNode(Node::Kind::Identifier, name);
3232     auto LayoutRequirement = createWithChildren(
3233         Node::Kind::DependentGenericLayoutRequirement, ConstrTy, NameNode);
3234     if (size)
3235       addChild(LayoutRequirement, size);
3236     if (alignment)
3237       addChild(LayoutRequirement, alignment);
3238     return LayoutRequirement;
3239   }
3240   }
3241   return nullptr;
3242 }
3243 
3244 NodePointer Demangler::demangleGenericType() {
3245   NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
3246   NodePointer Ty = popNode(Node::Kind::Type);
3247   return createType(createWithChildren(Node::Kind::DependentGenericType,
3248                                        GenSig, Ty));
3249 }
3250 
3251 static int decodeValueWitnessKind(StringRef CodeStr) {
3252 #define VALUE_WITNESS(MANGLING, NAME) \
3253   if (CodeStr == #MANGLING) return (int)ValueWitnessKind::NAME;
3254 #include "swift/Demangling/ValueWitnessMangling.def"
3255   return -1;
3256 }
3257 
3258 NodePointer Demangler::demangleValueWitness() {
3259   char Code[2];
3260   Code[0] = nextChar();
3261   Code[1] = nextChar();
3262   int Kind = decodeValueWitnessKind(StringRef(Code, 2));
3263   if (Kind < 0)
3264     return nullptr;
3265   NodePointer VW = createNode(Node::Kind::ValueWitness);
3266   addChild(VW, createNode(Node::Kind::Index, unsigned(Kind)));
3267   return addChild(VW, popNode(Node::Kind::Type));
3268 }
3269