summaryrefslogtreecommitdiff
path: root/src/jit/gcencode.cpp
blob: a48f7451fbec2c741fdf96f9bd93c53f8246b69e (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX                                                                           XX
XX                          GCEncode                                         XX
XX                                                                           XX
XX   Logic to encode the JIT method header and GC pointer tables             XX
XX                                                                           XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/

#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop

#pragma warning(disable : 4244) // loss of data int -> char ..

#endif

#include "gcinfotypes.h"

ReturnKind GCTypeToReturnKind(CorInfoGCType gcType)
{
    switch (gcType)
    {
        case TYPE_GC_NONE:
            return RT_Scalar;
        case TYPE_GC_REF:
            return RT_Object;
        case TYPE_GC_BYREF:
            return RT_ByRef;
        default:
            _ASSERTE(!"TYP_GC_OTHER is unexpected");
            return RT_Illegal;
    }
}

ReturnKind GCInfo::getReturnKind()
{
    switch (compiler->info.compRetType)
    {
        case TYP_REF:
        case TYP_ARRAY:
            return RT_Object;
        case TYP_BYREF:
            return RT_ByRef;
        case TYP_STRUCT:
        {
            CORINFO_CLASS_HANDLE structType = compiler->info.compMethodInfo->args.retTypeClass;
            var_types            retType    = compiler->getReturnTypeForStruct(structType);

            switch (retType)
            {
                case TYP_ARRAY:
                    _ASSERTE(false && "TYP_ARRAY unexpected from getReturnTypeForStruct()");
                // fall through
                case TYP_REF:
                    return RT_Object;

                case TYP_BYREF:
                    return RT_ByRef;

                case TYP_STRUCT:
                    if (compiler->IsHfa(structType))
                    {
#ifdef _TARGET_X86_
                        _ASSERTE(false && "HFAs not expected for X86");
#endif // _TARGET_X86_

                        return RT_Scalar;
                    }
                    else
                    {
                        // Multi-reg return
                        BYTE gcPtrs[2] = {TYPE_GC_NONE, TYPE_GC_NONE};
                        compiler->info.compCompHnd->getClassGClayout(structType, gcPtrs);

                        ReturnKind first  = GCTypeToReturnKind((CorInfoGCType)gcPtrs[0]);
                        ReturnKind second = GCTypeToReturnKind((CorInfoGCType)gcPtrs[1]);

                        return GetStructReturnKind(first, second);
                    }

#ifdef _TARGET_X86_
                case TYP_FLOAT:
                case TYP_DOUBLE:
                    return RT_Float;
#endif // _TARGET_X86_
                default:
                    return RT_Scalar;
            }
        }

#ifdef _TARGET_X86_
        case TYP_FLOAT:
        case TYP_DOUBLE:
            return RT_Float;
#endif // _TARGET_X86_

        default:
            return RT_Scalar;
    }
}

#if !defined(JIT32_GCENCODER) || defined(WIN64EXCEPTIONS)

// gcMarkFilterVarsPinned - Walk all lifetimes and make it so that anything
//     live in a filter is marked as pinned (often by splitting the lifetime
//     so that *only* the filter region is pinned).  This should only be
//     called once (after generating all lifetimes, but before slot ids are
//     finalized.
//
// DevDiv 376329 - The VM has to double report filters and their parent frame
// because they occur during the 1st pass and the parent frame doesn't go dead
// until we start unwinding in the 2nd pass.
//
// Untracked locals will only be reported in non-filter funclets and the
// parent.
// Registers can't be double reported by 2 frames since they're different.
// That just leaves stack variables which might be double reported.
//
// Technically double reporting is only a problem when the GC has to relocate a
// reference. So we avoid that problem by marking all live tracked stack
// variables as pinned inside the filter.  Thus if they are double reported, it
// won't be a problem since they won't be double relocated.
//
void GCInfo::gcMarkFilterVarsPinned()
{
    assert(compiler->ehAnyFunclets());
    const EHblkDsc* endHBtab = &(compiler->compHndBBtab[compiler->compHndBBtabCount]);

    for (EHblkDsc* HBtab = compiler->compHndBBtab; HBtab < endHBtab; HBtab++)
    {
        if (HBtab->HasFilter())
        {
            const UNATIVE_OFFSET filterBeg = compiler->ehCodeOffset(HBtab->ebdFilter);
            const UNATIVE_OFFSET filterEnd = compiler->ehCodeOffset(HBtab->ebdHndBeg);

            for (varPtrDsc* varTmp = gcVarPtrList; varTmp != nullptr; varTmp = varTmp->vpdNext)
            {
                // Get hold of the variable's flags.
                const unsigned lowBits = varTmp->vpdVarNum & OFFSET_MASK;

                // Compute the actual lifetime offsets.
                const unsigned begOffs = varTmp->vpdBegOfs;
                const unsigned endOffs = varTmp->vpdEndOfs;

                // Special case: skip any 0-length lifetimes.
                if (endOffs == begOffs)
                {
                    continue;
                }

                // Skip lifetimes with no overlap with the filter
                if ((endOffs <= filterBeg) || (begOffs >= filterEnd))
                {
                    continue;
                }

#ifndef JIT32_GCENCODER
                // Because there is no nesting within filters, nothing
                // should be already pinned.
                // For JIT32_GCENCODER, we should not do this check as gcVarPtrList are always sorted by vpdBegOfs
                // which means that we could see some varPtrDsc that were already pinned by previous splitting.
                assert((lowBits & pinned_OFFSET_FLAG) == 0);
#endif // JIT32_GCENCODER

                if (begOffs < filterBeg)
                {
                    if (endOffs > filterEnd)
                    {
                        // The variable lifetime is starts before AND ends after
                        // the filter, so we need to create 2 new lifetimes:
                        //     (1) a pinned one for the filter
                        //     (2) a regular one for after the filter
                        // and then adjust the original lifetime to end before
                        // the filter.
                        CLANG_FORMAT_COMMENT_ANCHOR;

#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("Splitting lifetime for filter: [%04X, %04X).\nOld: ", filterBeg, filterEnd);
                            gcDumpVarPtrDsc(varTmp);
                        }
#endif // DEBUG

                        varPtrDsc* desc1 = new (compiler, CMK_GC) varPtrDsc;
                        desc1->vpdVarNum = varTmp->vpdVarNum | pinned_OFFSET_FLAG;
                        desc1->vpdBegOfs = filterBeg;
                        desc1->vpdEndOfs = filterEnd;

                        varPtrDsc* desc2 = new (compiler, CMK_GC) varPtrDsc;
                        desc2->vpdVarNum = varTmp->vpdVarNum;
                        desc2->vpdBegOfs = filterEnd;
                        desc2->vpdEndOfs = endOffs;

                        varTmp->vpdEndOfs = filterBeg;

                        gcInsertVarPtrDscSplit(desc1, varTmp);
                        gcInsertVarPtrDscSplit(desc2, varTmp);

#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("New (1 of 3): ");
                            gcDumpVarPtrDsc(varTmp);
                            printf("New (2 of 3): ");
                            gcDumpVarPtrDsc(desc1);
                            printf("New (3 of 3): ");
                            gcDumpVarPtrDsc(desc2);
                        }
#endif // DEBUG
                    }
                    else
                    {
                        // The variable lifetime started before the filter and ends
                        // somewhere inside it, so we only create 1 new lifetime,
                        // and then adjust the original lifetime to end before
                        // the filter.
                        CLANG_FORMAT_COMMENT_ANCHOR;

#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("Splitting lifetime for filter.\nOld: ");
                            gcDumpVarPtrDsc(varTmp);
                        }
#endif // DEBUG

                        varPtrDsc* desc = new (compiler, CMK_GC) varPtrDsc;
                        desc->vpdVarNum = varTmp->vpdVarNum | pinned_OFFSET_FLAG;
                        desc->vpdBegOfs = filterBeg;
                        desc->vpdEndOfs = endOffs;

                        varTmp->vpdEndOfs = filterBeg;

                        gcInsertVarPtrDscSplit(desc, varTmp);

#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("New (1 of 2): ");
                            gcDumpVarPtrDsc(varTmp);
                            printf("New (2 of 2): ");
                            gcDumpVarPtrDsc(desc);
                        }
#endif // DEBUG
                    }
                }
                else
                {
                    if (endOffs > filterEnd)
                    {
                        // The variable lifetime starts inside the filter and
                        // ends somewhere after it, so we create 1 new
                        // lifetime for the part inside the filter and adjust
                        // the start of the original lifetime to be the end
                        // of the filter
                        CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("Splitting lifetime for filter.\nOld: ");
                            gcDumpVarPtrDsc(varTmp);
                        }
#endif // DEBUG

                        varPtrDsc* desc = new (compiler, CMK_GC) varPtrDsc;
#ifndef JIT32_GCENCODER
                        desc->vpdVarNum = varTmp->vpdVarNum | pinned_OFFSET_FLAG;
                        desc->vpdBegOfs = begOffs;
                        desc->vpdEndOfs = filterEnd;

                        varTmp->vpdBegOfs = filterEnd;
#else
                        // Mark varTmp as pinned and generated use varPtrDsc(desc) as non-pinned
                        // since gcInsertVarPtrDscSplit requires that varTmp->vpdBegOfs must precede desc->vpdBegOfs
                        desc->vpdVarNum = varTmp->vpdVarNum;
                        desc->vpdBegOfs = filterEnd;
                        desc->vpdEndOfs = endOffs;

                        varTmp->vpdVarNum = varTmp->vpdVarNum | pinned_OFFSET_FLAG;
                        varTmp->vpdEndOfs = filterEnd;
#endif

                        gcInsertVarPtrDscSplit(desc, varTmp);

#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("New (1 of 2): ");
                            gcDumpVarPtrDsc(desc);
                            printf("New (2 of 2): ");
                            gcDumpVarPtrDsc(varTmp);
                        }
#endif // DEBUG
                    }
                    else
                    {
                        // The variable lifetime is completely within the filter,
                        // so just add the pinned flag.
                        CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("Pinning lifetime for filter.\nOld: ");
                            gcDumpVarPtrDsc(varTmp);
                        }
#endif // DEBUG

                        varTmp->vpdVarNum |= pinned_OFFSET_FLAG;
#ifdef DEBUG
                        if (compiler->verbose)
                        {
                            printf("New : ");
                            gcDumpVarPtrDsc(varTmp);
                        }
#endif // DEBUG
                    }
                }
            }
        } // HasFilter
    }     // Foreach EH
}

// gcInsertVarPtrDscSplit - Insert varPtrDsc that were created by splitting lifetimes
//     From gcMarkFilterVarsPinned, we may have created one or two `varPtrDsc`s due to splitting lifetimes
//     and these newly created `varPtrDsc`s should be inserted in gcVarPtrList.
//     However the semantics of this call depend on the architecture.
//
//     x86-GCInfo requires gcVarPtrList to be sorted by vpdBegOfs.
//     Every time inserting an entry we should keep the order of entries.
//     So this function searches for a proper insertion point from "begin" then "desc" gets inserted.
//
//     For other architectures(ones that uses GCInfo{En|De}coder), we don't need any sort.
//     So the argument "begin" is unused and "desc" will be inserted at the front of the list.

void GCInfo::gcInsertVarPtrDscSplit(varPtrDsc* desc, varPtrDsc* begin)
{
#ifndef JIT32_GCENCODER
    (void)begin;
    desc->vpdNext = gcVarPtrList;
    gcVarPtrList  = desc;
#else  // JIT32_GCENCODER
    // "desc" and "begin" must not be null
    assert(desc != nullptr);
    assert(begin != nullptr);

    // The caller must guarantee that desc's BegOfs is equal or greater than begin's
    // since we will search for insertion point from "begin"
    assert(desc->vpdBegOfs >= begin->vpdBegOfs);

    varPtrDsc* varTmp    = begin->vpdNext;
    varPtrDsc* varInsert = begin;

    while (varTmp != nullptr && varTmp->vpdBegOfs < desc->vpdBegOfs)
    {
        varInsert = varTmp;
        varTmp    = varTmp->vpdNext;
    }

    // Insert point cannot be null
    assert(varInsert != nullptr);

    desc->vpdNext      = varInsert->vpdNext;
    varInsert->vpdNext = desc;
#endif // JIT32_GCENCODER
}

#ifdef DEBUG

void GCInfo::gcDumpVarPtrDsc(varPtrDsc* desc)
{
    const int    offs   = (desc->vpdVarNum & ~OFFSET_MASK);
    const GCtype gcType = (desc->vpdVarNum & byref_OFFSET_FLAG) ? GCT_BYREF : GCT_GCREF;
    const bool   isPin  = (desc->vpdVarNum & pinned_OFFSET_FLAG) != 0;

    printf("[%08X] %s%s var at [%s", dspPtr(desc), GCtypeStr(gcType), isPin ? "pinned-ptr" : "",
           compiler->isFramePointerUsed() ? STR_FPBASE : STR_SPBASE);

    if (offs < 0)
    {
        printf("-%02XH", -offs);
    }
    else if (offs > 0)
    {
        printf("+%02XH", +offs);
    }

    printf("] live from %04X to %04X\n", desc->vpdBegOfs, desc->vpdEndOfs);
}

#endif // DEBUG

#endif // !defined(JIT32_GCENCODER) || defined(WIN64EXCEPTIONS)

#ifdef JIT32_GCENCODER

#include "emit.h"

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

/*****************************************************************************/
// (see jit.h) #define REGEN_SHORTCUTS 0
// To Regenerate the compressed info header shortcuts, define REGEN_SHORTCUTS
// and use the following command line pipe/filter to give you the 128
// most useful encodings.
//
// find . -name regen.txt | xargs cat | grep InfoHdr | sort | uniq -c | sort -r | head -128

// (see jit.h) #define REGEN_CALLPAT 0
// To Regenerate the compressed info header shortcuts, define REGEN_CALLPAT
// and use the following command line pipe/filter to give you the 80
// most useful encodings.
//
// find . -name regen.txt | xargs cat | grep CallSite | sort | uniq -c | sort -r | head -80

#if REGEN_SHORTCUTS || REGEN_CALLPAT
static FILE*     logFile = NULL;
CRITICAL_SECTION logFileLock;
#endif

#if REGEN_CALLPAT
static void regenLog(unsigned codeDelta,
                     unsigned argMask,
                     unsigned regMask,
                     unsigned argCnt,
                     unsigned byrefArgMask,
                     unsigned byrefRegMask,
                     BYTE*    base,
                     unsigned enSize)
{
    CallPattern pat;

    pat.fld.argCnt    = (argCnt < 0xff) ? argCnt : 0xff;
    pat.fld.regMask   = (regMask < 0xff) ? regMask : 0xff;
    pat.fld.argMask   = (argMask < 0xff) ? argMask : 0xff;
    pat.fld.codeDelta = (codeDelta < 0xff) ? codeDelta : 0xff;

    if (logFile == NULL)
    {
        logFile = fopen("regen.txt", "a");
        InitializeCriticalSection(&logFileLock);
    }

    assert(((enSize > 0) && (enSize < 256)) && ((pat.val & 0xffffff) != 0xffffff));

    EnterCriticalSection(&logFileLock);

    fprintf(logFile, "CallSite( 0x%08x, 0x%02x%02x, 0x", pat.val, byrefArgMask, byrefRegMask);

    while (enSize > 0)
    {
        fprintf(logFile, "%02x", *base++);
        enSize--;
    }
    fprintf(logFile, "),\n");
    fflush(logFile);

    LeaveCriticalSection(&logFileLock);
}
#endif

#if REGEN_SHORTCUTS
static void regenLog(unsigned encoding, InfoHdr* header, InfoHdr* state)
{
    if (logFile == NULL)
    {
        logFile = fopen("regen.txt", "a");
        InitializeCriticalSection(&logFileLock);
    }

    EnterCriticalSection(&logFileLock);

    fprintf(logFile, "InfoHdr( %2d, %2d, %1d, %1d, %1d,"
                     " %1d, %1d, %1d, %1d, %1d,"
                     " %1d, %1d, %1d, %1d, %1d, %1d,"
                     " %1d, %1d, %1d,"
                     " %1d, %2d, %2d,"
                     " %2d, %2d, %2d, %2d, %2d, %2d), \n",
            state->prologSize, state->epilogSize, state->epilogCount, state->epilogAtEnd, state->ediSaved,
            state->esiSaved, state->ebxSaved, state->ebpSaved, state->ebpFrame, state->interruptible,
            state->doubleAlign, state->security, state->handlers, state->localloc, state->editNcontinue, state->varargs,
            state->profCallbacks, state->genericsContext, state->genericsContextIsMethodDesc, state->returnKind,
            state->argCount, state->frameSize,
            (state->untrackedCnt <= SET_UNTRACKED_MAX) ? state->untrackedCnt : HAS_UNTRACKED,
            (state->varPtrTableSize == 0) ? 0 : HAS_VARPTR,
            (state->gsCookieOffset == INVALID_GS_COOKIE_OFFSET) ? 0 : HAS_GS_COOKIE_OFFSET,
            (state->syncStartOffset == INVALID_SYNC_OFFSET) ? 0 : HAS_SYNC_OFFSET,
            (state->syncStartOffset == INVALID_SYNC_OFFSET) ? 0 : HAS_SYNC_OFFSET,
            (state->revPInvokeOffset == INVALID_REV_PINVOKE_OFFSET) ? 0 : HAS_REV_PINVOKE_FRAME_OFFSET);

    fflush(logFile);

    LeaveCriticalSection(&logFileLock);
}
#endif

/*****************************************************************************
 *
 *  Given the four parameters return the index into the callPatternTable[]
 *  that is used to encoding these four items.  If an exact match cannot
 *  found then ignore the codeDelta and search the table again for a near
 *  match.
 *  Returns 0..79 for an exact match or
 *         (delta<<8) | (0..79) for a near match.
 *  A near match will be encoded using two bytes, the first byte will
 *  skip the adjustment delta that prevented an exact match and the
 *  rest of the delta plus the other three items are encoded in the
 *  second byte.
 */
int FASTCALL lookupCallPattern(unsigned argCnt, unsigned regMask, unsigned argMask, unsigned codeDelta)
{
    if ((argCnt <= CP_MAX_ARG_CNT) && (argMask <= CP_MAX_ARG_MASK))
    {
        CallPattern pat;

        pat.fld.argCnt    = argCnt;
        pat.fld.regMask   = regMask; // EBP,EBX,ESI,EDI
        pat.fld.argMask   = argMask;
        pat.fld.codeDelta = codeDelta;

        bool     codeDeltaOK = (pat.fld.codeDelta == codeDelta);
        unsigned bestDelta2  = 0xff;
        unsigned bestPattern = 0xff;
        unsigned patval      = pat.val;
        assert(sizeof(CallPattern) == sizeof(unsigned));

        const unsigned* curp = &callPatternTable[0];
        for (unsigned inx = 0; inx < 80; inx++, curp++)
        {
            unsigned curval = *curp;
            if ((patval == curval) && codeDeltaOK)
                return inx;

            if (((patval ^ curval) & 0xffffff) == 0)
            {
                unsigned delta2 = codeDelta - (curval >> 24);
                if (delta2 < bestDelta2)
                {
                    bestDelta2  = delta2;
                    bestPattern = inx;
                }
            }
        }

        if (bestPattern != 0xff)
        {
            return (bestDelta2 << 8) | bestPattern;
        }
    }
    return -1;
}

static bool initNeeded3(unsigned cur, unsigned tgt, unsigned max, unsigned* hint)
{
    assert(cur != tgt);

    unsigned tmp = tgt;
    unsigned nib = 0;
    unsigned cnt = 0;

    while (tmp > max)
    {
        nib = tmp & 0x07;
        tmp >>= 3;
        if (tmp == cur)
        {
            *hint = nib;
            return false;
        }
        cnt++;
    }

    *hint = tmp;
    return true;
}

