File: SILGenLValue.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 (5716 lines) | stat: -rw-r--r-- 238,241 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
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
//===--- SILGenLValue.cpp - Constructs logical lvalues for SILGen ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Emission of l-value expressions and basic operations on them.
//
//===----------------------------------------------------------------------===//

#include "ASTVisitor.h"
#include "ArgumentScope.h"
#include "ArgumentSource.h"
#include "Conversion.h"
#include "ExecutorBreadcrumb.h"
#include "Initialization.h"
#include "LValue.h"
#include "ManagedValue.h"
#include "RValue.h"
#include "SILGen.h"
#include "SILGenFunction.h"
#include "Scope.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/SIL/Consumption.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace Lowering;

//===----------------------------------------------------------------------===//

namespace {

struct LValueWritebackCleanup : Cleanup {
  FormalEvaluationContext::stable_iterator Depth;

  LValueWritebackCleanup() : Depth() {}

  void emit(SILGenFunction &SGF, CleanupLocation loc,
            ForUnwind_t forUnwind) override {
    FullExpr scope(SGF.Cleanups, loc);

    // TODO: honor forUnwind!
    auto &evaluation = getEvaluation(SGF);
    evaluation.performWriteback(SGF, /*isFinal*/ false);
  }

  void dump(SILGenFunction &) const override {
#ifndef NDEBUG
    llvm::errs() << "LValueWritebackCleanup\n"
                 << "State: " << getState() << " Depth: " << Depth.getDepth()
                 << "\n";
#endif
  }

private:
  ExclusiveBorrowFormalAccess &getEvaluation(SILGenFunction &SGF) {
    auto &evaluation = *SGF.FormalEvalContext.find(Depth);
    assert(evaluation.getKind() == FormalAccess::Exclusive);
    return static_cast<ExclusiveBorrowFormalAccess &>(evaluation);
  }
};

} // end anonymous namespace

/// Push a writeback onto the current LValueWriteback stack.
static void pushWriteback(SILGenFunction &SGF,
                          SILLocation loc,
                          std::unique_ptr<LogicalPathComponent> &&comp,
                          ManagedValue base,
                          MaterializedLValue materialized) {
  assert(SGF.isInFormalEvaluationScope());

  // Push a cleanup to execute the writeback consistently.
  auto &context = SGF.FormalEvalContext;
  LValueWritebackCleanup &cleanup =
      SGF.Cleanups.pushCleanup<LValueWritebackCleanup>();
  CleanupHandle handle = SGF.Cleanups.getTopCleanup();

  context.push<ExclusiveBorrowFormalAccess>(loc, std::move(comp), base,
                                            materialized, handle);
  cleanup.Depth = context.stable_begin();
}

static bool areCertainlyEqualArgumentLists(const ArgumentList *l1,
                                           const ArgumentList *l2);

void ExclusiveBorrowFormalAccess::diagnoseConflict(
                                    const ExclusiveBorrowFormalAccess &rhs,
                                    SILGenFunction &SGF) const {
  // If the two writebacks we're comparing are of different kinds (e.g.
  // ownership conversion vs a computed property) then they aren't the
  // same and thus cannot conflict.
  if (component->getKind() != rhs.component->getKind())
    return;

  // If the lvalues don't have the same base value (possibly null), then
  // they aren't the same.  Note that this is the primary source of false
  // negative for this diagnostic.
  SILValue lhsBaseValue = base.getValue(), rhsBaseValue = rhs.base.getValue();
  if (lhsBaseValue != rhsBaseValue &&
      (!lhsBaseValue || !rhsBaseValue ||
       !RValue::areObviouslySameValue(lhsBaseValue, rhsBaseValue))) {
    return;
  }

  auto lhsStorage = component->getAccessStorage();
  if (!lhsStorage) return;

  auto rhsStorage = rhs.component->getAccessStorage();
  if (!rhsStorage) return;

  // If the decls match, then this could conflict.
  if (lhsStorage->Storage != rhsStorage->Storage ||
      !lhsStorage->Storage ||
      lhsStorage->IsSuper != rhsStorage->IsSuper)
    return;

  assert((lhsStorage->Indices != nullptr) == (rhsStorage->Indices != nullptr));

  auto storage = lhsStorage->Storage;

  // If the decl is monomorphically a stored property, allow aliases.
  // It could be overridden by a computed property in a subclass, but
  // that's not likely enough to be worth the strictness here.
  auto impl = storage->getImplInfo();
  // TODO: Stored properties with didSet accessors that don't look at the
  // oldValue could also be addressed.
  if ((impl.getReadImpl() == ReadImplKind::Stored ||
       impl.getReadImpl() == ReadImplKind::Address) &&
      (impl.getWriteImpl() == WriteImplKind::Immutable ||
       impl.getWriteImpl() == WriteImplKind::Stored ||
       impl.getWriteImpl() == WriteImplKind::MutableAddress)) {
    return;
  }

  // If the property is a generic requirement, allow aliases, because
  // it may be conformed to using a stored property.
  if (isa<ProtocolDecl>(storage->getDeclContext()))
    return;

  // If this is a simple property access, then we must have a conflict.
  if (!lhsStorage->Indices) {
    assert(isa<VarDecl>(storage));
    SGF.SGM.diagnose(loc, diag::writeback_overlap_property,
                     storage->getBaseIdentifier())
       .highlight(loc.getSourceRange());
    SGF.SGM.diagnose(rhs.loc, diag::writebackoverlap_note)
       .highlight(rhs.loc.getSourceRange());
    return;
  }

  // Otherwise, it is a subscript, check the index values.

  // If the indices are literally identical SILValue's, then there is
  // clearly a conflict.
  if (!lhsStorage->Indices->isObviouslyEqual(*rhsStorage->Indices)) {
    // If the index value doesn't lower to literally the same SILValue's,
    // do some fuzzy matching to catch the common case.
    if (!lhsStorage->ArgListForDiagnostics ||
        !rhsStorage->ArgListForDiagnostics ||
        !areCertainlyEqualArgumentLists(lhsStorage->ArgListForDiagnostics,
                                        rhsStorage->ArgListForDiagnostics))
      return;
  }

  // The locations for the subscripts are almost certainly SubscriptExprs.
  // If so, dig into them to produce better location info in the
  // diagnostics and be able to do more precise analysis.
  auto expr1 = loc.getAsASTNode<SubscriptExpr>();
  auto expr2 = rhs.loc.getAsASTNode<SubscriptExpr>();

  if (expr1 && expr2) {
    SGF.SGM.diagnose(loc, diag::writeback_overlap_subscript)
       .highlight(expr1->getBase()->getSourceRange());

    SGF.SGM.diagnose(rhs.loc, diag::writebackoverlap_note)
       .highlight(expr2->getBase()->getSourceRange());

  } else {
    SGF.SGM.diagnose(loc, diag::writeback_overlap_subscript)
       .highlight(loc.getSourceRange());
    SGF.SGM.diagnose(rhs.loc, diag::writebackoverlap_note)
       .highlight(rhs.loc.getSourceRange());
  }
}

//===----------------------------------------------------------------------===//

static CanType getSubstFormalRValueType(Expr *expr) {
  return expr->getType()->getRValueType()->getCanonicalType();
}

static LValueTypeData getAbstractedTypeData(TypeExpansionContext context,
                                            SILGenModule &SGM,
                                            SGFAccessKind accessKind,
                                            AbstractionPattern origFormalType,
                                            CanType substFormalType) {
  return {
      accessKind, origFormalType, substFormalType,
      SGM.Types.getLoweredRValueType(context, origFormalType, substFormalType)};
}

static LValueTypeData getLogicalStorageTypeData(TypeExpansionContext context,
                                                SILGenModule &SGM,
                                                SGFAccessKind accessKind,
                                                CanType substFormalType) {
  assert(!isa<ReferenceStorageType>(substFormalType));
  AbstractionPattern origFormalType(
      substFormalType.getReferenceStorageReferent());
  return getAbstractedTypeData(context, SGM, accessKind, origFormalType,
                               substFormalType);
}

static LValueTypeData getPhysicalStorageTypeData(TypeExpansionContext context,
                                                 SILGenModule &SGM,
                                                 SGFAccessKind accessKind,
                                                 AbstractStorageDecl *storage,
                                                 SubstitutionMap subs,
                                                 CanType substFormalType) {
  assert(!isa<ReferenceStorageType>(substFormalType));
  auto origFormalType = SGM.Types.getAbstractionPattern(storage)
                                 .getReferenceStorageReferentType()
                                 .withSubstitutions(subs);
  return getAbstractedTypeData(context, SGM, accessKind, origFormalType,
                               substFormalType);
}

static bool shouldUseUnsafeEnforcement(VarDecl *var) {
  if (var->isDebuggerVar())
    return true;

  return false;
}

static bool hasExclusivityAttr(VarDecl *var, ExclusivityAttr::Mode mode) {
  if (!var)
    return false;
  auto *exclAttr = var->getAttrs().getAttribute<ExclusivityAttr>();
  return exclAttr && exclAttr->getMode() == mode;
}

std::optional<SILAccessEnforcement>
SILGenFunction::getStaticEnforcement(VarDecl *var) {
  if (var && shouldUseUnsafeEnforcement(var))
    return SILAccessEnforcement::Unsafe;

  return SILAccessEnforcement::Static;
}

std::optional<SILAccessEnforcement>
SILGenFunction::getDynamicEnforcement(VarDecl *var) {
  if (getOptions().EnforceExclusivityDynamic) {
    if (var && shouldUseUnsafeEnforcement(var))
      return SILAccessEnforcement::Unsafe;
    if (hasExclusivityAttr(var, ExclusivityAttr::Unchecked))
      return SILAccessEnforcement::Unsafe;
    return SILAccessEnforcement::Dynamic;
  } else if (hasExclusivityAttr(var, ExclusivityAttr::Checked)) {
    return SILAccessEnforcement::Dynamic;
  }
  return std::nullopt;
}

std::optional<SILAccessEnforcement>
SILGenFunction::getUnknownEnforcement(VarDecl *var) {
  if (var && shouldUseUnsafeEnforcement(var))
    return SILAccessEnforcement::Unsafe;

  return SILAccessEnforcement::Unknown;
}

/// SILGenLValue - An ASTVisitor for building logical lvalues.
class LLVM_LIBRARY_VISIBILITY SILGenLValue
  : public Lowering::ExprVisitor<SILGenLValue, LValue,
                                 SGFAccessKind, LValueOptions>
{

public:
  SILGenFunction &SGF;
  SILGenLValue(SILGenFunction &SGF) : SGF(SGF) {}
  
  LValue visitRec(Expr *e, SGFAccessKind accessKind, LValueOptions options,
                  AbstractionPattern orig = AbstractionPattern::getInvalid());
  
  /// Dummy handler to log unimplemented nodes.
  LValue visitExpr(Expr *e, SGFAccessKind accessKind, LValueOptions options);

  // Nodes that form the root of lvalue paths
  LValue visitDiscardAssignmentExpr(DiscardAssignmentExpr *e,
                                    SGFAccessKind accessKind,
                                    LValueOptions options);
  LValue visitDeclRefExpr(DeclRefExpr *e, SGFAccessKind accessKind,
                          LValueOptions options);
  LValue visitOpaqueValueExpr(OpaqueValueExpr *e, SGFAccessKind accessKind,
                              LValueOptions options);
  LValue visitPackElementExpr(PackElementExpr *e, SGFAccessKind accessKind,
                              LValueOptions options);

  // Nodes that make up components of lvalue paths
  
  LValue visitMemberRefExpr(MemberRefExpr *e, SGFAccessKind accessKind,
                            LValueOptions options);
  LValue visitSubscriptExpr(SubscriptExpr *e, SGFAccessKind accessKind,
                            LValueOptions options);
  LValue visitTupleElementExpr(TupleElementExpr *e, SGFAccessKind accessKind,
                               LValueOptions options);
  LValue visitForceValueExpr(ForceValueExpr *e, SGFAccessKind accessKind,
                             LValueOptions options);
  LValue visitBindOptionalExpr(BindOptionalExpr *e, SGFAccessKind accessKind,
                               LValueOptions options);
  LValue visitOpenExistentialExpr(OpenExistentialExpr *e,
                                  SGFAccessKind accessKind,
                                  LValueOptions options);
  LValue visitKeyPathApplicationExpr(KeyPathApplicationExpr *e,
                                     SGFAccessKind accessKind,
                                     LValueOptions options);
  LValue visitConsumeExpr(ConsumeExpr *e, SGFAccessKind accessKind,
                          LValueOptions options);
  LValue visitCopyExpr(CopyExpr *e, SGFAccessKind accessKind,
                       LValueOptions options);
  LValue visitABISafeConversionExpr(ABISafeConversionExpr *e,
                                    SGFAccessKind accessKind,
                                    LValueOptions options);

  // Expressions that wrap lvalues
  
  LValue visitLoadExpr(LoadExpr *e, SGFAccessKind accessKind,
                        LValueOptions options);
  LValue visitInOutExpr(InOutExpr *e, SGFAccessKind accessKind,
                        LValueOptions options);
  LValue visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *e,
                                       SGFAccessKind accessKind,
                                       LValueOptions options);
};

/// Read this component.
ManagedValue
LogicalPathComponent::projectForRead(SILGenFunction &SGF, SILLocation loc,
                                     ManagedValue base,
                                     SGFAccessKind accessKind) && {
  assert(isReadAccess(accessKind));

  const TypeLowering &RValueTL = SGF.getTypeLowering(getTypeOfRValue());

  // If the access doesn't require us to make an owned address, don't
  // force a materialization.
  if (!isReadAccessResultAddress(accessKind)) {
    auto rvalue = std::move(*this).get(SGF, loc, base, SGFContext());
    return std::move(rvalue).getAsSingleValue(SGF, loc);
  }

  TemporaryInitializationPtr tempInit;
  ManagedValue result;
  RValue rvalue;

  // If the RValue type has an openedExistential, then the RValue must be
  // materialized before allocating a temporary for the RValue type. In that
  // case, the RValue cannot be emitted directly into the temporary.
  if (getTypeOfRValue().hasOpenedExistential()) {
    // Emit a 'get'.
    rvalue = std::move(*this).get(SGF, loc, base, SGFContext());

    // Create a temporary, whose type may depend on the 'get'.
    tempInit = SGF.emitFormalAccessTemporary(loc, RValueTL);
    result = tempInit->getManagedAddress();
  } else {
    // Create a temporary for a static (non-dependent) RValue type.
    tempInit = SGF.emitFormalAccessTemporary(loc, RValueTL);
    result = tempInit->getManagedAddress();

    // Emit a 'get' directly into the temporary.
    rvalue = std::move(*this).get(SGF, loc, base, SGFContext(tempInit.get()));
  }
  // `this` is now dead.

  // Force `value` into a temporary if is wasn't emitted there.
  if (!rvalue.isInContext())
    std::move(rvalue).forwardInto(SGF, loc, tempInit.get());

  assert(result);
  return result;
}

ManagedValue LogicalPathComponent::project(SILGenFunction &SGF,
                                           SILLocation loc,
                                           ManagedValue base) && {
  auto accessKind = getAccessKind();
  if (isReadAccess(accessKind))
    return std::move(*this).projectForRead(SGF, loc, base, accessKind);

  // AccessKind is Write or ReadWrite. We need to emit a get and set.
  assert(SGF.isInFormalEvaluationScope() &&
         "materializing l-value for modification without writeback scope");

  // Clone anything else about the component that we might need in the
  // writeback.
  auto clonedComponent = clone(SGF, loc);

  ManagedValue temp =
    std::move(*this).projectForRead(SGF, loc, base,
                                    SGFAccessKind::OwnedAddressRead);

  if (SGF.getOptions().VerifyExclusivity) {
    // Begin an access of the temporary. It is unenforced because enforcement
    // isn't required for RValues.
    SILValue accessAddress = UnenforcedFormalAccess::enter(
        SGF, loc, temp.getValue(), SILAccessKind::Modify);
    temp = std::move(temp).transform(accessAddress);
  }
  // Push a writeback for the temporary.
  pushWriteback(SGF, loc, std::move(clonedComponent), base,
                MaterializedLValue(temp));
  return ManagedValue::forLValue(temp.getValue());
}

void LogicalPathComponent::writeback(SILGenFunction &SGF, SILLocation loc,
                                     ManagedValue base,
                                     MaterializedLValue materialized,
                                     bool isFinal) {
  assert(!materialized.callback &&
         "unexpected materialized lvalue with callback!");

  // Load the value from the temporary unless the type is address-only
  // and this is the final use, in which case we can just consume the
  // value as-is.
  auto temporary = materialized.temporary;

  assert(temporary.getType().isAddress());
  auto &tempTL = SGF.getTypeLowering(temporary.getType());
  if (!tempTL.isAddressOnly() || !isFinal ||
      !SGF.silConv.useLoweredAddresses()) {
    if (isFinal) temporary.forward(SGF);
    temporary = SGF.emitLoad(loc, temporary.getValue(), tempTL,
                             SGFContext(), IsTake_t(isFinal));
  }
  RValue rvalue(SGF, loc, getSubstFormalType(), temporary);

  // Don't consume cleanups on the base if this isn't final.
  if (base && !isFinal) {
    if (base.getOwnershipKind() == OwnershipKind::Guaranteed) {
      base = ManagedValue::forBorrowedRValue(base.getValue());
    } else {
      base = ManagedValue::forUnmanagedOwnedValue(base.getValue());
    }
  }

  // Clone the component if this isn't final.
  std::unique_ptr<LogicalPathComponent> clonedComponent =
    (isFinal ? nullptr : clone(SGF, loc));
  LogicalPathComponent *component = (isFinal ? this : &*clonedComponent);
  std::move(*component).set(SGF, loc, ArgumentSource(loc, std::move(rvalue)),
                            base);
}

InOutConversionScope::InOutConversionScope(SILGenFunction &SGF)
  : SGF(SGF)
{
  assert(SGF.isInFormalEvaluationScope()
         && "inout conversions should happen in writeback scopes");
  assert(!SGF.InInOutConversionScope
         && "inout conversions should not be nested");
  SGF.InInOutConversionScope = true;
}

InOutConversionScope::~InOutConversionScope() {
  assert(SGF.InInOutConversionScope && "already exited conversion scope?!");
  SGF.InInOutConversionScope = false;
}

void PathComponent::_anchor() {}
void PhysicalPathComponent::_anchor() {}

void PhysicalPathComponent::set(SILGenFunction &SGF, SILLocation loc,
                                ArgumentSource &&value, ManagedValue base) && {
  auto finalDestAddr = std::move(*this).project(SGF, loc, base);
  assert(finalDestAddr.getType().isAddress());

  auto srcRValue = std::move(value).getAsRValue(SGF).ensurePlusOne(SGF, loc);
  std::move(srcRValue).assignInto(SGF, loc, finalDestAddr.getValue());
}

void PathComponent::dump() const {
  dump(llvm::errs());
}

/// Return the LValueTypeData for a SIL value with the given AST formal type.
static LValueTypeData getValueTypeData(SGFAccessKind accessKind,
                                       CanType formalType, SILValue value) {
  return {
    accessKind,
    AbstractionPattern(formalType),
    formalType,
    value->getType().getASTType(),
  };
}
static LValueTypeData getValueTypeData(SILGenFunction &SGF,
                                       SGFAccessKind accessKind, Expr *e) {
  CanType formalType = getSubstFormalRValueType(e);
  CanType loweredType = SGF.getLoweredType(formalType).getASTType();

  return {
    accessKind,
    AbstractionPattern(formalType),
    formalType,
    loweredType
  };
}

/// Given the address of an optional value, unsafely project out the
/// address of the value.
static ManagedValue getPayloadOfOptionalValue(SILGenFunction &SGF,
                                              SILLocation loc,
                                              ManagedValue optBase,
                                        const LValueTypeData &valueTypeData,
                                        SGFAccessKind accessKind) {
  // Project out the 'Some' payload.
  EnumElementDecl *someDecl = SGF.getASTContext().getOptionalSomeDecl();

  // If the base is +1, we want to forward the cleanup.
  SILValue value;
  bool isOwned;
  if (optBase.isPlusOne(SGF)) {
    value = optBase.forward(SGF);
    isOwned = true;
  } else {
    value = optBase.getValue();
    isOwned = false;
  }

  // UncheckedTakeEnumDataAddr is safe to apply to Optional, because it is
  // a single-payload enum. There will (currently) never be spare bits
  // embedded in the payload.
  SILValue payload;
  if (optBase.getType().isAddress()) {
    payload = SGF.B.createUncheckedTakeEnumDataAddr(loc, value, someDecl,
                                          SILType::getPrimitiveAddressType(
                                              valueTypeData.TypeOfRValue));
  } else {
    payload = SGF.B.createUncheckedEnumData(loc, value, someDecl,
                                          SILType::getPrimitiveObjectType(
                                              valueTypeData.TypeOfRValue));
  }

  // Return the value as +1 if the optional was +1.
  if (isOwned) {
    return SGF.emitManagedBufferWithCleanup(payload);
  } else if (payload->getType().isAddress()) {
    return ManagedValue::forLValue(payload);
  } else {
    return ManagedValue::forBorrowedRValue(payload);
  }
}

namespace {
  /// A helper class for creating writebacks associated with l-value
  /// components that don't really need them.
  class WritebackPseudoComponent : public LogicalPathComponent {
  protected:
    WritebackPseudoComponent(const LValueTypeData &typeData)
      : LogicalPathComponent(typeData, WritebackPseudoKind) {}

  public:
    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation l) const override {
      llvm_unreachable("called clone on pseudo-component");
    }

    RValue get(SILGenFunction &SGF, SILLocation loc,
               ManagedValue base, SGFContext c) && override {
      llvm_unreachable("called get on a pseudo-component");
    }
    void set(SILGenFunction &SGF, SILLocation loc,
             ArgumentSource &&value, ManagedValue base) && override {
      llvm_unreachable("called set on a pseudo-component");
    }
    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      llvm_unreachable("called project on a pseudo-component");
    }

    std::optional<AccessStorage> getAccessStorage() const override {
      return std::nullopt;
    }
  };

  class EndAccessPseudoComponent : public WritebackPseudoComponent {
  private:
    ExecutorBreadcrumb ExecutorHop;
  public:
    EndAccessPseudoComponent(const LValueTypeData &typeData,
                             ExecutorBreadcrumb &&executorHop)
      : WritebackPseudoComponent(typeData),
        ExecutorHop(std::move(executorHop)) {}

  private:
    void writeback(SILGenFunction &SGF, SILLocation loc,
                   ManagedValue base,
                   MaterializedLValue materialized,
                   bool isFinal) override {
      loc.markAutoGenerated();

      assert(base.isLValue());
      loc.markAutoGenerated();
      SGF.B.createEndAccess(loc, base.getValue(), /*abort*/ false);
      ExecutorHop.emit(SGF, loc);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "EndAccessPseudoComponent\n";
    }
  };
} // end anonymous namespace

static SILValue enterAccessScope(SILGenFunction &SGF, SILLocation loc,
                                 ManagedValue base, SILValue addr,
                                 LValueTypeData typeData,
                                 SGFAccessKind accessKind,
                                 SILAccessEnforcement enforcement,
                                 std::optional<ActorIsolation> actorIso,
                                 bool noNestedConflict = false) {
  auto silAccessKind = SILAccessKind::Modify;
  if (isReadAccess(accessKind))
    silAccessKind = SILAccessKind::Read;
  else if (isConsumeAccess(accessKind))
    silAccessKind = SILAccessKind::Deinit;

  assert(SGF.isInFormalEvaluationScope() &&
         "tried to enter access scope without a writeback scope!");

  ExecutorBreadcrumb prevExecutor =
      SGF.emitHopToTargetActor(loc, actorIso, base);

  // Enter the access.
  addr = SGF.B.createBeginAccess(loc, addr, silAccessKind, enforcement,
                                 noNestedConflict,
                                 /*fromBuiltin=*/false);

  // Push a writeback to end it.
  auto accessedMV = ManagedValue::forLValue(addr);
  std::unique_ptr<LogicalPathComponent> component(
      new EndAccessPseudoComponent(typeData, std::move(prevExecutor)));
  pushWriteback(SGF, loc, std::move(component), accessedMV,
                MaterializedLValue());

  return addr;
}

static ManagedValue enterAccessScope(SILGenFunction &SGF, SILLocation loc,
                                     ManagedValue base, ManagedValue addr,
                                     LValueTypeData typeData,
                                     SGFAccessKind accessKind,
                                     SILAccessEnforcement enforcement,
                                     std::optional<ActorIsolation> actorIso,
                                     bool noNestedConflict = false) {
  auto access = enterAccessScope(SGF, loc, base, addr.getValue(), typeData,
                           accessKind, enforcement, actorIso, noNestedConflict);
  return ManagedValue::forLValue(access);
}

// Find the base of the formal access at `address`. If the base requires an
// access marker, then create a begin_access on `address`. Return the
// address to be used for the access.
//
// FIXME: In order to generate more consistent and verifiable SIL patterns, or
// subobject projections, create the access on the base address and recreate the
// projection.
SILValue UnenforcedAccess::beginAccess(SILGenFunction &SGF, SILLocation loc,
                                       SILValue address, SILAccessKind kind) {
  if (!SGF.getOptions().VerifyExclusivity)
    return address;

  auto storage = AccessStorage::compute(address);
  // Unsafe access may have invalid storage (e.g. a RawPointer).
  if (storage && !isPossibleFormalAccessStorage(storage, &SGF.F))
    return address;

  auto BAI =
    SGF.B.createBeginAccess(loc, address, kind, SILAccessEnforcement::Unsafe,
                            /*hasNoNestedConflict=*/false,
                            /*fromBuiltin=*/false);
  beginAccessPtr = BeginAccessPtr(BAI, DeleterCheck());

  return BAI;
}

void UnenforcedAccess::endAccess(SILGenFunction &SGF) {
  emitEndAccess(SGF);
  beginAccessPtr.release();
}

void UnenforcedAccess::emitEndAccess(SILGenFunction &SGF) {
  if (!beginAccessPtr)
    return;

  SGF.B.createEndAccess(beginAccessPtr->getLoc(), beginAccessPtr.get(),
                        /*abort*/ false);
}

// Emit an end_access marker when executing a cleanup (on a side branch).
void UnenforcedFormalAccess::emitEndAccess(SILGenFunction &SGF) {
  access.emitEndAccess(SGF);
}

// End the access when existing the FormalEvaluationScope.
void UnenforcedFormalAccess::finishImpl(SILGenFunction &SGF) {
  access.endAccess(SGF);
}

namespace {
struct UnenforcedAccessCleanup : Cleanup {
  FormalEvaluationContext::stable_iterator Depth;

  UnenforcedAccessCleanup() : Depth() {}

  void emit(SILGenFunction &SGF, CleanupLocation loc,
            ForUnwind_t forUnwind) override {
    auto &evaluation = *SGF.FormalEvalContext.find(Depth);
    assert(evaluation.getKind() == FormalAccess::Unenforced);
    auto &formalAccess = static_cast<UnenforcedFormalAccess &>(evaluation);
    formalAccess.emitEndAccess(SGF);
  }

  void dump(SILGenFunction &) const override {
#ifndef NDEBUG
    llvm::errs() << "UnenforcedAccessCleanup\n"
                 << "State: " << getState() << " Depth: " << Depth.getDepth()
                 << "\n";
#endif
  }
};
} // end anonymous namespace

SILValue UnenforcedFormalAccess::enter(SILGenFunction &SGF, SILLocation loc,
                                       SILValue address, SILAccessKind kind) {
  assert(SGF.isInFormalEvaluationScope());

  UnenforcedAccess access;
  SILValue accessAddress = access.beginAccess(SGF, loc, address, kind);
  if (!access.beginAccessPtr)
    return address;

  auto &cleanup = SGF.Cleanups.pushCleanup<UnenforcedAccessCleanup>();
  CleanupHandle handle = SGF.Cleanups.getTopCleanup();
  auto &context = SGF.FormalEvalContext;
  context.push<UnenforcedFormalAccess>(loc, std::move(access), handle);
  cleanup.Depth = context.stable_begin();

  return accessAddress;
}

