File: Demangler.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (4367 lines) | stat: -rw-r--r-- 148,211 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
//===--- Demangler.cpp - String to Node-Tree Demangling -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements new Swift de-mangler.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Compiler.h"
#include "swift/Demangling/Demangler.h"
#include "DemanglerAssert.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Demangling/ManglingUtils.h"
#include "swift/Demangling/Punycode.h"
#include "swift/Strings.h"
#include <stdio.h>
#include <stdlib.h>

using namespace swift;
using namespace Mangle;
using swift::Demangle::FunctionSigSpecializationParamKind;

//////////////////////////////////
// Private utility functions    //
//////////////////////////////////

namespace {

static bool isDeclName(Node::Kind kind) {
  switch (kind) {
    case Node::Kind::Identifier:
    case Node::Kind::LocalDeclName:
    case Node::Kind::PrivateDeclName:
    case Node::Kind::RelatedEntityDeclName:
    case Node::Kind::PrefixOperator:
    case Node::Kind::PostfixOperator:
    case Node::Kind::InfixOperator:
    case Node::Kind::TypeSymbolicReference:
    case Node::Kind::ProtocolSymbolicReference:
    case Node::Kind::ObjectiveCProtocolSymbolicReference:
      return true;
    default:
      return false;
  }
}

static bool isAnyGeneric(Node::Kind kind) {
  switch (kind) {
    case Node::Kind::Structure:
    case Node::Kind::Class:
    case Node::Kind::Enum:
    case Node::Kind::Protocol:
    case Node::Kind::ProtocolSymbolicReference:
    case Node::Kind::ObjectiveCProtocolSymbolicReference:
    case Node::Kind::OtherNominalType:
    case Node::Kind::TypeAlias:
    case Node::Kind::TypeSymbolicReference:
    case Node::Kind::BuiltinTupleType:
      return true;
    default:
      return false;
  }
}

static bool isEntity(Node::Kind kind) {
  // Also accepts some kind which are not entities.
  if (kind == Node::Kind::Type)
    return true;
  return isContext(kind);
}

static bool isRequirement(Node::Kind kind) {
  switch (kind) {
    case Node::Kind::DependentGenericParamPackMarker:
    case Node::Kind::DependentGenericSameTypeRequirement:
    case Node::Kind::DependentGenericSameShapeRequirement:
    case Node::Kind::DependentGenericLayoutRequirement:
    case Node::Kind::DependentGenericConformanceRequirement:
    case Node::Kind::DependentGenericInverseConformanceRequirement:
      return true;
    default:
      return false;
  }
}

} // anonymous namespace

//////////////////////////////////
// Public utility functions    //
//////////////////////////////////

void swift::Demangle::failAssert(const char *file, unsigned line,
                                 NodePointer node, const char *expr) {
  std::string treeStr = getNodeTreeAsString(node);

  fatal(0,
        "%s:%u: assertion failed for Node %p: %s\n"
        "%s:%u: Node %p is:\n%s\n",
        file, line, node, expr, file, line, node, treeStr.c_str());
}

bool swift::Demangle::isContext(Node::Kind kind) {
  switch (kind) {
#define NODE(ID)
#define CONTEXT_NODE(ID)                                                \
    case Node::Kind::ID:
#include "swift/Demangling/DemangleNodes.def"
      return true;
    case Node::Kind::BuiltinTupleType:
      return true;
    default:
      return false;
  }
}

bool swift::Demangle::isFunctionAttr(Node::Kind kind) {
  switch (kind) {
    case Node::Kind::FunctionSignatureSpecialization:
    case Node::Kind::GenericSpecialization:
    case Node::Kind::GenericSpecializationPrespecialized:
    case Node::Kind::InlinedGenericFunction:
    case Node::Kind::GenericSpecializationNotReAbstracted:
    case Node::Kind::GenericPartialSpecialization:
    case Node::Kind::GenericPartialSpecializationNotReAbstracted:
    case Node::Kind::GenericSpecializationInResilienceDomain:
    case Node::Kind::ObjCAttribute:
    case Node::Kind::NonObjCAttribute:
    case Node::Kind::DynamicAttribute:
    case Node::Kind::DirectMethodReferenceAttribute:
    case Node::Kind::VTableAttribute:
    case Node::Kind::PartialApplyForwarder:
    case Node::Kind::PartialApplyObjCForwarder:
    case Node::Kind::OutlinedVariable:
    case Node::Kind::OutlinedReadOnlyObject:
    case Node::Kind::OutlinedBridgedMethod:
    case Node::Kind::MergedFunction:
    case Node::Kind::DistributedThunk:
    case Node::Kind::DistributedAccessor:
    case Node::Kind::DynamicallyReplaceableFunctionImpl:
    case Node::Kind::DynamicallyReplaceableFunctionKey:
    case Node::Kind::DynamicallyReplaceableFunctionVar:
    case Node::Kind::AsyncFunctionPointer:
    case Node::Kind::AsyncAwaitResumePartialFunction:
    case Node::Kind::AsyncSuspendResumePartialFunction:
    case Node::Kind::AccessibleFunctionRecord:
    case Node::Kind::BackDeploymentThunk:
    case Node::Kind::BackDeploymentFallback:
    case Node::Kind::HasSymbolQuery:
      return true;
    default:
      return false;
  }
}

llvm::StringRef
swift::Demangle::makeSymbolicMangledNameStringRef(const char *base) {
  if (!base)
    return {};

  auto end = base;
  while (*end != '\0') {
    // Skip over symbolic references.
    if (*end >= '\x01' && *end <= '\x17')
      end += sizeof(uint32_t);
    else if (*end >= '\x18' && *end <= '\x1F')
      end += sizeof(void*);
    ++end;
  }
  return StringRef(base, end - base);
}

int swift::Demangle::getManglingPrefixLength(llvm::StringRef mangledName) {
  if (mangledName.empty()) return 0;

  llvm::StringRef prefixes[] = {
    /*Swift 4*/   "_T0",
    /*Swift 4.x*/ "$S", "_$S",
    /*Swift 5+*/  "$s", "_$s",
    /*Swift 5+ for filenames*/ "@__swiftmacro_",
  };

  // Look for any of the known prefixes
  for (auto prefix : prefixes) {
    if (mangledName.starts_with(prefix))
      return prefix.size();
  }

  return 0;
}

bool swift::Demangle::isSwiftSymbol(llvm::StringRef mangledName) {
  if (isOldFunctionTypeMangling(mangledName))
    return true;

  return getManglingPrefixLength(mangledName) != 0;
}

bool swift::Demangle::isSwiftSymbol(const char *mangledName) {
  StringRef mangledNameRef(mangledName);
  return isSwiftSymbol(mangledNameRef);
}

bool swift::Demangle::isObjCSymbol(llvm::StringRef mangledName) {
  StringRef nameWithoutPrefix = dropSwiftManglingPrefix(mangledName);
  return nameWithoutPrefix.starts_with("So") ||
         nameWithoutPrefix.starts_with("SC");
}

bool swift::Demangle::isOldFunctionTypeMangling(llvm::StringRef mangledName) {
  return mangledName.starts_with("_T");
}

llvm::StringRef swift::Demangle::dropSwiftManglingPrefix(StringRef mangledName){
  return mangledName.drop_front(getManglingPrefixLength(mangledName));
}

static bool isAliasNode(Demangle::NodePointer Node) {
  switch (Node->getKind()) {
  case Demangle::Node::Kind::Type:
    return isAliasNode(Node->getChild(0));
  case Demangle::Node::Kind::TypeAlias:
    return true;
  default:
    return false;
  }
  assert(0 && "unknown node kind");
}

bool swift::Demangle::isAlias(llvm::StringRef mangledName) {
  Demangle::Demangler Dem;
  return isAliasNode(Dem.demangleType(mangledName));
}

static bool isClassNode(Demangle::NodePointer Node) {
  switch (Node->getKind()) {
  case Demangle::Node::Kind::Type:
    return isClassNode(Node->getChild(0));
  case Demangle::Node::Kind::Class:
  case Demangle::Node::Kind::BoundGenericClass:
    return true;
  default:
    return false;
  }
  assert(0 && "unknown node kind");
}

bool swift::Demangle::isClass(llvm::StringRef mangledName) {
  Demangle::Demangler Dem;
  return isClassNode(Dem.demangleType(mangledName));
}

static bool isEnumNode(Demangle::NodePointer Node) {
  switch (Node->getKind()) {
  case Demangle::Node::Kind::Type:
    return isEnumNode(Node->getChild(0));
  case Demangle::Node::Kind::Enum:
  case Demangle::Node::Kind::BoundGenericEnum:
    return true;
  default:
    return false;
  }
  assert(0 && "unknown node kind");
}

bool swift::Demangle::isEnum(llvm::StringRef mangledName) {
  Demangle::Demangler Dem;
  return isEnumNode(Dem.demangleType(mangledName));
}

static bool isProtocolNode(Demangle::NodePointer Node) {
  switch (Node->getKind()) {
  case Demangle::Node::Kind::Type:
    return isProtocolNode(Node->getChild(0));
  case Demangle::Node::Kind::Protocol:
  case Demangle::Node::Kind::ProtocolSymbolicReference:
  case Demangle::Node::Kind::ObjectiveCProtocolSymbolicReference:
    return true;
  default:
    return false;
  }
  assert(0 && "unknown node kind");
}

bool swift::Demangle::isProtocol(llvm::StringRef mangledName) {
  Demangle::Demangler Dem;
  return isProtocolNode(Dem.demangleType(dropSwiftManglingPrefix(mangledName)));
}

static bool isStructNode(Demangle::NodePointer Node) {
  switch (Node->getKind()) {
  case Demangle::Node::Kind::Type:
    return isStructNode(Node->getChild(0));
  case Demangle::Node::Kind::Structure:
  case Demangle::Node::Kind::BoundGenericStructure:
    return true;
  default:
    return false;
  }
  assert(0 && "unknown node kind");
}

bool swift::Demangle::isStruct(llvm::StringRef mangledName) {
  Demangle::Demangler Dem;
  return isStructNode(Dem.demangleType(mangledName));
}

std::string swift::Demangle::mangledNameForTypeMetadataAccessor(
    StringRef moduleName, StringRef typeName, Node::Kind typeKind) {
  using namespace Demangle;

  //  kind=Global
  //    kind=NominalTypeDescriptor
  //      kind=Type
  //        kind=Structure|Enum|Class
  //          kind=Module, text=moduleName
  //          kind=Identifier, text=typeName
  Demangle::Demangler D;
  auto *global = D.createNode(Node::Kind::Global);
  {
    auto *nominalDescriptor =
        D.createNode(Node::Kind::TypeMetadataAccessFunction);
    {
      auto *type = D.createNode(Node::Kind::Type);
      {
        auto *module = D.createNode(Node::Kind::Module, moduleName);
        auto *identifier = D.createNode(Node::Kind::Identifier, typeName);
        auto *structNode = D.createNode(typeKind);
        structNode->addChild(module, D);
        structNode->addChild(identifier, D);
        type->addChild(structNode, D);
      }
      nominalDescriptor->addChild(type, D);
    }
    global->addChild(nominalDescriptor, D);
  }

  auto mangleResult = mangleNode(global);
  assert(mangleResult.isSuccess());
  return mangleResult.result();
}

using namespace swift;
using namespace Demangle;

//////////////////////////////////
// Node member functions        //
//////////////////////////////////

void Node::addChild(NodePointer Child, NodeFactory &Factory) {
  DEMANGLER_ALWAYS_ASSERT(Child, this);
  switch (NodePayloadKind) {
    case PayloadKind::None:
      InlineChildren[0] = Child;
      InlineChildren[1] = nullptr;
      NodePayloadKind = PayloadKind::OneChild;
      break;
    case PayloadKind::OneChild:
      assert(!InlineChildren[1]);
      InlineChildren[1] = Child;
      NodePayloadKind = PayloadKind::TwoChildren;
      break;
    case PayloadKind::TwoChildren: {
      NodePointer Child0 = InlineChildren[0];
      NodePointer Child1 = InlineChildren[1];
      Children.Nodes = nullptr;
      Children.Number = 0;
      Children.Capacity = 0;
      Factory.Reallocate(Children.Nodes, Children.Capacity, 3);
      assert(Children.Capacity >= 3);
      Children.Nodes[0] = Child0;
      Children.Nodes[1] = Child1;
      Children.Nodes[2] = Child;
      Children.Number = 3;
      NodePayloadKind = PayloadKind::ManyChildren;
      break;
    }
    case PayloadKind::ManyChildren:
      if (Children.Number >= Children.Capacity) {
        Factory.Reallocate(Children.Nodes, Children.Capacity, 1);
      }
      assert(Children.Number < Children.Capacity);
      Children.Nodes[Children.Number++] = Child;
      break;
    default:
      assert(false && "cannot add child");
  }
}

void Node::removeChildAt(unsigned Pos) {
  switch (NodePayloadKind) {
    case PayloadKind::OneChild:
      assert(Pos == 0);
      NodePayloadKind = PayloadKind::None;
      break;
    case PayloadKind::TwoChildren: {
      assert(Pos < 2);
      if (Pos == 0)
        InlineChildren[0] = InlineChildren[1];
      NodePayloadKind = PayloadKind::OneChild;
      break;
    }
    case PayloadKind::ManyChildren:
      for (unsigned i = Pos, n = Children.Number - 1; i != n; ++i) {
        Children.Nodes[i] = Children.Nodes[i + 1];
      }
      --Children.Number;
      break;
    default:
      assert(false && "cannot remove child");
  }
}

void Node::replaceChild(unsigned Pos, NodePointer Child) {
  switch (NodePayloadKind) {
    case PayloadKind::OneChild:
      assert(Pos == 0);
      InlineChildren[0] = Child;
      break;
    case PayloadKind::TwoChildren:
      assert(Pos < 2);
      InlineChildren[Pos] = Child;
      break;
    case PayloadKind::ManyChildren:
      Children.Nodes[Pos] = Child;
      break;
    default:
      assert(false && "cannot remove child");
  }
}

void Node::reverseChildren(size_t StartingAt) {
  assert(StartingAt <= getNumChildren());
  switch (NodePayloadKind) {
    case PayloadKind::TwoChildren:
      if (StartingAt == 0)
        std::swap(InlineChildren[0], InlineChildren[1]);
      break;
    case PayloadKind::ManyChildren:
      std::reverse(Children.Nodes + StartingAt,
                   Children.Nodes + Children.Number);
      break;
    default:
      break;
  }
}

Node* Node::findByKind(Node::Kind kind, int maxDepth) {
  if (getKind() == kind)
    return this;

  if (maxDepth <= 0)
    return nullptr;

  for (auto node : *this)
    if (auto matchingChild = node->findByKind(kind, maxDepth - 1))
      return matchingChild;

  return nullptr;
}

//////////////////////////////////
// NodeFactory member functions //
//////////////////////////////////

void NodeFactory::freeSlabs(Slab *slab) {
  while (slab) {
    Slab *prev = slab->Previous;
    free(slab);
    slab = prev;
  }
}
  
void NodeFactory::clear() {
  assert(!isBorrowed);
  if (CurrentSlab) {
#ifdef NODE_FACTORY_DEBUGGING
    fprintf(stderr, "%s## clear: allocated memory = %zu\n", indent().c_str(), allocatedMemory);
#endif

    freeSlabs(CurrentSlab->Previous);
    
    // Recycle the last allocated slab.
    // Note that the size of the last slab is at least as big as all previous
    // slabs combined. Therefore it's not worth the effort of reusing all slabs.
    // The slab size also stays the same. So at some point the demangling
    // process converges to a single large slab across repeated demangle-clear
    // cycles.
    CurrentSlab->Previous = nullptr;
    CurPtr = (char *)(CurrentSlab + 1);
#ifdef NODE_FACTORY_DEBUGGING
    allocatedMemory = 0;
#endif
  }
}

NodeFactory::Checkpoint NodeFactory::pushCheckpoint() const {
  return {CurrentSlab, CurPtr, End};
}

void NodeFactory::popCheckpoint(NodeFactory::Checkpoint checkpoint) {
  if (checkpoint.Slab == CurrentSlab) {
    if (checkpoint.CurPtr > CurPtr) {
      fatal(0,
            "Popping checkpoint {%p, %p, %p} that is after the current "
            "pointer.\n",
            checkpoint.Slab, checkpoint.CurPtr, checkpoint.End);
    }
    if (checkpoint.End != End) {
      fatal(0,
            "Popping checkpoint {%p, %p, %p} with End that does not match "
            "current End %p.\n",
            checkpoint.Slab, checkpoint.CurPtr, checkpoint.End, End);
    }
#ifndef NDEBUG
    // Scribble the newly freed area.
    memset(checkpoint.CurPtr, 0xaa, CurPtr - checkpoint.CurPtr);
#endif
    CurPtr = checkpoint.CurPtr;
  } else {
    // We may want to keep using the current slab rather than destroying
    // it, since over time this allows us to converge on a steady state
    // with no allocation activity (see the comment above in
    // NodeFactory::clear). Keep using the current slab if the free space in the
    // checkpoint's slab is less than 1/16th of the current slab's space. We
    // won't repeatedly allocate and deallocate the current slab. The size
    // doubles each time so we'll quickly pass the threshold.
    Slab *savedSlab = nullptr;
    if (CurrentSlab) {
      size_t checkpointSlabFreeSpace = checkpoint.End - checkpoint.CurPtr;
      size_t currentSlabSize = End - (char *)(CurrentSlab + 1);
      if (currentSlabSize / 16 > checkpointSlabFreeSpace) {
        savedSlab = CurrentSlab;
        CurrentSlab = CurrentSlab->Previous;
        // No need to save End, as it will still be in place later.
      }
    }

    // Free all slabs (possibly except the one we saved) until we find the end
    // or we find the checkpoint.
    while (CurrentSlab && checkpoint.Slab != CurrentSlab) {
      auto Slab = CurrentSlab;
      CurrentSlab = CurrentSlab->Previous;
      free(Slab);
    }

    // If we ran to the end and the checkpoint actually has a slab pointer, then
    // the checkpoint is invalid.
    if (!CurrentSlab && checkpoint.Slab) {
      fatal(0,
            "Popping checkpoint {%p, %p, %p} with slab that is not within "
            "the allocator's slab chain.\n",
            checkpoint.Slab, checkpoint.CurPtr, checkpoint.End);
    }

    if (savedSlab) {
      // Reinstall the saved slab.
      savedSlab->Previous = CurrentSlab;
      CurrentSlab = savedSlab;
      CurPtr = (char *)(CurrentSlab + 1);
      // End is still valid from before.
    } else {
      // Set CurPtr and End to match the checkpoint's position.
      CurPtr = checkpoint.CurPtr;
      End = checkpoint.End;
    }

#ifndef NDEBUG
    // Scribble the now freed end of the slab.
    if (CurPtr)
      memset(CurPtr, 0xaa, End - CurPtr);
#endif
  }
}