static bool initNeeded4(unsigned cur, unsigned tgt, unsigned max, unsigned* hint)
{
    assert(cur != tgt);

    unsigned tmp = tgt;
    unsigned nib = 0;
    unsigned cnt = 0;

    while (tmp > max)
    {
        nib = tmp & 0x0f;
        tmp >>= 4;
        if (tmp == cur)
        {
            *hint = nib;
            return false;
        }
        cnt++;
    }

    *hint = tmp;
    return true;
}

static int bigEncoding3(unsigned cur, unsigned tgt, unsigned max)
{
    assert(cur != tgt);

    unsigned tmp = tgt;
    unsigned nib = 0;
    unsigned cnt = 0;

    while (tmp > max)
    {
        nib = tmp & 0x07;
        tmp >>= 3;
        if (tmp == cur)
            break;
        cnt++;
    }
    return cnt;
}

static int bigEncoding4(unsigned cur, unsigned tgt, unsigned max)
{
    assert(cur != tgt);

    unsigned tmp = tgt;
    unsigned nib = 0;
    unsigned cnt = 0;

    while (tmp > max)
    {
        nib = tmp & 0x0f;
        tmp >>= 4;
        if (tmp == cur)
            break;
        cnt++;
    }
    return cnt;
}

BYTE FASTCALL encodeHeaderNext(const InfoHdr& header, InfoHdr* state, BYTE& codeSet)
{
    BYTE encoding = 0xff;
    codeSet       = 1; // codeSet is 1 or 2, depending on whether the returned encoding
                       // corresponds to InfoHdrAdjust, or InfoHdrAdjust2 enumerations.

    if (state->argCount != header.argCount)
    {
        // We have one-byte encodings for 0..8
        if (header.argCount <= SET_ARGCOUNT_MAX)
        {
            state->argCount = header.argCount;
            encoding        = SET_ARGCOUNT + header.argCount;
            goto DO_RETURN;
        }
        else
        {
            unsigned hint;
            if (initNeeded4(state->argCount, header.argCount, SET_ARGCOUNT_MAX, &hint))
            {
                assert(hint <= SET_ARGCOUNT_MAX);
                state->argCount = hint;
                encoding        = SET_ARGCOUNT + hint;
                goto DO_RETURN;
            }
            else
            {
                assert(hint <= 0xf);
                state->argCount <<= 4;
                state->argCount += hint;
                encoding = NEXT_FOUR_ARGCOUNT + hint;
                goto DO_RETURN;
            }
        }
    }

    if (state->frameSize != header.frameSize)
    {
        // We have one-byte encodings for 0..7
        if (header.frameSize <= SET_FRAMESIZE_MAX)
        {
            state->frameSize = header.frameSize;
            encoding         = SET_FRAMESIZE + header.frameSize;
            goto DO_RETURN;
        }
        else
        {
            unsigned hint;
            if (initNeeded4(state->frameSize, header.frameSize, SET_FRAMESIZE_MAX, &hint))
            {
                assert(hint <= SET_FRAMESIZE_MAX);
                state->frameSize = hint;
                encoding         = SET_FRAMESIZE + hint;
                goto DO_RETURN;
            }
            else
            {
                assert(hint <= 0xf);
                state->frameSize <<= 4;
                state->frameSize += hint;
                encoding = NEXT_FOUR_FRAMESIZE + hint;
                goto DO_RETURN;
            }
        }
    }

    if ((state->epilogCount != header.epilogCount) || (state->epilogAtEnd != header.epilogAtEnd))
    {
        if (header.epilogCount > SET_EPILOGCNT_MAX)
            IMPL_LIMITATION("More than SET_EPILOGCNT_MAX epilogs");

        state->epilogCount = header.epilogCount;
        state->epilogAtEnd = header.epilogAtEnd;
        encoding           = SET_EPILOGCNT + header.epilogCount * 2;
        if (header.epilogAtEnd)
            encoding++;
        goto DO_RETURN;
    }

    if (state->varPtrTableSize != header.varPtrTableSize)
    {
        assert(state->varPtrTableSize == 0 || state->varPtrTableSize == HAS_VARPTR);

        if (state->varPtrTableSize == 0)
        {
            state->varPtrTableSize = HAS_VARPTR;
            encoding               = FLIP_VAR_PTR_TABLE_SZ;
            goto DO_RETURN;
        }
        else if (header.varPtrTableSize == 0)
        {
            state->varPtrTableSize = 0;
            encoding               = FLIP_VAR_PTR_TABLE_SZ;
            goto DO_RETURN;
        }
    }

    if (state->untrackedCnt != header.untrackedCnt)
    {
        assert(state->untrackedCnt <= SET_UNTRACKED_MAX || state->untrackedCnt == HAS_UNTRACKED);

        // We have one-byte encodings for 0..3
        if (header.untrackedCnt <= SET_UNTRACKED_MAX)
        {
            state->untrackedCnt = header.untrackedCnt;
            encoding            = SET_UNTRACKED + header.untrackedCnt;
            goto DO_RETURN;
        }
        else if (state->untrackedCnt != HAS_UNTRACKED)
        {
            state->untrackedCnt = HAS_UNTRACKED;
            encoding            = FFFF_UNTRACKED_CNT;
            goto DO_RETURN;
        }
    }

    if (state->epilogSize != header.epilogSize)
    {
        // We have one-byte encodings for 0..10
        if (header.epilogSize <= SET_EPILOGSIZE_MAX)
        {
            state->epilogSize = header.epilogSize;
            encoding          = SET_EPILOGSIZE + header.epilogSize;
            goto DO_RETURN;
        }
        else
        {
            unsigned hint;
            if (initNeeded3(state->epilogSize, header.epilogSize, SET_EPILOGSIZE_MAX, &hint))
            {
                assert(hint <= SET_EPILOGSIZE_MAX);
                state->epilogSize = hint;
                encoding          = SET_EPILOGSIZE + hint;
                goto DO_RETURN;
            }
            else
            {
                assert(hint <= 0x7);
                state->epilogSize <<= 3;
                state->epilogSize += hint;
                encoding = NEXT_THREE_EPILOGSIZE + hint;
                goto DO_RETURN;
            }
        }
    }

    if (state->prologSize != header.prologSize)
    {
        // We have one-byte encodings for 0..16
        if (header.prologSize <= SET_PROLOGSIZE_MAX)
        {
            state->prologSize = header.prologSize;
            encoding          = SET_PROLOGSIZE + header.prologSize;
            goto DO_RETURN;
        }
        else
        {
            unsigned hint;
            assert(SET_PROLOGSIZE_MAX > 15);
            if (initNeeded3(state->prologSize, header.prologSize, 15, &hint))
            {
                assert(hint <= 15);
                state->prologSize = hint;
                encoding          = SET_PROLOGSIZE + hint;
                goto DO_RETURN;
            }
            else
            {
                assert(hint <= 0x7);
                state->prologSize <<= 3;
                state->prologSize += hint;
                encoding = NEXT_THREE_PROLOGSIZE + hint;
                goto DO_RETURN;
            }
        }
    }

    if (state->ediSaved != header.ediSaved)
    {
        state->ediSaved = header.ediSaved;
        encoding        = FLIP_EDI_SAVED;
        goto DO_RETURN;
    }

    if (state->esiSaved != header.esiSaved)
    {
        state->esiSaved = header.esiSaved;
        encoding        = FLIP_ESI_SAVED;
        goto DO_RETURN;
    }

    if (state->ebxSaved != header.ebxSaved)
    {
        state->ebxSaved = header.ebxSaved;
        encoding        = FLIP_EBX_SAVED;
        goto DO_RETURN;
    }

    if (state->ebpSaved != header.ebpSaved)
    {
        state->ebpSaved = header.ebpSaved;
        encoding        = FLIP_EBP_SAVED;
        goto DO_RETURN;
    }

    if (state->ebpFrame != header.ebpFrame)
    {
        state->ebpFrame = header.ebpFrame;
        encoding        = FLIP_EBP_FRAME;
        goto DO_RETURN;
    }

    if (state->interruptible != header.interruptible)
    {
        state->interruptible = header.interruptible;
        encoding             = FLIP_INTERRUPTIBLE;
        goto DO_RETURN;
    }

#if DOUBLE_ALIGN
    if (state->doubleAlign != header.doubleAlign)
    {
        state->doubleAlign = header.doubleAlign;
        encoding           = FLIP_DOUBLE_ALIGN;
        goto DO_RETURN;
    }
#endif

    if (state->security != header.security)
    {
        state->security = header.security;
        encoding        = FLIP_SECURITY;
        goto DO_RETURN;
    }

    if (state->handlers != header.handlers)
    {
        state->handlers = header.handlers;
        encoding        = FLIP_HANDLERS;
        goto DO_RETURN;
    }

    if (state->localloc != header.localloc)
    {
        state->localloc = header.localloc;
        encoding        = FLIP_LOCALLOC;
        goto DO_RETURN;
    }

    if (state->editNcontinue != header.editNcontinue)
    {
        state->editNcontinue = header.editNcontinue;
        encoding             = FLIP_EDITnCONTINUE;
        goto DO_RETURN;
    }

    if (state->varargs != header.varargs)
    {
        state->varargs = header.varargs;
        encoding       = FLIP_VARARGS;
        goto DO_RETURN;
    }

    if (state->profCallbacks != header.profCallbacks)
    {
        state->profCallbacks = header.profCallbacks;
        encoding             = FLIP_PROF_CALLBACKS;
        goto DO_RETURN;
    }

    if (state->genericsContext != header.genericsContext)
    {
        state->genericsContext = header.genericsContext;
        encoding               = FLIP_HAS_GENERICS_CONTEXT;
        goto DO_RETURN;
    }

    if (state->genericsContextIsMethodDesc != header.genericsContextIsMethodDesc)
    {
        state->genericsContextIsMethodDesc = header.genericsContextIsMethodDesc;
        encoding                           = FLIP_GENERICS_CONTEXT_IS_METHODDESC;
        goto DO_RETURN;
    }

    if (GCInfoEncodesReturnKind() && (state->returnKind != header.returnKind))
    {
        state->returnKind = header.returnKind;
        codeSet           = 2; // Two byte encoding
        encoding          = header.returnKind;
        _ASSERTE(encoding < SET_RET_KIND_MAX);
        goto DO_RETURN;
    }

    if (state->gsCookieOffset != header.gsCookieOffset)
    {
        assert(state->gsCookieOffset == INVALID_GS_COOKIE_OFFSET || state->gsCookieOffset == HAS_GS_COOKIE_OFFSET);

        if (state->gsCookieOffset == INVALID_GS_COOKIE_OFFSET)
        {
            // header.gsCookieOffset is non-zero. We can set it
            // to zero using FLIP_HAS_GS_COOKIE
            state->gsCookieOffset = HAS_GS_COOKIE_OFFSET;
            encoding              = FLIP_HAS_GS_COOKIE;
            goto DO_RETURN;
        }
        else if (header.gsCookieOffset == INVALID_GS_COOKIE_OFFSET)
        {
            state->gsCookieOffset = INVALID_GS_COOKIE_OFFSET;
            encoding              = FLIP_HAS_GS_COOKIE;
            goto DO_RETURN;
        }
    }

    if (state->syncStartOffset != header.syncStartOffset)
    {
        assert(state->syncStartOffset == INVALID_SYNC_OFFSET || state->syncStartOffset == HAS_SYNC_OFFSET);

        if (state->syncStartOffset == INVALID_SYNC_OFFSET)
        {
            // header.syncStartOffset is non-zero. We can set it
            // to zero using FLIP_SYNC
            state->syncStartOffset = HAS_SYNC_OFFSET;
            encoding               = FLIP_SYNC;
            goto DO_RETURN;
        }
        else if (header.syncStartOffset == INVALID_SYNC_OFFSET)
        {
            state->syncStartOffset = INVALID_SYNC_OFFSET;
            encoding               = FLIP_SYNC;
            goto DO_RETURN;
        }
    }

    if (GCInfoEncodesRevPInvokeFrame() && (state->revPInvokeOffset != header.revPInvokeOffset))
    {
        assert(state->revPInvokeOffset == INVALID_REV_PINVOKE_OFFSET ||
               state->revPInvokeOffset == HAS_REV_PINVOKE_FRAME_OFFSET);

        if (state->revPInvokeOffset == INVALID_REV_PINVOKE_OFFSET)
        {
            // header.revPInvokeOffset is non-zero.
            state->revPInvokeOffset = HAS_REV_PINVOKE_FRAME_OFFSET;
            encoding                = FLIP_REV_PINVOKE_FRAME;
            goto DO_RETURN;
        }
        else if (header.revPInvokeOffset == INVALID_REV_PINVOKE_OFFSET)
        {
            state->revPInvokeOffset = INVALID_REV_PINVOKE_OFFSET;
            encoding                = FLIP_REV_PINVOKE_FRAME;
            goto DO_RETURN;
        }
    }

DO_RETURN:
    _ASSERTE(encoding < MORE_BYTES_TO_FOLLOW);
    if (!state->isHeaderMatch(header))
        encoding |= MORE_BYTES_TO_FOLLOW;

    return encoding;
}

static int measureDistance(const InfoHdr& header, const InfoHdrSmall* p, int closeness)
{
    int distance = 0;

    if (p->untrackedCnt != header.untrackedCnt)
    {
        if (header.untrackedCnt > 3)
        {
            if (p->untrackedCnt != HAS_UNTRACKED)
                distance += 1;
        }
        else
        {
            distance += 1;
        }
        if (distance >= closeness)
            return distance;
    }

    if (p->varPtrTableSize != header.varPtrTableSize)
    {
        if (header.varPtrTableSize != 0)
        {
            if (p->varPtrTableSize != HAS_VARPTR)
                distance += 1;
        }
        else
        {
            assert(p->varPtrTableSize == HAS_VARPTR);
            distance += 1;
        }
        if (distance >= closeness)
            return distance;
    }

    if (p->frameSize != header.frameSize)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;

        // We have one-byte encodings for 0..7
        if (header.frameSize > SET_FRAMESIZE_MAX)
        {
            distance += bigEncoding4(p->frameSize, header.frameSize, SET_FRAMESIZE_MAX);
            if (distance >= closeness)
                return distance;
        }
    }

    if (p->argCount != header.argCount)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;

        // We have one-byte encodings for 0..8
        if (header.argCount > SET_ARGCOUNT_MAX)
        {
            distance += bigEncoding4(p->argCount, header.argCount, SET_ARGCOUNT_MAX);
            if (distance >= closeness)
                return distance;
        }
    }

    if (p->prologSize != header.prologSize)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;

        // We have one-byte encodings for 0..16
        if (header.prologSize > SET_PROLOGSIZE_MAX)
        {
            assert(SET_PROLOGSIZE_MAX > 15);
            distance += bigEncoding3(p->prologSize, header.prologSize, 15);
            if (distance >= closeness)
                return distance;
        }
    }

    if (p->epilogSize != header.epilogSize)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
        // We have one-byte encodings for 0..10
        if (header.epilogSize > SET_EPILOGSIZE_MAX)
        {
            distance += bigEncoding3(p->epilogSize, header.epilogSize, SET_EPILOGSIZE_MAX);
            if (distance >= closeness)
                return distance;
        }
    }

    if ((p->epilogCount != header.epilogCount) || (p->epilogAtEnd != header.epilogAtEnd))
    {
        distance += 1;
        if (distance >= closeness)
            return distance;

        if (header.epilogCount > SET_EPILOGCNT_MAX)
            IMPL_LIMITATION("More than SET_EPILOGCNT_MAX epilogs");
    }

    if (p->ediSaved != header.ediSaved)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->esiSaved != header.esiSaved)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->ebxSaved != header.ebxSaved)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->ebpSaved != header.ebpSaved)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->ebpFrame != header.ebpFrame)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->interruptible != header.interruptible)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

#if DOUBLE_ALIGN
    if (p->doubleAlign != header.doubleAlign)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }
#endif

    if (p->security != header.security)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->handlers != header.handlers)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->localloc != header.localloc)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->editNcontinue != header.editNcontinue)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->varargs != header.varargs)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->profCallbacks != header.profCallbacks)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->genericsContext != header.genericsContext)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->genericsContextIsMethodDesc != header.genericsContextIsMethodDesc)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (p->returnKind != header.returnKind)
    {
        // Setting the ReturnKind requires two bytes of encoding.
        distance += 2;
        if (distance >= closeness)
            return distance;
    }

    if (header.gsCookieOffset != INVALID_GS_COOKIE_OFFSET)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (header.syncStartOffset != INVALID_SYNC_OFFSET)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    if (header.revPInvokeOffset != INVALID_REV_PINVOKE_OFFSET)
    {
        distance += 1;
        if (distance >= closeness)
            return distance;
    }

    return distance;
}

// DllMain calls gcInitEncoderLookupTable to fill in this table
/* extern */ int infoHdrLookup[IH_MAX_PROLOG_SIZE + 2];

/* static */ void GCInfo::gcInitEncoderLookupTable()
{
    const InfoHdrSmall* p  = &infoHdrShortcut[0];
    int                 lo = -1;
    int                 hi = 0;
    int                 n;

    for (n = 0; n < 128; n++, p++)
    {
        if (p->prologSize != lo)
        {
            if (p->prologSize < lo)
            {
                assert(p->prologSize == 0);
                hi = IH_MAX_PROLOG_SIZE;
            }
            else
                hi = p->prologSize;

            assert(hi <= IH_MAX_PROLOG_SIZE);

            while (lo < hi)
                infoHdrLookup[++lo] = n;

            if (lo == IH_MAX_PROLOG_SIZE)
                break;
        }
    }

    assert(lo == IH_MAX_PROLOG_SIZE);
    assert(infoHdrLookup[IH_MAX_PROLOG_SIZE] < 128);

    while (p->prologSize == lo)
    {
        n++;
        if (n >= 128)
            break;
        p++;
    }

    infoHdrLookup[++lo] = n;

#ifdef DEBUG
    //
    // We do some other DEBUG only validity checks here
    //
    assert(callCommonDelta[0] < callCommonDelta[1]);
    assert(callCommonDelta[1] < callCommonDelta[2]);
    assert(callCommonDelta[2] < callCommonDelta[3]);
    assert(sizeof(CallPattern) == sizeof(unsigned));
    unsigned maxMarks = 0;
    for (unsigned inx = 0; inx < 80; inx++)
    {
        CallPattern pat;
        pat.val = callPatternTable[inx];

        assert(pat.fld.codeDelta <= CP_MAX_CODE_DELTA);
        if (pat.fld.codeDelta == CP_MAX_CODE_DELTA)
            maxMarks |= 0x01;

        assert(pat.fld.argCnt <= CP_MAX_ARG_CNT);
        if (pat.fld.argCnt == CP_MAX_ARG_CNT)
            maxMarks |= 0x02;

        assert(pat.fld.argMask <= CP_MAX_ARG_MASK);
        if (pat.fld.argMask == CP_MAX_ARG_MASK)
            maxMarks |= 0x04;
    }
    assert(maxMarks == 0x07);
#endif
}

const int NO_CACHED_HEADER = -1;