static void copyBorrowedYieldsIntoTemporary(SILGenFunction &SGF,
                                            SILLocation loc,
                                            ArrayRef<ManagedValue> &yields,
                                            AbstractionPattern origFormalType,
                                            CanType substFormalType,
                                            Initialization *init) {
  if (!origFormalType.isTuple()) {
    auto value = yields.front();
    yields = yields.drop_front();
    init->copyOrInitValueInto(SGF, loc, value, /*isInit*/ false);
    init->finishInitialization(SGF);
    return;
  }

  assert(init->canSplitIntoTupleElements());
  SmallVector<InitializationPtr, 4> scratch;
  auto eltInits =
    init->splitIntoTupleElements(SGF, loc, substFormalType, scratch);
  for (size_t i : indices(eltInits)) {
    auto origEltType = origFormalType.getTupleElementType(i);
    auto substEltType = cast<TupleType>(substFormalType).getElementType(i);
    copyBorrowedYieldsIntoTemporary(SGF, loc, yields, origEltType,
                                    substEltType, eltInits[i].get());
  }
  init->finishInitialization(SGF);
}

namespace {
  class RefElementComponent : public PhysicalPathComponent {
    VarDecl *Field;
    SILType SubstFieldType;
    bool IsNonAccessing;
  public:
    RefElementComponent(VarDecl *field, LValueOptions options,
                        SILType substFieldType, LValueTypeData typeData,
                        std::optional<ActorIsolation> actorIso)
        : PhysicalPathComponent(typeData, RefElementKind, actorIso),
          Field(field), SubstFieldType(substFieldType),
          IsNonAccessing(options.IsNonAccessing) {}

    virtual bool isLoadingPure() const override { return true; }

    VarDecl *getField() const { return Field; }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(base.getType().hasReferenceSemantics() &&
             "base for ref element component must be a reference type");

      // Borrow the ref element addr using formal access. If we need the ref
      // element addr, we will load it in this expression.
      if (base.getType().isAddress()) {
        base = SGF.B.createFormalAccessLoadBorrow(loc, base);
      } else {
        base = base.formalAccessBorrow(SGF, loc);
      }
      SILValue result =
        SGF.B.createRefElementAddr(loc, base.getUnmanagedValue(),
                                   Field, SubstFieldType);

      // Avoid emitting access markers completely for non-accesses or immutable
      // declarations. Access marker verification is aware of these cases.
      if (!IsNonAccessing && !Field->isLet()) {
        if (auto enforcement = SGF.getDynamicEnforcement(Field)) {
          result = enterAccessScope(SGF, loc, base, result, getTypeData(),
                                    getAccessKind(), *enforcement,
                                    takeActorIsolation());
        }
      }

      // If we have a move only type, add a marker.
      //
      // NOTE: We purposely do this on the access itself to ensure that when we
      // hoist destroy_addr, they stay within the access scope.
      if (result->getType().isMoveOnly()) {
        auto checkKind = MarkUnresolvedNonCopyableValueInst::CheckKind::
            AssignableButNotConsumable;
        if (isReadAccess(getAccessKind())) {
          // Add a mark_unresolved_non_copyable_value [no_consume_or_assign].
          checkKind =
              MarkUnresolvedNonCopyableValueInst::CheckKind::NoConsumeOrAssign;
        }
        result = SGF.B.createMarkUnresolvedNonCopyableValueInst(loc, result,
                                                                checkKind);
      }

      return ManagedValue::forLValue(result);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "RefElementComponent(" << Field->getName() << ")\n";
    }
  };

  class TupleElementComponent : public PhysicalPathComponent {
    unsigned ElementIndex;
  public:
    TupleElementComponent(unsigned elementIndex, LValueTypeData typeData)
        : PhysicalPathComponent(typeData, TupleElementKind,
                                /*actorIsolation=*/std::nullopt),
          ElementIndex(elementIndex) {}

    virtual bool isLoadingPure() const override { return true; }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(base && "invalid value for element base");
      if (base.getType().isObject()) {
        return SGF.B.createTupleExtract(loc, base, ElementIndex);
      }

      // TODO: if the base is +1, break apart its cleanup.
      auto Res = SGF.B.createTupleElementAddr(loc, base.getValue(),
                                              ElementIndex,
                                              getTypeOfRValue().getAddressType());
      return ManagedValue::forLValue(Res);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "TupleElementComponent(" << ElementIndex << ")\n";
    }
  };

  class StructElementComponent : public PhysicalPathComponent {
    VarDecl *Field;
    SILType SubstFieldType;
  public:
    StructElementComponent(VarDecl *field, SILType substFieldType,
                           LValueTypeData typeData,
                           std::optional<ActorIsolation> actorIso)
        : PhysicalPathComponent(typeData, StructElementKind, actorIso),
          Field(field), SubstFieldType(substFieldType) {}

    virtual bool isLoadingPure() const override { return true; }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(base && "invalid value for element base");
      if (base.getType().isObject()) {
        return SGF.B.createStructExtract(loc, base, Field);
      }

      // If we have a moveonlywrapped type, unwrap it. The reason why is that
      // any fields that we access we want to be treated as copyable.
      if (base.getType().isMoveOnlyWrapped())
        base = ManagedValue::forLValue(
            SGF.B.createMoveOnlyWrapperToCopyableAddr(loc, base.getValue()));

      // TODO: if the base is +1, break apart its cleanup.
      auto Res = SGF.B.createStructElementAddr(loc, base.getValue(),
                                               Field, SubstFieldType);

      if (!Field->getPointerAuthQualifier().isPresent() ||
          !SGF.getOptions().EnableImportPtrauthFieldFunctionPointers) {
        return ManagedValue::forLValue(Res);
      }
      auto beginAccess =
          enterAccessScope(SGF, loc, base, Res, getTypeData(), getAccessKind(),
                           SILAccessEnforcement::Signed, takeActorIsolation());
      return ManagedValue::forLValue(beginAccess);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "StructElementComponent("
                        << Field->getName() << ")\n";
    }
  };

  /// A physical path component which force-projects the address of
  /// the value of an optional l-value.
  class ForceOptionalObjectComponent : public PhysicalPathComponent {
    bool isImplicitUnwrap;
  public:
    ForceOptionalObjectComponent(LValueTypeData typeData, bool isImplicitUnwrap)
        : PhysicalPathComponent(typeData, OptionalObjectKind,
                                /*actorIsolation=*/std::nullopt),
          isImplicitUnwrap(isImplicitUnwrap) {}

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      // Assert that the optional value is present and return the projected out
      // payload.
      if (isConsumeAccess(getTypeData().getAccessKind())) {
        base = base.ensurePlusOne(SGF, loc);
      }
      return SGF.emitPreconditionOptionalHasValue(loc, base, isImplicitUnwrap);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "ForceOptionalObjectComponent(" << isImplicitUnwrap << ")\n";
    }
  };

  /// A physical path component which projects out an opened archetype
  /// from an existential.
  class OpenOpaqueExistentialComponent : public PhysicalPathComponent {
  public:
    OpenOpaqueExistentialComponent(CanArchetypeType openedArchetype,
                                   LValueTypeData typeData)
        : PhysicalPathComponent(typeData, OpenOpaqueExistentialKind,
                                /*actorIsolation=*/std::nullopt) {
      assert(getSubstFormalType() == openedArchetype);
    }

    virtual bool isLoadingPure() const override { return true; }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(base.getType().isExistentialType() &&
             "base for open existential component must be an existential");
      assert((base.getType().isAddress() ||
              base.getType().getPreferredExistentialRepresentation() ==
                  ExistentialRepresentation::Boxed ||
              !SGF.useLoweredAddresses()) &&
             "base value of open-existential component was not an address or a "
             "boxed existential?");
      SILValue addr;

      auto rep = base.getType().getPreferredExistentialRepresentation();
      switch (rep) {
      case ExistentialRepresentation::Opaque:
        if (!base.getValue()->getType().isAddress()) {
          assert(!SGF.useLoweredAddresses());
          auto borrow = SGF.B.createBeginBorrow(
              loc, base.getValue(), IsNotLexical, DoesNotHavePointerEscape);
          auto value =
              SGF.B.createOpenExistentialValue(loc, borrow, getTypeOfRValue());

          SGF.Cleanups.pushCleanup<EndBorrowCleanup>(borrow);
          return ManagedValue::forForwardedRValue(SGF, value);
        } else {
          addr = SGF.B.createOpenExistentialAddr(
              loc, base.getValue(), getTypeOfRValue().getAddressType(),
              getOpenedExistentialAccessFor(
                  getFormalAccessKind(getAccessKind())));
        }
        break;
      case ExistentialRepresentation::Boxed: {
        ManagedValue error;
        if (base.getType().isObject()) {
          error = base;
        } else {
          auto &TL = SGF.getTypeLowering(base.getType());
          error = SGF.emitLoad(loc, base.getValue(), TL,
                               SGFContext(), IsNotTake);
          // Error comes back to us with a +1 cleanup that is not a formal
          // access cleanup. We need it to be that so that the load nests
          // properly with other lvalue scoped things like the borrow below.
          error = SGF.emitFormalAccessManagedRValueWithCleanup(
              loc, error.forward(SGF));
        }
        SILType addrType = getTypeOfRValue().getAddressType();
        addr = SGF.B.createOpenExistentialBox(loc, error, addrType).getValue();
        break;
      }
      default:
        llvm_unreachable("Bad existential representation for address-only type");
      }

      return ManagedValue::forLValue(addr);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "OpenOpaqueExistentialComponent("
                        << getSubstFormalType() << ")\n";
    }
  };

  /// A local path component for the payload of a class or metatype existential.
  ///
  /// TODO: Could be physical if we had a way to project out the
  /// payload.
  class OpenNonOpaqueExistentialComponent : public LogicalPathComponent {
    CanArchetypeType OpenedArchetype;
  public:
    OpenNonOpaqueExistentialComponent(CanArchetypeType openedArchetype,
                                      LValueTypeData typeData)
      : LogicalPathComponent(typeData, OpenNonOpaqueExistentialKind),
        OpenedArchetype(openedArchetype) {}

    virtual bool isLoadingPure() const override { return true; }

    std::optional<AccessStorage> getAccessStorage() const override {
      return std::nullopt;
    }

    RValue get(SILGenFunction &SGF, SILLocation loc,
               ManagedValue base, SGFContext c) && override {
      auto refType = base.getType().getObjectType();
      auto &TL = SGF.getTypeLowering(refType);

      // Load the original value if necessary.
      auto result = base.getType().isAddress()
                      ? SGF.emitLoad(loc, base.getValue(), TL,
                                     SGFContext(), IsNotTake)
                      : base;

      assert(refType.isAnyExistentialType() &&
             "base for open existential component must be an existential");
      ManagedValue ref;
      if (refType.is<ExistentialMetatypeType>()) {
        assert(refType.getPreferredExistentialRepresentation()
                 == ExistentialRepresentation::Metatype);
        ref = ManagedValue::forObjectRValueWithoutOwnership(
            SGF.B.createOpenExistentialMetatype(loc, result.getUnmanagedValue(),
                                                getTypeOfRValue()));
      } else {
        assert(refType.getPreferredExistentialRepresentation()
                 == ExistentialRepresentation::Class);
        ref = SGF.B.createOpenExistentialRef(loc, result, getTypeOfRValue());
      }

      return RValue(SGF, loc, getSubstFormalType(), ref);
    }

    void set(SILGenFunction &SGF, SILLocation loc,
             ArgumentSource &&value, ManagedValue base) && override {
      auto payload = std::move(value).getAsSingleValue(SGF).forward(SGF);

      SmallVector<ProtocolConformanceRef, 2> conformances;
      for (auto proto : OpenedArchetype->getConformsTo())
        conformances.push_back(ProtocolConformanceRef(proto));

      SILValue ref;
      if (base.getType().is<ExistentialMetatypeType>()) {
        ref = SGF.B.createInitExistentialMetatype(
                loc,
                payload,
                base.getType().getObjectType(),
                SGF.getASTContext().AllocateCopy(conformances));
      } else {
        assert(getSubstFormalType()->isBridgeableObjectType());
        ref = SGF.B.createInitExistentialRef(
                loc,
                base.getType().getObjectType(),
                getSubstFormalType(),
                payload,
                SGF.getASTContext().AllocateCopy(conformances));
      }

      auto &TL = SGF.getTypeLowering(base.getType());
      SGF.emitSemanticStore(loc, ref,
                            base.getValue(), TL, IsNotInitialization);
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      LogicalPathComponent *clone =
        new OpenNonOpaqueExistentialComponent(OpenedArchetype, getTypeData());
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "OpenNonOpaqueExistentialComponent("
                        << OpenedArchetype << ", ...)\n";
    }
  };

  /// A physical path component which returns a literal address.
  class ValueComponent : public PhysicalPathComponent {
    ManagedValue Value;
    std::optional<SILAccessEnforcement> Enforcement;
    bool IsRValue;
    bool IsLazyInitializedGlobal;

  public:
    ValueComponent(ManagedValue value,
                   std::optional<SILAccessEnforcement> enforcement,
                   LValueTypeData typeData, bool isRValue = false,
                   std::optional<ActorIsolation> actorIso = std::nullopt,
                   bool isLazyInitializedGlobal = false)
        : PhysicalPathComponent(typeData, ValueKind, actorIso), Value(value),
          Enforcement(enforcement), IsRValue(isRValue),
          IsLazyInitializedGlobal(isLazyInitializedGlobal) {
      assert(IsRValue || value.getType().isAddress() ||
             value.getType().isBoxedNonCopyableType(value.getFunction()));
    }

    virtual bool isLoadingPure() const override { return true; }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(!base && "value component must be root of lvalue path");

      // See if we have a noncopyable address from a project_box or global.
      if (Value.getType().isAddress() && Value.getType().isMoveOnly()) {
        SILValue addr = Value.getValue();
        auto boxProject = addr;
        if (auto m = dyn_cast<CopyableToMoveOnlyWrapperAddrInst>(boxProject)) {
          boxProject = m->getOperand();
        }
        auto box = dyn_cast<ProjectBoxInst>(boxProject);
        if (box || isa<GlobalAddrInst>(boxProject) || IsLazyInitializedGlobal) {
          if (Enforcement)
            addr = enterAccessScope(SGF, loc, base, addr, getTypeData(),
                                    getAccessKind(), *Enforcement,
                                    takeActorIsolation());
          // Mark all move only as having mark_unresolved_non_copyable_value.
          //
          // DISCUSSION: LValue access to let boxes must have a
          // mark_unresolved_non_copyable_value to allow for DI to properly
          // handle delayed initialization of the boxes and convert those to
          // initable_but_not_consumable.
          addr = SGF.B.createMarkUnresolvedNonCopyableValueInst(
              loc, addr,
              isReadAccess(getAccessKind())
                  ? MarkUnresolvedNonCopyableValueInst::CheckKind::
                        NoConsumeOrAssign
                  : MarkUnresolvedNonCopyableValueInst::CheckKind::
                        AssignableButNotConsumable);
          return ManagedValue::forLValue(addr);
        }
      }

      if (!Enforcement)
        return Value;

      assert(Value.getType().isAddress() && "Must have an address here?!");

      SILValue addr = Value.getLValueAddress();
      addr =
          enterAccessScope(SGF, loc, base, addr, getTypeData(), getAccessKind(),
                           *Enforcement, takeActorIsolation());

      return ManagedValue::forLValue(addr);
    }

    bool isRValue() const override {
      return IsRValue;
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS << "ValueComponent(";
      if (IsRValue) OS << "rvalue, ";
      if (Enforcement) {
        OS << getSILAccessEnforcementName(*Enforcement);
      } else {
        OS << "unenforced";
      }
      if (hasActorIsolation()) OS << " requires actor-hop";
      OS << "):\n";
      Value.dump(OS, indent + 2);
    }
  };
  
  class BorrowValueComponent : public PhysicalPathComponent {
  public:
    BorrowValueComponent(LValueTypeData typeData)
        : PhysicalPathComponent(typeData, BorrowValueKind, std::nullopt) {}

    virtual bool isLoadingPure() const override { return true; }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      // If the base is already loaded, we just need to borrow it.
      if (!base.getType().isAddress()) {
        return base.formalAccessBorrow(SGF, loc);
      }

      // If the base value is address-only then we can borrow from the
      // address in-place.
      if (!base.getType().isLoadable(SGF.F)) {
        return base;
      }
      auto result = SGF.B.createLoadBorrow(loc, base.getValue());
      // Mark the load_borrow as unchecked. We can't stop the source code from
      // trying to mutate or consume the same lvalue during this borrow, so
      // we don't want verifiers to trip before the move checker gets a chance
      // to diagnose these situations.
      result->setUnchecked(true);
      return SGF.emitFormalEvaluationManagedBorrowedRValueWithCleanup(loc,
         base.getValue(), result);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "BorrowValueComponent\n";
    }
  };
} // end anonymous namespace

static bool isReadNoneFunction(const Expr *e) {
  // If this is a curried call to an integer literal conversion operations, then
  // we can "safely" assume it is readnone (btw, yes this is totally gross).
  // This is better to be attribute driven, a la rdar://15587352.
  if (auto *dre = dyn_cast<DeclRefExpr>(e)) {
    const DeclName name = dre->getDecl()->getName();
    return (name.getArgumentNames().size() == 1 &&
            name.getBaseName().isConstructor() &&
            !name.getArgumentNames()[0].empty() &&
            (name.getArgumentNames()[0].str() == "integerLiteral" ||
             name.getArgumentNames()[0].str() == "_builtinIntegerLiteral"));
  }
  
  // Look through DotSyntaxCallExpr, since the literal functions are curried.
  if (auto *CRCE = dyn_cast<ConstructorRefCallExpr>(e))
    return isReadNoneFunction(CRCE->getFn());
  
  return false;
}

/// Given two expressions used as arguments to the same SubscriptDecl (and thus
/// are guaranteed to have the same AST type) check to see if they are going to
/// produce the same value.
static bool areCertainlyEqualArgs(const Expr *e1, const Expr *e2) {
  if (e1->getKind() != e2->getKind()) return false;

  // Look through ParenExpr's.
  if (auto *pe1 = dyn_cast<ParenExpr>(e1)) {
    auto *pe2 = cast<ParenExpr>(e2);
    return areCertainlyEqualArgs(pe1->getSubExpr(), pe2->getSubExpr());
  }

  // Calls are identical if the callee and operands are identical and we know
  // that the call is something that is "readnone".
  if (auto *ae1 = dyn_cast<ApplyExpr>(e1)) {
    auto *ae2 = cast<ApplyExpr>(e2);
    return areCertainlyEqualArgs(ae1->getFn(), ae2->getFn()) &&
           areCertainlyEqualArgumentLists(ae1->getArgs(), ae2->getArgs()) &&
           isReadNoneFunction(ae1->getFn());
  }

  // TypeExpr's that produce the same metatype type are identical.
  if (isa<TypeExpr>(e1))
    return true;

  if (auto *dre1 = dyn_cast<DeclRefExpr>(e1)) {
    auto *dre2 = cast<DeclRefExpr>(e2);
    return dre1->getDecl() == dre2->getDecl() &&
           dre1->getType()->isEqual(dre2->getType());
  }

  // Compare a variety of literals.
  if (auto *il1 = dyn_cast<IntegerLiteralExpr>(e1)) {
    const auto &val1 = il1->getValue();
    const auto &val2 = cast<IntegerLiteralExpr>(e2)->getValue();
    // If the integers are arbitrary-precision, their bit-widths may differ,
    // but only if they represent different values.
    return val1.getBitWidth() == val2.getBitWidth() && val1 == val2;
  }
  if (auto *il1 = dyn_cast<FloatLiteralExpr>(e1))
    return il1->getValue().bitwiseIsEqual(
                                        cast<FloatLiteralExpr>(e2)->getValue());
  if (auto *bl1 = dyn_cast<BooleanLiteralExpr>(e1))
    return bl1->getValue() == cast<BooleanLiteralExpr>(e2)->getValue();
  if (auto *sl1 = dyn_cast<StringLiteralExpr>(e1))
    return sl1->getValue() == cast<StringLiteralExpr>(e2)->getValue();

  // Compare tuple expressions.
  if (auto *te1 = dyn_cast<TupleExpr>(e1)) {
    auto *te2 = cast<TupleExpr>(e2);

    // Easy checks: # of elements, element names.
    if (te1->getNumElements() != te2->getNumElements() ||
        te1->getElementNames() != te2->getElementNames()) {
      return false;
    }

    for (unsigned i = 0, n = te1->getNumElements(); i != n; ++i) {
      if (!areCertainlyEqualArgs(te1->getElement(i), te2->getElement(i)))
        return false;
    }

    return true;
  }

  // Otherwise, we have no idea if they are identical.
  return false;
}

/// Given two argument lists to the same SubscriptDecl (and thus are guaranteed
/// to have the same AST type) check to see if they are going to produce the
/// same value.
static bool areCertainlyEqualArgumentLists(const ArgumentList *l1,
                                           const ArgumentList *l2) {
  if (l1->size() != l2->size())
    return false;

  for (auto idx : indices(*l1)) {
    if (l1->getLabel(idx) != l2->getLabel(idx))
      return false;
    if (!areCertainlyEqualArgs(l1->getExpr(idx), l2->getExpr(idx)))
      return false;
  }
  return true;
}

static LValueOptions getBaseOptions(LValueOptions options,
                                    AccessStrategy strategy) {
  return (strategy.getKind() == AccessStrategy::Storage
            ? options.forProjectedBaseLValue()
            : options.forComputedBaseLValue());
}

static ArgumentSource emitBaseValueForAccessor(SILGenFunction &SGF,
                                               SILLocation loc, LValue &&dest,
                                               CanType baseFormalType,
                                               SILDeclRef accessor);

static SGFAccessKind getBaseAccessKind(SILGenModule &SGM,
                                       AbstractStorageDecl *member,
                                       SGFAccessKind accessKind,
                                       AccessStrategy strategy,
                                       CanType baseFormalType,
                                       bool forBorrowExpr);

namespace {
  /// A helper class for implementing components that involve accessing
  /// storage.
  template <class Base>
  class AccessComponent : public Base {
  protected:
    // The VarDecl or SubscriptDecl being get/set.
    AbstractStorageDecl *Storage;

    /// The subscript argument list.  Useless
    ArgumentList *ArgListForDiagnostics;
    PreparedArguments Indices;

    /// AST type of the base expression, in case the accessor call
    /// requires re-abstraction.
    CanType BaseFormalType;

    struct AccessorArgs {
      ArgumentSource base;
      PreparedArguments Indices;
    };

    /// Returns a tuple of RValues holding the accessor value, base (retained if
    /// necessary), and subscript arguments, in that order.
    AccessorArgs
    prepareAccessorArgs(SILGenFunction &SGF, SILLocation loc,
                        ManagedValue base, SILDeclRef accessor) &&
    {
      AccessorArgs result;
      if (base) {
        // Borrow the base, because we may need it again to invoke other
        // accessors.
        result.base = SGF.prepareAccessorBaseArg(loc,
                                             base.formalAccessBorrow(SGF, loc),
                                             BaseFormalType,
                                             accessor);
      }

      if (!Indices.isNull())
        result.Indices = std::move(Indices);
      
      return result;
    }

    AccessComponent(PathComponent::KindTy kind,
                    AbstractStorageDecl *storage,
                    CanType baseFormalType,
                    LValueTypeData typeData,
                    ArgumentList *argListForDiagnostics,
                    PreparedArguments &&indices)
      : Base(typeData, kind), Storage(storage),
        ArgListForDiagnostics(argListForDiagnostics),
        Indices(std::move(indices)),
        BaseFormalType(baseFormalType)
    {
    }

    AccessComponent(const AccessComponent &copied,
                    SILGenFunction &SGF,
                    SILLocation loc)
      : Base(copied.getTypeData(), copied.getKind()),
        Storage(copied.Storage),
        ArgListForDiagnostics(copied.ArgListForDiagnostics),
        Indices(copied.Indices.copy(SGF, loc)) ,
        BaseFormalType(copied.BaseFormalType) {}

    bool doesAccessorMutateSelf(SILGenFunction &SGF,
                                SILDeclRef accessor) const {
      auto accessorSelf = SGF.SGM.Types.getConstantSelfParameter(
          SGF.getTypeExpansionContext(), accessor);
      return accessorSelf.getInterfaceType()
        && accessorSelf.isIndirectMutating();
    }
    
    void printBase(raw_ostream &OS, unsigned indent, StringRef name) const {
      OS.indent(indent) << name << "(" << Storage->getBaseName() << ")";
      if (ArgListForDiagnostics) {
        OS << " subscript_index:\n";
        ArgListForDiagnostics->dump(OS, 2);
      }
      OS << '\n';
    }
  };

  /// A helper class for implementing a component that involves
  /// calling accessors.
  template <class Base>
  class AccessorBasedComponent : public AccessComponent<Base> {
    using super = AccessComponent<Base>;

  protected:
    SILDeclRef Accessor;
    bool IsSuper;
    bool IsDirectAccessorUse;
    bool IsOnSelfParameter;
    SubstitutionMap Substitutions;
    std::optional<ActorIsolation> ActorIso;

  public:
    AccessorBasedComponent(
        PathComponent::KindTy kind, AbstractStorageDecl *decl,
        SILDeclRef accessor, bool isSuper, bool isDirectAccessorUse,
        SubstitutionMap substitutions, CanType baseFormalType,
        LValueTypeData typeData, ArgumentList *argListForDiagnostics,
        PreparedArguments &&indices, bool isOnSelfParameter = false,
        std::optional<ActorIsolation> actorIso = std::nullopt)
        : super(kind, decl, baseFormalType, typeData, argListForDiagnostics,
                std::move(indices)),
          Accessor(accessor), IsSuper(isSuper),
          IsDirectAccessorUse(isDirectAccessorUse),
          IsOnSelfParameter(isOnSelfParameter), Substitutions(substitutions),
          ActorIso(actorIso) {}

    AccessorBasedComponent(const AccessorBasedComponent &copied,
                           SILGenFunction &SGF,
                           SILLocation loc)
      : super(copied, SGF, loc),
        Accessor(copied.Accessor),
        IsSuper(copied.IsSuper),
        IsDirectAccessorUse(copied.IsDirectAccessorUse),
        IsOnSelfParameter(copied.IsOnSelfParameter),
        Substitutions(copied.Substitutions),
        ActorIso(copied.ActorIso) {}

    AccessorDecl *getAccessorDecl() const {
      return cast<AccessorDecl>(Accessor.getFuncDecl());
    }

    ManagedValue emitValue(SILGenFunction &SGF, SILLocation loc, VarDecl *field,
                           ArgumentSource &&value, AccessorKind accessorKind) {
      auto accessorInfo = SGF.getConstantInfo(
          SGF.getTypeExpansionContext(),
          SILDeclRef(field->getOpaqueAccessor(accessorKind)));

      auto fieldTy = field->getValueInterfaceType();
      auto accessorTy = SGF.SGM.Types
                            .getLoweredType(accessorInfo.SILFnType,
                                            SGF.getTypeExpansionContext())
                            .castTo<SILFunctionType>();

      if (!Substitutions.empty()) {
        fieldTy = fieldTy.subst(Substitutions);
        accessorTy = accessorTy->substGenericArgs(
            SGF.SGM.M, Substitutions, SGF.getTypeExpansionContext());
      }

      SILFunctionConventions accessorConv(accessorTy, SGF.SGM.M);

      // FIXME: This should use CallEmission instead of doing everything
      // manually.
      assert(value.isRValue());
      ManagedValue Mval =
          std::move(value).asKnownRValue(SGF).getAsSingleValue(SGF, loc);
      auto param = accessorTy->getParameters()[0];
      SILType loweredSubstArgType = Mval.getType();
      if (param.isIndirectInOut()) {
        loweredSubstArgType =
            SILType::getPrimitiveAddressType(loweredSubstArgType.getASTType());
      }

      auto loweredSubstParamTy = SILType::getPrimitiveType(
          param.getArgumentType(SGF.SGM.M, accessorTy,
                                SGF.getTypeExpansionContext()),
          loweredSubstArgType.getCategory());

      // Handle reabstraction differences.
      if (Mval.getType() != loweredSubstParamTy) {
        Mval = SGF.emitSubstToOrigValue(
            loc, Mval, SGF.SGM.Types.getAbstractionPattern(field),
            fieldTy->getCanonicalType());
      }

      auto newValueArgIdx = accessorConv.getNumIndirectSILResults();
      // If we need the argument in memory, materialize an address.
      if (accessorConv.getSILArgumentConvention(newValueArgIdx)
              .isIndirectConvention() &&
          !Mval.getType().isAddress()) {
        Mval = Mval.materialize(SGF, loc);
      }

      return Mval;
    }
  };

