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

using namespace swift;
using namespace swift::constraints;

static bool isArithmeticOperatorDecl(ValueDecl *vd) {
  return vd && vd->getBaseIdentifier().isArithmeticOperator();
}

static bool mergeRepresentativeEquivalenceClasses(ConstraintSystem &CS,
                                                  TypeVariableType* tyvar1,
                                                  TypeVariableType* tyvar2) {
  if (tyvar1 && tyvar2) {
    auto rep1 = CS.getRepresentative(tyvar1);
    auto rep2 = CS.getRepresentative(tyvar2);

    if (rep1 != rep2) {
      auto fixedType2 = CS.getFixedType(rep2);

      // If the there exists fixed type associated with the second
      // type variable, and we simply merge two types together it would
      // mean that portion of the constraint graph previously associated
      // with that (second) variable is going to be disconnected from its
      // new equivalence class, which is going to lead to incorrect solutions,
      // so we need to make sure to re-bind fixed to the new representative.
      if (fixedType2) {
        CS.addConstraint(ConstraintKind::Bind, fixedType2, rep1,
                         rep1->getImpl().getLocator());
      }

      CS.mergeEquivalenceClasses(rep1, rep2, /*updateWorkList*/ false);
      return true;
    }
  }

  return false;
}

namespace {
  
  /// Internal struct for tracking information about types within a series
  /// of "linked" expressions. (Such as a chain of binary operator invocations.)
  struct LinkedTypeInfo {
    bool hasLiteral = false;

    llvm::SmallSet<TypeBase*, 16> collectedTypes;
    llvm::SmallVector<BinaryExpr *, 4> binaryExprs;
  };

  /// Walks an expression sub-tree, and collects information about expressions
  /// whose types are mutually dependent upon one another.
  class LinkedExprCollector : public ASTWalker {
    
    llvm::SmallVectorImpl<Expr*> &LinkedExprs;

  public:
    LinkedExprCollector(llvm::SmallVectorImpl<Expr *> &linkedExprs)
        : LinkedExprs(linkedExprs) {}

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

    PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
      if (isa<ClosureExpr>(expr))
        return Action::SkipNode(expr);

      // Store top-level binary exprs for further analysis.
      if (isa<BinaryExpr>(expr) ||
          
          // Literal exprs are contextually typed, so store them off as well.
          isa<LiteralExpr>(expr) ||

          // We'd like to look at the elements of arrays and dictionaries.
          isa<ArrayExpr>(expr) ||
          isa<DictionaryExpr>(expr) ||

          // assignment expression can involve anonymous closure parameters
          // as source and destination, so it's beneficial for diagnostics if
          // we look at the assignment.
          isa<AssignExpr>(expr)) {
        LinkedExprs.push_back(expr);
        return Action::SkipNode(expr);
      }
      
      return Action::Continue(expr);
    }

    /// Ignore statements.
    PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
      return Action::SkipNode(stmt);
    }
    
    /// Ignore declarations.
    PreWalkAction walkToDeclPre(Decl *decl) override {
      return Action::SkipNode();
    }

    /// Ignore patterns.
    PreWalkResult<Pattern *> walkToPatternPre(Pattern *pat) override {
      return Action::SkipNode(pat);
    }

    /// Ignore types.
    PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
      return Action::SkipNode();
    }
  };
  
  /// Given a collection of "linked" expressions, analyzes them for
  /// commonalities regarding their types. This will help us compute a
  /// "best common type" from the expression types.
  class LinkedExprAnalyzer : public ASTWalker {
    
    LinkedTypeInfo &LTI;
    ConstraintSystem &CS;
    
  public:
    
    LinkedExprAnalyzer(LinkedTypeInfo &lti, ConstraintSystem &cs) :
        LTI(lti), CS(cs) {}

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

    PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
      if (isa<LiteralExpr>(expr)) {
        LTI.hasLiteral = true;
        return Action::SkipNode(expr);
      }

      if (isa<CollectionExpr>(expr)) {
        return Action::Continue(expr);
      }
      
      if (auto UDE = dyn_cast<UnresolvedDotExpr>(expr)) {
        
        if (CS.hasType(UDE))
          LTI.collectedTypes.insert(CS.getType(UDE).getPointer());
        
        // Don't recurse into the base expression.
        return Action::SkipNode(expr);
      }


      if (isa<ClosureExpr>(expr)) {
        return Action::SkipNode(expr);
      }

      if (auto FVE = dyn_cast<ForceValueExpr>(expr)) {
        LTI.collectedTypes.insert(CS.getType(FVE).getPointer());
        return Action::SkipNode(expr);
      }

      if (auto DRE = dyn_cast<DeclRefExpr>(expr)) {
        if (auto varDecl = dyn_cast<VarDecl>(DRE->getDecl())) {
          if (CS.hasType(DRE)) {
            LTI.collectedTypes.insert(CS.getType(DRE).getPointer());
          }
          return Action::SkipNode(expr);
        } 
      }             

      // In the case of a function application, we would have already captured
      // the return type during constraint generation, so there's no use in
      // looking any further.
      if (isa<ApplyExpr>(expr) &&
          !(isa<BinaryExpr>(expr) || isa<PrefixUnaryExpr>(expr) ||
            isa<PostfixUnaryExpr>(expr))) {
        return Action::SkipNode(expr);
      }

      if (auto *binaryExpr = dyn_cast<BinaryExpr>(expr)) {
        LTI.binaryExprs.push_back(binaryExpr);
      }  
      
      if (auto favoredType = CS.getFavoredType(expr)) {
        LTI.collectedTypes.insert(favoredType);

        return Action::SkipNode(expr);
      }

      // Optimize branches of a conditional expression separately.
      if (auto IE = dyn_cast<TernaryExpr>(expr)) {
        CS.optimizeConstraints(IE->getCondExpr());
        CS.optimizeConstraints(IE->getThenExpr());
        CS.optimizeConstraints(IE->getElseExpr());
        return Action::SkipNode(expr);
      }      

      // For exprs of a tuple, avoid favoring. (We need to allow for cases like
      // (Int, Int32).)
      if (isa<TupleExpr>(expr)) {
        return Action::SkipNode(expr);
      }

      // Coercion exprs have a rigid type, so there's no use in gathering info
      // about them.
      if (auto *coercion = dyn_cast<CoerceExpr>(expr)) {
        // Let's not collect information about types initialized by
        // coercions just like we don't for regular initializer calls,
        // because that might lead to overly eager type variable merging.
        if (!coercion->isLiteralInit())
          LTI.collectedTypes.insert(CS.getType(expr).getPointer());
        return Action::SkipNode(expr);
      }

      // Don't walk into subscript expressions - to do so would risk factoring
      // the index expression into edge contraction. (We don't want to do this
      // if the index expression is a literal type that differs from the return
      // type of the subscript operation.)
      if (isa<SubscriptExpr>(expr) || isa<DynamicLookupExpr>(expr)) {
        return Action::SkipNode(expr);
      }
      
      // Don't walk into unresolved member expressions - we avoid merging type
      // variables inside UnresolvedMemberExpr and those outside, since they
      // should be allowed to behave independently in CS.
      if (isa<UnresolvedMemberExpr>(expr)) {
        return Action::SkipNode(expr);
      }

      return Action::Continue(expr);
    }
    
    /// Ignore statements.
    PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
      return Action::SkipNode(stmt);
    }
    
    /// Ignore declarations.
    PreWalkAction walkToDeclPre(Decl *decl) override {
      return Action::SkipNode();
    }

    /// Ignore patterns.
    PreWalkResult<Pattern *> walkToPatternPre(Pattern *pat) override {
      return Action::SkipNode(pat);
    }

    /// Ignore types.
    PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
      return Action::SkipNode();
    }
  };
  
  /// For a given expression, given information that is global to the
  /// expression, attempt to derive a favored type for it.
  void computeFavoredTypeForExpr(Expr *expr, ConstraintSystem &CS) {
    LinkedTypeInfo lti;

    expr->walk(LinkedExprAnalyzer(lti, CS));

    // Check whether we can proceed with favoring.
    if (llvm::any_of(lti.binaryExprs, [](const BinaryExpr *op) {
          auto *ODRE = dyn_cast<OverloadedDeclRefExpr>(op->getFn());
          if (!ODRE)
            return false;

          // Attempting to favor based on operand types is wrong for
          // nil-coalescing operator.
          auto identifier = ODRE->getDecls().front()->getBaseIdentifier();
          return identifier.isNilCoalescingOperator();
        })) {
      return;
    }

    if (lti.collectedTypes.size() == 1) {
      // TODO: Compute the BCT.

      // It's only useful to favor the type instead of
      // binding it directly to arguments/result types,
      // which means in case it has been miscalculated
      // solver can still make progress.
      auto favoredTy = (*lti.collectedTypes.begin())->getWithoutSpecifierType();
      CS.setFavoredType(expr, favoredTy.getPointer());

      // If we have a chain of identical binop expressions with homogeneous
      // argument types, we can directly simplify the associated constraint
      // graph.
      auto simplifyBinOpExprTyVars = [&]() {
        // Don't attempt to do linking if there are
        // literals intermingled with other inferred types.
        if (lti.hasLiteral)
          return;

        for (auto binExp1 : lti.binaryExprs) {
          for (auto binExp2 : lti.binaryExprs) {
            if (binExp1 == binExp2)
              continue;

            auto fnTy1 = CS.getType(binExp1)->getAs<TypeVariableType>();
            auto fnTy2 = CS.getType(binExp2)->getAs<TypeVariableType>();

            if (!(fnTy1 && fnTy2))
              return;

            auto ODR1 = dyn_cast<OverloadedDeclRefExpr>(binExp1->getFn());
            auto ODR2 = dyn_cast<OverloadedDeclRefExpr>(binExp2->getFn());

            if (!(ODR1 && ODR2))
              return;

            // TODO: We currently limit this optimization to known arithmetic
            // operators, but we should be able to broaden this out to
            // logical operators as well.
            if (!isArithmeticOperatorDecl(ODR1->getDecls()[0]))
              return;

            if (ODR1->getDecls()[0]->getBaseName() !=
                ODR2->getDecls()[0]->getBaseName())
              return;

            // All things equal, we can merge the tyvars for the function
            // types.
            auto rep1 = CS.getRepresentative(fnTy1);
            auto rep2 = CS.getRepresentative(fnTy2);

            if (rep1 != rep2) {
              CS.mergeEquivalenceClasses(rep1, rep2,
                                         /*updateWorkList*/ false);
            }

            auto odTy1 = CS.getType(ODR1)->getAs<TypeVariableType>();
            auto odTy2 = CS.getType(ODR2)->getAs<TypeVariableType>();

            if (odTy1 && odTy2) {
              auto odRep1 = CS.getRepresentative(odTy1);
              auto odRep2 = CS.getRepresentative(odTy2);

              // Since we'll be choosing the same overload, we can merge
              // the overload tyvar as well.
              if (odRep1 != odRep2)
                CS.mergeEquivalenceClasses(odRep1, odRep2,
                                           /*updateWorkList*/ false);
            }
          }
        }
      };

      simplifyBinOpExprTyVars();
    }
  }

  /// Determine whether the given parameter type and argument should be
  /// "favored" because they match exactly.
  bool isFavoredParamAndArg(ConstraintSystem &CS, Type paramTy, Type argTy,
                            Type otherArgTy = Type()) {
    // Determine the argument type.
    argTy = argTy->getWithoutSpecifierType();

    // Do the types match exactly?
    if (paramTy->isEqual(argTy))
      return true;

    // Don't favor narrowing conversions.
    if (argTy->isDouble() && paramTy->isCGFloat())
      return false;

    llvm::SmallSetVector<ProtocolDecl *, 2> literalProtos;
    if (auto argTypeVar = argTy->getAs<TypeVariableType>()) {
      auto constraints = CS.getConstraintGraph().gatherConstraints(
          argTypeVar, ConstraintGraph::GatheringKind::EquivalenceClass,
          [](Constraint *constraint) {
            return constraint->getKind() == ConstraintKind::LiteralConformsTo;
          });

      for (auto constraint : constraints) {
        literalProtos.insert(constraint->getProtocol());
      }
    }

    // Dig out the second argument type.
    if (otherArgTy)
      otherArgTy = otherArgTy->getWithoutSpecifierType();

    for (auto literalProto : literalProtos) {
      // If there is another, concrete argument, check whether it's type
      // conforms to the literal protocol and test against it directly.
      // This helps to avoid 'widening' the favored type to the default type for
      // the literal.
      if (otherArgTy && otherArgTy->getAnyNominal()) {
        if (otherArgTy->isEqual(paramTy) &&
            CS.lookupConformance(otherArgTy, literalProto)) {
          return true;
        }
      } else if (Type defaultType =
                     TypeChecker::getDefaultType(literalProto, CS.DC)) {
        // If there is a default type for the literal protocol, check whether
        // it is the same as the parameter type.
        // Check whether there is a default type to compare against.
        if (paramTy->isEqual(defaultType) ||
            (defaultType->isDouble() && paramTy->isCGFloat()))
          return true;
      }
    }

    return false;
  }

  /// Favor certain overloads in a call based on some basic analysis
  /// of the overload set and call arguments.
  ///
  /// \param expr The application.
  /// \param isFavored Determine whether the given overload is favored, passing
  /// it the "effective" overload type when it's being called.
  /// \param mustConsider If provided, a function to detect the presence of
  /// overloads which inhibit any overload from being favored.
  void favorCallOverloads(ApplyExpr *expr,
                          ConstraintSystem &CS,
                          llvm::function_ref<bool(ValueDecl *, Type)> isFavored,
                          std::function<bool(ValueDecl *)>
                              mustConsider = nullptr) {
    // Find the type variable associated with the function, if any.
    auto tyvarType = CS.getType(expr->getFn())->getAs<TypeVariableType>();
    if (!tyvarType || CS.getFixedType(tyvarType))
      return;
    
    // This type variable is only currently associated with the function
    // being applied, and the only constraint attached to it should
    // be the disjunction constraint for the overload group.
    auto disjunction = CS.getUnboundBindOverloadDisjunction(tyvarType);
    if (!disjunction)
      return;
    
    // Find the favored constraints and mark them.
    SmallVector<Constraint *, 4> newlyFavoredConstraints;
    unsigned numFavoredConstraints = 0;
    Constraint *firstFavored = nullptr;
    for (auto constraint : disjunction->getNestedConstraints()) {
      auto *decl = constraint->getOverloadChoice().getDeclOrNull();
      if (!decl)
        continue;

      if (mustConsider && mustConsider(decl)) {
        // Roll back any constraints we favored.
        for (auto favored : newlyFavoredConstraints)
          favored->setFavored(false);

        return;
      }

      Type overloadType = CS.getEffectiveOverloadType(
          constraint->getLocator(), constraint->getOverloadChoice(),
          /*allowMembers=*/true, CS.DC);
      if (!overloadType)
        continue;

      if (!CS.isDeclUnavailable(decl, constraint->getLocator()) &&
          !decl->getAttrs().hasAttribute<DisfavoredOverloadAttr>() &&
          isFavored(decl, overloadType)) {
        // If we might need to roll back the favored constraints, keep
        // track of those we are favoring.
        if (mustConsider && !constraint->isFavored())
          newlyFavoredConstraints.push_back(constraint);

        constraint->setFavored();
        ++numFavoredConstraints;
        if (!firstFavored)
          firstFavored = constraint;
      }
    }

    // If there was one favored constraint, set the favored type based on its
    // result type.
    if (numFavoredConstraints == 1) {
      auto overloadChoice = firstFavored->getOverloadChoice();
      auto overloadType = CS.getEffectiveOverloadType(
          firstFavored->getLocator(), overloadChoice, /*allowMembers=*/true,
          CS.DC);
      auto resultType = overloadType->castTo<AnyFunctionType>()->getResult();
      if (!resultType->hasTypeParameter())
        CS.setFavoredType(expr, resultType.getPointer());
    }
  }
  
  /// Return a pair, containing the total parameter count of a function, coupled
  /// with the number of non-default parameters.
  std::pair<size_t, size_t> getParamCount(ValueDecl *VD) {
    auto fTy = VD->getInterfaceType()->castTo<AnyFunctionType>();
    
    size_t nOperands = fTy->getParams().size();
    size_t nNoDefault = 0;
    
    if (auto AFD = dyn_cast<AbstractFunctionDecl>(VD)) {
      assert(!AFD->hasImplicitSelfDecl());
      for (auto param : *AFD->getParameters()) {
        if (!param->isDefaultArgument())
          ++nNoDefault;
      }
    } else {
      nNoDefault = nOperands;
    }
    
    return { nOperands, nNoDefault };
  }

  bool hasContextuallyFavorableResultType(AnyFunctionType *choice,
                                          Type contextualTy) {
    // No restrictions of what result could be.
    if (!contextualTy)
      return true;

    auto resultTy = choice->getResult();
    // Result type of the call matches expected contextual type.
    return contextualTy->isEqual(resultTy);
  }

  /// Favor unary operator constraints where we have exact matches
  /// for the operand and contextual type.
  void favorMatchingUnaryOperators(ApplyExpr *expr,
                                   ConstraintSystem &CS) {
    auto *unaryArg = expr->getArgs()->getUnaryExpr();
    assert(unaryArg);

    // Determine whether the given declaration is favored.
    auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
      auto fnTy = type->getAs<AnyFunctionType>();
      if (!fnTy)
        return false;

      auto params = fnTy->getParams();
      if (params.size() != 1)
        return false;

      auto paramTy = params[0].getPlainType();
      auto argTy = CS.getType(unaryArg);

      // There are no CGFloat overloads on some of the unary operators, so
      // in order to preserve current behavior, let's not favor overloads
      // which would result in conversion from CGFloat to Double; otherwise
      // it would lead to ambiguities.
      if (argTy->isCGFloat() && paramTy->isDouble())
        return false;

      return isFavoredParamAndArg(CS, paramTy, argTy) &&
             hasContextuallyFavorableResultType(
                 fnTy,
                 CS.getContextualType(expr, /*forConstraint=*/false));
    };

    favorCallOverloads(expr, CS, isFavoredDecl);
  }
  
  void favorMatchingOverloadExprs(ApplyExpr *expr,
                                  ConstraintSystem &CS) {
    // Find the argument type.
    size_t nArgs = expr->getArgs()->size();
    auto fnExpr = expr->getFn();

    auto mustConsiderVariadicGenericOverloads = [&](ValueDecl *overload) {
      if (overload->getAttrs().hasAttribute<DisfavoredOverloadAttr>())
        return false;

      auto genericContext = overload->getAsGenericContext();
      if (!genericContext)
        return false;

      auto *GPL = genericContext->getGenericParams();
      if (!GPL)
        return false;

      return llvm::any_of(GPL->getParams(),
                          [&](const GenericTypeParamDecl *GP) {
                            return GP->isParameterPack();
                          });
    };

    // Check to ensure that we have an OverloadedDeclRef, and that we're not
    // favoring multiple overload constraints. (Otherwise, in this case
    // favoring is useless.
    if (auto ODR = dyn_cast<OverloadedDeclRefExpr>(fnExpr)) {
      bool haveMultipleApplicableOverloads = false;
      
      for (auto VD : ODR->getDecls()) {
        if (VD->getInterfaceType()->is<AnyFunctionType>()) {
          auto nParams = getParamCount(VD);
          
          if (nArgs == nParams.first) {
            if (haveMultipleApplicableOverloads) {
              return;
            } else {
              haveMultipleApplicableOverloads = true;
            }
          }
        }
      }
      
      // Determine whether the given declaration is favored.
      auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
        // We want to consider all options for calls that might contain the code
        // completion location, as missing arguments after the completion
        // location are valid (since it might be that they just haven't been
        // written yet).
        if (CS.isForCodeCompletion())
          return false;

        if (!type->is<AnyFunctionType>())
          return false;

        auto paramCount = getParamCount(value);
        
        return nArgs == paramCount.first ||
               nArgs == paramCount.second;
      };

      favorCallOverloads(expr, CS, isFavoredDecl,
                         mustConsiderVariadicGenericOverloads);
    }

    // We only currently perform favoring for unary args.
    auto *unaryArg = expr->getArgs()->getUnlabeledUnaryExpr();
    if (!unaryArg)
      return;

    if (auto favoredTy = CS.getFavoredType(unaryArg)) {
      // Determine whether the given declaration is favored.
      auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
        auto fnTy = type->getAs<AnyFunctionType>();
        if (!fnTy || fnTy->getParams().size() != 1)
          return false;

        return favoredTy->isEqual(fnTy->getParams()[0].getPlainType());
      };

      // This is a hack to ensure we always consider the protocol requirement
      // itself when calling something that has a default implementation in an
      // extension. Otherwise, the extension method might be favored if we're
      // inside an extension context, since any archetypes in the parameter
      // list could match exactly.
      auto mustConsider = [&](ValueDecl *value) -> bool {
        return isa<ProtocolDecl>(value->getDeclContext()) ||
               mustConsiderVariadicGenericOverloads(value);
      };

      favorCallOverloads(expr, CS, isFavoredDecl, mustConsider);
    }
  }
  
  /// Favor binary operator constraints where we have exact matches
  /// for the operands and contextual type.
  void favorMatchingBinaryOperators(ApplyExpr *expr, ConstraintSystem &CS) {
    // If we're generating constraints for a binary operator application,
    // there are two special situations to consider:
    //  1. If the type checker has any newly created functions with the
    //     operator's name. If it does, the overloads were created after the
    //     associated overloaded id expression was created, and we'll need to
    //     add a new disjunction constraint for the new set of overloads.
    //  2. If any component argument expressions (nested or otherwise) are
    //     literals, we can favor operator overloads whose argument types are
    //     identical to the literal type, or whose return types are identical
    //     to any contextual type associated with the application expression.
    
    // Find the argument types.
    auto *args = expr->getArgs();
    auto *lhs = args->getExpr(0);
    auto *rhs = args->getExpr(1);

    auto firstArgTy = CS.getType(lhs)->getWithoutParens();
    auto secondArgTy = CS.getType(rhs)->getWithoutParens();

    auto isOptionalWithMatchingObjectType = [](Type optional,
                                               Type object) -> bool {
      if (auto objTy = optional->getRValueType()->getOptionalObjectType())
        return objTy->getRValueType()->isEqual(object->getRValueType());

      return false;
    };

    auto isPotentialForcingOpportunity = [&](Type first, Type second) -> bool {
      return isOptionalWithMatchingObjectType(first, second) ||
             isOptionalWithMatchingObjectType(second, first);
    };

    // Determine whether the given declaration is favored.
    auto isFavoredDecl = [&](ValueDecl *value, Type type) -> bool {
      auto fnTy = type->getAs<AnyFunctionType>();
      if (!fnTy)
        return false;

      auto firstFavoredTy = CS.getFavoredType(lhs);
      auto secondFavoredTy = CS.getFavoredType(rhs);
      
      auto favoredExprTy = CS.getFavoredType(expr);
      
      if (isArithmeticOperatorDecl(value)) {
        // If the parent has been favored on the way down, propagate that
        // information to its children.
        // TODO: This is only valid for arithmetic expressions.
        if (!firstFavoredTy) {
          CS.setFavoredType(lhs, favoredExprTy);
          firstFavoredTy = favoredExprTy;
        }
        
        if (!secondFavoredTy) {
          CS.setFavoredType(rhs, favoredExprTy);
          secondFavoredTy = favoredExprTy;
        }
      }
      
      auto params = fnTy->getParams();
      if (params.size() != 2)
        return false;

      auto firstParamTy = params[0].getOldType();
      auto secondParamTy = params[1].getOldType();

      auto contextualTy = CS.getContextualType(expr, /*forConstraint=*/false);

      // Avoid favoring overloads that would require narrowing conversion
      // to match the arguments.
      {
        if (firstArgTy->isDouble() && firstParamTy->isCGFloat())
          return false;

        if (secondArgTy->isDouble() && secondParamTy->isCGFloat())
          return false;
      }

      return (isFavoredParamAndArg(CS, firstParamTy, firstArgTy, secondArgTy) ||
              isFavoredParamAndArg(CS, secondParamTy, secondArgTy,
                                   firstArgTy)) &&
             firstParamTy->isEqual(secondParamTy) &&
             !isPotentialForcingOpportunity(firstArgTy, secondArgTy) &&
             hasContextuallyFavorableResultType(fnTy, contextualTy);
    };
    
    favorCallOverloads(expr, CS, isFavoredDecl);
  }

  /// If \p expr is a call and that call contains the code completion token,
  /// add the expressions of all arguments after the code completion token to
  /// \p ignoredArguments.
  /// Otherwise, returns an empty vector.
  /// Assumes that we are solving for code completion.
  void getArgumentsAfterCodeCompletionToken(
      Expr *expr, ConstraintSystem &CS,
      SmallVectorImpl<Expr *> &ignoredArguments) {
    assert(CS.isForCodeCompletion());

    /// Don't ignore the rhs argument if the code completion token is the lhs of
    /// an operator call. Main use case is the implicit `<complete> ~= $match`
    /// call created for pattern matching, in which we need to type-check
    /// `$match` to get a contextual type for `<complete>`
    if (isa<BinaryExpr>(expr)) {
      return;
    }

    auto args = expr->getArgs();
    auto argInfo = getCompletionArgInfo(expr, CS);
    if (!args || !argInfo) {
      return;
    }

    for (auto argIndex : indices(*args)) {
      if (argInfo->isBefore(argIndex)) {
        ignoredArguments.push_back(args->get(argIndex).getExpr());
      }
    }
  }

  class ConstraintOptimizer : public ASTWalker {
    ConstraintSystem &CS;
    
  public:
    
    ConstraintOptimizer(ConstraintSystem &cs) :
      CS(cs) {}

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

    PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
      if (CS.isArgumentIgnoredForCodeCompletion(expr)) {
        return Action::SkipNode(expr);
      }
      
      if (auto applyExpr = dyn_cast<ApplyExpr>(expr)) {
        if (isa<PrefixUnaryExpr>(applyExpr) ||
            isa<PostfixUnaryExpr>(applyExpr)) {
          favorMatchingUnaryOperators(applyExpr, CS);
        } else if (isa<BinaryExpr>(applyExpr)) {
          favorMatchingBinaryOperators(applyExpr, CS);
        } else {
          favorMatchingOverloadExprs(applyExpr, CS);
        }
      }
      
      // If the paren expr has a favored type, and the subExpr doesn't,
      // propagate downwards. Otherwise, propagate upwards.
      if (auto parenExpr = dyn_cast<ParenExpr>(expr)) {
        if (!CS.getFavoredType(parenExpr->getSubExpr())) {
          CS.setFavoredType(parenExpr->getSubExpr(),
                            CS.getFavoredType(parenExpr));
        } else if (!CS.getFavoredType(parenExpr)) {
          CS.setFavoredType(parenExpr,
                            CS.getFavoredType(parenExpr->getSubExpr()));
        }
      }

      if (isa<ClosureExpr>(expr))
        return Action::SkipNode(expr);

      return Action::Continue(expr);
    }
    /// Ignore statements.
    PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
      return Action::SkipNode(stmt);
    }
    
    /// Ignore declarations.
    PreWalkAction walkToDeclPre(Decl *decl) override {
      return Action::SkipNode();
    }
  };
} // end anonymous namespace