NodePointer NodeFactory::createNode(Node::Kind K) {
  return new (Allocate<Node>()) Node(K);
}
NodePointer NodeFactory::createNode(Node::Kind K, Node::IndexType Index) {
  return new (Allocate<Node>()) Node(K, Index);
}
NodePointer NodeFactory::createNodeWithAllocatedText(Node::Kind K,
                                                     llvm::StringRef Text) {
  return new (Allocate<Node>()) Node(K, Text);
}
NodePointer NodeFactory::createNode(Node::Kind K, const CharVector &Text) {
  return createNodeWithAllocatedText(K, Text.str());
}
NodePointer NodeFactory::createNode(Node::Kind K, const char *Text) {
  return new (Allocate<Node>()) Node(K, llvm::StringRef(Text));
}

#ifdef NODE_FACTORY_DEBUGGING
int NodeFactory::nestingLevel = 0;
#endif

// Fast integer formatting
namespace {

// Format an unsigned integer into a buffer
template <typename U,
          typename std::enable_if<std::is_unsigned<U>::value, bool>::type = true>
size_t int2str(U n, char *buf) {
  // The easy case is zero
  if (n == 0) {
    *buf++ = '0';
    *buf++ = '\0';
    return 1;
  }

  // Do the digits one a time (for really high speed we could do these in
  // chunks, but that's probably not necessary here.)
  char *ptr = buf;
  while (n) {
    char digit = '0' + (n % 10);
    n /= 10;
    *ptr++ = digit;
  }
  size_t len = ptr - buf;

  // Terminate the string
  *ptr = '\0';

  // Now reverse the digits
  while (buf < ptr) {
    char tmp = *--ptr;
    *ptr = *buf;
    *buf++ = tmp;
  }

  return len;
}

// Deal with negative numbers
template <typename S,
          typename std::enable_if<std::is_signed<S>::value, bool>::type = true>
size_t int2str(S n, char *buf) {
  using U = typename std::make_unsigned<S>::type;

  if (n < 0) {
    *buf++ = '-';
    return int2str(static_cast<U>(-n), buf);
  }
  return int2str(static_cast<U>(n), buf);
}

} // namespace

//////////////////////////////////
// CharVector member functions  //
//////////////////////////////////

void CharVector::append(StringRef Rhs, NodeFactory &Factory) {
  if (NumElems + Rhs.size() > Capacity)
    Factory.Reallocate(Elems, Capacity, /*Growth*/ Rhs.size());
  memcpy(Elems + NumElems, Rhs.data(), Rhs.size());
  NumElems += Rhs.size();
  assert(NumElems <= Capacity);
}

void CharVector::append(int Number, NodeFactory &Factory) {
  const int MaxIntPrintSize = 11;
  if (NumElems + MaxIntPrintSize > Capacity)
    Factory.Reallocate(Elems, Capacity, /*Growth*/ MaxIntPrintSize);
  int Length = int2str(Number, Elems + NumElems);
  assert(Length > 0 && Length < MaxIntPrintSize);
  NumElems += Length;
}

void CharVector::append(unsigned long long Number, NodeFactory &Factory) {
  const int MaxPrintSize = 21;
  if (NumElems + MaxPrintSize > Capacity)
    Factory.Reallocate(Elems, Capacity, /*Growth*/ MaxPrintSize);
  int Length = int2str(Number, Elems + NumElems);
  assert(Length > 0 && Length < MaxPrintSize);
  NumElems += Length;
}

//////////////////////////////////
// Demangler member functions   //
//////////////////////////////////

void Demangler::clear() {
  NodeStack.free();
  Substitutions.free();
  NodeFactory::clear();
}

Demangler::DemangleInitRAII::DemangleInitRAII(Demangler &Dem,
        StringRef MangledName,
        std::function<SymbolicReferenceResolver_t> TheSymbolicReferenceResolver)
// Save the current demangler state so we can restore it.
  : Dem(Dem),
    NodeStack(Dem.NodeStack), Substitutions(Dem.Substitutions),
    NumWords(Dem.NumWords), Text(Dem.Text), Pos(Dem.Pos),
    SymbolicReferenceResolver(std::move(Dem.SymbolicReferenceResolver))
{
  // Reset the demangler state for a nested job.
  Dem.NodeStack.init(Dem, 16);
  Dem.Substitutions.init(Dem, 16);
  Dem.NumWords = 0;
  Dem.Text = MangledName;
  Dem.Pos = 0;
  Dem.SymbolicReferenceResolver = std::move(TheSymbolicReferenceResolver);
}

Demangler::DemangleInitRAII::~DemangleInitRAII() {
  // Restore the saved state.
  Dem.NodeStack = NodeStack;
  Dem.Substitutions = Substitutions;
  Dem.NumWords = NumWords;
  Dem.Text = Text;
  Dem.Pos = Pos;
  Dem.SymbolicReferenceResolver = std::move(SymbolicReferenceResolver);
}

NodePointer Demangler::demangleSymbol(StringRef MangledName,
        std::function<SymbolicReferenceResolver_t> Resolver) {
  DemangleInitRAII state(*this, MangledName, std::move(Resolver));

#if SWIFT_SUPPORT_OLD_MANGLING
  // Demangle old-style class and protocol names, which are still used in the
  // ObjC metadata.
  if (nextIf("_Tt"))
    return demangleOldSymbolAsNode(Text, *this);
#endif

  unsigned PrefixLength = getManglingPrefixLength(MangledName);
  if (PrefixLength == 0)
    return nullptr;

  IsOldFunctionTypeMangling = isOldFunctionTypeMangling(MangledName);
  Pos += PrefixLength;

  // If any other prefixes are accepted, please update Mangler::verify.

  if (!parseAndPushNodes())
    return nullptr;

  NodePointer topLevel = createNode(Node::Kind::Global);

  NodePointer Parent = topLevel;
  while (NodePointer FuncAttr = popNode(isFunctionAttr)) {
    Parent->addChild(FuncAttr, *this);
    if (FuncAttr->getKind() == Node::Kind::PartialApplyForwarder ||
        FuncAttr->getKind() == Node::Kind::PartialApplyObjCForwarder)
      Parent = FuncAttr;
  }
  for (Node *Nd : NodeStack) {
    switch (Nd->getKind()) {
      case Node::Kind::Type:
        Parent->addChild(Nd->getFirstChild(), *this);
        break;
      default:
        Parent->addChild(Nd, *this);
        break;
    }
  }
  if (topLevel->getNumChildren() == 0)
    return nullptr;

  return topLevel;
}

NodePointer Demangler::demangleType(StringRef MangledName,
        std::function<SymbolicReferenceResolver_t> Resolver) {
  DemangleInitRAII state(*this, MangledName, std::move(Resolver));

  parseAndPushNodes();

  if (NodePointer Result = popNode())
    return Result;

  return createNode(Node::Kind::Suffix, Text);
}

bool Demangler::parseAndPushNodes() {
  const auto textSize = Text.size();
  while (Pos < textSize) {
    NodePointer Node = demangleOperator();
    if (!Node)
      return false;
    pushNode(Node);
  }
  return true;
}

NodePointer Demangler::addChild(NodePointer Parent, NodePointer Child) {
  if (!Parent || !Child)
    return nullptr;
  Parent->addChild(Child, *this);
  return Parent;
}

NodePointer Demangler::createWithChild(Node::Kind kind,
                                            NodePointer Child) {
  if (!Child)
    return nullptr;
  NodePointer Nd = createNode(kind);
  Nd->addChild(Child, *this);
  return Nd;
}

NodePointer Demangler::createType(NodePointer Child) {
  return createWithChild(Node::Kind::Type, Child);
}

NodePointer Demangler::Demangler::createWithChildren(Node::Kind kind,
                                       NodePointer Child1, NodePointer Child2) {
  if (!Child1 || !Child2)
    return nullptr;
  NodePointer Nd = createNode(kind);
  Nd->addChild(Child1, *this);
  Nd->addChild(Child2, *this);
  return Nd;
}

NodePointer Demangler::createWithChildren(Node::Kind kind,
                                               NodePointer Child1,
                                               NodePointer Child2,
                                               NodePointer Child3) {
  if (!Child1 || !Child2 || !Child3)
    return nullptr;
  NodePointer Nd = createNode(kind);
  Nd->addChild(Child1, *this);
  Nd->addChild(Child2, *this);
  Nd->addChild(Child3, *this);
  return Nd;
}

NodePointer Demangler::createWithChildren(Node::Kind kind, NodePointer Child1,
                                          NodePointer Child2,
                                          NodePointer Child3,
                                          NodePointer Child4) {
  if (!Child1 || !Child2 || !Child3 || !Child4)
    return nullptr;
  NodePointer Nd = createNode(kind);
  Nd->addChild(Child1, *this);
  Nd->addChild(Child2, *this);
  Nd->addChild(Child3, *this);
  Nd->addChild(Child4, *this);
  return Nd;
}

NodePointer Demangler::changeKind(NodePointer Node, Node::Kind NewKind) {
  if (!Node)
    return nullptr;
  NodePointer NewNode = nullptr;
  if (Node->hasText()) {
    NewNode = createNodeWithAllocatedText(NewKind, Node->getText());
  } else if (Node->hasIndex()) {
    NewNode = createNode(NewKind, Node->getIndex());
  } else {
    NewNode = createNode(NewKind);
  }
  for (NodePointer Child : *Node) {
    NewNode->addChild(Child, *this);
  }
  return NewNode;
}

NodePointer Demangler::demangleTypeMangling() {
  auto Type = popNode(Node::Kind::Type);
  auto LabelList = popFunctionParamLabels(Type);
  auto TypeMangling = createNode(Node::Kind::TypeMangling);

  addChild(TypeMangling, LabelList);
  TypeMangling = addChild(TypeMangling, Type);
  return TypeMangling;
}

NodePointer Demangler::demangleSymbolicReference(unsigned char rawKind) {
  // The symbolic reference is a 4-byte machine integer encoded in the following
  // four bytes.
  if (Pos + 4 > Text.size())
    return nullptr;
  const void *at = Text.data() + Pos;
  int32_t value;
  memcpy(&value, at, 4);
  Pos += 4;
  
  // Map the encoded kind to a specific kind and directness.
  SymbolicReferenceKind kind;
  Directness direct;
  switch (rawKind) {
  case 0x01:
    kind = SymbolicReferenceKind::Context;
    direct = Directness::Direct;
    break;
  case 0x02:
    kind = SymbolicReferenceKind::Context;
    direct = Directness::Indirect;
    break;
  case 0x09:
    kind = SymbolicReferenceKind::AccessorFunctionReference;
    direct = Directness::Direct;
    break;
  case 0x0a:
    kind = SymbolicReferenceKind::UniqueExtendedExistentialTypeShape;
    direct = Directness::Direct;
    break;
  case 0x0b:
    kind = SymbolicReferenceKind::NonUniqueExtendedExistentialTypeShape;
    direct = Directness::Direct;
    break;
  case 0x0c:
    kind = SymbolicReferenceKind::ObjectiveCProtocol;
    direct = Directness::Direct;
    break;
  // These are all currently reserved but unused.
  case 0x03: // direct to protocol conformance descriptor
  case 0x04: // indirect to protocol conformance descriptor
  case 0x05: // direct to associated conformance descriptor
  case 0x06: // indirect to associated conformance descriptor
  case 0x07: // direct to associated conformance access function
  case 0x08: // indirect to associated conformance access function
  default:
    return nullptr;
  }
  
  // Use the resolver, if any, to produce the demangling tree the symbolic
  // reference represents.
  NodePointer resolved = nullptr;
  if (SymbolicReferenceResolver)
    resolved = SymbolicReferenceResolver(kind, direct, value, at);

  // With no resolver, or a resolver that failed, refuse to demangle further.
  if (!resolved)
    return nullptr;
  
  // Types register as substitutions even when symbolically referenced.
  // OOPS: Except for opaque type references!
  if ((kind == SymbolicReferenceKind::Context ||
       kind == SymbolicReferenceKind::ObjectiveCProtocol) &&
      resolved->getKind() !=
          Node::Kind::OpaqueTypeDescriptorSymbolicReference &&
      resolved->getKind() != Node::Kind::OpaqueReturnTypeOf)
    addSubstitution(resolved);
  return resolved;
}

NodePointer Demangler::demangleTypeAnnotation() {
  switch (char c2 = nextChar()) {
  case 'a':
    return createNode(Node::Kind::AsyncAnnotation);
  case 'A':
    return createNode(Node::Kind::IsolatedAnyFunctionType);
  case 'b':
    return createNode(Node::Kind::ConcurrentFunctionType);
  case 'c':
    return createWithChild(
        Node::Kind::GlobalActorFunctionType, popTypeAndGetChild());
  case 'i':
    return createType(
        createWithChild(Node::Kind::Isolated, popTypeAndGetChild()));
  case 'j':
    return demangleDifferentiableFunctionType();
  case 'k':
    return createType(
        createWithChild(Node::Kind::NoDerivative, popTypeAndGetChild()));
  case 'K':
    return createWithChild(Node::Kind::TypedThrowsAnnotation, popTypeAndGetChild());
  case 't':
    return createType(
        createWithChild(Node::Kind::CompileTimeConst, popTypeAndGetChild()));
  case 'T':
    return createNode(Node::Kind::SendingResultFunctionType);
  case 'u':
    return createType(
        createWithChild(Node::Kind::Sending, popTypeAndGetChild()));
  case 'l':
    return demangleLifetimeDependenceKind(/*isSelfDependence*/ false);
  case 'L':
    return demangleLifetimeDependenceKind(/*isSelfDependence*/ true);
  default:
    return nullptr;
  }
}

NodePointer Demangler::demangleOperator() {
recur:
  switch (unsigned char c = nextChar()) {
    case 0xFF:
      // A 0xFF byte is used as alignment padding for symbolic references
      // when the platform toolchain has alignment restrictions for the
      // relocations that form the reference value. It can be skipped.
      goto recur;
    case 1: case 2:   case 3:   case 4:   case 5: case 6: case 7: case 8:
    case 9: case 0xA: case 0xB: case 0xC:
      return demangleSymbolicReference((unsigned char)c);
    case 'A': return demangleMultiSubstitutions();
    case 'B': return demangleBuiltinType();
    case 'C': return demangleAnyGenericType(Node::Kind::Class);
    case 'D': return demangleTypeMangling();
    case 'E': return demangleExtensionContext();
    case 'F': return demanglePlainFunction();
    case 'G': return demangleBoundGenericType();
    case 'H':
      switch (char c2 = nextChar()) {
      case 'A': return demangleDependentProtocolConformanceAssociated();
      case 'C': return demangleConcreteProtocolConformance();
      case 'D': return demangleDependentProtocolConformanceRoot();
      case 'I': return demangleDependentProtocolConformanceInherited();
      case 'P':
        return createWithChild(
            Node::Kind::ProtocolConformanceRefInTypeModule, popProtocol());
      case 'p':
        return createWithChild(
            Node::Kind::ProtocolConformanceRefInProtocolModule, popProtocol());
      case 'X': return demanglePackProtocolConformance();

      // Runtime records (type/protocol/conformance/function)
      case 'c':
        return createWithChild(Node::Kind::ProtocolConformanceDescriptorRecord,
                               popProtocolConformance());
      case 'n':
        return createWithPoppedType(Node::Kind::NominalTypeDescriptorRecord);
      case 'o': // XXX
        return createWithChild(Node::Kind::OpaqueTypeDescriptorRecord, popNode());
      case 'r':
        return createWithChild(Node::Kind::ProtocolDescriptorRecord, popProtocol());
      case 'F':
        return createNode(Node::Kind::AccessibleFunctionRecord);

      default:
        pushBack();
        pushBack();
        return demangleIdentifier();
      }

    case 'I': return demangleImplFunctionType();
    case 'K': return createNode(Node::Kind::ThrowsAnnotation);
    case 'L': return demangleLocalIdentifier();
    case 'M': return demangleMetatype();
    case 'N': return createWithChild(Node::Kind::TypeMetadata,
                                     popNode(Node::Kind::Type));
    case 'O': return demangleAnyGenericType(Node::Kind::Enum);
    case 'P': return demangleAnyGenericType(Node::Kind::Protocol);
    case 'Q': return demangleArchetype();
    case 'R': return demangleGenericRequirement();
    case 'S': return demangleStandardSubstitution();
    case 'T': return demangleThunkOrSpecialization();
    case 'V': return demangleAnyGenericType(Node::Kind::Structure);
    case 'W': return demangleWitness();
    case 'X': return demangleSpecialType();
    case 'Y': return demangleTypeAnnotation();
    case 'Z': return createWithChild(Node::Kind::Static, popNode(isEntity));
    case 'a': return demangleAnyGenericType(Node::Kind::TypeAlias);
    case 'c': return popFunctionType(Node::Kind::FunctionType);
    case 'd': return createNode(Node::Kind::VariadicMarker);
    case 'f': return demangleFunctionEntity();
    case 'g': return demangleRetroactiveConformance();
    case 'h': return createType(createWithChild(Node::Kind::Shared,
                                                popTypeAndGetChild()));
    case 'i': return demangleSubscript();
    case 'l': return demangleGenericSignature(/*hasParamCounts*/ false);
    case 'm': return createType(createWithChild(Node::Kind::Metatype,
                                                popNode(Node::Kind::Type)));
    case 'n':
      return createType(
          createWithChild(Node::Kind::Owned, popTypeAndGetChild()));
    case 'o': return demangleOperatorIdentifier();
    case 'p': return demangleProtocolListType();
    case 'q': return createType(demangleGenericParamIndex());
    case 'r': return demangleGenericSignature(/*hasParamCounts*/ true);
    case 's': return createNode(Node::Kind::Module, STDLIB_NAME);
    case 't': return popTuple();
    case 'u': return demangleGenericType();
    case 'v': return demangleVariable();
    case 'w': return demangleValueWitness();
    case 'x': return createType(getDependentGenericParamType(0, 0));
    case 'y': return createNode(Node::Kind::EmptyList);
    case 'z': return createType(createWithChild(Node::Kind::InOut,
                                                popTypeAndGetChild()));
    case '_': return createNode(Node::Kind::FirstElementMarker);
    case '.':
      // IRGen still uses '.<n>' to disambiguate partial apply thunks and
      // outlined copy functions. We treat such a suffix as "unmangled suffix".
      pushBack();
      return createNode(Node::Kind::Suffix, consumeAll());
    default:
      pushBack();
      return demangleIdentifier();
  }
}