  class InitAccessorComponent
      : public AccessorBasedComponent<LogicalPathComponent> {
  public:
    InitAccessorComponent(AbstractStorageDecl *decl, SILDeclRef accessor,
                          bool isSuper, bool isDirectAccessorUse,
                          SubstitutionMap substitutions, CanType baseFormalType,
                          LValueTypeData typeData,
                          ArgumentList *subscriptArgList,
                          PreparedArguments &&indices, bool isOnSelfParameter,
                          std::optional<ActorIsolation> actorIso)
        : AccessorBasedComponent(
              InitAccessorKind, decl, accessor, isSuper, isDirectAccessorUse,
              substitutions, baseFormalType, typeData, subscriptArgList,
              std::move(indices), isOnSelfParameter, actorIso) {
      assert(getAccessorDecl()->isInitAccessor());
    }

    InitAccessorComponent(const InitAccessorComponent &copied,
                          SILGenFunction &SGF, SILLocation loc)
        : AccessorBasedComponent(copied, SGF, loc) {}

    void set(SILGenFunction &SGF, SILLocation loc, ArgumentSource &&value,
             ManagedValue base) &&
        override {
      VarDecl *field = cast<VarDecl>(Storage);
      auto Mval =
          emitValue(SGF, loc, field, std::move(value), AccessorKind::Init);
      SGF.emitAssignOrInit(loc, base, field, Mval, Substitutions);
    }

    RValue get(SILGenFunction &SGF, SILLocation loc, ManagedValue base,
               SGFContext c) &&
        override {
      llvm_unreachable("called get on an init accessor component");
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      LogicalPathComponent *clone = new InitAccessorComponent(*this, SGF, loc);
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      printBase(OS, indent, "InitAccessorComponent");
    }

    /// Compare 'this' lvalue and the 'rhs' lvalue (which is guaranteed to have
    /// the same dynamic PathComponent type as the receiver) to see if they are
    /// identical.  If so, there is a conflicting writeback happening, so emit a
    /// diagnostic.
    std::optional<AccessStorage> getAccessStorage() const override {
      return AccessStorage{Storage, IsSuper,
                           Indices.isNull() ? nullptr : &Indices,
                           ArgListForDiagnostics};
    }
  };

  class GetterSetterComponent
    : public AccessorBasedComponent<LogicalPathComponent> {
  public:
    GetterSetterComponent(AbstractStorageDecl *decl, SILDeclRef accessor,
                          bool isSuper, bool isDirectAccessorUse,
                          SubstitutionMap substitutions, CanType baseFormalType,
                          LValueTypeData typeData,
                          ArgumentList *subscriptArgList,
                          PreparedArguments &&indices, bool isOnSelfParameter,
                          std::optional<ActorIsolation> actorIso)
        : AccessorBasedComponent(
              GetterSetterKind, decl, accessor, isSuper, isDirectAccessorUse,
              substitutions, baseFormalType, typeData, subscriptArgList,
              std::move(indices), isOnSelfParameter, actorIso) {
      assert(getAccessorDecl()->isGetterOrSetter());
    }

    GetterSetterComponent(const GetterSetterComponent &copied,
                          SILGenFunction &SGF,
                          SILLocation loc)
      : AccessorBasedComponent(copied, SGF, loc)
    {
    }

    bool canRewriteSetAsPropertyWrapperInit(SILGenFunction &SGF) const {
      if (auto *VD = dyn_cast<VarDecl>(Storage)) {
        if (VD->isImplicit() || isa<ParamDecl>(VD))
          return false;

        // If this is not a wrapper property that can be initialized from
        // a value of the wrapped type, we can't perform the initialization.
        auto initInfo = VD->getPropertyWrapperInitializerInfo();
        if (!initInfo.hasInitFromWrappedValue())
          return false;

        auto *fnDecl = SGF.FunctionDC->getAsDecl();
        bool isAssignmentToSelfParamInInit =
            IsOnSelfParameter && isa<ConstructorDecl>(fnDecl) &&
            // Convenience initializers only contain assignments and not
            // initializations.
            !(cast<ConstructorDecl>(fnDecl)->isConvenienceInit());

        // Assignment to a wrapped property can only be re-written to initialization for
        // members of `self` in an initializer, and for local variables.
        if (!(isAssignmentToSelfParamInInit || VD->getDeclContext()->isLocalContext()))
          return false;

        // If this var isn't in a type context, assignment will always use the setter
        // if there is an initial value.
        if (!VD->getDeclContext()->isTypeContext() &&
            initInfo.getWrappedValuePlaceholder()->getOriginalWrappedValue())
          return false;

        // If this property wrapper uses autoclosure in it's initializer,
        // the argument types of the setter and initializer shall be
        // different, so we don't rewrite an assignment into an
        // initialization.
        return !initInfo.getWrappedValuePlaceholder()->isAutoClosure();
      }

      return false;
    }

    /// Whether an assignment 'x = y' can be re-written as a call to an
    /// init accessor declared by 'x'.
    bool canRewriteSetAsInitAccessor(SILGenFunction &SGF) const {
      auto *varDecl = dyn_cast<VarDecl>(Storage);
      if (!varDecl || varDecl->isStatic() ||
          varDecl->getDeclContext()->isLocalContext())
        return false;

      auto *fnDecl = SGF.FunctionDC->getAsDecl();
      bool isAssignmentToSelfParamInInit =
          IsOnSelfParameter && isa<ConstructorDecl>(fnDecl) &&
          // Convenience initializers only contain assignments and not
          // initializations.
          !(cast<ConstructorDecl>(fnDecl)->isConvenienceInit());

      // Assignment to a wrapped property can only be re-written to initialization for
      // members of `self` in an initializer, and for local variables.
      if (!isAssignmentToSelfParamInInit)
        return false;

      // Properties declared in a superclass cannot be initialized via
      // init accessor because `super.init()` should always precede
      // any such property reference which means that it can only be
      // mutated by a setter call.
      if (varDecl->getDeclContext()->getSelfNominalTypeDecl() !=
          fnDecl->getDeclContext()->getSelfNominalTypeDecl())
        return false;

      auto *initAccessor = varDecl->getAccessor(AccessorKind::Init);
      if (!initAccessor)
        return false;

      return true;
    }

    void emitAssignWithSetter(SILGenFunction &SGF, SILLocation loc,
                              LValue &&dest, ArgumentSource &&value) {
      assert(getAccessorDecl()->isSetter());
      SILDeclRef setter = Accessor;

      // Pull everything out of this that we'll need, because we're
      // about to modify the LValue and delete this component.
      auto subs = this->Substitutions;
      bool isSuper = this->IsSuper;
      bool isDirectAccessorUse = this->IsDirectAccessorUse;
      auto indices = std::move(this->Indices);
      auto baseFormalType = this->BaseFormalType;
      bool isOnSelfParameter = this->IsOnSelfParameter;

      // Drop this component from the l-value.
      dest.dropLastComponent(*this);

      return emitAssignWithSetter(SGF, loc, std::move(dest), baseFormalType,
                                  isSuper, setter, isDirectAccessorUse, subs,
                                  std::move(indices), std::move(value),
                                  isOnSelfParameter);
    }

    static void emitAssignWithSetter(SILGenFunction &SGF, SILLocation loc,
                                     LValue &&baseLV, CanType baseFormalType,
                                     bool isSuper, SILDeclRef setter,
                                     bool isDirectAccessorUse,
                                     SubstitutionMap subs,
                                     PreparedArguments &&indices,
                                     ArgumentSource &&value,
                                     bool isSelfParameter) {
      ArgumentSource self = [&] {
        if (!baseLV.isValid()) {
          return ArgumentSource();
        } else if (computeSelfParam(cast<FuncDecl>(setter.getDecl()))
                     .getParameterFlags().isInOut()) {
          return ArgumentSource(loc, std::move(baseLV));
        } else {
          return emitBaseValueForAccessor(SGF, loc, std::move(baseLV),
                                          baseFormalType, setter);
        }
      }();

      return SGF.emitSetAccessor(loc, setter, subs, std::move(self), isSuper,
                                 isDirectAccessorUse, std::move(indices),
                                 std::move(value), isSelfParameter);
    }

    /// Determine whether the backing variable for the given
    /// property (that has a wrapper) is visible from the
    /// current context.
    static bool isBackingVarVisible(VarDecl *field,
                                    DeclContext *fromDC){
      VarDecl *backingVar = field->getPropertyWrapperBackingProperty();
      return backingVar->isAccessibleFrom(fromDC);
    }

    void set(SILGenFunction &SGF, SILLocation loc,
             ArgumentSource &&value, ManagedValue base) && override {
      assert(getAccessorDecl()->isSetter());
      assert(!ActorIso && "no support for cross-actor set operations");
      SILDeclRef setter = Accessor;

      if (canRewriteSetAsInitAccessor(SGF)) {
        // Emit an assign_or_init with the allocating initializer function and the
        // setter function as arguments. DefiniteInitialization will then decide
        // between the two functions, depending if it's an init call or a
        // set call.
        SILDeclRef initAccessorRef(Storage->getAccessor(AccessorKind::Init));
        InitAccessorComponent IAC(Storage,
                                  initAccessorRef,
                                  IsSuper,
                                  IsDirectAccessorUse,
                                  Substitutions,
                                  BaseFormalType,
                                  getTypeData(),
                                  ArgListForDiagnostics,
                                  std::move(Indices),
                                  IsOnSelfParameter,
                                  ActorIso);
        std::move(IAC).set(SGF, loc, std::move(value), base);
        return;
      }

      if (canRewriteSetAsPropertyWrapperInit(SGF) &&
          !Storage->isStatic() &&
          isBackingVarVisible(cast<VarDecl>(Storage),
                              SGF.FunctionDC)) {
        // This is wrapped property. Instead of emitting a setter, emit an
        // assign_by_wrapper with the allocating initializer function and the
        // setter function as arguments. DefiniteInitialization will then decide
        // between the two functions, depending if it's an initialization or a
        // re-assignment.
        //
        VarDecl *field = cast<VarDecl>(Storage);
        VarDecl *backingVar = field->getPropertyWrapperBackingProperty();
        assert(backingVar);
        auto FieldType = field->getValueInterfaceType();
        auto ValType = backingVar->getValueInterfaceType();
        if (!Substitutions.empty()) {
          FieldType = FieldType.subst(Substitutions);
          ValType = ValType.subst(Substitutions);
        }

        auto typeData = getLogicalStorageTypeData(
            SGF.getTypeExpansionContext(), SGF.SGM, getTypeData().AccessKind,
            ValType->getCanonicalType());

        // Stores the address of the storage property.
        ManagedValue proj;

        // TODO: revist minimal
        SILType varStorageType = SGF.SGM.Types.getSubstitutedStorageType(
            TypeExpansionContext::minimal(), backingVar,
            ValType->getCanonicalType());

        if (!BaseFormalType) {
          proj =
              SGF.maybeEmitValueOfLocalVarDecl(backingVar, AccessKind::Write);
        } else if (BaseFormalType->mayHaveSuperclass()) {
          RefElementComponent REC(backingVar, LValueOptions(), varStorageType,
                                  typeData, /*actorIsolation=*/std::nullopt);
          proj = std::move(REC).project(SGF, loc, base);
        } else {
          assert(BaseFormalType->getStructOrBoundGenericStruct());
          StructElementComponent SEC(backingVar, varStorageType, typeData,
                                     /*actorIsolation=*/std::nullopt);
          proj = std::move(SEC).project(SGF, loc, base);
        }

        // The property wrapper backing initializer forms an instance of
        // the backing storage type from a wrapped value.
        SILDeclRef initConstant(
            field, SILDeclRef::Kind::PropertyWrapperBackingInitializer);
        SILValue initFRef = SGF.emitGlobalFunctionRef(loc, initConstant);

        PartialApplyInst *initPAI =
          SGF.B.createPartialApply(loc, initFRef,
                                   Substitutions, ArrayRef<SILValue>(),
                                   ParameterConvention::Direct_Guaranteed);
        ManagedValue initFn = SGF.emitManagedRValueWithCleanup(initPAI);

        // Create the allocating setter function. It captures the base address.
        SILValue setterFn =
            SGF.emitApplyOfSetterToBase(loc, Accessor, base, Substitutions);

        // Create the assign_by_wrapper with the initializer and setter.

        auto Mval =
            emitValue(SGF, loc, field, std::move(value), AccessorKind::Set);

        SGF.B.createAssignByWrapper(loc, Mval.forward(SGF), proj.forward(SGF),
                                    initFn.getValue(), setterFn,
                                    AssignByWrapperInst::Unknown);
        return;
      }

      FormalEvaluationScope scope(SGF);
      // Pass in just the setter.
      auto args =
        std::move(*this).prepareAccessorArgs(SGF, loc, base, setter);

      return SGF.emitSetAccessor(loc, setter, Substitutions,
                                 std::move(args.base), IsSuper,
                                 IsDirectAccessorUse, std::move(args.Indices),
                                 std::move(value), IsOnSelfParameter);
    }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(isReadAccess(getAccessKind()) &&
             "shouldn't be using this path to call modify");
      return std::move(*this).LogicalPathComponent::project(SGF, loc, base);
    }

    RValue get(SILGenFunction &SGF, SILLocation loc,
               ManagedValue base, SGFContext c) && override {
      assert(getAccessorDecl()->isGetter());

      SILDeclRef getter = Accessor;
      RValue rvalue;
      FormalEvaluationScope scope(SGF);

      auto args =
          std::move(*this).prepareAccessorArgs(SGF, loc, base, getter);

      rvalue = SGF.emitGetAccessor(
          loc, getter, Substitutions, std::move(args.base), IsSuper,
          IsDirectAccessorUse, std::move(args.Indices), c,
          IsOnSelfParameter, ActorIso);

      return rvalue;
    }
    
    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      LogicalPathComponent *clone = new GetterSetterComponent(*this, SGF, loc);
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      printBase(OS, indent, "GetterSetterComponent");
    }

    /// Compare 'this' lvalue and the 'rhs' lvalue (which is guaranteed to have
    /// the same dynamic PathComponent type as the receiver) to see if they are
    /// identical.  If so, there is a conflicting writeback happening, so emit a
    /// diagnostic.
    std::optional<AccessStorage> getAccessStorage() const override {
      return AccessStorage{Storage, IsSuper,
                             Indices.isNull() ? nullptr : &Indices,
                             ArgListForDiagnostics };
    }
  };

  class MaterializeToTemporaryComponent final
      : public AccessComponent<LogicalPathComponent> {
    SubstitutionMap Substitutions;
    AccessStrategy ReadStrategy;
    AccessStrategy WriteStrategy;
    LValueOptions Options;
    bool IsSuper;
    bool IsOnSelfParameter;

  public:
    MaterializeToTemporaryComponent(AbstractStorageDecl *storage,
                                    bool isSuper, SubstitutionMap subs,
                                    LValueOptions options,
                                    AccessStrategy readStrategy,
                                    AccessStrategy writeStrategy,
                                    CanType baseFormalType,
                                    LValueTypeData typeData,
                                    ArgumentList *argListForDiagnostics,
                                    PreparedArguments &&indices,
                                    bool isOnSelfParameter)
      : AccessComponent(MaterializeToTemporaryKind, storage, baseFormalType,
                        typeData, argListForDiagnostics, std::move(indices)),
        Substitutions(subs),
        ReadStrategy(readStrategy), WriteStrategy(writeStrategy),
        Options(options), IsSuper(isSuper), IsOnSelfParameter(isOnSelfParameter)
        {}


    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      PreparedArguments clonedIndices = Indices.copy(SGF, loc);

      LogicalPathComponent *clone =
        new MaterializeToTemporaryComponent(Storage, IsSuper, Substitutions,
                                            Options,
                                            ReadStrategy, WriteStrategy,
                                            BaseFormalType, getTypeData(),
                                            ArgListForDiagnostics,
                                            std::move(clonedIndices),
                                            IsOnSelfParameter);
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    RValue get(SILGenFunction &SGF, SILLocation loc,
               ManagedValue base, SGFContext C) && override {
      LValue lv = std::move(*this).prepareLValue(SGF, loc, base,
                                                 SGFAccessKind::OwnedObjectRead,
                                                 ReadStrategy);
      return SGF.emitLoadOfLValue(loc, std::move(lv), C);
    }

    void set(SILGenFunction &SGF, SILLocation loc,
             ArgumentSource &&value, ManagedValue base) && override {
      LValue lv = std::move(*this).prepareLValue(SGF, loc, base,
                                                 SGFAccessKind::Write,
                                                 WriteStrategy);
      return SGF.emitAssignToLValue(loc, std::move(value), std::move(lv));
    }

    std::optional<AccessStorage> getAccessStorage() const override {
      return AccessStorage{Storage, IsSuper,
                             Indices.isNull() ? nullptr : &Indices,
                             ArgListForDiagnostics};
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "MaterializeToTemporaryComponent\n";
    }

  private:
    LValue prepareLValue(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base, SGFAccessKind accessKind,
                         AccessStrategy strategy) && {
      LValue lv = [&] {
        if (!base) return LValue();
        auto baseAccessKind =
          getBaseAccessKind(SGF.SGM, Storage, accessKind, strategy,
                            BaseFormalType,
                            /*for borrow*/ false);
        return LValue::forValue(baseAccessKind, base, BaseFormalType);
      }();

      if (auto subscript = dyn_cast<SubscriptDecl>(Storage)) {
        lv.addMemberSubscriptComponent(SGF, loc, subscript, Substitutions,
                                       Options, IsSuper, accessKind, strategy,
                                       getSubstFormalType(),
                                       std::move(Indices),
                                       ArgListForDiagnostics);
      } else {
        auto var = cast<VarDecl>(Storage);
        if (base) {
          lv.addMemberVarComponent(SGF, loc, var, Substitutions, Options,
                                   IsSuper, accessKind, strategy,
                                   getSubstFormalType());
        } else {
          lv.addNonMemberVarComponent(SGF, loc, var, Substitutions, Options,
                                      accessKind, strategy,
                                      getSubstFormalType(),
                                      /*actorIsolation=*/std::nullopt);
        }
      }
      
      if (lv.getTypeOfRValue() != getTypeOfRValue()) {
        lv.addOrigToSubstComponent(getTypeOfRValue());
      }

      return lv;
    }
  };

  /// A physical component which involves calling addressors.
  class AddressorComponent
      : public AccessorBasedComponent<PhysicalPathComponent> {
    SILType SubstFieldType;
    
    static SGFAccessKind getAccessKindForAddressor(SGFAccessKind accessKind) {
      // Addressors cannot be consumed through.
      switch (accessKind) {
      case SGFAccessKind::IgnoredRead:
      case SGFAccessKind::BorrowedAddressRead:
      case SGFAccessKind::BorrowedObjectRead:
      case SGFAccessKind::OwnedAddressRead:
      case SGFAccessKind::OwnedObjectRead:
      case SGFAccessKind::Write:
      case SGFAccessKind::ReadWrite:
        return accessKind;
        
      case SGFAccessKind::OwnedAddressConsume:
      case SGFAccessKind::OwnedObjectConsume:
        return SGFAccessKind::ReadWrite;
      }
      llvm_unreachable("uncovered switch");
    }
  public:
     AddressorComponent(AbstractStorageDecl *decl, SILDeclRef accessor,
                        bool isSuper,
                        bool isDirectAccessorUse,
                        SubstitutionMap substitutions,
                        CanType baseFormalType, LValueTypeData typeData,
                        SILType substFieldType,
                        ArgumentList *argListForDiagnostics,
                        PreparedArguments &&indices, bool isOnSelfParameter)
      : AccessorBasedComponent(AddressorKind, decl, accessor, isSuper,
                               isDirectAccessorUse,
                               substitutions,
                               baseFormalType, typeData,
                               argListForDiagnostics, std::move(indices),
                               isOnSelfParameter),
        SubstFieldType(substFieldType)
    {
      assert(getAccessorDecl()->isAnyAddressor());
    }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(SGF.isInFormalEvaluationScope() &&
             "offsetting l-value for modification without writeback scope");

      ManagedValue addr;
      {
        FormalEvaluationScope scope(SGF);

        auto args =
            std::move(*this).prepareAccessorArgs(SGF, loc, base, Accessor);
        addr = SGF.emitAddressorAccessor(
            loc, Accessor, Substitutions, std::move(args.base), IsSuper,
            IsDirectAccessorUse, std::move(args.Indices),
            SubstFieldType, IsOnSelfParameter);
      }

      // Enter an unsafe access scope for the access.
      addr =
          enterAccessScope(SGF, loc, base, addr, getTypeData(),
                           getAccessKindForAddressor(getAccessKind()),
                           SILAccessEnforcement::Unsafe, ActorIso);

      // Validate the use of the access if it's noncopyable.
      if (addr.getType().isMoveOnly()) {
        MarkUnresolvedNonCopyableValueInst::CheckKind kind
          = getAccessorDecl()->getAccessorKind() == AccessorKind::MutableAddress
              ? MarkUnresolvedNonCopyableValueInst::CheckKind::ConsumableAndAssignable
              : MarkUnresolvedNonCopyableValueInst::CheckKind::NoConsumeOrAssign;
        auto checkedAddr = SGF.B.createMarkUnresolvedNonCopyableValueInst(
          loc, addr.getValue(), kind);
        addr = std::move(addr).transform(checkedAddr);
      }

      return addr;
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      printBase(OS, indent, "AddressorComponent");
    }
  };

  class EndApplyPseudoComponent : public WritebackPseudoComponent {
    CleanupHandle EndApplyHandle;
    AbstractStorageDecl *Storage;
    bool IsSuper;
    PreparedArguments PeekedIndices;
    ArgumentList *ArgListForDiagnostics;
  public:
    EndApplyPseudoComponent(const LValueTypeData &typeData,
                            CleanupHandle endApplyHandle,
                            AbstractStorageDecl *storage,
                            bool isSuper,
                            PreparedArguments &&peekedIndices,
                            ArgumentList *argListForDiagnostics)
      : WritebackPseudoComponent(typeData),
        EndApplyHandle(endApplyHandle),
        Storage(storage), IsSuper(isSuper),
        PeekedIndices(std::move(peekedIndices)),
        ArgListForDiagnostics(argListForDiagnostics) {}

  private:
    void writeback(SILGenFunction &SGF, SILLocation loc,
                   ManagedValue base,
                   MaterializedLValue materialized,
                   bool isFinal) override {
      // Just let the cleanup get emitted normally if the writeback is for
      // an unwind.
      if (!isFinal) return;

      SGF.Cleanups.popAndEmitCleanup(EndApplyHandle, CleanupLocation(loc),
                                     NotForUnwind);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "EndApplyPseudoComponent";
    }

    std::optional<AccessStorage> getAccessStorage() const override {
      return AccessStorage{Storage, IsSuper,
                             PeekedIndices.isNull() ? nullptr : &PeekedIndices,
                             ArgListForDiagnostics};
    }
  };
}

static void pushEndApplyWriteback(SILGenFunction &SGF, SILLocation loc,
                                  CleanupHandle endApplyHandle,
                                  LValueTypeData typeData,
                                  ManagedValue base = ManagedValue(),
                                  AbstractStorageDecl *storage = nullptr,
                                  bool isSuper = false,
                                  PreparedArguments &&indices
                                    = PreparedArguments(),
                                  ArgumentList *argListForDiagnostics = nullptr) {
  std::unique_ptr<LogicalPathComponent>
    component(new EndApplyPseudoComponent(typeData, endApplyHandle,
                                          storage, isSuper, std::move(indices),
                                          argListForDiagnostics));
  pushWriteback(SGF, loc, std::move(component), /*for diagnostics*/ base,
                MaterializedLValue());
}

namespace {

  /// A physical component which involves calling coroutine accessors.
  class CoroutineAccessorComponent
      : public AccessorBasedComponent<PhysicalPathComponent> {
  public:
    CoroutineAccessorComponent(AbstractStorageDecl *decl, SILDeclRef accessor,
                               bool isSuper, bool isDirectAccessorUse,
                               SubstitutionMap substitutions,
                               CanType baseFormalType, LValueTypeData typeData,
                               ArgumentList *argListForDiagnostics,
                               PreparedArguments &&indices,
                               bool isOnSelfParameter)
        : AccessorBasedComponent(
              CoroutineAccessorKind, decl, accessor, isSuper,
              isDirectAccessorUse,
              substitutions, baseFormalType, typeData,
              argListForDiagnostics, std::move(indices), isOnSelfParameter) {}

    using AccessorBasedComponent::AccessorBasedComponent;

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(SGF.isInFormalEvaluationScope() &&
             "offsetting l-value for modification without writeback scope");

      ManagedValue result;

      auto args =
        std::move(*this).prepareAccessorArgs(SGF, loc, base, Accessor);
      auto peekedIndices = args.Indices.copyForDiagnostics();
      SmallVector<ManagedValue, 4> yields;
      auto endApplyHandle = SGF.emitCoroutineAccessor(
          loc, Accessor, Substitutions, std::move(args.base), IsSuper,
          IsDirectAccessorUse, std::move(args.Indices), yields,
          IsOnSelfParameter);

      // Push a writeback that ends the access.
      pushEndApplyWriteback(SGF, loc, endApplyHandle, getTypeData(),
                            base, Storage, IsSuper, std::move(peekedIndices),
                            ArgListForDiagnostics);

      auto decl = cast<AccessorDecl>(Accessor.getFuncDecl());

      // 'modify' always returns an address of the right type.
      if (decl->getAccessorKind() == AccessorKind::Modify) {
        assert(yields.size() == 1);
        return yields[0];
      }

      // 'read' returns a borrowed r-value, which might or might not be
      // an address of the right type.

      // Use the yield value directly if it's the right type.
      if (!getOrigFormalType().isTuple()) {
        assert(yields.size() == 1);
        auto value = yields[0];
        if (value.getType().isAddress() ||
            !isReadAccessResultAddress(getAccessKind()))
          return value;

        // If we have a guaranteed object and our read access result requires an
        // address, store it using a store_borrow.
        if (value.getType().isObject() &&
            value.getOwnershipKind() == OwnershipKind::Guaranteed) {
          SILValue alloc = SGF.emitTemporaryAllocation(loc, getTypeOfRValue());
          if (alloc->getType().isMoveOnly())
            alloc = SGF.B.createMarkUnresolvedNonCopyableValueInst(
                loc, alloc,
                MarkUnresolvedNonCopyableValueInst::CheckKind::
                    NoConsumeOrAssign);
          return SGF.B.createFormalAccessStoreBorrow(loc, value, alloc);
        }
      }

      // Otherwise, we need to make a temporary.
      // TODO: This needs to be changed to use actual store_borrows. Noncopyable
      // types do not support tuples today, so we can avoid this for now.
      // TODO: build a scalar tuple if possible.
      auto temporary = SGF.emitFormalAccessTemporary(
          loc, SGF.getTypeLowering(getTypeOfRValue()));
      auto yieldsAsArray = llvm::ArrayRef(yields);
      copyBorrowedYieldsIntoTemporary(SGF, loc, yieldsAsArray,
                                      getOrigFormalType(), getSubstFormalType(),
                                      temporary.get());
      assert(yieldsAsArray.empty() && "didn't claim all yields");
      return temporary->getManagedAddress();
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      printBase(OS, indent, "CoroutineAccessorComponent");
    }
  };
}

