File: TypeCheckDecl.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 (3115 lines) | stat: -rw-r--r-- 108,928 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
//===--- TypeCheckDecl.cpp - Type Checking for Declarations ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//

#include "TypeCheckDecl.h"
#include "CodeSynthesis.h"
#include "DerivedConformances.h"
#include "MiscDiagnostics.h"
#include "TypeCheckAccess.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckBitwise.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckInvertible.h"
#include "TypeCheckObjC.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/Attr.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/OperatorNameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Defer.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DJB.h"

using namespace swift;

#define DEBUG_TYPE "TypeCheckDecl"

namespace {

/// Used during enum raw value checking to identify duplicate raw values.
/// Character, string, float, and integer literals are all keyed by value.
/// Float and integer literals are additionally keyed by numeric equivalence.
struct RawValueKey {
  enum class Kind : uint8_t {
    String, Float, Int, Bool, Tombstone, Empty
  } kind;
  
  struct IntValueTy {
    uint64_t v0;
    uint64_t v1;

    IntValueTy(const APInt &bits) {
      APInt bits128 = bits.sextOrTrunc(128);
      assert(bits128.getBitWidth() <= 128);
      const uint64_t *data = bits128.getRawData();
      v0 = data[0];
      v1 = data[1];
    }
  };

  struct FloatValueTy {
    uint64_t v0;
    uint64_t v1;
  };

  // FIXME: doesn't accommodate >64-bit or signed raw integer or float values.
  union {
    StringRef stringValue;
    IntValueTy intValue;
    FloatValueTy floatValue;
    bool boolValue;
  };
  
  explicit RawValueKey(LiteralExpr *expr) {
    switch (expr->getKind()) {
    case ExprKind::IntegerLiteral:
      kind = Kind::Int;
      intValue = IntValueTy(cast<IntegerLiteralExpr>(expr)->getValue());
      return;
    case ExprKind::FloatLiteral: {
      APFloat value = cast<FloatLiteralExpr>(expr)->getValue();
      llvm::APSInt asInt(127, /*isUnsigned=*/false);
      bool isExact = false;
      APFloat::opStatus status =
          value.convertToInteger(asInt, APFloat::rmTowardZero, &isExact);
      if (asInt.getBitWidth() <= 128 && status == APFloat::opOK && isExact) {
        kind = Kind::Int;
        intValue = IntValueTy(asInt);
        return;
      }
      APInt bits = value.bitcastToAPInt();
      const uint64_t *data = bits.getRawData();
      if (bits.getBitWidth() == 80) {
        kind = Kind::Float;
        floatValue = FloatValueTy{ data[0], data[1] };
      } else {
        assert(bits.getBitWidth() == 64);
        kind = Kind::Float;
        floatValue = FloatValueTy{ data[0], 0 };
      }
      return;
    }
    case ExprKind::StringLiteral:
      kind = Kind::String;
      stringValue = cast<StringLiteralExpr>(expr)->getValue();
      return;

    case ExprKind::BooleanLiteral:
      kind = Kind::Bool;
      boolValue = cast<BooleanLiteralExpr>(expr)->getValue();
      return;

    default:
      llvm_unreachable("not a valid literal expr for raw value");
    }
  }
  
  explicit RawValueKey(Kind k) : kind(k) {
    assert((k == Kind::Tombstone || k == Kind::Empty)
           && "this ctor is only for creating DenseMap special values");
  }
};
  
/// Used during enum raw value checking to identify the source of a raw value,
/// which may have been derived by auto-incrementing, for diagnostic purposes.
struct RawValueSource {
  /// The decl that has the raw value.
  EnumElementDecl *sourceElt;
  /// If the sourceDecl didn't explicitly name a raw value, this is the most
  /// recent preceding decl with an explicit raw value. This is used to
  /// diagnose 'autoincrementing from' messages.
  EnumElementDecl *lastExplicitValueElt;
};

} // end anonymous namespace

namespace llvm {

template<>
class DenseMapInfo<RawValueKey> {
public:
  static RawValueKey getEmptyKey() {
    return RawValueKey(RawValueKey::Kind::Empty);
  }
  static RawValueKey getTombstoneKey() {
    return RawValueKey(RawValueKey::Kind::Tombstone);
  }
  static unsigned getHashValue(RawValueKey k) {
    switch (k.kind) {
    case RawValueKey::Kind::Float:
      // Hash as bits. We want to treat distinct but IEEE-equal values as not
      // equal.
      return DenseMapInfo<uint64_t>::getHashValue(k.floatValue.v0) ^
             DenseMapInfo<uint64_t>::getHashValue(k.floatValue.v1);
    case RawValueKey::Kind::Int:
      return DenseMapInfo<uint64_t>::getHashValue(k.intValue.v0) &
             DenseMapInfo<uint64_t>::getHashValue(k.intValue.v1);
    case RawValueKey::Kind::String:
      return DenseMapInfo<StringRef>::getHashValue(k.stringValue);
    case RawValueKey::Kind::Bool:
      return DenseMapInfo<uint64_t>::getHashValue(k.boolValue);
    case RawValueKey::Kind::Empty:
    case RawValueKey::Kind::Tombstone:
      return 0;
    }

    llvm_unreachable("Unhandled RawValueKey in switch.");
  }
  static bool isEqual(RawValueKey a, RawValueKey b) {
    if (a.kind != b.kind)
      return false;
    switch (a.kind) {
    case RawValueKey::Kind::Float:
      // Hash as bits. We want to treat distinct but IEEE-equal values as not
      // equal.
      return a.floatValue.v0 == b.floatValue.v0 &&
             a.floatValue.v1 == b.floatValue.v1;
    case RawValueKey::Kind::Int:
      return a.intValue.v0 == b.intValue.v0 &&
             a.intValue.v1 == b.intValue.v1;
    case RawValueKey::Kind::String:
      return a.stringValue.equals(b.stringValue);
    case RawValueKey::Kind::Bool:
      return a.boolValue == b.boolValue;
    case RawValueKey::Kind::Empty:
    case RawValueKey::Kind::Tombstone:
      return true;
    }

    llvm_unreachable("Unhandled RawValueKey in switch.");
  }
};
  
} // namespace llvm

static bool canSkipCircularityCheck(NominalTypeDecl *decl) {
  // Don't bother checking imported or deserialized decls.
  return decl->hasClangNode() || decl->wasDeserialized();
}

bool
HasCircularInheritedProtocolsRequest::evaluate(Evaluator &evaluator,
                                               ProtocolDecl *decl) const {
  if (canSkipCircularityCheck(decl))
    return false;

  InvertibleProtocolSet inverses;
  bool anyObject = false;
  auto inherited = getDirectlyInheritedNominalTypeDecls(decl, inverses, anyObject);
  for (auto &found : inherited) {
    auto *protoDecl = dyn_cast<ProtocolDecl>(found.Item);
    if (!protoDecl)
      continue;

    // If we have a cycle, handle it and return true.
    auto result = evaluateOrDefault(evaluator,
                                    HasCircularInheritedProtocolsRequest{protoDecl},
                                    true);
    if (result)
      return true;
  }
  return false;
}

bool
HasCircularRawValueRequest::evaluate(Evaluator &evaluator,
                                     EnumDecl *decl) const {
  if (canSkipCircularityCheck(decl) || !decl->hasRawType())
    return false;

  auto *inherited = decl->getRawType()->getEnumOrBoundGenericEnum();
  if (!inherited)
    return false;

  // If we have a cycle, handle it and return true.
  return evaluateOrDefault(evaluator, HasCircularRawValueRequest{inherited}, true);
}

namespace {
// The raw values of this enum must be kept in sync with
// diag::implicitly_final_cannot_be_open.
enum class ImplicitlyFinalReason : unsigned {
  /// A property was declared with 'let'.
  Let,
  /// The containing class is final.
  FinalClass,
  /// A member was declared as 'static'.
  Static
};
}

static bool inferFinalAndDiagnoseIfNeeded(ValueDecl *D, ClassDecl *cls,
                                          FinalAttr *explicitFinalAttr,
                                          StaticSpellingKind staticSpelling) {
  // Are there any reasons to infer 'final'? Prefer 'static' over the class
  // being final for the purposes of diagnostics.
  std::optional<ImplicitlyFinalReason> reason;
  if (staticSpelling == StaticSpellingKind::KeywordStatic) {
    reason = ImplicitlyFinalReason::Static;

    if (explicitFinalAttr) {
      auto finalRange = explicitFinalAttr->getRange();
      if (finalRange.isValid()) {
        auto &context = D->getASTContext();
        context.Diags.diagnose(finalRange.Start, diag::static_decl_already_final)
        .fixItRemove(finalRange);
      }
    }
  } else if (cls->isFinal()) {
    reason = ImplicitlyFinalReason::FinalClass;
  }

  if (!reason)
    return false;

  if (D->getFormalAccess() == AccessLevel::Open) {
    auto &context = D->getASTContext();
    auto diagID = diag::implicitly_final_cannot_be_open;
    if (!context.isSwiftVersionAtLeast(5))
      diagID = diag::implicitly_final_cannot_be_open_swift4;
    auto inFlightDiag = context.Diags.diagnose(D, diagID,
                                    static_cast<unsigned>(reason.value()));
    fixItAccess(inFlightDiag, D, AccessLevel::Public);
  }

  return true;
}

/// Runtime-replaceable accessors are dynamic when their storage declaration
/// is dynamic and they were explicitly defined or they are implicitly defined
/// getter/setter because no accessor was defined.
static bool doesAccessorNeedDynamicAttribute(AccessorDecl *accessor) {
  auto kind = accessor->getAccessorKind();
  auto storage = accessor->getStorage();
  bool isObjC = storage->isObjC();

  switch (kind) {
  case AccessorKind::Get: {
    auto readImpl = storage->getReadImpl();
    if (!isObjC &&
        (readImpl == ReadImplKind::Read || readImpl == ReadImplKind::Address))
      return false;
    return storage->isDynamic();
  }
  case AccessorKind::DistributedGet: {
    return false;
  }
  case AccessorKind::Set: {
    auto writeImpl = storage->getWriteImpl();
    if (!isObjC && (writeImpl == WriteImplKind::Modify ||
                    writeImpl == WriteImplKind::MutableAddress ||
                    writeImpl == WriteImplKind::StoredWithObservers))
      return false;
    return storage->isDynamic();
  }
  case AccessorKind::Read:
    if (!isObjC && storage->getReadImpl() == ReadImplKind::Read)
      return storage->isDynamic();
    return false;
  case AccessorKind::Modify: {
    if (!isObjC && storage->getWriteImpl() == WriteImplKind::Modify)
      return storage->isDynamic();
    return false;
  }
  case AccessorKind::MutableAddress: {
    if (!isObjC && storage->getWriteImpl() == WriteImplKind::MutableAddress)
      return storage->isDynamic();
    return false;
  }
  case AccessorKind::Address: {
    if (!isObjC && storage->getReadImpl() == ReadImplKind::Address)
      return storage->isDynamic();
    return false;
  }
  case AccessorKind::DidSet:
  case AccessorKind::WillSet:
    if (!isObjC &&
        storage->getWriteImpl() == WriteImplKind::StoredWithObservers)
      return storage->isDynamic();
    return false;
  case AccessorKind::Init:
    return false;
  }
  llvm_unreachable("covered switch");
}

CtorInitializerKind
InitKindRequest::evaluate(Evaluator &evaluator, ConstructorDecl *decl) const {
  auto &diags = decl->getASTContext().Diags;
  auto dc = decl->getDeclContext();

  if (auto nominal = dc->getSelfNominalTypeDecl()) {

    // Convenience inits are only allowed on classes and in extensions thereof.
    if (auto convenAttr = decl->getAttrs().getAttribute<ConvenienceAttr>()) {
      if (auto classDecl = dyn_cast<ClassDecl>(nominal)) {
        if (classDecl->isAnyActor()) {
          // For an actor "convenience" is not required, but we'll honor it.
          diags.diagnose(decl->getLoc(),
                diag::no_convenience_keyword_init, "actors")
            .fixItRemove(convenAttr->getLocation())
            .warnInSwiftInterface(dc)
            .warnUntilSwiftVersion(6);

        } else { // not an actor
          // Forbid convenience inits on Foreign CF types, as Swift does not yet
          // support user-defined factory inits.
          if (classDecl->getForeignClassKind() == ClassDecl::ForeignKind::CFType)
            diags.diagnose(decl->getLoc(), diag::cfclass_convenience_init);
        }

      } else { // not a ClassDecl
        auto ConvenienceLoc = convenAttr->getLocation();

        // Produce a tailored diagnostic for structs and enums. They should
        // not have `convenience`.
        bool isStruct = dyn_cast<StructDecl>(nominal) != nullptr;
        if (isStruct || dyn_cast<EnumDecl>(nominal)) {
          diags.diagnose(decl->getLoc(), diag::no_convenience_keyword_init,
                         isStruct ? "structs" : "enums")
            .fixItRemove(ConvenienceLoc);
        } else {
          diags.diagnose(decl->getLoc(), diag::no_convenience_keyword_init,
                         nominal->getName().str())
            .fixItRemove(ConvenienceLoc);
        }
        return CtorInitializerKind::Designated;
      }

      return CtorInitializerKind::Convenience;
    }

    // if there's no `convenience` attribute...

    if (auto classDcl = dyn_cast<ClassDecl>(nominal)) {

      // actors infer whether they are `convenience` from their body kind.
      if (classDcl->isAnyActor()) {
        auto kind = decl->getDelegatingOrChainedInitKind();
        switch (kind.initKind) {
          case BodyInitKind::ImplicitChained:
          case BodyInitKind::Chained:
          case BodyInitKind::None:
            break; // it's designated, we need more checks.

          case BodyInitKind::Delegating:
            return CtorInitializerKind::Convenience;
        }
      }

      // A designated init for a class must be written within the class itself.
      //
      // This is because designated initializers of classes get a vtable entry,
      // and extensions cannot add vtable entries to the extended type.
      //
      // If we implement the ability for extensions defined in the same module
      // (or the same file) to add vtable entries, we can re-evaluate this
      // restriction.
      if (!decl->isSynthesized() &&
          isa<ExtensionDecl>(dc->getImplementedObjCContext()) &&
          !(decl->getAttrs().hasAttribute<DynamicReplacementAttr>())) {

        if (classDcl->getForeignClassKind() == ClassDecl::ForeignKind::CFType) {
          diags.diagnose(decl->getLoc(),
                         diag::designated_init_in_extension_no_convenience_tip,
                         nominal);

          // despite having reported it as an error, say that it is designated.
          return CtorInitializerKind::Designated;

        } else if (classDcl->isAnyActor()) {
          // tailor the diagnostic to not mention `convenience`
          diags.diagnose(decl->getLoc(),
                         diag::designated_init_in_extension_no_convenience_tip,
                         nominal);

        } else {
          diags.diagnose(decl->getLoc(),
                             diag::designated_init_in_extension, nominal)
                 .fixItInsert(decl->getLoc(), "convenience ");
        }

        return CtorInitializerKind::Convenience;
      }
    } // end of Class context
  } // end of Nominal context

  // initializers in protocol extensions must be convenience inits
  if (dc->getExtendedProtocolDecl()) {
    return CtorInitializerKind::Convenience;
  }

  return CtorInitializerKind::Designated;
}