BYTE FASTCALL encodeHeaderFirst(const InfoHdr& header, InfoHdr* state, int* more, int* pCached)
{
    // First try the cached value for an exact match, if there is one
    //
    int                 n = *pCached;
    const InfoHdrSmall* p;

    if (n != NO_CACHED_HEADER)
    {
        p = &infoHdrShortcut[n];
        if (p->isHeaderMatch(header))
        {
            // exact match found
            GetInfoHdr(n, state);
            *more = 0;
            return n;
        }
    }

    // Next search the table for an exact match
    // Only search entries that have a matching prolog size
    // Note: lo and hi are saved here as they specify the
    // range of entries that have the correct prolog size
    //
    unsigned psz = header.prologSize;
    int      lo  = 0;
    int      hi  = 0;

    if (psz <= IH_MAX_PROLOG_SIZE)
    {
        lo = infoHdrLookup[psz];
        hi = infoHdrLookup[psz + 1];
        p  = &infoHdrShortcut[lo];
        for (n = lo; n < hi; n++, p++)
        {
            assert(psz == p->prologSize);
            if (p->isHeaderMatch(header))
            {
                // exact match found
                GetInfoHdr(n, state);
                *pCached = n; // cache the value
                *more    = 0;
                return n;
            }
        }
    }

    //
    // no exact match in infoHdrShortcut[]
    //
    // find the nearest entry in the table
    //
    int nearest   = -1;
    int closeness = 255; // (i.e. not very close)

    //
    // Calculate the minimum acceptable distance
    // if we find an entry that is at least this close
    // we will stop the search and use that value
    //
    int min_acceptable_distance = 1;

    if (header.frameSize > SET_FRAMESIZE_MAX)
    {
        ++min_acceptable_distance;
        if (header.frameSize > 32)
            ++min_acceptable_distance;
    }
    if (header.argCount > SET_ARGCOUNT_MAX)
    {
        ++min_acceptable_distance;
        if (header.argCount > 32)
            ++min_acceptable_distance;
    }

    // First try the cached value
    // and see if it meets the minimum acceptable distance
    //
    if (*pCached != NO_CACHED_HEADER)
    {
        p            = &infoHdrShortcut[*pCached];
        int distance = measureDistance(header, p, closeness);
        assert(distance > 0);
        if (distance <= min_acceptable_distance)
        {
            GetInfoHdr(*pCached, state);
            *more = distance;
            return 0x80 | *pCached;
        }
        else
        {
            closeness = distance;
            nearest   = *pCached;
        }
    }

    // Then try the ones pointed to by [lo..hi),
    // (i.e. the ones that have the correct prolog size)
    //
    p = &infoHdrShortcut[lo];
    for (n = lo; n < hi; n++, p++)
    {
        if (n == *pCached)
            continue; // already tried this one
        int distance = measureDistance(header, p, closeness);
        assert(distance > 0);
        if (distance <= min_acceptable_distance)
        {
            GetInfoHdr(n, state);
            *pCached = n; // Cache this value
            *more    = distance;
            return 0x80 | n;
        }
        else if (distance < closeness)
        {
            closeness = distance;
            nearest   = n;
        }
    }

    int last = infoHdrLookup[IH_MAX_PROLOG_SIZE + 1];
    assert(last <= 128);

    // Then try all the rest [0..last-1]
    p = &infoHdrShortcut[0];
    for (n = 0; n < last; n++, p++)
    {
        if (n == *pCached)
            continue; // already tried this one
        if ((n >= lo) && (n < hi))
            continue; // already tried these
        int distance = measureDistance(header, p, closeness);
        assert(distance > 0);
        if (distance <= min_acceptable_distance)
        {
            GetInfoHdr(n, state);
            *pCached = n; // Cache this value
            *more    = distance;
            return 0x80 | n;
        }
        else if (distance < closeness)
        {
            closeness = distance;
            nearest   = n;
        }
    }

    //
    // If we reach here then there was no adjacent neighbor
    //  in infoHdrShortcut[], closeness indicate how many extra
    //  bytes we will need to encode this item.
    //
    assert((nearest >= 0) && (nearest <= 127));
    GetInfoHdr(nearest, state);
    *pCached = nearest; // Cache this value
    *more    = closeness;
    return 0x80 | nearest;
}

/*****************************************************************************
 *
 *  Write the initial part of the method info block. This is called twice;
 *  first to compute the size needed for the info (mask=0), the second time
 *  to actually generate the contents of the table (mask=-1,dest!=NULL).
 */

size_t GCInfo::gcInfoBlockHdrSave(
    BYTE* dest, int mask, unsigned methodSize, unsigned prologSize, unsigned epilogSize, InfoHdr* header, int* pCached)
{
#ifdef DEBUG
    if (compiler->verbose)
        printf("*************** In gcInfoBlockHdrSave()\n");
#endif
    size_t size = 0;

#if VERIFY_GC_TABLES
    *castto(dest, unsigned short*)++ = 0xFEEF;
    size += sizeof(short);
#endif

    /* Write the method size first (using between 1 and 5 bytes) */
    CLANG_FORMAT_COMMENT_ANCHOR;

#ifdef DEBUG
    if (compiler->verbose)
    {
        if (mask)
            printf("GCINFO: methodSize = %04X\n", methodSize);
        if (mask)
            printf("GCINFO: prologSize = %04X\n", prologSize);
        if (mask)
            printf("GCINFO: epilogSize = %04X\n", epilogSize);
    }
#endif

    size_t methSz = encodeUnsigned(dest, methodSize);
    size += methSz;
    dest += methSz & mask;

    //
    // New style InfoBlk Header
    //
    // Typically only uses one-byte to store everything.
    //

    if (mask == 0)
    {
        memset(header, 0, sizeof(InfoHdr));
        *pCached = NO_CACHED_HEADER;
    }

    assert(FitsIn<unsigned char>(prologSize));
    header->prologSize = static_cast<unsigned char>(prologSize);
    assert(FitsIn<unsigned char>(epilogSize));
    header->epilogSize  = static_cast<unsigned char>(epilogSize);
    header->epilogCount = compiler->getEmitter()->emitGetEpilogCnt();
    if (header->epilogCount != compiler->getEmitter()->emitGetEpilogCnt())
        IMPL_LIMITATION("emitGetEpilogCnt() does not fit in InfoHdr::epilogCount");
    header->epilogAtEnd = compiler->getEmitter()->emitHasEpilogEnd();

    if (compiler->codeGen->regSet.rsRegsModified(RBM_EDI))
        header->ediSaved = 1;
    if (compiler->codeGen->regSet.rsRegsModified(RBM_ESI))
        header->esiSaved = 1;
    if (compiler->codeGen->regSet.rsRegsModified(RBM_EBX))
        header->ebxSaved = 1;

    header->interruptible = compiler->codeGen->genInterruptible;

    if (!compiler->isFramePointerUsed())
    {
#if DOUBLE_ALIGN
        if (compiler->genDoubleAlign())
        {
            header->ebpSaved = true;
            assert(!compiler->codeGen->regSet.rsRegsModified(RBM_EBP));
        }
#endif
        if (compiler->codeGen->regSet.rsRegsModified(RBM_EBP))
        {
            header->ebpSaved = true;
        }
    }
    else
    {
        header->ebpSaved = true;
        header->ebpFrame = true;
    }

#if DOUBLE_ALIGN
    header->doubleAlign = compiler->genDoubleAlign();
#endif

    header->security = compiler->opts.compNeedSecurityCheck;

    header->handlers = compiler->ehHasCallableHandlers();
    header->localloc = compiler->compLocallocUsed;

    header->varargs         = compiler->info.compIsVarArgs;
    header->profCallbacks   = compiler->info.compProfilerCallback;
    header->editNcontinue   = compiler->opts.compDbgEnC;
    header->genericsContext = compiler->lvaReportParamTypeArg();
    header->genericsContextIsMethodDesc =
        header->genericsContext && (compiler->info.compMethodInfo->options & (CORINFO_GENERICS_CTXT_FROM_METHODDESC));

    if (GCInfoEncodesReturnKind())
    {
        ReturnKind returnKind = getReturnKind();
        _ASSERTE(IsValidReturnKind(returnKind) && "Return Kind must be valid");
        _ASSERTE(!IsStructReturnKind(returnKind) && "Struct Return Kinds Unexpected for JIT32");
        _ASSERTE(((int)returnKind < (int)SET_RET_KIND_MAX) && "ReturnKind has no legal encoding");
        header->returnKind = returnKind;
    }

    header->gsCookieOffset = INVALID_GS_COOKIE_OFFSET;
    if (compiler->getNeedsGSSecurityCookie())
    {
        assert(compiler->lvaGSSecurityCookie != BAD_VAR_NUM);
        int stkOffs            = compiler->lvaTable[compiler->lvaGSSecurityCookie].lvStkOffs;
        header->gsCookieOffset = compiler->isFramePointerUsed() ? -stkOffs : stkOffs;
        assert(header->gsCookieOffset != INVALID_GS_COOKIE_OFFSET);
    }

    header->syncStartOffset = INVALID_SYNC_OFFSET;
    header->syncEndOffset   = INVALID_SYNC_OFFSET;
#ifndef UNIX_X86_ABI
    // JIT is responsible for synchronization on funclet-based EH model that x86/Linux uses.
    if (compiler->info.compFlags & CORINFO_FLG_SYNCH)
    {
        assert(compiler->syncStartEmitCookie != NULL);
        header->syncStartOffset = compiler->getEmitter()->emitCodeOffset(compiler->syncStartEmitCookie, 0);
        assert(header->syncStartOffset != INVALID_SYNC_OFFSET);

        assert(compiler->syncEndEmitCookie != NULL);
        header->syncEndOffset = compiler->getEmitter()->emitCodeOffset(compiler->syncEndEmitCookie, 0);
        assert(header->syncEndOffset != INVALID_SYNC_OFFSET);

        assert(header->syncStartOffset < header->syncEndOffset);
        // synchronized methods can't have more than 1 epilog
        assert(header->epilogCount <= 1);
    }
#endif

    header->revPInvokeOffset = INVALID_REV_PINVOKE_OFFSET;

    assert((compiler->compArgSize & 0x3) == 0);

    size_t argCount =
        (compiler->compArgSize - (compiler->codeGen->intRegState.rsCalleeRegArgCount * sizeof(void*))) / sizeof(void*);
    assert(argCount <= MAX_USHORT_SIZE_T);
    header->argCount = static_cast<unsigned short>(argCount);

    header->frameSize = compiler->compLclFrameSize / sizeof(int);
    if (header->frameSize != (compiler->compLclFrameSize / sizeof(int)))
        IMPL_LIMITATION("compLclFrameSize does not fit in InfoHdr::frameSize");

    if (mask == 0)
    {
        gcCountForHeader((UNALIGNED unsigned int*)&header->untrackedCnt,
                         (UNALIGNED unsigned int*)&header->varPtrTableSize);
    }

    //
    // If the high-order bit of headerEncoding is set
    // then additional bytes will update the InfoHdr state
    // until the fully state is encoded
    //
    InfoHdr state;
    int     more           = 0;
    BYTE    headerEncoding = encodeHeaderFirst(*header, &state, &more, pCached);
    ++size;
    if (mask)
    {
#if REGEN_SHORTCUTS
        regenLog(headerEncoding, header, &state);
#endif
        *dest++ = headerEncoding;

        BYTE encoding = headerEncoding;
        BYTE codeSet  = 1;
        while (encoding & MORE_BYTES_TO_FOLLOW)
        {
            encoding = encodeHeaderNext(*header, &state, codeSet);

#if REGEN_SHORTCUTS
            regenLog(headerEncoding, header, &state);
#endif
            _ASSERTE(codeSet == 1 || codeSet == 2 && "Encoding must correspond to InfoHdrAdjust or InfoHdrAdjust2");
            if (codeSet == 2)
            {
                *dest++ = NEXT_OPCODE | MORE_BYTES_TO_FOLLOW;
                ++size;
            }

            *dest++ = encoding;
            ++size;
        }
    }
    else
    {
        size += more;
    }

    if (header->untrackedCnt > SET_UNTRACKED_MAX)
    {
        unsigned count = header->untrackedCnt;
        unsigned sz    = encodeUnsigned(mask ? dest : NULL, count);
        size += sz;
        dest += (sz & mask);
    }

    if (header->varPtrTableSize != 0)
    {
        unsigned count = header->varPtrTableSize;
        unsigned sz    = encodeUnsigned(mask ? dest : NULL, count);
        size += sz;
        dest += (sz & mask);
    }

    if (header->gsCookieOffset != INVALID_GS_COOKIE_OFFSET)
    {
        assert(mask == 0 || state.gsCookieOffset == HAS_GS_COOKIE_OFFSET);
        unsigned offset = header->gsCookieOffset;
        unsigned sz     = encodeUnsigned(mask ? dest : NULL, offset);
        size += sz;
        dest += (sz & mask);
    }

    if (header->syncStartOffset != INVALID_SYNC_OFFSET)
    {
        assert(mask == 0 || state.syncStartOffset == HAS_SYNC_OFFSET);

        {
            unsigned offset = header->syncStartOffset;
            unsigned sz     = encodeUnsigned(mask ? dest : NULL, offset);
            size += sz;
            dest += (sz & mask);
        }

        {
            unsigned offset = header->syncEndOffset;
            unsigned sz     = encodeUnsigned(mask ? dest : NULL, offset);
            size += sz;
            dest += (sz & mask);
        }
    }

    if (header->epilogCount)
    {
        /* Generate table unless one epilog at the end of the method */

        if (header->epilogAtEnd == 0 || header->epilogCount != 1)
        {
#if VERIFY_GC_TABLES
            *castto(dest, unsigned short*)++ = 0xFACE;
            size += sizeof(short);
#endif

            /* Simply write a sorted array of offsets using encodeUDelta */

            gcEpilogTable      = mask ? dest : NULL;
            gcEpilogPrevOffset = 0;

            size_t sz = compiler->getEmitter()->emitGenEpilogLst(gcRecordEpilog, this);

            /* Add the size of the epilog table to the total size */

            size += sz;
            dest += (sz & mask);
        }
    }

#if DISPLAY_SIZES

    if (mask)
    {
        if (compiler->codeGen->genInterruptible)
        {
            genMethodICnt++;
        }
        else
        {
            genMethodNCnt++;
        }
    }

#endif // DISPLAY_SIZES

    return size;
}

/*****************************************************************************
 *
 *  Return the size of the pointer tracking tables.
 */

size_t GCInfo::gcPtrTableSize(const InfoHdr& header, unsigned codeSize, size_t* pArgTabOffset)
{
    BYTE temp[16 + 1];
#ifdef DEBUG
    temp[16] = 0xAB; // Set some marker
#endif

    /* Compute the total size of the tables */

    size_t size = gcMakeRegPtrTable(temp, 0, header, codeSize, pArgTabOffset);

    assert(temp[16] == 0xAB); // Check that marker didnt get overwritten

    return size;
}

/*****************************************************************************
 * Encode the callee-saved registers into 3 bits.
 */

unsigned gceEncodeCalleeSavedRegs(unsigned regs)
{
    unsigned encodedRegs = 0;

    if (regs & RBM_EBX)
        encodedRegs |= 0x04;
    if (regs & RBM_ESI)
        encodedRegs |= 0x02;
    if (regs & RBM_EDI)
        encodedRegs |= 0x01;

    return encodedRegs;
}

/*****************************************************************************
 * Is the next entry for a byref pointer. If so, emit the prefix for the
 * interruptible encoding. Check only for pushes and registers
 */

inline BYTE* gceByrefPrefixI(GCInfo::regPtrDsc* rpd, BYTE* dest)
{
    // For registers, we don't need a prefix if it is going dead.
    assert(rpd->rpdArg || rpd->rpdCompiler.rpdDel == 0);

    if (!rpd->rpdArg || rpd->rpdArgType == GCInfo::rpdARG_PUSH)
        if (rpd->rpdGCtypeGet() == GCT_BYREF)
            *dest++ = 0xBF;

    return dest;
}

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

/* These functions are needed to work around a VC5.0 compiler bug */
/* DO NOT REMOVE, unless you are sure that the free build works   */
static int zeroFN()
{
    return 0;
}
static int (*zeroFunc)() = zeroFN;

/*****************************************************************************
 *  Modelling of the GC ptrs pushed on the stack
 */

typedef unsigned pasMaskType;
#define BITS_IN_pasMask (BITS_IN_BYTE * sizeof(pasMaskType))
#define HIGHEST_pasMask_BIT (((pasMaskType)0x1) << (BITS_IN_pasMask - 1))

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

class PendingArgsStack
{
public:
    PendingArgsStack(unsigned maxDepth, Compiler* pComp);

    void pasPush(GCtype gcType);
    void pasPop(unsigned count);
    void pasKill(unsigned gcCount);

    unsigned pasCurDepth()
    {
        return pasDepth;
    }
    pasMaskType pasArgMask()
    {
        assert(pasDepth <= BITS_IN_pasMask);
        return pasBottomMask;
    }
    pasMaskType pasByrefArgMask()
    {
        assert(pasDepth <= BITS_IN_pasMask);
        return pasByrefBottomMask;
    }
    bool pasHasGCptrs();

    // Use these in the case where there actually are more ptrs than pasArgMask
    unsigned pasEnumGCoffsCount();
#define pasENUM_START ((unsigned)-1)
#define pasENUM_LAST ((unsigned)-2)
#define pasENUM_END ((unsigned)-3)
    unsigned pasEnumGCoffs(unsigned iter, unsigned* offs);

protected:
    unsigned pasMaxDepth;

    unsigned pasDepth;

    pasMaskType pasBottomMask;      // The first 32 args
    pasMaskType pasByrefBottomMask; // byref qualifier for pasBottomMask

    BYTE*    pasTopArray;       // More than 32 args are represented here
    unsigned pasPtrsInTopArray; // How many GCptrs here
};

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

PendingArgsStack::PendingArgsStack(unsigned maxDepth, Compiler* pComp)
    : pasMaxDepth(maxDepth)
    , pasDepth(0)
    , pasBottomMask(0)
    , pasByrefBottomMask(0)
    , pasTopArray(NULL)
    , pasPtrsInTopArray(0)
{
    /* Do we need an array as well as the mask ? */

    if (pasMaxDepth > BITS_IN_pasMask)
        pasTopArray = (BYTE*)pComp->compGetMemA(pasMaxDepth - BITS_IN_pasMask);
}

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

void PendingArgsStack::pasPush(GCtype gcType)
{
    assert(pasDepth < pasMaxDepth);

    if (pasDepth < BITS_IN_pasMask)
    {
        /* Shift the mask */

        pasBottomMask <<= 1;
        pasByrefBottomMask <<= 1;

        if (needsGC(gcType))
        {
            pasBottomMask |= 1;

            if (gcType == GCT_BYREF)
                pasByrefBottomMask |= 1;
        }
    }
    else
    {
        /* Push on array */

        pasTopArray[pasDepth - BITS_IN_pasMask] = (BYTE)gcType;

        if (gcType)
            pasPtrsInTopArray++;
    }

    pasDepth++;
}

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

void PendingArgsStack::pasPop(unsigned count)
{
    assert(pasDepth >= count);

    /* First pop from array (if applicable) */

    for (/**/; (pasDepth > BITS_IN_pasMask) && count; pasDepth--, count--)
    {
        unsigned topIndex = pasDepth - BITS_IN_pasMask - 1;

        GCtype topArg = (GCtype)pasTopArray[topIndex];

        if (needsGC(topArg))
            pasPtrsInTopArray--;
    }
    if (count == 0)
        return;

    /* Now un-shift the mask */

    assert(pasPtrsInTopArray == 0);
    assert(count <= BITS_IN_pasMask);

    if (count == BITS_IN_pasMask) // (x>>32) is a nop on x86. So special-case it
    {
        pasBottomMask = pasByrefBottomMask = 0;
        pasDepth                           = 0;
    }
    else
    {
        pasBottomMask >>= count;
        pasByrefBottomMask >>= count;
        pasDepth -= count;
    }
}

//-----------------------------------------------------------------------------
// Kill (but don't pop) the top 'gcCount' args

void PendingArgsStack::pasKill(unsigned gcCount)
{
    assert(gcCount != 0);

    /* First kill args in array (if any) */

    for (unsigned curPos = pasDepth; (curPos > BITS_IN_pasMask) && gcCount; curPos--)
    {
        unsigned curIndex = curPos - BITS_IN_pasMask - 1;

        GCtype curArg = (GCtype)pasTopArray[curIndex];

        if (needsGC(curArg))
        {
            pasTopArray[curIndex] = GCT_NONE;
            pasPtrsInTopArray--;
            gcCount--;
        }
    }

    /* Now kill bits from the mask */

    assert(pasPtrsInTopArray == 0);
    assert(gcCount <= BITS_IN_pasMask);

    for (unsigned bitPos = 1; gcCount; bitPos <<= 1)
    {
        assert(pasBottomMask != 0);

        if (pasBottomMask & bitPos)
        {
            pasBottomMask &= ~bitPos;
            pasByrefBottomMask &= ~bitPos;
            --gcCount;
        }
        else
        {
            assert(bitPos != HIGHEST_pasMask_BIT);
        }
    }
}