void TypeVarRefCollector::inferTypeVars(Decl *D) {
  // We're only interested in VarDecls.
  if (!isa_and_nonnull<VarDecl>(D))
    return;

  auto ty = CS.getTypeIfAvailable(D);
  if (!ty)
    return;

  SmallPtrSet<TypeVariableType *, 4> typeVars;
  ty->getTypeVariables(typeVars);
  TypeVars.insert(typeVars.begin(), typeVars.end());
}

void TypeVarRefCollector::inferTypeVars(PackExpansionExpr *E) {
  auto expansionType = CS.getType(E)->castTo<PackExpansionType>();

  SmallPtrSet<TypeVariableType *, 4> referencedVars;
  expansionType->getTypeVariables(referencedVars);
  TypeVars.insert(referencedVars.begin(), referencedVars.end());
}

ASTWalker::PreWalkResult<Expr *>
TypeVarRefCollector::walkToExprPre(Expr *expr) {
  if (isa<ClosureExpr>(expr))
    DCDepth += 1;

  if (auto *DRE = dyn_cast<DeclRefExpr>(expr))
    inferTypeVars(DRE->getDecl());

  // FIXME: We can see UnresolvedDeclRefExprs here because we don't walk into
  // patterns when running preCheckExpression, since we don't resolve patterns
  // until CSGen. We ought to consider moving pattern resolution into
  // pre-checking, which would allow us to pre-check patterns normally.
  if (auto *declRef = dyn_cast<UnresolvedDeclRefExpr>(expr)) {
    auto name = declRef->getName();
    auto loc = declRef->getLoc();
    if (name.isSimpleName() && loc.isValid()) {
      auto *SF = CS.DC->getParentSourceFile();
      auto *D = ASTScope::lookupSingleLocalDecl(SF, name.getFullName(), loc);
      inferTypeVars(D);
    }
  }

  if (auto *packElement = getAsExpr<PackElementExpr>(expr)) {
    // If environment hasn't been established yet, it means that pack expansion
    // appears inside of this closure.
    if (auto *outerEnvironment = CS.getPackEnvironment(packElement))
      inferTypeVars(outerEnvironment);
  }

  return Action::Continue(expr);
}

ASTWalker::PostWalkResult<Expr *>
TypeVarRefCollector::walkToExprPost(Expr *expr) {
  if (isa<ClosureExpr>(expr))
    DCDepth -= 1;

  return Action::Continue(expr);
}

ASTWalker::PreWalkResult<Stmt *>
TypeVarRefCollector::walkToStmtPre(Stmt *stmt) {
  // If we have a return without any intermediate DeclContexts in a ClosureExpr,
  // we need to include any type variables in the closure's result type, since
  // the conjunction will generate constraints using that type. We don't need to
  // connect to returns in e.g nested closures since we'll connect those when we
  // generate constraints for those closures. We also don't need to bother if
  // we're generating constraints for the closure itself, since we'll connect
  // the conjunction to the closure type variable itself.
  if (auto *CE = dyn_cast<ClosureExpr>(DC)) {
    if (isa<ReturnStmt>(stmt) && DCDepth == 0 &&
        !Locator->directlyAt<ClosureExpr>()) {
      SmallPtrSet<TypeVariableType *, 4> typeVars;
      CS.getClosureType(CE)->getResult()->getTypeVariables(typeVars);
      TypeVars.insert(typeVars.begin(), typeVars.end());
    }
  }
  return Action::Continue(stmt);
}

namespace {
  class ConstraintGenerator : public ExprVisitor<ConstraintGenerator, Type> {
    ConstraintSystem &CS;
    DeclContext *CurDC;
    ConstraintSystemPhase CurrPhase;

    /// A map from each UnresolvedMemberExpr to the respective (implicit) base
    /// found during our walk.
    llvm::MapVector<UnresolvedMemberExpr *, Type> UnresolvedBaseTypes;

    /// A stack of pack expansions that can open pack elements.
    llvm::SmallVector<PackExpansionExpr *, 1> OuterExpansions;

    /// Returns false and emits the specified diagnostic if the member reference
    /// base is a nil literal. Returns true otherwise.
    bool isValidBaseOfMemberRef(Expr *base, Diag<> diagnostic) {
      if (auto nilLiteral = dyn_cast<NilLiteralExpr>(base)) {
        CS.getASTContext().Diags.diagnose(nilLiteral->getLoc(), diagnostic);
        return false;
      }
      return true;
    }

    /// Retrieves a matching set of function params for an argument list.
    void getMatchingParams(ArgumentList *argList,
                           SmallVectorImpl<AnyFunctionType::Param> &result) {
      for (auto arg : *argList) {
        ParameterTypeFlags flags;
        auto ty = CS.getType(arg.getExpr());
        if (arg.isInOut()) {
          ty = ty->getInOutObjectType();
          flags = flags.withInOut(true);
        }
        if (arg.isConst()) {
          flags = flags.withCompileTimeConst(true);
        }
        result.emplace_back(ty, arg.getLabel(), flags);
      }
    }

    /// If the provided type is a tuple, decomposes it into a matching set of
    /// function params. Otherwise produces a single parameter of the type,
    /// stripping a ParenType if needed.
    void decomposeTuple(Type ty,
                        SmallVectorImpl<AnyFunctionType::Param> &result) {
      switch (ty->getKind()) {
      case TypeKind::Tuple: {
        auto tupleTy = cast<TupleType>(ty.getPointer());
        for (auto &elt : tupleTy->getElements())
          result.emplace_back(elt.getType(), elt.getName());
        return;
      }
      case TypeKind::Paren: {
        auto pty = cast<ParenType>(ty.getPointer());
        result.emplace_back(pty->getUnderlyingType(), Identifier());
        return;
      }
      default:
        result.emplace_back(ty, Identifier());
      }
    }

    /// Add constraints for a reference to a named member of the given
    /// base type, and return the type of such a reference.
    Type addMemberRefConstraints(Expr *expr, Expr *base, DeclNameRef name,
                                 FunctionRefKind functionRefKind,
                                 ArrayRef<ValueDecl *> outerAlternatives) {
      // The base must have a member of the given name, such that accessing
      // that member through the base returns a value convertible to the type
      // of this expression.
      auto baseTy = CS.getType(base);
      if (isa<ErrorExpr>(base)) {
        return CS.createTypeVariable(
            CS.getConstraintLocator(expr, ConstraintLocator::Member),
            TVO_CanBindToHole);
      }
      unsigned options = (TVO_CanBindToLValue |
                          TVO_CanBindToNoEscape);
      if (!OuterExpansions.empty())
        options |= TVO_CanBindToPack;

      auto tv = CS.createTypeVariable(
                  CS.getConstraintLocator(expr, ConstraintLocator::Member),
                  options);
      SmallVector<OverloadChoice, 4> outerChoices;
      for (auto decl : outerAlternatives) {
        outerChoices.push_back(OverloadChoice(Type(), decl, functionRefKind));
      }
      CS.addValueMemberConstraint(
          baseTy, name, tv, CurDC, functionRefKind, outerChoices,
          CS.getConstraintLocator(expr, ConstraintLocator::Member));
      return tv;
    }

    /// Add constraints for a reference to a specific member of the given
    /// base type, and return the type of such a reference.
    Type addMemberRefConstraints(Expr *expr, Expr *base, ValueDecl *decl,
                                 FunctionRefKind functionRefKind) {
      // If we're referring to an invalid declaration, fail.
      if (!decl)
        return nullptr;
      
      if (decl->isInvalid())
        return nullptr;

      auto memberLocator =
        CS.getConstraintLocator(expr, ConstraintLocator::Member);
      auto tv = CS.createTypeVariable(memberLocator,
                                      TVO_CanBindToLValue | TVO_CanBindToNoEscape);

      OverloadChoice choice =
          OverloadChoice(CS.getType(base), decl, functionRefKind);

      auto locator = CS.getConstraintLocator(expr, ConstraintLocator::Member);
      CS.addBindOverloadConstraint(tv, choice, locator, CurDC);
      return tv;
    }

    /// Add constraints for a subscript operation.
    Type addSubscriptConstraints(
        Expr *anchor, Type baseTy, ValueDecl *declOrNull, ArgumentList *argList,
        ConstraintLocator *locator = nullptr,
        SmallVectorImpl<TypeVariableType *> *addedTypeVars = nullptr) {
      // Locators used in this expression.
      if (locator == nullptr)
        locator = CS.getConstraintLocator(anchor);

      auto fnLocator =
        CS.getConstraintLocator(locator,
                                ConstraintLocator::ApplyFunction);
      auto memberLocator =
        CS.getConstraintLocator(locator,
                                ConstraintLocator::SubscriptMember);
      auto resultLocator =
        CS.getConstraintLocator(locator,
                                ConstraintLocator::FunctionResult);

      CS.associateArgumentList(memberLocator, argList);

      Type outputTy;

      // For an integer subscript expression on an array slice type, instead of
      // introducing a new type variable we can easily obtain the element type.
      if (isa<SubscriptExpr>(anchor)) {

        auto isLValueBase = false;
        auto baseObjTy = baseTy;
        if (baseObjTy->is<LValueType>()) {
          isLValueBase = true;
          baseObjTy = baseObjTy->getWithoutSpecifierType();
        }

        if (baseObjTy->isArrayType()) {

          if (auto arraySliceTy = 
                dyn_cast<ArraySliceType>(baseObjTy.getPointer())) {
            baseObjTy = arraySliceTy->getDesugaredType();
          }

          if (argList->isUnlabeledUnary() &&
              isa<IntegerLiteralExpr>(argList->getExpr(0))) {

            outputTy = baseObjTy->getAs<BoundGenericType>()->getGenericArgs()[0];
            
            if (isLValueBase)
              outputTy = LValueType::get(outputTy);
          }
        } else if (auto dictTy = CS.isDictionaryType(baseObjTy)) {
          auto keyTy = dictTy->first;
          auto valueTy = dictTy->second;

          if (argList->isUnlabeledUnary()) {
            auto argTy = CS.getType(argList->getExpr(0));
            if (isFavoredParamAndArg(CS, keyTy, argTy)) {
              outputTy = OptionalType::get(valueTy);
              if (isLValueBase)
                outputTy = LValueType::get(outputTy);
            }
          }
        }
      }
      
      if (outputTy.isNull()) {
        outputTy = CS.createTypeVariable(resultLocator,
                                         TVO_CanBindToLValue | TVO_CanBindToNoEscape);
        if (addedTypeVars)
          addedTypeVars->push_back(outputTy->castTo<TypeVariableType>());
      }

      // FIXME: This can only happen when diagnostics successfully type-checked
      // sub-expression of the subscript and mutated AST, but under normal
      // circumstances subscript should never have InOutExpr as a direct child
      // until type checking is complete and expression is re-written.
      // Proper fix for such situation requires preventing diagnostics from
      // re-writing AST after successful type checking of the sub-expressions.
      if (auto inoutTy = baseTy->getAs<InOutType>()) {
        baseTy = LValueType::get(inoutTy->getObjectType());
      }

      // Add the member constraint for a subscript declaration.
      // FIXME: weak name!
      auto memberTy = CS.createTypeVariable(
          memberLocator, TVO_CanBindToLValue | TVO_CanBindToNoEscape);
      if (addedTypeVars)
        addedTypeVars->push_back(memberTy);

      // FIXME: synthesizeMaterializeForSet() wants to statically dispatch to
      // a known subscript here. This might be cleaner if we split off a new
      // UnresolvedSubscriptExpr from SubscriptExpr.
      if (auto decl = declOrNull) {
        OverloadChoice choice =
            OverloadChoice(baseTy, decl, FunctionRefKind::DoubleApply);
        CS.addBindOverloadConstraint(memberTy, choice, memberLocator,
                                     CurDC);
      } else {
        CS.addValueMemberConstraint(baseTy, DeclNameRef::createSubscript(),
                                    memberTy, CurDC,
                                    FunctionRefKind::DoubleApply,
                                    /*outerAlternatives=*/{},
                                    memberLocator);
      }

      SmallVector<AnyFunctionType::Param, 8> params;
      getMatchingParams(argList, params);

      // Add the constraint that the index expression's type be convertible
      // to the input type of the subscript operator.
      CS.addConstraint(ConstraintKind::ApplicableFunction,
                       FunctionType::get(params, outputTy),
                       memberTy,
                       fnLocator);

      Type fixedOutputType =
          CS.getFixedTypeRecursive(outputTy, /*wantRValue=*/false);
      if (!fixedOutputType->isTypeVariableOrMember()) {
        CS.setFavoredType(anchor, fixedOutputType.getPointer());
        outputTy = fixedOutputType;
      }

      return outputTy;
    }

    Type openPackElement(Type packType, ConstraintLocator *locator,
                         PackExpansionExpr *packElementEnvironment) {
      if (!packElementEnvironment) {
        return CS.createTypeVariable(locator,
                                     TVO_CanBindToHole | TVO_CanBindToNoEscape);
      }

      // The type of a PackElementExpr is the opened pack element archetype
      // of the pack reference.
      OpenPackElementType openPackElement(CS, locator, packElementEnvironment);
      return openPackElement(packType, /*packRepr*/ nullptr);
    }

  public:
    ConstraintGenerator(ConstraintSystem &CS, DeclContext *DC)
        : CS(CS), CurDC(DC ? DC : CS.DC), CurrPhase(CS.getPhase()) {
      // Although constraint system is initialized in `constraint
      // generation` phase, we have to set it here manually because e.g.
      // result builders could generate constraints for its body
      // in the middle of the solving.
      CS.setPhase(ConstraintSystemPhase::ConstraintGeneration);

      // Pick up the saved stack of pack expansions so we can continue
      // to handle pack element references inside the closure body.
      if (auto *ACE = dyn_cast<AbstractClosureExpr>(CurDC)) {
        OuterExpansions = CS.getCapturedExpansions(ACE);
      }
    }

    virtual ~ConstraintGenerator() {
      CS.setPhase(CurrPhase);
    }

    ConstraintSystem &getConstraintSystem() const { return CS; }

    void pushPackExpansionExpr(PackExpansionExpr *expr) {
      OuterExpansions.push_back(expr);

      SmallVector<ASTNode, 2> expandedPacks;
      collectExpandedPacks(expr, expandedPacks);
      for (auto pack : expandedPacks) {
        if (auto *elementExpr = getAsExpr<PackElementExpr>(pack)) {
          CS.addPackEnvironment(elementExpr, expr);
        }
      }

      auto *patternLoc = CS.getConstraintLocator(
          expr, ConstraintLocator::PackExpansionPattern);
      auto patternType = CS.createTypeVariable(
          patternLoc,
          TVO_CanBindToPack | TVO_CanBindToNoEscape | TVO_CanBindToHole);
      auto *shapeLoc =
          CS.getConstraintLocator(expr, ConstraintLocator::PackShape);
      auto *shapeTypeVar = CS.createTypeVariable(
          shapeLoc, TVO_CanBindToPack | TVO_CanBindToHole);

      auto expansionType = PackExpansionType::get(patternType, shapeTypeVar);
      CS.setType(expr, expansionType);
    }

    virtual Type visitErrorExpr(ErrorExpr *E) {
      CS.recordFix(
          IgnoreInvalidASTNode::create(CS, CS.getConstraintLocator(E)));

      return CS.createTypeVariable(CS.getConstraintLocator(E),
                                   TVO_CanBindToHole);
    }

    virtual Type visitCodeCompletionExpr(CodeCompletionExpr *E) {
      CS.Options |= ConstraintSystemFlags::SuppressDiagnostics;
      auto locator = CS.getConstraintLocator(E);
      return CS.createTypeVariable(locator, TVO_CanBindToLValue |
                                                TVO_CanBindToNoEscape |
                                                TVO_CanBindToHole);
    }

    Type visitNilLiteralExpr(NilLiteralExpr *expr) {
      auto literalTy = visitLiteralExpr(expr);
      // Allow `nil` to be a hole so we can diagnose it via a fix
      // if it turns out that there is no contextual information.
      if (auto *typeVar = literalTy->getAs<TypeVariableType>())
        CS.recordPotentialHole(typeVar);

      return literalTy;
    }

    Type visitFloatLiteralExpr(FloatLiteralExpr *expr) {
      auto &ctx = CS.getASTContext();
      // Get the _MaxBuiltinFloatType decl, or look for it if it's not cached.
      auto maxFloatTypeDecl = ctx.get_MaxBuiltinFloatTypeDecl();

      if (!maxFloatTypeDecl ||
          !maxFloatTypeDecl->getDeclaredInterfaceType()->is<BuiltinFloatType>()) {
        ctx.Diags.diagnose(expr->getLoc(), diag::no_MaxBuiltinFloatType_found);
        return nullptr;
      }

      return visitLiteralExpr(expr);
    }

    Type visitLiteralExpr(LiteralExpr *expr) {
      // If the expression has already been assigned a type; just use that type.
      if (expr->getType())
        return expr->getType();

      auto protocol = TypeChecker::getLiteralProtocol(CS.getASTContext(), expr);
      if (!protocol)
        return nullptr;

      auto tv = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                      TVO_PrefersSubtypeBinding |
                                      TVO_CanBindToNoEscape);
      CS.addConstraint(ConstraintKind::LiteralConformsTo, tv,
                       protocol->getDeclaredInterfaceType(),
                       CS.getConstraintLocator(expr));
      return tv;
    }

    Type
    visitInterpolatedStringLiteralExpr(InterpolatedStringLiteralExpr *expr) {
      // Dig out the ExpressibleByStringInterpolation protocol.
      auto &ctx = CS.getASTContext();
      auto interpolationProto = TypeChecker::getProtocol(
          ctx, expr->getLoc(),
          KnownProtocolKind::ExpressibleByStringInterpolation);
      if (!interpolationProto) {
        ctx.Diags.diagnose(expr->getStartLoc(),
                           diag::interpolation_missing_proto);
        return nullptr;
      }

      // The type of the expression must conform to the
      // ExpressibleByStringInterpolation protocol.
      auto locator = CS.getConstraintLocator(expr);
      auto tv = CS.createTypeVariable(locator,
                                      TVO_PrefersSubtypeBinding |
                                      TVO_CanBindToNoEscape);
      CS.addConstraint(ConstraintKind::LiteralConformsTo, tv,
                       interpolationProto->getDeclaredInterfaceType(),
                       locator);

      if (auto appendingExpr = expr->getAppendingExpr()) {
        auto associatedTypeDecl = interpolationProto->getAssociatedType(
          ctx.Id_StringInterpolation);
        if (associatedTypeDecl == nullptr) {
          ctx.Diags.diagnose(expr->getStartLoc(),
                             diag::interpolation_broken_proto);
          return nullptr;
        }

        auto interpolationTV =
            CS.createTypeVariable(locator, TVO_CanBindToNoEscape);
        auto interpolationType =
            DependentMemberType::get(tv, associatedTypeDecl);

        CS.addConstraint(ConstraintKind::Equal, interpolationTV,
                         interpolationType, locator);

        auto appendingExprType = CS.getType(appendingExpr);
        auto appendingLocator = CS.getConstraintLocator(appendingExpr);

        SmallVector<TypeVariableType *, 2> referencedVars;

        if (auto *tap = getAsExpr<TapExpr>(appendingExpr)) {
          // Collect all of the variable references that appear
          // in the tap body, otherwise tap expression is going
          // to get disconnected from the context.
          if (auto *body = tap->getBody()) {
            TypeVarRefCollector refCollector(
                CS, tap->getVar()->getDeclContext(), locator);

            body->walk(refCollector);

            auto vars = refCollector.getTypeVars();
            referencedVars.append(vars.begin(), vars.end());
          }
        }

        // Must be Conversion; if it's Equal, then in semi-rare cases, the
        // interpolation temporary variable cannot be @lvalue.
        CS.addUnsolvedConstraint(Constraint::create(
            CS, ConstraintKind::Conversion, appendingExprType, interpolationTV,
            appendingLocator, referencedVars));
      }

      return tv;
    }