BodyInitKindAndExpr
BodyInitKindRequest::evaluate(Evaluator &evaluator,
                              ConstructorDecl *decl) const {

  struct FindReferenceToInitializer : ASTWalker {
    const ConstructorDecl *Decl;
    BodyInitKind Kind = BodyInitKind::None;
    ApplyExpr *InitExpr = nullptr;
    ASTContext &ctx;

    FindReferenceToInitializer(const ConstructorDecl *decl,
                               ASTContext &ctx)
        : Decl(decl), ctx(ctx) { }

    MacroWalking getMacroWalkingBehavior() const override {
      return MacroWalking::Expansion;
    }

    PreWalkAction walkToDeclPre(class Decl *D) override {
      // Don't walk into further nominal decls.
      return Action::SkipNodeIf(isa<NominalTypeDecl>(D));
    }
    
    PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
      // Don't walk into closures.
      if (isa<ClosureExpr>(E))
        return Action::SkipNode(E);

      // Look for calls of a constructor on self or super.
      auto apply = dyn_cast<ApplyExpr>(E);
      if (!apply)
        return Action::Continue(E);

      auto *argList = apply->getArgs();
      auto Callee = apply->getSemanticFn();
      
      Expr *arg;

      if (isa<OtherConstructorDeclRefExpr>(Callee)) {
        arg = argList->getUnaryExpr();
        assert(arg);
      } else if (auto *CRE = dyn_cast<ConstructorRefCallExpr>(Callee)) {
        arg = CRE->getBase();
      } else if (auto *dotExpr = dyn_cast<UnresolvedDotExpr>(Callee)) {
        if (!dotExpr->getName().getBaseName().isConstructor())
          return Action::Continue(E);

        arg = dotExpr->getBase();
      } else {
        // Not a constructor call.
        return Action::Continue(E);
      }

      // Look for a base of 'self' or 'super'.
      arg = arg->getSemanticsProvidingExpr();

      auto myKind = BodyInitKind::None;
      if (arg->isSuperExpr())
        myKind = BodyInitKind::Chained;
      else if (arg->isSelfExprOf(Decl, /*sameBase*/true))
        myKind = BodyInitKind::Delegating;
      else if (auto *declRef = dyn_cast<UnresolvedDeclRefExpr>(arg)) {
        // FIXME: We can see UnresolvedDeclRefExprs here because we have
        // not yet run preCheckExpression() on the entire function body
        // yet.
        //
        // We could consider pre-checking more eagerly.
        auto name = declRef->getName();
        auto loc = declRef->getLoc();
        if (name.isSimpleName(ctx.Id_self)) {
          auto *otherSelfDecl =
            ASTScope::lookupSingleLocalDecl(Decl->getParentSourceFile(),
                                            name.getFullName(), loc);
          if (otherSelfDecl == Decl->getImplicitSelfDecl())
            myKind = BodyInitKind::Delegating;
        }
      }
      
      if (myKind == BodyInitKind::None)
        return Action::Continue(E);

      if (Kind == BodyInitKind::None) {
        Kind = myKind;

        InitExpr = apply;
        return Action::Continue(E);
      }

      // If the kind changed, complain.
      if (Kind != myKind) {
        // The kind changed. Complain.
        ctx.Diags.diagnose(E->getLoc(), diag::init_delegates_and_chains);
        ctx.Diags.diagnose(InitExpr->getLoc(), diag::init_delegation_or_chain,
                           Kind == BodyInitKind::Chained);
      }

      return Action::Continue(E);
    }
  };

  auto &ctx = decl->getASTContext();
  FindReferenceToInitializer finder(decl, ctx);
  if (auto *body = decl->getBody())
    body->walk(finder);

  // get the kind out of the finder.
  auto Kind = finder.Kind;

  auto *NTD = decl->getDeclContext()->getSelfNominalTypeDecl();

  // Protocol extension and enum initializers are always delegating.
  if (Kind == BodyInitKind::None) {
    if (isa<ProtocolDecl>(NTD) || isa<EnumDecl>(NTD)) {
      Kind = BodyInitKind::Delegating;
    }
  }

  // Struct initializers that cannot see the layout of the struct type are
  // always delegating. This occurs if the struct type is not fixed layout,
  // and the constructor is either inlinable or defined in another module.
  if (Kind == BodyInitKind::None && isa<StructDecl>(NTD)) {
    // Note: This is specifically not using isFormallyResilient. We relax this
    // rule for structs in non-resilient modules so that they can have inlinable
    // constructors, as long as those constructors don't reference private
    // declarations.
    if (NTD->isResilient() &&
        decl->getResilienceExpansion() == ResilienceExpansion::Minimal) {
      Kind = BodyInitKind::Delegating;

    } else if (isa<ExtensionDecl>(decl->getDeclContext())) {
      // Prior to Swift 5, cross-module initializers were permitted to be
      // non-delegating. However, if the struct isn't fixed-layout, we have to
      // be delegating because, well, we don't know the layout.
      // A dynamic replacement is permitted to be non-delegating.
      if (NTD->isResilient() ||
          (ctx.isSwiftVersionAtLeast(5) &&
           !decl->getAttrs().getAttribute<DynamicReplacementAttr>())) {
        if (decl->getParentModule() != NTD->getParentModule())
          Kind = BodyInitKind::Delegating;
      }
    }
  }

  // If we didn't find any delegating or chained initializers, check whether
  // the initializer was explicitly marked 'convenience'.
  if (Kind == BodyInitKind::None &&
      decl->getAttrs().hasAttribute<ConvenienceAttr>())
    Kind = BodyInitKind::Delegating;

  // If we still don't know, check whether we have a class with a superclass: it
  // gets an implicit chained initializer.
  if (Kind == BodyInitKind::None) {
    if (auto classDecl = decl->getDeclContext()->getSelfClassDecl()) {
      if (classDecl->hasSuperclass())
        Kind = BodyInitKind::ImplicitChained;
    }
  }

  return BodyInitKindAndExpr(Kind, finder.InitExpr);
}

bool
ProtocolRequiresClassRequest::evaluate(Evaluator &evaluator,
                                       ProtocolDecl *decl) const {
  // Quick check: @objc protocols require a class.
  if (decl->isObjC())
    return true;

  // Determine the set of nominal types that this protocol inherits.
  InvertibleProtocolSet inverses;
  bool anyObject = false;
  auto allInheritedNominals =
    getDirectlyInheritedNominalTypeDecls(decl, inverses, anyObject);

  // Quick check: do we inherit AnyObject?
  if (anyObject)
    return true;

  // Look through all of the inherited nominals for a superclass or a
  // class-bound protocol.
  for (const auto &found : allInheritedNominals) {
    // Superclass bound.
    if (isa<ClassDecl>(found.Item))
      return true;

    // A protocol that might be class-constrained.
    if (auto proto = dyn_cast<ProtocolDecl>(found.Item)) {
      if (proto->requiresClass())
        return true;
    }
  }

  return false;
}

bool
ExistentialConformsToSelfRequest::evaluate(Evaluator &evaluator,
                                           ProtocolDecl *decl) const {
  // Marker protocols always self-conform.
  if (decl->isMarkerProtocol()) {
    // Except for BitwiseCopyable an existential of which is not bitwise
    // copyable.
    if (decl->getKnownProtocolKind() == KnownProtocolKind::BitwiseCopyable) {
      return false;
    }
    return true;
  }

  // Otherwise, if it's not @objc, it conforms to itself only if it has a
  // self-conformance witness table.
  if (!decl->isObjC())
    return decl->requiresSelfConformanceWitnessTable();

  // Check whether this protocol conforms to itself.
  for (auto member : decl->getMembers()) {
    if (member->isInvalid()) continue;

    if (auto vd = dyn_cast<ValueDecl>(member)) {
      // A protocol cannot conform to itself if it has static members.
      if (!vd->isInstanceMember())
        return false;
    }
  }

  // Check whether any of the inherited protocols fail to conform to themselves.
  for (auto proto : decl->getInheritedProtocols()) {
    if (!proto->existentialConformsToSelf())
      return false;
  }

  return true;
}

bool HasSelfOrAssociatedTypeRequirementsRequest::evaluate(
    Evaluator &evaluator, ProtocolDecl *decl) const {
  // ObjC protocols do not require `any`.
  if (decl->isObjC())
    return false;

  for (auto member : decl->getMembers()) {
    // Existential types require `any` if the protocol has an associated type.
    if (isa<AssociatedTypeDecl>(member))
      return true;

    // For value members, look at their type signatures.
    if (auto valueMember = dyn_cast<ValueDecl>(member)) {
      const auto info = valueMember->findExistentialSelfReferences(
          decl->getDeclaredInterfaceType(),
          /*treatNonResultCovariantSelfAsInvariant=*/false);
      if (info.selfRef > TypePosition::Covariant || info.assocTypeRef) {
        return true;
      }
    }
  }

  // Check whether any of the inherited protocols require `any`.
  for (auto proto : decl->getInheritedProtocols()) {
    if (proto->hasSelfOrAssociatedTypeRequirements())
      return true;
  }

  return false;
}

ArrayRef<AssociatedTypeDecl *>
PrimaryAssociatedTypesRequest::evaluate(Evaluator &evaluator,
                                        ProtocolDecl *decl) const {
  SmallVector<AssociatedTypeDecl *, 2> assocTypes;

  if (decl->hasLazyPrimaryAssociatedTypes()) {
    auto &ctx = decl->getASTContext();
    auto contextData = static_cast<LazyProtocolData *>(
        ctx.getOrCreateLazyContextData(decl, nullptr));

    contextData->loader->loadPrimaryAssociatedTypes(
        decl, contextData->primaryAssociatedTypesData, assocTypes);

    return decl->getASTContext().AllocateCopy(assocTypes);
  }

  llvm::SmallDenseSet<Identifier, 2> assocTypeNames;

  for (auto pair : decl->getPrimaryAssociatedTypeNames()) {
    if (!assocTypeNames.insert(pair.first).second) {
      auto &ctx = decl->getASTContext();
      ctx.Diags.diagnose(pair.second,
                         diag::protocol_declares_duplicate_primary_assoc_type,
                         pair.first);
      continue;
    }

    SmallVector<ValueDecl *, 2> result;

    decl->lookupQualified(ArrayRef<NominalTypeDecl *>(decl),
                          DeclNameRef(pair.first), decl->getLoc(),
                          NL_QualifiedDefault | NL_OnlyTypes,
                          result);

    AssociatedTypeDecl *bestAssocType = nullptr;
    for (auto *decl : result) {
      if (auto *assocType = dyn_cast<AssociatedTypeDecl>(decl)) {
        if (bestAssocType == nullptr ||
            TypeDecl::compare(assocType, bestAssocType) < 0) {
          bestAssocType = assocType;
        }
      }
    }

    if (bestAssocType == nullptr) {
      auto &ctx = decl->getASTContext();
      ctx.Diags.diagnose(pair.second,
                         diag::protocol_declares_unknown_primary_assoc_type,
                         pair.first, decl->getDeclaredInterfaceType());
      continue;
    }

    assocTypes.push_back(bestAssocType);
  }

  return decl->getASTContext().AllocateCopy(assocTypes);
}