int Demangler::demangleNatural() {
  if (!isDigit(peekChar()))
    return -1000;
  int num = 0;
  while (true) {
    char c = peekChar();
    if (!isDigit(c))
      return num;
    int newNum = (10 * num) + (c - '0');
    if (newNum < num)
      return -1000;
    num = newNum;
    nextChar();
  }
}

int Demangler::demangleIndex() {
  if (nextIf('_'))
    return 0;
  int num = demangleNatural();
  if (num >= 0 && nextIf('_'))
    return num + 1;
  return -1000;
}

NodePointer Demangler::demangleIndexAsNode() {
  int Idx = demangleIndex();
  if (Idx >= 0)
    return createNode(Node::Kind::Number, Idx);
  return nullptr;
}

NodePointer Demangler::demangleMultiSubstitutions() {
  int RepeatCount = -1;
  while (true) {
    char c = nextChar();
    if (c == 0) {
      // End of text.
      return nullptr;
    }
    if (isLowerLetter(c)) {
      // It's a substitution with an index < 26.
      NodePointer Nd = pushMultiSubstitutions(RepeatCount, c - 'a');
      if (!Nd)
        return nullptr;
      pushNode(Nd);
      RepeatCount = -1;
      // A lowercase letter indicates that there are more substitutions to
      // follow.
      continue;
    }
    if (isUpperLetter(c)) {
      // The last substitution.
      return pushMultiSubstitutions(RepeatCount, c - 'A');
    }
    if (c == '_') {
      // The previously demangled number is actually not a repeat count but
      // the large (> 26) index of a substitution. Because it's an index we
      // have to add 27 and not 26.
      unsigned Idx = RepeatCount + 27;
      if (Idx >= Substitutions.size())
        return nullptr;
      return Substitutions[Idx];
    }
    pushBack();
    // Not a letter? Then it can only be a natural number which might be the
    // repeat count or a large (> 26) substitution index.
    RepeatCount = demangleNatural();
    if (RepeatCount < 0)
      return nullptr;
  }
}

NodePointer Demangler::pushMultiSubstitutions(int RepeatCount,
                                              size_t SubstIdx) {
  if (SubstIdx >= Substitutions.size())
    return nullptr;
  if (RepeatCount > SubstitutionMerging::MaxRepeatCount)
    return nullptr;
  NodePointer Nd = Substitutions[SubstIdx];
  while (RepeatCount-- > 1) {
    pushNode(Nd);
  }
  return Nd;
}

NodePointer Demangler::createSwiftType(Node::Kind typeKind, const char *name) {
  return createType(createWithChildren(typeKind,
    createNode(Node::Kind::Module, STDLIB_NAME),
    createNode(Node::Kind::Identifier, name)));
}

NodePointer Demangler::demangleStandardSubstitution() {
  switch (char c = nextChar()) {
    case 'o':
      return createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
    case 'C':
      return createNode(Node::Kind::Module, MANGLING_MODULE_CLANG_IMPORTER);
    case 'g': {
      NodePointer OptionalTy =
        createType(createWithChildren(Node::Kind::BoundGenericEnum,
          createSwiftType(Node::Kind::Enum, "Optional"),
          createWithChild(Node::Kind::TypeList, popNode(Node::Kind::Type))));
      addSubstitution(OptionalTy);
      return OptionalTy;
    }
    default: {
      pushBack();
      int RepeatCount = demangleNatural();
      if (RepeatCount > SubstitutionMerging::MaxRepeatCount)
        return nullptr;
      bool secondLevelSubstitution = nextIf('c');
      if (NodePointer Nd = createStandardSubstitution(
              nextChar(), secondLevelSubstitution)) {
        while (RepeatCount-- > 1) {
          pushNode(Nd);
        }
        return Nd;
      }
      return nullptr;
    }
  }
}

NodePointer Demangler::createStandardSubstitution(
    char Subst, bool SecondLevel) {
#define STANDARD_TYPE(KIND, MANGLING, TYPENAME)                   \
  if (!SecondLevel && Subst == #MANGLING[0]) {                    \
    return createSwiftType(Node::Kind::KIND, #TYPENAME);          \
  }

#define STANDARD_TYPE_CONCURRENCY(KIND, MANGLING, TYPENAME)                   \
  if (SecondLevel && Subst == #MANGLING[0]) {                    \
    return createSwiftType(Node::Kind::KIND, #TYPENAME);          \
  }

#include "swift/Demangling/StandardTypesMangling.def"
  return nullptr;
}

NodePointer Demangler::demangleIdentifier() {
  bool hasWordSubsts = false;
  bool isPunycoded = false;
  char c = peekChar();
  if (!isDigit(c))
    return nullptr;
  if (c == '0') {
    nextChar();
    if (peekChar() == '0') {
      nextChar();
      isPunycoded = true;
    } else {
      hasWordSubsts = true;
    }
  }
  CharVector Identifier;
  do {
    while (hasWordSubsts && isLetter(peekChar())) {
      char c = nextChar();
      int WordIdx = 0;
      if (isLowerLetter(c)) {
        WordIdx = c - 'a';
      } else {
        assert(isUpperLetter(c));
        WordIdx = c - 'A';
        hasWordSubsts = false;
      }
      if (WordIdx >= NumWords)
        return nullptr;
      assert(WordIdx < MaxNumWords);
      StringRef Slice = Words[WordIdx];
      Identifier.append(Slice, *this);
    }
    if (nextIf('0'))
      break;
    int numChars = demangleNatural();
    if (numChars <= 0)
      return nullptr;
    if (isPunycoded)
      nextIf('_');
    if (Pos + numChars > Text.size())
      return nullptr;
    StringRef Slice = StringRef(Text.data() + Pos, numChars);
    if (isPunycoded) {
      std::string PunycodedString;
      if (!Punycode::decodePunycodeUTF8(Slice, PunycodedString))
        return nullptr;
      Identifier.append(StringRef(PunycodedString), *this);
    } else {
      Identifier.append(Slice, *this);
      int wordStartPos = -1;
      for (int Idx = 0, End = (int)Slice.size(); Idx <= End; ++Idx) {
        char c = (Idx < End ? Slice[Idx] : 0);
        if (wordStartPos >= 0 && isWordEnd(c, Slice[Idx - 1])) {
          if (Idx - wordStartPos >= 2 && NumWords < MaxNumWords) {
            StringRef word(Slice.begin() + wordStartPos, Idx - wordStartPos);
            Words[NumWords++] = word;
          }
          wordStartPos = -1;
        }
        if (wordStartPos < 0 && isWordStart(c)) {
          wordStartPos = Idx;
        }
      }
    }
    Pos += numChars;
  } while (hasWordSubsts);

  if (Identifier.empty())
    return nullptr;
  NodePointer Ident = createNode(Node::Kind::Identifier, Identifier);
  addSubstitution(Ident);
  return Ident;
}

NodePointer Demangler::demangleOperatorIdentifier() {
  NodePointer Ident = popNode(Node::Kind::Identifier);
  if (!Ident)
    return nullptr;

  static const char op_char_table[] = "& @/= >    <*!|+?%-~   ^ .";

  CharVector OpStr;
  for (signed char c : Ident->getText()) {
    if (c < 0) {
      // Pass through Unicode characters.
      OpStr.push_back(c, *this);
      continue;
    }
    if (!isLowerLetter(c))
      return nullptr;
    char o = op_char_table[c - 'a'];
    if (o == ' ')
      return nullptr;
    OpStr.push_back(o, *this);
  }
  switch (nextChar()) {
    case 'i': return createNode(Node::Kind::InfixOperator, OpStr);
    case 'p': return createNode(Node::Kind::PrefixOperator, OpStr);
    case 'P': return createNode(Node::Kind::PostfixOperator, OpStr);
    default: return nullptr;
  }
}

NodePointer Demangler::demangleLocalIdentifier() {
  if (nextIf('L')) {
    NodePointer discriminator = popNode(Node::Kind::Identifier);
    NodePointer name = popNode(isDeclName);
    return createWithChildren(Node::Kind::PrivateDeclName, discriminator, name);
  }
  if (nextIf('l')) {
    NodePointer discriminator = popNode(Node::Kind::Identifier);
    return createWithChild(Node::Kind::PrivateDeclName, discriminator);
  }
  if ((peekChar() >= 'a' && peekChar() <= 'j') ||
      (peekChar() >= 'A' && peekChar() <= 'J')) {
    char relatedEntityKind = nextChar();
    NodePointer kindNd = createNode(Node::Kind::Identifier,
                                    StringRef(&relatedEntityKind, 1));
    NodePointer name = popNode();
    NodePointer result = createNode(Node::Kind::RelatedEntityDeclName);
    addChild(result, kindNd);
    return addChild(result, name);
  }
  NodePointer discriminator = demangleIndexAsNode();
  NodePointer name = popNode(isDeclName);
  return createWithChildren(Node::Kind::LocalDeclName, discriminator, name);
}

NodePointer Demangler::popModule() {
  if (NodePointer Ident = popNode(Node::Kind::Identifier))
    return changeKind(Ident, Node::Kind::Module);
  return popNode(Node::Kind::Module);
}

NodePointer Demangler::popContext() {
  if (NodePointer Mod = popModule())
    return Mod;

  if (NodePointer Ty = popNode(Node::Kind::Type)) {
    if (Ty->getNumChildren() != 1)
      return nullptr;
    NodePointer Child = Ty->getFirstChild();
    if (!isContext(Child->getKind()))
      return nullptr;
    return Child;
  }
  return popNode(isContext);
}

NodePointer Demangler::popTypeAndGetChild() {
  NodePointer Ty = popNode(Node::Kind::Type);
  if (!Ty || Ty->getNumChildren() != 1)
    return nullptr;
  return Ty->getFirstChild();
}

NodePointer Demangler::popTypeAndGetAnyGeneric() {
  NodePointer Child = popTypeAndGetChild();
  if (Child && isAnyGeneric(Child->getKind()))
    return Child;
  return nullptr;
}

NodePointer Demangler::demangleBuiltinType() {
  NodePointer Ty = nullptr;
  const int maxTypeSize = 4096; // a very conservative upper bound
  switch (nextChar()) {
    case 'b':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_BRIDGEOBJECT);
      break;
    case 'B':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                              BUILTIN_TYPE_NAME_UNSAFEVALUEBUFFER);
      break;
    case 'e':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                              BUILTIN_TYPE_NAME_EXECUTOR);
      break;
    case 'f': {
      int size = demangleIndex() - 1;
      if (size <= 0 || size > maxTypeSize)
        return nullptr;
      CharVector name;
      name.append(BUILTIN_TYPE_NAME_FLOAT, *this);
      name.append(size, *this);
      Ty = createNode(Node::Kind::BuiltinTypeName, name);
      break;
    }
    case 'i': {
      int size = demangleIndex() - 1;
      if (size <= 0 || size > maxTypeSize)
        return nullptr;
      CharVector name;
      name.append(BUILTIN_TYPE_NAME_INT, *this);
      name.append(size, *this);
      Ty = createNode(Node::Kind::BuiltinTypeName, name);
      break;
    }
    case 'I':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                      BUILTIN_TYPE_NAME_INTLITERAL);
      break;
    case 'v': {
      int elts = demangleIndex() - 1;
      if (elts <= 0 || elts > maxTypeSize)
        return nullptr;
      NodePointer EltType = popTypeAndGetChild();
      if (!EltType || EltType->getKind() != Node::Kind::BuiltinTypeName ||
          !EltType->getText().starts_with(BUILTIN_TYPE_NAME_PREFIX))
        return nullptr;
      CharVector name;
      name.append(BUILTIN_TYPE_NAME_VEC, *this);
      name.append(elts, *this);
      name.push_back('x', *this);
      name.append(EltType->getText().substr(BUILTIN_TYPE_NAME_PREFIX.size()),
                  *this);
      Ty = createNode(Node::Kind::BuiltinTypeName, name);
      break;
    }
    case 'O':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_UNKNOWNOBJECT);
      break;
    case 'o':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_NATIVEOBJECT);
      break;
    case 'p':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_RAWPOINTER);
      break;
    case 'j':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_JOB);
      break;
    case 'D':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_DEFAULTACTORSTORAGE);
      break;
    case 'd':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_NONDEFAULTDISTRIBUTEDACTORSTORAGE);
      break;
    case 'c':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_RAWUNSAFECONTINUATION);
      break;
    case 't':
      Ty = createNode(Node::Kind::BuiltinTypeName, BUILTIN_TYPE_NAME_SILTOKEN);
      break;
    case 'w':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_WORD);
      break;
    case 'P':
      Ty = createNode(Node::Kind::BuiltinTypeName,
                               BUILTIN_TYPE_NAME_PACKINDEX);
      break;
    case 'T':
      Ty = createNode(Node::Kind::BuiltinTupleType);
      break;
    default:
      return nullptr;
  }
  return createType(Ty);
}

NodePointer Demangler::demangleAnyGenericType(Node::Kind kind) {
  NodePointer Name = popNode(isDeclName);
  NodePointer Ctx = popContext();
  NodePointer NTy = createType(createWithChildren(kind, Ctx, Name));
  addSubstitution(NTy);
  return NTy;
}

NodePointer Demangler::demangleExtensionContext() {
  NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
  NodePointer Module = popModule();
  NodePointer Type = popTypeAndGetAnyGeneric();
  NodePointer Ext = createWithChildren(Node::Kind::Extension, Module, Type);
  if (GenSig)
    Ext = addChild(Ext, GenSig);
  return Ext;
}

/// Associate any \c OpaqueReturnType nodes with the declaration whose opaque
/// return type they refer back to.
static Node *setParentForOpaqueReturnTypeNodes(Demangler &D,
                                              Node *parent,
                                              Node *visitedNode) {
  if (!parent || !visitedNode)
    return nullptr;
  if (visitedNode->getKind() == Node::Kind::OpaqueReturnType) {
    // If this node is not already parented, parent it.
    if (visitedNode->hasChildren()
        && visitedNode->getLastChild()->getKind() == Node::Kind::OpaqueReturnTypeParent) {
      return parent;
    }
    visitedNode->addChild(D.createNode(Node::Kind::OpaqueReturnTypeParent,
                                       (Node::IndexType)parent), D);
    return parent;
  }
  
  // If this node is one that may in turn define its own opaque return type,
  // stop recursion, since any opaque return type nodes underneath would refer
  // to the nested declaration rather than the one we're looking at.
  if (visitedNode->getKind() == Node::Kind::Function
      || visitedNode->getKind() == Node::Kind::Variable
      || visitedNode->getKind() == Node::Kind::Subscript) {
    return parent;
  }
  
  for (size_t i = 0, e = visitedNode->getNumChildren(); i < e; ++i) {
    setParentForOpaqueReturnTypeNodes(D, parent, visitedNode->getChild(i));
  }
  return parent;
}

NodePointer Demangler::demanglePlainFunction() {
  NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
  NodePointer Type = popFunctionType(Node::Kind::FunctionType);
  NodePointer LabelList = popFunctionParamLabels(Type);

  if (GenSig) {
    Type = createType(createWithChildren(Node::Kind::DependentGenericType,
                                         GenSig, Type));
  }

  auto Name = popNode(isDeclName);
  auto Ctx = popContext();

  NodePointer result = LabelList
    ? createWithChildren(Node::Kind::Function, Ctx, Name, LabelList, Type)
    : createWithChildren(Node::Kind::Function, Ctx, Name, Type);
    
  result = setParentForOpaqueReturnTypeNodes(*this, result, Type);
  return result;
}

NodePointer Demangler::popFunctionType(Node::Kind kind, bool hasClangType) {
  NodePointer FuncType = createNode(kind);
  NodePointer ClangType = nullptr;
  if (hasClangType) {
    ClangType = demangleClangType();
  }
  addChild(FuncType, ClangType);
  addChild(FuncType, popNode(Node::Kind::SelfLifetimeDependence));
  addChild(FuncType, popNode(Node::Kind::GlobalActorFunctionType));
  addChild(FuncType, popNode(Node::Kind::IsolatedAnyFunctionType));
  addChild(FuncType, popNode(Node::Kind::SendingResultFunctionType));
  addChild(FuncType, popNode(Node::Kind::DifferentiableFunctionType));
  addChild(FuncType, popNode([](Node::Kind kind) {
    return kind == Node::Kind::ThrowsAnnotation ||
      kind == Node::Kind::TypedThrowsAnnotation;
  }));
  addChild(FuncType, popNode(Node::Kind::ConcurrentFunctionType));
  addChild(FuncType, popNode(Node::Kind::AsyncAnnotation));

  FuncType = addChild(FuncType, popFunctionParams(Node::Kind::ArgumentTuple));
  FuncType = addChild(FuncType, popFunctionParams(Node::Kind::ReturnType));
  return createType(FuncType);
}

NodePointer Demangler::popFunctionParams(Node::Kind kind) {
  NodePointer ParamsType = nullptr;
  if (popNode(Node::Kind::EmptyList)) {
    ParamsType = createType(createNode(Node::Kind::Tuple));
  } else {
    ParamsType = popNode(Node::Kind::Type);
  }
  return createWithChild(kind, ParamsType);
}