static ManagedValue
makeBaseConsumableMaterializedRValue(SILGenFunction &SGF,
                                     SILLocation loc, ManagedValue base) {
  if (base.isLValue()) {
    if (SGF.useLoweredAddresses()) {
      auto tmp = SGF.emitTemporaryAllocation(loc, base.getType());
      SGF.B.createCopyAddr(loc, base.getValue(), tmp, IsNotTake,
                           IsInitialization);
      return SGF.emitManagedBufferWithCleanup(tmp);
    }
    return SGF.emitLoad(loc, base.getValue(),
                        SGF.getTypeLowering(base.getType()), SGFContext(),
                        IsNotTake);
  }

  bool isBorrowed = base.isPlusZeroRValueOrTrivial()
    && !base.getType().isTrivial(SGF.F);
  if (!base.getType().isAddress() || isBorrowed) {
    if (SGF.useLoweredAddresses()) {
      auto tmp = SGF.emitTemporaryAllocation(loc, base.getType());
      if (isBorrowed)
        base.copyInto(SGF, loc, tmp);
      else
        base.forwardInto(SGF, loc, tmp);
      return SGF.emitManagedBufferWithCleanup(tmp);
    } else {
      return base.copy(SGF, loc);
    }
  }

  return base;
}

static ManagedValue
emitUpcastToKeyPath(SILGenFunction &SGF, SILLocation loc,
                    KeyPathTypeKind typeKind, ManagedValue keyPath) {
  if (typeKind == KPTK_KeyPath) return keyPath;
  assert(typeKind == KPTK_WritableKeyPath ||
         typeKind == KPTK_ReferenceWritableKeyPath);

  auto derivedKeyPathTy = keyPath.getType().castTo<BoundGenericType>();
  auto baseKeyPathTy =
    BoundGenericType::get(SGF.getASTContext().getKeyPathDecl(),
                          Type(), derivedKeyPathTy->getGenericArgs())
      ->getCanonicalType();
  return SGF.B.createUpcast(loc, keyPath,
                            SILType::getPrimitiveObjectType(baseKeyPathTy));
}

namespace {
  class LogicalKeyPathApplicationComponent final
      : public LogicalPathComponent {
    KeyPathTypeKind TypeKind;
    ManagedValue KeyPath;
    Type BaseFormalType;
  public:
    LogicalKeyPathApplicationComponent(LValueTypeData typeData,
                                       KeyPathTypeKind typeKind,
                                       ManagedValue keyPath,
                                       Type baseFormalType)
      : LogicalPathComponent(typeData, LogicalKeyPathApplicationKind),
        TypeKind(typeKind), KeyPath(keyPath), BaseFormalType(baseFormalType) {
      assert(isReadAccess(getAccessKind()) ||
             typeKind == KPTK_WritableKeyPath ||
             typeKind == KPTK_ReferenceWritableKeyPath);
    }

    RValue get(SILGenFunction &SGF, SILLocation loc,
               ManagedValue base, SGFContext C) && override {
      assert(isReadAccess(getAccessKind()));
      FuncDecl *projectFn;

      auto keyPathValue = KeyPath;

      GenericSignature sig;
      SmallVector<Type, 2> replacementTypes;

      if (TypeKind == KPTK_AnyKeyPath) {
        projectFn = SGF.getASTContext().getGetAtAnyKeyPath();
        sig = projectFn->getGenericSignature();
        replacementTypes.push_back(BaseFormalType);
      } else if (TypeKind == KPTK_PartialKeyPath) {
        projectFn = SGF.getASTContext().getGetAtPartialKeyPath();
        sig = projectFn->getGenericSignature();
        replacementTypes.push_back(BaseFormalType);
      } else if (TypeKind == KPTK_KeyPath ||
                 TypeKind == KPTK_WritableKeyPath ||
                 TypeKind == KPTK_ReferenceWritableKeyPath) {
        projectFn = SGF.getASTContext().getGetAtKeyPath();
        sig = projectFn->getGenericSignature();

        auto keyPathTy = keyPathValue.getType().castTo<BoundGenericType>();
        assert(keyPathTy->getGenericArgs().size() == 2);
        assert(keyPathTy->getGenericArgs()[0]->getCanonicalType() ==
               BaseFormalType->getCanonicalType());
        replacementTypes.push_back(keyPathTy->getGenericArgs()[0]);
        replacementTypes.push_back(keyPathTy->getGenericArgs()[1]);

        keyPathValue = emitUpcastToKeyPath(SGF, loc, TypeKind, keyPathValue);
      } else {
        llvm_unreachable("bad key path kind for this component");
      }

      auto subs = SubstitutionMap::get(sig, replacementTypes,
                  LookUpConformanceInModule{SGF.getModule().getSwiftModule()});

      base = makeBaseConsumableMaterializedRValue(SGF, loc, base);

      return SGF.emitApplyOfLibraryIntrinsic(loc, projectFn, subs,
                                             {base, keyPathValue}, C);
    }

    void set(SILGenFunction &SGF, SILLocation loc,
             ArgumentSource &&value, ManagedValue base) && override {
      assert(!isReadAccess(getAccessKind()));

      auto keyPathValue = KeyPath;
      FuncDecl *setFn;
      if (TypeKind == KPTK_WritableKeyPath) {
        setFn = SGF.getASTContext().getSetAtWritableKeyPath();
        assert(base.isLValue());
      } else if (TypeKind == KPTK_ReferenceWritableKeyPath) {
        setFn = SGF.getASTContext().getSetAtReferenceWritableKeyPath();
        base = makeBaseConsumableMaterializedRValue(SGF, loc, base);
      } else {
        llvm_unreachable("bad writable type kind");
      }

      auto keyPathTy = keyPathValue.getType().castTo<BoundGenericType>();
      auto subs = keyPathTy->getContextSubstitutionMap(
          keyPathTy->getDecl()->getParentModule(),
          keyPathTy->getDecl());

      auto origType = AbstractionPattern::getOpaque();
      auto loweredTy = SGF.getLoweredType(origType, value.getSubstRValueType());

      auto setValue =
        std::move(value).getAsSingleValue(SGF, origType, loweredTy);
      if (SGF.useLoweredAddresses() && !setValue.getType().isAddress()) {
        setValue = setValue.materialize(SGF, loc);
      }

      SGF.emitApplyOfLibraryIntrinsic(loc, setFn, subs,
                                      {base, keyPathValue, setValue},
                                      SGFContext());
    }

    std::optional<AccessStorage> getAccessStorage() const override {
      return std::nullopt;
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation l) const override {
      llvm_unreachable("can't be cloned");
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "LogicalKeyPathApplicationComponent\n";
    }
  };

  /// A physical component which involves applying a key path.
  class PhysicalKeyPathApplicationComponent final
      : public PhysicalPathComponent {
    KeyPathTypeKind TypeKind;
    ManagedValue KeyPath;
  public:
    PhysicalKeyPathApplicationComponent(LValueTypeData typeData,
                                        KeyPathTypeKind typeKind,
                                        ManagedValue keyPath)
        : PhysicalPathComponent(typeData, PhysicalKeyPathApplicationKind,
                                /*actorIsolation=*/std::nullopt),
          TypeKind(typeKind), KeyPath(keyPath) {
      assert(typeKind == KPTK_KeyPath ||
             typeKind == KPTK_WritableKeyPath ||
             typeKind == KPTK_ReferenceWritableKeyPath);
      assert(typeKind != KPTK_KeyPath || isReadAccess(getAccessKind()));
    }

    ManagedValue project(SILGenFunction &SGF, SILLocation loc,
                         ManagedValue base) && override {
      assert(SGF.isInFormalEvaluationScope() &&
             "offsetting l-value for modification without writeback scope");

      bool isRead = isReadAccess(getAccessKind());

      // Set up the base and key path values correctly.
      auto keyPathValue = KeyPath;
      if (isRead) {
        keyPathValue = emitUpcastToKeyPath(SGF, loc, TypeKind, keyPathValue);
        base = makeBaseConsumableMaterializedRValue(SGF, loc, base);
      } else if (TypeKind == KPTK_WritableKeyPath) {
        // nothing to do
      } else if (TypeKind == KPTK_ReferenceWritableKeyPath) {
        base = makeBaseConsumableMaterializedRValue(SGF, loc, base);
      } else {
        llvm_unreachable("bad combination");
      }

      SILFunction *projectFn =
        SGF.SGM.getKeyPathProjectionCoroutine(isRead, TypeKind);
      auto projectFnRef = SGF.B.createManagedFunctionRef(loc, projectFn);
      auto projectFnType = projectFn->getLoweredFunctionType();

      auto keyPathTy = keyPathValue.getType().castTo<BoundGenericType>();
      auto subs = keyPathTy->getContextSubstitutionMap(
          keyPathTy->getDecl()->getParentModule(),
          keyPathTy->getDecl());

      auto substFnType = projectFnType->substGenericArgs(
          SGF.SGM.M, subs, SGF.getTypeExpansionContext());

      // Perform the begin_apply.
      SmallVector<ManagedValue, 1> yields;
      auto cleanup =
        SGF.emitBeginApply(loc, projectFnRef, subs, { base, keyPathValue },
                           substFnType, ApplyOptions(), yields);

      // Push an operation to do the end_apply.
      pushEndApplyWriteback(SGF, loc, cleanup, getTypeData());

      assert(yields.size() == 1);
      return yields[0];
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "PhysicalKeyPathApplicationComponent\n";
    }
  };

  /// A translation component that performs \c unchecked_*_cast 's as-needed.
  class UncheckedConversionComponent final : public TranslationPathComponent {
  private:
    Type OrigType;

    /// \returns the type this component is trying to convert \b to
    CanType getTranslatedType() const {
      return getTypeData().SubstFormalType->getCanonicalType();
    }

    /// \returns the type this component is trying to convert \b from
    CanType getUntranslatedType() const {
      return OrigType->getRValueType()->getCanonicalType();
    }

    /// perform a conversion of ManagedValue -> ManagedValue
    ManagedValue doUncheckedConversion(SILGenFunction &SGF, SILLocation loc,
                                       ManagedValue val, CanType toType) {
      auto toTy = SGF.getLoweredType(toType);
      auto fromTy = val.getType();

      if (fromTy == toTy)
        return val; // nothing to do.

      // otherwise emit the right kind of cast based on whether it's an address.
      assert(fromTy.isAddress() == toTy.isAddress());

      if (toTy.isAddress())
        return SGF.B.createUncheckedAddrCast(loc, val, toTy);

      return SGF.B.createUncheckedBitCast(loc, val, toTy);
    }

    /// perform a conversion of RValue -> RValue
    RValue doUncheckedConversion(SILGenFunction &SGF, SILLocation loc,
                                 RValue &&rv, CanType toType) {
      auto val = std::move(rv).getAsSingleValue(SGF, loc);
      val = doUncheckedConversion(SGF, loc, val, toType);
      return RValue(SGF, loc, toType, val);
    }

  public:
    /// \param OrigType is the type we are converting \b from
    /// \param typeData will contain the type we are converting \b to
    UncheckedConversionComponent(LValueTypeData typeData, Type OrigType)
      : TranslationPathComponent(typeData, UncheckedConversionKind),
      OrigType(OrigType) {}

    bool isLoadingPure() const override { return true; }

    /// Used during write operations to convert the value prior to writing to
    /// the base.
    RValue untranslate(SILGenFunction &SGF, SILLocation loc,
                       RValue &&rv, SGFContext c) && override {
      return doUncheckedConversion(SGF, loc, std::move(rv),
                getUntranslatedType());
    }

    /// Used during read operations to convert the value after reading the base.
    RValue translate(SILGenFunction &SGF, SILLocation loc,
                     RValue &&rv, SGFContext c) && override {
      return doUncheckedConversion(SGF, loc, std::move(rv),
                getTranslatedType());
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      return std::make_unique<UncheckedConversionComponent>(getTypeData(),
                                                            OrigType);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "UncheckedConversionComponent"
                        << "\n\tfromType: " << getUntranslatedType()
                        << "\n\ttoType: " << getTranslatedType()
                        << "\n";
    }
  };
} // end anonymous namespace

RValue
TranslationPathComponent::get(SILGenFunction &SGF, SILLocation loc,
                              ManagedValue base, SGFContext c) && {
  // Inline constructor.
  RValue baseVal = [&]() -> RValue {
    // If our base is an object, just put it into an RValue and return.
    if (base.getType().isObject()) {
      return RValue(SGF, loc, getSubstFormalType(), base);
    }

    // Otherwise, load the value and put it into an RValue.
    return RValue(SGF, loc, getSubstFormalType(),
                  SGF.emitLoad(loc, base.getValue(),
                               SGF.getTypeLowering(base.getType()),
                               SGFContext(), IsNotTake));
  }();

  // Map the base value to its substituted representation.
  return std::move(*this).translate(SGF, loc, std::move(baseVal), c);
}

void TranslationPathComponent::set(SILGenFunction &SGF, SILLocation loc,
                                   ArgumentSource &&valueSource,
                                   ManagedValue base) && {
  assert(base.getType().isAddress() &&
         "Only support setting bases that have addresses");
  RValue value = std::move(valueSource).getAsRValue(SGF);

  // Map the value to the original pattern.
  RValue newValue = std::move(*this).untranslate(SGF, loc, std::move(value));

  // Store to the base.
  std::move(newValue).assignInto(SGF, loc, base.getValue());
}

namespace {
  /// Remap an lvalue referencing a generic type to an lvalue of its
  /// substituted type in a concrete context.
  class OrigToSubstComponent : public TranslationPathComponent {
    AbstractionPattern OrigType;

  public:
    OrigToSubstComponent(const LValueTypeData &typeData,
                         AbstractionPattern origType)
      : TranslationPathComponent(typeData, OrigToSubstKind),
        OrigType(origType)
    {}

    virtual bool isLoadingPure() const override { return true; }

    RValue untranslate(SILGenFunction &SGF, SILLocation loc,
                       RValue &&rv, SGFContext c) && override {
      return SGF.emitSubstToOrigValue(loc, std::move(rv), OrigType,
                                      getSubstFormalType(), c);
    }

    RValue translate(SILGenFunction &SGF, SILLocation loc,
                     RValue &&rv, SGFContext c) && override {
      return SGF.emitOrigToSubstValue(loc, std::move(rv), OrigType,
                                      getSubstFormalType(), c);
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      LogicalPathComponent *clone
        = new OrigToSubstComponent(getTypeData(), OrigType);
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "OrigToSubstComponent("
                        << getOrigFormalType() << ", "
                        << getSubstFormalType() << ", "
                        << getTypeOfRValue() << ")\n";
    }
  };

  /// Remap an lvalue referencing a concrete type to an lvalue of a
  /// generically-reabstracted type.
  class SubstToOrigComponent : public TranslationPathComponent {
  public:
    SubstToOrigComponent(const LValueTypeData &typeData)
      : TranslationPathComponent(typeData, SubstToOrigKind)
    {}

    virtual bool isLoadingPure() const override { return true; }

    RValue untranslate(SILGenFunction &SGF, SILLocation loc,
                       RValue &&rv, SGFContext c) && override {
      return SGF.emitOrigToSubstValue(loc, std::move(rv), getOrigFormalType(),
                                      getSubstFormalType(), c);
    }

    RValue translate(SILGenFunction &SGF, SILLocation loc,
                     RValue &&rv, SGFContext c) && override {
      return SGF.emitSubstToOrigValue(loc, std::move(rv), getOrigFormalType(),
                                      getSubstFormalType(), c);
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      LogicalPathComponent *clone
        = new SubstToOrigComponent(getTypeData());
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "SubstToOrigComponent("
                        << getOrigFormalType() << ", "
                        << getSubstFormalType() << ", "
                        << getTypeOfRValue() << ")\n";
    }
  };

  /// Remap a weak value to Optional<T>*, or unowned pointer to T*.
  class OwnershipComponent : public LogicalPathComponent {
  public:
    OwnershipComponent(LValueTypeData typeData)
      : LogicalPathComponent(typeData, OwnershipKind) {
    }

    virtual bool isLoadingPure() const override { return true; }

    std::optional<AccessStorage> getAccessStorage() const override {
      return std::nullopt;
    }

    RValue get(SILGenFunction &SGF, SILLocation loc,
               ManagedValue base, SGFContext c) && override {
      assert(base && "ownership component must not be root of lvalue path");

      auto &TL = SGF.getTypeLowering(getTypeOfRValue());

      ManagedValue result;
      if (base.getType().isObject()) {
        result = SGF.emitConversionToSemanticRValue(loc, base, TL);
      } else {
        result = SGF.emitLoad(loc, base.getValue(), TL, SGFContext(),
                              IsNotTake);
      }

      return RValue(SGF, loc, getSubstFormalType(), result);
    }

    void set(SILGenFunction &SGF, SILLocation loc,
             ArgumentSource &&valueSource, ManagedValue base) && override {
      assert(base && "ownership component must not be root of lvalue path");
      auto &TL = SGF.getTypeLowering(base.getType());

      auto value = std::move(valueSource).getAsSingleValue(SGF).forward(SGF);
      SGF.emitSemanticStore(loc, value, base.getValue(), TL,
                            IsNotInitialization);
    }

    std::unique_ptr<LogicalPathComponent>
    clone(SILGenFunction &SGF, SILLocation loc) const override {
      LogicalPathComponent *clone = new OwnershipComponent(getTypeData());
      return std::unique_ptr<LogicalPathComponent>(clone);
    }

    void dump(raw_ostream &OS, unsigned indent) const override {
      OS.indent(indent) << "OwnershipComponent(...)\n";
    }
  };
} // end anonymous namespace

LValue LValue::forValue(SGFAccessKind accessKind, ManagedValue value,
                        CanType substFormalType) {
  if (value.getType().isObject()) {
    LValueTypeData typeData = getValueTypeData(accessKind, substFormalType,
                                               value.getValue());

    LValue lv;
    lv.add<ValueComponent>(value, std::nullopt, typeData, /*isRValue=*/true);
    return lv;
  } else {
    // Treat an address-only value as an lvalue we only read from.
    if (!value.isLValue())
      value = ManagedValue::forLValue(value.getValue());
    return forAddress(accessKind, value, std::nullopt,
                      AbstractionPattern(substFormalType), substFormalType);
  }
}

LValue LValue::forAddress(SGFAccessKind accessKind, ManagedValue address,
                          std::optional<SILAccessEnforcement> enforcement,
                          AbstractionPattern origFormalType,
                          CanType substFormalType) {
  assert(address.isLValue());
  LValueTypeData typeData = {
    accessKind, origFormalType, substFormalType,
    address.getType().getASTType()
  };

  LValue lv;
  lv.add<ValueComponent>(address, enforcement, typeData);
  return lv;
}

void LValue::addMemberComponent(SILGenFunction &SGF, SILLocation loc,
                                AbstractStorageDecl *storage,
                                SubstitutionMap subs,
                                LValueOptions options,
                                bool isSuper,
                                SGFAccessKind accessKind,
                                AccessStrategy accessStrategy,
                                CanType formalRValueType,
                                PreparedArguments &&indices,
                                ArgumentList *argListForDiagnostics) {
  if (auto var = dyn_cast<VarDecl>(storage)) {
    assert(indices.isNull());
    addMemberVarComponent(SGF, loc, var, subs, options, isSuper,
                          accessKind, accessStrategy, formalRValueType);
  } else {
    auto subscript = cast<SubscriptDecl>(storage);
    addMemberSubscriptComponent(SGF, loc, subscript, subs, options, isSuper,
                                accessKind, accessStrategy, formalRValueType,
                                std::move(indices), argListForDiagnostics);
  }
}

void LValue::addOrigToSubstComponent(SILType loweredSubstType) {
  loweredSubstType = loweredSubstType.getObjectType();
  assert(getTypeOfRValue() != loweredSubstType &&
         "reabstraction component is unnecessary!");

  // Peephole away complementary reabstractions.
  assert(!Path.empty() && "adding translation component to empty l-value");
  if (Path.back()->getKind() == PathComponent::SubstToOrigKind) {
    // But only if the lowered type matches exactly.
    if (Path[Path.size()-2]->getTypeOfRValue() == loweredSubstType) {
      Path.pop_back();
      return;
    }
    // TODO: combine reabstractions; this doesn't matter all that much
    // for most things, but it can be dramatically better for function
    // reabstraction.
  }

  auto substFormalType = getSubstFormalType();
  LValueTypeData typeData = {
    getAccessKind(),
    AbstractionPattern(substFormalType),
    substFormalType,
    loweredSubstType.getASTType()
  };
  add<OrigToSubstComponent>(typeData, getOrigFormalType());
}

void LValue::addSubstToOrigComponent(AbstractionPattern origType,
                                     SILType loweredSubstType) {
  loweredSubstType = loweredSubstType.getObjectType();
  assert(getTypeOfRValue() != loweredSubstType &&
         "reabstraction component is unnecessary!");

  // Peephole away complementary reabstractions.
  assert(!Path.empty() && "adding translation component to empty l-value");
  if (Path.back()->getKind() == PathComponent::OrigToSubstKind) {
    // But only if the lowered type matches exactly.
    if (Path[Path.size()-2]->getTypeOfRValue() == loweredSubstType) {
      Path.pop_back();
      return;
    }
    // TODO: combine reabstractions; this doesn't matter all that much
    // for most things, but it can be dramatically better for function
    // reabstraction.
  }

  LValueTypeData typeData = {
    getAccessKind(),
    origType,
    getSubstFormalType(),
    loweredSubstType.getASTType()
  };
  add<SubstToOrigComponent>(typeData);
}

void LValue::dump() const {
  dump(llvm::errs());
}

void LValue::dump(raw_ostream &OS, unsigned indent) const {
  for (const auto &component : *this) {
    component->dump(OS, indent);
  }
}

LValue SILGenFunction::emitLValue(Expr *e, SGFAccessKind accessKind,
                                  LValueOptions options) {
  // Some lvalue nodes (namely BindOptionalExprs) require immediate evaluation
  // of their subexpression, so we must have a writeback scope open while
  // building an lvalue.
  assert(isInFormalEvaluationScope() && "must be in a formal evaluation scope");

  LValue r = SILGenLValue(*this).visit(e, accessKind, options);
  // If the final component has an abstraction change, introduce a
  // reabstraction component.
  auto substFormalType = r.getSubstFormalType();
  auto loweredSubstType = getLoweredType(substFormalType);
  if (r.getTypeOfRValue() != loweredSubstType.getObjectType()) {
    // Logical components always re-abstract back to the substituted
    // type.
    assert(r.isLastComponentPhysical());
    r.addOrigToSubstComponent(loweredSubstType);
  }
  return r;
}

static LValue visitRecInOut(SILGenLValue &SGL, Expr *e,
                            SGFAccessKind accessKind,
                            LValueOptions options, AbstractionPattern orig) {
  auto lv = SGL.visit(e, accessKind, options);
  // If necessary, handle reabstraction with a SubstToOrigComponent that handles
  // writeback in the original representation.
  if (orig.isValid()) {
    auto &origTL = SGL.SGF.getTypeLowering(orig, e->getType()->getRValueType());
    if (lv.getTypeOfRValue() != origTL.getLoweredType().getObjectType())
      lv.addSubstToOrigComponent(orig, origTL.getLoweredType().getObjectType());
  }

  return lv;
}

// Otherwise we have a non-lvalue type (references, values, metatypes,
// etc). These act as the root of a logical lvalue.
static ManagedValue visitRecNonInOutBase(SILGenLValue &SGL, Expr *e,
                                         SGFAccessKind accessKind,
                                         LValueOptions options,
                                         AbstractionPattern orig) {
  auto &SGF = SGL.SGF;

  // For an rvalue base, apply the reabstraction (if any) eagerly, since
  // there's no need for writeback.
  if (orig.isValid()) {
    return SGF.emitRValueAsOrig(
        e, orig, SGF.getTypeLowering(orig, e->getType()->getRValueType()));
  }

  // Ok, at this point we know that re-abstraction is not required.

  SGFContext ctx;

  if (auto *dre = dyn_cast<DeclRefExpr>(e)) {
    // Any reference to "self" can be done at +0 so long as it is a direct
    // access, since we know it is guaranteed.
    //
    // TODO: it would be great to factor this even lower into SILGen to the
    // point where we can see that the parameter is +0 guaranteed.  Note that
    // this handles the case in initializers where there is actually a stack
    // allocation for it as well.
    if (isa<ParamDecl>(dre->getDecl()) &&
        dre->getDecl()->getName() == SGF.getASTContext().Id_self &&
        dre->getDecl()->isImplicit()) {
      ctx = SGFContext::AllowGuaranteedPlusZero;
      if (SGF.SelfInitDelegationState != SILGenFunction::NormalSelf) {
        // This needs to be inlined since there is a Formal Evaluation Scope
        // in emitRValueForDecl that causing any borrow for this LValue to be
        // popped too soon.
        auto *vd = cast<ParamDecl>(dre->getDecl());
        CanType formalRValueType = dre->getType()->getCanonicalType();
        ManagedValue selfLValue =
          SGF.emitAddressOfLocalVarDecl(dre, vd, formalRValueType,
                                        SGFAccessKind::OwnedObjectRead);
        selfLValue = SGF.emitFormalEvaluationRValueForSelfInDelegationInit(
                            e, formalRValueType,
                            selfLValue.getLValueAddress(), ctx)
                         .getAsSingleValue(SGF, e);

        return selfLValue;
      }
    }

    if (auto *VD = dyn_cast<VarDecl>(dre->getDecl())) {
      // All let values are guaranteed to be held alive across their lifetime,
      // and won't change once initialized.  Any loaded value is good for the
      // duration of this expression evaluation.
      if (VD->isLet()) {
        ctx = SGFContext::AllowGuaranteedPlusZero;
      }
    }
  }
  
  if (SGF.SGM.Types.isIndirectPlusZeroSelfParameter(e->getType())) {
    ctx = SGFContext::AllowGuaranteedPlusZero;
  }

  ManagedValue mv = SGF.emitRValueAsSingleValue(e, ctx);
  if (mv.isPlusZeroRValueOrTrivial())
    return mv;

  // Any temporaries needed to materialize the lvalue must be destroyed when
  // at the end of the lvalue's formal evaluation scope.
  // e.g. for foo(self.bar)
  //   %self = load [copy] %ptr_self
  //   %rvalue = barGetter(%self)
  //   destroy_value %self // self must be released before calling foo.
  //   foo(%rvalue)
  SILValue value = mv.forward(SGF);
  return SGF.emitFormalAccessManagedRValueWithCleanup(CleanupLocation(e),
                                                      value);
}

static CanType getBaseFormalType(Expr *baseExpr) {
  return baseExpr->getType()->getWithoutSpecifierType()->getCanonicalType();
}