bool
IsFinalRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {
  auto explicitFinalAttr = decl->getAttrs().getAttribute<FinalAttr>();
  if (isa<ClassDecl>(decl))
    return explicitFinalAttr;

  auto cls = decl->getDeclContext()->getSelfClassDecl();
  if (!cls)
    return false;

  switch (decl->getKind()) {
    case DeclKind::Var: {
      // Properties are final if they are declared 'static' or a 'let'
      auto *VD = cast<VarDecl>(decl);

      // Backing storage for 'lazy' or property wrappers is always final.
      if (VD->isLazyStorageProperty() ||
          VD->getOriginalWrappedProperty(PropertyWrapperSynthesizedPropertyKind::Backing))
        return true;

      // Property wrapper storage wrappers are final if the original property
      // is final.
      if (auto *original = VD->getOriginalWrappedProperty(
            PropertyWrapperSynthesizedPropertyKind::Projection)) {
        if (original->isFinal())
          return true;
      }

      if (VD->getDeclContext()->getSelfClassDecl()) {
        // If this variable is a class member, mark it final if the
        // class is final, or if it was declared with 'let'.
        auto *PBD = VD->getParentPatternBinding();
        if (PBD && inferFinalAndDiagnoseIfNeeded(decl, cls, explicitFinalAttr,
                                                 PBD->getStaticSpelling()))
          return true;

        if (VD->isLet()) {
          // If this `let` is in an `@_objcImplementation extension`, don't
          // infer `final` unless it is written explicitly.
          auto ed = dyn_cast<ExtensionDecl>(VD->getDeclContext());
          if (!explicitFinalAttr && ed && ed->isObjCImplementation())
            return false;

          if (VD->getFormalAccess() == AccessLevel::Open) {
            auto &context = decl->getASTContext();
            auto diagID = diag::implicitly_final_cannot_be_open;
            if (!context.isSwiftVersionAtLeast(5))
              diagID = diag::implicitly_final_cannot_be_open_swift4;
            auto inFlightDiag =
              context.Diags.diagnose(decl, diagID,
                                     static_cast<unsigned>(ImplicitlyFinalReason::Let));
            fixItAccess(inFlightDiag, decl, AccessLevel::Public);
          }

          return true;
        }
      }

      break;
    }

    case DeclKind::Func: {
      // Methods declared 'static' are final.
      auto staticSpelling = cast<FuncDecl>(decl)->getStaticSpelling();
      if (inferFinalAndDiagnoseIfNeeded(decl, cls, explicitFinalAttr,
                                        staticSpelling))
        return true;
      break;
    }

    case DeclKind::Accessor:
      if (auto accessor = dyn_cast<AccessorDecl>(decl)) {
        switch (accessor->getAccessorKind()) {
          case AccessorKind::DidSet:
          case AccessorKind::WillSet:
            // Observing accessors are marked final if in a class.
            return true;

          case AccessorKind::Read:
          case AccessorKind::Modify:
          case AccessorKind::Get:
          case AccessorKind::DistributedGet:
          case AccessorKind::Set: {
            // Coroutines and accessors are final if their storage is.
            auto storage = accessor->getStorage();
            if (storage->isFinal())
              return true;
            break;
          }

          default:
            break;
        }
      }
      break;

    case DeclKind::Subscript: {
      // Member subscripts.
      auto staticSpelling = cast<SubscriptDecl>(decl)->getStaticSpelling();
      if (inferFinalAndDiagnoseIfNeeded(decl, cls, explicitFinalAttr,
                                        staticSpelling))
        return true;
      break;
    }

    default:
      break;
  }

  return explicitFinalAttr;
}

bool
IsStaticRequest::evaluate(Evaluator &evaluator, FuncDecl *decl) const {
  if (auto *accessor = dyn_cast<AccessorDecl>(decl))
    return accessor->getStorage()->isStatic();

  bool result = (decl->getStaticLoc().isValid() ||
                 decl->getStaticSpelling() != StaticSpellingKind::None);
  auto *dc = decl->getDeclContext();
  if (!result &&
      decl->isOperator() &&
      dc->isTypeContext()) {
    const auto operatorName = decl->getBaseIdentifier();
    if (auto ED = dyn_cast<ExtensionDecl>(dc->getAsDecl())) {
      decl->diagnose(diag::nonstatic_operator_in_extension, operatorName,
                     ED->getExtendedTypeRepr() != nullptr,
                     ED->getExtendedTypeRepr())
          .fixItInsert(decl->getAttributeInsertionLoc(/*forModifier=*/true),
                       "static ");
    } else {
      auto *NTD = cast<NominalTypeDecl>(dc->getAsDecl());
      decl->diagnose(diag::nonstatic_operator_in_nominal, operatorName, NTD)
          .fixItInsert(decl->getAttributeInsertionLoc(/*forModifier=*/true),
                       "static ");
    }
    result = true;
  }

  return result;
}

bool
IsDynamicRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {
  // If we can't infer dynamic here, don't.
  if (!DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind::Dynamic, decl))
    return false;

  // Add dynamic if -enable-implicit-dynamic was requested.
  TypeChecker::addImplicitDynamicAttribute(decl);

  // If 'dynamic' was explicitly specified, check it.
  if (decl->getAttrs().hasAttribute<DynamicAttr>()) {
    return true;
  }

  // @_objcImplementation extension member implementations are implicitly
  // dynamic.
  if (decl->isObjCMemberImplementation())
    return true;

  if (auto accessor = dyn_cast<AccessorDecl>(decl)) {
    // Runtime-replaceable accessors are dynamic when their storage declaration
    // is dynamic and they were explicitly defined or they are implicitly defined
    // getter/setter because no accessor was defined.
    return doesAccessorNeedDynamicAttribute(accessor);
  }

  // The 'NSManaged' attribute implies 'dynamic'.
  // FIXME: Use a semantic check for NSManaged rather than looking for the
  // attribute (which could be ill-formed).
  if (decl->getAttrs().hasAttribute<NSManagedAttr>())
    return true;

  // The presence of 'final' blocks the inference of 'dynamic'.
  if (decl->isSemanticallyFinal())
    return false;

  // Types are never 'dynamic'.
  if (isa<TypeDecl>(decl))
    return false;

  // A non-@objc entity is never 'dynamic'.
  if (!decl->isObjC())
    return false;

  // @objc declarations in class extensions are implicitly dynamic.
  // This is intended to enable overriding the declarations.
  auto dc = decl->getDeclContext();
  if (isa<ExtensionDecl>(dc) && dc->getSelfClassDecl())
    return true;

  // If any of the declarations overridden by this declaration are dynamic
  // or were imported from Objective-C, this declaration is dynamic.
  // Don't do this if the declaration is not exposed to Objective-C; that's
  // currently the (only) manner in which one can make an override of a
  // dynamic declaration non-dynamic.
  auto overriddenDecls = evaluateOrDefault(evaluator,
    OverriddenDeclsRequest{decl}, {});
  for (auto overridden : overriddenDecls) {
    if (overridden->isDynamic() || overridden->hasClangNode())
      return true;
  }

  return false;
}

Type
DefaultDefinitionTypeRequest::evaluate(Evaluator &evaluator,
                                       AssociatedTypeDecl *assocType) const {
  auto &ctx = assocType->getASTContext();
  if (auto *data = static_cast<LazyAssociatedTypeData *>(
          ctx.getLazyContextData(assocType))) {
    return data->loader->loadAssociatedTypeDefault(
        assocType, data->defaultDefinitionTypeData);
  }

  TypeRepr *defaultDefinition = assocType->getDefaultDefinitionTypeRepr();
  if (defaultDefinition) {
    return TypeResolution::forInterface(assocType->getDeclContext(),
                                        std::nullopt,
                                        // Diagnose unbound generics and
                                        // placeholders.
                                        /*unboundTyOpener*/ nullptr,
                                        /*placeholderHandler*/ nullptr,
                                        /*packElementOpener*/ nullptr)
        .resolveType(defaultDefinition);
  }

  return Type();
}

bool
NeedsNewVTableEntryRequest::evaluate(Evaluator &evaluator,
                                     AbstractFunctionDecl *decl) const {
  auto *dc = decl->getDeclContext();

  if (!isa<ClassDecl>(dc->getImplementedObjCContext()))
    return false;

  // Destructors always use a fixed vtable entry.
  if (isa<DestructorDecl>(decl))
    return false;
  
  assert(isa<FuncDecl>(decl) || isa<ConstructorDecl>(decl));

  // Final members are always be called directly.
  // Dynamic methods are always accessed by objc_msgSend().
  if (decl->isFinal() || decl->shouldUseObjCDispatch() || decl->hasClangNode())
    return false;

  auto &ctx = dc->getASTContext();

  // Initializers are not normally inherited, but required initializers can
  // be overridden for invocation from dynamic types, and convenience initializers
  // are conditionally inherited when all designated initializers are available,
  // working by dynamically invoking the designated initializer implementation
  // from the subclass. Convenience initializers can also override designated
  // initializer implementations from their superclass.
  if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
    if (!ctor->isRequired() && !ctor->isDesignatedInit()) {
      return false;
    }

    // Stub constructors don't appear in the vtable.
    if (ctor->hasStubImplementation())
      return false;
  }

  if (auto *accessor = dyn_cast<AccessorDecl>(decl)) {
    // Check to see if it's one of the opaque accessors for the declaration.
    auto storage = accessor->getStorage();
    if (accessor->getAccessorKind() == AccessorKind::DistributedGet) {
      return true;
    }
    if (!storage->requiresOpaqueAccessor(accessor->getAccessorKind()))
      return false;
  }

  auto base = decl->getOverriddenDecl();

  if (!base || base->hasClangNode() || base->shouldUseObjCDispatch())
    return true;

  // As above, convenience initializers are not formally overridable in Swift
  // vtables, although same-named initializers are modeled as overriding for
  // various QoI and objc interop reasons. Even if we "override" a non-required
  // convenience init, we still need a distinct vtable entry.
  if (auto baseCtor = dyn_cast<ConstructorDecl>(base)) {
    if (!baseCtor->isRequired() && !baseCtor->isDesignatedInit()) {
      return true;
    }
  }

  // If the base is less visible than the override, we might need a vtable
  // entry since callers of the override might not be able to see the base
  // at all.
  if (decl->isMoreVisibleThan(base))
    return true;

  using Direction = ASTContext::OverrideGenericSignatureReqCheck;
  if (!ctx.overrideGenericSignatureReqsSatisfied(
          base, decl, Direction::BaseReqSatisfiedByDerived)) {
    return true;
  }

  // If this method is an ABI compatible override, then we don't need a new
  // vtable entry. Otherwise, if it's not ABI compatible, for example if the
  // base has a more general AST type, then we need a new entry. Note that an
  // abstraction change is OK; we don't want to add a whole new vtable entry
  // just because an @in parameter becomes @owned, or whatever.
  auto isABICompatibleOverride =
      evaluateOrDefault(evaluator, IsABICompatibleOverrideRequest{decl}, false);
  return !isABICompatibleOverride;
}

/// Given the raw value literal expression for an enum case, produces the
/// auto-incremented raw value for the subsequent case, or returns null if
/// the value is not auto-incrementable.
static LiteralExpr *getAutomaticRawValueExpr(AutomaticEnumValueKind valueKind,
                                             EnumElementDecl *forElt,
                                             LiteralExpr *prevValue) {
  auto &Ctx = forElt->getASTContext();
  switch (valueKind) {
  case AutomaticEnumValueKind::None:
    Ctx.Diags.diagnose(forElt->getLoc(),
                       diag::enum_non_integer_convertible_raw_type_no_value);
    return nullptr;

  case AutomaticEnumValueKind::String:
    return new (Ctx) StringLiteralExpr(forElt->getNameStr(), SourceLoc(),
                                              /*Implicit=*/true);

  case AutomaticEnumValueKind::Integer:
    // If there was no previous value, start from zero.
    if (!prevValue) {
      return new (Ctx) IntegerLiteralExpr("0", SourceLoc(),
                                                 /*Implicit=*/true);
    }

    if (auto intLit = dyn_cast<IntegerLiteralExpr>(prevValue)) {
      APInt raw = intLit->getRawValue();
      APInt sext = (raw.getBitWidth() < 128 ? raw.sext(128) : raw);
      APInt nextVal = sext + 1;
      bool negative = nextVal.slt(0);
      if (negative)
        nextVal = -nextVal;

      llvm::SmallString<10> nextValStr;
      nextVal.toStringSigned(nextValStr);
      auto expr = new (Ctx)
        IntegerLiteralExpr(Ctx.AllocateCopy(StringRef(nextValStr)),
                           forElt->getLoc(), /*Implicit=*/true);
      if (negative)
        expr->setNegative(forElt->getLoc());

      return expr;
    }

    Ctx.Diags.diagnose(forElt->getLoc(),
                       diag::enum_non_integer_raw_value_auto_increment);
    return nullptr;
  }

  llvm_unreachable("Unhandled AutomaticEnumValueKind in switch.");
}

std::optional<AutomaticEnumValueKind>
swift::computeAutomaticEnumValueKind(EnumDecl *ED) {
  Type rawTy = ED->getRawType();
  assert(rawTy && "Cannot compute value kind without raw type!");
  
  if (ED->getGenericEnvironmentOfContext() != nullptr)
    rawTy = ED->mapTypeIntoContext(rawTy);

  auto *module = ED->getParentModule();

  // Swift enums require that the raw type is convertible from one of the
  // primitive literal protocols.
  auto conformsToProtocol = [&](KnownProtocolKind protoKind) {
    return TypeChecker::conformsToKnownProtocol(rawTy, protoKind, module);
  };

  static auto otherLiteralProtocolKinds = {
    KnownProtocolKind::ExpressibleByFloatLiteral,
    KnownProtocolKind::ExpressibleByUnicodeScalarLiteral,
    KnownProtocolKind::ExpressibleByExtendedGraphemeClusterLiteral,
  };
  
  if (conformsToProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)) {
    return AutomaticEnumValueKind::Integer;
  } else if (conformsToProtocol(KnownProtocolKind::ExpressibleByStringLiteral)){
    return AutomaticEnumValueKind::String;
  } else if (std::any_of(otherLiteralProtocolKinds.begin(),
                         otherLiteralProtocolKinds.end(),
                         conformsToProtocol)) {
    return AutomaticEnumValueKind::None;
  } else {
    return std::nullopt;
  }
}

