File: MetadataLookup.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 (3819 lines) | stat: -rw-r--r-- 138,535 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
//===--- MetadataLookup.cpp - Swift Language Type Name Lookup -------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Implementations of runtime functions for looking up a type by name.
//
//===----------------------------------------------------------------------===//

#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "ImageInspection.h"
#include "Private.h"
#include "Tracing.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/Basic/Lazy.h"
#include "swift/Basic/Range.h"
#include "swift/Demangling/Demangler.h"
#include "swift/Demangling/TypeDecoder.h"
#include "swift/RemoteInspection/Records.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Concurrent.h"
#include "swift/Runtime/Debug.h"
#include "swift/Runtime/EnvironmentVariables.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/LibPrespecialized.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Strings.h"
#include "swift/Threading/Mutex.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringExtras.h"
#include <cctype>
#include <cstring>
#include <functional>
#include <list>
#include <new>
#include <optional>
#include <vector>

using namespace swift;
using namespace Demangle;
using namespace reflection;

#if SWIFT_OBJC_INTEROP
#include <objc/runtime.h>
#include <objc/message.h>
#include <objc/objc.h>
#include <dlfcn.h>
#endif

#if __has_include(<mach-o/dyld_priv.h>)
#include <mach-o/dyld_priv.h>
#endif

/// A Demangler suitable for resolving runtime type metadata strings.
template <class Base = Demangler>
class DemanglerForRuntimeTypeResolution : public Base {
public:
  using Base::demangleSymbol;
  using Base::demangleType;

  // Force callers to explicitly pass `nullptr` to demangleSymbol or
  // demangleType if they don't want to demangle symbolic references.
  NodePointer demangleSymbol(StringRef symbolName) = delete;
  NodePointer demangleType(StringRef typeName) = delete;

  NodePointer demangleTypeRef(StringRef symbolName) {
    // Resolve symbolic references to type contexts into the absolute address of
    // the type context descriptor, so that if we see a symbolic reference in
    // the mangled name we can immediately find the associated metadata.
    return Base::demangleType(symbolName,
                              ResolveAsSymbolicReference(*this));
  }
};

/// Resolve the relative reference in a mangled symbolic reference.
static uintptr_t resolveSymbolicReferenceOffset(SymbolicReferenceKind kind,
                                                Directness isIndirect,
                                                int32_t offset,
                                                const void *base) {
  uintptr_t ptr;
  // Function references may be resolved differently than other data references.
  switch (kind) {
  case SymbolicReferenceKind::AccessorFunctionReference:
    ptr = (uintptr_t)TargetCompactFunctionPointer<InProcess, void>::resolve(base, offset);
    break;
  default:
    ptr = detail::applyRelativeOffset(base, offset);
    break;
  }

  // Indirect references may be authenticated in a way appropriate for the
  // referent.
  if (isIndirect == Directness::Indirect) {
    switch (kind) {
    case SymbolicReferenceKind::Context: {
      ContextDescriptor *contextPtr =
        *(const TargetSignedContextPointer<InProcess> *)ptr;
      return (uintptr_t)contextPtr;
    }
    case SymbolicReferenceKind::ObjectiveCProtocol:
    case SymbolicReferenceKind::UniqueExtendedExistentialTypeShape:
    case SymbolicReferenceKind::NonUniqueExtendedExistentialTypeShape:
    case SymbolicReferenceKind::AccessorFunctionReference: {
      swift_unreachable("should not be indirectly referenced");
    }
    }
    swift_unreachable("unknown symbolic reference kind");
  } else {
    return ptr;
  }
}

NodePointer
ResolveAsSymbolicReference::operator()(SymbolicReferenceKind kind,
                                       Directness isIndirect,
                                       int32_t offset,
                                       const void *base) {
  // Resolve the absolute pointer to the entity being referenced.
  auto ptr = resolveSymbolicReferenceOffset(kind, isIndirect, offset, base);
  if (SWIFT_UNLIKELY(!ptr)) {
    auto symInfo = SymbolInfo::lookup(base);
    const char *fileName = "<unknown>";
    const char *symbolName = "<unknown>";
    if (symInfo) {
      if (symInfo->getFilename())
        fileName = symInfo->getFilename();
      if (symInfo->getSymbolName())
        symbolName = symInfo->getSymbolName();
    }
    swift::fatalError(
        0,
        "Failed to look up symbolic reference at %p - offset %" PRId32
        " - symbol %s in %s\n",
        base, offset, symbolName, fileName);
  }

  // Figure out this symbolic reference's grammatical role.
  Node::Kind nodeKind;
  bool isType;
  switch (kind) {
  case Demangle::SymbolicReferenceKind::Context: {
    auto descriptor = (const ContextDescriptor *)ptr;
    switch (descriptor->getKind()) {
    case ContextDescriptorKind::Protocol:
      nodeKind = Node::Kind::ProtocolSymbolicReference;
      isType = false;
      break;
    
    case ContextDescriptorKind::OpaqueType:
      nodeKind = Node::Kind::OpaqueTypeDescriptorSymbolicReference;
      isType = false;
      break;
        
    default:
      if (auto typeContext = dyn_cast<TypeContextDescriptor>(descriptor)) {
        nodeKind = Node::Kind::TypeSymbolicReference;
        isType = true;
        break;
      }
      
      // References to other kinds of context aren't yet implemented.
      return nullptr;
    }
    break;
  }
  case Demangle::SymbolicReferenceKind::AccessorFunctionReference: {
    // Save the pointer to the accessor function. We can't demangle it any
    // further as AST, but the consumer of the demangle tree may be able to
    // invoke the function to resolve the thing they're trying to access.
    nodeKind = Node::Kind::AccessorFunctionReference;
    isType = false;
#if SWIFT_PTRAUTH
    // The pointer refers to an accessor function, which we need to sign.
    ptr = (uintptr_t)ptrauth_sign_unauthenticated((void*)ptr,
      ptrauth_key_function_pointer, 0);
#endif
    break;
  }
  case Demangle::SymbolicReferenceKind::UniqueExtendedExistentialTypeShape:
    nodeKind = Node::Kind::UniqueExtendedExistentialTypeShapeSymbolicReference;
    isType = false;
#if SWIFT_PTRAUTH
    ptr = (uintptr_t)ptrauth_sign_unauthenticated((void*)ptr,
      ptrauth_key_process_independent_data,
      SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape);
#endif
    break;
  case Demangle::SymbolicReferenceKind::NonUniqueExtendedExistentialTypeShape:
    nodeKind = Node::Kind::NonUniqueExtendedExistentialTypeShapeSymbolicReference;
    isType = false;
#if SWIFT_PTRAUTH
    ptr = (uintptr_t)ptrauth_sign_unauthenticated((void*)ptr,
      ptrauth_key_process_independent_data,
      SpecialPointerAuthDiscriminators::NonUniqueExtendedExistentialTypeShape);
#endif
    break;
  case Demangle::SymbolicReferenceKind::ObjectiveCProtocol:
    nodeKind = Node::Kind::ObjectiveCProtocolSymbolicReference;
    isType = false;
    break;
  }
  
  auto node = Dem.createNode(nodeKind, ptr);
  if (isType) {
    auto typeNode = Dem.createNode(Node::Kind::Type);
    typeNode->addChild(node, Dem);
    node = typeNode;
  }
  return node;
}

static NodePointer
_buildDemanglingForSymbolicReference(SymbolicReferenceKind kind,
                                     const void *resolvedReference,
                                     Demangler &Dem) {
  switch (kind) {
  case SymbolicReferenceKind::Context:
    return _buildDemanglingForContext(
        (const ContextDescriptor *)resolvedReference, {}, Dem);

  case SymbolicReferenceKind::AccessorFunctionReference:
#if SWIFT_PTRAUTH
    // The pointer refers to an accessor function, which we need to sign.
    resolvedReference = ptrauth_sign_unauthenticated(resolvedReference,
      ptrauth_key_function_pointer, 0);
#endif
    return Dem.createNode(Node::Kind::AccessorFunctionReference,
                          (uintptr_t)resolvedReference);

  case SymbolicReferenceKind::UniqueExtendedExistentialTypeShape:
#if SWIFT_PTRAUTH
    resolvedReference = ptrauth_sign_unauthenticated(resolvedReference,
      ptrauth_key_process_independent_data,
      SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape);
#endif
    return Dem.createNode(Node::Kind::UniqueExtendedExistentialTypeShapeSymbolicReference,
                          (uintptr_t)resolvedReference);

  case SymbolicReferenceKind::NonUniqueExtendedExistentialTypeShape:
#if SWIFT_PTRAUTH
    // The pointer refers to an accessor function, which we need to sign.
    resolvedReference = ptrauth_sign_unauthenticated(resolvedReference,
      ptrauth_key_process_independent_data,
      SpecialPointerAuthDiscriminators::NonUniqueExtendedExistentialTypeShape);
#endif
    return Dem.createNode(Node::Kind::NonUniqueExtendedExistentialTypeShapeSymbolicReference,
                          (uintptr_t)resolvedReference);
  case SymbolicReferenceKind::ObjectiveCProtocol:
    return Dem.createNode(Node::Kind::ObjectiveCProtocolSymbolicReference,
                          (uintptr_t)resolvedReference);
  }

  swift_unreachable("invalid symbolic reference kind");
}
  
NodePointer
ResolveToDemanglingForContext::operator()(SymbolicReferenceKind kind,
                                          Directness isIndirect,
                                          int32_t offset,
                                          const void *base) {
  auto ptr = resolveSymbolicReferenceOffset(kind, isIndirect, offset, base);

  return _buildDemanglingForSymbolicReference(kind, (const void *)ptr, Dem);
}

NodePointer
ExpandResolvedSymbolicReferences::operator()(SymbolicReferenceKind kind,
                                             const void *ptr) {
  return _buildDemanglingForSymbolicReference(kind, (const void *)ptr, Dem);
}

#pragma mark Nominal type descriptor cache
// Type Metadata Cache.

namespace {
  struct TypeMetadataSection {
    const TypeMetadataRecord *Begin, *End;
    const TypeMetadataRecord *begin() const {
      return Begin;
    }
    const TypeMetadataRecord *end() const {
      return End;
    }
  };

  struct NominalTypeDescriptorCacheEntry {
  private:
    const char *Name;
    size_t NameLength;
    const ContextDescriptor *Description;

  public:
    NominalTypeDescriptorCacheEntry(const llvm::StringRef name,
                                    const ContextDescriptor *description)
        : Description(description) {
      char *nameCopy = reinterpret_cast<char *>(malloc(name.size()));
      memcpy(nameCopy, name.data(), name.size());
      Name = nameCopy;
      NameLength = name.size();
    }

    const ContextDescriptor *getDescription() const { return Description; }

    bool matchesKey(llvm::StringRef aName) {
      return aName == llvm::StringRef{Name, NameLength};
    }

    friend llvm::hash_code
    hash_value(const NominalTypeDescriptorCacheEntry &value) {
      return hash_value(llvm::StringRef{value.Name, value.NameLength});
    }

    template <class... T>
    static size_t getExtraAllocationSize(T &&... ignored) {
      return 0;
    }
  };
} // end anonymous namespace

#if DYLD_GET_SWIFT_PRESPECIALIZED_DATA_DEFINED
struct SharedCacheInfoState {
  uintptr_t dyldSharedCacheStart;
  uintptr_t dyldSharedCacheEnd;

  bool inSharedCache(const void *ptr) {
    auto uintPtr = reinterpret_cast<uintptr_t>(ptr);
    return dyldSharedCacheStart <= uintPtr && uintPtr < dyldSharedCacheEnd;
  }

  SharedCacheInfoState() {
    size_t length;
    dyldSharedCacheStart = (uintptr_t)_dyld_get_shared_cache_range(&length);
    dyldSharedCacheEnd =
        dyldSharedCacheStart ? dyldSharedCacheStart + length : 0;
  }
};

static Lazy<SharedCacheInfoState> SharedCacheInfo;
#endif

struct TypeMetadataPrivateState {
  ConcurrentReadableHashMap<NominalTypeDescriptorCacheEntry> NominalCache;
  ConcurrentReadableArray<TypeMetadataSection> SectionsToScan;

#if DYLD_GET_SWIFT_PRESPECIALIZED_DATA_DEFINED
  ConcurrentReadableArray<TypeMetadataSection> SharedCacheSectionsToScan;
#endif

  TypeMetadataPrivateState() {
    initializeTypeMetadataRecordLookup();
  }
};

static Lazy<TypeMetadataPrivateState> TypeMetadataRecords;

static void
_registerTypeMetadataRecords(TypeMetadataPrivateState &T,
                             const TypeMetadataRecord *begin,
                             const TypeMetadataRecord *end) {
#if DYLD_GET_SWIFT_PRESPECIALIZED_DATA_DEFINED
  if (SharedCacheInfo.get().inSharedCache(begin)) {
    T.SharedCacheSectionsToScan.push_back(TypeMetadataSection{begin, end});
    return;
  }
#endif
  T.SectionsToScan.push_back(TypeMetadataSection{begin, end});
}

void swift::addImageTypeMetadataRecordBlockCallbackUnsafe(
    const void *baseAddress,
    const void *records, uintptr_t recordsSize) {
  assert(recordsSize % sizeof(TypeMetadataRecord) == 0
         && "weird-sized type metadata section?!");

  libPrespecializedImageLoaded();

  // If we have a section, enqueue the type metadata for lookup.
  auto recordBytes = reinterpret_cast<const char *>(records);
  auto recordsBegin
    = reinterpret_cast<const TypeMetadataRecord*>(records);
  auto recordsEnd
    = reinterpret_cast<const TypeMetadataRecord*>(recordBytes + recordsSize);

  // Type metadata cache should always be sufficiently initialized by this
  // point. Attempting to go through get() may also lead to an infinite loop,
  // since we register records during the initialization of
  // TypeMetadataRecords.
  _registerTypeMetadataRecords(TypeMetadataRecords.unsafeGetAlreadyInitialized(),
                               recordsBegin, recordsEnd);
}

void swift::addImageTypeMetadataRecordBlockCallback(const void *baseAddress,
                                                    const void *records,
                                                    uintptr_t recordsSize) {
  TypeMetadataRecords.get();
  addImageTypeMetadataRecordBlockCallbackUnsafe(baseAddress,
                                                records, recordsSize);
}

void
swift::swift_registerTypeMetadataRecords(const TypeMetadataRecord *begin,
                                         const TypeMetadataRecord *end) {
  auto &T = TypeMetadataRecords.get();
  _registerTypeMetadataRecords(T, begin, end);
}

static const ContextDescriptor *
_findContextDescriptor(Demangle::NodePointer node,
                           Demangle::Demangler &Dem);

/// Find the context descriptor for the type extended by the given extension.
///
/// If \p maybeExtension isn't actually an extension context, returns nullptr.
static const ContextDescriptor *
_findExtendedTypeContextDescriptor(const ContextDescriptor *maybeExtension,
                                   Demangler &demangler,
                                   Demangle::NodePointer *demangledNode
                                     = nullptr) {
  auto extension = dyn_cast<ExtensionContextDescriptor>(maybeExtension);
  if (!extension)
    return nullptr;

  Demangle::NodePointer localNode;
  Demangle::NodePointer &node = demangledNode ? *demangledNode : localNode;

  auto mangledName = extension->getMangledExtendedContext();
  
  // A extension of the form `extension Protocol where Self == ConcreteType`
  // is formally a protocol extension, so the formal generic parameter list
  // is `<Self>`, but because of the same type constraint, the extended context
  // looks like a reference to that nominal type. We want to match the
  // extension's formal generic environment rather than the nominal type's
  // in this case, so we should skip out on this case.
  //
  // We can detect this by looking at whether the generic context of the
  // extension has a first generic parameter, which would be the Self parameter,
  // with a same type constraint matching the extended type.
  for (auto &reqt : extension->getGenericRequirements()) {
    if (reqt.getKind() != GenericRequirementKind::SameType) {
      continue;
    }
    // 'x' is the mangling of the first generic parameter
    if (!reqt.getParam().equals("x")) {
      continue;
    }
    // Is the generic parameter same-type-constrained to the same type
    // we're extending? Then this is a `Self == ExtendedType` constraint.
    // This is impossible for normal generic nominal type extensions because
    // that would mean that you had:
    //   struct Foo<T> {...}
    //   extension Foo where T == Foo<T> {...}
    // which would mean that the extended type is the infinite expansion
    // Foo<Foo<Foo<Foo<...>>>>, which we don't allow.
    if (reqt.getMangledTypeName().data() == mangledName.data()) {
      return nullptr;
    }
  }
  
  node = demangler.demangleType(mangledName,
                                ResolveAsSymbolicReference(demangler));
  if (!node)
    return nullptr;
  if (node->getKind() == Node::Kind::Type) {
    if (node->getNumChildren() < 1)
      return nullptr;
    node = node->getChild(0);
  }
  if (Demangle::isSpecialized(node)) {
    auto unspec = Demangle::getUnspecialized(node, demangler);
    if (!unspec.isSuccess())
      return nullptr;
    node = unspec.result();
  }

  return _findContextDescriptor(node, demangler);
}