NodePointer Demangler::popFunctionParamLabels(NodePointer Type) {
  if (!IsOldFunctionTypeMangling && popNode(Node::Kind::EmptyList))
    return createNode(Node::Kind::LabelList);

  if (!Type || Type->getKind() != Node::Kind::Type)
    return nullptr;

  auto FuncType = Type->getFirstChild();
  if (FuncType->getKind() == Node::Kind::DependentGenericType)
    FuncType = FuncType->getChild(1)->getFirstChild();

  if (FuncType->getKind() != Node::Kind::FunctionType &&
      FuncType->getKind() != Node::Kind::NoEscapeFunctionType)
    return nullptr;

  unsigned FirstChildIdx = 0;
  if (FuncType->getChild(FirstChildIdx)->getKind() ==
      Node::Kind::SelfLifetimeDependence)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::GlobalActorFunctionType)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::IsolatedAnyFunctionType)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind() ==
      Node::Kind::SendingResultFunctionType)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::DifferentiableFunctionType)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::ThrowsAnnotation ||
      FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::TypedThrowsAnnotation)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::ConcurrentFunctionType)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind()
        == Node::Kind::AsyncAnnotation)
    ++FirstChildIdx;
  if (FuncType->getChild(FirstChildIdx)->getKind() ==
      Node::Kind::ParamLifetimeDependence)
    ++FirstChildIdx;
  auto ParameterType = FuncType->getChild(FirstChildIdx);

  assert(ParameterType->getKind() == Node::Kind::ArgumentTuple);

  NodePointer ParamsType = ParameterType->getFirstChild();
  assert(ParamsType->getKind() == Node::Kind::Type);
  auto Params = ParamsType->getFirstChild();
  unsigned NumParams =
    Params->getKind() == Node::Kind::Tuple ? Params->getNumChildren() : 1;

  if (NumParams == 0)
    return nullptr;

  auto getChildIf =
      [](NodePointer Node,
         Node::Kind filterBy) -> std::pair<NodePointer, unsigned> {
    for (unsigned i = 0, n = Node->getNumChildren(); i != n; ++i) {
      auto Child = Node->getChild(i);
      if (Child->getKind() == filterBy)
        return {Child, i};
    }
    return {nullptr, 0};
  };

  auto getLabel = [&](NodePointer Params, unsigned Idx) -> NodePointer {
    // Old-style function type mangling has labels as part of the argument.
    if (IsOldFunctionTypeMangling) {
      auto Param = Params->getChild(Idx);
      auto Label = getChildIf(Param, Node::Kind::TupleElementName);

      if (Label.first) {
        Param->removeChildAt(Label.second);
        return createNodeWithAllocatedText(Node::Kind::Identifier,
                                           Label.first->getText());
      }

      return createNode(Node::Kind::FirstElementMarker);
    }

    return popNode();
  };

  auto LabelList = createNode(Node::Kind::LabelList);
  auto Tuple = ParameterType->getFirstChild()->getFirstChild();

  if (IsOldFunctionTypeMangling &&
      (!Tuple || Tuple->getKind() != Node::Kind::Tuple))
    return LabelList;

  bool hasLabels = false;
  for (unsigned i = 0; i != NumParams; ++i) {
    auto Label = getLabel(Tuple, i);

    if (!Label)
      return nullptr;

    if (Label->getKind() != Node::Kind::Identifier &&
        Label->getKind() != Node::Kind::FirstElementMarker)
      return nullptr;

    LabelList->addChild(Label, *this);
    hasLabels |= Label->getKind() != Node::Kind::FirstElementMarker;
  }

  // Old style label mangling can produce label list without
  // actual labels, we need to support that case specifically.
  if (!hasLabels)
    return createNode(Node::Kind::LabelList);

  if (!IsOldFunctionTypeMangling)
    LabelList->reverseChildren();

  return LabelList;
}

NodePointer Demangler::popTuple() {
  NodePointer Root = createNode(Node::Kind::Tuple);

  if (!popNode(Node::Kind::EmptyList)) {
    bool firstElem = false;
    do {
      firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
      NodePointer TupleElmt = createNode(Node::Kind::TupleElement);
      addChild(TupleElmt, popNode(Node::Kind::VariadicMarker));
      if (NodePointer Ident = popNode(Node::Kind::Identifier)) {
        TupleElmt->addChild(createNodeWithAllocatedText(
                              Node::Kind::TupleElementName, Ident->getText()),
                            *this);
      }
      NodePointer Ty = popNode(Node::Kind::Type);
      if (!Ty)
        return nullptr;
      TupleElmt->addChild(Ty, *this);
      Root->addChild(TupleElmt, *this);
    } while (!firstElem);

    Root->reverseChildren();
  }
  return createType(Root);
}

NodePointer Demangler::popPack() {
  NodePointer Root = createNode(Node::Kind::Pack);

  if (!popNode(Node::Kind::EmptyList)) {
    bool firstElem = false;
    do {
      firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
      NodePointer Ty = popNode(Node::Kind::Type);
      if (!Ty)
        return nullptr;
      Root->addChild(Ty, *this);
    } while (!firstElem);

    Root->reverseChildren();
  }
  return createType(Root);
}

NodePointer Demangler::popSILPack() {
  NodePointer Root;

  switch (nextChar()) {
  case 'd':
    Root = createNode(Node::Kind::SILPackDirect);
    break;

  case 'i':
    Root = createNode(Node::Kind::SILPackIndirect);
    break;

  default:
    return nullptr;
  }

  if (!popNode(Node::Kind::EmptyList)) {
    bool firstElem = false;
    do {
      firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
      NodePointer Ty = popNode(Node::Kind::Type);
      if (!Ty)
        return nullptr;
      Root->addChild(Ty, *this);
    } while (!firstElem);

    Root->reverseChildren();
  }

  return createType(Root);
}

NodePointer Demangler::popTypeList() {
  NodePointer Root = createNode(Node::Kind::TypeList);

  if (!popNode(Node::Kind::EmptyList)) {
    bool firstElem = false;
    do {
      firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
      NodePointer Ty = popNode(Node::Kind::Type);
      if (!Ty)
        return nullptr;
      Root->addChild(Ty, *this);
    } while (!firstElem);
    
    Root->reverseChildren();
  }
  return Root;
}

NodePointer Demangler::popProtocol() {
  if (NodePointer Type = popNode(Node::Kind::Type)) {
    if (Type->getNumChildren() < 1)
      return nullptr;

    if (!isProtocolNode(Type))
      return nullptr;

    return Type;
  }
  
  if (NodePointer SymbolicRef = popNode(Node::Kind::ProtocolSymbolicReference)){
    return SymbolicRef;
  } else if (NodePointer SymbolicRef =
                 popNode(Node::Kind::ObjectiveCProtocolSymbolicReference)) {
    return SymbolicRef;
  }

  NodePointer Name = popNode(isDeclName);
  NodePointer Ctx = popContext();
  NodePointer Proto = createWithChildren(Node::Kind::Protocol, Ctx, Name);
  return createType(Proto);
}

NodePointer Demangler::popAnyProtocolConformanceList() {
  NodePointer conformanceList
    = createNode(Node::Kind::AnyProtocolConformanceList);
  if (!popNode(Node::Kind::EmptyList)) {
    bool firstElem = false;
    do {
      firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
      NodePointer anyConformance = popAnyProtocolConformance();
      if (!anyConformance)
        return nullptr;
      conformanceList->addChild(anyConformance, *this);
    } while (!firstElem);

    conformanceList->reverseChildren();
  }
  return conformanceList;
}

NodePointer Demangler::popAnyProtocolConformance() {
  return popNode([](Node::Kind kind) {
    switch (kind) {
    case Node::Kind::ConcreteProtocolConformance:
    case Node::Kind::PackProtocolConformance:
    case Node::Kind::DependentProtocolConformanceRoot:
    case Node::Kind::DependentProtocolConformanceInherited:
    case Node::Kind::DependentProtocolConformanceAssociated:
      return true;

    default:
      return false;
    }
  });
}

NodePointer Demangler::demangleRetroactiveProtocolConformanceRef() {
  NodePointer module = popModule();
  NodePointer proto = popProtocol();
  auto protocolConformanceRef =
      createWithChildren(Node::Kind::ProtocolConformanceRefInOtherModule,
                         proto, module);
  return protocolConformanceRef;
}

NodePointer Demangler::demangleConcreteProtocolConformance() {
  NodePointer conditionalConformanceList = popAnyProtocolConformanceList();

  NodePointer conformanceRef =
      popNode(Node::Kind::ProtocolConformanceRefInTypeModule);
  if (!conformanceRef) {
    conformanceRef =
        popNode(Node::Kind::ProtocolConformanceRefInProtocolModule);
  }
  if (!conformanceRef)
    conformanceRef = demangleRetroactiveProtocolConformanceRef();

  NodePointer type = popNode(Node::Kind::Type);
  return createWithChildren(Node::Kind::ConcreteProtocolConformance,
                            type, conformanceRef, conditionalConformanceList);
}

NodePointer Demangler::demanglePackProtocolConformance() {
  NodePointer patternConformanceList = popAnyProtocolConformanceList();

  return createWithChild(Node::Kind::PackProtocolConformance,
                         patternConformanceList);
}

NodePointer Demangler::popDependentProtocolConformance() {
  return popNode([](Node::Kind kind) {
    switch (kind) {
    case Node::Kind::DependentProtocolConformanceRoot:
    case Node::Kind::DependentProtocolConformanceInherited:
    case Node::Kind::DependentProtocolConformanceAssociated:
      return true;

    default:
      return false;
    }
  });
}

NodePointer Demangler::demangleDependentProtocolConformanceRoot() {
  NodePointer index = demangleDependentConformanceIndex();
  NodePointer protocol = popProtocol();
  NodePointer dependentType = popNode(Node::Kind::Type);
  return createWithChildren(Node::Kind::DependentProtocolConformanceRoot,
                            dependentType, protocol, index);
}

NodePointer Demangler::demangleDependentProtocolConformanceInherited() {
  NodePointer index = demangleDependentConformanceIndex();
  NodePointer protocol = popProtocol();
  NodePointer nested = popDependentProtocolConformance();
  return createWithChildren(Node::Kind::DependentProtocolConformanceInherited,
                            nested, protocol, index);
}

NodePointer Demangler::popDependentAssociatedConformance() {
  NodePointer protocol = popProtocol();
  NodePointer dependentType = popNode(Node::Kind::Type);
  return createWithChildren(Node::Kind::DependentAssociatedConformance,
                            dependentType, protocol);
}

NodePointer Demangler::demangleDependentProtocolConformanceAssociated() {
  NodePointer index = demangleDependentConformanceIndex();
  NodePointer associatedConformance = popDependentAssociatedConformance();
  NodePointer nested = popDependentProtocolConformance();
  return createWithChildren(Node::Kind::DependentProtocolConformanceAssociated,
                            nested, associatedConformance, index);
}

NodePointer Demangler::demangleDependentConformanceIndex() {
  int index = demangleIndex();
  // index < 0 indicates a demangling error.
  // index == 0 is ill-formed by the (originally buggy) use of this production.
  if (index <= 0) return nullptr;

  // index == 1 indicates an unknown index.
  if (index == 1) return createNode(Node::Kind::UnknownIndex);

  // Remove the index adjustment.
  return createNode(Node::Kind::Index, unsigned(index) - 2);
}

NodePointer Demangler::demangleRetroactiveConformance() {
  NodePointer index = demangleIndexAsNode();
  NodePointer conformance = popAnyProtocolConformance();
  return createWithChildren(Node::Kind::RetroactiveConformance, index, conformance);
}

NodePointer Demangler::popRetroactiveConformances() {
  NodePointer conformancesNode = nullptr;
  while (auto conformance = popNode(Node::Kind::RetroactiveConformance)) {
    if (!conformancesNode)
      conformancesNode = createNode(Node::Kind::TypeList);
    conformancesNode->addChild(conformance, *this);
  }
  if (conformancesNode)
    conformancesNode->reverseChildren();
  return conformancesNode;
}

bool Demangler::demangleBoundGenerics(Vector<NodePointer> &TypeListList,
                                      NodePointer &RetroactiveConformances) {
  RetroactiveConformances = popRetroactiveConformances();
  
  for (;;) {
    NodePointer TList = createNode(Node::Kind::TypeList);
    TypeListList.push_back(TList, *this);
    while (NodePointer Ty = popNode(Node::Kind::Type)) {
      TList->addChild(Ty, *this);
    }
    TList->reverseChildren();
    
    if (popNode(Node::Kind::EmptyList))
      break;
    if (!popNode(Node::Kind::FirstElementMarker))
      return false;
  }
  return true;
}

NodePointer Demangler::demangleBoundGenericType() {
  NodePointer RetroactiveConformances;
  Vector<NodePointer> TypeListList(*this, 4);
  
  if (!demangleBoundGenerics(TypeListList, RetroactiveConformances))
    return nullptr;

  NodePointer Nominal = popTypeAndGetAnyGeneric();
  if (!Nominal)
    return nullptr;
  NodePointer BoundNode = demangleBoundGenericArgs(Nominal, TypeListList, 0);
  if (!BoundNode)
    return nullptr;
  addChild(BoundNode, RetroactiveConformances);
  NodePointer NTy = createType(BoundNode);
  addSubstitution(NTy);
  return NTy;
}

bool Demangle::nodeConsumesGenericArgs(Node *node) {
  switch (node->getKind()) {
    case Node::Kind::Variable:
    case Node::Kind::Subscript:
    case Node::Kind::ImplicitClosure:
    case Node::Kind::ExplicitClosure:
    case Node::Kind::DefaultArgumentInitializer:
    case Node::Kind::Initializer:
    case Node::Kind::PropertyWrapperBackingInitializer:
    case Node::Kind::PropertyWrapperInitFromProjectedValue:
    case Node::Kind::Static:
      return false;
    default:
      return true;
  }
}

NodePointer Demangler::demangleBoundGenericArgs(NodePointer Nominal,
                                    const Vector<NodePointer> &TypeLists,
                                    size_t TypeListIdx) {
  // TODO: This would be a lot easier if we represented bound generic args
  // flatly in the demangling tree, since that's how they're mangled and also
  // how the runtime generally wants to consume them.
  
  if (!Nominal)
    return nullptr;

  if (TypeListIdx >= TypeLists.size())
    return nullptr;

  // Associate a context symbolic reference with all remaining generic
  // arguments.
  if (Nominal->getKind() == Node::Kind::TypeSymbolicReference
      || Nominal->getKind() == Node::Kind::ProtocolSymbolicReference) {
    auto remainingTypeList = createNode(Node::Kind::TypeList);
    for (unsigned i = TypeLists.size() - 1;
         i >= TypeListIdx && i < TypeLists.size();
         --i) {
      auto list = TypeLists[i];
      for (auto child : *list) {
        remainingTypeList->addChild(child, *this);
      }
    }
    return createWithChildren(Node::Kind::BoundGenericOtherNominalType,
                              createType(Nominal), remainingTypeList);
  }

  // Generic arguments for the outermost type come first.
  if (Nominal->getNumChildren() == 0)
    return nullptr;
  NodePointer Context = Nominal->getFirstChild();

  bool consumesGenericArgs = nodeConsumesGenericArgs(Nominal);

  NodePointer args = TypeLists[TypeListIdx];

  if (consumesGenericArgs)
    ++TypeListIdx;

  if (TypeListIdx < TypeLists.size()) {
    NodePointer BoundParent = nullptr;
    if (Context->getKind() == Node::Kind::Extension) {
      BoundParent = demangleBoundGenericArgs(Context->getChild(1), TypeLists,
                                             TypeListIdx);
      BoundParent = createWithChildren(Node::Kind::Extension,
                                       Context->getFirstChild(),
                                       BoundParent);
      if (Context->getNumChildren() == 3) {
        // Add the generic signature of the extension context.
        addChild(BoundParent, Context->getChild(2));
      }
    } else {
      BoundParent = demangleBoundGenericArgs(Context, TypeLists, TypeListIdx);
    }
    // Rebuild this type with the new parent type, which may have
    // had its generic arguments applied.
    NodePointer NewNominal = createWithChild(Nominal->getKind(), BoundParent);
    if (!NewNominal)
      return nullptr;

    // Append remaining children of the origin nominal.
    for (unsigned Idx = 1; Idx < Nominal->getNumChildren(); ++Idx) {
      addChild(NewNominal, Nominal->getChild(Idx));
    }
    Nominal = NewNominal;
  }
  if (!consumesGenericArgs)
    return Nominal;

  // If there were no arguments at this level there is nothing left
  // to do.
  if (args->getNumChildren() == 0)
    return Nominal;

  Node::Kind kind;
  switch (Nominal->getKind()) {
  case Node::Kind::Class:
    kind = Node::Kind::BoundGenericClass;
    break;
  case Node::Kind::Structure:
    kind = Node::Kind::BoundGenericStructure;
    break;
  case Node::Kind::Enum:
    kind = Node::Kind::BoundGenericEnum;
    break;
  case Node::Kind::Protocol:
    kind = Node::Kind::BoundGenericProtocol;
    break;
  case Node::Kind::OtherNominalType:
    kind = Node::Kind::BoundGenericOtherNominalType;
    break;
  case Node::Kind::TypeAlias:
    kind = Node::Kind::BoundGenericTypeAlias;
    break;
  case Node::Kind::Function:
  case Node::Kind::Constructor:
    // Well, not really a nominal type.
    return createWithChildren(Node::Kind::BoundGenericFunction, Nominal, args);
  default:
    return nullptr;
  }
  return createWithChildren(kind, createType(Nominal), args);
}

NodePointer Demangler::demangleImplParamConvention(Node::Kind ConvKind) {
  const char *attr = nullptr;
  switch (nextChar()) {
    case 'i': attr = "@in"; break;
    case 'c':
      attr = "@in_constant";
      break;
    case 'l': attr = "@inout"; break;
    case 'b': attr = "@inout_aliasable"; break;
    case 'n': attr = "@in_guaranteed"; break;
    case 'x': attr = "@owned"; break;
    case 'g': attr = "@guaranteed"; break;
    case 'e': attr = "@deallocating"; break;
    case 'y': attr = "@unowned"; break;
    case 'v': attr = "@pack_owned"; break;
    case 'p': attr = "@pack_guaranteed"; break;
    case 'm': attr = "@pack_inout"; break;
    default:
      pushBack();
      return nullptr;
  }
  return createWithChild(ConvKind,
                         createNode(Node::Kind::ImplConvention, attr));
}

NodePointer Demangler::demangleImplResultConvention(Node::Kind ConvKind) {
  const char *attr = nullptr;
  switch (nextChar()) {
    case 'r': attr = "@out"; break;
    case 'o': attr = "@owned"; break;
    case 'd': attr = "@unowned"; break;
    case 'u': attr = "@unowned_inner_pointer"; break;
    case 'a': attr = "@autoreleased"; break;
    case 'k': attr = "@pack_out"; break;
    default:
      pushBack();
      return nullptr;
  }
  return createWithChild(ConvKind,
                         createNode(Node::Kind::ImplConvention, attr));
}

NodePointer Demangler::demangleImplParameterSending() {
  // Empty string represents default differentiability.
  if (!nextIf('T'))
    return nullptr;
  const char *attr = "sending";
  return createNode(Node::Kind::ImplParameterSending, attr);
}

NodePointer Demangler::demangleImplParameterResultDifferentiability() {
  // Empty string represents default differentiability.
  const char *attr = "";
  if (nextIf('w'))
    attr = "@noDerivative";
  return createNode(Node::Kind::ImplParameterResultDifferentiability, attr);
}

NodePointer Demangler::demangleClangType() {
  int numChars = demangleNatural();
  if (numChars <= 0 || Pos + numChars > Text.size())
    return nullptr;
  CharVector mangledClangType;
  mangledClangType.append(StringRef(Text.data() + Pos, numChars), *this);
  Pos = Pos + numChars;
  return createNode(Node::Kind::ClangType, mangledClangType);
}