class LLVM_LIBRARY_VISIBILITY SILGenBorrowedBaseVisitor
    : public Lowering::ExprVisitor<SILGenBorrowedBaseVisitor, LValue,
                                   SGFAccessKind, LValueOptions> {
public:
  SILGenLValue &SGL;
  SILGenFunction &SGF;
  AbstractionPattern Orig;

  SILGenBorrowedBaseVisitor(SILGenLValue &SGL,
                            SILGenFunction &SGF,
                            AbstractionPattern Orig)
      : SGL(SGL), SGF(SGF), Orig(Orig) {}

  static bool isNonCopyableBaseBorrow(SILGenFunction &SGF, Expr *e) {
    if (auto *m = dyn_cast<MemberRefExpr>(e)) {
      // If our m is a pure noncopyable type or our base is, we need to perform
      // a noncopyable base borrow.
      //
      // DISCUSSION: We can have a noncopyable member_ref_expr with a copyable
      // base if the noncopyable member_ref_expr is from a computed method. In
      // such a case, we want to ensure that we wrap things the right way.
      return m->getType()->isNoncopyable() ||
          m->getBase()->getType()->isNoncopyable();
    }

    if (auto *le = dyn_cast<LoadExpr>(e)) {
      // Noncopyable type is obviously noncopyable.
      if (le->getType()->isNoncopyable()) {
        return true;
      }
      // Otherwise, check if the thing we're loading from is a noncopyable
      // param decl.
      e = le->getSubExpr();
      // fall through...
    }
    
    if (auto *de = dyn_cast<DeclRefExpr>(e)) {
      // Noncopyable type is obviously noncopyable.
      if (de->getType()->isNoncopyable()) {
        return true;
      }
      // If the decl ref refers to a parameter with an explicit ownership
      // modifier, it is not implicitly copyable.
      if (auto pd = dyn_cast<ParamDecl>(de->getDecl())) {
        switch (pd->getSpecifier()) {
        case ParamSpecifier::Borrowing:
        case ParamSpecifier::Consuming:
          return true;
        case ParamSpecifier::Default:
        case ParamSpecifier::InOut:
        case ParamSpecifier::LegacyShared:
        case ParamSpecifier::LegacyOwned:
        case ParamSpecifier::ImplicitlyCopyableConsuming:
          return false;
        }
        if (pd->hasResultDependsOn()) {
          return true;
        }
      }
    }
    return false;
  }

  /// For any other Expr's that this SILGenBorrowedBaseVisitor doesn't already
  /// define a visitor stub, defer back to SILGenLValue's visitRec as it is
  /// most-likely a non-lvalue root expression.
  LValue visitExpr(Expr *e, SGFAccessKind accessKind, LValueOptions options) {
    assert(!isNonCopyableBaseBorrow(SGF, e)
            && "unexpected recursion in SILGenLValue::visitRec!");

    return SGL.visitRec(e, accessKind, options, Orig);
  }

  LValue visitMemberRefExpr(MemberRefExpr *e, SGFAccessKind accessKind,
                            LValueOptions options) {
    // If we have a member_ref_expr, we create a component that will when we
    // evaluate the lvalue,
    VarDecl *var = cast<VarDecl>(e->getMember().getDecl());

    assert(!e->getType()->is<LValueType>());

    auto accessSemantics = e->getAccessSemantics();
    AccessStrategy strategy = var->getAccessStrategy(
        accessSemantics, getFormalAccessKind(accessKind),
        SGF.SGM.M.getSwiftModule(), SGF.F.getResilienceExpansion());

    auto baseFormalType = getBaseFormalType(e->getBase());
    LValue lv = visit(
        e->getBase(),
        getBaseAccessKind(SGF.SGM, var, accessKind, strategy, baseFormalType,
                          /*for borrow*/ true),
        getBaseOptions(options, strategy));
    std::optional<ActorIsolation> actorIso;
    if (e->isImplicitlyAsync())
      actorIso = getActorIsolation(var);
    lv.addMemberVarComponent(SGF, e, var, e->getMember().getSubstitutions(),
                             options, e->isSuper(), accessKind, strategy,
                             getSubstFormalRValueType(e),
                             false /*is on self parameter*/, actorIso);

    SGF.SGM.noteMemberRefExpr(e);

    return lv;
  }

  ManagedValue emitImmediateBaseValue(Expr *e) {
    // We are going to immediately use this base value, so we want to borrow it.
    ManagedValue mv =
        SGF.emitRValueAsSingleValue(e, SGFContext::AllowImmediatePlusZero);
    if (mv.isPlusZeroRValueOrTrivial())
      return mv;

    // Any temporaries needed to materialize the lvalue must be destroyed when
    // at the end of the lvalue's formal evaluation scope.
    // e.g. for foo(self.bar)
    //   %self = load [copy] %ptr_self
    //   %rvalue = barGetter(%self)
    //   destroy_value %self // self must be released before calling foo.
    //   foo(%rvalue)
    SILValue value = mv.forward(SGF);
    return SGF.emitFormalAccessManagedRValueWithCleanup(CleanupLocation(e),
                                                        value);
  }

  LValue visitDeclRefExpr(DeclRefExpr *e, SGFAccessKind accessKind,
                          LValueOptions options) {
    if (accessKind == SGFAccessKind::BorrowedObjectRead) {
      auto rv = emitImmediateBaseValue(e);
      CanType formalType = getSubstFormalRValueType(e);
      auto typeData = getValueTypeData(accessKind, formalType, rv.getValue());
      LValue lv;
      lv.add<ValueComponent>(rv, std::nullopt, typeData, /*isRValue=*/true);
      return lv;
    }

    return SGL.visitDeclRefExpr(e, accessKind, options);
  }

  LValue visitLoadExpr(LoadExpr *e, SGFAccessKind accessKind,
                       LValueOptions options) {
    // TODO: orig abstraction pattern.
    LValue lv = SGL.visitRec(e->getSubExpr(),
                             SGFAccessKind::BorrowedAddressRead, options);
    CanType formalType = getSubstFormalRValueType(e);
    LValueTypeData typeData{accessKind, AbstractionPattern(formalType),
                            formalType, lv.getTypeOfRValue().getASTType()};
    lv.add<BorrowValueComponent>(typeData);
    return lv;
  }
};

LValue SILGenLValue::visitRec(Expr *e, SGFAccessKind accessKind,
                              LValueOptions options, AbstractionPattern orig) {
  // First see if we have an lvalue type. If we do, then quickly handle that and
  // return.
  if (e->getType()->is<LValueType>() || e->isSemanticallyInOutExpr()) {
    return visitRecInOut(*this, e, accessKind, options, orig);
  }
  
  // If the base is a load of a noncopyable type (or, eventually, when we have
  // a `borrow x` operator, the operator is used on the base here), we want to
  // apply the lvalue within a formal access to the original value instead of
  // an actual loaded copy.
  if (SILGenBorrowedBaseVisitor::isNonCopyableBaseBorrow(SGF, e)) {
    SILGenBorrowedBaseVisitor visitor(*this, SGF, orig);
    auto accessKind = SGFAccessKind::BorrowedObjectRead;
    assert(!e->getType()->is<LValueType>()
        && "maybe need SGFAccessKind::BorrowedAddressRead ?");
    return visitor.visit(e, accessKind, options);
  }

  // Otherwise we have a non-lvalue type (references, values, metatypes,
  // etc). These act as the root of a logical lvalue. Compute the root value,
  // wrap it in a ValueComponent, and return it for our caller.
  ManagedValue rv = visitRecNonInOutBase(*this, e, accessKind, options, orig);
  CanType formalType = getSubstFormalRValueType(e);
  auto typeData = getValueTypeData(accessKind, formalType, rv.getValue());
  LValue lv;
  lv.add<ValueComponent>(rv, std::nullopt, typeData, /*isRValue=*/true);
  return lv;
}

LValue SILGenLValue::visitExpr(Expr *e, SGFAccessKind accessKind,
                               LValueOptions options) {
  e->dump(llvm::errs());
  llvm::errs() << "\n";
  llvm_unreachable("unimplemented lvalue expr");
}

namespace {
  /// A CRTP class for emitting accesses.
  template <class Impl, class StorageType>
  struct AccessEmitter {
    SILGenFunction &SGF;
    StorageType *Storage;
    SubstitutionMap Subs;
    CanType FormalRValueType;
    SGFAccessKind AccessKind;

    Impl &asImpl() { return static_cast<Impl&>(*this); }

    AccessEmitter(SILGenFunction &SGF, StorageType *storage,
                  SubstitutionMap subs, SGFAccessKind accessKind,
                  CanType formalRValueType)
      : SGF(SGF), Storage(storage), Subs(subs),
        FormalRValueType(formalRValueType), AccessKind(accessKind) {}

    void emitUsingStrategy(AccessStrategy strategy) {
      switch (strategy.getKind()) {
      case AccessStrategy::Storage: {
        auto typeData =
            getPhysicalStorageTypeData(SGF.getTypeExpansionContext(), SGF.SGM,
                                       AccessKind, Storage, Subs,
                                       FormalRValueType);
        return asImpl().emitUsingStorage(typeData);
      }

      case AccessStrategy::DirectToAccessor:
        return asImpl()
            .emitUsingAccessor(strategy.getAccessor(),
                               /*isDirect=*/true);

      case AccessStrategy::DispatchToAccessor:
        return asImpl().emitUsingAccessor(strategy.getAccessor(),
                                          /*isDirect=*/false);

      case AccessStrategy::MaterializeToTemporary: {
        auto typeData = getLogicalStorageTypeData(
            SGF.getTypeExpansionContext(), SGF.SGM, AccessKind, FormalRValueType);
        return asImpl().emitUsingMaterialization(strategy.getReadStrategy(),
                                                 strategy.getWriteStrategy(),
                                                 typeData);
      }

      case AccessStrategy::DispatchToDistributedThunk:
        return asImpl().emitUsingDistributedThunk();
      }
      llvm_unreachable("unknown kind");
    }

    void emitUsingAccessor(AccessorKind accessorKind,
                           bool isDirect) {
      auto accessor =
          SGF.getAccessorDeclRef(Storage->getOpaqueAccessor(accessorKind));

      switch (accessorKind) {
      case AccessorKind::Set: {
        LLVM_FALLTHROUGH;
      }
      case AccessorKind::Get:
      case AccessorKind::DistributedGet: {
        auto typeData = getLogicalStorageTypeData(
            SGF.getTypeExpansionContext(), SGF.SGM, AccessKind, FormalRValueType);
        return asImpl().emitUsingGetterSetter(accessor, isDirect, typeData);
      }

      case AccessorKind::Address:
      case AccessorKind::MutableAddress: {
        auto typeData =
            getPhysicalStorageTypeData(SGF.getTypeExpansionContext(), SGF.SGM,
                                       AccessKind, Storage, Subs,
                                       FormalRValueType);
        return asImpl().emitUsingAddressor(accessor, isDirect, typeData);
      }

      case AccessorKind::Read:
      case AccessorKind::Modify: {
        auto typeData =
            getPhysicalStorageTypeData(SGF.getTypeExpansionContext(), SGF.SGM,
                                       AccessKind, Storage, Subs,
                                       FormalRValueType);
        return asImpl().emitUsingCoroutineAccessor(accessor, isDirect,
                                                   typeData);
      }

      case AccessorKind::WillSet:
      case AccessorKind::DidSet:
        llvm_unreachable("cannot use accessor directly to perform an access");

      case AccessorKind::Init: {
        auto typeData =
            getLogicalStorageTypeData(SGF.getTypeExpansionContext(), SGF.SGM,
                                      AccessKind, FormalRValueType);
        return asImpl().emitUsingInitAccessor(accessor, isDirect, typeData);
      }
      }

      llvm_unreachable("bad kind");
    }
  };
}

static LValue emitLValueForNonMemberVarDecl(
    SILGenFunction &SGF, SILLocation loc, ConcreteDeclRef declRef,
    CanType formalRValueType, SGFAccessKind accessKind, LValueOptions options,
    AccessSemantics semantics, std::optional<ActorIsolation> actorIso) {
  LValue lv;

  auto *var = cast<VarDecl>(declRef.getDecl());
  auto subs = declRef.getSubstitutions();
  if (!subs)
    subs = SGF.F.getForwardingSubstitutionMap();

  auto access = getFormalAccessKind(accessKind);
  auto strategy =
      var->getAccessStrategy(semantics, access, SGF.SGM.M.getSwiftModule(),
                             SGF.F.getResilienceExpansion());

  lv.addNonMemberVarComponent(SGF, loc, var, subs, options, accessKind,
                              strategy, formalRValueType, actorIso);

  return lv;
}

/// Map a SILGen access kind back to an AST access kind.
static AccessKind mapAccessKind(SGFAccessKind accessKind) {
  switch (accessKind) {
  case SGFAccessKind::IgnoredRead:
  case SGFAccessKind::BorrowedAddressRead:
  case SGFAccessKind::BorrowedObjectRead:
  case SGFAccessKind::OwnedAddressRead:
  case SGFAccessKind::OwnedObjectRead:
    return AccessKind::Read;

  case SGFAccessKind::Write:
    return AccessKind::Write;

  case SGFAccessKind::OwnedAddressConsume:
  case SGFAccessKind::OwnedObjectConsume:
  case SGFAccessKind::ReadWrite:
    return AccessKind::ReadWrite;
  }
  llvm_unreachable("covered switch");
}

void LValue::addNonMemberVarComponent(
    SILGenFunction &SGF, SILLocation loc, VarDecl *var, SubstitutionMap subs,
    LValueOptions options, SGFAccessKind accessKind, AccessStrategy strategy,
    CanType formalRValueType, std::optional<ActorIsolation> actorIso) {
  struct NonMemberVarAccessEmitter :
      AccessEmitter<NonMemberVarAccessEmitter, VarDecl> {
    LValue &LV;
    SILLocation Loc;
    LValueOptions Options;
    std::optional<ActorIsolation> ActorIso;

    NonMemberVarAccessEmitter(SILGenFunction &SGF, SILLocation loc,
                              VarDecl *var, SubstitutionMap subs,
                              SGFAccessKind accessKind,
                              CanType formalRValueType, LValueOptions options,
                              std::optional<ActorIsolation> actorIso,
                              LValue &lv)
        : AccessEmitter(SGF, var, subs, accessKind, formalRValueType), LV(lv),
          Loc(loc), Options(options), ActorIso(actorIso) {}

    void emitUsingAddressor(SILDeclRef addressor, bool isDirect,
                            LValueTypeData typeData) {
      assert(!ActorIso);
      SILType storageType =
        SGF.getLoweredType(Storage->getTypeInContext()).getAddressType();
      LV.add<AddressorComponent>(Storage, addressor,
                                 /*isSuper=*/false, isDirect, Subs,
                                 CanType(), typeData, storageType, nullptr,
                                 PreparedArguments(),
                                 /* isOnSelfParameter */ false);
    }

    void emitUsingCoroutineAccessor(SILDeclRef accessor, bool isDirect,
                                    LValueTypeData typeData) {
      assert(!ActorIso);
      LV.add<CoroutineAccessorComponent>(
          Storage, accessor,
          /*isSuper*/ false, isDirect, Subs, CanType(), typeData, nullptr,
          PreparedArguments(), /*isOnSelfParameter*/ false);
    }

    void emitUsingGetterSetter(SILDeclRef accessor,
                               bool isDirect,
                               LValueTypeData typeData) {
      LV.add<GetterSetterComponent>(
          Storage, accessor,
          /*isSuper=*/false, isDirect, Subs, CanType(), typeData,
          nullptr, PreparedArguments(),
          /*isOnSelfParameter=*/false,
          ActorIso);
    }

    void emitUsingMaterialization(AccessStrategy readStrategy,
                                  AccessStrategy writeStrategy,
                                  LValueTypeData typeData) {
      assert(!ActorIso);
      LV.add<MaterializeToTemporaryComponent>(
          Storage, /*super*/ false, Subs, Options, readStrategy,
          writeStrategy,
          /*base type*/ CanType(), typeData, nullptr, PreparedArguments(),
          /* isOnSelfParameter */ false);
    }

    void emitUsingStorage(LValueTypeData typeData) {
      // If it's a physical value (e.g. a local variable in memory), push its
      // address.

      // Check for a local (possibly captured) variable.
      auto astAccessKind = mapAccessKind(this->AccessKind);
      auto address = SGF.maybeEmitValueOfLocalVarDecl(Storage, astAccessKind);

      bool isLazyInitializedGlobal = false;

      // The only other case that should get here is a global variable.
      if (!address) {
        address = SGF.emitGlobalVariableRef(Loc, Storage, ActorIso);
        isLazyInitializedGlobal = Storage->isLazilyInitializedGlobal();
      } else {
        assert((!ActorIso || Storage->isTopLevelGlobal()) &&
               "local var should not be actor isolated!");
      }

      if (!address.isLValue()) {
        assert((AccessKind == SGFAccessKind::BorrowedObjectRead
                || AccessKind == SGFAccessKind::BorrowedAddressRead)
               && "non-borrow component requires an address base");
        LV.add<ValueComponent>(address, std::nullopt, typeData,
                               /*rvalue*/ true);
        LV.add<BorrowValueComponent>(typeData);
        return;
      }

      std::optional<SILAccessEnforcement> enforcement;
      if (!Storage->isLet()) {
        if (Options.IsNonAccessing) {
          enforcement = std::nullopt;
        } else if (Storage->getDeclContext()->isLocalContext()) {
          enforcement = SGF.getUnknownEnforcement(Storage);
        } else if (Storage->getDeclContext()->isModuleScopeContext()) {
          enforcement = SGF.getDynamicEnforcement(Storage);
        } else {
          assert(Storage->getDeclContext()->isTypeContext() &&
                 !Storage->isInstanceMember());
          enforcement = SGF.getDynamicEnforcement(Storage);
        }
      }

      LV.add<ValueComponent>(address, enforcement, typeData,
                             /*isRValue=*/false, ActorIso,
                             isLazyInitializedGlobal);

      if (address.getType().is<ReferenceStorageType>())
        LV.add<OwnershipComponent>(typeData);
    }

    void emitUsingDistributedThunk() {
      llvm_unreachable("cannot dispatch non-member var via distributed thunk");
    }

    void emitUsingInitAccessor(SILDeclRef accessor, bool isDirect,
                               LValueTypeData typeData) {
      llvm_unreachable("cannot dispatch non-member var via init accessor");
    }

  } emitter(SGF, loc, var, subs, accessKind, formalRValueType, options,
            actorIso, *this);

  emitter.emitUsingStrategy(strategy);
}

ManagedValue
SILGenFunction::maybeEmitValueOfLocalVarDecl(
    VarDecl *var, AccessKind accessKind) {
  // For local decls, use the address we allocated or the value if we have it.
  auto It = VarLocs.find(var);
  if (It != VarLocs.end()) {
    SILValue ptr = It->second.value;

    // If this has an address, return it.  By-value let bindings have no address.
    if (ptr->getType().isAddress())
      return ManagedValue::forLValue(ptr);

    // Otherwise, it is an RValue let. SILGen is inconsistent here and may store
    // either an "unmanaged borrowed" owned value that must be borrowed before
    // use /or/ it may store an already borrowed value. In the case of the
    // former, we don't want to proactively emit a borrow here.
    //
    // TODO: integrate this with how callers want these values so we can do
    // something more semantic than just forUnmanagedOwnedValue.
    if (ptr->getOwnershipKind().isCompatibleWith(OwnershipKind::Guaranteed))
      return ManagedValue::forBorrowedRValue(ptr);
    return ManagedValue::forUnmanagedOwnedValue(ptr);
  }

  // Otherwise, it's non-local or not stored.
  return ManagedValue();
}

ManagedValue
SILGenFunction::emitAddressOfLocalVarDecl(SILLocation loc, VarDecl *var,
                                          CanType formalRValueType,
                                          SGFAccessKind accessKind) {
  assert(var->getDeclContext()->isLocalContext());
  assert(var->getImplInfo().isSimpleStored());
  AccessKind astAccessKind = mapAccessKind(accessKind);
  
  assert(!var->isAsyncLet() && "async let does not have an address");
  
  auto address = maybeEmitValueOfLocalVarDecl(var, astAccessKind);
  assert(address.isLValue());
  return address;
}

RValue SILGenFunction::emitRValueForNonMemberVarDecl(SILLocation loc,
                                                     ConcreteDeclRef declRef,
                                                     CanType formalRValueType,
                                                     AccessSemantics semantics,
                                                     SGFContext C) {
  // Any writebacks for this access are tightly scoped.
  FormalEvaluationScope scope(*this);

  auto *var = cast<VarDecl>(declRef.getDecl());
  // If the variable is part of an async let, get the result from the child
  // task.
  if (var->isAsyncLet()) {
    return RValue(*this, loc, formalRValueType,
                  emitReadAsyncLetBinding(loc, var));
  }

  // If our localValue is a closure captured box of a noncopyable type, project
  // it out eagerly and insert a no_consume_or_assign constraint.
  ManagedValue localValue = maybeEmitValueOfLocalVarDecl(var, AccessKind::Read);

  // If this VarDecl is represented as an address, emit it as an lvalue, then
  // perform a load to get the rvalue.
  if (localValue && localValue.isLValue()) {
    bool guaranteedValid = false;
    IsTake_t shouldTake = IsNotTake;

    // We should only end up in this path for local and global variables,
    // i.e. ones whose lifetime is assured for the duration of the evaluation.
    // Therefore, if the variable is a constant, the value is guaranteed
    // valid as well.
    if (var->isLet())
      guaranteedValid = true;

    // Protect the lvalue read with access markers. The !is<LValueType> assert
    // above ensures that the "LValue" is actually immutable, so we use an
    // unenforced access marker.
    SILValue destAddr = localValue.getLValueAddress();
    SILValue accessAddr = UnenforcedFormalAccess::enter(*this, loc, destAddr,
                                                        SILAccessKind::Read);

    auto isEffectivelyMarkUnresolvedInst = [](auto *inst) -> bool {
      if (!inst)
        return false;
      if (isa<MarkUnresolvedNonCopyableValueInst>(inst))
        return true;
      auto *ddi = dyn_cast<DropDeinitInst>(inst);
      if (!ddi)
        return false;
      return isa<MarkUnresolvedNonCopyableValueInst>(ddi->getOperand());
    };

    if (accessAddr->getType().isMoveOnly() &&
        !isEffectivelyMarkUnresolvedInst(
            accessAddr->getDefiningInstruction())) {
      auto kind =
          MarkUnresolvedNonCopyableValueInst::CheckKind::NoConsumeOrAssign;
      // When loading an rvalue, we should never need to modify the place
      // we're loading from.
      accessAddr =
          B.createMarkUnresolvedNonCopyableValueInst(loc, accessAddr, kind);
    }

    auto propagateRValuePastAccess = [&](RValue &&rvalue) {
      // Check if a new begin_access was emitted and returned as the
      // RValue. This means that the load did not actually load. If so, then
      // fix the rvalue to begin_access operand. The end_access cleanup
      // doesn't change. FIXME: this can't happen with sil-opaque-values.
      if (accessAddr != destAddr && rvalue.isComplete()
          && rvalue.isPlusZero(*this) && !isa<TupleType>(rvalue.getType())) {
        auto mv = std::move(rvalue).getScalarValue();
        if (mv.getValue() == accessAddr)
          mv = std::move(mv).transform(
              cast<BeginAccessInst>(accessAddr)->getOperand());
        return RValue(*this, loc, formalRValueType, mv);
      }
      return std::move(rvalue);
    };
    // If we have self, see if we are in an 'init' delegation sequence. If so,
    // call out to the special delegation init routine. Otherwise, use the
    // normal RValue emission logic.
    if (var->getName() == getASTContext().Id_self &&
        SelfInitDelegationState != NormalSelf) {
      auto rvalue =
        emitRValueForSelfInDelegationInit(loc, formalRValueType, accessAddr, C);
      return propagateRValuePastAccess(std::move(rvalue));
    }

    // Avoid computing an abstraction pattern for local variables.
    // This is a slight compile-time optimization, but more importantly
    // it avoids problems where locals don't always have interface types.
    if (var->getDeclContext()->isLocalContext()) {
      auto &rvalueTL = getTypeLowering(formalRValueType);
      auto rvalue = RValue(*this, loc, formalRValueType,
                           emitLoad(loc, accessAddr, rvalueTL,
                                    C, shouldTake, guaranteedValid));

      return propagateRValuePastAccess(std::move(rvalue));
    }

    // Otherwise, do the full thing where we potentially bridge and
    // reabstract the declaration.
    auto origFormalType = SGM.Types.getAbstractionPattern(var);
    auto rvalue = RValue(*this, loc, formalRValueType,
                         emitLoad(loc, accessAddr, origFormalType,
                                  formalRValueType,
                                  getTypeLowering(formalRValueType),
                                  C, shouldTake, guaranteedValid));
    return propagateRValuePastAccess(std::move(rvalue));
  }

  // For local decls, use the address we allocated or the value if we have it.
  if (localValue) {
    // Mutable lvalue and address-only 'let's are LValues.
    assert(!localValue.getType().isAddress() &&
           "LValue cases should be handled above");

    SILValue Scalar = localValue.getUnmanagedValue();

    // For weak and unowned types, convert the reference to the right
    // pointer.
    if (Scalar->getType().is<ReferenceStorageType>()) {
      Scalar = emitConversionToSemanticRValue(loc, Scalar,
                                             getTypeLowering(formalRValueType));
      // emitConversionToSemanticRValue always produces a +1 strong result.
      return RValue(*this, loc, formalRValueType,
                    emitManagedRValueWithCleanup(Scalar));
    }

    // This is a let, so we can make guarantees, so begin the borrow scope.
    ManagedValue Result = emitManagedBeginBorrow(loc, Scalar);

    // If the client can't handle a +0 result, retain it to get a +1.
    // This is a 'let', so we can make guarantees.
    return RValue(*this, loc, formalRValueType,
                  C.isGuaranteedPlusZeroOk()
                    ? Result : Result.copyUnmanaged(*this, loc));
  }

  LValue lv = emitLValueForNonMemberVarDecl(
      *this, loc, declRef, formalRValueType, SGFAccessKind::OwnedObjectRead,
      LValueOptions(), semantics,
      /*actorIsolation=*/std::nullopt);
  return emitLoadOfLValue(loc, std::move(lv), C);
}

LValue SILGenLValue::visitDiscardAssignmentExpr(DiscardAssignmentExpr *e,
                                                SGFAccessKind accessKind,
                                                LValueOptions options) {
  LValueTypeData typeData = getValueTypeData(SGF, accessKind, e);

  SILValue address = SGF.emitTemporaryAllocation(e,
                                               SILType::getPrimitiveObjectType(
                                                 typeData.TypeOfRValue));
  address = SGF.B.createMarkUninitialized(e, address,
                                          MarkUninitializedInst::Var);
  LValue lv;
  lv.add<ValueComponent>(SGF.emitManagedBufferWithCleanup(address),
                         std::nullopt, typeData);
  return lv;
}


LValue SILGenLValue::visitDeclRefExpr(DeclRefExpr *e, SGFAccessKind accessKind,
                                      LValueOptions options) {
  std::optional<ActorIsolation> actorIso;
  if (e->isImplicitlyAsync())
    actorIso = getActorIsolation(e->getDecl());

  return emitLValueForNonMemberVarDecl(SGF, e, e->getDeclRef(),
                                       getSubstFormalRValueType(e),
                                       accessKind, options,
                                       e->getAccessSemantics(),
                                       actorIso);
}

LValue SILGenLValue::visitOpaqueValueExpr(OpaqueValueExpr *e,
                                          SGFAccessKind accessKind,
                                          LValueOptions options) {
  // Handle an opaque lvalue that refers to an opened existential.
  auto known = SGF.OpaqueValueExprs.find(e);
  if (known != SGF.OpaqueValueExprs.end()) {
    // Dig the open-existential expression out of the list.
    OpenExistentialExpr *opened = known->second;
    SGF.OpaqueValueExprs.erase(known);

    // Do formal evaluation of the underlying existential lvalue.
    auto lv = visitRec(opened->getExistentialValue(), accessKind, options);
    lv = SGF.emitOpenExistentialLValue(
        opened, std::move(lv),
        CanArchetypeType(opened->getOpenedArchetype()),
        e->getType()->getWithoutSpecifierType()->getCanonicalType(),
        accessKind);
    return lv;
  }

  assert(SGF.OpaqueValues.count(e) && "Didn't bind OpaqueValueExpr");
  auto value = SGF.OpaqueValues[e];

  RegularLocation loc(e);
  LValue lv;
  lv.add<ValueComponent>(value.formalAccessBorrow(SGF, loc), std::nullopt,
                         getValueTypeData(SGF, accessKind, e));
  return lv;
}