//-----------------------------------------------------------------------------
// Used for the case where there are more than BITS_IN_pasMask args on stack,
// but none are any pointers. May avoid reporting anything to GCinfo

bool PendingArgsStack::pasHasGCptrs()
{
    if (pasDepth <= BITS_IN_pasMask)
        return pasBottomMask != 0;
    else
        return pasBottomMask != 0 || pasPtrsInTopArray != 0;
}

//-----------------------------------------------------------------------------
//  Iterates over mask and array to return total count.
//  Use only when you are going to emit a table of the offsets

unsigned PendingArgsStack::pasEnumGCoffsCount()
{
    /* Should only be used in the worst case, when just the mask can't be used */

    assert(pasDepth > BITS_IN_pasMask && pasHasGCptrs());

    /* Count number of set bits in mask */

    unsigned count = 0;

    for (pasMaskType mask = 0x1, i = 0; i < BITS_IN_pasMask; mask <<= 1, i++)
    {
        if (mask & pasBottomMask)
            count++;
    }

    return count + pasPtrsInTopArray;
}

//-----------------------------------------------------------------------------
//  Initalize enumeration by passing in iter=pasENUM_START.
//  Continue by passing in the return value as the new value of iter
//  End of enumeration when pasENUM_END is returned
//  If return value != pasENUM_END, *offs is set to the offset for GCinfo

unsigned PendingArgsStack::pasEnumGCoffs(unsigned iter, unsigned* offs)
{
    if (iter == pasENUM_LAST)
        return pasENUM_END;

    unsigned i = (iter == pasENUM_START) ? pasDepth : iter;

    for (/**/; i > BITS_IN_pasMask; i--)
    {
        GCtype curArg = (GCtype)pasTopArray[i - BITS_IN_pasMask - 1];
        if (needsGC(curArg))
        {
            unsigned offset;

            offset = (pasDepth - i) * sizeof(void*);
            if (curArg == GCT_BYREF)
                offset |= byref_OFFSET_FLAG;

            *offs = offset;
            return i - 1;
        }
    }

    if (!pasBottomMask)
        return pasENUM_END;

    // Have we already processed some of the bits in pasBottomMask ?

    i = (iter == pasENUM_START || iter >= BITS_IN_pasMask) ? 0     // no
                                                           : iter; // yes

    for (pasMaskType mask = 0x1 << i; mask; i++, mask <<= 1)
    {
        if (mask & pasBottomMask)
        {
            unsigned lvl = (pasDepth > BITS_IN_pasMask) ? (pasDepth - BITS_IN_pasMask) : 0; // How many in pasTopArray[]
            lvl += i;

            unsigned offset;
            offset = lvl * sizeof(void*);
            if (mask & pasByrefBottomMask)
                offset |= byref_OFFSET_FLAG;

            *offs = offset;

            unsigned remMask = -int(mask << 1);
            return ((pasBottomMask & remMask) ? (i + 1) : pasENUM_LAST);
        }
    }

    assert(!"Shouldnt reach here");
    return pasENUM_END;
}

/*****************************************************************************
 *
 *  Generate the register pointer map, and return its total size in bytes. If
 *  'mask' is 0, we don't actually store any data in 'dest' (except for one
 *  entry, which is never more than 10 bytes), so this can be used to merely
 *  compute the size of the table.
 */