NodePointer Demangler::demangleImplFunctionType() {
  NodePointer type = createNode(Node::Kind::ImplFunctionType);

  if (nextIf('s')) {
    Vector<NodePointer> Substitutions;
    NodePointer SubstitutionRetroConformances;
    if (!demangleBoundGenerics(Substitutions, SubstitutionRetroConformances))
      return nullptr;

    NodePointer sig = popNode(Node::Kind::DependentGenericSignature);
    if (!sig)
      return nullptr;

    auto subsNode = createNode(Node::Kind::ImplPatternSubstitutions);
    subsNode->addChild(sig, *this);
    assert(Substitutions.size() == 1);
    subsNode->addChild(Substitutions[0], *this);
    if (SubstitutionRetroConformances)
      subsNode->addChild(SubstitutionRetroConformances, *this);
    type->addChild(subsNode, *this);
  }

  if (nextIf('I')) {
    Vector<NodePointer> Substitutions;
    NodePointer SubstitutionRetroConformances;
    if (!demangleBoundGenerics(Substitutions, SubstitutionRetroConformances))
      return nullptr;

    auto subsNode = createNode(Node::Kind::ImplInvocationSubstitutions);
    if (Substitutions.size() != 1)
      return nullptr;
    subsNode->addChild(Substitutions[0], *this);
    if (SubstitutionRetroConformances)
      subsNode->addChild(SubstitutionRetroConformances, *this);
    type->addChild(subsNode, *this);
  }
  
  NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
  if (GenSig && nextIf('P'))
    GenSig = changeKind(GenSig, Node::Kind::DependentPseudogenericSignature);

  if (nextIf('e'))
    type->addChild(createNode(Node::Kind::ImplEscaping), *this);

  if (nextIf('A'))
    type->addChild(createNode(Node::Kind::ImplErasedIsolation), *this);

  switch ((MangledDifferentiabilityKind)peekChar()) {
  case MangledDifferentiabilityKind::Normal:  // 'd'
  case MangledDifferentiabilityKind::Linear:  // 'l'
  case MangledDifferentiabilityKind::Forward: // 'f'
  case MangledDifferentiabilityKind::Reverse: // 'r'
    type->addChild(
        createNode(
            Node::Kind::ImplDifferentiabilityKind, (Node::IndexType)nextChar()),
        *this);
    break;
  default:
    break;
  }

  const char *CAttr = nullptr;
  switch (nextChar()) {
    case 'y': CAttr = "@callee_unowned"; break;
    case 'g': CAttr = "@callee_guaranteed"; break;
    case 'x': CAttr = "@callee_owned"; break;
    case 't': CAttr = "@convention(thin)"; break;
    default: return nullptr;
  }
  type->addChild(createNode(Node::Kind::ImplConvention, CAttr), *this);

  const char *FConv = nullptr;
  bool hasClangType = false;
  switch (nextChar()) {
  case 'B': FConv = "block"; break;
  case 'C': FConv = "c"; break;
  case 'z': {
    switch (nextChar()) {
    case 'B': hasClangType = true; FConv = "block"; break;
    case 'C': hasClangType = true; FConv = "c"; break;
    default: pushBack(); pushBack(); break;
    }
    break;
  }
  case 'M': FConv = "method"; break;
  case 'O': FConv = "objc_method"; break;
  case 'K': FConv = "closure"; break;
  case 'W': FConv = "witness_method"; break;
  default: pushBack(); break;
  }
  if (FConv) {
    auto FAttrNode = createNode(Node::Kind::ImplFunctionConvention);
    FAttrNode->addChild(
        createNode(Node::Kind::ImplFunctionConventionName, FConv), *this);
    if (hasClangType)
      addChild(FAttrNode, demangleClangType());
    type->addChild(FAttrNode, *this);
  }

  const char *CoroAttr = nullptr;
  if (nextIf('A'))
    CoroAttr = "@yield_once";
  else if (nextIf('G'))
    CoroAttr = "@yield_many";
  if (CoroAttr)
    type->addChild(createNode(Node::Kind::ImplFunctionAttribute, CoroAttr), *this);

  if (nextIf('h')) {
    type->addChild(createNode(Node::Kind::ImplFunctionAttribute, "@Sendable"),
                   *this);
  }

  if (nextIf('H')) {
    type->addChild(createNode(Node::Kind::ImplFunctionAttribute, "@async"),
                   *this);
  }

  addChild(type, GenSig);

  int NumTypesToAdd = 0;
  while (NodePointer Param =
             demangleImplParamConvention(Node::Kind::ImplParameter)) {
    type = addChild(type, Param);
    if (NodePointer Diff = demangleImplParameterResultDifferentiability())
      Param = addChild(Param, Diff);
    if (auto Sending = demangleImplParameterSending())
      Param = addChild(Param, Sending);
    ++NumTypesToAdd;
  }

  if (nextIf('T')) {
    type->addChild(createNode(Node::Kind::ImplSendingResult), *this);
  }

  while (NodePointer Result = demangleImplResultConvention(
                                                    Node::Kind::ImplResult)) {
    type = addChild(type, Result);
    if (NodePointer Diff = demangleImplParameterResultDifferentiability())
      Result = addChild(Result, Diff);
    ++NumTypesToAdd;
  }
  while (nextIf('Y')) {
    NodePointer YieldResult =
      demangleImplParamConvention(Node::Kind::ImplYield);
    if (!YieldResult)
      return nullptr;
    type = addChild(type, YieldResult);
    ++NumTypesToAdd;
  }
  if (nextIf('z')) {
    NodePointer ErrorResult = demangleImplResultConvention(
                                                  Node::Kind::ImplErrorResult);
    if (!ErrorResult)
      return nullptr;
    type = addChild(type, ErrorResult);
    ++NumTypesToAdd;
  }
  if (!nextIf('_'))
    return nullptr;

  for (int Idx = 0; Idx < NumTypesToAdd; ++Idx) {
    NodePointer ConvTy = popNode(Node::Kind::Type);
    if (!ConvTy)
      return nullptr;
    type->getChild(type->getNumChildren() - Idx - 1)->addChild(ConvTy, *this);
  }
  
  return createType(type);
}

NodePointer Demangler::demangleMetatype() {
  switch (nextChar()) {
    case 'a':
      return createWithPoppedType(Node::Kind::TypeMetadataAccessFunction);
    case 'A':
      return createWithChild(Node::Kind::ReflectionMetadataAssocTypeDescriptor,
                             popProtocolConformance());
    case 'b':
      return createWithPoppedType(
          Node::Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction);
    case 'B':
      return createWithChild(Node::Kind::ReflectionMetadataBuiltinDescriptor,
                               popNode(Node::Kind::Type));
    case 'c':
      return createWithChild(Node::Kind::ProtocolConformanceDescriptor,
                             popProtocolConformance());
    case 'C': {
      NodePointer Ty = popNode(Node::Kind::Type);
      if (!Ty || !isAnyGeneric(Ty->getChild(0)->getKind()))
        return nullptr;
      return createWithChild(Node::Kind::ReflectionMetadataSuperclassDescriptor,
                             Ty->getChild(0));
    }
    case 'D':
      return createWithPoppedType(Node::Kind::TypeMetadataDemanglingCache);
    case 'f':
      return createWithPoppedType(Node::Kind::FullTypeMetadata);
    case 'F':
      return createWithChild(Node::Kind::ReflectionMetadataFieldDescriptor,
                             popNode(Node::Kind::Type));
    case 'g':
      return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessor,
                             popNode());
    case 'h':
      return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessorImpl,
                             popNode());
    case 'i':
      return createWithPoppedType(Node::Kind::TypeMetadataInstantiationFunction);
    case 'I':
      return createWithPoppedType(Node::Kind::TypeMetadataInstantiationCache);
    case 'j':
      return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessorKey,
                             popNode());
    case 'J':
      return createWithChild(Node::Kind::NoncanonicalSpecializedGenericTypeMetadataCache, popNode());
    case 'k':
      return createWithChild(Node::Kind::OpaqueTypeDescriptorAccessorVar,
                             popNode());
    case 'K':
      return createWithChild(Node::Kind::MetadataInstantiationCache,
                             popNode());
    case 'l':
      return createWithPoppedType(
                          Node::Kind::TypeMetadataSingletonInitializationCache);
    case 'L':
      return createWithPoppedType(Node::Kind::TypeMetadataLazyCache);
    case 'm':
      return createWithPoppedType(Node::Kind::Metaclass);
    case 'M':
      return createWithPoppedType(
          Node::Kind::CanonicalSpecializedGenericMetaclass);
    case 'n':
      return createWithPoppedType(Node::Kind::NominalTypeDescriptor);
    case 'N':
      return createWithPoppedType(
          Node::Kind::NoncanonicalSpecializedGenericTypeMetadata);
    case 'o':
      return createWithPoppedType(Node::Kind::ClassMetadataBaseOffset);
    case 'p':
      return createWithChild(Node::Kind::ProtocolDescriptor, popProtocol());
    case 'P':
      return createWithPoppedType(Node::Kind::GenericTypeMetadataPattern);
    case 'q':
      return createWithChild(Node::Kind::Uniquable, popNode());
    case 'Q':
      return createWithChild(Node::Kind::OpaqueTypeDescriptor, popNode());
    case 'r':
      return createWithPoppedType(Node::Kind::TypeMetadataCompletionFunction);
    case 's':
      return createWithPoppedType(Node::Kind::ObjCResilientClassStub);
    case 'S':
      return createWithChild(Node::Kind::ProtocolSelfConformanceDescriptor,
                             popProtocol());
    case 't':
      return createWithPoppedType(Node::Kind::FullObjCResilientClassStub);
    case 'u':
      return createWithPoppedType(Node::Kind::MethodLookupFunction);
    case 'U':
      return createWithPoppedType(Node::Kind::ObjCMetadataUpdateFunction);
    case 'V':
      return createWithChild(Node::Kind::PropertyDescriptor,
                             popNode(isEntity));
    case 'X':
      return demanglePrivateContextDescriptor();
    case 'z':
      return createWithPoppedType(
          Node::Kind::CanonicalPrespecializedGenericTypeCachingOnceToken);
    default:
      return nullptr;
  }
}
  
NodePointer Demangler::demanglePrivateContextDescriptor() {
  switch (nextChar()) {
  case 'E': {
    auto Extension = popContext();
    if (!Extension)
      return nullptr;
    return createWithChild(Node::Kind::ExtensionDescriptor, Extension);
  }
  case 'M': {
    auto Module = popModule();
    if (!Module)
      return nullptr;
    return createWithChild(Node::Kind::ModuleDescriptor, Module);
  }
  case 'Y': {
    auto Discriminator = popNode();
    if (!Discriminator)
      return nullptr;
    auto Context = popContext();
    if (!Context)
      return nullptr;
    
    auto node = createNode(Node::Kind::AnonymousDescriptor);
    node->addChild(Context, *this);
    node->addChild(Discriminator, *this);
    return node;
  }
  case 'X': {
    auto Context = popContext();
    if (!Context)
      return nullptr;
    return createWithChild(Node::Kind::AnonymousDescriptor, Context);
  }
  case 'A': {
    auto path = popAssocTypePath();
    if (!path)
      return nullptr;
    auto base = popNode(Node::Kind::Type);
    if (!base)
      return nullptr;
    return createWithChildren(Node::Kind::AssociatedTypeGenericParamRef,
                              base, path);
  }
  default:
    return nullptr;
  }
}

NodePointer Demangler::demangleArchetype() {
  switch (nextChar()) {
  case 'a': {
    NodePointer Ident = popNode(Node::Kind::Identifier);
    NodePointer ArcheTy = popTypeAndGetChild();
    NodePointer AssocTy = createType(
          createWithChildren(Node::Kind::AssociatedTypeRef, ArcheTy, Ident));
    addSubstitution(AssocTy);
    return AssocTy;
  }
  case 'O': {
    auto definingContext = popContext();
    return createWithChild(Node::Kind::OpaqueReturnTypeOf, definingContext);
  }
  case 'o': {
    auto index = demangleIndex();
    Vector<NodePointer> boundGenericArgs;
    NodePointer retroactiveConformances;
    if (!demangleBoundGenerics(boundGenericArgs, retroactiveConformances))
      return nullptr;
    auto Name = popNode();
    if (!Name)
      return nullptr;
    auto opaque = createWithChildren(Node::Kind::OpaqueType, Name,
                                   createNode(Node::Kind::Index, index));
    auto boundGenerics = createNode(Node::Kind::TypeList);
    for (unsigned i = boundGenericArgs.size(); i-- > 0;)
      boundGenerics->addChild(boundGenericArgs[i], *this);
    opaque->addChild(boundGenerics, *this);
    if (retroactiveConformances)
      opaque->addChild(retroactiveConformances, *this);
    
    auto opaqueTy = createType(opaque);
    addSubstitution(opaqueTy);
    return opaqueTy;
  }
  case 'r': {
    return createType(createNode(Node::Kind::OpaqueReturnType));
  }
  case 'R': {
    int ordinal = demangleIndex();
    if (ordinal < 0)
      return NULL;
    return createType(createWithChild(Node::Kind::OpaqueReturnType,
                      createNode(Node::Kind::OpaqueReturnTypeIndex, ordinal)));
  }

  case 'x': {
    NodePointer T = demangleAssociatedTypeSimple(nullptr);
    addSubstitution(T);
    return T;
  }
      
  case 'X': {
    NodePointer T = demangleAssociatedTypeCompound(nullptr);
    addSubstitution(T);
    return T;
  }

  case 'y': {
    NodePointer T = demangleAssociatedTypeSimple(demangleGenericParamIndex());
    addSubstitution(T);
    return T;
  }
  case 'Y': {
    NodePointer T = demangleAssociatedTypeCompound(
                                                 demangleGenericParamIndex());
    addSubstitution(T);
    return T;
  }

  case 'z': {
    NodePointer T = demangleAssociatedTypeSimple(
                                          getDependentGenericParamType(0, 0));
    addSubstitution(T);
    return T;
  }
  case 'Z': {
    NodePointer T = demangleAssociatedTypeCompound(
                                          getDependentGenericParamType(0, 0));
    addSubstitution(T);
    return T;
  }
  case 'p': {
    NodePointer CountTy = popTypeAndGetChild();
    NodePointer PatternTy = popTypeAndGetChild();
    NodePointer PackExpansionTy = createType(
          createWithChildren(Node::Kind::PackExpansion, PatternTy, CountTy));
    return PackExpansionTy;
  }
  case 'e': {
    NodePointer PackTy = popTypeAndGetChild();
    int level = demangleIndex();
    if (level < 0)
      return NULL;

    NodePointer PackElementTy = createType(
          createWithChildren(Node::Kind::PackElement, PackTy,
              createNode(Node::Kind::PackElementLevel, level)));
    return PackElementTy;
  }
  case 'P':
    return popPack();
  case 'S':
    return popSILPack();
  default:
    return nullptr;
  }
}

NodePointer Demangler::demangleAssociatedTypeSimple(NodePointer Base) {
  NodePointer ATName = popAssocTypeName();
  NodePointer BaseTy;
  if (Base) {
    BaseTy = createType(Base);
  } else {
    BaseTy = popNode(Node::Kind::Type);
  }
  return createType(createWithChildren(Node::Kind::DependentMemberType,
                                       BaseTy, ATName));
}

NodePointer Demangler::demangleAssociatedTypeCompound(NodePointer Base) {
  Vector<NodePointer> AssocTyNames(*this, 4);
  bool firstElem = false;
  do {
    firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
    NodePointer AssocTyName = popAssocTypeName();
    if (!AssocTyName)
      return nullptr;
    AssocTyNames.push_back(AssocTyName, *this);
  } while (!firstElem);
    
  NodePointer BaseTy;
  if (Base)
    BaseTy = createType(Base);
  else
    BaseTy = popNode(Node::Kind::Type);

  while (NodePointer AssocTy = AssocTyNames.pop_back_val()) {
    NodePointer depTy = createNode(Node::Kind::DependentMemberType);
    depTy = addChild(depTy, BaseTy);
    BaseTy = createType(addChild(depTy, AssocTy));
  }
  return BaseTy;
}

NodePointer Demangler::popAssocTypeName() {
  NodePointer Proto = popNode(Node::Kind::Type);
  if (Proto && !isProtocolNode(Proto))
    return nullptr;

  // If we haven't seen a protocol, check for a symbolic reference.
  if (!Proto)
    Proto = popNode(Node::Kind::ProtocolSymbolicReference);
  if (!Proto)
    Proto = popNode(Node::Kind::ObjectiveCProtocolSymbolicReference);

  NodePointer Id = popNode(Node::Kind::Identifier);
  NodePointer AssocTy = createWithChild(Node::Kind::DependentAssociatedTypeRef, Id);
  addChild(AssocTy, Proto);
  return AssocTy;
}
  
NodePointer Demangler::popAssocTypePath() {
  NodePointer AssocTypePath = createNode(Node::Kind::AssocTypePath);
  bool firstElem = false;
  do {
    firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
    NodePointer AssocTy = popAssocTypeName();
    if (!AssocTy)
      return nullptr;
    AssocTypePath->addChild(AssocTy, *this);
  } while (!firstElem);
  AssocTypePath->reverseChildren();
  return AssocTypePath;
}

NodePointer Demangler::getDependentGenericParamType(int depth, int index) {
  if (depth < 0 || index < 0)
    return nullptr;

  auto paramTy = createNode(Node::Kind::DependentGenericParamType);
  paramTy->addChild(createNode(Node::Kind::Index, depth), *this);
  paramTy->addChild(createNode(Node::Kind::Index, index), *this);
  return paramTy;
}

NodePointer Demangler::demangleGenericParamIndex() {
  if (nextIf('d')) {
    int depth = demangleIndex() + 1;
    int index = demangleIndex();
    return getDependentGenericParamType(depth, index);
  }
  if (nextIf('z')) {
    return getDependentGenericParamType(0, 0);
  }
  if (nextIf('s')) {
    return createNode(Node::Kind::ConstrainedExistentialSelf);
  }
  return getDependentGenericParamType(0, demangleIndex() + 1);
}

NodePointer Demangler::popProtocolConformance() {
  NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
  NodePointer Module = popModule();
  NodePointer Proto = popProtocol();
  NodePointer Type = popNode(Node::Kind::Type);
  NodePointer Ident = nullptr;
  if (!Type) {
    // Property behavior conformance
    Ident = popNode(Node::Kind::Identifier);
    Type = popNode(Node::Kind::Type);
  }
  if (GenSig) {
    Type = createType(createWithChildren(Node::Kind::DependentGenericType,
                                         GenSig, Type));
  }
  NodePointer Conf = createWithChildren(Node::Kind::ProtocolConformance,
                                        Type, Proto, Module);
  addChild(Conf, Ident);
  return Conf;
}

