Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MarkStep.cs « Linker.Steps « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 646e2e6bd96da9b440902e261da09642c02969b5 (plain)
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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

//
// MarkStep.cs
//
// Author:
//   Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
// (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection.Runtime.TypeParsing;
using System.Text.RegularExpressions;
using ILLink.Shared;
using ILLink.Shared.TrimAnalysis;
using ILLink.Shared.TypeSystemProxy;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.Linker.Dataflow;

namespace Mono.Linker.Steps
{

	public partial class MarkStep : IStep
	{
		LinkContext? _context;
		protected LinkContext Context {
			get {
				Debug.Assert (_context != null);
				return _context;
			}
		}

		protected Queue<(MethodDefinition, DependencyInfo, MessageOrigin)> _methods;
		protected HashSet<(MethodDefinition, MarkScopeStack.Scope)> _virtual_methods;
		protected Queue<AttributeProviderPair> _assemblyLevelAttributes;
		readonly List<AttributeProviderPair> _ivt_attributes;
		protected Queue<(AttributeProviderPair, DependencyInfo, MarkScopeStack.Scope)> _lateMarkedAttributes;
		protected List<(TypeDefinition, MarkScopeStack.Scope)> _typesWithInterfaces;
		protected HashSet<(OverrideInformation, MarkScopeStack.Scope)> _interfaceOverrides;
		protected HashSet<AssemblyDefinition> _dynamicInterfaceCastableImplementationTypesDiscovered;
		protected List<TypeDefinition> _dynamicInterfaceCastableImplementationTypes;
		protected List<(MethodBody, MarkScopeStack.Scope)> _unreachableBodies;

		readonly List<(TypeDefinition Type, MethodBody Body, Instruction Instr)> _pending_isinst_instr;

		// Stores, for compiler-generated methods only, whether they require the reflection
		// method body scanner.
		readonly Dictionary<MethodBody, bool> _compilerGeneratedMethodRequiresScanner;

		MarkStepContext? _markContext;
		MarkStepContext MarkContext {
			get {
				Debug.Assert (_markContext != null);
				return _markContext;
			}
		}
		readonly HashSet<TypeDefinition> _entireTypesMarked;
		DynamicallyAccessedMembersTypeHierarchy? _dynamicallyAccessedMembersTypeHierarchy;
		MarkScopeStack? _scopeStack;
		MarkScopeStack ScopeStack {
			get {
				Debug.Assert (_scopeStack != null);
				return _scopeStack;
			}
		}

		internal DynamicallyAccessedMembersTypeHierarchy DynamicallyAccessedMembersTypeHierarchy {
			get {
				Debug.Assert (_dynamicallyAccessedMembersTypeHierarchy != null);
				return _dynamicallyAccessedMembersTypeHierarchy;
			}
		}

#if DEBUG
		static readonly DependencyKind[] _entireTypeReasons = new DependencyKind[] {
			DependencyKind.AccessedViaReflection,
			DependencyKind.BaseType,
			DependencyKind.PreservedDependency,
			DependencyKind.NestedType,
			DependencyKind.TypeInAssembly,
			DependencyKind.Unspecified,
		};

		static readonly DependencyKind[] _fieldReasons = new DependencyKind[] {
			DependencyKind.Unspecified,
			DependencyKind.AccessedViaReflection,
			DependencyKind.AlreadyMarked,
			DependencyKind.Custom,
			DependencyKind.CustomAttributeField,
			DependencyKind.DynamicallyAccessedMember,
			DependencyKind.DynamicallyAccessedMemberOnType,
			DependencyKind.EventSourceProviderField,
			DependencyKind.FieldAccess,
			DependencyKind.FieldOnGenericInstance,
			DependencyKind.InteropMethodDependency,
			DependencyKind.Ldtoken,
			DependencyKind.MemberOfType,
			DependencyKind.DynamicDependency,
			DependencyKind.ReferencedBySpecialAttribute,
			DependencyKind.TypePreserve,
			DependencyKind.XmlDescriptor,
		};

		static readonly DependencyKind[] _typeReasons = new DependencyKind[] {
			DependencyKind.Unspecified,
			DependencyKind.AccessedViaReflection,
			DependencyKind.AlreadyMarked,
			DependencyKind.AttributeType,
			DependencyKind.BaseType,
			DependencyKind.CatchType,
			DependencyKind.Custom,
			DependencyKind.CustomAttributeArgumentType,
			DependencyKind.CustomAttributeArgumentValue,
			DependencyKind.DeclaringType,
			DependencyKind.DeclaringTypeOfCalledMethod,
			DependencyKind.DynamicallyAccessedMember,
			DependencyKind.DynamicallyAccessedMemberOnType,
			DependencyKind.DynamicDependency,
			DependencyKind.ElementType,
			DependencyKind.FieldType,
			DependencyKind.GenericArgumentType,
			DependencyKind.GenericParameterConstraintType,
			DependencyKind.InterfaceImplementationInterfaceType,
			DependencyKind.Ldtoken,
			DependencyKind.ModifierType,
			DependencyKind.InstructionTypeRef,
			DependencyKind.ParameterType,
			DependencyKind.ReferencedBySpecialAttribute,
			DependencyKind.ReturnType,
			DependencyKind.TypeInAssembly,
			DependencyKind.UnreachableBodyRequirement,
			DependencyKind.VariableType,
			DependencyKind.ParameterMarshalSpec,
			DependencyKind.FieldMarshalSpec,
			DependencyKind.ReturnTypeMarshalSpec,
			DependencyKind.DynamicInterfaceCastableImplementation,
			DependencyKind.XmlDescriptor,
		};

		static readonly DependencyKind[] _methodReasons = new DependencyKind[] {
			DependencyKind.Unspecified,
			DependencyKind.AccessedViaReflection,
			DependencyKind.AlreadyMarked,
			DependencyKind.AttributeConstructor,
			DependencyKind.AttributeProperty,
			DependencyKind.BaseDefaultCtorForStubbedMethod,
			DependencyKind.BaseMethod,
			DependencyKind.CctorForType,
			DependencyKind.CctorForField,
			DependencyKind.Custom,
			DependencyKind.DefaultCtorForNewConstrainedGenericArgument,
			DependencyKind.DirectCall,
			DependencyKind.DynamicallyAccessedMember,
			DependencyKind.DynamicallyAccessedMemberOnType,
			DependencyKind.DynamicDependency,
			DependencyKind.ElementMethod,
			DependencyKind.EventMethod,
			DependencyKind.EventOfEventMethod,
			DependencyKind.InteropMethodDependency,
			DependencyKind.KeptForSpecialAttribute,
			DependencyKind.Ldftn,
			DependencyKind.Ldtoken,
			DependencyKind.Ldvirtftn,
			DependencyKind.MemberOfType,
			DependencyKind.MethodForInstantiatedType,
			DependencyKind.MethodForSpecialType,
			DependencyKind.MethodImplOverride,
			DependencyKind.MethodOnGenericInstance,
			DependencyKind.Newobj,
			DependencyKind.Override,
			DependencyKind.OverrideOnInstantiatedType,
			DependencyKind.DynamicDependency,
			DependencyKind.PreservedMethod,
			DependencyKind.ReferencedBySpecialAttribute,
			DependencyKind.SerializationMethodForType,
			DependencyKind.TriggersCctorForCalledMethod,
			DependencyKind.TriggersCctorThroughFieldAccess,
			DependencyKind.TypePreserve,
			DependencyKind.UnreachableBodyRequirement,
			DependencyKind.VirtualCall,
			DependencyKind.VirtualNeededDueToPreservedScope,
			DependencyKind.ParameterMarshalSpec,
			DependencyKind.FieldMarshalSpec,
			DependencyKind.ReturnTypeMarshalSpec,
			DependencyKind.XmlDescriptor,
		};
#endif

		public MarkStep ()
		{
			_methods = new Queue<(MethodDefinition, DependencyInfo, MessageOrigin)> ();
			_virtual_methods = new HashSet<(MethodDefinition, MarkScopeStack.Scope)> ();
			_assemblyLevelAttributes = new Queue<AttributeProviderPair> ();
			_ivt_attributes = new List<AttributeProviderPair> ();
			_lateMarkedAttributes = new Queue<(AttributeProviderPair, DependencyInfo, MarkScopeStack.Scope)> ();
			_typesWithInterfaces = new List<(TypeDefinition, MarkScopeStack.Scope)> ();
			_interfaceOverrides = new HashSet<(OverrideInformation, MarkScopeStack.Scope)> ();
			_dynamicInterfaceCastableImplementationTypesDiscovered = new HashSet<AssemblyDefinition> ();
			_dynamicInterfaceCastableImplementationTypes = new List<TypeDefinition> ();
			_unreachableBodies = new List<(MethodBody, MarkScopeStack.Scope)> ();
			_pending_isinst_instr = new List<(TypeDefinition, MethodBody, Instruction)> ();
			_entireTypesMarked = new HashSet<TypeDefinition> ();
			_compilerGeneratedMethodRequiresScanner = new Dictionary<MethodBody, bool> ();
		}

		public AnnotationStore Annotations => Context.Annotations;
		public MarkingHelpers MarkingHelpers => Context.MarkingHelpers;
		public Tracer Tracer => Context.Tracer;

		public virtual void Process (LinkContext context)
		{
			_context = context;
			_markContext = new MarkStepContext ();
			_scopeStack = new MarkScopeStack ();
			_dynamicallyAccessedMembersTypeHierarchy = new DynamicallyAccessedMembersTypeHierarchy (_context, this);

			Initialize ();
			Process ();
			Complete ();
		}

		void Initialize ()
		{
			InitializeCorelibAttributeXml ();
			Context.Pipeline.InitializeMarkHandlers (Context, MarkContext);

			ProcessMarkedPending ();
		}

		void InitializeCorelibAttributeXml ()
		{
			// Pre-load corelib and process its attribute XML first. This is necessary because the
			// corelib attribute XML can contain modifications to other assemblies.
			// We could just mark it here, but the attribute processing isn't necessarily tied to marking,
			// so this would rely on implementation details of corelib.
			var coreLib = Context.TryResolve (PlatformAssemblies.CoreLib);
			if (coreLib == null)
				return;

			var xmlInfo = EmbeddedXmlInfo.ProcessAttributes (coreLib, Context);
			if (xmlInfo == null)
				return;

			// Because the attribute XML can reference other assemblies, they must go in the global store,
			// instead of the per-assembly stores.
			foreach (var (provider, annotations) in xmlInfo.CustomAttributes)
				Context.CustomAttributes.PrimaryAttributeInfo.AddCustomAttributes (provider, annotations);

			foreach (var (ca, origin) in xmlInfo.CustomAttributesOrigins)
				Context.CustomAttributes.PrimaryAttributeInfo.CustomAttributesOrigins.Add (ca, origin);
		}

		void Complete ()
		{
			foreach ((var body, var _) in _unreachableBodies) {
				Annotations.SetAction (body.Method, MethodAction.ConvertToThrow);
			}
		}

		bool ProcessInternalsVisibleAttributes ()
		{
			bool marked_any = false;
			foreach (var attr in _ivt_attributes) {

				var provider = attr.Provider;
				Debug.Assert (attr.Provider is ModuleDefinition or AssemblyDefinition);
				var assembly = (provider is ModuleDefinition module) ? module.Assembly : provider as AssemblyDefinition;

				using var assemblyScope = ScopeStack.PushScope (new MessageOrigin (assembly));

				if (!Annotations.IsMarked (attr.Attribute) && IsInternalsVisibleAttributeAssemblyMarked (attr.Attribute)) {
					MarkCustomAttribute (attr.Attribute, new DependencyInfo (DependencyKind.AssemblyOrModuleAttribute, attr.Provider));
					marked_any = true;
				}
			}

			return marked_any;

			bool IsInternalsVisibleAttributeAssemblyMarked (CustomAttribute ca)
			{
				System.Reflection.AssemblyName an;
				try {
					an = new System.Reflection.AssemblyName ((string) ca.ConstructorArguments[0].Value);
				} catch {
					return false;
				}

				var assembly = Context.GetLoadedAssembly (an.Name!);
				if (assembly == null)
					return false;

				return Annotations.IsMarked (assembly.MainModule);
			}
		}

		static bool TypeIsDynamicInterfaceCastableImplementation (TypeDefinition type)
		{
			if (!type.IsInterface || !type.HasInterfaces || !type.HasCustomAttributes)
				return false;

			foreach (var ca in type.CustomAttributes) {
				if (ca.AttributeType.IsTypeOf ("System.Runtime.InteropServices", "DynamicInterfaceCastableImplementationAttribute"))
					return true;
			}
			return false;
		}

		protected bool IsFullyPreserved (TypeDefinition type)
		{
			if (Annotations.TryGetPreserve (type, out TypePreserve preserve) && preserve == TypePreserve.All)
				return true;

			switch (Annotations.GetAction (type.Module.Assembly)) {
			case AssemblyAction.Save:
			case AssemblyAction.Copy:
			case AssemblyAction.CopyUsed:
			case AssemblyAction.AddBypassNGen:
			case AssemblyAction.AddBypassNGenUsed:
				return true;
			}

			return false;
		}

		internal void MarkEntireType (TypeDefinition type, in DependencyInfo reason)
		{
#if DEBUG
			if (!_entireTypeReasons.Contains (reason.Kind))
				throw new InternalErrorException ($"Unsupported type dependency '{reason.Kind}'.");
#endif

			// Prevent cases where there's nothing on the stack (can happen when marking entire assemblies)
			// In which case we would generate warnings with no source (hard to debug)
			using var _ = ScopeStack.CurrentScope.Origin.Provider == null ? ScopeStack.PushScope (new MessageOrigin (type)) : null;

			if (!_entireTypesMarked.Add (type))
				return;

			if (type.HasNestedTypes) {
				foreach (TypeDefinition nested in type.NestedTypes)
					MarkEntireType (nested, new DependencyInfo (DependencyKind.NestedType, type));
			}

			Annotations.Mark (type, reason, ScopeStack.CurrentScope.Origin);
			MarkCustomAttributes (type, new DependencyInfo (DependencyKind.CustomAttribute, type));
			MarkTypeSpecialCustomAttributes (type);

			if (type.HasInterfaces) {
				foreach (InterfaceImplementation iface in type.Interfaces)
					MarkInterfaceImplementation (iface, new MessageOrigin (type));
			}

			MarkGenericParameterProvider (type);

			if (type.HasFields) {
				foreach (FieldDefinition field in type.Fields) {
					MarkField (field, new DependencyInfo (DependencyKind.MemberOfType, type), ScopeStack.CurrentScope.Origin);
				}
			}

			if (type.HasMethods) {
				foreach (MethodDefinition method in type.Methods) {
					Annotations.SetAction (method, MethodAction.ForceParse);
					MarkMethod (method, new DependencyInfo (DependencyKind.MemberOfType, type), ScopeStack.CurrentScope.Origin);
				}
			}

			if (type.HasProperties) {
				foreach (var property in type.Properties) {
					MarkProperty (property, new DependencyInfo (DependencyKind.MemberOfType, type));
				}
			}

			if (type.HasEvents) {
				foreach (var ev in type.Events) {
					MarkEvent (ev, new DependencyInfo (DependencyKind.MemberOfType, type));
				}
			}
		}

		void Process ()
		{
			while (ProcessPrimaryQueue () ||
				ProcessMarkedPending () ||
				ProcessLazyAttributes () ||
				ProcessLateMarkedAttributes () ||
				MarkFullyPreservedAssemblies () ||
				ProcessInternalsVisibleAttributes ()) ;

			ProcessPendingTypeChecks ();
		}

		static bool IsFullyPreservedAction (AssemblyAction action) => action == AssemblyAction.Copy || action == AssemblyAction.Save;

		bool MarkFullyPreservedAssemblies ()
		{
			// Fully mark any assemblies with copy/save action.

			// Unresolved references could get the copy/save action if this is the default action.
			bool scanReferences = IsFullyPreservedAction (Context.TrimAction) || IsFullyPreservedAction (Context.DefaultAction);

			if (!scanReferences) {
				// Unresolved references could get the copy/save action if it was set explicitly
				// for some referenced assembly that has not been resolved yet
				foreach (var (assemblyName, action) in Context.Actions) {
					if (!IsFullyPreservedAction (action))
						continue;

					var assembly = Context.GetLoadedAssembly (assemblyName);
					if (assembly == null) {
						scanReferences = true;
						break;
					}

					// The action should not change from the explicit command-line action
					Debug.Assert (Annotations.GetAction (assembly) == action);
				}
			}

			// Setup empty scope - there has to be some scope setup since we're doing marking below
			// but there's no "origin" right now (command line is the origin really)
			using var localScope = ScopeStack.PushScope (new MessageOrigin ((ICustomAttributeProvider?) null));

			// Beware: this works on loaded assemblies, not marked assemblies, so it should not be tied to marking.
			// We could further optimize this to only iterate through assemblies if the last mark iteration loaded
			// a new assembly, since this is the only way that the set we need to consider could have changed.
			var assembliesToCheck = scanReferences ? Context.GetReferencedAssemblies ().ToArray () : Context.GetAssemblies ();
			bool markedNewAssembly = false;
			foreach (var assembly in assembliesToCheck) {
				var action = Annotations.GetAction (assembly);
				if (!IsFullyPreservedAction (action))
					continue;
				if (!Annotations.IsProcessed (assembly))
					markedNewAssembly = true;
				MarkAssembly (assembly, new DependencyInfo (DependencyKind.AssemblyAction, null));
			}
			return markedNewAssembly;
		}

		bool ProcessPrimaryQueue ()
		{
			if (QueueIsEmpty ())
				return false;

			while (!QueueIsEmpty ()) {
				ProcessQueue ();
				ProcessVirtualMethods ();
				ProcessMarkedTypesWithInterfaces ();
				ProcessDynamicCastableImplementationInterfaces ();
				ProcessPendingBodies ();
				DoAdditionalProcessing ();
			}

			return true;
		}

		bool ProcessMarkedPending ()
		{
			using var emptyScope = ScopeStack.PushScope (new MessageOrigin (null as ICustomAttributeProvider));

			bool marked = false;
			foreach (var pending in Annotations.GetMarkedPending ()) {
				marked = true;

				// Some pending items might be processed by the time we get to them.
				if (Annotations.IsProcessed (pending.Key))
					continue;

				using var localScope = ScopeStack.PushScope (pending.Value);

				switch (pending.Key) {
				case TypeDefinition type:
					MarkType (type, DependencyInfo.AlreadyMarked);
					break;
				case MethodDefinition method:
					MarkMethod (method, DependencyInfo.AlreadyMarked, ScopeStack.CurrentScope.Origin);
					// Methods will not actually be processed until we drain the method queue.
					break;
				case FieldDefinition field:
					MarkField (field, DependencyInfo.AlreadyMarked, ScopeStack.CurrentScope.Origin);
					break;
				case ModuleDefinition module:
					MarkModule (module, DependencyInfo.AlreadyMarked);
					break;
				case ExportedType exportedType:
					Annotations.SetProcessed (exportedType);
					// No additional processing is done for exported types.
					break;
				default:
					throw new NotImplementedException (pending.GetType ().ToString ());
				}
			}

			foreach (var type in Annotations.GetPendingPreserve ()) {
				marked = true;
				Debug.Assert (Annotations.IsProcessed (type));
				ApplyPreserveInfo (type);
			}

			return marked;
		}