LValue SILGenLValue::visitPackElementExpr(PackElementExpr *e,
                                          SGFAccessKind accessKind,
                                          LValueOptions options) {
  auto refExpr = e->getPackRefExpr();

  auto substFormalType = e->getType()->getCanonicalType();

  if (auto declRefExpr = dyn_cast<DeclRefExpr>(refExpr)) {
    if (auto var = dyn_cast<VarDecl>(declRefExpr->getDecl())) {
      auto origFormalType = SGF.SGM.Types.getAbstractionPattern(var);
      auto elementTy =
        SGF.getLoweredType(origFormalType, substFormalType).getAddressType();
      SILValue packAddr =
        SGF.emitAddressOfLocalVarDecl(declRefExpr, var,
                                      substFormalType,
                                      accessKind)
           .getLValueAddress();
      auto packIndex = SGF.getInnermostPackExpansion()->ExpansionIndex;
      auto elementAddr =
        SGF.B.createPackElementGet(e, packIndex, packAddr, elementTy);
      return LValue::forAddress(
          accessKind, ManagedValue::forLValue(elementAddr),
          /*access enforcement*/ std::nullopt, origFormalType, substFormalType);
    }
  }

  if (auto packExpr = dyn_cast<MaterializePackExpr>(refExpr)) {
    auto *activeExpansion = SGF.getInnermostPackExpansion();
    assert(activeExpansion->MaterializedPacks.count(packExpr) &&
           "didn't materialize pack before dynamic pack loop emission");

    auto elementTy =
      SGF.getLoweredType(substFormalType).getAddressType();
    auto tupleAddr = activeExpansion->MaterializedPacks.find(packExpr);
    auto packIndex = activeExpansion->ExpansionIndex;
    auto elementAddr =
      SGF.B.createTuplePackElementAddr(e, packIndex, tupleAddr->second, elementTy);
    return LValue::forAddress(accessKind, ManagedValue::forLValue(elementAddr),
                              /*access enforcement*/ std::nullopt,
                              AbstractionPattern(substFormalType),
                              substFormalType);
  }

  SGF.SGM.diagnose(refExpr, diag::not_implemented,
                   "emission of 'each' for this kind of expression");
  auto loweredTy = SGF.getLoweredType(substFormalType).getAddressType();
  auto fakeAddr = ManagedValue::forLValue(SILUndef::get(SGF.F, loweredTy));
  return LValue::forAddress(
      accessKind, fakeAddr, /*access enforcement*/ std::nullopt,
      AbstractionPattern(substFormalType), substFormalType);
}

LValue SILGenLValue::visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *e,
                                                   SGFAccessKind accessKind,
                                                   LValueOptions options) {
  SGF.emitIgnoredExpr(e->getLHS());
  return visitRec(e->getRHS(), accessKind, options);
}

/// Should the self argument of the given method always be emitted as
/// an r-value (meaning that it can be borrowed only if that is not
/// semantically detectable), or it acceptable to emit it as a borrowed
/// storage reference?
static bool shouldEmitSelfAsRValue(AccessorDecl *fn, CanType selfType,
                                   bool forBorrowExpr) {
  if (fn->isStatic())
    return true;

  switch (fn->getSelfAccessKind()) {
  case SelfAccessKind::Mutating:
    return false;
  case SelfAccessKind::Borrowing:
  case SelfAccessKind::NonMutating:
    // Normally we'll copy the base to minimize accesses. But if the base
    // is noncopyable, or we're accessing it in a `borrow` expression, then
    // we want to keep the access nested on the original base.
    if (forBorrowExpr || selfType->isNoncopyable()) {
      return false;
    }
    return true;

  case SelfAccessKind::LegacyConsuming:
  case SelfAccessKind::Consuming:
    return true;
  }
  llvm_unreachable("bad self-access kind");
}

static SGFAccessKind getBaseAccessKindForAccessor(SILGenModule &SGM,
                                                  AccessorDecl *accessor,
                                                  CanType baseFormalType,
                                                  bool forBorrowExpr) {
  if (accessor->isMutating())
    return SGFAccessKind::ReadWrite;

  auto declRef = SGM.getAccessorDeclRef(accessor, ResilienceExpansion::Minimal);
  if (shouldEmitSelfAsRValue(accessor, baseFormalType, forBorrowExpr)) {
    return SGM.isNonMutatingSelfIndirect(declRef)
               ? SGFAccessKind::OwnedAddressRead
               : SGFAccessKind::OwnedObjectRead;
  } else {
    return SGM.isNonMutatingSelfIndirect(declRef)
               ? SGFAccessKind::BorrowedAddressRead
               : SGFAccessKind::BorrowedObjectRead;
  }
}

static SGFAccessKind getBaseAccessKindForStorage(SGFAccessKind accessKind) {
  // Assume that the member only partially projects the enclosing value,
  // so a write to the member is a read/write of the base.
  return (accessKind == SGFAccessKind::Write
            ? SGFAccessKind::ReadWrite : accessKind);
}

/// Return the appropriate access kind for the base l-value of a
/// particular member, which is being accessed in a particular way.
static SGFAccessKind getBaseAccessKind(SILGenModule &SGM,
                                       AbstractStorageDecl *member,
                                       SGFAccessKind accessKind,
                                       AccessStrategy strategy,
                                       CanType baseFormalType,
                                       bool forBorrowExpr) {
  switch (strategy.getKind()) {
  case AccessStrategy::Storage:
    return getBaseAccessKindForStorage(accessKind);

  case AccessStrategy::MaterializeToTemporary: {
    assert(accessKind == SGFAccessKind::ReadWrite);
    auto writeBaseKind = getBaseAccessKind(SGM, member, SGFAccessKind::Write,
                                           strategy.getWriteStrategy(),
                                           baseFormalType,
                                           /*for borrow*/ false);

    // Fast path for the common case that the write will need to mutate
    // the base.
    if (writeBaseKind == SGFAccessKind::ReadWrite)
      return writeBaseKind;

    auto readBaseKind = getBaseAccessKind(SGM, member,
                                          SGFAccessKind::OwnedAddressRead,
                                          strategy.getReadStrategy(),
                                          baseFormalType,
                                          /*for borrow*/ false);

    // If they're the same kind, just use that.
    if (readBaseKind == writeBaseKind)
      return readBaseKind;

    // If either access is mutating, the total access is a read-write.
    if (!isReadAccess(readBaseKind) || !isReadAccess(writeBaseKind))
      return SGFAccessKind::ReadWrite;

    // Okay, we have two different kinds of read somehow for different
    // accessors of the same storage?
    return SGFAccessKind::OwnedObjectRead;
  }

  case AccessStrategy::DirectToAccessor:
  case AccessStrategy::DispatchToAccessor:
  case AccessStrategy::DispatchToDistributedThunk: {
    auto accessor = member->getOpaqueAccessor(strategy.getAccessor());
    return getBaseAccessKindForAccessor(SGM, accessor, baseFormalType,
                                        forBorrowExpr);
  }
  }
  llvm_unreachable("bad access strategy");
}

bool isCallToReplacedInDynamicReplacement(SILGenFunction &SGF,
                                          AbstractFunctionDecl *afd,
                                          bool &isObjCReplacementSelfCall);

static bool isCallToSelfOfCurrentFunction(SILGenFunction &SGF, LookupExpr *e) {
  return isa_and_nonnull<AbstractFunctionDecl>(SGF.FunctionDC->getAsDecl()) &&
         e->getBase()->isSelfExprOf(
             cast<AbstractFunctionDecl>(SGF.FunctionDC->getAsDecl()), false);
}

static bool isCurrentFunctionAccessor(SILGenFunction &SGF,
                                      AccessorKind accessorKind) {
  auto *contextAccessorDecl =
      dyn_cast_or_null<AccessorDecl>(SGF.FunctionDC->getAsDecl());
  return contextAccessorDecl &&
         contextAccessorDecl->getAccessorKind() == accessorKind;
}

LValue SILGenLValue::visitMemberRefExpr(MemberRefExpr *e,
                                        SGFAccessKind accessKind,
                                        LValueOptions options) {
  // MemberRefExpr can refer to type and function members, but the only case
  // that can be an lvalue is a VarDecl.
  VarDecl *var = cast<VarDecl>(e->getMember().getDecl());

  // A reference to an instance property in init accessor body
  // has to be remapped into an argument reference because all
  // of the properties from initialized/accesses lists are passed
  // to init accessors individually via arguments.
  if (isCurrentFunctionAccessor(SGF, AccessorKind::Init)) {
    if (auto *arg = SGF.isMappedToInitAccessorArgument(var)) {
      auto subs = e->getMember().getSubstitutions();
      return emitLValueForNonMemberVarDecl(
          SGF, e, ConcreteDeclRef(arg, subs), getSubstFormalRValueType(e),
          accessKind, options, AccessSemantics::Ordinary, std::nullopt);
    }
  }

  auto accessSemantics = e->getAccessSemantics();
  AccessStrategy strategy =
    var->getAccessStrategy(accessSemantics,
                           getFormalAccessKind(accessKind),
                           SGF.SGM.M.getSwiftModule(),
                           SGF.F.getResilienceExpansion());

  bool isOnSelfParameter = isCallToSelfOfCurrentFunction(SGF, e);

  bool isContextRead = isCurrentFunctionAccessor(SGF, AccessorKind::Read);

  // If we are inside _read, calling self.get, and the _read we are inside of is
  // the same as the as self's variable and the current function is a
  // dynamic replacement directly call the implementation.
  if (isContextRead && isOnSelfParameter && strategy.hasAccessor() &&
      strategy.getAccessor() == AccessorKind::Get &&
      var->getOpaqueAccessor(AccessorKind::Read)) {
    bool isObjC = false;
    auto readAccessor =
        SGF.getAccessorDeclRef(var->getOpaqueAccessor(AccessorKind::Read));
    if (isCallToReplacedInDynamicReplacement(
            SGF, readAccessor.getAbstractFunctionDecl(), isObjC)) {
      accessSemantics = AccessSemantics::DirectToImplementation;
      strategy = var->getAccessStrategy(
          accessSemantics,
          getFormalAccessKind(accessKind),
          SGF.SGM.M.getSwiftModule(),
          SGF.F.getResilienceExpansion());
    }
  }
  
  LValue lv = visitRec(e->getBase(),
                       getBaseAccessKind(SGF.SGM, var, accessKind, strategy,
                                         getBaseFormalType(e->getBase()),
                                         /* for borrow */ false),
                       getBaseOptions(options, strategy));
  assert(lv.isValid());

  std::optional<ActorIsolation> actorIso;
  if (e->isImplicitlyAsync())
    actorIso = getActorIsolation(var);

  CanType substFormalRValueType = getSubstFormalRValueType(e);
  lv.addMemberVarComponent(SGF, e, var, e->getMember().getSubstitutions(),
                           options, e->isSuper(), accessKind, strategy,
                           substFormalRValueType, isOnSelfParameter, actorIso);

  SGF.SGM.noteMemberRefExpr(e);

  return lv;
}

namespace {

/// A CRTP class for emitting member accesses.
template <class Impl, class StorageType>
struct MemberStorageAccessEmitter : AccessEmitter<Impl, StorageType> {
  using super = AccessEmitter<Impl, StorageType>;
  using super::SGF;
  using super::Storage;
  using super::Subs;
  using super::FormalRValueType;
  LValue &LV;
  LValueOptions Options;
  SILLocation Loc;
  bool IsSuper;
  bool IsOnSelfParameter; // Is self the self parameter in context.
  CanType BaseFormalType;
  ArgumentList *ArgListForDiagnostics;
  PreparedArguments Indices;
  // If any, holds the actor we must switch to when performing the access.
  std::optional<ActorIsolation> ActorIso;

  MemberStorageAccessEmitter(
      SILGenFunction &SGF, SILLocation loc, StorageType *storage,
      SubstitutionMap subs, bool isSuper, SGFAccessKind accessKind,
      CanType formalRValueType, LValueOptions options, LValue &lv,
      ArgumentList *argListForDiagnostics, PreparedArguments &&indices,
      bool isSelf = false,
      std::optional<ActorIsolation> actorIso = std::nullopt)
      : super(SGF, storage, subs, accessKind, formalRValueType), LV(lv),
        Options(options), Loc(loc), IsSuper(isSuper), IsOnSelfParameter(isSelf),
        BaseFormalType(lv.getSubstFormalType()),
        ArgListForDiagnostics(argListForDiagnostics),
        Indices(std::move(indices)), ActorIso(actorIso) {}

  void emitUsingAddressor(SILDeclRef addressor, bool isDirect,
                          LValueTypeData typeData) {
    assert(!ActorIso);
    SILType varStorageType = SGF.SGM.Types.getSubstitutedStorageType(
        SGF.getTypeExpansionContext(), Storage, FormalRValueType);

    LV.add<AddressorComponent>(Storage, addressor, IsSuper, isDirect, Subs,
                               BaseFormalType, typeData, varStorageType,
                               ArgListForDiagnostics, std::move(Indices),
                               IsOnSelfParameter);
    
  }

  void emitUsingCoroutineAccessor(SILDeclRef accessor, bool isDirect,
                                  LValueTypeData typeData) {
    assert(!ActorIso);
    LV.add<CoroutineAccessorComponent>(
        Storage, accessor, IsSuper, isDirect, Subs, BaseFormalType, typeData,
        ArgListForDiagnostics, std::move(Indices), IsOnSelfParameter);
  }

  void emitUsingGetterSetter(SILDeclRef accessor,
                             bool isDirect,
                             LValueTypeData typeData) {
    LV.add<GetterSetterComponent>(
        Storage, accessor, IsSuper, isDirect, Subs,
        BaseFormalType, typeData, ArgListForDiagnostics, std::move(Indices),
        IsOnSelfParameter, ActorIso);
  }

  void emitUsingMaterialization(AccessStrategy readStrategy,
                                AccessStrategy writeStrategy,
                                LValueTypeData typeData) {
    assert(!ActorIso);
    LV.add<MaterializeToTemporaryComponent>(
        Storage, IsSuper, Subs, Options, readStrategy, writeStrategy,
        BaseFormalType, typeData, ArgListForDiagnostics, std::move(Indices),
        IsOnSelfParameter);
  }

  void emitUsingInitAccessor(SILDeclRef accessor, bool isDirect,
                             LValueTypeData typeData) {
    LV.add<InitAccessorComponent>(
        Storage, accessor, IsSuper, isDirect, Subs, BaseFormalType, typeData,
        ArgListForDiagnostics, std::move(Indices), IsOnSelfParameter, ActorIso);
  }
};
} // end anonymous namespace

void LValue::addMemberVarComponent(
    SILGenFunction &SGF, SILLocation loc, VarDecl *var, SubstitutionMap subs,
    LValueOptions options, bool isSuper, SGFAccessKind accessKind,
    AccessStrategy strategy, CanType formalRValueType, bool isOnSelfParameter,
    std::optional<ActorIsolation> actorIso) {
  struct MemberVarAccessEmitter
      : MemberStorageAccessEmitter<MemberVarAccessEmitter, VarDecl> {
    using MemberStorageAccessEmitter::MemberStorageAccessEmitter;

    void emitUsingStorage(LValueTypeData typeData) {
      // For static variables, emit a reference to the global variable backing
      // them.
      // FIXME: This has to be dynamically looked up for classes, and
      // dynamically instantiated for generics.
      if (Storage->isStatic()) {
        // FIXME: this implicitly drops the earlier components, but maybe
        // we ought to evaluate them for side-effects even during the
        // formal access?
        LV.Path.clear();
        LV.addNonMemberVarComponent(SGF, Loc, Storage, Subs, Options,
                                    typeData.getAccessKind(),
                                    AccessStrategy::getStorage(),
                                    FormalRValueType,
                                    ActorIso);
        return;
      }

      // Otherwise, it's a physical member.
      SILType varStorageType = SGF.SGM.Types.getSubstitutedStorageType(
          SGF.getTypeExpansionContext(), Storage, FormalRValueType);

      if (BaseFormalType->mayHaveSuperclass()) {
        LV.add<RefElementComponent>(Storage, Options, varStorageType,
                                    typeData, ActorIso);
      } else {
        assert(BaseFormalType->getStructOrBoundGenericStruct());
        LV.add<StructElementComponent>(Storage, varStorageType, typeData,
                                       ActorIso);
      }

      // If the member has weak or unowned storage, convert it away.
      if (varStorageType.is<ReferenceStorageType>()) {
        LV.add<OwnershipComponent>(typeData);
      }
    }

    void emitUsingDistributedThunk() {
      auto *var = cast<VarDecl>(Storage);
      SILDeclRef accessor(var->getAccessor(AccessorKind::Get),
                          SILDeclRef::Kind::Func,
                          /*isForeign=*/false, /*isDistributed=*/true);

      auto typeData = getLogicalStorageTypeData(
          SGF.getTypeExpansionContext(), SGF.SGM, AccessKind, FormalRValueType);

      // If we're in a protocol, we must use a witness call for the getter,
      // otherwise (in a class) we must use a direct call.
      auto isDirect = isa<ClassDecl>(var->getDeclContext());
      asImpl().emitUsingGetterSetter(accessor, /*isDirect=*/isDirect, typeData);
    }

  } emitter(SGF, loc, var, subs, isSuper, accessKind,
            formalRValueType, options, *this,
            /*indices for diags*/ nullptr, /*indices*/ PreparedArguments(),
            isOnSelfParameter, actorIso);

  emitter.emitUsingStrategy(strategy);
}

LValue SILGenLValue::visitSubscriptExpr(SubscriptExpr *e,
                                        SGFAccessKind accessKind,
                                        LValueOptions options) {
  auto decl = cast<SubscriptDecl>(e->getDecl().getDecl());
  auto subs = e->getDecl().getSubstitutions();


  auto accessSemantics = e->getAccessSemantics();
  auto strategy =
    decl->getAccessStrategy(accessSemantics,
                            getFormalAccessKind(accessKind),
                            SGF.SGM.M.getSwiftModule(),
                            SGF.F.getResilienceExpansion());

  bool isOnSelfParameter = isCallToSelfOfCurrentFunction(SGF, e);
  bool isContextRead = isCurrentFunctionAccessor(SGF, AccessorKind::Read);

  // If we are inside _read, calling self.get, and the _read we are inside of is
  // the same as the as self's variable and the current function is a
  // dynamic replacement directly call the implementation.
  if (isContextRead && isOnSelfParameter && strategy.hasAccessor() &&
      strategy.getAccessor() == AccessorKind::Get &&
      decl->getOpaqueAccessor(AccessorKind::Read)) {
    bool isObjC = false;
    auto readAccessor =
        SGF.getAccessorDeclRef(decl->getOpaqueAccessor(AccessorKind::Read));
    if (isCallToReplacedInDynamicReplacement(
            SGF, readAccessor.getAbstractFunctionDecl(), isObjC)) {
      accessSemantics = AccessSemantics::DirectToImplementation;
      strategy = decl->getAccessStrategy(
          accessSemantics,
          getFormalAccessKind(accessKind),
          SGF.SGM.M.getSwiftModule(),
          SGF.F.getResilienceExpansion());
    }
  }

  LValue lv = visitRec(e->getBase(),
                       getBaseAccessKind(SGF.SGM, decl, accessKind, strategy,
                                         getBaseFormalType(e->getBase()),
                                         /*for borrow*/ false),
                       getBaseOptions(options, strategy));
  assert(lv.isValid());

  // Now that the base components have been resolved, check the isolation for
  // this subscript decl.
  std::optional<ActorIsolation> actorIso;
  if (e->isImplicitlyAsync())
    actorIso = getActorIsolation(decl);

  auto *argList = e->getArgs();
  auto indices = SGF.prepareSubscriptIndices(e, decl, subs, strategy, argList);

  CanType formalRValueType = getSubstFormalRValueType(e);
  lv.addMemberSubscriptComponent(SGF, e, decl, subs,
                                 options, e->isSuper(), accessKind, strategy,
                                 formalRValueType, std::move(indices),
                                 argList, isOnSelfParameter, actorIso);
  return lv;
}

LValue SILGenLValue::visitKeyPathApplicationExpr(KeyPathApplicationExpr *e,
                                                 SGFAccessKind accessKind,
                                                 LValueOptions options) {
  auto keyPathExpr = e->getKeyPath();
  auto keyPathKind =
    *keyPathExpr->getType()->getAnyNominal()->getKeyPathTypeKind();

  // Determine the base access strategy based on the strategy of this access.
  SGFAccessKind subAccess;
  if (!isReadAccess(accessKind)) {
    // The only read-write accesses we allow are with WritableKeyPath and
    // ReferenceWritableKeyPath.
    assert(keyPathKind == KPTK_WritableKeyPath ||
           keyPathKind == KPTK_ReferenceWritableKeyPath);
    subAccess = (keyPathKind == KPTK_ReferenceWritableKeyPath
                    ? SGFAccessKind::BorrowedAddressRead
                    : SGFAccessKind::ReadWrite);
  } else {
    // For all the other kinds, we want the emit the base as an address
    // r-value; we don't support key paths for storage with mutating read
    // operations.
    subAccess = SGFAccessKind::BorrowedAddressRead;
  }

  // For now, just ignore any options we were given.
  LValueOptions subOptions = LValueOptions();

  // Do formal evaluation of the base l-value.
  // The base should be reabstracted to the maximal abstraction pattern.
  LValue lv = visitRec(e->getBase(), subAccess, subOptions,
                       AbstractionPattern::getOpaque());

  // Emit the key path r-value.
  auto keyPath = SGF.emitRValueAsSingleValue(keyPathExpr);

  // The result will end up projected at the maximal abstraction level too.
  auto substFormalType = e->getType()->getRValueType()->getCanonicalType();

  bool useLogical = [&] {
    switch (accessKind) {
    // Use the physical 'read' pattern for these unless we're working with
    // AnyKeyPath or PartialKeyPath, which only have getters.
    case SGFAccessKind::BorrowedAddressRead:
    case SGFAccessKind::BorrowedObjectRead:
      return (keyPathKind == KPTK_AnyKeyPath ||
              keyPathKind == KPTK_PartialKeyPath);

    case SGFAccessKind::OwnedObjectRead:
    case SGFAccessKind::OwnedAddressRead:
    case SGFAccessKind::IgnoredRead: // should we use physical for this?
    case SGFAccessKind::Write:
      return true;

    case SGFAccessKind::ReadWrite:
    case SGFAccessKind::OwnedAddressConsume:
    case SGFAccessKind::OwnedObjectConsume:
      return false;
    }
    llvm_unreachable("bad access kind");
  }();

  if (useLogical) {
    auto typeData = getLogicalStorageTypeData(
        SGF.getTypeExpansionContext(), SGF.SGM, accessKind, substFormalType);

    Type baseFormalType = e->getBase()->getType()->getRValueType();
    lv.add<LogicalKeyPathApplicationComponent>(typeData, keyPathKind, keyPath,
                                               baseFormalType);

    // TODO: make LogicalKeyPathApplicationComponent expect/produce values
    // in the opaque AbstractionPattern and push an OrigToSubstComponent here
    // so it can be peepholed.
  } else {
    auto typeData = getAbstractedTypeData(
        TypeExpansionContext::minimal(), SGF.SGM, accessKind,
        AbstractionPattern::getOpaque(), substFormalType);

    lv.add<PhysicalKeyPathApplicationComponent>(typeData, keyPathKind, keyPath);

    // Reabstract to the substituted abstraction level if necessary.
    auto substResultSILTy = SGF.getLoweredType(substFormalType);
    if (typeData.TypeOfRValue != substResultSILTy.getASTType()) {
      lv.addOrigToSubstComponent(substResultSILTy);
    }
  }

  return lv;
}

void LValue::addMemberSubscriptComponent(
    SILGenFunction &SGF, SILLocation loc, SubscriptDecl *decl,
    SubstitutionMap subs, LValueOptions options, bool isSuper,
    SGFAccessKind accessKind, AccessStrategy strategy, CanType formalRValueType,
    PreparedArguments &&indices, ArgumentList *argListForDiagnostics,
    bool isOnSelfParameter, std::optional<ActorIsolation> actorIso) {
  struct MemberSubscriptAccessEmitter
      : MemberStorageAccessEmitter<MemberSubscriptAccessEmitter,
                                   SubscriptDecl> {
    using MemberStorageAccessEmitter::MemberStorageAccessEmitter;

    void emitUsingStorage(LValueTypeData typeData) {
      llvm_unreachable("subscripts never have storage");
    }

    void emitUsingDistributedThunk() {
      llvm_unreachable("subscripts cannot be dispatch via distributed thunk");
    }
  } emitter(SGF, loc, decl, subs, isSuper, accessKind, formalRValueType,
            options, *this, argListForDiagnostics, std::move(indices),
            isOnSelfParameter, actorIso);

  emitter.emitUsingStrategy(strategy);
}

bool LValue::isObviouslyNonConflicting(const LValue &other,
                                       SGFAccessKind selfAccess,
                                       SGFAccessKind otherAccess) {
  // Reads never conflict with reads.
  if (isReadAccess(selfAccess) && isReadAccess(otherAccess))
    return true;

  // We can cover more cases here.
  return false;
}

LValue SILGenLValue::visitTupleElementExpr(TupleElementExpr *e,
                                           SGFAccessKind accessKind,
                                           LValueOptions options) {
  unsigned index = e->getFieldNumber();
  LValue lv = visitRec(e->getBase(),
                       getBaseAccessKindForStorage(accessKind),
                       options.forProjectedBaseLValue());

  auto baseTypeData = lv.getTypeData();
  LValueTypeData typeData = {
    accessKind,
    baseTypeData.OrigFormalType.getTupleElementType(index),
    cast<TupleType>(baseTypeData.SubstFormalType).getElementType(index),
    cast<TupleType>(baseTypeData.TypeOfRValue).getElementType(index)
  };

  lv.add<TupleElementComponent>(index, typeData);
  return lv;
}

LValue SILGenLValue::visitOpenExistentialExpr(OpenExistentialExpr *e,
                                              SGFAccessKind accessKind,
                                              LValueOptions options) {
  // If the opaque value is not an lvalue, open the existential immediately.
  if (!e->getOpaqueValue()->getType()->is<LValueType>()) {
    return SGF.emitOpenExistentialExpr<LValue>(e,
                                               [&](Expr *subExpr) -> LValue {
                                                 return visitRec(subExpr,
                                                                 accessKind,
                                                                 options);
                                               });
  }

  // Record the fact that we're opening this existential. The actual
  // opening operation will occur when we see the OpaqueValueExpr.
  bool inserted = SGF.OpaqueValueExprs.insert({e->getOpaqueValue(), e}).second;
  (void)inserted;
  assert(inserted && "already have this opened existential?");

  // Visit the subexpression.
  LValue lv = visitRec(e->getSubExpr(), accessKind, options);

  // Soundness check that we did see the OpaqueValueExpr.
  assert(SGF.OpaqueValueExprs.count(e->getOpaqueValue()) == 0 &&
         "opened existential not removed?");
  return lv;
}

static LValueTypeData
getOptionalObjectTypeData(SILGenFunction &SGF, SGFAccessKind accessKind,
                          const LValueTypeData &baseTypeData) {
  return {
      accessKind,
      baseTypeData.OrigFormalType.getOptionalObjectType(),
      baseTypeData.SubstFormalType.getOptionalObjectType(),
      baseTypeData.TypeOfRValue.getOptionalObjectType(),
  };
}