    Type visitMagicIdentifierLiteralExpr(MagicIdentifierLiteralExpr *expr) {
#ifdef SWIFT_BUILD_SWIFT_SYNTAX
      auto &ctx = CS.getASTContext();
      if (ctx.LangOpts.hasFeature(Feature::BuiltinMacros)) {
        auto kind = MagicIdentifierLiteralExpr::getKindString(expr->getKind())
                        .drop_front();

        auto protocol =
            TypeChecker::getLiteralProtocol(CS.getASTContext(), expr);
        if (!protocol)
          return Type();

        auto macroIdent = ctx.getIdentifier(kind);
        auto macros =
            lookupMacros(Identifier(), macroIdent, FunctionRefKind::Unapplied,
                         MacroRole::Expression);
        if (!macros.empty()) {
          // Introduce an overload set for the macro reference.
          auto locator = CS.getConstraintLocator(expr);
          auto macroRefType = Type(CS.createTypeVariable(locator, 0));
          CS.addOverloadSet(macroRefType, macros, CurDC, locator);

          // FIXME: Can this be encoded in the macro definition somehow?
          CS.addConstraint(ConstraintKind::LiteralConformsTo, macroRefType,
                           protocol->getDeclaredInterfaceType(),
                           CS.getConstraintLocator(expr));

          return macroRefType;
        }
      }

      // Fall through to use old implementation.
#endif

      switch (expr->getKind()) {
      // Magic pointer identifiers are of type UnsafeMutableRawPointer.
#define MAGIC_POINTER_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \
      case MagicIdentifierLiteralExpr::NAME:
#include "swift/AST/MagicIdentifierKinds.def"
      {
        auto &ctx = CS.getASTContext();
        if (TypeChecker::requirePointerArgumentIntrinsics(ctx, expr->getLoc()))
          return nullptr;

        return ctx.getUnsafeRawPointerType();
      }

      default:
        // Others are actual literals and should be handled like any literal.
        return visitLiteralExpr(expr);
      }

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

    Type visitObjectLiteralExpr(ObjectLiteralExpr *expr) {
      auto *exprLoc = CS.getConstraintLocator(expr);
      CS.associateArgumentList(exprLoc, expr->getArgs());

      // If the expression has already been assigned a type; just use that type.
      if (expr->getType())
        return expr->getType();

      auto &ctx = CS.getASTContext();
      auto &de = ctx.Diags;
      auto protocol = TypeChecker::getLiteralProtocol(ctx, expr);
      if (!protocol) {
        de.diagnose(expr->getLoc(), diag::use_unknown_object_literal_protocol,
                    expr->getLiteralKindPlainName());
        return nullptr;
      }

      auto witnessType = CS.createTypeVariable(
          exprLoc, TVO_PrefersSubtypeBinding | TVO_CanBindToNoEscape |
                       TVO_CanBindToHole);

      CS.addConstraint(ConstraintKind::LiteralConformsTo, witnessType,
                       protocol->getDeclaredInterfaceType(), exprLoc);

      // The arguments are required to be argument-convertible to the
      // idealized parameter type of the initializer, which generally
      // simplifies the first label (e.g. "colorLiteralRed:") by stripping
      // all the redundant stuff about literals (leaving e.g. "red:").
      // Constraint application will quietly rewrite the type of 'args' to
      // use the right labels before forming the call to the initializer.
      auto constrName = TypeChecker::getObjectLiteralConstructorName(ctx, expr);
      assert(constrName);
      auto *constr = dyn_cast_or_null<ConstructorDecl>(
          protocol->getSingleRequirement(constrName));
      if (!constr) {
        de.diagnose(protocol, diag::object_literal_broken_proto);
        return nullptr;
      }

      auto *memberLoc =
          CS.getConstraintLocator(expr, ConstraintLocator::ConstructorMember);

      auto *fnLoc =
          CS.getConstraintLocator(expr, ConstraintLocator::ApplyFunction);

      auto *memberTypeLoc = CS.getConstraintLocator(
          fnLoc, LocatorPathElt::ConstructorMemberType());

      auto *memberType =
          CS.createTypeVariable(memberTypeLoc, TVO_CanBindToNoEscape);

      CS.addValueMemberConstraint(MetatypeType::get(witnessType, ctx),
                                  DeclNameRef(constrName), memberType, CurDC,
                                  FunctionRefKind::DoubleApply, {}, memberLoc);

      SmallVector<AnyFunctionType::Param, 8> params;
      getMatchingParams(expr->getArgs(), params);

      auto resultType = CS.createTypeVariable(
          CS.getConstraintLocator(expr, ConstraintLocator::FunctionResult),
          TVO_CanBindToNoEscape);

      CS.addConstraint(ConstraintKind::ApplicableFunction,
                       FunctionType::get(params, resultType), memberType,
                       fnLoc);

      if (constr->isFailable())
        return OptionalType::get(witnessType);

      return witnessType;
    }

    Type visitRegexLiteralExpr(RegexLiteralExpr *E) {
      auto &ctx = CS.getASTContext();
      auto *regexDecl = ctx.getRegexDecl();
      if (!regexDecl) {
        ctx.Diags.diagnose(E->getLoc(),
                           diag::string_processing_lib_missing,
                           ctx.Id_Regex.str());
        return Type();
      }
      SmallVector<TupleTypeElt, 4> matchElements;
      if (decodeRegexCaptureTypes(ctx,
                                  E->getSerializedCaptureStructure(),
                                  /*atomType*/ ctx.getSubstringType(),
                                  matchElements)) {
        ctx.Diags.diagnose(E->getLoc(),
                           diag::regex_capture_types_failed_to_decode);
        return Type();
      }
      assert(!matchElements.empty() && "Should have decoded at least an atom");
      if (matchElements.size() == 1)
        return BoundGenericStructType::get(
            regexDecl, Type(), matchElements.front().getType());
      // Form a tuple.
      auto matchType = TupleType::get(matchElements, ctx);
      return BoundGenericStructType::get(regexDecl, Type(), {matchType});
    }

    PackExpansionExpr *getParentPackExpansionExpr(Expr *E) const {
      auto *current = E;
      while (auto *parent = CS.getParentExpr(current)) {
        if (auto *expansion = dyn_cast<PackExpansionExpr>(parent)) {
          return expansion;
        }
        current = parent;
      }
      return nullptr;
    }

    Type visitDeclRefExpr(DeclRefExpr *E) {
      auto locator = CS.getConstraintLocator(E);

      auto invalidateReference = [&]() -> Type {
        auto *hole = CS.createTypeVariable(locator, TVO_CanBindToHole);
        (void)CS.recordFix(AllowRefToInvalidDecl::create(CS, locator));
        CS.setType(E, hole);
        return hole;
      };

      Type knownType;
      if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
        knownType = CS.getTypeIfAvailable(VD);
        if (!knownType)
          knownType = CS.getVarType(VD);

        if (knownType) {
          // An out-of-scope type variable(s) could appear the type of
          // a declaration only in diagnostic mode when invalid variable
          // declaration is recursively referenced inside of a multi-statement
          // closure located somewhere within its initializer e.g.:
          // `let x = [<call>] { ... print(x) }`. It happens because the
          // variable assumes the result type of its initializer unless
          // its specified explicitly.
          if (isa<ClosureExpr>(CurDC) && knownType->hasTypeVariable()) {
            if (knownType.findIf([&](Type type) {
                  auto *typeVar = type->getAs<TypeVariableType>();
                  if (!typeVar || CS.getFixedType(typeVar))
                    return false;

                  return !CS.isActiveTypeVariable(typeVar);
                }))
              return invalidateReference();
          }

          // If the known type has an error, bail out.
          if (knownType->hasError()) {
            return invalidateReference();
          }

          // value packs cannot be referenced without `each` immediately
          // preceding them.
          if (auto *expansionType = knownType->getAs<PackExpansionType>()) {
            if (auto *parentExpansionExpr = getParentPackExpansionExpr(E);
                parentExpansionExpr &&
                !isExpr<PackElementExpr>(CS.getParentExpr(E))) {
              auto packType = expansionType->getPatternType();
              (void)CS.recordFix(
                  IgnoreMissingEachKeyword::create(CS, packType, locator));
              auto eltType =
                  openPackElement(packType, locator, parentExpansionExpr);
              CS.setType(E, eltType);
              return eltType;
            }
          }

          if (!knownType->hasPlaceholder()) {
            // Set the favored type for this expression to the known type.
            CS.setFavoredType(E, knownType.getPointer());
          }
        }
      }

      // If declaration is invalid, let's turn it into a potential hole
      // and keep generating constraints.
      // For code completion, we still resolve the overload and replace error
      // types inside the function decl with placeholders
      // (in getTypeOfReference) so we can match non-error param types.
      if (!knownType && E->getDecl()->isInvalid() &&
          !CS.isForCodeCompletion()) {
        return invalidateReference();
      }

      unsigned options = (TVO_CanBindToLValue |
                          TVO_CanBindToNoEscape);
      if (!OuterExpansions.empty())
        options |= TVO_CanBindToPack;

      // Create an overload choice referencing this declaration and immediately
      // resolve it. This records the overload for use later.
      auto tv = CS.createTypeVariable(locator, options);

      OverloadChoice choice =
          OverloadChoice(Type(), E->getDecl(), E->getFunctionRefKind());
      CS.resolveOverload(locator, tv, choice, CurDC);
      return tv;
    }

    Type visitOtherConstructorDeclRefExpr(OtherConstructorDeclRefExpr *E) {
      return E->getType();
    }

    Type visitSuperRefExpr(SuperRefExpr *E) {
      if (E->getType())
        return E->getType();

      // Resolve the super type of 'self'.
      return getSuperType(E->getSelf(), E->getLoc(),
                          diag::super_not_in_class_method,
                          diag::super_with_no_base_class);
    }

    Type
    resolveTypeReferenceInExpression(TypeRepr *repr,
                                     TypeResolutionOptions options,
                                     const ConstraintLocatorBuilder &locator) {
      // Introduce type variables for unbound generics.
      const auto genericOpener = OpenUnboundGenericType(CS, locator);
      const auto placeholderHandler = HandlePlaceholderType(CS, locator);

      // Add a PackElementOf constraint for 'each T' type reprs.
      PackExpansionExpr *elementEnv = nullptr;
      if (!OuterExpansions.empty()) {
        options |= TypeResolutionFlags::AllowPackReferences;
        elementEnv = OuterExpansions.back();
      }
      const auto packElementOpener = OpenPackElementType(CS, locator, elementEnv);

      const auto result = TypeResolution::resolveContextualType(
          repr, CS.DC, options, genericOpener, placeholderHandler,
          packElementOpener);
      if (result->hasError()) {
        CS.recordFix(
            IgnoreInvalidASTNode::create(CS, CS.getConstraintLocator(locator)));

        return CS.createTypeVariable(CS.getConstraintLocator(repr),
                                     TVO_CanBindToHole);
      }
      // Diagnose top-level usages of placeholder types.
      if (isa<PlaceholderTypeRepr>(repr->getWithoutParens())) {
        CS.getASTContext().Diags.diagnose(repr->getLoc(),
                                          diag::placeholder_type_not_allowed);
      }
      return result;
    }

    Type visitTypeExpr(TypeExpr *E) {
      Type type;
      // If this is an implicit TypeExpr, don't validate its contents.
      auto *const locator = CS.getConstraintLocator(E);
      if (E->isImplicit()) {
        type = CS.getInstanceType(CS.cacheType(E));
        assert(type && "Implicit type expr must have type set!");
        type = CS.replaceInferableTypesWithTypeVars(type, locator);
      } else {
        auto *repr = E->getTypeRepr();
        assert(repr && "Explicit node has no type repr!");
        type = resolveTypeReferenceInExpression(
            repr, TypeResolverContext::InExpression, locator);
      }

      if (!type || type->hasError()) return Type();

      return MetatypeType::get(type);
    }