#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable : 21000) // Suppress PREFast warning about overly large function
#endif
size_t GCInfo::gcMakeRegPtrTable(BYTE* dest, int mask, const InfoHdr& header, unsigned codeSize, size_t* pArgTabOffset)
{
    unsigned count;

    unsigned   varNum;
    LclVarDsc* varDsc;

    unsigned pass;

    size_t   totalSize = 0;
    unsigned lastOffset;

    bool thisKeptAliveIsInUntracked = false;

    /* The mask should be all 0's or all 1's */

    assert(mask == 0 || mask == -1);

    /* Start computing the total size of the table */

    BOOL emitArgTabOffset = (header.varPtrTableSize != 0 || header.untrackedCnt > SET_UNTRACKED_MAX);
    if (mask != 0 && emitArgTabOffset)
    {
        assert(*pArgTabOffset <= MAX_UNSIGNED_SIZE_T);
        unsigned sz = encodeUnsigned(dest, static_cast<unsigned>(*pArgTabOffset));
        dest += sz;
        totalSize += sz;
    }

#if VERIFY_GC_TABLES
    if (mask)
    {
        *(short*)dest = (short)0xBEEF;
        dest += sizeof(short);
    }
    totalSize += sizeof(short);
#endif

    /**************************************************************************
     *
     *                      Untracked ptr variables
     *
     **************************************************************************
     */

    count = 0;
    for (pass = 0; pass < 2; pass++)
    {
        /* If pass==0, generate the count
         * If pass==1, write the table of untracked pointer variables.
         */

        int lastoffset = 0;
        if (pass == 1)
        {
            assert(count == header.untrackedCnt);
            if (header.untrackedCnt == 0)
                break; // No entries, break exits the loop since pass==1
        }

        /* Count&Write untracked locals and non-enregistered args */

        for (varNum = 0, varDsc = compiler->lvaTable; varNum < compiler->lvaCount; varNum++, varDsc++)
        {
            if (compiler->lvaIsFieldOfDependentlyPromotedStruct(varDsc))
            {
                // Field local of a PROMOTION_TYPE_DEPENDENT struct must have been
                // reported through its parent local
                continue;
            }

            if (varTypeIsGC(varDsc->TypeGet()))
            {
                /* Do we have an argument or local variable? */
                if (!varDsc->lvIsParam)
                {
                    // If is is pinned, it must be an untracked local
                    assert(!varDsc->lvPinned || !varDsc->lvTracked);

                    if (varDsc->lvTracked || !varDsc->lvOnFrame)
                        continue;
                }
                else
                {
/* Stack-passed arguments which are not enregistered
 * are always reported in this "untracked stack
 * pointers" section of the GC info even if lvTracked==true
 */

/* Has this argument been enregistered? */
#ifndef LEGACY_BACKEND
                    if (!varDsc->lvOnFrame)
#else  // LEGACY_BACKEND
                    if (varDsc->lvRegister)
#endif // LEGACY_BACKEND
                    {
                        /* if a CEE_JMP has been used, then we need to report all the arguments
                           even if they are enregistered, since we will be using this value
                           in JMP call.  Note that this is subtle as we require that
                           argument offsets are always fixed up properly even if lvRegister
                           is set */
                        if (!compiler->compJmpOpUsed)
                            continue;
                    }
                    else
                    {
                        if (!varDsc->lvOnFrame)
                        {
                            /* If this non-enregistered pointer arg is never
                             * used, we don't need to report it
                             */
                            assert(varDsc->lvRefCnt == 0); // This assert is currently a known issue for X86-RyuJit
                            continue;
                        }
                        else if (varDsc->lvIsRegArg && varDsc->lvTracked)
                        {
                            /* If this register-passed arg is tracked, then
                             * it has been allocated space near the other
                             * pointer variables and we have accurate life-
                             * time info. It will be reported with
                             * gcVarPtrList in the "tracked-pointer" section
                             */

                            continue;
                        }
                    }
                }

#ifndef WIN64EXCEPTIONS
                // For WIN64EXCEPTIONS, "this" must always be in untracked variables
                // so we cannot have "this" in variable lifetimes
                if (compiler->lvaIsOriginalThisArg(varNum) && compiler->lvaKeepAliveAndReportThis())

                {
                    // Encoding of untracked variables does not support reporting
                    // "this". So report it as a tracked variable with a liveness
                    // extending over the entire method.

                    thisKeptAliveIsInUntracked = true;
                    continue;
                }
#endif

                if (pass == 0)
                    count++;
                else
                {
                    int offset;
                    assert(pass == 1);

                    offset = varDsc->lvStkOffs;
#if DOUBLE_ALIGN
                    // For genDoubleAlign(), locals are addressed relative to ESP and
                    // arguments are addressed relative to EBP.

                    if (compiler->genDoubleAlign() && varDsc->lvIsParam && !varDsc->lvIsRegArg)
                        offset += compiler->codeGen->genTotalFrameSize();
#endif

                    // The lower bits of the offset encode properties of the stk ptr

                    assert(~OFFSET_MASK % sizeof(offset) == 0);

                    if (varDsc->TypeGet() == TYP_BYREF)
                    {
                        // Or in byref_OFFSET_FLAG for 'byref' pointer tracking
                        offset |= byref_OFFSET_FLAG;
                    }

                    if (varDsc->lvPinned)
                    {
                        // Or in pinned_OFFSET_FLAG for 'pinned' pointer tracking
                        offset |= pinned_OFFSET_FLAG;
                    }

                    int encodedoffset = lastoffset - offset;
                    lastoffset        = offset;

                    if (mask == 0)
                        totalSize += encodeSigned(NULL, encodedoffset);
                    else
                    {
                        unsigned sz = encodeSigned(dest, encodedoffset);
                        dest += sz;
                        totalSize += sz;
                    }
                }
            }

            // A struct will have gcSlots only if it is at least TARGET_POINTER_SIZE.
            if (varDsc->lvType == TYP_STRUCT && varDsc->lvOnFrame && (varDsc->lvExactSize >= TARGET_POINTER_SIZE))
            {
                unsigned slots  = compiler->lvaLclSize(varNum) / sizeof(void*);
                BYTE*    gcPtrs = compiler->lvaGetGcLayout(varNum);

                // walk each member of the array
                for (unsigned i = 0; i < slots; i++)
                {
                    if (gcPtrs[i] == TYPE_GC_NONE) // skip non-gc slots
                        continue;

                    if (pass == 0)
                        count++;
                    else
                    {
                        assert(pass == 1);

                        unsigned offset = varDsc->lvStkOffs + i * sizeof(void*);
#if DOUBLE_ALIGN
                        // For genDoubleAlign(), locals are addressed relative to ESP and
                        // arguments are addressed relative to EBP.

                        if (compiler->genDoubleAlign() && varDsc->lvIsParam && !varDsc->lvIsRegArg)
                            offset += compiler->codeGen->genTotalFrameSize();
#endif
                        if (gcPtrs[i] == TYPE_GC_BYREF)
                            offset |= byref_OFFSET_FLAG; // indicate it is a byref GC pointer

                        int encodedoffset = lastoffset - offset;
                        lastoffset        = offset;

                        if (mask == 0)
                            totalSize += encodeSigned(NULL, encodedoffset);
                        else
                        {
                            unsigned sz = encodeSigned(dest, encodedoffset);
                            dest += sz;
                            totalSize += sz;
                        }
                    }
                }
            }
        }

        /* Count&Write spill temps that hold pointers */

        assert(compiler->tmpAllFree());
        for (TempDsc* tempItem = compiler->tmpListBeg(); tempItem != nullptr; tempItem = compiler->tmpListNxt(tempItem))
        {
            if (varTypeIsGC(tempItem->tdTempType()))
            {
                if (pass == 0)
                    count++;
                else
                {
                    int offset;
                    assert(pass == 1);

                    offset = tempItem->tdTempOffs();

                    if (tempItem->tdTempType() == TYP_BYREF)
                    {
                        offset |= byref_OFFSET_FLAG;
                    }

                    int encodedoffset = lastoffset - offset;
                    lastoffset        = offset;

                    if (mask == 0)
                    {
                        totalSize += encodeSigned(NULL, encodedoffset);
                    }
                    else
                    {
                        unsigned sz = encodeSigned(dest, encodedoffset);
                        dest += sz;
                        totalSize += sz;
                    }
                }
            }
        }
    }

#if VERIFY_GC_TABLES
    if (mask)
    {
        *(short*)dest = (short)0xCAFE;
        dest += sizeof(short);
    }
    totalSize += sizeof(short);
#endif

    /**************************************************************************
     *
     *  Generate the table of stack pointer variable lifetimes.
     *
     *  In the first pass we'll count the lifetime entries and note
     *  whether there are any that don't fit in a small encoding. In
     *  the second pass we actually generate the table contents.
     *
     **************************************************************************
     */

    // First we check for the most common case - no lifetimes at all.

    if (header.varPtrTableSize == 0)
        goto DONE_VLT;

    varPtrDsc* varTmp;
    count = 0;

#ifndef WIN64EXCEPTIONS
    if (thisKeptAliveIsInUntracked)
    {
        count = 1;

        // Encoding of untracked variables does not support reporting
        // "this". So report it as a tracked variable with a liveness
        // extending over the entire method.

        assert(compiler->lvaTable[compiler->info.compThisArg].TypeGet() == TYP_REF);

        unsigned varOffs = compiler->lvaTable[compiler->info.compThisArg].lvStkOffs;

        /* For negative stack offsets we must reset the low bits,
         * take abs and then set them back */

        varOffs = abs(static_cast<int>(varOffs));
        varOffs |= this_OFFSET_FLAG;

        size_t sz = 0;
        sz        = encodeUnsigned(mask ? (dest + sz) : NULL, varOffs);
        sz += encodeUDelta(mask ? (dest + sz) : NULL, 0, 0);
        sz += encodeUDelta(mask ? (dest + sz) : NULL, codeSize, 0);

        dest += (sz & mask);
        totalSize += sz;
    }
#endif

    for (pass = 0; pass < 2; pass++)
    {
        /* If second pass, generate the count */

        if (pass)
        {
            assert(header.varPtrTableSize > 0);
            assert(header.varPtrTableSize == count);
        }

        /* We'll use a delta encoding for the lifetime offsets */

        lastOffset = 0;

        for (varTmp = gcVarPtrList; varTmp; varTmp = varTmp->vpdNext)
        {
            unsigned varOffs;
            unsigned lowBits;

            unsigned begOffs;
            unsigned endOffs;

            assert(~OFFSET_MASK % sizeof(void*) == 0);

            /* Get hold of the variable's stack offset */

            lowBits = varTmp->vpdVarNum & OFFSET_MASK;

            /* For negative stack offsets we must reset the low bits,
             * take abs and then set them back */

            varOffs = abs(static_cast<int>(varTmp->vpdVarNum & ~OFFSET_MASK));
            varOffs |= lowBits;

            /* Compute the actual lifetime offsets */

            begOffs = varTmp->vpdBegOfs;
            endOffs = varTmp->vpdEndOfs;

            /* Special case: skip any 0-length lifetimes */

            if (endOffs == begOffs)
                continue;

            /* Are we counting or generating? */

            if (!pass)
            {
                count++;
            }
            else
            {
                size_t sz = 0;
                sz        = encodeUnsigned(mask ? (dest + sz) : NULL, varOffs);
                sz += encodeUDelta(mask ? (dest + sz) : NULL, begOffs, lastOffset);
                sz += encodeUDelta(mask ? (dest + sz) : NULL, endOffs, begOffs);

                dest += (sz & mask);
                totalSize += sz;
            }

            /* The next entry will be relative to the one we just processed */

            lastOffset = begOffs;
        }
    }

DONE_VLT:

    if (pArgTabOffset != NULL)
        *pArgTabOffset = totalSize;

#if VERIFY_GC_TABLES
    if (mask)
    {
        *(short*)dest = (short)0xBABE;
        dest += sizeof(short);
    }
    totalSize += sizeof(short);
#endif

    if (!mask && emitArgTabOffset)
    {
        assert(*pArgTabOffset <= MAX_UNSIGNED_SIZE_T);
        totalSize += encodeUnsigned(NULL, static_cast<unsigned>(*pArgTabOffset));
    }

    /**************************************************************************
     *
     * Prepare to generate the pointer register/argument map
     *
     **************************************************************************
     */

    lastOffset = 0;

    if (compiler->codeGen->genInterruptible)
    {
#ifdef _TARGET_X86_
        assert(compiler->genFullPtrRegMap);

        unsigned ptrRegs = 0;

        regPtrDsc* genRegPtrTemp;

        /* Walk the list of pointer register/argument entries */

        for (genRegPtrTemp = gcRegPtrList; genRegPtrTemp; genRegPtrTemp = genRegPtrTemp->rpdNext)
        {
            BYTE* base = dest;

            unsigned nextOffset;
            DWORD    codeDelta;

            nextOffset = genRegPtrTemp->rpdOffs;

            /*
                Encoding table for methods that are fully interruptible

                The encoding used is as follows:

                ptr reg dead    00RRRDDD    [RRR != 100]
                ptr reg live    01RRRDDD    [RRR != 100]

            non-ptr arg push    10110DDD                    [SSS == 110]
                ptr arg push    10SSSDDD                    [SSS != 110] && [SSS != 111]
                ptr arg pop     11CCCDDD    [CCC != 000] && [CCC != 110] && [CCC != 111]
                little skip     11000DDD    [CCC == 000]
                bigger skip     11110BBB                    [CCC == 110]

                The values used in the above encodings are as follows:

                  DDD                 code offset delta from previous entry (0-7)
                  BBB                 bigger delta 000=8,001=16,010=24,...,111=64
                  RRR                 register number (EAX=000,ECX=001,EDX=010,EBX=011,
                                        EBP=101,ESI=110,EDI=111), ESP=100 is reserved
                  SSS                 argument offset from base of stack. This is
                                        redundant for frameless methods as we can
                                        infer it from the previous pushes+pops. However,
                                        for EBP-methods, we only report GC pushes, and
                                        so we need SSS
                  CCC                 argument count being popped (includes only ptrs for EBP methods)

                The following are the 'large' versions:

                  large delta skip        10111000 [0xB8] , encodeUnsigned(delta)

                  large     ptr arg push  11111000 [0xF8] , encodeUnsigned(pushCount)
                  large non-ptr arg push  11111001 [0xF9] , encodeUnsigned(pushCount)
                  large     ptr arg pop   11111100 [0xFC] , encodeUnsigned(popCount)
                  large         arg dead  11111101 [0xFD] , encodeUnsigned(popCount) for caller-pop args.
                                                              Any GC args go dead after the call,
                                                              but are still sitting on the stack

                  this pointer prefix     10111100 [0xBC]   the next encoding is a ptr live
                                                              or a ptr arg push
                                                              and contains the this pointer

                  interior or by-ref      10111111 [0xBF]   the next encoding is a ptr live
                       pointer prefix                         or a ptr arg push
                                                              and contains an interior
                                                              or by-ref pointer


                  The value 11111111 [0xFF] indicates the end of the table.
            */

            codeDelta = nextOffset - lastOffset;
            assert((int)codeDelta >= 0);

            // If the code delta is between 8 and (64+7),
            // generate a 'bigger delta' encoding

            if ((codeDelta >= 8) && (codeDelta <= (64 + 7)))
            {
                unsigned biggerDelta = ((codeDelta - 8) & 0x38) + 8;
                *dest++              = 0xF0 | ((biggerDelta - 8) >> 3);
                lastOffset += biggerDelta;
                codeDelta &= 0x07;
            }

            // If the code delta is still bigger than 7,
            // generate a 'large code delta' encoding

            if (codeDelta > 7)
            {
                *dest++ = 0xB8;
                dest += encodeUnsigned(dest, codeDelta);
                codeDelta = 0;

                /* Remember the new 'last' offset */

                lastOffset = nextOffset;
            }

            /* Is this a pointer argument or register entry? */

            if (genRegPtrTemp->rpdArg)
            {
                if (genRegPtrTemp->rpdArgTypeGet() == rpdARG_KILL)
                {
                    if (codeDelta)
                    {
                        /*
                            Use the small encoding:
                            little delta skip       11000DDD    [0xC0]
                         */

                        assert((codeDelta & 0x7) == codeDelta);
                        *dest++ = 0xC0 | (BYTE)codeDelta;

                        /* Remember the new 'last' offset */

                        lastOffset = nextOffset;
                    }

                    /* Caller-pop arguments are dead after call but are still
                       sitting on the stack */

                    *dest++ = 0xFD;
                    assert(genRegPtrTemp->rpdPtrArg != 0);
                    dest += encodeUnsigned(dest, genRegPtrTemp->rpdPtrArg);
                }
                else if (genRegPtrTemp->rpdPtrArg < 6 && genRegPtrTemp->rpdGCtypeGet())
                {
                    /* Is the argument offset/count smaller than 6 ? */

                    dest = gceByrefPrefixI(genRegPtrTemp, dest);

                    if (genRegPtrTemp->rpdArgTypeGet() == rpdARG_PUSH || (genRegPtrTemp->rpdPtrArg != 0))
                    {
                        /*
                          Use the small encoding:

                            ptr arg push 10SSSDDD [SSS != 110] && [SSS != 111]
                            ptr arg pop  11CCCDDD [CCC != 110] && [CCC != 111]
                         */

                        bool isPop = genRegPtrTemp->rpdArgTypeGet() == rpdARG_POP;

                        *dest++ = 0x80 | (BYTE)codeDelta | genRegPtrTemp->rpdPtrArg << 3 | isPop << 6;

                        /* Remember the new 'last' offset */

                        lastOffset = nextOffset;
                    }
                    else
                    {
                        assert(!"Check this");
                    }
                }
                else if (genRegPtrTemp->rpdGCtypeGet() == GCT_NONE)
                {
                    /*
                        Use the small encoding:
`                        non-ptr arg push 10110DDD [0xB0] (push of sizeof(int))
                     */

                    assert((codeDelta & 0x7) == codeDelta);
                    *dest++ = 0xB0 | (BYTE)codeDelta;
#ifndef UNIX_X86_ABI
                    assert(!compiler->isFramePointerUsed());
#endif

                    /* Remember the new 'last' offset */

                    lastOffset = nextOffset;
                }
                else
                {
                    /* Will have to use large encoding;
                     *   first do the code delta
                     */

                    if (codeDelta)
                    {
                        /*
                            Use the small encoding:
                            little delta skip       11000DDD    [0xC0]
                         */

                        assert((codeDelta & 0x7) == codeDelta);
                        *dest++ = 0xC0 | (BYTE)codeDelta;
                    }

                    /*
                        Now append a large argument record:

                            large ptr arg push  11111000 [0xF8]
                            large ptr arg pop   11111100 [0xFC]
                     */

                    bool isPop = genRegPtrTemp->rpdArgTypeGet() == rpdARG_POP;

                    dest = gceByrefPrefixI(genRegPtrTemp, dest);

                    *dest++ = 0xF8 | (isPop << 2);
                    dest += encodeUnsigned(dest, genRegPtrTemp->rpdPtrArg);

                    /* Remember the new 'last' offset */

                    lastOffset = nextOffset;
                }
            }
            else
            {
                unsigned regMask;

                /* Record any registers that are becoming dead */

                regMask = genRegPtrTemp->rpdCompiler.rpdDel & ptrRegs;

                while (regMask) // EAX,ECX,EDX,EBX,---,EBP,ESI,EDI
                {
                    unsigned  tmpMask;
                    regNumber regNum;

                    /* Get hold of the next register bit */

                    tmpMask = genFindLowestReg(regMask);
                    assert(tmpMask);

                    /* Remember the new state of this register */

                    ptrRegs &= ~tmpMask;

                    /* Figure out which register the next bit corresponds to */

                    regNum = genRegNumFromMask(tmpMask);
                    assert(regNum <= 7);

                    /* Reserve ESP, regNum==4 for future use */

                    assert(regNum != 4);

                    /*
                        Generate a small encoding:

                            ptr reg dead        00RRRDDD
                     */

                    assert((codeDelta & 0x7) == codeDelta);
                    *dest++ = 0x00 | regNum << 3 | (BYTE)codeDelta;

                    /* Turn the bit we've just generated off and continue */

                    regMask -= tmpMask; // EAX,ECX,EDX,EBX,---,EBP,ESI,EDI

                    /* Remember the new 'last' offset */

                    lastOffset = nextOffset;

                    /* Any entries that follow will be at the same offset */

                    codeDelta = zeroFunc(); /* DO NOT REMOVE */
                }

                /* Record any registers that are becoming live */

                regMask = genRegPtrTemp->rpdCompiler.rpdAdd & ~ptrRegs;

                while (regMask) // EAX,ECX,EDX,EBX,---,EBP,ESI,EDI
                {
                    unsigned  tmpMask;
                    regNumber regNum;

                    /* Get hold of the next register bit */

                    tmpMask = genFindLowestReg(regMask);
                    assert(tmpMask);

                    /* Remember the new state of this register */

                    ptrRegs |= tmpMask;

                    /* Figure out which register the next bit corresponds to */

                    regNum = genRegNumFromMask(tmpMask);
                    assert(regNum <= 7);

                    /*
                        Generate a small encoding:

                            ptr reg live        01RRRDDD
                     */

                    dest = gceByrefPrefixI(genRegPtrTemp, dest);

                    if (!thisKeptAliveIsInUntracked && genRegPtrTemp->rpdIsThis)
                    {
                        // Mark with 'this' pointer prefix
                        *dest++ = 0xBC;
                        // Can only have one bit set in regMask
                        assert(regMask == tmpMask);
                    }

                    assert((codeDelta & 0x7) == codeDelta);
                    *dest++ = 0x40 | (regNum << 3) | (BYTE)codeDelta;

                    /* Turn the bit we've just generated off and continue */

                    regMask -= tmpMask; // EAX,ECX,EDX,EBX,---,EBP,ESI,EDI

                    /* Remember the new 'last' offset */

                    lastOffset = nextOffset;

                    /* Any entries that follow will be at the same offset */

                    codeDelta = zeroFunc(); /* DO NOT REMOVE */
                }
            }

            /* Keep track of the total amount of generated stuff */

            totalSize += dest - base;

            /* Go back to the buffer start if we're not generating a table */

            if (!mask)
                dest = base;
        }
#endif // _TARGET_X86_

        /* Terminate the table with 0xFF */

        *dest = 0xFF;
        dest -= mask;
        totalSize++;
    }
    else if (compiler->isFramePointerUsed()) // genInterruptible is false
    {
#ifdef _TARGET_X86_
        /*
            Encoding table for methods with an EBP frame and
                               that are not fully interruptible

            The encoding used is as follows:

            this pointer encodings:

               01000000          this pointer in EBX
               00100000          this pointer in ESI
               00010000          this pointer in EDI

            tiny encoding:

               0bsdDDDD
                                 requires code delta > 0 & delta < 16 (4-bits)
                                 requires pushed argmask == 0

                 where    DDDD   is code delta
                             b   indicates that register EBX is a live pointer
                             s   indicates that register ESI is a live pointer
                             d   indicates that register EDI is a live pointer


            small encoding:

               1DDDDDDD bsdAAAAA

                                 requires code delta     < 120 (7-bits)
                                 requires pushed argmask <  64 (5-bits)

                 where DDDDDDD   is code delta
                         AAAAA   is the pushed args mask
                             b   indicates that register EBX is a live pointer
                             s   indicates that register ESI is a live pointer
                             d   indicates that register EDI is a live pointer

            medium encoding

               0xFD aaaaaaaa AAAAdddd bseDDDDD

                                 requires code delta     <  512  (9-bits)
                                 requires pushed argmask < 2048 (12-bits)

                 where    DDDDD  is the upper 5-bits of the code delta
                           dddd  is the low   4-bits of the code delta
                           AAAA  is the upper 4-bits of the pushed arg mask
                       aaaaaaaa  is the low   8-bits of the pushed arg mask
                              b  indicates that register EBX is a live pointer
                              s  indicates that register ESI is a live pointer
                              e  indicates that register EDI is a live pointer

            medium encoding with interior pointers

               0xF9 DDDDDDDD bsdAAAAAA iiiIIIII

                                 requires code delta     < 256 (8-bits)
                                 requires pushed argmask <  64 (5-bits)

                 where  DDDDDDD  is the code delta
                              b  indicates that register EBX is a live pointer
                              s  indicates that register ESI is a live pointer
                              d  indicates that register EDI is a live pointer
                          AAAAA  is the pushed arg mask
                            iii  indicates that EBX,EDI,ESI are interior pointers
                          IIIII  indicates that bits in the arg mask are interior
                                 pointers

            large encoding

               0xFE [0BSD0bsd][32-bit code delta][32-bit argMask]

                              b  indicates that register EBX is a live pointer
                              s  indicates that register ESI is a live pointer
                              d  indicates that register EDI is a live pointer
                              B  indicates that register EBX is an interior pointer
                              S  indicates that register ESI is an interior pointer
                              D  indicates that register EDI is an interior pointer
                                 requires pushed  argmask < 32-bits

            large encoding  with interior pointers

               0xFA [0BSD0bsd][32-bit code delta][32-bit argMask][32-bit interior pointer mask]


                              b  indicates that register EBX is a live pointer
                              s  indicates that register ESI is a live pointer
                              d  indicates that register EDI is a live pointer
                              B  indicates that register EBX is an interior pointer
                              S  indicates that register ESI is an interior pointer
                              D  indicates that register EDI is an interior pointer
                                 requires pushed  argmask < 32-bits
                                 requires pushed iArgmask < 32-bits


            huge encoding        This is the only encoding that supports
                                 a pushed argmask which is greater than
                                 32-bits.

               0xFB [0BSD0bsd][32-bit code delta]
                    [32-bit table count][32-bit table size]
                    [pushed ptr offsets table...]

                             b   indicates that register EBX is a live pointer
                             s   indicates that register ESI is a live pointer
                             d   indicates that register EDI is a live pointer
                             B   indicates that register EBX is an interior pointer
                             S   indicates that register ESI is an interior pointer
                             D   indicates that register EDI is an interior pointer
                             the list count is the number of entries in the list
                             the list size gives the byte-length of the list
                             the offsets in the list are variable-length
        */

        /* If "this" is enregistered, note it. We do this explicitly here as
           genFullPtrRegMap==false, and so we don't have any regPtrDsc's. */

        if (compiler->lvaKeepAliveAndReportThis() && compiler->lvaTable[compiler->info.compThisArg].lvRegister)
        {
            unsigned thisRegMask   = genRegMask(compiler->lvaTable[compiler->info.compThisArg].lvRegNum);
            unsigned thisPtrRegEnc = gceEncodeCalleeSavedRegs(thisRegMask) << 4;

            if (thisPtrRegEnc)
            {
                totalSize += 1;
                if (mask)
                    *dest++ = thisPtrRegEnc;
            }
        }

        CallDsc* call;

        assert(compiler->genFullPtrRegMap == false);

        /* Walk the list of pointer register/argument entries */

        for (call = gcCallDescList; call; call = call->cdNext)
        {
            BYTE*    base = dest;
            unsigned nextOffset;

            /* Figure out the code offset of this entry */

            nextOffset = call->cdOffs;

            /* Compute the distance from the previous call */

            DWORD codeDelta = nextOffset - lastOffset;

            assert((int)codeDelta >= 0);

            /* Remember the new 'last' offset */

            lastOffset = nextOffset;

            /* Compute the register mask */

            unsigned gcrefRegMask = 0;
            unsigned byrefRegMask = 0;

            gcrefRegMask |= gceEncodeCalleeSavedRegs(call->cdGCrefRegs);
            byrefRegMask |= gceEncodeCalleeSavedRegs(call->cdByrefRegs);

            assert((gcrefRegMask & byrefRegMask) == 0);

            unsigned regMask = gcrefRegMask | byrefRegMask;

            bool byref = (byrefRegMask | call->u1.cdByrefArgMask) != 0;

            /* Check for the really large argument offset case */
            /* The very rare Huge encodings */

            if (call->cdArgCnt)
            {
                unsigned argNum;
                DWORD    argCnt    = call->cdArgCnt;
                DWORD    argBytes  = 0;
                BYTE*    pArgBytes = DUMMY_INIT(NULL);

                if (mask != 0)
                {
                    *dest++       = 0xFB;
                    *dest++       = (byrefRegMask << 4) | regMask;
                    *(DWORD*)dest = codeDelta;
                    dest += sizeof(DWORD);
                    *(DWORD*)dest = argCnt;
                    dest += sizeof(DWORD);
                    // skip the byte-size for now. Just note where it will go
                    pArgBytes = dest;
                    dest += sizeof(DWORD);
                }

                for (argNum = 0; argNum < argCnt; argNum++)
                {
                    unsigned eltSize;
                    eltSize = encodeUnsigned(dest, call->cdArgTable[argNum]);
                    argBytes += eltSize;
                    if (mask)
                        dest += eltSize;
                }

                if (mask == 0)
                {
                    dest = base + 1 + 1 + 3 * sizeof(DWORD) + argBytes;
                }
                else
                {
                    assert(dest == pArgBytes + sizeof(argBytes) + argBytes);
                    *(DWORD*)pArgBytes = argBytes;
                }
            }

            /* Check if we can use a tiny encoding */
            else if ((codeDelta < 16) && (codeDelta != 0) && (call->u1.cdArgMask == 0) && !byref)
            {
                *dest++ = (regMask << 4) | (BYTE)codeDelta;
            }

            /* Check if we can use the small encoding */
            else if ((codeDelta < 0x79) && (call->u1.cdArgMask <= 0x1F) && !byref)
            {
                *dest++ = 0x80 | (BYTE)codeDelta;
                *dest++ = call->u1.cdArgMask | (regMask << 5);
            }

            /* Check if we can use the medium encoding */
            else if (codeDelta <= 0x01FF && call->u1.cdArgMask <= 0x0FFF && !byref)
            {
                *dest++ = 0xFD;
                *dest++ = call->u1.cdArgMask;
                *dest++ = ((call->u1.cdArgMask >> 4) & 0xF0) | ((BYTE)codeDelta & 0x0F);
                *dest++ = (regMask << 5) | (BYTE)((codeDelta >> 4) & 0x1F);
            }

            /* Check if we can use the medium encoding with byrefs */
            else if (codeDelta <= 0x0FF && call->u1.cdArgMask <= 0x01F)
            {
                *dest++ = 0xF9;
                *dest++ = (BYTE)codeDelta;
                *dest++ = (regMask << 5) | call->u1.cdArgMask;
                *dest++ = (byrefRegMask << 5) | call->u1.cdByrefArgMask;
            }

            /* We'll use the large encoding */
            else if (!byref)
            {
                *dest++       = 0xFE;
                *dest++       = (byrefRegMask << 4) | regMask;
                *(DWORD*)dest = codeDelta;
                dest += sizeof(DWORD);
                *(DWORD*)dest = call->u1.cdArgMask;
                dest += sizeof(DWORD);
            }

            /* We'll use the large encoding with byrefs */
            else
            {
                *dest++       = 0xFA;
                *dest++       = (byrefRegMask << 4) | regMask;
                *(DWORD*)dest = codeDelta;
                dest += sizeof(DWORD);
                *(DWORD*)dest = call->u1.cdArgMask;
                dest += sizeof(DWORD);
                *(DWORD*)dest = call->u1.cdByrefArgMask;
                dest += sizeof(DWORD);
            }

            /* Keep track of the total amount of generated stuff */

            totalSize += dest - base;

            /* Go back to the buffer start if we're not generating a table */

            if (!mask)
                dest = base;
        }
#endif // _TARGET_X86_

        /* Terminate the table with 0xFF */

        *dest = 0xFF;
        dest -= mask;
        totalSize++;
    }
    else // genInterruptible is false and we have an EBP-less frame
    {
        assert(compiler->genFullPtrRegMap);

#ifdef _TARGET_X86_

        regPtrDsc*       genRegPtrTemp;
        regNumber        thisRegNum = regNumber(0);
        PendingArgsStack pasStk(compiler->getEmitter()->emitMaxStackDepth, compiler);

        /* Walk the list of pointer register/argument entries */

        for (genRegPtrTemp = gcRegPtrList; genRegPtrTemp; genRegPtrTemp = genRegPtrTemp->rpdNext)
        {

            /*
             *    Encoding table for methods without an EBP frame and
             *     that are not fully interruptible
             *
             *               The encoding used is as follows:
             *
             *  push     000DDDDD                     ESP push one item with 5-bit delta
             *  push     00100000 [pushCount]         ESP push multiple items
             *  reserved 0010xxxx                     xxxx != 0000
             *  reserved 0011xxxx
             *  skip     01000000 [Delta]             Skip Delta, arbitrary sized delta
             *  skip     0100DDDD                     Skip small Delta, for call (DDDD != 0)
             *  pop      01CCDDDD                     ESP pop  CC items with 4-bit delta (CC != 00)
             *  call     1PPPPPPP                     Call Pattern, P=[0..79]
             *  call     1101pbsd DDCCCMMM            Call RegMask=pbsd,ArgCnt=CCC,
             *                                        ArgMask=MMM Delta=commonDelta[DD]
             *  call     1110pbsd [ArgCnt] [ArgMask]  Call ArgCnt,RegMask=pbsd,ArgMask
             *  call     11111000 [PBSDpbsd][32-bit delta][32-bit ArgCnt]
             *                    [32-bit PndCnt][32-bit PndSize][PndOffs...]
             *  iptr     11110000 [IPtrMask]          Arbitrary Interior Pointer Mask
             *  thisptr  111101RR                     This pointer is in Register RR
             *                                        00=EDI,01=ESI,10=EBX,11=EBP
             *  reserved 111100xx                     xx  != 00
             *  reserved 111110xx                     xx  != 00
             *  reserved 11111xxx                     xxx != 000 && xxx != 111(EOT)
             *
             *   The value 11111111 [0xFF] indicates the end of the table. (EOT)
             *
             *  An offset (at which stack-walking is performed) without an explicit encoding
             *  is assumed to be a trivial call-site (no GC registers, stack empty before and
             *  after) to avoid having to encode all trivial calls.
             *
             * Note on the encoding used for interior pointers
             *
             *   The iptr encoding must immediately precede a call encoding.  It is used
             *   to transform a normal GC pointer addresses into an interior pointers for
             *   GC purposes.  The mask supplied to the iptr encoding is read from the
             *   least signicant bit to the most signicant bit. (i.e the lowest bit is
             *   read first)
             *
             *   p   indicates that register EBP is a live pointer
             *   b   indicates that register EBX is a live pointer
             *   s   indicates that register ESI is a live pointer
             *   d   indicates that register EDI is a live pointer
             *   P   indicates that register EBP is an interior pointer
             *   B   indicates that register EBX is an interior pointer
             *   S   indicates that register ESI is an interior pointer
             *   D   indicates that register EDI is an interior pointer
             *
             *   As an example the following sequence indicates that EDI.ESI and the
             *   second pushed pointer in ArgMask are really interior pointers.  The
             *   pointer in ESI in a normal pointer:
             *
             *   iptr 11110000 00010011           => read Interior Ptr, Interior Ptr,
             *                                       Normal Ptr, Normal Ptr, Interior Ptr
             *
             *   call 11010011 DDCCC011 RRRR=1011 => read EDI is a GC-pointer,
             *                                            ESI is a GC-pointer.
             *                                            EBP is a GC-pointer
             *                           MMM=0011 => read two GC-pointers arguments
             *                                         on the stack (nested call)
             *
             *   Since the call instruction mentions 5 GC-pointers we list them in
             *   the required order:  EDI, ESI, EBP, 1st-pushed pointer, 2nd-pushed pointer
             *
             *   And we apply the Interior Pointer mask mmmm=10011 to the five GC-pointers
             *   we learn that EDI and ESI are interior GC-pointers and that
             *   the second push arg is an interior GC-pointer.
             */

            BYTE* base = dest;

            bool     usePopEncoding;
            unsigned regMask;
            unsigned argMask;
            unsigned byrefRegMask;
            unsigned byrefArgMask;
            DWORD    callArgCnt;

            unsigned nextOffset;
            DWORD    codeDelta;

            nextOffset = genRegPtrTemp->rpdOffs;

            /* Compute the distance from the previous call */

            codeDelta = nextOffset - lastOffset;
            assert((int)codeDelta >= 0);

#if REGEN_CALLPAT
            // Must initialize this flag to true when REGEN_CALLPAT is on
            usePopEncoding         = true;
            unsigned origCodeDelta = codeDelta;
#endif

            if (!thisKeptAliveIsInUntracked && genRegPtrTemp->rpdIsThis)
            {
                unsigned tmpMask = genRegPtrTemp->rpdCompiler.rpdAdd;

                /* tmpMask must have exactly one bit set */

                assert(tmpMask && ((tmpMask & (tmpMask - 1)) == 0));

                thisRegNum = genRegNumFromMask(tmpMask);
                switch (thisRegNum)
                {
                    case 0: // EAX
                    case 1: // ECX
                    case 2: // EDX
                    case 4: // ESP
                        break;
                    case 7:             // EDI
                        *dest++ = 0xF4; /* 11110100  This pointer is in EDI */
                        break;
                    case 6:             // ESI
                        *dest++ = 0xF5; /* 11110100  This pointer is in ESI */
                        break;
                    case 3:             // EBX
                        *dest++ = 0xF6; /* 11110100  This pointer is in EBX */
                        break;
                    case 5:             // EBP
                        *dest++ = 0xF7; /* 11110100  This pointer is in EBP */
                        break;
                    default:
                        break;
                }
            }

            /* Is this a stack pointer change or call? */

            if (genRegPtrTemp->rpdArg)
            {
                if (genRegPtrTemp->rpdArgTypeGet() == rpdARG_KILL)
                {
                    // kill 'rpdPtrArg' number of pointer variables in pasStk
                    pasStk.pasKill(genRegPtrTemp->rpdPtrArg);
                }
                /* Is this a call site? */
                else if (genRegPtrTemp->rpdCall)
                {
                    /* This is a true call site */

                    /* Remember the new 'last' offset */

                    lastOffset = nextOffset;

                    callArgCnt = genRegPtrTemp->rpdPtrArg;

                    unsigned gcrefRegMask = genRegPtrTemp->rpdCallGCrefRegs;

                    byrefRegMask = genRegPtrTemp->rpdCallByrefRegs;

                    assert((gcrefRegMask & byrefRegMask) == 0);

                    regMask = gcrefRegMask | byrefRegMask;

                    /* adjust argMask for this call-site */
                    pasStk.pasPop(callArgCnt);

                    /* Do we have to use the fat encoding */

                    if (pasStk.pasCurDepth() > BITS_IN_pasMask && pasStk.pasHasGCptrs())
                    {
                        /* use fat encoding:
                         *   11111000 [PBSDpbsd][32-bit delta][32-bit ArgCnt]
                         *            [32-bit PndCnt][32-bit PndSize][PndOffs...]
                         */

                        DWORD pndCount = pasStk.pasEnumGCoffsCount();
                        DWORD pndSize  = 0;
                        BYTE* pPndSize = DUMMY_INIT(NULL);

                        if (mask)
                        {
                            *dest++       = 0xF8;
                            *dest++       = (byrefRegMask << 4) | regMask;
                            *(DWORD*)dest = codeDelta;
                            dest += sizeof(DWORD);
                            *(DWORD*)dest = callArgCnt;
                            dest += sizeof(DWORD);
                            *(DWORD*)dest = pndCount;
                            dest += sizeof(DWORD);
                            pPndSize = dest;
                            dest += sizeof(DWORD); // Leave space for pndSize
                        }

                        unsigned offs, iter;

                        for (iter = pasStk.pasEnumGCoffs(pasENUM_START, &offs); pndCount;
                             iter = pasStk.pasEnumGCoffs(iter, &offs), pndCount--)
                        {
                            unsigned eltSize = encodeUnsigned(dest, offs);

                            pndSize += eltSize;
                            if (mask)
                                dest += eltSize;
                        }
                        assert(iter == pasENUM_END);

                        if (mask == 0)
                        {
                            dest = base + 2 + 4 * sizeof(DWORD) + pndSize;
                        }
                        else
                        {
                            assert(pPndSize + sizeof(pndSize) + pndSize == dest);
                            *(DWORD*)pPndSize = pndSize;
                        }

                        goto NEXT_RPD;
                    }

                    argMask = byrefArgMask = 0;

                    if (pasStk.pasHasGCptrs())
                    {
                        assert(pasStk.pasCurDepth() <= BITS_IN_pasMask);

                        argMask      = pasStk.pasArgMask();
                        byrefArgMask = pasStk.pasByrefArgMask();
                    }

                    /* Shouldn't be reporting trivial call-sites */

                    assert(regMask || argMask || callArgCnt || pasStk.pasCurDepth());

// Emit IPtrMask if needed

#define CHK_NON_INTRPT_ESP_IPtrMask                                                                                    \
                                                                                                                       \
    if (byrefRegMask || byrefArgMask)                                                                                  \
    {                                                                                                                  \
        *dest++        = 0xF0;                                                                                         \
        unsigned imask = (byrefArgMask << 4) | byrefRegMask;                                                           \
        dest += encodeUnsigned(dest, imask);                                                                           \
    }

                    /* When usePopEncoding is true:
                     *  this is not an interesting call site
                     *   because nothing is live here.
                     */
                    usePopEncoding = ((callArgCnt < 4) && (regMask == 0) && (argMask == 0));

                    if (!usePopEncoding)
                    {
                        int pattern = lookupCallPattern(callArgCnt, regMask, argMask, codeDelta);
                        if (pattern != -1)
                        {
                            if (pattern > 0xff)
                            {
                                codeDelta = pattern >> 8;
                                pattern &= 0xff;
                                if (codeDelta >= 16)
                                {
                                    /* use encoding: */
                                    /*   skip 01000000 [Delta] */
                                    *dest++ = 0x40;
                                    dest += encodeUnsigned(dest, codeDelta);
                                    codeDelta = 0;
                                }
                                else
                                {
                                    /* use encoding: */
                                    /*   skip 0100DDDD  small delta=DDDD */
                                    *dest++ = 0x40 | (BYTE)codeDelta;
                                }
                            }

                            // Emit IPtrMask if needed
                            CHK_NON_INTRPT_ESP_IPtrMask;

                            assert((pattern >= 0) && (pattern < 80));
                            *dest++ = 0x80 | pattern;
                            goto NEXT_RPD;
                        }

                        /* See if we can use 2nd call encoding
                         *     1101RRRR DDCCCMMM encoding */

                        if ((callArgCnt <= 7) && (argMask <= 7))
                        {
                            unsigned inx; // callCommonDelta[] index
                            unsigned maxCommonDelta = callCommonDelta[3];

                            if (codeDelta > maxCommonDelta)
                            {
                                if (codeDelta > maxCommonDelta + 15)
                                {
                                    /* use encoding: */
                                    /*   skip    01000000 [Delta] */
                                    *dest++ = 0x40;
                                    dest += encodeUnsigned(dest, codeDelta - maxCommonDelta);
                                }
                                else
                                {
                                    /* use encoding: */
                                    /*   skip 0100DDDD  small delta=DDDD */
                                    *dest++ = 0x40 | (BYTE)(codeDelta - maxCommonDelta);
                                }

                                codeDelta = maxCommonDelta;
                                inx       = 3;
                                goto EMIT_2ND_CALL_ENCODING;
                            }

                            for (inx = 0; inx < 4; inx++)
                            {
                                if (codeDelta == callCommonDelta[inx])
                                {
                                EMIT_2ND_CALL_ENCODING:
                                    // Emit IPtrMask if needed
                                    CHK_NON_INTRPT_ESP_IPtrMask;

                                    *dest++ = 0xD0 | regMask;
                                    *dest++ = (inx << 6) | (callArgCnt << 3) | argMask;
                                    goto NEXT_RPD;
                                }
                            }

                            unsigned minCommonDelta = callCommonDelta[0];

                            if ((codeDelta > minCommonDelta) && (codeDelta < maxCommonDelta))
                            {
                                assert((minCommonDelta + 16) > maxCommonDelta);
                                /* use encoding: */
                                /*   skip 0100DDDD  small delta=DDDD */
                                *dest++ = 0x40 | (BYTE)(codeDelta - minCommonDelta);

                                codeDelta = minCommonDelta;
                                inx       = 0;
                                goto EMIT_2ND_CALL_ENCODING;
                            }
                        }
                    }

                    if (codeDelta >= 16)
                    {
                        unsigned i = (usePopEncoding ? 15 : 0);
                        /* use encoding: */
                        /*   skip    01000000 [Delta]  arbitrary sized delta */
                        *dest++ = 0x40;
                        dest += encodeUnsigned(dest, codeDelta - i);
                        codeDelta = i;
                    }

                    if ((codeDelta > 0) || usePopEncoding)
                    {
                        if (usePopEncoding)
                        {
                            /* use encoding: */
                            /*   pop 01CCDDDD  ESP pop CC items, 4-bit delta */
                            if (callArgCnt || codeDelta)
                                *dest++ = (BYTE)(0x40 | (callArgCnt << 4) | codeDelta);
                            goto NEXT_RPD;
                        }
                        else
                        {
                            /* use encoding: */
                            /*   skip 0100DDDD  small delta=DDDD */
                            *dest++ = 0x40 | (BYTE)codeDelta;
                        }
                    }

                    // Emit IPtrMask if needed
                    CHK_NON_INTRPT_ESP_IPtrMask;

                    /* use encoding:                                   */
                    /*   call 1110RRRR [ArgCnt] [ArgMask]              */

                    *dest++ = 0xE0 | regMask;
                    dest += encodeUnsigned(dest, callArgCnt);

                    dest += encodeUnsigned(dest, argMask);
                }
                else
                {
                    /* This is a push or a pop site */

                    /* Remember the new 'last' offset */

                    lastOffset = nextOffset;

                    if (genRegPtrTemp->rpdArgTypeGet() == rpdARG_POP)
                    {
                        /* This must be a gcArgPopSingle */

                        assert(genRegPtrTemp->rpdPtrArg == 1);

                        if (codeDelta >= 16)
                        {
                            /* use encoding: */
                            /*   skip    01000000 [Delta] */
                            *dest++ = 0x40;
                            dest += encodeUnsigned(dest, codeDelta - 15);
                            codeDelta = 15;
                        }

                        /* use encoding: */
                        /*   pop1    0101DDDD  ESP pop one item, 4-bit delta */

                        *dest++ = 0x50 | (BYTE)codeDelta;

                        /* adjust argMask for this pop */
                        pasStk.pasPop(1);
                    }
                    else
                    {
                        /* This is a push */

                        if (codeDelta >= 32)
                        {
                            /* use encoding: */
                            /*   skip    01000000 [Delta] */
                            *dest++ = 0x40;
                            dest += encodeUnsigned(dest, codeDelta - 31);
                            codeDelta = 31;
                        }

                        assert(codeDelta < 32);

                        /* use encoding: */
                        /*   push    000DDDDD ESP push one item, 5-bit delta */

                        *dest++ = (BYTE)codeDelta;

                        /* adjust argMask for this push */
                        pasStk.pasPush(genRegPtrTemp->rpdGCtypeGet());
                    }
                }
            }

        /*  We ignore the register live/dead information, since the
         *  rpdCallRegMask contains all the liveness information
         *  that we need
         */
        NEXT_RPD:

            totalSize += dest - base;

            /* Go back to the buffer start if we're not generating a table */

            if (!mask)
                dest = base;

#if REGEN_CALLPAT
            if ((mask == -1) && (usePopEncoding == false) && ((dest - base) > 0))
                regenLog(origCodeDelta, argMask, regMask, callArgCnt, byrefArgMask, byrefRegMask, base, (dest - base));
#endif
        }

        /* Verify that we pop every arg that was pushed and that argMask is 0 */

        assert(pasStk.pasCurDepth() == 0);

#endif // _TARGET_X86_

        /* Terminate the table with 0xFF */

        *dest = 0xFF;
        dest -= mask;
        totalSize++;
    }

#if VERIFY_GC_TABLES
    if (mask)
    {
        *(short*)dest = (short)0xBEEB;
        dest += sizeof(short);
    }
    totalSize += sizeof(short);
#endif

#if MEASURE_PTRTAB_SIZE

    if (mask)
        s_gcTotalPtrTabSize += totalSize;

#endif

    return totalSize;
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif

/*****************************************************************************/
#if DUMP_GC_TABLES
/*****************************************************************************
 *
 *  Dump the contents of a GC pointer table.
 */

#include "gcdump.h"

#if VERIFY_GC_TABLES
const bool verifyGCTables = true;
#else
const bool verifyGCTables = false;
#endif

/*****************************************************************************
 *
 *  Dump the info block header.
 */

unsigned GCInfo::gcInfoBlockHdrDump(const BYTE* table, InfoHdr* header, unsigned* methodSize)
{
    GCDump gcDump(GCINFO_VERSION);

    gcDump.gcPrintf = gcDump_logf; // use my printf (which logs to VM)
    printf("Method info block:\n");

    return gcDump.DumpInfoHdr(table, header, methodSize, verifyGCTables);
}

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

unsigned GCInfo::gcDumpPtrTable(const BYTE* table, const InfoHdr& header, unsigned methodSize)
{
    printf("Pointer table:\n");

    GCDump gcDump(GCINFO_VERSION);
    gcDump.gcPrintf = gcDump_logf; // use my printf (which logs to VM)

    return gcDump.DumpGCTable(table, header, methodSize, verifyGCTables);
}

/*****************************************************************************
 *
 *  Find all the live pointers in a stack frame.
 */

void GCInfo::gcFindPtrsInFrame(const void* infoBlock, const void* codeBlock, unsigned offs)
{
    GCDump gcDump(GCINFO_VERSION);
    gcDump.gcPrintf = gcDump_logf; // use my printf (which logs to VM)

    gcDump.DumpPtrsInFrame((PTR_CBYTE)infoBlock, (const BYTE*)codeBlock, offs, verifyGCTables);
}

#endif // DUMP_GC_TABLES

#else // !JIT32_GCENCODER

#include "gcinfoencoder.h"
#include "simplerhash.h"

// Do explicit instantiation.
template class SimplerHashTable<RegSlotIdKey, RegSlotIdKey, GcSlotId, JitSimplerHashBehavior>;
template class SimplerHashTable<StackSlotIdKey, StackSlotIdKey, GcSlotId, JitSimplerHashBehavior>;

#ifdef DEBUG

static const char* const GcSlotFlagsNames[] = {"",
                                               "(byref) ",
                                               "(pinned) ",
                                               "(byref, pinned) ",
                                               "(untracked) ",
                                               "(byref, untracked) ",
                                               "(pinned, untracked) ",
                                               "(byref, pinned, untracked) "};

// I'm making a local wrapper class for GcInfoEncoder so that can add logging of my own (DLD).
class GcInfoEncoderWithLogging
{
    GcInfoEncoder* m_gcInfoEncoder;
    bool           m_doLogging;

public:
    GcInfoEncoderWithLogging(GcInfoEncoder* gcInfoEncoder, bool verbose)
        : m_gcInfoEncoder(gcInfoEncoder), m_doLogging(verbose || JitConfig.JitGCInfoLogging() != 0)
    {
    }

    GcSlotId GetStackSlotId(INT32 spOffset, GcSlotFlags flags, GcStackSlotBase spBase = GC_CALLER_SP_REL)
    {
        GcSlotId newSlotId = m_gcInfoEncoder->GetStackSlotId(spOffset, flags, spBase);
        if (m_doLogging)
        {
            printf("Stack slot id for offset %d (0x%x) (%s) %s= %d.\n", spOffset, spOffset,
                   GcStackSlotBaseNames[spBase], GcSlotFlagsNames[flags & 7], newSlotId);
        }
        return newSlotId;
    }

    GcSlotId GetRegisterSlotId(UINT32 regNum, GcSlotFlags flags)
    {
        GcSlotId newSlotId = m_gcInfoEncoder->GetRegisterSlotId(regNum, flags);
        if (m_doLogging)
        {
            printf("Register slot id for reg %s %s= %d.\n", getRegName(regNum), GcSlotFlagsNames[flags & 7], newSlotId);
        }
        return newSlotId;
    }

    void SetSlotState(UINT32 instructionOffset, GcSlotId slotId, GcSlotState slotState)
    {
        m_gcInfoEncoder->SetSlotState(instructionOffset, slotId, slotState);
        if (m_doLogging)
        {
            printf("Set state of slot %d at instr offset 0x%x to %s.\n", slotId, instructionOffset,
                   (slotState == GC_SLOT_LIVE ? "Live" : "Dead"));
        }
    }

    void DefineCallSites(UINT32* pCallSites, BYTE* pCallSiteSizes, UINT32 numCallSites)
    {
        m_gcInfoEncoder->DefineCallSites(pCallSites, pCallSiteSizes, numCallSites);
        if (m_doLogging)
        {
            printf("Defining %d call sites:\n", numCallSites);
            for (UINT32 k = 0; k < numCallSites; k++)
            {
                printf("    Offset 0x%x, size %d.\n", pCallSites[k], pCallSiteSizes[k]);
            }
        }
    }

    void DefineInterruptibleRange(UINT32 startInstructionOffset, UINT32 length)
    {
        m_gcInfoEncoder->DefineInterruptibleRange(startInstructionOffset, length);
        if (m_doLogging)
        {
            printf("Defining interruptible range: [0x%x, 0x%x).\n", startInstructionOffset,
                   startInstructionOffset + length);
        }
    }

    void SetCodeLength(UINT32 length)
    {
        m_gcInfoEncoder->SetCodeLength(length);
        if (m_doLogging)
        {
            printf("Set code length to %d.\n", length);
        }
    }

    void SetReturnKind(ReturnKind returnKind)
    {
        m_gcInfoEncoder->SetReturnKind(returnKind);
        if (m_doLogging)
        {
            printf("Set ReturnKind to %s.\n", ReturnKindToString(returnKind));
        }
    }

    void SetStackBaseRegister(UINT32 registerNumber)
    {
        m_gcInfoEncoder->SetStackBaseRegister(registerNumber);
        if (m_doLogging)
        {
            printf("Set stack base register to %s.\n", getRegName(registerNumber));
        }
    }

    void SetPrologSize(UINT32 prologSize)
    {
        m_gcInfoEncoder->SetPrologSize(prologSize);
        if (m_doLogging)
        {
            printf("Set prolog size 0x%x.\n", prologSize);
        }
    }

    void SetGSCookieStackSlot(INT32 spOffsetGSCookie, UINT32 validRangeStart, UINT32 validRangeEnd)
    {
        m_gcInfoEncoder->SetGSCookieStackSlot(spOffsetGSCookie, validRangeStart, validRangeEnd);
        if (m_doLogging)
        {
            printf("Set GS Cookie stack slot to %d, valid from 0x%x to 0x%x.\n", spOffsetGSCookie, validRangeStart,
                   validRangeEnd);
        }
    }

    void SetPSPSymStackSlot(INT32 spOffsetPSPSym)
    {
        m_gcInfoEncoder->SetPSPSymStackSlot(spOffsetPSPSym);
        if (m_doLogging)
        {
            printf("Set PSPSym stack slot to %d.\n", spOffsetPSPSym);
        }
    }

    void SetGenericsInstContextStackSlot(INT32 spOffsetGenericsContext, GENERIC_CONTEXTPARAM_TYPE type)
    {
        m_gcInfoEncoder->SetGenericsInstContextStackSlot(spOffsetGenericsContext, type);
        if (m_doLogging)
        {
            printf("Set generic instantiation context stack slot to %d, type is %s.\n", spOffsetGenericsContext,
                   (type == GENERIC_CONTEXTPARAM_THIS
                        ? "THIS"
                        : (type == GENERIC_CONTEXTPARAM_MT ? "MT"
                                                           : (type == GENERIC_CONTEXTPARAM_MD ? "MD" : "UNKNOWN!"))));
        }
    }

    void SetSecurityObjectStackSlot(INT32 spOffset)
    {
        m_gcInfoEncoder->SetSecurityObjectStackSlot(spOffset);
        if (m_doLogging)
        {
            printf("Set security object stack slot to %d.\n", spOffset);
        }
    }

    void SetIsVarArg()
    {
        m_gcInfoEncoder->SetIsVarArg();
        if (m_doLogging)
        {
            printf("SetIsVarArg.\n");
        }
    }

    void SetWantsReportOnlyLeaf()
    {
        m_gcInfoEncoder->SetWantsReportOnlyLeaf();
        if (m_doLogging)
        {
            printf("Set WantsReportOnlyLeaf.\n");
        }
    }

    void SetSizeOfStackOutgoingAndScratchArea(UINT32 size)
    {
        m_gcInfoEncoder->SetSizeOfStackOutgoingAndScratchArea(size);
        if (m_doLogging)
        {
            printf("Set Outgoing stack arg area size to %d.\n", size);
        }
    }
};

#define GCENCODER_WITH_LOGGING(withLog, realEncoder)                                                                   \
    GcInfoEncoderWithLogging  withLog##Var(realEncoder, compiler->verbose || compiler->opts.dspGCtbls);                \
    GcInfoEncoderWithLogging* withLog = &withLog##Var;

#else // DEBUG

#define GCENCODER_WITH_LOGGING(withLog, realEncoder) GcInfoEncoder* withLog = realEncoder;

#endif // DEBUG

void GCInfo::gcInfoBlockHdrSave(GcInfoEncoder* gcInfoEncoder, unsigned methodSize, unsigned prologSize)
{
#ifdef DEBUG
    if (compiler->verbose)
    {
        printf("*************** In gcInfoBlockHdrSave()\n");
    }
#endif

    GCENCODER_WITH_LOGGING(gcInfoEncoderWithLog, gcInfoEncoder);

    // Can't create tables if we've not saved code.

    gcInfoEncoderWithLog->SetCodeLength(methodSize);

    gcInfoEncoderWithLog->SetReturnKind(getReturnKind());

    if (compiler->isFramePointerUsed())
    {
        gcInfoEncoderWithLog->SetStackBaseRegister(REG_FPBASE);
    }

    if (compiler->info.compIsVarArgs)
    {
        gcInfoEncoderWithLog->SetIsVarArg();
    }
    // No equivalents.
    // header->profCallbacks = compiler->info.compProfilerCallback;
    // header->editNcontinue = compiler->opts.compDbgEnC;
    //
    if (compiler->lvaReportParamTypeArg())
    {
        // The predicate above is true only if there is an extra generic context parameter, not for
        // the case where the generic context is provided by "this."
        assert(compiler->info.compTypeCtxtArg != BAD_VAR_NUM);
        GENERIC_CONTEXTPARAM_TYPE ctxtParamType = GENERIC_CONTEXTPARAM_NONE;
        switch (compiler->info.compMethodInfo->options & CORINFO_GENERICS_CTXT_MASK)
        {
            case CORINFO_GENERICS_CTXT_FROM_METHODDESC:
                ctxtParamType = GENERIC_CONTEXTPARAM_MD;
                break;
            case CORINFO_GENERICS_CTXT_FROM_METHODTABLE:
                ctxtParamType = GENERIC_CONTEXTPARAM_MT;
                break;

            case CORINFO_GENERICS_CTXT_FROM_THIS: // See comment above.
            default:
                // If we have a generic context parameter, then we should have
                // one of the two options flags handled above.
                assert(false);
        }

        gcInfoEncoderWithLog->SetGenericsInstContextStackSlot(
            compiler->lvaToCallerSPRelativeOffset(compiler->lvaCachedGenericContextArgOffset(),
                                                  compiler->isFramePointerUsed()),
            ctxtParamType);
    }
    // As discussed above, handle the case where the generics context is obtained via
    // the method table of "this".
    else if (compiler->lvaKeepAliveAndReportThis())
    {
        assert(compiler->info.compThisArg != BAD_VAR_NUM);
        gcInfoEncoderWithLog->SetGenericsInstContextStackSlot(
            compiler->lvaToCallerSPRelativeOffset(compiler->lvaCachedGenericContextArgOffset(),
                                                  compiler->isFramePointerUsed()),
            GENERIC_CONTEXTPARAM_THIS);
    }

    if (compiler->getNeedsGSSecurityCookie())
    {
        assert(compiler->lvaGSSecurityCookie != BAD_VAR_NUM);

        // The lv offset is FP-relative, and the using code expects caller-sp relative, so translate.
        // The code offset ranges assume that the GS Cookie slot is initialized in the prolog, and is valid
        // through the remainder of the method.  We will not query for the GS Cookie while we're in an epilog,
        // so the question of where in the epilog it becomes invalid is moot.
        gcInfoEncoderWithLog->SetGSCookieStackSlot(compiler->lvaGetCallerSPRelativeOffset(
                                                       compiler->lvaGSSecurityCookie),
                                                   prologSize, methodSize);
    }
    else if (compiler->opts.compNeedSecurityCheck || compiler->lvaReportParamTypeArg() ||
             compiler->lvaKeepAliveAndReportThis())
    {
        gcInfoEncoderWithLog->SetPrologSize(prologSize);
    }

    if (compiler->opts.compNeedSecurityCheck)
    {
        assert(compiler->lvaSecurityObject != BAD_VAR_NUM);

        // A VM requirement due to how the decoder works (it ignores partially interruptible frames when
        // an exception has escaped, but the VM requires the security object to live on).
        assert(compiler->codeGen->genInterruptible);

        // The lv offset is FP-relative, and the using code expects caller-sp relative, so translate.
        // The normal GC lifetime reporting mechanisms will report a proper lifetime to the GC.
        // The security subsystem can safely assume that anywhere it might walk the stack, it will be
        // valid (null or a live GC ref).
        gcInfoEncoderWithLog->SetSecurityObjectStackSlot(
            compiler->lvaGetCallerSPRelativeOffset(compiler->lvaSecurityObject));
    }

#if FEATURE_EH_FUNCLETS
    if (compiler->lvaPSPSym != BAD_VAR_NUM)
    {
#ifdef _TARGET_AMD64_
        // The PSPSym is relative to InitialSP on X64 and CallerSP on other platforms.
        gcInfoEncoderWithLog->SetPSPSymStackSlot(compiler->lvaGetInitialSPRelativeOffset(compiler->lvaPSPSym));
#else  // !_TARGET_AMD64_
        gcInfoEncoderWithLog->SetPSPSymStackSlot(compiler->lvaGetCallerSPRelativeOffset(compiler->lvaPSPSym));
#endif // !_TARGET_AMD64_
    }

    if (compiler->ehAnyFunclets())
    {
        // Set this to avoid double-reporting the parent frame (unlike JIT64)
        gcInfoEncoderWithLog->SetWantsReportOnlyLeaf();
    }
#endif // FEATURE_EH_FUNCLETS

#if FEATURE_FIXED_OUT_ARGS
    // outgoing stack area size
    gcInfoEncoderWithLog->SetSizeOfStackOutgoingAndScratchArea(compiler->lvaOutgoingArgSpaceSize);
#endif // FEATURE_FIXED_OUT_ARGS

#if DISPLAY_SIZES

    if (compiler->codeGen->genInterruptible)
    {
        genMethodICnt++;
    }
    else
    {
        genMethodNCnt++;
    }

#endif // DISPLAY_SIZES
}

#ifdef DEBUG
#define Encoder GcInfoEncoderWithLogging
#else
#define Encoder GcInfoEncoder
#endif

// Small helper class to handle the No-GC-Interrupt callbacks
// when reporting interruptible ranges.
//
// Encoder should be either GcInfoEncoder or GcInfoEncoderWithLogging
//
struct InterruptibleRangeReporter
{
    unsigned prevStart;
    Encoder* gcInfoEncoderWithLog;

    InterruptibleRangeReporter(unsigned _prevStart, Encoder* _gcInfo)
        : prevStart(_prevStart), gcInfoEncoderWithLog(_gcInfo)
    {
    }

    // This callback is called for each insGroup marked with
    // IGF_NOGCINTERRUPT (currently just prologs and epilogs).
    // Report everything between the previous region and the current
    // region as interruptible.

    bool operator()(unsigned igFuncIdx, unsigned igOffs, unsigned igSize)
    {
        if (igOffs < prevStart)
        {
            // We're still in the main method prolog, which has already
            // had it's interruptible range reported.
            assert(igFuncIdx == 0);
            assert(igOffs + igSize <= prevStart);
            return true;
        }

        assert(igOffs >= prevStart);
        if (igOffs > prevStart)
        {
            gcInfoEncoderWithLog->DefineInterruptibleRange(prevStart, igOffs - prevStart);
        }
        prevStart = igOffs + igSize;
        return true;
    }
};

void GCInfo::gcMakeRegPtrTable(
    GcInfoEncoder* gcInfoEncoder, unsigned codeSize, unsigned prologSize, MakeRegPtrMode mode, unsigned* callCntRef)
{
    GCENCODER_WITH_LOGGING(gcInfoEncoderWithLog, gcInfoEncoder);

    const bool noTrackedGCSlots =
        (compiler->opts.MinOpts() && !compiler->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT)
#if !defined(JIT32_GCENCODER) || !defined(LEGACY_BACKEND)
         && !JitConfig.JitMinOptsTrackGCrefs()
#endif // !defined(JIT32_GCENCODER) || !defined(LEGACY_BACKEND)
             );

    if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
    {
        m_regSlotMap   = new (compiler->getAllocator()) RegSlotMap(compiler->getAllocator());
        m_stackSlotMap = new (compiler->getAllocator()) StackSlotMap(compiler->getAllocator());
    }

    /**************************************************************************
     *
     *                      Untracked ptr variables
     *
     **************************************************************************
     */

    unsigned count = 0;

    int lastoffset = 0;

    /* Count&Write untracked locals and non-enregistered args */

    unsigned   varNum;
    LclVarDsc* varDsc;
    for (varNum = 0, varDsc = compiler->lvaTable; varNum < compiler->lvaCount; varNum++, varDsc++)
    {
        if (compiler->lvaIsFieldOfDependentlyPromotedStruct(varDsc))
        {
            // Field local of a PROMOTION_TYPE_DEPENDENT struct must have been
            // reported through its parent local.
            continue;
        }

        if (varTypeIsGC(varDsc->TypeGet()))
        {
            // Do we have an argument or local variable?
            if (!varDsc->lvIsParam)
            {
                // If is is pinned, it must be an untracked local.
                assert(!varDsc->lvPinned || !varDsc->lvTracked);

                if (varDsc->lvTracked || !varDsc->lvOnFrame)
                {
                    continue;
                }
            }
            else
            {
                // Stack-passed arguments which are not enregistered
                // are always reported in this "untracked stack
                // pointers" section of the GC info even if lvTracked==true

                // Has this argument been fully enregistered?
                CLANG_FORMAT_COMMENT_ANCHOR;

#ifndef LEGACY_BACKEND
                if (!varDsc->lvOnFrame)
#else  // LEGACY_BACKEND
                if (varDsc->lvRegister)
#endif // LEGACY_BACKEND
                {
                    // If a CEE_JMP has been used, then we need to report all the arguments
                    // even if they are enregistered, since we will be using this value
                    // in a JMP call.  Note that this is subtle as we require that
                    // argument offsets are always fixed up properly even if lvRegister
                    // is set.
                    if (!compiler->compJmpOpUsed)
                    {
                        continue;
                    }
                }
                else
                {
                    if (!varDsc->lvOnFrame)
                    {
                        // If this non-enregistered pointer arg is never
                        // used, we don't need to report it.
                        assert(varDsc->lvRefCnt == 0);
                        continue;
                    }
                    else if (varDsc->lvIsRegArg && varDsc->lvTracked)
                    {
                        // If this register-passed arg is tracked, then
                        // it has been allocated space near the other
                        // pointer variables and we have accurate life-
                        // time info. It will be reported with
                        // gcVarPtrList in the "tracked-pointer" section.
                        continue;
                    }
                }
            }

            // If we haven't continued to the next variable, we should report this as an untracked local.
            CLANG_FORMAT_COMMENT_ANCHOR;

            GcSlotFlags flags = GC_SLOT_UNTRACKED;

            if (varDsc->TypeGet() == TYP_BYREF)
            {
                // Or in byref_OFFSET_FLAG for 'byref' pointer tracking
                flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR);
            }

            if (varDsc->lvPinned)
            {
                // Or in pinned_OFFSET_FLAG for 'pinned' pointer tracking
                flags = (GcSlotFlags)(flags | GC_SLOT_PINNED);
            }
            GcStackSlotBase stackSlotBase = GC_SP_REL;
            if (varDsc->lvFramePointerBased)
            {
                stackSlotBase = GC_FRAMEREG_REL;
            }
            if (noTrackedGCSlots)
            {
                // No need to hash/lookup untracked GC refs; just grab a new Slot Id.
                if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
                {
                    gcInfoEncoderWithLog->GetStackSlotId(varDsc->lvStkOffs, flags, stackSlotBase);
                }
            }
            else
            {
                StackSlotIdKey sskey(varDsc->lvStkOffs, (stackSlotBase == GC_FRAMEREG_REL), flags);
                GcSlotId       varSlotId;
                if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
                {
                    if (!m_stackSlotMap->Lookup(sskey, &varSlotId))
                    {
                        varSlotId = gcInfoEncoderWithLog->GetStackSlotId(varDsc->lvStkOffs, flags, stackSlotBase);
                        m_stackSlotMap->Set(sskey, varSlotId);
                    }
                }
            }
        }

        // If this is a TYP_STRUCT, handle its GC pointers.
        // Note that the enregisterable struct types cannot have GC pointers in them.
        if ((varDsc->lvType == TYP_STRUCT) && varDsc->lvOnFrame && (varDsc->lvExactSize >= TARGET_POINTER_SIZE))
        {
            unsigned slots  = compiler->lvaLclSize(varNum) / sizeof(void*);
            BYTE*    gcPtrs = compiler->lvaGetGcLayout(varNum);

            // walk each member of the array
            for (unsigned i = 0; i < slots; i++)
            {
                if (gcPtrs[i] == TYPE_GC_NONE)
                { // skip non-gc slots
                    continue;
                }

                int offset = varDsc->lvStkOffs + i * sizeof(void*);
#if DOUBLE_ALIGN
                // For genDoubleAlign(), locals are addressed relative to ESP and
                // arguments are addressed relative to EBP.

                if (compiler->genDoubleAlign() && varDsc->lvIsParam && !varDsc->lvIsRegArg)
                    offset += compiler->codeGen->genTotalFrameSize();
#endif
                GcSlotFlags flags = GC_SLOT_UNTRACKED;
                if (gcPtrs[i] == TYPE_GC_BYREF)
                {
                    flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR);
                }

                GcStackSlotBase stackSlotBase = GC_SP_REL;
                if (varDsc->lvFramePointerBased)
                {
                    stackSlotBase = GC_FRAMEREG_REL;
                }
                StackSlotIdKey sskey(offset, (stackSlotBase == GC_FRAMEREG_REL), flags);
                GcSlotId       varSlotId;
                if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
                {
                    if (!m_stackSlotMap->Lookup(sskey, &varSlotId))
                    {
                        varSlotId = gcInfoEncoderWithLog->GetStackSlotId(offset, flags, stackSlotBase);
                        m_stackSlotMap->Set(sskey, varSlotId);
                    }
                }
            }
        }
    }

    if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
    {
        // Count&Write spill temps that hold pointers.

        assert(compiler->tmpAllFree());
        for (TempDsc* tempItem = compiler->tmpListBeg(); tempItem != nullptr; tempItem = compiler->tmpListNxt(tempItem))
        {
            if (varTypeIsGC(tempItem->tdTempType()))
            {
                int offset = tempItem->tdTempOffs();

                GcSlotFlags flags = GC_SLOT_UNTRACKED;
                if (tempItem->tdTempType() == TYP_BYREF)
                {
                    flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR);
                }

                GcStackSlotBase stackSlotBase = GC_SP_REL;
                if (compiler->isFramePointerUsed())
                {
                    stackSlotBase = GC_FRAMEREG_REL;
                }
                StackSlotIdKey sskey(offset, (stackSlotBase == GC_FRAMEREG_REL), flags);
                GcSlotId       varSlotId;
                if (!m_stackSlotMap->Lookup(sskey, &varSlotId))
                {
                    varSlotId = gcInfoEncoderWithLog->GetStackSlotId(offset, flags, stackSlotBase);
                    m_stackSlotMap->Set(sskey, varSlotId);
                }
            }
        }

        if (compiler->lvaKeepAliveAndReportThis())
        {
            // We need to report the cached copy as an untracked pointer
            assert(compiler->info.compThisArg != BAD_VAR_NUM);
            assert(!compiler->lvaReportParamTypeArg());
            GcSlotFlags flags = GC_SLOT_UNTRACKED;

            if (compiler->lvaTable[compiler->info.compThisArg].TypeGet() == TYP_BYREF)
            {
                // Or in GC_SLOT_INTERIOR for 'byref' pointer tracking
                flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR);
            }

            GcStackSlotBase stackSlotBase = compiler->isFramePointerUsed() ? GC_FRAMEREG_REL : GC_SP_REL;

            gcInfoEncoderWithLog->GetStackSlotId(compiler->lvaCachedGenericContextArgOffset(), flags, stackSlotBase);
        }
    }

    // Generate the table of tracked stack pointer variable lifetimes.
    gcMakeVarPtrTable(gcInfoEncoder, mode);

    /**************************************************************************
     *
     * Prepare to generate the pointer register/argument map
     *
     **************************************************************************
     */

    if (compiler->codeGen->genInterruptible)
    {
        assert(compiler->genFullPtrRegMap);

        regMaskSmall ptrRegs          = 0;
        regPtrDsc*   regStackArgFirst = nullptr;

        // Walk the list of pointer register/argument entries.

        for (regPtrDsc* genRegPtrTemp = gcRegPtrList; genRegPtrTemp != nullptr; genRegPtrTemp = genRegPtrTemp->rpdNext)
        {
            int nextOffset = genRegPtrTemp->rpdOffs;

            if (genRegPtrTemp->rpdArg)
            {
                if (genRegPtrTemp->rpdArgTypeGet() == rpdARG_KILL)
                {
                    // Kill all arguments for a call
                    if ((mode == MAKE_REG_PTR_MODE_DO_WORK) && (regStackArgFirst != nullptr))
                    {
                        // Record any outgoing arguments as becoming dead
                        gcInfoRecordGCStackArgsDead(gcInfoEncoder, genRegPtrTemp->rpdOffs, regStackArgFirst,
                                                    genRegPtrTemp);
                    }
                    regStackArgFirst = nullptr;
                }
                else if (genRegPtrTemp->rpdGCtypeGet() != GCT_NONE)
                {
                    if (genRegPtrTemp->rpdArgTypeGet() == rpdARG_PUSH || (genRegPtrTemp->rpdPtrArg != 0))
                    {
                        bool isPop = genRegPtrTemp->rpdArgTypeGet() == rpdARG_POP;
                        assert(!isPop);
                        gcInfoRecordGCStackArgLive(gcInfoEncoder, mode, genRegPtrTemp);
                        if (regStackArgFirst == nullptr)
                        {
                            regStackArgFirst = genRegPtrTemp;
                        }
                    }
                    else
                    {
                        // We know it's a POP.  Sometimes we'll record a POP for a call, just to make sure
                        // the call site is recorded.
                        // This is just the negation of the condition:
                        assert(genRegPtrTemp->rpdArgTypeGet() == rpdARG_POP && genRegPtrTemp->rpdPtrArg == 0);
                        // This asserts that we only get here when we're recording a call site.
                        assert(genRegPtrTemp->rpdArg && genRegPtrTemp->rpdIsCallInstr());

                        // Kill all arguments for a call
                        if ((mode == MAKE_REG_PTR_MODE_DO_WORK) && (regStackArgFirst != nullptr))
                        {
                            // Record any outgoing arguments as becoming dead
                            gcInfoRecordGCStackArgsDead(gcInfoEncoder, genRegPtrTemp->rpdOffs, regStackArgFirst,
                                                        genRegPtrTemp);
                        }
                        regStackArgFirst = nullptr;
                    }
                }
            }
            else
            {
                // Record any registers that are becoming dead.

                regMaskSmall regMask   = genRegPtrTemp->rpdCompiler.rpdDel & ptrRegs;
                regMaskSmall byRefMask = 0;
                if (genRegPtrTemp->rpdGCtypeGet() == GCT_BYREF)
                {
                    byRefMask = regMask;
                }
                gcInfoRecordGCRegStateChange(gcInfoEncoder, mode, genRegPtrTemp->rpdOffs, regMask, GC_SLOT_DEAD,
                                             byRefMask, &ptrRegs);

                // Record any registers that are becoming live.
                regMask   = genRegPtrTemp->rpdCompiler.rpdAdd & ~ptrRegs;
                byRefMask = 0;
                // As far as I (DLD, 2010) can tell, there's one GCtype for the entire genRegPtrTemp, so if
                // it says byref then all the registers in "regMask" contain byrefs.
                if (genRegPtrTemp->rpdGCtypeGet() == GCT_BYREF)
                {
                    byRefMask = regMask;
                }
                gcInfoRecordGCRegStateChange(gcInfoEncoder, mode, genRegPtrTemp->rpdOffs, regMask, GC_SLOT_LIVE,
                                             byRefMask, &ptrRegs);
            }
        }

        // Now we can declare the entire method body fully interruptible.
        if (mode == MAKE_REG_PTR_MODE_DO_WORK)
        {
            assert(prologSize <= codeSize);

            // Now exempt any other region marked as IGF_NOGCINTERRUPT
            // Currently just prologs and epilogs.

            InterruptibleRangeReporter reporter(prologSize, gcInfoEncoderWithLog);
            compiler->getEmitter()->emitGenNoGCLst(reporter);
            prologSize = reporter.prevStart;

            // Report any remainder
            if (prologSize < codeSize)
            {
                gcInfoEncoderWithLog->DefineInterruptibleRange(prologSize, codeSize - prologSize);
            }
        }
    }
    else if (compiler->isFramePointerUsed()) // genInterruptible is false, and we're using EBP as a frame pointer.
    {
        assert(compiler->genFullPtrRegMap == false);

        // Walk the list of pointer register/argument entries.

        // First count them.
        unsigned numCallSites = 0;

        // Now we can allocate the information.
        unsigned* pCallSites     = nullptr;
        BYTE*     pCallSiteSizes = nullptr;
        unsigned  callSiteNum    = 0;

        if (mode == MAKE_REG_PTR_MODE_DO_WORK)
        {
            if (gcCallDescList != nullptr)
            {
                if (noTrackedGCSlots)
                {
                    // We have the call count from the previous run.
                    numCallSites = *callCntRef;

                    // If there are no calls, tell the world and bail.
                    if (numCallSites == 0)
                    {
                        gcInfoEncoderWithLog->DefineCallSites(nullptr, nullptr, 0);
                        return;
                    }
                }
                else
                {
                    for (CallDsc* call = gcCallDescList; call != nullptr; call = call->cdNext)
                    {
                        numCallSites++;
                    }
                }
                pCallSites     = new (compiler, CMK_GC) unsigned[numCallSites];
                pCallSiteSizes = new (compiler, CMK_GC) BYTE[numCallSites];
            }
        }

        // Now consider every call.
        for (CallDsc* call = gcCallDescList; call != nullptr; call = call->cdNext)
        {
            // Figure out the code offset of this entry.
            unsigned nextOffset = call->cdOffs;

            // As far as I (DLD, 2010) can determine by asking around, the "call->u1.cdArgMask"
            // and "cdArgCnt" cases are to handle x86 situations in which a call expression is nested as an
            // argument to an outer call.  The "natural" (evaluation-order-preserving) thing to do is to
            // evaluate the outer call's arguments, pushing those that are not enregistered, until you
            // encounter the nested call.  These parts of the call description, then, describe the "pending"
            // pushed arguments.  This situation does not exist outside of x86, where we're going to use a
            // fixed-size stack frame: in situations like this nested call, we would evaluate the pending
            // arguments to temporaries, and only "push" them (really, write them to the outgoing argument section
            // of the stack frame) when it's the outer call's "turn."  So we can assert that these
            // situations never occur.
            assert(call->u1.cdArgMask == 0 && call->cdArgCnt == 0);

            // Other than that, we just have to deal with the regmasks.
            regMaskSmall gcrefRegMask = call->cdGCrefRegs & RBM_CALLEE_SAVED;
            regMaskSmall byrefRegMask = call->cdByrefRegs & RBM_CALLEE_SAVED;

            assert((gcrefRegMask & byrefRegMask) == 0);

            regMaskSmall regMask = gcrefRegMask | byrefRegMask;

            assert(call->cdOffs >= call->cdCallInstrSize);
            // call->cdOffs is actually the offset of the instruction *following* the call, so subtract
            // the call instruction size to get the offset of the actual call instruction...
            unsigned callOffset = nextOffset - call->cdCallInstrSize;

            if (noTrackedGCSlots && regMask == 0)
            {
                // No live GC refs in regs at the call -> don't record the call.
            }
            else
            {
                // Append an entry for the call if doing the real thing.
                if (mode == MAKE_REG_PTR_MODE_DO_WORK)
                {
                    pCallSites[callSiteNum]     = callOffset;
                    pCallSiteSizes[callSiteNum] = call->cdCallInstrSize;
                }
                callSiteNum++;

                // Record that these registers are live before the call...
                gcInfoRecordGCRegStateChange(gcInfoEncoder, mode, callOffset, regMask, GC_SLOT_LIVE, byrefRegMask,
                                             nullptr);
                // ...and dead after.
                gcInfoRecordGCRegStateChange(gcInfoEncoder, mode, nextOffset, regMask, GC_SLOT_DEAD, byrefRegMask,
                                             nullptr);
            }
        }
        // Make sure we've recorded the expected number of calls
        assert(mode != MAKE_REG_PTR_MODE_DO_WORK || numCallSites == callSiteNum);
        // Return the actual recorded call count to the caller
        *callCntRef = callSiteNum;

        // OK, define the call sites.
        if (mode == MAKE_REG_PTR_MODE_DO_WORK)
        {
            gcInfoEncoderWithLog->DefineCallSites(pCallSites, pCallSiteSizes, numCallSites);
        }
    }
    else // genInterruptible is false and we have an EBP-less frame
    {
        assert(compiler->genFullPtrRegMap);

        // Walk the list of pointer register/argument entries */
        // First count them.
        unsigned numCallSites = 0;

        // Now we can allocate the information (if we're in the "DO_WORK" pass...)
        unsigned* pCallSites     = nullptr;
        BYTE*     pCallSiteSizes = nullptr;
        unsigned  callSiteNum    = 0;

        if (mode == MAKE_REG_PTR_MODE_DO_WORK)
        {
            for (regPtrDsc* genRegPtrTemp = gcRegPtrList; genRegPtrTemp != nullptr;
                 genRegPtrTemp            = genRegPtrTemp->rpdNext)
            {
                if (genRegPtrTemp->rpdArg && genRegPtrTemp->rpdIsCallInstr())
                {
                    numCallSites++;
                }
            }

            if (numCallSites > 0)
            {
                pCallSites     = new (compiler, CMK_GC) unsigned[numCallSites];
                pCallSiteSizes = new (compiler, CMK_GC) BYTE[numCallSites];
            }
        }

        for (regPtrDsc* genRegPtrTemp = gcRegPtrList; genRegPtrTemp != nullptr; genRegPtrTemp = genRegPtrTemp->rpdNext)
        {
            if (genRegPtrTemp->rpdArg)
            {
                // Is this a call site?
                if (genRegPtrTemp->rpdIsCallInstr())
                {
                    // This is a true call site.

                    regMaskSmall gcrefRegMask = genRegMaskFromCalleeSavedMask(genRegPtrTemp->rpdCallGCrefRegs);

                    regMaskSmall byrefRegMask = genRegMaskFromCalleeSavedMask(genRegPtrTemp->rpdCallByrefRegs);

                    assert((gcrefRegMask & byrefRegMask) == 0);

                    regMaskSmall regMask = gcrefRegMask | byrefRegMask;

                    // The "rpdOffs" is (apparently) the offset of the following instruction already.
                    // GcInfoEncoder wants the call instruction, so subtract the width of the call instruction.
                    assert(genRegPtrTemp->rpdOffs >= genRegPtrTemp->rpdCallInstrSize);
                    unsigned callOffset = genRegPtrTemp->rpdOffs - genRegPtrTemp->rpdCallInstrSize;

                    // Tell the GCInfo encoder about these registers.  We say that the registers become live
                    // before the call instruction, and dead after.
                    gcInfoRecordGCRegStateChange(gcInfoEncoder, mode, callOffset, regMask, GC_SLOT_LIVE, byrefRegMask,
                                                 nullptr);
                    gcInfoRecordGCRegStateChange(gcInfoEncoder, mode, genRegPtrTemp->rpdOffs, regMask, GC_SLOT_DEAD,
                                                 byrefRegMask, nullptr);

                    // Also remember the call site.
                    if (mode == MAKE_REG_PTR_MODE_DO_WORK)
                    {
                        assert(pCallSites != nullptr && pCallSiteSizes != nullptr);
                        pCallSites[callSiteNum]     = callOffset;
                        pCallSiteSizes[callSiteNum] = genRegPtrTemp->rpdCallInstrSize;
                        callSiteNum++;
                    }
                }
                else
                {
                    // These are reporting outgoing stack arguments, but we don't need to report anything
                    // for partially interruptible
                    assert(genRegPtrTemp->rpdGCtypeGet() != GCT_NONE);
                    assert(genRegPtrTemp->rpdArgTypeGet() == rpdARG_PUSH);
                }
            }
        }
        // The routine is fully interruptible.
        if (mode == MAKE_REG_PTR_MODE_DO_WORK)
        {
            gcInfoEncoderWithLog->DefineCallSites(pCallSites, pCallSiteSizes, numCallSites);
        }
    }
}