evaluator::SideEffect
EnumRawValuesRequest::evaluate(Evaluator &eval, EnumDecl *ED,
                               TypeResolutionStage stage) const {
  Type rawTy = ED->getRawType();
  if (!rawTy) {
    return std::make_tuple<>();
  }
  
  // Avoid computing raw values for enum cases in swiftinterface files since raw
  // values are intentionally omitted from them (unless the enum is @objc).
  // Without bailing here, incorrect raw values can be automatically generated
  // and incorrect diagnostics may be omitted for some decls.
  SourceFile *Parent = ED->getDeclContext()->getParentSourceFile();
  if (Parent && Parent->Kind == SourceFileKind::Interface && !ED->isObjC())
    return std::make_tuple<>();

  if (!computeAutomaticEnumValueKind(ED)) {
    return std::make_tuple<>();
  }

  if (ED->getGenericEnvironmentOfContext() != nullptr)
    rawTy = ED->mapTypeIntoContext(rawTy);
  if (rawTy->hasError())
    return std::make_tuple<>();

  // Check the raw values of the cases.
  LiteralExpr *prevValue = nullptr;
  EnumElementDecl *lastExplicitValueElt = nullptr;

  // Keep a map we can use to check for duplicate case values.
  llvm::SmallDenseMap<RawValueKey, RawValueSource, 8> uniqueRawValues;

  // Make the raw member accesses explicit.
  auto uncheckedRawValueOf = [](EnumElementDecl *EED) -> LiteralExpr * {
    return EED->RawValueExpr;
  };

  std::optional<AutomaticEnumValueKind> valueKind;
  for (auto elt : ED->getAllElements()) {
    // If the element has been diagnosed up to now, skip it.
    if (elt->isInvalid())
      continue;

    if (uncheckedRawValueOf(elt)) {
      if (!uncheckedRawValueOf(elt)->isImplicit())
        lastExplicitValueElt = elt;
    } else if (!ED->SemanticFlags.contains(EnumDecl::HasFixedRawValues)) {
      // Try to pull out the automatic enum value kind.  If that fails, bail.
      if (!valueKind) {
        valueKind = computeAutomaticEnumValueKind(ED);
        if (!valueKind) {
          elt->setInvalid();
          return std::make_tuple<>();
        }
      }
      
      // If the enum element has no explicit raw value, try to
      // autoincrement from the previous value, or start from zero if this
      // is the first element.
      auto nextValue = getAutomaticRawValueExpr(*valueKind, elt, prevValue);
      if (!nextValue) {
        elt->setInvalid();
        break;
      }
      elt->setRawValueExpr(nextValue);
    }
    prevValue = uncheckedRawValueOf(elt);
    assert(prevValue && "continued without setting raw value of enum case");

    switch (stage) {
    case TypeResolutionStage::Structural:
      // We're only interested in computing the complete set of raw values,
      // so we can skip type checking.
      continue;
    default:
      // Continue on to type check the raw value.
      break;
    }

    
    {
      Expr *exprToCheck = prevValue;
      if (TypeChecker::typeCheckExpression(
              exprToCheck, ED,
              /*contextualInfo=*/{rawTy, CTP_EnumCaseRawValue})) {
        checkEnumElementActorIsolation(elt, exprToCheck);
        TypeChecker::checkEnumElementEffects(elt, exprToCheck);
      }
    }

    // If we didn't find a valid initializer (maybe the initial value was
    // incompatible with the raw value type) mark the entry as being erroneous.
    if (!prevValue->getType() || prevValue->getType()->hasError()) {
      elt->setInvalid();
      continue;
    }


    // If the raw values of the enum case are fixed, then we trust our callers
    // to have set things up correctly.  This comes up with imported enums
    // and deserialized @objc enums which always have their raw values setup
    // beforehand.
    if (ED->SemanticFlags.contains(EnumDecl::HasFixedRawValues))
      continue;

    // Using magic literals like #file as raw value is not supported right now.
    // TODO: We could potentially support #file, #function, #line and #column.
    auto &Diags = ED->getASTContext().Diags;
    SourceLoc diagLoc = uncheckedRawValueOf(elt)->isImplicit()
                            ? elt->getLoc()
                            : uncheckedRawValueOf(elt)->getLoc();
    if (auto magicLiteralExpr =
            dyn_cast<MagicIdentifierLiteralExpr>(prevValue)) {
      auto kindString =
          magicLiteralExpr->getKindString(magicLiteralExpr->getKind());
      Diags.diagnose(diagLoc, diag::enum_raw_value_magic_literal, kindString);
      elt->setInvalid();
      continue;
    }

    // Check that the raw value is unique.
    RawValueKey key{prevValue};
    RawValueSource source{elt, lastExplicitValueElt};

    auto insertIterPair = uniqueRawValues.insert({key, source});
    if (insertIterPair.second)
      continue;

    // Diagnose the duplicate value.
    Diags.diagnose(diagLoc, diag::enum_raw_value_not_unique);
    
    if (lastExplicitValueElt != elt &&
        valueKind == AutomaticEnumValueKind::Integer) {
      Diags.diagnose(uncheckedRawValueOf(lastExplicitValueElt)->getLoc(),
                     diag::enum_raw_value_incrementing_from_here);
    }

    RawValueSource prevSource = insertIterPair.first->second;
    auto foundElt = prevSource.sourceElt;
    diagLoc = uncheckedRawValueOf(foundElt)->isImplicit()
        ? foundElt->getLoc() : uncheckedRawValueOf(foundElt)->getLoc();
    Diags.diagnose(diagLoc, diag::enum_raw_value_used_here);
    
    if (foundElt != prevSource.lastExplicitValueElt &&
        valueKind == AutomaticEnumValueKind::Integer) {
      if (prevSource.lastExplicitValueElt)
        Diags.diagnose(uncheckedRawValueOf(prevSource.lastExplicitValueElt)
                         ->getLoc(),
                       diag::enum_raw_value_incrementing_from_here);
      else
        Diags.diagnose(ED->getAllElements().front()->getLoc(),
                       diag::enum_raw_value_incrementing_from_zero);
    }
  }
  return std::make_tuple<>();
}

const ConstructorDecl *
swift::findNonImplicitRequiredInit(const ConstructorDecl *CD) {
  while (CD->isImplicit()) {
    auto *overridden = CD->getOverriddenDecl();
    if (!overridden || !overridden->isRequired())
      break;
    CD = overridden;
  }
  return CD;
}

/// For building the higher-than component of the diagnostic path,
/// we use the visited set, which we've embellished with information
/// about how we reached a particular node.  This is reasonable because
/// we need to maintain the set anyway.
static void buildHigherThanPath(
    PrecedenceGroupDecl *last,
    const llvm::DenseMap<PrecedenceGroupDecl *, PrecedenceGroupDecl *>
        &visitedFrom,
    raw_ostream &out) {
  auto it = visitedFrom.find(last);
  assert(it != visitedFrom.end());
  auto from = it->second;
  if (from) {
    buildHigherThanPath(from, visitedFrom, out);
  }
  out << last->getName() << " -> ";
}

/// For building the lower-than component of the diagnostic path,
/// we just do a depth-first search to find a path.
static bool buildLowerThanPath(PrecedenceGroupDecl *start,
                               PrecedenceGroupDecl *target, raw_ostream &out) {
  if (start == target) {
    out << start->getName();
    return true;
  }

  if (start->isInvalid())
    return false;

  for (auto &rel : start->getLowerThan()) {
    if (rel.Group && buildLowerThanPath(rel.Group, target, out)) {
      out << " -> " << start->getName();
      return true;
    }
  }

  return false;
}

static void checkPrecedenceCircularity(DiagnosticEngine &D,
                                       PrecedenceGroupDecl *PGD) {
  // Don't diagnose if this group is already marked invalid.
  if (PGD->isInvalid())
    return;

  // The cycle doesn't necessarily go through this specific group,
  // so we need a proper visited set to avoid infinite loops.  We
  // also record a back-reference so that we can easily reconstruct
  // the cycle.
  llvm::DenseMap<PrecedenceGroupDecl *, PrecedenceGroupDecl *> visitedFrom;
  SmallVector<PrecedenceGroupDecl *, 4> stack;

  // Fill out the targets set.
  llvm::SmallPtrSet<PrecedenceGroupDecl *, 4> targets;
  stack.push_back(PGD);
  do {
    auto cur = stack.pop_back_val();

    // If we reach an invalid node, just bail out.
    if (cur->isInvalid()) {
      PGD->setInvalid();
      return;
    }

    targets.insert(cur);

    for (auto &rel : cur->getLowerThan()) {
      if (!rel.Group)
        continue;

      // We can't have cycles in the lower-than relationship
      // because it has to point outside of the module.

      stack.push_back(rel.Group);
    }
  } while (!stack.empty());

  // Make sure that the PGD is its own source.
  visitedFrom.insert({PGD, nullptr});

  stack.push_back(PGD);
  do {
    auto cur = stack.pop_back_val();

    // If we reach an invalid node, just bail out.
    if (cur->isInvalid()) {
      PGD->setInvalid();
      return;
    }

    for (auto &rel : cur->getHigherThan()) {
      if (!rel.Group)
        continue;

      // Check whether we've reached a target declaration.
      if (!targets.count(rel.Group)) {
        // If not, check whether we've visited this group before.
        if (visitedFrom.insert({rel.Group, cur}).second) {
          // If not, add it to the queue.
          stack.push_back(rel.Group);
        }

        // Note that we'll silently ignore cycles that don't go through PGD.
        // We should eventually process the groups that are involved.
        continue;
      }

      // Otherwise, we have something to report.
      SmallString<128> path;
      {
        llvm::raw_svector_ostream str(path);

        // Build the higherThan portion of the path (PGD -> cur).
        buildHigherThanPath(cur, visitedFrom, str);

        // Build the lowerThan portion of the path (rel.Group -> PGD).
        buildLowerThanPath(PGD, rel.Group, str);
      }

      D.diagnose(PGD->getHigherThanLoc(),
                 diag::higher_than_precedence_group_cycle, path);
      PGD->setInvalid();
      return;
    }
  } while (!stack.empty());
}

static PrecedenceGroupDecl *lookupPrecedenceGroupForRelation(
    DeclContext *dc, PrecedenceGroupDecl::Relation rel,
    PrecedenceGroupDescriptor::PathDirection direction) {
  auto &ctx = dc->getASTContext();
  PrecedenceGroupDescriptor desc{dc, rel.Name, rel.NameLoc, direction};

  bool hadCycle = false;
  auto result = ctx.evaluator(ValidatePrecedenceGroupRequest{desc},
                              [&hadCycle]() -> TinyPtrVector<PrecedenceGroupDecl *> {
                                hadCycle = true;
                                return {};
                              });
  if (hadCycle) {
    // Handle a cycle error specially. We don't want to default to an empty
    // result, as we don't want to emit an error about not finding a precedence
    // group.
    return nullptr;
  }
  return PrecedenceGroupLookupResult(dc, rel.Name, std::move(result))
      .getSingleOrDiagnose(rel.NameLoc);
}

void swift::validatePrecedenceGroup(PrecedenceGroupDecl *PGD) {
  assert(PGD && "Cannot validate a null precedence group!");
  if (PGD->isInvalid())
    return;

  auto &Diags = PGD->getASTContext().Diags;
  auto *dc = PGD->getDeclContext();

  // Validate the higherThan relationships.
  bool addedHigherThan = false;
  for (auto &rel : PGD->getMutableHigherThan()) {
    if (rel.Group)
      continue;

    // TODO: Requestify the lookup of a relation's group.
    rel.Group = lookupPrecedenceGroupForRelation(
        dc, rel, PrecedenceGroupDescriptor::HigherThan);
    if (rel.Group) {
      addedHigherThan = true;
    } else {
      PGD->setInvalid();
    }
  }

  // Validate the lowerThan relationships.
  for (auto &rel : PGD->getMutableLowerThan()) {
    if (rel.Group)
      continue;

    auto *group = lookupPrecedenceGroupForRelation(
        dc, rel, PrecedenceGroupDescriptor::LowerThan);
    rel.Group = group;

    // If we didn't find anything, try doing a raw lookup for the group before
    // diagnosing the 'lowerThan' within the same-module restriction. This can
    // allow us to diagnose even if we have a precedence group cycle.
    if (!group)
      group = dc->lookupPrecedenceGroup(rel.Name).getSingle();

    if (group &&
        group->getDeclContext()->getParentModule() == dc->getParentModule()) {
      if (!PGD->isInvalid()) {
        Diags.diagnose(rel.NameLoc, diag::precedence_group_lower_within_module);
        Diags.diagnose(group->getNameLoc(), diag::kind_declared_here,
                       DescriptiveDeclKind::PrecedenceGroup);
      }
      PGD->setInvalid();
    }

    if (!rel.Group)
      PGD->setInvalid();
  }

  // Try to diagnose trickier cycles that request evaluation alone can't catch.
  if (addedHigherThan)
    checkPrecedenceCircularity(Diags, PGD);
}

TinyPtrVector<PrecedenceGroupDecl *> ValidatePrecedenceGroupRequest::evaluate(
    Evaluator &eval, PrecedenceGroupDescriptor descriptor) const {
  auto groups = descriptor.dc->lookupPrecedenceGroup(descriptor.ident);
  for (auto *group : groups)
    validatePrecedenceGroup(group);

  // Return the raw results vector, which will get wrapped back in a
  // PrecedenceGroupLookupResult by the TypeChecker entry point. This dance
  // avoids unnecessarily caching the name and context for the lookup.
  return std::move(groups).get();
}

PrecedenceGroupLookupResult
TypeChecker::lookupPrecedenceGroup(DeclContext *dc, Identifier name,
                                   SourceLoc nameLoc) {
  auto groups = evaluateOrDefault(
      dc->getASTContext().evaluator,
      ValidatePrecedenceGroupRequest({dc, name, nameLoc, std::nullopt}), {});
  return PrecedenceGroupLookupResult(dc, name, std::move(groups));
}