    Type visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *expr) {
      llvm_unreachable("Already type-checked");
    }

    Type visitOverloadedDeclRefExpr(OverloadedDeclRefExpr *expr) {
      // For a reference to an overloaded declaration, we create a type variable
      // that will be equal to different types depending on which overload
      // is selected.
      auto locator = CS.getConstraintLocator(expr);
      auto tv = CS.createTypeVariable(locator,
                                      TVO_CanBindToLValue | TVO_CanBindToNoEscape);
      ArrayRef<ValueDecl*> decls = expr->getDecls();
      SmallVector<OverloadChoice, 4> choices;

      for (unsigned i = 0, n = decls.size(); i != n; ++i) {
        // If the result is invalid, skip it.
        // FIXME: Note this as invalid, in case we don't find a solution,
        // so we don't let errors cascade further.
        if (decls[i]->isInvalid())
          continue;

        OverloadChoice choice =
            OverloadChoice(Type(), decls[i], expr->getFunctionRefKind());
        choices.push_back(choice);
      }

      if (choices.empty()) {
        // There are no suitable overloads. Just fail.
        return nullptr;
      }

      // Record this overload set.
      CS.addOverloadSet(tv, choices, CurDC, locator);
      return tv;
    }

    Type visitUnresolvedDeclRefExpr(UnresolvedDeclRefExpr *expr) {
      // This is an error case, where we're trying to use type inference
      // to help us determine which declaration the user meant to refer to.
      // FIXME: Do we need to note that we're doing some kind of recovery?
      return CS.createTypeVariable(CS.getConstraintLocator(expr),
                                   TVO_CanBindToLValue |
                                   TVO_CanBindToNoEscape);
    }
    
    Type visitMemberRefExpr(MemberRefExpr *expr) {
      return addMemberRefConstraints(expr, expr->getBase(),
                                     expr->getMember().getDecl(),
                                     /*FIXME:*/FunctionRefKind::DoubleApply);
    }
    
    Type visitDynamicMemberRefExpr(DynamicMemberRefExpr *expr) {
      llvm_unreachable("Already typechecked");
    }

    void setUnresolvedBaseType(UnresolvedMemberExpr *UME, Type ty) {
      UnresolvedBaseTypes.insert({UME, ty});
    }

    Type getUnresolvedBaseType(UnresolvedMemberExpr *UME) {
      auto result = UnresolvedBaseTypes.find(UME);
      assert(result != UnresolvedBaseTypes.end());
      return result->second;
    }
    
    virtual Type visitUnresolvedMemberExpr(UnresolvedMemberExpr *expr) {
      auto baseLocator = CS.getConstraintLocator(
                            expr,
                            ConstraintLocator::MemberRefBase);
      auto memberLocator
        = CS.getConstraintLocator(expr, ConstraintLocator::UnresolvedMember);

      // Since base type in this case is completely dependent on context it
      // should be marked as a potential hole.
      auto baseTy = CS.createTypeVariable(baseLocator, TVO_CanBindToNoEscape |
                                                           TVO_CanBindToHole);
      setUnresolvedBaseType(expr, baseTy);

      auto memberTy = CS.createTypeVariable(
          memberLocator, TVO_CanBindToLValue | TVO_CanBindToNoEscape);

      // An unresolved member expression '.member' is modeled as a value member
      // constraint
      //
      //   T0.Type[.member] == T1
      //
      // for fresh type variables T0 and T1, which pulls out a static
      // member, i.e., an enum case or a static variable.
      auto baseMetaTy = MetatypeType::get(baseTy);
      CS.addUnresolvedValueMemberConstraint(baseMetaTy, expr->getName(),
                                            memberTy, CurDC,
                                            expr->getFunctionRefKind(),
                                            memberLocator);
      return memberTy;
    }

    Type visitUnresolvedMemberChainResultExpr(
        UnresolvedMemberChainResultExpr *expr) {
      auto *tail = expr->getSubExpr();
      auto memberTy = CS.getType(tail);
      auto *base = expr->getChainBase();
      assert(base == TypeChecker::getUnresolvedMemberChainBase(tail));

      // The result type of the chain is represented by a new type variable.
      auto locator = CS.getConstraintLocator(
          expr, ConstraintLocator::UnresolvedMemberChainResult);
      auto chainResultTy = CS.createTypeVariable(
          locator,
          TVO_CanBindToLValue | TVO_CanBindToHole | TVO_CanBindToNoEscape);
      auto chainBaseTy = getUnresolvedBaseType(base);

      // The result of the last element of the chain must be convertible to the
      // whole chain, and the type of the whole chain must be equal to the base.
      CS.addConstraint(ConstraintKind::Conversion, memberTy, chainResultTy,
                       locator);
      CS.addConstraint(ConstraintKind::UnresolvedMemberChainBase, chainResultTy,
                       chainBaseTy, locator);

      return chainResultTy;
    }

    Type visitUnresolvedDotExpr(UnresolvedDotExpr *expr) {
      // UnresolvedDot applies the base to remove a single curry level from a
      // member reference without using an applicable function constraint so
      // we record the call argument matching here so it can be found later when
      // a solution is applied to the AST.
      CS.recordMatchCallArgumentResult(
          CS.getConstraintLocator(expr, ConstraintLocator::ApplyArgument),
          MatchCallArgumentResult::forArity(1));

      // If this is Builtin.type_join*, just return any type and move
      // on since we're going to discard this, and creating any type
      // variables for the reference will cause problems.
      auto &ctx = CS.getASTContext();
      auto typeOperation = getTypeOperation(expr, ctx);
      if (typeOperation != TypeOperation::None)
        return ctx.getAnyExistentialType();

      // If this is `Builtin.trigger_fallback_diagnostic()`, fail
      // without producing any diagnostics, in order to test fallback error.
      if (isTriggerFallbackDiagnosticBuiltin(expr, ctx))
        return Type();

      // Open a member constraint for constructor delegations on the
      // subexpr type.
      if (TypeChecker::getSelfForInitDelegationInConstructor(CS.DC, expr)) {
        auto baseTy = CS.getType(expr->getBase())
                        ->getWithoutSpecifierType();

        // 'self' or 'super' will reference an instance, but the constructor
        // is semantically a member of the metatype. This:
        //   self.init()
        //   super.init()
        // is really more like:
        //   self = Self.init()
        //   self.super = Super.init()
        baseTy = MetatypeType::get(baseTy, ctx);

        auto memberTypeLoc = CS.getConstraintLocator(
            expr, LocatorPathElt::ConstructorMemberType(
                      /*shortFormOrSelfDelegating*/ true));

        auto methodTy =
            CS.createTypeVariable(memberTypeLoc, TVO_CanBindToNoEscape);

        // HACK: Bind the function's parameter list as a tuple to a type
        // variable. This only exists to preserve compatibility with
        // rdar://85263844, as it can affect the prioritization of bindings,
        // which can affect behavior for tuple matching as tuple subtyping is
        // currently a *weaker* constraint than tuple conversion.
        if (!CS.getASTContext().isSwiftVersionAtLeast(6)) {
          auto paramTypeVar = CS.createTypeVariable(
              CS.getConstraintLocator(expr, ConstraintLocator::ApplyArgument),
              TVO_CanBindToLValue | TVO_CanBindToInOut | TVO_CanBindToNoEscape |
                  TVO_CanBindToPack);
          CS.addConstraint(ConstraintKind::BindTupleOfFunctionParams, methodTy,
                           paramTypeVar, CS.getConstraintLocator(expr));
        }

        CS.addValueMemberConstraint(
            baseTy, expr->getName(), methodTy, CurDC,
            expr->getFunctionRefKind(),
            /*outerAlternatives=*/{},
            CS.getConstraintLocator(expr,
                                    ConstraintLocator::ConstructorMember));

        // The result of the expression is the partial application of the
        // constructor to the subexpression.
        return methodTy;
      }

      return addMemberRefConstraints(expr, expr->getBase(), expr->getName(),
                                     expr->getFunctionRefKind(),
                                     expr->getOuterAlternatives());
    }

    /// Given a set of specialization arguments, resolve those arguments and
    /// introduce them as an explicit generic arguments constraint.
    ///
    /// \returns true if resolving any of the specialization types failed.
    bool addSpecializationConstraint(
        ConstraintLocator *locator, Type boundType,
        ArrayRef<TypeRepr *> specializationArgs) {
      // Resolve each type.
      SmallVector<Type, 2> specializationArgTypes;
      auto options =
          TypeResolutionOptions(TypeResolverContext::InExpression);
      for (auto specializationArg : specializationArgs) {
        PackExpansionExpr *elementEnv = nullptr;
        if (!OuterExpansions.empty()) {
          options |= TypeResolutionFlags::AllowPackReferences;
          elementEnv = OuterExpansions.back();
        }
        const auto result = TypeResolution::resolveContextualType(
            specializationArg, CurDC, options,
            // Introduce type variables for unbound generics.
            OpenUnboundGenericType(CS, locator),
            HandlePlaceholderType(CS, locator),
            OpenPackElementType(CS, locator, elementEnv));
        if (result->hasError())
          return true;

        specializationArgTypes.push_back(result);
      }

      CS.addConstraint(
          ConstraintKind::ExplicitGenericArguments, boundType,
          PackType::get(CS.getASTContext(), specializationArgTypes),
          locator);
      return false;
    }

    Type visitUnresolvedSpecializeExpr(UnresolvedSpecializeExpr *expr) {
      auto baseTy = CS.getType(expr->getSubExpr());

      if (baseTy->isTypeVariableOrMember()) {
        return baseTy;
      }

      // We currently only support explicit specialization of generic types.
      // FIXME: We could support explicit function specialization.
      auto &de = CS.getASTContext().Diags;
      if (baseTy->is<AnyFunctionType>()) {
        de.diagnose(expr->getSubExpr()->getLoc(),
                    diag::cannot_explicitly_specialize_generic_function);
        de.diagnose(expr->getLAngleLoc(),
                    diag::while_parsing_as_left_angle_bracket);
        return Type();
      }
      
      if (AnyMetatypeType *meta = baseTy->getAs<AnyMetatypeType>()) {
        auto *overloadLocator = CS.getConstraintLocator(expr->getSubExpr());
        if (addSpecializationConstraint(overloadLocator,
                                        meta->getInstanceType(),
                                        expr->getUnresolvedParams())) {
          return Type();
        }

        return baseTy;
      }

      // FIXME: If the base type is a type variable, constrain it to a metatype
      // of a bound generic type.
      de.diagnose(expr->getSubExpr()->getLoc(),
                  diag::not_a_generic_definition);
      de.diagnose(expr->getLAngleLoc(),
                  diag::while_parsing_as_left_angle_bracket);
      return Type();
    }
    
    Type visitSequenceExpr(SequenceExpr *expr) {
      // If a SequenceExpr survived until CSGen, then there was an upstream
      // error that was already reported.
      return Type();
    }

    Type visitArrowExpr(ArrowExpr *expr) {
      // If an ArrowExpr survived until CSGen, then there was an upstream
      // error that was already reported.
      return Type();
    }

    Type visitIdentityExpr(IdentityExpr *expr) {
      return CS.getType(expr->getSubExpr());
    }

    Type visitCopyExpr(CopyExpr *expr) {
      auto valueTy = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                           TVO_PrefersSubtypeBinding |
                                               TVO_CanBindToNoEscape);
      CS.addConstraint(ConstraintKind::Equal, valueTy,
                       CS.getType(expr->getSubExpr()),
                       CS.getConstraintLocator(expr));
      return valueTy;
    }

    Type visitConsumeExpr(ConsumeExpr *expr) {
      auto valueTy = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                           TVO_PrefersSubtypeBinding |
                                               TVO_CanBindToNoEscape);
      CS.addConstraint(ConstraintKind::Equal, valueTy,
                       CS.getType(expr->getSubExpr()),
                       CS.getConstraintLocator(expr));
      return valueTy;
    }

    Type visitAnyTryExpr(AnyTryExpr *expr) {
      return CS.getType(expr->getSubExpr());
    }

    Type visitOptionalTryExpr(OptionalTryExpr *expr) {
      auto valueTy = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                           TVO_PrefersSubtypeBinding |
                                           TVO_CanBindToNoEscape);

      Type optTy = getOptionalType(expr->getSubExpr()->getLoc(), valueTy);
      if (!optTy)
        return Type();

      bool isDelegationToOptionalInit = false;
      {
        Expr *e = expr->getSubExpr();
        while (true) {
          e = e->getSemanticsProvidingExpr();

          // Look through force-value expressions.
          if (auto *FVE = dyn_cast<ForceValueExpr>(e)) {
            e = FVE->getSubExpr();
            continue;
          }

          break;
        }

        if (auto *CE = dyn_cast<CallExpr>(e)) {
          if (auto *UDE = dyn_cast<UnresolvedDotExpr>(CE->getFn())) {
            if (!CS.getType(UDE->getBase())->is<AnyMetatypeType>()) {
              auto overload =
                  CS.findSelectedOverloadFor(CS.getConstraintLocator(
                      UDE, ConstraintLocator::ConstructorMember));
              if (overload) {
                auto *decl = overload->choice.getDeclOrNull();
                if (decl && isa<ConstructorDecl>(decl) &&
                    decl->getDeclContext()
                        ->getSelfNominalTypeDecl()
                        ->isOptionalDecl())
                  isDelegationToOptionalInit = true;
              }
            }
          }
        }
      }

      // Prior to Swift 5, 'try?' always adds an additional layer of
      // optionality, even if the sub-expression was already optional.
      //
      // NB Keep adding the additional layer in Swift 5 and on if this 'try?'
      // applies to a delegation to an 'Optional' initializer, or else we won't
      // discern the difference between a failure and a constructed value.
      if (CS.getASTContext().LangOpts.isSwiftVersionAtLeast(5) &&
          !isDelegationToOptionalInit) {
        CS.addConstraint(ConstraintKind::Conversion,
                         CS.getType(expr->getSubExpr()), optTy,
                         CS.getConstraintLocator(expr));
      } else {
        CS.addConstraint(ConstraintKind::OptionalObject,
                         optTy, CS.getType(expr->getSubExpr()),
                         CS.getConstraintLocator(expr));
      }
      return optTy;
    }

    virtual Type visitParenExpr(ParenExpr *expr) {
      // If the ParenExpr contains a pack expansion, generate a tuple
      // type containing the pack expansion type.
      if (CS.getType(expr->getSubExpr())->getAs<PackExpansionType>()) {
        return TupleType::get({CS.getType(expr->getSubExpr())},
                              CS.getASTContext());
      }

      if (auto favoredTy = CS.getFavoredType(expr->getSubExpr())) {
        CS.setFavoredType(expr, favoredTy);
      }
      return ParenType::get(CS.getASTContext(), CS.getType(expr->getSubExpr()));
    }

    Type visitTupleExpr(TupleExpr *expr) {
      // The type of a tuple expression is simply a tuple of the types of
      // its subexpressions.
      SmallVector<TupleTypeElt, 4> elements;
      elements.reserve(expr->getNumElements());
      for (unsigned i = 0, n = expr->getNumElements(); i != n; ++i) {
        elements.emplace_back(CS.getType(expr->getElement(i)),
                              expr->getElementName(i));
      }

      return TupleType::get(elements, CS.getASTContext());
    }

    Type visitSubscriptExpr(SubscriptExpr *expr) {
      ValueDecl *decl = nullptr;
      if (expr->hasDecl()) {
        decl = expr->getDecl().getDecl();
        if (decl->isInvalid())
          return Type();
      }

      auto *base = expr->getBase();
      if (!isValidBaseOfMemberRef(base, diag::cannot_subscript_nil_literal))
        return nullptr;

      return addSubscriptConstraints(expr, CS.getType(base), decl,
                                     expr->getArgs());
    }
    
    Type visitArrayExpr(ArrayExpr *expr) {
      auto &ctx = CS.getASTContext();

      // An array expression can be of a type T that conforms to the
      // ExpressibleByArrayLiteral protocol.
      auto *arrayProto = TypeChecker::getProtocol(
          ctx, expr->getLoc(),
          KnownProtocolKind::ExpressibleByArrayLiteral);
      if (!arrayProto) {
        return Type();
      }

      // Assume that ExpressibleByArrayLiteral contains a single associated type.
      auto *elementAssocTy = arrayProto->getAssociatedTypeMembers()[0];
      if (!elementAssocTy)
        return Type();

      auto locator = CS.getConstraintLocator(expr);
      auto contextualType = CS.getContextualType(expr, /*forConstraint=*/false);
      auto contextualPurpose = CS.getContextualTypePurpose(expr);

      auto joinElementTypes = [&](std::optional<Type> elementType) {
        const auto elements = expr->getElements();
        unsigned index = 0;

        using Iterator = decltype(elements)::iterator;
        CS.addJoinConstraint<Iterator>(
            locator, elements.begin(), elements.end(), elementType,
            [&](const auto it) {
              auto *locator = CS.getConstraintLocator(
                  expr, LocatorPathElt::TupleElement(index++));
              return std::make_pair(CS.getType(*it), locator);
            });
      };

      // If a contextual type exists for this expression, apply it directly.
      if (contextualType && contextualType->isArrayType()) {
        // Now that we know we're actually going to use the type, get the
        // version for use in a constraint.
        contextualType = CS.getContextualType(expr, /*forConstraint=*/true);
        contextualType = CS.openOpaqueType(
            contextualType, contextualPurpose, locator);
        Type arrayElementType = contextualType->isArrayType();
        CS.addConstraint(ConstraintKind::LiteralConformsTo, contextualType,
                         arrayProto->getDeclaredInterfaceType(),
                         locator);
        joinElementTypes(arrayElementType);
        return contextualType;
      }

      // Produce a specialized diagnostic if this is an attempt to initialize
      // or convert an array literal to a dictionary e.g.
      // `let _: [String: Int] = ["A", 0]`
      auto isDictionaryContextualType = [&](Type contextualType) -> bool {
        if (!contextualType)
          return false;

        auto *M = CS.DC->getParentModule();

        auto type = contextualType->lookThroughAllOptionalTypes();

        if (M->lookupConformance(type, arrayProto))
          return false;

        if (auto *proto = ctx.getProtocol(KnownProtocolKind::ExpressibleByDictionaryLiteral))
          if (M->lookupConformance(type, proto))
            return true;

        return false;
      };

      if (isDictionaryContextualType(contextualType)) {
        auto &DE = CS.getASTContext().Diags;
        auto numElements = expr->getNumElements();

        // Empty and single element array literals with dictionary contextual
        // types are fixed during solving, so continue as normal in those
        // cases.
        if (numElements > 1) {
          bool isIniting =
              CS.getContextualTypePurpose(expr) == CTP_Initialization;
          DE.diagnose(expr->getStartLoc(), diag::should_use_dictionary_literal,
                      contextualType->lookThroughAllOptionalTypes(), isIniting);

          auto diagnostic =
              DE.diagnose(expr->getStartLoc(), diag::meant_dictionary_lit);

          // If there is an even number of elements in the array, let's produce
          // a fix-it which suggests to replace "," with ":" to form a dictionary
          // literal.
          if ((numElements & 1) == 0) {
            const auto commaLocs = expr->getCommaLocs();
            if (commaLocs.size() == numElements - 1) {
              for (unsigned i = 0, e = numElements / 2; i != e; ++i)
                diagnostic.fixItReplace(commaLocs[i * 2], ":");
            }
          }

          return nullptr;
        }
      }

      auto arrayTy = CS.createTypeVariable(locator,
                                           TVO_PrefersSubtypeBinding |
                                           TVO_CanBindToNoEscape);

      // The array must be an array literal type.
      CS.addConstraint(ConstraintKind::LiteralConformsTo, arrayTy,
                       arrayProto->getDeclaredInterfaceType(),
                       locator);
      
      // Its subexpression should be convertible to a tuple (T.Element...).
      Type arrayElementTy = DependentMemberType::get(arrayTy, elementAssocTy);

      // Introduce conversions from each element to the element type of the
      // array.
      joinElementTypes(arrayElementTy);

      // The array element type defaults to 'Any'.
      CS.addConstraint(ConstraintKind::Defaultable, arrayElementTy,
                       ctx.getAnyExistentialType(), locator);

      return arrayTy;
    }

    static bool isMergeableValueKind(Expr *expr) {
      return isa<StringLiteralExpr>(expr) || isa<IntegerLiteralExpr>(expr) ||
             isa<FloatLiteralExpr>(expr);
    }

    Type visitDictionaryExpr(DictionaryExpr *expr) {
      ASTContext &C = CS.getASTContext();
      // A dictionary expression can be of a type T that conforms to the
      // ExpressibleByDictionaryLiteral protocol.
      // FIXME: This isn't actually used for anything at the moment.
      ProtocolDecl *dictionaryProto = TypeChecker::getProtocol(
          C, expr->getLoc(), KnownProtocolKind::ExpressibleByDictionaryLiteral);
      if (!dictionaryProto) {
        return Type();
      }

      // FIXME: Protect against broken standard library.
      auto keyAssocTy = dictionaryProto->getAssociatedType(C.Id_Key);
      auto valueAssocTy = dictionaryProto->getAssociatedType(C.Id_Value);

      auto locator = CS.getConstraintLocator(expr);
      auto contextualType = CS.getContextualType(expr, /*forConstraint=*/false);
      auto contextualPurpose = CS.getContextualTypePurpose(expr);

      // If a contextual type exists for this expression and is a dictionary
      // type, apply it directly.
      if (contextualType && ConstraintSystem::isDictionaryType(contextualType)) {
        // Now that we know we're actually going to use the type, get the
        // version for use in a constraint.
        contextualType = CS.getContextualType(expr, /*forConstraint=*/true);
        auto openedType =
            CS.openOpaqueType(contextualType, contextualPurpose, locator);
        auto dictionaryKeyValue =
            ConstraintSystem::isDictionaryType(openedType);
        Type contextualDictionaryKeyType;
        Type contextualDictionaryValueType;
        std::tie(contextualDictionaryKeyType,
                 contextualDictionaryValueType) = *dictionaryKeyValue;
        
        // Form an explicit tuple type from the contextual type's key and value types.
        TupleTypeElt tupleElts[2] = { TupleTypeElt(contextualDictionaryKeyType),
                                      TupleTypeElt(contextualDictionaryValueType) };
        Type contextualDictionaryElementType = TupleType::get(tupleElts, C);

        CS.addConstraint(ConstraintKind::LiteralConformsTo, openedType,
                         dictionaryProto->getDeclaredInterfaceType(), locator);

        unsigned index = 0;
        for (auto element : expr->getElements()) {
          CS.addConstraint(ConstraintKind::Conversion,
                           CS.getType(element),
                           contextualDictionaryElementType,
                           CS.getConstraintLocator(
                               expr, LocatorPathElt::TupleElement(index++)));
        }

        return openedType;
      }

      auto dictionaryTy = CS.createTypeVariable(locator,
                                                TVO_PrefersSubtypeBinding |
                                                TVO_CanBindToNoEscape);

      // The dictionary must be a dictionary literal type.
      CS.addConstraint(ConstraintKind::LiteralConformsTo, dictionaryTy,
                       dictionaryProto->getDeclaredInterfaceType(),
                       locator);


      // Its subexpression should be convertible to a tuple ((T.Key,T.Value)...).
      ConstraintLocatorBuilder locatorBuilder(locator);
      auto dictionaryKeyTy = DependentMemberType::get(dictionaryTy,
                                                      keyAssocTy);
      auto dictionaryValueTy = DependentMemberType::get(dictionaryTy,
                                                        valueAssocTy);
      TupleTypeElt tupleElts[2] = { TupleTypeElt(dictionaryKeyTy),
                                    TupleTypeElt(dictionaryValueTy) };
      Type elementTy = TupleType::get(tupleElts, C);

      // Keep track of which elements have been "merged". This way, we won't create
      // needless conversion constraints for elements whose equivalence classes have
      // been merged.
      llvm::DenseSet<Expr *> mergedElements;

      // If no contextual type is present, Merge equivalence classes of key 
      // and value types as necessary.
      if (!CS.getContextualType(expr, /*forConstraint=*/false)) {
        for (auto element1 : expr->getElements()) {
          for (auto element2 : expr->getElements()) {
            if (element1 == element2)
              continue;

            auto tty1 = CS.getType(element1)->getAs<TupleType>();
            auto tty2 = CS.getType(element2)->getAs<TupleType>();

            if (tty1 && tty2) {
              auto mergedKey = false;
              auto mergedValue = false;

              auto keyTyvar1 = tty1->getElementTypes()[0]->
                                getAs<TypeVariableType>();
              auto keyTyvar2 = tty2->getElementTypes()[0]->
                                getAs<TypeVariableType>();

              auto keyExpr1 = cast<TupleExpr>(element1)->getElements()[0];
              auto keyExpr2 = cast<TupleExpr>(element2)->getElements()[0];

              if (keyExpr1->getKind() == keyExpr2->getKind() &&
                  isMergeableValueKind(keyExpr1)) {
                mergedKey = mergeRepresentativeEquivalenceClasses(CS,
                            keyTyvar1, keyTyvar2);
              }

              auto valueTyvar1 = tty1->getElementTypes()[1]->
                                  getAs<TypeVariableType>();
              auto valueTyvar2 = tty2->getElementTypes()[1]->
                                  getAs<TypeVariableType>();

              auto elemExpr1 = cast<TupleExpr>(element1)->getElements()[1];
              auto elemExpr2 = cast<TupleExpr>(element2)->getElements()[1];

              if (elemExpr1->getKind() == elemExpr2->getKind() &&
                isMergeableValueKind(elemExpr1)) {
                mergedValue = mergeRepresentativeEquivalenceClasses(CS, 
                                valueTyvar1, valueTyvar2);
              }

              if (mergedKey && mergedValue)
                mergedElements.insert(element2);
            }
          }
        }
      }      

      // Introduce conversions from each element to the element type of the
      // dictionary. (If the equivalence class of an element has already been
      // merged with a previous one, skip it.)
      unsigned index = 0;
      for (auto element : expr->getElements()) {
        if (!mergedElements.count(element))
          CS.addConstraint(ConstraintKind::Conversion,
                           CS.getType(element),
                           elementTy,
                           CS.getConstraintLocator(
                               expr, LocatorPathElt::TupleElement(index++)));
      }

      // The dictionary key type defaults to 'AnyHashable'.
      auto &ctx = CS.getASTContext();
      if (dictionaryKeyTy->isTypeVariableOrMember() &&
          ctx.getAnyHashableDecl()) {
        auto anyHashable = ctx.getAnyHashableDecl();
        CS.addConstraint(ConstraintKind::Defaultable, dictionaryKeyTy,
                         anyHashable->getDeclaredInterfaceType(), locator);
      }

      // The dictionary value type defaults to 'Any'.
      if (dictionaryValueTy->isTypeVariableOrMember()) {
        CS.addConstraint(ConstraintKind::Defaultable, dictionaryValueTy,
                         ctx.getAnyExistentialType(), locator);
      }

      return dictionaryTy;
    }

    Type visitDynamicSubscriptExpr(DynamicSubscriptExpr *expr) {
      return addSubscriptConstraints(expr, CS.getType(expr->getBase()),
                                     /*decl*/ nullptr, expr->getArgs());
    }

    Type visitTupleElementExpr(TupleElementExpr *expr) {
      ASTContext &context = CS.getASTContext();
      DeclNameRef name(
          context.getIdentifier(llvm::utostr(expr->getFieldNumber())));
      return addMemberRefConstraints(expr, expr->getBase(), name,
                                     FunctionRefKind::Unapplied,
                                     /*outerAlternatives=*/{});
    }

    /// If \p allowResultBindToHole is \c true, we always allow the closure's
    /// result type to bind to a hole, otherwise the result type may only bind
    /// to a hole if the closure does not participate in type inference. Setting
    /// \p allowResultBindToHole to \c true is useful when ignoring a closure
    /// argument in a function call after the code completion token and thus
    /// wanting to ignore the closure's type.
    FunctionType *inferClosureType(ClosureExpr *closure,
                                   bool allowResultBindToHole = false) {
      SmallVector<AnyFunctionType::Param, 4> closureParams;

      if (auto *paramList = closure->getParameters()) {
        for (unsigned i = 0, n = paramList->size(); i != n; ++i) {
          auto *param = paramList->get(i);
          auto *paramLoc =
              CS.getConstraintLocator(closure, LocatorPathElt::TupleElement(i));

          // If one of the parameters represents a destructured tuple
          // e.g. `{ (x: Int, (y: Int, z: Int)) in ... }` let's fail
          // inference here and not attempt to solve the system because:
          //
          // a. Destructuring has already been diagnosed by the parser;
          // b. Body of the closure would have error expressions for
          //    each incorrect parameter reference and solver wouldn't
          //    be able to produce any viable solutions.
          if (param->isDestructured())
            return nullptr;

          Type externalType;
          if (param->getTypeRepr()) {
            auto declaredTy = CS.getVarType(param);

            // If closure parameter couldn't be resolved, let's record
            // a fix to make sure that type resolution diagnosed the
            // problem and replace it with a placeholder, so that solver
            // can make forward progress (especially important for result
            // builders).
            if (declaredTy->hasError()) {
              CS.recordFix(AllowRefToInvalidDecl::create(
                  CS, CS.getConstraintLocator(param)));
              declaredTy = PlaceholderType::get(CS.getASTContext(), param);
            }

            externalType = CS.replaceInferableTypesWithTypeVars(declaredTy,
                                                                paramLoc);
          } else {
            // Let's allow parameters which haven't been explicitly typed
            // to become holes by default, this helps in situations like
            // `foo { a in }` where `foo` doesn't exist.
            externalType = CS.createTypeVariable(
                paramLoc,
                TVO_CanBindToInOut | TVO_CanBindToNoEscape | TVO_CanBindToHole);
          }

          closureParams.push_back(param->toFunctionParam(externalType));
        }

        checkVariadicParameters(paramList, closure);
      }

      auto extInfo = CS.closureEffects(closure);
      auto resultLocator =
          CS.getConstraintLocator(closure, ConstraintLocator::ClosureResult);

      auto thrownErrorLocator =
        CS.getConstraintLocator(closure, ConstraintLocator::ClosureThrownError);

      // Determine the thrown error type, when appropriate.
      Type thrownErrorTy = [&] {
        // Explicitly-specified thrown type.
        if (closure->getExplicitThrownTypeRepr()) {
          if (Type explicitType = closure->getExplicitThrownType())
            return explicitType;
        }

        // Explicitly-specified 'throws' without a type is untyped throws.
        // Use a NULL return here so that the inferred type is written with
        // `throws` instead of `throws(any Error)`, although the two are
        // semantically equivalent.
        if (closure->getThrowsLoc().isValid())
          return Type();

        // Thrown type inferred from context.
        if (auto contextualType = CS.getContextualType(
                closure, /*forConstraint=*/false)) {
          if (auto fnType = contextualType->getAs<AnyFunctionType>()) {
            if (Type thrownErrorTy = fnType->getThrownError())
              return thrownErrorTy;
          }
        }

        // We do not try to infer a thrown error type if one isn't immediately
        // available.
        return Type();
      }();

      if (thrownErrorTy) {
        // Record the thrown error type in the extended info for the function
        // type of the closure.
        extInfo = extInfo.withThrows(true, thrownErrorTy);

        // Ensure that the thrown error type conforms to Error.
        if (auto errorProto =
                CS.getASTContext().getProtocol(KnownProtocolKind::Error)) {
          CS.addConstraint(
              ConstraintKind::ConformsTo, thrownErrorTy,
              errorProto->getDeclaredInterfaceType(), thrownErrorLocator);
        }
      }

      // Closure expressions always have function type. In cases where a
      // parameter or return type is omitted, a fresh type variable is used to
      // stand in for that parameter or return type, allowing it to be inferred
      // from context.
      Type resultTy = [&] {
        if (closure->hasExplicitResultType()) {
          if (auto declaredTy = closure->getExplicitResultType()) {
            return declaredTy;
          }

          auto options =
              TypeResolutionOptions(TypeResolverContext::InExpression);
          options.setContext(TypeResolverContext::ClosureExpr);
          const auto resolvedTy = resolveTypeReferenceInExpression(
              closure->getExplicitResultTypeRepr(), options, resultLocator);
          if (resolvedTy)
            return resolvedTy;
        }

        // Because we are only pulling out the result type from the contextual
        // type, we avoid prematurely converting any inferrable types by setting
        // forConstraint=false. Later on in inferClosureType we call
        // replaceInferableTypesWithTypeVars before returning to ensure we don't
        // introduce any placeholders into the constraint system.
        if (auto contextualType =
                CS.getContextualType(closure, /*forConstraint=*/false)) {
          if (auto fnType = contextualType->getAs<FunctionType>())
            return fnType->getResult();
        }

        // If no return type was specified, create a fresh type
        // variable for it and mark it as possible hole.
        //
        // If this is a multi-statement closure, let's mark result
        // as potential hole right away.
        return Type(CS.createTypeVariable(
            resultLocator,
            (!CS.participatesInInference(closure) || allowResultBindToHole)
                ? TVO_CanBindToHole
                : 0));
      }();

      // Determine the isolation of the closure.
      auto isolation = [&] {
        // Priority goes to an explicit isolated parameter.
        if (hasIsolatedParameter(closureParams))
          return FunctionTypeIsolation::forParameter();

        // Honor an explicit global actor.  This is suppressed if the
        // closure is async (but should it be?).
        if (!extInfo.isAsync()) {
          if (auto actorType = getExplicitGlobalActor(closure))
            return FunctionTypeIsolation::forGlobalActor(actorType);
        }

        return FunctionTypeIsolation::forNonIsolated();
      }();
      extInfo = extInfo.withIsolation(isolation);
      if (isolation.isGlobalActor() &&
          CS.getASTContext().LangOpts.hasFeature(Feature::GlobalActorIsolatedTypesUsability)) {
        extInfo = extInfo.withSendable();
      }

      auto *fnTy = FunctionType::get(closureParams, resultTy, extInfo);
      return CS.replaceInferableTypesWithTypeVars(
          fnTy, CS.getConstraintLocator(closure))->castTo<FunctionType>();
    }

    /// Produces a type for the given pattern, filling in any missing
    /// type information with fresh type variables.
    ///
    /// \param pattern The pattern.
    ///
    /// \param locator The locator to use for generated constraints and
    /// type variables.
    ///
    /// \param bindPatternVarsOneWay When true, generate fresh type variables
    /// for the types of each variable declared within the pattern, along
    /// with a one-way constraint binding that to the type to which the
    /// variable will be ascribed or inferred.
    Type getTypeForPattern(
       Pattern *pattern, ConstraintLocatorBuilder locator,
       bool bindPatternVarsOneWay,
       PatternBindingDecl *patternBinding = nullptr,
       unsigned patternBindingIndex = 0) {
      assert(pattern);

      // Local function that must be called for each "return" throughout this
      // function, to set the type of the pattern.
      auto setType = [&](Type type) {
        CS.setType(pattern, type);
        return type;
      };

      switch (pattern->getKind()) {
      case PatternKind::Paren: {
        auto *paren = cast<ParenPattern>(pattern);

        auto *subPattern = paren->getSubPattern();
        auto underlyingType = getTypeForPattern(
            subPattern,
            locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
            bindPatternVarsOneWay);

        return setType(ParenType::get(CS.getASTContext(), underlyingType));
      }
      case PatternKind::Binding: {
        auto *subPattern = cast<BindingPattern>(pattern)->getSubPattern();
        auto type = getTypeForPattern(subPattern, locator,
                                      bindPatternVarsOneWay);
        // Var doesn't affect the type.
        return setType(type);
      }
      case PatternKind::Any: {
        Type type;

        // If this is a situation like `[let] _ = <expr>`, return
        // initializer expression.
        auto getInitializerExpr = [&locator]() -> Expr * {
          auto last = locator.last();
          if (!last)
            return nullptr;

          auto contextualTy = last->getAs<LocatorPathElt::ContextualType>();
          return (contextualTy && contextualTy->isFor(CTP_Initialization))
                     ? locator.trySimplifyToExpr()
                     : nullptr;
        };

        auto matchLoc =
            locator.withPathElement(LocatorPathElt::PatternMatch(pattern));

        // Always prefer a contextual type when it's available.
        if (auto *initializer = getInitializerExpr()) {
          // For initialization always assume a type of initializer.
          type = CS.getType(initializer)->getRValueType();
        } else {
          type = CS.createTypeVariable(
              CS.getConstraintLocator(matchLoc,
                                      LocatorPathElt::AnyPatternDecl()),
              TVO_CanBindToNoEscape | TVO_CanBindToHole);
        }
        return setType(type);
      }

      case PatternKind::Named: {
        auto var = cast<NamedPattern>(pattern)->getDecl();

        Type varType;

        // Determine whether optionality will be required.
        auto ROK = ReferenceOwnership::Strong;
        if (auto *OA = var->getAttrs().getAttribute<ReferenceOwnershipAttr>())
          ROK = OA->get();
        auto optionality = optionalityOf(ROK);

        // If we have a type from an initializer expression, and that
        // expression does not produce an InOut type, use it.  This
        // will avoid exponential typecheck behavior in the case of
        // tuples, nested arrays, and dictionary literals.
        //
        // FIXME: This should be handled in the solver, not here.
        //
        // Otherwise, create a new type variable.
        if (var->getParentPatternBinding() &&
            !var->hasAttachedPropertyWrapper() &&
            optionality != ReferenceOwnershipOptionality::Required) {
          if (auto boundExpr = locator.trySimplifyToExpr()) {
            if (!boundExpr->isSemanticallyInOutExpr()) {
              varType = CS.getType(boundExpr)->getRValueType();
            }
          }
        }

        auto matchLoc =
            locator.withPathElement(LocatorPathElt::PatternMatch(pattern));

        if (!varType) {
          varType = CS.createTypeVariable(
              CS.getConstraintLocator(matchLoc,
                                      LocatorPathElt::NamedPatternDecl()),
              TVO_CanBindToNoEscape | TVO_CanBindToHole);

          // If this is either a `weak` declaration or capture e.g.
          // `weak var ...` or `[weak self]`. Let's wrap type variable
          // into an optional.
          if (optionality == ReferenceOwnershipOptionality::Required)
            varType = TypeChecker::getOptionalType(var->getLoc(), varType);
        }

        // When we are supposed to bind pattern variables, create a fresh
        // type variable and a one-way constraint to assign it to either the
        // deduced type or the externally-imposed type.
        Type oneWayVarType;
        if (bindPatternVarsOneWay) {
          oneWayVarType = CS.createTypeVariable(
              CS.getConstraintLocator(locator), TVO_CanBindToNoEscape);

          // If there is externally-imposed type, and the variable
          // is marked as `weak`, let's fallthrough and allow the
          // `one-way` constraint to be fixed in diagnostic mode.
          //
          // That would make sure that type of this variable is
          // recorded in the constraint  system, which would then
          // be used instead of `getVarType` upon discovering a
          // reference to this variable in subsequent expression(s).
          //
          // If we let constraint generation fail here, it would trigger
          // interface type request via `var->getType()` that would
          // attempt to validate `weak` attribute, and produce a
          // diagnostic in the middle of the solver path.

          CS.addConstraint(ConstraintKind::OneWayEqual, oneWayVarType,
                           varType, locator);
        }

        // Ascribe a type to the declaration so it's always available to
        // constraint system.
        if (oneWayVarType) {
          CS.setType(var, oneWayVarType);
        } else {
          // Otherwise, let's use the type of the pattern. The type
          // of the declaration has to be r-value, so let's add an
          // equality constraint if pattern type has any type variables
          // that are allowed to be l-value.
          bool foundLValueVars = false;

          // Note that it wouldn't be always correct to allocate a single type
          // variable, that disallows l-value types, to use as a declaration
          // type because equality constraint would drop TVO_CanBindToLValue
          // from the right-hand side (which is not the case for `OneWayEqual`)
          // e.g.:
          //
          // struct S { var x, y: Int }
          //
          // func test(s: S) {
          //   let (x, y) = (s.x, s.y)
          // }
          //
          // Single type variable approach results in the following constraint:
          // `$T_x_y = ($T_s_x, $T_s_y)` where both `$T_s_x` and `$T_s_y` have
          // to allow l-value, but `$T_x_y` does not. Early simplification of `=`
          // constraint (due to right-hand side being a "concrete" tuple type)
          // would drop l-value option from `$T_s_x` and `$T_s_y` which leads to
          // a failure during member lookup because `x` and `y` are both
          // `@lvalue Int`. To avoid that, declaration type would mimic pattern
          // type with all l-value options stripped, so the equality constraint
          // becomes `($T_x, $_T_y) = ($T_s_x, $T_s_y)` which doesn't result in
          // stripping of l-value flag from the right-hand side since
          // simplification can only happen when either side is resolved.
          auto declTy = varType.transform([&](Type type) -> Type {
            if (auto *typeVar = type->getAs<TypeVariableType>()) {
              if (typeVar->getImpl().canBindToLValue()) {
                foundLValueVars = true;

                // Drop l-value from the options but preserve the rest.
                auto options = typeVar->getImpl().getRawOptions();
                options &= ~TVO_CanBindToLValue;

                return CS.createTypeVariable(typeVar->getImpl().getLocator(),
                                             options);
              }
            }
            return type;
          });

          // If pattern types allows l-value types, let's create an
          // equality constraint between r-value only declaration type
          // and l-value pattern type that would take care of looking
          // through l-values when necessary.
          if (foundLValueVars) {
            CS.addConstraint(ConstraintKind::Equal, declTy, varType,
                             CS.getConstraintLocator(locator));
          }

          CS.setType(var, declTy);
        }

        return setType(varType);
      }

      case PatternKind::Typed: {
        // FIXME: Need a better locator for a pattern as a base.
        // Compute the type ascribed to the pattern.
        auto contextualPattern = patternBinding
            ? ContextualPattern::forPatternBindingDecl(
                patternBinding, patternBindingIndex)
            : ContextualPattern::forRawPattern(pattern, CurDC);

        Type type = TypeChecker::typeCheckPattern(contextualPattern);

        // Look through reference storage types.
        type = type->getReferenceStorageReferent();

        Type replacedType = CS.replaceInferableTypesWithTypeVars(type, locator);
        Type openedType =
            CS.openOpaqueType(replacedType, CTP_Initialization, locator);
        assert(openedType);

        auto *subPattern = cast<TypedPattern>(pattern)->getSubPattern();
        // Determine the subpattern type. It will be convertible to the
        // ascribed type.
        Type subPatternType = getTypeForPattern(
            subPattern,
            locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
            bindPatternVarsOneWay);

        // NOTE: The order here is important! Pattern matching equality is
        // not symmetric (we need to fix that either by using a different
        // constraint, or actually making it symmetric).
        CS.addConstraint(
            ConstraintKind::Equal, openedType, subPatternType,
            locator.withPathElement(LocatorPathElt::PatternMatch(pattern)));

        // FIXME [OPAQUE SUPPORT]: the distinction between where we want opaque
        // types in opened vs. un-unopened form is *very* tricky. The pattern
        // ultimately needs the un-opened type and it gets this from the set
        // type of the expression.
        CS.setType(pattern, replacedType);
        return openedType;
      }

      case PatternKind::Tuple: {
        auto tuplePat = cast<TuplePattern>(pattern);

        SmallVector<TupleTypeElt, 4> tupleTypeElts;
        tupleTypeElts.reserve(tuplePat->getNumElements());
        for (unsigned i = 0, e = tuplePat->getNumElements(); i != e; ++i) {
          auto &tupleElt = tuplePat->getElement(i);

          auto *eltPattern = tupleElt.getPattern();
          Type eltTy = getTypeForPattern(
              eltPattern,
              locator.withPathElement(LocatorPathElt::PatternMatch(eltPattern)),
              bindPatternVarsOneWay);

          tupleTypeElts.push_back(TupleTypeElt(eltTy, tupleElt.getLabel()));
        }

        return setType(TupleType::get(tupleTypeElts, CS.getASTContext()));
      }

      case PatternKind::OptionalSome: {
        auto *subPattern = cast<OptionalSomePattern>(pattern)->getSubPattern();
        // The subpattern must have optional type.
        Type subPatternType = getTypeForPattern(
            subPattern,
            locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
            bindPatternVarsOneWay);

        return setType(OptionalType::get(subPatternType));
      }

      case PatternKind::Is: {
        auto isPattern = cast<IsPattern>(pattern);

        const Type castType = resolveTypeReferenceInExpression(
            isPattern->getCastTypeRepr(), TypeResolverContext::InExpression,
            locator.withPathElement(LocatorPathElt::PatternMatch(pattern)));

        // Allow `is` pattern to infer type from context which is then going
        // to be propaged down to its sub-pattern via conversion. This enables
        // correct handling of patterns like `_ as Foo` where `_` would
        // get a type of `Foo` but `is` pattern enclosing it could still be
        // inferred from enclosing context.
        auto isType =
            CS.createTypeVariable(CS.getConstraintLocator(pattern),
                                  TVO_CanBindToNoEscape | TVO_CanBindToHole);

        // Make sure we can cast from the subpattern type to the type we're
        // checking; if it's impossible, fail.
        CS.addConstraint(
            ConstraintKind::CheckedCast, isType, castType,
            locator.withPathElement(LocatorPathElt::PatternMatch(pattern)));

        if (auto *subPattern = isPattern->getSubPattern()) {
          auto subPatternType = getTypeForPattern(
              subPattern,
              locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
              bindPatternVarsOneWay);

          // NOTE: The order here is important! Pattern matching equality is
          // not symmetric (we need to fix that either by using a different
          // constraint, or actually making it symmetric).
          CS.addConstraint(
              ConstraintKind::Equal, castType, subPatternType,
              locator.withPathElement(LocatorPathElt::PatternMatch(pattern)));
        }
        return setType(isType);
      }

      case PatternKind::Bool:
        return setType(CS.getASTContext().getBoolType());

      case PatternKind::EnumElement: {
        auto enumPattern = cast<EnumElementPattern>(pattern);

        // Create a type variable to represent the pattern.
        Type patternType =
            CS.createTypeVariable(CS.getConstraintLocator(locator),
                                  TVO_CanBindToNoEscape);

        // Form the member constraint for a reference to a member of this
        // type.
        Type baseType;
        Type memberType = CS.createTypeVariable(
            CS.getConstraintLocator(locator),
            TVO_CanBindToLValue | TVO_CanBindToNoEscape);

        // Tuple splat is still allowed for patterns (with a warning in Swift 5)
        // so we need to start here from single-apply to make sure that e.g.
        // `case test(x: Int, y: Int)` gets the labels preserved when matched
        // with `case let .test(tuple)`.
        FunctionRefKind functionRefKind = FunctionRefKind::SingleApply;
        // If sub-pattern is a tuple we'd need to mark reference as compound,
        // that would make sure that the labels are dropped in cases
        // when `case` has a single tuple argument (tuple explosion) or multiple
        // arguments (tuple-to-tuple conversion).
        if (dyn_cast_or_null<TuplePattern>(enumPattern->getSubPattern()))
          functionRefKind = FunctionRefKind::Compound;

        auto patternLocator =
            locator.withPathElement(LocatorPathElt::PatternMatch(pattern));

        if (enumPattern->getParentType() || enumPattern->getParentTypeRepr()) {
          // Resolve the parent type.
          const auto parentType = [&] {
            auto *const patternMatchLoc = CS.getConstraintLocator(
                locator, {LocatorPathElt::PatternMatch(pattern),
                          ConstraintLocator::ParentType});

            // FIXME: Sometimes the parent type is realized eagerly in
            // ResolvePattern::visitUnresolvedDotExpr, so we have to open it
            // ex post facto. Remove this once we learn how to resolve patterns
            // while generating constraints to keep the opening of generic types
            // contained within the type resolver.
            if (const auto preresolvedTy = enumPattern->getParentType()) {
              const auto openedTy =
                  CS.replaceInferableTypesWithTypeVars(preresolvedTy,
                                                       patternMatchLoc);
              assert(openedTy);
              return openedTy;
            }

            return resolveTypeReferenceInExpression(
                enumPattern->getParentTypeRepr(),
                TypeResolverContext::InExpression, patternMatchLoc);
          }();

          // Perform member lookup into the parent's metatype.
          Type parentMetaType = MetatypeType::get(parentType);
          CS.addValueMemberConstraint(parentMetaType, enumPattern->getName(),
                                      memberType, CurDC, functionRefKind, {},
                                      patternLocator);

          // Parent type needs to be convertible to the pattern type; this
          // accounts for cases where the pattern type is existential.
          CS.addConstraint(
              ConstraintKind::Conversion, parentType, patternType,
              patternLocator.withPathElement(
                  ConstraintLocator::EnumPatternImplicitCastMatch));

          baseType = parentType;
        } else {
          // Use the pattern type for member lookup.
          CS.addUnresolvedValueMemberConstraint(
              MetatypeType::get(patternType), enumPattern->getName(),
              memberType, CurDC, functionRefKind, patternLocator);

          baseType = patternType;
        }

        if (auto subPattern = enumPattern->getSubPattern()) {
          // When there is a subpattern, the member will have function type,
          // and we're matching the type of that subpattern to the parameter
          // types.
          Type subPatternType = getTypeForPattern(
              subPattern,
              locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
              bindPatternVarsOneWay);

          SmallVector<AnyFunctionType::Param, 4> params;
          decomposeTuple(subPatternType, params);

          // Remove parameter labels; they aren't used when matching cases,
          // but outright conflicts will be checked during coercion.
          for (auto &param : params) {
            param = param.getWithoutLabels();
          }

          Type outputType = CS.createTypeVariable(
              CS.getConstraintLocator(locator),
              TVO_CanBindToNoEscape);
          // Equal constraints require ExtInfo comparison.
          // FIXME: Verify ExtInfo state is correct, not working by accident.
          FunctionType::ExtInfo info;
          Type functionType = FunctionType::get(params, outputType, info);

          // TODO: Convert to own constraint? Note that ApplicableFn isn't quite
          // right, as pattern matching has data flowing *into* the apply result
          // and call arguments, not the other way around.
          // NOTE: The order here is important! Pattern matching equality is
          // not symmetric (we need to fix that either by using a different
          // constraint, or actually making it symmetric).
          CS.addConstraint(ConstraintKind::Equal, functionType, memberType,
                           patternLocator);

          CS.addConstraint(ConstraintKind::Conversion, outputType, baseType,
                           patternLocator);
        }

        return setType(patternType);
      }

      case PatternKind::Expr: {
        // We generate constraints for ExprPatterns in a separate pass. For
        // now, just create a type variable.
        return setType(CS.createTypeVariable(CS.getConstraintLocator(locator),
                                             TVO_CanBindToNoEscape));
      }
      }

      llvm_unreachable("Unhandled pattern kind");
    }

    Type visitCaptureListExpr(CaptureListExpr *expr) {
      // The type of the capture list is just the type of its closure.
      return CS.getType(expr->getClosureBody());
    }

    Type visitClosureExpr(ClosureExpr *closure) {
      auto *locator = CS.getConstraintLocator(closure);
      auto closureType = CS.createTypeVariable(locator, TVO_CanBindToNoEscape);

      TypeVarRefCollector refCollector(CS, /*DC*/ closure, locator);
      // Walk the capture list if this closure has one,  because it could
      // reference declarations from the outer closure.
      if (auto *captureList =
              getAsExpr<CaptureListExpr>(CS.getParentExpr(closure))) {
        captureList->walk(refCollector);
      } else {
        closure->walk(refCollector);
      }

      auto inferredType = inferClosureType(closure);
      if (!inferredType || inferredType->hasError())
        return Type();

      auto referencedVars = refCollector.getTypeVars();
      CS.addUnsolvedConstraint(
          Constraint::create(CS, ConstraintKind::FallbackType, closureType,
                             inferredType, locator, referencedVars));

      if (!OuterExpansions.empty())
        CS.setCapturedExpansions(closure, OuterExpansions);

      CS.setClosureType(closure, inferredType);
      return closureType;
    }

    Type visitAutoClosureExpr(AutoClosureExpr *expr) {
      // AutoClosureExpr is introduced by CSApply.
      llvm_unreachable("Already type-checked");
    }

    Type visitInOutExpr(InOutExpr *expr) {
      // The address-of operator produces an explicit inout T from an lvalue T.
      // We model this with the constraint
      //
      //     S < lvalue T
      //
      // where T is a fresh type variable.
      auto lvalue = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                          TVO_CanBindToNoEscape);
      auto bound = LValueType::get(lvalue);
      auto result = InOutType::get(lvalue);
      CS.addConstraint(ConstraintKind::Conversion,
                       CS.getType(expr->getSubExpr()), bound,
                       CS.getConstraintLocator(expr));
      return result;
    }

    Type visitVarargExpansionExpr(VarargExpansionExpr *expr) {
      // Create a fresh type variable.
      auto element = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                           TVO_CanBindToNoEscape);

      // Try to build the appropriate type for a variadic argument list of
      // the fresh element type.  If that failed, just bail out.
      auto variadicSeq = VariadicSequenceType::get(element);

      // Require the operand to be convertible to the array type.
      CS.addConstraint(ConstraintKind::Conversion,
                       CS.getType(expr->getSubExpr()), variadicSeq,
                       CS.getConstraintLocator(expr));
      return variadicSeq;
    }

    void collectExpandedPacks(PackExpansionExpr *expansion,
                              SmallVectorImpl<ASTNode> &packs) {
      struct PackCollector : public ASTWalker {
      private:
        ConstraintSystem &CS;
        SmallVectorImpl<ASTNode> &Packs;

      public:
        PackCollector(ConstraintSystem &cs, SmallVectorImpl<ASTNode> &packs)
            : CS(cs), Packs(packs) {}

        /// Walk everything that's available.
        MacroWalking getMacroWalkingBehavior() const override {
          return MacroWalking::ArgumentsAndExpansion;
        }

        virtual PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
          // Don't walk into nested pack expansions
          if (isa<PackExpansionExpr>(E)) {
            return Action::SkipNode(E);
          }

          if (isa<PackElementExpr>(E)) {
            Packs.push_back(E);
          }

          if (auto *declRef = dyn_cast<DeclRefExpr>(E)) {
            auto type = CS.getTypeIfAvailable(declRef);
            if (!type)
              return Action::Continue(E);

            if (type->is<ElementArchetypeType>() &&
                CS.hasFixFor(CS.getConstraintLocator(declRef),
                             FixKind::IgnoreMissingEachKeyword)) {
              auto *packElementExpr =
                  PackElementExpr::create(CS.getASTContext(),
                                          /*eachLoc=*/{}, declRef,
                                          /*implicit=*/true, type);
              Packs.push_back(CS.cacheType(packElementExpr));
            }
          }

          return Action::Continue(E);
        }

        virtual PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
          // Don't walk into nested pack expansions
          if (isa<PackExpansionTypeRepr>(T)) {
            return Action::SkipNode();
          }

          if (isa<PackElementTypeRepr>(T)) {
            Packs.push_back(T);
          }

          return Action::Continue();
        }
      } packCollector(CS, packs);

      expansion->getPatternExpr()->walk(packCollector);
    }

    Type visitPackExpansionExpr(PackExpansionExpr *expr) {
      assert(OuterExpansions.back() == expr);
      OuterExpansions.pop_back();

      auto expansionType = CS.getType(expr)->castTo<PackExpansionType>();
      auto elementResultType = CS.getType(expr->getPatternExpr());
      CS.addConstraint(ConstraintKind::PackElementOf, elementResultType,
                       expansionType->getPatternType(),
                       CS.getConstraintLocator(expr));

      // Generate ShapeOf constraints between all packs expanded by this
      // pack expansion expression through the shape type variable.
      SmallVector<ASTNode, 2> expandedPacks;
      collectExpandedPacks(expr, expandedPacks);

      if (expandedPacks.empty()) {
        (void)CS.recordFix(AllowValueExpansionWithoutPackReferences::create(
            CS, CS.getConstraintLocator(expr)));
      }

      for (auto pack : expandedPacks) {
        Type packType;
        /// Skipping over pack elements because the relationship to its
        /// environment is now established during \c pushPackExpansionExpr
        /// upon visiting its pack expansion and the Shape constraint added
        /// upon visiting the pack element.
        if (isExpr<PackElementExpr>(pack)) {
          continue;
        } else if (auto *elementType =
                       getAsTypeRepr<PackElementTypeRepr>(pack)) {
          // OpenPackElementType sets types for 'each T' type reprs in
          // expressions. Some invalid code won't make it there, and
          // the constraint system won't have recorded a type.
          if (!CS.hasType(elementType->getPackType()))
            return Type();

          packType = CS.getType(elementType->getPackType());
        } else {
          llvm_unreachable("unsupported pack reference ASTNode");
        }

        auto *elementShape = CS.createTypeVariable(
            CS.getConstraintLocator(pack, ConstraintLocator::PackShape),
            TVO_CanBindToPack);
        CS.addConstraint(
            ConstraintKind::ShapeOf, elementShape, packType,
            CS.getConstraintLocator(pack, ConstraintLocator::PackShape));
        CS.addConstraint(
            ConstraintKind::Equal, elementShape, expansionType->getCountType(),
            CS.getConstraintLocator(expr, ConstraintLocator::PackShape));
      }

      return expansionType;
    }

    Type visitPackElementExpr(PackElementExpr *expr) {
      auto packType = CS.getType(expr->getPackRefExpr());
      auto *packEnvironment = CS.getPackEnvironment(expr);
      auto elementType = openPackElement(
          packType, CS.getConstraintLocator(expr), packEnvironment);
      if (packEnvironment) {
        auto expansionType =
            CS.getType(packEnvironment)->castTo<PackExpansionType>();
        CS.addConstraint(ConstraintKind::ShapeOf, expansionType->getCountType(),
                         packType,
                         CS.getConstraintLocator(packEnvironment,
                                                 ConstraintLocator::PackShape));
      } else {
        CS.recordFix(AllowInvalidPackReference::create(
            CS, packType, CS.getConstraintLocator(expr->getPackRefExpr())));
      }

      return elementType;
    }

    Type visitMaterializePackExpr(MaterializePackExpr *expr) {
      llvm_unreachable("MaterializePackExpr already type-checked");
    }

    Type visitDynamicTypeExpr(DynamicTypeExpr *expr) {
      auto tv = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                      TVO_CanBindToNoEscape);
      CS.addConstraint(
          ConstraintKind::DynamicTypeOf, tv, CS.getType(expr->getBase()),
          CS.getConstraintLocator(expr, ConstraintLocator::DynamicType));
      return tv;
    }

    Type visitOpaqueValueExpr(OpaqueValueExpr *expr) {
      return expr->getType();
    }

    Type visitPropertyWrapperValuePlaceholderExpr(
        PropertyWrapperValuePlaceholderExpr *expr) {
      if (auto ty = expr->getType()) {
        CS.cacheType(expr);
        return ty;
      }

      assert(CS.getType(expr));
      return CS.getType(expr);
    }

    Type visitAppliedPropertyWrapperExpr(AppliedPropertyWrapperExpr *expr) {
      return expr->getType();
    }

    Type visitDefaultArgumentExpr(DefaultArgumentExpr *expr) {
      return expr->getType();
    }

    Type visitApplyExpr(ApplyExpr *expr) {
      auto fnExpr = expr->getFn();

      CS.associateArgumentList(CS.getConstraintLocator(expr), expr->getArgs());

      if (auto *UDE = dyn_cast<UnresolvedDotExpr>(fnExpr)) {
        auto typeOperation = getTypeOperation(UDE, CS.getASTContext());
        if (typeOperation != TypeOperation::None)
          return resultOfTypeOperation(typeOperation, expr->getArgs());
      }

      // The result type is a fresh type variable.
      Type resultType = CS.createTypeVariable(
          CS.getConstraintLocator(expr, ConstraintLocator::FunctionResult),
          TVO_CanBindToNoEscape);

      // A direct call to a ClosureExpr makes it noescape.
      FunctionType::ExtInfo extInfo;
      if (isa<ClosureExpr>(fnExpr->getSemanticsProvidingExpr()))
        extInfo = extInfo.withNoEscape();

      SmallVector<AnyFunctionType::Param, 8> params;
      getMatchingParams(expr->getArgs(), params);

      CS.addConstraint(ConstraintKind::ApplicableFunction,
                       FunctionType::get(params, resultType, extInfo),
                       CS.getType(fnExpr),
        CS.getConstraintLocator(expr, ConstraintLocator::ApplyFunction));

      // If we ended up resolving the result type variable to a concrete type,
      // set it as the favored type for this expression.
      Type fixedType =
          CS.getFixedTypeRecursive(resultType, /*wantRvalue=*/true);
      if (!fixedType->isTypeVariableOrMember()) {
        CS.setFavoredType(expr, fixedType.getPointer());
        resultType = fixedType;
      }

      return resultType;
    }

    Type getSuperType(VarDecl *selfDecl,
                      SourceLoc diagLoc,
                      Diag<> diag_not_in_class,
                      Diag<> diag_no_base_class) {
      DeclContext *typeContext = selfDecl->getDeclContext()->getParent();
      assert(typeContext && "constructor without parent context?!");

      auto &de = CS.getASTContext().Diags;
      ClassDecl *classDecl = typeContext->getSelfClassDecl();
      if (!classDecl) {
        de.diagnose(diagLoc, diag_not_in_class);
        return Type();
      }
      if (!classDecl->hasSuperclass()) {
        de.diagnose(diagLoc, diag_no_base_class);
        return Type();
      }

      auto selfTy = CS.DC->mapTypeIntoContext(
        typeContext->getDeclaredInterfaceType());
      auto superclassTy = selfTy->getSuperclass();

      if (!superclassTy)
        return Type();

      if (selfDecl->getInterfaceType()->is<MetatypeType>())
        superclassTy = MetatypeType::get(superclassTy);

      return superclassTy;
    }
    
    Type visitRebindSelfInConstructorExpr(RebindSelfInConstructorExpr *expr) {
      // The result is void.
      return TupleType::getEmpty(CS.getASTContext());
    }

    Type visitTernaryExpr(TernaryExpr *expr) {
      // Condition must convert to Bool.
      auto boolDecl = CS.getASTContext().getBoolDecl();
      if (!boolDecl)
        return Type();

      CS.addConstraint(
          ConstraintKind::Conversion, CS.getType(expr->getCondExpr()),
          boolDecl->getDeclaredInterfaceType(),
          CS.getConstraintLocator(expr, ConstraintLocator::Condition));

      // The branches must be convertible to a common type.
      return CS.addJoinConstraint(
          CS.getConstraintLocator(expr),
          {{CS.getType(expr->getThenExpr()),
            CS.getConstraintLocator(expr, LocatorPathElt::TernaryBranch(true))},
           {CS.getType(expr->getElseExpr()),
            CS.getConstraintLocator(expr,
                                    LocatorPathElt::TernaryBranch(false))}});
    }

    virtual Type visitImplicitConversionExpr(ImplicitConversionExpr *expr) {
      llvm_unreachable("Already type-checked");
    }

    Type
    createTypeVariableAndDisjunctionForIUOCoercion(Type toType,
                                                   ConstraintLocator *locator) {
      auto typeVar = CS.createTypeVariable(locator, TVO_CanBindToNoEscape);
      CS.buildDisjunctionForImplicitlyUnwrappedOptional(typeVar, toType,
                                                        locator);
      return typeVar;
    }

    Type getTypeForCast(ExplicitCastExpr *E) {
      if (auto *const repr = E->getCastTypeRepr()) {
        // Validate the resulting type.
        return resolveTypeReferenceInExpression(
            repr, TypeResolverContext::ExplicitCastExpr,
            CS.getConstraintLocator(E));
      }
      assert(E->isImplicit());
      return E->getCastType();
    }

    Type visitForcedCheckedCastExpr(ForcedCheckedCastExpr *expr) {
      auto fromExpr = expr->getSubExpr();
      if (!fromExpr) // Either wasn't constructed correctly or wasn't folded.
        return nullptr;

      auto toType = getTypeForCast(expr);
      if (!toType)
        return Type();

      auto *const repr = expr->getCastTypeRepr();

      // Cache the type we're casting to.
      if (repr) CS.setType(repr, toType);

      auto fromType = CS.getType(fromExpr);
      auto locator = CS.getConstraintLocator(expr);

      // The source type can be checked-cast to the destination type.
      CS.addConstraint(ConstraintKind::CheckedCast, fromType, toType, locator);

      // If the result type was declared IUO, add a disjunction for
      // bindings for the result of the coercion.
      if (repr && repr->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional)
        return createTypeVariableAndDisjunctionForIUOCoercion(toType, locator);

      return toType;
    }

    Type visitCoerceExpr(CoerceExpr *expr) {
      // Validate the resulting type.
      auto toType = getTypeForCast(expr);
      if (!toType)
        return nullptr;

      auto *const repr = expr->getCastTypeRepr();

      // Cache the type we're casting to.
      if (repr) CS.setType(repr, toType);

      auto fromType = CS.getType(expr->getSubExpr());
      auto locator =
          CS.getConstraintLocator(expr, ConstraintLocator::CoercionOperand);

      // Literal initialization (e.g. `UInt32(0)`) doesn't require
      // a conversion because the literal is supposed to assume the
      // `to` type.
      //
      // `to` type could be a type variable if i.e. the repr is invalid,
      // in such cases a slower conversion path is a better choice to
      // let it be inferred from the context and/or from the literal itself.
      if (expr->isLiteralInit() && !toType->isTypeVariableOrMember()) {
        CS.addConstraint(ConstraintKind::Equal, fromType, toType, locator);
      } else {
        // Add a conversion constraint for the direct conversion between
        // types.
        CS.addExplicitConversionConstraint(fromType, toType, RememberChoice,
                                           locator);
      }

      // If the result type was declared IUO, add a disjunction for
      // bindings for the result of the coercion.
      if (repr &&
          repr->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional) {
        return createTypeVariableAndDisjunctionForIUOCoercion(
            toType, CS.getConstraintLocator(expr));
      }

      return toType;
    }

    Type visitConditionalCheckedCastExpr(ConditionalCheckedCastExpr *expr) {
      auto fromExpr = expr->getSubExpr();
      if (!fromExpr) // Either wasn't constructed correctly or wasn't folded.
        return nullptr;

      // Validate the resulting type.
      const auto toType = getTypeForCast(expr);
      if (!toType)
        return nullptr;

      auto *const repr = expr->getCastTypeRepr();

      // Cache the type we're casting to.
      if (repr) CS.setType(repr, toType);

      auto fromType = CS.getType(fromExpr);
      auto locator = CS.getConstraintLocator(expr);

      CS.addConstraint(ConstraintKind::CheckedCast, fromType, toType, locator);

      // If the result type was declared IUO, add a disjunction for
      // bindings for the result of the coercion.
      if (repr && repr->getKind() == TypeReprKind::ImplicitlyUnwrappedOptional)
        return createTypeVariableAndDisjunctionForIUOCoercion(
            OptionalType::get(toType), locator);

      return OptionalType::get(toType);
    }

    Type visitIsExpr(IsExpr *expr) {
      auto toType = getTypeForCast(expr);
      if (!toType)
        return nullptr;

      auto *const repr = expr->getCastTypeRepr();
      // Cache the type we're checking.
      if (repr)
        CS.setType(repr, toType);

      // Add a checked cast constraint.
      auto fromType = CS.getType(expr->getSubExpr());
      
      CS.addConstraint(ConstraintKind::CheckedCast, fromType, toType,
                       CS.getConstraintLocator(expr));

      auto &ctx = CS.getASTContext();
      // The result is Bool.
      auto boolDecl = ctx.getBoolDecl();

      if (!boolDecl) {
        ctx.Diags.diagnose(SourceLoc(), diag::broken_bool);
        return Type();
      }

      return boolDecl->getDeclaredInterfaceType();
    }

    Type visitDiscardAssignmentExpr(DiscardAssignmentExpr *expr) {
      auto locator = CS.getConstraintLocator(expr);
      auto typeVar = CS.createTypeVariable(locator, TVO_CanBindToNoEscape);
      return LValueType::get(typeVar);
    }

    static Type genAssignDestType(Expr *expr, ConstraintSystem &CS) {
      if (auto *TE = dyn_cast<TupleExpr>(expr)) {
        SmallVector<TupleTypeElt, 4> destTupleTypes;
        for (unsigned i = 0; i !=  TE->getNumElements(); ++i) {
          Type subType = genAssignDestType(TE->getElement(i), CS);
          destTupleTypes.push_back(TupleTypeElt(subType, TE->getElementName(i)));
        }
        return TupleType::get(destTupleTypes, CS.getASTContext());
      } else {
        auto *locator = CS.getConstraintLocator(expr);

        auto isOrCanBeLValueType = [](Type type) {
          if (auto *typeVar = type->getAs<TypeVariableType>()) {
            return typeVar->getImpl().canBindToLValue();
          }
          return type->is<LValueType>();
        };

        auto exprType = CS.getType(expr);
        if (!isOrCanBeLValueType(exprType)) {
          // Pretend that destination is an l-value type.
          exprType = LValueType::get(exprType);
          (void)CS.recordFix(TreatRValueAsLValue::create(CS, locator));
        }

        auto *destTy = CS.createTypeVariable(locator, TVO_CanBindToNoEscape);
        CS.addConstraint(ConstraintKind::Bind, LValueType::get(destTy),
                         exprType, locator);
        return destTy;
      }
    }

    Type visitAssignExpr(AssignExpr *expr) {
      // Handle invalid code.
      if (!expr->getDest() || !expr->getSrc())
        return Type();
      Type destTy = genAssignDestType(expr->getDest(), CS);
      CS.addConstraint(ConstraintKind::Conversion,
                       CS.getType(expr->getSrc()), destTy,
                       CS.getConstraintLocator(expr));
      return TupleType::getEmpty(CS.getASTContext());
    }
    
    Type visitUnresolvedPatternExpr(UnresolvedPatternExpr *expr) {
      // Encountering an UnresolvedPatternExpr here means we have an invalid
      // ExprPattern with a Pattern node like 'let x' nested in it. Record a
      // fix, and assign ErrorTypes to any VarDecls bound.
      auto *locator = CS.getConstraintLocator(expr);
      auto *P = expr->getSubPattern();
      CS.recordFix(IgnoreInvalidPatternInExpr::create(CS, P, locator));

      P->forEachVariable([&](VarDecl *VD) {
        CS.setType(VD, ErrorType::get(CS.getASTContext()));
      });

      return CS.createTypeVariable(locator, TVO_CanBindToHole);
    }

    /// Get the type T?
    ///
    ///  This is not the ideal source location, but it's only used for
    /// diagnosing ill-formed standard libraries, so it really isn't
    /// worth QoI efforts.
    Type getOptionalType(SourceLoc optLoc, Type valueTy) {
      auto optTy = TypeChecker::getOptionalType(optLoc, valueTy);
      if (optTy->hasError() ||
          TypeChecker::requireOptionalIntrinsics(CS.getASTContext(), optLoc))
        return Type();

      return optTy;
    }

    Type visitBindOptionalExpr(BindOptionalExpr *expr) {
      // The operand must be coercible to T?, and we will have type T.
      auto locator = CS.getConstraintLocator(expr);

      auto objectTy = CS.createTypeVariable(locator,
                                            TVO_PrefersSubtypeBinding |
                                            TVO_CanBindToLValue |
                                            TVO_CanBindToNoEscape);
      
      // The result is the object type of the optional subexpression.
      CS.addConstraint(ConstraintKind::OptionalObject,
                       CS.getType(expr->getSubExpr()), objectTy,
                       locator);
      return objectTy;
    }
    
    Type visitOptionalEvaluationExpr(OptionalEvaluationExpr *expr) {
      // The operand must be coercible to T? for some type T.  We'd
      // like this to be the smallest possible nesting level of
      // optional types, e.g. T? over T??; otherwise we don't really
      // have a preference.
      auto valueTy = CS.createTypeVariable(CS.getConstraintLocator(expr),
                                           TVO_PrefersSubtypeBinding |
                                           TVO_CanBindToNoEscape);

      Type optTy = getOptionalType(expr->getSubExpr()->getLoc(), valueTy);
      if (!optTy)
        return Type();

      CS.addConstraint(ConstraintKind::Conversion,
                       CS.getType(expr->getSubExpr()), optTy,
                       CS.getConstraintLocator(expr));
      return optTy;
    }

    Type visitForceValueExpr(ForceValueExpr *expr) {
      // Force-unwrap an optional of type T? to produce a T.
      auto locator = CS.getConstraintLocator(expr);

      auto objectTy = CS.createTypeVariable(locator,
                                            TVO_PrefersSubtypeBinding |
                                            TVO_CanBindToLValue |
                                            TVO_CanBindToNoEscape);

      auto *valueExpr = expr->getSubExpr();
      // It's invalid to force unwrap `nil` literal e.g. `_ = nil!` or
      // `_ = (try nil)!` and similar constructs.
      if (auto *nilLiteral = dyn_cast<NilLiteralExpr>(
              valueExpr->getSemanticsProvidingExpr())) {
        CS.recordFix(SpecifyContextualTypeForNil::create(
            CS, CS.getConstraintLocator(nilLiteral)));
      }

      // The result is the object type of the optional subexpression.
      CS.addConstraint(ConstraintKind::OptionalObject, CS.getType(valueExpr),
                       objectTy, locator);
      return objectTy;
    }

    Type visitOpenExistentialExpr(OpenExistentialExpr *expr) {
      llvm_unreachable("Already type-checked");
    }
    Type visitMakeTemporarilyEscapableExpr(MakeTemporarilyEscapableExpr *expr) {
      llvm_unreachable("Already type-checked");
    }
    Type visitKeyPathApplicationExpr(KeyPathApplicationExpr *expr) {
      // This should only appear in already-type-checked solutions, but we may
      // need to re-check for failure diagnosis.
      auto locator = CS.getConstraintLocator(expr);
      auto projectedTy = CS.createTypeVariable(locator,
                                               TVO_CanBindToLValue |
                                               TVO_CanBindToNoEscape);
      CS.addKeyPathApplicationConstraint(CS.getType(expr->getKeyPath()),
                                         CS.getType(expr->getBase()),
                                         projectedTy,
                                         locator);
      return projectedTy;
    }
    
    Type visitEnumIsCaseExpr(EnumIsCaseExpr *expr) {
      return CS.getASTContext().getBoolType();
    }

    Type visitLazyInitializerExpr(LazyInitializerExpr *expr) {
      llvm_unreachable("Already type-checked");
    }

    Type visitEditorPlaceholderExpr(EditorPlaceholderExpr *E) {
      auto *locator = CS.getConstraintLocator(E);

      if (auto *placeholderRepr = E->getPlaceholderTypeRepr()) {
        // Let's try to use specified type, if that's impossible,
        // fallback to a type variable.
        if (auto preferredTy = resolveTypeReferenceInExpression(
                placeholderRepr, TypeResolverContext::InExpression, locator))
          return preferredTy;
      }

      // A placeholder may have any type, but default to Void type if
      // otherwise unconstrained.
      auto *placeholderTy =
          CS.createTypeVariable(locator, TVO_CanBindToNoEscape);

      CS.addConstraint(ConstraintKind::Defaultable, placeholderTy,
                       TupleType::getEmpty(CS.getASTContext()), locator);

      return placeholderTy;
    }

    Type visitObjCSelectorExpr(ObjCSelectorExpr *E) {
      // #selector only makes sense when we have the Objective-C
      // runtime.
      auto &ctx = CS.getASTContext();
      if (!ctx.LangOpts.EnableObjCInterop) {
        ctx.Diags.diagnose(E->getLoc(), diag::expr_selector_no_objc_runtime);
        return nullptr;
      }

      
      // Make sure we can reference ObjectiveC.Selector.
      // FIXME: Fix-It to add the import?
      auto type = CS.getASTContext().getSelectorType();
      if (!type) {
        ctx.Diags.diagnose(E->getLoc(), diag::expr_selector_module_missing);
        return nullptr;
      }

      return type;
    }

    Type visitKeyPathExpr(KeyPathExpr *E) {
      if (E->isObjC())
        return CS.getType(E->getObjCStringLiteralExpr());
      
      auto kpDecl = CS.getASTContext().getKeyPathDecl();
      
      if (!kpDecl) {
        auto &de = CS.getASTContext().Diags;
        de.diagnose(E->getLoc(), diag::expr_keypath_no_keypath_type);
        return ErrorType::get(CS.getASTContext());
      }
      
      // For native key paths, traverse the key path components to set up
      // appropriate type relationships at each level.
      auto rootLocator =
          CS.getConstraintLocator(E, ConstraintLocator::KeyPathRoot);
      auto locator = CS.getConstraintLocator(E);
      auto *root = CS.createTypeVariable(rootLocator, TVO_CanBindToNoEscape |
                                                          TVO_CanBindToHole);

      // If a root type was explicitly given, then resolve it now.
      if (auto rootRepr = E->getExplicitRootType()) {
        const auto rootObjectTy = resolveTypeReferenceInExpression(
            rootRepr, TypeResolverContext::InExpression, locator);
        if (!rootObjectTy || rootObjectTy->hasError())
          return Type();

        CS.setType(rootRepr, rootObjectTy);
        // Allow \Derived.property to be inferred as \Base.property to
        // simulate a sort of covariant conversion from
        // KeyPath<Derived, T> to KeyPath<Base, T>.
        CS.addConstraint(ConstraintKind::Subtype, rootObjectTy, root,
                         rootLocator);
      }

      bool didOptionalChain = false;
      // We start optimistically from an lvalue base.
      Type base = LValueType::get(root);

      SmallVector<TypeVariableType *, 2> componentTypeVars;
      for (unsigned i : indices(E->getComponents())) {
        auto &component = E->getComponents()[i];
        auto memberLocator = CS.getConstraintLocator(
            locator, LocatorPathElt::KeyPathComponent(i));
        auto resultLocator = CS.getConstraintLocator(
            memberLocator, ConstraintLocator::KeyPathComponentResult);

        switch (auto kind = component.getKind()) {
        case KeyPathExpr::Component::Kind::Invalid:
          break;
        case KeyPathExpr::Component::Kind::CodeCompletion:
          // We don't know what the code completion might resolve to, so we are
          // creating a new type variable for its result, which might be a hole.
          base = CS.createTypeVariable(
              resultLocator,
              TVO_CanBindToLValue | TVO_CanBindToNoEscape | TVO_CanBindToHole);
          break;
        case KeyPathExpr::Component::Kind::UnresolvedProperty:
        // This should only appear in resolved ASTs, but we may need to
        // re-type-check the constraints during failure diagnosis.
        case KeyPathExpr::Component::Kind::Property: {
          auto memberTy = CS.createTypeVariable(resultLocator,
                                                TVO_CanBindToLValue |
                                                TVO_CanBindToNoEscape);
          componentTypeVars.push_back(memberTy);
          auto lookupName = kind == KeyPathExpr::Component::Kind::UnresolvedProperty
            ? DeclNameRef(component.getUnresolvedDeclName()) // FIXME: type change needed
            : component.getDeclRef().getDecl()->createNameRef();
          
          auto refKind = lookupName.isSimpleName()
            ? FunctionRefKind::Unapplied
            : FunctionRefKind::Compound;
          CS.addValueMemberConstraint(base, lookupName,
                                      memberTy,
                                      CurDC,
                                      refKind,
                                      /*outerAlternatives=*/{},
                                      memberLocator);
          base = memberTy;
          break;
        }
          
        case KeyPathExpr::Component::Kind::UnresolvedSubscript:
        // Subscript should only appear in resolved ASTs, but we may need to
        // re-type-check the constraints during failure diagnosis.
        case KeyPathExpr::Component::Kind::Subscript: {
          auto *args = component.getSubscriptArgs();
          base = addSubscriptConstraints(E, base, /*decl*/ nullptr, args,
                                         memberLocator, &componentTypeVars);

          auto &ctx = CS.getASTContext();
          // All of the type variables that appear in subscript arguments
          // need to be connected to a key path, otherwise it won't be
          // possible to determine sendability of the key path type if
          // the arguments are disconnected from it before being fully
          // resolved.
          if (args &&
              ctx.LangOpts.hasFeature(Feature::InferSendableFromCaptures)) {
            SmallPtrSet<TypeVariableType *, 2> referencedVars;
            for (const auto &arg : *args) {
              CS.getType(arg.getExpr())->getTypeVariables(referencedVars);
            }

            componentTypeVars.append(referencedVars.begin(),
                                     referencedVars.end());
          }
          break;
        }

        case KeyPathExpr::Component::Kind::TupleElement: {
          // Note: If implemented, the logic in `getCalleeLocator` will need
          // updating to return the correct callee locator for this.
          llvm_unreachable("not implemented");
          break;
        }
                
        case KeyPathExpr::Component::Kind::OptionalChain: {
          didOptionalChain = true;

          // We can't assign an optional back through an optional chain
          // today. Force the base to an rvalue.
          auto rvalueTy = CS.createTypeVariable(resultLocator,
                                                TVO_CanBindToNoEscape);
          componentTypeVars.push_back(rvalueTy);
          CS.addConstraint(ConstraintKind::Equal, base, rvalueTy,
                           resultLocator);

          base = rvalueTy;
          LLVM_FALLTHROUGH;
        }
        case KeyPathExpr::Component::Kind::OptionalForce: {
          auto optionalObjTy = CS.createTypeVariable(resultLocator,
                                                     TVO_CanBindToLValue |
                                                     TVO_CanBindToNoEscape);
          componentTypeVars.push_back(optionalObjTy);

          CS.addConstraint(ConstraintKind::OptionalObject, base, optionalObjTy,
                           resultLocator);
          base = optionalObjTy;
          break;
        }
        
        case KeyPathExpr::Component::Kind::OptionalWrap: {
          // This should only appear in resolved ASTs, but we may need to
          // re-type-check the constraints during failure diagnosis.
          base = OptionalType::get(base);
          break;
        }
        case KeyPathExpr::Component::Kind::Identity:
          break;
        case KeyPathExpr::Component::Kind::DictionaryKey:
          llvm_unreachable("DictionaryKey only valid in #keyPath");
          break;
        }

        // By now, `base` is the result type of this component. Set it in the
        // constraint system so we can find it later.
        CS.setType(E, i, base);
      }

      auto valueLocator =
        CS.getConstraintLocator(E, ConstraintLocator::KeyPathValue);

      // If there was an optional chaining component, the end result must be
      // optional.
      if (didOptionalChain) {
        auto objTy = CS.createTypeVariable(locator, TVO_CanBindToNoEscape |
                                                        TVO_CanBindToHole);
        componentTypeVars.push_back(objTy);

        auto optTy = OptionalType::get(objTy);
        CS.addConstraint(ConstraintKind::Conversion, base, optTy, valueLocator);
        base = optTy;
      }

      // If we have a malformed KeyPathExpr e.g. let _: KeyPath<A, C> = \A
      // let's record a AllowKeyPathMissingComponent fix.
      if (E->hasSingleInvalidComponent()) {
        (void)CS.recordFix(AllowKeyPathWithoutComponents::create(CS, locator));
      }


      auto *value = CS.createTypeVariable(valueLocator, TVO_CanBindToNoEscape |
                                                            TVO_CanBindToHole);
      CS.addConstraint(ConstraintKind::Equal, base, value, valueLocator);
      CS.recordKeyPath(E, root, value, CurDC);

      // The result is a KeyPath from the root to the end component.
      // The type of key path depends on the overloads chosen for the key
      // path components.
      auto typeLoc =
          CS.getConstraintLocator(locator, LocatorPathElt::KeyPathType());

      Type kpTy = CS.createTypeVariable(typeLoc, TVO_CanBindToNoEscape |
                                                     TVO_CanBindToHole);

      CS.addKeyPathConstraint(kpTy, root, value, componentTypeVars, locator);

      // Add a fallback constraint so we have an anchor to use for
      // capability inference when there is no context.
      CS.addUnsolvedConstraint(Constraint::create(
          CS, ConstraintKind::FallbackType, kpTy,
          BoundGenericType::get(kpDecl, /*parent=*/Type(), {root, value}),
          CS.getConstraintLocator(E, ConstraintLocator::FallbackType)));

      return kpTy;
    }

    Type visitCurrentContextIsolationExpr(CurrentContextIsolationExpr *E) {
      // If this was expanded from the builtin `#isolation` macro, it
      // already has a type.
      if (auto type = E->getType())
        return type;

      // Otherwise, this was created for a `for await` loop, where its
      // type is always `(any Actor)?`.
      auto actorProto = CS.getASTContext().getProtocol(
          KnownProtocolKind::Actor);
      return OptionalType::get(actorProto->getDeclaredExistentialType());
    }

    Type visitExtractFunctionIsolationExpr(ExtractFunctionIsolationExpr *E) {
      llvm_unreachable("found ExtractFunctionIsolationExpr in CSGen");
    }

    Type visitKeyPathDotExpr(KeyPathDotExpr *E) {
      llvm_unreachable("found KeyPathDotExpr in CSGen");
    }

    Type visitSingleValueStmtExpr(SingleValueStmtExpr *E) {
      llvm_unreachable("Handled by the walker directly");
    }

    Type visitOneWayExpr(OneWayExpr *expr) {
      auto locator = CS.getConstraintLocator(expr);
      auto resultTypeVar = CS.createTypeVariable(locator, 0);
      CS.addConstraint(ConstraintKind::OneWayEqual, resultTypeVar,
                       CS.getType(expr->getSubExpr()), locator);
      return resultTypeVar;
    }

    Type visitTapExpr(TapExpr *expr) {
      DeclContext *varDC = expr->getVar()->getDeclContext();
      assert(varDC == CS.DC || (varDC && isa<AbstractClosureExpr>(varDC)) &&
             "TapExpr var should be in the same DeclContext we're checking it in!");
      
      auto locator = CS.getConstraintLocator(expr);
      auto tv = CS.createTypeVariable(locator, TVO_CanBindToNoEscape);

      if (auto subExpr = expr->getSubExpr()) {
        auto subExprType = CS.getType(subExpr);
        CS.addConstraint(ConstraintKind::Bind, subExprType, tv, locator);
      }

      return tv;
    }

    Type visitTypeJoinExpr(TypeJoinExpr *expr) {
      auto *locator = CS.getConstraintLocator(expr);
      SmallVector<std::pair<Type, ConstraintLocator *>, 4> elements;
      elements.reserve(expr->getNumElements());

      if (auto *SVE = expr->getSingleValueStmtExpr()) {
        // If we have a SingleValueStmtExpr, form a join of the branch types.
        SmallVector<Expr *, 4> scratch;
        auto branches = SVE->getResultExprs(scratch);
        for (auto idx : indices(branches)) {
          auto *eltLoc = CS.getConstraintLocator(
              SVE, {LocatorPathElt::SingleValueStmtResult(idx)});
          elements.emplace_back(CS.getType(branches[idx]), eltLoc);
        }
      } else {
        for (auto *element : expr->getElements()) {
          elements.emplace_back(CS.getType(element),
                                CS.getConstraintLocator(element));
        }
      }

      Type resultTy;

      if (auto *var = expr->getVar()) {
        resultTy = CS.getType(var);
      } else {
        resultTy = expr->getType();
      }

      assert(resultTy);

      // If we have a single branch of a SingleValueStmtExpr, we want a
      // conversion of the result, not a join, which would skip the conversion.
      // This is needed to ensure we apply the Void/Never conversions.
      if (elements.size() == 1 && expr->getSingleValueStmtExpr()) {
        auto &elt = elements[0];
        CS.addConstraint(ConstraintKind::Conversion, elt.first,
                         resultTy, elt.second);
        return resultTy;
      }

      // The type of a join expression is obtained by performing
      // a "join-meet" operation on deduced types of its elements
      // and the underlying variable.
      auto joinedTy = CS.addJoinConstraint(locator, elements);

      CS.addConstraint(ConstraintKind::Equal, resultTy, joinedTy, locator);
      return resultTy;
    }

    /// Lookup all macros with the given macro name.
    SmallVector<OverloadChoice, 1> lookupMacros(Identifier moduleName,
                                                Identifier macroName,
                                                FunctionRefKind functionRefKind,
                                                MacroRoles roles) {
      SmallVector<OverloadChoice, 1> choices;
      auto results = namelookup::lookupMacros(CurDC, DeclNameRef(moduleName),
                                              DeclNameRef(macroName), roles);
      for (const auto &result : results) {
        OverloadChoice choice = OverloadChoice(Type(), result, functionRefKind);
        choices.push_back(choice);
      }

      // FIXME: At some point, we need to check for function-like macros without
      // arguments and vice-versa.

      return choices;
    }

    Type visitMacroExpansionExpr(MacroExpansionExpr *expr) {
      // Assign a discriminator.
      (void)expr->getDiscriminator();

      auto &ctx = CS.getASTContext();
      auto locator = CS.getConstraintLocator(expr);

      CS.associateArgumentList(locator, expr->getArgs());

      // Look up the macros with this name.
      auto moduleIdent = expr->getModuleName().getBaseIdentifier();
      auto macroIdent = expr->getMacroName().getBaseIdentifier();
      FunctionRefKind functionRefKind = FunctionRefKind::SingleApply;
      auto macros = lookupMacros(moduleIdent, macroIdent, functionRefKind,
                                 expr->getMacroRoles());
      if (macros.empty()) {
        ctx.Diags.diagnose(expr->getMacroNameLoc(), diag::macro_undefined,
                           macroIdent)
            .highlight(expr->getMacroNameLoc().getSourceRange());
        return Type();
      }

      // Introduce an overload set for the macro reference.
      auto macroRefType = Type(CS.createTypeVariable(locator, 0));
      CS.addOverloadSet(macroRefType, macros, CurDC, locator);

      // Add explicit generic arguments, if there were any.
      if (expr->getGenericArgsRange().isValid()) {
        if (addSpecializationConstraint(
              CS.getConstraintLocator(expr), macroRefType,
              expr->getGenericArgs()))
          return Type();
      }

      // Form the applicable-function constraint. The result type
      // is the result of that call.
      SmallVector<AnyFunctionType::Param, 8> params;
      getMatchingParams(expr->getArgs(), params);

      Type resultType = CS.createTypeVariable(
          CS.getConstraintLocator(expr, ConstraintLocator::FunctionResult),
          TVO_CanBindToNoEscape);

      CS.addConstraint(
          ConstraintKind::ApplicableFunction,
          FunctionType::get(params, resultType),
          macroRefType,
          CS.getConstraintLocator(
            expr, ConstraintLocator::ApplyFunction));

      return resultType;
    }

    static bool isTriggerFallbackDiagnosticBuiltin(UnresolvedDotExpr *UDE,
                                                   ASTContext &Context) {
      auto *DRE = dyn_cast<DeclRefExpr>(UDE->getBase());
      if (!DRE)
        return false;

      if (DRE->getDecl() != Context.TheBuiltinModule)
        return false;

      auto member = UDE->getName().getBaseName().userFacingName();
      return member.equals("trigger_fallback_diagnostic");
    }

    enum class TypeOperation { None,
                               Join,
                               JoinInout,
                               JoinMeta,
                               JoinNonexistent,
                               OneWay,
    };

    static TypeOperation getTypeOperation(UnresolvedDotExpr *UDE,
                                          ASTContext &Context) {
      auto *DRE = dyn_cast<DeclRefExpr>(UDE->getBase());
      if (!DRE)
        return TypeOperation::None;

      if (DRE->getDecl() != Context.TheBuiltinModule)
        return TypeOperation::None;

      return llvm::StringSwitch<TypeOperation>(
                 UDE->getName().getBaseIdentifier().str())
          .Case("one_way", TypeOperation::OneWay)
          .Case("type_join", TypeOperation::Join)
          .Case("type_join_inout", TypeOperation::JoinInout)
          .Case("type_join_meta", TypeOperation::JoinMeta)
          .Case("type_join_nonexistent", TypeOperation::JoinNonexistent)
          .Default(TypeOperation::None);
    }

    Type resultOfTypeOperation(TypeOperation op, ArgumentList *Args) {
      auto *lhs = Args->getExpr(0);
      auto *rhs = Args->getExpr(1);

      switch (op) {
      case TypeOperation::None:
      case TypeOperation::OneWay:
        llvm_unreachable(
            "We should have a valid type operation at this point!");

      case TypeOperation::Join: {
        auto lhsMeta = CS.getType(lhs)->getAs<MetatypeType>();
        auto rhsMeta = CS.getType(rhs)->getAs<MetatypeType>();
        if (!lhsMeta || !rhsMeta)
          llvm_unreachable("Unexpected argument types for Builtin.type_join!");

        auto &ctx = lhsMeta->getASTContext();

        auto join =
            Type::join(lhsMeta->getInstanceType(), rhsMeta->getInstanceType());

        if (!join)
          return ErrorType::get(ctx);

        return MetatypeType::get(*join, ctx)->getCanonicalType();
      }

      case TypeOperation::JoinInout: {
        auto lhsInOut = CS.getType(lhs)->getAs<InOutType>();
        auto rhsMeta = CS.getType(rhs)->getAs<MetatypeType>();
        if (!lhsInOut || !rhsMeta)
          llvm_unreachable("Unexpected argument types for Builtin.type_join!");

        auto &ctx = lhsInOut->getASTContext();

        auto join =
            Type::join(lhsInOut, rhsMeta->getInstanceType());

        if (!join)
          return ErrorType::get(ctx);

        return MetatypeType::get(*join, ctx)->getCanonicalType();
      }

      case TypeOperation::JoinMeta: {
        auto lhsMeta = CS.getType(lhs)->getAs<MetatypeType>();
        auto rhsMeta = CS.getType(rhs)->getAs<MetatypeType>();
        if (!lhsMeta || !rhsMeta)
          llvm_unreachable("Unexpected argument types for Builtin.type_join!");

        auto &ctx = lhsMeta->getASTContext();

        auto join = Type::join(lhsMeta, rhsMeta);

        if (!join)
          return ErrorType::get(ctx);

        return *join;
      }

      case TypeOperation::JoinNonexistent: {
        auto lhsMeta = CS.getType(lhs)->getAs<MetatypeType>();
        auto rhsMeta = CS.getType(rhs)->getAs<MetatypeType>();
        if (!lhsMeta || !rhsMeta)
          llvm_unreachable("Unexpected argument types for Builtin.type_join_nonexistent!");

        auto &ctx = lhsMeta->getASTContext();

        auto join =
            Type::join(lhsMeta->getInstanceType(), rhsMeta->getInstanceType());

        // Verify that we could not compute a join.
        if (join)
          llvm_unreachable("Unexpected result from join - it should not have been computable!");

        // The return value is unimportant.
        return MetatypeType::get(ctx.getAnyExistentialType())->getCanonicalType();
      }
      }
      llvm_unreachable("unhandled operation");
    }

    /// Assuming that we are solving for code completion, assign \p expr a fresh
    /// and unconstrained type variable as its type.
    void setTypeForArgumentIgnoredForCompletion(Expr *expr) {
      assert(CS.isForCodeCompletion());
      ConstraintSystem &CS = getConstraintSystem();

      if (auto closure = dyn_cast<ClosureExpr>(expr)) {
        FunctionType *closureTy =
            inferClosureType(closure, /*allowResultBindToHole=*/true);
        CS.setClosureType(closure, closureTy);
        CS.setType(closure, closureTy);
      } else {
        TypeVariableType *exprType = CS.createTypeVariable(
            CS.getConstraintLocator(expr),
            TVO_CanBindToLValue | TVO_CanBindToInOut | TVO_CanBindToNoEscape |
                TVO_CanBindToHole);
        CS.setType(expr, exprType);
      }
    }
  };

  class ConstraintWalker : public ASTWalker {
    ConstraintGenerator &CG;

  public:
    ConstraintWalker(ConstraintGenerator &CG) : CG(CG) { }

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

    PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
      auto &CS = CG.getConstraintSystem();

      if (CS.isArgumentIgnoredForCodeCompletion(expr)) {
        CG.setTypeForArgumentIgnoredForCompletion(expr);
        return Action::SkipNode(expr);
      }

      if (auto *SVE = dyn_cast<SingleValueStmtExpr>(expr)) {
        if (CS.generateConstraints(SVE))
          return Action::Stop();
        return Action::SkipNode(expr);
      }

      // Note that the subexpression of a #selector expression is
      // unevaluated.
      if (auto sel = dyn_cast<ObjCSelectorExpr>(expr)) {
        auto *subExpr = sel->getSubExpr()->getSemanticsProvidingExpr();
        CG.getConstraintSystem().UnevaluatedRootExprs.insert(subExpr);
      }

      // Check an objc key-path expression, which fills in its semantic
      // expression as a string literal.
      if (auto keyPath = dyn_cast<KeyPathExpr>(expr)) {
        if (keyPath->isObjC()) {
          auto &cs = CG.getConstraintSystem();
          (void)TypeChecker::checkObjCKeyPathExpr(cs.DC, keyPath);
        }
      }

      // Generate constraints for each of the entries in the capture list.
      if (auto captureList = dyn_cast<CaptureListExpr>(expr)) {
        TypeChecker::diagnoseDuplicateCaptureVars(captureList);
      }

      // Both multi- and single-statement closures now behave the same way
      // when it comes to constraint generation.
      if (auto closure = dyn_cast<ClosureExpr>(expr)) {
        auto &CS = CG.getConstraintSystem();
        auto closureType = CG.visitClosureExpr(closure);
        if (!closureType)
          return Action::Stop();

        CS.setType(expr, closureType);
        return Action::SkipNode(expr);
      }

      // Don't visit CoerceExpr with an empty sub expression. They may occur
      // if the body of a closure was not visited while pre-checking because
      // of an error in the closure's signature.
      if (auto coerceExpr = dyn_cast<CoerceExpr>(expr)) {
        if (!coerceExpr->getSubExpr()) {
          return Action::SkipNode(expr);
        }
      }

      // Don't visit TernaryExpr with empty sub expressions. They may occur
      // if the body of a closure was not visited while pre-checking because
      // of an error in the closure's signature.
      if (auto *ternary = dyn_cast<TernaryExpr>(expr)) {
        if (!ternary->getThenExpr() || !ternary->getElseExpr())
          return Action::SkipNode(expr);
      }

      if (CS.isForCodeCompletion()) {
        SmallVector<Expr *, 2> ignoredArgs;
        getArgumentsAfterCodeCompletionToken(expr, CS, ignoredArgs);
        for (auto ignoredArg : ignoredArgs) {
          CS.markArgumentIgnoredForCodeCompletion(ignoredArg);
        }
      }

      if (auto *expansion = dyn_cast<PackExpansionExpr>(expr)) {
        CG.pushPackExpansionExpr(expansion);
      }

      return Action::Continue(expr);
    }

    /// Once we've visited the children of the given expression,
    /// generate constraints from the expression.
    PostWalkResult<Expr *> walkToExprPost(Expr *expr) override {
      auto &CS = CG.getConstraintSystem();
      // Translate special type-checker Builtin calls into simpler expressions.
      if (auto *apply = dyn_cast<ApplyExpr>(expr)) {
        auto fnExpr = apply->getFn();
        if (auto *UDE = dyn_cast<UnresolvedDotExpr>(fnExpr)) {
          auto typeOperation =
              ConstraintGenerator::getTypeOperation(UDE, CS.getASTContext());

          if (typeOperation == ConstraintGenerator::TypeOperation::OneWay) {
            // For a one-way constraint, create the OneWayExpr node.
            auto *unaryArg = apply->getArgs()->getUnlabeledUnaryExpr();
            assert(unaryArg);
            expr = new (CS.getASTContext()) OneWayExpr(unaryArg);
          } else if (typeOperation !=
                         ConstraintGenerator::TypeOperation::None) {
            // Handle the Builtin.type_join* family of calls by replacing
            // them with dot_self_expr of type_expr with the type being the
            // result of the join.
            auto joinMetaTy =
                CG.resultOfTypeOperation(typeOperation, apply->getArgs());
            auto joinTy = joinMetaTy->castTo<MetatypeType>();

            auto *TE = TypeExpr::createImplicit(joinTy->getInstanceType(),
                                                CS.getASTContext());
            CS.cacheType(TE);

            auto *DSE = new (CS.getASTContext())
                DotSelfExpr(TE, SourceLoc(), SourceLoc(), CS.getType(TE));
            DSE->setImplicit();
            CS.cacheType(DSE);

            return Action::Continue(DSE);
          }
        }
      }
      if (auto type = CG.visit(expr)) {
        auto simplifiedType = CS.simplifyType(type);
        CS.setType(expr, simplifiedType);
        return Action::Continue(expr);
      }
      return Action::Stop();
    }

    /// Ignore statements.
    PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
      return Action::SkipNode(stmt);
    }

    /// Ignore declarations.
    PreWalkAction walkToDeclPre(Decl *decl) override {
      return Action::SkipNode();
    }
  };
} // end anonymous namespace