		void ProcessPendingTypeChecks ()
		{
			for (int i = 0; i < _pending_isinst_instr.Count; ++i) {
				var item = _pending_isinst_instr[i];
				TypeDefinition type = item.Type;
				if (Annotations.IsInstantiated (type))
					continue;

				Instruction instr = item.Instr;
				LinkerILProcessor ilProcessor = item.Body.GetLinkerILProcessor ();

				ilProcessor.InsertAfter (instr, Instruction.Create (OpCodes.Ldnull));
				Instruction new_instr = Instruction.Create (OpCodes.Pop);
				ilProcessor.Replace (instr, new_instr);

				Context.LogMessage ($"Removing typecheck of '{type.FullName}' inside '{item.Body.Method.GetDisplayName ()}' method.");
			}
		}

		void ProcessQueue ()
		{
			while (!QueueIsEmpty ()) {
				(MethodDefinition method, DependencyInfo reason, MessageOrigin origin) = _methods.Dequeue ();
				ProcessMethod (method, reason, origin);
			}
		}

		bool QueueIsEmpty ()
		{
			return _methods.Count == 0;
		}

		protected virtual void EnqueueMethod (MethodDefinition method, in DependencyInfo reason, in MessageOrigin origin)
		{
			_methods.Enqueue ((method, reason, origin));
		}

		void ProcessVirtualMethods ()
		{
			foreach ((MethodDefinition method, MarkScopeStack.Scope scope) in _virtual_methods) {
				using (ScopeStack.PushScope (scope))
					ProcessVirtualMethod (method);
			}
		}

		/// <summary>
		/// Handles marking of interface implementations, and the marking of methods that implement interfaces
		/// once the linker knows whether a type is instantiated or relevant to variant casting,
		/// and after interfaces and interface methods have been marked.
		/// </summary>
		void ProcessMarkedTypesWithInterfaces ()
		{
			// We may mark an interface type later on.  Which means we need to reprocess any time with one or more interface implementations that have not been marked
			// and if an interface type is found to be marked and implementation is not marked, then we need to mark that implementation

			// copy the data to avoid modified while enumerating error potential, which can happen under certain conditions.
			var typesWithInterfaces = _typesWithInterfaces.ToArray ();

			foreach ((var type, var scope) in typesWithInterfaces) {
				// Exception, types that have not been flagged as instantiated yet.  These types may not need their interfaces even if the
				// interface type is marked
				// UnusedInterfaces optimization is turned off mark all interface implementations
				bool unusedInterfacesOptimizationEnabled = Context.IsOptimizationEnabled (CodeOptimizations.UnusedInterfaces, type);

				using (ScopeStack.PushScope (scope)) {
					if (Annotations.IsInstantiated (type) || Annotations.IsRelevantToVariantCasting (type) ||
						!unusedInterfacesOptimizationEnabled) {
						MarkInterfaceImplementations (type);
					}
					// OverrideInformation for interfaces in PreservedScope aren't added yet
					foreach (var method in type.Methods) {
						var baseOverrideInformations = Annotations.GetBaseMethods (method);
						if (baseOverrideInformations is null)
							continue;
						foreach (var ov in baseOverrideInformations) {
							if (ov.Base.DeclaringType is not null && ov.Base.DeclaringType.IsInterface && IgnoreScope (ov.Base.DeclaringType.Scope))
								_interfaceOverrides.Add ((ov, ScopeStack.CurrentScope));
						}
					}
				}
			}

			var interfaceOverrides = _interfaceOverrides.ToArray ();
			foreach ((var overrideInformation, var scope) in interfaceOverrides) {
				using (ScopeStack.PushScope (scope)) {
					if (IsInterfaceImplementationMethodNeededByTypeDueToInterface (overrideInformation))
						MarkMethod (overrideInformation.Override, new DependencyInfo (DependencyKind.Override, overrideInformation.Base), scope.Origin);
				}
			}
		}

		void DiscoverDynamicCastableImplementationInterfaces ()
		{
			// We could potentially avoid loading all references here: https://github.com/dotnet/linker/issues/1788
			foreach (var assembly in Context.GetReferencedAssemblies ().ToArray ()) {
				switch (Annotations.GetAction (assembly)) {
				// We only need to search assemblies where we don't mark everything
				// Assemblies that are fully marked already mark these types.
				case AssemblyAction.Link:
				case AssemblyAction.AddBypassNGen:
				case AssemblyAction.AddBypassNGenUsed:
					if (!_dynamicInterfaceCastableImplementationTypesDiscovered.Add (assembly))
						continue;

					foreach (TypeDefinition type in assembly.MainModule.Types)
						CheckIfTypeOrNestedTypesIsDynamicCastableImplementation (type);

					break;
				}
			}

			void CheckIfTypeOrNestedTypesIsDynamicCastableImplementation (TypeDefinition type)
			{
				if (!Annotations.IsMarked (type) && TypeIsDynamicInterfaceCastableImplementation (type))
					_dynamicInterfaceCastableImplementationTypes.Add (type);

				if (type.HasNestedTypes) {
					foreach (var nestedType in type.NestedTypes)
						CheckIfTypeOrNestedTypesIsDynamicCastableImplementation (nestedType);
				}
			}
		}

		void ProcessDynamicCastableImplementationInterfaces ()
		{
			DiscoverDynamicCastableImplementationInterfaces ();

			// We may mark an interface type later on.  Which means we need to reprocess any time with one or more interface implementations that have not been marked
			// and if an interface type is found to be marked and implementation is not marked, then we need to mark that implementation

			for (int i = 0; i < _dynamicInterfaceCastableImplementationTypes.Count; i++) {
				var type = _dynamicInterfaceCastableImplementationTypes[i];

				Debug.Assert (TypeIsDynamicInterfaceCastableImplementation (type));

				// If the type has already been marked, we can remove it from this list.
				if (Annotations.IsMarked (type)) {
					_dynamicInterfaceCastableImplementationTypes.RemoveAt (i--);
					continue;
				}

				foreach (var iface in type.Interfaces) {
					if (Annotations.IsMarked (iface.InterfaceType)) {
						// We only need to mark the type definition because the linker will ensure that all marked implemented interfaces and used method implementations
						// will be marked on this type as well.
						MarkType (type, new DependencyInfo (DependencyKind.DynamicInterfaceCastableImplementation, iface.InterfaceType), new MessageOrigin (Context.TryResolve (iface.InterfaceType)));

						_dynamicInterfaceCastableImplementationTypes.RemoveAt (i--);
						break;
					}
				}
			}
		}

		void ProcessPendingBodies ()
		{
			for (int i = 0; i < _unreachableBodies.Count; i++) {
				(var body, var scope) = _unreachableBodies[i];
				if (Annotations.IsInstantiated (body.Method.DeclaringType)) {
					using (ScopeStack.PushScope (scope))
						MarkMethodBody (body);

					_unreachableBodies.RemoveAt (i--);
				}
			}
		}

		void ProcessVirtualMethod (MethodDefinition method)
		{
			Annotations.EnqueueVirtualMethod (method);

			var defaultImplementations = Annotations.GetDefaultInterfaceImplementations (method);
			if (defaultImplementations != null) {
				foreach (var defaultImplementationInfo in defaultImplementations) {
					ProcessDefaultImplementation (defaultImplementationInfo.InstanceType, defaultImplementationInfo.ProvidingInterface);
				}
			}
		}

		/// <summary>
		/// Returns true if the Override in <paramref name="overrideInformation"/> should be marked because it is needed by the base method.
		/// Does not take into account if the base method is in a preserved scope.
		/// Assumes the base method is marked.
		/// </summary>
		// TODO: Move interface method marking logic here https://github.com/dotnet/linker/issues/3090
		bool ShouldMarkOverrideForBase (OverrideInformation overrideInformation)
		{
			if (overrideInformation.IsOverrideOfInterfaceMember) {
				_interfaceOverrides.Add ((overrideInformation, ScopeStack.CurrentScope));
				return false;
			}

			if (!Context.IsOptimizationEnabled (CodeOptimizations.OverrideRemoval, overrideInformation.Override))
				return true;

			// Methods on instantiated types that override a ov.Override from a base type (not an interface) should be marked
			// Interface ov.Overrides should only be marked if the interfaceImplementation is marked, which is handled below
			if (Annotations.IsInstantiated (overrideInformation.Override.DeclaringType))
				return true;

			// Direct overrides of marked abstract ov.Overrides must be marked or we get invalid IL.
			// Overrides further in the hierarchy will override the direct override (which will be implemented by the above rule), so we don't need to worry about invalid IL.
			if (overrideInformation.Base.IsAbstract)
				return true;

			return false;
		}

		/// <summary>
		/// Marks the Override of <paramref name="overrideInformation"/> with the correct reason. Should be called when <see cref="ShouldMarkOverrideForBase(OverrideInformation, bool)"/> returns true.
		/// </summary>
		// TODO: Take into account a base method in preserved scope
		void MarkOverrideForBaseMethod (OverrideInformation overrideInformation)
		{
			if (Context.IsOptimizationEnabled (CodeOptimizations.OverrideRemoval, overrideInformation.Override) && Annotations.IsInstantiated (overrideInformation.Override.DeclaringType)) {
				MarkMethod (overrideInformation.Override, new DependencyInfo (DependencyKind.OverrideOnInstantiatedType, overrideInformation.Override.DeclaringType), ScopeStack.CurrentScope.Origin);
			} else {
				// If the optimization is disabled or it's an abstract type, we just mark it as a normal override.
				Debug.Assert (!Context.IsOptimizationEnabled (CodeOptimizations.OverrideRemoval, overrideInformation.Override) || overrideInformation.Base.IsAbstract);
				MarkMethod (overrideInformation.Override, new DependencyInfo (DependencyKind.Override, overrideInformation.Base), ScopeStack.CurrentScope.Origin);
			}
		}

		void MarkMethodIfNeededByBaseMethod (MethodDefinition method)
		{
			Debug.Assert (Annotations.IsMarked (method.DeclaringType));

			var bases = Annotations.GetBaseMethods (method);
			if (bases is null)
				return;

			var markedBaseMethods = bases.Where (ov => Annotations.IsMarked (ov.Base) || IgnoreScope (ov.Base.DeclaringType.Scope));
			foreach (var ov in markedBaseMethods) {
				if (ShouldMarkOverrideForBase (ov))
					MarkOverrideForBaseMethod (ov);
			}
		}

		/// <summary>
		/// Returns true if <paramref name="type"/> implements <paramref name="interfaceType"/> and the interface implementation is marked,
		/// or if any marked interface implementations on <paramref name="type"/> are interfaces that implement <paramref name="interfaceType"/> and that interface implementation is marked
		/// </summary>
		bool IsInterfaceImplementationMarkedRecursively (TypeDefinition type, TypeDefinition interfaceType)
		{
			if (type.HasInterfaces) {
				foreach (var intf in type.Interfaces) {
					TypeDefinition? resolvedInterface = Context.Resolve (intf.InterfaceType);
					if (resolvedInterface == null)
						continue;

					if (Annotations.IsMarked (intf) && RequiresInterfaceRecursively (resolvedInterface, interfaceType))
						return true;
				}
			}

			return false;
		}

		bool RequiresInterfaceRecursively (TypeDefinition typeToExamine, TypeDefinition interfaceType)
		{
			if (typeToExamine == interfaceType)
				return true;

			if (typeToExamine.HasInterfaces) {
				foreach (var iface in typeToExamine.Interfaces) {
					var resolved = Context.TryResolve (iface.InterfaceType);
					if (resolved == null)
						continue;

					if (RequiresInterfaceRecursively (resolved, interfaceType))
						return true;
				}
			}

			return false;
		}

		void ProcessDefaultImplementation (TypeDefinition typeWithDefaultImplementedInterfaceMethod, InterfaceImplementation implementation)
		{
			if (!Annotations.IsInstantiated (typeWithDefaultImplementedInterfaceMethod))
				return;

			MarkInterfaceImplementation (implementation);
		}

		void MarkMarshalSpec (IMarshalInfoProvider spec, in DependencyInfo reason)
		{
			if (!spec.HasMarshalInfo)
				return;

			if (spec.MarshalInfo is CustomMarshalInfo marshaler) {
				MarkType (marshaler.ManagedType, reason);
				TypeDefinition? type = Context.Resolve (marshaler.ManagedType);
				if (type != null) {
					MarkICustomMarshalerMethods (type, in reason);
					MarkCustomMarshalerGetInstance (type, in reason);
				}
			}
		}

		void MarkCustomAttributes (ICustomAttributeProvider provider, in DependencyInfo reason)
		{
			if (provider.HasCustomAttributes) {
				bool providerInLinkedAssembly = Annotations.GetAction (CustomAttributeSource.GetAssemblyFromCustomAttributeProvider (provider)) == AssemblyAction.Link;
				bool markOnUse = Context.KeepUsedAttributeTypesOnly && providerInLinkedAssembly;

				foreach (CustomAttribute ca in provider.CustomAttributes) {
					if (ProcessLinkerSpecialAttribute (ca, provider, reason))
						continue;

					if (markOnUse) {
						_lateMarkedAttributes.Enqueue ((new AttributeProviderPair (ca, provider), reason, ScopeStack.CurrentScope));
						continue;
					}

					var resolvedAttributeType = Context.Resolve (ca.AttributeType);
					if (resolvedAttributeType == null) {
						continue;
					}

					if (providerInLinkedAssembly && IsAttributeRemoved (ca, resolvedAttributeType))
						continue;

					MarkCustomAttribute (ca, reason);
				}
			}

			if (!(provider is MethodDefinition || provider is FieldDefinition))
				return;

			IMemberDefinition providerMember = (IMemberDefinition) provider; ;
			using (ScopeStack.PushScope (new MessageOrigin (providerMember)))
				foreach (var dynamicDependency in Annotations.GetLinkerAttributes<DynamicDependency> (providerMember))
					MarkDynamicDependency (dynamicDependency, providerMember);
		}

		bool IsAttributeRemoved (CustomAttribute ca, TypeDefinition attributeType)
		{
			foreach (var attr in Annotations.GetLinkerAttributes<RemoveAttributeInstancesAttribute> (attributeType)) {
				var args = attr.Arguments;
				if (args.Length == 0)
					return true;

				if (args.Length > ca.ConstructorArguments.Count)
					continue;

				if (HasMatchingArguments (args, ca.ConstructorArguments))
					return true;
			}

			return false;

			static bool HasMatchingArguments (CustomAttributeArgument[] removeAttrInstancesArgs, Collection<CustomAttributeArgument> attributeInstanceArgs)
			{
				for (int i = 0; i < removeAttrInstancesArgs.Length; ++i) {
					if (!removeAttrInstancesArgs[i].IsEqualTo (attributeInstanceArgs[i]))
						return false;
				}
				return true;
			}
		}

		protected virtual bool ProcessLinkerSpecialAttribute (CustomAttribute ca, ICustomAttributeProvider provider, in DependencyInfo reason)
		{
			var isPreserveDependency = IsUserDependencyMarker (ca.AttributeType);
			var isDynamicDependency = ca.AttributeType.IsTypeOf<DynamicDependencyAttribute> ();

			if (!((isPreserveDependency || isDynamicDependency) && provider is IMemberDefinition member))
				return false;

			if (isPreserveDependency)
				MarkUserDependency (member, ca);

			if (Context.CanApplyOptimization (CodeOptimizations.RemoveDynamicDependencyAttribute, member.DeclaringType.Module.Assembly)) {
				// Record the custom attribute so that it has a reason, without actually marking it.
				Tracer.AddDirectDependency (ca, reason, marked: false);
			} else {
				MarkCustomAttribute (ca, reason);
			}

			return true;
		}

		void MarkDynamicDependency (DynamicDependency dynamicDependency, IMemberDefinition context)
		{
			Debug.Assert (context is MethodDefinition || context is FieldDefinition);
			AssemblyDefinition? assembly;
			if (dynamicDependency.AssemblyName != null) {
				assembly = Context.TryResolve (dynamicDependency.AssemblyName);
				if (assembly == null) {
					Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.UnresolvedAssemblyInDynamicDependencyAttribute, dynamicDependency.AssemblyName);
					return;
				}
			} else {
				assembly = context.DeclaringType.Module.Assembly;
				Debug.Assert (assembly != null);
			}

			TypeDefinition? type;
			if (dynamicDependency.TypeName is string typeName) {
				type = DocumentationSignatureParser.GetTypeByDocumentationSignature (assembly, typeName, Context);
				if (type == null) {
					Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, typeName);
					return;
				}