/// Recognize imported tag types, which have a special mangling rule.
///
/// This should be kept in sync with the AST mangler and with
/// buildContextDescriptorMangling in MetadataReader.
bool swift::_isCImportedTagType(const TypeContextDescriptor *type,
                                const ParsedTypeIdentity &identity) {
  // Tag types are always imported as structs or enums.
  if (type->getKind() != ContextDescriptorKind::Enum &&
      type->getKind() != ContextDescriptorKind::Struct)
    return false;

  // Not a typedef imported as a nominal type.
  if (identity.isCTypedef())
    return false;

  // Not a related entity.
  if (identity.isAnyRelatedEntity())
    return false;

  // Imported from C.
  return type->Parent->isCImportedContext();
}

ParsedTypeIdentity
ParsedTypeIdentity::parse(const TypeContextDescriptor *type) {
  ParsedTypeIdentity result;

  // The first component is the user-facing name and (unless overridden)
  // the ABI name.
  StringRef component = type->Name.get();
  result.UserFacingName = component;

  // If we don't have import info, we're done.
  if (!type->getTypeContextDescriptorFlags().hasImportInfo()) {
    result.FullIdentity = result.UserFacingName;
    return result;
  }

  // Otherwise, start parsing the import information.
  result.ImportInfo.emplace();

  // The identity starts with the user-facing name.
  const char *startOfIdentity = component.begin();
  const char *endOfIdentity = component.end();

#ifndef NDEBUG
  enum {
    AfterName,
    AfterABIName,
    AfterSymbolNamespace,
    AfterRelatedEntityName,
    AfterIdentity,
  } stage = AfterName;
#endif

  while (true) {
    // Parse the next component.  If it's empty, we're done.
    component = StringRef(component.end() + 1);
    if (component.empty()) break;

    // Update the identity bounds and assert that the identity
    // components are in the right order.
    auto kind = TypeImportComponent(component[0]);
    if (kind == TypeImportComponent::ABIName) {
#ifndef NDEBUG
      assert(stage < AfterABIName);
      stage = AfterABIName;
      assert(result.UserFacingName != component.drop_front(1) &&
             "user-facing name was same as the ABI name");
#endif
      startOfIdentity = component.begin() + 1;
      endOfIdentity = component.end();
    } else if (kind == TypeImportComponent::SymbolNamespace) {
#ifndef NDEBUG
      assert(stage < AfterSymbolNamespace);
      stage = AfterSymbolNamespace;
#endif
      endOfIdentity = component.end();
    } else if (kind == TypeImportComponent::RelatedEntityName) {
#ifndef NDEBUG
      assert(stage < AfterRelatedEntityName);
      stage = AfterRelatedEntityName;
#endif
      endOfIdentity = component.end();
    } else {
#ifndef NDEBUG
      // Anything else is assumed to not be part of the identity.
      stage = AfterIdentity;
#endif
    }

    // Collect the component, whatever it is.
    result.ImportInfo->collect</*asserting*/true>(component);
  }

#ifndef NDEBUG
  assert(stage != AfterName && "no components?");
#endif

  // Record the full identity.
  result.FullIdentity =
    StringRef(startOfIdentity, endOfIdentity - startOfIdentity);

  return result;
}

#if SWIFT_OBJC_INTEROP
/// Determine whether the two demangle trees both refer to the same
/// Objective-C class or protocol referenced by name.
static bool sameObjCTypeManglings(Demangle::NodePointer node1,
                                  Demangle::NodePointer node2) {
  // Entities need to be of the same kind.
  if (node1->getKind() != node2->getKind())
    return false;

  auto name1 = Demangle::getObjCClassOrProtocolName(node1);
  if (!name1) return false;

  auto name2 = Demangle::getObjCClassOrProtocolName(node2);
  if (!name2) return false;

  return *name1 == *name2;
}
#endif

/// Optimization for the case where we need to compare a StringRef and a null terminated C string
/// Not converting s2 to a StringRef avoids the need to call both strlen and memcmp when non-matching
/// but equal length
static bool stringRefEqualsCString(StringRef s1, const char *s2) {
  size_t length = s1.size();
  // It may be possible for s1 to contain embedded NULL characters
  // so additionally validate that the lengths match
  return strncmp(s1.data(), s2, length) == 0 && strlen(s2) == length;
}

bool
swift::_contextDescriptorMatchesMangling(const ContextDescriptor *context,
                                         Demangle::NodePointer node) {
  while (context) {
    if (node->getKind() == Demangle::Node::Kind::Type)
      node = node->getChild(0);
    
    // We can directly match symbolic references to the current context.
    if (node) {
      if (node->getKind() == Demangle::Node::Kind::TypeSymbolicReference
         || node->getKind() == Demangle::Node::Kind::ProtocolSymbolicReference){
        if (equalContexts(context,
               reinterpret_cast<const ContextDescriptor *>(node->getIndex()))) {
          return true;
        }
      }
    }

    switch (context->getKind()) {
    case ContextDescriptorKind::Module: {
      auto module = cast<ModuleContextDescriptor>(context);
      // Match to a mangled module name.
      if (node->getKind() != Demangle::Node::Kind::Module)
        return false;
      if (!stringRefEqualsCString(node->getText(), module->Name.get()))
        return false;
      
      node = nullptr;
      break;
    }
    
    case ContextDescriptorKind::Extension: {
      auto extension = cast<ExtensionContextDescriptor>(context);
      
      // Check whether the extension context matches the mangled context.
      if (node->getKind() != Demangle::Node::Kind::Extension)
        return false;
      if (node->getNumChildren() < 2)
        return false;
      
      // Check that the context being extended matches as well.
      auto extendedContextNode = node->getChild(1);
      DemanglerForRuntimeTypeResolution<> demangler;

      auto extendedDescriptorFromNode =
        _findContextDescriptor(extendedContextNode, demangler);

      Demangle::NodePointer extendedContextDemangled;
      auto extendedDescriptorFromDemangled =
        _findExtendedTypeContextDescriptor(extension, demangler,
                                           &extendedContextDemangled);

      // Determine whether the contexts match.
      bool contextsMatch =
        extendedDescriptorFromNode && extendedDescriptorFromDemangled &&
        equalContexts(extendedDescriptorFromNode,
                      extendedDescriptorFromDemangled);
      
#if SWIFT_OBJC_INTEROP
      // If we have manglings of the same Objective-C type, the contexts match.
      if (!contextsMatch &&
          (!extendedDescriptorFromNode || !extendedDescriptorFromDemangled) &&
          sameObjCTypeManglings(extendedContextNode,
                                extendedContextDemangled)) {
        contextsMatch = true;
      }
#endif

      if (!contextsMatch)
        return false;
      
      // Check whether the generic signature of the extension matches the
      // mangled constraints, if any.

      if (node->getNumChildren() >= 3) {
        // NB: If we ever support extensions with independent generic arguments
        // like `extension <T> Array where Element == Optional<T>`, we'd need
        // to look at the mangled context name to match up generic arguments.
        // That would probably need a new extension mangling form, though.
        
        // TODO
      }
      
      // The parent context of the extension should match in the mangling and
      // context descriptor.
      node = node->getChild(0);
      break;
    }

    case ContextDescriptorKind::Protocol:
      // Match a protocol context.
      if (node->getKind() == Demangle::Node::Kind::Protocol) {
        auto proto = llvm::cast<ProtocolDescriptor>(context);
        auto nameNode = node->getChild(1);
        if (nameNode->getKind() != Demangle::Node::Kind::Identifier)
          return false;
        if (stringRefEqualsCString(nameNode->getText(), proto->Name.get())) {
          node = node->getChild(0);
          break;
        }
      }
      return false;

    default:
      if (auto type = llvm::dyn_cast<TypeContextDescriptor>(context)) {
        std::optional<ParsedTypeIdentity> _identity;
        auto getIdentity = [&]() -> const ParsedTypeIdentity & {
          if (_identity) return *_identity;
          _identity = ParsedTypeIdentity::parse(type);
          return *_identity;
        };

        switch (node->getKind()) {
        // If the mangled name doesn't indicate a type kind, accept anything.
        // Otherwise, try to match them up.
        case Demangle::Node::Kind::OtherNominalType:
          break;
        case Demangle::Node::Kind::Structure:
          // We allow non-structs to match Kind::Structure if they are
          // imported C tag types.  This is necessary because we artificially
          // make imported C tag types Kind::Structure.
          if (type->getKind() != ContextDescriptorKind::Struct &&
              !_isCImportedTagType(type, getIdentity()))
            return false;
          break;
        case Demangle::Node::Kind::Class:
          if (type->getKind() != ContextDescriptorKind::Class)
            return false;
          break;
        case Demangle::Node::Kind::Enum:
          if (type->getKind() != ContextDescriptorKind::Enum)
            return false;
          break;
        case Demangle::Node::Kind::TypeAlias:
          if (!getIdentity().isCTypedef())
            return false;
          break;

        default:
          return false;
        }

        auto nameNode = node->getChild(1);
        
        // Declarations synthesized by the Clang importer get a small tag
        // string in addition to their name.
        if (nameNode->getKind() == Demangle::Node::Kind::RelatedEntityDeclName){          
          if (!getIdentity().isRelatedEntity(
                                        nameNode->getFirstChild()->getText()))
            return false;
          
          nameNode = nameNode->getChild(1);
        } else if (getIdentity().isAnyRelatedEntity()) {
          return false;
        }
        
        // We should only match public or internal declarations with stable
        // names. The runtime metadata for private declarations would be
        // anonymized.
        if (nameNode->getKind() == Demangle::Node::Kind::Identifier) {
          if (nameNode->getText() != getIdentity().getABIName())
            return false;
          
          node = node->getChild(0);
          break;
        }
        
        return false;

      }

      // We don't know about this kind of context, or it doesn't have a stable
      // name we can match to.
      return false;
    }
    
    context = context->Parent;
  }
  
  // We should have reached the top of the node tree at the same time we reached
  // the top of the context tree.
  if (node)
    return false;
  
  return true;
}

static const ContextDescriptor *getContextDescriptor(const TypeMetadataRecord &record) {
  return record.getContextDescriptor();
}

static const ContextDescriptor *getContextDescriptor(const ProtocolRecord &record) {
  return record.Protocol.getPointer();
}

template <typename SectionsContainer>
static const ContextDescriptor *_searchTypeMetadataRecordsInSections(
    SectionsContainer &sectionsToScan,
    Demangle::NodePointer node) {
  for (auto &section : sectionsToScan.snapshot()) {
    for (const auto &record : section) {
      if (auto context = getContextDescriptor(record)) {
        if (_contextDescriptorMatchesMangling(context, node)) {
          return context;
        }
      }
    }
  }

  return nullptr;
}

template <typename State, typename TraceBegin>
static const ContextDescriptor *_searchForContextDescriptor(State &state, NodePointer node, TraceBegin traceBegin) {
#if DYLD_GET_SWIFT_PRESPECIALIZED_DATA_DEFINED
  auto result = getLibPrespecializedTypeDescriptor(node);

  // Validate the result if requested.
  if (SWIFT_UNLIKELY(
          runtime::environment::
              SWIFT_DEBUG_VALIDATE_LIB_PRESPECIALIZED_DESCRIPTOR_LOOKUP())) {
    // Only validate a definitive result.
    if (result.first == LibPrespecializedLookupResult::Found ||
        result.first == LibPrespecializedLookupResult::DefinitiveNotFound) {
      // Perform a scan of the shared cache sections and see if the result
      // matches.
      auto scanResult = _searchTypeMetadataRecordsInSections(
          state.SharedCacheSectionsToScan, node);

      // Ignore a result that's outside the shared cache. This can happen for
      // indirect descriptor records that get fixed up to point to a root.
      if (SharedCacheInfo.get().inSharedCache(scanResult)) {
        // We may find a different but equivalent context if they're not unique,
        // as iteration order may be different between the two. Use
        // equalContexts to compare distinct but equal non-unique contexts
        // properly.
        if (!equalContexts(result.second, scanResult)) {
          auto tree = getNodeTreeAsString(node);
          swift::fatalError(
              0,
              "Searching for type descriptor, prespecialized descriptor map "
              "returned %p, but scan returned %p. Node tree:\n%s",
              result.second, scanResult, tree.c_str());
        }
      }
    }
  }

  if (result.first == LibPrespecializedLookupResult::Found) {
    assert(result.second);
    return result.second;
  }

  // If the result was not definitive, then we must search the shared cache
  // sections.
  if (result.first == LibPrespecializedLookupResult::NonDefinitiveNotFound) {
    auto traceState = traceBegin(node);
    auto descriptor =
        _searchTypeMetadataRecordsInSections(state.SharedCacheSectionsToScan, node);
    traceState.end(descriptor);
    if (descriptor)
      return descriptor;
  }

  // If we didn't find anything in the shared cache, then search the rest.
#endif

  auto traceState = traceBegin(node);
  auto foundDescriptor = _searchTypeMetadataRecordsInSections(state.SectionsToScan, node);
  traceState.end(foundDescriptor);
  return foundDescriptor;
}

// returns the nominal type descriptor for the type named by typeName
static const ContextDescriptor *
_searchTypeMetadataRecords(TypeMetadataPrivateState &T,
                           Demangle::NodePointer node) {
#if SWIFT_OBJC_INTEROP
  // Classes in the __C module are ObjC classes. They never have a
  // nominal type descriptor, so don't bother to search for one.
  if (node && node->getKind() == Node::Kind::Class)
    if (auto child = node->getFirstChild())
      if (child->getKind() == Node::Kind::Module && child->hasText())
        if (child->getText() == MANGLING_MODULE_OBJC)
          return nullptr;
#endif

  return _searchForContextDescriptor(T, node, runtime::trace::metadata_scan_begin);
}

#define DESCRIPTOR_MANGLING_SUFFIX_Structure Mn
#define DESCRIPTOR_MANGLING_SUFFIX_Enum Mn
#define DESCRIPTOR_MANGLING_SUFFIX_Protocol Mp