static Expr *generateConstraintsFor(ConstraintSystem &cs, Expr *expr,
                                    DeclContext *DC) {
  // Walk the expression, generating constraints.
  ConstraintGenerator cg(cs, DC);
  ConstraintWalker cw(cg);

  Expr *result = expr->walk(cw);

  if (result)
    cs.optimizeConstraints(result);

  return result;
}

bool ConstraintSystem::generateWrappedPropertyTypeConstraints(
    VarDecl *wrappedVar, Type initializerType, Type propertyType) {
  auto dc = wrappedVar->getInnermostDeclContext();

  Type wrappedValueType;
  Type wrapperType;
  auto wrapperAttributes = wrappedVar->getAttachedPropertyWrappers();
  for (unsigned i : indices(wrapperAttributes)) {
    // FIXME: We should somehow pass an OpenUnboundGenericTypeFn to
    // AttachedPropertyWrapperTypeRequest::evaluate to open up unbound
    // generics on the fly.
    Type rawWrapperType = wrappedVar->getAttachedPropertyWrapperType(i);
    auto wrapperInfo = wrappedVar->getAttachedPropertyWrapperTypeInfo(i);
    if (rawWrapperType->hasError() || !wrapperInfo)
      return true;

    auto *typeExpr = wrapperAttributes[i]->getTypeExpr();

    if (!wrappedValueType) {
      // Equate the outermost wrapper type to the initializer type.
      auto *locator = getConstraintLocator(typeExpr);
      wrapperType =
          replaceInferableTypesWithTypeVars(rawWrapperType, locator);
      if (initializerType)
        addConstraint(ConstraintKind::Equal, wrapperType, initializerType, locator);
    } else {
      // The former wrappedValue type must be equal to the current wrapper type
      auto *locator = getConstraintLocator(
          typeExpr, LocatorPathElt::WrappedValue(wrapperType));
      wrapperType =
          replaceInferableTypesWithTypeVars(rawWrapperType, locator);
      addConstraint(ConstraintKind::Equal, wrapperType, wrappedValueType, locator);
    }

    setType(typeExpr, wrapperType);

    wrappedValueType = wrapperType->getTypeOfMember(
        dc->getParentModule(), wrapperInfo.valueVar);
  }

  // The property type must be equal to the wrapped value type
  addConstraint(
      ConstraintKind::Equal, propertyType, wrappedValueType,
      getConstraintLocator(
          wrappedVar, LocatorPathElt::ContextualType(CTP_WrappedProperty)));

  ContextualTypeInfo contextInfo(wrappedValueType, CTP_WrappedProperty);
  setContextualInfo(wrappedVar, contextInfo);
  return false;
}