NodePointer Demangler::demangleThunkOrSpecialization() {
  switch (char c = nextChar()) {
    case 'c': return createWithChild(Node::Kind::CurryThunk, popNode(isEntity));
    case 'j': return createWithChild(Node::Kind::DispatchThunk, popNode(isEntity));
    case 'q': return createWithChild(Node::Kind::MethodDescriptor, popNode(isEntity));
    case 'o': return createNode(Node::Kind::ObjCAttribute);
    case 'O': return createNode(Node::Kind::NonObjCAttribute);
    case 'D': return createNode(Node::Kind::DynamicAttribute);
    case 'd': return createNode(Node::Kind::DirectMethodReferenceAttribute);
    case 'E': return createNode(Node::Kind::DistributedThunk);
    case 'F': return createNode(Node::Kind::DistributedAccessor);
    case 'a': return createNode(Node::Kind::PartialApplyObjCForwarder);
    case 'A': return createNode(Node::Kind::PartialApplyForwarder);
    case 'm': return createNode(Node::Kind::MergedFunction);
    case 'X': return createNode(Node::Kind::DynamicallyReplaceableFunctionVar);
    case 'x': return createNode(Node::Kind::DynamicallyReplaceableFunctionKey);
    case 'I': return createNode(Node::Kind::DynamicallyReplaceableFunctionImpl);
    case 'Y':
    case 'Q': {
      NodePointer discriminator = demangleIndexAsNode();
      return createWithChild(
          c == 'Q' ? Node::Kind::AsyncAwaitResumePartialFunction :
             /*'Y'*/ Node::Kind::AsyncSuspendResumePartialFunction,
          discriminator);
    }
    case 'C': {
      NodePointer type = popNode(Node::Kind::Type);
      return createWithChild(Node::Kind::CoroutineContinuationPrototype, type);
    }
    case 'z':
    case 'Z': {
      NodePointer flagMode = demangleIndexAsNode();
      NodePointer sig = popNode(Node::Kind::DependentGenericSignature);
      NodePointer resultType = popNode(Node::Kind::Type);
      NodePointer implType = popNode(Node::Kind::Type);
      auto node = createWithChildren(c == 'z'
                                  ? Node::Kind::ObjCAsyncCompletionHandlerImpl
                                  : Node::Kind::PredefinedObjCAsyncCompletionHandlerImpl,
                                implType, resultType, flagMode);
      if (sig)
        addChild(node, sig);
      return node;
    }
    case 'V': {
      NodePointer Base = popNode(isEntity);
      NodePointer Derived = popNode(isEntity);
      return createWithChildren(Node::Kind::VTableThunk, Derived, Base);
    }
    case 'W': {
      NodePointer Entity = popNode(isEntity);
      NodePointer Conf = popProtocolConformance();
      return createWithChildren(Node::Kind::ProtocolWitness, Conf, Entity);
    }
    case 'S':
      return createWithChild(Node::Kind::ProtocolSelfConformanceWitness,
                             popNode(isEntity));
    case 'R':
    case 'r':
    case 'y': {
      Node::Kind kind;
      if (c == 'R') kind = Node::Kind::ReabstractionThunkHelper;
      else if (c == 'y') kind = Node::Kind::ReabstractionThunkHelperWithSelf;
      else kind = Node::Kind::ReabstractionThunk;
      NodePointer Thunk = createNode(kind);
      if (NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature))
        addChild(Thunk, GenSig);
      if (kind == Node::Kind::ReabstractionThunkHelperWithSelf)
        addChild(Thunk, popNode(Node::Kind::Type));
      addChild(Thunk, popNode(Node::Kind::Type));
      addChild(Thunk, popNode(Node::Kind::Type));
      return Thunk;
    }
    case 'g':
      return demangleGenericSpecialization(Node::Kind::GenericSpecialization);
    case 'G':
      return demangleGenericSpecialization(Node::Kind::
                                          GenericSpecializationNotReAbstracted);
    case 'B':
      return demangleGenericSpecialization(Node::Kind::
                                      GenericSpecializationInResilienceDomain);
    case 's':
      return demangleGenericSpecialization(
          Node::Kind::GenericSpecializationPrespecialized);
    case 'i':
      return demangleGenericSpecialization(Node::Kind::InlinedGenericFunction);
    case 'p': {
      NodePointer Spec = demangleSpecAttributes(Node::Kind::
                                                GenericPartialSpecialization);
      NodePointer Param = createWithChild(Node::Kind::GenericSpecializationParam,
                                          popNode(Node::Kind::Type));
      return addChild(Spec, Param);
    }
    case'P': {
      NodePointer Spec = demangleSpecAttributes(Node::Kind::
                                  GenericPartialSpecializationNotReAbstracted);
      NodePointer Param = createWithChild(Node::Kind::GenericSpecializationParam,
                                          popNode(Node::Kind::Type));
      return addChild(Spec, Param);
    }
    case'f':
      return demangleFunctionSpecialization();
    case 'K':
    case 'k': {
      auto nodeKind = c == 'K' ? Node::Kind::KeyPathGetterThunkHelper
                               : Node::Kind::KeyPathSetterThunkHelper;

      bool isSerialized = nextIf('q');

      std::vector<NodePointer> types;
      auto node = popNode();
      if (!node || node->getKind() != Node::Kind::Type)
        return nullptr;
      do {
        types.push_back(node);
        node = popNode();
      } while (node && node->getKind() == Node::Kind::Type);
      
      NodePointer result;
      if (node) {
        if (node->getKind() == Node::Kind::DependentGenericSignature) {
          auto decl = popNode();
          if (!decl)
            return nullptr;
          result = createWithChildren(nodeKind, decl, /*sig*/ node);
        } else {
          result = createWithChild(nodeKind, /*decl*/ node);
        }
      } else {
        return nullptr;
      }
      for (auto i = types.rbegin(), e = types.rend(); i != e; ++i) {
        result->addChild(*i, *this);
      }

      if (isSerialized)
        result->addChild(createNode(Node::Kind::IsSerialized), *this);

      return result;
    }
    case 'l': {
      auto assocTypeName = popAssocTypeName();
      if (!assocTypeName)
        return nullptr;

      return createWithChild(Node::Kind::AssociatedTypeDescriptor,
                             assocTypeName);
    }
    case 'L':
      return createWithChild(Node::Kind::ProtocolRequirementsBaseDescriptor,
                             popProtocol());
    case 'M':
      return createWithChild(Node::Kind::DefaultAssociatedTypeMetadataAccessor,
                             popAssocTypeName());

    case 'n': {
      NodePointer requirementTy = popProtocol();
      NodePointer conformingType = popAssocTypePath();
      NodePointer protoTy = popNode(Node::Kind::Type);
      return createWithChildren(Node::Kind::AssociatedConformanceDescriptor,
                                protoTy, conformingType, requirementTy);
    }

    case 'N': {
      NodePointer requirementTy = popProtocol();
      auto assocTypePath = popAssocTypePath();
      NodePointer protoTy = popNode(Node::Kind::Type);
      return createWithChildren(
                            Node::Kind::DefaultAssociatedConformanceAccessor,
                            protoTy, assocTypePath, requirementTy);
    }

    case 'b': {
      NodePointer requirementTy = popProtocol();
      NodePointer protoTy = popNode(Node::Kind::Type);
      return createWithChildren(Node::Kind::BaseConformanceDescriptor,
                                protoTy, requirementTy);
    }

    case 'H':
    case 'h': {
      auto nodeKind = c == 'H' ? Node::Kind::KeyPathEqualsThunkHelper
                               : Node::Kind::KeyPathHashThunkHelper;

      bool isSerialized = nextIf('q');

      NodePointer genericSig = nullptr;
      std::vector<NodePointer> types;
      
      auto node = popNode();
      if (node) {
        if (node->getKind() == Node::Kind::DependentGenericSignature) {
          genericSig = node;
        } else if (node->getKind() == Node::Kind::Type) {
          types.push_back(node);
        } else {
          return nullptr;
        }
      } else {
        return nullptr;
      }
      
      while (auto node = popNode()) {
        if (node->getKind() != Node::Kind::Type) {
          return nullptr;
        }
        types.push_back(node);
      }
      
      NodePointer result = createNode(nodeKind);
      for (auto i = types.rbegin(), e = types.rend(); i != e; ++i) {
        result->addChild(*i, *this);
      }
      if (genericSig)
        result->addChild(genericSig, *this);

      if (isSerialized)
        result->addChild(createNode(Node::Kind::IsSerialized), *this);

      return result;
    }
    case 'v': {
      int Idx = demangleIndex();
      if (Idx < 0)
        return nullptr;
      if (nextChar() == 'r')
        return createNode(Node::Kind::OutlinedReadOnlyObject, Idx);
      return createNode(Node::Kind::OutlinedVariable, Idx);
    }
    case 'e': {
      std::string Params = demangleBridgedMethodParams();
      if (Params.empty())
        return nullptr;
      return createNode(Node::Kind::OutlinedBridgedMethod, Params);
    }
    case 'u': return createNode(Node::Kind::AsyncFunctionPointer);
    case 'U': {
      auto globalActor = popNode(Node::Kind::Type);
      if (!globalActor)
        return nullptr;
      
      auto reabstraction = popNode();
      if (!reabstraction)
        return nullptr;
      
      auto node = createNode(Node::Kind::ReabstractionThunkHelperWithGlobalActor);
      node->addChild(reabstraction, *this);
      node->addChild(globalActor, *this);
      return node;
    }
    case 'J':
      switch (peekChar()) {
      case 'S':
        nextChar();
        return demangleAutoDiffSubsetParametersThunk();
      case 'O':
        nextChar();
        return demangleAutoDiffSelfReorderingReabstractionThunk();
      case 'V':
        nextChar();
        return demangleAutoDiffFunctionOrSimpleThunk(
            Node::Kind::AutoDiffDerivativeVTableThunk);
      default:
        return demangleAutoDiffFunctionOrSimpleThunk(
            Node::Kind::AutoDiffFunction);
      }
    case 'w':
      switch (nextChar()) {
      case 'b': return createNode(Node::Kind::BackDeploymentThunk);
      case 'B': return createNode(Node::Kind::BackDeploymentFallback);
      case 'S': return createNode(Node::Kind::HasSymbolQuery);
      default:
        return nullptr;
      }
    default:
      return nullptr;
  }
}

NodePointer
Demangler::demangleAutoDiffFunctionOrSimpleThunk(Node::Kind nodeKind) {
  auto result = createNode(nodeKind);
  while (auto *originalNode = popNode())
    result = addChild(result, originalNode);
  result->reverseChildren();
  auto kind = demangleAutoDiffFunctionKind();
  result = addChild(result, kind);
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('p'))
    return nullptr;
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('r'))
    return nullptr;
  return result;
}

NodePointer Demangler::demangleAutoDiffFunctionKind() {
  char kind = nextChar();
  if (kind != 'f' && kind != 'r' && kind != 'd' && kind != 'p')
    return nullptr;
  return createNode(Node::Kind::AutoDiffFunctionKind, kind);
}

NodePointer Demangler::demangleAutoDiffSubsetParametersThunk() {
  auto result = createNode(Node::Kind::AutoDiffSubsetParametersThunk);
  while (auto *node = popNode())
    result = addChild(result, node);
  result->reverseChildren();
  auto kind = demangleAutoDiffFunctionKind();
  result = addChild(result, kind);
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('p'))
    return nullptr;
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('r'))
    return nullptr;
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('P'))
    return nullptr;
  return result;
}

NodePointer Demangler::demangleAutoDiffSelfReorderingReabstractionThunk() {
  auto result = createNode(
      Node::Kind::AutoDiffSelfReorderingReabstractionThunk);
  addChild(result, popNode(Node::Kind::DependentGenericSignature));
  result = addChild(result, popNode(Node::Kind::Type));
  result = addChild(result, popNode(Node::Kind::Type));
  if (result)
    result->reverseChildren();
  result = addChild(result, demangleAutoDiffFunctionKind());
  return result;
}

NodePointer Demangler::demangleDifferentiabilityWitness() {
  auto result = createNode(Node::Kind::DifferentiabilityWitness);
  auto optionalGenSig = popNode(Node::Kind::DependentGenericSignature);
  while (auto *node = popNode())
    result = addChild(result, node);
  result->reverseChildren();
  MangledDifferentiabilityKind kind;
  switch (auto c = nextChar()) {
  case 'f': kind = MangledDifferentiabilityKind::Forward; break;
  case 'r': kind = MangledDifferentiabilityKind::Reverse; break;
  case 'd': kind = MangledDifferentiabilityKind::Normal; break;
  case 'l': kind = MangledDifferentiabilityKind::Linear; break;
  default: return nullptr;
  }
  result = addChild(
      result, createNode(Node::Kind::Index, (Node::IndexType)kind));
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('p'))
    return nullptr;
  result = addChild(result, demangleIndexSubset());
  if (!nextIf('r'))
    return nullptr;
  addChild(result, optionalGenSig);
  return result;
}

NodePointer Demangler::demangleIndexSubset() {
  std::string str;
  for (auto c = peekChar(); c == 'S' || c == 'U'; c = peekChar()) {
    str.push_back(c);
    (void)nextChar();
  }
  if (str.empty())
    return nullptr;
  return createNode(Node::Kind::IndexSubset, str);
}

NodePointer Demangler::demangleDifferentiableFunctionType() {
  MangledDifferentiabilityKind kind;
  switch (auto c = nextChar()) {
  case 'f': kind = MangledDifferentiabilityKind::Forward; break;
  case 'r': kind = MangledDifferentiabilityKind::Reverse; break;
  case 'd': kind = MangledDifferentiabilityKind::Normal; break;
  case 'l': kind = MangledDifferentiabilityKind::Linear; break;
  default: return nullptr;
  }
  return createNode(
      Node::Kind::DifferentiableFunctionType, (Node::IndexType)kind);
}

NodePointer Demangler::demangleLifetimeDependenceKind(bool isSelfDependence) {
  MangledLifetimeDependenceKind kind;
  switch (auto c = nextChar()) {
  case 's':
    kind = MangledLifetimeDependenceKind::Scope;
    break;
  case 'i':
    kind = MangledLifetimeDependenceKind::Inherit;
    break;
  default:
    return nullptr;
  }
  if (isSelfDependence) {
    return createNode(Node::Kind::SelfLifetimeDependence,
                      (Node::IndexType)kind);
  }
  auto node = createWithChildren(Node::Kind::ParamLifetimeDependence,
                                 createNode(Node::Kind::Index, unsigned(kind)),
                                 popTypeAndGetChild());
  return createType(node);
}

std::string Demangler::demangleBridgedMethodParams() {
  if (nextIf('_'))
    return std::string();

  std::string Str;

  auto kind = nextChar();
  switch (kind) {
  default:
    return std::string();
  case 'o': case 'p': case 'a': case 'm':
    Str.push_back(kind);
  }

  while (!nextIf('_')) {
    auto c = nextChar();
    if (c != 'n' && c != 'b' && c != 'g')
      return std::string();
    Str.push_back(c);
  }
  return Str;
}

NodePointer Demangler::demangleGenericSpecialization(Node::Kind SpecKind) {
  NodePointer Spec = demangleSpecAttributes(SpecKind);
  if (!Spec)
    return nullptr;
  NodePointer TyList = popTypeList();
  if (!TyList)
    return nullptr;
  for (NodePointer Ty : *TyList) {
    Spec->addChild(createWithChild(Node::Kind::GenericSpecializationParam, Ty),
                   *this);
  }
  return Spec;
}

NodePointer Demangler::demangleFunctionSpecialization() {
  NodePointer Spec = demangleSpecAttributes(
        Node::Kind::FunctionSignatureSpecialization);
  while (Spec && !nextIf('_')) {
    Spec = addChild(Spec, demangleFuncSpecParam(Node::Kind::FunctionSignatureSpecializationParam));
  }
  if (!nextIf('n'))
    Spec = addChild(Spec, demangleFuncSpecParam(Node::Kind::FunctionSignatureSpecializationReturn));

  if (!Spec)
    return nullptr;

  // Add the required parameters in reverse order.
  for (size_t Idx = 0, Num = Spec->getNumChildren(); Idx < Num; ++Idx) {
    NodePointer Param = Spec->getChild(Num - Idx - 1);
    if (Param->getKind() != Node::Kind::FunctionSignatureSpecializationParam)
      continue;

    if (Param->getNumChildren() == 0)
      continue;
    NodePointer KindNd = Param->getFirstChild();
    assert(KindNd->getKind() ==
             Node::Kind::FunctionSignatureSpecializationParamKind);
    auto ParamKind = (FunctionSigSpecializationParamKind)KindNd->getIndex();
    switch (ParamKind) {
      case FunctionSigSpecializationParamKind::ConstantPropFunction:
      case FunctionSigSpecializationParamKind::ConstantPropGlobal:
      case FunctionSigSpecializationParamKind::ConstantPropString:
      case FunctionSigSpecializationParamKind::ConstantPropKeyPath:
      case FunctionSigSpecializationParamKind::ClosureProp: {
        size_t FixedChildren = Param->getNumChildren();
        while (NodePointer Ty = popNode(Node::Kind::Type)) {
          if (ParamKind != FunctionSigSpecializationParamKind::ClosureProp &&
              ParamKind != FunctionSigSpecializationParamKind::ConstantPropKeyPath)
            return nullptr;
          Param = addChild(Param, Ty);
        }
        NodePointer Name = popNode(Node::Kind::Identifier);
        if (!Name)
          return nullptr;
        StringRef Text = Name->getText();
        if (ParamKind ==
                FunctionSigSpecializationParamKind::ConstantPropString &&
            !Text.empty() && Text[0] == '_') {
          // A '_' escapes a leading digit or '_' of a string constant.
          Text = Text.drop_front(1);
        }
        addChild(Param, createNodeWithAllocatedText(
          Node::Kind::FunctionSignatureSpecializationParamPayload, Text));
        Param->reverseChildren(FixedChildren);
        break;
      }
      default:
        break;
    }
  }
  return Spec;
}