#define DESCRIPTOR_MANGLING_SUFFIX_(X) X
#define DESCRIPTOR_MANGLING_SUFFIX(KIND) \
  DESCRIPTOR_MANGLING_SUFFIX_(DESCRIPTOR_MANGLING_SUFFIX_ ## KIND)

#define DESCRIPTOR_MANGLING_(CHAR, SUFFIX) \
  $sS ## CHAR ## SUFFIX
#define DESCRIPTOR_MANGLING(CHAR, SUFFIX) DESCRIPTOR_MANGLING_(CHAR, SUFFIX)

#define STANDARD_TYPE(KIND, MANGLING, TYPENAME) \
  extern "C" const ContextDescriptor DESCRIPTOR_MANGLING(MANGLING, DESCRIPTOR_MANGLING_SUFFIX(KIND));

// FIXME: When the _Concurrency library gets merged into the Standard Library,
// we will be able to reference those symbols directly as well.
#define STANDARD_TYPE_CONCURRENCY(KIND, MANGLING, TYPENAME)

#if !SWIFT_OBJC_INTEROP
# define OBJC_INTEROP_STANDARD_TYPE(KIND, MANGLING, TYPENAME)
#endif

#include "swift/Demangling/StandardTypesMangling.def"

static const ConcurrencyStandardTypeDescriptors *concurrencyDescriptors;

/// Perform a fast-path lookup for standard library type references with short
/// manglings. Returns the appropriate descriptor, or NULL if the descriptor
/// couldn't be resolved, or if the node does not refer to one of those types.
static const ContextDescriptor *
descriptorFromStandardMangling(Demangle::NodePointer symbolicNode) {
#if SWIFT_STDLIB_SHORT_MANGLING_LOOKUPS
  // Fast-path lookup for standard library type references with short manglings.
  if (symbolicNode->getNumChildren() >= 2
      && symbolicNode->getChild(0)->getKind() == Node::Kind::Module
      && symbolicNode->getChild(0)->getText().equals("Swift")
      && symbolicNode->getChild(1)->getKind() == Node::Kind::Identifier) {
    auto name = symbolicNode->getChild(1)->getText();

#define STANDARD_TYPE(KIND, MANGLING, TYPENAME) \
    if (name.equals(#TYPENAME)) { \
      return &DESCRIPTOR_MANGLING(MANGLING, DESCRIPTOR_MANGLING_SUFFIX(KIND)); \
    }
  // FIXME: When the _Concurrency library gets merged into the Standard Library,
  // we will be able to reference those symbols directly as well.
#define STANDARD_TYPE_CONCURRENCY(KIND, MANGLING, TYPENAME)                    \
  if (concurrencyDescriptors && name.equals(#TYPENAME)) {                      \
    return concurrencyDescriptors->TYPENAME;                                   \
  }
#if !SWIFT_OBJC_INTEROP
# define OBJC_INTEROP_STANDARD_TYPE(KIND, MANGLING, TYPENAME)
#endif

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

static const ContextDescriptor *
_findContextDescriptor(Demangle::NodePointer node,
                       Demangle::Demangler &Dem) {
  NodePointer symbolicNode = node;
  if (symbolicNode->getKind() == Node::Kind::Type)
    symbolicNode = symbolicNode->getChild(0);

  // If we have a symbolic reference to a context, resolve it immediately.
  if (symbolicNode->getKind() == Node::Kind::TypeSymbolicReference) {
    return cast<TypeContextDescriptor>(
      (const ContextDescriptor *)symbolicNode->getIndex());
  }

  if (auto *standardDescriptor = descriptorFromStandardMangling(symbolicNode))
    return standardDescriptor;
  
  const ContextDescriptor *foundContext = nullptr;
  auto &T = TypeMetadataRecords.get();

  // Nothing to resolve if have a generic parameter.
  if (symbolicNode->getKind() == Node::Kind::DependentGenericParamType)
    return nullptr;

  auto mangling =
    Demangle::mangleNode(node, ExpandResolvedSymbolicReferences(Dem), Dem);

  if (!mangling.isSuccess())
    return nullptr;

  StringRef mangledName = mangling.result();


  // Look for an existing entry.
  // Find the bucket for the metadata entry.
  {
    auto snapshot = T.NominalCache.snapshot();
    if (auto Value = snapshot.find(mangledName))
      return Value->getDescription();
  }

  // Check type metadata records		   
  // Scan any newly loaded images for context descriptors, then try the context
  foundContext = _searchTypeMetadataRecords(T, node);
  
  // Check protocol conformances table. Note that this has no support for		
  // resolving generic types yet.
  if (!foundContext)
    foundContext = _searchConformancesByMangledTypeName(node);
  
  if (foundContext)
    T.NominalCache.getOrInsert(mangledName, [&](NominalTypeDescriptorCacheEntry
                                                    *entry,
                                                bool created) {
      if (created)
        ::new (entry) NominalTypeDescriptorCacheEntry{mangledName, foundContext};
      return true;
    });

  return foundContext;
}

void swift::_swift_registerConcurrencyStandardTypeDescriptors(
    const ConcurrencyStandardTypeDescriptors *descriptors) {
  concurrencyDescriptors = descriptors;
}

#pragma mark Protocol descriptor cache
namespace {
  struct ProtocolSection {
    const ProtocolRecord *Begin, *End;

    const ProtocolRecord *begin() const {
      return Begin;
    }
    const ProtocolRecord *end() const {
      return End;
    }
  };

  struct ProtocolDescriptorCacheEntry {
  private:
    const char *Name;
    size_t NameLength;
    const ProtocolDescriptor *Description;

  public:
    ProtocolDescriptorCacheEntry(const llvm::StringRef name,
                                 const ProtocolDescriptor *description)
        : Description(description) {
      char *nameCopy = reinterpret_cast<char *>(malloc(name.size()));
      memcpy(nameCopy, name.data(), name.size());
      Name = nameCopy;
      NameLength = name.size();
    }

    const ProtocolDescriptor *getDescription() const { return Description; }

    bool matchesKey(llvm::StringRef aName) {
      return aName == llvm::StringRef{Name, NameLength};
    }

    friend llvm::hash_code
    hash_value(const ProtocolDescriptorCacheEntry &value) {
      return hash_value(llvm::StringRef{value.Name, value.NameLength});
    }

    template <class... T>
    static size_t getExtraAllocationSize(T &&... ignored) {
      return 0;
    }
  };

  struct ProtocolMetadataPrivateState {
    ConcurrentReadableHashMap<ProtocolDescriptorCacheEntry> ProtocolCache;
    ConcurrentReadableArray<ProtocolSection> SectionsToScan;

#if DYLD_GET_SWIFT_PRESPECIALIZED_DATA_DEFINED
    ConcurrentReadableArray<ProtocolSection> SharedCacheSectionsToScan;
#endif

    ProtocolMetadataPrivateState() {
      initializeProtocolLookup();
    }
  };

  static Lazy<ProtocolMetadataPrivateState> Protocols;
}

static void
_registerProtocols(ProtocolMetadataPrivateState &C,
                   const ProtocolRecord *begin,
                   const ProtocolRecord *end) {
#if DYLD_GET_SWIFT_PRESPECIALIZED_DATA_DEFINED
  if (SharedCacheInfo.get().inSharedCache(begin)) {
    C.SharedCacheSectionsToScan.push_back(ProtocolSection{begin, end});
    return;
  }
#endif
  C.SectionsToScan.push_back(ProtocolSection{begin, end});
}

void swift::addImageProtocolsBlockCallbackUnsafe(const void *baseAddress,
                                                 const void *protocols,
                                                 uintptr_t protocolsSize) {
  assert(protocolsSize % sizeof(ProtocolRecord) == 0 &&
         "protocols section not a multiple of ProtocolRecord");

  // If we have a section, enqueue the protocols for lookup.
  auto protocolsBytes = reinterpret_cast<const char *>(protocols);
  auto recordsBegin
    = reinterpret_cast<const ProtocolRecord *>(protocols);
  auto recordsEnd
    = reinterpret_cast<const ProtocolRecord *>(protocolsBytes + protocolsSize);

  // Conformance cache should always be sufficiently initialized by this point.
  _registerProtocols(Protocols.unsafeGetAlreadyInitialized(),
                     recordsBegin, recordsEnd);
}

void swift::addImageProtocolsBlockCallback(const void *baseAddress,
                                           const void *protocols,
                                           uintptr_t protocolsSize) {
  Protocols.get();
  addImageProtocolsBlockCallbackUnsafe(baseAddress, protocols, protocolsSize);
}

void swift::swift_registerProtocols(const ProtocolRecord *begin,
                                    const ProtocolRecord *end) {
  auto &C = Protocols.get();
  _registerProtocols(C, begin, end);
}

static const ProtocolDescriptor *
_searchProtocolRecords(ProtocolMetadataPrivateState &C,
                       NodePointer node) {
  auto descriptor = _searchForContextDescriptor(C, node, runtime::trace::protocol_scan_begin);
  assert(!descriptor || isa<ProtocolDescriptor>(descriptor) && "Protocol record search found non-protocol descriptor.");
  return reinterpret_cast<const ProtocolDescriptor *>(descriptor);
}

static const ProtocolDescriptor *
_findProtocolDescriptor(NodePointer node,
                        Demangle::Demangler &Dem) {
  const ProtocolDescriptor *foundProtocol = nullptr;
  auto &T = Protocols.get();

  // If we have a symbolic reference to a context, resolve it immediately.
  NodePointer symbolicNode = node;
  if (symbolicNode->getKind() == Node::Kind::Type)
    symbolicNode = symbolicNode->getChild(0);
  if (symbolicNode->getKind() == Node::Kind::ProtocolSymbolicReference)
    return cast<ProtocolDescriptor>(
      (const ContextDescriptor *)symbolicNode->getIndex());

  if (auto *standardDescriptor = descriptorFromStandardMangling(symbolicNode)) {
    assert(standardDescriptor->getKind() == ContextDescriptorKind::Protocol);
    return static_cast<const ProtocolDescriptor *>(standardDescriptor);
  }

  auto mangling =
    Demangle::mangleNode(node, ExpandResolvedSymbolicReferences(Dem), Dem);

  if (!mangling.isSuccess())
    return nullptr;

  auto mangledName = mangling.result().str();

  // Look for an existing entry.
  // Find the bucket for the metadata entry.
  {
    auto snapshot = T.ProtocolCache.snapshot();
    if (auto Value = snapshot.find(mangledName))
      return Value->getDescription();
  }

  // Check type metadata records
  foundProtocol = _searchProtocolRecords(T, node);

  if (foundProtocol) {
    T.ProtocolCache.getOrInsert(mangledName, [&](ProtocolDescriptorCacheEntry
                                                     *entry,
                                                 bool created) {
      if (created)
        ::new (entry) ProtocolDescriptorCacheEntry{mangledName, foundProtocol};
      return true;
    });
  }

  return foundProtocol;
}

#pragma mark Type field descriptor cache
namespace {
struct FieldDescriptorCacheEntry {
private:
  const Metadata *Type;
  const FieldDescriptor *Description;

public:
  FieldDescriptorCacheEntry(const Metadata *type,
                            const FieldDescriptor *description)
      : Type(type), Description(description) {}

  const FieldDescriptor *getDescription() { return Description; }

  int compareWithKey(const Metadata *other) const {
    auto a = (uintptr_t)Type;
    auto b = (uintptr_t)other;
    return a == b ? 0 : (a < b ? -1 : 1);
  }

  template <class... Args>
  static size_t getExtraAllocationSize(Args &&... ignored) {
    return 0;
  }
};

} // namespace

#pragma mark Metadata lookup via mangled name

std::optional<unsigned>
swift::_depthIndexToFlatIndex(unsigned depth, unsigned index,
                              llvm::ArrayRef<unsigned> paramCounts) {
  // Out-of-bounds depth.
  if (depth >= paramCounts.size())
    return std::nullopt;

  // Compute the flat index.
  unsigned flatIndex = index + (depth == 0 ? 0 : paramCounts[depth - 1]);

  // Out-of-bounds index.
  if (flatIndex >= paramCounts[depth])
    return std::nullopt;

  return flatIndex;
}

/// Gather generic parameter counts from a context descriptor.
///
/// \returns true if the innermost descriptor is generic.
bool swift::_gatherGenericParameterCounts(
    const ContextDescriptor *descriptor,
    llvm::SmallVectorImpl<unsigned> &genericParamCounts,
    Demangler &BorrowFrom) {
  DemanglerForRuntimeTypeResolution<> demangler;
  demangler.providePreallocatedMemory(BorrowFrom);

  if (auto extension = _findExtendedTypeContextDescriptor(descriptor,
                                                          demangler)) {
    // If we have a nominal type extension descriptor, extract the extended type
    // and use that. If the extension is not nominal, then we can use the
    // extension's own signature.
    descriptor = extension;
  }

  // Once we hit a non-generic descriptor, we're done.
  if (!descriptor->isGeneric()) return false;

  // Recurse to record the parent context's generic parameters.
  auto parent = descriptor->Parent.get();
  (void)_gatherGenericParameterCounts(parent, genericParamCounts, demangler);

  // Record a new level of generic parameters if the count exceeds the
  // previous count.
  unsigned parentCount = parent->getNumGenericParams();
  unsigned myCount = descriptor->getNumGenericParams();
  if (myCount > parentCount) {
    genericParamCounts.push_back(myCount);
    return true;
  }

  return false;
}

/// Retrieve the generic parameters introduced in this context.
static llvm::ArrayRef<GenericParamDescriptor>
getLocalGenericParams(const ContextDescriptor *context) {
  if (!context->isGeneric())
    return { };

  // Determine where to start looking at generic parameters.
  unsigned startParamIndex;
  if (auto parent = context->Parent.get())
    startParamIndex = parent->getNumGenericParams();
  else
    startParamIndex = 0;

  auto genericContext = context->getGenericContext();
  return genericContext->getGenericParams().slice(startParamIndex);
}

namespace {

/// Function object that produces substitutions for the generic parameters
/// that occur within a mangled name, using the complete set of generic
/// arguments "as written".
///
/// Use with \c _getTypeByMangledName to decode potentially-generic types.
class SubstGenericParametersFromWrittenArgs {
  /// The complete set of generic arguments.
  const llvm::SmallVectorImpl<MetadataOrPack> &allGenericArgs;

  /// The counts of generic parameters at each level.
  const llvm::SmallVectorImpl<unsigned> &genericParamCounts;

public:
  /// Initialize a new function object to handle substitutions. Both
  /// parameters are references to vectors that must live longer than
  /// this function object.
  ///
  /// \param allGenericArgs The complete set of generic arguments, as written.
  /// This could come directly from "source" (where all generic arguments are
  /// encoded) or from metadata via gatherWrittenGenericArgs().
  ///
  /// \param genericParamCounts The count of generic parameters at each
  /// generic level, typically gathered by _gatherGenericParameterCounts.
  explicit SubstGenericParametersFromWrittenArgs(
      const llvm::SmallVectorImpl<MetadataOrPack> &allGenericArgs,
      const llvm::SmallVectorImpl<unsigned> &genericParamCounts)
      : allGenericArgs(allGenericArgs),
        genericParamCounts(genericParamCounts) {}

  MetadataOrPack getMetadata(unsigned depth, unsigned index) const;
  MetadataOrPack getMetadataFullOrdinal(unsigned ordinal) const;
  const WitnessTable *getWitnessTable(const Metadata *type,
                                      unsigned index) const;
};

}  // end anonymous namespace

static std::optional<TypeLookupError>
_gatherGenericParameters(const ContextDescriptor *context,
                         llvm::ArrayRef<MetadataOrPack> genericArgs,
                         const Metadata *parent,
                         llvm::SmallVectorImpl<unsigned> &genericParamCounts,
                         llvm::SmallVectorImpl<const void *> &allGenericArgsVec,
                         Demangler &demangler) {
  auto makeCommonErrorStringGetter = [&] {
    auto metadataVector = genericArgs.vec();
    return [=] {
      std::string str;

      str += "_gatherGenericParameters: context: ";

      if (auto contextInfo = SymbolInfo::lookup(context)) {
        str += contextInfo->getSymbolName();
        str += " ";
      }

      char *contextStr;
      swift_asprintf(&contextStr, "%p", context);
      str += contextStr;
      free(contextStr);

      str += " <";

      bool first = true;
      for (MetadataOrPack metadata : genericArgs) {
        if (!first)
          str += ", ";
        first = false;
        str += metadata.nameForMetadata();
      }

      str += "> ";

      str += "parent: ";
      if (parent)
        str += nameForMetadata(parent);
      else
        str += "<null>";
      str += " - ";

      return str;
    };
  };

  // Figure out the various levels of generic parameters we have in
  // this type.
  (void)_gatherGenericParameterCounts(context,
                                      genericParamCounts, demangler);
  unsigned numTotalGenericParams =
    genericParamCounts.empty() ? context->getNumGenericParams()
                               : genericParamCounts.back();
  
  // Check whether we have the right number of generic arguments.
  if (genericArgs.size() == getLocalGenericParams(context).size()) {
    // Okay: genericArgs is the innermost set of generic arguments.
  } else if (genericArgs.size() == numTotalGenericParams && !parent) {
    // Okay: genericArgs is the complete set of generic arguments.
  } else {
    auto commonString = makeCommonErrorStringGetter();
    auto genericArgsSize = genericArgs.size();
    return TypeLookupError([=] {
      return commonString() + "incorrect number of generic args (" +
             std::to_string(genericArgsSize) + "), " +
             std::to_string(getLocalGenericParams(context).size()) +
             " local params, " + std::to_string(numTotalGenericParams) +
             " total params";
    });
  }
  
  // If there are generic parameters at any level, check the generic
  // requirements and fill in the generic arguments vector.
  if (!genericParamCounts.empty()) {
    // Compute the set of generic arguments "as written".
    llvm::SmallVector<MetadataOrPack, 8> allGenericArgs;

    auto generics = context->getGenericContext();
    assert(generics);

    // If we have a parent, gather its generic arguments "as written". If our
    // parent is not generic, there are no generic arguments to add.
    if (parent && parent->getTypeContextDescriptor() &&
        parent->getTypeContextDescriptor()->getGenericContext()) {
      auto parentDescriptor = parent->getTypeContextDescriptor();
      auto parentGenerics = parentDescriptor->getGenericContext();
      auto packHeader = parentGenerics->getGenericPackShapeHeader();

      // _gatherWrittenGenericParameters expects to immediately read key generic
      // arguments, so skip past the shape classes if we have any.
      auto nonShapeClassGenericArgs = parent->getGenericArgs() + packHeader.NumShapeClasses;

      auto numKeyArgs = 0;
      for (auto param : parentGenerics->getGenericParams()) {
        if (param.hasKeyArgument()) {
          numKeyArgs += 1;
        }
      }

      llvm::ArrayRef<const void *> genericArgsRef(
          reinterpret_cast<const void * const *>(nonShapeClassGenericArgs),
          numKeyArgs);

      if (!_gatherWrittenGenericParameters(parentDescriptor,
                                           genericArgsRef,
                                           allGenericArgs, demangler)) {
        auto commonString = makeCommonErrorStringGetter();
        return TypeLookupError([=] {
          return commonString() + "failed to get parent context's written" +
                 " generic arguments";
        });
      }
    }
    
    // Add the generic arguments we were given.
    allGenericArgs.insert(allGenericArgs.end(),
                          genericArgs.begin(), genericArgs.end());
    
    // Copy the generic arguments needed for metadata from the generic
    // arguments "as written".
    {
      // Add a placeholder length for each shape class.
      auto packShapeHeader = generics->getGenericPackShapeHeader();
      if (packShapeHeader.NumShapeClasses > 0) {
        assert(allGenericArgsVec.empty());
        allGenericArgsVec.resize(packShapeHeader.NumShapeClasses);
      }

      // If we have the wrong number of generic arguments, fail.
      auto genericParams = generics->getGenericParams();
      unsigned n = genericParams.size();
      if (allGenericArgs.size() != n) {
        auto commonString = makeCommonErrorStringGetter();
        auto argsVecSize = allGenericArgsVec.size();
        return TypeLookupError([=] {
          return commonString() + "have " + std::to_string(argsVecSize) +
                 "generic args, expected " + std::to_string(n);
        });
      }

      // Add metadata for each canonical generic parameter.
      auto packShapeDescriptors = generics->getGenericPackShapeDescriptors();
      unsigned packIdx = 0;

      for (unsigned i = 0; i != n; ++i) {
        const auto &param = genericParams[i];
        auto arg = allGenericArgs[i];

        switch (param.getKind()) {
        case GenericParamKind::Type: {
          if (!arg.isMetadata()) {
            auto commonString = makeCommonErrorStringGetter();
            return TypeLookupError([=] {
              return commonString() + "param " + std::to_string(i) +
                     " expected metadata but got a metadata pack";
            });
          }

          if (param.hasKeyArgument()) {
            allGenericArgsVec.push_back(arg.getMetadata());
          }

          break;
        }
        case GenericParamKind::TypePack: {
          if (!arg.isMetadataPack()) {
            auto commonString = makeCommonErrorStringGetter();
            return TypeLookupError([=] {
              return commonString() + "param " + std::to_string(i) +
                     " expected a metadata pack but got metadata";
            });
          }

          if (param.hasKeyArgument()) {
            auto packShapeDescriptor = packShapeDescriptors[packIdx];
            assert(packShapeDescriptor.Kind == GenericPackKind::Metadata);
            assert(packShapeDescriptor.Index == allGenericArgsVec.size());
            assert(packShapeDescriptor.ShapeClass < packShapeHeader.NumShapeClasses);

            auto argPack = arg.getMetadataPack();
            assert(argPack.getLifetime() == PackLifetime::OnHeap);

            // Fill in the length for each shape class.
            allGenericArgsVec[packShapeDescriptor.ShapeClass] =
                reinterpret_cast<const void *>(argPack.getNumElements());

            allGenericArgsVec.push_back(argPack.getPointer());
            ++packIdx;
          }

          break;
        }
        default:
          auto commonString = makeCommonErrorStringGetter();
          return TypeLookupError([=] {
            return commonString() + "param " + std::to_string(i) +
                   " has unexpected kind " +
                   std::to_string(static_cast<uint8_t>(param.getKind()));
          });
        }
      }
    }

    // Check whether the generic requirements are satisfied, collecting
    // any extra arguments we need for the instantiation function.
    SubstGenericParametersFromWrittenArgs substitutions(allGenericArgs,
                                                        genericParamCounts);
    auto error = _checkGenericRequirements(
        generics->getGenericParams(),
        generics->getGenericRequirements(), allGenericArgsVec,
        [&substitutions](unsigned depth, unsigned index) {
          return substitutions.getMetadata(depth, index).Ptr;
        },
        [&substitutions](unsigned fullOrdinal, unsigned keyOrdinal) {
          return substitutions.getMetadataFullOrdinal(fullOrdinal).Ptr;
        },
        [&substitutions](const Metadata *type, unsigned index) {
          return substitutions.getWitnessTable(type, index);
        });
    if (error)
      return *error;

    // If we still have the wrong number of generic arguments, this is
    // some kind of metadata mismatch.
    if (generics->getGenericContextHeader().getNumArguments() !=
        allGenericArgsVec.size()) {
      auto commonString = makeCommonErrorStringGetter();
      auto argsVecSize = allGenericArgsVec.size();
      return TypeLookupError([=] {
        return commonString() + "generic argument count mismatch, expected " +
               std::to_string(
                   generics->getGenericContextHeader().getNumArguments()) +
               ", have " + std::to_string(argsVecSize);
      });
    }
  }

  return std::nullopt;
}

namespace {

/// Find the offset of the protocol requirement for an associated type with
/// the given name in the given protocol descriptor.
std::optional<const ProtocolRequirement *>
findAssociatedTypeByName(const ProtocolDescriptor *protocol, StringRef name) {
  // If we don't have associated type names, there's nothing to do.
  const char *associatedTypeNamesPtr = protocol->AssociatedTypeNames.get();
  if (!associatedTypeNamesPtr)
    return std::nullopt;

  // Look through the list of associated type names.
  StringRef associatedTypeNames(associatedTypeNamesPtr);
  unsigned matchingAssocTypeIdx = 0;
  bool found = false;
  while (!associatedTypeNames.empty()) {
    // Avoid using StringRef::split because its definition is not
    // provided in the header so that it requires linking with libSupport.a.
    auto splitIdx = associatedTypeNames.find(' ');
    if (associatedTypeNames.substr(0, splitIdx) == name) {
      found = true;
      break;
    }

    ++matchingAssocTypeIdx;
    associatedTypeNames = associatedTypeNames.substr(splitIdx).substr(1);
  }

  if (!found)
    return std::nullopt;

  // We have a match on the Nth associated type; go find the Nth associated
  // type requirement.
  unsigned currentAssocTypeIdx = 0;
  unsigned numRequirements = protocol->NumRequirements;
  auto requirements = protocol->getRequirements();
  for (unsigned reqIdx = 0; reqIdx != numRequirements; ++reqIdx) {
    if (requirements[reqIdx].Flags.getKind() !=
        ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction)
      continue;

    if (currentAssocTypeIdx == matchingAssocTypeIdx)
      return requirements.begin() + reqIdx;

    ++currentAssocTypeIdx;
  }

  swift_unreachable("associated type names don't line up");
}

} // end unnamed namespace

static Lazy<Mutex> DynamicReplacementLock;

namespace {
struct OpaqueTypeMappings {
  llvm::DenseMap<const OpaqueTypeDescriptor *, const OpaqueTypeDescriptor *>
      descriptorMapping;
  const OpaqueTypeDescriptor* find(const OpaqueTypeDescriptor *orig) {
    const OpaqueTypeDescriptor *replacement = nullptr;
    DynamicReplacementLock.get().withLock([&] {
      auto entry = descriptorMapping.find(orig);
      if (entry != descriptorMapping.end())
        replacement = entry->second;
    });
    return replacement;
  }

  // We take a mutex argument to make sure someone is holding the lock.
  void insert(const OpaqueTypeDescriptor *orig,
              const OpaqueTypeDescriptor *replacement, const Mutex &) {
    descriptorMapping[orig] = replacement;
  }
};
} // end unnamed namespace

static Lazy<OpaqueTypeMappings> opaqueTypeMappings;

static const OpaqueTypeDescriptor *
_findOpaqueTypeDescriptor(NodePointer demangleNode,
                          Demangler &dem) {
  // Directly resolve a symbolic reference.
  if (demangleNode->getKind()
        == Node::Kind::OpaqueTypeDescriptorSymbolicReference) {
    auto context = (const ContextDescriptor *)demangleNode->getIndex();
    auto *orig = cast<OpaqueTypeDescriptor>(context);
    if (auto *entry = opaqueTypeMappings.get().find(orig)) {
      return entry;
    }
    return orig;
  }
  
  // TODO: Find non-symbolic-referenced opaque decls.
  return nullptr;
}

#if SWIFT_OBJC_INTEROP
static Protocol *_asObjectiveCProtocol(NodePointer demangleNode) {
  if (demangleNode->getKind() ==
      Node::Kind::ObjectiveCProtocolSymbolicReference) {

    auto protocolPtr =
        ((RelativeDirectPointer<Protocol *, false> *)demangleNode->getIndex())
            ->get();
    Protocol *protocol = *protocolPtr;
    return protocol;
  }
  return nullptr;
}
#endif

namespace {

/// Constructs metadata by decoding a mangled type name, for use with
/// \c TypeDecoder.
class DecodedMetadataBuilder {
private:
  /// The demangler we'll use when building new nodes.
  Demangler &demangler;

  /// Substitute generic parameters.
  SubstGenericParameterFn substGenericParameter;

  /// Substitute dependent witness tables.
  SubstDependentWitnessTableFn substWitnessTable;

  /// Ownership information related to the metadata we are trying to lookup.
  TypeReferenceOwnership ReferenceOwnership;

  /// Stack of shape pack/current index pairs.
  std::vector<std::pair<MetadataPackPointer, size_t>> ActivePackExpansions;

public:
  using BuiltType = MetadataOrPack;

  struct BuiltLayoutConstraint {
    bool operator==(BuiltLayoutConstraint rhs) const { return true; }
    operator bool() const { return true; }
  };
  using BuiltLayoutConstraint = BuiltLayoutConstraint;
  using BuiltTypeDecl = const ContextDescriptor *;
  using BuiltProtocolDecl = ProtocolDescriptorRef;
  using BuiltGenericSignature = const Metadata *;
  using BuiltSubstitution = std::pair<BuiltType, BuiltType>;
  using BuiltSubstitutionMap = llvm::ArrayRef<BuiltSubstitution>;
  using BuiltGenericTypeParam = const Metadata *;

  struct BuiltRequirement {
    RequirementKind Kind;
    BuiltType FirstType;

    union {
      BuiltType SecondType;
      BuiltLayoutConstraint SecondLayout;
    };

    BuiltRequirement(RequirementKind kind, BuiltType first,
                     BuiltType second)
        : Kind(kind), FirstType(first), SecondType(second) {
      assert(first);
      assert(second);
      assert(kind != RequirementKind::Layout);
    }

    BuiltRequirement(RequirementKind kind, BuiltType first,
                     BuiltLayoutConstraint second)
        : Kind(kind), FirstType(first), SecondLayout(second) {
      assert(first);
      assert(second);
      assert(kind == RequirementKind::Layout);
    }

    /// Determine the kind of requirement.
    RequirementKind getKind() const {
      return Kind;
    }

    /// Retrieve the first type.
    BuiltType getFirstType() const {
      return FirstType;
    }

    /// Retrieve the second type.
    BuiltType getSecondType() const {
      assert(getKind() != RequirementKind::Layout);
      return SecondType;
    }

    /// Retrieve the layout constraint.
    BuiltLayoutConstraint getLayoutConstraint() const {
      assert(getKind() == RequirementKind::Layout);
      return SecondLayout;
    }
  };

  struct BuiltInverseRequirement {
    BuiltType SubjectType;
    InvertibleProtocolKind Kind;
  };

  DecodedMetadataBuilder(Demangler &demangler,
                         SubstGenericParameterFn substGenericParameter,
                         SubstDependentWitnessTableFn substWitnessTable)
    : demangler(demangler),
      substGenericParameter(substGenericParameter),
      substWitnessTable(substWitnessTable) { }

  BuiltType decodeMangledType(NodePointer node,
                              bool forRequirement = true) {
    return Demangle::decodeMangledType(*this, node, forRequirement)
        .getType();
  }

  Demangle::NodeFactory &getNodeFactory() { return demangler; }

  TypeLookupErrorOr<BuiltType>
  resolveOpaqueType(NodePointer opaqueDecl,
                    llvm::ArrayRef<llvm::ArrayRef<BuiltType>> genericArgs,
                    unsigned ordinal) {
    auto descriptor = _findOpaqueTypeDescriptor(opaqueDecl, demangler);
    if (!descriptor)
      return BuiltType();
    auto outerContext = descriptor->Parent.get();

    llvm::SmallVector<MetadataOrPack, 8> allGenericArgs;
    for (auto argSet : genericArgs)
      allGenericArgs.append(argSet.begin(), argSet.end());
    
    // Gather the generic parameters we need to parameterize the opaque decl.
    llvm::SmallVector<unsigned, 8> genericParamCounts;
    llvm::SmallVector<const void *, 8> allGenericArgsVec;

    if (auto error = _gatherGenericParameters(
            outerContext, allGenericArgs, nullptr, /* no parent */
            genericParamCounts, allGenericArgsVec, demangler))
      return *error;

    auto mangledName = descriptor->getUnderlyingTypeArgument(ordinal);
    SubstGenericParametersFromMetadata substitutions(descriptor,
                                                     allGenericArgsVec.data());
    return BuiltType(
        swift_getTypeByMangledName(MetadataState::Complete,
                                   mangledName, allGenericArgsVec.data(),
        [&substitutions](unsigned depth, unsigned index) {
          return substitutions.getMetadata(depth, index).Ptr;
        },
        [&substitutions](const Metadata *type, unsigned index) {
          return substitutions.getWitnessTable(type, index);
        }).getType().getMetadata());
  }

  BuiltTypeDecl createTypeDecl(NodePointer node,
                               bool &typeAlias) const {
    // Look for a nominal type descriptor based on its mangled name.
    return _findContextDescriptor(node, demangler);
  }

  BuiltProtocolDecl createProtocolDecl(NodePointer node) const {
#if SWIFT_OBJC_INTEROP
    // Check for an objective c protocol symbolic reference.
    if (auto protocol = _asObjectiveCProtocol(node)) {
      return ProtocolDescriptorRef::forObjC(protocol);
    }
#endif

    // Look for a protocol descriptor based on its mangled name.
    if (auto protocol = _findProtocolDescriptor(node, demangler))
      return ProtocolDescriptorRef::forSwift(protocol);;

#if SWIFT_OBJC_INTEROP
    // Look for a Swift-defined @objc protocol with the Swift 3 mangling that
    // is used for Objective-C entities.
    auto mangling = mangleNodeAsObjcCString(node, demangler);
    if (mangling.isSuccess()) {
      const char *objcMangledName = mangling.result();
      if (auto protocol = objc_getProtocol(objcMangledName))
        return ProtocolDescriptorRef::forObjC(protocol);
    }
#endif

    return ProtocolDescriptorRef();
  }

  BuiltProtocolDecl createObjCProtocolDecl(
                                         const std::string &mangledName) const {
#if SWIFT_OBJC_INTEROP
    return ProtocolDescriptorRef::forObjC(
        objc_getProtocol(mangledName.c_str()));
#else
    return ProtocolDescriptorRef();
#endif
  }

  TypeLookupErrorOr<BuiltType>
  createObjCClassType(const std::string &mangledName) const {
#if SWIFT_OBJC_INTEROP
    auto objcClass = objc_getClass(mangledName.c_str());
    return BuiltType(
        swift_getObjCClassMetadata((const ClassMetadata *)objcClass));
#else
    return BuiltType();
#endif
  }

  TypeLookupErrorOr<BuiltType>
  createBoundGenericObjCClassType(const std::string &mangledName,
                                  llvm::ArrayRef<BuiltType> args) const {
    // Generic arguments of lightweight Objective-C generic classes are not
    // reified in the metadata.
    return createObjCClassType(mangledName);
  }

  TypeLookupErrorOr<BuiltType>
  createNominalType(BuiltTypeDecl metadataOrTypeDecl, BuiltType parent) const {
    // Treat nominal type creation the same way as generic type creation,
    // but with no generic arguments at this level.
    return createBoundGenericType(metadataOrTypeDecl, { }, parent);
  }

  TypeLookupErrorOr<BuiltType> createTypeAliasType(BuiltTypeDecl typeAliasDecl,
                                                   BuiltType parent) const {
    // We can't support sugared types here since we have no way to
    // resolve the underlying type of the type alias. However, some
    // CF types are mangled as type aliases.
    return createNominalType(typeAliasDecl, parent);
  }

  TypeLookupErrorOr<BuiltType>
  createBoundGenericType(BuiltTypeDecl anyTypeDecl,
                         llvm::ArrayRef<BuiltType> genericArgs,
                         BuiltType parent) const {
    auto typeDecl = dyn_cast<TypeContextDescriptor>(anyTypeDecl);
    if (!typeDecl) {
      if (auto protocol = dyn_cast<ProtocolDescriptor>(anyTypeDecl))
        return BuiltType(_getSimpleProtocolTypeMetadata(protocol));

      return BuiltType();
    }

    if (!parent.isMetadataOrNull()) {
      return TYPE_LOOKUP_ERROR_FMT("Tried to build a bound generic type where "
                                   "the parent type is a pack");
    }

    // Figure out the various levels of generic parameters we have in
    // this type.
    llvm::SmallVector<unsigned, 8> genericParamCounts;
    llvm::SmallVector<const void *, 8> allGenericArgsVec;

    if (auto error = _gatherGenericParameters(typeDecl, genericArgs,
                                              parent.getMetadataOrNull(),
                                              genericParamCounts,
                                              allGenericArgsVec, demangler))
      return *error;

    // Call the access function.
    auto accessFunction = typeDecl->getAccessFunction();
    if (!accessFunction) return BuiltType();

    return BuiltType(accessFunction(MetadataState::Abstract,
                                    allGenericArgsVec));
  }

  TypeLookupErrorOr<BuiltType>
  createSymbolicExtendedExistentialType(NodePointer shapeNode,
                                  llvm::ArrayRef<BuiltType> genArgs) const {
    const ExtendedExistentialTypeShape *shape;
    if (shapeNode->getKind() ==
          Node::Kind::UniqueExtendedExistentialTypeShapeSymbolicReference) {
      shape = reinterpret_cast<const ExtendedExistentialTypeShape *>(
                shapeNode->getIndex());
    } else if (shapeNode->getKind() ==
        Node::Kind::NonUniqueExtendedExistentialTypeShapeSymbolicReference) {
      auto nonUniqueShape =
        reinterpret_cast<const NonUniqueExtendedExistentialTypeShape *>(
                shapeNode->getIndex());
      shape = swift_getExtendedExistentialTypeShape(nonUniqueShape);
    } else {
      return TYPE_LOOKUP_ERROR_FMT("Tried to build an extended existential "
                                   "metatype from an unexpected shape node");
    }

    auto rawShape =
      swift_auth_data_non_address(shape,
          SpecialPointerAuthDiscriminators::ExtendedExistentialTypeShape);
    auto genSig = rawShape->getGeneralizationSignature();

    // Collect the type arguments; they should all be key arguments.
    if (genArgs.size() != genSig.getParams().size())
      return TYPE_LOOKUP_ERROR_FMT("Length mismatch building an extended "
                                   "existential metatype");
    llvm::SmallVector<const void *, 8> allArgsVec;

    // FIXME: variadic-generics
    for (auto arg : genArgs)
      allArgsVec.push_back(arg.getMetadata());

    // Collect any other generic arguments.
    auto error = _checkGenericRequirements(
        genSig.getParams(), genSig.getRequirements(), allArgsVec,
        [genArgs](unsigned depth, unsigned index) -> const Metadata * {
          if (depth != 0 || index >= genArgs.size())
            return (const Metadata*)nullptr;

          // FIXME: variadic generics
          return genArgs[index].getMetadata();
        },
        [genArgs](unsigned fullOrdinal, unsigned keyOrdinal) {
          if (fullOrdinal >= genArgs.size())
            return (const Metadata*)nullptr;

          // FIXME: variadic generics
          return genArgs[fullOrdinal].getMetadata();
        },
        [](const Metadata *type, unsigned index) -> const WitnessTable * {
          swift_unreachable("never called");
        });
    if (error)
      return *error;

    return BuiltType(
        swift_getExtendedExistentialTypeMetadata_unique(shape,
                                                        allArgsVec.data()));
  }

  TypeLookupErrorOr<BuiltType> createBuiltinType(StringRef builtinName,
                                                 StringRef mangledName) const {
#define BUILTIN_TYPE(Symbol, _) \
    if (mangledName.equals(#Symbol)) \
      return BuiltType(&METADATA_SYM(Symbol).base);
#if !SWIFT_STDLIB_ENABLE_VECTOR_TYPES
#define BUILTIN_VECTOR_TYPE(ElementSymbol, ElementName, Width)
#endif
#include "swift/Runtime/BuiltinTypes.def"
    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType>
  createMetatypeType(BuiltType instance,
                     std::optional<Demangle::ImplMetatypeRepresentation> repr =
                         std::nullopt) const {
    if (!instance.isMetadata())
      return TYPE_LOOKUP_ERROR_FMT("Tried to build a metatype from a pack");
    return BuiltType(swift_getMetatypeMetadata(instance.getMetadata()));
  }

  TypeLookupErrorOr<BuiltType> createExistentialMetatypeType(
      BuiltType instance,
      std::optional<Demangle::ImplMetatypeRepresentation> repr =
          std::nullopt) const {
    if (!instance.isMetadata()) {
      return TYPE_LOOKUP_ERROR_FMT("Tried to build an existential metatype "
                                   "from a pack");
    }
    auto *instanceMetadata = instance.getMetadata();
    if (instanceMetadata->getKind() != MetadataKind::Existential
        && instanceMetadata->getKind() != MetadataKind::ExistentialMetatype) {
      return TYPE_LOOKUP_ERROR_FMT("Tried to build an existential metatype from "
                                   "a type that was neither an existential nor "
                                   "an existential metatype");
    }
    return BuiltType(swift_getExistentialMetatypeMetadata(instanceMetadata));
  }

  TypeLookupErrorOr<BuiltType>
  createProtocolCompositionType(llvm::ArrayRef<BuiltProtocolDecl> protocols,
                                BuiltType superclass, bool isClassBound,
                                bool forRequirement = true) const {
    // Determine whether we have a class bound.
    ProtocolClassConstraint classConstraint = ProtocolClassConstraint::Any;
    if (isClassBound || superclass) {
      classConstraint = ProtocolClassConstraint::Class;
    } else {
      for (auto protocol : protocols) {
        if (protocol.getClassConstraint() == ProtocolClassConstraint::Class) {
          classConstraint = ProtocolClassConstraint::Class;
          break;
        }
      }
    }

    if (!superclass.isMetadataOrNull()) {
      return TYPE_LOOKUP_ERROR_FMT("Tried to build a protocol composition where "
                                   "the superclass type is a pack");
    }
    return BuiltType(
        swift_getExistentialTypeMetadata(classConstraint,
                                         superclass.getMetadataOrNull(),
                                         protocols.size(), protocols.data()));
  }

  TypeLookupErrorOr<BuiltType>
  createConstrainedExistentialType(
      BuiltType base,
      llvm::ArrayRef<BuiltRequirement> rs,
      llvm::ArrayRef<BuiltInverseRequirement> InverseRequirements) const {
    // FIXME: Runtime plumbing.
    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType> createDynamicSelfType(BuiltType selfType) const {
    // Free-standing mangled type strings should not contain DynamicSelfType.
    return BuiltType();
  }

  void pushGenericParams(llvm::ArrayRef<std::pair<unsigned, unsigned>> parameterPacks) {}
  void popGenericParams() {}

  BuiltType
  createGenericTypeParameterType(unsigned depth, unsigned index) const {
    // Use the callback, when provided.
    if (substGenericParameter) {
      BuiltType substType(substGenericParameter(depth, index));

      // If we're in the middle of a pack expansion, return the correct element
      // from the substituted pack type.
      if (!ActivePackExpansions.empty()) {
        size_t index = ActivePackExpansions.back().second;
        if (substType.isMetadataPack()) {
          auto substPack = substType.getMetadataPack();
          if (index >= substPack.getNumElements()) {
            swift::fatalError(0, "Pack index %zu exceeds pack length %zu\n",
                              index, substPack.getNumElements());
          }

          return BuiltType(substPack.getElements()[index]);
        }
      }

      return substType;
    }

    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType>
  createFunctionType(
      llvm::ArrayRef<Demangle::FunctionParam<BuiltType>> params,
      BuiltType result, FunctionTypeFlags flags,
      ExtendedFunctionTypeFlags extFlags,
      FunctionMetadataDifferentiabilityKind diffKind,
      BuiltType globalActorType, BuiltType thrownError) const {
    assert(
        (flags.isDifferentiable() && diffKind.isDifferentiable()) ||
        (!flags.isDifferentiable() && !diffKind.isDifferentiable()));

    if (!result.isMetadata()) {
      return TYPE_LOOKUP_ERROR_FMT("Tried to build a function type where "
                                   "the result type is a pack");
    }

    llvm::SmallVector<const Metadata *, 8> paramTypes;
    llvm::SmallVector<uint32_t, 8> paramFlags;

    // Fill in the parameters.
    paramTypes.reserve(params.size());
    if (flags.hasParameterFlags())
      paramFlags.reserve(params.size());
    for (const auto &param : params) {
      if (!param.getType().isMetadata()) {
        return TYPE_LOOKUP_ERROR_FMT("Tried to build a function type where "
                                     "a parameter type is a pack");
      }
      paramTypes.push_back(param.getType().getMetadata());
      if (flags.hasParameterFlags())
        paramFlags.push_back(param.getFlags().getIntValue());
    }

    if (globalActorType) {
      if (!globalActorType.isMetadata()) {
        return TYPE_LOOKUP_ERROR_FMT("Tried to build a function type where "
                                     "the global actor type is a pack");
      }
      flags = flags.withGlobalActor(true);
    }

    return BuiltType(
        swift_getExtendedFunctionTypeMetadata(
            flags, diffKind, paramTypes.data(),
            flags.hasParameterFlags() ? paramFlags.data() : nullptr,
            result.getMetadata(), globalActorType.getMetadataOrNull(), extFlags,
            thrownError.getMetadataOrNull()));
  }

  TypeLookupErrorOr<BuiltType> createImplFunctionType(
      Demangle::ImplParameterConvention calleeConvention,
      llvm::ArrayRef<Demangle::ImplFunctionParam<BuiltType>> params,
      llvm::ArrayRef<Demangle::ImplFunctionResult<BuiltType>> results,
      std::optional<Demangle::ImplFunctionResult<BuiltType>> errorResult,
      ImplFunctionTypeFlags flags) {
    // We can't realize the metadata for a SILFunctionType.
    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType>
  createTupleType(llvm::ArrayRef<BuiltType> elements,
                  llvm::ArrayRef<StringRef> labels) const {
    // Unwrap unlabeled one-element tuples.
    //
    // FIXME: The behavior of one-element labeled tuples is inconsistent
    // throughout the different re-implementations of type substitution
    // and pack expansion.
    if (elements.size() == 1 && labels[0].empty())
      return elements[0];

    for (auto element : elements) {
      if (!element.isMetadata()) {
        return TYPE_LOOKUP_ERROR_FMT("Tried to build a tuple type where "
                                     "an element type is a pack");
      }
    }

    std::string labelStr;
    for (unsigned i : indices(labels)) {
      auto label = labels[i];
      if (label.empty()) {
        if (!labelStr.empty())
          labelStr += ' ';
        continue;
      }

      // Add spaces to terminate all the previous labels if this
      // is the first we've seen.
      if (labelStr.empty()) labelStr.append(i, ' ');

      // Add the label and its terminator.
      labelStr += label;
      labelStr += ' ';
    }

    auto flags = TupleTypeFlags().withNumElements(elements.size());
    if (!labelStr.empty())
      flags = flags.withNonConstantLabels(true);
    return BuiltType(
        swift_getTupleTypeMetadata(
          MetadataState::Abstract, flags,
          reinterpret_cast<const Metadata * const *>(elements.data()),
          labelStr.empty() ? nullptr : labelStr.c_str(),
          /*proposedWitnesses=*/nullptr));
  }

  TypeLookupErrorOr<BuiltType>
  createPackType(llvm::ArrayRef<BuiltType> elements) const {
    for (auto element : elements) {
      if (!element.isMetadata()) {
        return TYPE_LOOKUP_ERROR_FMT("Can't have nested metadata packs");
      }
    }

    MetadataPackPointer pack(swift_allocateMetadataPack(
        reinterpret_cast<const Metadata * const *>(elements.data()),
        elements.size()));

    return BuiltType(pack);
  }

  TypeLookupErrorOr<BuiltType>
  createSILPackType(llvm::ArrayRef<BuiltType> elements, bool isElementAddress) const {
    return TYPE_LOOKUP_ERROR_FMT("Lowered SILPackType cannot be demangled");
  }

  size_t beginPackExpansion(BuiltType countType) {
    if (!countType.isMetadataPack()) {
      swift::fatalError(0, "Pack expansion count type should be a pack\n");
    }

    auto pack = countType.getMetadataPack();
    ActivePackExpansions.emplace_back(pack, /*index=*/0);

    return pack.getNumElements();
  }

  void advancePackExpansion(size_t index) {
    if (ActivePackExpansions.empty()) {
      swift::fatalError(0, "advancePackExpansion() without beginPackExpansion()\n");
    }

    ActivePackExpansions.back().second = index;
  }

  BuiltType createExpandedPackElement(BuiltType patternType) {
    return patternType;
  }

  void endPackExpansion() {
    if (ActivePackExpansions.empty()) {
      swift::fatalError(0, "endPackExpansion() without beginPackExpansion()\n");
    }

    ActivePackExpansions.pop_back();
  }

  TypeLookupErrorOr<BuiltType> createDependentMemberType(StringRef name,
                                                         BuiltType base) const {
    return TYPE_LOOKUP_ERROR_FMT("Unbound dependent member type cannot be demangled");
  }

  TypeLookupErrorOr<BuiltType>
  createDependentMemberType(StringRef name, BuiltType base,
                            BuiltProtocolDecl protocol) const {
#if SWIFT_OBJC_INTEROP
    if (protocol.isObjC())
      return BuiltType();
#endif

    auto swiftProtocol = protocol.getSwiftProtocol();

    // Look for the named associated type within the protocol.
    auto assocType = findAssociatedTypeByName(swiftProtocol, name);
    if (!assocType) return BuiltType();

    auto projectDependentMemberType = [&](const Metadata *baseMetadata) -> const Metadata * {
      auto witnessTable = swift_conformsToProtocolCommon(baseMetadata, swiftProtocol);
      if (!witnessTable)
        return nullptr;

      // Call the associated type access function.
  #if SWIFT_STDLIB_USE_RELATIVE_PROTOCOL_WITNESS_TABLES
      auto tbl = reinterpret_cast<RelativeWitnessTable *>(
        const_cast<WitnessTable *>(witnessTable));
      return swift_getAssociatedTypeWitnessRelative(
                                   MetadataState::Abstract,
                                   tbl,
                                   baseMetadata,
                                   swiftProtocol->getRequirementBaseDescriptor(),
                                   *assocType).Value;
  #else
      return swift_getAssociatedTypeWitness(
                                   MetadataState::Abstract,
                                   const_cast<WitnessTable *>(witnessTable),
                                   baseMetadata,
                                   swiftProtocol->getRequirementBaseDescriptor(),
                                   *assocType).Value;
  #endif
    };

    if (base.isMetadata()) {
      return BuiltType(projectDependentMemberType(base.getMetadata()));
    } else {
      MetadataPackPointer basePack = base.getMetadataPack();

      llvm::SmallVector<const Metadata *, 4> packElts;
      for (size_t i = 0, e = basePack.getNumElements(); i < e; ++i) {
        auto *projectedElt = projectDependentMemberType(basePack.getElements()[i]);
        packElts.push_back(projectedElt);
      }

      return BuiltType(swift_allocateMetadataPack(packElts.data(), packElts.size()));
    }
  }

#define REF_STORAGE(Name, ...)                                                 \
  TypeLookupErrorOr<BuiltType> create##Name##StorageType(BuiltType base) {     \
    ReferenceOwnership.set##Name();                                            \
    return base;                                                               \
  }
#include "swift/AST/ReferenceStorage.def"

  TypeLookupErrorOr<BuiltType> createSILBoxType(BuiltType base) const {
    // FIXME: Implement.
    return BuiltType();
  }

  struct BuiltSILBoxField {
    BuiltType Type;
    bool Mutable;

    BuiltSILBoxField(BuiltType type, bool isMutable)
      : Type(type), Mutable(isMutable) {}
  };

  BuiltLayoutConstraint getLayoutConstraint(LayoutConstraintKind kind) {
    return {};
  }
  BuiltLayoutConstraint
  getLayoutConstraintWithSizeAlign(LayoutConstraintKind kind, unsigned size,
                                   unsigned alignment) {
    return {};
  }

  BuiltInverseRequirement createInverseRequirement(
      BuiltType subjectType, InvertibleProtocolKind kind) {
    return BuiltInverseRequirement{subjectType, kind};
  }

  TypeLookupErrorOr<BuiltType> createSILBoxTypeWithLayout(
      llvm::ArrayRef<BuiltSILBoxField> Fields,
      llvm::ArrayRef<BuiltSubstitution> Substitutions,
      llvm::ArrayRef<BuiltRequirement> Requirements,
      llvm::ArrayRef<BuiltInverseRequirement> InverseRequirements) const {
    // FIXME: Implement.
    return BuiltType();
  }

  bool isExistential(BuiltType) {
    // FIXME: Implement.
    return true;
  }

  TypeReferenceOwnership getReferenceOwnership() const {
    return ReferenceOwnership;
  }

  TypeLookupErrorOr<BuiltType> createOptionalType(BuiltType base) {
    // Mangled types for building metadata don't contain sugared types
    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType> createArrayType(BuiltType base) {
    // Mangled types for building metadata don't contain sugared types
    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType> createDictionaryType(BuiltType key,
                                                    BuiltType value) {
    // Mangled types for building metadata don't contain sugared types
    return BuiltType();
  }

  TypeLookupErrorOr<BuiltType> createParenType(BuiltType base) {
    // Mangled types for building metadata don't contain sugared types
    return BuiltType();
  }
};

}

SWIFT_CC(swift)
static TypeLookupErrorOr<TypeInfo>
swift_getTypeByMangledNodeImpl(MetadataRequest request, Demangler &demangler,
                               Demangle::NodePointer node,
                               const void *const *origArgumentVector,
                               SubstGenericParameterFn substGenericParam,
                               SubstDependentWitnessTableFn substWitnessTable) {
  // Simply call an accessor function if that's all we got.
  if (node->getKind() == Node::Kind::AccessorFunctionReference) {
    // The accessor function is passed the pointer to the original argument
    // buffer. It's assumed to match the generic context.
    auto accessorFn =
        (const Metadata *(*)(const void * const *))node->getIndex();
    auto type = accessorFn(origArgumentVector);
    // We don't call checkMetadataState here since the result may not really
    // *be* type metadata. If the accessor returns a type, it is responsible
    // for completing the metadata.
    return TypeInfo{MetadataResponse{type, MetadataState::Complete},
                    TypeReferenceOwnership()};
  }
    
  // TODO: propagate the request down to the builder instead of calling
  // swift_checkMetadataState after the fact.
  DecodedMetadataBuilder builder(demangler, substGenericParam,
                                 substWitnessTable);
  auto type = Demangle::decodeMangledType(builder, node);
  if (type.isError()) {
    return *type.getError();
  }
  if (!type.getType()) {
    return TypeLookupError("NULL type but no error provided");
  }

  if (!type.getType().isMetadata()) {
    return TypeLookupError("Cannot demangle a free-standing pack");
  }

  return TypeInfo{swift_checkMetadataState(request,
                  type.getType().getMetadata()),
                  builder.getReferenceOwnership()};
}

SWIFT_CC(swift)
static TypeLookupErrorOr<TypeInfo>
swift_getTypeByMangledNameImpl(MetadataRequest request, StringRef typeName,
                               const void *const *origArgumentVector,
                               SubstGenericParameterFn substGenericParam,
                               SubstDependentWitnessTableFn substWitnessTable) {
  DemanglerForRuntimeTypeResolution<StackAllocatedDemangler<2048>> demangler;

  NodePointer node;

  // Check whether this is the convenience syntax "ModuleName.ClassName".
  auto getDotPosForConvenienceSyntax = [&]() -> size_t {
    size_t dotPos = llvm::StringRef::npos;
    for (unsigned i = 0; i < typeName.size(); ++i) {
      // Should only contain one dot.
      if (typeName[i] == '.') {
        if (dotPos == llvm::StringRef::npos) {
          dotPos = i;
          continue;
        } else {
          return llvm::StringRef::npos;
        }
      }
      
      // Should not contain symbolic references.
      if ((unsigned char)typeName[i] <= '\x1F') {
        return llvm::StringRef::npos;
      }
    }
    return dotPos;
  };

  auto dotPos = getDotPosForConvenienceSyntax();
  if (dotPos != llvm::StringRef::npos) {
    // Form a demangle tree for this class.
    NodePointer classNode = demangler.createNode(Node::Kind::Class);
    NodePointer moduleNode = demangler.createNode(Node::Kind::Module,
                                                  typeName.substr(0, dotPos));
    NodePointer nameNode = demangler.createNode(Node::Kind::Identifier,
                                                typeName.substr(dotPos + 1));
    classNode->addChild(moduleNode, demangler);
    classNode->addChild(nameNode, demangler);

    node = classNode;
  } else {
    // Demangle the type name.
    node = demangler.demangleTypeRef(typeName);
    if (!node) {
      return TypeInfo();
    }
  }

  return swift_getTypeByMangledNode(request, demangler, node,
                                    origArgumentVector,
                                    substGenericParam, substWitnessTable);
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const Metadata * _Nullable
swift_getTypeByMangledNameInEnvironment(
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const TargetGenericEnvironment<InProcess> *environment,
                        const void * const *genericArgs) {
  llvm::StringRef typeName(typeNameStart, typeNameLength);
  SubstGenericParametersFromMetadata substitutions(environment, genericArgs);
  TypeLookupErrorOr<TypeInfo> result = swift_getTypeByMangledName(
    MetadataState::Complete, typeName,
    genericArgs,
    [&substitutions](unsigned depth, unsigned index) {
      return substitutions.getMetadata(depth, index).Ptr;
    },
    [&substitutions](const Metadata *type, unsigned index) {
      return substitutions.getWitnessTable(type, index);
    });
  if (result.isError()
      && runtime::environment::SWIFT_DEBUG_FAILED_TYPE_LOOKUP()) {
    TypeLookupError *error = result.getError();
    char *errorString = error->copyErrorString();
    swift::warning(0, "failed type lookup for %.*s: %s\n",
                   (int)typeNameLength, typeNameStart,
                   errorString);
    error->freeErrorString(errorString);
    return nullptr;
  }
  return result.getType().getMetadata();
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const Metadata * _Nullable
swift_getTypeByMangledNameInEnvironmentInMetadataState(
                        size_t metadataState,
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const TargetGenericEnvironment<InProcess> *environment,
                        const void * const *genericArgs) {
  llvm::StringRef typeName(typeNameStart, typeNameLength);
  SubstGenericParametersFromMetadata substitutions(environment, genericArgs);
  TypeLookupErrorOr<TypeInfo> result = swift_getTypeByMangledName(
    (MetadataState)metadataState, typeName,
    genericArgs,
    [&substitutions](unsigned depth, unsigned index) {
      return substitutions.getMetadata(depth, index).Ptr;
    },
    [&substitutions](const Metadata *type, unsigned index) {
      return substitutions.getWitnessTable(type, index);
    });
  if (result.isError()
      && runtime::environment::SWIFT_DEBUG_FAILED_TYPE_LOOKUP()) {
    TypeLookupError *error = result.getError();
    char *errorString = error->copyErrorString();
    swift::warning(0, "failed type lookup for %.*s: %s\n",
                   (int)typeNameLength, typeNameStart,
                   errorString);
    error->freeErrorString(errorString);
    return nullptr;
  }
  return result.getType().getMetadata();
}

static
const Metadata * _Nullable
swift_getTypeByMangledNameInContextImpl(
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const TargetContextDescriptor<InProcess> *context,
                        const void * const *genericArgs) {
  llvm::StringRef typeName(typeNameStart, typeNameLength);
  SubstGenericParametersFromMetadata substitutions(context, genericArgs);
  TypeLookupErrorOr<TypeInfo> result = swift_getTypeByMangledName(
    MetadataState::Complete, typeName,
    genericArgs,
    [&substitutions](unsigned depth, unsigned index) {
      return substitutions.getMetadata(depth, index).Ptr;
    },
    [&substitutions](const Metadata *type, unsigned index) {
      return substitutions.getWitnessTable(type, index);
    });
  if (result.isError()
      && runtime::environment::SWIFT_DEBUG_FAILED_TYPE_LOOKUP()) {
    TypeLookupError *error = result.getError();
    char *errorString = error->copyErrorString();
    swift::warning(0, "failed type lookup for %.*s: %s\n",
                   (int)typeNameLength, typeNameStart,
                   errorString);
    error->freeErrorString(errorString);
    return nullptr;
  }
  return result.getType().getMetadata();
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const Metadata * _Nullable
swift_getTypeByMangledNameInContext2(
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const TargetContextDescriptor<InProcess> *context,
                        const void * const *genericArgs) {
  context = swift_auth_data_non_address(
      context, SpecialPointerAuthDiscriminators::ContextDescriptor);
  return swift_getTypeByMangledNameInContextImpl(typeNameStart, typeNameLength,
                                                 context, genericArgs);
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const Metadata * _Nullable
swift_getTypeByMangledNameInContext(
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const void *context,
                        const void * const *genericArgs) {
  // This call takes `context` without a ptrauth signature. We
  // declare it as `void *` to avoid the implicit ptrauth we get from
  // the ptrauth_struct attribute. The static_cast implicitly signs the
  // pointer when we call through to the implementation in
  // swift_getTypeByMangledNameInContextImpl.
  return swift_getTypeByMangledNameInContextImpl(
      typeNameStart, typeNameLength,
      static_cast<const TargetContextDescriptor<InProcess> *>(context),
      genericArgs);
}

static
const Metadata * _Nullable
swift_getTypeByMangledNameInContextInMetadataStateImpl(
                        size_t metadataState,
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const TargetContextDescriptor<InProcess> *context,
                        const void * const *genericArgs) {
  llvm::StringRef typeName(typeNameStart, typeNameLength);
  SubstGenericParametersFromMetadata substitutions(context, genericArgs);
  TypeLookupErrorOr<TypeInfo> result = swift_getTypeByMangledName(
    (MetadataState)metadataState, typeName,
    genericArgs,
    [&substitutions](unsigned depth, unsigned index) {
      return substitutions.getMetadata(depth, index).Ptr;
    },
    [&substitutions](const Metadata *type, unsigned index) {
      return substitutions.getWitnessTable(type, index);
    });
  if (result.isError()
      && runtime::environment::SWIFT_DEBUG_FAILED_TYPE_LOOKUP()) {
    TypeLookupError *error = result.getError();
    char *errorString = error->copyErrorString();
    swift::warning(0, "failed type lookup for %.*s: %s\n",
                   (int)typeNameLength, typeNameStart,
                   errorString);
    error->freeErrorString(errorString);
    return nullptr;
  }
  return result.getType().getMetadata();
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const Metadata * _Nullable
swift_getTypeByMangledNameInContextInMetadataState2(
                        size_t metadataState,
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const TargetContextDescriptor<InProcess> *context,
                        const void * const *genericArgs) {
  context = swift_auth_data_non_address(
      context, SpecialPointerAuthDiscriminators::ContextDescriptor);
  return swift_getTypeByMangledNameInContextInMetadataStateImpl(
      metadataState, typeNameStart, typeNameLength, context, genericArgs);
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const Metadata * _Nullable
swift_getTypeByMangledNameInContextInMetadataState(
                        size_t metadataState,
                        const char *typeNameStart,
                        size_t typeNameLength,
                        const void *context,
                        const void * const *genericArgs) {
  // This call takes `descriptor` without a ptrauth signature. We
  // declare it as `void *` to avoid the implicit ptrauth we get from
  // the ptrauth_struct attribute. The static_cast implicitly signs the
  // pointer when we call through to the implementation in
  // swift_getTypeByMangledNameInContextInMetadataState2.
  return swift_getTypeByMangledNameInContextInMetadataStateImpl(
      metadataState, typeNameStart, typeNameLength,
      static_cast<const TargetContextDescriptor<InProcess> *>(context),
      genericArgs);
}

/// Demangle a mangled name, but don't allow symbolic references.
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
const Metadata *_Nullable
swift_stdlib_getTypeByMangledNameUntrusted(const char *typeNameStart,
                                           size_t typeNameLength) {
  llvm::StringRef typeName(typeNameStart, typeNameLength);
  for (char c : typeName) {
    if (c >= '\x01' && c <= '\x1F')
      return nullptr;
  }

  return swift_getTypeByMangledName(MetadataState::Complete, typeName, nullptr,
                                    {}, {}).getType().getMetadata();
}

TypeLookupErrorOr<MetadataPackPointer>
swift::getTypePackByMangledName(StringRef typeName,
                                const void *const *origArgumentVector,
                                SubstGenericParameterFn substGenericParam,
                                SubstDependentWitnessTableFn substWitnessTable) {
  DemanglerForRuntimeTypeResolution<StackAllocatedDemangler<2048>> demangler;

  NodePointer node = demangler.demangleTypeRef(typeName);
  if (!node)
    return TypeLookupError("Demangling failed");

  DecodedMetadataBuilder builder(demangler, substGenericParam,
                                 substWitnessTable);
  auto type = Demangle::decodeMangledType(builder, node);
  if (type.isError()) {
    return *type.getError();
  }
  if (!type.getType()) {
    return TypeLookupError("NULL type but no error provided");
  }

  if (!type.getType().isMetadataPack()) {
    return TypeLookupError("This entry point is only for packs");
  }

  return type.getType().getMetadataPack();
}

// ==== Function metadata functions ----------------------------------------------

static std::optional<llvm::StringRef> cstrToStringRef(const char *typeNameStart,
                                                      size_t typeNameLength) {
  llvm::StringRef typeName(typeNameStart, typeNameLength);
  for (char c : typeName) {
    if (c >= '\x01' && c <= '\x1F')
      return std::nullopt;
  }
  return typeName;
}

/// Given mangling for a method, extract its function type in demangled
/// representation.
static NodePointer extractFunctionTypeFromMethod(Demangler &demangler,
                                                 const char *typeNameStart,
                                                 size_t typeNameLength) {
  std::optional<llvm::StringRef> typeName =
      cstrToStringRef(typeNameStart, typeNameLength);
  if (!typeName)
    return nullptr;

  auto node = demangler.demangleSymbol(*typeName);
  if (!node)
    return nullptr;

  node = node->findByKind(Node::Kind::Function, /*maxDepth=*/2);
  if (!node)
    return nullptr;

  node = node->findByKind(Node::Kind::Type, /*maxDepth=*/2);
  if (!node)
    return nullptr;

  // If this is a generic function, it requires special handling.
  if (auto genericType =
          node->findByKind(Node::Kind::DependentGenericType, /*maxDepth=*/1)) {
    node = genericType->findByKind(Node::Kind::Type, /*maxDepth=*/1);
    return node->findByKind(Node::Kind::FunctionType, /*maxDepth=*/1);
  }

  auto funcType = node->getFirstChild();
  assert(funcType->getKind() == Node::Kind::FunctionType);
  return funcType;
}

/// For a single unlabeled parameter this function returns whole
/// `ArgumentTuple`, for everything else a `Tuple` element inside it.
static NodePointer getParameterList(NodePointer funcType) {
  assert(funcType->getKind() == Node::Kind::FunctionType);

  auto parameterContainer =
      funcType->findByKind(Node::Kind::ArgumentTuple, /*maxDepth=*/1);
  assert(parameterContainer->getNumChildren() > 0);

  // This is a type that covers entire parameter list.
  auto parameterList = parameterContainer->getFirstChild();
  assert(parameterList->getKind() == Node::Kind::Type);

  auto parameters = parameterList->getFirstChild();
  if (parameters->getKind() == Node::Kind::Tuple)
    return parameters;

  return parameterContainer;
}

static const Metadata *decodeType(TypeDecoder<DecodedMetadataBuilder> &decoder,
                                  NodePointer type) {
  assert(type->getKind() == Node::Kind::Type);

  auto builtTypeOrError = decoder.decodeMangledType(type);

  if (builtTypeOrError.isError()) {
    auto err = builtTypeOrError.getError();
    char *errStr = err->copyErrorString();
    err->freeErrorString(errStr);
    return nullptr;
  }

  if (!builtTypeOrError.getType().isMetadata())
    return nullptr;

  return builtTypeOrError.getType().getMetadata();
}

SWIFT_CC(swift)
SWIFT_RUNTIME_STDLIB_SPI
unsigned swift_func_getParameterCount(const char *typeNameStart,
                                      size_t typeNameLength) {
  StackAllocatedDemangler<1024> demangler;

  auto funcType =
      extractFunctionTypeFromMethod(demangler, typeNameStart, typeNameLength);
  if (!funcType)
    return -1;

  auto parameterList = getParameterList(funcType);
  return parameterList->getNumChildren();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_SPI
const Metadata *_Nullable
swift_func_getReturnTypeInfo(const char *typeNameStart, size_t typeNameLength,
                             GenericEnvironmentDescriptor *genericEnv,
                             const void * const *genericArguments) {
  StackAllocatedDemangler<1024> demangler;

  auto *funcType =
      extractFunctionTypeFromMethod(demangler, typeNameStart, typeNameLength);
  if (!funcType)
    return nullptr;

  auto resultType = funcType->getLastChild();
  if (!resultType)
    return nullptr;

  assert(resultType->getKind() == Node::Kind::ReturnType);

  SubstGenericParametersFromMetadata substFn(genericEnv, genericArguments);

  DecodedMetadataBuilder builder(
      demangler,
      /*substGenericParam=*/
      [&substFn](unsigned depth, unsigned index) {
        return substFn.getMetadata(depth, index).Ptr;
      },
      /*SubstDependentWitnessTableFn=*/
      [&substFn](const Metadata *type, unsigned index) {
        return substFn.getWitnessTable(type, index);
      });

  TypeDecoder<DecodedMetadataBuilder> decoder(builder);

  return decodeType(decoder, resultType->getFirstChild());
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_SPI
unsigned
swift_func_getParameterTypeInfo(
    const char *typeNameStart, size_t typeNameLength,
    GenericEnvironmentDescriptor *genericEnv,
    const void * const *genericArguments,
    Metadata const **types, unsigned typesLength) {
  if (typesLength < 0) return -1;

  StackAllocatedDemangler<1024> demangler;

  auto *funcType =
      extractFunctionTypeFromMethod(demangler, typeNameStart, typeNameLength);
  if (!funcType)
    return -1;

  auto parameterList = getParameterList(funcType);

  // Only successfully return if the expected parameter count is the same
  // as space prepared for it in the buffer.
  if (!(parameterList && parameterList->getNumChildren() == typesLength))
    return -2;

  SubstGenericParametersFromMetadata substFn(genericEnv, genericArguments);

  DecodedMetadataBuilder builder(
      demangler,
      /*substGenericParam=*/
      [&substFn](unsigned depth, unsigned index) {
        return substFn.getMetadata(depth, index).Ptr;
      },
      /*SubstDependentWitnessTableFn=*/
      [&substFn](const Metadata *type, unsigned index) {
        return substFn.getWitnessTable(type, index);
      });
  TypeDecoder<DecodedMetadataBuilder> decoder(builder);

  // for each parameter (TupleElement), store it into the provided buffer
  for (unsigned index = 0; index != typesLength; ++index) {
    auto *parameter = parameterList->getChild(index);

    if (parameter->getKind() == Node::Kind::TupleElement) {
      assert(parameter->getNumChildren() == 1);
      parameter = parameter->getFirstChild();
    }

    assert(parameter->getKind() == Node::Kind::Type);

    auto type = decodeType(decoder, parameter);
    if (!type)
      return -3; // Failed to decode a type.

    types[index] = type;
  } // end foreach parameter

  return typesLength;
}

SWIFT_CC(swift)
SWIFT_RUNTIME_STDLIB_SPI
BufferAndSize
swift_distributed_getWitnessTables(GenericEnvironmentDescriptor *genericEnv,
                                   const void *const *genericArguments) {
  assert(genericEnv);
  assert(genericArguments);

  llvm::SmallVector<const void *, 4> witnessTables;
  SubstGenericParametersFromMetadata substFn(genericEnv, genericArguments);

  auto error = _checkGenericRequirements(
      genericEnv->getGenericParameters(),
      genericEnv->getGenericRequirements(), witnessTables,
      [&substFn](unsigned depth, unsigned index) {
        return substFn.getMetadata(depth, index).Ptr;
      },
      [&substFn](unsigned fullOrdinal, unsigned keyOrdinal) {
        return substFn.getMetadataKeyArgOrdinal(keyOrdinal).Ptr;
      },
      [&substFn](const Metadata *type, unsigned index) {
        return substFn.getWitnessTable(type, index);
      });

  if (error) {
    return {/*ptr=*/nullptr, -1};
  }

  if (witnessTables.empty())
    return {/*ptr=*/nullptr, 0};

  void **tables = (void **)malloc(witnessTables.size() * sizeof(void *));
  for (unsigned i = 0, n = witnessTables.size(); i != n; ++i)
    tables[i] = const_cast<void *>(witnessTables[i]);

  return {tables, static_cast<intptr_t>(witnessTables.size())};
}

// ==== End of Function metadata functions ---------------------------------------

static
MetadataResponse
swift_getOpaqueTypeMetadataImpl(MetadataRequest request,
                            const void * const *arguments,
                            const OpaqueTypeDescriptor *descriptor,
                            unsigned index) {
  auto mangledName = descriptor->getUnderlyingTypeArgument(index);
  SubstGenericParametersFromMetadata substitutions(descriptor, arguments);

  return swift_getTypeByMangledName(request.getState(),
                                    mangledName, arguments,
    [&substitutions](unsigned depth, unsigned index) {
      return substitutions.getMetadata(depth, index).Ptr;
    },
    [&substitutions](const Metadata *type, unsigned index) {
      return substitutions.getWitnessTable(type, index);
    }).getType().getResponse();
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
MetadataResponse
swift_getOpaqueTypeMetadata2(MetadataRequest request,
                            const void * const *arguments,
                            const OpaqueTypeDescriptor *descriptor,
                            unsigned index) {
  descriptor = swift_auth_data_non_address(
      descriptor, SpecialPointerAuthDiscriminators::OpaqueTypeDescriptor);
  return swift_getOpaqueTypeMetadataImpl(request, arguments, descriptor, index);
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
MetadataResponse
swift_getOpaqueTypeMetadata(MetadataRequest request,
                            const void * const *arguments,
                            const void *descriptor,
                            unsigned index) {
  // This call takes `descriptor` without a ptrauth signature. We
  // declare it as `void *` to avoid the implicit ptrauth we get from
  // the ptrauth_struct attribute. The static_cast implicitly signs the
  // pointer when we call through to the implementation in
  // swift_getOpaqueTypeMetadataImpl.
  return swift_getOpaqueTypeMetadataImpl(
      request, arguments, static_cast<const OpaqueTypeDescriptor *>(descriptor),
      index);
}

static const WitnessTable *
swift_getOpaqueTypeConformanceImpl(const void *const *arguments,
                                   const OpaqueTypeDescriptor *descriptor,
                                   unsigned index) {
  auto response = swift_getOpaqueTypeMetadataImpl(
      MetadataRequest(MetadataState::Complete), arguments, descriptor, index);
  return (const WitnessTable *)response.Value;
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const WitnessTable *
swift_getOpaqueTypeConformance2(const void * const *arguments,
                               const OpaqueTypeDescriptor *descriptor,
                               unsigned index) {
  descriptor = swift_auth_data_non_address(
      descriptor, SpecialPointerAuthDiscriminators::OpaqueTypeDescriptor);
  return swift_getOpaqueTypeConformanceImpl(arguments, descriptor, index);
}

SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
const WitnessTable *
swift_getOpaqueTypeConformance(const void * const *arguments,
                               const void *descriptor,
                               unsigned index) {
  // This call takes `descriptor` without a ptrauth signature. We
  // declare it as `void *` to avoid the implicit ptrauth we get from
  // the ptrauth_struct attribute. The static_cast implicitly signs the
  // pointer when we call through to the implementation in
  // swift_getOpaqueTypeConformanceImpl.
  return swift_getOpaqueTypeConformanceImpl(
      arguments, static_cast<const OpaqueTypeDescriptor *>(descriptor), index);
}

SWIFT_RUNTIME_STDLIB_SPI
SWIFT_CC(swift)
const Metadata *swift::_swift_instantiateCheckedGenericMetadata(
    const TypeContextDescriptor *context,
    const void * const *genericArgs,
    size_t genericArgsSize) {
  context = swift_auth_data_non_address(
      context, SpecialPointerAuthDiscriminators::ContextDescriptor);

  if (!context->isGeneric()) {
    return nullptr;
  }

  DemanglerForRuntimeTypeResolution<StackAllocatedDemangler<2048>> demangler;

  // _instantiateCheckedGenericMetadata expects generic args to NOT begin with
  // shape classes.
  llvm::ArrayRef<const void *> genericArgsRef(genericArgs, genericArgsSize);
  llvm::SmallVector<MetadataOrPack, 8> writtenGenericArgs;

  // If we fail to fill in all of the generic parameters, just fail.
  if (!_gatherWrittenGenericParameters(context, genericArgsRef,
                                       writtenGenericArgs, demangler)) {
    return nullptr;
  }

  llvm::SmallVector<unsigned, 8> genericParamCounts;
  llvm::SmallVector<const void *, 8> allGenericArgs;

  auto result = _gatherGenericParameters(context, writtenGenericArgs,
                                         /* parent */ nullptr,
                                         genericParamCounts, allGenericArgs,
                                         demangler);

  // _gatherGenericParameters returns std::nullopt on success.
  if (result.has_value()) {
    return nullptr;
  }

  auto accessFunction = context->getAccessFunction();

  return accessFunction(MetadataState::Complete, allGenericArgs).Value;
}

#if SWIFT_OBJC_INTEROP

// Return the ObjC class for the given type name.
// This gets installed as a callback from libobjc.

static bool validateObjCMangledName(const char *_Nonnull typeName) {
  // Accept names with a mangling prefix.
  if (getManglingPrefixLength(typeName))
    return true;

  // Accept names that start with a digit (unprefixed mangled names).
  if (isdigit(typeName[0]))
    return true;

  // Accept names that contain a dot.
  if (strchr(typeName, '.'))
    return true;

  // Reject anything else.
  return false;
}

// FIXME: delete this #if and dlsym once we don't
// need to build with older libobjc headers
#if !OBJC_GETCLASSHOOK_DEFINED
using objc_hook_getClass =  BOOL(*)(const char * _Nonnull name,
                                    Class _Nullable * _Nonnull outClass);
#endif
static objc_hook_getClass OldGetClassHook;

static BOOL
getObjCClassByMangledName(const char * _Nonnull typeName,
                          Class _Nullable * _Nonnull outClass) {
  // Demangle old-style class and protocol names, which are still used in the
  // ObjC metadata.
  StringRef typeStr(typeName);
  const Metadata *metadata = nullptr;
  if (typeStr.starts_with("_Tt")) {
    Demangler demangler;
    auto node = demangler.demangleSymbol(typeName);
    if (!node)
      return NO;

    // If we successfully demangled but there is a suffix, then we did NOT use
    // the entire name, and this is NOT a match. Reject it.
    if (node->hasChildren() &&
        node->getLastChild()->getKind() == Node::Kind::Suffix)
      return NO;

    metadata = swift_getTypeByMangledNode(
      MetadataState::Complete, demangler, node,
      nullptr,
      /* no substitutions */
      [&](unsigned depth, unsigned index) { return nullptr; },
      [&](const Metadata *type, unsigned index) { return nullptr; }
    ).getType().getMetadata();
  } else {
    if (validateObjCMangledName(typeName))
      metadata = swift_stdlib_getTypeByMangledNameUntrusted(typeStr.data(),
                                                            typeStr.size());
  }
  if (metadata) {
    auto objcClass =
      reinterpret_cast<Class>(
        const_cast<ClassMetadata *>(
          swift_getObjCClassFromMetadataConditional(metadata)));

    if (objcClass) {
      *outClass = objcClass;
      return YES;
    }
  }

  return OldGetClassHook(typeName, outClass);
}

__attribute__((constructor))
static void installGetClassHook() {
  if (SWIFT_RUNTIME_WEAK_CHECK(objc_setHook_getClass)) {
    SWIFT_RUNTIME_WEAK_USE(objc_setHook_getClass(getObjCClassByMangledName, &OldGetClassHook));
  }
}

#endif

unsigned SubstGenericParametersFromMetadata::
buildDescriptorPath(const ContextDescriptor *context,
                    Demangler &borrowFrom) const {
  assert(sourceKind == SourceKind::Metadata);

  // Terminating condition: we don't have a context.
  if (!context)
    return 0;

  DemanglerForRuntimeTypeResolution<> demangler;
  demangler.providePreallocatedMemory(borrowFrom);

  if (auto extension = _findExtendedTypeContextDescriptor(context, demangler)) {
    // If we have a nominal type extension descriptor, extract the extended type
    // and use that. If the extension is not nominal, then we can use the
    // extension's own signature.
    context = extension;
  }

  // Add the parent's contribution to the descriptor path.
  const ContextDescriptor *parent = context->Parent.get();
  unsigned numKeyGenericParamsInParent = buildDescriptorPath(parent, demangler);

  // If this context is non-generic, we're done.
  if (!context->isGeneric())
    return numKeyGenericParamsInParent;

  // Count the number of key generic params at this level.
  auto allGenericParams = baseContext->getGenericContext()->getGenericParams();
  unsigned parentCount = parent->getNumGenericParams();
  unsigned localCount = context->getNumGenericParams();
  auto localGenericParams = allGenericParams.slice(parentCount,
                                                   localCount - parentCount);

  unsigned numKeyGenericParamsHere = 0;
  bool hasNonKeyGenericParams = false;
  for (const auto &genericParam : localGenericParams) {
    if (genericParam.hasKeyArgument())
      ++numKeyGenericParamsHere;
    else
      hasNonKeyGenericParams = true;
  }

  // Form the path element if there are any new generic parameters.
  if (localCount > parentCount)
    descriptorPath.push_back(PathElement{localGenericParams,
                                         context->getNumGenericParams(),
                                         numKeyGenericParamsInParent,
                                         numKeyGenericParamsHere,
                                         hasNonKeyGenericParams});
  return numKeyGenericParamsInParent + numKeyGenericParamsHere;
}

  /// Builds a path from the generic environment.
unsigned SubstGenericParametersFromMetadata::
buildEnvironmentPath(
    const TargetGenericEnvironment<InProcess> *environment) const {
  unsigned totalParamCount = 0;
  unsigned totalKeyParamCount = 0;
  auto genericParams = environment->getGenericParameters();
  for (unsigned numLocalParams : environment->getGenericParameterCounts()) {
    // Adjust totalParamCount so we have the # of local parameters.
    numLocalParams -= totalParamCount;

    // Get the local generic parameters.
    auto localGenericParams = genericParams.slice(0, numLocalParams);
    genericParams = genericParams.slice(numLocalParams);

    // Count the parameters.
    unsigned numKeyGenericParamsInParent = totalKeyParamCount;
    unsigned numKeyGenericParamsHere = 0;
    bool hasNonKeyGenericParams = false;
    for (const auto &genericParam : localGenericParams) {
      if (genericParam.hasKeyArgument())
        ++numKeyGenericParamsHere;
      else
        hasNonKeyGenericParams = true;
    }

    // Update totals.
    totalParamCount += numLocalParams;
    totalKeyParamCount += numKeyGenericParamsHere;

    // Add to the descriptor path.
    descriptorPath.push_back(PathElement{localGenericParams,
                                         totalParamCount,
                                         numKeyGenericParamsInParent,
                                         numKeyGenericParamsHere,
                                         hasNonKeyGenericParams});
  }

  return totalKeyParamCount;
}

unsigned SubstGenericParametersFromMetadata::buildShapePath(
    const TargetExtendedExistentialTypeShape<InProcess> *shape) const {
  unsigned totalParamCount = 0;

  auto genSig = shape->getGeneralizationSignature();
  if (!genSig.getParams().empty()) {
    totalParamCount += genSig.getParams().size();
    descriptorPath.push_back(PathElement{genSig.getParams(),
                                         totalParamCount,
                                         /*numKeyGenericParamsInParent*/ 0,
                                         (unsigned)genSig.getParams().size(),
                                         /*hasNonKeyGenericParams*/ false});
  }

  const unsigned genSigParamCount = genSig.getParams().size();
  auto reqSig = shape->getRequirementSignature();
  assert(reqSig.getParams().size() > genSig.getParams().size());
  {
    auto remainingParams = reqSig.getParams().drop_front(genSig.getParams().size());
    totalParamCount += remainingParams.size();
    descriptorPath.push_back(PathElement{remainingParams,
                                         totalParamCount,
                                         genSigParamCount,
                                         (unsigned)remainingParams.size(),
                                         /*hasNonKeyGenericParams*/ false});
  }

  // All parameters in this signature are key parameters.
  return totalParamCount;
}

void SubstGenericParametersFromMetadata::setup() const {
  if (!descriptorPath.empty())
    return;

  switch (sourceKind) {
  case SourceKind::Metadata: {
    assert(baseContext);
    DemanglerForRuntimeTypeResolution<StackAllocatedDemangler<2048>> demangler;
    numKeyGenericParameters = buildDescriptorPath(baseContext, demangler);
    if (auto *genericCtx = baseContext->getGenericContext())
      numShapeClasses = genericCtx->getGenericPackShapeHeader().NumShapeClasses;
    return;
  }
  case SourceKind::Environment: {
    assert(environment);
    numKeyGenericParameters = buildEnvironmentPath(environment);
    // FIXME: Variadic generics
    return;
  }
  case SourceKind::Shape: {
    assert(shape);
    numKeyGenericParameters = buildShapePath(shape);
    // FIXME: Variadic generics
    return;
  }
  }
}

MetadataOrPack
SubstGenericParametersFromMetadata::getMetadata(
                                        unsigned depth, unsigned index) const {
  // Don't attempt anything if we have no generic parameters.
  if (genericArgs == nullptr)
    return MetadataOrPack();

  // On first access, compute the descriptor path.
  setup();

  // If the depth is too great, there is nothing to do.
  if (depth >= descriptorPath.size())
    return MetadataOrPack();

  /// Retrieve the descriptor path element at this depth.
  auto &pathElement = descriptorPath[depth];

  // Check whether the index is clearly out of bounds.
  if (index >= pathElement.numTotalGenericParams)
    return MetadataOrPack();

  // Compute the flat index.
  unsigned flatIndex = pathElement.numKeyGenericParamsInParent + numShapeClasses;
  if (pathElement.hasNonKeyGenericParams > 0) {
    // We have non-key generic parameters at this level, so the index needs to
    // be checked more carefully.
    auto genericParams = pathElement.localGenericParams;

    // Make sure that the requested parameter itself has a key argument.
    if (!genericParams[index].hasKeyArgument())
      return MetadataOrPack();

    // Increase the flat index for each parameter with a key argument, up to
    // the given index.
    for (const auto &genericParam : genericParams.slice(0, index)) {
      if (genericParam.hasKeyArgument())
        ++flatIndex;
    }
  } else {
    flatIndex += index;
  }

  return MetadataOrPack(genericArgs[flatIndex]);
}

MetadataOrPack SubstGenericParametersFromMetadata::getMetadataKeyArgOrdinal(
    unsigned ordinal) const {
  // Don't attempt anything if we have no generic parameters.
  if (genericArgs == nullptr)
    return MetadataOrPack();

  // On first access, compute the descriptor path.
  setup();

  return MetadataOrPack(genericArgs[numShapeClasses + ordinal]);
}

const WitnessTable *
SubstGenericParametersFromMetadata::getWitnessTable(const Metadata *type,
                                                    unsigned index) const {
  // Don't attempt anything if we have no generic parameters.
  if (genericArgs == nullptr)
    return nullptr;

  // On first access, compute the descriptor path.
  setup();

  return (const WitnessTable *)genericArgs[
      index + numKeyGenericParameters + numShapeClasses];
}

MetadataOrPack SubstGenericParametersFromWrittenArgs::getMetadata(
                                        unsigned depth, unsigned index) const {
  if (auto flatIndex =
          _depthIndexToFlatIndex(depth, index, genericParamCounts)) {
    if (*flatIndex < allGenericArgs.size()) {
      return MetadataOrPack(allGenericArgs[*flatIndex]);
    }
  }

  return MetadataOrPack();
}

MetadataOrPack SubstGenericParametersFromWrittenArgs::getMetadataFullOrdinal(
    unsigned ordinal) const {
  if (ordinal < allGenericArgs.size()) {
    return MetadataOrPack(allGenericArgs[ordinal]);
  }

  return MetadataOrPack();
}

const WitnessTable *
SubstGenericParametersFromWrittenArgs::getWitnessTable(const Metadata *type,
                                                       unsigned index) const {
  return nullptr;
}

/// Demangle the given type name to a generic parameter reference, which
/// will be returned as (depth, index).
static std::optional<std::pair<unsigned, unsigned>>
demangleToGenericParamRef(StringRef typeName) {
  StackAllocatedDemangler<1024> demangler;
  NodePointer node = demangler.demangleType(typeName);
  if (!node)
    return std::nullopt;

  // Find the flat index that the right-hand side refers to.
  if (node->getKind() == Demangle::Node::Kind::Type)
    node = node->getChild(0);
  if (node->getKind() != Demangle::Node::Kind::DependentGenericParamType)
    return std::nullopt;

  return std::pair<unsigned, unsigned>(node->getChild(0)->getIndex(),
                                       node->getChild(1)->getIndex());
}

bool swift::_gatherWrittenGenericParameters(
    const TypeContextDescriptor *descriptor,
    llvm::ArrayRef<const void *> keyArgs,
    llvm::SmallVectorImpl<MetadataOrPack> &genericArgs,
    Demangle::Demangler &Dem) {
  if (!descriptor) {
    return false;
  }

  auto genericContext = descriptor->getGenericContext();

  // If the type itself is not generic, then we're done.
  if (!genericContext) {
    return true;
  }

  unsigned argIndex = 0;
  bool missingWrittenArguments = false;

  for (auto param : genericContext->getGenericParams()) {
    // The type should have a key argument unless it's been same-typed to
    // another type.
    if (param.hasKeyArgument()) {
      genericArgs.push_back(MetadataOrPack(keyArgs[argIndex]));

      argIndex += 1;
    } else {
      // Leave a gap for us to fill in by looking at same-type requirements.
      genericArgs.push_back(MetadataOrPack());
      missingWrittenArguments = true;
    }

    assert((param.getKind() == GenericParamKind::Type ||
           param.getKind() == GenericParamKind::TypePack) &&
           "Unknown generic parameter kind");
  }

  // If there is no follow-up work to do, we're done.
  if (!missingWrittenArguments)
    return true;

  // We have generic arguments that would be written, but have been
  // canonicalized away. Use same-type requirements to reconstitute them.

  // Retrieve the mapping information needed for depth/index -> flat index.
  llvm::SmallVector<unsigned, 8> genericParamCounts;
  (void)_gatherGenericParameterCounts(descriptor, genericParamCounts, Dem);

  SubstGenericParametersFromWrittenArgs substitutions(genericArgs,
                                                      genericParamCounts);

  // Walk through the generic requirements to evaluate same-type
  // constraints that are needed to fill in missing generic arguments.
  for (const auto &req : genericContext->getGenericRequirements()) {
    // We only care about same-type constraints.
    if (req.Flags.getKind() != GenericRequirementKind::SameType)
      continue;

    auto lhsParam = demangleToGenericParamRef(req.getParam());
    if (!lhsParam)
      continue;

    assert(!req.Flags.isPackRequirement() &&
           "Pack requirements not supported here yet");

    // If we don't yet have an argument for this parameter, it's a
    // same-type-to-concrete constraint.
    auto lhsFlatIndex =
      _depthIndexToFlatIndex(lhsParam->first, lhsParam->second,
                             genericParamCounts);
    if (!lhsFlatIndex || *lhsFlatIndex >= genericArgs.size())
      return false;

    if (!genericArgs[*lhsFlatIndex]) {
      // Substitute into the right-hand side.
      auto *genericArg =
          swift_getTypeByMangledName(MetadataState::Abstract,
            req.getMangledTypeName(),
            keyArgs.data(),
            [&substitutions](unsigned depth, unsigned index) {
              return substitutions.getMetadata(depth, index).Ptr;
            },
            [&substitutions](const Metadata *type, unsigned index) {
              return substitutions.getWitnessTable(type, index);
            }).getType().getMetadata();
      if (!genericArg)
        return false;

      genericArgs[*lhsFlatIndex] = MetadataOrPack(genericArg);
      continue;
    }

    // If we do have an argument for this parameter, it might be that
    // the right-hand side is itself a generic parameter, which means
    // we have a same-type constraint A == B where A is already filled in.
    auto rhsParam = demangleToGenericParamRef(req.getMangledTypeName());

    // If the rhs parameter is not a generic parameter itself with
    // (depth, index), it could potentially be some associated type. If that's
    // the case, then we don't need to do anything else for this rhs because it
    // won't appear in the key arguments list.
    if (!rhsParam) {
      continue;
    }

    auto rhsFlatIndex =
      _depthIndexToFlatIndex(rhsParam->first, rhsParam->second,
                             genericParamCounts);
    if (!rhsFlatIndex || *rhsFlatIndex >= genericArgs.size())
      return false;

    if (genericArgs[*rhsFlatIndex] || !genericArgs[*lhsFlatIndex])
      return false;

    genericArgs[*rhsFlatIndex] = genericArgs[*lhsFlatIndex];
  }

  return true;
}

struct InitializeDynamicReplacementLookup {
  InitializeDynamicReplacementLookup() {
    initializeDynamicReplacementLookup();
  }
};

SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_BEGIN
static InitializeDynamicReplacementLookup initDynamicReplacements;
SWIFT_ALLOWED_RUNTIME_GLOBAL_CTOR_END

void DynamicReplacementDescriptor::enableReplacement() const {
  // Weakly linked symbols can be zero.
  if (replacedFunctionKey.get() == nullptr)
    return;

  auto *chainRoot = const_cast<DynamicReplacementChainEntry *>(
      replacedFunctionKey->root.get());

  // Make sure this entry is not already enabled.
  // This does not work until we make sure that when a dynamic library is
  // unloaded all descriptors are removed.
#if 0
  for (auto *curr = chainRoot; curr != nullptr; curr = curr->next) {
    if (curr == chainEntry.get()) {
      swift::swift_abortDynamicReplacementEnabling();
    }
  }
#endif

  // Unlink the previous entry if we are not chaining.
  if (!shouldChain() && chainRoot->next) {
    auto *previous = chainRoot->next;
    chainRoot->next = previous->next;
    //chainRoot->implementationFunction = previous->implementationFunction;
    swift_ptrauth_copy_code_or_data(
        reinterpret_cast<void **>(&chainRoot->implementationFunction),
        reinterpret_cast<void *const *>(&previous->implementationFunction),
        replacedFunctionKey->getExtraDiscriminator(),
        !replacedFunctionKey->isAsync(), /*allowNull*/ false);
  }

  // First populate the current replacement's chain entry.
  auto *currentEntry =
      const_cast<DynamicReplacementChainEntry *>(chainEntry.get());
  // currentEntry->implementationFunction = chainRoot->implementationFunction;
  swift_ptrauth_copy_code_or_data(
      reinterpret_cast<void **>(&currentEntry->implementationFunction),
      reinterpret_cast<void *const *>(&chainRoot->implementationFunction),
      replacedFunctionKey->getExtraDiscriminator(),
      !replacedFunctionKey->isAsync(), /*allowNull*/ false);

  currentEntry->next = chainRoot->next;

  // Link the replacement entry.
  chainRoot->next = chainEntry.get();
  // chainRoot->implementationFunction = getReplacementFunction();
  swift_ptrauth_init_code_or_data(
      reinterpret_cast<void **>(&chainRoot->implementationFunction),
      reinterpret_cast<void *>(getReplacementFunction()),
      replacedFunctionKey->getExtraDiscriminator(),
      !replacedFunctionKey->isAsync());
}

void DynamicReplacementDescriptor::disableReplacement() const {
  const auto *chainRoot = replacedFunctionKey->root.get();
  auto *thisEntry =
      const_cast<DynamicReplacementChainEntry *>(chainEntry.get());

  // Find the entry previous to this one.
  auto *prev = chainRoot;
  while (prev && prev->next != thisEntry)
    prev = prev->next;
  if (!prev) {
    swift::swift_abortDynamicReplacementDisabling();
    return;
  }

  // Unlink this entry.
  auto *previous = const_cast<DynamicReplacementChainEntry *>(prev);
  previous->next = thisEntry->next;
  // previous->implementationFunction = thisEntry->implementationFunction;
  swift_ptrauth_copy_code_or_data(
      reinterpret_cast<void **>(&previous->implementationFunction),
      reinterpret_cast<void *const *>(&thisEntry->implementationFunction),
      replacedFunctionKey->getExtraDiscriminator(),
      !replacedFunctionKey->isAsync(), /*allowNull*/ false);
}

/// An automatic dynamic replacement entry.
namespace {
class AutomaticDynamicReplacementEntry {
  RelativeDirectPointer<DynamicReplacementScope, false> replacementScope;
  uint32_t flags;

public:
  void enable() const { replacementScope->enable(); }

  uint32_t getFlags() { return flags; }
};

/// A list of automatic dynamic replacement scopes.
class AutomaticDynamicReplacements
    : private swift::ABI::TrailingObjects<AutomaticDynamicReplacements,
                                          AutomaticDynamicReplacementEntry> {
  uint32_t flags;
  uint32_t numScopes;

  using TrailingObjects =
      swift::ABI::TrailingObjects<AutomaticDynamicReplacements,
                                  AutomaticDynamicReplacementEntry>;
  friend TrailingObjects;

  llvm::ArrayRef<AutomaticDynamicReplacementEntry>
  getReplacementEntries() const {
    return {
        this->template getTrailingObjects<AutomaticDynamicReplacementEntry>(),
        numScopes};
  }

public:
  void enableReplacements() const {
    for (auto &replacementEntry : getReplacementEntries())
      replacementEntry.enable();
  }

  uint32_t getNumScopes() const { return numScopes; }
};

/// A map from original to replaced opaque type descriptor of a some type.
class DynamicReplacementSomeDescriptor {
  RelativeIndirectablePointer<
      const OpaqueTypeDescriptor, false, int32_t,
      TargetSignedPointer<InProcess, OpaqueTypeDescriptor *
                                         __ptrauth_swift_type_descriptor>>
      originalOpaqueTypeDesc;
  RelativeDirectPointer<const OpaqueTypeDescriptor, false>
      replacementOpaqueTypeDesc;

public:
  void enable(const Mutex &lock) const {
    opaqueTypeMappings.get().insert(originalOpaqueTypeDesc.get(),
                                    replacementOpaqueTypeDesc.get(), lock);
  }
};

/// A list of dynamic replacements of some types.
class AutomaticDynamicReplacementsSome
    : private swift::ABI::TrailingObjects<AutomaticDynamicReplacementsSome,
                                          DynamicReplacementSomeDescriptor> {
  uint32_t flags;
  uint32_t numEntries;
  using TrailingObjects =
      swift::ABI::TrailingObjects<AutomaticDynamicReplacementsSome,
                                  DynamicReplacementSomeDescriptor>;
  friend TrailingObjects;

  llvm::ArrayRef<DynamicReplacementSomeDescriptor>
  getReplacementEntries() const {
    return {
        this->template getTrailingObjects<DynamicReplacementSomeDescriptor>(),
        numEntries};
  }

public:
  void enableReplacements(const Mutex &lock) const {
    for (auto &replacementEntry : getReplacementEntries())
      replacementEntry.enable(lock);
  }
  uint32_t getNumEntries() const { return numEntries; }
};

} // anonymous namespace

void swift::addImageDynamicReplacementBlockCallback(
    const void *baseAddress,
    const void *replacements, uintptr_t replacementsSize,
    const void *replacementsSome, uintptr_t replacementsSomeSize) {

  auto *automaticReplacements =
      reinterpret_cast<const AutomaticDynamicReplacements *>(replacements);

  const AutomaticDynamicReplacementsSome *someReplacements = nullptr;
  if (replacementsSomeSize) {
    someReplacements =
        reinterpret_cast<const AutomaticDynamicReplacementsSome *>(
            replacementsSome);
  }

  auto sizeOfCurrentEntry = sizeof(AutomaticDynamicReplacements) +
                            (automaticReplacements->getNumScopes() *
                             sizeof(AutomaticDynamicReplacementEntry));
  auto sizeOfCurrentSomeEntry =
      replacementsSomeSize == 0
          ? 0
          : sizeof(AutomaticDynamicReplacementsSome) +
                (someReplacements->getNumEntries() *
                 sizeof(DynamicReplacementSomeDescriptor));

  auto &lock = DynamicReplacementLock.get();
  lock.withLock([&] {
    auto endOfAutomaticReplacements =
        ((const char *)automaticReplacements) + replacementsSize;
    while (((const char *)automaticReplacements) < endOfAutomaticReplacements) {
      automaticReplacements->enableReplacements();
      automaticReplacements =
          reinterpret_cast<const AutomaticDynamicReplacements *>(
              ((const char *)automaticReplacements) + sizeOfCurrentEntry);
      if ((const char*)automaticReplacements <  endOfAutomaticReplacements)
        sizeOfCurrentEntry = sizeof(AutomaticDynamicReplacements) +
                             (automaticReplacements->getNumScopes() *
                              sizeof(AutomaticDynamicReplacementEntry));
    }
    if (!replacementsSomeSize)
      return;
    auto endOfSomeReplacements =
        ((const char *)someReplacements) + replacementsSomeSize;
    while (((const char *)someReplacements) < endOfSomeReplacements) {
      someReplacements->enableReplacements(lock);
      someReplacements =
          reinterpret_cast<const AutomaticDynamicReplacementsSome *>(
              ((const char *)someReplacements) + sizeOfCurrentSomeEntry);
      if  ((const char*) someReplacements < endOfSomeReplacements)
        sizeOfCurrentSomeEntry = sizeof(AutomaticDynamicReplacementsSome) +
                                 (someReplacements->getNumEntries() *
                                  sizeof(DynamicReplacementSomeDescriptor));
    }
  });
}

void swift::swift_enableDynamicReplacementScope(
    const DynamicReplacementScope *scope) {
  scope = swift_auth_data_non_address(
      scope, SpecialPointerAuthDiscriminators::DynamicReplacementScope);
  DynamicReplacementLock.get().withLock([=] { scope->enable(); });
}

void swift::swift_disableDynamicReplacementScope(
    const DynamicReplacementScope *scope) {
  scope = swift_auth_data_non_address(
      scope, SpecialPointerAuthDiscriminators::DynamicReplacementScope);
  DynamicReplacementLock.get().withLock([=] { scope->disable(); });
}
#define OVERRIDE_METADATALOOKUP COMPATIBILITY_OVERRIDE
#include COMPATIBILITY_OVERRIDE_INCLUDE_PATH