/// Generate additional constraints for the pattern of an initialization.
static bool generateInitPatternConstraints(ConstraintSystem &cs,
                                           SyntacticElementTarget target,
                                           Expr *initializer) {
  auto locator = cs.getConstraintLocator(
      initializer, LocatorPathElt::ContextualType(CTP_Initialization));

  Type patternType;
  if (auto pattern = target.getInitializationPattern()) {
    patternType = cs.generateConstraints(
        pattern, locator, target.shouldBindPatternVarsOneWay(),
        target.getInitializationPatternBindingDecl(),
        target.getInitializationPatternBindingIndex());
  } else {
    patternType = cs.createTypeVariable(locator, TVO_CanBindToNoEscape);
  }

  if (auto wrappedVar = target.getInitializationWrappedVar())
    return cs.generateWrappedPropertyTypeConstraints(
        wrappedVar, cs.getType(target.getAsExpr()), patternType);

  // Add a conversion constraint between the types.
  cs.addConstraint(ConstraintKind::Conversion, cs.getType(target.getAsExpr()),
                   patternType, locator, /*isFavored*/true);

  return false;
}

/// Generate constraints for a for-in statement preamble where the expression
/// is a `PackExpansionExpr`.
static std::optional<PackIterationInfo>
generateForEachStmtConstraints(ConstraintSystem &cs, DeclContext *dc,
                               PackExpansionExpr *expansion, Type patternType) {
  auto packIterationInfo = PackIterationInfo();
  auto elementLocator = cs.getConstraintLocator(
      expansion, ConstraintLocator::SequenceElementType);

  {
    SyntacticElementTarget target(expansion, dc, CTP_Unused,
                                  /*contextualType=*/Type(),
                                  /*isDiscarded=*/false);

    if (cs.generateConstraints(target))
      return std::nullopt;

    cs.setTargetFor(expansion, target);
  }

  auto elementType = cs.getType(expansion->getPatternExpr());

  cs.addConstraint(ConstraintKind::Conversion, elementType, patternType,
                   elementLocator);

  packIterationInfo.patternType = patternType;
  return packIterationInfo;
}