/// Validate the given operator declaration.
///
/// This establishes key invariants, such as an InfixOperatorDecl's
/// reference to its precedence group and the transitive validity of that
/// group.
PrecedenceGroupDecl *
OperatorPrecedenceGroupRequest::evaluate(Evaluator &evaluator,
                                         InfixOperatorDecl *IOD) const {
  auto &ctx = IOD->getASTContext();
  auto *dc = IOD->getDeclContext();

  auto name = IOD->getPrecedenceGroupName();
  if (!name.empty()) {
    auto loc = IOD->getPrecedenceGroupLoc();
    auto groups = TypeChecker::lookupPrecedenceGroup(dc, name, loc);

    if (groups.hasResults() ||
        !ctx.TypeCheckerOpts.EnableOperatorDesignatedTypes)
      return groups.getSingleOrDiagnose(loc);

    // We didn't find the named precedence group and designated types are
    // enabled, so we will assume that it was actually a designated type. Warn
    // and fall through as though `PrecedenceGroupName` had never been set.
    ctx.Diags.diagnose(IOD->getColonLoc(),
                       diag::operator_decl_remove_designated_types)
        .fixItRemove({IOD->getColonLoc(), loc});
  }

  auto groups = TypeChecker::lookupPrecedenceGroup(
      dc, ctx.Id_DefaultPrecedence, SourceLoc());
  return groups.getSingleOrDiagnose(IOD->getLoc(), /*forBuiltin*/ true);
}

SelfAccessKind
SelfAccessKindRequest::evaluate(Evaluator &evaluator, FuncDecl *FD) const {
  if (FD->getAttrs().getAttribute<MutatingAttr>(true)) {
    if (!FD->isInstanceMember() || !FD->getDeclContext()->hasValueSemantics()) {
      // If this decl is on a class-constrained protocol extension, then
      // respect the explicit mutatingness. Otherwise, we would throw an
      // error.
      if (FD->getDeclContext()->isClassConstrainedProtocolExtension())
        return SelfAccessKind::Mutating;
      return SelfAccessKind::NonMutating;
    }
    return SelfAccessKind::Mutating;
  } else if (FD->getAttrs().hasAttribute<NonMutatingAttr>()) {
    return SelfAccessKind::NonMutating;
  } else if (FD->getAttrs().hasAttribute<LegacyConsumingAttr>()) {
    return SelfAccessKind::LegacyConsuming;
  } else if (FD->getAttrs().hasAttribute<ConsumingAttr>()) {
    return SelfAccessKind::Consuming;
  } else if (FD->getAttrs().hasAttribute<BorrowingAttr>()) {
    return SelfAccessKind::Borrowing;
  }

  if (auto *AD = dyn_cast<AccessorDecl>(FD)) {
    // Non-static set/willSet/didSet/mutableAddress default to mutating.
    // get/address default to non-mutating.
    switch (AD->getAccessorKind()) {
    case AccessorKind::Address:
    case AccessorKind::Get:
    case AccessorKind::DistributedGet:
    case AccessorKind::Read:
      break;

    case AccessorKind::Init:
    case AccessorKind::MutableAddress:
    case AccessorKind::Set:
    case AccessorKind::Modify:
      if (AD->isInstanceMember() && AD->getDeclContext()->hasValueSemantics())
        return SelfAccessKind::Mutating;
      break;

    case AccessorKind::WillSet:
    case AccessorKind::DidSet: {
      auto *storage =AD->getStorage();
      if (storage->isSetterMutating())
        return SelfAccessKind::Mutating;

      break;
    }
    }
  }

  return SelfAccessKind::NonMutating;
}

bool TypeChecker::isAvailabilitySafeForConformance(
    ProtocolDecl *proto, ValueDecl *requirement, ValueDecl *witness,
    DeclContext *dc, AvailabilityContext &requirementInfo) {

  // We assume conformances in
  // non-SourceFiles have already been checked for availability.
  if (!dc->getParentSourceFile())
    return true;

  auto &Context = proto->getASTContext();
  assert(dc->getSelfNominalTypeDecl() &&
         "Must have a nominal or extension context");

  // Make sure that any access of the witness through the protocol
  // can only occur when the witness is available. That is, make sure that
  // on every version where the conforming declaration is available, if the
  // requirement is available then the witness is available as well.
  // We do this by checking that (an over-approximation of) the intersection of
  // the requirement's available range with both the conforming declaration's
  // available range and the protocol's available range is fully contained in
  // (an over-approximation of) the intersection of the witnesses's available
  // range with both the conforming type's available range and the protocol
  // declaration's available range.
  AvailabilityContext witnessInfo =
      AvailabilityInference::availableRange(witness, Context);
  requirementInfo = AvailabilityInference::availableRange(requirement, Context);

  AvailabilityContext infoForConformingDecl =
      overApproximateAvailabilityAtLocation(dc->getAsDecl()->getLoc(), dc);

  // Relax the requirements for @_spi witnesses by treating the requirement as
  // if it were introduced at the deployment target. This is not strictly sound
  // since clients of SPI do not necessarily have the same deployment target as
  // the module declaring the requirement. However, now that the public
  // declarations in API libraries are checked according to the minimum possible
  // deployment target of their clients this relaxation is needed for source
  // compatibility with some existing code and is reasonably safe for the
  // majority of cases.
  if (witness->isSPI()) {
    AvailabilityContext deploymentTarget =
        AvailabilityContext::forDeploymentTarget(Context);
    requirementInfo.constrainWith(deploymentTarget);
  }

  // Constrain over-approximates intersection of version ranges.
  witnessInfo.constrainWith(infoForConformingDecl);
  requirementInfo.constrainWith(infoForConformingDecl);

  AvailabilityContext infoForProtocolDecl =
      overApproximateAvailabilityAtLocation(proto->getLoc(), proto);

  witnessInfo.constrainWith(infoForProtocolDecl);
  requirementInfo.constrainWith(infoForProtocolDecl);

  return requirementInfo.isContainedIn(witnessInfo);
}

// Returns 'nullptr' if this is the 'newValue' or 'oldValue' parameter;
// otherwise, returns the corresponding parameter of the subscript
// declaration.
static ParamDecl *getOriginalParamFromAccessor(AbstractStorageDecl *storage,
                                               AccessorDecl *accessor,
                                               ParamDecl *param) {
  auto *accessorParams = accessor->getParameters();
  unsigned startIndex = 0;

  switch (accessor->getAccessorKind()) {
  case AccessorKind::DidSet:
  case AccessorKind::WillSet:
  case AccessorKind::Set:
  case AccessorKind::Init:
    if (param == accessorParams->get(0)) {
      // This is the 'newValue' or 'oldValue' parameter.
      return nullptr;
    }

    startIndex = 1;
    break;

  default:
    startIndex = 0;
    break;
  }

  // If the parameter is not the 'newValue' parameter to a setter, it
  // must be a subscript index parameter (or we have an invalid AST).
  auto *subscript = cast<SubscriptDecl>(storage);
  auto *subscriptParams = subscript->getIndices();

  auto where = llvm::find_if(*accessorParams,
                              [param](ParamDecl *other) {
                                return other == param;
                              });
  assert(where != accessorParams->end());
  unsigned index = where - accessorParams->begin();

  return subscriptParams->get(index - startIndex);
}

bool
IsImplicitlyUnwrappedOptionalRequest::evaluate(Evaluator &evaluator,
                                               ValueDecl *decl) const {
  TypeRepr *TyR = nullptr;

  switch (decl->getKind()) {
  case DeclKind::Func: {
    TyR = cast<FuncDecl>(decl)->getResultTypeRepr();
    break;
  }

  case DeclKind::Accessor: {
    auto *accessor = cast<AccessorDecl>(decl);
    if (!accessor->isGetter())
      break;

    auto *storage = accessor->getStorage();
    if (auto *subscript = dyn_cast<SubscriptDecl>(storage))
      TyR = subscript->getElementTypeRepr();
    else
      TyR = cast<VarDecl>(storage)->getTypeReprOrParentPatternTypeRepr();
    break;
  }

  case DeclKind::Subscript:
    TyR = cast<SubscriptDecl>(decl)->getElementTypeRepr();
    break;

  case DeclKind::Param: {
    auto *param = cast<ParamDecl>(decl);
    if (param->isSelfParameter())
      return false;

    if (auto *accessor = dyn_cast<AccessorDecl>(param->getDeclContext())) {
      auto *storage = accessor->getStorage();
      auto *originalParam = getOriginalParamFromAccessor(
        storage, accessor, param);
      if (originalParam == nullptr) {
        // This is the setter's newValue parameter.
        return storage->isImplicitlyUnwrappedOptional();
      }

      if (param != originalParam) {
        // This is the 'subscript(...) { get { ... } set { ... } }' case.
        // This means we cloned the parameter list for each accessor.
        // Delegate to the original parameter.
        return originalParam->isImplicitlyUnwrappedOptional();
      }

      // This is the 'subscript(...) { <<body of getter>> }' case.
      // The subscript and the getter share their ParamDecls.
      // Fall through.
    }

    // Handle eg, 'inout Int!' or '__owned NSObject!'.
    TyR = param->getTypeRepr();
    if (auto *STR = dyn_cast_or_null<SpecifierTypeRepr>(TyR))
      TyR = STR->getBase();
    break;
  }

  case DeclKind::Var:
    if (decl->hasClangNode()) {
      // ClangImporter does not use this request to compute whether imported
      // declarations are IUOs; instead, it explicitly sets the bit itself when
      // it imports the declaration's type. For most declarations this is done
      // greedily, but for VarDecls, it is deferred until `getInterfaceType()`
      // is called for the first time. (See apple/swift#61026.)
      //
      // Force the interface type, then see if a result for this request is now
      // cached.
      // FIXME: This is a little gross.
      (void)decl->getInterfaceType();
      if (auto cachedResult = this->getCachedResult())
        return *cachedResult;
    }
    TyR = cast<VarDecl>(decl)->getTypeReprOrParentPatternTypeRepr();
    break;

  default:
    break;
  }

  return (TyR && TyR->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional);
}

/// Validate the underlying type of the given typealias.
Type
UnderlyingTypeRequest::evaluate(Evaluator &evaluator,
                                TypeAliasDecl *typeAlias) const {
  TypeResolutionOptions options((typeAlias->getGenericParams()
                                     ? TypeResolverContext::GenericTypeAliasDecl
                                     : TypeResolverContext::TypeAliasDecl));
  if (typeAlias->preconcurrency())
    options |= TypeResolutionFlags::Preconcurrency;

  // This can happen when code completion is attempted inside
  // of typealias underlying type e.g. `typealias F = () -> Int#^TOK^#`
  auto *underlyingRepr = typeAlias->getUnderlyingTypeRepr();
  if (!underlyingRepr) {
    typeAlias->setInvalid();
    return ErrorType::get(typeAlias->getASTContext());
  }

  const auto result =
      TypeResolution::forInterface(typeAlias, options,
                                   /*unboundTyOpener*/ nullptr,
                                   /*placeholderHandler*/ nullptr,
                                   /*packElementOpener*/ nullptr)
          .resolveType(underlyingRepr);

  if (result->hasError()) {
    typeAlias->setInvalid();
    return ErrorType::get(typeAlias->getASTContext());
  }
  return result;
}

/// Bind the given function declaration, which declares an operator, to the
/// corresponding operator declaration.
OperatorDecl *
FunctionOperatorRequest::evaluate(Evaluator &evaluator, FuncDecl *FD) const {  
  auto &C = FD->getASTContext();
  auto &diags = C.Diags;
  const auto operatorName = FD->getBaseIdentifier();

  // Check for static/final/class when we're in a type.
  auto dc = FD->getDeclContext();
  if (dc->isTypeContext()) {
    if (auto classDecl = dc->getSelfClassDecl()) {
      // For a class, we also need the function or class to be 'final'.
      if (!classDecl->isSemanticallyFinal() && !FD->isFinal() &&
          FD->getStaticLoc().isValid() &&
          FD->getStaticSpelling() != StaticSpellingKind::KeywordStatic) {
        FD->diagnose(diag::nonfinal_operator_in_class,
                     operatorName, dc->getDeclaredInterfaceType())
          .fixItInsert(FD->getAttributeInsertionLoc(/*forModifier=*/true),
                       "final ");
        FD->getAttrs().add(new (C) FinalAttr(/*IsImplicit=*/true));
      }
    }
  } else if (!dc->isModuleScopeContext()) {
    FD->diagnose(diag::operator_in_local_scope);
  }

  NullablePtr<OperatorDecl> op;
  if (FD->isUnaryOperator()) {
    if (FD->getAttrs().hasAttribute<PrefixAttr>()) {
      op = FD->lookupPrefixOperator(operatorName);
    } else if (FD->getAttrs().hasAttribute<PostfixAttr>()) {
      op = FD->lookupPostfixOperator(operatorName);
    } else {
      auto *prefixOp = FD->lookupPrefixOperator(operatorName);
      auto *postfixOp = FD->lookupPostfixOperator(operatorName);

      // If we found both prefix and postfix, or neither prefix nor postfix,
      // complain. We can't fix this situation.
      if (static_cast<bool>(prefixOp) == static_cast<bool>(postfixOp)) {
        diags.diagnose(FD, diag::declared_unary_op_without_attribute);

        // If we found both, point at them.
        if (prefixOp) {
          diags.diagnose(prefixOp, diag::unary_operator_declaration_here,
                         /*isPostfix*/ false)
            .fixItInsert(FD->getLoc(), "prefix ");
          diags.diagnose(postfixOp, diag::unary_operator_declaration_here,
                         /*isPostfix*/ true)
            .fixItInsert(FD->getLoc(), "postfix ");
        } else {
          // FIXME: Introduce a Fix-It that adds the operator declaration?
        }

        // FIXME: Errors could cascade here, because name lookup for this
        // operator won't find this declaration.
        return nullptr;
      }

      // We found only one operator declaration, so we know whether this
      // should be a prefix or a postfix operator.

      // Fix the AST and determine the insertion text.
      const char *insertionText;
      auto &C = FD->getASTContext();
      auto isPostfix = static_cast<bool>(postfixOp);
      if (isPostfix) {
        insertionText = "postfix ";
        op = postfixOp;
        FD->getAttrs().add(new (C) PostfixAttr(/*implicit*/false));
      } else {
        insertionText = "prefix ";
        op = prefixOp;
        FD->getAttrs().add(new (C) PrefixAttr(/*implicit*/false));
      }

      // Emit diagnostic with the Fix-It.
      diags.diagnose(FD->getFuncLoc(), diag::unary_op_missing_prepos_attribute,
                     isPostfix)
        .fixItInsert(FD->getFuncLoc(), insertionText);
      op.get()->diagnose(diag::unary_operator_declaration_here, isPostfix);
    }
  } else if (FD->isBinaryOperator()) {
    auto results = FD->lookupInfixOperator(operatorName);

    // If we have an ambiguity, diagnose and return. Otherwise fall through, as
    // we have a custom diagnostic for missing operator decls.
    if (results.isAmbiguous()) {
      results.diagnoseAmbiguity(FD->getLoc());
      return nullptr;
    }
    op = results.getSingle();
  } else {
    diags.diagnose(FD, diag::invalid_arg_count_for_operator);
    return nullptr;
  }

  if (!op) {
    // We want to insert at the start of the top-most declaration, taking
    // attributes into consideration.
    auto *insertionDecl = FD->getTopmostDeclarationDeclContext();
    auto insertionLoc = insertionDecl->getSourceRangeIncludingAttrs().Start;

    SmallString<128> insertion;
    {
      llvm::raw_svector_ostream str(insertion);
      assert(FD->isUnaryOperator() || FD->isBinaryOperator());
      if (FD->isUnaryOperator()) {
        if (FD->getAttrs().hasAttribute<PrefixAttr>())
          str << "prefix operator ";
        else
          str << "postfix operator ";
      } else {
        str << "infix operator ";
      }

       str << operatorName.str() << " : <# Precedence Group #>\n";
    }
    InFlightDiagnostic opDiagnostic =
        diags.diagnose(FD, diag::declared_operator_without_operator_decl);
    if (insertionLoc.isValid())
      opDiagnostic.fixItInsert(insertionLoc, insertion);
    return nullptr;
  }
  return op.get();
}