void GCInfo::gcInfoRecordGCRegStateChange(GcInfoEncoder* gcInfoEncoder,
                                          MakeRegPtrMode mode,
                                          unsigned       instrOffset,
                                          regMaskSmall   regMask,
                                          GcSlotState    newState,
                                          regMaskSmall   byRefMask,
                                          regMaskSmall*  pPtrRegs)
{
    // Precondition: byRefMask is a subset of regMask.
    assert((byRefMask & ~regMask) == 0);

    GCENCODER_WITH_LOGGING(gcInfoEncoderWithLog, gcInfoEncoder);

    while (regMask)
    {
        // Get hold of the next register bit.
        regMaskTP tmpMask = genFindLowestReg(regMask);
        assert(tmpMask);

        // Remember the new state of this register.
        if (pPtrRegs != nullptr)
        {
            if (newState == GC_SLOT_DEAD)
            {
                *pPtrRegs &= ~tmpMask;
            }
            else
            {
                *pPtrRegs |= tmpMask;
            }
        }

        // Figure out which register the next bit corresponds to.
        regNumber regNum = genRegNumFromMask(tmpMask);

        /* Reserve SP future use */
        assert(regNum != REG_SPBASE);

        GcSlotFlags regFlags = GC_SLOT_BASE;
        if ((tmpMask & byRefMask) != 0)
        {
            regFlags = (GcSlotFlags)(regFlags | GC_SLOT_INTERIOR);
        }

        RegSlotIdKey rskey(regNum, regFlags);
        GcSlotId     regSlotId;
        if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
        {
            if (!m_regSlotMap->Lookup(rskey, &regSlotId))
            {
                regSlotId = gcInfoEncoderWithLog->GetRegisterSlotId(regNum, regFlags);
                m_regSlotMap->Set(rskey, regSlotId);
            }
        }
        else
        {
            BOOL b = m_regSlotMap->Lookup(rskey, &regSlotId);
            assert(b); // Should have been added in the first pass.
            gcInfoEncoderWithLog->SetSlotState(instrOffset, regSlotId, newState);
        }

        // Turn the bit we've just generated off and continue.
        regMask -= tmpMask; // EAX,ECX,EDX,EBX,---,EBP,ESI,EDI
    }
}