/// Generate constraints for a for-in statement preamble, expecting an
/// expression that conforms to `Swift.Sequence`.
static std::optional<SequenceIterationInfo>
generateForEachStmtConstraints(ConstraintSystem &cs, DeclContext *dc,
                               ForEachStmt *stmt, Pattern *typeCheckedPattern,
                               bool shouldBindPatternVarsOneWay,
                               bool ignoreForEachWhereClause) {
  ASTContext &ctx = cs.getASTContext();
  bool isAsync = stmt->getAwaitLoc().isValid();
  auto *sequenceExpr = stmt->getParsedSequence();
  auto contextualLocator = cs.getConstraintLocator(
      sequenceExpr, LocatorPathElt::ContextualType(CTP_ForEachSequence));
  auto elementLocator = cs.getConstraintLocator(
      sequenceExpr, ConstraintLocator::SequenceElementType);

  auto sequenceIterationInfo = SequenceIterationInfo();

  // The expression type must conform to the Sequence protocol.
  auto sequenceProto = TypeChecker::getProtocol(
      cs.getASTContext(), stmt->getForLoc(),
      isAsync ? KnownProtocolKind::AsyncSequence : KnownProtocolKind::Sequence);
  if (!sequenceProto)
    return std::nullopt;

  std::string name;
  {
    if (auto np = dyn_cast_or_null<NamedPattern>(stmt->getPattern()))
      name = "$"+np->getBoundName().str().str();
    name += "$generator";
  }

  auto *makeIteratorVar = new (ctx)
      VarDecl(/*isStatic=*/false, VarDecl::Introducer::Var,
              sequenceExpr->getStartLoc(), ctx.getIdentifier(name), dc);
  makeIteratorVar->setImplicit();

  // FIXME: Apply `nonisolated(unsafe)` to async iterators.
  //
  // Async iterators are not `Sendable`; they're only meant to be used from
  // the isolation domain that creates them. But the `next()` method runs on
  // the generic executor, so calling it from an actor-isolated context passes
  // non-`Sendable` state across the isolation boundary. `next()` should
  // inherit the isolation of the caller, but for now, use the opt out.
  if (isAsync) {
    auto *nonisolated = new (ctx)
        NonisolatedAttr(/*unsafe=*/true, /*implicit=*/true);
    makeIteratorVar->getAttrs().add(nonisolated);
  }

  // First, let's form a call from sequence to `.makeIterator()` and save
  // that in a special variable which is going to be used by SILGen.
  {
    FuncDecl *makeIterator = isAsync ? ctx.getAsyncSequenceMakeAsyncIterator()
                                     : ctx.getSequenceMakeIterator();

    auto *makeIteratorRef = UnresolvedDotExpr::createImplicit(
        ctx, sequenceExpr, makeIterator->getName());
    makeIteratorRef->setFunctionRefKind(FunctionRefKind::SingleApply);

    auto *makeIteratorCall =
        CallExpr::createImplicitEmpty(ctx, makeIteratorRef);

    Pattern *pattern = NamedPattern::createImplicit(ctx, makeIteratorVar);
    auto *PB = PatternBindingDecl::createImplicit(
        ctx, StaticSpellingKind::None, pattern, makeIteratorCall, dc);

    auto makeIteratorTarget = SyntacticElementTarget::forInitialization(
        makeIteratorCall, /*patternType=*/Type(), PB, /*index=*/0,
        /*shouldBindPatternsOneWay=*/false);

    ContextualTypeInfo contextInfo(sequenceProto->getDeclaredInterfaceType(),
                                   CTP_ForEachSequence);
    cs.setContextualInfo(sequenceExpr, contextInfo);

    if (cs.generateConstraints(makeIteratorTarget))
      return std::nullopt;

    sequenceIterationInfo.makeIteratorVar = PB;

    // Type of sequence expression has to conform to Sequence protocol.
    //
    // Note that the following emulates having `$generator` separately
    // type-checked by introducing a `TVO_PrefersSubtypeBinding` type
    // variable that would make sure that result of `.makeIterator` would
    // get ranked standalone.
    {
      auto *externalIteratorType = cs.createTypeVariable(
          cs.getConstraintLocator(sequenceExpr), TVO_PrefersSubtypeBinding);

      cs.addConstraint(ConstraintKind::Equal, externalIteratorType,
                       cs.getType(sequenceExpr),
                       externalIteratorType->getImpl().getLocator());

      cs.addConstraint(ConstraintKind::ConformsTo, externalIteratorType,
                       sequenceProto->getDeclaredInterfaceType(),
                       contextualLocator);

      sequenceIterationInfo.sequenceType = cs.getType(sequenceExpr);
    }

    cs.setTargetFor({PB, /*index=*/0}, makeIteratorTarget);
  }

  // Now, result type of `.makeIterator()` is used to form a call to
  // `.next()`. `next()` is called on each iteration of the loop.
  {
    FuncDecl *nextFn = 
        TypeChecker::getForEachIteratorNextFunction(dc, stmt->getForLoc(), isAsync);
    Identifier nextId = nextFn ? nextFn->getName().getBaseIdentifier()
                               : ctx.Id_next;
    TinyPtrVector<Identifier> labels;
    if (nextFn && nextFn->getParameters()->size() == 1)
      labels.push_back(ctx.Id_isolation);
    auto *nextRef = UnresolvedDotExpr::createImplicit(
        ctx,
        new (ctx) DeclRefExpr(makeIteratorVar, DeclNameLoc(stmt->getForLoc()),
                              /*Implicit=*/true),
        nextId, labels);
    nextRef->setFunctionRefKind(FunctionRefKind::Compound);

    ArgumentList *nextArgs;
    if (nextFn && nextFn->getParameters()->size() == 1) {
      auto isolationArg =
        new (ctx) CurrentContextIsolationExpr(stmt->getForLoc(), Type());
      nextArgs = ArgumentList::forImplicitUnlabeled(ctx, { isolationArg });
    } else {
      nextArgs = ArgumentList::createImplicit(ctx, {});
    }
    Expr *nextCall = CallExpr::createImplicit(ctx, nextRef, nextArgs);

    // `next` is always async but witness might not be throwing
    if (isAsync) {
      nextCall =
          AwaitExpr::createImplicit(ctx, nextCall->getLoc(), nextCall);
    }

    // The iterator type must conform to IteratorProtocol.
    {
      ProtocolDecl *iteratorProto = TypeChecker::getProtocol(
          cs.getASTContext(), stmt->getForLoc(),
          isAsync ? KnownProtocolKind::AsyncIteratorProtocol
                  : KnownProtocolKind::IteratorProtocol);
      if (!iteratorProto)
        return std::nullopt;

      ContextualTypeInfo contextInfo(iteratorProto->getDeclaredInterfaceType(),
                                     CTP_ForEachSequence);
      cs.setContextualInfo(nextRef->getBase(), contextInfo);
    }

    SyntacticElementTarget nextTarget(nextCall, dc, CTP_Unused,
                                      /*contextualType=*/Type(),
                                      /*isDiscarded=*/false);
    if (cs.generateConstraints(nextTarget, FreeTypeVariableBinding::Disallow))
      return std::nullopt;

    sequenceIterationInfo.nextCall = nextTarget.getAsExpr();
    cs.setTargetFor(sequenceIterationInfo.nextCall, nextTarget);
  }

  // Generate constraints for the pattern.
  Type initType =
      cs.generateConstraints(typeCheckedPattern, elementLocator,
                             shouldBindPatternVarsOneWay, nullptr, 0);
  if (!initType)
    return std::nullopt;

  // Add a conversion constraint between the element type of the sequence
  // and the type of the element pattern.
  auto *elementTypeLoc = cs.getConstraintLocator(
      elementLocator, ConstraintLocator::OptionalPayload);
  auto elementType = cs.createTypeVariable(elementTypeLoc,
                                           /*flags=*/0);
  {
    auto nextType = cs.getType(sequenceIterationInfo.nextCall);
    cs.addConstraint(ConstraintKind::OptionalObject, nextType, elementType,
                     elementTypeLoc);
    cs.addConstraint(ConstraintKind::Conversion, elementType, initType,
                     elementLocator);
  }

  // Generate constraints for the "where" expression, if there is one.
  auto *whereExpr = stmt->getWhere();
  if (whereExpr && !ignoreForEachWhereClause) {
    Type boolType = dc->getASTContext().getBoolType();
    if (!boolType)
      return std::nullopt;

    SyntacticElementTarget whereTarget(whereExpr, dc, CTP_Condition, boolType,
                                       /*isDiscarded=*/false);
    if (cs.generateConstraints(whereTarget, FreeTypeVariableBinding::Disallow))
      return std::nullopt;

    cs.setTargetFor(whereExpr, whereTarget);

    ContextualTypeInfo contextInfo(boolType, CTP_Condition);
    cs.setContextualInfo(whereExpr, contextInfo);
  }

  // Populate all of the information for a for-each loop.
  sequenceIterationInfo.elementType = elementType;
  sequenceIterationInfo.initType = initType;

  return sequenceIterationInfo;
}