bool swift::isMemberOperator(FuncDecl *decl, Type type) {
  // Check that member operators reference the type of 'Self'.
  if (decl->isInvalid())
    return true;

  auto *DC = decl->getDeclContext();

  auto selfNominal = DC->getSelfNominalTypeDecl();

  // Check the parameters for a reference to 'Self'.
  bool isProtocol = isa_and_nonnull<ProtocolDecl>(selfNominal);
  bool isTuple = isa_and_nonnull<BuiltinTupleDecl>(selfNominal);

  for (auto param : *decl->getParameters()) {
    // Look through a metatype reference, if there is one.
    auto paramType = param->getInterfaceType()->getMetatypeInstanceType();

    auto nominal = paramType->getAnyNominal();
    if (type.isNull()) {
      // Is it the same nominal type?
      if (selfNominal && nominal == selfNominal)
        return true;
    } else {
      // Is it the same nominal type? Or a generic (which may or may not match)?
      if (paramType->is<GenericTypeParamType>() ||
          nominal == type->getAnyNominal())
        return true;
    }

    if (isProtocol) {
      // FIXME: Source compatibility hack for Swift 5. The compiler
      // accepts member operators on protocols with existential
      // type arguments. We should consider banning this in Swift 6.
      if (auto existential = paramType->getAs<ExistentialType>()) {
        if (selfNominal == existential->getConstraintType()->getAnyNominal())
          return true;
      }
    }

    if (isProtocol || isTuple) {
      // For a protocol or tuple extension, is it the 'Self' type parameter?
      if (paramType->isEqual(DC->getSelfInterfaceType()))
        return true;
    }
  }

  return false;
}

static Type buildAddressorResultType(AccessorDecl *addressor,
                                     Type valueType) {
  assert(addressor->getAccessorKind() == AccessorKind::Address ||
         addressor->getAccessorKind() == AccessorKind::MutableAddress);

  PointerTypeKind pointerKind =
    (addressor->getAccessorKind() == AccessorKind::Address)
      ? PTK_UnsafePointer
      : PTK_UnsafeMutablePointer;
  return valueType->wrapInPointer(pointerKind);
}

Type
ResultTypeRequest::evaluate(Evaluator &evaluator, ValueDecl *decl) const {
  auto &ctx = decl->getASTContext();

  // Accessors always inherit their result type from their storage.
  if (auto *accessor = dyn_cast<AccessorDecl>(decl)) {
    auto *storage = accessor->getStorage();

    switch (accessor->getAccessorKind()) {
    // For getters, set the result type to the value type.
    case AccessorKind::Get:
    case AccessorKind::DistributedGet:
      return storage->getValueInterfaceType();

    // For setters and observers, set the old/new value parameter's type
    // to the value type.
    case AccessorKind::DidSet:
    case AccessorKind::WillSet:
    case AccessorKind::Set:
    case AccessorKind::Init:
      return TupleType::getEmpty(ctx);

    // Addressor result types can get complicated because of the owner.
    case AccessorKind::Address:
    case AccessorKind::MutableAddress:
      return buildAddressorResultType(accessor, storage->getValueInterfaceType());

    // Coroutine accessors don't mention the value type directly.
    // If we add yield types to the function type, we'll need to update this.
    case AccessorKind::Read:
    case AccessorKind::Modify:
      return TupleType::getEmpty(ctx);
    }
  }

  TypeRepr *resultTyRepr = nullptr;
  if (const auto *const funcDecl = dyn_cast<FuncDecl>(decl)) {
    resultTyRepr = funcDecl->getResultTypeRepr();
  } else if (auto subscriptDecl = dyn_cast<SubscriptDecl>(decl)) {
    resultTyRepr = subscriptDecl->getElementTypeRepr();
  } else {
    resultTyRepr = cast<MacroDecl>(decl)->resultType.getTypeRepr();
  }

  if (!resultTyRepr && decl->getClangDecl() &&
      isa<clang::FunctionDecl>(decl->getClangDecl())) {
    auto clangFn = cast<clang::FunctionDecl>(decl->getClangDecl());
    auto returnType = ctx.getClangModuleLoader()->importFunctionReturnType(
        clangFn, decl->getDeclContext());
    if (returnType)
      return *returnType;
    // Mark the imported Swift function as unavailable.
    // That will ensure that the function will not be
    // usable from Swift, even though it is imported.
    if (!decl->getAttrs().isUnavailable(ctx)) {
      StringRef unavailabilityMsgRef = "return type is unavailable in Swift";
      auto ua =
          AvailableAttr::createPlatformAgnostic(ctx, unavailabilityMsgRef);
      decl->getAttrs().add(ua);
    }

    return ctx.getNeverType();
  }

  // Nothing to do if there's no result type.
  if (resultTyRepr == nullptr)
    return TupleType::getEmpty(ctx);

  // Handle opaque types.
  if (auto *opaqueDecl = decl->getOpaqueResultTypeDecl()) {
      return opaqueDecl->getDeclaredInterfaceType();
  }

  auto options =
      TypeResolutionOptions(TypeResolverContext::FunctionResult);
  if (decl->preconcurrency())
    options |= TypeResolutionFlags::Preconcurrency;

  auto *const dc = decl->getInnermostDeclContext();
  return TypeResolution::forInterface(dc, options,
                                      /*unboundTyOpener*/ nullptr,
                                      PlaceholderType::get,
                                      /*packElementOpener*/ nullptr)
      .resolveType(resultTyRepr);
}

ParamSpecifier
ParamSpecifierRequest::evaluate(Evaluator &evaluator,
                                ParamDecl *param) const {
  auto *dc = param->getDeclContext();

  if (param->isSelfParameter()) {
    auto afd = cast<AbstractFunctionDecl>(dc);
    auto selfParam = computeSelfParam(afd,
                                      /*isInitializingCtor*/true,
                                      /*wantDynamicSelf*/false);
    if (auto fd = dyn_cast<FuncDecl>(afd)) {
      switch (fd->getSelfAccessKind()) {
      case SelfAccessKind::LegacyConsuming:
        return ParamSpecifier::LegacyOwned;
      case SelfAccessKind::Consuming:
        return ParamSpecifier::Consuming;
      case SelfAccessKind::Borrowing:
        return ParamSpecifier::Borrowing;
      case SelfAccessKind::Mutating:
        return ParamSpecifier::InOut;
      case SelfAccessKind::NonMutating:
        return ParamSpecifier::Default;
      }
      llvm_unreachable("nonexhaustive switch");
    } else {
      return (selfParam.getParameterFlags().isInOut()
              ? ParamSpecifier::InOut
              : ParamSpecifier::Default);
    }
  }

  if (auto *accessor = dyn_cast<AccessorDecl>(dc)) {
    auto *storage = accessor->getStorage();
    auto *originalParam = getOriginalParamFromAccessor(
      storage, accessor, param);
    if (originalParam == nullptr) {
      // This is the setter's newValue parameter. Note that even though
      // the AST uses the 'Default' specifier, SIL will lower this to a
      // +1 parameter.
      return ParamSpecifier::Default;
    }

    if (param != originalParam) {
      // This is the 'subscript(...) { get { ... } set { ... } }' case.
      // This means we cloned the parameter list for each accessor.
      // Delegate to the original parameter.
      return originalParam->getSpecifier();
    }

    // This is the 'subscript(...) { <<body of getter>> }' case.
    // The subscript and the getter share their ParamDecls.
    // Fall through.
  }

  auto typeRepr = param->getTypeRepr();
  assert(typeRepr != nullptr && "Should call setSpecifier() on "
         "synthesized parameter declarations");

  // Look through top-level pack expansions.  These specifiers are
  // part of what's repeated.
  if (auto expansion = dyn_cast<PackExpansionTypeRepr>(typeRepr))
    typeRepr = expansion->getPatternType();

  // Look through parens here; other than parens, specifiers
  // must appear at the top level of a parameter type.
  auto *nestedRepr = typeRepr->getWithoutParens();

  if (auto isolated = dyn_cast<IsolatedTypeRepr>(nestedRepr))
    nestedRepr = isolated->getBase();

  if (auto sending = dyn_cast<SendingTypeRepr>(nestedRepr)) {
    // If we do not have an Ownership Repr and do not have a no escape type,
    // return implicit copyable consuming.
    auto *base = sending->getBase();
    if (!param->getInterfaceType()->isNoEscape() &&
        !isa<OwnershipTypeRepr>(base)) {
      return ParamSpecifier::ImplicitlyCopyableConsuming;
    }
    nestedRepr = base;
  }

  if (auto ownershipRepr = dyn_cast<OwnershipTypeRepr>(nestedRepr)) {
    if (ownershipRepr->getSpecifier() == ParamSpecifier::InOut
        && param->isDefaultArgument()) {
      auto &ctx = param->getASTContext();
      ctx.Diags.diagnose(param->getStructuralDefaultExpr()->getLoc(),
                         swift::diag::cannot_provide_default_value_inout,
                         param->getName());
      return ParamSpecifier::Default;
    }
    return ownershipRepr->getSpecifier();
  }
  
  return ParamSpecifier::Default;
}

static Type validateParameterType(ParamDecl *decl) {
  auto *dc = decl->getDeclContext();
  auto &ctx = dc->getASTContext();

  TypeResolutionOptions options(std::nullopt);
  OpenUnboundGenericTypeFn unboundTyOpener = nullptr;
  if (isa<AbstractClosureExpr>(dc)) {
    options = TypeResolutionOptions(TypeResolverContext::ClosureExpr);
    options |= TypeResolutionFlags::AllowUnspecifiedTypes;
    unboundTyOpener = [](auto unboundTy) {
      // FIXME: Don't let unbound generic types escape type resolution.
      // For now, just return the unbound generic type.
      return unboundTy;
    };
    // FIXME: Don't let placeholder types escape type resolution.
    // For now, just return the placeholder type.
  } else if (isa<AbstractFunctionDecl>(dc)) {
    options = TypeResolutionOptions(TypeResolverContext::AbstractFunctionDecl);
  } else if (isa<SubscriptDecl>(dc)) {
    options = TypeResolutionOptions(TypeResolverContext::SubscriptDecl);
  } else if (isa<EnumElementDecl>(dc)) {
    options = TypeResolutionOptions(TypeResolverContext::EnumElementDecl);
  } else {
    assert(isa<MacroDecl>(dc));
    options = TypeResolutionOptions(TypeResolverContext::MacroDecl);
  }

  // Set the "preconcurrency" flag if this is a parameter of a preconcurrency
  // declaration.
  if (auto decl = dc->getAsDecl()) {
    if (decl->preconcurrency())
      options |= TypeResolutionFlags::Preconcurrency;
  }

  if (dc->isInSpecializeExtensionContext())
    options |= TypeResolutionFlags::AllowUsableFromInline;

  Type Ty;

  auto *nestedRepr = decl->getTypeRepr();
  ParamSpecifier ownership = ParamSpecifier::Default;
  while (true) {
    if (auto *attrTypeRepr = dyn_cast<AttributedTypeRepr>(nestedRepr)) {
      nestedRepr = attrTypeRepr->getTypeRepr();
      continue;
    }
    if (auto *specifierTypeRepr = dyn_cast<SpecifierTypeRepr>(nestedRepr)) {
      if (specifierTypeRepr->getKind() == TypeReprKind::Ownership)
        ownership = cast<OwnershipTypeRepr>(specifierTypeRepr)->getSpecifier();

      nestedRepr = specifierTypeRepr->getBase();
      continue;
    }
    break;
  }

  // If the element is a variadic parameter, resolve the parameter type as if
  // it were in non-parameter position, since we want functions to be
  // @escaping in this case.
  options.setContext(isa<VarargTypeRepr>(nestedRepr)
                     ? TypeResolverContext::VariadicFunctionInput
                     : TypeResolverContext::FunctionInput);
  options |= TypeResolutionFlags::Direct;

  const auto resolution =
      TypeResolution::forInterface(dc, options, unboundTyOpener,
                                   PlaceholderType::get,
                                   /*packElementOpener*/ nullptr);

  if (auto *varargTypeRepr = dyn_cast<VarargTypeRepr>(nestedRepr)) {
    Ty = resolution.resolveType(nestedRepr);

    // Monovariadic types (T...) for <T> resolve to [T].
    Ty = VariadicSequenceType::get(Ty);

    // Set the old-style variadic bit.
    decl->setVariadic();
    if (!ctx.getArrayDecl()) {
      ctx.Diags.diagnose(decl->getTypeRepr()->getLoc(),
                         diag::sugar_type_not_found, 0);
      return ErrorType::get(ctx);
    }
  } else {
    Ty = resolution.resolveType(decl->getTypeRepr());
  }

  if (Ty->hasError()) {
    decl->setInvalid();
    return ErrorType::get(ctx);
  }

  // Validate the presence of ownership for a parameter with an inverse applied.
  if (!Ty->hasUnboundGenericType() &&
      diagnoseMissingOwnership(ownership, decl->getTypeRepr(), Ty, resolution)) {
    decl->setInvalid();
    return ErrorType::get(ctx);
  }

  return Ty;
}