/**************************************************************************
 *
 *  gcMakeVarPtrTable - Generate the table of tracked stack pointer
 *      variable lifetimes.
 *
 *  In the first pass we'll allocate slot Ids
 *  In the second pass we actually generate the lifetimes.
 *
 **************************************************************************
 */

void GCInfo::gcMakeVarPtrTable(GcInfoEncoder* gcInfoEncoder, MakeRegPtrMode mode)
{
    GCENCODER_WITH_LOGGING(gcInfoEncoderWithLog, gcInfoEncoder);

    // Make sure any flags we hide in the offset are in the bits guaranteed
    // unused by alignment
    C_ASSERT((OFFSET_MASK + 1) <= sizeof(int));

#ifdef DEBUG
    if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
    {
        // Tracked variables can't be pinned, and the encoding takes
        // advantage of that by using the same bit for 'pinned' and 'this'
        // Since we don't track 'this', we should never see either flag here.
        // Check it now before we potentially add some pinned flags.
        for (varPtrDsc* varTmp = gcVarPtrList; varTmp != nullptr; varTmp = varTmp->vpdNext)
        {
            const unsigned flags = varTmp->vpdVarNum & OFFSET_MASK;
            assert((flags & pinned_OFFSET_FLAG) == 0);
            assert((flags & this_OFFSET_FLAG) == 0);
        }
    }
#endif // DEBUG

    // Only need to do this once, and only if we have EH.
    if ((mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS) && compiler->ehAnyFunclets())
    {
        gcMarkFilterVarsPinned();
    }

    for (varPtrDsc* varTmp = gcVarPtrList; varTmp != nullptr; varTmp = varTmp->vpdNext)
    {
        C_ASSERT((OFFSET_MASK + 1) <= sizeof(int));

        // Get hold of the variable's stack offset.

        unsigned lowBits = varTmp->vpdVarNum & OFFSET_MASK;

        // For negative stack offsets we must reset the low bits
        int varOffs = static_cast<int>(varTmp->vpdVarNum & ~OFFSET_MASK);

        // Compute the actual lifetime offsets.
        unsigned begOffs = varTmp->vpdBegOfs;
        unsigned endOffs = varTmp->vpdEndOfs;

        // Special case: skip any 0-length lifetimes.
        if (endOffs == begOffs)
        {
            continue;
        }

        GcSlotFlags flags = GC_SLOT_BASE;
        if ((lowBits & byref_OFFSET_FLAG) != 0)
        {
            flags = (GcSlotFlags)(flags | GC_SLOT_INTERIOR);
        }
        if ((lowBits & pinned_OFFSET_FLAG) != 0)
        {
            flags = (GcSlotFlags)(flags | GC_SLOT_PINNED);
        }

        GcStackSlotBase stackSlotBase = GC_SP_REL;
        if (compiler->isFramePointerUsed())
        {
            stackSlotBase = GC_FRAMEREG_REL;
        }
        StackSlotIdKey sskey(varOffs, (stackSlotBase == GC_FRAMEREG_REL), flags);
        GcSlotId       varSlotId;
        if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
        {
            if (!m_stackSlotMap->Lookup(sskey, &varSlotId))
            {
                varSlotId = gcInfoEncoderWithLog->GetStackSlotId(varOffs, flags, stackSlotBase);
                m_stackSlotMap->Set(sskey, varSlotId);
            }
        }
        else
        {
            BOOL b = m_stackSlotMap->Lookup(sskey, &varSlotId);
            assert(b); // Should have been added in the first pass.
            // Live from the beginning to the end.
            gcInfoEncoderWithLog->SetSlotState(begOffs, varSlotId, GC_SLOT_LIVE);
            gcInfoEncoderWithLog->SetSlotState(endOffs, varSlotId, GC_SLOT_DEAD);
        }
    }
}