static std::optional<SyntacticElementTarget>
generateForEachPreambleConstraints(ConstraintSystem &cs,
                                   SyntacticElementTarget target) {
  ForEachStmt *stmt = target.getAsForEachStmt();
  auto *forEachExpr = stmt->getParsedSequence();
  auto *dc = target.getDeclContext();

  auto elementLocator = cs.getConstraintLocator(
      forEachExpr, ConstraintLocator::SequenceElementType);

  Pattern *pattern = TypeChecker::resolvePattern(stmt->getPattern(), dc,
                                                 /*isStmtCondition*/ false);
  if (!pattern)
    return std::nullopt;
  target.setPattern(pattern);

  auto contextualPattern = ContextualPattern::forRawPattern(pattern, dc);

  if (TypeChecker::typeCheckPattern(contextualPattern)->hasError()) {
    return std::nullopt;
  }

  if (isa<PackExpansionExpr>(forEachExpr)) {
    auto *expansion = cast<PackExpansionExpr>(forEachExpr);

    // Generate constraints for the pattern.
    Type patternType = cs.generateConstraints(
        pattern, elementLocator, target.shouldBindPatternVarsOneWay(), nullptr,
        0);
    if (!patternType)
      return std::nullopt;

    if (auto whereClause = stmt->getWhere()) {
      cs.recordFix(IgnoreWhereClauseInPackIteration::create(
          cs, cs.getConstraintLocator(whereClause)));
    }

    auto packIterationInfo =
        generateForEachStmtConstraints(cs, dc, expansion, patternType);
    if (!packIterationInfo) {
      return std::nullopt;
    }

    target.getForEachStmtInfo() = *packIterationInfo;
  } else {
    auto sequenceIterationInfo = generateForEachStmtConstraints(
        cs, dc, stmt, pattern, target.shouldBindPatternVarsOneWay(),
        target.ignoreForEachWhereClause());
    if (!sequenceIterationInfo) {
      return std::nullopt;
    }

    target.getForEachStmtInfo() = *sequenceIterationInfo;
  }
  return target;
}

bool ConstraintSystem::generateConstraints(
    SyntacticElementTarget &target,
    FreeTypeVariableBinding allowFreeTypeVariables) {
  if (Expr *expr = target.getAsExpr()) {
    // If the target requires an optional of some type, form a new appropriate
    // type variable and update the target's type with an optional of that
    // type variable.
    if (target.isOptionalSomePatternInit()) {
      assert(!target.getExprContextualType() &&
             "some pattern cannot have contextual type pre-configured");
      auto *convertTypeLocator = getConstraintLocator(
          expr, LocatorPathElt::ContextualType(
                    target.getExprContextualTypePurpose()));
      Type var = createTypeVariable(convertTypeLocator, TVO_CanBindToNoEscape);
      target.setExprConversionType(TypeChecker::getOptionalType(expr->getLoc(), var));
    }

    // If we have a parent return statement, record whether it's implied.
    if (auto *RS = target.getParentReturnStmt()) {
      if (RS->isImplied())
        recordImpliedResult(expr, ImpliedResultKind::Regular);
    }

    expr = buildTypeErasedExpr(expr, target.getDeclContext(),
                               target.getExprContextualType(),
                               target.getExprContextualTypePurpose());

    // Generate constraints for the main system.
    expr = generateConstraints(expr, target.getDeclContext());
    if (!expr)
      return true;
    target.setExpr(expr);

    // If there is a type that we're expected to convert to, add the conversion
    // constraint.
    if (Type convertType = target.getExprConversionType()) {
      ContextualTypePurpose ctp = target.getExprContextualTypePurpose();

      // If a custom locator wasn't specified, create a locator anchored on
      // the expression itself.
      auto *convertTypeLocator = target.getExprConvertTypeLocator();
      if (!convertTypeLocator) {
        convertTypeLocator =
            getConstraintLocator(expr, LocatorPathElt::ContextualType(ctp));
      }

      auto getLocator = [&](Type ty) -> ConstraintLocator * {
        // If we have a placeholder originating from a PlaceholderTypeRepr,
        // tack that on to the locator.
        if (auto *placeholderTy = ty->getAs<PlaceholderType>())
          if (auto *placeholderRepr = placeholderTy->getOriginator()
                                          .dyn_cast<PlaceholderTypeRepr *>())
            return getConstraintLocator(
                convertTypeLocator,
                LocatorPathElt::PlaceholderType(placeholderRepr));
        return convertTypeLocator;
      };

      // Substitute type variables in for placeholder types (and unresolved
      // types, if allowed).
      if (allowFreeTypeVariables == FreeTypeVariableBinding::UnresolvedType) {
        convertType = convertType.transform([&](Type type) -> Type {
          if (type->is<UnresolvedType>() || type->is<PlaceholderType>()) {
            return createTypeVariable(getLocator(type),
                                      TVO_CanBindToNoEscape |
                                          TVO_PrefersSubtypeBinding |
                                          TVO_CanBindToHole);
          }
          return type;
        });
      } else {
        convertType = convertType.transform([&](Type type) -> Type {
          if (type->is<PlaceholderType>()) {
            return createTypeVariable(getLocator(type),
                                      TVO_CanBindToNoEscape |
                                          TVO_PrefersSubtypeBinding |
                                          TVO_CanBindToHole);
          }
          return type;
        });
      }

      addContextualConversionConstraint(expr, convertType, ctp,
                                        convertTypeLocator);
    }

    // For an initialization target, generate constraints for the pattern.
    if (target.isForInitialization() &&
        generateInitPatternConstraints(*this, target, expr)) {
      return true;
    }

    if (isDebugMode()) {
      auto &log = llvm::errs();
      log << "\n---Initial constraints for the given expression---\n";
      print(log, expr);
      log << "\n";
      print(log);
      log << "\n";
    }

    return false;
  }

  switch (target.kind) {
  case SyntacticElementTarget::Kind::expression:
    llvm_unreachable("Handled above");

  case SyntacticElementTarget::Kind::closure:
  case SyntacticElementTarget::Kind::caseLabelItem:
  case SyntacticElementTarget::Kind::function:
  case SyntacticElementTarget::Kind::stmtCondition:
    llvm_unreachable("Handled separately");

  case SyntacticElementTarget::Kind::patternBinding: {
    auto patternBinding = target.getAsPatternBinding();
    auto dc = target.getDeclContext();
    bool hadError = false;

    /// Generate constraints for each pattern binding entry
    for (unsigned index : range(patternBinding->getNumPatternEntries())) {
      auto *pattern = TypeChecker::resolvePattern(
          patternBinding->getPattern(index), dc, /*isStmtCondition=*/true);

      if (!pattern)
        return true;

      // Reset binding to point to the resolved pattern. This is required
      // before calling `forPatternBindingDecl`.
      patternBinding->setPattern(index, pattern);

      auto contextualPattern =
          ContextualPattern::forPatternBindingDecl(patternBinding, index);
      Type patternType = TypeChecker::typeCheckPattern(contextualPattern);

      // Fail early if pattern couldn't be type-checked.
      if (!patternType || patternType->hasError())
        return true;

      auto *init = patternBinding->getInit(index);

      if (!init && patternBinding->isDefaultInitializable(index) &&
          pattern->hasStorage()) {
        init = TypeChecker::buildDefaultInitializer(patternType);
      }

      auto target = init ? SyntacticElementTarget::forInitialization(
                               init, patternType, patternBinding, index,
                               /*bindPatternVarsOneWay=*/true)
                         : SyntacticElementTarget::forUninitializedVar(
                               patternBinding, index, patternType);

      if (generateConstraints(target)) {
        hadError = true;
        continue;
      }

      // Keep track of this binding entry.
      setTargetFor({patternBinding, index}, target);
    }

    return hadError;
  }

  case SyntacticElementTarget::Kind::uninitializedVar: {
    if (auto *wrappedVar = target.getAsUninitializedWrappedVar()) {
      auto propertyType = getVarType(wrappedVar);
      if (propertyType->hasError())
        return true;

      return generateWrappedPropertyTypeConstraints(
        wrappedVar, /*initializerType=*/Type(), propertyType);
    } else {
      auto pattern = target.getAsUninitializedVar();
      auto locator = getConstraintLocator(
          pattern, LocatorPathElt::ContextualType(CTP_Initialization));

      // Generate constraints to bind all of the internal declarations
      // and verify the pattern.
      Type patternType = generateConstraints(
          pattern, locator, /*shouldBindPatternVarsOneWay*/ true,
          target.getPatternBindingOfUninitializedVar(),
          target.getIndexOfUninitializedVar());

      return !patternType;
    }
  }

  case SyntacticElementTarget::Kind::forEachPreamble: {

    // Cache the outer generic environment, if it exists.
    if (target.getPackElementEnv()) {
      PackElementGenericEnvironments.push_back(target.getPackElementEnv());
    }

    // For a for-each statement, generate constraints for the pattern, where
    // clause, and sequence traversal.
    auto resultTarget = generateForEachPreambleConstraints(*this, target);
    if (!resultTarget)
      return true;

    target = *resultTarget;
    return false;
  }
  }
}

Expr *ConstraintSystem::generateConstraints(Expr *expr, DeclContext *dc) {
  InputExprs.insert(expr);
  return generateConstraintsFor(*this, expr, dc);
}

Type ConstraintSystem::generateConstraints(
    Pattern *pattern, ConstraintLocatorBuilder locator,
    bool bindPatternVarsOneWay, PatternBindingDecl *patternBinding,
    unsigned patternIndex) {
  ConstraintGenerator cg(*this, nullptr);
  auto ty = cg.getTypeForPattern(pattern, locator, bindPatternVarsOneWay,
                                 patternBinding, patternIndex);
  assert(ty);

  // Gather the ExprPatterns, and form a conjunction for their expressions.
  SmallVector<ExprPattern *, 4> exprPatterns;
  pattern->forEachNode([&](Pattern *P) {
    if (auto *EP = dyn_cast<ExprPattern>(P))
      exprPatterns.push_back(EP);
  });
  if (!exprPatterns.empty())
    generateConstraints(exprPatterns, getConstraintLocator(pattern));

  return ty;
}

bool ConstraintSystem::generateConstraints(StmtCondition condition,
                                           DeclContext *dc) {
  // FIXME: This should be folded into constraint generation for conditions.
  auto boolDecl = getASTContext().getBoolDecl();
  if (!boolDecl) {
    return true;
  }

  Type boolTy = boolDecl->getDeclaredInterfaceType();
  for (const auto &condElement : condition) {
    switch (condElement.getKind()) {
    case StmtConditionElement::CK_Availability:
      // Nothing to do here.
      continue;

    case StmtConditionElement::CK_HasSymbol: {
      Expr *symbolExpr = condElement.getHasSymbolInfo()->getSymbolExpr();
      auto target = SyntacticElementTarget(symbolExpr, dc, CTP_Unused, Type(),
                                           /*isDiscarded=*/false);

      if (generateConstraints(target))
        return true;

      setTargetFor(&condElement, target);
      continue;
    }

    case StmtConditionElement::CK_Boolean: {
      Expr *condExpr = condElement.getBoolean();
      auto target = SyntacticElementTarget(condExpr, dc, CTP_Condition, boolTy,
                                           /*isDiscarded=*/false);

      if (generateConstraints(target, FreeTypeVariableBinding::Disallow))
        return true;

      setTargetFor(&condElement, target);
      continue;
    }

    case StmtConditionElement::CK_PatternBinding: {
      auto *pattern = TypeChecker::resolvePattern(
          condElement.getPattern(), dc, /*isStmtCondition*/true);
      if (!pattern)
        return true;

      auto target = SyntacticElementTarget::forInitialization(
          condElement.getInitializer(), dc, Type(), pattern,
          /*bindPatternVarsOneWay=*/true);
      if (generateConstraints(target, FreeTypeVariableBinding::Disallow))
        return true;

      setTargetFor(&condElement, target);
      continue;
    }
    }
  }

  return false;
}

ConstraintSystem::TypeMatchResult
ConstraintSystem::applyPropertyWrapperToParameter(
    Type wrapperType, Type paramType, ParamDecl *param, Identifier argLabel,
    ConstraintKind matchKind, ConstraintLocatorBuilder locator) {
  Expr *anchor = getAsExpr(locator.getAnchor());
  if (auto *apply = dyn_cast<ApplyExpr>(anchor)) {
    anchor = apply->getFn();
  }

  if (argLabel.hasDollarPrefix() && (!param || !param->hasExternalPropertyWrapper())) {
    if (!shouldAttemptFixes())
      return getTypeMatchFailure(locator);

    recordAnyTypeVarAsPotentialHole(paramType);

    auto *loc = getConstraintLocator(locator);
    auto *fix = RemoveProjectedValueArgument::create(*this, wrapperType, param, loc);
    if (recordFix(fix))
      return getTypeMatchFailure(locator);

    return getTypeMatchSuccess();
  }

  if (argLabel.hasDollarPrefix()) {
    Type projectionType = computeProjectedValueType(param, wrapperType);
    addConstraint(matchKind, paramType, projectionType, locator);
    if (param->hasImplicitPropertyWrapper()) {
      auto wrappedValueType = getType(param->getPropertyWrapperWrappedValueVar());
      addConstraint(ConstraintKind::PropertyWrapper, projectionType, wrappedValueType,
                    getConstraintLocator(param));
      setType(param->getPropertyWrapperProjectionVar(), projectionType);
    }

    appliedPropertyWrappers[anchor].push_back({ wrapperType, PropertyWrapperInitKind::ProjectedValue });
  } else if (param->hasExternalPropertyWrapper()) {
    Type wrappedValueType = computeWrappedValueType(param, wrapperType);
    addConstraint(matchKind, paramType, wrappedValueType, locator);
    setType(param->getPropertyWrapperWrappedValueVar(), wrappedValueType);

    appliedPropertyWrappers[anchor].push_back({ wrapperType, PropertyWrapperInitKind::WrappedValue });
  } else {
    return getTypeMatchFailure(locator);
  }

  return getTypeMatchSuccess();
}

void ConstraintSystem::optimizeConstraints(Expr *e) {
  if (getASTContext().TypeCheckerOpts.DisableConstraintSolverPerformanceHacks)
    return;
  
  SmallVector<Expr *, 16> linkedExprs;
  
  // Collect any linked expressions.
  LinkedExprCollector collector(linkedExprs);
  e->walk(collector);
  
  // Favor types, as appropriate.
  for (auto linkedExpr : linkedExprs) {
    computeFavoredTypeForExpr(linkedExpr, *this);
  }
  
  // Optimize the constraints.
  ConstraintOptimizer optimizer(*this);
  e->walk(optimizer);
}

struct ResolvedMemberResult::Implementation {
  llvm::SmallVector<ValueDecl*, 4> AllDecls;
  unsigned ViableStartIdx;
  std::optional<unsigned> BestIdx;
};

ResolvedMemberResult::ResolvedMemberResult(): Impl(new Implementation()) {}

ResolvedMemberResult::~ResolvedMemberResult() { delete Impl; }

ResolvedMemberResult::operator bool() const {
  return !Impl->AllDecls.empty();
}

bool ResolvedMemberResult::
hasBestOverload() const { return Impl->BestIdx.has_value(); }

ValueDecl* ResolvedMemberResult::
getBestOverload() const { return Impl->AllDecls[Impl->BestIdx.value()]; }

ArrayRef<ValueDecl*> ResolvedMemberResult::
getMemberDecls(InterestedMemberKind Kind) {
  auto Result = llvm::ArrayRef(Impl->AllDecls);
  switch (Kind) {
  case InterestedMemberKind::Viable:
    return Result.slice(Impl->ViableStartIdx);
  case InterestedMemberKind::Unviable:
    return Result.slice(0, Impl->ViableStartIdx);
  case InterestedMemberKind::All:
    return Result;
  }
  llvm_unreachable("unhandled kind");
}

ResolvedMemberResult swift::resolveValueMember(DeclContext &DC, Type BaseTy,
                                               DeclName Name) {
  ResolvedMemberResult Result;
  ConstraintSystem CS(&DC, std::nullopt);

  // Look up all members of BaseTy with the given Name.
  MemberLookupResult LookupResult = CS.performMemberLookup(
      ConstraintKind::ValueMember, DeclNameRef(Name), BaseTy,
      FunctionRefKind::SingleApply, CS.getConstraintLocator({}), false);

  // Keep track of all the unviable members.
  for (auto Can : LookupResult.UnviableCandidates)
    Result.Impl->AllDecls.push_back(Can.getDecl());

  // Keep track of the start of viable choices.
  Result.Impl->ViableStartIdx = Result.Impl->AllDecls.size();

  // If no viable members, we are done.
  if (LookupResult.ViableCandidates.empty())
    return Result;

  // If there's only one viable member, that is the best one.
  if (LookupResult.ViableCandidates.size() == 1) {
    Result.Impl->BestIdx = Result.Impl->AllDecls.size();
    Result.Impl->AllDecls.push_back(LookupResult.ViableCandidates[0].getDecl());
    return Result;
  }

  // Try to figure out the best overload.
  ConstraintLocator *Locator = CS.getConstraintLocator({});
  TypeVariableType *TV = CS.createTypeVariable(Locator,
                                               TVO_CanBindToLValue |
                                               TVO_CanBindToNoEscape);
  CS.addOverloadSet(TV, LookupResult.ViableCandidates, &DC, Locator);
  std::optional<Solution> OpSolution = CS.solveSingle();
  ValueDecl *Selected = nullptr;
  if (OpSolution.has_value()) {
    Selected = OpSolution.value().overloadChoices[Locator].choice.getDecl();
  }
  for (OverloadChoice& Choice : LookupResult.ViableCandidates) {
    ValueDecl *VD = Choice.getDecl();

    // If this VD is the best overload, keep track of its index.
    if (VD == Selected)
      Result.Impl->BestIdx = Result.Impl->AllDecls.size();
    Result.Impl->AllDecls.push_back(VD);
  }
  return Result;
}