NodePointer Demangler::demangleFuncSpecParam(Node::Kind Kind) {
  assert(Kind == Node::Kind::FunctionSignatureSpecializationParam ||
         Kind == Node::Kind::FunctionSignatureSpecializationReturn);
  NodePointer Param = createNode(Kind);
  switch (nextChar()) {
    case 'n':
      return Param;
    case 'c':
      // Consumes an identifier and multiple type parameters.
      // The parameters will be added later.
      return addChild(Param, createNode(
        Node::Kind::FunctionSignatureSpecializationParamKind,
        uint64_t(FunctionSigSpecializationParamKind::ClosureProp)));
    case 'p': {
      switch (nextChar()) {
        case 'f':
          // Consumes an identifier parameter, which will be added later.
          return addChild(
              Param,
              createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
                         Node::IndexType(FunctionSigSpecializationParamKind::
                                             ConstantPropFunction)));
        case 'g':
          // Consumes an identifier parameter, which will be added later.
          return addChild(
              Param,
              createNode(
                  Node::Kind::FunctionSignatureSpecializationParamKind,
                  Node::IndexType(
                      FunctionSigSpecializationParamKind::ConstantPropGlobal)));
        case 'i':
          return addFuncSpecParamNumber(Param,
                    FunctionSigSpecializationParamKind::ConstantPropInteger);
        case 'd':
          return addFuncSpecParamNumber(Param,
                      FunctionSigSpecializationParamKind::ConstantPropFloat);
        case 's': {
          // Consumes an identifier parameter (the string constant),
          // which will be added later.
          const char *Encoding = nullptr;
          switch (nextChar()) {
            case 'b': Encoding = "u8"; break;
            case 'w': Encoding = "u16"; break;
            case 'c': Encoding = "objc"; break;
            default: return nullptr;
          }
          addChild(Param,
                   createNode(
                       Node::Kind::FunctionSignatureSpecializationParamKind,
                       Node::IndexType(
                           swift::Demangle::FunctionSigSpecializationParamKind::
                               ConstantPropString)));
          return addChild(Param, createNode(
                  Node::Kind::FunctionSignatureSpecializationParamPayload,
                  Encoding));
        }
        case 'k': {
          // Consumes two types and a SHA1 identifier.
          return addChild(
              Param,
              createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
                         Node::IndexType(FunctionSigSpecializationParamKind::
                                             ConstantPropKeyPath)));
        }
        default:
          return nullptr;
      }
    }
    case 'e': {
      unsigned Value =
          unsigned(FunctionSigSpecializationParamKind::ExistentialToGeneric);
      if (nextIf('D'))
        Value |= unsigned(FunctionSigSpecializationParamKind::Dead);
      if (nextIf('G'))
        Value |=
            unsigned(FunctionSigSpecializationParamKind::OwnedToGuaranteed);
      if (nextIf('O'))
        Value |=
            unsigned(FunctionSigSpecializationParamKind::GuaranteedToOwned);
      if (nextIf('X'))
        Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
      return addChild(
          Param,
          createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
                     Value));
    }
    case 'd': {
      unsigned Value = unsigned(FunctionSigSpecializationParamKind::Dead);
      if (nextIf('G'))
        Value |= unsigned(FunctionSigSpecializationParamKind::OwnedToGuaranteed);
      if (nextIf('O'))
        Value |=
            unsigned(FunctionSigSpecializationParamKind::GuaranteedToOwned);
      if (nextIf('X'))
        Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
      return addChild(Param, createNode(
                  Node::Kind::FunctionSignatureSpecializationParamKind, Value));
    }
    case 'g': {
      unsigned Value = unsigned(FunctionSigSpecializationParamKind::
                                OwnedToGuaranteed);
      if (nextIf('X'))
        Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
      return addChild(Param, createNode(
                  Node::Kind::FunctionSignatureSpecializationParamKind, Value));
    }
    case 'o': {
      unsigned Value =
          unsigned(FunctionSigSpecializationParamKind::GuaranteedToOwned);
      if (nextIf('X'))
        Value |= unsigned(FunctionSigSpecializationParamKind::SROA);
      return addChild(
          Param,
          createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
                     Value));
    }
    case 'x':
      return addChild(Param, createNode(
                Node::Kind::FunctionSignatureSpecializationParamKind,
                unsigned(FunctionSigSpecializationParamKind::SROA)));
    case 'i':
      return addChild(Param, createNode(
                Node::Kind::FunctionSignatureSpecializationParamKind,
                unsigned(FunctionSigSpecializationParamKind::BoxToValue)));
    case 's':
      return addChild(Param, createNode(
                Node::Kind::FunctionSignatureSpecializationParamKind,
                unsigned(FunctionSigSpecializationParamKind::BoxToStack)));
    case 'r':
      return addChild(
          Param,
          createNode(Node::Kind::FunctionSignatureSpecializationParamKind,
                     unsigned(FunctionSigSpecializationParamKind::InOutToOut)));
    default:
      return nullptr;
  }
}

NodePointer Demangler::addFuncSpecParamNumber(NodePointer Param,
                                    FunctionSigSpecializationParamKind Kind) {
  Param->addChild(createNode(
        Node::Kind::FunctionSignatureSpecializationParamKind, unsigned(Kind)),
        *this);
  CharVector Str;
  while (isDigit(peekChar())) {
    Str.push_back(nextChar(), *this);
  }
  if (Str.empty())
    return nullptr;
  return addChild(Param, createNode(
     Node::Kind::FunctionSignatureSpecializationParamPayload, Str));
}

NodePointer Demangler::demangleSpecAttributes(Node::Kind SpecKind) {
  bool metatypeParamsRemoved = nextIf('m');
  bool isSerialized = nextIf('q');
  bool asyncRemoved = nextIf('a');

  int PassID = (int)nextChar() - '0';
  if (PassID < 0 || PassID >= MAX_SPECIALIZATION_PASS) {
    assert(false && "unexpected pass id");
    return nullptr;
  }

  NodePointer SpecNd = createNode(SpecKind);

  if (metatypeParamsRemoved)
    SpecNd->addChild(createNode(Node::Kind::MetatypeParamsRemoved), *this);

  if (isSerialized)
    SpecNd->addChild(createNode(Node::Kind::IsSerialized),
                     *this);

  if (asyncRemoved)
    SpecNd->addChild(createNode(Node::Kind::AsyncRemoved),
                     *this);

  SpecNd->addChild(createNode(Node::Kind::SpecializationPassID, PassID),
                   *this);
  return SpecNd;
}

NodePointer Demangler::demangleWitness() {
  switch (char c = nextChar()) {
    case 'C':
      return createWithChild(Node::Kind::EnumCase,
                             popNode(isEntity));
    case 'V':
      return createWithChild(Node::Kind::ValueWitnessTable,
                             popNode(Node::Kind::Type));
    case 'v': {
      unsigned Directness;
      switch (nextChar()) {
        case 'd': Directness = unsigned(Directness::Direct); break;
        case 'i': Directness = unsigned(Directness::Indirect); break;
        default: return nullptr;
      }
      return createWithChildren(Node::Kind::FieldOffset,
                        createNode(Node::Kind::Directness, Directness),
                        popNode(isEntity));
    }
    case 'S':
      return createWithChild(Node::Kind::ProtocolSelfConformanceWitnessTable,
                             popProtocol());
    case 'P':
      return createWithChild(Node::Kind::ProtocolWitnessTable,
                             popProtocolConformance());
    case 'p':
      return createWithChild(Node::Kind::ProtocolWitnessTablePattern,
                             popProtocolConformance());
    case 'G':
      return createWithChild(Node::Kind::GenericProtocolWitnessTable,
                             popProtocolConformance());
    case 'I':
      return createWithChild(
                  Node::Kind::GenericProtocolWitnessTableInstantiationFunction,
                  popProtocolConformance());

    case 'r':
      return createWithChild(Node::Kind::ResilientProtocolWitnessTable,
                             popProtocolConformance());

    case 'l': {
      NodePointer Conf = popProtocolConformance();
      NodePointer Type = popNode(Node::Kind::Type);
      return createWithChildren(Node::Kind::LazyProtocolWitnessTableAccessor,
                                Type, Conf);
    }
    case 'L': {
      NodePointer Conf = popProtocolConformance();
      NodePointer Type = popNode(Node::Kind::Type);
      return createWithChildren(
               Node::Kind::LazyProtocolWitnessTableCacheVariable, Type, Conf);
    }
    case 'a':
      return createWithChild(Node::Kind::ProtocolWitnessTableAccessor,
                             popProtocolConformance());
    case 't': {
      NodePointer Name = popNode(isDeclName);
      NodePointer Conf = popProtocolConformance();
      return createWithChildren(Node::Kind::AssociatedTypeMetadataAccessor,
                                Conf, Name);
    }
    case 'T': {
      NodePointer ProtoTy = popNode(Node::Kind::Type);
      NodePointer ConformingType = popAssocTypePath();
      NodePointer Conf = popProtocolConformance();
      return createWithChildren(Node::Kind::AssociatedTypeWitnessTableAccessor,
                                Conf, ConformingType, ProtoTy);
    }
    case 'b': {
      NodePointer ProtoTy = popNode(Node::Kind::Type);
      NodePointer Conf = popProtocolConformance();
      return createWithChildren(Node::Kind::BaseWitnessTableAccessor,
                                Conf, ProtoTy);
    }
    case 'O': {
      switch (nextChar()) {
      case 'C': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedInitializeWithCopyNoValueWitness,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedInitializeWithCopyNoValueWitness,
                               popNode(Node::Kind::Type));
      }
      case 'D': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedAssignWithTakeNoValueWitness,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedAssignWithTakeNoValueWitness,
                               popNode(Node::Kind::Type));
      }
      case 'F': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedAssignWithCopyNoValueWitness,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedAssignWithCopyNoValueWitness,
                               popNode(Node::Kind::Type));
      }
      case 'H': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedDestroyNoValueWitness,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedDestroyNoValueWitness,
                               popNode(Node::Kind::Type));
      }
      case 'y': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedCopy,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedCopy,
                               popNode(Node::Kind::Type));
      }
      case 'e': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedConsume,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedConsume,
                               popNode(Node::Kind::Type));
      }
      case 'r': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedRetain,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedRetain,
                               popNode(Node::Kind::Type));
      }
      case 's': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedRelease,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedRelease,
                               popNode(Node::Kind::Type));
      }
      case 'b': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedInitializeWithTake,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedInitializeWithTake,
                               popNode(Node::Kind::Type));
      }
      case 'c': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedInitializeWithCopy,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedInitializeWithCopy,
                               popNode(Node::Kind::Type));
      }
      case 'd': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedAssignWithTake,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedAssignWithTake,
                               popNode(Node::Kind::Type));
      }
      case 'f': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedAssignWithCopy,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedAssignWithCopy,
                               popNode(Node::Kind::Type));
      }
      case 'h': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedDestroy,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedDestroy,
                               popNode(Node::Kind::Type));
      }
      case 'g': {
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedEnumGetTag,
                                    popNode(Node::Kind::Type), sig);
        return createWithChild(Node::Kind::OutlinedEnumGetTag,
                               popNode(Node::Kind::Type));
      }

      case 'i': {
        auto enumCaseIdx = demangleIndexAsNode();
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedEnumTagStore,
                                    popNode(Node::Kind::Type), sig,
                                    enumCaseIdx);
        return createWithChildren(Node::Kind::OutlinedEnumTagStore,
                                  popNode(Node::Kind::Type), enumCaseIdx);
      }
      case 'j': {
        auto enumCaseIdx = demangleIndexAsNode();
        if (auto sig = popNode(Node::Kind::DependentGenericSignature))
          return createWithChildren(Node::Kind::OutlinedEnumProjectDataForLoad,
                                    popNode(Node::Kind::Type), sig,
                                    enumCaseIdx);
        return createWithChildren(Node::Kind::OutlinedEnumProjectDataForLoad,
                                  popNode(Node::Kind::Type), enumCaseIdx);
      }

      default:
        return nullptr;
      }
    }
    case 'Z':
    case 'z': {
      auto declList = createNode(Node::Kind::GlobalVariableOnceDeclList);
      std::vector<NodePointer> vars;
      while (auto sig = popNode(Node::Kind::FirstElementMarker)) {
        auto identifier = popNode(isDeclName);
        if (!identifier)
          return nullptr;
        vars.push_back(identifier);
      }
      for (auto i = vars.rbegin(); i != vars.rend(); ++i) {
        declList->addChild(*i, *this);
      }
      
      auto context = popContext();
      if (!context)
        return nullptr;
      Node::Kind kind = c == 'Z'
        ? Node::Kind::GlobalVariableOnceFunction
        : Node::Kind::GlobalVariableOnceToken;
      return createWithChildren(kind,
                                context,
                                declList);
    }
    case 'J':
      return demangleDifferentiabilityWitness();
    default:
      return nullptr;
  }
}

NodePointer Demangler::demangleSpecialType() {
  switch (auto specialChar = nextChar()) {
    case 'E':
      return popFunctionType(Node::Kind::NoEscapeFunctionType);
    case 'A':
      return popFunctionType(Node::Kind::EscapingAutoClosureType);
    case 'f':
      return popFunctionType(Node::Kind::ThinFunctionType);
    case 'K':
      return popFunctionType(Node::Kind::AutoClosureType);
    case 'U':
      return popFunctionType(Node::Kind::UncurriedFunctionType);
    case 'L':
      return popFunctionType(Node::Kind::EscapingObjCBlock);
    case 'B':
      return popFunctionType(Node::Kind::ObjCBlock);
    case 'C':
      return popFunctionType(Node::Kind::CFunctionPointer);
    case 'g':
    case 'G':
      return demangleExtendedExistentialShape(specialChar);
    case 'j':
      return demangleSymbolicExtendedExistentialType();
    case 'z':
      switch (auto cchar = nextChar()) {
      case 'B':
        return popFunctionType(Node::Kind::ObjCBlock, true);
      case 'C':
        return popFunctionType(Node::Kind::CFunctionPointer, true);
      default:
        return nullptr;
      }
    case 'o':
      return createType(createWithChild(Node::Kind::Unowned,
                                        popNode(Node::Kind::Type)));
    case 'u':
      return createType(createWithChild(Node::Kind::Unmanaged,
                                        popNode(Node::Kind::Type)));
    case 'w':
      return createType(createWithChild(Node::Kind::Weak,
                                        popNode(Node::Kind::Type)));
    case 'b':
      return createType(createWithChild(Node::Kind::SILBoxType,
                                        popNode(Node::Kind::Type)));
    case 'D':
      return createType(createWithChild(Node::Kind::DynamicSelf,
                                        popNode(Node::Kind::Type)));
    case 'M': {
      NodePointer MTR = demangleMetatypeRepresentation();
      NodePointer Type = popNode(Node::Kind::Type);
      return createType(createWithChildren(Node::Kind::Metatype, MTR, Type));
    }
    case 'm': {
      NodePointer MTR = demangleMetatypeRepresentation();
      NodePointer Type = popNode(Node::Kind::Type);
      return createType(createWithChildren(Node::Kind::ExistentialMetatype,
                                           MTR, Type));
    }
    case 'P': {
      NodePointer Reqs = demangleConstrainedExistentialRequirementList();
      NodePointer Base = popNode(Node::Kind::Type);
      return createType(
          createWithChildren(Node::Kind::ConstrainedExistential, Base, Reqs));
    }
    case 'p':
      return createType(createWithChild(Node::Kind::ExistentialMetatype,
                                        popNode(Node::Kind::Type)));
    case 'c': {
      NodePointer Superclass = popNode(Node::Kind::Type);
      NodePointer Protocols = demangleProtocolList();
      return createType(createWithChildren(Node::Kind::ProtocolListWithClass,
                                           Protocols, Superclass));
    }
    case 'l': {
      NodePointer Protocols = demangleProtocolList();
      return createType(createWithChild(Node::Kind::ProtocolListWithAnyObject,
                                        Protocols));
    }
    case 'X':
    case 'x': {
      // SIL box types.
      NodePointer signature = nullptr, genericArgs = nullptr;
      if (specialChar == 'X') {
        signature = popNode(Node::Kind::DependentGenericSignature);
        if (!signature)
          return nullptr;
        genericArgs = popTypeList();
        if (!genericArgs)
          return nullptr;
      }
      
      auto fieldTypes = popTypeList();
      if (!fieldTypes)
        return nullptr;
      // Build layout.
      auto layout = createNode(Node::Kind::SILBoxLayout);
      for (size_t i = 0, e = fieldTypes->getNumChildren(); i < e; ++i) {
        auto fieldType = fieldTypes->getChild(i);
        assert(fieldType->getKind() == Node::Kind::Type);
        bool isMutable = false;
        // 'inout' typelist mangling is used to represent mutable fields.
        if (fieldType->getChild(0)->getKind() == Node::Kind::InOut) {
          isMutable = true;
          fieldType = createType(fieldType->getChild(0)->getChild(0));
        }
        auto field = createNode(isMutable
                                         ? Node::Kind::SILBoxMutableField
                                         : Node::Kind::SILBoxImmutableField);
        field->addChild(fieldType, *this);
        layout->addChild(field, *this);
      }
      auto boxTy = createNode(Node::Kind::SILBoxTypeWithLayout);
      boxTy->addChild(layout, *this);
      if (signature) {
        boxTy->addChild(signature, *this);
        assert(genericArgs);
        boxTy->addChild(genericArgs, *this);
      }
      return createType(boxTy);
    }
    case 'Y':
      return demangleAnyGenericType(Node::Kind::OtherNominalType);
    case 'Z': {
      auto types = popTypeList();
      auto name = popNode(Node::Kind::Identifier);
      auto parent = popContext();
      auto anon = createNode(Node::Kind::AnonymousContext);
      anon = addChild(anon, name);
      anon = addChild(anon, parent);
      anon = addChild(anon, types);
      return anon;
    }
    case 'e':
      return createType(createNode(Node::Kind::ErrorType));
    case 'S':
      // Sugared type for debugger.
      switch (nextChar()) {
      case 'q':
        return createType(createWithChild(Node::Kind::SugaredOptional,
                                          popNode(Node::Kind::Type)));
      case 'a':
        return createType(createWithChild(Node::Kind::SugaredArray,
                                          popNode(Node::Kind::Type)));
      case 'D': {
        NodePointer value = popNode(Node::Kind::Type);
        NodePointer key = popNode(Node::Kind::Type);
        return createType(createWithChildren(Node::Kind::SugaredDictionary,
                                             key, value));
      }
      case 'p':
        return createType(createWithChild(Node::Kind::SugaredParen,
                                          popNode(Node::Kind::Type)));
      default:
        return nullptr;
      }
    default:
      return nullptr;
  }
}

NodePointer Demangler::demangleSymbolicExtendedExistentialType() {
  NodePointer retroactiveConformances = popRetroactiveConformances();

  NodePointer args = createNode(Node::Kind::TypeList);
  while (NodePointer ty = popNode(Node::Kind::Type)) {
    args->addChild(ty, *this);
  }
  args->reverseChildren();

  auto shape = popNode();
  if (!shape)
    return nullptr;
  if (shape->getKind() !=
        Node::Kind::UniqueExtendedExistentialTypeShapeSymbolicReference &&
      shape->getKind() !=
        Node::Kind::NonUniqueExtendedExistentialTypeShapeSymbolicReference)
    return nullptr;

  NodePointer existentialType;
  if (!retroactiveConformances) {
    existentialType =
      createWithChildren(Node::Kind::SymbolicExtendedExistentialType,
                         shape, args);
  } else {
    existentialType =
      createWithChildren(Node::Kind::SymbolicExtendedExistentialType,
                         shape, args, retroactiveConformances);
  }
  return createType(existentialType);
}