LValue SILGenLValue::visitForceValueExpr(ForceValueExpr *e,
                                         SGFAccessKind accessKind,
                                         LValueOptions options) {
  // Since Sema doesn't reason about borrows, a borrowed force expr
  // might end up type checked with the load inside of the force.
  auto subExpr = e->getSubExpr();
  if (auto load = dyn_cast<LoadExpr>(subExpr)) {
    assert((isBorrowAccess(accessKind) || isConsumeAccess(accessKind))
           && "should only see a (force_value (load)) lvalue as part of a "
              "borrow or consume");
    subExpr = load->getSubExpr();
  }
                                         
  // Like BindOptional, this is a read even if we only write to the result.
  // (But it's unnecessary to use a force this way!)
  LValue lv = visitRec(e->getSubExpr(),
                       getBaseAccessKindForStorage(accessKind),
                       options.forComputedBaseLValue());
  LValueTypeData typeData =
    getOptionalObjectTypeData(SGF, accessKind, lv.getTypeData());
  bool isImplicitUnwrap = e->isImplicit() &&
    e->isForceOfImplicitlyUnwrappedOptional(); 
  lv.add<ForceOptionalObjectComponent>(typeData, isImplicitUnwrap);
  return lv;
}

LValue SILGenLValue::visitBindOptionalExpr(BindOptionalExpr *e,
                                           SGFAccessKind accessKind,
                                           LValueOptions options) {
  // Binding reads the base even if we then only write to the result.
  auto baseAccessKind = getBaseAccessKindForStorage(accessKind);

  if (!isBorrowAccess(accessKind)) {
    // We're going to take the address of the base.
    // TODO: deal more efficiently with an object-preferring access.
    baseAccessKind = getAddressAccessKind(baseAccessKind);
  }
  
  // Do formal evaluation of the base l-value.
  LValue optLV = visitRec(e->getSubExpr(), baseAccessKind,
                          options.forComputedBaseLValue());
  // For move-checking purposes, the binding is also treated as an opaque use
  // of the entire value, since we can't leave the value partially initialized
  // across multiple optional binding expressions.
  LValueTypeData optTypeData = optLV.getTypeData();
  LValueTypeData valueTypeData =
    getOptionalObjectTypeData(SGF, accessKind, optTypeData);

  // The chaining operator immediately evaluates the base.
  
  ManagedValue optBase;
  if (isBorrowAccess(baseAccessKind)) {
    optBase = SGF.emitBorrowedLValue(e, std::move(optLV));
    
    if (optBase.getType().isMoveOnly()) {
      if (optBase.getType().isAddress()) {
        // Strip the move-only wrapper if any.
        if (optBase.getType().isMoveOnlyWrapped()) {
          optBase = ManagedValue::forBorrowedAddressRValue(
            SGF.B.createMoveOnlyWrapperToCopyableAddr(e,
                                                      optBase.getValue()));
        }
      
        optBase = enterAccessScope(SGF, e, ManagedValue(),
                                   optBase, optTypeData,
                                   baseAccessKind,
                                   SILAccessEnforcement::Static,
                                   std::nullopt,
                                   /*no nested conflict*/ true);
        if (optBase.getType().isLoadable(SGF.F)) {
          optBase = SGF.B.createFormalAccessLoadBorrow(e, optBase);
        }
      } else {
        optBase = SGF.B.createFormalAccessBeginBorrow(e, optBase, IsNotLexical,
                                                      BeginBorrowInst::IsFixed);
        // Strip the move-only wrapper if any.
        if (optBase.getType().isMoveOnlyWrapped()) {
          optBase
            = SGF.B.createGuaranteedMoveOnlyWrapperToCopyableValue(e, optBase);
        }
      }
    }
  } else {
    optBase = SGF.emitAddressOfLValue(e, std::move(optLV));
    bool isMoveOnly = optBase.getType().isMoveOnly();
    
    // Strip the move-only wrapper if any.
    if (optBase.getType().isMoveOnlyWrapped()) {
      optBase = ManagedValue::forLValue(
        SGF.B.createMoveOnlyWrapperToCopyableAddr(e,
                                                  optBase.getValue()));
    }
    
    if (isConsumeAccess(baseAccessKind)) {
      if (isMoveOnly) {
        optBase = enterAccessScope(SGF, e, ManagedValue(),
                                   optBase, optTypeData,
                                   baseAccessKind,
                                   SILAccessEnforcement::Static,
                                   std::nullopt,
                                   /*no nested conflict*/ true);
      }
      // Take ownership of the base.
      optBase = SGF.emitManagedRValueWithCleanup(optBase.getValue());
    }
  }
  // Bind the value, branching to the destination address if there's no
  // value there.
  assert(e->getDepth() < SGF.BindOptionalFailureDests.size());
  auto failureDepth = SGF.BindOptionalFailureDests.size() - e->getDepth() - 1;
  auto failureDest = SGF.BindOptionalFailureDests[failureDepth];
  assert(failureDest.isValid() && "too big to fail");

  // Since we know that we have an address, we do not need to worry about
  // ownership invariants. Instead just use a select_enum_addr.
  SILBasicBlock *someBB = SGF.createBasicBlock();
  SILValue hasValue = SGF.emitDoesOptionalHaveValue(e, optBase.getValue());

  auto noneBB = SGF.Cleanups.emitBlockForCleanups(failureDest, e);
  SGF.B.createCondBranch(e, hasValue, someBB, noneBB);

  // Reset the insertion point at the end of hasValueBB so we can
  // continue to emit code there.
  SGF.B.setInsertionPoint(someBB);
  
  // Project out the payload on the success branch.  We can just use a
  // naked ValueComponent here; this is effectively a separate l-value.
  ManagedValue optPayload =
    getPayloadOfOptionalValue(SGF, e, optBase, valueTypeData, accessKind);
  // Disable the cleanup if consuming since the consumer should pull straight
  // from the address we give them.
  if (optBase.getType().isMoveOnly() && isConsumeAccess(baseAccessKind)) {
    optPayload = ManagedValue::forLValue(optPayload.forward(SGF));
  }
  LValue valueLV;
  valueLV.add<ValueComponent>(optPayload, std::nullopt, valueTypeData,
                              /*is rvalue*/optBase.getType().isObject());
  return valueLV;
}

LValue SILGenLValue::visitInOutExpr(InOutExpr *e, SGFAccessKind accessKind,
                                    LValueOptions options) {
  return visitRec(e->getSubExpr(), accessKind, options);
}

LValue SILGenLValue::visitLoadExpr(LoadExpr *e, SGFAccessKind accessKind,
                               LValueOptions options) {
  return visit(e->getSubExpr(), accessKind, options);
}

LValue SILGenLValue::visitConsumeExpr(ConsumeExpr *e, SGFAccessKind accessKind,
                                      LValueOptions options) {
  // Do formal evaluation of the base l-value.
  LValue baseLV = visitRec(e->getSubExpr(), SGFAccessKind::ReadWrite,
                           options.forComputedBaseLValue());

  ManagedValue addr = SGF.emitAddressOfLValue(e, std::move(baseLV));

  // Now create the temporary and move our value into there.
  auto temp =
      SGF.emitFormalAccessTemporary(e, SGF.F.getTypeLowering(addr.getType()));
  auto toAddr = temp->getAddressForInPlaceInitialization(SGF, e);

  // If we have a move only type, we use a copy_addr that will be handled by the
  // address move only checker. If we have a copyable type, we need to use a
  // mark_unresolved_move_addr to ensure that the move operator checker performs
  // the relevant checking.
  if (addr.getType().isMoveOnly()) {
    SGF.B.createCopyAddr(e, addr.getValue(), toAddr, IsNotTake,
                         IsInitialization);
  } else {
    SGF.B.createMarkUnresolvedMoveAddr(e, addr.getValue(), toAddr);
  }
  temp->finishInitialization(SGF);

  // Now return the temporary in a value component.
  return LValue::forValue(SGFAccessKind::BorrowedAddressRead,
                          temp->getManagedAddress(),
                          toAddr->getType().getASTType());
}

LValue SILGenLValue::visitCopyExpr(CopyExpr *e, SGFAccessKind accessKind,
                                   LValueOptions options) {
  // Do formal evaluation of the base l-value.
  LValue baseLV = visitRec(e->getSubExpr(), SGFAccessKind::BorrowedAddressRead,
                           options.forComputedBaseLValue());

  ManagedValue addr = SGF.emitAddressOfLValue(e, std::move(baseLV));

  // Now create the temporary and copy our value into there using an explicit
  // copy_value. This ensures that the rest of the move checker views this as a
  // liveness requiring use rather than a copy that must be eliminated.
  auto temp =
      SGF.emitFormalAccessTemporary(e, SGF.F.getTypeLowering(addr.getType()));
  auto toAddr = temp->getAddressForInPlaceInitialization(SGF, e);
  SGF.B.createExplicitCopyAddr(e, addr.getValue(), toAddr, IsNotTake,
                               IsInitialization);
  temp->finishInitialization(SGF);

  // Now return the temporary in a value component.
  return LValue::forValue(SGFAccessKind::BorrowedAddressRead,
                          temp->getManagedAddress(),
                          toAddr->getType().getASTType());
}

LValue SILGenLValue::visitABISafeConversionExpr(ABISafeConversionExpr *e,
                                    SGFAccessKind accessKind,
                                    LValueOptions options) {
  LValue lval = visitRec(e->getSubExpr(), accessKind, options);
  auto typeData = getValueTypeData(SGF, accessKind, e);
  auto subExprType = e->getSubExpr()->getType()->getRValueType();
  auto loweredSubExprType = SGF.getLoweredType(subExprType);
  
  // Ensure the lvalue is re-abstracted to the substituted type, since that's
  // the type with which we have ABI compatibility.
  if (lval.getTypeOfRValue().getASTType() != loweredSubExprType.getASTType()) {
    // Logical components always re-abstract back to the substituted
    // type.
    assert(lval.isLastComponentPhysical());
    lval.addOrigToSubstComponent(loweredSubExprType);
  }

  lval.add<UncheckedConversionComponent>(typeData, subExprType);

  return lval;
}

/// Emit an lvalue that refers to the given property.  This is
/// designed to work with ManagedValue 'base's that are either +0 or +1.
LValue SILGenFunction::emitPropertyLValue(SILLocation loc, ManagedValue base,
                                          CanType baseFormalType,
                                          VarDecl *ivar,
                                          LValueOptions options,
                                          SGFAccessKind accessKind,
                                          AccessSemantics semantics) {
  SILGenLValue sgl(*this);
  LValue lv;

  auto baseType = base.getType().getASTType();
  auto subMap = baseType->getContextSubstitutionMap(
      SGM.M.getSwiftModule(), ivar->getDeclContext());

  AccessStrategy strategy =
    ivar->getAccessStrategy(semantics,
                            getFormalAccessKind(accessKind),
                            SGM.M.getSwiftModule(),
                            F.getResilienceExpansion());

  auto baseAccessKind =
    getBaseAccessKind(SGM, ivar, accessKind, strategy, baseFormalType,
                      /*for borrow*/ false);

  LValueTypeData baseTypeData =
    getValueTypeData(baseAccessKind, baseFormalType, base.getValue());

  // Refer to 'self' as the base of the lvalue.
  lv.add<ValueComponent>(base, std::nullopt, baseTypeData,
                         /*isRValue=*/!base.isLValue());

  auto substFormalType = ivar->getValueInterfaceType().subst(subMap)
    ->getCanonicalType();

  lv.addMemberVarComponent(*this, loc, ivar, subMap, options, /*super*/ false,
                           accessKind, strategy, substFormalType);
  return lv;
}

// This is emitLoad that will handle re-abstraction and bridging for the client.
ManagedValue SILGenFunction::emitLoad(SILLocation loc, SILValue addr,
                                      AbstractionPattern origFormalType,
                                      CanType substFormalType,
                                      const TypeLowering &rvalueTL,
                                      SGFContext C, IsTake_t isTake,
                                      bool isAddressGuaranteed) {
  assert(addr->getType().isAddress());
  SILType addrRValueType = addr->getType().getReferenceStorageReferentType();

  // Fast path: the types match exactly.
  if (addrRValueType == rvalueTL.getLoweredType().getAddressType()) {
    return emitLoad(loc, addr, rvalueTL, C, isTake, isAddressGuaranteed);
  }

  // Otherwise, we need to reabstract or bridge.
  auto conversion =
    origFormalType.isClangType()
      ? Conversion::getBridging(Conversion::BridgeFromObjC,
                                origFormalType.getType(),
                                substFormalType, rvalueTL.getLoweredType())
      : Conversion::getOrigToSubst(origFormalType, substFormalType,
                                   /*input*/addrRValueType,
                                   /*output*/rvalueTL.getLoweredType());

  return emitConvertedRValue(loc, conversion, C,
      [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) {
    return SGF.emitLoad(loc, addr, getTypeLowering(addrRValueType),
                        C, isTake, isAddressGuaranteed);
  });
}

/// Load an r-value out of the given address.
///
/// \param rvalueTL - the type lowering for the type-of-rvalue
///   of the address
/// \param isAddrGuaranteed - true if the value in this address
///   is guaranteed to be valid for the duration of the current
///   evaluation (see SGFContext::AllowGuaranteedPlusZero)
ManagedValue SILGenFunction::emitLoad(SILLocation loc, SILValue addr,
                                      const TypeLowering &rvalueTL,
                                      SGFContext C, IsTake_t isTake,
                                      bool isAddrGuaranteed) {
  SILType addrType = addr->getType();
  // Get the lowering for the address type.  We can avoid a re-lookup
  // in the very common case of this being equivalent to the r-value
  // type.
  auto &addrTL = (addrType == rvalueTL.getLoweredType().getAddressType()
                      ? rvalueTL
                      : getTypeLowering(addrType));

  // Never do a +0 load together with a take.
  bool isPlusZeroOk = (isTake == IsNotTake &&
                       (isAddrGuaranteed ? C.isGuaranteedPlusZeroOk()
                                          : C.isImmediatePlusZeroOk()));

  if (rvalueTL.isAddressOnly() && silConv.useLoweredAddresses()) {
    // If the client is cool with a +0 rvalue, the decl has an address-only
    // type, and there are no conversions, then we can return this as a +0
    // address RValue.
    if (isPlusZeroOk) {
      SILType rvalueType = rvalueTL.getLoweredType();
      SILType addrType = addrTL.getLoweredType();
      if (!rvalueType.isMoveOnlyWrapped() && addrType.isMoveOnlyWrapped()) {
        SILValue value = B.createMoveOnlyWrapperToCopyableAddr(loc, addr);
        return ManagedValue::forBorrowedAddressRValue(value);
      }
      if (rvalueTL.getLoweredType() == addrTL.getLoweredType()) {
        return ManagedValue::forBorrowedAddressRValue(addr);
      }
    }

    // Copy the address-only value.
    return B.bufferForExpr(
        loc, rvalueTL.getLoweredType(), rvalueTL, C, [&](SILValue newAddr) {
          // If our dest address is a move only value from C, we can not reuse
          // rvalueTL here.
          SILType newAddrType = newAddr->getType();
          auto &newAddrTL = newAddrType.isMoveOnlyWrapped()
                                ? getTypeLowering(newAddrType)
                                : rvalueTL;
          return emitSemanticLoadInto(loc, addr, addrTL, newAddr, newAddrTL,
                                      isTake, IsInitialization);
        });
  }

  // Ok, this is something loadable.  If this is a non-take access at plus zero,
  // we can perform a +0 load of the address instead of materializing a +1
  // value.
  if (isPlusZeroOk && addrTL.getLoweredType() == rvalueTL.getLoweredType()) {
    return B.createLoadBorrow(loc,
                              ManagedValue::forBorrowedAddressRValue(addr));
  }

  // Load the loadable value, and retain it if we aren't taking it.
  SILValue loadedV = emitSemanticLoad(loc, addr, addrTL, rvalueTL, isTake);
  return emitManagedRValueWithCleanup(loadedV);
}

/// Load an r-value out of the given address.
///
/// \param rvalueTL - the type lowering for the type-of-rvalue
///   of the address
/// \param isAddressGuaranteed - true if the value in this address
///   is guaranteed to be valid for the duration of the current
///   evaluation (see SGFContext::AllowGuaranteedPlusZero)
ManagedValue SILGenFunction::emitFormalAccessLoad(SILLocation loc,
                                                  SILValue addr,
                                                  const TypeLowering &rvalueTL,
                                                  SGFContext C, IsTake_t isTake,
                                                  bool isAddressGuaranteed) {
  // Get the lowering for the address type.  We can avoid a re-lookup
  // in the very common case of this being equivalent to the r-value
  // type.
  auto &addrTL = (addr->getType() == rvalueTL.getLoweredType().getAddressType()
                      ? rvalueTL
                      : getTypeLowering(addr->getType()));

  // Never do a +0 load together with a take.
  bool isPlusZeroOk =
      (isTake == IsNotTake && (isAddressGuaranteed ? C.isGuaranteedPlusZeroOk()
                                                 : C.isImmediatePlusZeroOk()));

  if (rvalueTL.isAddressOnly() && silConv.useLoweredAddresses()) {
    // If the client is cool with a +0 rvalue, the decl has an address-only
    // type, and there are no conversions, then we can return this as a +0
    // address RValue.
    if (isPlusZeroOk && rvalueTL.getLoweredType() == addrTL.getLoweredType())
      return ManagedValue::forBorrowedAddressRValue(addr);

    // Copy the address-only value.
    return B.formalAccessBufferForExpr(
        loc, rvalueTL.getLoweredType(), rvalueTL, C,
        [&](SILValue addressForCopy) {
          // If our dest address is a move only value from C, we can not reuse
          // rvalueTL here.
          SILType addressForCopyType = addressForCopy->getType();
          auto &addressForCopyTL = addressForCopyType.isMoveOnlyWrapped()
                                       ? getTypeLowering(addressForCopyType)
                                       : rvalueTL;
          return emitSemanticLoadInto(loc, addr, addrTL, addressForCopy,
                                      addressForCopyTL, isTake,
                                      IsInitialization);
        });
  }

  // Ok, this is something loadable.  If this is a non-take access at plus zero,
  // we can perform a +0 load of the address instead of materializing a +1
  // value.
  if (isPlusZeroOk && addrTL.getLoweredType() == rvalueTL.getLoweredType()) {
    return B.createFormalAccessLoadBorrow(
        loc, ManagedValue::forBorrowedAddressRValue(addr));
  }

  // Load the loadable value, and retain it if we aren't taking it.
  SILValue loadedV = emitSemanticLoad(loc, addr, addrTL, rvalueTL, isTake);
  return emitFormalAccessManagedRValueWithCleanup(loc, loadedV);
}

static void emitUnloweredStoreOfCopy(SILGenBuilder &B, SILLocation loc,
                                     SILValue value, SILValue addr,
                                     IsInitialization_t isInit) {
  if (isInit) {
    B.emitStoreValueOperation(loc, value, addr, StoreOwnershipQualifier::Init);
  } else {
    B.createAssign(loc, value, addr, AssignOwnershipQualifier::Unknown);
  }
}

SILValue SILGenFunction::emitConversionToSemanticRValue(SILLocation loc,
                                                        SILValue src,
                                                  const TypeLowering &valueTL) {
  auto storageType = src->getType();
  auto swiftStorageType = storageType.castTo<ReferenceStorageType>();

  switch (swiftStorageType->getOwnership()) {
  case ReferenceOwnership::Strong:
    llvm_unreachable("strong reference storage type should be impossible");
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: \
    /* Address-only storage types are handled with their underlying type. */ \
    llvm_unreachable("address-only pointers are handled elsewhere");
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                         \
  case ReferenceOwnership::Name:                                               \
    return B.createStrongCopy##Name##Value(loc, src);
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                      \
  case ReferenceOwnership::Name: {                                             \
    /* For loadable reference storage types, we need to generate a strong */   \
    /* retain and strip the box. */                                            \
    assert(storageType.castTo<Name##StorageType>()->isLoadable(                \
        ResilienceExpansion::Maximal));                                        \
    return B.createStrongCopy##Name##Value(loc, src);                          \
  }
#define UNCHECKED_REF_STORAGE(Name, ...)                                       \
  case ReferenceOwnership::Name: {                                             \
    /* For static reference storage types, we need to strip the box and */     \
    /* then do an (unsafe) retain. */                                          \
    return B.createStrongCopy##Name##Value(loc, src);                          \
  }
#include "swift/AST/ReferenceStorage.def"
  }
  llvm_unreachable("impossible");
}

ManagedValue SILGenFunction::emitConversionToSemanticRValue(
    SILLocation loc, ManagedValue src, const TypeLowering &valueTL) {
  auto swiftStorageType = src.getType().castTo<ReferenceStorageType>();

  switch (swiftStorageType->getOwnership()) {
  case ReferenceOwnership::Strong:
    llvm_unreachable("strong reference storage type should be impossible");
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                          \
  case ReferenceOwnership::Name:                                               \
    if (!useLoweredAddresses()) {                                              \
      auto refTy = src.getType();                                              \
      auto ty = refTy.getReferenceStorageReferentType();                       \
      assert(ty);                                                              \
      assert(ty.getOptionalObjectType());                                      \
      (void)ty;                                                                \
      /* Copy the weak value, opening the @sil_weak box. */                    \
      return B.createStrongCopy##Name##Value(loc, src);                        \
    }                                                                          \
    /* Address-only storage types are handled with their underlying type. */   \
    llvm_unreachable("address-only pointers are handled elsewhere");
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \
  case ReferenceOwnership::Name:                                               \
    /* Generate a strong retain and strip the box. */                          \
    return B.createStrongCopy##Name##Value(loc, src);
#define UNCHECKED_REF_STORAGE(Name, ...)                                       \
  case ReferenceOwnership::Name:                                               \
    /* Strip the box and then do an (unsafe) retain. */                        \
    return B.createStrongCopy##Name##Value(loc, src);
#include "swift/AST/ReferenceStorage.def"
  }
  llvm_unreachable("impossible");
}

/// Given that the type-of-rvalue differs from the type-of-storage,
/// and given that the type-of-rvalue is loadable, produce a +1 scalar
/// of the type-of-rvalue.
static SILValue emitLoadOfSemanticRValue(SILGenFunction &SGF,
                                         SILLocation loc,
                                         SILValue src,
                                         const TypeLowering &valueTL,
                                         IsTake_t isTake) {
  auto storageType = src->getType();
  auto swiftStorageType = storageType.castTo<ReferenceStorageType>();

  switch (swiftStorageType->getOwnership()) {
  case ReferenceOwnership::Strong:
    llvm_unreachable("strong reference storage type should be impossible");
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: \
    return SGF.B.createLoad##Name(loc, src, isTake);
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name)          \
  {                                                                            \
    /* For loadable types, we need to strip the box. */                        \
    /* If we are not performing a take, use a load_borrow. */                  \
    if (!isTake) {                                                             \
      SILValue value = SGF.B.createLoadBorrow(loc, src);                       \
      SILValue strongValue = SGF.B.createStrongCopy##Name##Value(loc, value);  \
      SGF.B.createEndBorrow(loc, value);                                       \
      return strongValue;                                                      \
    }                                                                          \
    /* Otherwise perform a load take and destroy the stored value. */          \
    auto value =                                                               \
        SGF.B.emitLoadValueOperation(loc, src, LoadOwnershipQualifier::Take);  \
    SILValue strongValue = SGF.B.createStrongCopy##Name##Value(loc, value);    \
    SGF.B.createDestroyValue(loc, value);                                      \
    return strongValue;                                                        \
  }
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: \
    ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name)
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: { \
    /* For loadable types, we need to strip the box. */ \
    auto type = storageType.castTo<Name##StorageType>(); \
    if (!type->isLoadable(ResilienceExpansion::Maximal)) { \
      return SGF.B.createLoad##Name(loc, src, isTake); \
    } \
    ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name) \
  }
#define UNCHECKED_REF_STORAGE(Name, ...)                                       \
  case ReferenceOwnership::Name: {                                             \
    /* For static reference storage types, we need to strip the box. */        \
    auto value = SGF.B.createLoad(loc, src, LoadOwnershipQualifier::Trivial);  \
    return SGF.B.createStrongCopy##Name##Value(loc, value);                    \
  }
#include "swift/AST/ReferenceStorage.def"
#undef ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER
  }
  llvm_unreachable("unhandled ownership");
}

/// Given that the type-of-rvalue differs from the type-of-storage,
/// store a +1 value (possibly not a scalar) of the type-of-rvalue
/// into the given address.
static void emitStoreOfSemanticRValue(SILGenFunction &SGF,
                                      SILLocation loc,
                                      SILValue value,
                                      SILValue dest,
                                      const TypeLowering &valueTL,
                                      IsInitialization_t isInit) {
  auto storageType = dest->getType();
  auto swiftStorageType = storageType.castTo<ReferenceStorageType>();

  switch (swiftStorageType->getOwnership()) {
  case ReferenceOwnership::Strong:
    llvm_unreachable("strong reference storage type should be impossible");
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: { \
    SGF.B.createStore##Name(loc, value, dest, isInit); \
    /* store doesn't take ownership of the input, so cancel it out. */ \
    SGF.B.emitDestroyValueOperation(loc, value); \
    return; \
  }
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name) \
  { \
    auto typedValue = SGF.B.createRefTo##Name(loc, value, \
                                              storageType.getObjectType()); \
    auto copiedVal = SGF.B.createCopyValue(loc, typedValue); \
    emitUnloweredStoreOfCopy(SGF.B, loc, copiedVal, dest, isInit); \
    SGF.B.emitDestroyValueOperation(loc, value); \
    return; \
  }
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: \
    ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name)
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: { \
    /* For loadable types, we need to enter the box by */ \
    /* turning the strong retain into an type-specific retain. */ \
    auto type = storageType.castTo<Name##StorageType>(); \
    /* FIXME: resilience */ \
    if (!type->isLoadable(ResilienceExpansion::Maximal)) { \
      SGF.B.createStore##Name(loc, value, dest, isInit); \
      /* store doesn't take ownership of the input, so cancel it out. */ \
      SGF.B.emitDestroyValueOperation(loc, value); \
      return; \
    } \
    ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name) \
  }
#define UNCHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: { \
    /* For static reference storage types, we need to enter the box and */ \
    /* release the strong retain. */ \
    auto typedValue = SGF.B.createRefTo##Name(loc, value, \
                                              storageType.getObjectType()); \
    emitUnloweredStoreOfCopy(SGF.B, loc, typedValue, dest, isInit); \
    SGF.B.emitDestroyValueOperation(loc, value); \
    return; \
  }
#include "swift/AST/ReferenceStorage.def"
#undef ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER
  }
  llvm_unreachable("impossible");
}

/// Load a value of the type-of-rvalue out of the given address as a
/// scalar.  The type-of-rvalue must be loadable.
SILValue SILGenFunction::emitSemanticLoad(SILLocation loc,
                                          SILValue src,
                                          const TypeLowering &srcTL,
                                          const TypeLowering &rvalueTL,
                                          IsTake_t isTake) {
  assert(srcTL.getLoweredType().getAddressType() == src->getType());
  assert(rvalueTL.isLoadable() || !silConv.useLoweredAddresses());

  SILType srcType = srcTL.getLoweredType();
  SILType rvalueType = rvalueTL.getLoweredType();

  // Easy case: the types match exactly.
  if (srcType == rvalueType) {
    return srcTL.emitLoadOfCopy(B, loc, src, isTake);
  }

  // Harder case: the srcTL and the rvalueTL match without move only.
  if (srcType.removingMoveOnlyWrapper() ==
      rvalueType.removingMoveOnlyWrapper()) {
    // Ok, we know that one must be move only and the other must not be. Thus we
    // perform one of two things:
    //
    // 1. If our source address is move only and our rvalue type is not move
    // only, lets perform a load [copy] and a moveonly_to_copyable. We just need
    // to insert something so that the move only checker knows that this copy of
    // the move only address must be a last use.
    //
    // 2. If our dest value type is move only and our rvalue type is not move
    // only, then we perform a load [copy] + copyable_to_moveonly.
    SILValue newCopy = srcTL.emitLoadOfCopy(B, loc, src, isTake);
    if (newCopy->getType().isMoveOnlyWrapped()) {
      return B.createOwnedMoveOnlyWrapperToCopyableValue(loc, newCopy);
    }

    return B.createOwnedCopyableToMoveOnlyWrapperValue(loc, newCopy);
  }

  return emitLoadOfSemanticRValue(*this, loc, src, rvalueTL, isTake);
}