static void maybeAddParameterIsolation(AnyFunctionType::ExtInfoBuilder &infoBuilder,
                                       ArrayRef<AnyFunctionType::Param> params) {
  if (hasIsolatedParameter(params))
    infoBuilder = infoBuilder.withIsolation(FunctionTypeIsolation::forParameter());
}

Type
InterfaceTypeRequest::evaluate(Evaluator &eval, ValueDecl *D) const {
  auto &Context = D->getASTContext();

  TypeChecker::checkForForbiddenPrefix(Context, D->getBaseName());

  switch (D->getKind()) {
  case DeclKind::Import:
  case DeclKind::Extension:
  case DeclKind::PatternBinding:
  case DeclKind::EnumCase:
  case DeclKind::TopLevelCode:
  case DeclKind::InfixOperator:
  case DeclKind::PrefixOperator:
  case DeclKind::PostfixOperator:
  case DeclKind::PrecedenceGroup:
  case DeclKind::IfConfig:
  case DeclKind::PoundDiagnostic:
  case DeclKind::Missing:
  case DeclKind::MissingMember:
  case DeclKind::Module:
  case DeclKind::OpaqueType:
  case DeclKind::GenericTypeParam:
  case DeclKind::MacroExpansion:
    llvm_unreachable("should not get here");
    return Type();

  case DeclKind::AssociatedType: {
    auto assocType = cast<AssociatedTypeDecl>(D);
    auto interfaceTy = assocType->getDeclaredInterfaceType();
    return MetatypeType::get(interfaceTy, Context);
  }

  case DeclKind::TypeAlias: {
    auto typeAlias = cast<TypeAliasDecl>(D);

    auto genericSig = typeAlias->getGenericSignature();
    SubstitutionMap subs;
    if (genericSig)
      subs = genericSig->getIdentitySubstitutionMap();

    Type parent;
    auto parentDC = typeAlias->getDeclContext();
    if (parentDC->isTypeContext())
      parent = parentDC->getSelfInterfaceType();
    auto sugaredType = TypeAliasType::get(typeAlias, parent, subs,
                                          typeAlias->getUnderlyingType());
    return MetatypeType::get(sugaredType, Context);
  }

  case DeclKind::Enum:
  case DeclKind::Struct:
  case DeclKind::Class:
  case DeclKind::Protocol:
  case DeclKind::BuiltinTuple: {
    auto nominal = cast<NominalTypeDecl>(D);
    Type declaredInterfaceTy = nominal->getDeclaredInterfaceType();
    // FIXME: For a protocol, this returns a MetatypeType wrapping a ProtocolType, but should be a MetatypeType wrapping an ExistentialType ('(any P).Type', not 'P.Type').
    return MetatypeType::get(declaredInterfaceTy, Context);
  }

  case DeclKind::Param: {
    auto *PD = cast<ParamDecl>(D);
    if (PD->isSelfParameter()) {
      auto *AFD = cast<AbstractFunctionDecl>(PD->getDeclContext());
      auto selfParam = computeSelfParam(AFD,
                                        /*isInitializingCtor*/true,
                                        /*wantDynamicSelf*/true);
      PD->setIsolated(selfParam.isIsolated());
      return selfParam.getPlainType();
    }

    if (auto *accessor = dyn_cast<AccessorDecl>(PD->getDeclContext())) {
      auto *storage = accessor->getStorage();
      auto *originalParam = getOriginalParamFromAccessor(
        storage, accessor, PD);
      if (originalParam == nullptr) {
        return storage->getValueInterfaceType();
      }

      if (originalParam != PD) {
        return originalParam->getInterfaceType();
      }
    }

    if (!PD->getTypeRepr())
      return ErrorType::get(Context);

    return validateParameterType(PD);
  }

  case DeclKind::Var: {
    auto *VD = cast<VarDecl>(D);

    if (auto clangDecl = VD->getClangDecl()) {
      auto clangVarDecl = cast<clang::VarDecl>(clangDecl);

      return VD->getASTContext().getClangModuleLoader()->importVarDeclType(
          clangVarDecl, VD, VD->getDeclContext());
    }

    auto *namingPattern = VD->getNamingPattern();
    if (!namingPattern) {
      return ErrorType::get(Context);
    }

    Type interfaceType = namingPattern->getType();
    if (interfaceType->hasArchetype())
      interfaceType = interfaceType->mapTypeOutOfContext();

    // In SIL mode, VarDecls are written as having reference storage types.
    if (!interfaceType->is<ReferenceStorageType>()) {
      if (auto *attr = VD->getAttrs().getAttribute<ReferenceOwnershipAttr>())
        interfaceType =
            TypeChecker::checkReferenceOwnershipAttr(VD, interfaceType, attr);
    }

    return interfaceType;
  }

  case DeclKind::Func:
  case DeclKind::Accessor:
  case DeclKind::Constructor:
  case DeclKind::Destructor: {
    // If this is a didSet, then we need to check whether the body references
    // the implicit 'oldValue' parameter or not, in order to correctly
    // compute the interface type.
    if (auto AD = dyn_cast<AccessorDecl>(D)) {
      (void)AD->isSimpleDidSet();
    }

    auto *AFD = cast<AbstractFunctionDecl>(D);

    auto sig = AFD->getGenericSignature();
    bool hasSelf = AFD->hasImplicitSelfDecl();

    AnyFunctionType::ExtInfoBuilder infoBuilder;

    // Thrown error type.
    Type thrownTy = AFD->getThrownInterfaceType();
    if (thrownTy) {
      thrownTy = AFD->getThrownInterfaceType();
      ProtocolDecl *errorProto = Context.getErrorDecl();
      if (thrownTy && errorProto) {
        Type thrownTyInContext = AFD->mapTypeIntoContext(thrownTy);
        if (!AFD->getParentModule()->checkConformance(
                thrownTyInContext, errorProto)) {
          SourceLoc loc;
          if (auto thrownTypeRepr = AFD->getThrownTypeRepr())
            loc = thrownTypeRepr->getLoc();
          else
            loc = AFD->getLoc();
          Context.Diags.diagnose(loc, diag::thrown_type_not_error, thrownTy);
        }
      }
    }

    // Result
    Type resultTy;
    if (auto fn = dyn_cast<FuncDecl>(D)) {
      resultTy = fn->getResultInterfaceType();
    } else if (auto ctor = dyn_cast<ConstructorDecl>(D)) {
      resultTy = ctor->getResultInterfaceType();
    } else {
      assert(isa<DestructorDecl>(D));
      resultTy = TupleType::getEmpty(AFD->getASTContext());
    }

    auto lifetimeDependenceInfo = AFD->getLifetimeDependenceInfo();

    // (Args...) -> Result
    Type funcTy;

    {
      SmallVector<AnyFunctionType::Param, 4> argTy;
      AFD->getParameters()->getParams(argTy);

      maybeAddParameterIsolation(infoBuilder, argTy);
      infoBuilder = infoBuilder.withAsync(AFD->hasAsync());
      infoBuilder = infoBuilder.withSendable(AFD->isSendable());
      // 'throws' only applies to the innermost function.
      infoBuilder = infoBuilder.withThrows(AFD->hasThrows(), thrownTy);
      // Defer bodies must not escape.
      if (auto fd = dyn_cast<FuncDecl>(D)) {
        infoBuilder = infoBuilder.withNoEscape(fd->isDeferBody());
        if (fd->hasSendingResult())
          infoBuilder = infoBuilder.withSendingResult();
      }

      if (lifetimeDependenceInfo.has_value()) {
        infoBuilder =
            infoBuilder.withLifetimeDependenceInfo(*lifetimeDependenceInfo);
      }

      auto info = infoBuilder.build();

      if (sig && !hasSelf) {
        funcTy = GenericFunctionType::get(sig, argTy, resultTy, info);
      } else {
        funcTy = FunctionType::get(argTy, resultTy, info);
      }
    }

    // (Self) -> (Args...) -> Result
    if (hasSelf) {
      // Substitute in our own 'self' parameter.
      auto selfParam = computeSelfParam(AFD);
      AnyFunctionType::ExtInfoBuilder selfInfoBuilder;
      maybeAddParameterIsolation(selfInfoBuilder, {selfParam});
      if (lifetimeDependenceInfo.has_value()) {
        selfInfoBuilder =
            selfInfoBuilder.withLifetimeDependenceInfo(*lifetimeDependenceInfo);
      }

      // FIXME: Verify ExtInfo state is correct, not working by accident.
      auto selfInfo = selfInfoBuilder.build();
      if (sig) {
        funcTy = GenericFunctionType::get(sig, {selfParam}, funcTy, selfInfo);
      } else {
        funcTy = FunctionType::get({selfParam}, funcTy, selfInfo);
      }
    }

    return funcTy;
  }

  case DeclKind::Subscript: {
    auto *SD = cast<SubscriptDecl>(D);

    auto elementTy = SD->getElementInterfaceType();

    SmallVector<AnyFunctionType::Param, 2> argTy;
    SD->getIndices()->getParams(argTy);

    AnyFunctionType::ExtInfoBuilder infoBuilder;
    maybeAddParameterIsolation(infoBuilder, argTy);

    Type funcTy;
    // FIXME: Verify ExtInfo state is correct, not working by accident.
    auto info = infoBuilder.build();
    if (auto sig = SD->getGenericSignature()) {
      funcTy = GenericFunctionType::get(sig, argTy, elementTy, info);
    } else {
      funcTy = FunctionType::get(argTy, elementTy, info);
    }

    return funcTy;
  }

  case DeclKind::EnumElement: {
    auto *EED = cast<EnumElementDecl>(D);

    auto *ED = EED->getParentEnum();

    // The type of the enum element is either (Self.Type) -> Self
    // or (Self.Type) -> (Args...) -> Self.
    auto resultTy = ED->getDeclaredInterfaceType();

    AnyFunctionType::Param selfTy(MetatypeType::get(resultTy, Context));

    if (auto *PL = EED->getParameterList()) {
      SmallVector<AnyFunctionType::Param, 4> argTy;
      PL->getParams(argTy);

      // FIXME: Verify ExtInfo state is correct, not working by accident.
      FunctionType::ExtInfo info;
      resultTy = FunctionType::get(argTy, resultTy, info);
    }

    // FIXME: Verify ExtInfo state is correct, not working by accident.
    if (auto genericSig = ED->getGenericSignature()) {
      GenericFunctionType::ExtInfo info;
      resultTy = GenericFunctionType::get(genericSig, {selfTy}, resultTy, info);
    } else {
      FunctionType::ExtInfo info;
      resultTy = FunctionType::get({selfTy}, resultTy, info);
    }

    return resultTy;
  }

  case DeclKind::Macro: {
    auto macro = cast<MacroDecl>(D);
    Type resultType = macro->getResultInterfaceType();
    if (!macro->parameterList)
      return resultType;

    SmallVector<AnyFunctionType::Param, 4> paramTypes;
    macro->parameterList->getParams(paramTypes);

    if (auto genericSig = macro->getGenericSignature()) {
      GenericFunctionType::ExtInfo info;
      return GenericFunctionType::get(
          genericSig, paramTypes, resultType, info);
    } else {
      FunctionType::ExtInfo info;
      return FunctionType::get(paramTypes, resultType, info);
    }
  }
  }
  llvm_unreachable("invalid decl kind");
}