NodePointer Demangler::demangleExtendedExistentialShape(char nodeKind) {
  assert(nodeKind == 'g' || nodeKind == 'G');

  NodePointer type = popNode(Node::Kind::Type);

  NodePointer genSig = nullptr;
  if (nodeKind == 'G')
    genSig = popNode(Node::Kind::DependentGenericSignature);

  if (genSig) {
    return createWithChildren(Node::Kind::ExtendedExistentialTypeShape,
                              genSig, type);
  } else {
    return createWithChild(Node::Kind::ExtendedExistentialTypeShape, type);
  }
}

NodePointer Demangler::demangleMetatypeRepresentation() {
  switch (nextChar()) {
    case 't':
      return createNode(Node::Kind::MetatypeRepresentation, "@thin");
    case 'T':
      return createNode(Node::Kind::MetatypeRepresentation, "@thick");
    case 'o':
      return createNode(Node::Kind::MetatypeRepresentation,
                                 "@objc_metatype");
    default:
      return nullptr;
  }
}

NodePointer Demangler::demangleAccessor(NodePointer ChildNode) {
  Node::Kind Kind;
  switch (nextChar()) {
    case 'm': Kind = Node::Kind::MaterializeForSet; break;
    case 's': Kind = Node::Kind::Setter; break;
    case 'g': Kind = Node::Kind::Getter; break;
    case 'G': Kind = Node::Kind::GlobalGetter; break;
    case 'w': Kind = Node::Kind::WillSet; break;
    case 'W': Kind = Node::Kind::DidSet; break;
    case 'r': Kind = Node::Kind::ReadAccessor; break;
    case 'M': Kind = Node::Kind::ModifyAccessor; break;
    case 'i': Kind = Node::Kind::InitAccessor; break;
    case 'a':
      switch (nextChar()) {
        case 'O': Kind = Node::Kind::OwningMutableAddressor; break;
        case 'o': Kind = Node::Kind::NativeOwningMutableAddressor; break;
        case 'P': Kind = Node::Kind::NativePinningMutableAddressor; break;
        case 'u': Kind = Node::Kind::UnsafeMutableAddressor; break;
        default: return nullptr;
      }
      break;
    case 'l':
      switch (nextChar()) {
        case 'O': Kind = Node::Kind::OwningAddressor; break;
        case 'o': Kind = Node::Kind::NativeOwningAddressor; break;
        case 'p': Kind = Node::Kind::NativePinningAddressor; break;
        case 'u': Kind = Node::Kind::UnsafeAddressor; break;
        default: return nullptr;
      }
      break;
    case 'p': // Pseudo-accessor referring to the variable/subscript itself
      return ChildNode;
    default: return nullptr;
  }
  NodePointer Entity = createWithChild(Kind, ChildNode);
  return Entity;
}

NodePointer Demangler::demangleFunctionEntity() {
  enum {
    None,
    TypeAndMaybePrivateName,
    TypeAndIndex,
    Index,
    ContextArg,
  } Args;

  Node::Kind Kind = Node::Kind::EmptyList;
  switch (nextChar()) {
    case 'D': Args = None; Kind = Node::Kind::Deallocator; break;
    case 'd': Args = None; Kind = Node::Kind::Destructor; break;
    case 'E': Args = None; Kind = Node::Kind::IVarDestroyer; break;
    case 'e': Args = None; Kind = Node::Kind::IVarInitializer; break;
    case 'i': Args = None; Kind = Node::Kind::Initializer; break;
    case 'C':
      Args = TypeAndMaybePrivateName; Kind = Node::Kind::Allocator; break;
    case 'c':
      Args = TypeAndMaybePrivateName; Kind = Node::Kind::Constructor; break;
    case 'U': Args = TypeAndIndex; Kind = Node::Kind::ExplicitClosure; break;
    case 'u': Args = TypeAndIndex; Kind = Node::Kind::ImplicitClosure; break;
    case 'A': Args = Index; Kind = Node::Kind::DefaultArgumentInitializer; break;
    case 'm': return demangleEntity(Node::Kind::Macro);
    case 'M': return demangleMacroExpansion();
    case 'p': return demangleEntity(Node::Kind::GenericTypeParamDecl);
    case 'P':
      Args = None;
      Kind = Node::Kind::PropertyWrapperBackingInitializer;
      break;
    case 'W':
      Args = None;
      Kind = Node::Kind::PropertyWrapperInitFromProjectedValue;
      break;
    default: return nullptr;
  }

  NodePointer NameOrIndex = nullptr, ParamType = nullptr, LabelList = nullptr,
              Context = nullptr;
  switch (Args) {
    case None:
      break;
    case TypeAndMaybePrivateName:
      NameOrIndex = popNode(Node::Kind::PrivateDeclName);
      ParamType = popNode(Node::Kind::Type);
      LabelList = popFunctionParamLabels(ParamType);
      break;
    case TypeAndIndex:
      NameOrIndex = demangleIndexAsNode();
      ParamType = popNode(Node::Kind::Type);
      break;
    case Index:
      NameOrIndex = demangleIndexAsNode();
      break;
    case ContextArg:
      Context = popNode();
      break;
  }
  NodePointer Entity = createWithChild(Kind, popContext());
  switch (Args) {
    case None:
      break;
    case Index:
      Entity = addChild(Entity, NameOrIndex);
      break;
    case TypeAndMaybePrivateName:
      addChild(Entity, LabelList);
      Entity = addChild(Entity, ParamType);
      addChild(Entity, NameOrIndex);
      break;
    case TypeAndIndex:
      Entity = addChild(Entity, NameOrIndex);
      Entity = addChild(Entity, ParamType);
      break;
    case ContextArg:
      Entity = addChild(Entity, Context);
      break;
  }
  return Entity;
}

NodePointer Demangler::demangleEntity(Node::Kind Kind) {
  NodePointer Type = popNode(Node::Kind::Type);
  NodePointer LabelList = popFunctionParamLabels(Type);
  NodePointer Name = popNode(isDeclName);
  NodePointer Context = popContext();
  auto result = LabelList ? createWithChildren(Kind, Context, Name, LabelList, Type)
                          : createWithChildren(Kind, Context, Name, Type);
                          
  result = setParentForOpaqueReturnTypeNodes(*this, result, Type);
  return result;
}

NodePointer Demangler::demangleVariable() {
  NodePointer Variable = demangleEntity(Node::Kind::Variable);
  return demangleAccessor(Variable);
}

NodePointer Demangler::demangleSubscript() {
  NodePointer PrivateName = popNode(Node::Kind::PrivateDeclName);
  NodePointer Type = popNode(Node::Kind::Type);
  NodePointer LabelList = popFunctionParamLabels(Type);
  NodePointer Context = popContext();

  if (!Type)
    return nullptr;

  NodePointer Subscript = createNode(Node::Kind::Subscript);
  Subscript = addChild(Subscript, Context);
  addChild(Subscript, LabelList);
  Subscript = addChild(Subscript, Type);
  addChild(Subscript, PrivateName);
  
  Subscript = setParentForOpaqueReturnTypeNodes(*this, Subscript, Type);

  return demangleAccessor(Subscript);
}

NodePointer Demangler::demangleProtocolList() {
  NodePointer TypeList = createNode(Node::Kind::TypeList);
  NodePointer ProtoList = createWithChild(Node::Kind::ProtocolList, TypeList);
  if (!popNode(Node::Kind::EmptyList)) {
    bool firstElem = false;
    do {
      firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
      NodePointer Proto = popProtocol();
      if (!Proto)
        return nullptr;
      TypeList->addChild(Proto, *this);
    } while (!firstElem);

    TypeList->reverseChildren();
  }
  return ProtoList;
}

NodePointer Demangler::demangleProtocolListType() {
  NodePointer ProtoList = demangleProtocolList();
  return createType(ProtoList);
}

NodePointer Demangler::demangleConstrainedExistentialRequirementList() {
  NodePointer ReqList =
      createNode(Node::Kind::ConstrainedExistentialRequirementList);
  bool firstElem = false;
  do {
    firstElem = (popNode(Node::Kind::FirstElementMarker) != nullptr);
    NodePointer Req = popNode(isRequirement);
    if (!Req)
      return nullptr;
    ReqList->addChild(Req, *this);
  } while (!firstElem);

  ReqList->reverseChildren();
  return ReqList;
}

NodePointer Demangler::demangleGenericSignature(bool hasParamCounts) {
  NodePointer Sig = createNode(Node::Kind::DependentGenericSignature);
  if (hasParamCounts) {
    while (!nextIf('l')) {
      int count = 0;
      if (!nextIf('z'))
        count = demangleIndex() + 1;
      if (count < 0)
        return nullptr;
      Sig->addChild(createNode(Node::Kind::DependentGenericParamCount,
                                        count), *this);
    }
  } else {
    Sig->addChild(createNode(Node::Kind::DependentGenericParamCount, 1),
                  *this);
  }
  size_t NumCounts = Sig->getNumChildren();
  while (NodePointer Req = popNode(isRequirement)) {
    Sig->addChild(Req, *this);
  }
  Sig->reverseChildren(NumCounts);
  return Sig;
}

NodePointer Demangler::demangleGenericRequirement() {

  enum { Generic, Assoc, CompoundAssoc, Substitution } TypeKind;
  enum { Protocol, BaseClass, SameType, SameShape, Layout, PackMarker, Inverse } ConstraintKind;

  NodePointer inverseKind = nullptr;
  switch (nextChar()) {
    case 'v': ConstraintKind = PackMarker; TypeKind = Generic; break;
    case 'c': ConstraintKind = BaseClass; TypeKind = Assoc; break;
    case 'C': ConstraintKind = BaseClass; TypeKind = CompoundAssoc; break;
    case 'b': ConstraintKind = BaseClass; TypeKind = Generic; break;
    case 'B': ConstraintKind = BaseClass; TypeKind = Substitution; break;
    case 't': ConstraintKind = SameType; TypeKind = Assoc; break;
    case 'T': ConstraintKind = SameType; TypeKind = CompoundAssoc; break;
    case 's': ConstraintKind = SameType; TypeKind = Generic; break;
    case 'S': ConstraintKind = SameType; TypeKind = Substitution; break;
    case 'm': ConstraintKind = Layout; TypeKind = Assoc; break;
    case 'M': ConstraintKind = Layout; TypeKind = CompoundAssoc; break;
    case 'l': ConstraintKind = Layout; TypeKind = Generic; break;
    case 'L': ConstraintKind = Layout; TypeKind = Substitution; break;
    case 'p': ConstraintKind = Protocol; TypeKind = Assoc; break;
    case 'P': ConstraintKind = Protocol; TypeKind = CompoundAssoc; break;
    case 'Q': ConstraintKind = Protocol; TypeKind = Substitution; break;
    case 'h': ConstraintKind = SameShape; TypeKind = Generic; break;
    case 'i': 
      ConstraintKind = Inverse;
      TypeKind = Generic;
      inverseKind = demangleIndexAsNode();
      if (!inverseKind)
        return nullptr;
      break;
    case 'I': 
      ConstraintKind = Inverse;
      TypeKind = Substitution;
      inverseKind = demangleIndexAsNode();
      if (!inverseKind)
        return nullptr;
      break;
    default:  ConstraintKind = Protocol; TypeKind = Generic; pushBack(); break;
  }

  NodePointer ConstrTy = nullptr;

  switch (TypeKind) {
  case Generic:
    ConstrTy = createType(demangleGenericParamIndex());
    break;
  case Assoc:
    ConstrTy = demangleAssociatedTypeSimple(demangleGenericParamIndex());
    addSubstitution(ConstrTy);
    break;
  case CompoundAssoc:
    ConstrTy = demangleAssociatedTypeCompound(demangleGenericParamIndex());
    addSubstitution(ConstrTy);
    break;
  case Substitution:
    ConstrTy = popNode(Node::Kind::Type);
    break;
  }

  switch (ConstraintKind) {
  case PackMarker:
    return createWithChild(
        Node::Kind::DependentGenericParamPackMarker, ConstrTy);
  case Protocol:
    return createWithChildren(
        Node::Kind::DependentGenericConformanceRequirement, ConstrTy,
        popProtocol());
  case Inverse:
    return createWithChildren(
        Node::Kind::DependentGenericInverseConformanceRequirement,
        ConstrTy, inverseKind);
  case BaseClass:
    return createWithChildren(
        Node::Kind::DependentGenericConformanceRequirement, ConstrTy,
        popNode(Node::Kind::Type));
  case SameType:
    return createWithChildren(Node::Kind::DependentGenericSameTypeRequirement,
                              ConstrTy, popNode(Node::Kind::Type));
  case SameShape:
    return createWithChildren(Node::Kind::DependentGenericSameShapeRequirement,
                              ConstrTy, popNode(Node::Kind::Type));
  case Layout: {
    auto c = nextChar();
    NodePointer size = nullptr;
    NodePointer alignment = nullptr;
    const char *name = nullptr;
    if (c == 'U') {
      name = "U";
    } else if (c == 'R') {
      name = "R";
    } else if (c == 'N') {
      name = "N";
    } else if (c == 'C') {
      name = "C";
    } else if (c == 'D') {
      name = "D";
    } else if (c == 'T') {
      name = "T";
    } else if (c == 'B') {
      name = "B";
    } else if (c == 'E') {
      size = demangleIndexAsNode();
      if (!size)
        return nullptr;
      alignment = demangleIndexAsNode();
      name = "E";
    } else if (c == 'e') {
      size = demangleIndexAsNode();
      if (!size)
        return nullptr;
      name = "e";
    } else if (c == 'M') {
      size = demangleIndexAsNode();
      if (!size)
        return nullptr;
      alignment = demangleIndexAsNode();
      name = "M";
    } else if (c == 'm') {
      size = demangleIndexAsNode();
      if (!size)
        return nullptr;
      name = "m";
    } else if (c == 'S') {
      size = demangleIndexAsNode();
      if (!size)
        return nullptr;
      name = "S";
    } else {
      // Unknown layout constraint.
      return nullptr;
    }

    auto NameNode = createNode(Node::Kind::Identifier, name);
    auto NodeKind = Node::Kind::DependentGenericLayoutRequirement;
    auto LayoutRequirement = createWithChildren(NodeKind, ConstrTy, NameNode);
    if (size)
      addChild(LayoutRequirement, size);
    if (alignment)
      addChild(LayoutRequirement, alignment);
    return LayoutRequirement;
  }
  }
  return nullptr;
}

NodePointer Demangler::demangleGenericType() {
  NodePointer GenSig = popNode(Node::Kind::DependentGenericSignature);
  NodePointer Ty = popNode(Node::Kind::Type);
  return createType(createWithChildren(Node::Kind::DependentGenericType,
                                       GenSig, Ty));
}

static int decodeValueWitnessKind(StringRef CodeStr) {
#define VALUE_WITNESS(MANGLING, NAME) \
  if (CodeStr == #MANGLING) return (int)ValueWitnessKind::NAME;
#include "swift/Demangling/ValueWitnessMangling.def"
  return -1;
}

NodePointer Demangler::demangleValueWitness() {
  char Code[2];
  Code[0] = nextChar();
  Code[1] = nextChar();
  int Kind = decodeValueWitnessKind(StringRef(Code, 2));
  if (Kind < 0)
    return nullptr;
  NodePointer VW = createNode(Node::Kind::ValueWitness);
  addChild(VW, createNode(Node::Kind::Index, unsigned(Kind)));
  return addChild(VW, popNode(Node::Kind::Type));
}

static bool isMacroExpansionNodeKind(Node::Kind kind) {
  return kind == Node::Kind::AccessorAttachedMacroExpansion ||
         kind == Node::Kind::MemberAttributeAttachedMacroExpansion ||
         kind == Node::Kind::FreestandingMacroExpansion ||
         kind == Node::Kind::MemberAttachedMacroExpansion ||
         kind == Node::Kind::PeerAttachedMacroExpansion ||
         kind == Node::Kind::ConformanceAttachedMacroExpansion ||
         kind == Node::Kind::ExtensionAttachedMacroExpansion ||
         kind == Node::Kind::MacroExpansionLoc;
}

NodePointer Demangler::demangleMacroExpansion() {
  Node::Kind kind;
  bool isAttached;
  bool isFreestanding;
  switch (nextChar()) {
#define FREESTANDING_MACRO_ROLE(Name, Description)
#define ATTACHED_MACRO_ROLE(Name, Description, MangledChar)    \
  case MangledChar[0]:                                         \
    kind = Node::Kind::Name##AttachedMacroExpansion;           \
    isAttached = true;                                         \
    isFreestanding = false;                                    \
    break;
#include "swift/Basic/MacroRoles.def"

  case 'f':
    kind = Node::Kind::FreestandingMacroExpansion;
    isAttached = false;
    isFreestanding = true;
    break;

  case 'u':
    kind = Node::Kind::MacroExpansionUniqueName;
    isAttached = false;
    isFreestanding = false;
    break;

  case 'X': {
    kind = Node::Kind::MacroExpansionLoc;

    int line = demangleIndex();
    int col = demangleIndex();

    auto lineNode = createNode(Node::Kind::Index, line);
    auto colNode = createNode(Node::Kind::Index, col);

    NodePointer buffer = popNode(Node::Kind::Identifier);
    NodePointer module = popNode(Node::Kind::Identifier);
    return createWithChildren(kind, module, buffer, lineNode, colNode);
  }

  default:
    return nullptr;
  }

  NodePointer macroName = popNode(Node::Kind::Identifier);
  NodePointer privateDiscriminator = nullptr;
  if (isFreestanding)
    privateDiscriminator = popNode(Node::Kind::PrivateDeclName);
  NodePointer attachedName = nullptr;
  if (isAttached)
    attachedName = popNode(isDeclName);

  NodePointer context = popNode(isMacroExpansionNodeKind);
  if (!context)
    context = popContext();
  NodePointer discriminator = demangleIndexAsNode();
  NodePointer result;
  if (isAttached) {
    result = createWithChildren(
        kind, context, attachedName, macroName, discriminator);
  } else {
    result = createWithChildren(kind, context, macroName, discriminator);
  }
  if (privateDiscriminator)
    result->addChild(privateDiscriminator, *this);
  return result;
}