/// Load a value of the type-of-reference out of the given address
/// and into the destination address.
void SILGenFunction::emitSemanticLoadInto(SILLocation loc,
                                          SILValue src,
                                          const TypeLowering &srcTL,
                                          SILValue dest,
                                          const TypeLowering &destTL,
                                          IsTake_t isTake,
                                          IsInitialization_t isInit) {
  assert(srcTL.getLoweredType().getAddressType() == src->getType());
  assert(destTL.getLoweredType().getAddressType() == dest->getType());

  // Easy case: the types match.
  if (srcTL.getLoweredType() == destTL.getLoweredType()) {
    B.createCopyAddr(loc, src, dest, isTake, isInit);
    return;
  }

  // Then see if our source address was a moveonlywrapped type and our dest was
  // not. In such a case, just cast away the move only and perform a
  // copy_addr. We are going to error on this later after SILGen.
  if (srcTL.getLoweredType().removingMoveOnlyWrapper() ==
      destTL.getLoweredType().removingMoveOnlyWrapper()) {
    // In such a case, for now emit B.createCopyAddr. In the future, insert the
    // address version of moveonly_to_copyable.
    if (src->getType().isMoveOnlyWrapped()) {
      // If we have a take, we are performing an owned usage of our src addr. If
      // we aren't taking, then we can use guaranteed.
      if (isTake) {
        src = B.createMoveOnlyWrapperToCopyableAddr(loc, src);
      } else {
        src = B.createMoveOnlyWrapperToCopyableAddr(loc, src);
      }
    }
    if (dest->getType().isMoveOnlyWrapped()) {
      if (isInit) {
        dest = B.createMoveOnlyWrapperToCopyableAddr(loc, dest);
      } else {
        dest = B.createMoveOnlyWrapperToCopyableAddr(loc, dest);
      }
    }
    B.createCopyAddr(loc, src, dest, isTake, isInit);
    return;
  }

  auto rvalue = emitLoadOfSemanticRValue(*this, loc, src, srcTL, isTake);
  emitUnloweredStoreOfCopy(B, loc, rvalue, dest, isInit);
}

/// Store an r-value into the given address as an initialization.
void SILGenFunction::emitSemanticStore(SILLocation loc,
                                       SILValue rvalue,
                                       SILValue dest,
                                       const TypeLowering &destTL,
                                       IsInitialization_t isInit) {
  assert(destTL.getLoweredType().getAddressType() == dest->getType());

  if (rvalue->getType().isMoveOnlyWrapped()) {

    // If our rvalue is a moveonlywrapped value, insert a moveonly_to_copyable
    // instruction. We rely on the relevant checkers at the SIL level to
    // validate that this is safe to do. SILGen is just leaving in crumbs to be
    // checked.
    if (rvalue->getType().isObject())
      rvalue = B.createOwnedMoveOnlyWrapperToCopyableValue(loc, rvalue);
    else
      rvalue = B.createMoveOnlyWrapperToCopyableAddr(loc, rvalue);
  }

  // If our dest is a moveonlywrapped address, unwrap it.
  if (dest->getType().isMoveOnlyWrapped()) {
    dest = B.createMoveOnlyWrapperToCopyableAddr(loc, dest);
  }

  // Easy case: the types match.
  if (rvalue->getType().getObjectType() == dest->getType().getObjectType()) {
    assert(!silConv.useLoweredAddresses() ||
           (dest->getType().isAddressOnly(F) == rvalue->getType().isAddress()));
    if (rvalue->getType().isAddress()) {
      B.createCopyAddr(loc, rvalue, dest, IsTake, isInit);
    } else {
      emitUnloweredStoreOfCopy(B, loc, rvalue, dest, isInit);
    }
    return;
  }

  auto &rvalueTL = getTypeLowering(rvalue->getType());
  emitStoreOfSemanticRValue(*this, loc, rvalue, dest, rvalueTL, isInit);
}

/// Convert a semantic rvalue to a value of storage type.
SILValue SILGenFunction::emitConversionFromSemanticValue(SILLocation loc,
                                                         SILValue semanticValue,
                                                         SILType storageType) {
  auto &destTL = getTypeLowering(storageType);
  (void)destTL;
  // Easy case: the types match.
  if (semanticValue->getType() == storageType) {
    return semanticValue;
  }

  auto swiftStorageType = storageType.castTo<ReferenceStorageType>();
  if (!useLoweredAddresses() && storageType.isAddressOnly(F)) {
    switch (swiftStorageType->getOwnership()) {
      case ReferenceOwnership::Strong:
        llvm_unreachable("strong reference storage type should be impossible");
      case ReferenceOwnership::Unmanaged:
        llvm_unreachable("unimplemented");
      case ReferenceOwnership::Weak: {
        auto value = B.createWeakCopyValue(loc, semanticValue);
        B.emitDestroyValueOperation(loc, semanticValue);
        return value;
      }
      case ReferenceOwnership::Unowned: {
        auto value = B.createUnownedCopyValue(loc, semanticValue);
        B.emitDestroyValueOperation(loc, semanticValue);
        return value;
      }
    }
  }
  switch (swiftStorageType->getOwnership()) {
  case ReferenceOwnership::Strong:
    llvm_unreachable("strong reference storage type should be impossible");
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                          \
  case ReferenceOwnership::Name:                                               \
    llvm_unreachable("address-only types are never loadable");
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: { \
    SILValue value = B.createRefTo##Name(loc, semanticValue, storageType); \
    value = B.createCopyValue(loc, value); \
    B.emitDestroyValueOperation(loc, semanticValue); \
    return value; \
  }
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)                      \
  case ReferenceOwnership::Name: {                                             \
    /* For loadable types, place into a box. */                                \
    auto type = storageType.castTo<Name##StorageType>();                       \
    assert(type->isLoadable(ResilienceExpansion::Maximal));                    \
    (void)type;                                                                \
    SILValue value = B.createRefTo##Name(loc, semanticValue, storageType);     \
    value = B.createCopyValue(loc, value);                                     \
    B.emitDestroyValueOperation(loc, semanticValue);                           \
    return value;                                                              \
  }
#define UNCHECKED_REF_STORAGE(Name, ...) \
  case ReferenceOwnership::Name: { \
    /* For static reference storage types, place into a box. */ \
    SILValue value = B.createRefTo##Name(loc, semanticValue, storageType); \
    B.emitDestroyValueOperation(loc, semanticValue); \
    return value; \
  }
#include "swift/AST/ReferenceStorage.def"
  }
  llvm_unreachable("impossible");
}

static void emitTsanInoutAccess(SILGenFunction &SGF, SILLocation loc,
                                ManagedValue address) {
  assert(address.getType().isAddress());
  SILValue accessFnArgs[] = {address.getValue()};

  SGF.B.createBuiltin(loc, SGF.getASTContext().getIdentifier("tsanInoutAccess"),
                      SGF.SGM.Types.getEmptyTupleType(), {}, accessFnArgs);
}

/// Produce a physical address that corresponds to the given l-value
/// component.
static ManagedValue drillIntoComponent(SILGenFunction &SGF,
                                       SILLocation loc,
                                       PathComponent &&component,
                                       ManagedValue base,
                                       TSanKind tsanKind) {
  bool isRValue = component.isRValue();
  ManagedValue addr = std::move(component).project(SGF, loc, base);

  if ((SGF.getModule().getOptions().Sanitizers & SanitizerKind::Thread) &&
      tsanKind == TSanKind::InoutAccess && !isRValue) {
    emitTsanInoutAccess(SGF, loc, addr);
  }

  return addr;
}

/// Find the last component of the given lvalue and derive a base
/// location for it.
static PathComponent &&
drillToLastComponent(SILGenFunction &SGF,
                     SILLocation loc,
                     LValue &&lv,
                     ManagedValue &addr,
                     TSanKind tsanKind = TSanKind::None) {
  assert(lv.begin() != lv.end() &&
         "lvalue must have at least one component");

  for (auto i = lv.begin(), e = lv.end() - 1; i != e; ++i) {
    addr = drillIntoComponent(SGF, loc, std::move(**i), addr, tsanKind);
  }

  return std::move(**(lv.end() - 1));
}

static ArgumentSource emitBaseValueForAccessor(SILGenFunction &SGF,
                                               SILLocation loc, LValue &&lvalue,
                                               CanType baseFormalType,
                                               SILDeclRef accessor) {
  ManagedValue base;
  PathComponent &&component =
    drillToLastComponent(SGF, loc, std::move(lvalue), base);
  base = drillIntoComponent(SGF, loc, std::move(component), base,
                            TSanKind::None);

  return SGF.prepareAccessorBaseArg(loc, base, baseFormalType, accessor);
}

RValue SILGenFunction::emitLoadOfLValue(SILLocation loc, LValue &&src,
                                        SGFContext C, bool isBaseGuaranteed) {
  assert(isReadAccess(src.getAccessKind()));
  ExecutorBreadcrumb prevExecutor;
  RValue result;
  {
    // Any writebacks should be scoped to after the load.
    FormalEvaluationScope scope(*this);

    // We shouldn't need to re-abstract here, but we might have to bridge.
    // This should only happen if we have a global variable of NSString type.
    auto origFormalType = src.getOrigFormalType();
    auto substFormalType = src.getSubstFormalType();
    auto &rvalueTL = getTypeLowering(src.getTypeOfRValue());

    ManagedValue addr;
    PathComponent &&component =
        drillToLastComponent(*this, loc, std::move(src), addr);

    // If the last component is physical, drill down and load from it.
    if (component.isPhysical()) {
      auto projection = std::move(component).project(*this, loc, addr);
      if (projection.getType().isAddress()) {
        auto actorIso = component.asPhysical().takeActorIsolation();

        // If the load must happen in the context of an actor, do a hop first.
        prevExecutor = emitHopToTargetActor(loc, actorIso, addr);
        projection =
            emitLoad(loc, projection.getValue(), origFormalType,
                     substFormalType, rvalueTL, C, IsNotTake, isBaseGuaranteed);
      } else if (isReadAccessResultOwned(src.getAccessKind()) &&
          !projection.isPlusOneOrTrivial(*this)) {

        // Before we copy, if we have a move only wrapped value, unwrap the
        // value using a guaranteed moveonlywrapper_to_copyable.
        if (projection.getType().isMoveOnlyWrapped()) {
          // We are assuming we always get a guaranteed value here.
          assert(projection.getValue()->getOwnershipKind() ==
                 OwnershipKind::Guaranteed);
          // We use SILValues here to ensure we get a tight scope around our
          // copy.
          projection =
              B.createGuaranteedMoveOnlyWrapperToCopyableValue(loc, projection);
        }

        projection = projection.copy(*this, loc);
      }

      result = RValue(*this, loc, substFormalType, projection);
    } else {
      // If the last component is logical, emit a get.
      result = std::move(component.asLogical()).get(*this, loc, addr, C);
    }
  } // End the evaluation scope before any hop back to the current executor.

  // If we hopped to the target's executor, then we need to hop back.
  prevExecutor.emit(*this, loc);
  return result;
}

static AbstractionPattern
getFormalStorageAbstractionPattern(SILGenFunction &SGF, AbstractStorageDecl *field) {
  if (auto var = dyn_cast<VarDecl>(field)) {
    auto origType = SGF.SGM.Types.getAbstractionPattern(var);
    return origType.getReferenceStorageReferentType();
  }
  auto sub = cast<SubscriptDecl>(field);
  return SGF.SGM.Types.getAbstractionPattern(sub);
}

/// Produce a singular RValue for a load from the specified property.  This is
/// designed to work with RValue ManagedValue bases that are either +0 or +1.
RValue SILGenFunction::emitRValueForStorageLoad(
    SILLocation loc, ManagedValue base, CanType baseFormalType,
    bool isSuper, AbstractStorageDecl *storage,
    PreparedArguments &&subscriptIndices,
    SubstitutionMap substitutions,
    AccessSemantics semantics, Type propTy, SGFContext C,
    bool isBaseGuaranteed) {
  AccessStrategy strategy =
    storage->getAccessStrategy(semantics, AccessKind::Read,
                               SGM.M.getSwiftModule(),
                               F.getResilienceExpansion());

  // If we should call an accessor of some kind, do so.
  if (strategy.getKind() != AccessStrategy::Storage) {
    auto accessKind = SGFAccessKind::OwnedObjectRead;

    LValue lv = [&] {
      if (!base) return LValue();

      auto baseAccess = getBaseAccessKind(SGM, storage, accessKind,
                                          strategy, baseFormalType,
                                          /*for borrow*/ false);
      return LValue::forValue(baseAccess, base, baseFormalType);
    }();

    lv.addMemberComponent(*this, loc, storage, substitutions, LValueOptions(),
                          isSuper, accessKind, strategy,
                          propTy->getCanonicalType(),
                          std::move(subscriptIndices),
                          /*index for diagnostics*/ nullptr);

    return emitLoadOfLValue(loc, std::move(lv), C, isBaseGuaranteed);
  }

  assert(isa<VarDecl>(storage) && "only properties should have storage");
  auto field = cast<VarDecl>(storage);
  assert(field->hasStorage() &&
         "Cannot directly access value without storage");

  // For static variables, emit a reference to the global variable backing
  // them.
  // FIXME: This has to be dynamically looked up for classes, and
  // dynamically instantiated for generics.
  if (field->isStatic()) {
    auto baseMeta = base.getType().castTo<MetatypeType>().getInstanceType();
    (void)baseMeta;
    assert(!baseMeta->is<BoundGenericType>() &&
           "generic static stored properties not implemented");
    if (field->getDeclContext()->getSelfClassDecl() &&
        field->hasStorage())
      // FIXME: don't need to check hasStorage, already done above
      assert(field->isFinal() && "non-final class stored properties not implemented");

    return emitRValueForDecl(loc, field, propTy, semantics, C);
  }


  // rvalue MemberRefExprs are produced in two cases: when accessing a 'let'
  // decl member, and when the base is a (non-lvalue) struct.
  assert(baseFormalType->getAnyNominal() &&
         base.getType().getASTType()->getAnyNominal() &&
         "The base of an rvalue MemberRefExpr should be an rvalue value");

  // If the accessed field is stored, emit a StructExtract on the base.

  auto substFormalType = propTy->getCanonicalType();
  auto &lowering = getTypeLowering(substFormalType);

  // Check for an abstraction difference.
  AbstractionPattern origFormalType =
    getFormalStorageAbstractionPattern(*this, field);
  bool hasAbstractionChange = false;
  auto &abstractedTL = getTypeLowering(origFormalType, substFormalType);
  if (!origFormalType.isExactType(substFormalType)) {
    hasAbstractionChange =
        (abstractedTL.getLoweredType() != lowering.getLoweredType());
  }

  // If the base is a reference type, just handle this as loading the lvalue.
  ManagedValue result;
  if (baseFormalType->hasReferenceSemantics()) {
    LValue LV = emitPropertyLValue(loc, base, baseFormalType, field,
                                   LValueOptions(),
                                   SGFAccessKind::OwnedObjectRead,
                                   AccessSemantics::DirectToStorage);
    auto loaded = emitLoadOfLValue(loc, std::move(LV), C, isBaseGuaranteed);
    // If we don't have to reabstract, the load is sufficient.
    if (!hasAbstractionChange)
      return loaded;

    // Otherwise, bring the component up to +1 so we can reabstract it.
    result = std::move(loaded).getAsSingleValue(*this, loc)
                              .copyUnmanaged(*this, loc);
  } else if (!base.getType().isAddress()) {
    // For non-address-only structs, we emit a struct_extract sequence.
    result = B.createStructExtract(loc, base, field);

    if (result.getType().is<ReferenceStorageType>()) {
      // For weak and unowned types, convert the reference to the right
      // pointer, producing a +1.
      result = emitConversionToSemanticRValue(loc, result, lowering);

    } else if (hasAbstractionChange ||
               (!C.isImmediatePlusZeroOk() &&
                !(C.isGuaranteedPlusZeroOk() && isBaseGuaranteed))) {
      // If we have an abstraction change or if we have to produce a result at
      // +1, then copy the value. If we know that our base will stay alive for
      // the entire usage of this value, we can borrow the value at +0 for a
      // guaranteed consumer. Otherwise, since we do not have enough information
      // to know if the base's lifetime last's as long as our use of the access,
      // we can only emit at +0 for immediate clients.
      result = result.copyUnmanaged(*this, loc);
    }
  } else {
    // Create a tiny unenforced access scope around a load from local memory. No
    // cleanup is necessary since we directly emit the load here. This will
    // probably go away with opaque values.
    UnenforcedAccess access;
    SILValue accessAddress =
      access.beginAccess(*this, loc, base.getValue(), SILAccessKind::Read);

    // For address-only sequences, the base is in memory.  Emit a
    // struct_element_addr to get to the field, and then load the element as an
    // rvalue.
    SILValue ElementPtr = B.createStructElementAddr(loc, accessAddress, field);

    result = emitLoad(loc, ElementPtr, abstractedTL,
                      hasAbstractionChange ? SGFContext() : C, IsNotTake);
    access.endAccess(*this);
  }

  // If we're accessing this member with an abstraction change, perform that
  // now.
  if (hasAbstractionChange)
    result =
        emitOrigToSubstValue(loc, result, origFormalType, substFormalType, C);
  return RValue(*this, loc, substFormalType, result);
}

ManagedValue SILGenFunction::emitAddressOfLValue(SILLocation loc,
                                                 LValue &&src,
                                                 TSanKind tsanKind) {
  assert(src.getAccessKind() == SGFAccessKind::IgnoredRead ||
         src.getAccessKind() == SGFAccessKind::BorrowedAddressRead ||
         src.getAccessKind() == SGFAccessKind::OwnedAddressRead ||
         src.getAccessKind() == SGFAccessKind::OwnedAddressConsume ||
         src.getAccessKind() == SGFAccessKind::ReadWrite);

  ManagedValue addr;
  PathComponent &&component =
    drillToLastComponent(*this, loc, std::move(src), addr, tsanKind);

  addr = drillIntoComponent(*this, loc, std::move(component), addr, tsanKind);
  assert(addr.getType().isAddress() &&
         "resolving lvalue did not give an address");
  return ManagedValue::forLValue(addr.getValue());
}

ManagedValue SILGenFunction::emitBorrowedLValue(SILLocation loc,
                                                LValue &&src,
                                                TSanKind tsanKind) {
  assert(src.getAccessKind() == SGFAccessKind::IgnoredRead ||
         src.getAccessKind() == SGFAccessKind::BorrowedAddressRead ||
         src.getAccessKind() == SGFAccessKind::BorrowedObjectRead);
  bool isIgnored = src.getAccessKind() == SGFAccessKind::IgnoredRead;

  ManagedValue base;
  PathComponent &&component =
    drillToLastComponent(*this, loc, std::move(src), base, tsanKind);

  auto value =
    drillIntoComponent(*this, loc, std::move(component), base, tsanKind);

  // If project() returned an owned value, and the caller cares, borrow it.
  if (value.hasCleanup() && !isIgnored)
    value = value.formalAccessBorrow(*this, loc);
  return value;
}

ManagedValue SILGenFunction::emitConsumedLValue(SILLocation loc, LValue &&src,
                                                TSanKind tsanKind) {
  assert(isConsumeAccess(src.getAccessKind()));

  ManagedValue base;
  PathComponent &&component =
      drillToLastComponent(*this, loc, std::move(src), base, tsanKind);

  auto value =
      drillIntoComponent(*this, loc, std::move(component), base, tsanKind);

  return value;
}

LValue
SILGenFunction::emitOpenExistentialLValue(SILLocation loc,
                                          LValue &&lv,
                                          CanArchetypeType openedArchetype,
                                          CanType formalRValueType,
                                          SGFAccessKind accessKind) {
  assert(!formalRValueType->hasLValueType());
  LValueTypeData typeData = {
    accessKind, AbstractionPattern::getOpaque(), formalRValueType,
    getLoweredType(formalRValueType).getASTType()
  };

  // Open up the existential.
  auto rep = lv.getTypeOfRValue()
    .getPreferredExistentialRepresentation();
  switch (rep) {
  case ExistentialRepresentation::Opaque:
  case ExistentialRepresentation::Boxed: {
    lv.add<OpenOpaqueExistentialComponent>(openedArchetype, typeData);
    break;
  }
  case ExistentialRepresentation::Metatype:
  case ExistentialRepresentation::Class: {
    lv.add<OpenNonOpaqueExistentialComponent>(openedArchetype, typeData);
    break;
  }
  case ExistentialRepresentation::None:
    llvm_unreachable("cannot open non-existential");
  }

  return std::move(lv);
}

static bool trySetterPeephole(SILGenFunction &SGF, SILLocation loc,
                              ArgumentSource &&src, LValue &&dest) {
  // The last component must be a getter/setter.
  // TODO: allow reabstraction here, too.
  auto &component = **(dest.end() - 1);
  if (component.getKind() != PathComponent::GetterSetterKind)
    return false;

  // We cannot apply the peephole if the l-value includes an
  // open-existential component because we need to make sure that
  // the opened archetype is available everywhere during emission.
  // TODO: should we instead just immediately open the existential
  // during emitLValue and simply leave the opened address in the LValue?
  // Or is there some reasonable way to detect that this is happening
  // and avoid affecting cases where it is not necessary?
  for (auto &componentPtr : dest) {
    if (componentPtr->isOpenExistential())
      return false;
  }

  auto &setterComponent = static_cast<GetterSetterComponent&>(component);
  if (setterComponent.canRewriteSetAsPropertyWrapperInit(SGF) ||
      setterComponent.canRewriteSetAsInitAccessor(SGF))
    return false;

  setterComponent.emitAssignWithSetter(SGF, loc, std::move(dest),
                                       std::move(src));
  return true;;
}

void SILGenFunction::emitAssignToLValue(SILLocation loc, RValue &&src,
                                        LValue &&dest) {
  emitAssignToLValue(loc, ArgumentSource(loc, std::move(src)), std::move(dest));
}

namespace {

} // end anonymous namespace

/// Checks if the last component of the LValue refers to the given var decl.
static bool referencesVar(PathComponent const& comp, VarDecl *var) {
  if (comp.getKind() != PathComponent::RefElementKind)
    return false;

  return static_cast<RefElementComponent const&>(comp).getField() == var;
}

void SILGenFunction::emitAssignToLValue(SILLocation loc,
                                        ArgumentSource &&src,
                                        LValue &&dest) {
  // Enter a FormalEvaluationScope so that formal access to independent LValue
  // components do not overlap. Furthermore, use an ArgumentScope to force
  // cleanup of materialized LValues immediately, before evaluating the next
  // LValue. For example: (x[i], x[j]) = a, b
  ArgumentScope argScope(*this, loc);

  // If this is an assignment to a distributed actor's actorSystem, push
  // a clean-up to also initialize its id.
  if (LLVM_UNLIKELY(DistActorCtorContext) &&
      referencesVar(**(dest.end()-1), DistActorCtorContext->getSystemVar()))
    Cleanups.pushCleanup<InitializeDistActorIdentity>(*DistActorCtorContext);

  // If the last component is a getter/setter component, use a special
  // generation pattern that allows us to peephole the emission of the RHS.
  if (trySetterPeephole(*this, loc, std::move(src), std::move(dest))) {
    argScope.pop();
    return;
  }

  // Otherwise, force the RHS now to preserve evaluation order.
  auto srcLoc = src.getLocation();
  RValue srcValue = std::move(src).getAsRValue(*this);

  // Peephole: instead of materializing and then assigning into a
  // translation component, untransform the value first.
  while (dest.isLastComponentTranslation()) {
    srcValue = std::move(dest.getLastTranslationComponent())
                 .untranslate(*this, loc, std::move(srcValue));
    dest.dropLastTranslationComponent();
  }

  src = ArgumentSource(srcLoc, std::move(srcValue));

  // Resolve all components up to the last, keeping track of value-type logical
  // properties we need to write back to.
  ManagedValue destAddr;
  PathComponent &&component =
    drillToLastComponent(*this, loc, std::move(dest), destAddr);
  
  // Write to the tail component.
  if (component.isPhysical()) {
    std::move(component.asPhysical()).set(*this, loc, std::move(src), destAddr);
  } else {
    std::move(component.asLogical()).set(*this, loc, std::move(src), destAddr);
  }

  // The writeback scope closing will propagate the value back up through the
  // writeback chain.
  argScope.pop();
}

void SILGenFunction::emitCopyLValueInto(SILLocation loc, LValue &&src,
                                        Initialization *dest) {
  auto skipPeephole = [&]{
    auto loaded = emitLoadOfLValue(loc, std::move(src), SGFContext(dest));
    if (!loaded.isInContext())
      std::move(loaded).forwardInto(*this, loc, dest);
  };
  
  // If the source is a physical lvalue, the destination is a single address,
  // and there's no semantic conversion necessary, do a copy_addr from the
  // lvalue into the destination.
  if (!src.isPhysical())
    return skipPeephole();
  if (!dest->canPerformInPlaceInitialization())
    return skipPeephole();
  auto destAddr = dest->getAddressForInPlaceInitialization(*this, loc);
  assert(src.getTypeOfRValue().getASTType()
           == destAddr->getType().getASTType());

  auto srcAddr = emitAddressOfLValue(loc, std::move(src)).getUnmanagedValue();

  UnenforcedAccess access;
  SILValue accessAddress =
    access.beginAccess(*this, loc, destAddr, SILAccessKind::Modify);

  if (srcAddr->getType().isMoveOnlyWrapped())
    srcAddr = B.createMoveOnlyWrapperToCopyableAddr(loc, srcAddr);
  if (accessAddress->getType().isMoveOnlyWrapped())
    accessAddress = B.createMoveOnlyWrapperToCopyableAddr(loc, accessAddress);

  B.createCopyAddr(loc, srcAddr, accessAddress, IsNotTake, IsInitialization);
  access.endAccess(*this);

  dest->finishInitialization(*this);
}

void SILGenFunction::emitAssignLValueToLValue(SILLocation loc, LValue &&src,
                                              LValue &&dest) {
  // Only perform the peephole if both operands are physical, there's no
  // semantic conversion necessary, and exclusivity enforcement
  // is not enabled. The peephole interferes with exclusivity enforcement
  // because it causes the formal accesses to the source and destination to
  // overlap.
  bool peepholeConflict =
      !src.isObviouslyNonConflicting(dest, SGFAccessKind::OwnedObjectRead,
                                     SGFAccessKind::Write);

  if (peepholeConflict || !src.isPhysical() || !dest.isPhysical()) {
    RValue loaded = emitLoadOfLValue(loc, std::move(src), SGFContext());
    emitAssignToLValue(loc, std::move(loaded), std::move(dest));
    return;
  }

  // If this is an assignment to a distributed actor's actorSystem, push
  // a clean-up to also initialize its id.
  // FIXME: in what situations does this lvalue to lvalue assign happen?
  if (LLVM_UNLIKELY(DistActorCtorContext) &&
      referencesVar(**(dest.end()-1), DistActorCtorContext->getSystemVar()))
    Cleanups.pushCleanup<InitializeDistActorIdentity>(*DistActorCtorContext);

  auto &rvalueTL = getTypeLowering(src.getTypeOfRValue());

  auto srcAddr = emitAddressOfLValue(loc, std::move(src)).getUnmanagedValue();
  auto destAddr = emitAddressOfLValue(loc, std::move(dest)).getUnmanagedValue();

  if (srcAddr->getType() == destAddr->getType()) {
    B.createCopyAddr(loc, srcAddr, destAddr, IsNotTake, IsNotInitialization);
  } else {
    // If there's a semantic conversion necessary, do a load then assign.
    auto loaded = emitLoad(loc, srcAddr, rvalueTL, SGFContext(), IsNotTake);
    loaded.assignInto(*this, loc, destAddr);
  }
}