NamedPattern *
NamingPatternRequest::evaluate(Evaluator &evaluator, VarDecl *VD) const {
  auto &Context = VD->getASTContext();
  auto *PBD = VD->getParentPatternBinding();
  // FIXME: In order for this request to properly express its dependencies,
  // all of the places that allow variable bindings need to also use pattern
  // binding decls. Otherwise, we'll have to go digging around in case
  // statements and patterns to find named patterns.
  if (PBD) {
    // FIXME: For now, this works because PatternBindingEntryRequest fills in
    // the naming pattern as a side effect in this case, and TypeCheckStmt
    // and TypeCheckPattern handle the others. But that's all really gross.
    unsigned i = PBD->getPatternEntryIndexForVarDecl(VD);
    (void)PBD->getCheckedPatternBindingEntry(i);
    if (PBD->isInvalid()) {
      VD->getParentPattern()->setType(ErrorType::get(Context));
      setBoundVarsTypeError(VD->getParentPattern(), Context);
      return nullptr;
    }
  } else if (!VD->getParentPatternStmt() && !VD->getParentVarDecl()) {
    // No parent?  That's an error.
    return nullptr;
  }

  // Go digging for the named pattern that declares this variable.
  auto *namingPattern = VD->NamingPattern;
  if (!namingPattern) {
    auto *canVD = VD->getCanonicalVarDecl();
    namingPattern = canVD->NamingPattern;
  }

  if (!namingPattern) {
    if (auto parentStmt = VD->getParentPatternStmt()) {
      // Try type checking parent control statement.
      if (auto condStmt = dyn_cast<LabeledConditionalStmt>(parentStmt)) {
        // The VarDecl is defined inside a condition of a `if` or `while` stmt.
        // Only type check the condition we care about: the one with the VarDecl
        bool foundVarDecl = false;
        for (auto &condElt : condStmt->getCond()) {
          if (auto pat = condElt.getPatternOrNull()) {
            if (!pat->containsVarDecl(VD)) {
              continue;
            }
            // We found the condition that declares the variable. Type check it
            // and stop the loop. The variable can only be declared once.

            // We don't care about isFalsable
            bool isFalsable = false;
            TypeChecker::typeCheckStmtConditionElement(condElt, isFalsable,
                                                       VD->getDeclContext());

            foundVarDecl = true;
            break;
          }
        }
        assert(foundVarDecl && "VarDecl not declared in its parent?");
        (void) foundVarDecl;
      } else {
        // We have some other parent stmt. Type check it completely.
        if (auto CS = dyn_cast<CaseStmt>(parentStmt))
          parentStmt = CS->getParentStmt();

        bool LeaveBodyUnchecked = true;
        // type-checking 'catch' patterns depends on the type checked body.
        if (isa<DoCatchStmt>(parentStmt))
          LeaveBodyUnchecked = false;

        ASTNode node(parentStmt);
        TypeChecker::typeCheckASTNode(node, VD->getDeclContext(),
                                      LeaveBodyUnchecked);
      }
      namingPattern = VD->getCanonicalVarDecl()->NamingPattern;
    }
  }

  if (!namingPattern) {
    // HACK: If no other diagnostic applies, emit a generic diagnostic about
    // a variable being unbound. We can't do better than this at the
    // moment because TypeCheckPattern does not reliably invalidate parts of
    // the pattern AST on failure.
    //
    // Once that's through, this will only fire during circular validation.
    if (VD->hasInterfaceType() &&
        !VD->isInvalid() && !VD->getParentPattern()->isImplicit()) {
      VD->diagnose(diag::variable_bound_by_no_pattern, VD);
    }

    VD->getParentPattern()->setType(ErrorType::get(Context));
    setBoundVarsTypeError(VD->getParentPattern(), Context);
    return nullptr;
  }

  if (!namingPattern->hasType()) {
    namingPattern->setType(ErrorType::get(Context));
    setBoundVarsTypeError(namingPattern, Context);
  }

  return namingPattern;
}

namespace {

// Utility class for deterministically ordering vtable entries for
// synthesized declarations.
struct SortedDeclList {
  using Key = std::tuple<DeclName, std::string>;
  using Entry = std::pair<Key, ValueDecl *>;
  SmallVector<Entry, 2> elts;
  bool sorted = false;

  void add(ValueDecl *vd) {
    assert(!isa<AccessorDecl>(vd));

    Key key{vd->getName(), vd->getInterfaceType()->getCanonicalType().getString()};
    elts.emplace_back(key, vd);
  }

  bool empty() { return elts.empty(); }

  void sort() {
    assert(!sorted);
    sorted = true;
    std::sort(elts.begin(),
              elts.end(),
              [](const Entry &lhs, const Entry &rhs) -> bool {
                return lhs.first < rhs.first;
              });
  }

  decltype(elts)::const_iterator begin() const {
    assert(sorted);
    return elts.begin();
  }

  decltype(elts)::const_iterator end() const {
    assert(sorted);
    return elts.end();
  }
};

} // end namespace

namespace {
  enum class MembersRequestKind {
    ABI,
    All,
  };

}

/// Evaluate a request for a particular set of members of an iterable
/// declaration context.
static ArrayRef<Decl *> evaluateMembersRequest(
  IterableDeclContext *idc, MembersRequestKind kind) {
  auto dc = cast<DeclContext>(idc->getDecl());
  auto &ctx = dc->getASTContext();
  SmallVector<Decl *, 8> result;

  // If there's no parent source file, everything is already in order.
  if (!dc->getParentSourceFile()) {
    for (auto *member : idc->getMembers())
      result.push_back(member);

    return ctx.AllocateCopy(result);
  }

  auto nominal = dyn_cast<NominalTypeDecl>(dc->getImplementedObjCContext());

  if (nominal) {
    // We need to add implicit initializers because they
    // affect vtable layout.
    TypeChecker::addImplicitConstructors(nominal);

    // Destructors don't affect vtable layout, but TBDGen needs to
    // see them, so we also force the destructor here.
    if (auto *classDecl = dyn_cast<ClassDecl>(nominal))
      (void) classDecl->getDestructor();
  }

  // Force any conformances that may introduce more members.
  for (auto conformance : idc->getLocalConformances()) {
    auto *normal = dyn_cast<NormalProtocolConformance>(
        conformance->getRootConformance());
    if (normal == nullptr)
      continue;

    auto proto = conformance->getProtocol();
    bool isDerivable = proto->getKnownDerivableProtocolKind().has_value();


    if (kind == MembersRequestKind::All &&
        !proto->getAssociatedTypeMembers().empty()) {
      evaluateOrDefault(ctx.evaluator,
                        ResolveTypeWitnessesRequest{normal},
                        evaluator::SideEffect());
    }

    if (isDerivable) {
      normal->resolveValueWitnesses();
    }
  }

  if (nominal) {
    // If the type conforms to Encodable or Decodable, even via an extension,
    // the CodingKeys enum is synthesized as a member of the type itself.
    // Force it into existence.
    (void) evaluateOrDefault(
      ctx.evaluator,
      ResolveImplicitMemberRequest{nominal,
                 ImplicitMemberAction::ResolveCodingKeys},
      {});
  }

  // Expand synthesized member macros.
  auto *mutableDecl = const_cast<Decl *>(idc->getDecl());
  (void)evaluateOrDefault(
      ctx.evaluator,
      ExpandSynthesizedMemberMacroRequest{mutableDecl},
      false);

  // If the decl has a @main attribute, we need to force synthesis of the
  // $main function.
  (void) evaluateOrDefault(
      ctx.evaluator,
      SynthesizeMainFunctionRequest{const_cast<Decl *>(idc->getDecl())},
      nullptr);

  for (auto *member : idc->getMembers()) {
    if (auto *var = dyn_cast<VarDecl>(member)) {
      // The projected storage wrapper ($foo) might have
      // dynamically-dispatched accessors, so force them to be synthesized.
      if (var->hasAttachedPropertyWrapper()) {
        (void) var->getPropertyWrapperAuxiliaryVariables();
        (void) var->getPropertyWrapperInitializerInfo();
      }
    }
  }

  SortedDeclList synthesizedMembers;

  std::function<void(Decl *)> addResult;
  addResult = [&](Decl *member) {
    member->visitAuxiliaryDecls(addResult);
    if (auto *vd = dyn_cast<ValueDecl>(member)) {
      // Add synthesized members to a side table and sort them by their mangled
      // name, since they could have been added to the class in any order.
      if (vd->isSynthesized() &&
          // FIXME: IRGen requires the distributed actor synthesized
          // properties to be in a specific order that is different
          // from ordering by their mangled name, so preserve the order
          // they were added in.
          !(nominal &&
            (vd == nominal->getDistributedActorIDProperty() ||
             vd == nominal->getDistributedActorSystemProperty()))) {
        synthesizedMembers.add(vd);
        return;
      }
    }
    result.push_back(member);
  };

  for (auto *member : idc->getMembers()) {
    addResult(member);
  }

  if (!synthesizedMembers.empty()) {
    synthesizedMembers.sort();
    for (const auto &pair : synthesizedMembers)
      result.push_back(pair.second);
  }

  return ctx.AllocateCopy(result);
}

ArrayRef<Decl *>
ABIMembersRequest::evaluate(
    Evaluator &evaluator, IterableDeclContext *idc) const {
  return evaluateMembersRequest(idc, MembersRequestKind::ABI);
}

ArrayRef<Decl *>
AllMembersRequest::evaluate(
    Evaluator &evaluator, IterableDeclContext *idc) const {
  return evaluateMembersRequest(idc, MembersRequestKind::All);
}

bool TypeChecker::isPassThroughTypealias(TypeAliasDecl *typealias,
                                         NominalTypeDecl *nominal) {
  // Pass-through only makes sense when the typealias refers to a nominal
  // type.
  if (!nominal) return false;

  // Check that the nominal type and the typealias are either both generic
  // at this level or neither are.
  if (nominal->isGeneric() != typealias->isGeneric())
    return false;

  // Make sure either both have generic signatures or neither do.
  auto nominalSig = nominal->getGenericSignature();
  auto typealiasSig = typealias->getGenericSignature();
  if (static_cast<bool>(nominalSig) != static_cast<bool>(typealiasSig))
    return false;

  // If neither is generic, we're done: it's a pass-through alias.
  if (!nominalSig) return true;

  // Check that the type parameters are the same the whole way through.
  auto nominalGenericParams = nominalSig.getGenericParams();
  auto typealiasGenericParams = typealiasSig.getGenericParams();
  if (nominalGenericParams.size() != typealiasGenericParams.size())
    return false;
  if (!std::equal(nominalGenericParams.begin(), nominalGenericParams.end(),
                  typealiasGenericParams.begin(),
                  [](GenericTypeParamType *gp1, GenericTypeParamType *gp2) {
                    return gp1->isEqual(gp2);
                  }))
    return false;

  // If neither is generic at this level, we have a pass-through typealias.
  if (!typealias->isGeneric()) return true;

  if (typealias->getUnderlyingType()->isEqual(
        nominal->getSelfInterfaceType())) {
    return true;
  }

  return false;
}

Type
ExtendedTypeRequest::evaluate(Evaluator &eval, ExtensionDecl *ext) const {
  auto error = [&ext]() {
    ext->setInvalid();
    return ErrorType::get(ext->getASTContext());
  };

  // If we didn't parse a type, fill in an error type and bail out.
  auto *extendedRepr = ext->getExtendedTypeRepr();
  if (!extendedRepr)
    return error();

  // Compute the extended type.
  TypeResolutionOptions options(TypeResolverContext::ExtensionBinding);
  if (ext->isInSpecializeExtensionContext())
    options |= TypeResolutionFlags::AllowUsableFromInline;
  const auto resolution = TypeResolution::forStructural(
      ext->getDeclContext(), options, nullptr,
      // FIXME: Don't let placeholder types escape type resolution.
      // For now, just return the placeholder type.
      PlaceholderType::get,
      /*packElementOpener*/ nullptr);

  auto extendedType = resolution.resolveType(extendedRepr);

  if (extendedType->hasError())
    return error();

  // Hack to allow extending a generic typealias.
  if (auto *unboundGeneric = extendedType->getAs<UnboundGenericType>()) {
    if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(unboundGeneric->getDecl())) {
      auto underlyingType = aliasDecl->getUnderlyingType();
      if (auto extendedNominal = underlyingType->getAnyNominal()) {
        return TypeChecker::isPassThroughTypealias(
                   aliasDecl, extendedNominal)
                   ? extendedType
                   : extendedNominal->getDeclaredType();
      }

      if (underlyingType->is<TupleType>()) {
        return extendedType;
      }
    }
  }

  auto &diags = ext->getASTContext().Diags;

  // Cannot extend a metatype.
  if (extendedType->is<AnyMetatypeType>()) {
    diags.diagnose(ext->getLoc(), diag::extension_metatype, extendedType)
         .highlight(extendedRepr->getSourceRange());
    return error();
  }

  // Cannot extend function types, metatypes, existentials, etc.
  if (!extendedType->is<TupleType>() &&
      !extendedType->getAnyNominal() &&
      !extendedType->is<ParameterizedProtocolType>()) {
    diags.diagnose(ext->getLoc(), diag::non_nominal_extension, extendedType)
         .highlight(extendedRepr->getSourceRange());
    return error();
  }

  // Cannot extend types who contain placeholders.
  if (extendedType->hasPlaceholder()) {
    diags.diagnose(ext->getLoc(), diag::extension_placeholder)
      .highlight(extendedRepr->getSourceRange());
    return error();
  }

  return extendedType;
}

//----------------------------------------------------------------------------//
// ImplicitKnownProtocolConformanceRequest
//----------------------------------------------------------------------------//
ProtocolConformance *
ImplicitKnownProtocolConformanceRequest::evaluate(Evaluator &evaluator,
                                                  NominalTypeDecl *nominal,
                                                  KnownProtocolKind kp) const {
  switch (kp) {
  case KnownProtocolKind::Sendable:
    return deriveImplicitSendableConformance(evaluator, nominal);
  case KnownProtocolKind::BitwiseCopyable:
    return deriveImplicitBitwiseCopyableConformance(nominal);
  default:
    llvm_unreachable("non-implicitly derived KnownProtocol");
  }
}

std::optional<LifetimeDependenceInfo>
LifetimeDependenceInfoRequest::evaluate(Evaluator &evaluator,
                                        AbstractFunctionDecl *decl) const {
  return LifetimeDependenceInfo::get(decl);
}