void GCInfo::gcInfoRecordGCStackArgLive(GcInfoEncoder* gcInfoEncoder, MakeRegPtrMode mode, regPtrDsc* genStackPtr)
{
    // On non-x86 platforms, don't have pointer argument push/pop/kill declarations.
    // But we use the same mechanism to record writes into the outgoing argument space...
    assert(genStackPtr->rpdGCtypeGet() != GCT_NONE);
    assert(genStackPtr->rpdArg);
    assert(genStackPtr->rpdArgTypeGet() == rpdARG_PUSH);

    // We only need to report these when we're doing fuly-interruptible
    assert(compiler->codeGen->genInterruptible);

    GCENCODER_WITH_LOGGING(gcInfoEncoderWithLog, gcInfoEncoder);

    StackSlotIdKey sskey(genStackPtr->rpdPtrArg, FALSE,
                         GcSlotFlags(genStackPtr->rpdGCtypeGet() == GCT_BYREF ? GC_SLOT_INTERIOR : GC_SLOT_BASE));
    GcSlotId varSlotId;
    if (mode == MAKE_REG_PTR_MODE_ASSIGN_SLOTS)
    {
        if (!m_stackSlotMap->Lookup(sskey, &varSlotId))
        {
            varSlotId = gcInfoEncoderWithLog->GetStackSlotId(sskey.m_offset, (GcSlotFlags)sskey.m_flags, GC_SP_REL);
            m_stackSlotMap->Set(sskey, varSlotId);
        }
    }
    else
    {
        BOOL b = m_stackSlotMap->Lookup(sskey, &varSlotId);
        assert(b); // Should have been added in the first pass.
        // Live until the call.
        gcInfoEncoderWithLog->SetSlotState(genStackPtr->rpdOffs, varSlotId, GC_SLOT_LIVE);
    }
}

void GCInfo::gcInfoRecordGCStackArgsDead(GcInfoEncoder* gcInfoEncoder,
                                         unsigned       instrOffset,
                                         regPtrDsc*     genStackPtrFirst,
                                         regPtrDsc*     genStackPtrLast)
{
    // After a call all of the outgoing arguments are marked as dead.
    // The calling loop keeps track of the first argument pushed for this call
    // and passes it in as genStackPtrFirst.
    // genStackPtrLast is the call.
    // Re-walk that list and mark all outgoing arguments that we're marked as live
    // earlier, as going dead after the call.

    // We only need to report these when we're doing fuly-interruptible
    assert(compiler->codeGen->genInterruptible);

    GCENCODER_WITH_LOGGING(gcInfoEncoderWithLog, gcInfoEncoder);

    for (regPtrDsc* genRegPtrTemp = genStackPtrFirst; genRegPtrTemp != genStackPtrLast;
         genRegPtrTemp            = genRegPtrTemp->rpdNext)
    {
        if (!genRegPtrTemp->rpdArg)
        {
            continue;
        }

        assert(genRegPtrTemp->rpdGCtypeGet() != GCT_NONE);
        assert(genRegPtrTemp->rpdArgTypeGet() == rpdARG_PUSH);

        StackSlotIdKey sskey(genRegPtrTemp->rpdPtrArg, FALSE,
                             genRegPtrTemp->rpdGCtypeGet() == GCT_BYREF ? GC_SLOT_INTERIOR : GC_SLOT_BASE);
        GcSlotId varSlotId;
        BOOL     b = m_stackSlotMap->Lookup(sskey, &varSlotId);
        assert(b); // Should have been added in the first pass.
        // Live until the call.
        gcInfoEncoderWithLog->SetSlotState(instrOffset, varSlotId, GC_SLOT_DEAD);
    }
}

#undef GCENCODER_WITH_LOGGING

#endif // !JIT32_GCENCODER

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