				MarkingHelpers.MarkMatchingExportedType (type, assembly, new DependencyInfo (DependencyKind.DynamicDependency, type), ScopeStack.CurrentScope.Origin);
			} else if (dynamicDependency.Type is TypeReference typeReference) {
				type = Context.TryResolve (typeReference);
				if (type == null) {
					Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, typeReference.GetDisplayName ());
					return;
				}
			} else {
				type = Context.TryResolve (context.DeclaringType);
				if (type == null) {
					Context.LogWarning (context, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, context.DeclaringType.GetDisplayName ());
					return;
				}
			}

			IEnumerable<IMetadataTokenProvider> members;
			if (dynamicDependency.MemberSignature is string memberSignature) {
				members = DocumentationSignatureParser.GetMembersByDocumentationSignature (type, memberSignature, Context, acceptName: true);
				if (!members.Any ()) {
					Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.NoMembersResolvedForMemberSignatureOrType, memberSignature, type.GetDisplayName ());
					return;
				}
			} else {
				var memberTypes = dynamicDependency.MemberTypes;
				members = type.GetDynamicallyAccessedMembers (Context, memberTypes);
				if (!members.Any ()) {
					Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.NoMembersResolvedForMemberSignatureOrType, memberTypes.ToString (), type.GetDisplayName ());
					return;
				}
			}

			MarkMembersVisibleToReflection (members, new DependencyInfo (DependencyKind.DynamicDependency, context));
		}

		void MarkMembersVisibleToReflection (IEnumerable<IMetadataTokenProvider> members, in DependencyInfo reason)
		{
			foreach (var member in members) {
				switch (member) {
				case TypeDefinition type:
					MarkTypeVisibleToReflection (type, type, reason, ScopeStack.CurrentScope.Origin);
					break;
				case MethodDefinition method:
					MarkMethodVisibleToReflection (method, reason, ScopeStack.CurrentScope.Origin);
					break;
				case FieldDefinition field:
					MarkFieldVisibleToReflection (field, reason, ScopeStack.CurrentScope.Origin);
					break;
				case PropertyDefinition property:
					MarkPropertyVisibleToReflection (property, reason, ScopeStack.CurrentScope.Origin);
					break;
				case EventDefinition @event:
					MarkEventVisibleToReflection (@event, reason, ScopeStack.CurrentScope.Origin);
					break;
				case InterfaceImplementation interfaceType:
					MarkInterfaceImplementation (interfaceType, null, reason);
					break;
				}
			}
		}

		protected virtual bool IsUserDependencyMarker (TypeReference type)
		{
			return type.Name == "PreserveDependencyAttribute" && type.Namespace == "System.Runtime.CompilerServices";
		}

		protected virtual void MarkUserDependency (IMemberDefinition context, CustomAttribute ca)
		{
			Context.LogWarning (context, DiagnosticId.DeprecatedPreserveDependencyAttribute);

			if (!DynamicDependency.ShouldProcess (Context, ca))
				return;

			AssemblyDefinition? assembly;
			var args = ca.ConstructorArguments;
			if (args.Count >= 3 && args[2].Value is string assemblyName) {
				assembly = Context.TryResolve (assemblyName);
				if (assembly == null) {
					Context.LogWarning (context, DiagnosticId.CouldNotResolveDependencyAssembly, assemblyName);
					return;
				}
			} else {
				assembly = null;
			}

			TypeDefinition? td;
			if (args.Count >= 2 && args[1].Value is string typeName) {
				AssemblyDefinition assemblyDef = assembly ?? ((MemberReference) context).Module.Assembly;
				td = Context.TryResolve (assemblyDef, typeName);

				if (td == null) {
					Context.LogWarning (context, DiagnosticId.CouldNotResolveDependencyType, typeName);
					return;
				}

				MarkingHelpers.MarkMatchingExportedType (td, assemblyDef, new DependencyInfo (DependencyKind.PreservedDependency, ca), ScopeStack.CurrentScope.Origin);
			} else {
				td = context.DeclaringType;
			}

			string? member = null;
			string[]? signature = null;
			if (args.Count >= 1 && args[0].Value is string memberSignature) {
				memberSignature = memberSignature.Replace (" ", "");
				var sign_start = memberSignature.IndexOf ('(');
				var sign_end = memberSignature.LastIndexOf (')');
				if (sign_start > 0 && sign_end > sign_start) {
					var parameters = memberSignature.Substring (sign_start + 1, sign_end - sign_start - 1);
					signature = string.IsNullOrEmpty (parameters) ? Array.Empty<string> () : parameters.Split (',');
					member = memberSignature.Substring (0, sign_start);
				} else {
					member = memberSignature;
				}
			}

			if (member == "*") {
				MarkEntireType (td, new DependencyInfo (DependencyKind.PreservedDependency, ca));
				return;
			}

			if (member != null) {
				if (MarkDependencyMethod (td, member, signature, new DependencyInfo (DependencyKind.PreservedDependency, ca)))
					return;

				if (MarkNamedField (td, member, new DependencyInfo (DependencyKind.PreservedDependency, ca)))
					return;
			}

			Context.LogWarning (context, DiagnosticId.CouldNotResolveDependencyMember, member ?? "", td.GetDisplayName ());
		}

		bool MarkDependencyMethod (TypeDefinition type, string name, string[]? signature, in DependencyInfo reason)
		{
			bool marked = false;

			int arity_marker = name.IndexOf ('`');
			if (arity_marker < 1 || !int.TryParse (name.AsSpan (arity_marker + 1), out int arity)) {
				arity = 0;
			} else {
				name = name.Substring (0, arity_marker);
			}

			foreach (var m in type.Methods) {
				if (m.Name != name)
					continue;

				if (m.GenericParameters.Count != arity)
					continue;

				if (signature == null) {
					MarkIndirectlyCalledMethod (m, reason, ScopeStack.CurrentScope.Origin);
					marked = true;
					continue;
				}

				if (m.GetMetadataParametersCount () != signature.Length)
					continue;

				bool matched = true;
				foreach (var p in m.GetMetadataParameters ()) {
					if (p.ParameterType.FullName != signature[p.MetadataIndex].Trim ().ToCecilName ()) {
						matched = false;
						break;
					}
				}

				if (!matched)
					continue;

				MarkIndirectlyCalledMethod (m, reason, ScopeStack.CurrentScope.Origin);
				marked = true;
			}

			return marked;
		}

		void LazyMarkCustomAttributes (ICustomAttributeProvider provider)
		{
			Debug.Assert (provider is ModuleDefinition or AssemblyDefinition);
			if (!provider.HasCustomAttributes)
				return;

			foreach (CustomAttribute ca in provider.CustomAttributes) {
				_assemblyLevelAttributes.Enqueue (new AttributeProviderPair (ca, provider));
			}
		}

		protected virtual void MarkCustomAttribute (CustomAttribute ca, in DependencyInfo reason)
		{
			Annotations.Mark (ca, reason);
			MarkMethod (ca.Constructor, new DependencyInfo (DependencyKind.AttributeConstructor, ca), ScopeStack.CurrentScope.Origin);

			MarkCustomAttributeArguments (ca);

			TypeReference constructor_type = ca.Constructor.DeclaringType;
			TypeDefinition? type = Context.Resolve (constructor_type);

			if (type == null) {
				return;
			}

			MarkCustomAttributeProperties (ca, type);
			MarkCustomAttributeFields (ca, type);
		}

		protected virtual bool ShouldMarkCustomAttribute (CustomAttribute ca, ICustomAttributeProvider provider)
		{
			var attr_type = ca.AttributeType;

			if (Context.KeepUsedAttributeTypesOnly) {
				switch (attr_type.FullName) {
				// These are required by the runtime
				case "System.ThreadStaticAttribute":
				case "System.ContextStaticAttribute":
				case "System.Runtime.CompilerServices.IsByRefLikeAttribute":
					return true;
				// Attributes related to `fixed` keyword used to declare fixed length arrays
				case "System.Runtime.CompilerServices.FixedBufferAttribute":
					return true;
				case "System.Runtime.InteropServices.InterfaceTypeAttribute":
				case "System.Runtime.InteropServices.GuidAttribute":
					return true;
				}

				TypeDefinition? type = Context.Resolve (attr_type);
				if (type is null || !Annotations.IsMarked (type))
					return false;
			}

			return true;
		}

		protected virtual bool ShouldMarkTypeStaticConstructor (TypeDefinition type)
		{
			if (Annotations.HasPreservedStaticCtor (type))
				return false;

			if (type.IsBeforeFieldInit && Context.IsOptimizationEnabled (CodeOptimizations.BeforeFieldInit, type))
				return false;

			return true;
		}

		protected internal void MarkStaticConstructor (TypeDefinition type, in DependencyInfo reason, in MessageOrigin origin)
		{
			if (MarkMethodIf (type.Methods, IsNonEmptyStaticConstructor, reason, origin) != null)
				Annotations.SetPreservedStaticCtor (type);
		}

		protected virtual bool ShouldMarkTopLevelCustomAttribute (AttributeProviderPair app, MethodDefinition resolvedConstructor)
		{
			var ca = app.Attribute;

			if (!ShouldMarkCustomAttribute (app.Attribute, app.Provider))
				return false;

			// If an attribute's module has not been marked after processing all types in all assemblies and the attribute itself has not been marked,
			// then surely nothing is using this attribute and there is no need to mark it
			if (!Annotations.IsMarked (resolvedConstructor.Module) &&
				!Annotations.IsMarked (ca.AttributeType) &&
				Annotations.GetAction (resolvedConstructor.Module.Assembly) == AssemblyAction.Link)
				return false;

			if (ca.Constructor.DeclaringType.Namespace == "System.Diagnostics") {
				string attributeName = ca.Constructor.DeclaringType.Name;
				if (attributeName == "DebuggerDisplayAttribute" || attributeName == "DebuggerTypeProxyAttribute") {
					var displayTargetType = GetDebuggerAttributeTargetType (app.Attribute, (AssemblyDefinition) app.Provider);
					if (displayTargetType == null || !Annotations.IsMarked (displayTargetType))
						return false;
				}
			}

			return true;
		}

		protected void MarkSecurityDeclarations (ISecurityDeclarationProvider provider, in DependencyInfo reason)
		{
			// most security declarations are removed (if linked) but user code might still have some
			// and if the attributes references types then they need to be marked too
			if ((provider == null) || !provider.HasSecurityDeclarations)
				return;

			foreach (var sd in provider.SecurityDeclarations)
				MarkSecurityDeclaration (sd, reason);
		}

		protected virtual void MarkSecurityDeclaration (SecurityDeclaration sd, in DependencyInfo reason)
		{
			if (!sd.HasSecurityAttributes)
				return;

			foreach (var sa in sd.SecurityAttributes)
				MarkSecurityAttribute (sa, reason);
		}

		protected virtual void MarkSecurityAttribute (SecurityAttribute sa, in DependencyInfo reason)
		{
			TypeReference security_type = sa.AttributeType;
			TypeDefinition? type = Context.Resolve (security_type);
			if (type == null) {
				return;
			}

			// Security attributes participate in inference logic without being marked.
			Tracer.AddDirectDependency (sa, reason, marked: false);
			MarkType (security_type, new DependencyInfo (DependencyKind.AttributeType, sa));
			MarkCustomAttributeProperties (sa, type);
			MarkCustomAttributeFields (sa, type);
		}

		protected void MarkCustomAttributeProperties (ICustomAttribute ca, TypeDefinition attribute)
		{
			if (!ca.HasProperties)
				return;

			foreach (var named_argument in ca.Properties)
				MarkCustomAttributeProperty (named_argument, attribute, ca, new DependencyInfo (DependencyKind.AttributeProperty, ca));
		}

		protected void MarkCustomAttributeProperty (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute, ICustomAttribute ca, in DependencyInfo reason)
		{
			PropertyDefinition? property = GetProperty (attribute, namedArgument.Name);
			if (property != null)
				MarkMethod (property.SetMethod, reason, ScopeStack.CurrentScope.Origin);

			MarkCustomAttributeArgument (namedArgument.Argument, ca);

			if (property != null && Annotations.FlowAnnotations.RequiresDataFlowAnalysis (property.SetMethod)) {
				var scanner = new AttributeDataFlow (Context, this, ScopeStack.CurrentScope.Origin);
				scanner.ProcessAttributeDataflow (property.SetMethod, new List<CustomAttributeArgument> { namedArgument.Argument });
			}
		}

		PropertyDefinition? GetProperty (TypeDefinition inputType, string propertyname)
		{
			TypeDefinition? type = inputType;
			while (type != null) {
				PropertyDefinition? property = type.Properties.FirstOrDefault (p => p.Name == propertyname);
				if (property != null)
					return property;

				type = Context.TryResolve (type.BaseType);
			}

			return null;
		}

		protected void MarkCustomAttributeFields (ICustomAttribute ca, TypeDefinition attribute)
		{
			if (!ca.HasFields)
				return;

			foreach (var named_argument in ca.Fields)
				MarkCustomAttributeField (named_argument, attribute, ca);
		}

		protected void MarkCustomAttributeField (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute, ICustomAttribute ca)
		{
			FieldDefinition? field = GetField (attribute, namedArgument.Name);
			if (field != null)
				MarkField (field, new DependencyInfo (DependencyKind.CustomAttributeField, ca), ScopeStack.CurrentScope.Origin);

			MarkCustomAttributeArgument (namedArgument.Argument, ca);

			if (field != null && Annotations.FlowAnnotations.RequiresDataFlowAnalysis (field)) {
				var scanner = new AttributeDataFlow (Context, this, ScopeStack.CurrentScope.Origin);
				scanner.ProcessAttributeDataflow (field, namedArgument.Argument);
			}
		}

		FieldDefinition? GetField (TypeDefinition inputType, string fieldname)
		{
			TypeDefinition? type = inputType;
			while (type != null) {
				FieldDefinition? field = type.Fields.FirstOrDefault (f => f.Name == fieldname);
				if (field != null)
					return field;

				type = Context.TryResolve (type.BaseType);
			}

			return null;
		}

		MethodDefinition? GetMethodWithNoParameters (TypeDefinition inputType, string methodname)
		{
			TypeDefinition? type = inputType;
			while (type != null) {
				MethodDefinition? method = type.Methods.FirstOrDefault (m => m.Name == methodname && !m.HasMetadataParameters ());
				if (method != null)
					return method;

				type = Context.TryResolve (type.BaseType);
			}

			return null;
		}

		void MarkCustomAttributeArguments (CustomAttribute ca)
		{
			if (!ca.HasConstructorArguments)
				return;

			foreach (var argument in ca.ConstructorArguments)
				MarkCustomAttributeArgument (argument, ca);

			var resolvedConstructor = Context.TryResolve (ca.Constructor);
			if (resolvedConstructor != null && Annotations.FlowAnnotations.RequiresDataFlowAnalysis (resolvedConstructor)) {
				var scanner = new AttributeDataFlow (Context, this, ScopeStack.CurrentScope.Origin);
				scanner.ProcessAttributeDataflow (resolvedConstructor, ca.ConstructorArguments);
			}
		}

		void MarkCustomAttributeArgument (CustomAttributeArgument argument, ICustomAttribute ca)
		{
			var at = argument.Type;

			if (at.IsArray) {
				var et = at.GetElementType ();

				MarkType (et, new DependencyInfo (DependencyKind.CustomAttributeArgumentType, ca));
				if (argument.Value == null)
					return;

				// Array arguments are modeled as a CustomAttributeArgument [], and will mark the
				// Type once for each element in the array.
				foreach (var caa in (CustomAttributeArgument[]) argument.Value)
					MarkCustomAttributeArgument (caa, ca);

				return;
			}

			if (at.Namespace == "System") {
				switch (at.Name) {
				case "Type":
					MarkType (argument.Type, new DependencyInfo (DependencyKind.CustomAttributeArgumentType, ca));
					MarkType ((TypeReference) argument.Value, new DependencyInfo (DependencyKind.CustomAttributeArgumentValue, ca));
					return;

				case "Object":
					var boxed_value = (CustomAttributeArgument) argument.Value;
					MarkType (boxed_value.Type, new DependencyInfo (DependencyKind.CustomAttributeArgumentType, ca));
					MarkCustomAttributeArgument (boxed_value, ca);
					return;
				}
			}
		}

		protected bool CheckProcessed (IMetadataTokenProvider provider)
		{
			return !Annotations.SetProcessed (provider);
		}

		protected void MarkAssembly (AssemblyDefinition assembly, DependencyInfo reason)
		{
			Annotations.Mark (assembly, reason, ScopeStack.CurrentScope.Origin);
			if (CheckProcessed (assembly))
				return;

			using var assemblyScope = ScopeStack.PushScope (new MessageOrigin (assembly));

			EmbeddedXmlInfo.ProcessDescriptors (assembly, Context);

			foreach (Action<AssemblyDefinition> handleMarkAssembly in MarkContext.MarkAssemblyActions)
				handleMarkAssembly (assembly);

			// Security attributes do not respect the attributes XML
			if (Context.StripSecurity)
				RemoveSecurity.ProcessAssembly (assembly, Context);

			MarkExportedTypesTarget.ProcessAssembly (assembly, Context);

			if (ProcessReferencesStep.IsFullyPreservedAction (Annotations.GetAction (assembly))) {
				if (!Context.TryGetCustomData ("DisableMarkingOfCopyAssemblies", out string? disableMarkingOfCopyAssembliesValue) ||
					disableMarkingOfCopyAssembliesValue != "true")
					MarkEntireAssembly (assembly);
				return;
			}

			ProcessModuleType (assembly);

			LazyMarkCustomAttributes (assembly);

			MarkSecurityDeclarations (assembly, new DependencyInfo (DependencyKind.AssemblyOrModuleAttribute, assembly));

			foreach (ModuleDefinition module in assembly.Modules)
				LazyMarkCustomAttributes (module);
		}

		void MarkEntireAssembly (AssemblyDefinition assembly)
		{
			Debug.Assert (Annotations.IsProcessed (assembly));

			ModuleDefinition module = assembly.MainModule;

			MarkCustomAttributes (assembly, new DependencyInfo (DependencyKind.AssemblyOrModuleAttribute, assembly));
			MarkCustomAttributes (module, new DependencyInfo (DependencyKind.AssemblyOrModuleAttribute, module));

			foreach (TypeDefinition type in module.Types)
				MarkEntireType (type, new DependencyInfo (DependencyKind.TypeInAssembly, assembly));

			// Mark scopes of type references and exported types.
			TypeReferenceMarker.MarkTypeReferences (assembly, MarkingHelpers);
		}

		sealed class TypeReferenceMarker : TypeReferenceWalker
		{

			readonly MarkingHelpers markingHelpers;

			TypeReferenceMarker (AssemblyDefinition assembly, MarkingHelpers markingHelpers)
				: base (assembly)
			{
				this.markingHelpers = markingHelpers;
			}

			public static void MarkTypeReferences (AssemblyDefinition assembly, MarkingHelpers markingHelpers)
			{
				new TypeReferenceMarker (assembly, markingHelpers).Process ();
			}

			protected override void ProcessTypeReference (TypeReference type)
			{
				markingHelpers.MarkForwardedScope (type, new MessageOrigin (assembly));
			}

			protected override void ProcessExportedType (ExportedType exportedType)
			{
				markingHelpers.MarkExportedType (exportedType, assembly.MainModule, new DependencyInfo (DependencyKind.ExportedType, assembly), new MessageOrigin (assembly));
				markingHelpers.MarkForwardedScope (CreateTypeReferenceForExportedTypeTarget (exportedType), new MessageOrigin (assembly));
			}

			protected override void ProcessExtra ()
			{
				// Also mark the scopes of metadata typeref rows to cover any not discovered by the traversal.
				// This can happen when the compiler emits typerefs into IL which aren't strictly necessary per ECMA 335.
				foreach (TypeReference typeReference in assembly.MainModule.GetTypeReferences ()) {
					if (!Visited!.Add (typeReference))
						continue;
					markingHelpers.MarkForwardedScope (typeReference, new MessageOrigin (assembly));
				}
			}

			TypeReference CreateTypeReferenceForExportedTypeTarget (ExportedType exportedType)
			{
				TypeReference? declaringTypeReference = null;
				if (exportedType.DeclaringType != null) {
					declaringTypeReference = CreateTypeReferenceForExportedTypeTarget (exportedType.DeclaringType);
				}

				return new TypeReference (exportedType.Namespace, exportedType.Name, assembly.MainModule, exportedType.Scope) {
					DeclaringType = declaringTypeReference
				};
			}
		}

		void ProcessModuleType (AssemblyDefinition assembly)
		{
			// The <Module> type may have an initializer, in which case we want to keep it.
			TypeDefinition? moduleType = assembly.MainModule.Types.FirstOrDefault (t => t.MetadataToken.RID == 1);
			if (moduleType != null && moduleType.HasMethods)
				MarkType (moduleType, new DependencyInfo (DependencyKind.TypeInAssembly, assembly));
		}

		bool ProcessLazyAttributes ()
		{
			if (Annotations.HasMarkedAnyIndirectlyCalledMethods () && MarkDisablePrivateReflectionAttribute ())
				return true;

			var startingQueueCount = _assemblyLevelAttributes.Count;
			if (startingQueueCount == 0)
				return false;

			var skippedItems = new List<AttributeProviderPair> ();
			var markOccurred = false;

			while (_assemblyLevelAttributes.Count != 0) {
				var assemblyLevelAttribute = _assemblyLevelAttributes.Dequeue ();
				var customAttribute = assemblyLevelAttribute.Attribute;

				var provider = assemblyLevelAttribute.Provider;
				Debug.Assert (provider is ModuleDefinition or AssemblyDefinition);
				var assembly = (provider is ModuleDefinition module) ? module.Assembly : provider as AssemblyDefinition;

				using var assemblyScope = ScopeStack.PushScope (new MessageOrigin (assembly));

				var resolved = Context.Resolve (customAttribute.Constructor);
				if (resolved == null) {
					continue;
				}

				if (IsAttributeRemoved (customAttribute, resolved.DeclaringType) && Annotations.GetAction (CustomAttributeSource.GetAssemblyFromCustomAttributeProvider (assemblyLevelAttribute.Provider)) == AssemblyAction.Link)
					continue;

				if (customAttribute.AttributeType.IsTypeOf ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute") && !Annotations.IsMarked (customAttribute)) {
					_ivt_attributes.Add (assemblyLevelAttribute);
					continue;
				} else if (!ShouldMarkTopLevelCustomAttribute (assemblyLevelAttribute, resolved)) {
					skippedItems.Add (assemblyLevelAttribute);
					continue;
				}

				markOccurred = true;
				MarkCustomAttribute (customAttribute, new DependencyInfo (DependencyKind.AssemblyOrModuleAttribute, assemblyLevelAttribute.Provider));

				string attributeFullName = customAttribute.Constructor.DeclaringType.FullName;
				switch (attributeFullName) {
				case "System.Diagnostics.DebuggerDisplayAttribute": {
						TypeDefinition? targetType = GetDebuggerAttributeTargetType (assemblyLevelAttribute.Attribute, (AssemblyDefinition) assemblyLevelAttribute.Provider);
						if (targetType != null)
							MarkTypeWithDebuggerDisplayAttribute (targetType, customAttribute);
						break;
					}
				case "System.Diagnostics.DebuggerTypeProxyAttribute": {
						TypeDefinition? targetType = GetDebuggerAttributeTargetType (assemblyLevelAttribute.Attribute, (AssemblyDefinition) assemblyLevelAttribute.Provider);
						if (targetType != null)
							MarkTypeWithDebuggerTypeProxyAttribute (targetType, customAttribute);
						break;
					}
				}
			}

			// requeue the items we skipped in case we need to make another pass
			foreach (var item in skippedItems)
				_assemblyLevelAttributes.Enqueue (item);

			return markOccurred;
		}

		bool ProcessLateMarkedAttributes ()
		{
			var startingQueueCount = _lateMarkedAttributes.Count;
			if (startingQueueCount == 0)
				return false;

			var skippedItems = new List<(AttributeProviderPair, DependencyInfo, MarkScopeStack.Scope)> ();
			var markOccurred = false;

			while (_lateMarkedAttributes.Count != 0) {
				var (attributeProviderPair, reason, scope) = _lateMarkedAttributes.Dequeue ();
				var customAttribute = attributeProviderPair.Attribute;
				var provider = attributeProviderPair.Provider;

				var resolved = Context.Resolve (customAttribute.Constructor);
				if (resolved == null) {
					continue;
				}

				if (!ShouldMarkCustomAttribute (customAttribute, provider)) {
					skippedItems.Add ((attributeProviderPair, reason, scope));
					continue;
				}

				markOccurred = true;
				using (ScopeStack.PushScope (scope)) {
					MarkCustomAttribute (customAttribute, reason);
				}
			}

			// requeue the items we skipped in case we need to make another pass
			foreach (var item in skippedItems)
				_lateMarkedAttributes.Enqueue (item);

			return markOccurred;
		}

		protected void MarkField (FieldReference reference, DependencyInfo reason, in MessageOrigin origin)
		{
			if (reference.DeclaringType is GenericInstanceType) {
				Debug.Assert (reason.Kind == DependencyKind.FieldAccess || reason.Kind == DependencyKind.Ldtoken);
				// Blame the field reference (without actually marking) on the original reason.
				Tracer.AddDirectDependency (reference, reason, marked: false);
				MarkType (reference.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, reference), new MessageOrigin (Context.TryResolve (reference)));

				// Blame the field definition that we will resolve on the field reference.
				reason = new DependencyInfo (DependencyKind.FieldOnGenericInstance, reference);
			}

			FieldDefinition? field = Context.Resolve (reference);

			if (field == null) {
				return;
			}

			MarkField (field, reason, origin);
		}

		void ReportWarningsForTypeHierarchyReflectionAccess (IMemberDefinition member, MessageOrigin origin)
		{
			Debug.Assert (member is MethodDefinition or FieldDefinition);

			// Don't check whether the current scope is a RUC type or RUC method because these warnings
			// are not suppressed in RUC scopes. Here the scope represents the DynamicallyAccessedMembers
			// annotation on a type, not a callsite which uses the annotation. We always want to warn about
			// possible reflection access indicated by these annotations.

			var type = origin.Provider as TypeDefinition;
			Debug.Assert (type != null);

			static bool IsDeclaredWithinType (IMemberDefinition member, TypeDefinition type)
			{
				while ((member = member.DeclaringType) != null) {
					if (member == type)
						return true;
				}
				return false;
			}

			var reportOnMember = IsDeclaredWithinType (member, type);
			if (reportOnMember)
				origin = new MessageOrigin (member);


			// All override methods should have the same annotations as their base methods
			// (else we will produce warning IL2046 or IL2092 or some other warning).
			// When marking override methods via DynamicallyAccessedMembers, we should only issue a warning for the base method.
			bool skipWarningsForOverride = member is MethodDefinition m && m.IsVirtual && Annotations.GetBaseMethods (m) != null;

			bool isReflectionAccessCoveredByRUC = Annotations.DoesMemberRequireUnreferencedCode (member, out RequiresUnreferencedCodeAttribute? requiresUnreferencedCodeAttribute);
			if (isReflectionAccessCoveredByRUC && !skipWarningsForOverride) {
				var id = reportOnMember ? DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesMemberWithRequiresUnreferencedCode : DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesMemberOnBaseWithRequiresUnreferencedCode;
				Context.LogWarning (origin, id, type.GetDisplayName (),
					((MemberReference) member).GetDisplayName (), // The cast is valid since it has to be a method or field
					MessageFormat.FormatRequiresAttributeMessageArg (requiresUnreferencedCodeAttribute!.Message),
					MessageFormat.FormatRequiresAttributeMessageArg (requiresUnreferencedCodeAttribute!.Url));
			}

			bool isReflectionAccessCoveredByDAM = Annotations.FlowAnnotations.ShouldWarnWhenAccessedForReflection (member);
			if (isReflectionAccessCoveredByDAM && !skipWarningsForOverride) {
				var id = reportOnMember ? DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesMemberWithDynamicallyAccessedMembers : DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesMemberOnBaseWithDynamicallyAccessedMembers;
				Context.LogWarning (origin, id, type.GetDisplayName (), ((MemberReference) member).GetDisplayName ());
			}

			// Warn on reflection access to compiler-generated methods, if the method isn't already unsafe to access via reflection
			// due to annotations. For the annotation-based warnings, we skip virtual overrides since those will produce warnings on
			// the base, but for unannotated compiler-generated methods this is not the case, so we must produce these warnings even
			// for virtual overrides. This ensures that we include the unannotated MoveNext state machine method. Lambdas and local
			// functions should never be virtual overrides in the first place.
			bool isCoveredByAnnotations = isReflectionAccessCoveredByRUC || isReflectionAccessCoveredByDAM;
			if (member is MethodDefinition method && ShouldWarnForReflectionAccessToCompilerGeneratedCode (method, isCoveredByAnnotations)) {
				var id = reportOnMember ? DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesCompilerGeneratedMember : DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesCompilerGeneratedMemberOnBase;
				Context.LogWarning (origin, id, type.GetDisplayName (), method.GetDisplayName ());
			}

			// Warn on reflection access to compiler-generated fields.
			if (member is FieldDefinition field && ShouldWarnForReflectionAccessToCompilerGeneratedCode (field, isCoveredByAnnotations)) {
				var id = reportOnMember ? DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesCompilerGeneratedMember : DiagnosticId.DynamicallyAccessedMembersOnTypeReferencesCompilerGeneratedMemberOnBase;
				Context.LogWarning (origin, id, type.GetDisplayName (), field.GetDisplayName ());
			}
		}

		void MarkField (FieldDefinition field, in DependencyInfo reason, in MessageOrigin origin)
		{
#if DEBUG
			if (!_fieldReasons.Contains (reason.Kind))
				throw new ArgumentOutOfRangeException ($"Internal error: unsupported field dependency {reason.Kind}");
#endif

			if (reason.Kind == DependencyKind.AlreadyMarked) {
				Debug.Assert (Annotations.IsMarked (field));
			} else {
				Annotations.Mark (field, reason, origin);
			}

			ProcessAnalysisAnnotationsForField (field, reason.Kind, in origin);

			if (CheckProcessed (field))
				return;

			// Use the original scope for marking the declaring type - it provides better warning message location
			MarkType (field.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, field));

			using var fieldScope = ScopeStack.PushScope (new MessageOrigin (field));
			MarkType (field.FieldType, new DependencyInfo (DependencyKind.FieldType, field));
			MarkCustomAttributes (field, new DependencyInfo (DependencyKind.CustomAttribute, field));
			MarkMarshalSpec (field, new DependencyInfo (DependencyKind.FieldMarshalSpec, field));
			DoAdditionalFieldProcessing (field);

			// If we accessed a field on a type and the type has explicit/sequential layout, make sure to keep
			// all the other fields.
			//
			// We normally do this when the type is seen as instantiated, but one can get into a situation
			// where the type is not seen as instantiated and the offsets still matter (usually when type safety
			// is violated with Unsafe.As).
			//
			// This won't do too much work because classes are rarely tagged for explicit/sequential layout.
			if (!field.DeclaringType.IsValueType && !field.DeclaringType.IsAutoLayout) {
				// We also need to walk the base hierarchy because the offset of the field depends on the
				// layout of the base.
				TypeDefinition? typeWithFields = field.DeclaringType;
				while (typeWithFields != null) {
					MarkImplicitlyUsedFields (typeWithFields);
					typeWithFields = Context.TryResolve (typeWithFields.BaseType);
				}
			}

			var parent = field.DeclaringType;
			if (!Annotations.HasPreservedStaticCtor (parent)) {
				var cctorReason = reason.Kind switch {
					// Report an edge directly from the method accessing the field to the static ctor it triggers
					DependencyKind.FieldAccess => new DependencyInfo (DependencyKind.TriggersCctorThroughFieldAccess, reason.Source),
					_ => new DependencyInfo (DependencyKind.CctorForField, field)
				};
				MarkStaticConstructor (parent, cctorReason, ScopeStack.CurrentScope.Origin);
			}

			if (Annotations.HasSubstitutedInit (field)) {
				Annotations.SetPreservedStaticCtor (parent);
				Annotations.SetSubstitutedInit (parent);
			}
		}

		bool ShouldWarnForReflectionAccessToCompilerGeneratedCode (FieldDefinition field, bool isCoveredByAnnotations)
		{
			// No need to warn if it's already covered by the Requires attribute or explicit annotations on the field.
			if (isCoveredByAnnotations)
				return false;

			if (!CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (field))
				return false;

			// Only warn for types which are interesting for dataflow. Note that this does
			// not include integer types, even though we track integers in the dataflow analysis.
			// Technically we should also warn for integer types, but this leads to more warnings
			// for example about the compiler-generated "state" field for state machine methods.
			// This should be ok because in most cases the state machine types will also have other
			// hoisted locals that produce warnings anyway when accessed via reflection.
			return Annotations.FlowAnnotations.IsTypeInterestingForDataflow (field.FieldType);
		}

		void ProcessAnalysisAnnotationsForField (FieldDefinition field, DependencyKind dependencyKind, in MessageOrigin origin)
		{
			if (origin.Provider != ScopeStack.CurrentScope.Origin.Provider) {
				Debug.Assert (dependencyKind == DependencyKind.DynamicallyAccessedMemberOnType ||
					(origin.Provider is MethodDefinition originMethod && CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (originMethod)));
			}

			if (dependencyKind == DependencyKind.DynamicallyAccessedMemberOnType) {
				ReportWarningsForTypeHierarchyReflectionAccess (field, origin);
				return;
			}

			if (Annotations.ShouldSuppressAnalysisWarningsForRequiresUnreferencedCode (origin.Provider))
				return;

			bool isReflectionAccessCoveredByRUC;
			if (isReflectionAccessCoveredByRUC = Annotations.DoesFieldRequireUnreferencedCode (field, out RequiresUnreferencedCodeAttribute? requiresUnreferencedCodeAttribute))
				ReportRequiresUnreferencedCode (field.GetDisplayName (), requiresUnreferencedCodeAttribute!, new DiagnosticContext (origin, diagnosticsEnabled: true, Context));

			bool isReflectionAccessCoveredByDAM = false;
			switch (dependencyKind) {
			case DependencyKind.AccessedViaReflection:
			case DependencyKind.DynamicDependency:
			case DependencyKind.DynamicallyAccessedMember:
			case DependencyKind.InteropMethodDependency:
				if (isReflectionAccessCoveredByDAM = Annotations.FlowAnnotations.ShouldWarnWhenAccessedForReflection (field))
					Context.LogWarning (origin, DiagnosticId.DynamicallyAccessedMembersFieldAccessedViaReflection, field.GetDisplayName ());

				break;
			}

			switch (dependencyKind) {
			case DependencyKind.AccessedViaReflection:
			case DependencyKind.DynamicallyAccessedMember:
				bool isCoveredByAnnotations = isReflectionAccessCoveredByRUC || isReflectionAccessCoveredByDAM;
				if (ShouldWarnForReflectionAccessToCompilerGeneratedCode (field, isCoveredByAnnotations))
					Context.LogWarning (origin, DiagnosticId.CompilerGeneratedMemberAccessedViaReflection, field.GetDisplayName ());
				break;
			}
		}

		/// <summary>
		/// Returns true if the assembly of the <paramref name="scope"></paramref> is not set to link (i.e. action=copy is set for that assembly)
		/// </summary>
		protected virtual bool IgnoreScope (IMetadataScope scope)
		{
			AssemblyDefinition? assembly = Context.Resolve (scope);
			return assembly != null && Annotations.GetAction (assembly) != AssemblyAction.Link;
		}

		void MarkModule (ModuleDefinition module, DependencyInfo reason)
		{
			if (reason.Kind == DependencyKind.AlreadyMarked) {
				Debug.Assert (Annotations.IsMarked (module));
			} else {
				Annotations.Mark (module, reason, ScopeStack.CurrentScope.Origin);
			}
			if (CheckProcessed (module))
				return;
			MarkAssembly (module.Assembly, new DependencyInfo (DependencyKind.AssemblyOfModule, module));
		}

		protected virtual void MarkSerializable (TypeDefinition type)
		{
			if (!type.HasMethods)
				return;

			if (Context.GetTargetRuntimeVersion () > TargetRuntimeVersion.NET5)
				return;

			if (type.IsSerializable ()) {
				MarkDefaultConstructor (type, new DependencyInfo (DependencyKind.SerializationMethodForType, type));
				MarkMethodsIf (type.Methods, IsSpecialSerializationConstructor, new DependencyInfo (DependencyKind.SerializationMethodForType, type), ScopeStack.CurrentScope.Origin);
			}

			MarkMethodsIf (type.Methods, HasOnSerializeOrDeserializeAttribute, new DependencyInfo (DependencyKind.SerializationMethodForType, type), ScopeStack.CurrentScope.Origin);
		}

		protected internal virtual TypeDefinition? MarkTypeVisibleToReflection (TypeReference type, TypeDefinition definition, in DependencyInfo reason, in MessageOrigin origin)
		{
			// If a type is visible to reflection, we need to stop doing optimization that could cause observable difference
			// in reflection APIs. This includes APIs like MakeGenericType (where variant castability of the produced type
			// could be incorrect) or IsAssignableFrom (where assignability of unconstructed types might change).
			Annotations.MarkRelevantToVariantCasting (definition);

			Annotations.MarkReflectionUsed (definition);

			MarkImplicitlyUsedFields (definition);

			return MarkType (type, reason, origin);
		}

		internal void MarkMethodVisibleToReflection (MethodDefinition method, in DependencyInfo reason, in MessageOrigin origin)
		{
			MarkIndirectlyCalledMethod (method, reason, origin);
			Annotations.MarkReflectionUsed (method);
		}

		internal void MarkFieldVisibleToReflection (FieldDefinition field, in DependencyInfo reason, in MessageOrigin origin)
		{
			MarkField (field, reason, origin);
		}

		internal void MarkPropertyVisibleToReflection (PropertyDefinition property, in DependencyInfo reason, in MessageOrigin origin)
		{
			// Marking the property itself actually doesn't keep it (it only marks its attributes and records the dependency), we have to mark the methods on it
			MarkProperty (property, reason);
			// We don't track PropertyInfo, so we can't tell if any accessor is needed by the app, so include them both.
			// With better tracking it might be possible to be more precise here: dotnet/linker/issues/1948
			MarkMethodIfNotNull (property.GetMethod, reason, origin);
			MarkMethodIfNotNull (property.SetMethod, reason, origin);
			MarkMethodsIf (property.OtherMethods, m => true, reason, origin);
		}

		internal void MarkEventVisibleToReflection (EventDefinition @event, in DependencyInfo reason, in MessageOrigin origin)
		{
			MarkEvent (@event, reason);
			// MarkEvent already marks the add/remove/invoke methods, but we need to mark them with the
			// DependencyInfo used to access the event from reflection, to produce warnings for annotated
			// event methods.
			MarkMethodIfNotNull (@event.AddMethod, reason, origin);
			MarkMethodIfNotNull (@event.InvokeMethod, reason, origin);
			MarkMethodIfNotNull (@event.InvokeMethod, reason, origin);
			MarkMethodsIf (@event.OtherMethods, m => true, reason, origin);
		}

		internal void MarkStaticConstructorVisibleToReflection (TypeDefinition type, in DependencyInfo reason, in MessageOrigin origin)
		{
			MarkStaticConstructor (type, reason, origin);
		}

		/// <summary>
		/// Marks the specified <paramref name="reference"/> as referenced.
		/// </summary>
		/// <param name="reference">The type reference to mark.</param>
		/// <param name="reason">The reason why the marking is occuring</param>
		/// <returns>The resolved type definition if the reference can be resolved</returns>
		protected internal virtual TypeDefinition? MarkType (TypeReference reference, DependencyInfo reason, MessageOrigin? origin = null)
		{
#if DEBUG
			if (!_typeReasons.Contains (reason.Kind))
				throw new ArgumentOutOfRangeException ($"Internal error: unsupported type dependency {reason.Kind}");
#endif
			if (reference == null)
				return null;

			using var localScope = origin.HasValue ? ScopeStack.PushScope (origin.Value) : null;

			(reference, reason) = GetOriginalType (reference, reason);

			if (reference is FunctionPointerType)
				return null;

			if (reference is GenericParameter)
				return null;

			TypeDefinition? type = Context.Resolve (reference);

			if (type == null)
				return null;

			// Track a mark reason for each call to MarkType.
			switch (reason.Kind) {
			case DependencyKind.AlreadyMarked:
				Debug.Assert (Annotations.IsMarked (type));
				break;
			default:
				Annotations.Mark (type, reason, ScopeStack.CurrentScope.Origin);
				break;
			}

			// Treat cctors triggered by a called method specially and mark this case up-front.
			if (type.HasMethods && ShouldMarkTypeStaticConstructor (type) && reason.Kind == DependencyKind.DeclaringTypeOfCalledMethod)
				MarkStaticConstructor (type, new DependencyInfo (DependencyKind.TriggersCctorForCalledMethod, reason.Source), ScopeStack.CurrentScope.Origin);

			if (Annotations.HasLinkerAttribute<RemoveAttributeInstancesAttribute> (type)) {
				// Don't warn about references from the removed attribute itself (for example the .ctor on the attribute
				// will call MarkType on the attribute type itself).
				// If for some reason we do keep the attribute type (could be because of previous reference which would cause IL2045
				// or because of a copy assembly with a reference and so on) then we should not spam the warnings due to the type itself.
				if (!(reason.Source is IMemberDefinition sourceMemberDefinition && sourceMemberDefinition.DeclaringType == type))
					Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.AttributeIsReferencedButTrimmerRemoveAllInstances, type.GetDisplayName ());
			}

			if (CheckProcessed (type))
				return type;

			if (type.Scope is ModuleDefinition module)
				MarkModule (module, new DependencyInfo (DependencyKind.ScopeOfType, type));

			using var typeScope = ScopeStack.PushScope (new MessageOrigin (type));

			foreach (Action<TypeDefinition> handleMarkType in MarkContext.MarkTypeActions)
				handleMarkType (type);

			MarkType (type.BaseType, new DependencyInfo (DependencyKind.BaseType, type));

			// The DynamicallyAccessedMembers hiearchy processing must be done after the base type was marked
			// (to avoid inconsistencies in the cache), but before anything else as work done below
			// might need the results of the processing here.
			DynamicallyAccessedMembersTypeHierarchy.ProcessMarkedTypeForDynamicallyAccessedMembersHierarchy (type);

			if (type.DeclaringType != null)
				MarkType (type.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, type));
			MarkCustomAttributes (type, new DependencyInfo (DependencyKind.CustomAttribute, type));
			MarkSecurityDeclarations (type, new DependencyInfo (DependencyKind.CustomAttribute, type));

			if (Context.TryResolve (type.BaseType) is TypeDefinition baseType &&
				!Annotations.HasLinkerAttribute<RequiresUnreferencedCodeAttribute> (type) &&
				Annotations.TryGetLinkerAttribute (baseType, out RequiresUnreferencedCodeAttribute? effectiveRequiresUnreferencedCode)) {

				var currentOrigin = ScopeStack.CurrentScope.Origin;

				string arg1 = MessageFormat.FormatRequiresAttributeMessageArg (effectiveRequiresUnreferencedCode.Message);
				string arg2 = MessageFormat.FormatRequiresAttributeUrlArg (effectiveRequiresUnreferencedCode.Url);
				Context.LogWarning (currentOrigin, DiagnosticId.RequiresUnreferencedCodeOnBaseClass, type.GetDisplayName (), type.BaseType.GetDisplayName (), arg1, arg2);
			}


			if (type.IsMulticastDelegate ()) {
				MarkMulticastDelegate (type);
			}

			if (type.IsClass && type.BaseType == null && type.Name == "Object" && ShouldMarkSystemObjectFinalize)
				MarkMethodIf (type.Methods, m => m.Name == "Finalize", new DependencyInfo (DependencyKind.MethodForSpecialType, type), ScopeStack.CurrentScope.Origin);

			MarkSerializable (type);

			// This marks static fields of KeyWords/OpCodes/Tasks subclasses of an EventSource type.
			// The special handling of EventSource is still needed in .NET6 in library mode
			if ((!Context.DisableEventSourceSpecialHandling || Context.GetTargetRuntimeVersion () < TargetRuntimeVersion.NET6) && BCL.EventTracingForWindows.IsEventSourceImplementation (type, Context)) {
				MarkEventSourceProviders (type);
			}

			// This marks properties for [EventData] types as well as other attribute dependencies.
			MarkTypeSpecialCustomAttributes (type);

			MarkGenericParameterProvider (type);

			// There are a number of markings we can defer until later when we know it's possible a reference type could be instantiated
			// For example, if no instance of a type exist, then we don't need to mark the interfaces on that type -- Note this is not true for static interfaces
			// However, for some other types there is no benefit to deferring
			if (type.IsInterface) {
				// There's no benefit to deferring processing of an interface type until we know a type implementing that interface is marked
				MarkRequirementsForInstantiatedTypes (type);
			} else if (type.IsValueType) {
				// Note : Technically interfaces could be removed from value types in some of the same cases as reference types, however, it's harder to know when
				// a value type instance could exist.  You'd have to track initobj and maybe locals types.  Going to punt for now.
				MarkRequirementsForInstantiatedTypes (type);
			} else if (IsFullyPreserved (type)) {
				// Here for a couple reasons:
				// * Edge case to cover a scenario where a type has preserve all, implements interfaces, but does not have any instance ctors.
				//    Normally TypePreserve.All would cause an instance ctor to be marked and that would in turn lead to MarkInterfaceImplementations being called
				//    Without an instance ctor, MarkInterfaceImplementations is not called and then TypePreserve.All isn't truly respected.
				// * If an assembly has the action Copy and had ResolveFromAssemblyStep ran for the assembly, then InitializeType will have led us here
				//    When the entire assembly is preserved, then all interfaces, base, etc will be preserved on the type, so we need to make sure
				//    all of these types are marked.  For example, if an interface implementation is of a type in another assembly that is linked,
				//    and there are no other usages of that interface type, then we need to make sure the interface type is still marked because
				//    this type is going to retain the interface implementation
				MarkRequirementsForInstantiatedTypes (type);
			} else if (AlwaysMarkTypeAsInstantiated (type)) {
				MarkRequirementsForInstantiatedTypes (type);
			}

			// Save for later once we know which interfaces are marked and then determine which interface implementations and methods to keep
			if (type.HasInterfaces)
				_typesWithInterfaces.Add ((type, ScopeStack.CurrentScope));

			if (type.HasMethods) {
				// TODO: MarkMethodIfNeededByBaseMethod should include logic for IsMethodNeededBytTypeDueToPreservedScope
				foreach (var method in type.Methods) {
					MarkMethodIfNeededByBaseMethod (method);
				}
				// For methods that must be preserved, blame the declaring type.
				MarkMethodsIf (type.Methods, IsMethodNeededByTypeDueToPreservedScope, new DependencyInfo (DependencyKind.VirtualNeededDueToPreservedScope, type), ScopeStack.CurrentScope.Origin);
				if (ShouldMarkTypeStaticConstructor (type) && reason.Kind != DependencyKind.TriggersCctorForCalledMethod) {
					using (ScopeStack.PopToParent ())
						MarkStaticConstructor (type, new DependencyInfo (DependencyKind.CctorForType, type), ScopeStack.CurrentScope.Origin);
				}
			}

			DoAdditionalTypeProcessing (type);

			ApplyPreserveInfo (type);
			ApplyPreserveMethods (type);

			return type;
		}

		/// <summary>
		/// Allow subclasses to disable marking of System.Object.Finalize()
		/// </summary>
		protected virtual bool ShouldMarkSystemObjectFinalize => true;

		// Allow subclassers to mark additional things in the main processing loop
		protected virtual void DoAdditionalProcessing ()
		{
		}

		// Allow subclassers to mark additional things
		protected virtual void DoAdditionalTypeProcessing (TypeDefinition type)
		{
		}

		// Allow subclassers to mark additional things
		protected virtual void DoAdditionalFieldProcessing (FieldDefinition field)
		{
		}

		// Allow subclassers to mark additional things
		protected virtual void DoAdditionalPropertyProcessing (PropertyDefinition property)
		{
		}

		// Allow subclassers to mark additional things
		protected virtual void DoAdditionalEventProcessing (EventDefinition evt)
		{
		}

		// Allow subclassers to mark additional things
		protected virtual void DoAdditionalInstantiatedTypeProcessing (TypeDefinition type)
		{
		}

		TypeDefinition? GetDebuggerAttributeTargetType (CustomAttribute ca, AssemblyDefinition asm)
		{
			foreach (var property in ca.Properties) {
				if (property.Name == "Target")
					return Context.TryResolve ((TypeReference) property.Argument.Value);

				if (property.Name == "TargetTypeName") {
					string targetTypeName = (string) property.Argument.Value;
					TypeName typeName = TypeParser.ParseTypeName (targetTypeName);
					if (typeName is AssemblyQualifiedTypeName assemblyQualifiedTypeName) {
						AssemblyDefinition? assembly = Context.TryResolve (assemblyQualifiedTypeName.AssemblyName.Name);
						return assembly == null ? null : Context.TryResolve (assembly, targetTypeName);
					}

					return Context.TryResolve (asm, targetTypeName);
				}
			}

			return null;
		}

		void MarkTypeSpecialCustomAttributes (TypeDefinition type)
		{
			if (!type.HasCustomAttributes)
				return;

			foreach (CustomAttribute attribute in type.CustomAttributes) {
				var attrType = attribute.Constructor.DeclaringType;
				var resolvedAttributeType = Context.Resolve (attrType);
				if (resolvedAttributeType == null) {
					continue;
				}

				if (Annotations.HasLinkerAttribute<RemoveAttributeInstancesAttribute> (resolvedAttributeType) && Annotations.GetAction (type.Module.Assembly) == AssemblyAction.Link)
					continue;

				switch (attrType.Name) {
				case "XmlSchemaProviderAttribute" when attrType.Namespace == "System.Xml.Serialization":
					MarkXmlSchemaProvider (type, attribute);
					break;
				case "DebuggerDisplayAttribute" when attrType.Namespace == "System.Diagnostics":
					MarkTypeWithDebuggerDisplayAttribute (type, attribute);
					break;
				case "DebuggerTypeProxyAttribute" when attrType.Namespace == "System.Diagnostics":
					MarkTypeWithDebuggerTypeProxyAttribute (type, attribute);
					break;
				// The special handling of EventSource is still needed in .NET6 in library mode
				case "EventDataAttribute" when attrType.Namespace == "System.Diagnostics.Tracing" && (!Context.DisableEventSourceSpecialHandling || Context.GetTargetRuntimeVersion () < TargetRuntimeVersion.NET6):
					if (MarkMethodsIf (type.Methods, MethodDefinitionExtensions.IsPublicInstancePropertyMethod, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, type), ScopeStack.CurrentScope.Origin))
						Tracer.AddDirectDependency (attribute, new DependencyInfo (DependencyKind.CustomAttribute, type), marked: false);
					break;
				}
			}
		}

		void MarkMethodSpecialCustomAttributes (MethodDefinition method)
		{
			if (!method.HasCustomAttributes)
				return;

			foreach (CustomAttribute attribute in method.CustomAttributes) {
				switch (attribute.Constructor.DeclaringType.FullName) {
				case "System.Web.Services.Protocols.SoapHeaderAttribute":
					MarkSoapHeader (method, attribute);
					break;
				}
			}
		}

		void MarkXmlSchemaProvider (TypeDefinition type, CustomAttribute attribute)
		{
			if (TryGetStringArgument (attribute, out string? name)) {
				Tracer.AddDirectDependency (attribute, new DependencyInfo (DependencyKind.CustomAttribute, type), marked: false);
				MarkNamedMethod (type, name, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));
			}
		}

		static readonly Regex DebuggerDisplayAttributeValueRegex = new Regex ("{[^{}]+}", RegexOptions.Compiled);

		void MarkTypeWithDebuggerDisplayAttribute (TypeDefinition type, CustomAttribute attribute)
		{
			if (Context.KeepMembersForDebugger) {

				// Members referenced by the DebuggerDisplayAttribute are kept even if the attribute may not be.
				// Record a logical dependency on the attribute so that we can blame it for the kept members below.
				Tracer.AddDirectDependency (attribute, new DependencyInfo (DependencyKind.CustomAttribute, type), marked: false);

				string displayString = (string) attribute.ConstructorArguments[0].Value;
				if (string.IsNullOrEmpty (displayString))
					return;

				foreach (Match match in DebuggerDisplayAttributeValueRegex.Matches (displayString)) {
					// Remove '{' and '}'
					string realMatch = match.Value.Substring (1, match.Value.Length - 2);

					// Remove ",nq" suffix if present
					// (it asks the expression evaluator to remove the quotes when displaying the final value)
					if (Regex.IsMatch (realMatch, @".+,\s*nq")) {
						realMatch = realMatch.Substring (0, realMatch.LastIndexOf (','));
					}

					if (realMatch.EndsWith ("()")) {
						string methodName = realMatch.Substring (0, realMatch.Length - 2);

						// It's a call to a method on some member.  Handling this scenario robustly would be complicated and a decent bit of work.
						//
						// We could implement support for this at some point, but for now it's important to make sure at least we don't crash trying to find some
						// method on the current type when it exists on some other type
						if (methodName.Contains ('.'))
							continue;

						MethodDefinition? method = GetMethodWithNoParameters (type, methodName);
						if (method != null) {
							MarkMethod (method, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), ScopeStack.CurrentScope.Origin);
							continue;
						}
					} else {
						FieldDefinition? field = GetField (type, realMatch);
						if (field != null) {
							MarkField (field, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), ScopeStack.CurrentScope.Origin);
							continue;
						}

						PropertyDefinition? property = GetProperty (type, realMatch);
						if (property != null) {
							if (property.GetMethod != null) {
								MarkMethod (property.GetMethod, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), ScopeStack.CurrentScope.Origin);
							}
							if (property.SetMethod != null) {
								MarkMethod (property.SetMethod, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), ScopeStack.CurrentScope.Origin);
							}
							continue;
						}
					}

					while (true) {
						// Currently if we don't understand the DebuggerDisplayAttribute we mark everything on the type
						// This can be improved: dotnet/linker/issues/1873
						MarkMethods (type, new DependencyInfo (DependencyKind.KeptForSpecialAttribute, attribute));
						MarkFields (type, includeStatic: true, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));
						if (Context.TryResolve (type.BaseType) is not TypeDefinition baseType)
							break;
						type = baseType;
					}
					return;
				}
			}
		}

		void MarkTypeWithDebuggerTypeProxyAttribute (TypeDefinition type, CustomAttribute attribute)
		{
			if (Context.KeepMembersForDebugger) {
				object constructorArgument = attribute.ConstructorArguments[0].Value;
				TypeReference? proxyTypeReference = constructorArgument as TypeReference;
				if (proxyTypeReference == null) {
					if (constructorArgument is string proxyTypeReferenceString) {
						proxyTypeReference = type.Module.GetType (proxyTypeReferenceString, runtimeName: true);
					}
				}

				if (proxyTypeReference == null) {
					return;
				}

				Tracer.AddDirectDependency (attribute, new DependencyInfo (DependencyKind.CustomAttribute, type), marked: false);
				MarkType (proxyTypeReference, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));

				if (Context.TryResolve (proxyTypeReference) is TypeDefinition proxyType) {
					MarkMethods (proxyType, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));
					MarkFields (proxyType, includeStatic: true, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));
				}
			}
		}

		static bool TryGetStringArgument (CustomAttribute attribute, [NotNullWhen (true)] out string? argument)
		{
			argument = null;

			if (attribute.ConstructorArguments.Count < 1)
				return false;

			argument = attribute.ConstructorArguments[0].Value as string;

			return argument != null;
		}

		protected int MarkNamedMethod (TypeDefinition type, string method_name, in DependencyInfo reason)
		{
			if (!type.HasMethods)
				return 0;

			int count = 0;
			foreach (MethodDefinition method in type.Methods) {
				if (method.Name != method_name)
					continue;

				MarkMethod (method, reason, ScopeStack.CurrentScope.Origin);
				count++;
			}

			return count;
		}

		void MarkSoapHeader (MethodDefinition method, CustomAttribute attribute)
		{
			if (!TryGetStringArgument (attribute, out string? member_name))
				return;

			MarkNamedField (method.DeclaringType, member_name, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));
			MarkNamedProperty (method.DeclaringType, member_name, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute));
		}

		bool MarkNamedField (TypeDefinition type, string field_name, in DependencyInfo reason)
		{
			if (!type.HasFields)
				return false;

			foreach (FieldDefinition field in type.Fields) {
				if (field.Name != field_name)
					continue;

				MarkField (field, reason, ScopeStack.CurrentScope.Origin);
				return true;
			}

			return false;
		}

		void MarkNamedProperty (TypeDefinition type, string property_name, in DependencyInfo reason)
		{
			if (!type.HasProperties)
				return;

			foreach (PropertyDefinition property in type.Properties) {
				if (property.Name != property_name)
					continue;

				using (ScopeStack.PushScope (new MessageOrigin (property))) {
					// This marks methods directly without reporting the property.
					MarkMethod (property.GetMethod, reason, ScopeStack.CurrentScope.Origin);
					MarkMethod (property.SetMethod, reason, ScopeStack.CurrentScope.Origin);
				}
			}
		}

		void MarkInterfaceImplementations (TypeDefinition type)
		{
			if (!type.HasInterfaces)
				return;

			foreach (var iface in type.Interfaces) {
				// Only mark interface implementations of interface types that have been marked.
				// This enables stripping of interfaces that are never used
				if (ShouldMarkInterfaceImplementation (type, iface))
					MarkInterfaceImplementation (iface, new MessageOrigin (type));
			}

			bool ShouldMarkInterfaceImplementation (TypeDefinition type, InterfaceImplementation iface)
			{
				if (Annotations.IsMarked (iface))
					return false;

				if (!Context.IsOptimizationEnabled (CodeOptimizations.UnusedInterfaces, type))
					return true;

				if (Context.Resolve (iface.InterfaceType) is not TypeDefinition resolvedInterfaceType)
					return false;

				if (Annotations.IsMarked (resolvedInterfaceType))
					return true;

				// It's hard to know if a com or windows runtime interface will be needed from managed code alone,
				// so as a precaution we will mark these interfaces once the type is instantiated
				if (resolvedInterfaceType.IsImport || resolvedInterfaceType.IsWindowsRuntime)
					return true;

				return IsFullyPreserved (type);
			}
		}

		void MarkGenericParameterProvider (IGenericParameterProvider provider)
		{
			if (!provider.HasGenericParameters)
				return;

			foreach (GenericParameter parameter in provider.GenericParameters)
				MarkGenericParameter (parameter);
		}

		void MarkGenericParameter (GenericParameter parameter)
		{
			MarkCustomAttributes (parameter, new DependencyInfo (DependencyKind.GenericParameterCustomAttribute, parameter.Owner));
			if (!parameter.HasConstraints)
				return;

			foreach (var constraint in parameter.Constraints) {
				MarkCustomAttributes (constraint, new DependencyInfo (DependencyKind.GenericParameterConstraintCustomAttribute, parameter.Owner));
				MarkType (constraint.ConstraintType, new DependencyInfo (DependencyKind.GenericParameterConstraintType, parameter.Owner));
			}
		}

		/// <summary>
		/// Returns true if any of the base methods of the <paramref name="method"/> passed is in an assembly that is not trimmed (i.e. action != trim).
		/// Meant to be used to determine whether methods should be marked regardless of whether it is instantiated or not.
		/// </summary>
		/// <remarks>
		/// When the unusedinterfaces optimization is on, this is used to mark methods that override an abstract method from a non-link assembly and must be kept.
		/// When the unusedinterfaces optimization is off, this will do the same as when on but will also mark interface methods from interfaces defined in a non-link assembly.
		/// If the containing type is instantiated, the caller should also use <see cref="IsMethodNeededByInstantiatedTypeDueToPreservedScope (MethodDefinition)" />
		/// </remarks>
		bool IsMethodNeededByTypeDueToPreservedScope (MethodDefinition method)
		{
			if (Annotations.IsMarked (method))
				return false;
			// All methods we care about here will be virtual
			if (!method.IsVirtual)
				return false;

			var base_list = Annotations.GetBaseMethods (method);
			if (base_list == null)
				return false;

			foreach (OverrideInformation ov in base_list) {
				// Skip interface methods, they will be captured later by IsInterfaceImplementationMethodNeededByTypeDueToInterface
				if (ov.Base.DeclaringType.IsInterface)
					continue;

				if (!IgnoreScope (ov.Base.DeclaringType.Scope) && !IsMethodNeededByTypeDueToPreservedScope (ov.Base))
					continue;

				// If the type is marked, we need to keep overrides of abstract members defined in assemblies
				// that are copied to keep the IL valid.
				// However, if the base method is a non-abstract virtual (has an implementation on the base type), then we don't need to keep the override
				// until the type could be instantiated
				if (!ov.Base.IsAbstract)
					continue;

				return true;
			}

			return false;
		}

		/// <summary>
		/// Returns true if the override method is required due to the interface that the base method is declared on. See doc at <see href="docs/methods-kept-by-interface.md"/> for explanation of logic.
		/// </summary>
		bool IsInterfaceImplementationMethodNeededByTypeDueToInterface (OverrideInformation overrideInformation)
		{
			var @base = overrideInformation.Base;
			var method = overrideInformation.Override;
			if (@base is null || method is null || @base.DeclaringType is null)
				return false;

			if (Annotations.IsMarked (method))
				return false;

			if (!@base.DeclaringType.IsInterface)
				return false;

			// If the interface implementation is not marked, do not mark the implementation method
			// A type that doesn't implement the interface isn't required to have methods that implement the interface.
			InterfaceImplementation? iface = overrideInformation.MatchingInterfaceImplementation;
			if (!((iface is not null && Annotations.IsMarked (iface))
				|| IsInterfaceImplementationMarkedRecursively (method.DeclaringType, @base.DeclaringType)))
				return false;

			// If the interface method is not marked and the interface doesn't come from a preserved scope, do not mark the implementation method
			// Unmarked interface methods from link assemblies will be removed so the implementing method does not need to be kept.
			if (!Annotations.IsMarked (@base) && !IgnoreScope (@base.DeclaringType.Scope))
				return false;

			// If the interface method is abstract, mark the implementation method
			// The method is needed for valid IL.
			if (@base.IsAbstract)
				return true;

			// If the method is static and the implementing type is relevant to variant casting, mark the implementation method.
			// A static method may only be called through a constrained call if the type is relevant to variant casting.
			if (@base.IsStatic)
				return Annotations.IsRelevantToVariantCasting (method.DeclaringType)
					|| IgnoreScope (@base.DeclaringType.Scope);

			// If the implementing type is marked as instantiated, mark the implementation method.
			// If the type is not instantiated, do not mark the implementation method
			return Annotations.IsInstantiated (method.DeclaringType);
		}

		static bool IsSpecialSerializationConstructor (MethodDefinition method)
		{
			if (!method.IsInstanceConstructor ())
				return false;

			if (method.GetMetadataParametersCount () != 2)
				return false;

			return method.TryGetParameter ((ParameterIndex) 1)?.ParameterType.Name == "SerializationInfo" &&
				method.TryGetParameter ((ParameterIndex) 2)?.ParameterType.Name == "StreamingContext";
		}

		protected internal bool MarkMethodsIf (Collection<MethodDefinition> methods, Func<MethodDefinition, bool> predicate, in DependencyInfo reason, in MessageOrigin origin)
		{
			bool marked = false;
			foreach (MethodDefinition method in methods) {
				if (predicate (method)) {
					MarkMethod (method, reason, origin);
					marked = true;
				}
			}
			return marked;
		}

		protected MethodDefinition? MarkMethodIf (Collection<MethodDefinition> methods, Func<MethodDefinition, bool> predicate, in DependencyInfo reason, in MessageOrigin origin)
		{
			foreach (MethodDefinition method in methods) {
				if (predicate (method)) {
					return MarkMethod (method, reason, origin);
				}
			}

			return null;
		}

		protected bool MarkDefaultConstructor (TypeDefinition type, in DependencyInfo reason)
		{
			if (type?.HasMethods != true)
				return false;

			return MarkMethodIf (type.Methods, MethodDefinitionExtensions.IsDefaultConstructor, reason, ScopeStack.CurrentScope.Origin) != null;
		}

		void MarkCustomMarshalerGetInstance (TypeDefinition type, in DependencyInfo reason)
		{
			if (!type.HasMethods)
				return;

			MarkMethodIf (type.Methods,
				m =>
					m.Name == "GetInstance"
					&& m.IsStatic
					&& m.GetMetadataParametersCount () == 1
					&& m.GetParameter ((ParameterIndex) 0).ParameterType.MetadataType == MetadataType.String,
				reason,
				ScopeStack.CurrentScope.Origin);
		}

		void MarkICustomMarshalerMethods (TypeDefinition inputType, in DependencyInfo reason)
		{
			TypeDefinition? type = inputType;
			do {
				if (!type.HasInterfaces)
					continue;

				foreach (var iface in type.Interfaces) {
					var iface_type = iface.InterfaceType;
					if (!iface_type.IsTypeOf ("System.Runtime.InteropServices", "ICustomMarshaler"))
						continue;

					//
					// Instead of trying to guess where to find the interface declaration linker walks
					// the list of implemented interfaces and resolve the declaration from there
					//
					var tdef = Context.Resolve (iface_type);
					if (tdef == null) {
						return;
					}

					MarkMethodsIf (tdef.Methods, m => !m.IsStatic, reason, ScopeStack.CurrentScope.Origin);

					MarkInterfaceImplementation (iface, new MessageOrigin (type));
					return;
				}
			} while ((type = Context.TryResolve (type.BaseType)) != null);
		}

		bool IsNonEmptyStaticConstructor (MethodDefinition method)
		{
			if (!method.IsStaticConstructor ())
				return false;

			if (!method.HasBody || !method.IsIL)
				return true;

			var body = Context.GetMethodIL (method);

			if (body.Body.CodeSize != 1)
				return true;

			return body.Instructions[0].OpCode.Code != Code.Ret;
		}

		static bool HasOnSerializeOrDeserializeAttribute (MethodDefinition method)
		{
			if (!method.HasCustomAttributes)
				return false;
			foreach (var ca in method.CustomAttributes) {
				var cat = ca.AttributeType;
				if (cat.Namespace != "System.Runtime.Serialization")
					continue;
				switch (cat.Name) {
				case "OnDeserializedAttribute":
				case "OnDeserializingAttribute":
				case "OnSerializedAttribute":
				case "OnSerializingAttribute":
					return true;
				}
			}
			return false;
		}

		protected virtual bool AlwaysMarkTypeAsInstantiated (TypeDefinition td)
		{
			switch (td.Name) {
			// These types are created from native code which means we are unable to track when they are instantiated
			// Since these are such foundational types, let's take the easy route and just always assume an instance of one of these
			// could exist
			case "Delegate":
			case "MulticastDelegate":
			case "ValueType":
			case "Enum":
				return td.Namespace == "System";
			}

			return false;
		}

		void MarkEventSourceProviders (TypeDefinition td)
		{
			Debug.Assert (Context.GetTargetRuntimeVersion () < TargetRuntimeVersion.NET6 || !Context.DisableEventSourceSpecialHandling);
			foreach (var nestedType in td.NestedTypes) {
				if (BCL.EventTracingForWindows.IsProviderName (nestedType.Name))
					MarkStaticFields (nestedType, new DependencyInfo (DependencyKind.EventSourceProviderField, td));
			}
		}

		protected virtual void MarkMulticastDelegate (TypeDefinition type)
		{
			MarkMethodsIf (type.Methods, m => m.Name == ".ctor" || m.Name == "Invoke", new DependencyInfo (DependencyKind.MethodForSpecialType, type), ScopeStack.CurrentScope.Origin);
		}

		protected (TypeReference, DependencyInfo) GetOriginalType (TypeReference type, DependencyInfo reason)
		{
			while (type is TypeSpecification specification) {
				if (type is GenericInstanceType git) {
					MarkGenericArguments (git);
					Debug.Assert (!(specification.ElementType is TypeSpecification));
				}

				if (type is IModifierType mod)
					MarkModifierType (mod);

				if (type is FunctionPointerType fnptr) {
					MarkParameters (fnptr);
					MarkType (fnptr.ReturnType, new DependencyInfo (DependencyKind.ReturnType, fnptr));
					break; // FunctionPointerType is the original type
				}

				// Blame the type reference (which isn't marked) on the original reason.
				Tracer.AddDirectDependency (specification, reason, marked: false);
				// Blame the outgoing element type on the specification.
				(type, reason) = (specification.ElementType, new DependencyInfo (DependencyKind.ElementType, specification));
			}

			return (type, reason);
		}

		void MarkParameters (FunctionPointerType fnptr)
		{
			if (!fnptr.HasParameters)
				return;

			for (int i = 0; i < fnptr.Parameters.Count; i++) {
				MarkType (fnptr.Parameters[i].ParameterType, new DependencyInfo (DependencyKind.ParameterType, fnptr));
			}
		}

		void MarkModifierType (IModifierType mod)
		{
			MarkType (mod.ModifierType, new DependencyInfo (DependencyKind.ModifierType, mod));
		}

		void MarkGenericArguments (IGenericInstance instance)
		{
			var arguments = instance.GenericArguments;

			var generic_element = GetGenericProviderFromInstance (instance);
			if (generic_element == null)
				return;

			var parameters = generic_element.GenericParameters;

			if (arguments.Count != parameters.Count)
				return;

			for (int i = 0; i < arguments.Count; i++) {
				var argument = arguments[i];
				var parameter = parameters[i];

				TypeDefinition? argumentTypeDef = MarkType (argument, new DependencyInfo (DependencyKind.GenericArgumentType, instance));

				if (Annotations.FlowAnnotations.RequiresGenericArgumentDataFlowAnalysis (parameter)) {
					// The only two implementations of IGenericInstance both derive from MemberReference
					Debug.Assert (instance is MemberReference);

					using var _ = ScopeStack.CurrentScope.Origin.Provider == null ? ScopeStack.PushScope (new MessageOrigin (((MemberReference) instance).Resolve ())) : null;
					var scanner = new GenericArgumentDataFlow (Context, this, ScopeStack.CurrentScope.Origin);
					scanner.ProcessGenericArgumentDataFlow (parameter, argument);
				}

				if (argumentTypeDef == null)
					continue;

				Annotations.MarkRelevantToVariantCasting (argumentTypeDef);

				if (parameter.HasDefaultConstructorConstraint)
					MarkDefaultConstructor (argumentTypeDef, new DependencyInfo (DependencyKind.DefaultCtorForNewConstrainedGenericArgument, instance));
			}
		}

		IGenericParameterProvider? GetGenericProviderFromInstance (IGenericInstance instance)
		{
			if (instance is GenericInstanceMethod method)
				return Context.TryResolve (method.ElementMethod);

			if (instance is GenericInstanceType type)
				return Context.TryResolve (type.ElementType);

			return null;
		}

		void ApplyPreserveInfo (TypeDefinition type)
		{
			using var typeScope = ScopeStack.PushScope (new MessageOrigin (type));

			if (Annotations.TryGetPreserve (type, out TypePreserve preserve)) {
				if (!Annotations.SetAppliedPreserve (type, preserve))
					throw new InternalErrorException ($"Type {type} already has applied {preserve}.");

				var di = new DependencyInfo (DependencyKind.TypePreserve, type);

				switch (preserve) {
				case TypePreserve.All:
					MarkFields (type, true, di);
					MarkMethods (type, di);
					return;

				case TypePreserve.Fields:
					if (!MarkFields (type, true, di, true))
						Context.LogWarning (type, DiagnosticId.TypeHasNoFieldsToPreserve, type.GetDisplayName ());
					break;
				case TypePreserve.Methods:
					if (!MarkMethods (type, di))
						Context.LogWarning (type, DiagnosticId.TypeHasNoMethodsToPreserve, type.GetDisplayName ());
					break;
				}
			}

			if (Annotations.TryGetPreservedMembers (type, out TypePreserveMembers members)) {
				var di = new DependencyInfo (DependencyKind.TypePreserve, type);

				if (type.HasMethods) {
					foreach (var m in type.Methods) {
						if ((members & TypePreserveMembers.Visible) != 0 && IsMethodVisible (m)) {
							MarkMethod (m, di, ScopeStack.CurrentScope.Origin);
							continue;
						}

						if ((members & TypePreserveMembers.Internal) != 0 && IsMethodInternal (m)) {
							MarkMethod (m, di, ScopeStack.CurrentScope.Origin);
							continue;
						}

						if ((members & TypePreserveMembers.Library) != 0) {
							if (IsSpecialSerializationConstructor (m) || HasOnSerializeOrDeserializeAttribute (m)) {
								MarkMethod (m, di, ScopeStack.CurrentScope.Origin);
								continue;
							}
						}
					}
				}

				if (type.HasFields) {
					foreach (var f in type.Fields) {
						if ((members & TypePreserveMembers.Visible) != 0 && IsFieldVisible (f)) {
							MarkField (f, di, ScopeStack.CurrentScope.Origin);
							continue;
						}

						if ((members & TypePreserveMembers.Internal) != 0 && IsFieldInternal (f)) {
							MarkField (f, di, ScopeStack.CurrentScope.Origin);
							continue;
						}
					}
				}
			}
		}

		static bool IsMethodVisible (MethodDefinition method)
		{
			return method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly;
		}

		static bool IsMethodInternal (MethodDefinition method)
		{
			return method.IsAssembly || method.IsFamilyAndAssembly;
		}

		static bool IsFieldVisible (FieldDefinition field)
		{
			return field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly;
		}

		static bool IsFieldInternal (FieldDefinition field)
		{
			return field.IsAssembly || field.IsFamilyAndAssembly;
		}

		void ApplyPreserveMethods (TypeDefinition type)
		{
			var list = Annotations.GetPreservedMethods (type);
			if (list == null)
				return;

			Annotations.ClearPreservedMethods (type);
			MarkMethodCollection (list, new DependencyInfo (DependencyKind.PreservedMethod, type));
		}

		void ApplyPreserveMethods (MethodDefinition method)
		{
			var list = Annotations.GetPreservedMethods (method);
			if (list == null)
				return;

			Annotations.ClearPreservedMethods (method);
			MarkMethodCollection (list, new DependencyInfo (DependencyKind.PreservedMethod, method));
		}

		protected bool MarkFields (TypeDefinition type, bool includeStatic, in DependencyInfo reason, bool markBackingFieldsOnlyIfPropertyMarked = false)
		{
			if (!type.HasFields)
				return false;

			foreach (FieldDefinition field in type.Fields) {
				if (!includeStatic && field.IsStatic)
					continue;

				if (markBackingFieldsOnlyIfPropertyMarked && field.Name.EndsWith (">k__BackingField", StringComparison.Ordinal)) {
					// We can't reliably construct the expected property name from the backing field name for all compilers
					// because csc shortens the name of the backing field in some cases
					// For example:
					// Field Name = <IFoo<int>.Bar>k__BackingField
					// Property Name = IFoo<System.Int32>.Bar
					//
					// instead we will search the properties and find the one that makes use of the current backing field
					var propertyDefinition = SearchPropertiesForMatchingFieldDefinition (field);
					if (propertyDefinition != null && !Annotations.IsMarked (propertyDefinition))
						continue;
				}
				MarkField (field, reason, ScopeStack.CurrentScope.Origin);
			}

			return true;
		}

		PropertyDefinition? SearchPropertiesForMatchingFieldDefinition (FieldDefinition field)
		{
			foreach (var property in field.DeclaringType.Properties) {
				var body = property.GetMethod?.Body;
				if (body == null)
					continue;

				foreach (var ins in Context.GetMethodIL (body).Instructions) {
					if (ins?.Operand == field)
						return property;
				}
			}

			return null;
		}

		protected void MarkStaticFields (TypeDefinition type, in DependencyInfo reason)
		{
			if (!type.HasFields)
				return;

			foreach (FieldDefinition field in type.Fields) {
				if (field.IsStatic)
					MarkField (field, reason, ScopeStack.CurrentScope.Origin);
			}
		}

		protected virtual bool MarkMethods (TypeDefinition type, in DependencyInfo reason)
		{
			if (!type.HasMethods)
				return false;

			MarkMethodCollection (type.Methods, reason);
			return true;
		}

		void MarkMethodCollection (IList<MethodDefinition> methods, in DependencyInfo reason)
		{
			foreach (MethodDefinition method in methods)
				MarkMethod (method, reason, ScopeStack.CurrentScope.Origin);
		}

		protected internal void MarkIndirectlyCalledMethod (MethodDefinition method, in DependencyInfo reason, in MessageOrigin origin)
		{
			MarkMethod (method, reason, origin);
			Annotations.MarkIndirectlyCalledMethod (method);
		}

		protected virtual MethodDefinition? MarkMethod (MethodReference reference, DependencyInfo reason, in MessageOrigin origin)
		{
			DependencyKind originalReasonKind = reason.Kind;
			(reference, reason) = GetOriginalMethod (reference, reason);

			if (reference.DeclaringType is ArrayType arrayType) {
				MarkType (reference.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, reference));

				if (reference.Name == ".ctor" && Context.TryResolve (arrayType) is TypeDefinition typeDefinition) {
					Annotations.MarkRelevantToVariantCasting (typeDefinition);
				}
				return null;
			}

			if (reference.DeclaringType is GenericInstanceType) {
				// Blame the method reference on the original reason without marking it.
				Tracer.AddDirectDependency (reference, reason, marked: false);
				MarkType (reference.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, reference));
				// Mark the resolved method definition as a dependency of the reference.
				reason = new DependencyInfo (DependencyKind.MethodOnGenericInstance, reference);
			}

			MethodDefinition? method = Context.Resolve (reference);
			if (method == null)
				return null;

			if (Annotations.GetAction (method) == MethodAction.Nothing)
				Annotations.SetAction (method, MethodAction.Parse);

			EnqueueMethod (method, reason, origin);

			// Use the original reason as it's important to correctly generate warnings
			// the updated reason is only useful for better tracking of dependencies.
			ProcessAnalysisAnnotationsForMethod (method, originalReasonKind, origin);

			return method;
		}

		bool ShouldWarnForReflectionAccessToCompilerGeneratedCode (MethodDefinition method, bool isCoveredByAnnotations)
		{
			// No need to warn if it's already covered by the Requires attribute or explicit annotations on the method.
			if (isCoveredByAnnotations)
				return false;

			if (!CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (method) || method.Body == null)
				return false;

			// Warn only if it has potential dataflow issues, as approximated by our check to see if it requires
			// the reflection scanner. Checking this will also mark direct dependencies of the method body, if it
			// hasn't been marked already. A cache ensures this only happens once for the method, whether or not
			// it is accessed via reflection.
			return CheckRequiresReflectionMethodBodyScanner (Context.GetMethodIL (method));
		}

		void ProcessAnalysisAnnotationsForMethod (MethodDefinition method, DependencyKind dependencyKind, in MessageOrigin origin)
		{
			// There are only two ways to get there such that the origin isn't the same as the top of the scopestack.
			// - For DAM on type, the current scope is the caller of GetType, while the origin is the type itself.
			// - For warnings produced inside compiler-generated code, the current scope is the user code that
			//   owns the compiler-generated code, while the origin is the compiler-generated code.
			// In either case any warnings produced here should use the origin instead of the scopestack.
			if (origin.Provider != ScopeStack.CurrentScope.Origin.Provider) {
				Debug.Assert (dependencyKind == DependencyKind.DynamicallyAccessedMemberOnType ||
					(origin.Provider is MethodDefinition originMethod && CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (originMethod)));
			}

			switch (dependencyKind) {
			// DirectCall, VirtualCall and NewObj are handled by ReflectionMethodBodyScanner
			// This is necessary since the ReflectionMethodBodyScanner has intrinsic handling for some
			// of the annotated methods (for example Type.GetType)
			// and it knows when it's OK and when it needs a warning. In this place we don't know
			// and would have to warn every time.
			case DependencyKind.DirectCall:
			case DependencyKind.VirtualCall:
			case DependencyKind.Newobj:

			// Special case (like object.Equals or similar) - avoid checking anything
			case DependencyKind.MethodForSpecialType:

			// Marked through things like descriptor - don't want to warn as it's intentional choice
			case DependencyKind.AlreadyMarked:
			case DependencyKind.TypePreserve:
			case DependencyKind.PreservedMethod:

			// Marking the base method only because it's a base method should not produce a warning
			// we should produce warning only if there's some other reference. This is because all methods
			// in the hierarchy should have the RUC (if base as it), and so something must have
			// started it.
			// Similarly for overrides.
			case DependencyKind.BaseMethod:
			case DependencyKind.MethodImplOverride:
			case DependencyKind.Override:
			case DependencyKind.OverrideOnInstantiatedType:

			// These are used for virtual methods which are kept because the base method is in an assembly
			// which is "copy" (or "skip"). We don't want to report warnings for methods which were kept
			// only because of "copy" action (or similar), so ignore it here. If the method is referenced
			// directly somewhere else (either the derived or base) the warning would be reported.
			case DependencyKind.MethodForInstantiatedType:
			case DependencyKind.VirtualNeededDueToPreservedScope:

			// Used when marked because the member must be kept for the type to function (for example explicit layout,
			// or because the type is included as a whole for some other reasons). This alone should not act as a base
			// for raising a warning.
			// Note that "include whole type" due to dynamic access is handled specifically in MarkEntireType
			// and the DependencyKind in that case will be one of the dynamic acccess kinds and not MemberOfType
			// since in those cases the warnings are desirable (potential access through reflection).
			case DependencyKind.MemberOfType:

			// We should not be generating code which would produce warnings
			case DependencyKind.UnreachableBodyRequirement:

			case DependencyKind.Custom:
			case DependencyKind.Unspecified:

			// Don't warn for methods kept due to non-understood DebuggerDisplayAttribute
			// until https://github.com/dotnet/linker/issues/1873 is fixed.
			case DependencyKind.KeptForSpecialAttribute:
				return;

			case DependencyKind.DynamicallyAccessedMemberOnType:
				// DynamicallyAccessedMembers on type gets special treatment so that the warning origin
				// is the type or the annotated member.
				ReportWarningsForTypeHierarchyReflectionAccess (method, origin);
				return;

			default:
				// All other cases have the potential of us missing a warning if we don't report it
				// It is possible that in some cases we may report the same warning twice, but that's better than not reporting it.
				break;
			};

			if (Annotations.ShouldSuppressAnalysisWarningsForRequiresUnreferencedCode (origin.Provider))
				return;

			// All override methods should have the same annotations as their base methods
			// (else we will produce warning IL2046 or IL2092 or some other warning).
			// When marking override methods via DynamicallyAccessedMembers, we should only issue a warning for the base method.
			bool skipWarningsForOverride = dependencyKind == DependencyKind.DynamicallyAccessedMember && method.IsVirtual && Annotations.GetBaseMethods (method) != null;

			bool isReflectionAccessCoveredByRUC = Annotations.DoesMethodRequireUnreferencedCode (method, out RequiresUnreferencedCodeAttribute? requiresUnreferencedCode);
			if (isReflectionAccessCoveredByRUC && !skipWarningsForOverride)
				ReportRequiresUnreferencedCode (method.GetDisplayName (), requiresUnreferencedCode!, new DiagnosticContext (origin, diagnosticsEnabled: true, Context));

			bool isReflectionAccessCoveredByDAM = Annotations.FlowAnnotations.ShouldWarnWhenAccessedForReflection (method);
			if (isReflectionAccessCoveredByDAM && !skipWarningsForOverride) {
				// ReflectionMethodBodyScanner handles more cases for data flow annotations
				// so don't warn for those.
				switch (dependencyKind) {
				case DependencyKind.AttributeConstructor:
				case DependencyKind.AttributeProperty:
					break;
				default:
					Context.LogWarning (origin, DiagnosticId.DynamicallyAccessedMembersMethodAccessedViaReflection, method.GetDisplayName ());
					break;
				}
			}

			// Warn on reflection access to compiler-generated methods, if the method isn't already unsafe to access via reflection
			// due to annotations. For the annotation-based warnings, we skip virtual overrides since those will produce warnings on
			// the base, but for unannotated compiler-generated methods this is not the case, so we must produce these warnings even
			// for virtual overrides. This ensures that we include the unannotated MoveNext state machine method. Lambdas and local
			// functions should never be virtual overrides in the first place.
			bool isCoveredByAnnotations = isReflectionAccessCoveredByRUC || isReflectionAccessCoveredByDAM;
			switch (dependencyKind) {
			case DependencyKind.AccessedViaReflection:
			case DependencyKind.DynamicallyAccessedMember:
				if (ShouldWarnForReflectionAccessToCompilerGeneratedCode (method, isCoveredByAnnotations))
					Context.LogWarning (origin, DiagnosticId.CompilerGeneratedMemberAccessedViaReflection, method.GetDisplayName ());
				break;
			}
		}

		internal static void ReportRequiresUnreferencedCode (string displayName, RequiresUnreferencedCodeAttribute requiresUnreferencedCode, in DiagnosticContext diagnosticContext)
		{
			string arg1 = MessageFormat.FormatRequiresAttributeMessageArg (requiresUnreferencedCode.Message);
			string arg2 = MessageFormat.FormatRequiresAttributeUrlArg (requiresUnreferencedCode.Url);
			diagnosticContext.AddDiagnostic (DiagnosticId.RequiresUnreferencedCode, displayName, arg1, arg2);
		}

		protected (MethodReference, DependencyInfo) GetOriginalMethod (MethodReference method, DependencyInfo reason)
		{
			while (method is MethodSpecification specification) {
				// Blame the method reference (which isn't marked) on the original reason.
				Tracer.AddDirectDependency (specification, reason, marked: false);
				// Blame the outgoing element method on the specification.
				if (method is GenericInstanceMethod gim)
					MarkGenericArguments (gim);

				(method, reason) = (specification.ElementMethod, new DependencyInfo (DependencyKind.ElementMethod, specification));
				Debug.Assert (!(method is MethodSpecification));
			}

			return (method, reason);
		}

		protected virtual void ProcessMethod (MethodDefinition method, in DependencyInfo reason, in MessageOrigin origin)
		{
#if DEBUG
			if (!_methodReasons.Contains (reason.Kind))
				throw new InternalErrorException ($"Unsupported method dependency {reason.Kind}");
#endif
			ScopeStack.AssertIsEmpty ();
			using var parentScope = ScopeStack.PushScope (new MarkScopeStack.Scope (origin));
			using var methodScope = ScopeStack.PushScope (new MessageOrigin (method));

			// Record the reason for marking a method on each call. The logic under CheckProcessed happens
			// only once per method.
			switch (reason.Kind) {
			case DependencyKind.AlreadyMarked:
				Debug.Assert (Annotations.IsMarked (method));
				break;
			default:
				Annotations.Mark (method, reason, ScopeStack.CurrentScope.Origin);
				break;
			}

			bool markedForCall =
				reason.Kind == DependencyKind.DirectCall ||
				reason.Kind == DependencyKind.VirtualCall ||
				reason.Kind == DependencyKind.Newobj;
			if (markedForCall) {
				// Record declaring type of a called method up-front as a special case so that we may
				// track at least some method calls that trigger a cctor.
				// Temporarily switch to the original source for marking this method
				// this is for the same reason as for tracking, but this time so that we report potential
				// warnings from a better place.
				MarkType (method.DeclaringType, new DependencyInfo (DependencyKind.DeclaringTypeOfCalledMethod, method), new MessageOrigin (reason.Source as IMemberDefinition ?? method));
			}

			if (CheckProcessed (method))
				return;

			foreach (Action<MethodDefinition> handleMarkMethod in MarkContext.MarkMethodActions)
				handleMarkMethod (method);

			if (!markedForCall)
				MarkType (method.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, method));
			MarkCustomAttributes (method, new DependencyInfo (DependencyKind.CustomAttribute, method));
			MarkSecurityDeclarations (method, new DependencyInfo (DependencyKind.CustomAttribute, method));

			MarkGenericParameterProvider (method);

			if (method.IsInstanceConstructor ()) {
				MarkRequirementsForInstantiatedTypes (method.DeclaringType);
				Tracer.AddDirectDependency (method.DeclaringType, new DependencyInfo (DependencyKind.InstantiatedByCtor, method), marked: false);
			} else if (method.IsStaticConstructor () && Annotations.HasLinkerAttribute<RequiresUnreferencedCodeAttribute> (method))
				Context.LogWarning (ScopeStack.CurrentScope.Origin, DiagnosticId.RequiresUnreferencedCodeOnStaticConstructor, method.GetDisplayName ());

			if (method.IsConstructor) {
				if (!Annotations.ProcessSatelliteAssemblies && KnownMembers.IsSatelliteAssemblyMarker (method))
					Annotations.ProcessSatelliteAssemblies = true;
			} else if (method.TryGetProperty (out PropertyDefinition? property))
				MarkProperty (property, new DependencyInfo (DependencyKind.PropertyOfPropertyMethod, method));
			else if (method.TryGetEvent (out EventDefinition? @event))
				MarkEvent (@event, new DependencyInfo (DependencyKind.EventOfEventMethod, method));

			if (method.HasMetadataParameters ()) {
#pragma warning disable RS0030 // MethodReference.Parameters is banned. It's easiest to leave the code as is for now
				foreach (ParameterDefinition pd in method.Parameters) {
					MarkType (pd.ParameterType, new DependencyInfo (DependencyKind.ParameterType, method));
					MarkCustomAttributes (pd, new DependencyInfo (DependencyKind.ParameterAttribute, method));
					MarkMarshalSpec (pd, new DependencyInfo (DependencyKind.ParameterMarshalSpec, method));
				}
#pragma warning restore RS0030
			}

			if (method.HasOverrides) {
				foreach (MethodReference @base in method.Overrides) {
					// Method implementing a static interface method will have an override to it - note instance methods usually don't unless they're explicit.
					// Calling the implementation method directly has no impact on the interface, and as such it should not mark the interface or its method.
					// Only if the interface method is referenced, then all the methods which implemented must be kept, but not the other way round.
					if (Context.Resolve (@base) is MethodDefinition baseDefinition
						&& new OverrideInformation.OverridePair (baseDefinition, method).IsStaticInterfaceMethodPair ())
						continue;
					MarkMethod (@base, new DependencyInfo (DependencyKind.MethodImplOverride, method), ScopeStack.CurrentScope.Origin);
					MarkExplicitInterfaceImplementation (method, @base);
				}
			}

			MarkMethodSpecialCustomAttributes (method);

			if (method.IsVirtual)
				_virtual_methods.Add ((method, ScopeStack.CurrentScope));

			MarkNewCodeDependencies (method);

			MarkBaseMethods (method);

			if (Annotations.GetOverrides (method) is IEnumerable<OverrideInformation> overrides) {
				foreach (var @override in overrides) {
					if (ShouldMarkOverrideForBase (@override))
						MarkOverrideForBaseMethod (@override);
				}
			}

			MarkType (method.ReturnType, new DependencyInfo (DependencyKind.ReturnType, method));
			MarkCustomAttributes (method.MethodReturnType, new DependencyInfo (DependencyKind.ReturnTypeAttribute, method));
			MarkMarshalSpec (method.MethodReturnType, new DependencyInfo (DependencyKind.ReturnTypeMarshalSpec, method));

			if (method.IsPInvokeImpl || method.IsInternalCall) {
				ProcessInteropMethod (method);
			}

			if (ShouldParseMethodBody (method))
				MarkMethodBody (method.Body);

			if (method.DeclaringType.IsMulticastDelegate ()) {
				string? methodPair = null;
				if (method.Name == "BeginInvoke")
					methodPair = "EndInvoke";
				else if (method.Name == "EndInvoke")
					methodPair = "BeginInvoke";

				if (methodPair != null) {
					TypeDefinition declaringType = method.DeclaringType;
					MarkMethodIf (declaringType.Methods, m => m.Name == methodPair, new DependencyInfo (DependencyKind.MethodForSpecialType, declaringType), ScopeStack.CurrentScope.Origin);
				}
			}

			DoAdditionalMethodProcessing (method);

			ApplyPreserveMethods (method);
		}

		// Allow subclassers to mark additional things when marking a method
		protected virtual void DoAdditionalMethodProcessing (MethodDefinition method)
		{
		}

		void MarkImplicitlyUsedFields (TypeDefinition type)
		{
			if (type?.HasFields != true)
				return;

			// keep fields for types with explicit layout and for enums
			if (!type.IsAutoLayout || type.IsEnum)
				MarkFields (type, includeStatic: type.IsEnum, reason: new DependencyInfo (DependencyKind.MemberOfType, type));
		}

		protected virtual void MarkRequirementsForInstantiatedTypes (TypeDefinition type)
		{
			if (Annotations.IsInstantiated (type))
				return;

			Annotations.MarkInstantiated (type);

			using var typeScope = ScopeStack.PushScope (new MessageOrigin (type));

			MarkInterfaceImplementations (type);

			// Requires interface implementations to be marked first
			foreach (var method in type.Methods) {
				MarkMethodIfNeededByBaseMethod (method);
			}

			MarkImplicitlyUsedFields (type);

			DoAdditionalInstantiatedTypeProcessing (type);
		}

		void MarkExplicitInterfaceImplementation (MethodDefinition method, MethodReference ov)
		{
			if (Context.Resolve (ov) is not MethodDefinition resolvedOverride)
				return;

			if (resolvedOverride.DeclaringType.IsInterface) {
				foreach (var ifaceImpl in method.DeclaringType.Interfaces) {
					var resolvedInterfaceType = Context.Resolve (ifaceImpl.InterfaceType);
					if (resolvedInterfaceType == null) {
						continue;
					}

					if (resolvedInterfaceType == resolvedOverride.DeclaringType) {
						MarkInterfaceImplementation (ifaceImpl, new MessageOrigin (method.DeclaringType));
						return;
					}
				}
			}
		}

		void MarkNewCodeDependencies (MethodDefinition method)
		{
			switch (Annotations.GetAction (method)) {
			case MethodAction.ConvertToStub:
				if (!method.IsInstanceConstructor ())
					return;

				var baseType = Context.Resolve (method.DeclaringType.BaseType);
				if (baseType == null)
					break;
				if (!MarkDefaultConstructor (baseType, new DependencyInfo (DependencyKind.BaseDefaultCtorForStubbedMethod, method)))
					throw new LinkerFatalErrorException (MessageContainer.CreateErrorMessage (ScopeStack.CurrentScope.Origin, DiagnosticId.CannotStubConstructorWhenBaseTypeDoesNotHaveConstructor, method.DeclaringType.GetDisplayName ()));

				break;

			case MethodAction.ConvertToThrow:
				MarkAndCacheConvertToThrowExceptionCtor (new DependencyInfo (DependencyKind.UnreachableBodyRequirement, method));
				break;
			}
		}

		protected virtual void MarkAndCacheConvertToThrowExceptionCtor (DependencyInfo reason)
		{
			if (Context.MarkedKnownMembers.NotSupportedExceptionCtorString != null)
				return;

			var nse = BCL.FindPredefinedType (WellKnownType.System_NotSupportedException, Context);
			if (nse == null)
				throw new LinkerFatalErrorException (MessageContainer.CreateErrorMessage (null, DiagnosticId.CouldNotFindType, "System.NotSupportedException"));

			MarkType (nse, reason);

			var nseCtor = MarkMethodIf (nse.Methods, KnownMembers.IsNotSupportedExceptionCtorString, reason, ScopeStack.CurrentScope.Origin);
			Context.MarkedKnownMembers.NotSupportedExceptionCtorString = nseCtor ??
				throw new LinkerFatalErrorException (MessageContainer.CreateErrorMessage (null, DiagnosticId.CouldNotFindConstructor, nse.GetDisplayName ()));

			var objectType = BCL.FindPredefinedType (WellKnownType.System_Object, Context);
			if (objectType == null)
				throw new NotSupportedException ("Missing predefined 'System.Object' type");

			MarkType (objectType, reason);

			var objectCtor = MarkMethodIf (objectType.Methods, MethodDefinitionExtensions.IsDefaultConstructor, reason, ScopeStack.CurrentScope.Origin);
			Context.MarkedKnownMembers.ObjectCtor = objectCtor ??
					throw new LinkerFatalErrorException (MessageContainer.CreateErrorMessage (null, DiagnosticId.CouldNotFindConstructor, objectType.GetDisplayName ()));
		}

		bool MarkDisablePrivateReflectionAttribute ()
		{
			if (Context.MarkedKnownMembers.DisablePrivateReflectionAttributeCtor != null)
				return false;

			var disablePrivateReflection = BCL.FindPredefinedType (WellKnownType.System_Runtime_CompilerServices_DisablePrivateReflectionAttribute, Context);
			if (disablePrivateReflection == null)
				throw new LinkerFatalErrorException (MessageContainer.CreateErrorMessage (null, DiagnosticId.CouldNotFindType, "System.Runtime.CompilerServices.DisablePrivateReflectionAttribute"));

			using (ScopeStack.PushScope (new MessageOrigin (null as ICustomAttributeProvider))) {
				MarkType (disablePrivateReflection, DependencyInfo.DisablePrivateReflectionRequirement);

				var ctor = MarkMethodIf (disablePrivateReflection.Methods, MethodDefinitionExtensions.IsDefaultConstructor, new DependencyInfo (DependencyKind.DisablePrivateReflectionRequirement, disablePrivateReflection), ScopeStack.CurrentScope.Origin);
				Context.MarkedKnownMembers.DisablePrivateReflectionAttributeCtor = ctor ??
					throw new LinkerFatalErrorException (MessageContainer.CreateErrorMessage (null, DiagnosticId.CouldNotFindConstructor, disablePrivateReflection.GetDisplayName ()));
			}

			return true;
		}

		void MarkBaseMethods (MethodDefinition method)
		{
			var base_methods = Annotations.GetBaseMethods (method);
			if (base_methods == null)
				return;

			foreach (OverrideInformation ov in base_methods) {
				// We should add all interface base methods to _virtual_methods for virtual override annotation validation
				// Interfaces from preserved scope will be missed if we don't add them here
				// This will produce warnings for all interface methods and virtual methods regardless of whether the interface, interface implementation, or interface method is kept or not.
				if (ov.Base.DeclaringType.IsInterface && !method.DeclaringType.IsInterface) {
					// These are all virtual, no need to check IsVirtual before adding to list
					_virtual_methods.Add ((ov.Base, ScopeStack.CurrentScope));
					continue;
				}

				MarkMethod (ov.Base, new DependencyInfo (DependencyKind.BaseMethod, method), ScopeStack.CurrentScope.Origin);
				MarkBaseMethods (ov.Base);
			}
		}

		void ProcessInteropMethod (MethodDefinition method)
		{
			if (method.IsPInvokeImpl && method.PInvokeInfo != null) {
				var pii = method.PInvokeInfo;
				Annotations.MarkProcessed (pii.Module, new DependencyInfo (DependencyKind.InteropMethodDependency, method));
				if (!string.IsNullOrEmpty (Context.PInvokesListFile)) {
					Context.PInvokes.Add (new PInvokeInfo (
						assemblyName: method.DeclaringType.Module.Name,
						entryPoint: pii.EntryPoint,
						fullName: method.FullName,
						moduleName: pii.Module.Name
					));
				}
			}

			TypeDefinition? returnTypeDefinition = Context.TryResolve (method.ReturnType);

			const bool includeStaticFields = false;
			if (returnTypeDefinition != null) {
				if (!returnTypeDefinition.IsImport) {
					// What we keep here is correct most of the time, but not every time. Fine for now.
					MarkDefaultConstructor (returnTypeDefinition, new DependencyInfo (DependencyKind.InteropMethodDependency, method));
					MarkFields (returnTypeDefinition, includeStaticFields, new DependencyInfo (DependencyKind.InteropMethodDependency, method));
				}
			}

			if (method.HasThis && !method.DeclaringType.IsImport) {
				// This is probably Mono-specific. One can't have InternalCall or P/invoke instance methods in CoreCLR or .NET.
				MarkFields (method.DeclaringType, includeStaticFields, new DependencyInfo (DependencyKind.InteropMethodDependency, method));
			}

#pragma warning disable RS0030 // MethodReference.Parameters is banned. It's easiest to leave this code as is for now
			foreach (ParameterDefinition pd in method.Parameters) {
				TypeReference paramTypeReference = pd.ParameterType;
				if (paramTypeReference is TypeSpecification paramTypeSpecification) {
					paramTypeReference = paramTypeSpecification.ElementType;
				}
				TypeDefinition? paramTypeDefinition = Context.TryResolve (paramTypeReference);
				if (paramTypeDefinition != null) {
					if (!paramTypeDefinition.IsImport) {
						// What we keep here is correct most of the time, but not every time. Fine for now.
						MarkFields (paramTypeDefinition, includeStaticFields, new DependencyInfo (DependencyKind.InteropMethodDependency, method));
						if (pd.ParameterType.IsByReference) {
							MarkDefaultConstructor (paramTypeDefinition, new DependencyInfo (DependencyKind.InteropMethodDependency, method));
						}
					}
				}
			}
#pragma warning restore RS0030
		}

		protected virtual bool ShouldParseMethodBody (MethodDefinition method)
		{
			if (!method.HasBody)
				return false;

			switch (Annotations.GetAction (method)) {
			case MethodAction.ForceParse:
				return true;
			case MethodAction.Parse:
				AssemblyDefinition? assembly = Context.Resolve (method.DeclaringType.Scope);
				if (assembly == null)
					return false;
				switch (Annotations.GetAction (assembly)) {
				case AssemblyAction.Link:
				case AssemblyAction.Copy:
				case AssemblyAction.CopyUsed:
				case AssemblyAction.AddBypassNGen:
				case AssemblyAction.AddBypassNGenUsed:
					return true;
				default:
					return false;
				}
			default:
				return false;
			}
		}

		protected internal void MarkProperty (PropertyDefinition prop, in DependencyInfo reason)
		{
			Tracer.AddDirectDependency (prop, reason, marked: false);

			using var propertyScope = ScopeStack.PushScope (new MessageOrigin (prop));

			// Consider making this more similar to MarkEvent method?
			MarkCustomAttributes (prop, new DependencyInfo (DependencyKind.CustomAttribute, prop));
			DoAdditionalPropertyProcessing (prop);
		}

		protected internal virtual void MarkEvent (EventDefinition evt, in DependencyInfo reason)
		{
			// Record the event without marking it in Annotations.
			Tracer.AddDirectDependency (evt, reason, marked: false);

			using var eventScope = ScopeStack.PushScope (new MessageOrigin (evt));

			MarkCustomAttributes (evt, new DependencyInfo (DependencyKind.CustomAttribute, evt));
			MarkMethodIfNotNull (evt.AddMethod, new DependencyInfo (DependencyKind.EventMethod, evt), ScopeStack.CurrentScope.Origin);
			MarkMethodIfNotNull (evt.InvokeMethod, new DependencyInfo (DependencyKind.EventMethod, evt), ScopeStack.CurrentScope.Origin);
			MarkMethodIfNotNull (evt.RemoveMethod, new DependencyInfo (DependencyKind.EventMethod, evt), ScopeStack.CurrentScope.Origin);
			DoAdditionalEventProcessing (evt);
		}

		internal void MarkMethodIfNotNull (MethodReference method, in DependencyInfo reason, in MessageOrigin origin)
		{
			if (method == null)
				return;

			MarkMethod (method, reason, origin);
		}

		protected virtual void MarkMethodBody (MethodBody body)
		{
			var processedMethodBody = Context.GetMethodIL (body);

			if (Context.IsOptimizationEnabled (CodeOptimizations.UnreachableBodies, body.Method) && IsUnreachableBody (processedMethodBody)) {
				MarkAndCacheConvertToThrowExceptionCtor (new DependencyInfo (DependencyKind.UnreachableBodyRequirement, body.Method));
				_unreachableBodies.Add ((body, ScopeStack.CurrentScope));
				return;
			}

			// Note: we mark the method body of every method here including compiler-generated methods,
			// whether they are accessed from the user method or via reflection.
			// But for compiler-generated methods we only do dataflow analysis if they're used through their
			// corresponding user method, so we will skip dataflow for compiler-generated methods which
			// are only accessed via reflection.
			bool requiresReflectionMethodBodyScanner = MarkAndCheckRequiresReflectionMethodBodyScanner (processedMethodBody);

			// Data-flow (reflection scanning) for compiler-generated methods will happen as part of the
			// data-flow scan of the user-defined method which uses this compiler-generated method.
			if (CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (body.Method))
				return;

			MarkReflectionLikeDependencies (processedMethodBody, requiresReflectionMethodBodyScanner);
		}

		bool CheckRequiresReflectionMethodBodyScanner (MethodIL methodIL)
		{
			// This method is only called on reflection access to compiler-generated methods.
			// This should be uncommon, so don't cache the result.
			if (ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForMethodBody (Context, methodIL.Method))
				return true;

			foreach (Instruction instruction in methodIL.Instructions) {
				switch (instruction.OpCode.OperandType) {
				case OperandType.InlineField:
					if (InstructionRequiresReflectionMethodBodyScannerForFieldAccess (instruction))
						return true;
					break;

				case OperandType.InlineMethod:
					if (ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForCallSite (Context, (MethodReference) instruction.Operand))
						return true;
					break;
				}
			}
			return false;
		}

		// Keep the return value of this method in sync with that of CheckRequiresReflectionMethodBodyScanner.
		// It computes the same value, while also marking as it goes, as an optimization.
		// This should only be called behind a check to IsProcessed for the method or corresponding user method,
		// to avoid recursion.
		bool MarkAndCheckRequiresReflectionMethodBodyScanner (MethodIL methodIL)
		{
#if DEBUG
			if (!Annotations.IsProcessed (methodIL.Method)) {
				Debug.Assert (CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (methodIL.Method));
				MethodDefinition owningMethod = methodIL.Method;
				while (Context.CompilerGeneratedState.TryGetOwningMethodForCompilerGeneratedMember (owningMethod, out var owner))
					owningMethod = owner;
				Debug.Assert (owningMethod != methodIL.Method);
				Debug.Assert (Annotations.IsProcessed (owningMethod));
			}
#endif
			// This may get called multiple times for compiler-generated code: once for
			// reflection access, and once as part of the interprocedural scan of the user method.
			// This check ensures that we only do the work and produce warnings once.
			if (_compilerGeneratedMethodRequiresScanner.TryGetValue (methodIL.Body, out bool requiresReflectionMethodBodyScanner))
				return requiresReflectionMethodBodyScanner;

			foreach (VariableDefinition var in methodIL.Variables)
				MarkType (var.VariableType, new DependencyInfo (DependencyKind.VariableType, methodIL.Method));

			foreach (ExceptionHandler eh in methodIL.ExceptionHandlers)
				if (eh.HandlerType == ExceptionHandlerType.Catch)
					MarkType (eh.CatchType, new DependencyInfo (DependencyKind.CatchType, methodIL.Method));

			requiresReflectionMethodBodyScanner =
				ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForMethodBody (Context, methodIL.Method);
			using var _ = ScopeStack.PushScope (new MessageOrigin (methodIL.Method));
			foreach (Instruction instruction in methodIL.Instructions)
				MarkInstruction (instruction, methodIL.Method, ref requiresReflectionMethodBodyScanner);

			MarkInterfacesNeededByBodyStack (methodIL);

			if (CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (methodIL.Method))
				_compilerGeneratedMethodRequiresScanner.Add (methodIL.Body, requiresReflectionMethodBodyScanner);

			PostMarkMethodBody (methodIL.Body);

			Debug.Assert (requiresReflectionMethodBodyScanner == CheckRequiresReflectionMethodBodyScanner (methodIL));
			return requiresReflectionMethodBodyScanner;
		}

		bool IsUnreachableBody (MethodIL methodIL)
		{
			return !methodIL.Method.IsStatic
				&& !Annotations.IsInstantiated (methodIL.Method.DeclaringType)
				&& MethodBodyScanner.IsWorthConvertingToThrow (methodIL);
		}


		partial void PostMarkMethodBody (MethodBody body);

		void MarkInterfacesNeededByBodyStack (MethodIL methodIL)
		{
			// If a type could be on the stack in the body and an interface it implements could be on the stack on the body
			// then we need to mark that interface implementation.  When this occurs it is not safe to remove the interface implementation from the type
			// even if the type is never instantiated
			var implementations = new InterfacesOnStackScanner (Context).GetReferencedInterfaces (methodIL);
			if (implementations == null)
				return;

			foreach (var (implementation, type) in implementations)
				MarkInterfaceImplementation (implementation, new MessageOrigin (type));
		}

		bool InstructionRequiresReflectionMethodBodyScannerForFieldAccess (Instruction instruction)
			=> instruction.OpCode.Code switch {
				// Field stores (Storing value to annotated field must be checked)
				Code.Stfld or
				Code.Stsfld or
				// Field address loads (as those can be used to store values to annotated field and thus must be checked)
				Code.Ldflda or
				Code.Ldsflda
					=> ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForAccess (Context, (FieldReference) instruction.Operand),
				// For ref fields, ldfld loads an address which can be used to store values to annotated fields
				Code.Ldfld or Code.Ldsfld when ((FieldReference) instruction.Operand).FieldType.IsByRefOrPointer ()
					=> ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForAccess (Context, (FieldReference) instruction.Operand),
				// Other field operations are not interesting as they don't need to be checked
				_ => false
			};

		protected virtual void MarkInstruction (Instruction instruction, MethodDefinition method, ref bool requiresReflectionMethodBodyScanner)
		{
			switch (instruction.OpCode.OperandType) {
			case OperandType.InlineField:
				requiresReflectionMethodBodyScanner |= InstructionRequiresReflectionMethodBodyScannerForFieldAccess (instruction);

				ScopeStack.UpdateCurrentScopeInstructionOffset (instruction.Offset);
				MarkField ((FieldReference) instruction.Operand, new DependencyInfo (DependencyKind.FieldAccess, method), ScopeStack.CurrentScope.Origin);
				break;

			case OperandType.InlineMethod: {
					DependencyKind dependencyKind = instruction.OpCode.Code switch {
						Code.Jmp => DependencyKind.DirectCall,
						Code.Call => DependencyKind.DirectCall,
						Code.Callvirt => DependencyKind.VirtualCall,
						Code.Newobj => DependencyKind.Newobj,
						Code.Ldvirtftn => DependencyKind.Ldvirtftn,
						Code.Ldftn => DependencyKind.Ldftn,
						_ => throw new InvalidOperationException ($"unexpected opcode {instruction.OpCode}")
					};

					requiresReflectionMethodBodyScanner |=
						ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForCallSite (Context, (MethodReference) instruction.Operand);

					ScopeStack.UpdateCurrentScopeInstructionOffset (instruction.Offset);
					MarkMethod ((MethodReference) instruction.Operand, new DependencyInfo (dependencyKind, method), ScopeStack.CurrentScope.Origin);
					break;
				}

			case OperandType.InlineTok: {
					object token = instruction.Operand;
					Debug.Assert (instruction.OpCode.Code == Code.Ldtoken);
					var reason = new DependencyInfo (DependencyKind.Ldtoken, method);
					ScopeStack.UpdateCurrentScopeInstructionOffset (instruction.Offset);

					if (token is TypeReference typeReference) {
						// Error will be reported as part of MarkType
						if (Context.TryResolve (typeReference) is TypeDefinition type)
							MarkTypeVisibleToReflection (typeReference, type, reason, ScopeStack.CurrentScope.Origin);
					} else if (token is MethodReference methodReference) {
						MarkMethod (methodReference, reason, ScopeStack.CurrentScope.Origin);
					} else {
						MarkField ((FieldReference) token, reason, ScopeStack.CurrentScope.Origin);
					}
					break;
				}

			case OperandType.InlineType:
				var operand = (TypeReference) instruction.Operand;
				switch (instruction.OpCode.Code) {
				case Code.Newarr:
					if (Context.TryResolve (operand) is TypeDefinition typeDefinition) {
						Annotations.MarkRelevantToVariantCasting (typeDefinition);
					}
					break;
				case Code.Isinst:
					if (operand is TypeSpecification || operand is GenericParameter)
						break;

					if (!Context.CanApplyOptimization (CodeOptimizations.UnusedTypeChecks, method.DeclaringType.Module.Assembly))
						break;

					TypeDefinition? type = Context.Resolve (operand);
					if (type == null)
						return;

					if (type.IsInterface)
						break;

					if (!Annotations.IsInstantiated (type)) {
						_pending_isinst_instr.Add ((type, method.Body, instruction));
						return;
					}

					break;
				}

				ScopeStack.UpdateCurrentScopeInstructionOffset (instruction.Offset);
				MarkType (operand, new DependencyInfo (DependencyKind.InstructionTypeRef, method));
				break;
			}
		}


		protected internal virtual void MarkInterfaceImplementation (InterfaceImplementation iface, MessageOrigin? origin = null, DependencyInfo? reason = null)
		{
			if (Annotations.IsMarked (iface))
				return;
			Annotations.MarkProcessed (iface, reason ?? new DependencyInfo (DependencyKind.InterfaceImplementationOnType, ScopeStack.CurrentScope.Origin.Provider));

			using var localScope = origin.HasValue ? ScopeStack.PushScope (origin.Value) : null;

			// Blame the type that has the interfaceimpl, expecting the type itself to get marked for other reasons.
			MarkCustomAttributes (iface, new DependencyInfo (DependencyKind.CustomAttribute, iface));
			// Blame the interface type on the interfaceimpl itself.
			MarkType (iface.InterfaceType, reason ?? new DependencyInfo (DependencyKind.InterfaceImplementationInterfaceType, iface));
		}

		//
		// Extension point for reflection logic handling customization
		//
		protected internal virtual bool ProcessReflectionDependency (MethodBody body, Instruction instruction)
		{
			return false;
		}

		//
		// Tries to mark additional dependencies used in reflection like calls (e.g. typeof (MyClass).GetField ("fname"))
		//
		protected virtual void MarkReflectionLikeDependencies (MethodIL methodIL, bool requiresReflectionMethodBodyScanner)
		{
			Debug.Assert (!CompilerGeneratedState.IsNestedFunctionOrStateMachineMember (methodIL.Method));
			// requiresReflectionMethodBodyScanner tells us whether the method body itself requires a dataflow scan.

			// If the method body owns any compiler-generated code, we might still need to do a scan of it together with
			// all of the compiler-generated code it owns, so first check any compiler-generated callees.
			if (Context.CompilerGeneratedState.TryGetCompilerGeneratedCalleesForUserMethod (methodIL.Method, out List<IMemberDefinition>? compilerGeneratedCallees)) {
				foreach (var compilerGeneratedCallee in compilerGeneratedCallees) {
					switch (compilerGeneratedCallee) {
					case MethodDefinition nestedFunction:
						if (nestedFunction.Body is MethodBody nestedBody)
							requiresReflectionMethodBodyScanner |= MarkAndCheckRequiresReflectionMethodBodyScanner (Context.GetMethodIL (nestedBody));
						break;
					case TypeDefinition stateMachineType:
						foreach (var method in stateMachineType.Methods) {
							if (method.Body is MethodBody stateMachineBody)
								requiresReflectionMethodBodyScanner |= MarkAndCheckRequiresReflectionMethodBodyScanner (Context.GetMethodIL (stateMachineBody));
						}
						break;
					default:
						throw new InvalidOperationException ();
					}
				}
			}

			if (!requiresReflectionMethodBodyScanner)
				return;

			Debug.Assert (ScopeStack.CurrentScope.Origin.Provider == methodIL.Method);
			var scanner = new ReflectionMethodBodyScanner (Context, this, ScopeStack.CurrentScope.Origin);
			scanner.InterproceduralScan (methodIL);
		}

		protected class AttributeProviderPair
		{
			public AttributeProviderPair (CustomAttribute attribute, ICustomAttributeProvider provider)
			{
				Attribute = attribute;
				Provider = provider;
			}

			public CustomAttribute Attribute { get; private set; }
			public ICustomAttributeProvider Provider { get; private set; }
		}
	}
}