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

compiler.h « jit « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 154cb199b756fd723586efc48a5c14e9845e2411 (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
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                           Compiler                                        XX
XX                                                                           XX
XX  Represents the method data we are currently JIT-compiling.               XX
XX  An instance of this class is created for every method we JIT.            XX
XX  This contains all the info needed for the method. So allocating a        XX
XX  a new instance per method makes it thread-safe.                          XX
XX  It should be used to do all the memory management for the compiler run.  XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

/*****************************************************************************/
#ifndef _COMPILER_H_
#define _COMPILER_H_
/*****************************************************************************/

#include "jit.h"
#include "opcode.h"
#include "varset.h"
#include "jitstd.h"
#include "jithashtable.h"
#include "gentree.h"
#include "debuginfo.h"
#include "lir.h"
#include "block.h"
#include "inline.h"
#include "jiteh.h"
#include "instr.h"
#include "regalloc.h"
#include "sm.h"
#include "cycletimer.h"
#include "blockset.h"
#include "arraystack.h"
#include "hashbv.h"
#include "jitexpandarray.h"
#include "tinyarray.h"
#include "valuenum.h"
#include "jittelemetry.h"
#include "namedintrinsiclist.h"
#ifdef LATE_DISASM
#include "disasm.h"
#endif

#include "codegeninterface.h"
#include "regset.h"
#include "jitgcinfo.h"

#if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
#include "gcdump.h"
#endif

#include "emit.h"

// Forward declaration
template <class T>
inline var_types genActualType(T value);

#include "hwintrinsic.h"
#include "simd.h"
#include "simdashwintrinsic.h"

// This is only used locally in the JIT to indicate that
// a verification block should be inserted
#define SEH_VERIFICATION_EXCEPTION 0xe0564552 // VER

/*****************************************************************************
 *                  Forward declarations
 */

struct InfoHdr;              // defined in GCInfo.h
struct escapeMapping_t;      // defined in fgdiagnostic.cpp
class emitter;               // defined in emit.h
struct ShadowParamVarInfo;   // defined in GSChecks.cpp
struct InitVarDscInfo;       // defined in registerargconvention.h
class FgStack;               // defined in fgbasic.cpp
class Instrumentor;          // defined in fgprofile.cpp
class SpanningTreeVisitor;   // defined in fgprofile.cpp
class CSE_DataFlow;          // defined in OptCSE.cpp
class OptBoolsDsc;           // defined in optimizer.cpp
struct RelopImplicationInfo; // defined in redundantbranchopts.cpp
struct JumpThreadInfo;       // defined in redundantbranchopts.cpp
#ifdef DEBUG
struct IndentStack;
#endif

class Lowering; // defined in lower.h

// The following are defined in this file, Compiler.h

class Compiler;

/*****************************************************************************
 *                  Unwind info
 */

#include "unwind.h"

/*****************************************************************************/

//
// Declare global operator new overloads that use the compiler's arena allocator
//

void* operator new(size_t n, Compiler* context, CompMemKind cmk);
void* operator new[](size_t n, Compiler* context, CompMemKind cmk);

// Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
#include "loopcloning.h"

/*****************************************************************************/

/* This is included here and not earlier as it needs the definition of "CSE"
 * which is defined in the section above */

/*****************************************************************************/

unsigned genLog2(unsigned value);
unsigned genLog2(unsigned __int64 value);

unsigned ReinterpretHexAsDecimal(unsigned in);

/*****************************************************************************/

const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);

#ifdef DEBUG
const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
#endif

//------------------------------------------------------------------------
// HFA info shared by LclVarDsc and CallArgABIInformation
//------------------------------------------------------------------------
inline bool IsHfa(CorInfoHFAElemType kind)
{
    return kind != CORINFO_HFA_ELEM_NONE;
}
inline var_types HfaTypeFromElemKind(CorInfoHFAElemType kind)
{
    switch (kind)
    {
        case CORINFO_HFA_ELEM_FLOAT:
            return TYP_FLOAT;
        case CORINFO_HFA_ELEM_DOUBLE:
            return TYP_DOUBLE;
#ifdef FEATURE_SIMD
        case CORINFO_HFA_ELEM_VECTOR64:
            return TYP_SIMD8;
        case CORINFO_HFA_ELEM_VECTOR128:
            return TYP_SIMD16;
#endif
        case CORINFO_HFA_ELEM_NONE:
            return TYP_UNDEF;
        default:
            assert(!"Invalid HfaElemKind");
            return TYP_UNDEF;
    }
}
inline CorInfoHFAElemType HfaElemKindFromType(var_types type)
{
    switch (type)
    {
        case TYP_FLOAT:
            return CORINFO_HFA_ELEM_FLOAT;
        case TYP_DOUBLE:
            return CORINFO_HFA_ELEM_DOUBLE;
#ifdef FEATURE_SIMD
        case TYP_SIMD8:
            return CORINFO_HFA_ELEM_VECTOR64;
        case TYP_SIMD16:
            return CORINFO_HFA_ELEM_VECTOR128;
#endif
        case TYP_UNDEF:
            return CORINFO_HFA_ELEM_NONE;
        default:
            assert(!"Invalid HFA Type");
            return CORINFO_HFA_ELEM_NONE;
    }
}

// The following holds the Local var info (scope information)
typedef const char* VarName; // Actual ASCII string
struct VarScopeDsc
{
    unsigned vsdVarNum; // (remapped) LclVarDsc number
    unsigned vsdLVnum;  // 'which' in eeGetLVinfo().
                        // Also, it is the index of this entry in the info.compVarScopes array,
                        // which is useful since the array is also accessed via the
                        // compEnterScopeList and compExitScopeList sorted arrays.

    IL_OFFSET vsdLifeBeg; // instr offset of beg of life
    IL_OFFSET vsdLifeEnd; // instr offset of end of life

#ifdef DEBUG
    VarName vsdName; // name of the var
#endif
};

// This class stores information associated with a LclVar SSA definition.
class LclSsaVarDsc
{
    // The basic block where the definition occurs. Definitions of uninitialized variables
    // are considered to occur at the start of the first basic block (fgFirstBB).
    //
    // TODO-Cleanup: In the case of uninitialized variables the block is set to nullptr by
    // SsaBuilder and changed to fgFirstBB during value numbering. It would be useful to
    // investigate and perhaps eliminate this rather unexpected behavior.
    BasicBlock* m_block = nullptr;
    // The GT_ASG node that generates the definition, or nullptr for definitions
    // of uninitialized variables.
    GenTreeOp* m_asg = nullptr;
    // The SSA number associated with the previous definition for partial (GTF_USEASG) defs.
    unsigned m_useDefSsaNum = SsaConfig::RESERVED_SSA_NUM;
    // Number of uses of this SSA def (may be an over-estimate).
    // May not be accurate for for promoted fields.
    unsigned short m_numUses = 0;
    // True if there may be phi args uses of this def
    // May not be accurate for for promoted fields.
    // (false implies all uses are non-phi).
    bool m_hasPhiUse = false;
    // True if there may be uses of the def in a different block.
    // May not be accurate for for promoted fields.
    bool m_hasGlobalUse = false;

public:
    LclSsaVarDsc()
    {
    }

    LclSsaVarDsc(BasicBlock* block) : m_block(block)
    {
    }

    LclSsaVarDsc(BasicBlock* block, GenTreeOp* asg) : m_block(block), m_asg(asg)
    {
        assert((asg == nullptr) || asg->OperIs(GT_ASG));
    }

    BasicBlock* GetBlock() const
    {
        return m_block;
    }

    void SetBlock(BasicBlock* block)
    {
        m_block = block;
    }

    GenTreeOp* GetAssignment() const
    {
        return m_asg;
    }

    void SetAssignment(GenTreeOp* asg)
    {
        assert((asg == nullptr) || asg->OperIs(GT_ASG));
        m_asg = asg;
    }

    unsigned GetUseDefSsaNum() const
    {
        return m_useDefSsaNum;
    }

    void SetUseDefSsaNum(unsigned ssaNum)
    {
        m_useDefSsaNum = ssaNum;
    }

    unsigned GetNumUses() const
    {
        return m_numUses;
    }

    void AddUse(BasicBlock* block)
    {
        if (block != m_block)
        {
            m_hasGlobalUse = true;
        }

        if (m_numUses < USHRT_MAX)
        {
            m_numUses++;
        }
    }

    void AddPhiUse(BasicBlock* block)
    {
        m_hasPhiUse = true;
        AddUse(block);
    }

    bool HasPhiUse() const
    {
        return m_hasPhiUse;
    }

    bool HasGlobalUse() const
    {
        return m_hasGlobalUse;
    }

    ValueNumPair m_vnPair;
};

// This class stores information associated with a memory SSA definition.
class SsaMemDef
{
public:
    ValueNumPair m_vnPair;
};

//------------------------------------------------------------------------
// SsaDefArray: A resizable array of SSA definitions.
//
// Unlike an ordinary resizable array implementation, this allows only element
// addition (by calling AllocSsaNum) and has special handling for RESERVED_SSA_NUM
// (basically it's a 1-based array). The array doesn't impose any particular
// requirements on the elements it stores and AllocSsaNum forwards its arguments
// to the array element constructor, this way the array supports both LclSsaVarDsc
// and SsaMemDef elements.
//
template <typename T>
class SsaDefArray
{
    T*       m_array;
    unsigned m_arraySize;
    unsigned m_count;

    static_assert_no_msg(SsaConfig::RESERVED_SSA_NUM == 0);
    static_assert_no_msg(SsaConfig::FIRST_SSA_NUM == 1);

    // Get the minimum valid SSA number.
    unsigned GetMinSsaNum() const
    {
        return SsaConfig::FIRST_SSA_NUM;
    }

    // Increase (double) the size of the array.
    void GrowArray(CompAllocator alloc)
    {
        unsigned oldSize = m_arraySize;
        unsigned newSize = max(2, oldSize * 2);

        T* newArray = alloc.allocate<T>(newSize);

        for (unsigned i = 0; i < oldSize; i++)
        {
            newArray[i] = m_array[i];
        }

        m_array     = newArray;
        m_arraySize = newSize;
    }

public:
    // Construct an empty SsaDefArray.
    SsaDefArray() : m_array(nullptr), m_arraySize(0), m_count(0)
    {
    }

    // Reset the array (used only if the SSA form is reconstructed).
    void Reset()
    {
        m_count = 0;
    }

    // Allocate a new SSA number (starting with SsaConfig::FIRST_SSA_NUM).
    template <class... Args>
    unsigned AllocSsaNum(CompAllocator alloc, Args&&... args)
    {
        if (m_count == m_arraySize)
        {
            GrowArray(alloc);
        }

        unsigned ssaNum    = GetMinSsaNum() + m_count;
        m_array[m_count++] = T(std::forward<Args>(args)...);

        // Ensure that the first SSA number we allocate is SsaConfig::FIRST_SSA_NUM
        assert((ssaNum == SsaConfig::FIRST_SSA_NUM) || (m_count > 1));

        return ssaNum;
    }

    // Get the number of SSA definitions in the array.
    unsigned GetCount() const
    {
        return m_count;
    }

    // Get a pointer to the SSA definition at the specified index.
    T* GetSsaDefByIndex(unsigned index) const
    {
        assert(index < m_count);
        return &m_array[index];
    }

    // Check if the specified SSA number is valid.
    bool IsValidSsaNum(unsigned ssaNum) const
    {
        return (GetMinSsaNum() <= ssaNum) && (ssaNum < (GetMinSsaNum() + m_count));
    }

    // Get a pointer to the SSA definition associated with the specified SSA number.
    T* GetSsaDef(unsigned ssaNum) const
    {
        assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
        return GetSsaDefByIndex(ssaNum - GetMinSsaNum());
    }

    // Get an SSA number associated with the specified SSA def (that must be in this array).
    unsigned GetSsaNum(T* ssaDef) const
    {
        assert((m_array <= ssaDef) && (ssaDef < &m_array[m_count]));
        return GetMinSsaNum() + static_cast<unsigned>(ssaDef - &m_array[0]);
    }
};

enum RefCountState
{
    RCS_INVALID, // not valid to get/set ref counts
    RCS_EARLY,   // early counts for struct promotion and struct passing
    RCS_NORMAL,  // normal ref counts (from lvaMarkRefs onward)
};

#ifdef DEBUG
// Reasons why we can't enregister a local.
enum class DoNotEnregisterReason
{
    None,
    AddrExposed,      // the address of this local is exposed.
    DontEnregStructs, // struct enregistration is disabled.
    NotRegSizeStruct, // the struct size does not much any register size, usually the struct size is too big.
    LocalField,       // the local is accessed with LCL_FLD, note we can do it not only for struct locals.
    VMNeedsStackAddr,
    LiveInOutOfHandler, // the local is alive in and out of exception handler and not single def.
    BlockOp,            // Is read or written via a block operation.
    IsStructArg,        // Is a struct passed as an argument in a way that requires a stack location.
    DepField,           // It is a field of a dependently promoted struct
    NoRegVars,          // opts.compFlags & CLFLG_REGVAR is not set
    MinOptsGC,          // It is a GC Ref and we are compiling MinOpts
#if !defined(TARGET_64BIT)
    LongParamField, // It is a decomposed field of a long parameter.
#endif
#ifdef JIT32_GCENCODER
    PinningRef,
#endif
    LclAddrNode, // the local is accessed with LCL_ADDR_VAR/FLD.
    CastTakesAddr,
    StoreBlkSrc,          // the local is used as STORE_BLK source.
    OneAsgRetyping,       // fgMorphOneAsgBlockOp prevents this local from being enregister.
    SwizzleArg,           // the local is passed using LCL_FLD as another type.
    BlockOpRet,           // the struct is returned and it promoted or there is a cast.
    ReturnSpCheck,        // the local is used to do SP check on return from function
    CallSpCheck,          // the local is used to do SP check on every call
    SimdUserForcesDep,    // a promoted struct was used by a SIMD/HWI node; it must be dependently promoted
    HiddenBufferStructArg // the argument is a hidden return buffer passed to a method.
};

enum class AddressExposedReason
{
    NONE,
    PARENT_EXPOSED,   // This is a promoted field but the parent is exposed.
    TOO_CONSERVATIVE, // Were marked as exposed to be conservative, fix these places.
    ESCAPE_ADDRESS,   // The address is escaping, for example, passed as call argument.
    WIDE_INDIR,       // We access via indirection with wider type.
    OSR_EXPOSED,      // It was exposed in the original method, osr has to repeat it.
    STRESS_LCL_FLD,   // Stress mode replaces localVar with localFld and makes them addrExposed.
    DISPATCH_RET_BUF  // Caller return buffer dispatch.
};

#endif // DEBUG

class LclVarDsc
{
public:
    // The constructor. Most things can just be zero'ed.
    //
    // Initialize the ArgRegs to REG_STK.
    // Morph will update if this local is passed in a register.
    LclVarDsc()
        : _lvArgReg(REG_STK)
        ,
#if FEATURE_MULTIREG_ARGS
        _lvOtherArgReg(REG_STK)
        ,
#endif // FEATURE_MULTIREG_ARGS
        lvClassHnd(NO_CLASS_HANDLE)
        , lvRefBlks(BlockSetOps::UninitVal())
        , lvPerSsaData()
    {
    }

    // note this only packs because var_types is a typedef of unsigned char
    var_types lvType : 5; // TYP_INT/LONG/FLOAT/DOUBLE/REF

    unsigned char lvIsParam : 1;           // is this a parameter?
    unsigned char lvIsRegArg : 1;          // is this an argument that was passed by register?
    unsigned char lvFramePointerBased : 1; // 0 = off of REG_SPBASE (e.g., ESP), 1 = off of REG_FPBASE (e.g., EBP)

    unsigned char lvOnFrame : 1;  // (part of) the variable lives on the frame
    unsigned char lvRegister : 1; // assigned to live in a register? For RyuJIT backend, this is only set if the
                                  // variable is in the same register for the entire function.
    unsigned char lvTracked : 1;  // is this a tracked variable?
    bool          lvTrackedNonStruct()
    {
        return lvTracked && lvType != TYP_STRUCT;
    }
    unsigned char lvPinned : 1; // is this a pinned variable?

    unsigned char lvMustInit : 1; // must be initialized

private:
    bool m_addrExposed : 1; // The address of this variable is "exposed" -- passed as an argument, stored in a
                            // global location, etc.
                            // We cannot reason reliably about the value of the variable.
public:
    unsigned char lvDoNotEnregister : 1; // Do not enregister this variable.
    unsigned char lvFieldAccessed : 1;   // The var is a struct local, and a field of the variable is accessed.  Affects
                                         // struct promotion.
    unsigned char lvLiveInOutOfHndlr : 1; // The variable is live in or out of an exception handler, and therefore must
                                          // be on the stack (at least at those boundaries.)

    unsigned char lvInSsa : 1;       // The variable is in SSA form (set by SsaBuilder)
    unsigned char lvIsCSE : 1;       // Indicates if this LclVar is a CSE variable.
    unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.

    unsigned char lvHasILStoreOp : 1;         // there is at least one STLOC or STARG on this local
    unsigned char lvHasMultipleILStoreOp : 1; // there is more than one STLOC on this local

    unsigned char lvIsTemp : 1; // Short-lifetime compiler temp

#if FEATURE_IMPLICIT_BYREFS
    unsigned char lvIsImplicitByRef : 1; // Set if the argument is an implicit byref.
#endif                                   // FEATURE_IMPLICIT_BYREFS

#if defined(TARGET_LOONGARCH64)
    unsigned char lvIs4Field1 : 1; // Set if the 1st field is int or float within struct for LA-ABI64.
    unsigned char lvIs4Field2 : 1; // Set if the 2nd field is int or float within struct for LA-ABI64.
    unsigned char lvIsSplit : 1;   // Set if the argument is splited.
#endif                             // defined(TARGET_LOONGARCH64)

    unsigned char lvIsBoolean : 1; // set if variable is boolean
    unsigned char lvSingleDef : 1; // variable has a single def
                                   // before lvaMarkLocalVars: identifies ref type locals that can get type updates
                                   // after lvaMarkLocalVars: identifies locals that are suitable for optAddCopies

    unsigned char lvSingleDefRegCandidate : 1; // variable has a single def and hence is a register candidate
                                               // Currently, this is only used to decide if an EH variable can be
                                               // a register candidate or not.

    unsigned char lvDisqualifySingleDefRegCandidate : 1; // tracks variable that are disqualified from register
                                                         // candidancy

    unsigned char lvSpillAtSingleDef : 1; // variable has a single def (as determined by LSRA interval scan)
                                          // and is spilled making it candidate to spill right after the
                                          // first (and only) definition.
                                          // Note: We cannot reuse lvSingleDefRegCandidate because it is set
                                          // in earlier phase and the information might not be appropriate
                                          // in LSRA.

    unsigned char lvDisqualify : 1;   // variable is no longer OK for add copy optimization
    unsigned char lvVolatileHint : 1; // hint for AssertionProp

#ifndef TARGET_64BIT
    unsigned char lvStructDoubleAlign : 1; // Must we double align this struct?
#endif                                     // !TARGET_64BIT
#ifdef TARGET_64BIT
    unsigned char lvQuirkToLong : 1; // Quirk to allocate this LclVar as a 64-bit long
#endif
#ifdef DEBUG
    unsigned char lvKeepType : 1;       // Don't change the type of this variable
    unsigned char lvNoLclFldStress : 1; // Can't apply local field stress on this one
#endif
    unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
                               // checks)
    unsigned char lvIsUnsafeBuffer : 1; // Does this contain an unsafe buffer requiring buffer overflow security checks?
    unsigned char lvPromoted : 1; // True when this local is a promoted struct, a normed struct, or a "split" long on a
                                  // 32-bit target.  For implicit byref parameters, this gets hijacked between
                                  // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to indicate whether
                                  // references to the arg are being rewritten as references to a promoted shadow local.
    unsigned char lvIsStructField : 1; // Is this local var a field of a promoted struct local?
    unsigned char lvContainsHoles : 1; // True when we have a promoted struct that contains holes
    unsigned char lvCustomLayout : 1;  // True when this struct has "CustomLayout"

    unsigned char lvIsMultiRegArg : 1; // true if this is a multireg LclVar struct used in an argument context
    unsigned char lvIsMultiRegRet : 1; // true if this is a multireg LclVar struct assigned from a multireg call

#ifdef DEBUG
    unsigned char lvHiddenBufferStructArg : 1; // True when this struct (or its field) are passed as hidden buffer
                                               // pointer.
#endif

#ifdef FEATURE_HFA_FIELDS_PRESENT
    CorInfoHFAElemType _lvHfaElemKind : 3; // What kind of an HFA this is (CORINFO_HFA_ELEM_NONE if it is not an HFA).
#endif                                     // FEATURE_HFA_FIELDS_PRESENT

#ifdef DEBUG
    // TODO-Cleanup: See the note on lvSize() - this flag is only in use by asserts that are checking for struct
    // types, and is needed because of cases where TYP_STRUCT is bashed to an integral type.
    // Consider cleaning this up so this workaround is not required.
    unsigned char lvUnusedStruct : 1; // All references to this promoted struct are through its field locals.
                                      // I.e. there is no longer any reference to the struct directly.
                                      // In this case we can simply remove this struct local.

    unsigned char lvUndoneStructPromotion : 1; // The struct promotion was undone and hence there should be no
                                               // reference to the fields of this struct.
#endif

    unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes

#ifdef FEATURE_SIMD
    // Note that both SIMD vector args and locals are marked as lvSIMDType = true, but the
    // type of an arg node is TYP_BYREF and a local node is TYP_SIMD*.
    unsigned char lvSIMDType : 1;            // This is a SIMD struct
    unsigned char lvUsedInSIMDIntrinsic : 1; // This tells lclvar is used for simd intrinsic
    unsigned char lvSimdBaseJitType : 5;     // Note: this only packs because CorInfoType has less than 32 entries

    CorInfoType GetSimdBaseJitType() const
    {
        return (CorInfoType)lvSimdBaseJitType;
    }

    void SetSimdBaseJitType(CorInfoType simdBaseJitType)
    {
        assert(simdBaseJitType < (1 << 5));
        lvSimdBaseJitType = (unsigned char)simdBaseJitType;
    }

    var_types GetSimdBaseType() const;
#endif                             // FEATURE_SIMD
    unsigned char lvRegStruct : 1; // This is a reg-sized non-field-addressed struct.

    unsigned char lvClassIsExact : 1; // lvClassHandle is the exact type

#ifdef DEBUG
    unsigned char lvClassInfoUpdated : 1; // true if this var has updated class handle or exactness
#endif

    unsigned char lvImplicitlyReferenced : 1; // true if there are non-IR references to this local (prolog, epilog, gc,
                                              // eh)

    unsigned char lvSuppressedZeroInit : 1; // local needs zero init if we transform tail call to loop

    unsigned char lvHasExplicitInit : 1; // The local is explicitly initialized and doesn't need zero initialization in
                                         // the prolog. If the local has gc pointers, there are no gc-safe points
                                         // between the prolog and the explicit initialization.

    unsigned char lvIsOSRLocal : 1; // Root method local in an OSR method. Any stack home will be on the Tier0 frame.
                                    // Initial value will be defined by Tier0. Requires special handing in prolog.

    union {
        unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
                                  // local.  For implicit byref parameters, this gets hijacked between
                                  // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to point to the
                                  // struct local created to model the parameter's struct promotion, if any.
        unsigned lvParentLcl; // The index of the local var representing the parent (i.e. the promoted struct local).
                              // Valid on promoted struct local fields.
    };

    unsigned char lvFieldCnt; //  Number of fields in the promoted VarDsc.
    unsigned char lvFldOffset;
    unsigned char lvFldOrdinal;

#ifdef DEBUG
    unsigned char lvSingleDefDisqualifyReason = 'H';
#endif

    unsigned char lvAllDefsAreNoGc : 1; // For pinned locals: true if all defs of this local are no-gc

#if FEATURE_MULTIREG_ARGS
    regNumber lvRegNumForSlot(unsigned slotNum)
    {
        if (slotNum == 0)
        {
            return (regNumber)_lvArgReg;
        }
        else if (slotNum == 1)
        {
            return GetOtherArgReg();
        }
        else
        {
            assert(false && "Invalid slotNum!");
        }

        unreached();
    }
#endif // FEATURE_MULTIREG_ARGS

    CorInfoHFAElemType GetLvHfaElemKind() const
    {
#ifdef FEATURE_HFA_FIELDS_PRESENT
        return _lvHfaElemKind;
#else
        NOWAY_MSG("GetLvHfaElemKind");
        return CORINFO_HFA_ELEM_NONE;
#endif // FEATURE_HFA_FIELDS_PRESENT
    }

    void SetLvHfaElemKind(CorInfoHFAElemType elemKind)
    {
#ifdef FEATURE_HFA_FIELDS_PRESENT
        _lvHfaElemKind = elemKind;
#else
        NOWAY_MSG("SetLvHfaElemKind");
#endif // FEATURE_HFA_FIELDS_PRESENT
    }

    bool lvIsHfa() const
    {
        if (GlobalJitOptions::compFeatureHfa)
        {
            return IsHfa(GetLvHfaElemKind());
        }
        else
        {
            return false;
        }
    }

    bool lvIsHfaRegArg() const
    {
        if (GlobalJitOptions::compFeatureHfa)
        {
            return lvIsRegArg && lvIsHfa();
        }
        else
        {
            return false;
        }
    }

    //------------------------------------------------------------------------------
    // lvHfaSlots: Get the number of slots used by an HFA local
    //
    // Return Value:
    //    On Arm64 - Returns 1-4 indicating the number of register slots used by the HFA
    //    On Arm32 - Returns the total number of single FP register slots used by the HFA, max is 8
    //
    unsigned lvHfaSlots() const
    {
        assert(lvIsHfa());
        assert(varTypeIsStruct(lvType));
        unsigned slots = 0;
#ifdef TARGET_ARM
        slots = lvExactSize / sizeof(float);
        assert(slots <= 8);
#elif defined(TARGET_ARM64)
        switch (GetLvHfaElemKind())
        {
            case CORINFO_HFA_ELEM_NONE:
                assert(!"lvHfaSlots called for non-HFA");
                break;
            case CORINFO_HFA_ELEM_FLOAT:
                assert((lvExactSize % 4) == 0);
                slots = lvExactSize >> 2;
                break;
            case CORINFO_HFA_ELEM_DOUBLE:
            case CORINFO_HFA_ELEM_VECTOR64:
                assert((lvExactSize % 8) == 0);
                slots = lvExactSize >> 3;
                break;
            case CORINFO_HFA_ELEM_VECTOR128:
                assert((lvExactSize % 16) == 0);
                slots = lvExactSize >> 4;
                break;
            default:
                unreached();
        }
        assert(slots <= 4);
#endif //  TARGET_ARM64
        return slots;
    }

    // lvIsMultiRegArgOrRet()
    //     returns true if this is a multireg LclVar struct used in an argument context
    //               or if this is a multireg LclVar struct assigned from a multireg call
    bool lvIsMultiRegArgOrRet()
    {
        return lvIsMultiRegArg || lvIsMultiRegRet;
    }

#if defined(DEBUG)
private:
    DoNotEnregisterReason m_doNotEnregReason;

    AddressExposedReason m_addrExposedReason;

public:
    void SetDoNotEnregReason(DoNotEnregisterReason reason)
    {
        m_doNotEnregReason = reason;
    }

    DoNotEnregisterReason GetDoNotEnregReason() const
    {
        return m_doNotEnregReason;
    }

    AddressExposedReason GetAddrExposedReason() const
    {
        return m_addrExposedReason;
    }
#endif // DEBUG

public:
    void SetAddressExposed(bool value DEBUGARG(AddressExposedReason reason))
    {
        m_addrExposed = value;
        INDEBUG(m_addrExposedReason = reason);
    }

    void CleanAddressExposed()
    {
        m_addrExposed = false;
    }

    bool IsAddressExposed() const
    {
        return m_addrExposed;
    }

#ifdef DEBUG
    void SetHiddenBufferStructArg(char value)
    {
        lvHiddenBufferStructArg = value;
    }

    bool IsHiddenBufferStructArg() const
    {
        return lvHiddenBufferStructArg;
    }
#endif

private:
    regNumberSmall _lvRegNum; // Used to store the register this variable is in (or, the low register of a
                              // register pair). It is set during codegen any time the
                              // variable is enregistered (lvRegister is only set
                              // to non-zero if the variable gets the same register assignment for its entire
                              // lifetime).
#if !defined(TARGET_64BIT)
    regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
#endif                          // !defined(TARGET_64BIT)

    regNumberSmall _lvArgReg; // The (first) register in which this argument is passed.

#if FEATURE_MULTIREG_ARGS
    regNumberSmall _lvOtherArgReg; // Used for the second part of the struct passed in a register.
                                   // Note this is defined but not used by ARM32
#endif                             // FEATURE_MULTIREG_ARGS

    regNumberSmall _lvArgInitReg; // the register into which the argument is moved at entry

public:
    // The register number is stored in a small format (8 bits), but the getters return and the setters take
    // a full-size (unsigned) format, to localize the casts here.

    /////////////////////

    regNumber GetRegNum() const
    {
        return (regNumber)_lvRegNum;
    }

    void SetRegNum(regNumber reg)
    {
        _lvRegNum = (regNumberSmall)reg;
        assert(_lvRegNum == reg);
    }

/////////////////////

#if defined(TARGET_64BIT)

    regNumber GetOtherReg() const
    {
        assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
                                       // "unreachable code" warnings
        return REG_NA;
    }

    void SetOtherReg(regNumber reg)
    {
        assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
                                       // "unreachable code" warnings
    }
#else  // !TARGET_64BIT

    regNumber GetOtherReg() const
    {
        return (regNumber)_lvOtherReg;
    }

    void SetOtherReg(regNumber reg)
    {
        _lvOtherReg = (regNumberSmall)reg;
        assert(_lvOtherReg == reg);
    }
#endif // !TARGET_64BIT

    /////////////////////

    regNumber GetArgReg() const
    {
        return (regNumber)_lvArgReg;
    }

    void SetArgReg(regNumber reg)
    {
        _lvArgReg = (regNumberSmall)reg;
        assert(_lvArgReg == reg);
    }

#if FEATURE_MULTIREG_ARGS

    regNumber GetOtherArgReg() const
    {
        return (regNumber)_lvOtherArgReg;
    }

    void SetOtherArgReg(regNumber reg)
    {
        _lvOtherArgReg = (regNumberSmall)reg;
        assert(_lvOtherArgReg == reg);
    }
#endif // FEATURE_MULTIREG_ARGS

#ifdef FEATURE_SIMD
    // Is this is a SIMD struct?
    bool lvIsSIMDType() const
    {
        return lvSIMDType;
    }

    // Is this is a SIMD struct which is used for SIMD intrinsic?
    bool lvIsUsedInSIMDIntrinsic() const
    {
        return lvUsedInSIMDIntrinsic;
    }
#else
    // If feature_simd not enabled, return false
    bool lvIsSIMDType() const
    {
        return false;
    }
    bool lvIsUsedInSIMDIntrinsic() const
    {
        return false;
    }
#endif

    /////////////////////

    regNumber GetArgInitReg() const
    {
        return (regNumber)_lvArgInitReg;
    }

    void SetArgInitReg(regNumber reg)
    {
        _lvArgInitReg = (regNumberSmall)reg;
        assert(_lvArgInitReg == reg);
    }

    /////////////////////

    bool lvIsRegCandidate() const
    {
        return lvLRACandidate != 0;
    }

    bool lvIsInReg() const
    {
        return lvIsRegCandidate() && (GetRegNum() != REG_STK);
    }

    regMaskTP lvRegMask() const
    {
        regMaskTP regMask = RBM_NONE;
        if (varTypeUsesFloatReg(TypeGet()))
        {
            if (GetRegNum() != REG_STK)
            {
                regMask = genRegMaskFloat(GetRegNum(), TypeGet());
            }
        }
        else
        {
            if (GetRegNum() != REG_STK)
            {
                regMask = genRegMask(GetRegNum());
            }
        }
        return regMask;
    }

    unsigned short lvVarIndex; // variable tracking index

private:
    unsigned short m_lvRefCnt; // unweighted (real) reference count.  For implicit by reference
                               // parameters, this gets hijacked from fgResetImplicitByRefRefCount
                               // through fgMarkDemotedImplicitByRefArgs, to provide a static
                               // appearance count (computed during address-exposed analysis)
                               // that fgMakeOutgoingStructArgCopy consults during global morph
                               // to determine if eliding its copy is legal.

    weight_t m_lvRefCntWtd; // weighted reference count

public:
    unsigned short lvRefCnt(RefCountState state = RCS_NORMAL) const;
    void incLvRefCnt(unsigned short delta, RefCountState state = RCS_NORMAL);
    void setLvRefCnt(unsigned short newValue, RefCountState state = RCS_NORMAL);

    weight_t lvRefCntWtd(RefCountState state = RCS_NORMAL) const;
    void incLvRefCntWtd(weight_t delta, RefCountState state = RCS_NORMAL);
    void setLvRefCntWtd(weight_t newValue, RefCountState state = RCS_NORMAL);

private:
    int lvStkOffs; // stack offset of home in bytes.

public:
    int GetStackOffset() const
    {
        return lvStkOffs;
    }

    void SetStackOffset(int offset)
    {
        lvStkOffs = offset;
    }

    unsigned lvExactSize; // (exact) size of a STRUCT/SIMD/BLK local in bytes.

    unsigned lvSize() const;

    size_t lvArgStackSize() const;

    unsigned lvSlotNum; // original slot # (if remapped)

    // class handle for the local or null if not known or not a class,
    // for a struct handle use `GetStructHnd()`.
    CORINFO_CLASS_HANDLE lvClassHnd;

    // Get class handle for a struct local or implicitByRef struct local.
    CORINFO_CLASS_HANDLE GetStructHnd() const
    {
#ifdef FEATURE_SIMD
        if (lvSIMDType && (m_layout == nullptr))
        {
            return NO_CLASS_HANDLE;
        }
#endif

        CORINFO_CLASS_HANDLE structHnd = GetLayout()->GetClassHandle();
        assert(structHnd != NO_CLASS_HANDLE);
        return structHnd;
    }

private:
    ClassLayout* m_layout; // layout info for structs

public:
    BlockSet   lvRefBlks;          // Set of blocks that contain refs
    Statement* lvDefStmt;          // Pointer to the statement with the single definition
    void       lvaDisqualifyVar(); // Call to disqualify a local variable from use in optAddCopies

    var_types TypeGet() const
    {
        return (var_types)lvType;
    }
    bool lvStackAligned() const
    {
        assert(lvIsStructField);
        return ((lvFldOffset % TARGET_POINTER_SIZE) == 0);
    }
    bool lvNormalizeOnLoad() const
    {
        return varTypeIsSmall(TypeGet()) &&
               // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
               (lvIsParam || m_addrExposed || lvIsStructField);
    }

    bool lvNormalizeOnStore() const
    {
        return varTypeIsSmall(TypeGet()) &&
               // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
               !(lvIsParam || m_addrExposed || lvIsStructField);
    }

    void incRefCnts(weight_t weight, Compiler* pComp, RefCountState state = RCS_NORMAL, bool propagate = true);

    var_types GetHfaType() const
    {
        if (GlobalJitOptions::compFeatureHfa)
        {
            assert(lvIsHfa());
            return HfaTypeFromElemKind(GetLvHfaElemKind());
        }
        else
        {
            return TYP_UNDEF;
        }
    }

    void SetHfaType(var_types type)
    {
        if (GlobalJitOptions::compFeatureHfa)
        {
            CorInfoHFAElemType elemKind = HfaElemKindFromType(type);
            SetLvHfaElemKind(elemKind);
            // Ensure we've allocated enough bits.
            assert(GetLvHfaElemKind() == elemKind);
        }
    }

    // Returns true if this variable contains GC pointers (including being a GC pointer itself).
    bool HasGCPtr() const
    {
        return varTypeIsGC(lvType) || ((lvType == TYP_STRUCT) && m_layout->HasGCPtr());
    }

    // Returns the layout of a struct variable or implicit byref.
    ClassLayout* GetLayout() const
    {
#if FEATURE_IMPLICIT_BYREFS
        assert(varTypeIsStruct(TypeGet()) || (lvIsImplicitByRef && (TypeGet() == TYP_BYREF)));
#else
        assert(varTypeIsStruct(TypeGet()));
#endif
        return m_layout;
    }

    // Sets the layout of a struct variable.
    void SetLayout(ClassLayout* layout)
    {
        assert(varTypeIsStruct(lvType));
        assert((m_layout == nullptr) || ClassLayout::AreCompatible(m_layout, layout));
        m_layout = layout;
    }

    SsaDefArray<LclSsaVarDsc> lvPerSsaData;

    // Returns the address of the per-Ssa data for the given ssaNum (which is required
    // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
    // not an SSA variable).
    LclSsaVarDsc* GetPerSsaData(unsigned ssaNum) const
    {
        return lvPerSsaData.GetSsaDef(ssaNum);
    }

    // Returns the SSA number for "ssaDef". Requires "ssaDef" to be a valid definition
    // of this variable.
    unsigned GetSsaNumForSsaDef(LclSsaVarDsc* ssaDef)
    {
        return lvPerSsaData.GetSsaNum(ssaDef);
    }

    var_types GetRegisterType(const GenTreeLclVarCommon* tree) const;

    var_types GetRegisterType() const;

    var_types GetStackSlotHomeType() const;

    bool IsEnregisterableType() const
    {
        return GetRegisterType() != TYP_UNDEF;
    }

    bool IsEnregisterableLcl() const
    {
        if (lvDoNotEnregister)
        {
            return false;
        }
        return IsEnregisterableType();
    }

    //-----------------------------------------------------------------------------
    //  IsAlwaysAliveInMemory: Determines if this variable's value is always
    //     up-to-date on stack. This is possible if this is an EH-var or
    //     we decided to spill after single-def.
    //
    bool IsAlwaysAliveInMemory() const
    {
        return lvLiveInOutOfHndlr || lvSpillAtSingleDef;
    }

    bool CanBeReplacedWithItsField(Compiler* comp) const;

#ifdef DEBUG
public:
    const char* lvReason;

    void PrintVarReg() const
    {
        printf("%s", getRegName(GetRegNum()));
    }
#endif // DEBUG

}; // class LclVarDsc

enum class SymbolicIntegerValue : int32_t
{
    LongMin,
    IntMin,
    ShortMin,
    ByteMin,
    Zero,
    One,
    ByteMax,
    UByteMax,
    ShortMax,
    UShortMax,
    ArrayLenMax,
    IntMax,
    UIntMax,
    LongMax,
};

inline constexpr bool operator>(SymbolicIntegerValue left, SymbolicIntegerValue right)
{
    return static_cast<int32_t>(left) > static_cast<int32_t>(right);
}

inline constexpr bool operator>=(SymbolicIntegerValue left, SymbolicIntegerValue right)
{
    return static_cast<int32_t>(left) >= static_cast<int32_t>(right);
}

inline constexpr bool operator<(SymbolicIntegerValue left, SymbolicIntegerValue right)
{
    return static_cast<int32_t>(left) < static_cast<int32_t>(right);
}

inline constexpr bool operator<=(SymbolicIntegerValue left, SymbolicIntegerValue right)
{
    return static_cast<int32_t>(left) <= static_cast<int32_t>(right);
}

// Represents an integral range useful for reasoning about integral casts.
// It uses a symbolic representation for lower and upper bounds so
// that it can efficiently handle integers of all sizes on all hosts.
//
// Note that the ranges represented by this class are **always** in the
// "signed" domain. This is so that if we know the range a node produces, it
// can be trivially used to determine if a cast above the node does or does not
// overflow, which requires that the interpretation of integers be the same both
// for the "input" and "output". We choose signed interpretation here because it
// produces nice continuous ranges and because IR uses sign-extension for constants.
//
// Some examples of how ranges are computed for casts:
// 1. CAST_OVF(ubyte <- uint): does not overflow for [0..UBYTE_MAX], produces the
//    same range - all casts that do not change the representation, i. e. have the same
//    "actual" input and output type, have the same "input" and "output" range.
// 2. CAST_OVF(ulong <- uint): never overflows => the "input" range is [INT_MIN..INT_MAX]
//    (aka all possible 32 bit integers). Produces [0..UINT_MAX] (aka all possible 32
//    bit integers zero-extended to 64 bits).
// 3. CAST_OVF(int <- uint): overflows for inputs larger than INT_MAX <=> less than 0
//    when interpreting as signed => the "input" range is [0..INT_MAX], the same range
//    being the produced one as the node does not change the width of the integer.
//
class IntegralRange
{
private:
    SymbolicIntegerValue m_lowerBound;
    SymbolicIntegerValue m_upperBound;

public:
    IntegralRange() = default;

    IntegralRange(SymbolicIntegerValue lowerBound, SymbolicIntegerValue upperBound)
        : m_lowerBound(lowerBound), m_upperBound(upperBound)
    {
        assert(lowerBound <= upperBound);
    }

    SymbolicIntegerValue GetLowerBound()
    {
        return m_lowerBound;
    }

    SymbolicIntegerValue GetUpperBound()
    {
        return m_upperBound;
    }

    bool Contains(int64_t value) const;

    bool Contains(IntegralRange other) const
    {
        return (m_lowerBound <= other.m_lowerBound) && (other.m_upperBound <= m_upperBound);
    }

    bool IsPositive()
    {
        return m_lowerBound >= SymbolicIntegerValue::Zero;
    }

    bool Equals(IntegralRange other) const
    {
        return (m_lowerBound == other.m_lowerBound) && (m_upperBound == other.m_upperBound);
    }

    static int64_t SymbolicToRealValue(SymbolicIntegerValue value);
    static SymbolicIntegerValue LowerBoundForType(var_types type);
    static SymbolicIntegerValue UpperBoundForType(var_types type);

    static IntegralRange ForType(var_types type)
    {
        return {LowerBoundForType(type), UpperBoundForType(type)};
    }

    static IntegralRange ForNode(GenTree* node, Compiler* compiler);
    static IntegralRange ForCastInput(GenTreeCast* cast);
    static IntegralRange ForCastOutput(GenTreeCast* cast);
    static IntegralRange Union(IntegralRange range1, IntegralRange range2);

#ifdef DEBUG
    static void Print(IntegralRange range);
#endif // DEBUG
};

/*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                           TempsInfo                                       XX
XX                                                                           XX
XX  The temporary lclVars allocated by the compiler for code generation      XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

/*****************************************************************************
 *
 *  The following keeps track of temporaries allocated in the stack frame
 *  during code-generation (after register allocation). These spill-temps are
 *  only used if we run out of registers while evaluating a tree.
 *
 *  These are different from the more common temps allocated by lvaGrabTemp().
 */

class TempDsc
{
public:
    TempDsc* tdNext;

private:
    int tdOffs;
#ifdef DEBUG
    static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
#endif                                             // DEBUG

    int       tdNum;
    BYTE      tdSize;
    var_types tdType;

public:
    TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
    {
#ifdef DEBUG
        // temps must have a negative number (so they have a different number from all local variables)
        assert(tdNum < 0);
        tdOffs = BAD_TEMP_OFFSET;
#endif // DEBUG
        if (tdNum != _tdNum)
        {
            IMPL_LIMITATION("too many spill temps");
        }
    }

#ifdef DEBUG
    bool tdLegalOffset() const
    {
        return tdOffs != BAD_TEMP_OFFSET;
    }
#endif // DEBUG

    int tdTempOffs() const
    {
        assert(tdLegalOffset());
        return tdOffs;
    }
    void tdSetTempOffs(int offs)
    {
        tdOffs = offs;
        assert(tdLegalOffset());
    }
    void tdAdjustTempOffs(int offs)
    {
        tdOffs += offs;
        assert(tdLegalOffset());
    }

    int tdTempNum() const
    {
        assert(tdNum < 0);
        return tdNum;
    }
    unsigned tdTempSize() const
    {
        return tdSize;
    }
    var_types tdTempType() const
    {
        return tdType;
    }
};

// Specify compiler data that a phase might modify
enum class PhaseStatus : unsigned
{
    MODIFIED_NOTHING,    // Phase did not make any changes that warrant running post-phase checks or dumping
                         // the main jit data strutures.
    MODIFIED_EVERYTHING, // Phase made changes that warrant running post-phase checks or dumping
                         // the main jit data strutures.
};

// interface to hide linearscan implementation from rest of compiler
class LinearScanInterface
{
public:
    virtual PhaseStatus doLinearScan()                         = 0;
    virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
    virtual bool willEnregisterLocalVars() const               = 0;
#if TRACK_LSRA_STATS
    virtual void dumpLsraStatsCsv(FILE* file)     = 0;
    virtual void dumpLsraStatsSummary(FILE* file) = 0;
#endif // TRACK_LSRA_STATS
};

LinearScanInterface* getLinearScanAllocator(Compiler* comp);

// This enumeration names the phases into which we divide compilation.  The phases should completely
// partition a compilation.
enum Phases
{
#define CompPhaseNameMacro(enum_nm, string_nm, hasChildren, parent, measureIR) enum_nm,
#include "compphases.h"
    PHASE_NUMBER_OF
};

extern const char* PhaseNames[];
extern const char* PhaseEnums[];

// Specify which checks should be run after each phase
//
enum class PhaseChecks
{
    CHECK_NONE,
    CHECK_ALL
};

// Specify which dumps should be run after each phase
//
enum class PhaseDumps
{
    DUMP_NONE,
    DUMP_ALL
};

// The following enum provides a simple 1:1 mapping to CLR API's
enum API_ICorJitInfo_Names
{
#define DEF_CLR_API(name) API_##name,
#include "ICorJitInfo_names_generated.h"
    API_COUNT
};

//---------------------------------------------------------------
// Compilation time.
//

// A "CompTimeInfo" is a structure for tracking the compilation time of one or more methods.
// We divide a compilation into a sequence of contiguous phases, and track the total (per-thread) cycles
// of the compilation, as well as the cycles for each phase.  We also track the number of bytecodes.
// If there is a failure in reading a timer at any point, the "CompTimeInfo" becomes invalid, as indicated
// by "m_timerFailure" being true.
// If FEATURE_JIT_METHOD_PERF is not set, we define a minimal form of this, enough to let other code compile.
struct CompTimeInfo
{
#ifdef FEATURE_JIT_METHOD_PERF
    // The string names of the phases.
    static const char* PhaseNames[];

    static bool PhaseHasChildren[];
    static int  PhaseParent[];
    static bool PhaseReportsIRSize[];

    unsigned         m_byteCodeBytes;
    unsigned __int64 m_totalCycles;
    unsigned __int64 m_invokesByPhase[PHASE_NUMBER_OF];
    unsigned __int64 m_cyclesByPhase[PHASE_NUMBER_OF];
#if MEASURE_CLRAPI_CALLS
    unsigned __int64 m_CLRinvokesByPhase[PHASE_NUMBER_OF];
    unsigned __int64 m_CLRcyclesByPhase[PHASE_NUMBER_OF];
#endif

    unsigned m_nodeCountAfterPhase[PHASE_NUMBER_OF];

    // For better documentation, we call EndPhase on
    // non-leaf phases.  We should also call EndPhase on the
    // last leaf subphase; obviously, the elapsed cycles between the EndPhase
    // for the last leaf subphase and the EndPhase for an ancestor should be very small.
    // We add all such "redundant end phase" intervals to this variable below; we print
    // it out in a report, so we can verify that it is, indeed, very small.  If it ever
    // isn't, this means that we're doing something significant between the end of the last
    // declared subphase and the end of its parent.
    unsigned __int64 m_parentPhaseEndSlop;
    bool             m_timerFailure;

#if MEASURE_CLRAPI_CALLS
    // The following measures the time spent inside each individual CLR API call.
    unsigned         m_allClrAPIcalls;
    unsigned         m_perClrAPIcalls[API_ICorJitInfo_Names::API_COUNT];
    unsigned __int64 m_allClrAPIcycles;
    unsigned __int64 m_perClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
    unsigned __int32 m_maxClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
#endif // MEASURE_CLRAPI_CALLS

    CompTimeInfo(unsigned byteCodeBytes);
#endif
};

#ifdef FEATURE_JIT_METHOD_PERF

#if MEASURE_CLRAPI_CALLS
struct WrapICorJitInfo;
#endif

// This class summarizes the JIT time information over the course of a run: the number of methods compiled,
// and the total and maximum timings.  (These are instances of the "CompTimeInfo" type described above).
// The operation of adding a single method's timing to the summary may be performed concurrently by several
// threads, so it is protected by a lock.
// This class is intended to be used as a singleton type, with only a single instance.
class CompTimeSummaryInfo
{
    // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
    static CritSecObject s_compTimeSummaryLock;

    int          m_numMethods;
    int          m_totMethods;
    CompTimeInfo m_total;
    CompTimeInfo m_maximum;

    int          m_numFilteredMethods;
    CompTimeInfo m_filtered;

    // This can use what ever data you want to determine if the value to be added
    // belongs in the filtered section (it's always included in the unfiltered section)
    bool IncludedInFilteredData(CompTimeInfo& info);

public:
    // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
    static CompTimeSummaryInfo s_compTimeSummary;

    CompTimeSummaryInfo()
        : m_numMethods(0), m_totMethods(0), m_total(0), m_maximum(0), m_numFilteredMethods(0), m_filtered(0)
    {
    }

    // Assumes that "info" is a completed CompTimeInfo for a compilation; adds it to the summary.
    // This is thread safe.
    void AddInfo(CompTimeInfo& info, bool includePhases);

    // Print the summary information to "f".
    // This is not thread-safe; assumed to be called by only one thread.
    void Print(FILE* f);
};

// A JitTimer encapsulates a CompTimeInfo for a single compilation. It also tracks the start of compilation,
// and when the current phase started.  This is intended to be part of a Compilation object.
//
class JitTimer
{
    unsigned __int64 m_start;         // Start of the compilation.
    unsigned __int64 m_curPhaseStart; // Start of the current phase.
#if MEASURE_CLRAPI_CALLS
    unsigned __int64 m_CLRcallStart;   // Start of the current CLR API call (if any).
    unsigned __int64 m_CLRcallInvokes; // CLR API invokes under current outer so far
    unsigned __int64 m_CLRcallCycles;  // CLR API  cycles under current outer so far.
    int              m_CLRcallAPInum;  // The enum/index of the current CLR API call (or -1).
    static double    s_cyclesPerSec;   // Cached for speedier measurements
#endif
#ifdef DEBUG
    Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
#endif
    CompTimeInfo m_info; // The CompTimeInfo for this compilation.

    static CritSecObject s_csvLock; // Lock to protect the time log file.
    static FILE*         s_csvFile; // The time log file handle.
    void PrintCsvMethodStats(Compiler* comp);

private:
    void* operator new(size_t);
    void* operator new[](size_t);
    void operator delete(void*);
    void operator delete[](void*);

public:
    // Initialized the timer instance
    JitTimer(unsigned byteCodeSize);

    static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
    {
        return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
    }

    static void PrintCsvHeader();

    // Ends the current phase (argument is for a redundant check).
    void EndPhase(Compiler* compiler, Phases phase);

#if MEASURE_CLRAPI_CALLS
    // Start and end a timed CLR API call.
    void CLRApiCallEnter(unsigned apix);
    void CLRApiCallLeave(unsigned apix);
#endif // MEASURE_CLRAPI_CALLS

    // Completes the timing of the current method, which is assumed to have "byteCodeBytes" bytes of bytecode,
    // and adds it to "sum".
    void Terminate(Compiler* comp, CompTimeSummaryInfo& sum, bool includePhases);

    // Attempts to query the cycle counter of the current thread.  If successful, returns "true" and sets
    // *cycles to the cycle counter value.  Otherwise, returns false and sets the "m_timerFailure" flag of
    // "m_info" to true.
    bool GetThreadCycles(unsigned __int64* cycles)
    {
        bool res = CycleTimer::GetThreadCyclesS(cycles);
        if (!res)
        {
            m_info.m_timerFailure = true;
        }
        return res;
    }

    static void Shutdown();
};
#endif // FEATURE_JIT_METHOD_PERF

//------------------- Function/Funclet info -------------------------------
enum FuncKind : BYTE
{
    FUNC_ROOT,    // The main/root function (always id==0)
    FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
    FUNC_FILTER,  // a funclet associated with an EH filter
    FUNC_COUNT
};

class emitLocation;

struct FuncInfoDsc
{
    FuncKind       funKind;
    BYTE           funFlags;   // Currently unused, just here for padding
    unsigned short funEHIndex; // index, into the ebd table, of innermost EH clause corresponding to this
                               // funclet. It is only valid if funKind field indicates this is a
                               // EH-related funclet: FUNC_HANDLER or FUNC_FILTER

#if defined(TARGET_AMD64)

    // TODO-AMD64-Throughput: make the AMD64 info more like the ARM info to avoid having this large static array.
    emitLocation* startLoc;
    emitLocation* endLoc;
    emitLocation* coldStartLoc; // locations for the cold section, if there is one.
    emitLocation* coldEndLoc;
    UNWIND_INFO   unwindHeader;
    // Maximum of 255 UNWIND_CODE 'nodes' and then the unwind header. If there are an odd
    // number of codes, the VM or Zapper will 4-byte align the whole thing.
    BYTE     unwindCodes[offsetof(UNWIND_INFO, UnwindCode) + (0xFF * sizeof(UNWIND_CODE))];
    unsigned unwindCodeSlot;

#elif defined(TARGET_X86)

    emitLocation* startLoc;
    emitLocation* endLoc;
    emitLocation* coldStartLoc; // locations for the cold section, if there is one.
    emitLocation* coldEndLoc;

#elif defined(TARGET_ARMARCH) || defined(TARGET_LOONGARCH64)

    UnwindInfo  uwi;     // Unwind information for this function/funclet's hot  section
    UnwindInfo* uwiCold; // Unwind information for this function/funclet's cold section
                         //   Note: we only have a pointer here instead of the actual object,
                         //   to save memory in the JIT case (compared to the NGEN case),
                         //   where we don't have any cold section.
                         //   Note 2: we currently don't support hot/cold splitting in functions
                         //   with EH, so uwiCold will be NULL for all funclets.

    emitLocation* startLoc;
    emitLocation* endLoc;
    emitLocation* coldStartLoc; // locations for the cold section, if there is one.
    emitLocation* coldEndLoc;

#endif // TARGET_ARMARCH || TARGET_LOONGARCH64

#if defined(FEATURE_CFI_SUPPORT)
    jitstd::vector<CFI_CODE>* cfiCodes;
#endif // FEATURE_CFI_SUPPORT

    // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
    // that isn't shared between the main function body and funclets.
};

struct TempInfo
{
    GenTree* asg;
    GenTree* load;
};

#ifdef DEBUG
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// We have the ability to mark source expressions with "Test Labels."
// These drive assertions within the JIT, or internal JIT testing.  For example, we could label expressions
// that should be CSE defs, and other expressions that should uses of those defs, with a shared label.

enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
{
    TL_SsaName,
    TL_VN,        // Defines a "VN equivalence class".  (For full VN, including exceptions thrown).
    TL_VNNorm,    // Like above, but uses the non-exceptional value of the expression.
    TL_CSE_Def,   //  This must be identified in the JIT as a CSE def
    TL_CSE_Use,   //  This must be identified in the JIT as a CSE use
    TL_LoopHoist, // Expression must (or must not) be hoisted out of the loop.
};

struct TestLabelAndNum
{
    TestLabel m_tl;
    ssize_t   m_num;

    TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
    {
    }
};

typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, TestLabelAndNum> NodeToTestDataMap;

// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#endif // DEBUG

//-------------------------------------------------------------------------
// LoopFlags: flags for the loop table.
//
enum LoopFlags : unsigned short
{
    LPFLG_EMPTY = 0,

    // LPFLG_UNUSED  = 0x0001,
    // LPFLG_UNUSED  = 0x0002,
    LPFLG_ITER = 0x0004, // loop of form: for (i = icon or expression; test_condition(); i++)
    // LPFLG_UNUSED    = 0x0008,

    LPFLG_CONTAINS_CALL = 0x0010, // If executing the loop body *may* execute a call
    // LPFLG_UNUSED     = 0x0020,
    LPFLG_CONST_INIT = 0x0040, // iterator is initialized with a constant (found in lpConstInit)
    LPFLG_SIMD_LIMIT = 0x0080, // iterator is compared with vector element count (found in lpConstLimit)

    LPFLG_VAR_LIMIT    = 0x0100, // iterator is compared with a local var (var # found in lpVarLimit)
    LPFLG_CONST_LIMIT  = 0x0200, // iterator is compared with a constant (found in lpConstLimit)
    LPFLG_ARRLEN_LIMIT = 0x0400, // iterator is compared with a.len or a[i].len (found in lpArrLenLimit)
    LPFLG_HAS_PREHEAD  = 0x0800, // lpHead is known to be a preHead for this loop

    LPFLG_REMOVED     = 0x1000, // has been removed from the loop table (unrolled or optimized away)
    LPFLG_DONT_UNROLL = 0x2000, // do not unroll this loop
    LPFLG_ASGVARS_YES = 0x4000, // "lpAsgVars" has been computed
    LPFLG_ASGVARS_INC = 0x8000, // "lpAsgVars" is incomplete -- vars beyond those representable in an AllVarSet
                                // type are assigned to.
};

inline constexpr LoopFlags operator~(LoopFlags a)
{
    return (LoopFlags)(~(unsigned short)a);
}

inline constexpr LoopFlags operator|(LoopFlags a, LoopFlags b)
{
    return (LoopFlags)((unsigned short)a | (unsigned short)b);
}

inline constexpr LoopFlags operator&(LoopFlags a, LoopFlags b)
{
    return (LoopFlags)((unsigned short)a & (unsigned short)b);
}

inline LoopFlags& operator|=(LoopFlags& a, LoopFlags b)
{
    return a = (LoopFlags)((unsigned short)a | (unsigned short)b);
}

inline LoopFlags& operator&=(LoopFlags& a, LoopFlags b)
{
    return a = (LoopFlags)((unsigned short)a & (unsigned short)b);
}

//  The following holds information about instr offsets in terms of generated code.

enum class IPmappingDscKind
{
    Prolog,    // The mapping represents the start of a prolog.
    Epilog,    // The mapping represents the start of an epilog.
    NoMapping, // This does not map to any IL offset.
    Normal,    // The mapping maps to an IL offset.
};

struct IPmappingDsc
{
    emitLocation     ipmdNativeLoc; // the emitter location of the native code corresponding to the IL offset
    IPmappingDscKind ipmdKind;      // The kind of mapping
    ILLocation       ipmdLoc;       // The location for normal mappings
    bool             ipmdIsLabel;   // Can this code be a branch label?
};

struct RichIPMapping
{
    emitLocation nativeLoc;
    DebugInfo    debugInfo;
};

/*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX   The big guy. The sections are currently organized as :                  XX
XX                                                                           XX
XX    o  GenTree and BasicBlock                                              XX
XX    o  LclVarsInfo                                                         XX
XX    o  Importer                                                            XX
XX    o  FlowGraph                                                           XX
XX    o  Optimizer                                                           XX
XX    o  RegAlloc                                                            XX
XX    o  EEInterface                                                         XX
XX    o  TempsInfo                                                           XX
XX    o  RegSet                                                              XX
XX    o  GCInfo                                                              XX
XX    o  Instruction                                                         XX
XX    o  ScopeInfo                                                           XX
XX    o  PrologScopeInfo                                                     XX
XX    o  CodeGenerator                                                       XX
XX    o  UnwindInfo                                                          XX
XX    o  Compiler                                                            XX
XX    o  typeInfo                                                            XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

struct HWIntrinsicInfo;

class Compiler
{
    friend class emitter;
    friend class UnwindInfo;
    friend class UnwindFragmentInfo;
    friend class UnwindEpilogInfo;
    friend class JitTimer;
    friend class LinearScan;
    friend class Rationalizer;
    friend class Phase;
    friend class Lowering;
    friend class CSE_DataFlow;
    friend class CSE_Heuristic;
    friend class CodeGenInterface;
    friend class CodeGen;
    friend class LclVarDsc;
    friend class TempDsc;
    friend class LIR;
    friend class ObjectAllocator;
    friend class LocalAddressVisitor;
    friend struct GenTree;
    friend class MorphInitBlockHelper;
    friend class MorphCopyBlockHelper;
    friend class CallArgs;
    friend class IndirectCallTransformer;

#ifdef FEATURE_HW_INTRINSICS
    friend struct HWIntrinsicInfo;
    friend struct SimdAsHWIntrinsicInfo;
#endif // FEATURE_HW_INTRINSICS

#ifndef TARGET_64BIT
    friend class DecomposeLongs;
#endif // !TARGET_64BIT

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX  Misc structs definitions                                                 XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.

#ifdef DEBUG
    bool verbose;
    bool verboseTrees;
    bool shouldUseVerboseTrees();
    bool asciiTrees; // If true, dump trees using only ASCII characters
    bool shouldDumpASCIITrees();
    bool verboseSsa; // If true, produce especially verbose dump output in SSA construction.
    bool shouldUseVerboseSsa();
    bool treesBeforeAfterMorph; // If true, print trees before/after morphing (paired by an intra-compilation id:
    int  morphNum;              // This counts the trees that have been morphed, allowing us to label each uniquely.
    bool doExtraSuperPmiQueries;
    void makeExtraStructQueries(CORINFO_CLASS_HANDLE structHandle, int level); // Make queries recursively 'level' deep.

    const char* VarNameToStr(VarName name)
    {
        return name;
    }

    DWORD expensiveDebugCheckLevel;
#endif

    GenTree* impAssignMultiRegTypeToVar(GenTree*             op,
                                        CORINFO_CLASS_HANDLE hClass DEBUGARG(CorInfoCallConvExtension callConv));

#ifdef TARGET_X86
    bool isTrivialPointerSizedStruct(CORINFO_CLASS_HANDLE clsHnd) const;
#endif // TARGET_X86

    //-------------------------------------------------------------------------
    // Functions to handle homogeneous floating-point aggregates (HFAs) in ARM/ARM64.
    // HFAs are one to four element structs where each element is the same
    // type, either all float or all double. We handle HVAs (one to four elements of
    // vector types) uniformly with HFAs. HFAs are treated specially
    // in the ARM/ARM64 Procedure Call Standards, specifically, they are passed in
    // floating-point registers instead of the general purpose registers.
    //

    bool IsHfa(CORINFO_CLASS_HANDLE hClass);
    var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
    unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);

    bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass, CorInfoCallConvExtension callConv);

    //-------------------------------------------------------------------------
    // The following is used for validating format of EH table
    //

    struct EHNodeDsc;
    typedef struct EHNodeDsc* pEHNodeDsc;

    EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
    EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.

    struct EHNodeDsc
    {
        enum EHBlockType
        {
            TryNode,
            FilterNode,
            HandlerNode,
            FinallyNode,
            FaultNode
        };

        EHBlockType ehnBlockType;   // kind of EH block
        IL_OFFSET   ehnStartOffset; // IL offset of start of the EH block
        IL_OFFSET ehnEndOffset; // IL offset past end of the EH block. (TODO: looks like verInsertEhNode() sets this to
                                // the last IL offset, not "one past the last one", i.e., the range Start to End is
                                // inclusive).
        pEHNodeDsc ehnNext;     // next (non-nested) block in sequential order
        pEHNodeDsc ehnChild;    // leftmost nested block
        union {
            pEHNodeDsc ehnTryNode;     // for filters and handlers, the corresponding try node
            pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
        };
        pEHNodeDsc ehnFilterNode; // if this is a try node and has a filter, otherwise 0
        pEHNodeDsc ehnEquivalent; // if blockType=tryNode, start offset and end offset is same,

        void ehnSetTryNodeType()
        {
            ehnBlockType = TryNode;
        }
        void ehnSetFilterNodeType()
        {
            ehnBlockType = FilterNode;
        }
        void ehnSetHandlerNodeType()
        {
            ehnBlockType = HandlerNode;
        }
        void ehnSetFinallyNodeType()
        {
            ehnBlockType = FinallyNode;
        }
        void ehnSetFaultNodeType()
        {
            ehnBlockType = FaultNode;
        }

        bool ehnIsTryBlock()
        {
            return ehnBlockType == TryNode;
        }
        bool ehnIsFilterBlock()
        {
            return ehnBlockType == FilterNode;
        }
        bool ehnIsHandlerBlock()
        {
            return ehnBlockType == HandlerNode;
        }
        bool ehnIsFinallyBlock()
        {
            return ehnBlockType == FinallyNode;
        }
        bool ehnIsFaultBlock()
        {
            return ehnBlockType == FaultNode;
        }

        // returns true if there is any overlap between the two nodes
        static bool ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
        {
            if (node1->ehnStartOffset < node2->ehnStartOffset)
            {
                return (node1->ehnEndOffset >= node2->ehnStartOffset);
            }
            else
            {
                return (node1->ehnStartOffset <= node2->ehnEndOffset);
            }
        }

        // fails with BADCODE if inner is not completely nested inside outer
        static bool ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
        {
            return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
        }
    };

//-------------------------------------------------------------------------
// Exception handling functions
//

#if !defined(FEATURE_EH_FUNCLETS)

    bool ehNeedsShadowSPslots()
    {
        return (info.compXcptnsCount || opts.compDbgEnC);
    }

    // 0 for methods with no EH
    // 1 for methods with non-nested EH, or where only the try blocks are nested
    // 2 for a method with a catch within a catch
    // etc.
    unsigned ehMaxHndNestingCount;

#endif // !FEATURE_EH_FUNCLETS

    static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
    static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);

    bool bbInCatchHandlerILRange(BasicBlock* blk);
    bool bbInFilterILRange(BasicBlock* blk);
    bool bbInTryRegions(unsigned regionIndex, BasicBlock* blk);
    bool bbInExnFlowRegions(unsigned regionIndex, BasicBlock* blk);
    bool bbInHandlerRegions(unsigned regionIndex, BasicBlock* blk);
    bool bbInCatchHandlerRegions(BasicBlock* tryBlk, BasicBlock* hndBlk);
    unsigned short bbFindInnermostCommonTryRegion(BasicBlock* bbOne, BasicBlock* bbTwo);

    unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
    unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);

    // Returns true if "block" is the start of a try region.
    bool bbIsTryBeg(BasicBlock* block);

    // Returns true if "block" is the start of a handler or filter region.
    bool bbIsHandlerBeg(BasicBlock* block);

    // Returns true iff "block" is where control flows if an exception is raised in the
    // try region, and sets "*regionIndex" to the index of the try for the handler.
    // Differs from "IsHandlerBeg" in the case of filters, where this is true for the first
    // block of the filter, but not for the filter's handler.
    bool bbIsExFlowBlock(BasicBlock* block, unsigned* regionIndex);

    bool ehHasCallableHandlers();

    // Return the EH descriptor for the given region index.
    EHblkDsc* ehGetDsc(unsigned regionIndex);

    // Return the EH index given a region descriptor.
    unsigned ehGetIndex(EHblkDsc* ehDsc);

    // Return the EH descriptor index of the enclosing try, for the given region index.
    unsigned ehGetEnclosingTryIndex(unsigned regionIndex);

    // Return the EH descriptor index of the enclosing handler, for the given region index.
    unsigned ehGetEnclosingHndIndex(unsigned regionIndex);

    // Return the EH descriptor for the most nested 'try' region this BasicBlock is a member of (or nullptr if this
    // block is not in a 'try' region).
    EHblkDsc* ehGetBlockTryDsc(BasicBlock* block);

    // Return the EH descriptor for the most nested filter or handler region this BasicBlock is a member of (or nullptr
    // if this block is not in a filter or handler region).
    EHblkDsc* ehGetBlockHndDsc(BasicBlock* block);

    // Return the EH descriptor for the most nested region that may handle exceptions raised in this BasicBlock (or
    // nullptr if this block's exceptions propagate to caller).
    EHblkDsc* ehGetBlockExnFlowDsc(BasicBlock* block);

    EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
    EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
    bool ehIsBlockEHLast(BasicBlock* block);

    bool ehBlockHasExnFlowDsc(BasicBlock* block);

    // Return the region index of the most nested EH region this block is in.
    unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);

    // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
    unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);

    // Return the index of the most nested enclosing region for a particular EH region. Returns NO_ENCLOSING_INDEX
    // if there is no enclosing region. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion'
    // is set to 'true' if the enclosing region is a 'try', or 'false' if the enclosing region is a handler.
    // (It can never be a filter.)
    unsigned ehGetEnclosingRegionIndex(unsigned regionIndex, bool* inTryRegion);

    // A block has been deleted. Update the EH table appropriately.
    void ehUpdateForDeletedBlock(BasicBlock* block);

    // Determine whether a block can be deleted while preserving the EH normalization rules.
    bool ehCanDeleteEmptyBlock(BasicBlock* block);

    // Update the 'last' pointers in the EH table to reflect new or deleted blocks in an EH region.
    void ehUpdateLastBlocks(BasicBlock* oldLast, BasicBlock* newLast);

    // For a finally handler, find the region index that the BBJ_CALLFINALLY lives in that calls the handler,
    // or NO_ENCLOSING_INDEX if the BBJ_CALLFINALLY lives in the main function body. Normally, the index
    // is the same index as the handler (and the BBJ_CALLFINALLY lives in the 'try' region), but for AMD64 the
    // BBJ_CALLFINALLY lives in the enclosing try or handler region, whichever is more nested, or the main function
    // body. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion' is set to 'true' if the
    // BBJ_CALLFINALLY lives in the returned index's 'try' region, or 'false' if lives in the handler region. (It never
    // lives in a filter.)
    unsigned ehGetCallFinallyRegionIndex(unsigned finallyIndex, bool* inTryRegion);

    // Find the range of basic blocks in which all BBJ_CALLFINALLY will be found that target the 'finallyIndex' region's
    // handler. Set begBlk to the first block, and endBlk to the block after the last block of the range
    // (nullptr if the last block is the last block in the program).
    // Precondition: 'finallyIndex' is the EH region of a try/finally clause.
    void ehGetCallFinallyBlockRange(unsigned finallyIndex, BasicBlock** begBlk, BasicBlock** endBlk);

#ifdef DEBUG
    // Given a BBJ_CALLFINALLY block and the EH region index of the finally it is calling, return
    // 'true' if the BBJ_CALLFINALLY is in the correct EH region.
    bool ehCallFinallyInCorrectRegion(BasicBlock* blockCallFinally, unsigned finallyIndex);
#endif // DEBUG

#if defined(FEATURE_EH_FUNCLETS)
    // Do we need a PSPSym in the main function? For codegen purposes, we only need one
    // if there is a filter that protects a region with a nested EH clause (such as a
    // try/catch nested in the 'try' body of a try/filter/filter-handler). See
    // genFuncletProlog() for more details. However, the VM seems to use it for more
    // purposes, maybe including debugging. Until we are sure otherwise, always create
    // a PSPSym for functions with any EH.
    bool ehNeedsPSPSym() const
    {
#ifdef TARGET_X86
        return false;
#else  // TARGET_X86
        return compHndBBtabCount > 0;
#endif // TARGET_X86
    }

    bool     ehAnyFunclets();  // Are there any funclets in this function?
    unsigned ehFuncletCount(); // Return the count of funclets in the function

    unsigned bbThrowIndex(BasicBlock* blk); // Get the index to use as the cache key for sharing throw blocks

#else  // !FEATURE_EH_FUNCLETS

    bool ehAnyFunclets()
    {
        return false;
    }
    unsigned ehFuncletCount()
    {
        return 0;
    }

    unsigned bbThrowIndex(BasicBlock* blk)
    {
        return blk->bbTryIndex;
    } // Get the index to use as the cache key for sharing throw blocks
#endif // !FEATURE_EH_FUNCLETS

    // Returns a flowList representing the "EH predecessors" of "blk".  These are the normal predecessors of
    // "blk", plus one special case: if "blk" is the first block of a handler, considers the predecessor(s) of the first
    // first block of the corresponding try region to be "EH predecessors".  (If there is a single such predecessor,
    // for example, we want to consider that the immediate dominator of the catch clause start block, so it's
    // convenient to also consider it a predecessor.)
    flowList* BlockPredsWithEH(BasicBlock* blk);

    // This table is useful for memoization of the method above.
    typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, flowList*> BlockToFlowListMap;
    BlockToFlowListMap* m_blockToEHPreds;
    BlockToFlowListMap* GetBlockToEHPreds()
    {
        if (m_blockToEHPreds == nullptr)
        {
            m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
        }
        return m_blockToEHPreds;
    }

    void* ehEmitCookie(BasicBlock* block);
    UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);

    EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);

    EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);

    EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);

    EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);

    void fgSetTryBeg(EHblkDsc* handlerTab, BasicBlock* newTryBeg);

    void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);

    void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);

    void fgSkipRmvdBlocks(EHblkDsc* handlerTab);

    void fgAllocEHTable();

    void fgRemoveEHTableEntry(unsigned XTnum);

#if defined(FEATURE_EH_FUNCLETS)

    EHblkDsc* fgAddEHTableEntry(unsigned XTnum);

#endif // FEATURE_EH_FUNCLETS

#if !FEATURE_EH
    void fgRemoveEH();
#endif // !FEATURE_EH

    void fgSortEHTable();

    // Causes the EH table to obey some well-formedness conditions, by inserting
    // empty BB's when necessary:
    //   * No block is both the first block of a handler and the first block of a try.
    //   * No block is the first block of multiple 'try' regions.
    //   * No block is the last block of multiple EH regions.
    void fgNormalizeEH();
    bool fgNormalizeEHCase1();
    bool fgNormalizeEHCase2();
    bool fgNormalizeEHCase3();

    bool fgCreateFiltersForGenericExceptions();

    void fgCheckForLoopsInHandlers();

#ifdef DEBUG
    void dispIncomingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
    void dispOutgoingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
    void fgVerifyHandlerTab();
    void fgDispHandlerTab();
#endif // DEBUG

    bool fgNeedToSortEHTable;

    void verInitEHTree(unsigned numEHClauses);
    void verInsertEhNode(CORINFO_EH_CLAUSE* clause, EHblkDsc* handlerTab);
    void verInsertEhNodeInTree(EHNodeDsc** ppRoot, EHNodeDsc* node);
    void verInsertEhNodeParent(EHNodeDsc** ppRoot, EHNodeDsc* node);
    void verCheckNestingLevel(EHNodeDsc* initRoot);

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                        GenTree and BasicBlock                             XX
    XX                                                                           XX
    XX  Functions to allocate and display the GenTrees and BasicBlocks           XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

    // Functions to create nodes
    Statement* gtNewStmt(GenTree* expr = nullptr);
    Statement* gtNewStmt(GenTree* expr, const DebugInfo& di);

    // For unary opers.
    GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1);

    // For binary opers.
    GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, GenTree* op2);

    GenTreeColon* gtNewColonNode(var_types type, GenTree* elseNode, GenTree* thenNode);
    GenTreeQmark* gtNewQmarkNode(var_types type, GenTree* cond, GenTreeColon* colon);

    GenTree* gtNewLargeOperNode(genTreeOps oper,
                                var_types  type = TYP_I_IMPL,
                                GenTree*   op1  = nullptr,
                                GenTree*   op2  = nullptr);

    GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
    GenTreeIntCon* gtNewIconNode(unsigned fieldOffset, FieldSeq* fieldSeq);
    GenTreeIntCon* gtNewNull();
    GenTreeIntCon* gtNewTrue();
    GenTreeIntCon* gtNewFalse();

    GenTree* gtNewPhysRegNode(regNumber reg, var_types type);

    GenTree* gtNewJmpTableNode();

    GenTree* gtNewIndOfIconHandleNode(var_types indType, size_t value, GenTreeFlags iconFlags, bool isInvariant);

    GenTreeIntCon* gtNewIconHandleNode(size_t value, GenTreeFlags flags, FieldSeq* fields = nullptr);

    GenTreeFlags gtTokenToIconFlags(unsigned token);

    GenTree* gtNewIconEmbHndNode(void* value, void* pValue, GenTreeFlags flags, void* compileTimeHandle);

    GenTree* gtNewIconEmbScpHndNode(CORINFO_MODULE_HANDLE scpHnd);
    GenTree* gtNewIconEmbClsHndNode(CORINFO_CLASS_HANDLE clsHnd);
    GenTree* gtNewIconEmbMethHndNode(CORINFO_METHOD_HANDLE methHnd);
    GenTree* gtNewIconEmbFldHndNode(CORINFO_FIELD_HANDLE fldHnd);

    GenTree* gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
    GenTreeIntCon* gtNewStringLiteralLength(GenTreeStrCon* node);

    GenTree* gtNewLconNode(__int64 value);

    GenTree* gtNewDconNode(double value, var_types type = TYP_DOUBLE);

    GenTree* gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);

    GenTreeVecCon* gtNewVconNode(var_types type);

    GenTree* gtNewAllBitsSetConNode(var_types type);

    GenTree* gtNewZeroConNode(var_types type);

    GenTree* gtNewOneConNode(var_types type, var_types simdBaseType = TYP_UNDEF);

    GenTreeLclVar* gtNewStoreLclVar(unsigned dstLclNum, GenTree* src);

    GenTree* gtNewBlkOpNode(GenTree* dst, GenTree* srcOrFillVal, bool isVolatile, bool isCopyBlock);

    GenTree* gtNewPutArgReg(var_types type, GenTree* arg, regNumber argReg);

    GenTree* gtNewBitCastNode(var_types type, GenTree* arg);

protected:
    void gtBlockOpInit(GenTree* result, GenTree* dst, GenTree* srcOrFillVal, bool isVolatile);

public:
    GenTreeObj* gtNewObjNode(ClassLayout* layout, GenTree* addr);
    GenTreeObj* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
    void gtSetObjGcInfo(GenTreeObj* objNode);
    GenTree* gtNewStructVal(ClassLayout* layout, GenTree* addr);
    GenTree* gtNewBlockVal(GenTree* addr, unsigned size);

    GenTreeCall* gtNewCallNode(gtCallTypes           callType,
                               CORINFO_METHOD_HANDLE handle,
                               var_types             type,
                               const DebugInfo&      di = DebugInfo());

    GenTreeCall* gtNewIndCallNode(GenTree* addr, var_types type, const DebugInfo& di = DebugInfo());

    GenTreeCall* gtNewHelperCallNode(
        unsigned helper, var_types type, GenTree* arg1 = nullptr, GenTree* arg2 = nullptr, GenTree* arg3 = nullptr);

    GenTreeCall* gtNewRuntimeLookupHelperCallNode(CORINFO_RUNTIME_LOOKUP* pRuntimeLookup,
                                                  GenTree*                ctxTree,
                                                  void*                   compileTimeHandle);

    GenTreeLclVar* gtNewLclvNode(unsigned lnum, var_types type DEBUGARG(IL_OFFSET offs = BAD_IL_OFFSET));
    GenTreeLclVar* gtNewLclLNode(unsigned lnum, var_types type DEBUGARG(IL_OFFSET offs = BAD_IL_OFFSET));

    GenTreeLclVar* gtNewLclVarAddrNode(unsigned lclNum, var_types type = TYP_I_IMPL);
    GenTreeLclFld* gtNewLclFldAddrNode(unsigned lclNum, unsigned lclOffs, var_types type = TYP_I_IMPL);

    GenTreeConditional* gtNewConditionalNode(
        genTreeOps oper, GenTree* cond, GenTree* op1, GenTree* op2, var_types type);

#ifdef FEATURE_SIMD
    GenTreeSIMD* gtNewSIMDNode(
        var_types type, GenTree* op1, SIMDIntrinsicID simdIntrinsicID, CorInfoType simdBaseJitType, unsigned simdSize);
    GenTreeSIMD* gtNewSIMDNode(var_types       type,
                               GenTree*        op1,
                               GenTree*        op2,
                               SIMDIntrinsicID simdIntrinsicID,
                               CorInfoType     simdBaseJitType,
                               unsigned        simdSize);
    void SetOpLclRelatedToSIMDIntrinsic(GenTree* op);
#endif

#ifdef FEATURE_HW_INTRINSICS
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
                                                 NamedIntrinsic hwIntrinsicID,
                                                 CorInfoType    simdBaseJitType,
                                                 unsigned       simdSize,
                                                 bool           isSimdAsHWIntrinsic = false);
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
                                                 GenTree*       op1,
                                                 NamedIntrinsic hwIntrinsicID,
                                                 CorInfoType    simdBaseJitType,
                                                 unsigned       simdSize,
                                                 bool           isSimdAsHWIntrinsic = false);
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
                                                 GenTree*       op1,
                                                 GenTree*       op2,
                                                 NamedIntrinsic hwIntrinsicID,
                                                 CorInfoType    simdBaseJitType,
                                                 unsigned       simdSize,
                                                 bool           isSimdAsHWIntrinsic = false);
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
                                                 GenTree*       op1,
                                                 GenTree*       op2,
                                                 GenTree*       op3,
                                                 NamedIntrinsic hwIntrinsicID,
                                                 CorInfoType    simdBaseJitType,
                                                 unsigned       simdSize,
                                                 bool           isSimdAsHWIntrinsic = false);
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
                                                 GenTree*       op1,
                                                 GenTree*       op2,
                                                 GenTree*       op3,
                                                 GenTree*       op4,
                                                 NamedIntrinsic hwIntrinsicID,
                                                 CorInfoType    simdBaseJitType,
                                                 unsigned       simdSize,
                                                 bool           isSimdAsHWIntrinsic = false);
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
                                                 GenTree**      operands,
                                                 size_t         operandCount,
                                                 NamedIntrinsic hwIntrinsicID,
                                                 CorInfoType    simdBaseJitType,
                                                 unsigned       simdSize,
                                                 bool           isSimdAsHWIntrinsic = false);
    GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types              type,
                                                 IntrinsicNodeBuilder&& nodeBuilder,
                                                 NamedIntrinsic         hwIntrinsicID,
                                                 CorInfoType            simdBaseJitType,
                                                 unsigned               simdSize,
                                                 bool                   isSimdAsHWIntrinsic = false);

    GenTreeHWIntrinsic* gtNewSimdAsHWIntrinsicNode(var_types      type,
                                                   NamedIntrinsic hwIntrinsicID,
                                                   CorInfoType    simdBaseJitType,
                                                   unsigned       simdSize)
    {
        bool isSimdAsHWIntrinsic = true;
        return gtNewSimdHWIntrinsicNode(type, hwIntrinsicID, simdBaseJitType, simdSize, isSimdAsHWIntrinsic);
    }

    GenTreeHWIntrinsic* gtNewSimdAsHWIntrinsicNode(
        var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID, CorInfoType simdBaseJitType, unsigned simdSize)
    {
        bool isSimdAsHWIntrinsic = true;
        return gtNewSimdHWIntrinsicNode(type, op1, hwIntrinsicID, simdBaseJitType, simdSize, isSimdAsHWIntrinsic);
    }

    GenTreeHWIntrinsic* gtNewSimdAsHWIntrinsicNode(var_types      type,
                                                   GenTree*       op1,
                                                   GenTree*       op2,
                                                   NamedIntrinsic hwIntrinsicID,
                                                   CorInfoType    simdBaseJitType,
                                                   unsigned       simdSize)
    {
        bool isSimdAsHWIntrinsic = true;
        return gtNewSimdHWIntrinsicNode(type, op1, op2, hwIntrinsicID, simdBaseJitType, simdSize, isSimdAsHWIntrinsic);
    }

    GenTreeHWIntrinsic* gtNewSimdAsHWIntrinsicNode(var_types      type,
                                                   GenTree*       op1,
                                                   GenTree*       op2,
                                                   GenTree*       op3,
                                                   NamedIntrinsic hwIntrinsicID,
                                                   CorInfoType    simdBaseJitType,
                                                   unsigned       simdSize)
    {
        bool isSimdAsHWIntrinsic = true;
        return gtNewSimdHWIntrinsicNode(type, op1, op2, op3, hwIntrinsicID, simdBaseJitType, simdSize,
                                        isSimdAsHWIntrinsic);
    }

    GenTree* gtNewSimdAbsNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdBinOpNode(genTreeOps  op,
                                var_types   type,
                                GenTree*    op1,
                                GenTree*    op2,
                                CorInfoType simdBaseJitType,
                                unsigned    simdSize,
                                bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdCeilNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdCmpOpNode(genTreeOps  op,
                                var_types   type,
                                GenTree*    op1,
                                GenTree*    op2,
                                CorInfoType simdBaseJitType,
                                unsigned    simdSize,
                                bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdCmpOpAllNode(genTreeOps  op,
                                   var_types   type,
                                   GenTree*    op1,
                                   GenTree*    op2,
                                   CorInfoType simdBaseJitType,
                                   unsigned    simdSize,
                                   bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdCmpOpAnyNode(genTreeOps  op,
                                   var_types   type,
                                   GenTree*    op1,
                                   GenTree*    op2,
                                   CorInfoType simdBaseJitType,
                                   unsigned    simdSize,
                                   bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdCndSelNode(var_types   type,
                                 GenTree*    op1,
                                 GenTree*    op2,
                                 GenTree*    op3,
                                 CorInfoType simdBaseJitType,
                                 unsigned    simdSize,
                                 bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdCreateBroadcastNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdDotProdNode(var_types   type,
                                  GenTree*    op1,
                                  GenTree*    op2,
                                  CorInfoType simdBaseJitType,
                                  unsigned    simdSize,
                                  bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdFloorNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdGetElementNode(var_types   type,
                                     GenTree*    op1,
                                     GenTree*    op2,
                                     CorInfoType simdBaseJitType,
                                     unsigned    simdSize,
                                     bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdMaxNode(var_types   type,
                              GenTree*    op1,
                              GenTree*    op2,
                              CorInfoType simdBaseJitType,
                              unsigned    simdSize,
                              bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdMinNode(var_types   type,
                              GenTree*    op1,
                              GenTree*    op2,
                              CorInfoType simdBaseJitType,
                              unsigned    simdSize,
                              bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdNarrowNode(var_types   type,
                                 GenTree*    op1,
                                 GenTree*    op2,
                                 CorInfoType simdBaseJitType,
                                 unsigned    simdSize,
                                 bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdShuffleNode(var_types   type,
                                  GenTree*    op1,
                                  GenTree*    op2,
                                  CorInfoType simdBaseJitType,
                                  unsigned    simdSize,
                                  bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdSqrtNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdSumNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdUnOpNode(genTreeOps  op,
                               var_types   type,
                               GenTree*    op1,
                               CorInfoType simdBaseJitType,
                               unsigned    simdSize,
                               bool        isSimdAsHWIntrinsic);

    GenTree* gtNewSimdWidenLowerNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdWidenUpperNode(
        var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic);

    GenTree* gtNewSimdWithElementNode(var_types   type,
                                      GenTree*    op1,
                                      GenTree*    op2,
                                      GenTree*    op3,
                                      CorInfoType simdBaseJitType,
                                      unsigned    simdSize,
                                      bool        isSimdAsHWIntrinsic);

    GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type, NamedIntrinsic hwIntrinsicID);
    GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID);
    GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types      type,
                                                   GenTree*       op1,
                                                   GenTree*       op2,
                                                   NamedIntrinsic hwIntrinsicID);
    GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(
        var_types type, GenTree* op1, GenTree* op2, GenTree* op3, NamedIntrinsic hwIntrinsicID);
    CORINFO_CLASS_HANDLE gtGetStructHandleForHWSIMD(var_types simdType, CorInfoType simdBaseJitType);
    CorInfoType getBaseJitTypeFromArgIfNeeded(NamedIntrinsic       intrinsic,
                                              CORINFO_CLASS_HANDLE clsHnd,
                                              CORINFO_SIG_INFO*    sig,
                                              CorInfoType          simdBaseJitType);
#endif // FEATURE_HW_INTRINSICS

    GenTree* gtNewMustThrowException(unsigned helper, var_types type, CORINFO_CLASS_HANDLE clsHnd);

    GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset);
    GenTreeRetExpr* gtNewInlineCandidateReturnExpr(GenTreeCall* inlineCandidate, var_types type);

    GenTreeField* gtNewFieldRef(var_types type, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj = nullptr, DWORD offset = 0);

    GenTreeField* gtNewFieldAddrNode(var_types            type,
                                     CORINFO_FIELD_HANDLE fldHnd,
                                     GenTree*             obj    = nullptr,
                                     DWORD                offset = 0);

    GenTreeIndexAddr* gtNewIndexAddr(GenTree*             arrayOp,
                                     GenTree*             indexOp,
                                     var_types            elemType,
                                     CORINFO_CLASS_HANDLE elemClassHandle,
                                     unsigned             firstElemOffset,
                                     unsigned             lengthOffset);

    GenTreeIndexAddr* gtNewArrayIndexAddr(GenTree*             arrayOp,
                                          GenTree*             indexOp,
                                          var_types            elemType,
                                          CORINFO_CLASS_HANDLE elemClassHandle);

    GenTreeIndir* gtNewIndexIndir(GenTreeIndexAddr* indexAddr);

    void gtAnnotateNewArrLen(GenTree* arrLen, BasicBlock* block);

    GenTreeArrLen* gtNewArrLen(var_types typ, GenTree* arrayOp, int lenOffset, BasicBlock* block);

    GenTreeMDArr* gtNewMDArrLen(GenTree* arrayOp, unsigned dim, unsigned rank, BasicBlock* block);

    GenTreeMDArr* gtNewMDArrLowerBound(GenTree* arrayOp, unsigned dim, unsigned rank, BasicBlock* block);

    GenTreeIndir* gtNewIndir(var_types typ, GenTree* addr, GenTreeFlags indirFlags = GTF_EMPTY);

    GenTree* gtNewNullCheck(GenTree* addr, BasicBlock* basicBlock);

    var_types gtTypeForNullCheck(GenTree* tree);
    void gtChangeOperToNullCheck(GenTree* tree, BasicBlock* block);

    GenTreeOp* gtNewAssignNode(GenTree* dst, GenTree* src);

    GenTree* gtNewTempAssign(unsigned         tmp,
                             GenTree*         val,
                             Statement**      pAfterStmt = nullptr,
                             const DebugInfo& di         = DebugInfo(),
                             BasicBlock*      block      = nullptr);

    GenTree* gtNewRefCOMfield(GenTree*                objPtr,
                              CORINFO_RESOLVED_TOKEN* pResolvedToken,
                              CORINFO_ACCESS_FLAGS    access,
                              CORINFO_FIELD_INFO*     pFieldInfo,
                              var_types               lclTyp,
                              CORINFO_CLASS_HANDLE    structType,
                              GenTree*                assg);

    GenTree* gtNewNothingNode();

    GenTree* gtUnusedValNode(GenTree* expr);

    GenTree* gtNewKeepAliveNode(GenTree* op);

    GenTreeCast* gtNewCastNode(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);

    GenTreeCast* gtNewCastNodeL(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);

    GenTreeAllocObj* gtNewAllocObjNode(
        unsigned int helper, bool helperHasSideEffects, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTree* op1);

    GenTreeAllocObj* gtNewAllocObjNode(CORINFO_RESOLVED_TOKEN* pResolvedToken, bool useParent);

    GenTree* gtNewRuntimeLookup(CORINFO_GENERIC_HANDLE hnd, CorInfoGenericHandleType hndTyp, GenTree* lookupTree);

    GenTreeIndir* gtNewMethodTableLookup(GenTree* obj);

    //------------------------------------------------------------------------
    // Other GenTree functions

    GenTree* gtClone(GenTree* tree, bool complexOK = false);

    // If `tree` is a lclVar with lclNum `varNum`, return an IntCns with value `varVal`; otherwise,
    // create a copy of `tree`, adding specified flags, replacing uses of lclVar `deepVarNum` with
    // IntCnses with value `deepVarVal`.
    GenTree* gtCloneExpr(
        GenTree* tree, GenTreeFlags addFlags, unsigned varNum, int varVal, unsigned deepVarNum, int deepVarVal);

    // Create a copy of `tree`, optionally adding specified flags, and optionally mapping uses of local
    // `varNum` to int constants with value `varVal`.
    GenTree* gtCloneExpr(GenTree*     tree,
                         GenTreeFlags addFlags = GTF_EMPTY,
                         unsigned     varNum   = BAD_VAR_NUM,
                         int          varVal   = 0)
    {
        return gtCloneExpr(tree, addFlags, varNum, varVal, varNum, varVal);
    }

    Statement* gtCloneStmt(Statement* stmt)
    {
        GenTree* exprClone = gtCloneExpr(stmt->GetRootNode());
        return gtNewStmt(exprClone, stmt->GetDebugInfo());
    }

    // Internal helper for cloning a call
    GenTreeCall* gtCloneExprCallHelper(GenTreeCall* call,
                                       GenTreeFlags addFlags   = GTF_EMPTY,
                                       unsigned     deepVarNum = BAD_VAR_NUM,
                                       int          deepVarVal = 0);

    // Create copy of an inline or guarded devirtualization candidate tree.
    GenTreeCall* gtCloneCandidateCall(GenTreeCall* call);

    void gtUpdateSideEffects(Statement* stmt, GenTree* tree);

    void gtUpdateTreeAncestorsSideEffects(GenTree* tree);

    void gtUpdateStmtSideEffects(Statement* stmt);

    void gtUpdateNodeSideEffects(GenTree* tree);

    void gtUpdateNodeOperSideEffects(GenTree* tree);

    // Returns "true" iff the complexity (not formally defined, but first interpretation
    // is #of nodes in subtree) of "tree" is greater than "limit".
    // (This is somewhat redundant with the "GetCostEx()/GetCostSz()" fields, but can be used
    // before they have been set.)
    bool gtComplexityExceeds(GenTree** tree, unsigned limit);

    GenTree* gtReverseCond(GenTree* tree);

    static bool gtHasRef(GenTree* tree, unsigned lclNum);

    bool gtHasLocalsWithAddrOp(GenTree* tree);

    unsigned gtSetCallArgsOrder(CallArgs* args, bool lateArgs, int* callCostEx, int* callCostSz);
    unsigned gtSetMultiOpOrder(GenTreeMultiOp* multiOp);

    void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* base, bool constOnly);

#ifdef DEBUG
    unsigned gtHashValue(GenTree* tree);

    GenTree* gtWalkOpEffectiveVal(GenTree* op);
#endif

    void gtPrepareCost(GenTree* tree);
    bool gtIsLikelyRegVar(GenTree* tree);

    // Returns true iff the secondNode can be swapped with firstNode.
    bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);

    // Given an address expression, compute its costs and addressing mode opportunities,
    // and mark addressing mode candidates as GTF_DONT_CSE.
    // TODO-Throughput - Consider actually instantiating these early, to avoid
    // having to re-run the algorithm that looks for them (might also improve CQ).
    bool gtMarkAddrMode(GenTree* addr, int* costEx, int* costSz, var_types type);

    unsigned gtSetEvalOrder(GenTree* tree);

    void gtSetStmtInfo(Statement* stmt);

    // Returns "true" iff "node" has any of the side effects in "flags".
    bool gtNodeHasSideEffects(GenTree* node, GenTreeFlags flags);

    // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
    bool gtTreeHasSideEffects(GenTree* tree, GenTreeFlags flags);

    // Appends 'expr' in front of 'list'
    //    'list' will typically start off as 'nullptr'
    //    when 'list' is non-null a GT_COMMA node is used to insert 'expr'
    GenTree* gtBuildCommaList(GenTree* list, GenTree* expr);

    void gtExtractSideEffList(GenTree*     expr,
                              GenTree**    pList,
                              GenTreeFlags GenTreeFlags = GTF_SIDE_EFFECT,
                              bool         ignoreRoot   = false);

    // Static fields of struct types (and sometimes the types that those are reduced to) are represented by having the
    // static field contain an object pointer to the boxed struct.  This simplifies the GC implementation...but
    // complicates the JIT somewhat.  This predicate returns "true" iff a node with type "fieldNodeType", representing
    // the given "fldHnd", is such an object pointer.
    bool gtIsStaticFieldPtrToBoxedStruct(var_types fieldNodeType, CORINFO_FIELD_HANDLE fldHnd);

    bool gtStoreDefinesField(
        LclVarDsc* fieldVarDsc, ssize_t offset, unsigned size, ssize_t* pFieldStoreOffset, unsigned* pFieldStoreSize);

    // Return true if call is a recursive call; return false otherwise.
    // Note when inlining, this looks for calls back to the root method.
    bool gtIsRecursiveCall(GenTreeCall* call)
    {
        return gtIsRecursiveCall(call->gtCallMethHnd);
    }

    bool gtIsRecursiveCall(CORINFO_METHOD_HANDLE callMethodHandle)
    {
        return (callMethodHandle == impInlineRoot()->info.compMethodHnd);
    }

    //-------------------------------------------------------------------------

    GenTree* gtFoldExpr(GenTree* tree);
    GenTree* gtFoldExprConst(GenTree* tree);
    GenTree* gtFoldIndirConst(GenTreeIndir* indir);
    GenTree* gtFoldExprSpecial(GenTree* tree);
    GenTree* gtFoldBoxNullable(GenTree* tree);
    GenTree* gtFoldExprCompare(GenTree* tree);
    GenTree* gtFoldExprConditional(GenTree* tree);
    GenTree* gtCreateHandleCompare(genTreeOps             oper,
                                   GenTree*               op1,
                                   GenTree*               op2,
                                   CorInfoInlineTypeCheck typeCheckInliningResult);
    GenTree* gtFoldExprCall(GenTreeCall* call);
    GenTree* gtFoldTypeCompare(GenTree* tree);
    GenTree* gtFoldTypeEqualityCall(bool isEq, GenTree* op1, GenTree* op2);

    // Options to control behavior of gtTryRemoveBoxUpstreamEffects
    enum BoxRemovalOptions
    {
        BR_REMOVE_AND_NARROW, // remove effects, minimize remaining work, return possibly narrowed source tree
        BR_REMOVE_AND_NARROW_WANT_TYPE_HANDLE, // remove effects and minimize remaining work, return type handle tree
        BR_REMOVE_BUT_NOT_NARROW,              // remove effects, return original source tree
        BR_DONT_REMOVE,                        // check if removal is possible, return copy source tree
        BR_DONT_REMOVE_WANT_TYPE_HANDLE,       // check if removal is possible, return type handle tree
        BR_MAKE_LOCAL_COPY                     // revise box to copy to temp local and return local's address
    };

    GenTree* gtTryRemoveBoxUpstreamEffects(GenTree* tree, BoxRemovalOptions options = BR_REMOVE_AND_NARROW);
    GenTree* gtOptimizeEnumHasFlag(GenTree* thisOp, GenTree* flagOp);

    //-------------------------------------------------------------------------
    // Get the handle, if any.
    CORINFO_CLASS_HANDLE gtGetStructHandleIfPresent(GenTree* tree);
    // Get the handle, and assert if not found.
    CORINFO_CLASS_HANDLE gtGetStructHandle(GenTree* tree);
    // Get the handle for a ref type.
    CORINFO_CLASS_HANDLE gtGetClassHandle(GenTree* tree, bool* pIsExact, bool* pIsNonNull);
    // Get the class handle for an helper call
    CORINFO_CLASS_HANDLE gtGetHelperCallClassHandle(GenTreeCall* call, bool* pIsExact, bool* pIsNonNull);
    // Get the element handle for an array of ref type.
    CORINFO_CLASS_HANDLE gtGetArrayElementClassHandle(GenTree* array);
    // Get a class handle from a helper call argument
    CORINFO_CLASS_HANDLE gtGetHelperArgClassHandle(GenTree* array);
    // Get the class handle for a field
    CORINFO_CLASS_HANDLE gtGetFieldClassHandle(CORINFO_FIELD_HANDLE fieldHnd, bool* pIsExact, bool* pIsNonNull);
    // Check if this tree is a typeof()
    bool gtIsTypeof(GenTree* tree, CORINFO_CLASS_HANDLE* handle = nullptr);

    GenTree* gtCallGetDefinedRetBufLclAddr(GenTreeCall* call);

//-------------------------------------------------------------------------
// Functions to display the trees

#ifdef DEBUG
    void gtDispNode(GenTree* tree, IndentStack* indentStack, _In_z_ const char* msg, bool isLIR);

    void gtDispConst(GenTree* tree);
    void gtDispLeaf(GenTree* tree, IndentStack* indentStack);
    void gtDispNodeName(GenTree* tree);
#if FEATURE_MULTIREG_RET
    unsigned gtDispMultiRegCount(GenTree* tree);
#endif
    void gtDispRegVal(GenTree* tree);
    void gtDispVN(GenTree* tree);
    void gtDispCommonEndLine(GenTree* tree);

    enum IndentInfo
    {
        IINone,
        IIArc,
        IIArcTop,
        IIArcBottom,
        IIEmbedded,
        IIError,
        IndentInfoCount
    };
    void gtDispChild(GenTree*             child,
                     IndentStack*         indentStack,
                     IndentInfo           arcType,
                     _In_opt_ const char* msg     = nullptr,
                     bool                 topOnly = false);
    void gtDispTree(GenTree*             tree,
                    IndentStack*         indentStack = nullptr,
                    _In_opt_ const char* msg         = nullptr,
                    bool                 topOnly     = false,
                    bool                 isLIR       = false);
    void gtGetLclVarNameInfo(unsigned lclNum, const char** ilKindOut, const char** ilNameOut, unsigned* ilNumOut);
    int gtGetLclVarName(unsigned lclNum, char* buf, unsigned buf_remaining);
    char* gtGetLclVarName(unsigned lclNum);
    void gtDispLclVar(unsigned lclNum, bool padForBiggestDisp = true);
    void gtDispLclVarStructType(unsigned lclNum);
    void gtDispSsaName(unsigned lclNum, unsigned ssaNum, bool isDef);
    void gtDispClassLayout(ClassLayout* layout, var_types type);
    void gtDispILLocation(const ILLocation& loc);
    void gtDispStmt(Statement* stmt, const char* msg = nullptr);
    void gtDispBlockStmts(BasicBlock* block);
    void gtPrintArgPrefix(GenTreeCall* call, CallArg* arg, char** bufp, unsigned* bufLength);
    const char* gtGetWellKnownArgNameForArgMsg(WellKnownArg arg);
    void gtGetArgMsg(GenTreeCall* call, CallArg* arg, char* bufp, unsigned bufLength);
    void gtGetLateArgMsg(GenTreeCall* call, CallArg* arg, char* bufp, unsigned bufLength);
    void gtDispArgList(GenTreeCall* call, GenTree* lastCallOperand, IndentStack* indentStack);
    void gtDispFieldSeq(FieldSeq* fieldSeq, ssize_t offset);

    void gtDispRange(LIR::ReadOnlyRange const& range);

    void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);

    void gtDispLIRNode(GenTree* node, const char* prefixMsg = nullptr);
#endif

    // For tree walks

    enum fgWalkResult
    {
        WALK_CONTINUE,
        WALK_SKIP_SUBTREES,
        WALK_ABORT
    };
    struct fgWalkData;
    typedef fgWalkResult(fgWalkPreFn)(GenTree** pTree, fgWalkData* data);
    typedef fgWalkResult(fgWalkPostFn)(GenTree** pTree, fgWalkData* data);

    static fgWalkPreFn gtMarkColonCond;
    static fgWalkPreFn gtClearColonCond;

    struct FindLinkData
    {
        GenTree*  nodeToFind;
        GenTree** result;
        GenTree*  parent;
    };

    FindLinkData gtFindLink(Statement* stmt, GenTree* node);
    bool gtHasCatchArg(GenTree* tree);

    typedef ArrayStack<GenTree*> GenTreeStack;

    static bool gtHasCallOnStack(GenTreeStack* parentStack);

//=========================================================================
// BasicBlock functions
#ifdef DEBUG
    // This is a debug flag we will use to assert when creating block during codegen
    // as this interferes with procedure splitting. If you know what you're doing, set
    // it to true before creating the block. (DEBUG only)
    bool fgSafeBasicBlockCreation;
#endif

    BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           LclVarsInfo                                     XX
    XX                                                                           XX
    XX   The variables to be used by the code generator.                         XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

    //
    // For both PROMOTION_TYPE_NONE and PROMOTION_TYPE_DEPENDENT the struct will
    // be placed in the stack frame and it's fields must be laid out sequentially.
    //
    // For PROMOTION_TYPE_INDEPENDENT each of the struct's fields is replaced by
    //  a local variable that can be enregistered or placed in the stack frame.
    //  The fields do not need to be laid out sequentially
    //
    enum lvaPromotionType
    {
        PROMOTION_TYPE_NONE,        // The struct local is not promoted
        PROMOTION_TYPE_INDEPENDENT, // The struct local is promoted,
                                    //   and its field locals are independent of its parent struct local.
        PROMOTION_TYPE_DEPENDENT    // The struct local is promoted,
                                    //   but its field locals depend on its parent struct local.
    };

    /*****************************************************************************/

    enum FrameLayoutState
    {
        NO_FRAME_LAYOUT,
        INITIAL_FRAME_LAYOUT,
        PRE_REGALLOC_FRAME_LAYOUT,
        REGALLOC_FRAME_LAYOUT,
        TENTATIVE_FRAME_LAYOUT,
        FINAL_FRAME_LAYOUT
    };

public:
    RefCountState lvaRefCountState; // Current local ref count state

    bool lvaLocalVarRefCounted() const
    {
        return lvaRefCountState == RCS_NORMAL;
    }

    bool     lvaTrackedFixed; // true: We cannot add new 'tracked' variable
    unsigned lvaCount;        // total number of locals, which includes function arguments,
                              // special arguments, IL local variables, and JIT temporary variables

    LclVarDsc* lvaTable;    // variable descriptor table
    unsigned   lvaTableCnt; // lvaTable size (>= lvaCount)

    unsigned lvaTrackedCount;             // actual # of locals being tracked
    unsigned lvaTrackedCountInSizeTUnits; // min # of size_t's sufficient to hold a bit for all the locals being tracked

#ifdef DEBUG
    VARSET_TP lvaTrackedVars; // set of tracked variables
#endif
#ifndef TARGET_64BIT
    VARSET_TP lvaLongVars; // set of long (64-bit) variables
#endif
    VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables

    unsigned lvaCurEpoch; // VarSets are relative to a specific set of tracked var indices.
                          // It that changes, this changes.  VarSets from different epochs
                          // cannot be meaningfully combined.

    unsigned GetCurLVEpoch()
    {
        return lvaCurEpoch;
    }

    // reverse map of tracked number to var number
    unsigned  lvaTrackedToVarNumSize;
    unsigned* lvaTrackedToVarNum;

#if DOUBLE_ALIGN
#ifdef DEBUG
    // # of procs compiled a with double-aligned stack
    static unsigned s_lvaDoubleAlignedProcsCount;
#endif
#endif

    // Getters and setters for address-exposed and do-not-enregister local var properties.
    bool lvaVarAddrExposed(unsigned varNum) const;
    void lvaSetVarAddrExposed(unsigned varNum DEBUGARG(AddressExposedReason reason));
    void lvaSetHiddenBufferStructArg(unsigned varNum);
    void lvaSetVarLiveInOutOfHandler(unsigned varNum);
    bool lvaVarDoNotEnregister(unsigned varNum);

    void lvSetMinOptsDoNotEnreg();

    bool lvaEnregEHVars;
    bool lvaEnregMultiRegVars;

    void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));

    unsigned lvaVarargsHandleArg;
#ifdef TARGET_X86
    unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
                                      // arguments
#endif                                // TARGET_X86

    unsigned lvaInlinedPInvokeFrameVar; // variable representing the InlinedCallFrame
    unsigned lvaReversePInvokeFrameVar; // variable representing the reverse PInvoke frame
#if FEATURE_FIXED_OUT_ARGS
    unsigned lvaPInvokeFrameRegSaveVar; // variable representing the RegSave for PInvoke inlining.
#endif
    unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
                             // that tracks whether the lock has been taken

    unsigned lvaArg0Var; // The lclNum of arg0. Normally this will be info.compThisArg.
                         // However, if there is a "ldarga 0" or "starg 0" in the IL,
                         // we will redirect all "ldarg(a) 0" and "starg 0" to this temp.

    unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
                                        // in case there are multiple BBJ_RETURN blocks in the inlinee
                                        // or if the inlinee has GC ref locals.

#if FEATURE_FIXED_OUT_ARGS
    unsigned            lvaOutgoingArgSpaceVar;  // dummy TYP_LCLBLK var for fixed outgoing argument space
    PhasedVar<unsigned> lvaOutgoingArgSpaceSize; // size of fixed outgoing argument space
#endif                                           // FEATURE_FIXED_OUT_ARGS

    static unsigned GetOutgoingArgByteSize(unsigned sizeWithoutPadding)
    {
        return roundUp(sizeWithoutPadding, TARGET_POINTER_SIZE);
    }

    // Variable representing the return address. The helper-based tailcall
    // mechanism passes the address of the return address to a runtime helper
    // where it is used to detect tail-call chains.
    unsigned lvaRetAddrVar;

#if defined(DEBUG) && defined(TARGET_XARCH)

    unsigned lvaReturnSpCheck; // Stores SP to confirm it is not corrupted on return.

#endif // defined(DEBUG) && defined(TARGET_XARCH)

#if defined(DEBUG) && defined(TARGET_X86)

    unsigned lvaCallSpCheck; // Stores SP to confirm it is not corrupted after every call.

#endif // defined(DEBUG) && defined(TARGET_X86)

    bool lvaGenericsContextInUse;

    bool lvaKeepAliveAndReportThis(); // Synchronized instance method of a reference type, or
                                      // CORINFO_GENERICS_CTXT_FROM_THIS?
    bool lvaReportParamTypeArg();     // Exceptions and CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG?

//-------------------------------------------------------------------------
// All these frame offsets are inter-related and must be kept in sync

#if !defined(FEATURE_EH_FUNCLETS)
    // This is used for the callable handlers
    unsigned lvaShadowSPslotsVar; // TYP_BLK variable for all the shadow SP slots
#endif                            // FEATURE_EH_FUNCLETS

    int lvaCachedGenericContextArgOffs;
    int lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
                                            // THIS pointer

#ifdef JIT32_GCENCODER

    unsigned lvaLocAllocSPvar; // variable which stores the value of ESP after the last alloca/localloc

#endif // JIT32_GCENCODER

    unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper

    // TODO-Review: Prior to reg predict we reserve 24 bytes for Spill temps.
    //              after the reg predict we will use a computed maxTmpSize
    //              which is based upon the number of spill temps predicted by reg predict
    //              All this is necessary because if we under-estimate the size of the spill
    //              temps we could fail when encoding instructions that reference stack offsets for ARM.
    //
    // Pre codegen max spill temp size.
    static const unsigned MAX_SPILL_TEMP_SIZE = 24;

    //-------------------------------------------------------------------------

    unsigned lvaGetMaxSpillTempSize();
#ifdef TARGET_ARM
    bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
#endif // TARGET_ARM
    void lvaAssignFrameOffsets(FrameLayoutState curState);
    void lvaFixVirtualFrameOffsets();
    void lvaUpdateArgWithInitialReg(LclVarDsc* varDsc);
    void lvaUpdateArgsWithInitialReg();
    void lvaAssignVirtualFrameOffsetsToArgs();
#ifdef UNIX_AMD64_ABI
    int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs, int* callerArgOffset);
#else  // !UNIX_AMD64_ABI
    int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs);
#endif // !UNIX_AMD64_ABI
    void lvaAssignVirtualFrameOffsetsToLocals();
    int lvaAllocLocalAndSetVirtualOffset(unsigned lclNum, unsigned size, int stkOffs);
#ifdef TARGET_AMD64
    // Returns true if compCalleeRegsPushed (including RBP if used as frame pointer) is even.
    bool lvaIsCalleeSavedIntRegCountEven();
#endif
    void lvaAlignFrame();
    void lvaAssignFrameOffsetsToPromotedStructs();
    int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);

#ifdef DEBUG
    void lvaDumpRegLocation(unsigned lclNum);
    void lvaDumpFrameLocation(unsigned lclNum);
    void lvaDumpEntry(unsigned lclNum, FrameLayoutState curState, size_t refCntWtdWidth = 6);
    void lvaTableDump(FrameLayoutState curState = NO_FRAME_LAYOUT); // NO_FRAME_LAYOUT means use the current frame
                                                                    // layout state defined by lvaDoneFrameLayout
#endif

// Limit frames size to 1GB. The maximum is 2GB in theory - make it intentionally smaller
// to avoid bugs from borderline cases.
#define MAX_FrameSize 0x3FFFFFFF
    void lvaIncrementFrameSize(unsigned size);

    unsigned lvaFrameSize(FrameLayoutState curState);

    // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
    int lvaToCallerSPRelativeOffset(int offs, bool isFpBased, bool forRootFrame = true) const;

    // Returns the caller-SP-relative offset for the local variable "varNum."
    int lvaGetCallerSPRelativeOffset(unsigned varNum);

    // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
    int lvaGetSPRelativeOffset(unsigned varNum);

    int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
    int lvaGetInitialSPRelativeOffset(unsigned varNum);

    // True if this is an OSR compilation and this local is potentially
    // located on the original method stack frame.
    bool lvaIsOSRLocal(unsigned varNum);

    //------------------------ For splitting types ----------------------------

    void lvaInitTypeRef();

    void lvaInitArgs(InitVarDscInfo* varDscInfo);
    void lvaInitThisPtr(InitVarDscInfo* varDscInfo);
    void lvaInitRetBuffArg(InitVarDscInfo* varDscInfo, bool useFixedRetBufReg);
    void lvaInitUserArgs(InitVarDscInfo* varDscInfo, unsigned skipArgs, unsigned takeArgs);
    void lvaInitGenericsCtxt(InitVarDscInfo* varDscInfo);
    void lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo);

    void lvaInitVarDsc(LclVarDsc*              varDsc,
                       unsigned                varNum,
                       CorInfoType             corInfoType,
                       CORINFO_CLASS_HANDLE    typeHnd,
                       CORINFO_ARG_LIST_HANDLE varList,
                       CORINFO_SIG_INFO*       varSig);

    var_types lvaGetActualType(unsigned lclNum);
    var_types lvaGetRealType(unsigned lclNum);

    //-------------------------------------------------------------------------

    void lvaInit();

    LclVarDsc* lvaGetDesc(unsigned lclNum)
    {
        assert(lclNum < lvaCount);
        return &lvaTable[lclNum];
    }

    LclVarDsc* lvaGetDesc(unsigned lclNum) const
    {
        assert(lclNum < lvaCount);
        return &lvaTable[lclNum];
    }

    LclVarDsc* lvaGetDesc(const GenTreeLclVarCommon* lclVar)
    {
        return lvaGetDesc(lclVar->GetLclNum());
    }

    unsigned lvaTrackedIndexToLclNum(unsigned trackedIndex)
    {
        assert(trackedIndex < lvaTrackedCount);
        unsigned lclNum = lvaTrackedToVarNum[trackedIndex];
        assert(lclNum < lvaCount);
        return lclNum;
    }

    LclVarDsc* lvaGetDescByTrackedIndex(unsigned trackedIndex)
    {
        return lvaGetDesc(lvaTrackedIndexToLclNum(trackedIndex));
    }

    unsigned lvaGetLclNum(const LclVarDsc* varDsc)
    {
        assert((lvaTable <= varDsc) && (varDsc < lvaTable + lvaCount)); // varDsc must point within the table
        assert(((char*)varDsc - (char*)lvaTable) % sizeof(LclVarDsc) ==
               0); // varDsc better not point in the middle of a variable
        unsigned varNum = (unsigned)(varDsc - lvaTable);
        assert(varDsc == &lvaTable[varNum]);
        return varNum;
    }

    unsigned lvaLclSize(unsigned varNum);
    unsigned lvaLclExactSize(unsigned varNum);

    bool lvaHaveManyLocals() const;

    unsigned lvaGrabTemp(bool shortLifetime DEBUGARG(const char* reason));
    unsigned lvaGrabTemps(unsigned cnt DEBUGARG(const char* reason));
    unsigned lvaGrabTempWithImplicitUse(bool shortLifetime DEBUGARG(const char* reason));

    void lvaSortByRefCount();

    PhaseStatus lvaMarkLocalVars(); // Local variable ref-counting
    void lvaComputeRefCounts(bool isRecompute, bool setSlotNumbers);
    void lvaMarkLocalVars(BasicBlock* block, bool isRecompute);

    void lvaAllocOutgoingArgSpaceVar(); // Set up lvaOutgoingArgSpaceVar

#ifdef DEBUG
    struct lvaStressLclFldArgs
    {
        Compiler* m_pCompiler;
        bool      m_bFirstPass;
    };

    static fgWalkPreFn lvaStressLclFldCB;
    void               lvaStressLclFld();
    unsigned lvaStressLclFldPadding(unsigned lclNum);

    void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
    void lvaDispVarSet(VARSET_VALARG_TP set);

#endif

#ifdef TARGET_ARM
    int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset, bool isFloatUsage);
#else
    int lvaFrameAddress(int varNum, bool* pFPbased);
#endif

    bool lvaIsParameter(unsigned varNum);
    bool lvaIsRegArgument(unsigned varNum);
    bool lvaIsOriginalThisArg(unsigned varNum); // Is this varNum the original this argument?
    bool lvaIsOriginalThisReadOnly();           // return true if there is no place in the code
                                                // that writes to arg0

#ifdef TARGET_X86
    bool lvaIsArgAccessedViaVarArgsCookie(unsigned lclNum)
    {
        if (!info.compIsVarArgs)
        {
            return false;
        }

        LclVarDsc* varDsc = lvaGetDesc(lclNum);
        return varDsc->lvIsParam && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg);
    }
#endif // TARGET_X86

    bool lvaIsImplicitByRefLocal(unsigned lclNum) const;
    bool lvaIsLocalImplicitlyAccessedByRef(unsigned lclNum) const;

    // Returns true if this local var is a multireg struct
    bool lvaIsMultiregStruct(LclVarDsc* varDsc, bool isVararg);

    // If the local is a TYP_STRUCT, get/set a class handle describing it
    CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
    void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck);
    void lvaSetStructUsedAsVarArg(unsigned varNum);

    // If the local is TYP_REF, set or update the associated class information.
    void lvaSetClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
    void lvaSetClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
    void lvaUpdateClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
    void lvaUpdateClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);

#define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct

    // Info about struct type fields.
    struct lvaStructFieldInfo
    {
        CORINFO_FIELD_HANDLE fldHnd;
        unsigned char        fldOffset;
        unsigned char        fldOrdinal;
        var_types            fldType;
        unsigned             fldSize;
        CORINFO_CLASS_HANDLE fldTypeHnd;

        lvaStructFieldInfo()
            : fldHnd(nullptr), fldOffset(0), fldOrdinal(0), fldType(TYP_UNDEF), fldSize(0), fldTypeHnd(nullptr)
        {
        }
    };

    // Info about a struct type, instances of which may be candidates for promotion.
    struct lvaStructPromotionInfo
    {
        CORINFO_CLASS_HANDLE typeHnd;
        bool                 canPromote;
        bool                 containsHoles;
        bool                 customLayout;
        bool                 fieldsSorted;
        unsigned char        fieldCnt;
        lvaStructFieldInfo   fields[MAX_NumOfFieldsInPromotableStruct];

        lvaStructPromotionInfo(CORINFO_CLASS_HANDLE typeHnd = nullptr)
            : typeHnd(typeHnd)
            , canPromote(false)
            , containsHoles(false)
            , customLayout(false)
            , fieldsSorted(false)
            , fieldCnt(0)
        {
        }
    };

    struct lvaFieldOffsetCmp
    {
        bool operator()(const lvaStructFieldInfo& field1, const lvaStructFieldInfo& field2);
    };

    // This class is responsible for checking validity and profitability of struct promotion.
    // If it is both legal and profitable, then TryPromoteStructVar promotes the struct and initializes
    // necessary information for fgMorphStructField to use.
    class StructPromotionHelper
    {
    public:
        StructPromotionHelper(Compiler* compiler);

        bool CanPromoteStructType(CORINFO_CLASS_HANDLE typeHnd);
        bool TryPromoteStructVar(unsigned lclNum);
        void Clear()
        {
            structPromotionInfo.typeHnd = NO_CLASS_HANDLE;
        }

    private:
        bool CanPromoteStructVar(unsigned lclNum);
        bool ShouldPromoteStructVar(unsigned lclNum);
        void PromoteStructVar(unsigned lclNum);
        void SortStructFields();

        bool CanConstructAndPromoteField(lvaStructPromotionInfo* structPromotionInfo);

        lvaStructFieldInfo GetFieldInfo(CORINFO_FIELD_HANDLE fieldHnd, BYTE ordinal);
        bool TryPromoteStructField(lvaStructFieldInfo& outerFieldInfo);

    private:
        Compiler*              compiler;
        lvaStructPromotionInfo structPromotionInfo;
    };

    StructPromotionHelper* structPromotionHelper;

    unsigned lvaGetFieldLocal(const LclVarDsc* varDsc, unsigned int fldOffset);
    lvaPromotionType lvaGetPromotionType(const LclVarDsc* varDsc);
    lvaPromotionType lvaGetPromotionType(unsigned varNum);
    lvaPromotionType lvaGetParentPromotionType(const LclVarDsc* varDsc);
    lvaPromotionType lvaGetParentPromotionType(unsigned varNum);
    bool lvaIsFieldOfDependentlyPromotedStruct(const LclVarDsc* varDsc);
    bool lvaIsGCTracked(const LclVarDsc* varDsc);

#if defined(FEATURE_SIMD)
    bool lvaMapSimd12ToSimd16(const LclVarDsc* varDsc)
    {
        assert(varDsc->lvType == TYP_SIMD12);
        assert(varDsc->lvExactSize == 12);

#if defined(TARGET_64BIT)
        assert(compMacOsArm64Abi() || varDsc->lvSize() == 16);
#endif // defined(TARGET_64BIT)

        // We make local variable SIMD12 types 16 bytes instead of just 12.
        // lvSize() will return 16 bytes for SIMD12, even for fields.
        // However, we can't do that mapping if the var is a dependently promoted struct field.
        // Such a field must remain its exact size within its parent struct unless it is a single
        // field *and* it is the only field in a struct of 16 bytes.
        if (varDsc->lvSize() != 16)
        {
            return false;
        }
        if (lvaIsFieldOfDependentlyPromotedStruct(varDsc))
        {
            LclVarDsc* parentVarDsc = lvaGetDesc(varDsc->lvParentLcl);
            return (parentVarDsc->lvFieldCnt == 1) && (parentVarDsc->lvSize() == 16);
        }
        return true;
    }
#endif // defined(FEATURE_SIMD)

    unsigned lvaGSSecurityCookie; // LclVar number
    bool     lvaTempsHaveLargerOffsetThanVars();

    // Returns "true" iff local variable "lclNum" is in SSA form.
    bool lvaInSsa(unsigned lclNum) const
    {
        return lvaGetDesc(lclNum)->lvInSsa;
    }

    unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX

#if defined(FEATURE_EH_FUNCLETS)
    unsigned lvaPSPSym; // variable representing the PSPSym
#endif

    InlineInfo*     impInlineInfo; // Only present for inlinees
    InlineStrategy* m_inlineStrategy;

    InlineContext* compInlineContext; // Always present

    // The Compiler* that is the root of the inlining tree of which "this" is a member.
    Compiler* impInlineRoot();

#if defined(DEBUG) || defined(INLINE_DATA)
    unsigned __int64 getInlineCycleCount()
    {
        return m_compCycles;
    }
#endif // defined(DEBUG) || defined(INLINE_DATA)

    bool fgNoStructPromotion;      // Set to TRUE to turn off struct promotion for this method.
    bool fgNoStructParamPromotion; // Set to TRUE to turn off struct promotion for parameters this method.

    //=========================================================================
    //                          PROTECTED
    //=========================================================================

protected:
    //---------------- Local variable ref-counting ----------------------------

    void lvaMarkLclRefs(GenTree* tree, BasicBlock* block, Statement* stmt, bool isRecompute);
    bool IsDominatedByExceptionalEntry(BasicBlock* block);
    void SetVolatileHint(LclVarDsc* varDsc);

    // Keeps the mapping from SSA #'s to VN's for the implicit memory variables.
    SsaDefArray<SsaMemDef> lvMemoryPerSsaData;

public:
    // Returns the address of the per-Ssa data for memory at the given ssaNum (which is required
    // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
    // not an SSA variable).
    SsaMemDef* GetMemoryPerSsaData(unsigned ssaNum)
    {
        return lvMemoryPerSsaData.GetSsaDef(ssaNum);
    }

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           Importer                                        XX
    XX                                                                           XX
    XX   Imports the given method and converts it to semantic trees              XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

private:
    // For prefixFlags
    enum
    {
        PREFIX_TAILCALL_EXPLICIT = 0x00000001, // call has "tail" IL prefix
        PREFIX_TAILCALL_IMPLICIT =
            0x00000010, // call is treated as having "tail" prefix even though there is no "tail" IL prefix
        PREFIX_TAILCALL_STRESS =
            0x00000100, // call doesn't "tail" IL prefix but is treated as explicit because of tail call stress
        PREFIX_TAILCALL    = (PREFIX_TAILCALL_EXPLICIT | PREFIX_TAILCALL_IMPLICIT | PREFIX_TAILCALL_STRESS),
        PREFIX_VOLATILE    = 0x00001000,
        PREFIX_UNALIGNED   = 0x00010000,
        PREFIX_CONSTRAINED = 0x00100000,
        PREFIX_READONLY    = 0x01000000
    };

    static void impValidateMemoryAccessOpcode(const BYTE* codeAddr, const BYTE* codeEndp, bool volatilePrefix);
    static OPCODE impGetNonPrefixOpcode(const BYTE* codeAddr, const BYTE* codeEndp);
    static bool impOpcodeIsCallOpcode(OPCODE opcode);

public:
    void impInit();
    void impImport();

    CORINFO_CLASS_HANDLE impGetRefAnyClass();
    CORINFO_CLASS_HANDLE impGetRuntimeArgumentHandle();
    CORINFO_CLASS_HANDLE impGetTypeHandleClass();
    CORINFO_CLASS_HANDLE impGetStringClass();
    CORINFO_CLASS_HANDLE impGetObjectClass();

    // Returns underlying type of handles returned by ldtoken instruction
    var_types GetRuntimeHandleUnderlyingType()
    {
        // RuntimeTypeHandle is backed by raw pointer on NativeAOT and by object reference on other runtimes
        return IsTargetAbi(CORINFO_NATIVEAOT_ABI) ? TYP_I_IMPL : TYP_REF;
    }

    void impDevirtualizeCall(GenTreeCall*            call,
                             CORINFO_RESOLVED_TOKEN* pResolvedToken,
                             CORINFO_METHOD_HANDLE*  method,
                             unsigned*               methodFlags,
                             CORINFO_CONTEXT_HANDLE* contextHandle,
                             CORINFO_CONTEXT_HANDLE* exactContextHandle,
                             bool                    isLateDevirtualization,
                             bool                    isExplicitTailCall,
                             IL_OFFSET               ilOffset = BAD_IL_OFFSET);

    bool impConsiderCallProbe(GenTreeCall* call, IL_OFFSET ilOffset);

    enum class GDVProbeType
    {
        None,
        ClassProfile,
        MethodProfile,
        MethodAndClassProfile,
    };

    GDVProbeType compClassifyGDVProbeType(GenTreeCall* call);

    //=========================================================================
    //                          PROTECTED
    //=========================================================================

protected:
    //-------------------- Stack manipulation ---------------------------------

    unsigned impStkSize; // Size of the full stack

#define SMALL_STACK_SIZE 16 // number of elements in impSmallStack

    struct SavedStack // used to save/restore stack contents.
    {
        unsigned    ssDepth; // number of values on stack
        StackEntry* ssTrees; // saved tree values
    };

    bool impIsPrimitive(CorInfoType type);
    bool impILConsumesAddr(const BYTE* codeAddr);

    void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);

    void impPushOnStack(GenTree* tree, typeInfo ti);
    void       impPushNullObjRefOnStack();
    StackEntry impPopStack();
    void impPopStack(unsigned n);
    StackEntry& impStackTop(unsigned n = 0);
    unsigned impStackHeight();

    void impSaveStackState(SavedStack* savePtr, bool copy);
    void impRestoreStackState(SavedStack* savePtr);

    GenTree* impImportLdvirtftn(GenTree* thisPtr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);

    enum class BoxPatterns
    {
        None                  = 0,
        IsByRefLike           = 1,
        MakeInlineObservation = 2,
    };

    int impBoxPatternMatch(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                           const BYTE*             codeAddr,
                           const BYTE*             codeEndp,
                           BoxPatterns             opts);
    void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);

    void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);

    bool impCanPInvokeInline();
    bool impCanPInvokeInlineCallSite(BasicBlock* block);
    void impCheckForPInvokeCall(
        GenTreeCall* call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags, BasicBlock* block);
    GenTreeCall* impImportIndirectCall(CORINFO_SIG_INFO* sig, const DebugInfo& di = DebugInfo());
    void impPopArgsForUnmanagedCall(GenTreeCall* call, CORINFO_SIG_INFO* sig);

    void impInsertHelperCall(CORINFO_HELPER_DESC* helperCall);
    void impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
    void impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);

    var_types impImportCall(OPCODE                  opcode,
                            CORINFO_RESOLVED_TOKEN* pResolvedToken,
                            CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
                                                                               // type parameter?
                            GenTree*           newobjThis,
                            int                prefixFlags,
                            CORINFO_CALL_INFO* callInfo,
                            IL_OFFSET          rawILOffset);

    CORINFO_CLASS_HANDLE impGetSpecialIntrinsicExactReturnType(GenTreeCall* call);

    GenTree* impFixupCallStructReturn(GenTreeCall* call, CORINFO_CLASS_HANDLE retClsHnd);

    GenTree* impFixupStructReturnType(GenTree* op);

#ifdef DEBUG
    var_types impImportJitTestLabelMark(int numArgs);
#endif // DEBUG

    GenTree* impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);

    GenTree* impImportStaticReadOnlyField(CORINFO_FIELD_HANDLE field, CORINFO_CLASS_HANDLE ownerCls);
    GenTree* impImportCnsTreeFromBuffer(uint8_t* buffer, var_types valueType);

    GenTree* impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                        CORINFO_ACCESS_FLAGS    access,
                                        CORINFO_FIELD_INFO*     pFieldInfo,
                                        var_types               lclTyp);

    static void impBashVarAddrsToI(GenTree* tree1, GenTree* tree2 = nullptr);

    GenTree* impImplicitIorI4Cast(GenTree* tree, var_types dstTyp);

    GenTree* impImplicitR4orR8Cast(GenTree* tree, var_types dstTyp);

    void impImportLeave(BasicBlock* block);
    void impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr);
    GenTree* impTypeIsAssignable(GenTree* typeTo, GenTree* typeFrom);

    // Mirrors StringComparison.cs
    enum StringComparison
    {
        Ordinal           = 4,
        OrdinalIgnoreCase = 5
    };
    enum StringComparisonJoint
    {
        Eq,  // (d1 == cns1) && (s2 == cns2)
        Xor, // (d1 ^ cns1) | (s2 ^ cns2)
    };
    GenTree* impStringEqualsOrStartsWith(bool startsWith, CORINFO_SIG_INFO* sig, unsigned methodFlags);
    GenTree* impSpanEqualsOrStartsWith(bool startsWith, CORINFO_SIG_INFO* sig, unsigned methodFlags);
    GenTree* impExpandHalfConstEquals(GenTreeLclVar*   data,
                                      GenTree*         lengthFld,
                                      bool             checkForNull,
                                      bool             startsWith,
                                      WCHAR*           cnsData,
                                      int              len,
                                      int              dataOffset,
                                      StringComparison cmpMode);
    GenTree* impCreateCompareInd(GenTreeLclVar*        obj,
                                 var_types             type,
                                 ssize_t               offset,
                                 ssize_t               value,
                                 StringComparison      ignoreCase,
                                 StringComparisonJoint joint = Eq);
    GenTree* impExpandHalfConstEqualsSWAR(
        GenTreeLclVar* data, WCHAR* cns, int len, int dataOffset, StringComparison cmpMode);
    GenTree* impExpandHalfConstEqualsSIMD(
        GenTreeLclVar* data, WCHAR* cns, int len, int dataOffset, StringComparison cmpMode);
    GenTreeStrCon* impGetStrConFromSpan(GenTree* span);

    GenTree* impIntrinsic(GenTree*                newobjThis,
                          CORINFO_CLASS_HANDLE    clsHnd,
                          CORINFO_METHOD_HANDLE   method,
                          CORINFO_SIG_INFO*       sig,
                          unsigned                methodFlags,
                          int                     memberRef,
                          bool                    readonlyCall,
                          bool                    tailCall,
                          CORINFO_RESOLVED_TOKEN* pContstrainedResolvedToken,
                          CORINFO_THIS_TRANSFORM  constraintCallThisTransform,
                          NamedIntrinsic*         pIntrinsicName,
                          bool*                   isSpecialIntrinsic = nullptr);
    GenTree* impMathIntrinsic(CORINFO_METHOD_HANDLE method,
                              CORINFO_SIG_INFO*     sig,
                              var_types             callType,
                              NamedIntrinsic        intrinsicName,
                              bool                  tailCall);
    NamedIntrinsic lookupNamedIntrinsic(CORINFO_METHOD_HANDLE method);
    GenTree* impUnsupportedNamedIntrinsic(unsigned              helper,
                                          CORINFO_METHOD_HANDLE method,
                                          CORINFO_SIG_INFO*     sig,
                                          bool                  mustExpand);

    GenTree* impSRCSUnsafeIntrinsic(NamedIntrinsic        intrinsic,
                                    CORINFO_CLASS_HANDLE  clsHnd,
                                    CORINFO_METHOD_HANDLE method,
                                    CORINFO_SIG_INFO*     sig);

#ifdef FEATURE_HW_INTRINSICS
    GenTree* impHWIntrinsic(NamedIntrinsic        intrinsic,
                            CORINFO_CLASS_HANDLE  clsHnd,
                            CORINFO_METHOD_HANDLE method,
                            CORINFO_SIG_INFO*     sig,
                            bool                  mustExpand);
    GenTree* impSimdAsHWIntrinsic(NamedIntrinsic        intrinsic,
                                  CORINFO_CLASS_HANDLE  clsHnd,
                                  CORINFO_METHOD_HANDLE method,
                                  CORINFO_SIG_INFO*     sig,
                                  GenTree*              newobjThis);

protected:
    bool compSupportsHWIntrinsic(CORINFO_InstructionSet isa);

    GenTree* impSimdAsHWIntrinsicSpecial(NamedIntrinsic       intrinsic,
                                         CORINFO_CLASS_HANDLE clsHnd,
                                         CORINFO_SIG_INFO*    sig,
                                         var_types            retType,
                                         CorInfoType          simdBaseJitType,
                                         unsigned             simdSize,
                                         GenTree*             newobjThis);

    GenTree* impSpecialIntrinsic(NamedIntrinsic        intrinsic,
                                 CORINFO_CLASS_HANDLE  clsHnd,
                                 CORINFO_METHOD_HANDLE method,
                                 CORINFO_SIG_INFO*     sig,
                                 CorInfoType           simdBaseJitType,
                                 var_types             retType,
                                 unsigned              simdSize);

    GenTree* getArgForHWIntrinsic(var_types            argType,
                                  CORINFO_CLASS_HANDLE argClass,
                                  bool                 expectAddr = false,
                                  GenTree*             newobjThis = nullptr);
    GenTree* impNonConstFallback(NamedIntrinsic intrinsic, var_types simdType, CorInfoType simdBaseJitType);
    GenTree* addRangeCheckIfNeeded(
        NamedIntrinsic intrinsic, GenTree* immOp, bool mustExpand, int immLowerBound, int immUpperBound);
    GenTree* addRangeCheckForHWIntrinsic(GenTree* immOp, int immLowerBound, int immUpperBound);

#ifdef TARGET_XARCH
    GenTree* impBaseIntrinsic(NamedIntrinsic        intrinsic,
                              CORINFO_CLASS_HANDLE  clsHnd,
                              CORINFO_METHOD_HANDLE method,
                              CORINFO_SIG_INFO*     sig,
                              CorInfoType           simdBaseJitType,
                              var_types             retType,
                              unsigned              simdSize);
    GenTree* impSSEIntrinsic(NamedIntrinsic intrinsic, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig);
    GenTree* impSSE2Intrinsic(NamedIntrinsic intrinsic, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig);
    GenTree* impAvxOrAvx2Intrinsic(NamedIntrinsic intrinsic, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig);
    GenTree* impBMI1OrBMI2Intrinsic(NamedIntrinsic intrinsic, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig);

    GenTree* impSerializeIntrinsic(NamedIntrinsic intrinsic, CORINFO_METHOD_HANDLE method, CORINFO_SIG_INFO* sig);
#endif // TARGET_XARCH
#endif // FEATURE_HW_INTRINSICS
    GenTree* impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
                                     CORINFO_SIG_INFO*    sig,
                                     int                  memberRef,
                                     bool                 readonlyCall,
                                     NamedIntrinsic       intrinsicName);
    GenTree* impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
    GenTree* impCreateSpanIntrinsic(CORINFO_SIG_INFO* sig);

    GenTree* impKeepAliveIntrinsic(GenTree* objToKeepAlive);

    GenTree* impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);

    GenTree* impTransformThis(GenTree*                thisPtr,
                              CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
                              CORINFO_THIS_TRANSFORM  transform);

    //----------------- Manipulating the trees and stmts ----------------------

    Statement* impStmtList; // Statements for the BB being imported.
    Statement* impLastStmt; // The last statement for the current BB.

public:
    static const unsigned CHECK_SPILL_ALL  = static_cast<unsigned>(-1);
    static const unsigned CHECK_SPILL_NONE = static_cast<unsigned>(-2);

    void impBeginTreeList();
    void impEndTreeList(BasicBlock* block, Statement* firstStmt, Statement* lastStmt);
    void impEndTreeList(BasicBlock* block);
    void impAppendStmtCheck(Statement* stmt, unsigned chkLevel);
    void impAppendStmt(Statement* stmt, unsigned chkLevel, bool checkConsumedDebugInfo = true);
    void impAppendStmt(Statement* stmt);
    void impInsertStmtBefore(Statement* stmt, Statement* stmtBefore);
    Statement* impAppendTree(GenTree* tree, unsigned chkLevel, const DebugInfo& di, bool checkConsumedDebugInfo = true);
    void impInsertTreeBefore(GenTree* tree, const DebugInfo& di, Statement* stmtBefore);
    void impAssignTempGen(unsigned         tmp,
                          GenTree*         val,
                          unsigned         curLevel   = CHECK_SPILL_NONE,
                          Statement**      pAfterStmt = nullptr,
                          const DebugInfo& di         = DebugInfo(),
                          BasicBlock*      block      = nullptr);
    void impAssignTempGen(unsigned             tmpNum,
                          GenTree*             val,
                          CORINFO_CLASS_HANDLE structHnd,
                          unsigned             curLevel,
                          Statement**          pAfterStmt = nullptr,
                          const DebugInfo&     di         = DebugInfo(),
                          BasicBlock*          block      = nullptr);

    Statement* impExtractLastStmt();
    GenTree* impCloneExpr(GenTree*             tree,
                          GenTree**            clone,
                          CORINFO_CLASS_HANDLE structHnd,
                          unsigned             curLevel,
                          Statement** pAfterStmt DEBUGARG(const char* reason));
    GenTree* impAssignStruct(GenTree*             dest,
                             GenTree*             src,
                             CORINFO_CLASS_HANDLE structHnd,
                             unsigned             curLevel,
                             Statement**          pAfterStmt = nullptr,
                             const DebugInfo&     di         = DebugInfo(),
                             BasicBlock*          block      = nullptr);
    GenTree* impAssignStructPtr(GenTree*             dest,
                                GenTree*             src,
                                CORINFO_CLASS_HANDLE structHnd,
                                unsigned             curLevel,
                                Statement**          pAfterStmt = nullptr,
                                const DebugInfo&     di         = DebugInfo(),
                                BasicBlock*          block      = nullptr);

    GenTree* impGetStructAddr(GenTree* structVal, CORINFO_CLASS_HANDLE structHnd, unsigned curLevel, bool willDeref);

    var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd, CorInfoType* simdBaseJitType = nullptr);

    GenTree* impNormStructVal(GenTree* structVal, CORINFO_CLASS_HANDLE structHnd, unsigned curLevel);

    GenTree* impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                              bool*                   pRuntimeLookup    = nullptr,
                              bool                    mustRestoreHandle = false,
                              bool                    importParent      = false);

    GenTree* impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                         bool*                   pRuntimeLookup    = nullptr,
                                         bool                    mustRestoreHandle = false)
    {
        return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, true);
    }

    GenTree* impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                             CORINFO_LOOKUP*         pLookup,
                             GenTreeFlags            flags,
                             void*                   compileTimeHandle);

    GenTree* getRuntimeContextTree(CORINFO_RUNTIME_LOOKUP_KIND kind);

    GenTree* impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                    CORINFO_LOOKUP*         pLookup,
                                    void*                   compileTimeHandle);

    GenTree* impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, GenTreeFlags flags, void* compileTimeHandle);

    GenTreeCall* impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                           CorInfoHelpFunc         helper,
                                           var_types               type,
                                           CORINFO_LOOKUP_KIND*    pGenericLookupKind = nullptr,
                                           GenTree*                arg1               = nullptr);

    bool impIsCastHelperEligibleForClassProbe(GenTree* tree);
    bool impIsCastHelperMayHaveProfileData(CorInfoHelpFunc helper);

    GenTree* impCastClassOrIsInstToTree(
        GenTree* op1, GenTree* op2, CORINFO_RESOLVED_TOKEN* pResolvedToken, bool isCastClass, IL_OFFSET ilOffset);

    GenTree* impOptimizeCastClassOrIsInst(GenTree* op1, CORINFO_RESOLVED_TOKEN* pResolvedToken, bool isCastClass);

    bool VarTypeIsMultiByteAndCanEnreg(var_types                type,
                                       CORINFO_CLASS_HANDLE     typeClass,
                                       unsigned*                typeSize,
                                       bool                     forReturn,
                                       bool                     isVarArg,
                                       CorInfoCallConvExtension callConv);

    bool IsIntrinsicImplementedByUserCall(NamedIntrinsic intrinsicName);
    bool IsTargetIntrinsic(NamedIntrinsic intrinsicName);
    bool IsMathIntrinsic(NamedIntrinsic intrinsicName);
    bool IsMathIntrinsic(GenTree* tree);

private:
    //----------------- Importing the method ----------------------------------

    CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.

#ifdef DEBUG
    unsigned    impCurOpcOffs;
    const char* impCurOpcName;
    bool        impNestedStackSpill;

    // For displaying instrs with generated native code (-n:B)
    Statement* impLastILoffsStmt; // oldest stmt added for which we did not call SetLastILOffset().
    void       impNoteLastILoffs();
#endif

    // Debug info of current statement being imported. It gets set to contain
    // no IL location (!impCurStmtDI.GetLocation().IsValid) after it has been
    // set in the appended trees. Then it gets updated at IL instructions for
    // which we have to report mapping info.
    // It will always contain the current inline context.
    DebugInfo impCurStmtDI;

    DebugInfo impCreateDIWithCurrentStackInfo(IL_OFFSET offs, bool isCall);
    void impCurStmtOffsSet(IL_OFFSET offs);

    void impNoteBranchOffs();

    unsigned impInitBlockLineInfo();

    bool impIsThis(GenTree* obj);

    void impPopCallArgs(CORINFO_SIG_INFO* sig, GenTreeCall* call);

public:
    static bool impCheckImplicitArgumentCoercion(var_types sigType, var_types nodeType);

private:
    void impPopReverseCallArgs(CORINFO_SIG_INFO* sig, GenTreeCall* call, unsigned skipReverseCount);

    //---------------- Spilling the importer stack ----------------------------

    // The maximum number of bytes of IL processed without clean stack state.
    // It allows to limit the maximum tree size and depth.
    static const unsigned MAX_TREE_SIZE = 200;
    bool impCanSpillNow(OPCODE prevOpcode);

    struct PendingDsc
    {
        PendingDsc* pdNext;
        BasicBlock* pdBB;
        SavedStack  pdSavedStack;
    };

    PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
    PendingDsc* impPendingFree; // Freed up dscs that can be reused

    // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
    JitExpandArray<BYTE> impPendingBlockMembers;

    // Return the byte for "b" (allocating/extending impPendingBlockMembers if necessary.)
    // Operates on the map in the top-level ancestor.
    BYTE impGetPendingBlockMember(BasicBlock* blk)
    {
        return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
    }

    // Set the byte for "b" to "val" (allocating/extending impPendingBlockMembers if necessary.)
    // Operates on the map in the top-level ancestor.
    void impSetPendingBlockMember(BasicBlock* blk, BYTE val)
    {
        impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
    }

    bool impCanReimport;

    bool impSpillStackEntry(unsigned level,
                            unsigned varNum
#ifdef DEBUG
                            ,
                            bool        bAssertOnRecursion,
                            const char* reason
#endif
                            );

    void impSpillStackEnsure(bool spillLeaves = false);
    void impEvalSideEffects();
    void impSpillSpecialSideEff();
    void impSpillSideEffect(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
    void impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
    void impSpillLclRefs(unsigned lclNum, unsigned chkLevel);

    BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd, bool isSingleBlockFilter);

    bool impBlockIsInALoop(BasicBlock* block);
    void impImportBlockCode(BasicBlock* block);

    void impReimportMarkBlock(BasicBlock* block);
    void impReimportMarkSuccessors(BasicBlock* block);

    void impVerifyEHBlock(BasicBlock* block, bool isTryStart);

    void impImportBlockPending(BasicBlock* block);

    // Similar to impImportBlockPending, but assumes that block has already been imported once and is being
    // reimported for some reason.  It specifically does *not* look at verCurrentState to set the EntryState
    // for the block, but instead, just re-uses the block's existing EntryState.
    void impReimportBlockPending(BasicBlock* block);

    var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTree** pOp1, GenTree** pOp2);

    void impImportBlock(BasicBlock* block);

    // Assumes that "block" is a basic block that completes with a non-empty stack. We will assign the values
    // on the stack to local variables (the "spill temp" variables). The successor blocks will assume that
    // its incoming stack contents are in those locals. This requires "block" and its successors to agree on
    // the variables that will be used -- and for all the predecessors of those successors, and the
    // successors of those predecessors, etc. Call such a set of blocks closed under alternating
    // successor/predecessor edges a "spill clique." A block is a "predecessor" or "successor" member of the
    // clique (or, conceivably, both). Each block has a specified sequence of incoming and outgoing spill
    // temps. If "block" already has its outgoing spill temps assigned (they are always a contiguous series
    // of local variable numbers, so we represent them with the base local variable number), returns that.
    // Otherwise, picks a set of spill temps, and propagates this choice to all blocks in the spill clique of
    // which "block" is a member (asserting, in debug mode, that no block in this clique had its spill temps
    // chosen already. More precisely, that the incoming or outgoing spill temps are not chosen, depending
    // on which kind of member of the clique the block is).
    unsigned impGetSpillTmpBase(BasicBlock* block);

    // Assumes that "block" is a basic block that completes with a non-empty stack. We have previously
    // assigned the values on the stack to local variables (the "spill temp" variables). The successor blocks
    // will assume that its incoming stack contents are in those locals. This requires "block" and its
    // successors to agree on the variables and their types that will be used.  The CLI spec allows implicit
    // conversions between 'int' and 'native int' or 'float' and 'double' stack types. So one predecessor can
    // push an int and another can push a native int.  For 64-bit we have chosen to implement this by typing
    // the "spill temp" as native int, and then importing (or re-importing as needed) so that all the
    // predecessors in the "spill clique" push a native int (sign-extending if needed), and all the
    // successors receive a native int. Similarly float and double are unified to double.
    // This routine is called after a type-mismatch is detected, and it will walk the spill clique to mark
    // blocks for re-importation as appropriate (both successors, so they get the right incoming type, and
    // predecessors, so they insert an upcast if needed).
    void impReimportSpillClique(BasicBlock* block);

    // When we compute a "spill clique" (see above) these byte-maps are allocated to have a byte per basic
    // block, and represent the predecessor and successor members of the clique currently being computed.
    // *** Access to these will need to be locked in a parallel compiler.
    JitExpandArray<BYTE> impSpillCliquePredMembers;
    JitExpandArray<BYTE> impSpillCliqueSuccMembers;

    enum SpillCliqueDir
    {
        SpillCliquePred,
        SpillCliqueSucc
    };

    // Abstract class for receiving a callback while walking a spill clique
    class SpillCliqueWalker
    {
    public:
        virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
    };

    // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
    class SetSpillTempsBase : public SpillCliqueWalker
    {
        unsigned m_baseTmp;

    public:
        SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
        {
        }
        virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
    };

    // This class is used for implementing impReimportSpillClique part on each block within the spill clique
    class ReimportSpillClique : public SpillCliqueWalker
    {
        Compiler* m_pComp;

    public:
        ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
        {
        }
        virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
    };

    // This is the heart of the algorithm for walking spill cliques. It invokes callback->Visit for each
    // predecessor or successor within the spill clique
    void impWalkSpillCliqueFromPred(BasicBlock* pred, SpillCliqueWalker* callback);

    // For a BasicBlock that has already been imported, the EntryState has an array of GenTrees for the
    // incoming locals. This walks that list an resets the types of the GenTrees to match the types of
    // the VarDscs. They get out of sync when we have int/native int issues (see impReimportSpillClique).
    void impRetypeEntryStateTemps(BasicBlock* blk);

    BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
    void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);

    void impPushVar(GenTree* op, typeInfo tiRetVal);
    GenTreeLclVar* impCreateLocalNode(unsigned lclNum DEBUGARG(IL_OFFSET offset));
    void impLoadVar(unsigned lclNum, IL_OFFSET offset);
    void impLoadArg(unsigned ilArgNum, IL_OFFSET offset);
    void impLoadLoc(unsigned ilLclNum, IL_OFFSET offset);
    bool impReturnInstruction(int prefixFlags, OPCODE& opcode);

#ifdef TARGET_ARM
    void impMarkLclDstNotPromotable(unsigned tmpNum, GenTree* op, CORINFO_CLASS_HANDLE hClass);
#endif

    // A free list of linked list nodes used to represent to-do stacks of basic blocks.
    struct BlockListNode
    {
        BasicBlock*    m_blk;
        BlockListNode* m_next;
        BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
        {
        }
        void* operator new(size_t sz, Compiler* comp);
    };
    BlockListNode* impBlockListNodeFreeList;

    void FreeBlockListNode(BlockListNode* node);

    var_types mangleVarArgsType(var_types type);

    regNumber getCallArgIntRegister(regNumber floatReg);
    regNumber getCallArgFloatRegister(regNumber intReg);

    static unsigned jitTotalMethodCompiled;

#ifdef DEBUG
    static LONG jitNestingLevel;
#endif // DEBUG

    static bool impIsInvariant(const GenTree* tree);
    static bool impIsAddressInLocal(const GenTree* tree, GenTree** lclVarTreeOut = nullptr);

    void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);

    // STATIC inlining decision based on the IL code.
    void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
                        CORINFO_METHOD_INFO*  methInfo,
                        bool                  forceInline,
                        InlineResult*         inlineResult);

    void impCheckCanInline(GenTreeCall*           call,
                           CORINFO_METHOD_HANDLE  fncHandle,
                           unsigned               methAttr,
                           CORINFO_CONTEXT_HANDLE exactContextHnd,
                           InlineCandidateInfo**  ppInlineCandidateInfo,
                           InlineResult*          inlineResult);

    void impInlineRecordArgInfo(InlineInfo* pInlineInfo, CallArg* arg, unsigned argNum, InlineResult* inlineResult);

    void impInlineInitVars(InlineInfo* pInlineInfo);

    unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));

    GenTree* impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);

    bool impInlineIsThis(GenTree* tree, InlArgInfo* inlArgInfo);

    bool impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTree*    additionalTree,
                                                            CallArgs*   additionalCallArgs,
                                                            GenTree*    dereferencedAddress,
                                                            InlArgInfo* inlArgInfo);

    void impMarkInlineCandidate(GenTree*               call,
                                CORINFO_CONTEXT_HANDLE exactContextHnd,
                                bool                   exactContextNeedsRuntimeLookup,
                                CORINFO_CALL_INFO*     callInfo,
                                IL_OFFSET              ilOffset);

    void impMarkInlineCandidateHelper(GenTreeCall*           call,
                                      CORINFO_CONTEXT_HANDLE exactContextHnd,
                                      bool                   exactContextNeedsRuntimeLookup,
                                      CORINFO_CALL_INFO*     callInfo,
                                      IL_OFFSET              ilOffset);

    bool impTailCallRetTypeCompatible(bool                     allowWidening,
                                      var_types                callerRetType,
                                      CORINFO_CLASS_HANDLE     callerRetTypeClass,
                                      CorInfoCallConvExtension callerCallConv,
                                      var_types                calleeRetType,
                                      CORINFO_CLASS_HANDLE     calleeRetTypeClass,
                                      CorInfoCallConvExtension calleeCallConv);

    bool impIsTailCallILPattern(
        bool tailPrefixed, OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, bool isRecursive);

    bool impIsImplicitTailCallCandidate(
        OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);

    bool impIsClassExact(CORINFO_CLASS_HANDLE classHnd);
    bool impCanSkipCovariantStoreCheck(GenTree* value, GenTree* array);

    methodPointerInfo* impAllocateMethodPointerInfo(const CORINFO_RESOLVED_TOKEN& token, mdToken tokenConstrained);

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           FlowGraph                                       XX
    XX                                                                           XX
    XX   Info about the basic-blocks, their contents and the flow analysis       XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    BasicBlock* fgFirstBB;        // Beginning of the basic block list
    BasicBlock* fgLastBB;         // End of the basic block list
    BasicBlock* fgFirstColdBlock; // First block to be placed in the cold section
    BasicBlock* fgEntryBB;        // For OSR, the original method's entry point
    BasicBlock* fgOSREntryBB;     // For OSR, the logical entry point (~ patchpoint)
#if defined(FEATURE_EH_FUNCLETS)
    BasicBlock* fgFirstFuncletBB; // First block of outlined funclets (to allow block insertion before the funclets)
#endif
    BasicBlock* fgFirstBBScratch;   // Block inserted for initialization stuff. Is nullptr if no such block has been
                                    // created.
    BasicBlockList* fgReturnBlocks; // list of BBJ_RETURN blocks
    unsigned        fgEdgeCount;    // # of control flow edges between the BBs
    unsigned        fgBBcount;      // # of BBs in the method
#ifdef DEBUG
    unsigned                     fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
    jitstd::vector<BasicBlock*>* fgBBOrder;          // ordered vector of BBs
#endif
    unsigned     fgBBNumMax;       // The max bbNum that has been assigned to basic blocks
    unsigned     fgDomBBcount;     // # of BBs for which we have dominator and reachability information
    BasicBlock** fgBBInvPostOrder; // The flow graph stored in an array sorted in topological order, needed to compute
                                   // dominance. Indexed by block number. Size: fgBBNumMax + 1.

    // After the dominance tree is computed, we cache a DFS preorder number and DFS postorder number to compute
    // dominance queries in O(1). fgDomTreePreOrder and fgDomTreePostOrder are arrays giving the block's preorder and
    // postorder number, respectively. The arrays are indexed by basic block number. (Note that blocks are numbered
    // starting from one. Thus, we always waste element zero. This makes debugging easier and makes the code less likely
    // to suffer from bugs stemming from forgetting to add or subtract one from the block number to form an array
    // index). The arrays are of size fgBBNumMax + 1.
    unsigned* fgDomTreePreOrder;
    unsigned* fgDomTreePostOrder;

    // Dominator tree used by SSA construction and copy propagation (the two are expected to use the same tree
    // in order to avoid the need for SSA reconstruction and an "out of SSA" phase).
    DomTreeNode* fgSsaDomTree;

    bool fgBBVarSetsInited;

    // Allocate array like T* a = new T[fgBBNumMax + 1];
    // Using helper so we don't keep forgetting +1.
    template <typename T>
    T* fgAllocateTypeForEachBlk(CompMemKind cmk = CMK_Unknown)
    {
        return getAllocator(cmk).allocate<T>(fgBBNumMax + 1);
    }

    // BlockSets are relative to a specific set of BasicBlock numbers. If that changes
    // (if the blocks are renumbered), this changes. BlockSets from different epochs
    // cannot be meaningfully combined. Note that new blocks can be created with higher
    // block numbers without changing the basic block epoch. These blocks *cannot*
    // participate in a block set until the blocks are all renumbered, causing the epoch
    // to change. This is useful if continuing to use previous block sets is valuable.
    // If the epoch is zero, then it is uninitialized, and block sets can't be used.
    unsigned fgCurBBEpoch;

    unsigned GetCurBasicBlockEpoch()
    {
        return fgCurBBEpoch;
    }

    // The number of basic blocks in the current epoch. When the blocks are renumbered,
    // this is fgBBcount. As blocks are added, fgBBcount increases, fgCurBBEpochSize remains
    // the same, until a new BasicBlock epoch is created, such as when the blocks are all renumbered.
    unsigned fgCurBBEpochSize;

    // The number of "size_t" elements required to hold a bitset large enough for fgCurBBEpochSize
    // bits. This is precomputed to avoid doing math every time BasicBlockBitSetTraits::GetArrSize() is called.
    unsigned fgBBSetCountInSizeTUnits;

    void NewBasicBlockEpoch()
    {
        INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);

        // We have a new epoch. Compute and cache the size needed for new BlockSets.
        fgCurBBEpoch++;
        fgCurBBEpochSize = fgBBNumMax + 1;
        fgBBSetCountInSizeTUnits =
            roundUp(fgCurBBEpochSize, (unsigned)(sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);

#ifdef DEBUG
        // All BlockSet objects are now invalid!
        fgReachabilitySetsValid = false; // the bbReach sets are now invalid!
        fgEnterBlksSetValid     = false; // the fgEnterBlks set is now invalid!

        if (verbose)
        {
            unsigned epochArrSize = BasicBlockBitSetTraits::GetArrSize(this);
            printf("\nNew BlockSet epoch %d, # of blocks (including unused BB00): %u, bitset array size: %u (%s)",
                   fgCurBBEpoch, fgCurBBEpochSize, epochArrSize, (epochArrSize <= 1) ? "short" : "long");
            if ((fgCurBBEpoch != 1) && ((oldEpochArrSize <= 1) != (epochArrSize <= 1)))
            {
                // If we're not just establishing the first epoch, and the epoch array size has changed such that we're
                // going to change our bitset representation from short (just a size_t bitset) to long (a pointer to an
                // array of size_t bitsets), then print that out.
                printf("; NOTE: BlockSet size was previously %s!", (oldEpochArrSize <= 1) ? "short" : "long");
            }
            printf("\n");
        }
#endif // DEBUG
    }

    void EnsureBasicBlockEpoch()
    {
        if (fgCurBBEpochSize != fgBBNumMax + 1)
        {
            NewBasicBlockEpoch();
        }
    }

    BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
    bool fgEnsureFirstBBisScratch();
    bool fgFirstBBisScratch();
    bool fgBBisScratch(BasicBlock* block);

    void fgExtendEHRegionBefore(BasicBlock* block);
    void fgExtendEHRegionAfter(BasicBlock* block);

    BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);

    BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);

    BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
                                unsigned    tryIndex,
                                unsigned    hndIndex,
                                BasicBlock* nearBlk,
                                bool        putInFilter = false,
                                bool        runRarely   = false,
                                bool        insertAtEnd = false);

    BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
                                BasicBlock* srcBlk,
                                bool        runRarely   = false,
                                bool        insertAtEnd = false);

    BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);

    BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
                                      BasicBlock* afterBlk,
                                      unsigned    xcptnIndex,
                                      bool        putInTryRegion);

    void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
    void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
    void fgUnlinkBlock(BasicBlock* block);

#ifdef FEATURE_JIT_METHOD_PERF
    unsigned fgMeasureIR();
#endif // FEATURE_JIT_METHOD_PERF

    bool fgModified;             // True if the flow graph has been modified recently
    bool fgComputePredsDone;     // Have we computed the bbPreds list
    bool fgCheapPredsValid;      // Is the bbCheapPreds list valid?
    bool fgDomsComputed;         // Have we computed the dominator sets?
    bool fgReturnBlocksComputed; // Have we computed the return blocks list?
    bool fgOptimizedFinally;     // Did we optimize any try-finallys?

    bool fgHasSwitch; // any BBJ_SWITCH jumps?

    BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
                          // begin blocks.
#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
    BlockSet fgAlwaysBlks; // Set of blocks which are BBJ_ALWAYS part  of BBJ_CALLFINALLY/BBJ_ALWAYS pair that should
                           // never be removed due to a requirement to use the BBJ_ALWAYS for generating code and
                           // not have "retless" blocks.

#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)

#ifdef DEBUG
    bool fgReachabilitySetsValid; // Are the bbReach sets valid?
    bool fgEnterBlksSetValid;     // Is the fgEnterBlks set valid?
#endif                            // DEBUG

    bool fgRemoveRestOfBlock; // true if we know that we will throw
    bool fgStmtRemoved;       // true if we remove statements -> need new DFA

    // There are two modes for ordering of the trees.
    //  - In FGOrderTree, the dominant ordering is the tree order, and the nodes contained in
    //    each tree and sub-tree are contiguous, and can be traversed (in gtNext/gtPrev order)
    //    by traversing the tree according to the order of the operands.
    //  - In FGOrderLinear, the dominant ordering is the linear order.

    enum FlowGraphOrder
    {
        FGOrderTree,
        FGOrderLinear
    };
    FlowGraphOrder fgOrder;

    // The following are boolean flags that keep track of the state of internal data structures

    bool     fgStmtListThreaded;       // true if the node list is now threaded
    bool     fgCanRelocateEHRegions;   // true if we are allowed to relocate the EH regions
    bool     fgEdgeWeightsComputed;    // true after we have called fgComputeEdgeWeights
    bool     fgHaveValidEdgeWeights;   // true if we were successful in computing all of the edge weights
    bool     fgSlopUsedInEdgeWeights;  // true if their was some slop used when computing the edge weights
    bool     fgRangeUsedInEdgeWeights; // true if some of the edgeWeight are expressed in Min..Max form
    weight_t fgCalledCount;            // count of the number of times this method was called
                                       // This is derived from the profile data
                                       // or is BB_UNITY_WEIGHT when we don't have profile data

#if defined(FEATURE_EH_FUNCLETS)
    bool fgFuncletsCreated; // true if the funclet creation phase has been run
#endif                      // FEATURE_EH_FUNCLETS

    bool fgGlobalMorph; // indicates if we are during the global morphing phase
                        // since fgMorphTree can be called from several places

    bool     impBoxTempInUse; // the temp below is valid and available
    unsigned impBoxTemp;      // a temporary that is used for boxing

#ifdef DEBUG
    bool jitFallbackCompile; // Are we doing a fallback compile? That is, have we executed a NO_WAY assert,
                             //   and we are trying to compile again in a "safer", minopts mode?
#endif

#if defined(DEBUG)
    unsigned impInlinedCodeSize;
    bool     fgPrintInlinedMethods;
#endif

    jitstd::vector<flowList*>* fgPredListSortVector;

    //-------------------------------------------------------------------------

    void fgInit();

    PhaseStatus fgImport();

    PhaseStatus fgTransformIndirectCalls();

    PhaseStatus fgTransformPatchpoints();

    PhaseStatus fgMorphInit();

    PhaseStatus fgInline();

    PhaseStatus fgRemoveEmptyTry();

    PhaseStatus fgRemoveEmptyFinally();

    PhaseStatus fgMergeFinallyChains();

    PhaseStatus fgCloneFinally();

    void fgCleanupContinuation(BasicBlock* continuation);

#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)

    PhaseStatus fgUpdateFinallyTargetFlags();

    void fgClearAllFinallyTargetBits();

    void fgAddFinallyTargetFlags();

#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)

    PhaseStatus fgTailMergeThrows();
    void fgTailMergeThrowsFallThroughHelper(BasicBlock* predBlock,
                                            BasicBlock* nonCanonicalBlock,
                                            BasicBlock* canonicalBlock,
                                            flowList*   predEdge);
    void fgTailMergeThrowsJumpToHelper(BasicBlock* predBlock,
                                       BasicBlock* nonCanonicalBlock,
                                       BasicBlock* canonicalBlock,
                                       flowList*   predEdge);

#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
    // Sometimes we need to defer updating the BBF_FINALLY_TARGET bit. fgNeedToAddFinallyTargetBits signals
    // when this is necessary.
    bool fgNeedToAddFinallyTargetBits;
#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)

    bool fgRetargetBranchesToCanonicalCallFinally(BasicBlock*      block,
                                                  BasicBlock*      handler,
                                                  BlockToBlockMap& continuationMap);

    GenTree* fgGetCritSectOfStaticMethod();

#if defined(FEATURE_EH_FUNCLETS)

    void fgAddSyncMethodEnterExit();

    GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);

    void fgConvertSyncReturnToLeave(BasicBlock* block);

#endif // FEATURE_EH_FUNCLETS

    void fgAddReversePInvokeEnterExit();

    bool fgMoreThanOneReturnBlock();

    // The number of separate return points in the method.
    unsigned fgReturnCount;

    PhaseStatus fgAddInternal();

    enum class FoldResult
    {
        FOLD_DID_NOTHING,
        FOLD_CHANGED_CONTROL_FLOW,
        FOLD_REMOVED_LAST_STMT,
        FOLD_ALTERED_LAST_STMT,
    };

    FoldResult fgFoldConditional(BasicBlock* block);

    void fgMorphStmts(BasicBlock* block);
    void fgMorphBlocks();

    void fgMergeBlockReturn(BasicBlock* block);

    bool fgMorphBlockStmt(BasicBlock* block, Statement* stmt DEBUGARG(const char* msg));

    //------------------------------------------------------------------------------------------------------------
    // MorphMDArrayTempCache: a simple cache of compiler temporaries in the local variable table, used to minimize
    // the number of locals allocated when doing early multi-dimensional array operation expansion. Two types of
    // temps are created and cached (due to the two types of temps needed by the MD array expansion): TYP_INT and
    // TYP_REF. `GrabTemp` either returns an available temp from the cache or allocates a new temp and returns it
    // after adding it to the cache. `Reset` makes all the temps in the cache available for subsequent re-use.
    //
    class MorphMDArrayTempCache
    {
    private:
        class TempList
        {
        public:
            TempList(Compiler* compiler)
                : m_compiler(compiler), m_first(nullptr), m_insertPtr(&m_first), m_nextAvail(nullptr)
            {
            }

            unsigned GetTemp();

            void Reset()
            {
                m_nextAvail = m_first;
            }

        private:
            struct Node
            {
                Node(unsigned tmp) : next(nullptr), tmp(tmp)
                {
                }

                Node*    next;
                unsigned tmp;
            };

            Compiler* m_compiler;
            Node*     m_first;
            Node**    m_insertPtr;
            Node*     m_nextAvail;
        };

        TempList intTemps; // Temps for genActualType() == TYP_INT
        TempList refTemps; // Temps for TYP_REF

    public:
        MorphMDArrayTempCache(Compiler* compiler) : intTemps(compiler), refTemps(compiler)
        {
        }

        unsigned GrabTemp(var_types type);

        void Reset()
        {
            intTemps.Reset();
            refTemps.Reset();
        }
    };

    bool fgMorphArrayOpsStmt(MorphMDArrayTempCache* pTempCache, BasicBlock* block, Statement* stmt);
    PhaseStatus fgMorphArrayOps();

    void fgSetOptions();

#ifdef DEBUG
    static fgWalkPreFn fgAssertNoQmark;
    void fgPreExpandQmarkChecks(GenTree* expr);
    void        fgPostExpandQmarkChecks();
    static void fgCheckQmarkAllowedForm(GenTree* tree);
#endif

    IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
    void fgFixEntryFlowForOSR();

    BasicBlock* fgSplitBlockAtBeginning(BasicBlock* curr);
    BasicBlock* fgSplitBlockAtEnd(BasicBlock* curr);
    BasicBlock* fgSplitBlockAfterStatement(BasicBlock* curr, Statement* stmt);
    BasicBlock* fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node); // for LIR
    BasicBlock* fgSplitEdge(BasicBlock* curr, BasicBlock* succ);

    Statement* fgNewStmtFromTree(GenTree* tree, BasicBlock* block, const DebugInfo& di);
    Statement* fgNewStmtFromTree(GenTree* tree);
    Statement* fgNewStmtFromTree(GenTree* tree, BasicBlock* block);
    Statement* fgNewStmtFromTree(GenTree* tree, const DebugInfo& di);

    GenTree* fgGetTopLevelQmark(GenTree* expr, GenTree** ppDst = nullptr);
    void fgExpandQmarkForCastInstOf(BasicBlock* block, Statement* stmt);
    void fgExpandQmarkStmt(BasicBlock* block, Statement* stmt);
    void fgExpandQmarkNodes();

    // Do "simple lowering."  This functionality is (conceptually) part of "general"
    // lowering that is distributed between fgMorph and the lowering phase of LSRA.
    PhaseStatus fgSimpleLowering();

#if FEATURE_LOOP_ALIGN
    PhaseStatus placeLoopAlignInstructions();
#endif

    GenTree* fgInitThisClass();

    GenTreeCall* fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);

    GenTreeCall* fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);

    bool backendRequiresLocalVarLifetimes()
    {
        return !opts.MinOpts() || m_pLinearScan->willEnregisterLocalVars();
    }

    void fgLocalVarLiveness();

    void fgLocalVarLivenessInit();

    void fgPerNodeLocalVarLiveness(GenTree* node);
    void fgPerBlockLocalVarLiveness();

    VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);

    void fgLiveVarAnalysis(bool updateInternalOnly = false);

    void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);

    void fgComputeLifeTrackedLocalUse(VARSET_TP& life, LclVarDsc& varDsc, GenTreeLclVarCommon* node);
    bool fgComputeLifeTrackedLocalDef(VARSET_TP&           life,
                                      VARSET_VALARG_TP     keepAliveVars,
                                      LclVarDsc&           varDsc,
                                      GenTreeLclVarCommon* node);
    bool fgComputeLifeUntrackedLocal(VARSET_TP&           life,
                                     VARSET_VALARG_TP     keepAliveVars,
                                     LclVarDsc&           varDsc,
                                     GenTreeLclVarCommon* lclVarNode);
    bool fgComputeLifeLocal(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, GenTree* lclVarNode);

    void fgComputeLife(VARSET_TP&       life,
                       GenTree*         startNode,
                       GenTree*         endNode,
                       VARSET_VALARG_TP volatileVars,
                       bool* pStmtInfoDirty DEBUGARG(bool* treeModf));

    void fgComputeLifeLIR(VARSET_TP& life, BasicBlock* block, VARSET_VALARG_TP volatileVars);

    bool fgTryRemoveNonLocal(GenTree* node, LIR::Range* blockRange);

    bool fgTryRemoveDeadStoreLIR(GenTree* store, GenTreeLclVarCommon* lclNode, BasicBlock* block);

    bool fgRemoveDeadStore(GenTree**        pTree,
                           LclVarDsc*       varDsc,
                           VARSET_VALARG_TP life,
                           bool*            doAgain,
                           bool*            pStmtInfoDirty,
                           bool* pStoreRemoved DEBUGARG(bool* treeModf));

    void fgInterBlockLocalVarLiveness();

    // Blocks: convenience methods for enabling range-based `for` iteration over the function's blocks, e.g.:
    // 1.   for (BasicBlock* const block : compiler->Blocks()) ...
    // 2.   for (BasicBlock* const block : compiler->Blocks(startBlock)) ...
    // 3.   for (BasicBlock* const block : compiler->Blocks(startBlock, endBlock)) ...
    // In case (1), the block list can be empty. In case (2), `startBlock` can be nullptr. In case (3),
    // both `startBlock` and `endBlock` must be non-null.
    //
    BasicBlockSimpleList Blocks() const
    {
        return BasicBlockSimpleList(fgFirstBB);
    }

    BasicBlockSimpleList Blocks(BasicBlock* startBlock) const
    {
        return BasicBlockSimpleList(startBlock);
    }

    BasicBlockRangeList Blocks(BasicBlock* startBlock, BasicBlock* endBlock) const
    {
        return BasicBlockRangeList(startBlock, endBlock);
    }

    // This array, managed by the SSA numbering infrastructure, keeps "outlined composite SSA numbers".
    // See "SsaNumInfo::GetNum" for more details on when this is needed.
    JitExpandArrayStack<unsigned>* m_outlinedCompositeSsaNums;

    // This map tracks nodes whose value numbers explicitly or implicitly depend on memory states.
    // The map provides the entry block of the most closely enclosing loop that
    // defines the memory region accessed when defining the nodes's VN.
    //
    // This information should be consulted when considering hoisting node out of a loop, as the VN
    // for the node will only be valid within the indicated loop.
    //
    // It is not fine-grained enough to track memory dependence within loops, so cannot be used
    // for more general code motion.
    //
    // If a node does not have an entry in the map we currently assume the VN is not memory dependent
    // and so memory does not constrain hoisting.
    //
    typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, BasicBlock*> NodeToLoopMemoryBlockMap;
    NodeToLoopMemoryBlockMap* m_nodeToLoopMemoryBlockMap;
    NodeToLoopMemoryBlockMap* GetNodeToLoopMemoryBlockMap()
    {
        if (m_nodeToLoopMemoryBlockMap == nullptr)
        {
            m_nodeToLoopMemoryBlockMap = new (getAllocator()) NodeToLoopMemoryBlockMap(getAllocator());
        }
        return m_nodeToLoopMemoryBlockMap;
    }

    void optRecordLoopMemoryDependence(GenTree* tree, BasicBlock* block, ValueNum memoryVN);
    void optCopyLoopMemoryDependence(GenTree* fromTree, GenTree* toTree);

    inline bool PreciseRefCountsRequired();

    // Performs SSA conversion.
    PhaseStatus fgSsaBuild();

    // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
    void fgResetForSsa();

    unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
    bool     fgSsaChecksEnabled;   // True if SSA info can be cross-checked versus IR

#ifdef DEBUG
    void DumpSsaSummary();
#endif

    // Returns "true" if this is a special variable that is never zero initialized in the prolog.
    inline bool fgVarIsNeverZeroInitializedInProlog(unsigned varNum);

    // Returns "true" if the variable needs explicit zero initialization.
    inline bool fgVarNeedsExplicitZeroInit(unsigned varNum, bool bbInALoop, bool bbIsReturn);

    // The value numbers for this compilation.
    ValueNumStore* vnStore;

public:
    ValueNumStore* GetValueNumStore()
    {
        return vnStore;
    }

    // Do value numbering (assign a value number to each
    // tree node).
    PhaseStatus fgValueNumber();

    void fgValueNumberLocalStore(GenTree*             storeNode,
                                 GenTreeLclVarCommon* lclDefNode,
                                 ssize_t              offset,
                                 unsigned             storeSize,
                                 ValueNumPair         value,
                                 bool                 normalize = true);

    void fgValueNumberArrayElemLoad(GenTree* loadTree, VNFuncApp* addrFunc);

    void fgValueNumberArrayElemStore(GenTree* storeNode, VNFuncApp* addrFunc, unsigned storeSize, ValueNum value);

    void fgValueNumberFieldLoad(GenTree* loadTree, GenTree* baseAddr, FieldSeq* fieldSeq, ssize_t offset);

    void fgValueNumberFieldStore(
        GenTree* storeNode, GenTree* baseAddr, FieldSeq* fieldSeq, ssize_t offset, unsigned storeSize, ValueNum value);

    // Compute the value number for a byref-exposed load of the given type via the given pointerVN.
    ValueNum fgValueNumberByrefExposedLoad(var_types type, ValueNum pointerVN);

    unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.

    // Utility functions for fgValueNumber.

    // Perform value-numbering for the trees in "blk".
    void fgValueNumberBlock(BasicBlock* blk);

    // Requires that "entryBlock" is the entry block of loop "loopNum", and that "loopNum" is the
    // innermost loop of which "entryBlock" is the entry.  Returns the value number that should be
    // assumed for the memoryKind at the start "entryBlk".
    ValueNum fgMemoryVNForLoopSideEffects(MemoryKind memoryKind, BasicBlock* entryBlock, unsigned loopNum);

    // Called when an operation (performed by "tree", described by "msg") may cause the GcHeap to be mutated.
    // As GcHeap is a subset of ByrefExposed, this will also annotate the ByrefExposed mutation.
    void fgMutateGcHeap(GenTree* tree DEBUGARG(const char* msg));

    // Called when an operation (performed by "tree", described by "msg") may cause an address-exposed local to be
    // mutated.
    void fgMutateAddressExposedLocal(GenTree* tree DEBUGARG(const char* msg));

    // For a GC heap store at curTree, record the new curMemoryVN's and update curTree's MemorySsaMap.
    // As GcHeap is a subset of ByrefExposed, this will also record the ByrefExposed store.
    void recordGcHeapStore(GenTree* curTree, ValueNum gcHeapVN DEBUGARG(const char* msg));

    // For a store to an address-exposed local at curTree, record the new curMemoryVN and update curTree's MemorySsaMap.
    void recordAddressExposedLocalStore(GenTree* curTree, ValueNum memoryVN DEBUGARG(const char* msg));

    void fgSetCurrentMemoryVN(MemoryKind memoryKind, ValueNum newMemoryVN);

    // Tree caused an update in the current memory VN.  If "tree" has an associated heap SSA #, record that
    // value in that SSA #.
    void fgValueNumberRecordMemorySsa(MemoryKind memoryKind, GenTree* tree);

    // The input 'tree' is a leaf node that is a constant
    // Assign the proper value number to the tree
    void fgValueNumberTreeConst(GenTree* tree);

    // If the VN store has been initialized, reassign the
    // proper value number to the constant tree.
    void fgUpdateConstTreeValueNumber(GenTree* tree);

    // Assumes that all inputs to "tree" have had value numbers assigned; assigns a VN to tree.
    // (With some exceptions: the VN of the lhs of an assignment is assigned as part of the
    // assignment.)
    void fgValueNumberTree(GenTree* tree);

    void fgValueNumberAssignment(GenTreeOp* tree);

    // Does value-numbering for a block assignment.
    void fgValueNumberBlockAssignment(GenTree* tree);

    // Does value-numbering for a variable definition that has SSA.
    void fgValueNumberSsaVarDef(GenTreeLclVarCommon* lcl);

    // Does value-numbering for a cast tree.
    void fgValueNumberCastTree(GenTree* tree);

    // Does value-numbering for a bitcast tree.
    void fgValueNumberBitCast(GenTree* tree);

    // Does value-numbering for an intrinsic tree.
    void fgValueNumberIntrinsic(GenTree* tree);

    void fgValueNumberArrIndexAddr(GenTreeArrAddr* arrAddr);

#ifdef FEATURE_SIMD
    // Does value-numbering for a GT_SIMD tree
    void fgValueNumberSimd(GenTreeSIMD* tree);
#endif // FEATURE_SIMD

#ifdef FEATURE_HW_INTRINSICS
    // Does value-numbering for a GT_HWINTRINSIC tree
    void fgValueNumberHWIntrinsic(GenTreeHWIntrinsic* tree);
#endif // FEATURE_HW_INTRINSICS

    // Does value-numbering for a call.  We interpret some helper calls.
    void fgValueNumberCall(GenTreeCall* call);

    // Does value-numbering for a helper representing a cast operation.
    void fgValueNumberCastHelper(GenTreeCall* call);

    // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
    void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);

    // Requires "helpCall" to be a helper call.  Assigns it a value number;
    // we understand the semantics of some of the calls.  Returns "true" if
    // the call may modify the heap (we assume arbitrary memory side effects if so).
    bool fgValueNumberHelperCall(GenTreeCall* helpCall);

    // Requires that "helpFunc" is one of the pure Jit Helper methods.
    // Returns the corresponding VNFunc to use for value numbering
    VNFunc fgValueNumberJitHelperMethodVNFunc(CorInfoHelpFunc helpFunc);

    // Adds the exception set for the current tree node which has a memory indirection operation
    void fgValueNumberAddExceptionSetForIndirection(GenTree* tree, GenTree* baseAddr);

    // Adds the exception sets for the current tree node which is performing a division or modulus operation
    void fgValueNumberAddExceptionSetForDivision(GenTree* tree);

    // Adds the exception set for the current tree node which is performing a overflow checking operation
    void fgValueNumberAddExceptionSetForOverflow(GenTree* tree);

    // Adds the exception set for the current tree node which is performing a bounds check operation
    void fgValueNumberAddExceptionSetForBoundsCheck(GenTree* tree);

    // Adds the exception set for the current tree node which is performing a ckfinite operation
    void fgValueNumberAddExceptionSetForCkFinite(GenTree* tree);

    // Adds the exception sets for the current tree node
    void fgValueNumberAddExceptionSet(GenTree* tree);

#ifdef DEBUG
    void fgDebugCheckExceptionSets();
#endif

    // These are the current value number for the memory implicit variables while
    // doing value numbering.  These are the value numbers under the "liberal" interpretation
    // of memory values; the "conservative" interpretation needs no VN, since every access of
    // memory yields an unknown value.
    ValueNum fgCurMemoryVN[MemoryKindCount];

    // Return a "pseudo"-class handle for an array element type.  If "elemType" is TYP_STRUCT,
    // requires "elemStructType" to be non-null (and to have a low-order zero).  Otherwise, low order bit
    // is 1, and the rest is an encoding of "elemTyp".
    static CORINFO_CLASS_HANDLE EncodeElemType(var_types elemTyp, CORINFO_CLASS_HANDLE elemStructType)
    {
        if (elemStructType != nullptr)
        {
            assert(varTypeIsStruct(elemTyp) || elemTyp == TYP_REF || elemTyp == TYP_BYREF ||
                   varTypeIsIntegral(elemTyp));
            assert((size_t(elemStructType) & 0x1) == 0x0); // Make sure the encoding below is valid.
            return elemStructType;
        }
        else
        {
            assert(elemTyp != TYP_STRUCT);
            elemTyp = varTypeToSigned(elemTyp);
            return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
        }
    }
    // If "clsHnd" is the result of an "EncodePrim" call, returns true and sets "*pPrimType" to the
    // var_types it represents.  Otherwise, returns TYP_STRUCT (on the assumption that "clsHnd" is
    // the struct type of the element).
    static var_types DecodeElemType(CORINFO_CLASS_HANDLE clsHnd)
    {
        size_t clsHndVal = size_t(clsHnd);
        if (clsHndVal & 0x1)
        {
            return var_types(clsHndVal >> 1);
        }
        else
        {
            return TYP_STRUCT;
        }
    }

    // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
    var_types getJitGCType(BYTE gcType);

    // Returns true if the provided type should be treated as a primitive type
    // for the unmanaged calling conventions.
    bool isNativePrimitiveStructType(CORINFO_CLASS_HANDLE clsHnd);

    enum structPassingKind
    {
        SPK_Unknown,       // Invalid value, never returned
        SPK_PrimitiveType, // The struct is passed/returned using a primitive type.
        SPK_EnclosingType, // Like SPK_Primitive type, but used for return types that
                           //  require a primitive type temp that is larger than the struct size.
                           //  Currently used for structs of size 3, 5, 6, or 7 bytes.
        SPK_ByValue,       // The struct is passed/returned by value (using the ABI rules)
                           //  for ARM64 and UNIX_X64 in multiple registers. (when all of the
                           //   parameters registers are used, then the stack will be used)
                           //  for X86 passed on the stack, for ARM32 passed in registers
                           //   or the stack or split between registers and the stack.
        SPK_ByValueAsHfa,  // The struct is passed/returned as an HFA in multiple registers.
        SPK_ByReference
    }; // The struct is passed/returned by reference to a copy/buffer.

    // Get the "primitive" type that is used when we are given a struct of size 'structSize'.
    // For pointer sized structs the 'clsHnd' is used to determine if the struct contains GC ref.
    // A "primitive" type is one of the scalar types: byte, short, int, long, ref, float, double
    // If we can't or shouldn't use a "primitive" type then TYP_UNKNOWN is returned.
    //
    // isVarArg is passed for use on Windows Arm64 to change the decision returned regarding
    // hfa types.
    //
    var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd, bool isVarArg);

    // Get the type that is used to pass values of the given struct type.
    // isVarArg is passed for use on Windows Arm64 to change the decision returned regarding
    // hfa types.
    //
    var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
                                  structPassingKind*   wbPassStruct,
                                  bool                 isVarArg,
                                  unsigned             structSize);

    // Get the type that is used to return values of the given struct type.
    // If the size is unknown, pass 0 and it will be determined from 'clsHnd'.
    var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE     clsHnd,
                                     CorInfoCallConvExtension callConv,
                                     structPassingKind*       wbPassStruct = nullptr,
                                     unsigned                 structSize   = 0);

#ifdef DEBUG
    // Print a representation of "vnp" or "vn" on standard output.
    // If "level" is non-zero, we also print out a partial expansion of the value.
    void vnpPrint(ValueNumPair vnp, unsigned level);
    void vnPrint(ValueNum vn, unsigned level);
#endif

    bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2

    // Dominator computation member functions
    // Not exposed outside Compiler
protected:
    bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2

    // Compute immediate dominators, the dominator tree and and its pre/post-order travsersal numbers.
    void fgComputeDoms();

    void fgCompDominatedByExceptionalEntryBlocks();

    BlockSet_ValRet_T fgGetDominatorSet(BasicBlock* block); // Returns a set of blocks that dominate the given block.
    // Note: this is relatively slow compared to calling fgDominate(),
    // especially if dealing with a single block versus block check.

    void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)

    void fgComputeReturnBlocks(); // Initialize fgReturnBlocks to a list of BBJ_RETURN blocks.

    void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.

    // Remove blocks determined to be unreachable by the 'canRemoveBlock'.
    template <typename CanRemoveBlockBody>
    bool fgRemoveUnreachableBlocks(CanRemoveBlockBody canRemoveBlock);

    PhaseStatus fgComputeReachability(); // Perform flow graph node reachability analysis.

    bool fgRemoveDeadBlocks(); // Identify and remove dead blocks.

    BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.

    void fgDfsInvPostOrder(); // In order to compute dominance using fgIntersectDom, the flow graph nodes must be
                              // processed in topological sort, this function takes care of that.

    void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);

    BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
                                             // Returns this as a set.

    INDEBUG(void fgDispDomTree(DomTreeNode* domTree);) // Helper that prints out the Dominator Tree in debug builds.

    DomTreeNode* fgBuildDomTree(); // Once we compute all the immediate dominator sets for each node in the flow graph
                                   // (performed by fgComputeDoms), this procedure builds the dominance tree represented
                                   // adjacency lists.

    // In order to speed up the queries of the form 'Does A dominates B', we can perform a DFS preorder and postorder
    // traversal of the dominance tree and the dominance query will become A dominates B iif preOrder(A) <= preOrder(B)
    // && postOrder(A) >= postOrder(B) making the computation O(1).
    void fgNumberDomTree(DomTreeNode* domTree);

    // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets,
    // dominators, and possibly loops.
    void fgUpdateChangedFlowGraph(const bool computePreds        = true,
                                  const bool computeDoms         = true,
                                  const bool computeReturnBlocks = false,
                                  const bool computeLoops        = false);

public:
    // Compute the predecessors of the blocks in the control flow graph.
    void fgComputePreds();

    // Remove all predecessor information.
    void fgRemovePreds();

    // Compute the cheap flow graph predecessors lists. This is used in some early phases
    // before the full predecessors lists are computed.
    void fgComputeCheapPreds();

private:
    void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);

    void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);

public:
    enum GCPollType
    {
        GCPOLL_NONE,
        GCPOLL_CALL,
        GCPOLL_INLINE
    };

    // Initialize the per-block variable sets (used for liveness analysis).
    void fgInitBlockVarSets();

    PhaseStatus fgInsertGCPolls();
    BasicBlock* fgCreateGCPoll(GCPollType pollType, BasicBlock* block);

    // Requires that "block" is a block that returns from
    // a finally.  Returns the number of successors (jump targets of
    // of blocks in the covered "try" that did a "LEAVE".)
    unsigned fgNSuccsOfFinallyRet(BasicBlock* block);

    // Requires that "block" is a block that returns (in the sense of BBJ_EHFINALLYRET) from
    // a finally.  Returns its "i"th successor (jump targets of
    // of blocks in the covered "try" that did a "LEAVE".)
    // Requires that "i" < fgNSuccsOfFinallyRet(block).
    BasicBlock* fgSuccOfFinallyRet(BasicBlock* block, unsigned i);

private:
    // Factor out common portions of the impls of the methods above.
    void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);

public:
    // For many purposes, it is desirable to be able to enumerate the *distinct* targets of a switch statement,
    // skipping duplicate targets.  (E.g., in flow analyses that are only interested in the set of possible targets.)
    // SwitchUniqueSuccSet contains the non-duplicated switch targets.
    // (Code that modifies the jump table of a switch has an obligation to call Compiler::UpdateSwitchTableTarget,
    // which in turn will call the "UpdateTarget" method of this type if a SwitchUniqueSuccSet has already
    // been computed for the switch block.  If a switch block is deleted or is transformed into a non-switch,
    // we leave the entry associated with the block, but it will no longer be accessed.)
    struct SwitchUniqueSuccSet
    {
        unsigned     numDistinctSuccs; // Number of distinct targets of the switch.
        BasicBlock** nonDuplicates;    // Array of "numDistinctSuccs", containing all the distinct switch target
                                       // successors.

        // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
        // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
        // remove it from "this", and ensure that "to" is a member.  Use "alloc" to do any required allocation.
        void UpdateTarget(CompAllocator alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
    };

    typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet> BlockToSwitchDescMap;

private:
    // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
    // iteration over only the distinct successors.
    BlockToSwitchDescMap* m_switchDescMap;

public:
    BlockToSwitchDescMap* GetSwitchDescMap(bool createIfNull = true)
    {
        if ((m_switchDescMap == nullptr) && createIfNull)
        {
            m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
        }
        return m_switchDescMap;
    }

    // Invalidate the map of unique switch block successors. For example, since the hash key of the map
    // depends on block numbers, we must invalidate the map when the blocks are renumbered, to ensure that
    // we don't accidentally look up and return the wrong switch data.
    void InvalidateUniqueSwitchSuccMap()
    {
        m_switchDescMap = nullptr;
    }

    // Requires "switchBlock" to be a block that ends in a switch.  Returns
    // the corresponding SwitchUniqueSuccSet.
    SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);

    // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
    // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
    // remove it from "this", and ensure that "to" is a member.
    void UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);

    // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
    void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);

    BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);

    bool fgIsFirstBlockOfFilterOrHandler(BasicBlock* block);

    flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);

    flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);

    flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);

    flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);

    void fgRemoveBlockAsPred(BasicBlock* block);

    void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);

    void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);

    void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);

    void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);

    flowList* fgAddRefPred(BasicBlock* block,
                           BasicBlock* blockPred,
                           flowList*   oldEdge           = nullptr,
                           bool        initializingPreds = false); // Only set to 'true' when we are computing preds in
                                                                   // fgComputePreds()

    void fgFindBasicBlocks();

    bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);

    bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);

    BasicBlock* fgFindInsertPoint(unsigned    regionIndex,
                                  bool        putInTryRegion,
                                  BasicBlock* startBlk,
                                  BasicBlock* endBlk,
                                  BasicBlock* nearBlk,
                                  BasicBlock* jumpBlk,
                                  bool        runRarely);

    unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);

    PhaseStatus fgPostImportationCleanup();

    void fgRemoveStmt(BasicBlock* block, Statement* stmt DEBUGARG(bool isUnlink = false));
    void fgUnlinkStmt(BasicBlock* block, Statement* stmt);

    bool fgCheckRemoveStmt(BasicBlock* block, Statement* stmt);

    bool fgCreateLoopPreHeader(unsigned lnum);

    void fgUnreachableBlock(BasicBlock* block);

    void fgRemoveConditionalJump(BasicBlock* block);

    BasicBlock* fgLastBBInMainFunction();

    BasicBlock* fgEndBBAfterMainFunction();

    BasicBlock* fgGetDomSpeculatively(const BasicBlock* block);

    void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);

    void fgRemoveBlock(BasicBlock* block, bool unreachable);

    bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);

    void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);

    void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);

    BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);

    bool fgRenumberBlocks();

    bool fgExpandRarelyRunBlocks();

    bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);

    void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);

    PhaseStatus fgTailMerge();

    enum FG_RELOCATE_TYPE
    {
        FG_RELOCATE_TRY,    // relocate the 'try' region
        FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
    };
    BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);

#if defined(FEATURE_EH_FUNCLETS)
#if defined(TARGET_ARM)
    void fgClearFinallyTargetBit(BasicBlock* block);
#endif // defined(TARGET_ARM)
    bool fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block);
    bool fgAnyIntraHandlerPreds(BasicBlock* block);
    void fgInsertFuncletPrologBlock(BasicBlock* block);
    void        fgCreateFuncletPrologBlocks();
    PhaseStatus fgCreateFunclets();
#else  // !FEATURE_EH_FUNCLETS
    bool fgRelocateEHRegions();
#endif // !FEATURE_EH_FUNCLETS

    bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);

    bool fgBlockEndFavorsTailDuplication(BasicBlock* block, unsigned lclNum);

    bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block, unsigned* lclNum);

    bool fgOptimizeEmptyBlock(BasicBlock* block);

    bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);

    bool fgOptimizeBranch(BasicBlock* bJump);

    bool fgOptimizeSwitchBranches(BasicBlock* block);

    bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);

    bool fgOptimizeSwitchJumps();
#ifdef DEBUG
    void fgPrintEdgeWeights();
#endif
    PhaseStatus fgComputeBlockAndEdgeWeights();
    bool fgComputeMissingBlockWeights(weight_t* returnWeight);
    bool fgComputeCalledCount(weight_t returnWeight);
    PhaseStatus fgComputeEdgeWeights();

    bool fgReorderBlocks(bool useProfile);

#ifdef FEATURE_EH_FUNCLETS
    bool fgFuncletsAreCold();
#endif // FEATURE_EH_FUNCLETS

    PhaseStatus fgDetermineFirstColdBlock();

    bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);

    bool fgUpdateFlowGraph(bool doTailDup = false, bool isPhase = false);
    PhaseStatus fgUpdateFlowGraphPhase();

    PhaseStatus fgFindOperOrder();

    // method that returns if you should split here
    typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);

    PhaseStatus fgSetBlockOrder();

    void fgRemoveReturnBlock(BasicBlock* block);

    /* Helper code that has been factored out */
    inline void fgConvertBBToThrowBB(BasicBlock* block);

    bool fgCastNeeded(GenTree* tree, var_types toType);
    GenTree* fgDoNormalizeOnStore(GenTree* tree);

    // The following check for loops that don't execute calls
    bool fgLoopCallMarked;

    void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
    void fgLoopCallMark();

    void fgMarkLoopHead(BasicBlock* block);

    unsigned fgGetCodeEstimate(BasicBlock* block);

#if DUMP_FLOWGRAPHS
    enum class PhasePosition
    {
        PrePhase,
        PostPhase
    };
    const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
    static void fgDumpTree(FILE* fgxFile, GenTree* const tree);
    FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, PhasePosition pos, const char* type);
    bool fgDumpFlowGraph(Phases phase, PhasePosition pos);
#endif // DUMP_FLOWGRAPHS

#ifdef DEBUG

    void fgDispDoms();
    void fgDispReach();
    void fgDispBBLiveness(BasicBlock* block);
    void fgDispBBLiveness();
    void fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth = 0);
    void fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees);
    void fgDispBasicBlocks(bool dumpTrees = false);
    void fgDumpStmtTree(Statement* stmt, unsigned bbNum);
    void fgDumpBlock(BasicBlock* block);
    void fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock);

    static fgWalkPreFn fgStress64RsltMulCB;
    void               fgStress64RsltMul();
    void               fgDebugCheckUpdate();

    void fgDebugCheckBBNumIncreasing();
    void fgDebugCheckBBlist(bool checkBBNum = false, bool checkBBRefs = true);
    void fgDebugCheckBlockLinks();
    void fgDebugCheckLinks(bool morphTrees = false);
    void fgDebugCheckStmtsList(BasicBlock* block, bool morphTrees);
    void fgDebugCheckNodeLinks(BasicBlock* block, Statement* stmt);
    void fgDebugCheckNodesUniqueness();
    void fgDebugCheckLoopTable();
    void fgDebugCheckSsa();

    void fgDebugCheckFlags(GenTree* tree);
    void fgDebugCheckDispFlags(GenTree* tree, GenTreeFlags dispFlags, GenTreeDebugFlags debugFlags);
    void fgDebugCheckFlagsHelper(GenTree* tree, GenTreeFlags actualFlags, GenTreeFlags expectedFlags);
    void fgDebugCheckTryFinallyExits();
    void fgDebugCheckProfileWeights();
    bool fgDebugCheckIncomingProfileData(BasicBlock* block);
    bool fgDebugCheckOutgoingProfileData(BasicBlock* block);

#endif // DEBUG

    static bool fgProfileWeightsEqual(weight_t weight1, weight_t weight2);
    static bool fgProfileWeightsConsistent(weight_t weight1, weight_t weight2);

    static GenTree* fgGetFirstNode(GenTree* tree);

    //--------------------- Walking the trees in the IR -----------------------

    struct fgWalkData
    {
        Compiler*     compiler;
        fgWalkPreFn*  wtprVisitorFn;
        fgWalkPostFn* wtpoVisitorFn;
        void*         pCallbackData; // user-provided data
        GenTree*      parent;        // parent of current node, provided to callback
        bool          wtprLclsOnly;  // whether to only visit lclvar nodes
#ifdef DEBUG
        bool printModified; // callback can use this
#endif
    };

    fgWalkResult fgWalkTreePre(GenTree**    pTree,
                               fgWalkPreFn* visitor,
                               void*        pCallBackData = nullptr,
                               bool         lclVarsOnly   = false,
                               bool         computeStack  = false);

    fgWalkResult fgWalkTree(GenTree**     pTree,
                            fgWalkPreFn*  preVisitor,
                            fgWalkPostFn* postVisitor,
                            void*         pCallBackData = nullptr);

    void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);

    //----- Postorder

    fgWalkResult fgWalkTreePost(GenTree**     pTree,
                                fgWalkPostFn* visitor,
                                void*         pCallBackData = nullptr,
                                bool          computeStack  = false);

    static fgWalkResult fgChkLocAllocCB(GenTree** pTree, Compiler::fgWalkData* data);
    static fgWalkResult fgChkQmarkCB(GenTree** pTree, Compiler::fgWalkData* data);

    /**************************************************************************
     *                          PROTECTED
     *************************************************************************/

protected:
    friend class SsaBuilder;
    friend struct ValueNumberState;

    //--------------------- Detect the basic blocks ---------------------------

    BasicBlock** fgBBs; // Table of pointers to the BBs

    void        fgInitBBLookup();
    BasicBlock* fgLookupBB(unsigned addr);

    bool fgCanSwitchToOptimized();
    void fgSwitchToOptimized(const char* reason);

    bool fgMayExplicitTailCall();

    void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget);

    void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);

    void fgLinkBasicBlocks();

    unsigned fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget);

    void fgCheckBasicBlockControlFlow();

    void fgControlFlowPermitted(BasicBlock* blkSrc,
                                BasicBlock* blkDest,
                                bool        IsLeave = false /* is the src a leave block */);

    bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);

    void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);

    void fgAdjustForAddressExposedOrWrittenThis();

    unsigned fgStressBBProf()
    {
#ifdef DEBUG
        unsigned result = JitConfig.JitStressBBProf();
        if (result == 0)
        {
            if (compStressCompile(STRESS_BB_PROFILE, 15))
            {
                result = 1;
            }
        }
        return result;
#else
        return 0;
#endif
    }

    bool fgHaveProfileData();
    bool fgHaveProfileWeights();
    bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, weight_t* weight);

    Instrumentor* fgCountInstrumentor;
    Instrumentor* fgHistogramInstrumentor;

    PhaseStatus fgPrepareToInstrumentMethod();
    PhaseStatus fgInstrumentMethod();
    PhaseStatus fgIncorporateProfileData();
    void        fgIncorporateBlockCounts();
    void        fgIncorporateEdgeCounts();

public:
    const char*                            fgPgoFailReason;
    bool                                   fgPgoDisabled;
    ICorJitInfo::PgoSource                 fgPgoSource;
    ICorJitInfo::PgoInstrumentationSchema* fgPgoSchema;
    BYTE*                                  fgPgoData;
    UINT32                                 fgPgoSchemaCount;
    HRESULT                                fgPgoQueryResult;
    UINT32                                 fgNumProfileRuns;
    UINT32                                 fgPgoBlockCounts;
    UINT32                                 fgPgoEdgeCounts;
    UINT32                                 fgPgoClassProfiles;
    UINT32                                 fgPgoMethodProfiles;
    unsigned                               fgPgoInlineePgo;
    unsigned                               fgPgoInlineeNoPgo;
    unsigned                               fgPgoInlineeNoPgoSingleBlock;
    bool                                   fgPgoHaveWeights;

    void WalkSpanningTree(SpanningTreeVisitor* visitor);
    void fgSetProfileWeight(BasicBlock* block, weight_t weight);
    void fgApplyProfileScale();
    bool fgHaveSufficientProfileWeights();
    bool fgHaveTrustedProfileWeights();

    // fgIsUsingProfileWeights - returns true if we have real profile data for this method
    //                           or if we have some fake profile data for the stress mode
    bool fgIsUsingProfileWeights()
    {
        return (fgHaveProfileWeights() || fgStressBBProf());
    }

    // fgProfileRunsCount - returns total number of scenario runs for the profile data
    //                      or BB_UNITY_WEIGHT_UNSIGNED when we aren't using profile data.
    unsigned fgProfileRunsCount()
    {
        return fgIsUsingProfileWeights() ? fgNumProfileRuns : BB_UNITY_WEIGHT_UNSIGNED;
    }

//-------- Insert a statement at the start or end of a basic block --------

#ifdef DEBUG
public:
    static bool fgBlockContainsStatementBounded(BasicBlock* block, Statement* stmt, bool answerOnBoundExceeded = true);
#endif

public:
    Statement* fgNewStmtAtBeg(BasicBlock* block, GenTree* tree, const DebugInfo& di = DebugInfo());
    void fgInsertStmtAtEnd(BasicBlock* block, Statement* stmt);
    Statement* fgNewStmtAtEnd(BasicBlock* block, GenTree* tree, const DebugInfo& di = DebugInfo());
    Statement* fgNewStmtNearEnd(BasicBlock* block, GenTree* tree, const DebugInfo& di = DebugInfo());

private:
    void fgInsertStmtNearEnd(BasicBlock* block, Statement* stmt);
    void fgInsertStmtAtBeg(BasicBlock* block, Statement* stmt);
    void fgInsertStmtAfter(BasicBlock* block, Statement* insertionPoint, Statement* stmt);

public:
    void fgInsertStmtBefore(BasicBlock* block, Statement* insertionPoint, Statement* stmt);

private:
    Statement* fgInsertStmtListAfter(BasicBlock* block, Statement* stmtAfter, Statement* stmtList);

    //                  Create a new temporary variable to hold the result of *ppTree,
    //                  and transform the graph accordingly.
    GenTree* fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);
    TempInfo fgMakeTemp(GenTree* rhs, CORINFO_CLASS_HANDLE structType = nullptr);
    GenTree* fgMakeMultiUse(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);

    //                  Recognize a bitwise rotation pattern and convert into a GT_ROL or a GT_ROR node.
    GenTree* fgRecognizeAndMorphBitwiseRotation(GenTree* tree);
    bool fgOperIsBitwiseRotationRoot(genTreeOps oper);

#if !defined(TARGET_64BIT)
    //                  Recognize and morph a long multiplication with 32 bit operands.
    GenTreeOp* fgRecognizeAndMorphLongMul(GenTreeOp* mul);
    GenTreeOp* fgMorphLongMul(GenTreeOp* mul);
#endif

    //-------- Determine the order in which the trees will be evaluated -------
public:
    void fgSetStmtSeq(Statement* stmt);

private:
    GenTree* fgSetTreeSeq(GenTree* tree, bool isLIR = false);
    void fgSetBlockOrder(BasicBlock* block);

    //------------------------- Morphing --------------------------------------

    unsigned fgPtrArgCntMax;

public:
    //------------------------------------------------------------------------
    // fgGetPtrArgCntMax: Return the maximum number of pointer-sized stack arguments that calls inside this method
    // can push on the stack. This value is calculated during morph.
    //
    // Return Value:
    //    Returns fgPtrArgCntMax, that is a private field.
    //
    unsigned fgGetPtrArgCntMax() const
    {
        return fgPtrArgCntMax;
    }

    //------------------------------------------------------------------------
    // fgSetPtrArgCntMax: Set the maximum number of pointer-sized stack arguments that calls inside this method
    // can push on the stack. This function is used during StackLevelSetter to fix incorrect morph calculations.
    //
    void fgSetPtrArgCntMax(unsigned argCntMax)
    {
        fgPtrArgCntMax = argCntMax;
    }

    bool compCanEncodePtrArgCntMax();

private:
    hashBv* fgOutgoingArgTemps;
    hashBv* fgCurrentlyInUseArgTemps;

    void fgSetRngChkTarget(GenTree* tree, bool delay = true);

    BasicBlock* fgSetRngChkTargetInner(SpecialCodeKind kind, bool delay);

#if REARRANGE_ADDS
    void fgMoveOpsLeft(GenTree* tree);
#endif

    bool fgIsCommaThrow(GenTree* tree, bool forFolding = false);

    bool fgIsThrow(GenTree* tree);

    bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
    bool fgIsBlockCold(BasicBlock* block);

    GenTree* fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* oper);

    GenTree* fgMorphIntoHelperCall(
        GenTree* tree, int helper, bool morphArgs, GenTree* arg1 = nullptr, GenTree* arg2 = nullptr);

    // A "MorphAddrContext" carries information from the surrounding context.  If we are evaluating a byref address,
    // it is useful to know whether the address will be immediately dereferenced, or whether the address value will
    // be used, perhaps by passing it as an argument to a called method.  This affects how null checking is done:
    // for sufficiently small offsets, we can rely on OS page protection to implicitly null-check addresses that we
    // know will be dereferenced.  To know that reliance on implicit null checking is sound, we must further know that
    // all offsets between the top-level indirection and the bottom are constant, and that their sum is sufficiently
    // small; hence the other fields of MorphAddrContext.
    enum MorphAddrContextKind
    {
        MACK_Ind,
        MACK_Addr,
    };
    struct MorphAddrContext
    {
        MorphAddrContextKind m_kind;
        bool                 m_allConstantOffsets; // Valid only for "m_kind == MACK_Ind".  True iff all offsets between
                                                   // top-level indirection and here have been constants.
        size_t m_totalOffset; // Valid only for "m_kind == MACK_Ind", and if "m_allConstantOffsets" is true.
                              // In that case, is the sum of those constant offsets.

        MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
        {
        }
    };

#ifdef FEATURE_SIMD
    GenTree* getSIMDStructFromField(GenTree*     tree,
                                    CorInfoType* simdBaseJitTypeOut,
                                    unsigned*    indexOut,
                                    unsigned*    simdSizeOut,
                                    bool         ignoreUsedInSIMDIntrinsic = false);
    GenTree* fgMorphFieldAssignToSimdSetElement(GenTree* tree);
    GenTree* fgMorphFieldToSimdGetElement(GenTree* tree);
    bool fgMorphCombineSIMDFieldAssignments(BasicBlock* block, Statement* stmt);
    void impMarkContiguousSIMDFieldAssignments(Statement* stmt);

    // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
    // in function: Compiler::impMarkContiguousSIMDFieldAssignments.
    Statement* fgPreviousCandidateSIMDFieldAsgStmt;

#endif // FEATURE_SIMD
    GenTree* fgMorphIndexAddr(GenTreeIndexAddr* tree);
    GenTree* fgMorphExpandCast(GenTreeCast* tree);
    GenTreeFieldList* fgMorphLclArgToFieldlist(GenTreeLclVarCommon* lcl);
    GenTreeCall* fgMorphArgs(GenTreeCall* call);

    void fgMakeOutgoingStructArgCopy(GenTreeCall* call, CallArg* arg);

    GenTree* fgMorphLocal(GenTreeLclVarCommon* lclNode);
#ifdef TARGET_X86
    GenTree* fgMorphExpandStackArgForVarArgs(GenTreeLclVarCommon* lclNode);
#endif // TARGET_X86
    GenTree* fgMorphExpandImplicitByRefArg(GenTreeLclVarCommon* lclNode);
    GenTree* fgMorphLocalVar(GenTree* tree, bool forceRemorph);

public:
    bool fgAddrCouldBeNull(GenTree* addr);
    void fgAssignSetVarDef(GenTree* tree);

private:
    GenTree* fgMorphField(GenTree* tree, MorphAddrContext* mac);
    GenTree* fgMorphExpandInstanceField(GenTree* tree, MorphAddrContext* mac);
    GenTree* fgMorphExpandTlsFieldAddr(GenTree* tree);
    bool fgCanFastTailCall(GenTreeCall* call, const char** failReason);
#if FEATURE_FASTTAILCALL
    bool fgCallHasMustCopyByrefParameter(GenTreeCall* callee);
#endif
    bool     fgCheckStmtAfterTailCall();
    GenTree* fgMorphTailCallViaHelpers(GenTreeCall* call, CORINFO_TAILCALL_HELPERS& help);
    bool fgCanTailCallViaJitHelper(GenTreeCall* call);
    void fgMorphTailCallViaJitHelper(GenTreeCall* call);
    GenTree* fgCreateCallDispatcherAndGetResult(GenTreeCall*          origCall,
                                                CORINFO_METHOD_HANDLE callTargetStubHnd,
                                                CORINFO_METHOD_HANDLE dispatcherHnd);
    GenTree* getLookupTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                           CORINFO_LOOKUP*         pLookup,
                           GenTreeFlags            handleFlags,
                           void*                   compileTimeHandle);
    GenTree* getRuntimeLookupTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                  CORINFO_LOOKUP*         pLookup,
                                  void*                   compileTimeHandle);
    GenTree* getVirtMethodPointerTree(GenTree*                thisPtr,
                                      CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                      CORINFO_CALL_INFO*      pCallInfo);
    GenTree* getTokenHandleTree(CORINFO_RESOLVED_TOKEN* pResolvedToken, bool parent);

    GenTree* fgMorphPotentialTailCall(GenTreeCall* call);
    void fgValidateIRForTailCall(GenTreeCall* call);
    GenTree* fgGetStubAddrArg(GenTreeCall* call);
    unsigned fgGetArgParameterLclNum(GenTreeCall* call, CallArg* arg);
    void fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall);
    Statement* fgAssignRecursiveCallArgToCallerParam(GenTree*         arg,
                                                     CallArg*         callArg,
                                                     unsigned         lclParamNum,
                                                     BasicBlock*      block,
                                                     const DebugInfo& callDI,
                                                     Statement*       tmpAssignmentInsertionPoint,
                                                     Statement*       paramAssignmentInsertionPoint);
    GenTree* fgMorphCall(GenTreeCall* call);
    GenTree* fgExpandVirtualVtableCallTarget(GenTreeCall* call);

    void fgMorphCallInline(GenTreeCall* call, InlineResult* result);
    void fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result, InlineContext** createdContext);
#if DEBUG
    void fgNoteNonInlineCandidate(Statement* stmt, GenTreeCall* call);
    static fgWalkPreFn fgFindNonInlineCandidate;
#endif
    GenTree* fgOptimizeDelegateConstructor(GenTreeCall*            call,
                                           CORINFO_CONTEXT_HANDLE* ExactContextHnd,
                                           methodPointerInfo*      ldftnToken);
    GenTree* fgMorphLeaf(GenTree* tree);
    GenTree* fgMorphOneAsgBlockOp(GenTree* tree);
    GenTree* fgMorphInitBlock(GenTree* tree);
    GenTree* fgMorphCopyBlock(GenTree* tree);
    GenTree* fgMorphStoreDynBlock(GenTreeStoreDynBlk* tree);
    GenTree* fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac, bool* optAssertionPropDone = nullptr);
    void fgTryReplaceStructLocalWithField(GenTree* tree);
    GenTree* fgOptimizeCast(GenTreeCast* cast);
    GenTree* fgOptimizeCastOnAssignment(GenTreeOp* asg);
    GenTree* fgOptimizeEqualityComparisonWithConst(GenTreeOp* cmp);
    GenTree* fgOptimizeRelationalComparisonWithConst(GenTreeOp* cmp);
    GenTree* fgOptimizeRelationalComparisonWithFullRangeConst(GenTreeOp* cmp);
#ifdef FEATURE_HW_INTRINSICS
    GenTree* fgOptimizeHWIntrinsic(GenTreeHWIntrinsic* node);
#endif
    GenTree* fgOptimizeCommutativeArithmetic(GenTreeOp* tree);
    GenTree* fgOptimizeRelationalComparisonWithCasts(GenTreeOp* cmp);
    GenTree* fgOptimizeAddition(GenTreeOp* add);
    GenTree* fgOptimizeMultiply(GenTreeOp* mul);
    GenTree* fgOptimizeBitwiseAnd(GenTreeOp* andOp);
    GenTree* fgOptimizeBitwiseXor(GenTreeOp* xorOp);
    GenTree* fgPropagateCommaThrow(GenTree* parent, GenTreeOp* commaThrow, GenTreeFlags precedingSideEffects);
    GenTree* fgMorphRetInd(GenTreeUnOp* tree);
    GenTree* fgMorphModToSubMulDiv(GenTreeOp* tree);
    GenTree* fgMorphUModToAndSub(GenTreeOp* tree);
    GenTree* fgMorphSmpOpOptional(GenTreeOp* tree, bool* optAssertionPropDone);
    GenTree* fgMorphMultiOp(GenTreeMultiOp* multiOp);
    GenTree* fgMorphConst(GenTree* tree);

    GenTreeOp* fgMorphCommutative(GenTreeOp* tree);
    GenTree* fgMorphCastedBitwiseOp(GenTreeOp* tree);

    GenTree* fgMorphReduceAddOps(GenTree* tree);

public:
    GenTree* fgMorphTree(GenTree* tree, MorphAddrContext* mac = nullptr);

private:
    void fgKillDependentAssertionsSingle(unsigned lclNum DEBUGARG(GenTree* tree));
    void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTree* tree));
    void fgMorphTreeDone(GenTree* tree);
    void fgMorphTreeDone(GenTree* tree, bool optAssertionPropDone, bool isMorphedTree DEBUGARG(int morphNum = 0));

    Statement* fgMorphStmt;
    unsigned   fgBigOffsetMorphingTemps[TYP_COUNT];

    unsigned fgGetFieldMorphingTemp(GenTreeField* type);

    //----------------------- Liveness analysis -------------------------------

    VARSET_TP fgCurUseSet; // vars used     by block (before an assignment)
    VARSET_TP fgCurDefSet; // vars assigned by block (before a use)

    MemoryKindSet fgCurMemoryUse;   // True iff the current basic block uses memory.
    MemoryKindSet fgCurMemoryDef;   // True iff the current basic block modifies memory.
    MemoryKindSet fgCurMemoryHavoc; // True if  the current basic block is known to set memory to a "havoc" value.

    bool byrefStatesMatchGcHeapStates; // True iff GcHeap and ByrefExposed memory have all the same def points.

    void fgMarkUseDef(GenTreeLclVarCommon* tree);

    void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
    void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);

    void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
    void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);

    void fgExtendDbgScopes();
    void fgExtendDbgLifetimes();

#ifdef DEBUG
    void fgDispDebugScopes();
#endif // DEBUG

    //-------------------------------------------------------------------------
    //
    //  The following keeps track of any code we've added for things like array
    //  range checking or explicit calls to enable GC, and so on.
    //
public:
    struct AddCodeDsc
    {
        AddCodeDsc*     acdNext;
        BasicBlock*     acdDstBlk; // block  to  which we jump
        unsigned        acdData;
        SpecialCodeKind acdKind; // what kind of a special block is this?
#if !FEATURE_FIXED_OUT_ARGS
        bool     acdStkLvlInit; // has acdStkLvl value been already set?
        unsigned acdStkLvl;     // stack level in stack slots.
#endif                          // !FEATURE_FIXED_OUT_ARGS
    };

private:
    static unsigned acdHelper(SpecialCodeKind codeKind);

    AddCodeDsc* fgAddCodeList;
    bool        fgAddCodeModf;
    bool        fgRngChkThrowAdded;
    AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];

    BasicBlock* fgRngChkTarget(BasicBlock* block, SpecialCodeKind kind);

    BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind);

public:
    AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);

    bool fgUseThrowHelperBlocks();

    AddCodeDsc* fgGetAdditionalCodeDescriptors()
    {
        return fgAddCodeList;
    }

private:
    bool fgIsCodeAdded();

    bool fgIsThrowHlpBlk(BasicBlock* block);

#if !FEATURE_FIXED_OUT_ARGS
    unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
#endif // !FEATURE_FIXED_OUT_ARGS

    unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
    void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result, InlineContext** createdContext);
    void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
    Statement* fgInlinePrependStatements(InlineInfo* inlineInfo);
    void fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* block, Statement* stmt);

#ifdef DEBUG
    static fgWalkPreFn fgDebugCheckInlineCandidates;

    void               CheckNoTransformableIndirectCallsRemain();
    static fgWalkPreFn fgDebugCheckForTransformableIndirectCalls;
#endif

    PhaseStatus fgPromoteStructs();
    void fgMorphLocalField(GenTree* tree, GenTree* parent);

    // Reset the refCount for implicit byrefs.
    void fgResetImplicitByRefRefCount();

    // Change implicit byrefs' types from struct to pointer, and for any that were
    // promoted, create new promoted struct temps.
    PhaseStatus fgRetypeImplicitByRefArgs();

    // Clear up annotations for any struct promotion temps created for implicit byrefs.
    void fgMarkDemotedImplicitByRefArgs();

    PhaseStatus fgMarkAddressExposedLocals();
    void fgMarkAddressExposedLocals(Statement* stmt);

    PhaseStatus fgForwardSub();
    bool fgForwardSubBlock(BasicBlock* block);
    bool fgForwardSubStatement(Statement* statement);

    // The given local variable, required to be a struct variable, is being assigned via
    // a "lclField", to make it masquerade as an integral type in the ABI.  Make sure that
    // the variable is not enregistered, and is therefore not promoted independently.
    void fgLclFldAssign(unsigned lclNum);

    enum TypeProducerKind
    {
        TPK_Unknown = 0, // May not be a RuntimeType
        TPK_Handle  = 1, // RuntimeType via handle
        TPK_GetType = 2, // RuntimeType via Object.get_Type()
        TPK_Null    = 3, // Tree value is null
        TPK_Other   = 4  // RuntimeType via other means
    };

    TypeProducerKind gtGetTypeProducerKind(GenTree* tree);
    bool gtIsTypeHandleToRuntimeTypeHelper(GenTreeCall* call);
    bool gtIsTypeHandleToRuntimeTypeHandleHelper(GenTreeCall* call, CorInfoHelpFunc* pHelper = nullptr);
    bool gtIsActiveCSE_Candidate(GenTree* tree);

    ExceptionSetFlags gtCollectExceptions(GenTree* tree);

    bool fgIsBigOffset(size_t offset);

    bool fgNeedReturnSpillTemp();

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           Optimizer                                       XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    void optInit();

    PhaseStatus rangeCheckPhase();
    GenTree* optRemoveRangeCheck(GenTreeBoundsChk* check, GenTree* comma, Statement* stmt);
    GenTree* optRemoveStandaloneRangeCheck(GenTreeBoundsChk* check, Statement* stmt);
    void optRemoveCommaBasedRangeCheck(GenTree* comma, Statement* stmt);

protected:
    // Do hoisting for all loops.
    PhaseStatus optHoistLoopCode();

    // To represent sets of VN's that have already been hoisted in outer loops.
    typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, bool> VNSet;

    struct LoopHoistContext
    {
    private:
        // The set of variables hoisted in the current loop (or nullptr if there are none).
        VNSet* m_pHoistedInCurLoop;

    public:
        // Value numbers of expressions that have been hoisted in the current (or most recent) loop in the nest.
        // Previous decisions on loop-invariance of value numbers in the current loop.
        VNSet m_curLoopVnInvariantCache;

        // Get the VN cache for current loop
        VNSet* GetHoistedInCurLoop(Compiler* comp)
        {
            if (m_pHoistedInCurLoop == nullptr)
            {
                m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
            }
            return m_pHoistedInCurLoop;
        }

        // Return the so far collected VNs in cache for current loop and reset it.
        void ResetHoistedInCurLoop()
        {
            m_pHoistedInCurLoop = nullptr;
            JITDUMP("Resetting m_pHoistedInCurLoop\n");
        }

        LoopHoistContext(Compiler* comp)
            : m_pHoistedInCurLoop(nullptr), m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
        {
        }
    };

    // Do hoisting of all loops nested within loop "lnum" (an index into the optLoopTable), followed
    // by the loop "lnum" itself.
    bool optHoistLoopNest(unsigned lnum, LoopHoistContext* hoistCtxt);

    // Do hoisting for a particular loop ("lnum" is an index into the optLoopTable.)
    bool optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt, BasicBlockList* existingPreHeaders);

    // Hoist all expressions in "blocks" that are invariant in loop "loopNum" (an index into the optLoopTable)
    // outside of that loop.
    void optHoistLoopBlocks(unsigned loopNum, ArrayStack<BasicBlock*>* blocks, LoopHoistContext* hoistContext);

    // Return true if the tree looks profitable to hoist out of loop 'lnum'.
    bool optIsProfitableToHoistTree(GenTree* tree, unsigned lnum);

    // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
    void optHoistCandidate(GenTree* tree, BasicBlock* treeBb, unsigned lnum, LoopHoistContext* hoistCtxt);

    // Note the new SSA uses in tree
    void optRecordSsaUses(GenTree* tree, BasicBlock* block);

    // Returns true iff the ValueNum "vn" represents a value that is loop-invariant in "lnum".
    //   Constants and init values are always loop invariant.
    //   VNPhi's connect VN's to the SSA definition, so we can know if the SSA def occurs in the loop.
    bool optVNIsLoopInvariant(ValueNum vn, unsigned lnum, VNSet* recordedVNs);

    // If "blk" is the entry block of a natural loop, returns true and sets "*pLnum" to the index of the loop
    // in the loop table.
    bool optBlockIsLoopEntry(BasicBlock* blk, unsigned* pLnum);

    // Records the set of "side effects" of all loops: fields (object instance and static)
    // written to, and SZ-array element type equivalence classes updated.
    void optComputeLoopSideEffects();

#ifdef DEBUG
    bool optAnyChildNotRemoved(unsigned loopNum);
#endif // DEBUG

    // Mark a loop as removed.
    void optMarkLoopRemoved(unsigned loopNum);

    // During global assertion prop, returns the conservative normal VN for a tree;
    // otherwise returns NoVN
    ValueNum optConservativeNormalVN(GenTree* tree);

private:
    // Requires "lnum" to be the index of an outermost loop in the loop table.  Traverses the body of that loop,
    // including all nested loops, and records the set of "side effects" of the loop: fields (object instance and
    // static) written to, and SZ-array element type equivalence classes updated.
    void optComputeLoopNestSideEffects(unsigned lnum);

    // Given a loop number 'lnum' mark it and any nested loops as having 'memoryHavoc'
    void optRecordLoopNestsMemoryHavoc(unsigned lnum, MemoryKindSet memoryHavoc);

    // Add the side effects of "blk" (which is required to be within a loop) to all loops of which it is a part.
    // Returns false if we encounter a block that is not marked as being inside a loop.
    //
    bool optComputeLoopSideEffectsOfBlock(BasicBlock* blk);

    // Hoist the expression "expr" out of loop "lnum".
    void optPerformHoistExpr(GenTree* expr, BasicBlock* exprBb, unsigned lnum);

public:
    PhaseStatus optOptimizeBools();

public:
    PhaseStatus optInvertLoops();    // Invert loops so they're entered at top and tested at bottom.
    PhaseStatus optOptimizeFlow();   // Simplify flow graph and do tail duplication
    PhaseStatus optOptimizeLayout(); // Optimize the BasicBlock layout of the method
    PhaseStatus optSetBlockWeights();
    PhaseStatus optFindLoopsPhase(); // Finds loops and records them in the loop table

    void optFindLoops();

    PhaseStatus optCloneLoops();
    void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
    void optEnsureUniqueHead(unsigned loopInd, weight_t ambientWeight);
    PhaseStatus optUnrollLoops(); // Unrolls loops (needs to have cost info)
    void        optRemoveRedundantZeroInits();
    PhaseStatus optIfConversion(); // If conversion

protected:
    // This enumeration describes what is killed by a call.

    enum callInterf
    {
        CALLINT_NONE,       // no interference                               (most helpers)
        CALLINT_REF_INDIRS, // kills GC ref indirections                     (SETFIELD OBJ)
        CALLINT_SCL_INDIRS, // kills non GC ref indirections                 (SETFIELD non-OBJ)
        CALLINT_ALL_INDIRS, // kills both GC ref and non GC ref indirections (SETFIELD STRUCT)
        CALLINT_ALL,        // kills everything                              (normal method call)
    };

    enum class FieldKindForVN
    {
        SimpleStatic,
        WithBaseAddr
    };

public:
    // A "LoopDsc" describes a ("natural") loop.  We (currently) require the body of a loop to be a contiguous (in
    // bbNext order) sequence of basic blocks.  (At times, we may require the blocks in a loop to be "properly numbered"
    // in bbNext order; we use comparisons on the bbNum to decide order.)
    // The blocks that define the body are
    //   top <= entry <= bottom
    // The "head" of the loop is a block outside the loop that has "entry" as a successor. We only support loops with a
    // single 'head' block. The meanings of these blocks are given in the definitions below. Also see the picture at
    // Compiler::optFindNaturalLoops().
    struct LoopDsc
    {
        BasicBlock* lpHead;   // HEAD of the loop (not part of the looping of the loop) -- has ENTRY as a successor.
        BasicBlock* lpTop;    // loop TOP (the back edge from lpBottom reaches here). Lexically first block (in bbNext
                              // order) reachable in this loop.
        BasicBlock* lpEntry;  // the ENTRY in the loop (in most cases TOP or BOTTOM)
        BasicBlock* lpBottom; // loop BOTTOM (from here we have a back edge to the TOP)
        BasicBlock* lpExit;   // if a single exit loop this is the EXIT (in most cases BOTTOM)

        callInterf   lpAsgCall;     // "callInterf" for calls in the loop
        ALLVARSET_TP lpAsgVars;     // set of vars assigned within the loop (all vars, not just tracked)
        varRefKinds  lpAsgInds : 8; // set of inds modified within the loop

        LoopFlags lpFlags;

        unsigned char lpExitCnt; // number of exits from the loop

        unsigned char lpParent;  // The index of the most-nested loop that completely contains this one,
                                 // or else BasicBlock::NOT_IN_LOOP if no such loop exists.
        unsigned char lpChild;   // The index of a nested loop, or else BasicBlock::NOT_IN_LOOP if no child exists.
                                 // (Actually, an "immediately" nested loop --
                                 // no other child of this loop is a parent of lpChild.)
        unsigned char lpSibling; // The index of another loop that is an immediate child of lpParent,
                                 // or else BasicBlock::NOT_IN_LOOP.  One can enumerate all the children of a loop
                                 // by following "lpChild" then "lpSibling" links.

        bool lpLoopHasMemoryHavoc[MemoryKindCount]; // The loop contains an operation that we assume has arbitrary
                                                    // memory side effects.  If this is set, the fields below
                                                    // may not be accurate (since they become irrelevant.)

        VARSET_TP lpVarInOut;  // The set of variables that are IN or OUT during the execution of this loop
        VARSET_TP lpVarUseDef; // The set of variables that are USE or DEF during the execution of this loop

        // The following counts are used for hoisting profitability checks.

        int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
                                // hoisted
        int lpLoopVarCount;     // The register count for the non-FP LclVars that are read/written inside this loop
        int lpVarInOutCount;    // The register count for the non-FP LclVars that are alive inside or across this loop

        int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
                                  // hoisted
        int lpLoopVarFPCount;     // The register count for the FP LclVars that are read/written inside this loop
        int lpVarInOutFPCount;    // The register count for the FP LclVars that are alive inside or across this loop

        bool lpHoistAddedPreheader; // The loop preheader was added during hoisting

        typedef JitHashTable<CORINFO_FIELD_HANDLE, JitPtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>, FieldKindForVN>
                        FieldHandleSet;
        FieldHandleSet* lpFieldsModified; // This has entries for all static field and object instance fields modified
                                          // in the loop.

        typedef JitHashTable<CORINFO_CLASS_HANDLE, JitPtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>, bool> ClassHandleSet;
        ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
                                                  // arrays of that type are modified
                                                  // in the loop.

        // Adds the variable liveness information for 'blk' to 'this' LoopDsc
        void AddVariableLiveness(Compiler* comp, BasicBlock* blk);

        inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd, FieldKindForVN fieldKind);
        // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles
        // (shifted left, with a low-order bit set to distinguish.)
        // Use the {Encode/Decode}ElemType methods to construct/destruct these.
        inline void AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd);

        /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */

        GenTree*   lpIterTree;          // The "i = i <op> const" tree
        unsigned   lpIterVar() const;   // iterator variable #
        int        lpIterConst() const; // the constant with which the iterator is incremented
        genTreeOps lpIterOper() const;  // the type of the operation on the iterator (ASG_ADD, ASG_SUB, etc.)
        void       VERIFY_lpIterTree() const;

        var_types lpIterOperType() const; // For overflow instructions

        // Set to the block where we found the initialization for LPFLG_CONST_INIT loops.
        // Initially, this will be 'head', but 'head' might change if we insert a loop pre-header block.
        BasicBlock* lpInitBlock;

        int lpConstInit; // initial constant value of iterator : Valid if LPFLG_CONST_INIT

        // The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var")

        GenTree*   lpTestTree;         // pointer to the node containing the loop test
        genTreeOps lpTestOper() const; // the type of the comparison between the iterator and the limit (GT_LE, GT_GE,
                                       // etc.)

        bool lpIsIncreasingLoop() const; // if the loop iterator increases from low to high value.
        bool lpIsDecreasingLoop() const; // if the loop iterator decreases from high to low value.

        void VERIFY_lpTestTree() const;

        bool     lpIsReversed() const; // true if the iterator node is the second operand in the loop condition
        GenTree* lpIterator() const;   // the iterator node in the loop test
        GenTree* lpLimit() const;      // the limit node in the loop test

        // Limit constant value of iterator - loop condition is "i RELOP const"
        // : Valid if LPFLG_CONST_LIMIT
        int lpConstLimit() const;

        // The lclVar # in the loop condition ( "i RELOP lclVar" )
        // : Valid if LPFLG_VAR_LIMIT
        unsigned lpVarLimit() const;

        // The array length in the loop condition ( "i RELOP arr.len" or "i RELOP arr[i][j].len" )
        // : Valid if LPFLG_ARRLEN_LIMIT
        bool lpArrLenLimit(Compiler* comp, ArrIndex* index) const;

        // Returns "true" iff this is a "top entry" loop.
        bool lpIsTopEntry() const
        {
            if (lpHead->bbNext == lpEntry)
            {
                assert(lpHead->bbFallsThrough());
                assert(lpTop == lpEntry);
                return true;
            }
            else
            {
                return false;
            }
        }

        // Returns "true" iff this is removed loop.
        bool lpIsRemoved() const
        {
            return (lpFlags & LPFLG_REMOVED) != 0;
        }

        // Returns "true" iff "*this" contains the blk.
        bool lpContains(BasicBlock* blk) const
        {
            return lpTop->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
        }

        // Returns "true" iff "*this" (properly) contains the range [top, bottom] (allowing tops
        // to be equal, but requiring bottoms to be different.)
        bool lpContains(BasicBlock* top, BasicBlock* bottom) const
        {
            return lpTop->bbNum <= top->bbNum && bottom->bbNum < lpBottom->bbNum;
        }

        // Returns "true" iff "*this" (properly) contains "lp2" (allowing tops to be equal, but requiring
        // bottoms to be different.)
        bool lpContains(const LoopDsc& lp2) const
        {
            return lpContains(lp2.lpTop, lp2.lpBottom);
        }

        // Returns "true" iff "*this" is (properly) contained by the range [top, bottom]
        // (allowing tops to be equal, but requiring bottoms to be different.)
        bool lpContainedBy(BasicBlock* top, BasicBlock* bottom) const
        {
            return top->bbNum <= lpTop->bbNum && lpBottom->bbNum < bottom->bbNum;
        }

        // Returns "true" iff "*this" is (properly) contained by "lp2"
        // (allowing tops to be equal, but requiring bottoms to be different.)
        bool lpContainedBy(const LoopDsc& lp2) const
        {
            return lpContainedBy(lp2.lpTop, lp2.lpBottom);
        }

        // Returns "true" iff "*this" is disjoint from the range [top, bottom].
        bool lpDisjoint(BasicBlock* top, BasicBlock* bottom) const
        {
            return bottom->bbNum < lpTop->bbNum || lpBottom->bbNum < top->bbNum;
        }
        // Returns "true" iff "*this" is disjoint from "lp2".
        bool lpDisjoint(const LoopDsc& lp2) const
        {
            return lpDisjoint(lp2.lpTop, lp2.lpBottom);
        }

        // Returns "true" iff the loop is well-formed (see code for defn).
        bool lpWellFormed() const
        {
            return lpTop->bbNum <= lpEntry->bbNum && lpEntry->bbNum <= lpBottom->bbNum &&
                   (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
        }

#ifdef DEBUG
        void lpValidatePreHeader() const
        {
            // If this is called, we expect there to be a pre-header.
            assert(lpFlags & LPFLG_HAS_PREHEAD);

            // The pre-header must unconditionally enter the loop.
            assert(lpHead->GetUniqueSucc() == lpEntry);

            // The loop block must be marked as a pre-header.
            assert(lpHead->bbFlags & BBF_LOOP_PREHEADER);

            // The loop entry must have a single non-loop predecessor, which is the pre-header.
            // We can't assume here that the bbNum are properly ordered, so we can't do a simple lpContained()
            // check. So, we defer this check, which will be done by `fgDebugCheckLoopTable()`.
        }
#endif // DEBUG

        // LoopBlocks: convenience method for enabling range-based `for` iteration over all the
        // blocks in a loop, e.g.:
        //    for (BasicBlock* const block : loop->LoopBlocks()) ...
        // Currently, the loop blocks are expected to be in linear, lexical, `bbNext` order
        // from `lpTop` through `lpBottom`, inclusive. All blocks in this range are considered
        // to be part of the loop.
        //
        BasicBlockRangeList LoopBlocks() const
        {
            return BasicBlockRangeList(lpTop, lpBottom);
        }
    };

protected:
    bool fgMightHaveLoop(); // returns true if there are any back edges
    bool fgHasLoops;        // True if this method has any loops, set in fgComputeReachability

public:
    LoopDsc*      optLoopTable;        // loop descriptor table
    bool          optLoopTableValid;   // info in loop table should be valid
    unsigned char optLoopCount;        // number of tracked loops
    unsigned char loopAlignCandidates; // number of loops identified for alignment

    // Every time we rebuild the loop table, we increase the global "loop epoch". Any loop indices or
    // loop table pointers from the previous epoch are invalid.
    // TODO: validate this in some way?
    unsigned optCurLoopEpoch;

    void NewLoopEpoch()
    {
        ++optCurLoopEpoch;
        JITDUMP("New loop epoch %d\n", optCurLoopEpoch);
    }

#ifdef DEBUG
    unsigned char loopsAligned; // number of loops actually aligned
#endif                          // DEBUG

    bool optRecordLoop(BasicBlock*   head,
                       BasicBlock*   top,
                       BasicBlock*   entry,
                       BasicBlock*   bottom,
                       BasicBlock*   exit,
                       unsigned char exitCnt);

    PhaseStatus optClearLoopIterInfo();

#ifdef DEBUG
    void optPrintLoopInfo(unsigned lnum, bool printVerbose = false);
    void optPrintLoopInfo(const LoopDsc* loop, bool printVerbose = false);
    void optPrintLoopTable();
#endif

protected:
    unsigned optCallCount;         // number of calls made in the method
    unsigned optIndirectCallCount; // number of virtual, interface and indirect calls made in the method
    unsigned optNativeCallCount;   // number of Pinvoke/Native calls made in the method
    unsigned optLoopsCloned;       // number of loops cloned in the current method.

#ifdef DEBUG
    void optCheckPreds();
#endif

    void optResetLoopInfo();
    void optFindAndScaleGeneralLoopBlocks();

    // Determine if there are any potential loops, and set BBF_LOOP_HEAD on potential loop heads.
    void optMarkLoopHeads();

    void optScaleLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);

    void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);

    void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);

    bool optIsLoopTestEvalIntoTemp(Statement* testStmt, Statement** newTestStmt);
    unsigned optIsLoopIncrTree(GenTree* incr);
    bool optCheckIterInLoopTest(unsigned loopInd, GenTree* test, unsigned iterVar);
    bool optComputeIterInfo(GenTree* incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar);
    bool optPopulateInitInfo(unsigned loopInd, BasicBlock* initBlock, GenTree* init, unsigned iterVar);
    bool optExtractInitTestIncr(
        BasicBlock* head, BasicBlock* bottom, BasicBlock* exit, GenTree** ppInit, GenTree** ppTest, GenTree** ppIncr);

    void optFindNaturalLoops();

    void optIdentifyLoopsForAlignment();

    // Ensures that all the loops in the loop nest rooted at "loopInd" (an index into the loop table) are 'canonical' --
    // each loop has a unique "top."  Returns "true" iff the flowgraph has been modified.
    bool optCanonicalizeLoopNest(unsigned char loopInd);

    // Ensures that the loop "loopInd" (an index into the loop table) is 'canonical' -- it has a unique "top,"
    // unshared with any other loop.  Returns "true" iff the flowgraph has been modified
    bool optCanonicalizeLoop(unsigned char loopInd);

    enum class LoopCanonicalizationOption
    {
        Outer,
        Current
    };

    bool optCanonicalizeLoopCore(unsigned char loopInd, LoopCanonicalizationOption option);

    // Requires "l1" to be a valid loop table index, and not "BasicBlock::NOT_IN_LOOP".
    // Requires "l2" to be a valid loop table index, or else "BasicBlock::NOT_IN_LOOP".
    // Returns true iff "l2" is not NOT_IN_LOOP, and "l1" contains "l2".
    // A loop contains itself.
    bool optLoopContains(unsigned l1, unsigned l2) const;

    // Returns the lpEntry for given preheader block of a loop
    BasicBlock* optLoopEntry(BasicBlock* preHeader);

    // Updates the loop table by changing loop "loopInd", whose head is required
    // to be "from", to be "to".  Also performs this transformation for any
    // loop nested in "loopInd" that shares the same head as "loopInd".
    void optUpdateLoopHead(unsigned loopInd, BasicBlock* from, BasicBlock* to);

    void optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap, const bool updatePreds = false);

    // Marks the containsCall information to "lnum" and any parent loops.
    void AddContainsCallAllContainingLoops(unsigned lnum);

    // Adds the variable liveness information from 'blk' to "lnum" and any parent loops.
    void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk);

    // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops.
    void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd, FieldKindForVN fieldKind);

    // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops.
    void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType);

    // Requires that "from" and "to" have the same "bbJumpKind" (perhaps because "to" is a clone
    // of "from".)  Copies the jump destination from "from" to "to".
    void optCopyBlkDest(BasicBlock* from, BasicBlock* to);

    // Returns true if 'block' is an entry block for any loop in 'optLoopTable'
    bool optIsLoopEntry(BasicBlock* block) const;

    // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
    unsigned optLoopDepth(unsigned lnum)
    {
        assert(lnum < optLoopCount);
        unsigned depth = 0;
        while ((lnum = optLoopTable[lnum].lpParent) != BasicBlock::NOT_IN_LOOP)
        {
            ++depth;
        }
        return depth;
    }

    // Struct used in optInvertWhileLoop to count interesting constructs to boost the profitability score.
    struct OptInvertCountTreeInfoType
    {
        int sharedStaticHelperCount;
        int arrayLengthCount;
    };

    OptInvertCountTreeInfoType optInvertCountTreeInfo(GenTree* tree);

    bool optInvertWhileLoop(BasicBlock* block);
    bool optIfConvert(BasicBlock* block);

private:
    static bool optIterSmallOverflow(int iterAtExit, var_types incrType);
    static bool optIterSmallUnderflow(int iterAtExit, var_types decrType);

    bool optComputeLoopRep(int        constInit,
                           int        constLimit,
                           int        iterInc,
                           genTreeOps iterOper,
                           var_types  iterType,
                           genTreeOps testOper,
                           bool       unsignedTest,
                           bool       dupCond,
                           unsigned*  iterCount);

protected:
    struct isVarAssgDsc
    {
        GenTree*     ivaSkip;
        ALLVARSET_TP ivaMaskVal;        // Set of variables assigned to.  This is a set of all vars, not tracked vars.
        unsigned     ivaVar;            // Variable we are interested in, or -1
        varRefKinds  ivaMaskInd;        // What kind of indirect assignments are there?
        callInterf   ivaMaskCall;       // What kind of calls are there?
        bool         ivaMaskIncomplete; // Variables not representable in ivaMaskVal were assigned to.
    };

    bool optIsVarAssignedWithDesc(Statement* stmt, isVarAssgDsc* dsc);

    bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTree* skip, unsigned var);

    bool optIsVarAssgLoop(unsigned lnum, unsigned var);

    bool optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);

    bool optNarrowTree(GenTree* tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);

protected:
    //  The following is the upper limit on how many expressions we'll keep track
    //  of for the CSE analysis.
    //
    static const unsigned MAX_CSE_CNT = EXPSET_SZ;

    static const int MIN_CSE_COST = 2;

    // BitVec trait information only used by the optCSE_canSwap() method, for the  CSE_defMask and CSE_useMask.
    // This BitVec uses one bit per CSE candidate
    BitVecTraits* cseMaskTraits; // one bit per CSE candidate

    // BitVec trait information for computing CSE availability using the CSE_DataFlow algorithm.
    // Two bits are allocated per CSE candidate to compute CSE availability
    // plus an extra bit to handle the initial unvisited case.
    // (See CSE_DataFlow::EndMerge for an explanation of why this is necessary.)
    //
    // The two bits per CSE candidate have the following meanings:
    //     11 - The CSE is available, and is also available when considering calls as killing availability.
    //     10 - The CSE is available, but is not available when considering calls as killing availability.
    //     00 - The CSE is not available
    //     01 - An illegal combination
    //
    BitVecTraits* cseLivenessTraits;

    //-----------------------------------------------------------------------------------------------------------------
    // getCSEnum2bit: Return the normalized index to use in the EXPSET_TP for the CSE with the given CSE index.
    // Each GenTree has a `gtCSEnum` field. Zero is reserved to mean this node is not a CSE, positive values indicate
    // CSE uses, and negative values indicate CSE defs. The caller must pass a non-zero positive value, as from
    // GET_CSE_INDEX().
    //
    static unsigned genCSEnum2bit(unsigned CSEnum)
    {
        assert((CSEnum > 0) && (CSEnum <= MAX_CSE_CNT));
        return CSEnum - 1;
    }

    //-----------------------------------------------------------------------------------------------------------------
    // getCSEAvailBit: Return the bit used by CSE dataflow sets (bbCseGen, etc.) for the availability bit for a CSE.
    //
    static unsigned getCSEAvailBit(unsigned CSEnum)
    {
        return genCSEnum2bit(CSEnum) * 2;
    }

    //-----------------------------------------------------------------------------------------------------------------
    // getCSEAvailCrossCallBit: Return the bit used by CSE dataflow sets (bbCseGen, etc.) for the availability bit
    // for a CSE considering calls as killing availability bit (see description above).
    //
    static unsigned getCSEAvailCrossCallBit(unsigned CSEnum)
    {
        return getCSEAvailBit(CSEnum) + 1;
    }

    void optPrintCSEDataFlowSet(EXPSET_VALARG_TP cseDataFlowSet, bool includeBits = true);

    EXPSET_TP cseCallKillsMask; // Computed once - A mask that is used to kill available CSEs at callsites

    /* Generic list of nodes - used by the CSE logic */

    struct treeLst
    {
        treeLst* tlNext;
        GenTree* tlTree;
    };

    struct treeStmtLst
    {
        treeStmtLst* tslNext;
        GenTree*     tslTree;  // tree node
        Statement*   tslStmt;  // statement containing the tree
        BasicBlock*  tslBlock; // block containing the statement
    };

    // The following logic keeps track of expressions via a simple hash table.

    struct CSEdsc
    {
        CSEdsc*  csdNextInBucket;  // used by the hash table
        size_t   csdHashKey;       // the original hashkey
        ssize_t  csdConstDefValue; // When we CSE similar constants, this is the value that we use as the def
        ValueNum csdConstDefVN;    // When we CSE similar constants, this is the ValueNumber that we use for the LclVar
                                   // assignment
        unsigned csdIndex;         // 1..optCSECandidateCount
        bool     csdIsSharedConst; // true if this CSE is a shared const
        bool     csdLiveAcrossCall;

        unsigned short csdDefCount; // definition   count
        unsigned short csdUseCount; // use          count  (excluding the implicit uses at defs)

        weight_t csdDefWtCnt; // weighted def count
        weight_t csdUseWtCnt; // weighted use count  (excluding the implicit uses at defs)

        GenTree*    csdTree;  // treenode containing the 1st occurrence
        Statement*  csdStmt;  // stmt containing the 1st occurrence
        BasicBlock* csdBlock; // block containing the 1st occurrence

        treeStmtLst* csdTreeList; // list of matching tree nodes: head
        treeStmtLst* csdTreeLast; // list of matching tree nodes: tail

        // ToDo: This can be removed when gtGetStructHandleIfPresent stops guessing
        // and GT_IND nodes always have valid struct handle.
        //
        CORINFO_CLASS_HANDLE csdStructHnd; // The class handle, currently needed to create a SIMD LclVar in PerformCSE
        bool                 csdStructHndMismatch;

        ValueNum defExcSetPromise; // The exception set that is now required for all defs of this CSE.
                                   // This will be set to NoVN if we decide to abandon this CSE

        ValueNum defExcSetCurrent; // The set of exceptions we currently can use for CSE uses.

        ValueNum defConservNormVN; // if all def occurrences share the same conservative normal value
                                   // number, this will reflect it; otherwise, NoVN.
                                   // not used for shared const CSE's
    };

    static const size_t s_optCSEhashSizeInitial;
    static const size_t s_optCSEhashGrowthFactor;
    static const size_t s_optCSEhashBucketSize;
    size_t              optCSEhashSize;                 // The current size of hashtable
    size_t              optCSEhashCount;                // Number of entries in hashtable
    size_t              optCSEhashMaxCountBeforeResize; // Number of entries before resize
    CSEdsc**            optCSEhash;
    CSEdsc**            optCSEtab;

    typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, GenTree*> NodeToNodeMap;

    NodeToNodeMap* optCseCheckedBoundMap; // Maps bound nodes to ancestor compares that should be
                                          // re-numbered with the bound to improve range check elimination

    // Given a compare, look for a cse candidate checked bound feeding it and add a map entry if found.
    void optCseUpdateCheckedBoundMap(GenTree* compare);

    void optCSEstop();

    CSEdsc* optCSEfindDsc(unsigned index);
    bool optUnmarkCSE(GenTree* tree);

    // user defined callback data for the tree walk function optCSE_MaskHelper()
    struct optCSE_MaskData
    {
        EXPSET_TP CSE_defMask;
        EXPSET_TP CSE_useMask;
    };

    // Treewalk helper for optCSE_DefMask and optCSE_UseMask
    static fgWalkPreFn optCSE_MaskHelper;

    // This function walks all the node for an given tree
    // and return the mask of CSE definitions and uses for the tree
    //
    void optCSE_GetMaskData(GenTree* tree, optCSE_MaskData* pMaskData);

    // Given a binary tree node return true if it is safe to swap the order of evaluation for op1 and op2.
    bool optCSE_canSwap(GenTree* firstNode, GenTree* secondNode);

    struct optCSEcostCmpEx
    {
        bool operator()(const CSEdsc* op1, const CSEdsc* op2);
    };
    struct optCSEcostCmpSz
    {
        bool operator()(const CSEdsc* op1, const CSEdsc* op2);
    };

    void optCleanupCSEs();

#ifdef DEBUG
    void optEnsureClearCSEInfo();
#endif // DEBUG

    static bool Is_Shared_Const_CSE(size_t key)
    {
        return ((key & TARGET_SIGN_BIT) != 0);
    }

    // returns the encoded key
    static size_t Encode_Shared_Const_CSE_Value(size_t key)
    {
        return TARGET_SIGN_BIT | (key >> CSE_CONST_SHARED_LOW_BITS);
    }

    // returns the original key
    static size_t Decode_Shared_Const_CSE_Value(size_t enckey)
    {
        assert(Is_Shared_Const_CSE(enckey));
        return (enckey & ~TARGET_SIGN_BIT) << CSE_CONST_SHARED_LOW_BITS;
    }

/**************************************************************************
 *                   Value Number based CSEs
 *************************************************************************/

// String to use for formatting CSE numbers. Note that this is the positive number, e.g., from GET_CSE_INDEX().
#define FMT_CSE "CSE #%02u"

public:
    PhaseStatus optOptimizeValnumCSEs();

protected:
    void     optValnumCSE_Init();
    unsigned optValnumCSE_Index(GenTree* tree, Statement* stmt);
    bool optValnumCSE_Locate();
    void optValnumCSE_InitDataFlow();
    void optValnumCSE_DataFlow();
    void optValnumCSE_Availability();
    bool optValnumCSE_Heuristic();

    bool     optDoCSE;             // True when we have found a duplicate CSE tree
    bool     optValnumCSE_phase;   // True when we are executing the optOptimizeValnumCSEs() phase
    unsigned optCSECandidateCount; // Count of CSE's candidates
    unsigned optCSEstart;          // The first local variable number that is a CSE
    unsigned optCSEcount;          // The total count of CSE's introduced.
    weight_t optCSEweight;         // The weight of the current block when we are doing PerformCSE

    bool optIsCSEcandidate(GenTree* tree);

    // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
    //
    bool lclNumIsTrueCSE(unsigned lclNum) const
    {
        return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
    }

    //  lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
    //
    bool lclNumIsCSE(unsigned lclNum) const
    {
        return lvaGetDesc(lclNum)->lvIsCSE;
    }

#ifdef DEBUG
    bool optConfigDisableCSE();
    bool optConfigDisableCSE2();
#endif

    void optOptimizeCSEs();

    static callInterf optCallInterf(GenTreeCall* call);

public:
    // VN based copy propagation.

    // In DEBUG builds, we'd like to know the tree that the SSA definition was pushed for.
    // While for ordinary SSA defs it will be available (as an ASG) in the SSA descriptor,
    // for locals which will use "definitions from uses", it will not be, so we store it
    // in this class instead.
    class CopyPropSsaDef
    {
        LclSsaVarDsc* m_ssaDef;
#ifdef DEBUG
        GenTree* m_defNode;
#endif
    public:
        CopyPropSsaDef(LclSsaVarDsc* ssaDef, GenTree* defNode)
            : m_ssaDef(ssaDef)
#ifdef DEBUG
            , m_defNode(defNode)
#endif
        {
        }

        LclSsaVarDsc* GetSsaDef() const
        {
            return m_ssaDef;
        }

#ifdef DEBUG
        GenTree* GetDefNode() const
        {
            return m_defNode;
        }
#endif
    };

    typedef ArrayStack<CopyPropSsaDef> CopyPropSsaDefStack;
    typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, CopyPropSsaDefStack*> LclNumToLiveDefsMap;

    // Copy propagation functions.
    bool optCopyProp(BasicBlock*          block,
                     Statement*           stmt,
                     GenTreeLclVarCommon* tree,
                     unsigned             lclNum,
                     LclNumToLiveDefsMap* curSsaName);
    void optBlockCopyPropPopStacks(BasicBlock* block, LclNumToLiveDefsMap* curSsaName);
    bool optBlockCopyProp(BasicBlock* block, LclNumToLiveDefsMap* curSsaName);
    void optCopyPropPushDef(GenTree* defNode, GenTreeLclVarCommon* lclNode, LclNumToLiveDefsMap* curSsaName);
    int optCopyProp_LclVarScore(const LclVarDsc* lclVarDsc, const LclVarDsc* copyVarDsc, bool preferOp2);
    PhaseStatus optVnCopyProp();
    INDEBUG(void optDumpCopyPropStack(LclNumToLiveDefsMap* curSsaName));

    /**************************************************************************
     *               Early value propagation
     *************************************************************************/
    struct SSAName
    {
        unsigned m_lvNum;
        unsigned m_ssaNum;

        SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
        {
        }

        static unsigned GetHashCode(SSAName ssaNm)
        {
            return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
        }

        static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
        {
            return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
        }
    };

// clang-format off

#define OMF_HAS_NEWARRAY                       0x00000001 // Method contains 'new' of an SD array
#define OMF_HAS_NEWOBJ                         0x00000002 // Method contains 'new' of an object type.
#define OMF_HAS_ARRAYREF                       0x00000004 // Method contains array element loads or stores.
#define OMF_HAS_NULLCHECK                      0x00000008 // Method contains null check.
#define OMF_HAS_FATPOINTER                     0x00000010 // Method contains call, that needs fat pointer transformation.
#define OMF_HAS_OBJSTACKALLOC                  0x00000020 // Method contains an object allocated on the stack.
#define OMF_HAS_GUARDEDDEVIRT                  0x00000040 // Method contains guarded devirtualization candidate
#define OMF_HAS_EXPRUNTIMELOOKUP               0x00000080 // Method contains a runtime lookup to an expandable dictionary.
#define OMF_HAS_PATCHPOINT                     0x00000100 // Method contains patchpoints
#define OMF_NEEDS_GCPOLLS                      0x00000200 // Method needs GC polls
#define OMF_HAS_FROZEN_OBJECTS                 0x00000400 // Method has frozen objects (REF constant int)
#define OMF_HAS_PARTIAL_COMPILATION_PATCHPOINT 0x00000800 // Method contains partial compilation patchpoints
#define OMF_HAS_TAILCALL_SUCCESSOR             0x00001000 // Method has potential tail call in a non BBJ_RETURN block
#define OMF_HAS_MDNEWARRAY                     0x00002000 // Method contains 'new' of an MD array
#define OMF_HAS_MDARRAYREF                     0x00004000 // Method contains multi-dimensional intrinsic array element loads or stores.

    // clang-format on

    bool doesMethodHaveFatPointer()
    {
        return (optMethodFlags & OMF_HAS_FATPOINTER) != 0;
    }

    void setMethodHasFatPointer()
    {
        optMethodFlags |= OMF_HAS_FATPOINTER;
    }

    void clearMethodHasFatPointer()
    {
        optMethodFlags &= ~OMF_HAS_FATPOINTER;
    }

    void addFatPointerCandidate(GenTreeCall* call);

    bool doesMethodHaveFrozenObjects() const
    {
        return (optMethodFlags & OMF_HAS_FROZEN_OBJECTS) != 0;
    }

    void setMethodHasFrozenObjects()
    {
        optMethodFlags |= OMF_HAS_FROZEN_OBJECTS;
    }

    bool doesMethodHaveGuardedDevirtualization() const
    {
        return (optMethodFlags & OMF_HAS_GUARDEDDEVIRT) != 0;
    }

    void setMethodHasGuardedDevirtualization()
    {
        optMethodFlags |= OMF_HAS_GUARDEDDEVIRT;
    }

    void pickGDV(GenTreeCall*           call,
                 IL_OFFSET              ilOffset,
                 bool                   isInterface,
                 CORINFO_CLASS_HANDLE*  classGuess,
                 CORINFO_METHOD_HANDLE* methodGuess,
                 unsigned*              likelihood);

    void considerGuardedDevirtualization(GenTreeCall*            call,
                                         IL_OFFSET               ilOffset,
                                         bool                    isInterface,
                                         CORINFO_METHOD_HANDLE   baseMethod,
                                         CORINFO_CLASS_HANDLE    baseClass,
                                         CORINFO_CONTEXT_HANDLE* pContextHandle);

    bool isCompatibleMethodGDV(GenTreeCall* call, CORINFO_METHOD_HANDLE gdvTarget);

    void addGuardedDevirtualizationCandidate(GenTreeCall*          call,
                                             CORINFO_METHOD_HANDLE methodHandle,
                                             CORINFO_CLASS_HANDLE  classHandle,
                                             unsigned              methodAttr,
                                             unsigned              classAttr,
                                             unsigned              likelihood);

    bool doesMethodHaveExpRuntimeLookup()
    {
        return (optMethodFlags & OMF_HAS_EXPRUNTIMELOOKUP) != 0;
    }

    void setMethodHasExpRuntimeLookup()
    {
        optMethodFlags |= OMF_HAS_EXPRUNTIMELOOKUP;
    }

    void clearMethodHasExpRuntimeLookup()
    {
        optMethodFlags &= ~OMF_HAS_EXPRUNTIMELOOKUP;
    }

    void addExpRuntimeLookupCandidate(GenTreeCall* call);

    bool doesMethodHavePatchpoints()
    {
        return (optMethodFlags & OMF_HAS_PATCHPOINT) != 0;
    }

    void setMethodHasPatchpoint()
    {
        optMethodFlags |= OMF_HAS_PATCHPOINT;
    }

    bool doesMethodHavePartialCompilationPatchpoints()
    {
        return (optMethodFlags & OMF_HAS_PARTIAL_COMPILATION_PATCHPOINT) != 0;
    }

    void setMethodHasPartialCompilationPatchpoint()
    {
        optMethodFlags |= OMF_HAS_PARTIAL_COMPILATION_PATCHPOINT;
    }

    unsigned optMethodFlags;

    bool doesMethodHaveNoReturnCalls()
    {
        return optNoReturnCallCount > 0;
    }

    void setMethodHasNoReturnCalls()
    {
        optNoReturnCallCount++;
    }

    unsigned optNoReturnCallCount;

    // Recursion bound controls how far we can go backwards tracking for a SSA value.
    // No throughput diff was found with backward walk bound between 3-8.
    static const int optEarlyPropRecurBound = 5;

    enum class optPropKind
    {
        OPK_INVALID,
        OPK_ARRAYLEN,
        OPK_NULLCHECK
    };

    typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, GenTree*> LocalNumberToNullCheckTreeMap;

    GenTree* getArrayLengthFromAllocation(GenTree* tree DEBUGARG(BasicBlock* block));
    GenTree* optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth);
    GenTree* optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind);
    GenTree* optEarlyPropRewriteTree(GenTree* tree, LocalNumberToNullCheckTreeMap* nullCheckMap);
    bool optDoEarlyPropForBlock(BasicBlock* block);
    bool        optDoEarlyPropForFunc();
    PhaseStatus optEarlyProp();
    bool optFoldNullCheck(GenTree* tree, LocalNumberToNullCheckTreeMap* nullCheckMap);
    GenTree* optFindNullCheckToFold(GenTree* tree, LocalNumberToNullCheckTreeMap* nullCheckMap);
    bool optIsNullCheckFoldingLegal(GenTree*    tree,
                                    GenTree*    nullCheckTree,
                                    GenTree**   nullCheckParent,
                                    Statement** nullCheckStmt);
    bool optCanMoveNullCheckPastTree(GenTree* tree,
                                     unsigned nullCheckLclNum,
                                     bool     isInsideTry,
                                     bool     checkSideEffectSummary);
#if DEBUG
    void optCheckFlagsAreSet(unsigned    methodFlag,
                             const char* methodFlagStr,
                             unsigned    bbFlag,
                             const char* bbFlagStr,
                             GenTree*    tree,
                             BasicBlock* basicBlock);
#endif

    // Redundant branch opts
    //
    PhaseStatus optRedundantBranches();
    bool optRedundantRelop(BasicBlock* const block);
    bool optRedundantBranch(BasicBlock* const block);
    bool optJumpThreadDom(BasicBlock* const block, BasicBlock* const domBlock, bool domIsSameRelop);
    bool optJumpThreadPhi(BasicBlock* const block, GenTree* tree, ValueNum treeNormVN);
    bool optJumpThreadCheck(BasicBlock* const block, BasicBlock* const domBlock);
    bool optJumpThreadCore(JumpThreadInfo& jti);
    bool optReachable(BasicBlock* const fromBlock, BasicBlock* const toBlock, BasicBlock* const excludedBlock);
    BitVecTraits* optReachableBitVecTraits;
    BitVec        optReachableBitVec;
    void optRelopImpliesRelop(RelopImplicationInfo* rii);

    /**************************************************************************
     *               Value/Assertion propagation
     *************************************************************************/
public:
    // Data structures for assertion prop
    BitVecTraits* apTraits;
    ASSERT_TP     apFull;

    enum optAssertionKind
    {
        OAK_INVALID,
        OAK_EQUAL,
        OAK_NOT_EQUAL,
        OAK_SUBRANGE,
        OAK_NO_THROW,
        OAK_COUNT
    };

    enum optOp1Kind
    {
        O1K_INVALID,
        O1K_LCLVAR,
        O1K_ARR_BND,
        O1K_BOUND_OPER_BND,
        O1K_BOUND_LOOP_BND,
        O1K_CONSTANT_LOOP_BND,
        O1K_CONSTANT_LOOP_BND_UN,
        O1K_EXACT_TYPE,
        O1K_SUBTYPE,
        O1K_VALUE_NUMBER,
        O1K_COUNT
    };

    enum optOp2Kind
    {
        O2K_INVALID,
        O2K_LCLVAR_COPY,
        O2K_IND_CNS_INT,
        O2K_CONST_INT,
        O2K_CONST_LONG,
        O2K_CONST_DOUBLE,
        O2K_ZEROOBJ,
        O2K_SUBRANGE,
        O2K_COUNT
    };

    struct AssertionDsc
    {
        optAssertionKind assertionKind;
        struct SsaVar
        {
            unsigned lclNum; // assigned to or property of this local var number
            unsigned ssaNum;
        };
        struct ArrBnd
        {
            ValueNum vnIdx;
            ValueNum vnLen;
        };
        struct AssertionDscOp1
        {
            optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
            ValueNum   vn;
            union {
                SsaVar lcl;
                ArrBnd bnd;
            };
        } op1;
        struct AssertionDscOp2
        {
            optOp2Kind kind; // a const or copy assignment
            ValueNum   vn;
            struct IntVal
            {
                ssize_t iconVal; // integer
#if !defined(HOST_64BIT)
                unsigned padding; // unused; ensures iconFlags does not overlap lconVal
#endif
                GenTreeFlags iconFlags; // gtFlags
            };
            union {
                SsaVar        lcl;
                IntVal        u1;
                __int64       lconVal;
                double        dconVal;
                IntegralRange u2;
            };
        } op2;

        bool IsCheckedBoundArithBound()
        {
            return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_OPER_BND);
        }
        bool IsCheckedBoundBound()
        {
            return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_LOOP_BND);
        }
        bool IsConstantBound()
        {
            return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
                    (op1.kind == O1K_CONSTANT_LOOP_BND));
        }
        bool IsConstantBoundUnsigned()
        {
            return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
                    (op1.kind == O1K_CONSTANT_LOOP_BND_UN));
        }
        bool IsBoundsCheckNoThrow()
        {
            return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
        }

        bool IsCopyAssertion()
        {
            return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
        }

        bool IsConstantInt32Assertion()
        {
            return ((assertionKind == OAK_EQUAL) || (assertionKind == OAK_NOT_EQUAL)) && (op2.kind == O2K_CONST_INT);
        }

        bool CanPropLclVar()
        {
            return assertionKind == OAK_EQUAL && op1.kind == O1K_LCLVAR;
        }

        bool CanPropEqualOrNotEqual()
        {
            return assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL;
        }

        bool CanPropNonNull()
        {
            return assertionKind == OAK_NOT_EQUAL && op2.vn == ValueNumStore::VNForNull();
        }

        bool CanPropBndsCheck()
        {
            return op1.kind == O1K_ARR_BND;
        }

        bool CanPropSubRange()
        {
            return assertionKind == OAK_SUBRANGE && op1.kind == O1K_LCLVAR;
        }

        static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
        {
            return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
                   a1->op2.kind == a2->op2.kind;
        }

        static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
        {
            if (kind == OAK_EQUAL)
            {
                return kind2 == OAK_NOT_EQUAL;
            }
            else if (kind == OAK_NOT_EQUAL)
            {
                return kind2 == OAK_EQUAL;
            }
            return false;
        }

        bool HasSameOp1(AssertionDsc* that, bool vnBased)
        {
            if (op1.kind != that->op1.kind)
            {
                return false;
            }
            else if (op1.kind == O1K_ARR_BND)
            {
                assert(vnBased);
                return (op1.bnd.vnIdx == that->op1.bnd.vnIdx) && (op1.bnd.vnLen == that->op1.bnd.vnLen);
            }
            else
            {
                return ((vnBased && (op1.vn == that->op1.vn)) ||
                        (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
            }
        }

        bool HasSameOp2(AssertionDsc* that, bool vnBased)
        {
            if (op2.kind != that->op2.kind)
            {
                return false;
            }

            switch (op2.kind)
            {
                case O2K_IND_CNS_INT:
                case O2K_CONST_INT:
                    return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));

                case O2K_CONST_LONG:
                    return (op2.lconVal == that->op2.lconVal);

                case O2K_CONST_DOUBLE:
                    // exact match because of positive and negative zero.
                    return (memcmp(&op2.dconVal, &that->op2.dconVal, sizeof(double)) == 0);

                case O2K_ZEROOBJ:
                    return true;

                case O2K_LCLVAR_COPY:
                    return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
                           (!vnBased || (op2.lcl.ssaNum == that->op2.lcl.ssaNum));

                case O2K_SUBRANGE:
                    return op2.u2.Equals(that->op2.u2);

                case O2K_INVALID:
                    // we will return false
                    break;

                default:
                    assert(!"Unexpected value for op2.kind in AssertionDsc.");
                    break;
            }

            return false;
        }

        bool Complementary(AssertionDsc* that, bool vnBased)
        {
            return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
                   HasSameOp2(that, vnBased);
        }

        bool Equals(AssertionDsc* that, bool vnBased)
        {
            if (assertionKind != that->assertionKind)
            {
                return false;
            }
            else if (assertionKind == OAK_NO_THROW)
            {
                assert(op2.kind == O2K_INVALID);
                return HasSameOp1(that, vnBased);
            }
            else
            {
                return HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
            }
        }
    };

protected:
    static fgWalkPreFn optAddCopiesCallback;
    static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
    unsigned           optAddCopyLclNum;
    GenTree*           optAddCopyAsgnNode;

    bool optLocalAssertionProp;  // indicates that we are performing local assertion prop
    bool optAssertionPropagated; // set to true if we modified the trees
    bool optAssertionPropagatedCurrentStmt;
#ifdef DEBUG
    GenTree* optAssertionPropCurrentTree;
#endif
    AssertionIndex*            optComplementaryAssertionMap;
    JitExpandArray<ASSERT_TP>* optAssertionDep; // table that holds dependent assertions (assertions
                                                // using the value of a local var) for each local var
    AssertionDsc*  optAssertionTabPrivate;      // table that holds info about value assignments
    AssertionIndex optAssertionCount;           // total number of assertions in the assertion table
    AssertionIndex optMaxAssertionCount;
    bool           optCanPropLclVar;
    bool           optCanPropEqual;
    bool           optCanPropNonNull;
    bool           optCanPropBndsChk;
    bool           optCanPropSubRange;

public:
    void optVnNonNullPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree);
    fgWalkResult optVNConstantPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree);
    GenTree* optVNConstantPropOnJTrue(BasicBlock* block, GenTree* test);
    GenTree* optVNConstantPropOnTree(BasicBlock* block, GenTree* tree);
    GenTree* optExtractSideEffListFromConst(GenTree* tree);

    AssertionIndex GetAssertionCount()
    {
        return optAssertionCount;
    }
    ASSERT_TP* bbJtrueAssertionOut;
    typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP> ValueNumToAssertsMap;
    ValueNumToAssertsMap* optValueNumToAsserts;

    // Assertion prop helpers.
    ASSERT_TP& GetAssertionDep(unsigned lclNum);
    AssertionDsc* optGetAssertion(AssertionIndex assertIndex);
    void optAssertionInit(bool isLocalProp);
    void optAssertionTraitsInit(AssertionIndex assertionCount);
    void optAssertionReset(AssertionIndex limit);
    void optAssertionRemove(AssertionIndex index);

    // Assertion prop data flow functions.
    PhaseStatus optAssertionPropMain();
    Statement* optVNAssertionPropCurStmt(BasicBlock* block, Statement* stmt);
    bool optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, GenTreeFlags* pIconFlags);
    ASSERT_TP* optInitAssertionDataflowFlags();
    ASSERT_TP* optComputeAssertionGen();

    // Assertion Gen functions.
    void optAssertionGen(GenTree* tree);
    AssertionIndex optAssertionGenCast(GenTreeCast* cast);
    AssertionIndex optAssertionGenPhiDefn(GenTree* tree);
    AssertionInfo optCreateJTrueBoundsAssertion(GenTree* tree);
    AssertionInfo optAssertionGenJtrue(GenTree* tree);
    AssertionIndex optCreateJtrueAssertions(GenTree*                   op1,
                                            GenTree*                   op2,
                                            Compiler::optAssertionKind assertionKind,
                                            bool                       helperCallArgs = false);
    AssertionIndex optFindComplementary(AssertionIndex assertionIndex);
    void optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index);

    // Assertion creation functions.
    AssertionIndex optCreateAssertion(GenTree*         op1,
                                      GenTree*         op2,
                                      optAssertionKind assertionKind,
                                      bool             helperCallArgs = false);

    AssertionIndex optFinalizeCreatingAssertion(AssertionDsc* assertion);
    ssize_t optCastConstantSmall(ssize_t iconVal, var_types smallType);

    bool optTryExtractSubrangeAssertion(GenTree* source, IntegralRange* pRange);

    void optCreateComplementaryAssertion(AssertionIndex assertionIndex,
                                         GenTree*       op1,
                                         GenTree*       op2,
                                         bool           helperCallArgs = false);

    bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
    AssertionIndex optAddAssertion(AssertionDsc* assertion);
    void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
#ifdef DEBUG
    void optPrintVnAssertionMapping();
#endif
    ASSERT_TP optGetVnMappedAssertions(ValueNum vn);

    // Used for respective assertion propagations.
    AssertionIndex optAssertionIsSubrange(GenTree* tree, IntegralRange range, ASSERT_VALARG_TP assertions);
    AssertionIndex optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions);
    AssertionIndex optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased));
    bool optAssertionIsNonNull(GenTree*         op,
                               ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex));

    AssertionIndex optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2);
    AssertionIndex optGlobalAssertionIsEqualOrNotEqualZero(ASSERT_VALARG_TP assertions, GenTree* op1);
    AssertionIndex optLocalAssertionIsEqualOrNotEqual(
        optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions);

    // Assertion prop for lcl var functions.
    bool optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
    GenTree* optCopyAssertionProp(AssertionDsc*        curAssertion,
                                  GenTreeLclVarCommon* tree,
                                  Statement* stmt DEBUGARG(AssertionIndex index));
    GenTree* optConstantAssertionProp(AssertionDsc*        curAssertion,
                                      GenTreeLclVarCommon* tree,
                                      Statement* stmt DEBUGARG(AssertionIndex index));
    bool optIsProfitableToSubstitute(GenTreeLclVarCommon* lcl, BasicBlock* lclBlock, GenTree* value);
    bool optZeroObjAssertionProp(GenTree* tree, ASSERT_VALARG_TP assertions);

    // Assertion propagation functions.
    GenTree* optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt, BasicBlock* block);
    GenTree* optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt);
    GenTree* optAssertionProp_LclFld(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt);
    GenTree* optAssertionProp_Asg(ASSERT_VALARG_TP assertions, GenTreeOp* asg, Statement* stmt);
    GenTree* optAssertionProp_Return(ASSERT_VALARG_TP assertions, GenTreeUnOp* ret, Statement* stmt);
    GenTree* optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTreeCast* cast, Statement* stmt);
    GenTree* optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, Statement* stmt);
    GenTree* optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionProp_ConditionalOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt);
    GenTree* optAssertionProp_Update(GenTree* newTree, GenTree* tree, Statement* stmt);
    GenTree* optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call);

    // Implied assertion functions.
    void optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions);
    void optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions);
    void optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result);
    void optImpliedByConstAssertion(AssertionDsc* curAssertion, ASSERT_TP& result);

#ifdef DEBUG
    void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
    void optPrintAssertionIndex(AssertionIndex index);
    void optPrintAssertionIndices(ASSERT_TP assertions);
    void optDebugCheckAssertion(AssertionDsc* assertion);
    void optDebugCheckAssertions(AssertionIndex AssertionIndex);
#endif

    static void optDumpAssertionIndices(const char* header, ASSERT_TP assertions, const char* footer = nullptr);
    static void optDumpAssertionIndices(ASSERT_TP assertions, const char* footer = nullptr);

    PhaseStatus optAddCopies();

    /**************************************************************************
     *                          Range checks
     *************************************************************************/

public:
    struct LoopCloneVisitorInfo
    {
        LoopCloneContext* context;
        Statement*        stmt;
        const unsigned    loopNum;
        const bool        cloneForArrayBounds;
        const bool        cloneForGDVTests;
        LoopCloneVisitorInfo(LoopCloneContext* context,
                             unsigned          loopNum,
                             Statement*        stmt,
                             bool              cloneForArrayBounds,
                             bool              cloneForGDVTests)
            : context(context)
            , stmt(nullptr)
            , loopNum(loopNum)
            , cloneForArrayBounds(cloneForArrayBounds)
            , cloneForGDVTests(cloneForGDVTests)
        {
        }
    };

    bool optIsStackLocalInvariant(unsigned loopNum, unsigned lclNum);
    bool optExtractArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum, bool* topLevelIsFinal);
    bool optReconstructArrIndexHelp(GenTree* tree, ArrIndex* result, unsigned lhsNum, bool* topLevelIsFinal);
    bool optReconstructArrIndex(GenTree* tree, ArrIndex* result);
    bool optIdentifyLoopOptInfo(unsigned loopNum, LoopCloneContext* context);
    static fgWalkPreFn optCanOptimizeByLoopCloningVisitor;
    fgWalkResult optCanOptimizeByLoopCloning(GenTree* tree, LoopCloneVisitorInfo* info);
    bool optObtainLoopCloningOpts(LoopCloneContext* context);
    bool optIsLoopClonable(unsigned loopInd);
    bool optCheckLoopCloningGDVTestProfitable(GenTreeOp* guard, LoopCloneVisitorInfo* info);
    bool optIsHandleOrIndirOfHandle(GenTree* tree, GenTreeFlags handleType);

    bool optLoopCloningEnabled();

#ifdef DEBUG
    void optDebugLogLoopCloning(BasicBlock* block, Statement* insertBefore);
#endif
    void optPerformStaticOptimizations(unsigned loopNum, LoopCloneContext* context DEBUGARG(bool fastPath));
    bool optComputeDerefConditions(unsigned loopNum, LoopCloneContext* context);
    bool optDeriveLoopCloningConditions(unsigned loopNum, LoopCloneContext* context);
    BasicBlock* optInsertLoopChoiceConditions(LoopCloneContext* context,
                                              unsigned          loopNum,
                                              BasicBlock*       slowHead,
                                              BasicBlock*       insertAfter);

protected:
    ssize_t optGetArrayRefScaleAndIndex(GenTree* mul, GenTree** pIndex DEBUGARG(bool bRngChk));

    bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           RegAlloc                                        XX
    XX                                                                           XX
    XX  Does the register allocation and puts the remaining lclVars on the stack XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);

    void raMarkStkVars();

#if FEATURE_PARTIAL_SIMD_CALLEE_SAVE
#if defined(TARGET_AMD64)
    static bool varTypeNeedsPartialCalleeSave(var_types type)
    {
        assert(type != TYP_STRUCT);
        return (type == TYP_SIMD32);
    }
#elif defined(TARGET_ARM64)
    static bool varTypeNeedsPartialCalleeSave(var_types type)
    {
        assert(type != TYP_STRUCT);
        // ARM64 ABI FP Callee save registers only require Callee to save lower 8 Bytes
        // For SIMD types longer than 8 bytes Caller is responsible for saving and restoring Upper bytes.
        return ((type == TYP_SIMD16) || (type == TYP_SIMD12));
    }
#else // !defined(TARGET_AMD64) && !defined(TARGET_ARM64)
#error("Unknown target architecture for FEATURE_SIMD")
#endif // !defined(TARGET_AMD64) && !defined(TARGET_ARM64)
#endif // FEATURE_PARTIAL_SIMD_CALLEE_SAVE

protected:
    // Some things are used by both LSRA and regpredict allocators.

    FrameType rpFrameType;
    bool      rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once

    bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));

private:
    Lowering*            m_pLowering;   // Lowering; needed to Lower IR that's added or modified after Lowering.
    LinearScanInterface* m_pLinearScan; // Linear Scan allocator

    /* raIsVarargsStackArg is called by raMaskStkVars and by
       lvaComputeRefCounts.  It identifies the special case
       where a varargs function has a parameter passed on the
       stack, other than the special varargs handle.  Such parameters
       require special treatment, because they cannot be tracked
       by the GC (their offsets in the stack are not known
       at compile time).
    */

    bool raIsVarargsStackArg(unsigned lclNum)
    {
#ifdef TARGET_X86

        LclVarDsc* varDsc = lvaGetDesc(lclNum);

        assert(varDsc->lvIsParam);

        return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));

#else // TARGET_X86

        return false;

#endif // TARGET_X86
    }

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           EEInterface                                     XX
    XX                                                                           XX
    XX   Get to the class and method info from the Execution Engine given        XX
    XX   tokens for the class and method                                         XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    // Get handles

    void eeGetCallInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                       CORINFO_RESOLVED_TOKEN* pConstrainedToken,
                       CORINFO_CALLINFO_FLAGS  flags,
                       CORINFO_CALL_INFO*      pResult);

    void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
                        CORINFO_ACCESS_FLAGS    flags,
                        CORINFO_FIELD_INFO*     pResult);

    // Get the flags

    bool eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
    bool eeIsIntrinsic(CORINFO_METHOD_HANDLE ftn);
    bool eeIsFieldStatic(CORINFO_FIELD_HANDLE fldHnd);

    var_types eeGetFieldType(CORINFO_FIELD_HANDLE fldHnd, CORINFO_CLASS_HANDLE* pStructHnd = nullptr);

    void eePrintJitType(class StringPrinter* printer, var_types jitType);
    void eePrintType(class StringPrinter* printer,
                     CORINFO_CLASS_HANDLE clsHnd,
                     bool                 includeNamespaces,
                     bool                 includeInstantiation);
    void eePrintTypeOrJitAlias(class StringPrinter* printer,
                               CORINFO_CLASS_HANDLE clsHnd,
                               bool                 includeNamespaces,
                               bool                 includeInstantiation);
    void eePrintMethod(class StringPrinter*  printer,
                       CORINFO_CLASS_HANDLE  clsHnd,
                       CORINFO_METHOD_HANDLE methodHnd,
                       CORINFO_SIG_INFO*     sig,
                       bool                  includeNamespaces,
                       bool                  includeClassInstantiation,
                       bool                  includeMethodInstantiation,
                       bool                  includeSignature,
                       bool                  includeReturnType,
                       bool                  includeThisSpecifier);

#if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) || defined(TRACK_LSRA_STATS)
    const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
    const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd,
                                    bool                  includeReturnType    = true,
                                    bool                  includeThisSpecifier = true);
    unsigned compMethodHash(CORINFO_METHOD_HANDLE methodHandle);

    bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
    CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
#endif

    var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
    var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig, bool* isPinned);
    CORINFO_CLASS_HANDLE eeGetArgClass(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE list);
    CORINFO_CLASS_HANDLE eeGetClassFromContext(CORINFO_CONTEXT_HANDLE context);
    unsigned eeGetArgSize(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
    static unsigned eeGetArgSizeAlignment(var_types type, bool isFloatHfa);

    // VOM info, method sigs

    void eeGetSig(unsigned               sigTok,
                  CORINFO_MODULE_HANDLE  scope,
                  CORINFO_CONTEXT_HANDLE context,
                  CORINFO_SIG_INFO*      retSig);

    void eeGetCallSiteSig(unsigned               sigTok,
                          CORINFO_MODULE_HANDLE  scope,
                          CORINFO_CONTEXT_HANDLE context,
                          CORINFO_SIG_INFO*      retSig);

    void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);

    // Method entry-points, instrs

    CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);

    CORINFO_EE_INFO eeInfo;
    bool            eeInfoInitialized;

    CORINFO_EE_INFO* eeGetEEInfo();

    // Gets the offset of a SDArray's first element
    static unsigned eeGetArrayDataOffset();

    // Get the offset of a MDArray's first element
    static unsigned eeGetMDArrayDataOffset(unsigned rank);

    // Get the offset of a MDArray's dimension length for a given dimension.
    static unsigned eeGetMDArrayLengthOffset(unsigned rank, unsigned dimension);

    // Get the offset of a MDArray's lower bound for a given dimension.
    static unsigned eeGetMDArrayLowerBoundOffset(unsigned rank, unsigned dimension);

    GenTree* eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);

    // Returns the page size for the target machine as reported by the EE.
    target_size_t eeGetPageSize()
    {
        return (target_size_t)eeGetEEInfo()->osPageSize;
    }

    //------------------------------------------------------------------------
    // VirtualStubParam: virtual stub dispatch extra parameter (slot address).
    //
    // It represents Abi and target specific registers for the parameter.
    //
    class VirtualStubParamInfo
    {
    public:
        VirtualStubParamInfo(bool isNativeAOT)
        {
#if defined(TARGET_X86)
            reg     = REG_EAX;
            regMask = RBM_EAX;
#elif defined(TARGET_AMD64)
            if (isNativeAOT)
            {
                reg     = REG_R10;
                regMask = RBM_R10;
            }
            else
            {
                reg     = REG_R11;
                regMask = RBM_R11;
            }
#elif defined(TARGET_ARM)
            if (isNativeAOT)
            {
                reg     = REG_R12;
                regMask = RBM_R12;
            }
            else
            {
                reg     = REG_R4;
                regMask = RBM_R4;
            }
#elif defined(TARGET_ARM64)
            reg     = REG_R11;
            regMask = RBM_R11;
#elif defined(TARGET_LOONGARCH64)
            reg     = REG_T8;
            regMask = RBM_T8;
#else
#error Unsupported or unset target architecture
#endif
        }

        regNumber GetReg() const
        {
            return reg;
        }

        _regMask_enum GetRegMask() const
        {
            return regMask;
        }

    private:
        regNumber     reg;
        _regMask_enum regMask;
    };

    VirtualStubParamInfo* virtualStubParamInfo;

    bool IsTargetAbi(CORINFO_RUNTIME_ABI abi)
    {
        return eeGetEEInfo()->targetAbi == abi;
    }

    bool generateCFIUnwindCodes()
    {
#if defined(FEATURE_CFI_SUPPORT)
        return TargetOS::IsUnix && IsTargetAbi(CORINFO_NATIVEAOT_ABI);
#else
        return false;
#endif
    }

    // Debugging support - Line number info

    void eeGetStmtOffsets();

    unsigned eeBoundariesCount;

    ICorDebugInfo::OffsetMapping* eeBoundaries; // Boundaries to report to the EE
    void eeSetLIcount(unsigned count);
    void eeSetLIinfo(unsigned which, UNATIVE_OFFSET offs, IPmappingDscKind kind, const ILLocation& loc);
    void eeSetLIdone();

#ifdef DEBUG
    static void eeDispILOffs(IL_OFFSET offs);
    static void eeDispSourceMappingOffs(uint32_t offs);
    static void eeDispLineInfo(const ICorDebugInfo::OffsetMapping* line);
    void eeDispLineInfos();
#endif // DEBUG

    // Debugging support - Local var info

    void eeGetVars();

    unsigned eeVarsCount;

    struct VarResultInfo
    {
        UNATIVE_OFFSET             startOffset;
        UNATIVE_OFFSET             endOffset;
        DWORD                      varNumber;
        CodeGenInterface::siVarLoc loc;
    } * eeVars;
    void eeSetLVcount(unsigned count);
    void eeSetLVinfo(unsigned                          which,
                     UNATIVE_OFFSET                    startOffs,
                     UNATIVE_OFFSET                    length,
                     unsigned                          varNum,
                     const CodeGenInterface::siVarLoc& loc);
    void eeSetLVdone();

#ifdef DEBUG
    void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
    void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
#endif // DEBUG

    // ICorJitInfo wrappers

    void eeAllocMem(AllocMemArgs* args, const UNATIVE_OFFSET roDataSectionAlignment);

    void eeReserveUnwindInfo(bool isFunclet, bool isColdCode, ULONG unwindSize);

    void eeAllocUnwindInfo(BYTE*          pHotCode,
                           BYTE*          pColdCode,
                           ULONG          startOffset,
                           ULONG          endOffset,
                           ULONG          unwindSize,
                           BYTE*          pUnwindBlock,
                           CorJitFuncKind funcKind);

    void eeSetEHcount(unsigned cEH);

    void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);

    WORD eeGetRelocTypeHint(void* target);

    // ICorStaticInfo wrapper functions

    bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);

#if defined(UNIX_AMD64_ABI)
#ifdef DEBUG
    static void dumpSystemVClassificationType(SystemVClassificationType ct);
#endif // DEBUG

    void eeGetSystemVAmd64PassStructInRegisterDescriptor(
        /*IN*/ CORINFO_CLASS_HANDLE                                  structHnd,
        /*OUT*/ SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
#endif // UNIX_AMD64_ABI

    template <typename ParamType>
    bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
    {
        return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
    }

    bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);

    template <typename ParamType>
    bool eeRunWithSPMIErrorTrap(void (*function)(ParamType*), ParamType* param)
    {
        return eeRunWithSPMIErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
    }

    template <typename Functor>
    bool eeRunFunctorWithSPMIErrorTrap(Functor f)
    {
        return eeRunWithSPMIErrorTrap<Functor>([](Functor* pf) { (*pf)(); }, &f);
    }

    bool eeRunWithSPMIErrorTrapImp(void (*function)(void*), void* param);

    // Utility functions

    const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);

#if defined(DEBUG)
    void eePrintObjectDescription(const char* prefix, CORINFO_OBJECT_HANDLE handle);
    unsigned eeTryGetClassSize(CORINFO_CLASS_HANDLE clsHnd);
    const char16_t* eeGetShortClassName(CORINFO_CLASS_HANDLE clsHnd);
#endif

    const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);

    static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
    static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);

    static bool IsSharedStaticHelper(GenTree* tree);
    static bool IsGcSafePoint(GenTreeCall* call);

    static CORINFO_FIELD_HANDLE eeFindJitDataOffs(unsigned jitDataOffs);
    // returns true/false if 'field' is a Jit Data offset
    static bool eeIsJitDataOffs(CORINFO_FIELD_HANDLE field);
    // returns a number < 0 if 'field' is not a Jit Data offset, otherwise the data offset (limited to 2GB)
    static int eeGetJitDataOffs(CORINFO_FIELD_HANDLE field);

    /*****************************************************************************/

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           CodeGenerator                                   XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    CodeGenInterface* codeGen;

    // Record the instr offset mapping to the generated code

    jitstd::list<IPmappingDsc>  genIPmappings;
    jitstd::list<RichIPMapping> genRichIPmappings;

    // Managed RetVal - A side hash table meant to record the mapping from a
    // GT_CALL node to its debug info.  This info is used to emit sequence points
    // that can be used by debugger to determine the native offset at which the
    // managed RetVal will be available.
    //
    // In fact we can store debug info in a GT_CALL node.  This was ruled out in
    // favor of a side table for two reasons: 1) We need debug info for only those
    // GT_CALL nodes (created during importation) that correspond to an IL call and
    // whose return type is other than TYP_VOID. 2) GT_CALL node is a frequently used
    // structure and IL offset is needed only when generating debuggable code. Therefore
    // it is desirable to avoid memory size penalty in retail scenarios.
    typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, DebugInfo> CallSiteDebugInfoTable;
    CallSiteDebugInfoTable* genCallSite2DebugInfoMap;

    unsigned    genReturnLocal; // Local number for the return value when applicable.
    BasicBlock* genReturnBB;    // jumped to when not optimizing for speed.

    // The following properties are part of CodeGenContext.  Getters are provided here for
    // convenience and backward compatibility, but the properties can only be set by invoking
    // the setter on CodeGenContext directly.

    emitter* GetEmitter() const
    {
        return codeGen->GetEmitter();
    }

    bool isFramePointerUsed() const
    {
        return codeGen->isFramePointerUsed();
    }

    bool GetInterruptible()
    {
        return codeGen->GetInterruptible();
    }
    void SetInterruptible(bool value)
    {
        codeGen->SetInterruptible(value);
    }

#if DOUBLE_ALIGN
    const bool genDoubleAlign()
    {
        return codeGen->doDoubleAlign();
    }
    DWORD getCanDoubleAlign();
    bool shouldDoubleAlign(unsigned refCntStk,
                           unsigned refCntReg,
                           weight_t refCntWtdReg,
                           unsigned refCntStkParam,
                           weight_t refCntWtdStkDbl);
#endif // DOUBLE_ALIGN

    bool IsFullPtrRegMapRequired()
    {
        return codeGen->IsFullPtrRegMapRequired();
    }
    void SetFullPtrRegMapRequired(bool value)
    {
        codeGen->SetFullPtrRegMapRequired(value);
    }

// Things that MAY belong either in CodeGen or CodeGenContext

#if defined(FEATURE_EH_FUNCLETS)
    FuncInfoDsc*   compFuncInfos;
    unsigned short compCurrFuncIdx;
    unsigned short compFuncInfoCount;

    unsigned short compFuncCount()
    {
        assert(fgFuncletsCreated);
        return compFuncInfoCount;
    }

#else // !FEATURE_EH_FUNCLETS

    // This is a no-op when there are no funclets!
    void genUpdateCurrentFunclet(BasicBlock* block)
    {
        return;
    }

    FuncInfoDsc compFuncInfoRoot;

    static const unsigned compCurrFuncIdx = 0;

    unsigned short compFuncCount()
    {
        return 1;
    }

#endif // !FEATURE_EH_FUNCLETS

    FuncInfoDsc* funCurrentFunc();
    void funSetCurrentFunc(unsigned funcIdx);
    FuncInfoDsc* funGetFunc(unsigned funcIdx);
    unsigned int funGetFuncIdx(BasicBlock* block);

    // LIVENESS

    VARSET_TP compCurLife;     // current live variables
    GenTree*  compCurLifeTree; // node after which compCurLife has been computed

    // Compare the given "newLife" with last set of live variables and update
    // codeGen "gcInfo", siScopes, "regSet" with the new variable's homes/liveness.
    template <bool ForCodeGen>
    void compChangeLife(VARSET_VALARG_TP newLife);

    // Update the GC's masks, register's masks and reports change on variable's homes given a set of
    // current live variables if changes have happened since "compCurLife".
    template <bool ForCodeGen>
    inline void compUpdateLife(VARSET_VALARG_TP newLife);

    // Gets a register mask that represent the kill set for a helper call since
    // not all JIT Helper calls follow the standard ABI on the target architecture.
    regMaskTP compHelperCallKillSet(CorInfoHelpFunc helper);

    // If "tree" is a indirection (GT_IND, or GT_OBJ) whose arg is an ADDR, whose arg is a LCL_VAR, return that LCL_VAR
    // node, else NULL.
    static GenTreeLclVar* fgIsIndirOfAddrOfLocal(GenTree* tree);

    // This map is indexed by GT_OBJ nodes that are address of promoted struct variables, which
    // have been annotated with the GTF_VAR_DEATH flag.  If such a node is *not* mapped in this
    // table, one may assume that all the (tracked) field vars die at this GT_OBJ.  Otherwise,
    // the node maps to a pointer to a VARSET_TP, containing set bits for each of the tracked field
    // vars of the promoted struct local that go dead at the given node (the set bits are the bits
    // for the tracked var indices of the field vars, as in a live var set).
    //
    // The map is allocated on demand so all map operations should use one of the following three
    // wrapper methods.

    NodeToVarsetPtrMap* m_promotedStructDeathVars;

    NodeToVarsetPtrMap* GetPromotedStructDeathVars()
    {
        if (m_promotedStructDeathVars == nullptr)
        {
            m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
        }
        return m_promotedStructDeathVars;
    }

    void ClearPromotedStructDeathVars()
    {
        if (m_promotedStructDeathVars != nullptr)
        {
            m_promotedStructDeathVars->RemoveAll();
        }
    }

    bool LookupPromotedStructDeathVars(GenTree* tree, VARSET_TP** bits)
    {
        *bits       = nullptr;
        bool result = false;

        if (m_promotedStructDeathVars != nullptr)
        {
            result = m_promotedStructDeathVars->Lookup(tree, bits);
        }

        return result;
    }

/*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                           UnwindInfo                                      XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

#if !defined(__GNUC__)
#pragma region Unwind information
#endif

public:
    //
    // Infrastructure functions: start/stop/reserve/emit.
    //

    void unwindBegProlog();
    void unwindEndProlog();
    void unwindBegEpilog();
    void unwindEndEpilog();
    void unwindReserve();
    void unwindEmit(void* pHotCode, void* pColdCode);

    //
    // Specific unwind information functions: called by code generation to indicate a particular
    // prolog or epilog unwindable instruction has been generated.
    //

    void unwindPush(regNumber reg);
    void unwindAllocStack(unsigned size);
    void unwindSetFrameReg(regNumber reg, unsigned offset);
    void unwindSaveReg(regNumber reg, unsigned offset);

#if defined(TARGET_ARM)
    void unwindPushMaskInt(regMaskTP mask);
    void unwindPushMaskFloat(regMaskTP mask);
    void unwindPopMaskInt(regMaskTP mask);
    void unwindPopMaskFloat(regMaskTP mask);
    void unwindBranch16();                    // The epilog terminates with a 16-bit branch (e.g., "bx lr")
    void unwindNop(unsigned codeSizeInBytes); // Generate unwind NOP code. 'codeSizeInBytes' is 2 or 4 bytes. Only
                                              // called via unwindPadding().
    void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
                          // instruction and the current location.
#endif                    // TARGET_ARM

#if defined(TARGET_ARM64)
    void unwindNop();
    void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
                          // instruction and the current location.
    void unwindSaveReg(regNumber reg, int offset);                                // str reg, [sp, #offset]
    void unwindSaveRegPreindexed(regNumber reg, int offset);                      // str reg, [sp, #offset]!
    void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset);           // stp reg1, reg2, [sp, #offset]
    void unwindSaveRegPairPreindexed(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]!
    void unwindSaveNext();                                                        // unwind code: save_next
    void unwindReturn(regNumber reg);                                             // ret lr
#endif                                                                            // defined(TARGET_ARM64)

#if defined(TARGET_LOONGARCH64)
    void unwindNop();
    void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
                          // instruction and the current location.
    void unwindSaveReg(regNumber reg, int offset);
    void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset);
    void unwindReturn(regNumber reg);
#endif // defined(TARGET_LOONGARCH64)

    //
    // Private "helper" functions for the unwind implementation.
    //

private:
#if defined(FEATURE_EH_FUNCLETS)
    void unwindGetFuncLocations(FuncInfoDsc*             func,
                                bool                     getHotSectionData,
                                /* OUT */ emitLocation** ppStartLoc,
                                /* OUT */ emitLocation** ppEndLoc);
#endif // FEATURE_EH_FUNCLETS

    void unwindReserveFunc(FuncInfoDsc* func);
    void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);

#if defined(TARGET_AMD64) || (defined(TARGET_X86) && defined(FEATURE_EH_FUNCLETS))

    void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
    void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);

#endif // TARGET_AMD64 || (TARGET_X86 && FEATURE_EH_FUNCLETS)

    UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);

#if defined(TARGET_AMD64)

    void unwindBegPrologWindows();
    void unwindPushWindows(regNumber reg);
    void unwindAllocStackWindows(unsigned size);
    void unwindSetFrameRegWindows(regNumber reg, unsigned offset);
    void unwindSaveRegWindows(regNumber reg, unsigned offset);

#ifdef UNIX_AMD64_ABI
    void unwindSaveRegCFI(regNumber reg, unsigned offset);
#endif // UNIX_AMD64_ABI
#elif defined(TARGET_ARM)

    void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
    void unwindPushPopMaskFloat(regMaskTP mask);

#endif // TARGET_ARM

#if defined(FEATURE_CFI_SUPPORT)
    short mapRegNumToDwarfReg(regNumber reg);
    void createCfiCode(FuncInfoDsc* func, UNATIVE_OFFSET codeOffset, UCHAR opcode, short dwarfReg, INT offset = 0);
    void unwindPushPopCFI(regNumber reg);
    void unwindBegPrologCFI();
    void unwindPushPopMaskCFI(regMaskTP regMask, bool isFloat);
    void unwindAllocStackCFI(unsigned size);
    void unwindSetFrameRegCFI(regNumber reg, unsigned offset);
    void unwindEmitFuncCFI(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
#ifdef DEBUG
    void DumpCfiInfo(bool                  isHotCode,
                     UNATIVE_OFFSET        startOffset,
                     UNATIVE_OFFSET        endOffset,
                     DWORD                 cfiCodeBytes,
                     const CFI_CODE* const pCfiCode);
#endif

#endif // FEATURE_CFI_SUPPORT

#if !defined(__GNUC__)
#pragma endregion // Note: region is NOT under !defined(__GNUC__)
#endif

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                               SIMD                                        XX
    XX                                                                           XX
    XX   Info about SIMD types, methods and the SIMD assembly (i.e. the assembly XX
    XX   that contains the distinguished, well-known SIMD type definitions).     XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

    bool IsBaselineSimdIsaSupported()
    {
#ifdef FEATURE_SIMD
#if defined(TARGET_XARCH)
        CORINFO_InstructionSet minimumIsa = InstructionSet_SSE2;
#elif defined(TARGET_ARM64)
        CORINFO_InstructionSet minimumIsa = InstructionSet_AdvSimd;
#elif defined(TARGET_LOONGARCH64)
        // TODO: supporting SIMD feature for LoongArch64.
        assert(!"unimplemented yet on LA");
        CORINFO_InstructionSet minimumIsa = 0;
#else
#error Unsupported platform
#endif // !TARGET_XARCH && !TARGET_ARM64 && !TARGET_LOONGARCH64

        return compOpportunisticallyDependsOn(minimumIsa);
#else
        return false;
#endif
    }

#if defined(DEBUG)
    bool IsBaselineSimdIsaSupportedDebugOnly()
    {
#ifdef FEATURE_SIMD
#if defined(TARGET_XARCH)
        CORINFO_InstructionSet minimumIsa = InstructionSet_SSE2;
#elif defined(TARGET_ARM64)
        CORINFO_InstructionSet minimumIsa = InstructionSet_AdvSimd;
#else
#error Unsupported platform
#endif // !TARGET_XARCH && !TARGET_ARM64

        return compIsaSupportedDebugOnly(minimumIsa);
#else
        return false;
#endif // FEATURE_SIMD
    }
#endif // DEBUG

    // Get highest available level for SIMD codegen
    SIMDLevel getSIMDSupportLevel()
    {
#if defined(TARGET_XARCH)
        if (compOpportunisticallyDependsOn(InstructionSet_AVX2))
        {
            return SIMD_AVX2_Supported;
        }

        if (compOpportunisticallyDependsOn(InstructionSet_SSE42))
        {
            return SIMD_SSE4_Supported;
        }

        // min bar is SSE2
        return SIMD_SSE2_Supported;
#else
        assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
        unreached();
        return SIMD_Not_Supported;
#endif
    }

    bool isIntrinsicType(CORINFO_CLASS_HANDLE clsHnd)
    {
        return info.compCompHnd->isIntrinsicType(clsHnd);
    }

    const char* getClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, const char** namespaceName)
    {
        return info.compCompHnd->getClassNameFromMetadata(cls, namespaceName);
    }

    CORINFO_CLASS_HANDLE getTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index)
    {
        return info.compCompHnd->getTypeInstantiationArgument(cls, index);
    }

#ifdef FEATURE_SIMD
    // Have we identified any SIMD types?
    // This is currently used by struct promotion to avoid getting type information for a struct
    // field to see if it is a SIMD type, if we haven't seen any SIMD types or operations in
    // the method.
    bool _usesSIMDTypes;
    bool usesSIMDTypes()
    {
        return _usesSIMDTypes;
    }
    void setUsesSIMDTypes(bool value)
    {
        _usesSIMDTypes = value;
    }

    // This is a temp lclVar allocated on the stack as TYP_SIMD.  It is used to implement intrinsics
    // that require indexed access to the individual fields of the vector, which is not well supported
    // by the hardware.  It is allocated when/if such situations are encountered during Lowering.
    unsigned lvaSIMDInitTempVarNum;

    struct SIMDHandlesCache
    {
        // SIMD Types
        CORINFO_CLASS_HANDLE SIMDFloatHandle;
        CORINFO_CLASS_HANDLE SIMDDoubleHandle;
        CORINFO_CLASS_HANDLE SIMDIntHandle;
        CORINFO_CLASS_HANDLE SIMDUShortHandle;
        CORINFO_CLASS_HANDLE SIMDUByteHandle;
        CORINFO_CLASS_HANDLE SIMDShortHandle;
        CORINFO_CLASS_HANDLE SIMDByteHandle;
        CORINFO_CLASS_HANDLE SIMDLongHandle;
        CORINFO_CLASS_HANDLE SIMDUIntHandle;
        CORINFO_CLASS_HANDLE SIMDULongHandle;
        CORINFO_CLASS_HANDLE SIMDNIntHandle;
        CORINFO_CLASS_HANDLE SIMDNUIntHandle;

        CORINFO_CLASS_HANDLE SIMDVector2Handle;
        CORINFO_CLASS_HANDLE SIMDVector3Handle;
        CORINFO_CLASS_HANDLE SIMDVector4Handle;
        CORINFO_CLASS_HANDLE SIMDVectorHandle;

#ifdef FEATURE_HW_INTRINSICS
#if defined(TARGET_ARM64)
        CORINFO_CLASS_HANDLE Vector64FloatHandle;
        CORINFO_CLASS_HANDLE Vector64DoubleHandle;
        CORINFO_CLASS_HANDLE Vector64IntHandle;
        CORINFO_CLASS_HANDLE Vector64UShortHandle;
        CORINFO_CLASS_HANDLE Vector64UByteHandle;
        CORINFO_CLASS_HANDLE Vector64ShortHandle;
        CORINFO_CLASS_HANDLE Vector64ByteHandle;
        CORINFO_CLASS_HANDLE Vector64LongHandle;
        CORINFO_CLASS_HANDLE Vector64UIntHandle;
        CORINFO_CLASS_HANDLE Vector64ULongHandle;
        CORINFO_CLASS_HANDLE Vector64NIntHandle;
        CORINFO_CLASS_HANDLE Vector64NUIntHandle;
#endif // defined(TARGET_ARM64)
        CORINFO_CLASS_HANDLE Vector128FloatHandle;
        CORINFO_CLASS_HANDLE Vector128DoubleHandle;
        CORINFO_CLASS_HANDLE Vector128IntHandle;
        CORINFO_CLASS_HANDLE Vector128UShortHandle;
        CORINFO_CLASS_HANDLE Vector128UByteHandle;
        CORINFO_CLASS_HANDLE Vector128ShortHandle;
        CORINFO_CLASS_HANDLE Vector128ByteHandle;
        CORINFO_CLASS_HANDLE Vector128LongHandle;
        CORINFO_CLASS_HANDLE Vector128UIntHandle;
        CORINFO_CLASS_HANDLE Vector128ULongHandle;
        CORINFO_CLASS_HANDLE Vector128NIntHandle;
        CORINFO_CLASS_HANDLE Vector128NUIntHandle;
#if defined(TARGET_XARCH)
        CORINFO_CLASS_HANDLE Vector256FloatHandle;
        CORINFO_CLASS_HANDLE Vector256DoubleHandle;
        CORINFO_CLASS_HANDLE Vector256IntHandle;
        CORINFO_CLASS_HANDLE Vector256UShortHandle;
        CORINFO_CLASS_HANDLE Vector256UByteHandle;
        CORINFO_CLASS_HANDLE Vector256ShortHandle;
        CORINFO_CLASS_HANDLE Vector256ByteHandle;
        CORINFO_CLASS_HANDLE Vector256LongHandle;
        CORINFO_CLASS_HANDLE Vector256UIntHandle;
        CORINFO_CLASS_HANDLE Vector256ULongHandle;
        CORINFO_CLASS_HANDLE Vector256NIntHandle;
        CORINFO_CLASS_HANDLE Vector256NUIntHandle;
#endif // defined(TARGET_XARCH)
#endif // FEATURE_HW_INTRINSICS

        CORINFO_CLASS_HANDLE CanonicalSimd8Handle;
        CORINFO_CLASS_HANDLE CanonicalSimd16Handle;
        CORINFO_CLASS_HANDLE CanonicalSimd32Handle;

        SIMDHandlesCache()
        {
            memset(this, 0, sizeof(*this));
        }
    };

    SIMDHandlesCache* m_simdHandleCache;

    // Get the handle for a SIMD type.
    CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, CorInfoType simdBaseJitType)
    {
        if (m_simdHandleCache == nullptr)
        {
            // This may happen if the JIT generates SIMD node on its own, without importing them.
            // Otherwise getBaseJitTypeAndSizeOfSIMDType should have created the cache.
            return NO_CLASS_HANDLE;
        }

        if (simdBaseJitType == CORINFO_TYPE_FLOAT)
        {
            switch (simdType)
            {
                case TYP_SIMD8:
                    return m_simdHandleCache->SIMDVector2Handle;
                case TYP_SIMD12:
                    return m_simdHandleCache->SIMDVector3Handle;
                case TYP_SIMD16:
                    if ((getSIMDVectorType() == TYP_SIMD32) ||
                        (m_simdHandleCache->SIMDVector4Handle != NO_CLASS_HANDLE))
                    {
                        return m_simdHandleCache->SIMDVector4Handle;
                    }
                    break;
                case TYP_SIMD32:
                    break;
                default:
                    unreached();
            }
        }
        assert(emitTypeSize(simdType) <= largestEnregisterableStructSize());
        switch (simdBaseJitType)
        {
            case CORINFO_TYPE_FLOAT:
                return m_simdHandleCache->SIMDFloatHandle;
            case CORINFO_TYPE_DOUBLE:
                return m_simdHandleCache->SIMDDoubleHandle;
            case CORINFO_TYPE_INT:
                return m_simdHandleCache->SIMDIntHandle;
            case CORINFO_TYPE_USHORT:
                return m_simdHandleCache->SIMDUShortHandle;
            case CORINFO_TYPE_UBYTE:
                return m_simdHandleCache->SIMDUByteHandle;
            case CORINFO_TYPE_SHORT:
                return m_simdHandleCache->SIMDShortHandle;
            case CORINFO_TYPE_BYTE:
                return m_simdHandleCache->SIMDByteHandle;
            case CORINFO_TYPE_LONG:
                return m_simdHandleCache->SIMDLongHandle;
            case CORINFO_TYPE_UINT:
                return m_simdHandleCache->SIMDUIntHandle;
            case CORINFO_TYPE_ULONG:
                return m_simdHandleCache->SIMDULongHandle;
            case CORINFO_TYPE_NATIVEINT:
                return m_simdHandleCache->SIMDNIntHandle;
            case CORINFO_TYPE_NATIVEUINT:
                return m_simdHandleCache->SIMDNUIntHandle;
            default:
                assert(!"Didn't find a class handle for simdType");
        }
        return NO_CLASS_HANDLE;
    }

#if defined(FEATURE_HW_INTRINSICS)
    CORINFO_CLASS_HANDLE gtGetStructHandleForSimdOrHW(var_types   simdType,
                                                      CorInfoType simdBaseJitType,
                                                      bool        isSimdAsHWIntrinsic = false)
    {
        CORINFO_CLASS_HANDLE clsHnd = NO_CLASS_HANDLE;

        if (isSimdAsHWIntrinsic)
        {
            clsHnd = gtGetStructHandleForSIMD(simdType, simdBaseJitType);
        }
        else
        {
            clsHnd = gtGetStructHandleForHWSIMD(simdType, simdBaseJitType);
        }

        return clsHnd;
    }
#endif // FEATURE_HW_INTRINSICS

    //------------------------------------------------------------------------
    // gtGetCanonicalStructHandleForSIMD: Get the "canonical" SIMD type handle.
    //
    // Some SIMD-typed trees do not carry struct handles with them (and in
    // some cases, they cannot, due to being created by the compiler itself).
    // To enable CSEing of these trees, we use "canonical" handles. These are
    // captured during importation, and can represent any type normalized to
    // be TYP_SIMD.
    //
    // Arguments:
    //    simdType - The SIMD type
    //
    // Return Value:
    //    The "canonical" type handle for "simdType", if one was available.
    //    "NO_CLASS_HANDLE" otherwise.
    //
    CORINFO_CLASS_HANDLE gtGetCanonicalStructHandleForSIMD(var_types simdType)
    {
        if (m_simdHandleCache == nullptr)
        {
            return NO_CLASS_HANDLE;
        }

        switch (simdType)
        {
            case TYP_SIMD8:
                return m_simdHandleCache->CanonicalSimd8Handle;
            case TYP_SIMD12:
                return m_simdHandleCache->SIMDVector3Handle;
            case TYP_SIMD16:
                return m_simdHandleCache->CanonicalSimd16Handle;
            case TYP_SIMD32:
                return m_simdHandleCache->CanonicalSimd32Handle;
            default:
                unreached();
        }
    }

    // Returns true if this is a SIMD type that should be considered an opaque
    // vector type (i.e. do not analyze or promote its fields).
    // Note that all but the fixed vector types are opaque, even though they may
    // actually be declared as having fields.
    bool isOpaqueSIMDType(CORINFO_CLASS_HANDLE structHandle) const
    {
        return ((m_simdHandleCache != nullptr) && (structHandle != m_simdHandleCache->SIMDVector2Handle) &&
                (structHandle != m_simdHandleCache->SIMDVector3Handle) &&
                (structHandle != m_simdHandleCache->SIMDVector4Handle));
    }

    // Returns true if the tree corresponds to a TYP_SIMD lcl var.
    // Note that both SIMD vector args and locals are mared as lvSIMDType = true, but
    // type of an arg node is TYP_BYREF and a local node is TYP_SIMD or TYP_STRUCT.
    bool isSIMDTypeLocal(GenTree* tree)
    {
        return tree->OperIsLocal() && lvaGetDesc(tree->AsLclVarCommon())->lvSIMDType;
    }

    // Returns true if the lclVar is an opaque SIMD type.
    bool isOpaqueSIMDLclVar(const LclVarDsc* varDsc) const
    {
        if (!varDsc->lvSIMDType)
        {
            return false;
        }
        return isOpaqueSIMDType(varDsc->GetStructHnd());
    }

    static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
    {
        return (intrinsicId == SIMDIntrinsicEqual);
    }

    bool isNumericsNamespace(const char* ns)
    {
        return strcmp(ns, "System.Numerics") == 0;
    }

    bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
    {
        if (isIntrinsicType(clsHnd))
        {
            const char* namespaceName = nullptr;
            (void)getClassNameFromMetadata(clsHnd, &namespaceName);
            return isNumericsNamespace(namespaceName);
        }
        return false;
    }

    bool isSIMDClass(typeInfo* pTypeInfo)
    {
        return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
    }

    bool isHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
    {
#ifdef FEATURE_HW_INTRINSICS
        if (isIntrinsicType(clsHnd))
        {
            const char* namespaceName = nullptr;
            (void)getClassNameFromMetadata(clsHnd, &namespaceName);
            return strcmp(namespaceName, "System.Runtime.Intrinsics") == 0;
        }
#endif // FEATURE_HW_INTRINSICS
        return false;
    }

    bool isHWSIMDClass(typeInfo* pTypeInfo)
    {
#ifdef FEATURE_HW_INTRINSICS
        return pTypeInfo->IsStruct() && isHWSIMDClass(pTypeInfo->GetClassHandleForValueClass());
#else
        return false;
#endif
    }

    bool isSIMDorHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
    {
        return isSIMDClass(clsHnd) || isHWSIMDClass(clsHnd);
    }

    bool isSIMDorHWSIMDClass(typeInfo* pTypeInfo)
    {
        return isSIMDClass(pTypeInfo) || isHWSIMDClass(pTypeInfo);
    }

    // Get the base (element) type and size in bytes for a SIMD type. Returns CORINFO_TYPE_UNDEF
    // if it is not a SIMD type or is an unsupported base JIT type.
    CorInfoType getBaseJitTypeAndSizeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd, unsigned* sizeBytes = nullptr);

    CorInfoType getBaseJitTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
    {
        return getBaseJitTypeAndSizeOfSIMDType(typeHnd, nullptr);
    }

    // Get SIMD Intrinsic info given the method handle.
    // Also sets typeHnd, argCount, baseType and sizeBytes out params.
    const SIMDIntrinsicInfo* getSIMDIntrinsicInfo(CORINFO_CLASS_HANDLE* typeHnd,
                                                  CORINFO_METHOD_HANDLE methodHnd,
                                                  CORINFO_SIG_INFO*     sig,
                                                  bool                  isNewObj,
                                                  unsigned*             argCount,
                                                  CorInfoType*          simdBaseJitType,
                                                  unsigned*             sizeBytes);

    // Pops and returns GenTree node from importers type stack.
    // Normalizes TYP_STRUCT value in case of GT_CALL, GT_RET_EXPR and arg nodes.
    GenTree* impSIMDPopStack(var_types type, bool expectAddr = false, CORINFO_CLASS_HANDLE structType = nullptr);

    // Transforms operands and returns the SIMD intrinsic to be applied on
    // transformed operands to obtain given relop result.
    SIMDIntrinsicID impSIMDRelOp(SIMDIntrinsicID      relOpIntrinsicId,
                                 CORINFO_CLASS_HANDLE typeHnd,
                                 unsigned             simdVectorSize,
                                 CorInfoType*         inOutBaseJitType,
                                 GenTree**            op1,
                                 GenTree**            op2);

#if defined(TARGET_XARCH)

    // Transforms operands and returns the SIMD intrinsic to be applied on
    // transformed operands to obtain == comparison result.
    SIMDIntrinsicID impSIMDLongRelOpEqual(CORINFO_CLASS_HANDLE typeHnd,
                                          unsigned             simdVectorSize,
                                          GenTree**            op1,
                                          GenTree**            op2);

#endif // defined(TARGET_XARCH)

    void setLclRelatedToSIMDIntrinsic(GenTree* tree);
    bool areFieldsContiguous(GenTree* op1, GenTree* op2);
    bool areLocalFieldsContiguous(GenTreeLclFld* first, GenTreeLclFld* second);
    bool areArrayElementsContiguous(GenTree* op1, GenTree* op2);
    bool areArgumentsContiguous(GenTree* op1, GenTree* op2);
    GenTree* createAddressNodeForSIMDInit(GenTree* tree, unsigned simdSize);

    // check methodHnd to see if it is a SIMD method that is expanded as an intrinsic in the JIT.
    GenTree* impSIMDIntrinsic(OPCODE                opcode,
                              GenTree*              newobjThis,
                              CORINFO_CLASS_HANDLE  clsHnd,
                              CORINFO_METHOD_HANDLE method,
                              CORINFO_SIG_INFO*     sig,
                              unsigned              methodFlags,
                              int                   memberRef);

    GenTree* getOp1ForConstructor(OPCODE opcode, GenTree* newobjThis, CORINFO_CLASS_HANDLE clsHnd);

    // Whether SIMD vector occupies part of SIMD register.
    // SSE2: vector2f/3f are considered sub register SIMD types.
    // AVX: vector2f, 3f and 4f are all considered sub register SIMD types.
    bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
    {
        unsigned vectorRegisterByteLength;
#if defined(TARGET_XARCH)
        // Calling the getSIMDVectorRegisterByteLength api causes the size of Vector<T> to be recorded
        // with the AOT compiler, so that it cannot change from aot compilation time to runtime
        // This api does not require such fixing as it merely pertains to the size of the simd type
        // relative to the Vector<T> size as used at compile time. (So detecting a vector length of 16 here
        // does not preclude the code from being used on a machine with a larger vector length.)
        if (getSIMDSupportLevel() < SIMD_AVX2_Supported)
        {
            vectorRegisterByteLength = 16;
        }
        else
        {
            vectorRegisterByteLength = 32;
        }
#else
        vectorRegisterByteLength = getSIMDVectorRegisterByteLength();
#endif
        return (simdNode->GetSimdSize() < vectorRegisterByteLength);
    }

    // Get the type for the hardware SIMD vector.
    // This is the maximum SIMD type supported for this target.
    var_types getSIMDVectorType()
    {
#if defined(TARGET_XARCH)
        if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
        {
            return TYP_SIMD32;
        }
        else
        {
            // Verify and record that AVX2 isn't supported
            compVerifyInstructionSetUnusable(InstructionSet_AVX2);
            assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
            return TYP_SIMD16;
        }
#elif defined(TARGET_ARM64)
        return TYP_SIMD16;
#else
        assert(!"getSIMDVectorType() unimplemented on target arch");
        unreached();
#endif
    }

    // Get the size of the SIMD type in bytes
    int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
    {
        unsigned sizeBytes = 0;
        (void)getBaseJitTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
        return sizeBytes;
    }

    // Get the number of elements of baseType of SIMD vector given by its size and baseType
    static int getSIMDVectorLength(unsigned simdSize, var_types baseType);

    // Get the number of elements of baseType of SIMD vector given by its type handle
    int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);

    // Get preferred alignment of SIMD type.
    int getSIMDTypeAlignment(var_types simdType);

    // Get the number of bytes in a System.Numeric.Vector<T> for the current compilation.
    // Note - cannot be used for System.Runtime.Intrinsic
    unsigned getSIMDVectorRegisterByteLength()
    {
#if defined(TARGET_XARCH)
        if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
        {
            return YMM_REGSIZE_BYTES;
        }
        else
        {
            // Verify and record that AVX2 isn't supported
            compVerifyInstructionSetUnusable(InstructionSet_AVX2);
            assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
            return XMM_REGSIZE_BYTES;
        }
#elif defined(TARGET_ARM64)
        return FP_REGSIZE_BYTES;
#else
        assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
        unreached();
#endif
    }

    // The minimum and maximum possible number of bytes in a SIMD vector.

    // maxSIMDStructBytes
    // The minimum SIMD size supported by System.Numeric.Vectors or System.Runtime.Intrinsic
    // SSE:  16-byte Vector<T> and Vector128<T>
    // AVX:  32-byte Vector256<T> (Vector<T> is 16-byte)
    // AVX2: 32-byte Vector<T> and Vector256<T>
    unsigned int maxSIMDStructBytes()
    {
#if defined(FEATURE_HW_INTRINSICS) && defined(TARGET_XARCH)
        if (compOpportunisticallyDependsOn(InstructionSet_AVX))
        {
            return YMM_REGSIZE_BYTES;
        }
        else
        {
            // Verify and record that AVX2 isn't supported
            compVerifyInstructionSetUnusable(InstructionSet_AVX2);
            assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
            return XMM_REGSIZE_BYTES;
        }
#else
        return getSIMDVectorRegisterByteLength();
#endif
    }

    unsigned int minSIMDStructBytes()
    {
        return emitTypeSize(TYP_SIMD8);
    }

public:
    // Returns the codegen type for a given SIMD size.
    static var_types getSIMDTypeForSize(unsigned size)
    {
        var_types simdType = TYP_UNDEF;
        if (size == 8)
        {
            simdType = TYP_SIMD8;
        }
        else if (size == 12)
        {
            simdType = TYP_SIMD12;
        }
        else if (size == 16)
        {
            simdType = TYP_SIMD16;
        }
        else if (size == 32)
        {
            simdType = TYP_SIMD32;
        }
        else
        {
            noway_assert(!"Unexpected size for SIMD type");
        }
        return simdType;
    }

private:
    unsigned getSIMDInitTempVarNum(var_types simdType);

#else  // !FEATURE_SIMD
    bool isOpaqueSIMDLclVar(LclVarDsc* varDsc)
    {
        return false;
    }
#endif // FEATURE_SIMD

public:
    //------------------------------------------------------------------------
    // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
    //
    // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
    //        candidate for enregistration.

    unsigned largestEnregisterableStructSize()
    {
#ifdef FEATURE_SIMD
#if defined(FEATURE_HW_INTRINSICS) && defined(TARGET_XARCH)
        if (opts.IsReadyToRun())
        {
            // Return constant instead of maxSIMDStructBytes, as maxSIMDStructBytes performs
            // checks that are effected by the current level of instruction set support would
            // otherwise cause the highest level of instruction set support to be reported to crossgen2.
            // and this api is only ever used as an optimization or assert, so no reporting should
            // ever happen.
            return YMM_REGSIZE_BYTES;
        }
#endif // defined(FEATURE_HW_INTRINSICS) && defined(TARGET_XARCH)
        unsigned vectorRegSize = maxSIMDStructBytes();
        assert(vectorRegSize >= TARGET_POINTER_SIZE);
        return vectorRegSize;
#else  // !FEATURE_SIMD
        return TARGET_POINTER_SIZE;
#endif // !FEATURE_SIMD
    }

    // Use to determine if a struct *might* be a SIMD type. As this function only takes a size, many
    // structs will fit the criteria.
    bool structSizeMightRepresentSIMDType(size_t structSize)
    {
#ifdef FEATURE_SIMD
        // Do not use maxSIMDStructBytes as that api in R2R on X86 and X64 may notify the JIT
        // about the size of a struct under the assumption that the struct size needs to be recorded.
        // By using largestEnregisterableStructSize here, the detail of whether or not Vector256<T> is
        // enregistered or not will not be messaged to the R2R compiler.
        return (structSize >= minSIMDStructBytes()) && (structSize <= largestEnregisterableStructSize());
#else
        return false;
#endif // FEATURE_SIMD
    }

#ifdef FEATURE_SIMD
    static bool vnEncodesResultTypeForSIMDIntrinsic(SIMDIntrinsicID intrinsicId);
#endif // !FEATURE_SIMD
#ifdef FEATURE_HW_INTRINSICS
    static bool vnEncodesResultTypeForHWIntrinsic(NamedIntrinsic hwIntrinsicID);
#endif // FEATURE_HW_INTRINSICS

private:
    // These routines need not be enclosed under FEATURE_SIMD since lvIsSIMDType()
    // is defined for both FEATURE_SIMD and !FEATURE_SIMD appropriately. The use
    // of this routines also avoids the need of #ifdef FEATURE_SIMD specific code.

    // Is this var is of type simd struct?
    bool lclVarIsSIMDType(unsigned varNum)
    {
        return lvaGetDesc(varNum)->lvIsSIMDType();
    }

    // Returns true if the TYP_SIMD locals on stack are aligned at their
    // preferred byte boundary specified by getSIMDTypeAlignment().
    //
    // As per the Intel manual, the preferred alignment for AVX vectors is
    // 32-bytes. It is not clear whether additional stack space used in
    // aligning stack is worth the benefit and for now will use 16-byte
    // alignment for AVX 256-bit vectors with unaligned load/stores to/from
    // memory. On x86, the stack frame is aligned to 4 bytes. We need to extend
    // existing support for double (8-byte) alignment to 16 or 32 byte
    // alignment for frames with local SIMD vars, if that is determined to be
    // profitable.
    //
    // On Amd64 and SysV, RSP+8 is aligned on entry to the function (before
    // prolog has run). This means that in RBP-based frames RBP will be 16-byte
    // aligned. For RSP-based frames these are only sometimes aligned, depending
    // on the frame size.
    //
    bool isSIMDTypeLocalAligned(unsigned varNum)
    {
#if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
        if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
        {
            // TODO-Cleanup: Can't this use the lvExactSize on the varDsc?
            int alignment = getSIMDTypeAlignment(lvaTable[varNum].lvType);
            if (alignment <= STACK_ALIGN)
            {
                bool rbpBased;
                int  off = lvaFrameAddress(varNum, &rbpBased);
                // On SysV and Winx64 ABIs RSP+8 will be 16-byte aligned at the
                // first instruction of a function. If our frame is RBP based
                // then RBP will always be 16 bytes aligned, so we can simply
                // check the offset.
                if (rbpBased)
                {
                    return (off % alignment) == 0;
                }

                // For RSP-based frame the alignment of RSP depends on our
                // locals. rsp+8 is aligned on entry and we just subtract frame
                // size so it is not hard to compute. Note that the compiler
                // tries hard to make sure the frame size means RSP will be
                // 16-byte aligned, but for leaf functions without locals (i.e.
                // frameSize = 0) it will not be.
                int frameSize = codeGen->genTotalFrameSize();
                return ((8 - frameSize + off) % alignment) == 0;
            }
        }
#endif // FEATURE_SIMD

        return false;
    }

#ifdef DEBUG
    // Answer the question: Is a particular ISA supported?
    // Use this api when asking the question so that future
    // ISA questions can be asked correctly or when asserting
    // support/nonsupport for an instruction set
    bool compIsaSupportedDebugOnly(CORINFO_InstructionSet isa) const
    {
#if defined(TARGET_XARCH) || defined(TARGET_ARM64)
        return opts.compSupportsISA.HasInstructionSet(isa);
#else
        return false;
#endif
    }
#endif // DEBUG

    bool notifyInstructionSetUsage(CORINFO_InstructionSet isa, bool supported) const;

    // Answer the question: Is a particular ISA allowed to be used implicitly by optimizations?
    // The result of this api call will exactly match the target machine
    // on which the function is executed (except for CoreLib, where there are special rules)
    bool compExactlyDependsOn(CORINFO_InstructionSet isa) const
    {
#if defined(TARGET_XARCH) || defined(TARGET_ARM64)
        if ((opts.compSupportsISAReported.HasInstructionSet(isa)) == false)
        {
            if (notifyInstructionSetUsage(isa, (opts.compSupportsISA.HasInstructionSet(isa))))
                ((Compiler*)this)->opts.compSupportsISAExactly.AddInstructionSet(isa);
            ((Compiler*)this)->opts.compSupportsISAReported.AddInstructionSet(isa);
        }
        return (opts.compSupportsISAExactly.HasInstructionSet(isa));
#else
        return false;
#endif
    }

    // Ensure that code will not execute if an instruction set is usable. Call only
    // if the instruction set has previously reported as unusable, but the status
    // has not yet been recorded to the AOT compiler.
    void compVerifyInstructionSetUnusable(CORINFO_InstructionSet isa)
    {
        // use compExactlyDependsOn to capture are record the use of the ISA.
        bool isaUsable = compExactlyDependsOn(isa);
        // Assert that the is unusable. If true, this function should never be called.
        assert(!isaUsable);
    }

    // Answer the question: Is a particular ISA allowed to be used implicitly by optimizations?
    // The result of this api call will match the target machine if the result is true.
    // If the result is false, then the target machine may have support for the instruction.
    bool compOpportunisticallyDependsOn(CORINFO_InstructionSet isa) const
    {
        if (opts.compSupportsISA.HasInstructionSet(isa))
        {
            return compExactlyDependsOn(isa);
        }
        else
        {
            return false;
        }
    }

    // Answer the question: Is a particular ISA supported for explicit hardware intrinsics?
    bool compHWIntrinsicDependsOn(CORINFO_InstructionSet isa) const
    {
        // Report intent to use the ISA to the EE
        compExactlyDependsOn(isa);
        return opts.compSupportsISA.HasInstructionSet(isa);
    }

    bool canUseVexEncoding() const
    {
#ifdef TARGET_XARCH
        return compOpportunisticallyDependsOn(InstructionSet_AVX);
#else
        return false;
#endif
    }

    //------------------------------------------------------------------------
    // canUseEvexEncoding - Answer the question: Is Evex encoding supported on this target.
    //
    // Returns:
    //    `true` if Evex encoding is supported, `false` if not.
    //
    bool canUseEvexEncoding() const
    {
#ifdef TARGET_XARCH

#ifdef DEBUG
        if (JitConfig.JitForceEVEXEncoding())
        {
            return true;
        }
#endif // DEBUG

        return compOpportunisticallyDependsOn(InstructionSet_AVX512F);
#else
        return false;
#endif
    }

    //------------------------------------------------------------------------
    // DoJitStressEvexEncoding- Answer the question: Do we force EVEX encoding.
    //
    // Returns:
    //    `true` if user requests EVEX encoding and it's safe, `false` if not.
    //
    bool DoJitStressEvexEncoding() const
    {
#if defined(TARGET_XARCH) && defined(DEBUG)
        // Using JitStressEVEXEncoding flag will force instructions which would
        // otherwise use VEX encoding but can be EVEX encoded to use EVEX encoding
        // This requires AVX512VL support. JitForceEVEXEncoding forces this encoding, thus
        // causing failure if not running on compatible hardware.

        if (JitConfig.JitForceEVEXEncoding())
        {
            return true;
        }
        if (JitConfig.JitStressEvexEncoding() && compOpportunisticallyDependsOn(InstructionSet_AVX512F_VL))
        {
            return true;
        }
#endif // TARGET_XARCH && DEBUG

        return false;
    }

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           Compiler                                        XX
    XX                                                                           XX
    XX   Generic info about the compilation and the method being compiled.       XX
    XX   It is responsible for driving the other phases.                         XX
    XX   It is also responsible for all the memory management.                   XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    Compiler* InlineeCompiler; // The Compiler instance for the inlinee

    InlineResult* compInlineResult; // The result of importing the inlinee method.

    bool compDoAggressiveInlining;     // If true, mark every method as CORINFO_FLG_FORCEINLINE
    bool compJmpOpUsed;                // Does the method do a JMP
    bool compLongUsed;                 // Does the method use TYP_LONG
    bool compFloatingPointUsed;        // Does the method use TYP_FLOAT or TYP_DOUBLE
    bool compTailCallUsed;             // Does the method do a tailcall
    bool compTailPrefixSeen;           // Does the method IL have tail. prefix
    bool compMayConvertTailCallToLoop; // Does the method have a recursive tail call that we may convert to a loop?
    bool compLocallocSeen;             // Does the method IL have localloc opcode
    bool compLocallocUsed;             // Does the method use localloc.
    bool compLocallocOptimized;        // Does the method have an optimized localloc
    bool compQmarkUsed;                // Does the method use GT_QMARK/GT_COLON
    bool compQmarkRationalized;        // Is it allowed to use a GT_QMARK/GT_COLON node.
    bool compHasBackwardJump;          // Does the method (or some inlinee) have a lexically backwards jump?
    bool compHasBackwardJumpInHandler; // Does the method have a lexically backwards jump in a handler?
    bool compSwitchedToOptimized;      // Codegen initially was Tier0 but jit switched to FullOpts
    bool compSwitchedToMinOpts;        // Codegen initially was Tier1/FullOpts but jit switched to MinOpts
    bool compSuppressedZeroInit;       // There are vars with lvSuppressedZeroInit set

// NOTE: These values are only reliable after
//       the importing is completely finished.

#ifdef DEBUG
    // State information - which phases have completed?
    // These are kept together for easy discoverability

    bool    bRangeAllowStress;
    bool    compCodeGenDone;
    int64_t compNumStatementLinksTraversed; // # of links traversed while doing debug checks
    bool    fgNormalizeEHDone;              // Has the flowgraph EH normalization phase been done?
    size_t  compSizeEstimate;               // The estimated size of the method as per `gtSetEvalOrder`.
    size_t  compCycleEstimate;              // The estimated cycle count of the method as per `gtSetEvalOrder`
#endif                                      // DEBUG

    bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
    bool fgLocalVarLivenessChanged;
    bool compLSRADone;
    bool compRationalIRForm;

    bool compUsesThrowHelper; // There is a call to a THROW_HELPER for the compiled method.

    bool compGeneratingProlog;
    bool compGeneratingEpilog;
    bool compNeedsGSSecurityCookie; // There is an unsafe buffer (or localloc) on the stack.
                                    // Insert cookie on frame and code to check the cookie, like VC++ -GS.
    bool compGSReorderStackLayout;  // There is an unsafe buffer on the stack, reorder locals and make local
    // copies of susceptible parameters to avoid buffer overrun attacks through locals/params
    bool getNeedsGSSecurityCookie() const
    {
        return compNeedsGSSecurityCookie;
    }
    void setNeedsGSSecurityCookie()
    {
        compNeedsGSSecurityCookie = true;
    }

    FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
                                         // frame layout calculations, this is the level we are currently
                                         // computing.

    //---------------------------- JITing options -----------------------------

    enum codeOptimize
    {
        BLENDED_CODE,
        SMALL_CODE,
        FAST_CODE,

        COUNT_OPT_CODE
    };

    struct Options
    {
        JitFlags* jitFlags; // all flags passed from the EE

        // The instruction sets that the compiler is allowed to emit.
        CORINFO_InstructionSetFlags compSupportsISA;
        // The instruction sets that were reported to the VM as being used by the current method. Subset of
        // compSupportsISA.
        CORINFO_InstructionSetFlags compSupportsISAReported;
        // The instruction sets that the compiler is allowed to take advantage of implicitly during optimizations.
        // Subset of compSupportsISA.
        // The instruction sets available in compSupportsISA and not available in compSupportsISAExactly can be only
        // used via explicit hardware intrinsics.
        CORINFO_InstructionSetFlags compSupportsISAExactly;

        void setSupportedISAs(CORINFO_InstructionSetFlags isas)
        {
            compSupportsISA = isas;
        }

        unsigned compFlags; // method attributes
        unsigned instrCount;
        unsigned lvRefCount;

        codeOptimize compCodeOpt; // what type of code optimizations

        bool compUseCMOV;

// optimize maximally and/or favor speed over size?

#define DEFAULT_MIN_OPTS_CODE_SIZE 60000
#define DEFAULT_MIN_OPTS_INSTR_COUNT 20000
#define DEFAULT_MIN_OPTS_BB_COUNT 2000
#define DEFAULT_MIN_OPTS_LV_NUM_COUNT 2000
#define DEFAULT_MIN_OPTS_LV_REF_COUNT 8000

// Maximum number of locals before turning off the inlining
#define MAX_LV_NUM_COUNT_FOR_INLINING 512

        bool compMinOpts;
        bool compMinOptsIsSet;
#ifdef DEBUG
        mutable bool compMinOptsIsUsed;

        bool MinOpts() const
        {
            assert(compMinOptsIsSet);
            compMinOptsIsUsed = true;
            return compMinOpts;
        }
        bool IsMinOptsSet() const
        {
            return compMinOptsIsSet;
        }
#else  // !DEBUG
        bool MinOpts() const
        {
            return compMinOpts;
        }
        bool IsMinOptsSet() const
        {
            return compMinOptsIsSet;
        }
#endif // !DEBUG

        bool OptimizationDisabled() const
        {
            return MinOpts() || compDbgCode;
        }
        bool OptimizationEnabled() const
        {
            return !OptimizationDisabled();
        }

        void SetMinOpts(bool val)
        {
            assert(!compMinOptsIsUsed);
            assert(!compMinOptsIsSet || (compMinOpts == val));
            compMinOpts      = val;
            compMinOptsIsSet = true;
        }

        // true if the CLFLG_* for an optimization is set.
        bool OptEnabled(unsigned optFlag) const
        {
            return !!(compFlags & optFlag);
        }

#ifdef FEATURE_READYTORUN
        bool IsReadyToRun() const
        {
            return jitFlags->IsSet(JitFlags::JIT_FLAG_READYTORUN);
        }
#else
        bool IsReadyToRun() const
        {
            return false;
        }
#endif

        // Check if the compilation is control-flow guard enabled.
        bool IsCFGEnabled() const
        {
#if defined(TARGET_ARM64) || defined(TARGET_AMD64)
            // On these platforms we assume the register that the target is
            // passed in is preserved by the validator and take care to get the
            // target from the register for the call (even in debug mode).
            static_assert_no_msg((RBM_VALIDATE_INDIRECT_CALL_TRASH & (1 << REG_VALIDATE_INDIRECT_CALL_ADDR)) == 0);
            if (JitConfig.JitForceControlFlowGuard())
                return true;

            return jitFlags->IsSet(JitFlags::JIT_FLAG_ENABLE_CFG);
#else
            // The remaining platforms are not supported and would require some
            // work to support.
            //
            // ARM32:
            //   The ARM32 validator does not preserve any volatile registers
            //   which means we have to take special care to allocate and use a
            //   callee-saved register (reloading the target from memory is a
            //   security issue).
            //
            // x86:
            //   On x86 some VSD calls disassemble the call site and expect an
            //   indirect call which is fundamentally incompatible with CFG.
            //   This would require a different way to pass this information
            //   through.
            //
            return false;
#endif
        }

#ifdef FEATURE_ON_STACK_REPLACEMENT
        bool IsOSR() const
        {
            return jitFlags->IsSet(JitFlags::JIT_FLAG_OSR);
        }
#else
        bool IsOSR() const
        {
            return false;
        }
#endif

        bool IsInstrumented() const
        {
            return jitFlags->IsSet(JitFlags::JIT_FLAG_BBINSTR);
        }

        bool IsInstrumentedOptimized() const
        {
            return IsInstrumented() && jitFlags->IsSet(JitFlags::JIT_FLAG_TIER1);
        }

        // true if we should use the PINVOKE_{BEGIN,END} helpers instead of generating
        // PInvoke transitions inline. Normally used by R2R, but also used when generating a reverse pinvoke frame, as
        // the current logic for frame setup initializes and pushes
        // the InlinedCallFrame before performing the Reverse PInvoke transition, which is invalid (as frames cannot
        // safely be pushed/popped while the thread is in a preemptive state.).
        bool ShouldUsePInvokeHelpers()
        {
            return jitFlags->IsSet(JitFlags::JIT_FLAG_USE_PINVOKE_HELPERS) ||
                   jitFlags->IsSet(JitFlags::JIT_FLAG_REVERSE_PINVOKE);
        }

        // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
        // prolog/epilog
        bool IsReversePInvoke()
        {
            return jitFlags->IsSet(JitFlags::JIT_FLAG_REVERSE_PINVOKE);
        }

        bool compScopeInfo; // Generate the LocalVar info ?
        bool compDbgCode;   // Generate debugger-friendly code?
        bool compDbgInfo;   // Gather debugging info?
        bool compDbgEnC;

#ifdef PROFILING_SUPPORTED
        bool compNoPInvokeInlineCB;
#else
        static const bool compNoPInvokeInlineCB;
#endif

#ifdef DEBUG
        bool compGcChecks; // Check arguments and return values to ensure they are sane
#endif

#if defined(DEBUG) && defined(TARGET_XARCH)

        bool compStackCheckOnRet; // Check stack pointer on return to ensure it is correct.

#endif // defined(DEBUG) && defined(TARGET_XARCH)

#if defined(DEBUG) && defined(TARGET_X86)

        bool compStackCheckOnCall; // Check stack pointer after call to ensure it is correct. Only for x86.

#endif // defined(DEBUG) && defined(TARGET_X86)

        bool compReloc; // Generate relocs for pointers in code, true for all ngen/prejit codegen

#ifdef DEBUG
#if defined(TARGET_XARCH)
        bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
#endif
#endif // DEBUG

#ifdef UNIX_AMD64_ABI
        // This flag  is indicating if there is a need to align the frame.
        // On AMD64-Windows, if there are calls, 4 slots for the outgoing ars are allocated, except for
        // FastTailCall. This slots makes the frame size non-zero, so alignment logic will be called.
        // On AMD64-Unix, there are no such slots. There is a possibility to have calls in the method with frame size of
        // 0. The frame alignment logic won't kick in. This flags takes care of the AMD64-Unix case by remembering that
        // there are calls and making sure the frame alignment logic is executed.
        bool compNeedToAlignFrame;
#endif // UNIX_AMD64_ABI

        bool compProcedureSplitting; // Separate cold code from hot code

        bool genFPorder; // Preserve FP order (operations are non-commutative)
        bool genFPopt;   // Can we do frame-pointer-omission optimization?
        bool altJit;     // True if we are an altjit and are compiling this method

#ifdef OPT_CONFIG
        bool optRepeat; // Repeat optimizer phases k times
#endif

        bool disAsm;      // Display native code as it is generated
        bool dspDiffable; // Makes the Jit Dump 'diff-able' (currently uses same COMPlus_* flag as disDiffable)
        bool disDiffable; // Makes the Disassembly code 'diff-able'
#ifdef DEBUG
        bool compProcedureSplittingEH; // Separate cold code from hot code for functions with EH
        bool dspCode;                  // Display native code generated
        bool dspEHTable;               // Display the EH table reported to the VM
        bool dspDebugInfo;             // Display the Debug info reported to the VM
        bool dspInstrs;                // Display the IL instructions intermixed with the native code output
        bool dspLines;                 // Display source-code lines intermixed with native code output
        bool dmpHex;                   // Display raw bytes in hex of native code output
        bool varNames;                 // Display variables names in native code output
        bool disAsmSpilled;            // Display native code when any register spilling occurs
        bool disasmWithGC;             // Display GC info interleaved with disassembly.
        bool disAddr;                  // Display process address next to each instruction in disassembly code
        bool disAlignment;             // Display alignment boundaries in disassembly code
        bool disAsm2;                  // Display native code after it is generated using external disassembler
        bool dspOrder;                 // Display names of each of the methods that we ngen/jit
        bool dspUnwind;                // Display the unwind info output
        bool compLongAddress;          // Force using large pseudo instructions for long address
                                       // (IF_LARGEJMP/IF_LARGEADR/IF_LARGLDC)
        bool dspGCtbls;                // Display the GC tables
#endif

// Default numbers used to perform loop alignment. All the numbers are chosen
// based on experimenting with various benchmarks.

// Default minimum loop block weight required to enable loop alignment.
#define DEFAULT_ALIGN_LOOP_MIN_BLOCK_WEIGHT 4

// By default a loop will be aligned at 32B address boundary to get better
// performance as per architecture manuals.
#define DEFAULT_ALIGN_LOOP_BOUNDARY 0x20

// For non-adaptive loop alignment, by default, only align a loop whose size is
// at most 3 times the alignment block size. If the loop is bigger than that, it is most
// likely complicated enough that loop alignment will not impact performance.
#define DEFAULT_MAX_LOOPSIZE_FOR_ALIGN DEFAULT_ALIGN_LOOP_BOUNDARY * 3

// By default only single iteration loops will be unrolled
#define DEFAULT_UNROLL_LOOP_MAX_ITERATION_COUNT 1

#ifdef DEBUG
        // Loop alignment variables

        // If set, for non-adaptive alignment, ensure loop jmps are not on or cross alignment boundary.
        bool compJitAlignLoopForJcc;
#endif
        // For non-adaptive alignment, minimum loop size (in bytes) for which alignment will be done.
        unsigned short compJitAlignLoopMaxCodeSize;

        // Minimum weight needed for the first block of a loop to make it a candidate for alignment.
        unsigned short compJitAlignLoopMinBlockWeight;

        // For non-adaptive alignment, address boundary (power of 2) at which loop alignment should
        // be done. By default, 32B.
        unsigned short compJitAlignLoopBoundary;

        // Padding limit to align a loop.
        unsigned short compJitAlignPaddingLimit;

        // If set, perform adaptive loop alignment that limits number of padding based on loop size.
        bool compJitAlignLoopAdaptive;

        // If set, tries to hide alignment instructions behind unconditional jumps.
        bool compJitHideAlignBehindJmp;

        // If set, tracks the hidden return buffer for struct arg.
        bool compJitOptimizeStructHiddenBuffer;

        // Iteration limit to unroll a loop.
        unsigned short compJitUnrollLoopMaxIterationCount;

#ifdef LATE_DISASM
        bool doLateDisasm; // Run the late disassembler
#endif                     // LATE_DISASM

#if DUMP_GC_TABLES && !defined(DEBUG)
#pragma message("NOTE: this non-debug build has GC ptr table dumping always enabled!")
        static const bool dspGCtbls = true;
#endif

#ifdef PROFILING_SUPPORTED
        // Whether to emit Enter/Leave/TailCall hooks using a dummy stub (DummyProfilerELTStub()).
        // This option helps make the JIT behave as if it is running under a profiler.
        bool compJitELTHookEnabled;
#endif // PROFILING_SUPPORTED

#if FEATURE_TAILCALL_OPT
        // Whether opportunistic or implicit tail call optimization is enabled.
        bool compTailCallOpt;
        // Whether optimization of transforming a recursive tail call into a loop is enabled.
        bool compTailCallLoopOpt;
#endif

#if FEATURE_FASTTAILCALL
        // Whether fast tail calls are allowed.
        bool compFastTailCalls;
#endif // FEATURE_FASTTAILCALL

#if defined(TARGET_ARM64)
        // Decision about whether to save FP/LR registers with callee-saved registers (see
        // COMPlus_JitSaveFpLrWithCalleSavedRegisters).
        int compJitSaveFpLrWithCalleeSavedRegisters;
#endif // defined(TARGET_ARM64)

#ifdef CONFIGURABLE_ARM_ABI
        bool compUseSoftFP = false;
#else
#ifdef ARM_SOFTFP
        static const bool compUseSoftFP = true;
#else  // !ARM_SOFTFP
        static const bool compUseSoftFP = false;
#endif // ARM_SOFTFP
#endif // CONFIGURABLE_ARM_ABI

        // Use early multi-dimensional array operator expansion (expand after loop optimizations; before lowering).
        bool compJitEarlyExpandMDArrays;

        // Collect 64 bit counts for PGO data.
        bool compCollect64BitCounts;

    } opts;

    static bool                s_pAltJitExcludeAssembliesListInitialized;
    static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;

#ifdef DEBUG
    static bool                s_pJitDisasmIncludeAssembliesListInitialized;
    static AssemblyNamesList2* s_pJitDisasmIncludeAssembliesList;

    static bool       s_pJitFunctionFileInitialized;
    static MethodSet* s_pJitMethodSet;

// silence warning of cast to greater size. It is easier to silence than construct code the compiler is happy with, and
// it is safe in this case
#pragma warning(push)
#pragma warning(disable : 4312)

    template <typename T>
    T dspPtr(T p)
    {
        return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
    }

    template <typename T>
    T dspOffset(T o)
    {
        return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
    }
#pragma warning(pop)
#else
#pragma warning(push)
#pragma warning(disable : 4312)
    template <typename T>
    T dspPtr(T p)
    {
        return p;
    }

    template <typename T>
    T dspOffset(T o)
    {
        return o;
    }
#pragma warning(pop)
#endif

#ifdef DEBUG

    static int dspTreeID(GenTree* tree)
    {
        return tree->gtTreeID;
    }

    static void printStmtID(Statement* stmt)
    {
        assert(stmt != nullptr);
        printf(FMT_STMT, stmt->GetID());
    }

    static void printTreeID(GenTree* tree)
    {
        if (tree == nullptr)
        {
            printf("[------]");
        }
        else
        {
            printf("[%06d]", dspTreeID(tree));
        }
    }

    const char* pgoSourceToString(ICorJitInfo::PgoSource p);
    const char* devirtualizationDetailToString(CORINFO_DEVIRTUALIZATION_DETAIL detail);

#endif // DEBUG

// clang-format off
#define STRESS_MODES                                                                            \
                                                                                                \
        STRESS_MODE(NONE)                                                                       \
                                                                                                \
        /* "Variations" stress areas which we try to mix up with each other. */                 \
        /* These should not be exhaustively used as they might */                               \
        /* hide/trivialize other areas */                                                       \
                                                                                                \
        STRESS_MODE(REGS)                                                                       \
        STRESS_MODE(DBL_ALN)                                                                    \
        STRESS_MODE(LCL_FLDS)                                                                   \
        STRESS_MODE(UNROLL_LOOPS)                                                               \
        STRESS_MODE(MAKE_CSE)                                                                   \
        STRESS_MODE(LEGACY_INLINE)                                                              \
        STRESS_MODE(CLONE_EXPR)                                                                 \
        STRESS_MODE(USE_CMOV)                                                                   \
        STRESS_MODE(FOLD)                                                                       \
        STRESS_MODE(MERGED_RETURNS)                                                             \
        STRESS_MODE(BB_PROFILE)                                                                 \
        STRESS_MODE(OPT_BOOLS_GC)                                                               \
        STRESS_MODE(REMORPH_TREES)                                                              \
        STRESS_MODE(64RSLT_MUL)                                                                 \
        STRESS_MODE(DO_WHILE_LOOPS)                                                             \
        STRESS_MODE(MIN_OPTS)                                                                   \
        STRESS_MODE(REVERSE_FLAG)     /* Will set GTF_REVERSE_OPS whenever we can */            \
        STRESS_MODE(TAILCALL)         /* Will make the call as a tailcall whenever legal */     \
        STRESS_MODE(CATCH_ARG)        /* Will spill catch arg */                                \
        STRESS_MODE(UNSAFE_BUFFER_CHECKS)                                                       \
        STRESS_MODE(NULL_OBJECT_CHECK)                                                          \
        STRESS_MODE(PINVOKE_RESTORE_ESP)                                                        \
        STRESS_MODE(RANDOM_INLINE)                                                              \
        STRESS_MODE(SWITCH_CMP_BR_EXPANSION)                                                    \
        STRESS_MODE(GENERIC_VARN)                                                               \
        STRESS_MODE(PROFILER_CALLBACKS) /* Will generate profiler hooks for ELT callbacks */    \
        STRESS_MODE(BYREF_PROMOTION) /* Change undoPromotion decisions for byrefs */            \
        STRESS_MODE(PROMOTE_FEWER_STRUCTS)/* Don't promote some structs that can be promoted */ \
        STRESS_MODE(VN_BUDGET)/* Randomize the VN budget */                                     \
        STRESS_MODE(SSA_INFO) /* Select lower thresholds for "complex" SSA num encoding */      \
                                                                                                \
        /* After COUNT_VARN, stress level 2 does all of these all the time */                   \
                                                                                                \
        STRESS_MODE(COUNT_VARN)                                                                 \
                                                                                                \
        /* "Check" stress areas that can be exhaustively used if we */                          \
        /*  dont care about performance at all */                                               \
                                                                                                \
        STRESS_MODE(FORCE_INLINE) /* Treat every method as AggressiveInlining */                \
        STRESS_MODE(CHK_FLOW_UPDATE)                                                            \
        STRESS_MODE(EMITTER)                                                                    \
        STRESS_MODE(CHK_REIMPORT)                                                               \
        STRESS_MODE(GENERIC_CHECK)                                                              \
        STRESS_MODE(IF_CONVERSION_COST)                                                         \
        STRESS_MODE(IF_CONVERSION_INNER_LOOPS)                                                  \
        STRESS_MODE(COUNT)

    enum                compStressArea
    {
#define STRESS_MODE(mode) STRESS_##mode,
        STRESS_MODES
#undef STRESS_MODE
    };
// clang-format on

#ifdef DEBUG
    static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
    BYTE                 compActiveStressModes[STRESS_COUNT];
#endif // DEBUG

#define MAX_STRESS_WEIGHT 100

    bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
    bool compStressCompileHelper(compStressArea stressArea, unsigned weightPercentage);

#ifdef DEBUG

    bool compInlineStress()
    {
        return compStressCompile(STRESS_LEGACY_INLINE, 50);
    }

    bool compRandomInlineStress()
    {
        return compStressCompile(STRESS_RANDOM_INLINE, 50);
    }

    bool compPromoteFewerStructs(unsigned lclNum);

#endif // DEBUG

    bool compTailCallStress()
    {
#ifdef DEBUG
        // Do not stress tailcalls in IL stubs as the runtime creates several IL
        // stubs to implement the tailcall mechanism, which would then
        // recursively create more IL stubs.
        return !opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IL_STUB) &&
               (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
#else
        return false;
#endif
    }

    const char* compGetTieringName(bool wantShortName = false) const;
    const char* compGetPgoSourceName() const;
    const char* compGetStressMessage() const;

    codeOptimize compCodeOpt() const
    {
#if 0
        // Switching between size & speed has measurable throughput impact
        // (3.5% on NGen CoreLib when measured). It used to be enabled for
        // DEBUG, but should generate identical code between CHK & RET builds,
        // so that's not acceptable.
        // TODO-Throughput: Figure out what to do about size vs. speed & throughput.
        //                  Investigate the cause of the throughput regression.

        return opts.compCodeOpt;
#else
        return BLENDED_CODE;
#endif
    }

    //--------------------- Info about the procedure --------------------------

    struct Info
    {
        COMP_HANDLE           compCompHnd;
        CORINFO_MODULE_HANDLE compScopeHnd;
        CORINFO_CLASS_HANDLE  compClassHnd;
        CORINFO_METHOD_HANDLE compMethodHnd;
        CORINFO_METHOD_INFO*  compMethodInfo;

        bool hasCircularClassConstraints;
        bool hasCircularMethodConstraints;

#if defined(DEBUG) || defined(LATE_DISASM) || DUMP_FLOWGRAPHS

        const char* compMethodName;
        const char* compClassName;
        const char* compFullName;
        double      compPerfScore;
        int         compMethodSuperPMIIndex; // useful when debugging under SuperPMI

#endif // defined(DEBUG) || defined(LATE_DISASM) || DUMP_FLOWGRAPHS

#if defined(DEBUG) || defined(INLINE_DATA)
        // Method hash is logically const, but computed
        // on first demand.
        mutable unsigned compMethodHashPrivate;
        unsigned         compMethodHash() const;
#endif // defined(DEBUG) || defined(INLINE_DATA)

#ifdef PSEUDORANDOM_NOP_INSERTION
        // things for pseudorandom nop insertion
        unsigned  compChecksum;
        CLRRandom compRNG;
#endif

        // The following holds the FLG_xxxx flags for the method we're compiling.
        unsigned compFlags;

        // The following holds the class attributes for the method we're compiling.
        unsigned compClassAttr;

        const BYTE*     compCode;
        IL_OFFSET       compILCodeSize;     // The IL code size
        IL_OFFSET       compILImportSize;   // Estimated amount of IL actually imported
        IL_OFFSET       compILEntry;        // The IL entry point (normally 0)
        PatchpointInfo* compPatchpointInfo; // Patchpoint data for OSR (normally nullptr)
        UNATIVE_OFFSET  compNativeCodeSize; // The native code size, after instructions are issued. This
        // is less than (compTotalHotCodeSize + compTotalColdCodeSize) only if:
        // (1) the code is not hot/cold split, and we issued less code than we expected, or
        // (2) the code is hot/cold split, and we issued less code than we expected
        // in the cold section (the hot section will always be padded out to compTotalHotCodeSize).

        bool compIsStatic : 1;           // Is the method static (no 'this' pointer)?
        bool compIsVarArgs : 1;          // Does the method have varargs parameters?
        bool compInitMem : 1;            // Is the CORINFO_OPT_INIT_LOCALS bit set in the method info options?
        bool compProfilerCallback : 1;   // JIT inserted a profiler Enter callback
        bool compPublishStubParam : 1;   // EAX captured in prolog will be available through an intrinsic
        bool compHasNextCallRetAddr : 1; // The NextCallReturnAddress intrinsic is used.

        var_types compRetType;       // Return type of the method as declared in IL (including SIMD normalization)
        var_types compRetNativeType; // Normalized return type as per target arch ABI
        unsigned  compILargsCount;   // Number of arguments (incl. implicit but not hidden)
        unsigned  compArgsCount;     // Number of arguments (incl. implicit and     hidden)

#if FEATURE_FASTTAILCALL
        unsigned compArgStackSize; // Incoming argument stack size in bytes
#endif                             // FEATURE_FASTTAILCALL

        unsigned compRetBuffArg; // position of hidden return param var (0, 1) (BAD_VAR_NUM means not present);
        int compTypeCtxtArg; // position of hidden param for type context for generic code (CORINFO_CALLCONV_PARAMTYPE)
        unsigned       compThisArg; // position of implicit this pointer param (not to be confused with lvaArg0Var)
        unsigned       compILlocalsCount; // Number of vars : args + locals (incl. implicit but not hidden)
        unsigned       compLocalsCount;   // Number of vars : args + locals (incl. implicit and     hidden)
        unsigned       compMaxStack;
        UNATIVE_OFFSET compTotalHotCodeSize;  // Total number of bytes of Hot Code in the method
        UNATIVE_OFFSET compTotalColdCodeSize; // Total number of bytes of Cold Code in the method

        unsigned compUnmanagedCallCountWithGCTransition; // count of unmanaged calls with GC transition.

        CorInfoCallConvExtension compCallConv; // The entry-point calling convention for this method.

        unsigned compLvFrameListRoot; // lclNum for the Frame root
        unsigned compXcptnsCount;     // Number of exception-handling clauses read in the method's IL.
                                      // You should generally use compHndBBtabCount instead: it is the
                                      // current number of EH clauses (after additions like synchronized
        // methods and funclets, and removals like unreachable code deletion).

        Target::ArgOrder compArgOrder;

        bool compMatchedVM; // true if the VM is "matched": either the JIT is a cross-compiler
                            // and the VM expects that, or the JIT is a "self-host" compiler
                            // (e.g., x86 hosted targeting x86) and the VM expects that.

        /*  The following holds IL scope information about local variables.
         */

        unsigned     compVarScopesCount;
        VarScopeDsc* compVarScopes;

        /* The following holds information about instr offsets for
         * which we need to report IP-mappings
         */

        IL_OFFSET*                   compStmtOffsets; // sorted
        unsigned                     compStmtOffsetsCount;
        ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;

#define CPU_X86 0x0100 // The generic X86 CPU
#define CPU_X86_PENTIUM_4 0x0110

#define CPU_X64 0x0200       // The generic x64 CPU
#define CPU_AMD_X64 0x0210   // AMD x64 CPU
#define CPU_INTEL_X64 0x0240 // Intel x64 CPU

#define CPU_ARM 0x0300   // The generic ARM CPU
#define CPU_ARM64 0x0400 // The generic ARM64 CPU

#define CPU_LOONGARCH64 0x0800 // The generic LOONGARCH64 CPU

        unsigned genCPU; // What CPU are we running on

        // Number of class profile probes in this method
        unsigned compHandleHistogramProbeCount;

    } info;

    ReturnTypeDesc compRetTypeDesc; // ABI return type descriptor for the method

    //------------------------------------------------------------------------
    // compMethodHasRetVal: Does this method return some kind of value?
    //
    // Return Value:
    //    If this method returns a struct via a return buffer, whether that
    //    buffer's address needs to be returned, otherwise whether signature
    //    return type is not "TYP_VOID".
    //
    bool compMethodHasRetVal() const
    {
        return (info.compRetBuffArg != BAD_VAR_NUM) ? compMethodReturnsRetBufAddr() : (info.compRetType != TYP_VOID);
    }

    // Returns true if the method being compiled returns RetBuf addr as its return value
    bool compMethodReturnsRetBufAddr() const
    {
        // There are cases where implicit RetBuf argument should be explicitly returned in a register.
        // In such cases the return type is changed to TYP_BYREF and appropriate IR is generated.
        // These cases are:
        CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef TARGET_AMD64
        // 1. on x64 Windows and Unix the address of RetBuf needs to be returned by
        //    methods with hidden RetBufArg in RAX. In such case GT_RETURN is of TYP_BYREF,
        //    returning the address of RetBuf.
        return (info.compRetBuffArg != BAD_VAR_NUM);
#else // TARGET_AMD64
#ifdef PROFILING_SUPPORTED
        // 2.  Profiler Leave callback expects the address of retbuf as return value for
        //    methods with hidden RetBuf argument.  impReturnInstruction() when profiler
        //    callbacks are needed creates GT_RETURN(TYP_BYREF, op1 = Addr of RetBuf) for
        //    methods with hidden RetBufArg.
        if (compIsProfilerHookNeeded())
        {
            return (info.compRetBuffArg != BAD_VAR_NUM);
        }
#endif
        // 3. Windows ARM64 native instance calling convention requires the address of RetBuff
        //    to be returned in x0.
        CLANG_FORMAT_COMMENT_ANCHOR;
#if defined(TARGET_ARM64)
        if (TargetOS::IsWindows)
        {
            auto callConv = info.compCallConv;
            if (callConvIsInstanceMethodCallConv(callConv))
            {
                return (info.compRetBuffArg != BAD_VAR_NUM);
            }
        }
#endif // TARGET_ARM64
        // 4. x86 unmanaged calling conventions require the address of RetBuff to be returned in eax.
        CLANG_FORMAT_COMMENT_ANCHOR;
#if defined(TARGET_X86)
        if (info.compCallConv != CorInfoCallConvExtension::Managed)
        {
            return (info.compRetBuffArg != BAD_VAR_NUM);
        }
#endif

        return false;
#endif // TARGET_AMD64
    }

    //------------------------------------------------------------------------
    // compMethodReturnsMultiRegRetType: Does this method return a multi-reg value?
    //
    // Return Value:
    //    If this method returns a value in multiple registers, "true", "false"
    //    otherwise.
    //
    bool compMethodReturnsMultiRegRetType() const
    {
        return compRetTypeDesc.IsMultiRegRetType();
    }

    bool compEnregLocals()
    {
        return ((opts.compFlags & CLFLG_REGVAR) != 0);
    }

    bool compEnregStructLocals()
    {
        return (JitConfig.JitEnregStructLocals() != 0);
    }

    bool compObjectStackAllocation()
    {
        return (JitConfig.JitObjectStackAllocation() != 0);
    }

    // Returns true if the method requires a PInvoke prolog and epilog
    bool compMethodRequiresPInvokeFrame()
    {
        return (info.compUnmanagedCallCountWithGCTransition > 0);
    }

    // Returns true if address-exposed user variables should be poisoned with a recognizable value
    bool compShouldPoisonFrame()
    {
#ifdef FEATURE_ON_STACK_REPLACEMENT
        if (opts.IsOSR())
            return false;
#endif
        return !info.compInitMem && opts.compDbgCode;
    }

    // Returns true if the jit supports having patchpoints in this method.
    // Optionally, get the reason why not.
    bool compCanHavePatchpoints(const char** reason = nullptr);

#if defined(DEBUG)

    void compDispLocalVars();

#endif // DEBUG

private:
    class ClassLayoutTable* m_classLayoutTable;

    class ClassLayoutTable* typCreateClassLayoutTable();
    class ClassLayoutTable* typGetClassLayoutTable();

public:
    // Get the layout having the specified layout number.
    ClassLayout* typGetLayoutByNum(unsigned layoutNum);
    // Get the layout number of the specified layout.
    unsigned typGetLayoutNum(ClassLayout* layout);
    // Get the layout having the specified size but no class handle.
    ClassLayout* typGetBlkLayout(unsigned blockSize);
    // Get the number of a layout having the specified size but no class handle.
    unsigned typGetBlkLayoutNum(unsigned blockSize);
    // Get the layout for the specified class handle.
    ClassLayout* typGetObjLayout(CORINFO_CLASS_HANDLE classHandle);
    // Get the number of a layout for the specified class handle.
    unsigned typGetObjLayoutNum(CORINFO_CLASS_HANDLE classHandle);

//-------------------------- Global Compiler Data ------------------------------------

#ifdef DEBUG
private:
    static LONG s_compMethodsCount; // to produce unique label names
#endif

public:
#ifdef DEBUG
    unsigned compGenTreeID;
    unsigned compStatementID;
    unsigned compBasicBlockID;
#endif
    LONG compMethodID;

    BasicBlock* compCurBB;   // the current basic block in process
    Statement*  compCurStmt; // the current statement in process
    GenTree*    compCurTree; // the current tree in process

    //  The following is used to create the 'method JIT info' block.
    size_t compInfoBlkSize;
    BYTE*  compInfoBlkAddr;

    EHblkDsc* compHndBBtab;           // array of EH data
    unsigned  compHndBBtabCount;      // element count of used elements in EH data array
    unsigned  compHndBBtabAllocCount; // element count of allocated elements in EH data array

#if defined(TARGET_X86)

    //-------------------------------------------------------------------------
    //  Tracking of region covered by the monitor in synchronized methods
    void* syncStartEmitCookie; // the emitter cookie for first instruction after the call to MON_ENTER
    void* syncEndEmitCookie;   // the emitter cookie for first instruction after the call to MON_EXIT

#endif // !TARGET_X86

    Phases      mostRecentlyActivePhase; // the most recently active phase
    PhaseChecks activePhaseChecks;       // the currently active phase checks
    PhaseDumps  activePhaseDumps;        // the currently active phase dumps

    //-------------------------------------------------------------------------
    //  The following keeps track of how many bytes of local frame space we've
    //  grabbed so far in the current function, and how many argument bytes we
    //  need to pop when we return.
    //

    unsigned compLclFrameSize; // secObject+lclBlk+locals+temps

    // Count of callee-saved regs we pushed in the prolog.
    // Does not include EBP for isFramePointerUsed() and double-aligned frames.
    // In case of Amd64 this doesn't include float regs saved on stack.
    unsigned compCalleeRegsPushed;

#if defined(TARGET_XARCH)
    // Mask of callee saved float regs on stack.
    regMaskTP compCalleeFPRegsSavedMask;
#endif
#ifdef TARGET_AMD64
// Quirk for VS debug-launch scenario to work:
// Bytes of padding between save-reg area and locals.
#define VSQUIRK_STACK_PAD (2 * REGSIZE_BYTES)
    unsigned compVSQuirkStackPaddingNeeded;
#endif

    unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))

#ifdef TARGET_ARM
    bool compHasSplitParam;
#endif

    unsigned compMapILargNum(unsigned ILargNum);      // map accounting for hidden args
    unsigned compMapILvarNum(unsigned ILvarNum);      // map accounting for hidden args
    unsigned compMap2ILvarNum(unsigned varNum) const; // map accounting for hidden args

#if defined(TARGET_ARM64)
    struct FrameInfo
    {
        // Frame type (1-5)
        int frameType;

        // Distance from established (method body) SP to base of callee save area
        int calleeSaveSpOffset;

        // Amount to subtract from SP before saving (prolog) OR
        // to add to SP after restoring (epilog) callee saves
        int calleeSaveSpDelta;

        // Distance from established SP to where caller's FP was saved
        int offsetSpToSavedFp;
    } compFrameInfo;
#endif

    //-------------------------------------------------------------------------

    static void compStartup();  // One-time initialization
    static void compShutdown(); // One-time finalization

    void compInit(ArenaAllocator*       pAlloc,
                  CORINFO_METHOD_HANDLE methodHnd,
                  COMP_HANDLE           compHnd,
                  CORINFO_METHOD_INFO*  methodInfo,
                  InlineInfo*           inlineInfo);
    void compDone();

    static void compDisplayStaticSizes(FILE* fout);

    //------------ Some utility functions --------------

    void* compGetHelperFtn(CorInfoHelpFunc ftnNum,         /* IN  */
                           void**          ppIndirection); /* OUT */

    // Several JIT/EE interface functions return a CorInfoType, and also return a
    // class handle as an out parameter if the type is a value class.  Returns the
    // size of the type these describe.
    unsigned compGetTypeSize(CorInfoType cit, CORINFO_CLASS_HANDLE clsHnd);

#ifdef DEBUG
    // Components used by the compiler may write unit test suites, and
    // have them run within this method.  They will be run only once per process, and only
    // in debug.  (Perhaps should be under the control of a COMPlus_ flag.)
    // These should fail by asserting.
    void compDoComponentUnitTestsOnce();
#endif // DEBUG

    int compCompile(CORINFO_MODULE_HANDLE classPtr,
                    void**                methodCodePtr,
                    uint32_t*             methodCodeSize,
                    JitFlags*             compileFlags);
    void compCompileFinish();
    int compCompileHelper(CORINFO_MODULE_HANDLE classPtr,
                          COMP_HANDLE           compHnd,
                          CORINFO_METHOD_INFO*  methodInfo,
                          void**                methodCodePtr,
                          uint32_t*             methodCodeSize,
                          JitFlags*             compileFlag);

    ArenaAllocator* compGetArenaAllocator();

    void generatePatchpointInfo();

#if MEASURE_MEM_ALLOC
    static bool s_dspMemStats; // Display per-phase memory statistics for every function
#endif                         // MEASURE_MEM_ALLOC

#if LOOP_HOIST_STATS
    unsigned m_loopsConsidered;
    bool     m_curLoopHasHoistedExpression;
    unsigned m_loopsWithHoistedExpressions;
    unsigned m_totalHoistedExpressions;

    void AddLoopHoistStats();
    void PrintPerMethodLoopHoistStats();

    static CritSecObject s_loopHoistStatsLock; // This lock protects the data structures below.
    static unsigned      s_loopsConsidered;
    static unsigned      s_loopsWithHoistedExpressions;
    static unsigned      s_totalHoistedExpressions;

    static void PrintAggregateLoopHoistStats(FILE* f);
#endif // LOOP_HOIST_STATS

#if TRACK_ENREG_STATS
    class EnregisterStats
    {
    private:
        unsigned m_totalNumberOfVars;
        unsigned m_totalNumberOfStructVars;
        unsigned m_totalNumberOfEnregVars;
        unsigned m_totalNumberOfStructEnregVars;

        unsigned m_addrExposed;
        unsigned m_hiddenStructArg;
        unsigned m_VMNeedsStackAddr;
        unsigned m_localField;
        unsigned m_blockOp;
        unsigned m_dontEnregStructs;
        unsigned m_notRegSizeStruct;
        unsigned m_structArg;
        unsigned m_lclAddrNode;
        unsigned m_castTakesAddr;
        unsigned m_storeBlkSrc;
        unsigned m_oneAsgRetyping;
        unsigned m_swizzleArg;
        unsigned m_blockOpRet;
        unsigned m_returnSpCheck;
        unsigned m_callSpCheck;
        unsigned m_simdUserForcesDep;
        unsigned m_liveInOutHndlr;
        unsigned m_depField;
        unsigned m_noRegVars;
        unsigned m_minOptsGC;
#ifdef JIT32_GCENCODER
        unsigned m_PinningRef;
#endif // JIT32_GCENCODER
#if !defined(TARGET_64BIT)
        unsigned m_longParamField;
#endif // !TARGET_64BIT
        unsigned m_parentExposed;
        unsigned m_tooConservative;
        unsigned m_escapeAddress;
        unsigned m_osrExposed;
        unsigned m_stressLclFld;
        unsigned m_dispatchRetBuf;
        unsigned m_wideIndir;

    public:
        void RecordLocal(const LclVarDsc* varDsc);
        void Dump(FILE* fout) const;
    };

    static EnregisterStats s_enregisterStats;
#endif // TRACK_ENREG_STATS

    bool compIsForImportOnly();
    bool compIsForInlining() const;
    bool compDonotInline();

#ifdef DEBUG
    // Get the default fill char value we randomize this value when JitStress is enabled.
    static unsigned char compGetJitDefaultFill(Compiler* comp);

    const char* compLocalVarName(unsigned varNum, unsigned offs);
    VarName compVarName(regNumber reg, bool isFloatReg = false);
    const char* compFPregVarName(unsigned fpReg, bool displayVar = false);
    void compDspSrcLinesByNativeIP(UNATIVE_OFFSET curIP);
    void compDspSrcLinesByLineNum(unsigned line, bool seek = false);
#endif // DEBUG
    const char* compRegNameForSize(regNumber reg, size_t size);
    const char* compRegVarName(regNumber reg, bool displayVar = false, bool isFloatReg = false);

    //-------------------------------------------------------------------------

    struct VarScopeListNode
    {
        VarScopeDsc*             data;
        VarScopeListNode*        next;
        static VarScopeListNode* Create(VarScopeDsc* value, CompAllocator alloc)
        {
            VarScopeListNode* node = new (alloc) VarScopeListNode;
            node->data             = value;
            node->next             = nullptr;
            return node;
        }
    };

    struct VarScopeMapInfo
    {
        VarScopeListNode*       head;
        VarScopeListNode*       tail;
        static VarScopeMapInfo* Create(VarScopeListNode* node, CompAllocator alloc)
        {
            VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
            info->head            = node;
            info->tail            = node;
            return info;
        }
    };

    // Max value of scope count for which we would use linear search; for larger values we would use hashtable lookup.
    static const unsigned MAX_LINEAR_FIND_LCL_SCOPELIST = 32;

    typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*> VarNumToScopeDscMap;

    // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
    VarNumToScopeDscMap* compVarScopeMap;

    VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);

    VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);

    VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);

    void compInitVarScopeMap();

    VarScopeDsc** compEnterScopeList; // List has the offsets where variables
                                      // enter scope, sorted by instr offset
    unsigned compNextEnterScope;

    VarScopeDsc** compExitScopeList; // List has the offsets where variables
                                     // go out of scope, sorted by instr offset
    unsigned compNextExitScope;

    void compInitScopeLists();

    void compResetScopeLists();

    VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);

    VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);

    void compProcessScopesUntil(unsigned   offset,
                                VARSET_TP* inScope,
                                void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
                                void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));

#ifdef DEBUG
    void compDispScopeLists();
#endif // DEBUG

    bool compIsProfilerHookNeeded() const;

    //-------------------------------------------------------------------------
    /*               Statistical Data Gathering                               */

    void compJitStats(); // call this function and enable
                         // various ifdef's below for statistical data

#if CALL_ARG_STATS
    void        compCallArgStats();
    static void compDispCallArgStats(FILE* fout);
#endif

    //-------------------------------------------------------------------------

protected:
#ifdef DEBUG
    bool skipMethod();
#endif

    ArenaAllocator* compArenaAllocator;

public:
    void compFunctionTraceStart();
    void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);

protected:
    size_t compMaxUncheckedOffsetForNullObject;

    void compInitOptions(JitFlags* compileFlags);

    void compSetProcessor();
    void compInitDebuggingInfo();
    void compSetOptimizationLevel();
#if defined(TARGET_ARMARCH) || defined(TARGET_LOONGARCH64)
    bool compRsvdRegCheck(FrameLayoutState curState);
#endif
    void compCompile(void** methodCodePtr, uint32_t* methodCodeSize, JitFlags* compileFlags);

    // Clear annotations produced during optimizations; to be used between iterations when repeating opts.
    void ResetOptAnnotations();

    // Regenerate loop descriptors; to be used between iterations when repeating opts.
    void RecomputeLoopInfo();

#ifdef PROFILING_SUPPORTED
    // Data required for generating profiler Enter/Leave/TailCall hooks

    bool  compProfilerHookNeeded; // Whether profiler Enter/Leave/TailCall hook needs to be generated for the method
    void* compProfilerMethHnd;    // Profiler handle of the method being compiled. Passed as param to ELT callbacks
    bool  compProfilerMethHndIndirected; // Whether compProfilerHandle is pointer to the handle or is an actual handle
#endif

public:
    // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
    static void ProcessShutdownWork(ICorStaticInfo* statInfo);

    CompAllocator getAllocator(CompMemKind cmk = CMK_Generic)
    {
        return CompAllocator(compArenaAllocator, cmk);
    }

    CompAllocator getAllocatorGC()
    {
        return getAllocator(CMK_GC);
    }

    CompAllocator getAllocatorLoopHoist()
    {
        return getAllocator(CMK_LoopHoist);
    }

#ifdef DEBUG
    CompAllocator getAllocatorDebugOnly()
    {
        return getAllocator(CMK_DebugOnly);
    }
#endif // DEBUG

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                           IL verification stuff                           XX
    XX                                                                           XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */

public:
    EntryState verCurrentState;

    void verInitBBEntryState(BasicBlock* block, EntryState* currentState);

    void verInitCurrentState();
    void verResetCurrentState(BasicBlock* block, EntryState* currentState);

    void verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg));
    void verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg));
    typeInfo verMakeTypeInfoForLocal(unsigned lclNum);
    typeInfo verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo
    typeInfo verMakeTypeInfo(CorInfoType          ciType,
                             CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo

    typeInfo verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args);
    bool verIsByRefLike(const typeInfo& ti);

    void DECLSPEC_NORETURN verRaiseVerifyException(INDEBUG(const char* reason) DEBUGARG(const char* file)
                                                       DEBUGARG(unsigned line));
    void verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* reason) DEBUGARG(const char* file)
                                             DEBUGARG(unsigned line));
    bool verCheckTailCallConstraint(OPCODE                  opcode,
                                    CORINFO_RESOLVED_TOKEN* pResolvedToken,
                                    CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken);

#ifdef DEBUG

    // One line log function. Default level is 0. Increasing it gives you
    // more log information

    // levels are currently unused: #define JITDUMP(level,...)                     ();
    void JitLogEE(unsigned level, const char* fmt, ...);

    bool compDebugBreak;

    bool compJitHaltMethod();

#endif

    /*
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XX                                                                           XX
    XX                   GS Security checks for unsafe buffers                   XX
    XX                                                                           XX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    */
public:
    struct ShadowParamVarInfo
    {
        FixedBitVect* assignGroup; // the closure set of variables whose values depend on each other
        unsigned      shadowCopy;  // Lcl var num, if not valid set to BAD_VAR_NUM

        static bool mayNeedShadowCopy(LclVarDsc* varDsc)
        {
#if defined(TARGET_AMD64)
            // GS cookie logic to create shadow slots, create trees to copy reg args to shadow
            // slots and update all trees to refer to shadow slots is done immediately after
            // fgMorph().  Lsra could potentially mark a param as DoNotEnregister after JIT determines
            // not to shadow a parameter.  Also, LSRA could potentially spill a param which is passed
            // in register. Therefore, conservatively all params may need a shadow copy.  Note that
            // GS cookie logic further checks whether the param is a ptr or an unsafe buffer before
            // creating a shadow slot even though this routine returns true.
            //
            // TODO-AMD64-CQ: Revisit this conservative approach as it could create more shadow slots than
            // required. There are two cases under which a reg arg could potentially be used from its
            // home location:
            //   a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
            //   b) LSRA spills it
            //
            // Possible solution to address case (a)
            //   - The conditions under which LSRA marks a varDsc as DoNotEnregister could be checked
            //     in this routine.  Note that live out of exception handler is something we may not be
            //     able to do it here since GS cookie logic is invoked ahead of liveness computation.
            //     Therefore, for methods with exception handling and need GS cookie check we might have
            //     to take conservative approach.
            //
            // Possible solution to address case (b)
            //   - Whenever a parameter passed in an argument register needs to be spilled by LSRA, we
            //     create a new spill temp if the method needs GS cookie check.
            return varDsc->lvIsParam;
#else // !defined(TARGET_AMD64)
            return varDsc->lvIsParam && !varDsc->lvIsRegArg;
#endif
        }

#ifdef DEBUG
        void Print()
        {
            printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
        }
#endif
    };

    GSCookie*           gsGlobalSecurityCookieAddr; // Address of global cookie for unsafe buffer checks
    GSCookie            gsGlobalSecurityCookieVal;  // Value of global cookie if addr is NULL
    ShadowParamVarInfo* gsShadowVarInfo;            // Table used by shadow param analysis code

    PhaseStatus gsPhase();
    void        gsGSChecksInitCookie();   // Grabs cookie variable
    void        gsCopyShadowParams();     // Identify vulnerable params and create dhadow copies
    bool        gsFindVulnerableParams(); // Shadow param analysis code
    void        gsParamsToShadows();      // Insert copy code and replave param uses by shadow

    static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
    static fgWalkPreFn gsReplaceShadowParams;     // Shadow param replacement tree-walk

#define DEFAULT_MAX_INLINE_SIZE 100 // Methods with >  DEFAULT_MAX_INLINE_SIZE IL bytes will never be inlined.
                                    // This can be overwritten by setting complus_JITInlineSize env variable.

#define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined

#define DEFAULT_MAX_LOCALLOC_TO_LOCAL_SIZE 32 // fixed locallocs of this size or smaller will convert to local buffers

private:
#ifdef FEATURE_JIT_METHOD_PERF
    JitTimer*                  pCompJitTimer;         // Timer data structure (by phases) for current compilation.
    static CompTimeSummaryInfo s_compJitTimerSummary; // Summary of the Timer information for the whole run.

    static LPCWSTR JitTimeLogCsv();        // Retrieve the file name for CSV from ConfigDWORD.
    static LPCWSTR compJitTimeLogFilename; // If a log file for JIT time is desired, filename to write it to.
#endif
    void BeginPhase(Phases phase); // Indicate the start of the given phase.
    void EndPhase(Phases phase);   // Indicate the end of the given phase.

#if MEASURE_CLRAPI_CALLS
    // Thin wrappers that call into JitTimer (if present).
    inline void CLRApiCallEnter(unsigned apix);
    inline void CLRApiCallLeave(unsigned apix);

public:
    inline void CLR_API_Enter(API_ICorJitInfo_Names ename);
    inline void CLR_API_Leave(API_ICorJitInfo_Names ename);

private:
#endif

#if defined(DEBUG) || defined(INLINE_DATA)
    // These variables are associated with maintaining SQM data about compile time.
    unsigned __int64 m_compCyclesAtEndOfInlining; // The thread-virtualized cycle count at the end of the inlining phase
                                                  // in the current compilation.
    unsigned __int64 m_compCycles;                // Net cycle count for current compilation
    DWORD m_compTickCountAtEndOfInlining; // The result of GetTickCount() (# ms since some epoch marker) at the end of
                                          // the inlining phase in the current compilation.
#endif                                    // defined(DEBUG) || defined(INLINE_DATA)

    // Records the SQM-relevant (cycles and tick count).  Should be called after inlining is complete.
    // (We do this after inlining because this marks the last point at which the JIT is likely to cause
    // type-loading and class initialization).
    void RecordStateAtEndOfInlining();
    // Assumes being called at the end of compilation.  Update the SQM state.
    void RecordStateAtEndOfCompilation();

public:
#if FUNC_INFO_LOGGING
    static LPCWSTR compJitFuncInfoFilename; // If a log file for per-function information is required, this is the
                                            // filename to write it to.
    static FILE* compJitFuncInfoFile;       // And this is the actual FILE* to write to.
#endif                                      // FUNC_INFO_LOGGING

    Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.

#if MEASURE_NOWAY
    void RecordNowayAssert(const char* filename, unsigned line, const char* condStr);
#endif // MEASURE_NOWAY

#ifndef FEATURE_TRACELOGGING
    // Should we actually fire the noway assert body and the exception handler?
    bool compShouldThrowOnNoway();
#else  // FEATURE_TRACELOGGING
    // Should we actually fire the noway assert body and the exception handler?
    bool compShouldThrowOnNoway(const char* filename, unsigned line);

    // Telemetry instance to use per method compilation.
    JitTelemetry compJitTelemetry;

    // Get common parameters that have to be logged with most telemetry data.
    void compGetTelemetryDefaults(const char** assemblyName,
                                  const char** scopeName,
                                  const char** methodName,
                                  unsigned*    methodHash);
#endif // !FEATURE_TRACELOGGING

#ifdef DEBUG
private:
    NodeToTestDataMap* m_nodeTestData;

    static const unsigned FIRST_LOOP_HOIST_CSE_CLASS = 1000;
    unsigned              m_loopHoistCSEClass; // LoopHoist test annotations turn into CSE requirements; we
                                               // label them with CSE Class #'s starting at FIRST_LOOP_HOIST_CSE_CLASS.
                                               // Current kept in this.
public:
    NodeToTestDataMap* GetNodeTestData()
    {
        Compiler* compRoot = impInlineRoot();
        if (compRoot->m_nodeTestData == nullptr)
        {
            compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
        }
        return compRoot->m_nodeTestData;
    }

    typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, int> NodeToIntMap;

    // Returns the set (i.e., the domain of the result map) of nodes that are keys in m_nodeTestData, and
    // currently occur in the AST graph.
    NodeToIntMap* FindReachableNodesInNodeTestData();

    // Node "from" is being eliminated, and being replaced by node "to".  If "from" had any associated
    // test data, associate that data with "to".
    void TransferTestDataToNode(GenTree* from, GenTree* to);

    // These are the methods that test that the various conditions implied by the
    // test attributes are satisfied.
    void JitTestCheckSSA(); // SSA builder tests.
    void JitTestCheckVN();  // Value numbering tests.
#endif                      // DEBUG

    FieldSeqStore* m_fieldSeqStore;

    FieldSeqStore* GetFieldSeqStore()
    {
        Compiler* compRoot = impInlineRoot();
        if (compRoot->m_fieldSeqStore == nullptr)
        {
            CompAllocator alloc       = getAllocator(CMK_FieldSeqStore);
            compRoot->m_fieldSeqStore = new (alloc) FieldSeqStore(alloc);
        }
        return compRoot->m_fieldSeqStore;
    }

    typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, unsigned> NodeToUnsignedMap;

    NodeToUnsignedMap* m_memorySsaMap[MemoryKindCount];

    // In some cases, we want to assign intermediate SSA #'s to memory states, and know what nodes create those memory
    // states. (We do this for try blocks, where, if the try block doesn't do a call that loses track of the memory
    // state, all the possible memory states are possible initial states of the corresponding catch block(s).)
    NodeToUnsignedMap* GetMemorySsaMap(MemoryKind memoryKind)
    {
        if (memoryKind == GcHeap && byrefStatesMatchGcHeapStates)
        {
            // Use the same map for GCHeap and ByrefExposed when their states match.
            memoryKind = ByrefExposed;
        }

        assert(memoryKind < MemoryKindCount);
        Compiler* compRoot = impInlineRoot();
        if (compRoot->m_memorySsaMap[memoryKind] == nullptr)
        {
            // Create a CompAllocator that labels sub-structure with CMK_MemorySsaMap, and use that for allocation.
            CompAllocator ialloc(getAllocator(CMK_MemorySsaMap));
            compRoot->m_memorySsaMap[memoryKind] = new (ialloc) NodeToUnsignedMap(ialloc);
        }
        return compRoot->m_memorySsaMap[memoryKind];
    }

    // The Refany type is the only struct type whose structure is implicitly assumed by IL.  We need its fields.
    CORINFO_CLASS_HANDLE m_refAnyClass;
    CORINFO_FIELD_HANDLE GetRefanyDataField()
    {
        if (m_refAnyClass == nullptr)
        {
            m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
        }
        return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
    }
    CORINFO_FIELD_HANDLE GetRefanyTypeField()
    {
        if (m_refAnyClass == nullptr)
        {
            m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
        }
        return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
    }

#if VARSET_COUNTOPS
    static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
#endif
#if ALLVARSET_COUNTOPS
    static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
#endif

    static HelperCallProperties s_helperCallProperties;

#ifdef UNIX_AMD64_ABI
    static var_types GetTypeFromClassificationAndSizes(SystemVClassificationType classType, int size);
    static var_types GetEightByteType(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
                                      unsigned                                                   slotNum);

    static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
                                    var_types*                                                 type0,
                                    var_types*                                                 type1,
                                    unsigned __int8*                                           offset0,
                                    unsigned __int8*                                           offset1);

    void GetStructTypeOffset(CORINFO_CLASS_HANDLE typeHnd,
                             var_types*           type0,
                             var_types*           type1,
                             unsigned __int8*     offset0,
                             unsigned __int8*     offset1);

#endif // defined(UNIX_AMD64_ABI)

    void fgMorphMultiregStructArgs(GenTreeCall* call);
    GenTree* fgMorphMultiregStructArg(CallArg* arg);

    bool killGCRefs(GenTree* tree);
}; // end of class Compiler

//---------------------------------------------------------------------------------------------------------------------
// GenTreeVisitor: a flexible tree walker implemented using the curiously-recurring-template pattern.
//
// This class implements a configurable walker for IR trees. There are five configuration options (defaults values are
// shown in parentheses):
//
// - ComputeStack (false): when true, the walker will push each node onto the `m_ancestors` stack. "Ancestors" is a bit
//                         of a misnomer, as the first entry will always be the current node.
//
// - DoPreOrder (false): when true, the walker will invoke `TVisitor::PreOrderVisit` with the current node as an
//                       argument before visiting the node's operands.
//
// - DoPostOrder (false): when true, the walker will invoke `TVisitor::PostOrderVisit` with the current node as an
//                        argument after visiting the node's operands.
//
// - DoLclVarsOnly (false): when true, the walker will only invoke `TVisitor::PreOrderVisit` for lclVar nodes.
//                          `DoPreOrder` must be true if this option is true.
//
// - UseExecutionOrder (false): when true, then walker will visit a node's operands in execution order (e.g. if a
//                              binary operator has the `GTF_REVERSE_OPS` flag set, the second operand will be
//                              visited before the first).
//
// At least one of `DoPreOrder` and `DoPostOrder` must be specified.
//
// A simple pre-order visitor might look something like the following:
//
//     class CountingVisitor final : public GenTreeVisitor<CountingVisitor>
//     {
//     public:
//         enum
//         {
//             DoPreOrder = true
//         };
//
//         unsigned m_count;
//
//         CountingVisitor(Compiler* compiler)
//             : GenTreeVisitor<CountingVisitor>(compiler), m_count(0)
//         {
//         }
//
//         Compiler::fgWalkResult PreOrderVisit(GenTree* node)
//         {
//             m_count++;
//         }
//     };
//
// This visitor would then be used like so:
//
//     CountingVisitor countingVisitor(compiler);
//     countingVisitor.WalkTree(root);
//
template <typename TVisitor>
class GenTreeVisitor
{
protected:
    typedef Compiler::fgWalkResult fgWalkResult;

    enum
    {
        ComputeStack      = false,
        DoPreOrder        = false,
        DoPostOrder       = false,
        DoLclVarsOnly     = false,
        UseExecutionOrder = false,
    };

    Compiler*            m_compiler;
    ArrayStack<GenTree*> m_ancestors;

    GenTreeVisitor(Compiler* compiler) : m_compiler(compiler), m_ancestors(compiler->getAllocator(CMK_ArrayStack))
    {
        assert(compiler != nullptr);

        static_assert_no_msg(TVisitor::DoPreOrder || TVisitor::DoPostOrder);
        static_assert_no_msg(!TVisitor::DoLclVarsOnly || TVisitor::DoPreOrder);
    }

    fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
    {
        return fgWalkResult::WALK_CONTINUE;
    }

    fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
    {
        return fgWalkResult::WALK_CONTINUE;
    }

public:
    fgWalkResult WalkTree(GenTree** use, GenTree* user)
    {
        assert(use != nullptr);

        GenTree* node = *use;

        if (TVisitor::ComputeStack)
        {
            m_ancestors.Push(node);
        }

        fgWalkResult result = fgWalkResult::WALK_CONTINUE;
        if (TVisitor::DoPreOrder && !TVisitor::DoLclVarsOnly)
        {
            result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
            if (result == fgWalkResult::WALK_ABORT)
            {
                return result;
            }

            node = *use;
            if ((node == nullptr) || (result == fgWalkResult::WALK_SKIP_SUBTREES))
            {
                goto DONE;
            }
        }

        switch (node->OperGet())
        {
            // Leaf lclVars
            case GT_LCL_VAR:
            case GT_LCL_FLD:
            case GT_LCL_VAR_ADDR:
            case GT_LCL_FLD_ADDR:
                if (TVisitor::DoLclVarsOnly)
                {
                    result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                FALLTHROUGH;

            // Leaf nodes
            case GT_CATCH_ARG:
            case GT_LABEL:
            case GT_FTN_ADDR:
            case GT_RET_EXPR:
            case GT_CNS_INT:
            case GT_CNS_LNG:
            case GT_CNS_DBL:
            case GT_CNS_STR:
            case GT_CNS_VEC:
            case GT_MEMORYBARRIER:
            case GT_JMP:
            case GT_JCC:
            case GT_SETCC:
            case GT_NO_OP:
            case GT_START_NONGC:
            case GT_START_PREEMPTGC:
            case GT_PROF_HOOK:
#if !defined(FEATURE_EH_FUNCLETS)
            case GT_END_LFIN:
#endif // !FEATURE_EH_FUNCLETS
            case GT_PHI_ARG:
            case GT_JMPTABLE:
            case GT_CLS_VAR_ADDR:
            case GT_PHYSREG:
            case GT_EMITNOP:
            case GT_PINVOKE_PROLOG:
            case GT_PINVOKE_EPILOG:
            case GT_IL_OFFSET:
                break;

            // Lclvar unary operators
            case GT_STORE_LCL_VAR:
            case GT_STORE_LCL_FLD:
                if (TVisitor::DoLclVarsOnly)
                {
                    result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                FALLTHROUGH;

            // Standard unary operators
            case GT_NOT:
            case GT_NEG:
            case GT_BSWAP:
            case GT_BSWAP16:
            case GT_COPY:
            case GT_RELOAD:
            case GT_ARR_LENGTH:
            case GT_MDARR_LENGTH:
            case GT_MDARR_LOWER_BOUND:
            case GT_CAST:
            case GT_BITCAST:
            case GT_CKFINITE:
            case GT_LCLHEAP:
            case GT_ADDR:
            case GT_IND:
            case GT_OBJ:
            case GT_BLK:
            case GT_BOX:
            case GT_ALLOCOBJ:
            case GT_INIT_VAL:
            case GT_JTRUE:
            case GT_SWITCH:
            case GT_NULLCHECK:
            case GT_PUTARG_REG:
            case GT_PUTARG_STK:
            case GT_RETURNTRAP:
            case GT_NOP:
            case GT_FIELD:
            case GT_FIELD_ADDR:
            case GT_RETURN:
            case GT_RETFILT:
            case GT_RUNTIMELOOKUP:
            case GT_ARR_ADDR:
            case GT_KEEPALIVE:
            case GT_INC_SATURATE:
            {
                GenTreeUnOp* const unOp = node->AsUnOp();
                if (unOp->gtOp1 != nullptr)
                {
                    result = WalkTree(&unOp->gtOp1, unOp);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                break;
            }

            // Special nodes
            case GT_PHI:
                for (GenTreePhi::Use& use : node->AsPhi()->Uses())
                {
                    result = WalkTree(&use.NodeRef(), node);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                break;

            case GT_FIELD_LIST:
                for (GenTreeFieldList::Use& use : node->AsFieldList()->Uses())
                {
                    result = WalkTree(&use.NodeRef(), node);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                break;

            case GT_CMPXCHG:
            {
                GenTreeCmpXchg* const cmpXchg = node->AsCmpXchg();

                result = WalkTree(&cmpXchg->gtOpLocation, cmpXchg);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(&cmpXchg->gtOpValue, cmpXchg);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(&cmpXchg->gtOpComparand, cmpXchg);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                break;
            }

            case GT_ARR_ELEM:
            {
                GenTreeArrElem* const arrElem = node->AsArrElem();

                result = WalkTree(&arrElem->gtArrObj, arrElem);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }

                const unsigned rank = arrElem->gtArrRank;
                for (unsigned dim = 0; dim < rank; dim++)
                {
                    result = WalkTree(&arrElem->gtArrInds[dim], arrElem);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                break;
            }

            case GT_ARR_OFFSET:
            {
                GenTreeArrOffs* const arrOffs = node->AsArrOffs();

                result = WalkTree(&arrOffs->gtOffset, arrOffs);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(&arrOffs->gtIndex, arrOffs);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(&arrOffs->gtArrObj, arrOffs);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                break;
            }

            case GT_STORE_DYN_BLK:
            {
                GenTreeStoreDynBlk* const dynBlock = node->AsStoreDynBlk();

                GenTree** op1Use = &dynBlock->gtOp1;
                GenTree** op2Use = &dynBlock->gtOp2;
                GenTree** op3Use = &dynBlock->gtDynamicSize;

                result = WalkTree(op1Use, dynBlock);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(op2Use, dynBlock);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(op3Use, dynBlock);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                break;
            }

            case GT_CALL:
            {
                GenTreeCall* const call = node->AsCall();

                for (CallArg& arg : call->gtArgs.EarlyArgs())
                {
                    result = WalkTree(&arg.EarlyNodeRef(), call);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }

                for (CallArg& arg : call->gtArgs.LateArgs())
                {
                    result = WalkTree(&arg.LateNodeRef(), call);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }

                if (call->gtCallType == CT_INDIRECT)
                {
                    if (call->gtCallCookie != nullptr)
                    {
                        result = WalkTree(&call->gtCallCookie, call);
                        if (result == fgWalkResult::WALK_ABORT)
                        {
                            return result;
                        }
                    }

                    result = WalkTree(&call->gtCallAddr, call);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }

                if (call->gtControlExpr != nullptr)
                {
                    result = WalkTree(&call->gtControlExpr, call);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }

                break;
            }

#if defined(FEATURE_SIMD) || defined(FEATURE_HW_INTRINSICS)
#if defined(FEATURE_SIMD)
            case GT_SIMD:
#endif
#if defined(FEATURE_HW_INTRINSICS)
            case GT_HWINTRINSIC:
#endif
                if (TVisitor::UseExecutionOrder && node->IsReverseOp())
                {
                    assert(node->AsMultiOp()->GetOperandCount() == 2);

                    result = WalkTree(&node->AsMultiOp()->Op(2), node);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                    result = WalkTree(&node->AsMultiOp()->Op(1), node);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                else
                {
                    for (GenTree** use : node->AsMultiOp()->UseEdges())
                    {
                        result = WalkTree(use, node);
                        if (result == fgWalkResult::WALK_ABORT)
                        {
                            return result;
                        }
                    }
                }
                break;
#endif // defined(FEATURE_SIMD) || defined(FEATURE_HW_INTRINSICS)

            case GT_SELECT:
            {
                GenTreeConditional* const conditional = node->AsConditional();

                result = WalkTree(&conditional->gtCond, conditional);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(&conditional->gtOp1, conditional);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                result = WalkTree(&conditional->gtOp2, conditional);
                if (result == fgWalkResult::WALK_ABORT)
                {
                    return result;
                }
                break;
            }

            // Binary nodes
            default:
            {
                assert(node->OperIsBinary());

                GenTreeOp* const op = node->AsOp();

                GenTree** op1Use = &op->gtOp1;
                GenTree** op2Use = &op->gtOp2;

                if (TVisitor::UseExecutionOrder && node->IsReverseOp())
                {
                    std::swap(op1Use, op2Use);
                }

                if (*op1Use != nullptr)
                {
                    result = WalkTree(op1Use, op);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }

                if (*op2Use != nullptr)
                {
                    result = WalkTree(op2Use, op);
                    if (result == fgWalkResult::WALK_ABORT)
                    {
                        return result;
                    }
                }
                break;
            }
        }

    DONE:
        // Finally, visit the current node
        if (TVisitor::DoPostOrder)
        {
            result = reinterpret_cast<TVisitor*>(this)->PostOrderVisit(use, user);
        }

        if (TVisitor::ComputeStack)
        {
            m_ancestors.Pop();
        }

        return result;
    }
};

template <bool doPreOrder, bool doPostOrder, bool doLclVarsOnly, bool useExecutionOrder>
class GenericTreeWalker final
    : public GenTreeVisitor<GenericTreeWalker<doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>
{
public:
    enum
    {
        ComputeStack      = false,
        DoPreOrder        = doPreOrder,
        DoPostOrder       = doPostOrder,
        DoLclVarsOnly     = doLclVarsOnly,
        UseExecutionOrder = useExecutionOrder,
    };

private:
    Compiler::fgWalkData* m_walkData;

public:
    GenericTreeWalker(Compiler::fgWalkData* walkData)
        : GenTreeVisitor<GenericTreeWalker<doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>(
              walkData->compiler)
        , m_walkData(walkData)
    {
        assert(walkData != nullptr);
    }

    Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
    {
        m_walkData->parent = user;
        return m_walkData->wtprVisitorFn(use, m_walkData);
    }

    Compiler::fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
    {
        m_walkData->parent = user;
        return m_walkData->wtpoVisitorFn(use, m_walkData);
    }
};

// A dominator tree visitor implemented using the curiously-recurring-template pattern, similar to GenTreeVisitor.
template <typename TVisitor>
class DomTreeVisitor
{
protected:
    Compiler* const    m_compiler;
    DomTreeNode* const m_domTree;

    DomTreeVisitor(Compiler* compiler, DomTreeNode* domTree) : m_compiler(compiler), m_domTree(domTree)
    {
    }

    void Begin()
    {
    }

    void PreOrderVisit(BasicBlock* block)
    {
    }

    void PostOrderVisit(BasicBlock* block)
    {
    }

    void End()
    {
    }

public:
    //------------------------------------------------------------------------
    // WalkTree: Walk the dominator tree, starting from fgFirstBB.
    //
    // Notes:
    //    This performs a non-recursive, non-allocating walk of the tree by using
    //    DomTreeNode's firstChild and nextSibling links to locate the children of
    //    a node and BasicBlock's bbIDom parent link to go back up the tree when
    //    no more children are left.
    //
    //    Forests are also supported, provided that all the roots are chained via
    //    DomTreeNode::nextSibling to fgFirstBB.
    //
    void WalkTree()
    {
        static_cast<TVisitor*>(this)->Begin();

        for (BasicBlock *next, *block = m_compiler->fgFirstBB; block != nullptr; block = next)
        {
            static_cast<TVisitor*>(this)->PreOrderVisit(block);

            next = m_domTree[block->bbNum].firstChild;

            if (next != nullptr)
            {
                assert(next->bbIDom == block);
                continue;
            }

            do
            {
                static_cast<TVisitor*>(this)->PostOrderVisit(block);

                next = m_domTree[block->bbNum].nextSibling;

                if (next != nullptr)
                {
                    assert(next->bbIDom == block->bbIDom);
                    break;
                }

                block = block->bbIDom;

            } while (block != nullptr);
        }

        static_cast<TVisitor*>(this)->End();
    }
};

// EHClauses: adapter class for forward iteration of the exception handling table using range-based `for`, e.g.:
//    for (EHblkDsc* const ehDsc : EHClauses(compiler))
//
class EHClauses
{
    EHblkDsc* m_begin;
    EHblkDsc* m_end;

    // Forward iterator for the exception handling table entries. Iteration is in table order.
    //
    class iterator
    {
        EHblkDsc* m_ehDsc;

    public:
        iterator(EHblkDsc* ehDsc) : m_ehDsc(ehDsc)
        {
        }

        EHblkDsc* operator*() const
        {
            return m_ehDsc;
        }

        iterator& operator++()
        {
            ++m_ehDsc;
            return *this;
        }

        bool operator!=(const iterator& i) const
        {
            return m_ehDsc != i.m_ehDsc;
        }
    };

public:
    EHClauses(Compiler* comp) : m_begin(comp->compHndBBtab), m_end(comp->compHndBBtab + comp->compHndBBtabCount)
    {
        assert((m_begin != nullptr) || (m_begin == m_end));
    }

    iterator begin() const
    {
        return iterator(m_begin);
    }

    iterator end() const
    {
        return iterator(m_end);
    }
};

/*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                   Miscellaneous Compiler stuff                            XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

class StringPrinter
{
    CompAllocator m_alloc;
    char*         m_buffer;
    size_t        m_bufferMax;
    size_t        m_bufferIndex = 0;

    void Grow(size_t newSize);

public:
    StringPrinter(CompAllocator alloc, char* buffer = nullptr, size_t bufferMax = 0)
        : m_alloc(alloc), m_buffer(buffer), m_bufferMax(bufferMax)
    {
        if ((m_buffer == nullptr) || (m_bufferMax == 0))
        {
            m_bufferMax = 128;
            m_buffer    = alloc.allocate<char>(m_bufferMax);
        }

        m_buffer[0] = '\0';
    }

    size_t GetLength()
    {
        return m_bufferIndex;
    }

    char* GetBuffer()
    {
        assert(m_buffer[GetLength()] == '\0');
        return m_buffer;
    }
    void Truncate(size_t newLength)
    {
        assert(newLength <= m_bufferIndex);
        m_bufferIndex           = newLength;
        m_buffer[m_bufferIndex] = '\0';
    }

    void Append(const char* str);
    void Append(char chr);
};

/*****************************************************************************
 *
 *  Variables to keep track of total code amounts.
 */

#if DISPLAY_SIZES

extern size_t grossVMsize;
extern size_t grossNCsize;
extern size_t totalNCsize;

extern unsigned genMethodICnt;
extern unsigned genMethodNCnt;
extern size_t   gcHeaderISize;
extern size_t   gcPtrMapISize;
extern size_t   gcHeaderNSize;
extern size_t   gcPtrMapNSize;

#endif // DISPLAY_SIZES

/*****************************************************************************
 *
 *  Variables to keep track of basic block counts (more data on 1 BB methods)
 */

#if COUNT_BASIC_BLOCKS
extern Histogram bbCntTable;
extern Histogram bbOneBBSizeTable;
#endif

/*****************************************************************************
 *
 *  Used by optFindNaturalLoops to gather statistical information such as
 *   - total number of natural loops
 *   - number of loops with 1, 2, ... exit conditions
 *   - number of loops that have an iterator (for like)
 *   - number of loops that have a constant iterator
 */

#if COUNT_LOOPS

extern unsigned  totalLoopMethods;        // counts the total number of methods that have natural loops
extern unsigned  maxLoopsPerMethod;       // counts the maximum number of loops a method has
extern unsigned  totalLoopOverflows;      // # of methods that identified more loops than we can represent
extern unsigned  totalLoopCount;          // counts the total number of natural loops
extern unsigned  totalUnnatLoopCount;     // counts the total number of (not-necessarily natural) loops
extern unsigned  totalUnnatLoopOverflows; // # of methods that identified more unnatural loops than we can represent
extern unsigned  iterLoopCount;           // counts the # of loops with an iterator (for like)
extern unsigned  constIterLoopCount;      // counts the # of loops with a constant iterator (for like)
extern bool      hasMethodLoops;          // flag to keep track if we already counted a method as having loops
extern unsigned  loopsThisMethod;         // counts the number of loops in the current method
extern bool      loopOverflowThisMethod;  // True if we exceeded the max # of loops in the method.
extern Histogram loopCountTable;          // Histogram of loop counts
extern Histogram loopExitCountTable;      // Histogram of loop exit counts

#endif // COUNT_LOOPS

/*****************************************************************************
 * variables to keep track of how many iterations we go in a dataflow pass
 */

#if DATAFLOW_ITER

extern unsigned CSEiterCount; // counts the # of iteration for the CSE dataflow
extern unsigned CFiterCount;  // counts the # of iteration for the Const Folding dataflow

#endif // DATAFLOW_ITER

#if MEASURE_BLOCK_SIZE
extern size_t genFlowNodeSize;
extern size_t genFlowNodeCnt;
#endif // MEASURE_BLOCK_SIZE

#if MEASURE_NODE_SIZE
struct NodeSizeStats
{
    void Init()
    {
        genTreeNodeCnt        = 0;
        genTreeNodeSize       = 0;
        genTreeNodeActualSize = 0;
    }

    // Count of tree nodes allocated.
    unsigned __int64 genTreeNodeCnt;

    // The size we allocate.
    unsigned __int64 genTreeNodeSize;

    // The actual size of the node. Note that the actual size will likely be smaller
    // than the allocated size, but we sometimes use SetOper()/ChangeOper() to change
    // a smaller node to a larger one. TODO-Cleanup: add stats on
    // SetOper()/ChangeOper() usage to quantify this.
    unsigned __int64 genTreeNodeActualSize;
};
extern NodeSizeStats genNodeSizeStats;        // Total node size stats
extern NodeSizeStats genNodeSizeStatsPerFunc; // Per-function node size stats
extern Histogram     genTreeNcntHist;
extern Histogram     genTreeNsizHist;
#endif // MEASURE_NODE_SIZE

/*****************************************************************************
 *  Count fatal errors (including noway_asserts).
 */

#if MEASURE_FATAL
extern unsigned fatal_badCode;
extern unsigned fatal_noWay;
extern unsigned fatal_implLimitation;
extern unsigned fatal_NOMEM;
extern unsigned fatal_noWayAssertBody;
#ifdef DEBUG
extern unsigned fatal_noWayAssertBodyArgs;
#endif // DEBUG
extern unsigned fatal_NYI;
#endif // MEASURE_FATAL

/*****************************************************************************
 * Codegen
 */

#ifdef TARGET_XARCH

const instruction INS_SHIFT_LEFT_LOGICAL  = INS_shl;
const instruction INS_SHIFT_RIGHT_LOGICAL = INS_shr;
const instruction INS_SHIFT_RIGHT_ARITHM  = INS_sar;

const instruction INS_AND             = INS_and;
const instruction INS_OR              = INS_or;
const instruction INS_XOR             = INS_xor;
const instruction INS_NEG             = INS_neg;
const instruction INS_TEST            = INS_test;
const instruction INS_MUL             = INS_imul;
const instruction INS_SIGNED_DIVIDE   = INS_idiv;
const instruction INS_UNSIGNED_DIVIDE = INS_div;
const instruction INS_BREAKPOINT      = INS_int3;
const instruction INS_ADDC            = INS_adc;
const instruction INS_SUBC            = INS_sbb;
const instruction INS_NOT             = INS_not;

#endif // TARGET_XARCH

#ifdef TARGET_ARM

const instruction INS_SHIFT_LEFT_LOGICAL  = INS_lsl;
const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
const instruction INS_SHIFT_RIGHT_ARITHM  = INS_asr;

const instruction INS_AND             = INS_and;
const instruction INS_OR              = INS_orr;
const instruction INS_XOR             = INS_eor;
const instruction INS_NEG             = INS_rsb;
const instruction INS_TEST            = INS_tst;
const instruction INS_MUL             = INS_mul;
const instruction INS_MULADD          = INS_mla;
const instruction INS_SIGNED_DIVIDE   = INS_sdiv;
const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
const instruction INS_BREAKPOINT      = INS_bkpt;
const instruction INS_ADDC            = INS_adc;
const instruction INS_SUBC            = INS_sbc;
const instruction INS_NOT             = INS_mvn;

const instruction INS_ABS  = INS_vabs;
const instruction INS_SQRT = INS_vsqrt;

#endif // TARGET_ARM

#ifdef TARGET_ARM64

const instruction        INS_MULADD = INS_madd;
inline const instruction INS_BREAKPOINT_osHelper()
{
    // GDB needs the encoding of brk #0
    // Windbg needs the encoding of brk #F000
    return TargetOS::IsUnix ? INS_brk_unix : INS_brk_windows;
}
#define INS_BREAKPOINT INS_BREAKPOINT_osHelper()

const instruction INS_ABS  = INS_fabs;
const instruction INS_SQRT = INS_fsqrt;

#endif // TARGET_ARM64

#ifdef TARGET_LOONGARCH64
const instruction INS_BREAKPOINT = INS_break;
const instruction INS_MULADD     = INS_fmadd_d; // NOTE: default is double.
const instruction INS_ABS        = INS_fabs_d;  // NOTE: default is double.
const instruction INS_SQRT       = INS_fsqrt_d; // NOTE: default is double.
#endif                                          // TARGET_LOONGARCH64

/*****************************************************************************/

extern const BYTE genTypeSizes[];
extern const BYTE genTypeAlignments[];
extern const BYTE genTypeStSzs[];
extern const BYTE genActualTypes[];

/*****************************************************************************/

#ifdef DEBUG
void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
#endif // DEBUG

#include "compiler.hpp" // All the shared inline functions

/*****************************************************************************/
#endif //_COMPILER_H_
/*****************************************************************************/