summaryrefslogtreecommitdiff
path: root/src/vm/compile.cpp
blob: 28283b662e490c2a600ada5a394a940c29d74ffe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
// 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.
// ===========================================================================
// File: compile.cpp
//

//
// Support for zap compiler and zap files 
// ===========================================================================



#include "common.h"

#ifdef FEATURE_PREJIT 

#include <corcompile.h>

#include "assemblyspec.hpp"

#include "compile.h"
#include "excep.h"
#include "field.h"
#include "eeconfig.h"
#include "zapsig.h"
#include "gcrefmap.h"


#include "virtualcallstub.h"
#include "typeparse.h"
#include "typestring.h"
#include "dllimport.h"
#include "comdelegate.h"
#include "stringarraylist.h"

#ifdef FEATURE_COMINTEROP
#include "clrtocomcall.h"
#include "comtoclrcall.h"
#include "winrttypenameconverter.h"
#endif // FEATURE_COMINTEROP

#include "dllimportcallback.h"
#include "caparser.h"
#include "sigbuilder.h"
#include "cgensys.h"
#include "peimagelayout.inl"


#ifdef FEATURE_COMINTEROP
#include "clrprivbinderwinrt.h"
#include "winrthelpers.h"
#endif

#ifdef CROSSGEN_COMPILE
#include "crossgenroresolvenamespace.h"
#endif

#ifndef NO_NGENPDB
#include <cvinfo.h>
#endif

#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif

#include "argdestination.h"

#include "versionresilienthashcode.h"
#include "inlinetracking.h"

#ifdef CROSSGEN_COMPILE
CompilationDomain * theDomain;
#endif

VerboseLevel g_CorCompileVerboseLevel = CORCOMPILE_NO_LOG;

//
// CEECompileInfo implements most of ICorCompileInfo
//

HRESULT CEECompileInfo::Startup(  BOOL fForceDebug,
                                  BOOL fForceProfiling,
                                  BOOL fForceInstrument)
{
    SystemDomain::SetCompilationOverrides(fForceDebug,
                                          fForceProfiling,
                                          fForceInstrument);

    HRESULT hr = S_OK;

    m_fCachingOfInliningHintsEnabled = TRUE;

    _ASSERTE(!g_fEEStarted && !g_fEEInit && "You cannot run the EE inside an NGEN compilation process");

    if (!g_fEEStarted && !g_fEEInit)
    {
#ifdef CROSSGEN_COMPILE
        GetSystemInfo(&g_SystemInfo);

        theDomain = new CompilationDomain(fForceDebug,
                                          fForceProfiling,
                                          fForceInstrument);
#endif

        // When NGEN'ing this call may execute EE code, e.g. the managed code to set up
        // the SharedDomain.
        hr = InitializeEE(COINITEE_DEFAULT);
    }

    //
    // JIT interface expects to be called with
    // preemptive GC enabled
    //
    if (SUCCEEDED(hr)) {
#ifdef _DEBUG
        Thread *pThread = GetThread();
        _ASSERTE(pThread);
#endif

        GCX_PREEMP_NO_DTOR();
    }

    return hr;
}

HRESULT CEECompileInfo::CreateDomain(ICorCompilationDomain **ppDomain,
                                     IMetaDataAssemblyEmit *pEmitter,
                                     BOOL fForceDebug,
                                     BOOL fForceProfiling,
                                     BOOL fForceInstrument)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

#ifndef CROSSGEN_COMPILE
    AppDomainCreationHolder<CompilationDomain> pCompilationDomain;

    pCompilationDomain.Assign(new CompilationDomain(fForceDebug,
                                                    fForceProfiling,
                                                    fForceInstrument));
#else
    CompilationDomain * pCompilationDomain = theDomain;
#endif

    {
        SystemDomain::LockHolder lh;
        pCompilationDomain->Init();
    }

    if (pEmitter)
        pCompilationDomain->SetDependencyEmitter(pEmitter);
    

#ifdef DEBUGGING_SUPPORTED 
    // Notify the debugger here, before the thread transitions into the
    // AD to finish the setup, and before any assemblies are loaded into it.
    SystemDomain::PublishAppDomainAndInformDebugger(pCompilationDomain);
#endif // DEBUGGING_SUPPORTED
    
    pCompilationDomain->LoadSystemAssemblies();
    
    pCompilationDomain->SetupSharedStatics();
    
    *ppDomain = static_cast<ICorCompilationDomain*>(pCompilationDomain);
    
    {
        GCX_COOP();

        ENTER_DOMAIN_PTR(pCompilationDomain,ADV_COMPILATION)
        {
            pCompilationDomain->InitializeDomainContext(TRUE, NULL, NULL);

            pCompilationDomain->SetFriendlyName(W("Compilation Domain"));
            SystemDomain::System()->LoadDomain(pCompilationDomain);

#ifndef CROSSGEN_COMPILE
            pCompilationDomain.DoneCreating();
#endif
        }
        END_DOMAIN_TRANSITION;
    }

    COOPERATIVE_TRANSITION_END();

    return S_OK;
}


HRESULT CEECompileInfo::DestroyDomain(ICorCompilationDomain *pDomain)
{
    STANDARD_VM_CONTRACT;

#ifndef CROSSGEN_COMPILE
    COOPERATIVE_TRANSITION_BEGIN();

    GCX_COOP();

    CompilationDomain *pCompilationDomain = (CompilationDomain *) pDomain;

    // DDB 175659: Make sure that canCallNeedsRestore() returns FALSE during compilation 
    // domain shutdown.
    pCompilationDomain->setCannotCallNeedsRestore();

    pCompilationDomain->Unload(TRUE);

    COOPERATIVE_TRANSITION_END();
#endif

    return S_OK;
}

HRESULT MakeCrossDomainCallbackWorker(
    CROSS_DOMAIN_CALLBACK   pfnCallback,
    LPVOID                  pArgs)
{
    STATIC_CONTRACT_MODE_COOPERATIVE;
    STATIC_CONTRACT_SO_INTOLERANT;

    HRESULT hrRetVal = E_UNEXPECTED;
    BEGIN_SO_TOLERANT_CODE(GetThread());
    hrRetVal = pfnCallback(pArgs);
    END_SO_TOLERANT_CODE;
    return hrRetVal;
}

HRESULT CEECompileInfo::MakeCrossDomainCallback(
    ICorCompilationDomain*  pDomain,
    CROSS_DOMAIN_CALLBACK   pfnCallback,
    LPVOID                  pArgs)
{
    STANDARD_VM_CONTRACT;

    HRESULT hrRetVal = E_UNEXPECTED;

    COOPERATIVE_TRANSITION_BEGIN();

    {
        // Switch to cooperative mode to switch appdomains
        GCX_COOP();

        ENTER_DOMAIN_PTR((CompilationDomain*)pDomain,ADV_COMPILATION)
        {
            //
            // Switch to preemptive mode on before calling back into
            // the zapper
            //
            
            GCX_PREEMP();
            
            hrRetVal = MakeCrossDomainCallbackWorker(pfnCallback, pArgs);
        }
        END_DOMAIN_TRANSITION;
    }

    COOPERATIVE_TRANSITION_END();

    return hrRetVal;
}

#ifdef TRITON_STRESS_NEED_IMPL
int LogToSvcLogger(LPCWSTR format, ...)
{
    STANDARD_VM_CONTRACT;

    StackSString s;

    va_list args;
    va_start(args, format);
    s.VPrintf(format, args);
    va_end(args);

    GetSvcLogger()->Printf(W("%s"), s.GetUnicode());

    return 0;
}
#endif

HRESULT CEECompileInfo::LoadAssemblyByPath(
    LPCWSTR                  wzPath,
    
    // Normally this is FALSE, but crossgen /CreatePDB sets this to TRUE, so it can
    // explicitly load an NI by path
    BOOL                     fExplicitBindToNativeImage,

    CORINFO_ASSEMBLY_HANDLE *pHandle)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = S_OK;

    COOPERATIVE_TRANSITION_BEGIN();

    Assembly * pAssembly;
    HRESULT    hrProcessLibraryBitnessMismatch = S_OK;

    // We don't want to do a LoadFrom, since they do not work with ngen. Instead,
    // read the metadata from the file and do a bind based on that.

    EX_TRY
    {
        // Pre-open the image so we can grab some metadata to help initialize the
        // binder's AssemblySpec, which we'll use later to load the assembly for real.

        PEImageHolder pImage;


        if (pImage == NULL)
        {
            pImage = PEImage::OpenImage(
                wzPath,

                // If we're explicitly binding to an NGEN image, we do not want the cache
                // this PEImage for use later, as pointers that need fixup
                // Normal caching is done when we open it "for real" further down when we
                // call LoadDomainAssembly().
                fExplicitBindToNativeImage ? MDInternalImport_NoCache : MDInternalImport_Default);
        }

        if (fExplicitBindToNativeImage && !pImage->HasReadyToRunHeader())
        {
            pImage->VerifyIsNIAssembly();
        }
        else
        {
            pImage->VerifyIsAssembly();
        }

        // Check to make sure the bitness of the assembly matches the bitness of the process
        // we will be loading it into and store the result.  If a COR_IMAGE_ERROR gets thrown
        // by LoadAssembly then we can blame it on bitness mismatch.  We do the check here
        // and not in the CATCH to distinguish between the COR_IMAGE_ERROR that can be thrown by
        // VerifyIsAssembly (not necessarily a bitness mismatch) and that from LoadAssembly
#ifdef _TARGET_64BIT_
        if (pImage->Has32BitNTHeaders())
        {
            hrProcessLibraryBitnessMismatch = PEFMT_E_32BIT;
        }
#else // !_TARGET_64BIT_
        if (!pImage->Has32BitNTHeaders())
        {
            hrProcessLibraryBitnessMismatch = PEFMT_E_64BIT;
        }
#endif // !_TARGET_64BIT_
        
        AssemblySpec spec;
        spec.InitializeSpec(TokenFromRid(1, mdtAssembly), pImage->GetMDImport(), NULL, FALSE);

        if (spec.IsMscorlib())
        {
            pAssembly = SystemDomain::System()->SystemAssembly();
        }
        else
        {
            AppDomain * pDomain = AppDomain::GetCurrentDomain();

            PEAssemblyHolder pAssemblyHolder;
            BOOL isWinRT = FALSE;

#ifdef FEATURE_COMINTEROP
            isWinRT = spec.IsContentType_WindowsRuntime();
            if (isWinRT)
            {
                LPCSTR  szNameSpace;
                LPCSTR  szTypeName;
                // It does not make sense to pass the file name to recieve fake type name for empty WinMDs, because we would use the name 
                // for binding in next call to BindAssemblySpec which would fail for fake WinRT type name
                // We will throw/return the error instead and the caller will recognize it and react to it by not creating the ngen image - 
                // see code:Zapper::ComputeDependenciesInCurrentDomain
                IfFailThrow(::GetFirstWinRTTypeDef(pImage->GetMDImport(), &szNameSpace, &szTypeName, NULL, NULL));
                spec.SetWindowsRuntimeType(szNameSpace, szTypeName);
            }
#endif //FEATURE_COMINTEROP

            // If there is a host binder then use it to bind the assembly.
            if (pDomain->HasLoadContextHostBinder() || isWinRT)
            {
                pAssemblyHolder = pDomain->BindAssemblySpec(&spec, TRUE, FALSE);
            }
            else
            {
                //ExplicitBind
                CoreBindResult bindResult;
                spec.SetCodeBase(pImage->GetPath());
                spec.Bind(
                    pDomain,
                    TRUE,                   // fThrowOnFileNotFound
                    &bindResult, 

                    // fNgenExplicitBind: Generally during NGEN compilation, this is
                    // TRUE, meaning "I am NGEN, and I am doing an explicit bind to the IL
                    // image, so don't infer the NI and try to open it, because I already
                    // have it open". But if we're executing crossgen /CreatePDB, this should
                    // be FALSE so that downstream code doesn't assume we're explicitly
                    // trying to bind to an IL image (we're actually explicitly trying to
                    // open an NI).
                    !fExplicitBindToNativeImage,

                    // fExplicitBindToNativeImage: Most callers want this FALSE; but crossgen
                    // /CreatePDB explicitly specifies NI names to open, and cannot assume
                    // that IL assemblies will be available.
                    fExplicitBindToNativeImage
                    );
                pAssemblyHolder = PEAssembly::Open(&bindResult,FALSE,FALSE);
            }

            // Now load assembly into domain.
            DomainAssembly * pDomainAssembly = pDomain->LoadDomainAssembly(&spec, pAssemblyHolder, FILE_LOAD_BEGIN);

            if (spec.CanUseWithBindingCache() && pDomainAssembly->CanUseWithBindingCache())
                pDomain->AddAssemblyToCache(&spec, pDomainAssembly);


            {
                // Mark the assembly before it gets fully loaded and NGen image dependencies are verified. This is necessary
                // to allow skipping compilation if there is NGen image already.
                pDomainAssembly->GetFile()->SetSafeToHardBindTo();
            }

            pAssembly = pDomain->LoadAssembly(&spec, pAssemblyHolder, FILE_LOADED);

            // Add a dependency to the current assembly.  This is done to match the behavior
            // of LoadAssemblyFusion, so that the same native image is generated whether we
            // ngen install by file name or by assembly name.
            pDomain->ToCompilationDomain()->AddDependency(&spec, pAssemblyHolder);
        }

        // Kind of a workaround - if we could have loaded this assembly via normal load,

        *pHandle = CORINFO_ASSEMBLY_HANDLE(pAssembly);
    }
    EX_CATCH_HRESULT(hr);
    
    if ( hrProcessLibraryBitnessMismatch != S_OK && ( hr == COR_E_BADIMAGEFORMAT || hr == HRESULT_FROM_WIN32(ERROR_BAD_EXE_FORMAT) ) )
    {
        hr = hrProcessLibraryBitnessMismatch;
    }
    
    COOPERATIVE_TRANSITION_END();

    return hr;
}


#ifdef FEATURE_COMINTEROP
HRESULT CEECompileInfo::LoadTypeRefWinRT(
    IMDInternalImport       *pAssemblyImport,
    mdTypeRef               ref,
    CORINFO_ASSEMBLY_HANDLE *pHandle)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = S_OK;

    ReleaseHolder<IAssemblyName> pAssemblyName;

    COOPERATIVE_TRANSITION_BEGIN();
    
    EX_TRY
    {
        Assembly *pAssembly;

        mdToken tkResolutionScope;
        if(FAILED(pAssemblyImport->GetResolutionScopeOfTypeRef(ref, &tkResolutionScope)))
            hr = S_FALSE;
        else if(TypeFromToken(tkResolutionScope) == mdtAssemblyRef)
        {
            DWORD dwAssemblyRefFlags;
            IfFailThrow(pAssemblyImport->GetAssemblyRefProps(tkResolutionScope, NULL, NULL,
                                                     NULL, NULL,
                                                     NULL, NULL, &dwAssemblyRefFlags));
            if (IsAfContentType_WindowsRuntime(dwAssemblyRefFlags))
            {
                LPCSTR psznamespace;
                LPCSTR pszname;
                pAssemblyImport->GetNameOfTypeRef(ref, &psznamespace, &pszname);
                AssemblySpec spec;
                spec.InitializeSpec(tkResolutionScope, pAssemblyImport, NULL, FALSE);
                spec.SetWindowsRuntimeType(psznamespace, pszname);
                
                _ASSERTE(spec.HasBindableIdentity());
                
                pAssembly = spec.LoadAssembly(FILE_LOADED);

                //
                // Return the module handle
                //

                *pHandle = CORINFO_ASSEMBLY_HANDLE(pAssembly);
            }
            else
            {
                hr = S_FALSE;
            }
        }
        else
        {
            hr = S_FALSE;
        }
    }
    EX_CATCH_HRESULT(hr);

    COOPERATIVE_TRANSITION_END();

    return hr;
}
#endif

BOOL CEECompileInfo::IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule)
{
    WRAPPER_NO_CONTRACT;

    return ((Module*)hModule)->IsInCurrentVersionBubble();
}

HRESULT CEECompileInfo::LoadAssemblyModule(
    CORINFO_ASSEMBLY_HANDLE assembly,
    mdFile                  file,
    CORINFO_MODULE_HANDLE   *pHandle)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    Assembly *pAssembly = (Assembly*) assembly;

    Module *pModule = pAssembly->GetManifestModule()->LoadModule(GetAppDomain(), file, TRUE)->GetModule();

    //
    // Return the module handle
    //

    *pHandle = CORINFO_MODULE_HANDLE(pModule);

    COOPERATIVE_TRANSITION_END();

    return S_OK;
}


BOOL CEECompileInfo::CheckAssemblyZap(
    CORINFO_ASSEMBLY_HANDLE assembly, 
  __out_ecount_opt(*cAssemblyManifestModulePath) 
    LPWSTR                  assemblyManifestModulePath, 
    LPDWORD                 cAssemblyManifestModulePath)
{
    STANDARD_VM_CONTRACT;

    BOOL result = FALSE;

    COOPERATIVE_TRANSITION_BEGIN();

    Assembly *pAssembly = (Assembly*) assembly;

    if (pAssembly->GetManifestFile()->HasNativeImage())
    {
        PEImage *pImage = pAssembly->GetManifestFile()->GetPersistentNativeImage();

        if (assemblyManifestModulePath != NULL)
        {
            DWORD length = pImage->GetPath().GetCount();
            if (length > *cAssemblyManifestModulePath)
            {
                length = *cAssemblyManifestModulePath - 1;
                wcsncpy_s(assemblyManifestModulePath, *cAssemblyManifestModulePath, pImage->GetPath(), length);
                assemblyManifestModulePath[length] = 0;
            }
            else
                wcscpy_s(assemblyManifestModulePath, *cAssemblyManifestModulePath, pImage->GetPath());
        }

        result = TRUE;
    }

    COOPERATIVE_TRANSITION_END();

    return result;
}

HRESULT CEECompileInfo::SetCompilationTarget(CORINFO_ASSEMBLY_HANDLE     assembly,
                                             CORINFO_MODULE_HANDLE       module)
{
    STANDARD_VM_CONTRACT;

    Assembly *pAssembly = (Assembly *) assembly;
    Module *pModule = (Module *) module;

    CompilationDomain *pDomain = (CompilationDomain *) GetAppDomain();
    pDomain->SetTarget(pAssembly, pModule);

    if (!pAssembly->IsSystem())
    {
        // It is possible to get through a compile without calling BindAssemblySpec on mscorlib.  This
        // is because refs to mscorlib are short circuited in a number of places.  So, we will explicitly
        // add it to our dependencies.

        AssemblySpec mscorlib;
        mscorlib.InitializeSpec(SystemDomain::SystemFile());
        GetAppDomain()->BindAssemblySpec(&mscorlib,TRUE,FALSE);

        if (!IsReadyToRunCompilation() && !SystemDomain::SystemFile()->HasNativeImage())
        {
            if (!CLRConfig::GetConfigValue(CLRConfig::INTERNAL_NgenAllowMscorlibSoftbind))
            {
                return NGEN_E_SYS_ASM_NI_MISSING;
            }
        }
    }

    return S_OK;
}

IMDInternalImport *
    CEECompileInfo::GetAssemblyMetaDataImport(CORINFO_ASSEMBLY_HANDLE assembly)
{
    STANDARD_VM_CONTRACT;

    IMDInternalImport * import;

    COOPERATIVE_TRANSITION_BEGIN();

    import = ((Assembly*)assembly)->GetManifestImport();
    import->AddRef();

    COOPERATIVE_TRANSITION_END();

    return import;
}

IMDInternalImport *
    CEECompileInfo::GetModuleMetaDataImport(CORINFO_MODULE_HANDLE scope)
{
    STANDARD_VM_CONTRACT;

    IMDInternalImport * import;

    COOPERATIVE_TRANSITION_BEGIN();

    import = ((Module*)scope)->GetMDImport();
    import->AddRef();

    COOPERATIVE_TRANSITION_END();

    return import;
}

CORINFO_MODULE_HANDLE
    CEECompileInfo::GetAssemblyModule(CORINFO_ASSEMBLY_HANDLE assembly)
{
    STANDARD_VM_CONTRACT;

    CANNOTTHROWCOMPLUSEXCEPTION();

    return (CORINFO_MODULE_HANDLE) ((Assembly*)assembly)->GetManifestModule();
}

PEDecoder * CEECompileInfo::GetModuleDecoder(CORINFO_MODULE_HANDLE scope)
{
    STANDARD_VM_CONTRACT;

    PEDecoder *result;

    COOPERATIVE_TRANSITION_BEGIN();

    //
    // Note that we go ahead and return the native image if we are using that.
    // It contains everything we need to ngen.  However, the caller must be
    // aware and check for the native image case, since some fields will need to come
    // from the CORCOMPILE_ZAP_HEADER rather than the PE headers.
    //

    PEFile *pFile = ((Module *) scope)->GetFile();

    if (pFile->HasNativeImage())
        result = pFile->GetLoadedNative();
    else
        result = pFile->GetLoadedIL();

    COOPERATIVE_TRANSITION_END();

    return result;

}

void CEECompileInfo::GetModuleFileName(CORINFO_MODULE_HANDLE scope,
                                       SString               &result)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    result.Set(((Module*)scope)->GetPath());

    COOPERATIVE_TRANSITION_END();
}

CORINFO_ASSEMBLY_HANDLE
    CEECompileInfo::GetModuleAssembly(CORINFO_MODULE_HANDLE module)
{
    STANDARD_VM_CONTRACT;

    CANNOTTHROWCOMPLUSEXCEPTION();

    return (CORINFO_ASSEMBLY_HANDLE) GetModule(module)->GetAssembly();
}


#ifdef CROSSGEN_COMPILE
//
// Small wrapper to avoid having too many crossgen ifdefs
//
class AssemblyForLoadHint
{
    IMDInternalImport * m_pMDImport;
public:
    AssemblyForLoadHint(IMDInternalImport * pMDImport)
        : m_pMDImport(pMDImport)
    {
    }

    IMDInternalImport * GetManifestImport()
    {
        return m_pMDImport;
    }

    LPCSTR GetSimpleName()
    {
        LPCSTR name = "";
        IfFailThrow(m_pMDImport->GetAssemblyProps(TokenFromRid(1, mdtAssembly), NULL, NULL, NULL, &name, NULL, NULL));
        return name;
    }

    void GetDisplayName(SString &result, DWORD flags = 0)
    {
        PEAssembly::GetFullyQualifiedAssemblyName(m_pMDImport, TokenFromRid(1, mdtAssembly), result, flags);
    }

    BOOL IsSystem()
    {
        return FALSE;
    }
};
#endif

//-----------------------------------------------------------------------------
// For an assembly with a full name of "Foo, Version=2.0.0.0, Culture=neutral",
// we want any of these attributes specifications to match:
//    DependencyAttribute("Foo", LoadHint.Always)
//    DependencyAttribute("Foo,", LoadHint.Always)
//    DependencyAttribute("Foo, Version=2.0.0.0, Culture=neutral", LoadHint.Always)
// The second case of "Foo," is needed only for intra-V2 compat as
// it was supported at one point during V2. We may be able to get rid of it.
template <typename ASSEMBLY>
BOOL IsAssemblySpecifiedInCA(ASSEMBLY * pAssembly, SString dependencyNameFromCA)
{
    STANDARD_VM_CONTRACT;

    // First, check for this:
    //    DependencyAttribute("Foo", LoadHint.Always)
    StackSString simpleName(SString::Utf8, pAssembly->GetSimpleName());
    if (simpleName.EqualsCaseInsensitive(dependencyNameFromCA, PEImage::GetFileSystemLocale()))
        return TRUE;

    // Now, check for this:
    //    DependencyAttribute("Foo,", LoadHint.Always)
    SString comma(W(","));
    StackSString simpleNameWithComma(simpleName, comma);
    if (simpleNameWithComma.EqualsCaseInsensitive(dependencyNameFromCA, PEImage::GetFileSystemLocale()))
        return TRUE;

    // Finally:
    //    DependencyAttribute("Foo, Version=2.0.0.0, Culture=neutral", LoadHint.Always)
    StackSString fullName;
    pAssembly->GetDisplayName(fullName);
    if (fullName.EqualsCaseInsensitive(dependencyNameFromCA))
        return TRUE;

    return FALSE;
}

template <typename ASSEMBLY>
void GetLoadHint(ASSEMBLY * pAssembly, ASSEMBLY *pAssemblyDependency,
                 LoadHintEnum *loadHint, LoadHintEnum *defaultLoadHint = NULL)
{
    STANDARD_VM_CONTRACT;

    *loadHint = LoadDefault;

    if (g_pConfig->NgenHardBind() == EEConfig::NGEN_HARD_BIND_ALL)
        *loadHint = LoadAlways;

    const BYTE  *pbAttr;                // Custom attribute data as a BYTE*.
    ULONG       cbAttr;                 // Size of custom attribute data.
    mdToken     mdAssembly;

    // Look for the binding custom attribute
    {
        IMDInternalImport *pImport = pAssembly->GetManifestImport();

        IfFailThrow(pImport->GetAssemblyFromScope(&mdAssembly));

        MDEnumHolder hEnum(pImport);        // Enumerator for custom attributes
        IfFailThrow(pImport->EnumCustomAttributeByNameInit(mdAssembly, DEPENDENCY_TYPE, &hEnum));

        mdCustomAttribute tkAttribute;      // A custom attribute on this assembly.
        while (pImport->EnumNext(&hEnum, &tkAttribute))
        {
            // Get raw custom attribute.
            IfFailThrow(pImport->GetCustomAttributeAsBlob(tkAttribute, (const void**)&pbAttr, &cbAttr));

            CustomAttributeParser cap(pbAttr, cbAttr);

            IfFailThrow(cap.ValidateProlog());

            // Extract string from custom attribute
            LPCUTF8 szString;
            ULONG   cbString;
            IfFailThrow(cap.GetNonNullString(&szString, &cbString));

            // Convert the string to Unicode.
            StackSString dependencyNameFromCA(SString::Utf8, szString, cbString);

            if (IsAssemblySpecifiedInCA(pAssemblyDependency, dependencyNameFromCA))
            {
                // Get dependency setting
                UINT32 u4;
                IfFailThrow(cap.GetU4(&u4));
                *loadHint = (LoadHintEnum)u4;
                break;
            }
        }
    }

    // If not preference is specified, look for the built-in assembly preference
    if (*loadHint == LoadDefault || defaultLoadHint != NULL)
    {
        IMDInternalImport *pImportDependency = pAssemblyDependency->GetManifestImport();

        IfFailThrow(pImportDependency->GetAssemblyFromScope(&mdAssembly));

        HRESULT hr = pImportDependency->GetCustomAttributeByName(mdAssembly,
            DEFAULTDEPENDENCY_TYPE,
            (const void**)&pbAttr, &cbAttr);
        IfFailThrow(hr);

        // Parse the attribute
        if (hr == S_OK)
        {
            CustomAttributeParser cap(pbAttr, cbAttr);
            IfFailThrow(cap.ValidateProlog());

            // Get default bind setting
            UINT32 u4 = 0;
            IfFailThrow(cap.GetU4(&u4));

            if (pAssemblyDependency->IsSystem() && CLRConfig::GetConfigValue(CLRConfig::INTERNAL_NgenAllowMscorlibSoftbind))
            {
                u4 = LoadDefault;
            }

            if (defaultLoadHint)
                *defaultLoadHint = (LoadHintEnum) u4;
            else
                *loadHint = (LoadHintEnum) u4;
        }
    }
}

HRESULT CEECompileInfo::GetLoadHint(CORINFO_ASSEMBLY_HANDLE hAssembly,
                                    CORINFO_ASSEMBLY_HANDLE hAssemblyDependency,
                                    LoadHintEnum *loadHint,
                                    LoadHintEnum *defaultLoadHint)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = S_OK;

    EX_TRY
    {
        Assembly *pAssembly           = (Assembly *) hAssembly;
        Assembly *pAssemblyDependency = (Assembly *) hAssemblyDependency;

        ::GetLoadHint(pAssembly, pAssemblyDependency, loadHint, defaultLoadHint);
    }
    EX_CATCH_HRESULT(hr);

    return hr;
}

HRESULT CEECompileInfo::GetAssemblyVersionInfo(CORINFO_ASSEMBLY_HANDLE hAssembly,
                                               CORCOMPILE_VERSION_INFO *pInfo)
{
    STANDARD_VM_CONTRACT;

    Assembly *pAssembly = (Assembly *) hAssembly;

    pAssembly->GetDomainAssembly()->GetCurrentVersionInfo(pInfo);

    return S_OK;
}

void CEECompileInfo::GetAssemblyCodeBase(CORINFO_ASSEMBLY_HANDLE hAssembly, SString &result)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    Assembly *pAssembly = (Assembly *)hAssembly;
    _ASSERTE(pAssembly != NULL);

    pAssembly->GetCodeBase(result);

    COOPERATIVE_TRANSITION_END();
}

//=================================================================================

void FakePromote(PTR_PTR_Object ppObj, ScanContext *pSC, uint32_t dwFlags)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    _ASSERTE(*ppObj == NULL);
    *(CORCOMPILE_GCREFMAP_TOKENS *)ppObj = (dwFlags & GC_CALL_INTERIOR) ? GCREFMAP_INTERIOR : GCREFMAP_REF;
}

//=================================================================================

void FakePromoteCarefully(promote_func *fn, Object **ppObj, ScanContext *pSC, uint32_t dwFlags)
{
    (*fn)(ppObj, pSC, dwFlags);
}

//=================================================================================

void FakeGcScanRoots(MetaSig& msig, ArgIterator& argit, MethodDesc * pMD, BYTE * pFrame)
{
    STANDARD_VM_CONTRACT;

    ScanContext sc;

    // Encode generic instantiation arg
    if (argit.HasParamType())
    {
        // Note that intrinsic array methods have hidden instantiation arg too, but it is not reported to GC
        if (pMD->RequiresInstMethodDescArg())
            *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetParamTypeArgOffset()) = GCREFMAP_METHOD_PARAM;
        else 
        if (pMD->RequiresInstMethodTableArg())
            *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetParamTypeArgOffset()) = GCREFMAP_TYPE_PARAM;
    }

    // If the function has a this pointer, add it to the mask
    if (argit.HasThis())
    {
        BOOL interior = pMD->GetMethodTable()->IsValueType() && !pMD->IsUnboxingStub();

        FakePromote((Object **)(pFrame + argit.GetThisOffset()), &sc, interior ? GC_CALL_INTERIOR : 0);
    }

    if (argit.IsVarArg())
    {
        *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetVASigCookieOffset()) = GCREFMAP_VASIG_COOKIE;

        // We are done for varargs - the remaining arguments are reported via vasig cookie
        return;
    }

    // Also if the method has a return buffer, then it is the first argument, and could be an interior ref,
    // so always promote it.
    if (argit.HasRetBuffArg())
    {
        FakePromote((Object **)(pFrame + argit.GetRetBuffArgOffset()), &sc, GC_CALL_INTERIOR);
    }

    //
    // Now iterate the arguments
    //

    // Cycle through the arguments, and call msig.GcScanRoots for each
    int argOffset;
    while ((argOffset = argit.GetNextOffset()) != TransitionBlock::InvalidOffset)
    {
        ArgDestination argDest(pFrame, argOffset, argit.GetArgLocDescForStructInRegs());
        msig.GcScanRoots(&argDest, &FakePromote, &sc, &FakePromoteCarefully);
    }
}

void CEECompileInfo::GetCallRefMap(CORINFO_METHOD_HANDLE hMethod, GCRefMapBuilder * pBuilder)
{
#ifdef _DEBUG
    DWORD dwInitialLength = pBuilder->GetBlobLength();
    UINT nTokensWritten = 0;
#endif

    MethodDesc *pMD = (MethodDesc *)hMethod;

    MetaSig msig(pMD);
    ArgIterator argit(&msig);

    UINT nStackBytes = argit.SizeOfFrameArgumentArray();

    // Allocate a fake stack
    CQuickBytes qbFakeStack;
    qbFakeStack.AllocThrows(sizeof(TransitionBlock) + nStackBytes);
    memset(qbFakeStack.Ptr(), 0, qbFakeStack.Size());

    BYTE * pFrame = (BYTE *)qbFakeStack.Ptr();

    // Fill it in
    FakeGcScanRoots(msig, argit, pMD, pFrame);

    //
    // Encode the ref map
    //

    UINT nStackSlots;

#ifdef _TARGET_X86_
    UINT cbStackPop = argit.CbStackPop();
    pBuilder->WriteStackPop(cbStackPop / sizeof(TADDR));

    nStackSlots = nStackBytes / sizeof(TADDR) + NUM_ARGUMENT_REGISTERS;
#else
    nStackSlots = (sizeof(TransitionBlock) + nStackBytes - TransitionBlock::GetOffsetOfArgumentRegisters()) / TARGET_POINTER_SIZE;
#endif

    for (UINT pos = 0; pos < nStackSlots; pos++)
    {
        int ofs;

#ifdef _TARGET_X86_
        ofs = (pos < NUM_ARGUMENT_REGISTERS) ?
            (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) :
            (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR));
#else
        ofs = TransitionBlock::GetOffsetOfArgumentRegisters() + pos * TARGET_POINTER_SIZE;
#endif

        CORCOMPILE_GCREFMAP_TOKENS token = *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + ofs);

        if (token != 0)
        {
            INDEBUG(nTokensWritten++;)
            pBuilder->WriteToken(pos, token);
        }
    }

    // We are done
    pBuilder->Flush();

#ifdef _DEBUG
    //
    // Verify that decoder produces what got encoded
    //

    DWORD dwFinalLength;
    PVOID pBlob = pBuilder->GetBlob(&dwFinalLength);

    UINT nTokensDecoded = 0;

    GCRefMapDecoder decoder((BYTE *)pBlob + dwInitialLength);

#ifdef _TARGET_X86_
    _ASSERTE(decoder.ReadStackPop() * sizeof(TADDR) == cbStackPop);
#endif

    while (!decoder.AtEnd())
    {
        int pos = decoder.CurrentPos();
        int token = decoder.ReadToken();

        int ofs;

#ifdef _TARGET_X86_
        ofs = (pos < NUM_ARGUMENT_REGISTERS) ?
            (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) :
            (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR));
#else
        ofs = TransitionBlock::GetOffsetOfArgumentRegisters() + pos * TARGET_POINTER_SIZE;
#endif

        if (token != 0)
        {
            _ASSERTE(*(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + ofs) == token);
            nTokensDecoded++;
        }
    }

    // Verify that all tokens got decoded.
    _ASSERTE(nTokensWritten == nTokensDecoded);
#endif // _DEBUG
}

void CEECompileInfo::CompressDebugInfo(
    IN ICorDebugInfo::OffsetMapping * pOffsetMapping,
    IN ULONG            iOffsetMapping,
    IN ICorDebugInfo::NativeVarInfo * pNativeVarInfo,
    IN ULONG            iNativeVarInfo,
    IN OUT SBuffer    * pDebugInfoBuffer
    )
{
    STANDARD_VM_CONTRACT;

    CompressDebugInfo::CompressBoundariesAndVars(pOffsetMapping, iOffsetMapping, pNativeVarInfo, iNativeVarInfo, pDebugInfoBuffer, NULL);
}

HRESULT CEECompileInfo::GetBaseJitFlags(
        IN  CORINFO_METHOD_HANDLE   hMethod,
        OUT CORJIT_FLAGS           *pFlags)
{
    STANDARD_VM_CONTRACT;

    MethodDesc *pMD = (MethodDesc *)hMethod;
    *pFlags = CEEInfo::GetBaseCompileFlags(pMD);

    return S_OK;
}

//=================================================================================

#ifdef _DEBUG 

static struct
{
    size_t total;
    size_t noEmbed;
    size_t array;
    size_t primitives;
    size_t szarray;
} embedStats;

#endif // _DEBUG

BOOL CEEPreloader::CanEmbedClassID(CORINFO_CLASS_HANDLE    typeHandle)
{
    STANDARD_VM_CONTRACT;

    TypeHandle hnd = (TypeHandle) typeHandle;
    return m_image->CanEagerBindToTypeHandle(hnd) && 
        !hnd.AsMethodTable()->NeedsCrossModuleGenericsStaticsInfo();
}

BOOL CEEPreloader::CanEmbedModuleID(CORINFO_MODULE_HANDLE    moduleHandle)
{
    STANDARD_VM_CONTRACT;

    return m_image->CanEagerBindToModule((Module *)moduleHandle);
}

BOOL CEEPreloader::CanEmbedModuleHandle(CORINFO_MODULE_HANDLE    moduleHandle)
{
    STANDARD_VM_CONTRACT;

    return m_image->CanEagerBindToModule((Module *)moduleHandle);

}
BOOL CEEPreloader::CanEmbedClassHandle(CORINFO_CLASS_HANDLE    typeHandle)
{
    STANDARD_VM_CONTRACT;

    TypeHandle hnd = (TypeHandle) typeHandle;

    BOOL decision = m_image->CanEagerBindToTypeHandle(hnd);

#ifdef _DEBUG 
    embedStats.total++;

    if (!decision)
        embedStats.noEmbed++;

    if (hnd.IsArray())
    {
        embedStats.array++;

        CorElementType arrType = hnd.AsArray()->GetInternalCorElementType();
        if (arrType == ELEMENT_TYPE_SZARRAY)
            embedStats.szarray++;

        CorElementType elemType = hnd.AsArray()->GetArrayElementTypeHandle().GetInternalCorElementType();
        if (elemType <= ELEMENT_TYPE_R8)
            embedStats.primitives++;
    }
#endif // _DEBUG
    return decision;
}


/*static*/ BOOL CanEmbedMethodDescViaContext(MethodDesc * pMethod, MethodDesc * pContext)
{
    STANDARD_VM_CONTRACT;

    if (pContext != NULL)
    {
        _ASSERTE(pContext->GetLoaderModule() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());

        // a method can always embed its own handle
        if (pContext == pMethod)
        {
            return TRUE;
        }

        // Methods that are tightly bound to the same method table can 
        // always refer each other directly. This check allows methods 
        // within one speculative generic instantiations to call each 
        // other directly.
        //
        if ((pContext->GetMethodTable() == pMethod->GetMethodTable()) &&
            pContext->IsTightlyBoundToMethodTable() &&
            pMethod->IsTightlyBoundToMethodTable())
        {
            return TRUE;
        }
    }
    return FALSE;
}

BOOL CEEPreloader::CanEmbedMethodHandle(CORINFO_METHOD_HANDLE methodHandle, 
                                        CORINFO_METHOD_HANDLE contextHandle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc * pContext = GetMethod(contextHandle);
    MethodDesc * pMethod  = GetMethod(methodHandle);

    if (CanEmbedMethodDescViaContext(pMethod, pContext))
        return TRUE;

    return m_image->CanEagerBindToMethodDesc(pMethod);
}

BOOL CEEPreloader::CanEmbedFieldHandle(CORINFO_FIELD_HANDLE    fieldHandle)
{
    STANDARD_VM_CONTRACT;

    return m_image->CanEagerBindToFieldDesc((FieldDesc *) fieldHandle);

}

void* CEECompileInfo::GetStubSize(void *pStubAddress, DWORD *pSizeToCopy)
{
    CONTRACT(void*)
    {
        STANDARD_VM_CHECK;
        PRECONDITION(pStubAddress && pSizeToCopy);
    }
    CONTRACT_END;

    Stub *stub = Stub::RecoverStubAndSize((TADDR)pStubAddress, pSizeToCopy);
    _ASSERTE(*pSizeToCopy > sizeof(Stub));
    RETURN stub;
}

HRESULT CEECompileInfo::GetStubClone(void *pStub, BYTE *pBuffer, DWORD dwBufferSize)
{
    STANDARD_VM_CONTRACT;

    if (pStub == NULL)
    {
        return E_INVALIDARG;
    }

    return (reinterpret_cast<Stub *>(pStub)->CloneStub(pBuffer, dwBufferSize));
}

HRESULT CEECompileInfo::GetTypeDef(CORINFO_CLASS_HANDLE classHandle,
                                   mdTypeDef *token)
{
    STANDARD_VM_CONTRACT;

    CANNOTTHROWCOMPLUSEXCEPTION();

    TypeHandle hClass(classHandle);

    *token = hClass.GetCl();

    return S_OK;
}

HRESULT CEECompileInfo::GetMethodDef(CORINFO_METHOD_HANDLE methodHandle,
                                     mdMethodDef *token)
{
    STANDARD_VM_CONTRACT;

    CANNOTTHROWCOMPLUSEXCEPTION();

    *token = ((MethodDesc*)methodHandle)->GetMemberDef();

    return S_OK;
}

/*********************************************************************/
// Used to determine if a methodHandle can be embedded in an ngen image.
// Depends on what things are persisted by CEEPreloader

BOOL CEEPreloader::CanEmbedFunctionEntryPoint(
    CORINFO_METHOD_HANDLE   methodHandle,
    CORINFO_METHOD_HANDLE   contextHandle, /* = NULL */
    CORINFO_ACCESS_FLAGS    accessFlags /*=CORINFO_ACCESS_ANY*/)
{
    STANDARD_VM_CONTRACT;

    MethodDesc * pMethod = GetMethod(methodHandle);
    MethodDesc * pContext = GetMethod(contextHandle);

    // IsRemotingInterceptedViaVirtualDispatch is a rather special case.
    //
    // Other remoting intercepts are implemented by one of:
    //  (1) in DoPrestub (for non-virtual calls)
    //  (2) by transparent proxy vtables, where all the entries in the vtable
    //      go to the same code.
    //
    // However when calling virtual functions non-virtually the JIT interface
    // pointer to the code for the function in a stub 
    // (see GetNonVirtualEntryPointForVirtualMethod).  
    // Thus we cannot embed non-virtual calls to these functions because we 
    // don't save these stubs.  Unlike most other remoting stubs these ones 
    // are NOT inserted by DoPrestub.
    //
    if (((accessFlags & CORINFO_ACCESS_THIS) == 0) &&
        (pMethod->IsRemotingInterceptedViaVirtualDispatch()))
    {
        return FALSE;
    }

    // Methods with native callable attribute are special , since 
    // they are used as LDFTN targets.Native Callable methods
    // uses the same code path as reverse pinvoke and embedding them
    // in an ngen image require saving the reverse pinvoke stubs.
    if (pMethod->HasNativeCallableAttribute())
        return FALSE;

    return TRUE;
}

BOOL CEEPreloader::DoesMethodNeedRestoringBeforePrestubIsRun(
        CORINFO_METHOD_HANDLE   methodHandle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc * ftn = GetMethod(methodHandle);

    // The restore mechanism for InstantiatedMethodDescs (IMDs) is complicated, and causes
    // circular dependency complications with the GC if we hardbind to the prestub/precode
    // of an unrestored IMD. As such, we're eliminating hardbinding to unrestored MethodDescs
    // that belong to generic types.

    //@TODO: The reduction may be overkill, and we may consider refining the cases.

    // Specifically, InstantiatedMethodDescs can have preferred zap modules different than
    // the zap modules for their owning types. As such, in a soft-binding case a MethodDesc
    // may not be able to trace back to its owning Module without hitting an unrestored
    // fixup token. For example, the 64-bit JIT can not yet provide generic type arguments
    // and uses instantiating stubs to call static methods on generic types. If such an stub
    // belong to a module other than the module in which the generic type is declared, then
    // it is possible for the MethodTable::m_pEEClass or the EEClass::m_pModule pointers to 
    // be unrestored. The complication arises when a call to the prestub/precode of such 
    // an unrestored IMD causes us try to restore the IMD and this in turn causes us to 
    // transition to preemptive GC and as such GC needs the metadata signature from the IMD 
    // to iterate its arguments. But since we're currently restoring the IMD, we may not be 
    // able to get to the signature, and as such we're stuck.

    // The same problem exists for instantiation arguments. We may need the instantiation
    // arguments while walking the signature during GC, and if they are not restored we're stuck.

    if (ftn->HasClassOrMethodInstantiation())
    {
        if (ftn->NeedsRestore(m_image))
            return TRUE;
    }

    return FALSE;
}

BOOL CEECompileInfo::IsNativeCallableMethod(CORINFO_METHOD_HANDLE handle)
{
    WRAPPER_NO_CONTRACT;

    MethodDesc * pMethod = GetMethod(handle);
    return pMethod->HasNativeCallableAttribute();
}

BOOL CEEPreloader::CanSkipDependencyActivation(CORINFO_METHOD_HANDLE   context,
                                               CORINFO_MODULE_HANDLE   moduleFrom,
                                               CORINFO_MODULE_HANDLE   moduleTo)
{
    STANDARD_VM_CONTRACT;

    // Can't skip any fixups for speculative generic instantiations
    if (Module::GetPreferredZapModuleForMethodDesc(GetMethod(context)) != m_image->GetModule())
        return FALSE;

    // We don't need a fixup for eager bound dependencies since we are going to have 
    // an uncontional one already.
    return m_image->CanEagerBindToModule((Module *)moduleTo);
}

CORINFO_MODULE_HANDLE CEEPreloader::GetPreferredZapModuleForClassHandle(
        CORINFO_CLASS_HANDLE classHnd)
{
    STANDARD_VM_CONTRACT;

    return CORINFO_MODULE_HANDLE(Module::GetPreferredZapModuleForTypeHandle(TypeHandle(classHnd)));
}

// This method is called directly from zapper
extern BOOL CanDeduplicateCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod);

BOOL CanDeduplicateCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();

    // For now, the deduplication is supported for IL stubs only
    DynamicMethodDesc * pMethod = GetMethod(method)->AsDynamicMethodDesc();
    DynamicMethodDesc * pDuplicateMethod = GetMethod(duplicateMethod)->AsDynamicMethodDesc();

    //
    // Make sure that the return types match (for code:Thread::HijackThread)
    //

#ifdef _TARGET_X86_
    MetaSig msig1(pMethod);
    MetaSig msig2(pDuplicateMethod);
    if (!msig1.HasFPReturn() != !msig2.HasFPReturn())
        return FALSE;
#endif // _TARGET_X86_

    MetaSig::RETURNTYPE returnType = pMethod->ReturnsObject();
    MetaSig::RETURNTYPE returnTypeDuplicate = pDuplicateMethod->ReturnsObject();

    if (returnType != returnTypeDuplicate)
        return FALSE;

    //
    // Do not enable deduplication of structs returned in registers
    //

    if (returnType == MetaSig::RETVALUETYPE)
        return FALSE;

    //
    // Make sure that the IL stub flags match
    //

    if (pMethod->GetExtendedFlags() != pDuplicateMethod->GetExtendedFlags())
        return FALSE;

    return TRUE;
}

void CEEPreloader::NoteDeduplicatedCode(CORINFO_METHOD_HANDLE method, CORINFO_METHOD_HANDLE duplicateMethod)
{
    STANDARD_VM_CONTRACT;

#ifndef FEATURE_FULL_NGEN // Deduplication
    DuplicateMethodEntry e;
    e.pMD = GetMethod(method);
    e.pDuplicateMD = GetMethod(duplicateMethod);
    m_duplicateMethodsHash.Add(e);
#endif
}

HRESULT CEECompileInfo::GetFieldDef(CORINFO_FIELD_HANDLE fieldHandle,
                                    mdFieldDef *token)
{
    STANDARD_VM_CONTRACT;

    CANNOTTHROWCOMPLUSEXCEPTION();

    *token = ((FieldDesc*)fieldHandle)->GetMemberDef();

    return S_OK;
}

void CEECompileInfo::EncodeModuleAsIndexes(CORINFO_MODULE_HANDLE  fromHandle,
                                           CORINFO_MODULE_HANDLE  handle,
                                           DWORD*                 pAssemblyIndex,
                                           DWORD*                 pModuleIndex,
                                           IMetaDataAssemblyEmit* pAssemblyEmit)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    Module *fromModule = GetModule(fromHandle);
    Assembly *fromAssembly = fromModule->GetAssembly();

    Module *module = GetModule(handle);
    Assembly *assembly = module->GetAssembly();

    if (assembly == fromAssembly)
        *pAssemblyIndex = 0;
    else
    {
        UPTR    result;
        mdToken token;

        CompilationDomain *pDomain = GetAppDomain()->ToCompilationDomain();
    
        RefCache *pRefCache = pDomain->GetRefCache(fromModule);
        if (!pRefCache)
            ThrowOutOfMemory();

        
        if (!assembly->GetManifestFile()->HasBindableIdentity())
        {
            // If the module that we'd like to encode for a later fixup doesn't have
            // a bindable identity, then this will fail at runtime. So, we ask the
            // compilation domain for a matching assembly with a bindable identity.
            // This is possible because this module must have been bound in the past,
            // and the compilation domain will keep track of at least one corresponding
            // bindable identity.
            AssemblySpec defSpec;
            defSpec.InitializeSpec(assembly->GetManifestFile());

            AssemblySpec* pRefSpec = pDomain->FindAssemblyRefSpecForDefSpec(&defSpec);
            _ASSERTE(pRefSpec != nullptr);

            IfFailThrow(pRefSpec->EmitToken(pAssemblyEmit, &token, TRUE, TRUE));
            token += fromModule->GetAssemblyRefMax();
        }
        else
        {
            result = pRefCache->m_sAssemblyRefMap.LookupValue((UPTR)assembly, NULL);

            if (result == (UPTR)INVALIDENTRY)
                token = fromModule->FindAssemblyRef(assembly);
            else
                token = (mdAssemblyRef) result;

            if (IsNilToken(token))
            {
                token = fromAssembly->AddAssemblyRef(assembly, pAssemblyEmit);
                token += fromModule->GetAssemblyRefMax();
            }
        }

        *pAssemblyIndex = RidFromToken(token);

        pRefCache->m_sAssemblyRefMap.InsertValue((UPTR) assembly, (UPTR)token);
    }

    if (module == assembly->GetManifestModule())
        *pModuleIndex = 0;
    else
    {
        _ASSERTE(module->GetModuleRef() != mdFileNil);
        *pModuleIndex = RidFromToken(module->GetModuleRef());
    }

    COOPERATIVE_TRANSITION_END();
}

void CEECompileInfo::EncodeClass(
                         CORINFO_MODULE_HANDLE referencingModule,
                         CORINFO_CLASS_HANDLE  classHandle,
                         SigBuilder *          pSigBuilder,
                         LPVOID                pEncodeModuleContext,
                         ENCODEMODULE_CALLBACK pfnEncodeModule)
{
    STANDARD_VM_CONTRACT;

    TypeHandle th(classHandle);

    ZapSig zapSig((Module *)referencingModule, pEncodeModuleContext, ZapSig::NormalTokens,
                  (EncodeModuleCallback) pfnEncodeModule, NULL);

    COOPERATIVE_TRANSITION_BEGIN();

    BOOL fSuccess;
    fSuccess = zapSig.GetSignatureForTypeHandle(th, pSigBuilder);
    _ASSERTE(fSuccess);

    COOPERATIVE_TRANSITION_END();
}

CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForMscorlib()
{
    STANDARD_VM_CONTRACT;

    return CORINFO_MODULE_HANDLE(SystemDomain::SystemModule());
}

CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForEmbeddableType(CORINFO_CLASS_HANDLE clsHnd)
{
    STANDARD_VM_CONTRACT;

    TypeHandle t = TypeHandle(clsHnd);
    return CORINFO_MODULE_HANDLE(t.GetLoaderModule());
}

CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForEmbeddableMethod(CORINFO_METHOD_HANDLE methHnd)
{
    STANDARD_VM_CONTRACT;

    MethodDesc *pMD = GetMethod(methHnd);
    return CORINFO_MODULE_HANDLE(pMD->GetLoaderModule());
}

CORINFO_MODULE_HANDLE CEECompileInfo::GetLoaderModuleForEmbeddableField(CORINFO_FIELD_HANDLE fieldHnd)
{
    STANDARD_VM_CONTRACT;

    FieldDesc *pFD = (FieldDesc *) fieldHnd;
    return CORINFO_MODULE_HANDLE(pFD->GetLoaderModule());
}

void CEECompileInfo::EncodeMethod(
                          CORINFO_MODULE_HANDLE referencingModule,
                          CORINFO_METHOD_HANDLE handle,
                          SigBuilder *          pSigBuilder,
                          LPVOID                pEncodeModuleContext,
                          ENCODEMODULE_CALLBACK pfnEncodeModule,
                          CORINFO_RESOLVED_TOKEN * pResolvedToken,
                          CORINFO_RESOLVED_TOKEN * pConstrainedResolvedToken,
                          BOOL                  fEncodeUsingResolvedTokenSpecStreams)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();
    MethodDesc *pMethod = GetMethod(handle);

    BOOL fSuccess;
    fSuccess = ZapSig::EncodeMethod(pMethod, 
                              (Module *) referencingModule,
                              pSigBuilder,
                              pEncodeModuleContext, 
                              pfnEncodeModule, NULL,
                              pResolvedToken, pConstrainedResolvedToken,
                              fEncodeUsingResolvedTokenSpecStreams);
    _ASSERTE(fSuccess);

    COOPERATIVE_TRANSITION_END();
}

mdToken CEECompileInfo::TryEncodeMethodAsToken(
                CORINFO_METHOD_HANDLE handle,
                CORINFO_RESOLVED_TOKEN * pResolvedToken,
                CORINFO_MODULE_HANDLE * referencingModule)
{
    STANDARD_VM_CONTRACT;

    MethodDesc * pMethod = GetMethod(handle);

#ifdef FEATURE_READYTORUN_COMPILER
    if (IsReadyToRunCompilation())
    {
        _ASSERTE(pResolvedToken != NULL);

        Module * pReferencingModule = (Module *)pResolvedToken->tokenScope;

        if (!pReferencingModule->IsInCurrentVersionBubble())
            return mdTokenNil;

        // If this is a MemberRef with TypeSpec, we might come to here because we resolved the method
        // into a non-generic base class in the same version bubble. However, since we don't have the
        // proper type context during ExternalMethodFixupWorker, we can't really encode using token
        if (pResolvedToken->pTypeSpec != NULL)
            return mdTokenNil;
            
        unsigned methodToken = pResolvedToken->token;

        switch (TypeFromToken(methodToken))
        {
        case mdtMethodDef:
            if (pReferencingModule->LookupMethodDef(methodToken) != pMethod)
                return mdTokenNil;
            break;

        case mdtMemberRef:
            if (pReferencingModule->LookupMemberRefAsMethod(methodToken) != pMethod)
                return mdTokenNil;
            break;

        default:
            return mdTokenNil;
        }

        *referencingModule = CORINFO_MODULE_HANDLE(pReferencingModule);
        return methodToken;
    }
#endif // FEATURE_READYTORUN_COMPILER

    Module *pModule = pMethod->GetModule();
    if (!pModule->IsInCurrentVersionBubble())
    {
        Module * pTargetModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
        *referencingModule = CORINFO_MODULE_HANDLE(pTargetModule);
        return pTargetModule->LookupMemberRefByMethodDesc(pMethod);
    }
    else
    {
        mdToken defToken = pMethod->GetMemberDef();
        if (pModule->LookupMethodDef(defToken) == pMethod)
        {
            *referencingModule = CORINFO_MODULE_HANDLE(pModule);
            return defToken;
        }
    }

    return mdTokenNil;
}

DWORD CEECompileInfo::TryEncodeMethodSlot(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc * pMethod = GetMethod(handle);

#ifdef FEATURE_READYTORUN_COMPILER
    if (IsReadyToRunCompilation())
    {
        // We can only encode real interface methods as slots
        if (!pMethod->IsInterface() || pMethod->IsStatic())
            return (DWORD)-1;

        // And only if the interface lives in the current version bubble
        // If may be possible to relax this restriction if we can guarantee that the external interfaces are
        // really not changing. We will play it safe for now.
        if (!pMethod->GetModule()->IsInCurrentVersionBubble())
            return (DWORD)-1;
    }
#endif

    return pMethod->GetSlot();
}

void EncodeTypeInDictionarySignature(
            Module * pInfoModule,
            SigPointer ptr, 
            SigBuilder * pSigBuilder,
            LPVOID encodeContext,
            ENCODEMODULE_CALLBACK pfnEncodeModule)
{
    STANDARD_VM_CONTRACT;

    CorElementType typ = ELEMENT_TYPE_END;
    IfFailThrow(ptr.GetElemType(&typ));

    if (typ == ELEMENT_TYPE_INTERNAL)
    {
        TypeHandle th;

        IfFailThrow(ptr.GetPointer((void**)&th));

        ZapSig zapSig(pInfoModule, encodeContext, ZapSig::NormalTokens,
                      (EncodeModuleCallback) pfnEncodeModule, NULL);

        //
        // Write class
        //
        BOOL fSuccess;
        fSuccess = zapSig.GetSignatureForTypeHandle(th, pSigBuilder);
        _ASSERTE(fSuccess);

        return;
    }
    else
    if (typ == ELEMENT_TYPE_GENERICINST)
    {
        //
        // SigParser expects ELEMENT_TYPE_MODULE_ZAPSIG to be before ELEMENT_TYPE_GENERICINST
        //
        SigPointer peek(ptr);
        ULONG instType = 0;
        IfFailThrow(peek.GetData(&instType));
        _ASSERTE(instType == ELEMENT_TYPE_INTERNAL);

        TypeHandle th;
        IfFailThrow(peek.GetPointer((void **)&th));

        Module * pTypeHandleModule = th.GetModule();

        if (!pTypeHandleModule->IsInCurrentVersionBubble())
        {
            pTypeHandleModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
        }

        if (pTypeHandleModule != pInfoModule)
        {
            DWORD index = pfnEncodeModule(encodeContext, (CORINFO_MODULE_HANDLE)pTypeHandleModule);
            _ASSERTE(index != ENCODE_MODULE_FAILED);

            pSigBuilder->AppendElementType((CorElementType) ELEMENT_TYPE_MODULE_ZAPSIG);
            pSigBuilder->AppendData(index);
        }

        pSigBuilder->AppendElementType(ELEMENT_TYPE_GENERICINST);

        EncodeTypeInDictionarySignature(pTypeHandleModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
        IfFailThrow(ptr.SkipExactlyOne());

        ULONG argCnt = 0; // Get number of parameters
        IfFailThrow(ptr.GetData(&argCnt));
        pSigBuilder->AppendData(argCnt);

        while (argCnt--)
        {
            EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
            IfFailThrow(ptr.SkipExactlyOne());
        }

        return;
    }
    else if((CorElementTypeZapSig)typ == ELEMENT_TYPE_NATIVE_ARRAY_TEMPLATE_ZAPSIG)
    {
        pSigBuilder->AppendElementType((CorElementType)ELEMENT_TYPE_NATIVE_ARRAY_TEMPLATE_ZAPSIG);

        IfFailThrow(ptr.GetElemType(&typ));

        _ASSERTE(typ == ELEMENT_TYPE_SZARRAY || typ == ELEMENT_TYPE_ARRAY);
    }

    pSigBuilder->AppendElementType(typ);

    if (!CorIsPrimitiveType(typ))
    {
        switch (typ)
        {
            case ELEMENT_TYPE_VAR:
            case ELEMENT_TYPE_MVAR:
                {
                    ULONG varNum;
                    // Skip variable number
                    IfFailThrow(ptr.GetData(&varNum));
                    pSigBuilder->AppendData(varNum);
                }
                break;
            case ELEMENT_TYPE_OBJECT:
            case ELEMENT_TYPE_STRING:
            case ELEMENT_TYPE_TYPEDBYREF:
                break;

            case ELEMENT_TYPE_BYREF: //fallthru
            case ELEMENT_TYPE_PTR:
            case ELEMENT_TYPE_PINNED:
            case ELEMENT_TYPE_SZARRAY:
                EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
                IfFailThrow(ptr.SkipExactlyOne());
                break;

            case ELEMENT_TYPE_ARRAY:
                {
                    EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
                    IfFailThrow(ptr.SkipExactlyOne());

                    ULONG rank = 0; // Get rank
                    IfFailThrow(ptr.GetData(&rank));
                    pSigBuilder->AppendData(rank);

                    if (rank)
                    {
                        ULONG nsizes = 0;
                        IfFailThrow(ptr.GetData(&nsizes));
                        pSigBuilder->AppendData(nsizes);

                        while (nsizes--)
                        {
                            ULONG data = 0;
                            IfFailThrow(ptr.GetData(&data));
                            pSigBuilder->AppendData(data);
                        }

                        ULONG nlbounds = 0;
                        IfFailThrow(ptr.GetData(&nlbounds));
                        pSigBuilder->AppendData(nlbounds);

                        while (nlbounds--)
                        {
                            ULONG data = 0;
                            IfFailThrow(ptr.GetData(&data));
                            pSigBuilder->AppendData(data);
                        }
                    }
                }
                break;

            default:
                _ASSERTE(!"Unexpected element in signature");
        }
    }
}

void CEECompileInfo::EncodeGenericSignature(
            LPVOID signature,
            BOOL fMethod,
            SigBuilder * pSigBuilder,
            LPVOID encodeContext,
            ENCODEMODULE_CALLBACK pfnEncodeModule)
{
    STANDARD_VM_CONTRACT;

    Module * pInfoModule = MscorlibBinder::GetModule();

    SigPointer ptr((PCCOR_SIGNATURE)signature);

    ULONG entryKind; // DictionaryEntryKind
    IfFailThrow(ptr.GetData(&entryKind));
    pSigBuilder->AppendData(entryKind);

    if (!fMethod)
    {
        ULONG dictionaryIndex = 0;
        IfFailThrow(ptr.GetData(&dictionaryIndex));

        pSigBuilder->AppendData(dictionaryIndex);
    }

    switch (entryKind)
    {
    case DeclaringTypeHandleSlot:
        EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
        IfFailThrow(ptr.SkipExactlyOne());
        // fall through

    case TypeHandleSlot:
        EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
        IfFailThrow(ptr.SkipExactlyOne());
        break;

    case ConstrainedMethodEntrySlot:
        EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
        IfFailThrow(ptr.SkipExactlyOne());
        // fall through

    case MethodDescSlot:
    case MethodEntrySlot:
    case DispatchStubAddrSlot:
        {
            EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
            IfFailThrow(ptr.SkipExactlyOne());

            ULONG methodFlags;
            IfFailThrow(ptr.GetData(&methodFlags));
            pSigBuilder->AppendData(methodFlags);

            if ((methodFlags & ENCODE_METHOD_SIG_SlotInsteadOfToken) == 0)
            {
                EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
                IfFailThrow(ptr.SkipExactlyOne());
            }
            
            ULONG tokenOrSlot;
            IfFailThrow(ptr.GetData(&tokenOrSlot));
            pSigBuilder->AppendData(tokenOrSlot);

            if (methodFlags & ENCODE_METHOD_SIG_MethodInstantiation)
            {
                DWORD nGenericMethodArgs;
                IfFailThrow(ptr.GetData(&nGenericMethodArgs));
                pSigBuilder->AppendData(nGenericMethodArgs);

                for (DWORD i = 0; i < nGenericMethodArgs; i++)
                {
                    EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
                    IfFailThrow(ptr.SkipExactlyOne());
                }
            }
        }
        break;

    case FieldDescSlot:
        {
            EncodeTypeInDictionarySignature(pInfoModule, ptr, pSigBuilder, encodeContext, pfnEncodeModule);
            IfFailThrow(ptr.SkipExactlyOne());

            DWORD fieldIndex;
            IfFailThrow(ptr.GetData(&fieldIndex));
            pSigBuilder->AppendData(fieldIndex);
        }
        break;

    default:
        _ASSERTE(false);
    }

    ULONG dictionarySlot;
    IfFailThrow(ptr.GetData(&dictionarySlot));
    pSigBuilder->AppendData(dictionarySlot);
}

void CEECompileInfo::EncodeField(
                         CORINFO_MODULE_HANDLE referencingModule,
                         CORINFO_FIELD_HANDLE  handle,
                         SigBuilder *          pSigBuilder,
                         LPVOID                encodeContext,
                         ENCODEMODULE_CALLBACK pfnEncodeModule,
                         CORINFO_RESOLVED_TOKEN * pResolvedToken, 
                         BOOL fEncodeUsingResolvedTokenSpecStreams)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    ZapSig::EncodeField(GetField(handle), 
                        (Module *) referencingModule,
                        pSigBuilder,
                        encodeContext, 
                        pfnEncodeModule,
                        pResolvedToken,
                        fEncodeUsingResolvedTokenSpecStreams);

    COOPERATIVE_TRANSITION_END();
}

BOOL CEECompileInfo::IsEmptyString(mdString token,
                                   CORINFO_MODULE_HANDLE module)
{
    STANDARD_VM_CONTRACT;

    BOOL fRet = FALSE;

    COOPERATIVE_TRANSITION_BEGIN();

    EEStringData strData;
    ((Module *)module)->InitializeStringData(token, &strData, NULL);
    fRet = (strData.GetCharCount() == 0);

    COOPERATIVE_TRANSITION_END();

    return fRet;
}

#ifdef FEATURE_READYTORUN_COMPILER
CORCOMPILE_FIXUP_BLOB_KIND CEECompileInfo::GetFieldBaseOffset(
        CORINFO_CLASS_HANDLE classHnd,
        DWORD * pBaseOffset)
{
    STANDARD_VM_CONTRACT;

    MethodTable * pMT = (MethodTable *)classHnd;
    Module * pModule = pMT->GetModule();

    if (!pMT->IsLayoutFixedInCurrentVersionBubble())
    {
        return pMT->IsValueType() ? ENCODE_CHECK_FIELD_OFFSET : ENCODE_FIELD_OFFSET;
    }

    if (pMT->IsValueType())
    {
        return ENCODE_NONE;
    }

    if (pMT->GetParentMethodTable()->IsInheritanceChainLayoutFixedInCurrentVersionBubble())
    {
        return ENCODE_NONE;
    }

    if (pMT->HasLayout())
    {
        // We won't try to be smart for classes with layout.
        // They are complex to get right, and very rare anyway.
        return ENCODE_FIELD_OFFSET;
    }

    *pBaseOffset = ReadyToRunInfo::GetFieldBaseOffset(pMT);
    return ENCODE_FIELD_BASE_OFFSET;
}

BOOL CEECompileInfo::NeedsTypeLayoutCheck(CORINFO_CLASS_HANDLE classHnd)
{
    STANDARD_VM_CONTRACT;

    TypeHandle th(classHnd);

    if (th.IsTypeDesc())
        return FALSE;

    MethodTable * pMT = th.AsMethodTable();

    if (!pMT->IsValueType())
        return FALSE;

    // Skip this check for equivalent types. Equivalent types are used for interop that ensures
    // matching layout.
    if (pMT->GetClass()->IsEquivalentType())
        return FALSE;

    return !pMT->IsLayoutFixedInCurrentVersionBubble();
}

extern void ComputeGCRefMap(MethodTable * pMT, BYTE * pGCRefMap, size_t cbGCRefMap);

void CEECompileInfo::EncodeTypeLayout(CORINFO_CLASS_HANDLE classHandle, SigBuilder * pSigBuilder)
{
    STANDARD_VM_CONTRACT;

    MethodTable * pMT = TypeHandle(classHandle).AsMethodTable();
    _ASSERTE(pMT->IsValueType());

    DWORD dwSize = pMT->GetNumInstanceFieldBytes();
    DWORD dwAlignment = CEEInfo::getClassAlignmentRequirementStatic(pMT);

    DWORD dwFlags = 0;

#ifdef FEATURE_HFA
    if (pMT->IsHFA())
        dwFlags |= READYTORUN_LAYOUT_HFA;
#endif

    // Check everything 
    dwFlags |= READYTORUN_LAYOUT_Alignment;
    if (dwAlignment == TARGET_POINTER_SIZE)
        dwFlags |= READYTORUN_LAYOUT_Alignment_Native;

    dwFlags |= READYTORUN_LAYOUT_GCLayout;
    if (!pMT->ContainsPointers())
        dwFlags |= READYTORUN_LAYOUT_GCLayout_Empty;

    pSigBuilder->AppendData(dwFlags);

    // Size is checked unconditionally
    pSigBuilder->AppendData(dwSize);

#ifdef FEATURE_HFA
    if (dwFlags & READYTORUN_LAYOUT_HFA)
    {
        pSigBuilder->AppendData(pMT->GetHFAType());
    }
#endif

    if ((dwFlags & READYTORUN_LAYOUT_Alignment) && !(dwFlags & READYTORUN_LAYOUT_Alignment_Native))
    {
        pSigBuilder->AppendData(dwAlignment);
    }

    if ((dwFlags & READYTORUN_LAYOUT_GCLayout) && !(dwFlags & READYTORUN_LAYOUT_GCLayout_Empty))
    {
        size_t cbGCRefMap = (dwSize / TARGET_POINTER_SIZE + 7) / 8;
        _ASSERTE(cbGCRefMap > 0);

        BYTE * pGCRefMap = (BYTE *)_alloca(cbGCRefMap);

        ComputeGCRefMap(pMT, pGCRefMap, cbGCRefMap);

        for (size_t i = 0; i < cbGCRefMap; i++)
            pSigBuilder->AppendByte(pGCRefMap[i]);
    }
}

BOOL CEECompileInfo::AreAllClassesFullyLoaded(CORINFO_MODULE_HANDLE moduleHandle)
{
    STANDARD_VM_CONTRACT;

    return ((Module *)moduleHandle)->AreAllClassesFullyLoaded();
}

int CEECompileInfo::GetVersionResilientTypeHashCode(CORINFO_MODULE_HANDLE moduleHandle, mdToken token)
{
    STANDARD_VM_CONTRACT;

    int dwHashCode;
    if (!::GetVersionResilientTypeHashCode(((Module *)moduleHandle)->GetMDImport(), token, &dwHashCode))
        ThrowHR(COR_E_BADIMAGEFORMAT);

    return dwHashCode;
}

int CEECompileInfo::GetVersionResilientMethodHashCode(CORINFO_METHOD_HANDLE methodHandle)
{
    STANDARD_VM_CONTRACT;

    return ::GetVersionResilientMethodHashCode(GetMethod(methodHandle));
}

#endif // FEATURE_READYTORUN_COMPILER

BOOL CEECompileInfo::HasCustomAttribute(CORINFO_METHOD_HANDLE method, LPCSTR customAttributeName)
{
    STANDARD_VM_CONTRACT;

    MethodDesc * pMD = GetMethod(method);
    return S_OK == pMD->GetMDImport()->GetCustomAttributeByName(pMD->GetMemberDef(), customAttributeName, NULL, NULL);
}

#define OMFConst_Read            0x0001
#define OMFConst_Write           0x0002
#define OMFConst_Exec            0x0004
#define OMFConst_F32Bit          0x0008
#define OMFConst_ReservedBits1   0x00f0
#define OMFConst_FSel            0x0100
#define OMFConst_FAbs            0x0200
#define OMFConst_ReservedBits2   0x0C00
#define OMFConst_FGroup          0x1000
#define OMFConst_ReservedBits3   0xE000

#define OMF_StandardText  (OMFConst_FSel|OMFConst_F32Bit|OMFConst_Exec|OMFConst_Read) // 0x10D
#define OMF_SentinelType  (OMFConst_FAbs|OMFConst_F32Bit) // 0x208


// ----------------------------------------------------------------------------
// NGEN PDB SUPPORT
// 
// The NGEN PDB format consists of structs stacked together into buffers, which are
// passed to the PDB API. For a description of the structures, see
// InternalApis\vctools\inc\cvinfo.h.
// 
// The interface to the PDB used below is NGEN-specific, and is exposed via
// diasymreader.dll. For a description of this interface, see ISymNGenWriter2 inside
// public\devdiv\inc\corsym.h and debugger\sh\symwrtr\ngenpdbwriter.h,cpp
// ----------------------------------------------------------------------------

#if defined(NO_NGENPDB) && !defined(FEATURE_PERFMAP)
BOOL CEECompileInfo::GetIsGeneratingNgenPDB() 
{
    return FALSE; 
}

void CEECompileInfo::SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB) 
{
}

BOOL IsNgenPDBCompilationProcess()
{
    return FALSE;
}
#else
BOOL CEECompileInfo::GetIsGeneratingNgenPDB() 
{
    LIMITED_METHOD_DAC_CONTRACT;
    return m_fGeneratingNgenPDB; 
}

void CEECompileInfo::SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB) 
{
    LIMITED_METHOD_DAC_CONTRACT;
    m_fGeneratingNgenPDB = fGeneratingNgenPDB; 
}

BOOL IsNgenPDBCompilationProcess()
{
    LIMITED_METHOD_DAC_CONTRACT;
    return IsCompilationProcess() && g_pCEECompileInfo->GetIsGeneratingNgenPDB();
}

#endif // NO_NGENPDB && !FEATURE_PERFMAP

#ifndef NO_NGENPDB
// This is the prototype of "CreateNGenPdbWriter" exported by diasymreader.dll 
typedef HRESULT (__stdcall *CreateNGenPdbWriter_t)(const WCHAR *pwszNGenImagePath, const WCHAR *pwszPdbPath, void **ppvObj);

// Allocator to specify when requesting boundaries information for PDB
BYTE* SimpleNew(void *, size_t cBytes)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    BYTE * p = new BYTE[cBytes];
    return p;
}

// PDB convention has any IPs that don't map to source code (e.g., prolog, epilog, etc.)
// to be mapped to line number "0xFeeFee".
const int kUnmappedIP = 0xFeeFee;


// ----------------------------------------------------------------------------
// Simple pair of offsets for each source file name.  Pair includes its offset into the
// PDB string table, and its offset in the files checksum table.
// 
struct DocNameOffsets
{
    ULONG32 m_dwStrTableOffset;
    ULONG32 m_dwChksumTableOffset;
    DocNameOffsets(ULONG32 dwStrTableOffset, ULONG32 dwChksumTableOffset)
        : m_dwStrTableOffset(dwStrTableOffset), m_dwChksumTableOffset(dwChksumTableOffset)
    {
        LIMITED_METHOD_CONTRACT;
    }

    DocNameOffsets()
        : m_dwStrTableOffset((ULONG32) -1), m_dwChksumTableOffset((ULONG32) -1)
    {
        LIMITED_METHOD_CONTRACT;
    }
};


// ----------------------------------------------------------------------------
// This is used when creating the hash table which maps source file names to
// DocNameOffsets instances.  The only interesting stuff here is that:
//     * Equality is determined by a case-insensitive comparison on the source file
//         names
//     * Hashing is done by hashing the source file names
//     
struct DocNameToOffsetMapTraits : public NoRemoveSHashTraits < MapSHashTraits<LPCSTR, DocNameOffsets> >
{
public:
    static BOOL Equals(key_t k1, key_t k2)
    {
        LIMITED_METHOD_CONTRACT;

        if (k1 == NULL && k2 == NULL)
            return TRUE;
        if (k1 == NULL || k2 == NULL)
            return FALSE;
        return _stricmp(k1, k2) == 0;
    }

    static count_t Hash(key_t k)
    {
        LIMITED_METHOD_CONTRACT;

        if (k == NULL)
            return 0;
        else
            return HashiStringA(k);
    }

    typedef LPCSTR KEY;
    typedef DocNameOffsets VALUE;
    typedef NoRemoveSHashTraits < MapSHashTraits<LPCSTR, DocNameOffsets> > PARENT;
    typedef PARENT::element_t element_t;
    static const element_t Null() { LIMITED_METHOD_CONTRACT; return element_t((KEY)0,VALUE((ULONG32) -1, (ULONG32) -1)); }
    static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return e.Key() == (KEY)0; }
};


// ----------------------------------------------------------------------------
// Hash table that maps the UTF-8 string of a source file name to its corresponding
// DocNameToOffsetMapTraits
// 
class DocNameToOffsetMap : public SHash<DocNameToOffsetMapTraits>
{
    typedef SHash<DocNameToOffsetMapTraits> PARENT;
    typedef LPCSTR KEY;
    typedef DocNameOffsets VALUE;
    
public:
    void Add(KEY key, VALUE value)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            PRECONDITION(key != (KEY)0);
        }
        CONTRACTL_END;

        PARENT::Add(KeyValuePair<KEY,VALUE>(key, value));
    }

    void AddOrReplace(KEY key, VALUE value)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            PRECONDITION(key != (KEY)0);
        }
        CONTRACTL_END;

        PARENT::AddOrReplace(KeyValuePair<KEY,VALUE>(key, value));
    }

    BOOL Lookup(KEY key, VALUE* pValue)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            PRECONDITION(key != (KEY)0);
        }
        CONTRACTL_END;

        const KeyValuePair<KEY,VALUE> *pRet = PARENT::LookupPtr(key);
        if (pRet == NULL)
            return FALSE;

        *pValue = pRet->Value();
        return TRUE;
    }
};

// ----------------------------------------------------------------------------
// Simple class to sort ICorDebugInfo::OffsetMapping arrays by IL offset
// 
class QuickSortILNativeMapByIL : public CQuickSort<ICorDebugInfo::OffsetMapping>
{
  public:
    QuickSortILNativeMapByIL(
        ICorDebugInfo::OffsetMapping * rgMap,
        int cEntries)
      : CQuickSort<ICorDebugInfo::OffsetMapping>(rgMap, cEntries)
    {
        LIMITED_METHOD_CONTRACT;
    }

    int Compare(ICorDebugInfo::OffsetMapping * pFirst,
                ICorDebugInfo::OffsetMapping * pSecond)
    {
        LIMITED_METHOD_CONTRACT;

        if (pFirst->ilOffset < pSecond->ilOffset)
            return -1;
        else if (pFirst->ilOffset == pSecond->ilOffset)
            return 0;
        else
            return 1;
    }
};

// ----------------------------------------------------------------------------
// Simple class to sort IL to Native mapping arrays by Native offset
// 
class QuickSortILNativeMapByNativeOffset : public CQuickSort<ICorDebugInfo::OffsetMapping>
{
public:
    QuickSortILNativeMapByNativeOffset(
        ICorDebugInfo::OffsetMapping * rgMap,
        int cEntries)
        : CQuickSort<ICorDebugInfo::OffsetMapping>(rgMap, cEntries)
    {
        LIMITED_METHOD_CONTRACT;
    }

    int Compare(ICorDebugInfo::OffsetMapping * pFirst,
        ICorDebugInfo::OffsetMapping * pSecond)
    {
        LIMITED_METHOD_CONTRACT;

        if (pFirst->nativeOffset < pSecond->nativeOffset)
            return -1;
        else if (pFirst->nativeOffset == pSecond->nativeOffset)
            return 0;
        else
            return 1;
    }
};

// ----------------------------------------------------------------------------
// Simple structure used when merging the JIT manager's IL-to-native maps
// (ICorDebugInfo::OffsetMapping) with the IL PDB's source-to-IL map.
// 
struct MapIndexPair
{
public:
    // Index into ICorDebugInfo::OffsetMapping
    ULONG32 m_iIlNativeMap;
    
    // Corresponding index into the IL PDB's sequence point arrays
    ULONG32 m_iSeqPoints;

    MapIndexPair() : 
        m_iIlNativeMap((ULONG32) -1), 
        m_iSeqPoints((ULONG32) -1)
    {
        LIMITED_METHOD_CONTRACT;
    }
};

// ----------------------------------------------------------------------------
// Simple class to sort MapIndexPairs by native IP offset. A MapIndexPair sorts "earlier"
// if its m_iIlNativeMap index gives you an IP offset (i.e.,
// m_rgIlNativeMap[m_iIlNativeMap].nativeOffset) that is smaller.
// 
class QuickSortMapIndexPairsByNativeOffset : public CQuickSort<MapIndexPair>
{
  public:
    QuickSortMapIndexPairsByNativeOffset(
        MapIndexPair * rgMap, 
        int cEntries, 
        ICorDebugInfo::OffsetMapping * rgIlNativeMap,
        ULONG32 cIlNativeMap)
        : CQuickSort<MapIndexPair>(rgMap, cEntries),
          m_rgIlNativeMap(rgIlNativeMap),
          m_cIlNativeMap(cIlNativeMap)
    {
        LIMITED_METHOD_CONTRACT;
    }

    int Compare(MapIndexPair * pFirst,
                MapIndexPair * pSecond)
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE(pFirst->m_iIlNativeMap < m_cIlNativeMap);
        _ASSERTE(pSecond->m_iIlNativeMap < m_cIlNativeMap);

        DWORD dwFirstNativeOffset = m_rgIlNativeMap[pFirst->m_iIlNativeMap].nativeOffset;
        DWORD dwSecondNativeOffset = m_rgIlNativeMap[pSecond->m_iIlNativeMap].nativeOffset;

        if (dwFirstNativeOffset < dwSecondNativeOffset)
            return -1;
        else if (dwFirstNativeOffset == dwSecondNativeOffset)
            return 0;
        else
            return 1;
    }

protected:
    ICorDebugInfo::OffsetMapping * m_rgIlNativeMap;
    ULONG32 m_cIlNativeMap;
};

// ----------------------------------------------------------------------------
// The following 3 classes contain the code to generate PDBs
// 

// NGEN always generates PDBs with public symbols lists (so tools can map IP ranges to
// methods).  This bitmask indicates what extra info should be added to the PDB
enum PDBExtraData
{
    // Add string table subsection, files checksum subsection, and lines subsection to
    // allow tools to map IP ranges to source lines.
    kPDBLines  = 0x00000001,
};


// ----------------------------------------------------------------------------
// Manages generating all PDB data for an NGENd image.  One of these is instantiated per
// run of "ngen createpdb"
// 
class NGenPdbWriter
{
private:
    CreateNGenPdbWriter_t m_Create;
    HMODULE m_hModule;
    ReleaseHolder<ISymUnmanagedBinder> m_pBinder;
    LPCWSTR m_wszPdbPath;
    DWORD m_dwExtraData;
    LPCWSTR m_wszManagedPDBSearchPath;

public:
    NGenPdbWriter (LPCWSTR wszNativeImagePath, LPCWSTR wszPdbPath, DWORD dwExtraData, LPCWSTR wszManagedPDBSearchPath)
        : m_Create(NULL),
          m_hModule(NULL),
          m_wszPdbPath(wszPdbPath),
          m_dwExtraData(dwExtraData),
          m_wszManagedPDBSearchPath(wszManagedPDBSearchPath)
    {
        LIMITED_METHOD_CONTRACT;
    }

#define WRITER_LOAD_ERROR_MESSAGE W("Unable to load ") NATIVE_SYMBOL_READER_DLL W(".  Please ensure that ") NATIVE_SYMBOL_READER_DLL W(" is on the path.  Error='%d'\n")

    HRESULT Load(LPCWSTR wszDiasymreaderPath = nullptr)
    {
        STANDARD_VM_CONTRACT;

        HRESULT hr = S_OK;

        m_hModule = WszLoadLibrary(wszDiasymreaderPath != nullptr ? wszDiasymreaderPath : (LPCWSTR)NATIVE_SYMBOL_READER_DLL);
        if (m_hModule == NULL)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            GetSvcLogger()->Printf(WRITER_LOAD_ERROR_MESSAGE, GetLastError());
            return hr;
        }

        m_Create = reinterpret_cast<CreateNGenPdbWriter_t>(GetProcAddress(m_hModule, "CreateNGenPdbWriter"));
        if (m_Create == NULL)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            GetSvcLogger()->Printf(WRITER_LOAD_ERROR_MESSAGE, GetLastError());
            return hr;
        }

        if ((m_dwExtraData & kPDBLines) != 0)
        {
            hr = FakeCoCreateInstanceEx(
                CLSID_CorSymBinder_SxS,
                wszDiasymreaderPath != nullptr ? wszDiasymreaderPath : (LPCWSTR)NATIVE_SYMBOL_READER_DLL,
                IID_ISymUnmanagedBinder,
                (void**)&m_pBinder,
                NULL);
        }

        return hr;
    }

    HRESULT WritePDBDataForModule(Module * pModule);

    ~NGenPdbWriter()
    {
        LIMITED_METHOD_CONTRACT;

        if (m_hModule)
            FreeLibrary(m_hModule);

        m_Create = NULL;
    }
};

#define UNKNOWN_SOURCE_FILE_PATH W("unknown")

// ----------------------------------------------------------------------------
// Manages generating all PDB data for an EE Module. Directly responsible for writing the
// string table and file checksum subsections. One of these is instantiated per Module
// found when using the ModuleIterator over the CORINFO_ASSEMBLY_HANDLE corresponding to
// this invocation of NGEN createpdb.
// 
class NGenModulePdbWriter
{
private:
    // Simple holder to coordinate the PDB calls to OpenModW and CloseMod on a given PDB
    // Mod *.
    class PDBModHolder
    {
    private:
        ReleaseHolder<ISymNGenWriter2> m_pWriter;
        LPBYTE m_pMod;

    public:
        PDBModHolder()
            : m_pWriter(NULL),
              m_pMod(NULL)
        {
            LIMITED_METHOD_CONTRACT;
        }

        ~PDBModHolder()
        {
            LIMITED_METHOD_CONTRACT;

            if ((m_pWriter != NULL) && (m_pMod != NULL))
            {
                m_pWriter->CloseMod(m_pMod);
            }
        }

        HRESULT Open(ISymNGenWriter2 * pWriter, LPCWSTR wszModule, LPCWSTR wszObjFile)
        {
            LIMITED_METHOD_CONTRACT;

            _ASSERTE(m_pWriter == NULL);

            m_pWriter = pWriter;
            m_pWriter->AddRef();

            _ASSERTE(m_pMod == NULL);

            HRESULT hr = m_pWriter->OpenModW(wszModule, wszObjFile, &m_pMod);
            if (FAILED(hr))
            {
                m_pMod = NULL;
            }
            return hr;
        }

        LPBYTE GetModPtr()
        {
            LIMITED_METHOD_CONTRACT;

            _ASSERTE(m_pMod != NULL);
            return m_pMod;
        }
    };

private:
    // This holder ensures we delete a half-generated PDB file if we manage to create it
    // on disk, but fail at some point after it was created. When NGenModulePdbWriter is
    // destroyed, m_deletePDBFileHolder's destructor will delete the PDB file if there
    // was a prior error.
    // 
    //************* NOTE! *************
    // 
    // These members should appear FIRST so that they get destructed last. That way, if
    // we encounter an error generating the PDB file, we ensure that we release all PDB
    // interfaces and close the PDB file BEFORE this holder tries to *delete* the PDB
    // file. Also, keep these two in this relative order, so that m_deletePDBFileHolder
    // is destructed before m_wszPDBFilePath.
    WCHAR m_wszPDBFilePath[MAX_LONGPATH];
    DeleteFileHolder m_deletePDBFileHolder;
    // 
    // ************* NOTE! *************
    
    CreateNGenPdbWriter_t m_Create;
    LPCWSTR m_wszPdbPath;
    ReleaseHolder<ISymNGenWriter2> m_pWriter;
    Module * m_pModule;
    DWORD m_dwExtraData;
    LPCWSTR m_wszManagedPDBSearchPath;

	// Currently The DiasymWriter does not use the correct PDB signature for NGEN PDBS unless 
	// the NGEN DLL whose symbols are being generated end in .ni.dll.   Thus we copy
	// to this name if it does not follow this covention (as is true with readyToRun
	// dlls).   This variable remembers this temp file path so we can delete it after
	// Pdb generation.   If DiaSymWriter is fixed, we can remove this.  
	SString m_tempSourceDllName;

    // Interfaces for reading IL PDB info
    ReleaseHolder<ISymUnmanagedBinder> m_pBinder;
    ReleaseHolder<ISymUnmanagedReader> m_pReader;
    NewInterfaceArrayHolder<ISymUnmanagedDocument> m_rgpDocs;       // All docs in the PDB Mod
	// I know m_ilPdbCount and m_finalPdbDocCount are confusing.Here is the reason :
	// For NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection, we won't write the path info.  
	// In order to let WriteDebugSILLinesSubsection find "UNKNOWN_SOURCE_FILE_PATH" which does 
	// not exist in m_rgpDocs, no matter if we have IL PDB or not, we let m_finalPdbDocCount 
	// equal m_ilPdbDocCount + 1 and write the extra one path as "UNKNOWN_SOURCE_FILE_PATH"
    ULONG32 m_ilPdbDocCount;
    ULONG32 m_finalPdbDocCount;

    // Keeps track of source file names and how they map to offsets in the relevant PDB
    // subsections.
    DocNameToOffsetMap m_docNameToOffsetMap;

    // Holds a PDB Mod *
    PDBModHolder m_pdbMod;

    // Buffer in which to store the entire string table (i.e., list of all source file
    // names).  This buffer is held alive as long as m_docNameToOffsetMap is needed, as
    // the latter contains offsets into this buffer.
    NewArrayHolder<BYTE> m_rgbStringTableSubsection;

    HRESULT InitILPdbData();
    HRESULT WriteStringTable();
    HRESULT WriteFileChecksums();

public:
    NGenModulePdbWriter(CreateNGenPdbWriter_t Create, LPCWSTR wszPdbPath, DWORD dwExtraData, ISymUnmanagedBinder * pBinder, Module * pModule, LPCWSTR wszManagedPDBSearchPath)
        : m_Create(Create),
          m_wszPdbPath(wszPdbPath),
          m_pWriter(NULL),
          m_pModule(pModule),
          m_dwExtraData(dwExtraData),
          m_wszManagedPDBSearchPath(wszManagedPDBSearchPath),
          m_pBinder(pBinder),
          m_ilPdbDocCount(0),
          m_finalPdbDocCount(1)
    {
        LIMITED_METHOD_CONTRACT;

        if (m_pBinder != NULL)
            m_pBinder->AddRef();

        ZeroMemory(m_wszPDBFilePath, sizeof(m_wszPDBFilePath));
    }

	~NGenModulePdbWriter();
    
    HRESULT WritePDBData();

    HRESULT WriteMethodPDBData(PEImageLayout * pLoadedLayout, USHORT iCodeSection, BYTE *pCodeBase, MethodDesc * hotDesc, PCODE start, bool isILPDBProvided);
};

// ----------------------------------------------------------------------------
// Manages generating the lines subsection in the PDB data for a given managed method.
// One of these is instantiated per managed method we find when iterating through all
// methods in a Module.
// 
class NGenMethodLinesPdbWriter
{
private:
    ISymNGenWriter2 * m_pWriter;
    LPBYTE m_pMod;
    ISymUnmanagedReader * m_pReader;
    MethodDesc * m_hotDesc;
    PCODE m_start;
    USHORT m_iCodeSection;
    TADDR m_addrCodeSection;
    const IJitManager::MethodRegionInfo * m_pMethodRegionInfo;
    EECodeInfo * m_pCodeInfo;
    DocNameToOffsetMap * m_pDocNameToOffsetMap;
    bool m_isILPDBProvided;

    // IL-to-native map from JIT manager
    ULONG32 m_cIlNativeMap;
    NewArrayHolder<ICorDebugInfo::OffsetMapping> m_rgIlNativeMap;

    // IL PDB info for this one method
    NewInterfaceArrayHolder<ISymUnmanagedDocument> m_rgpDocs;  // Source files defining this method.
    NewArrayHolder<ULONG32> m_rgilOffsets;                     // Array of IL offsets for this method
    NewArrayHolder<ULONG32> m_rgnLineStarts;                   // Array of source lines for this method
    ULONG32 m_cSeqPoints;                                      // Count of above two parallel arrays

    HRESULT WriteNativeILMapPDBData();
    LPBYTE InitDebugLinesHeaderSection(
        DEBUG_S_SUBSECTION_TYPE type,
        ULONG32 ulCodeStartOffset,
        ULONG32 cbCode,
        ULONG32 lineSize,
        CV_DebugSSubsectionHeader_t **ppSubSectHeader /*out*/,
        CV_DebugSLinesHeader_t ** ppLinesHeader /*out*/,
        LPBYTE * ppbLinesSubsectionCur /*out*/);

    HRESULT WriteDebugSLinesSubsection(
        ULONG32 ulCodeStartOffset,
        ULONG32 cbCode,
        MapIndexPair * rgMapIndexPairs,
        ULONG32 cMapIndexPairs);

    HRESULT WriteDebugSILLinesSubsection(
        ULONG32 ulCodeStartOffset,
        ULONG32 cbCode,
        ICorDebugInfo::OffsetMapping * rgILNativeMap,
        ULONG32 rgILNativeMapAdjustSize);

    BOOL FinalizeLinesFileBlock(
        CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader,
        CV_Line_t * pLineBlockStart,
        CV_Line_t * pLineBlockAfterEnd
#ifdef _DEBUG
        , BOOL ignorekUnmappedIPCheck = false
#endif
        );

public:
    NGenMethodLinesPdbWriter(
        ISymNGenWriter2 * pWriter,
        LPBYTE pMod,
        ISymUnmanagedReader * pReader,
        MethodDesc * hotDesc,
        PCODE start, 
        USHORT iCodeSection, 
        TADDR addrCodeSection,
        const IJitManager::MethodRegionInfo * pMethodRegionInfo,
        EECodeInfo * pCodeInfo,
        DocNameToOffsetMap * pDocNameToOffsetMap,
        bool isILPDBProvided)
        : m_pWriter(pWriter),
          m_pMod(pMod),
          m_pReader(pReader),
          m_hotDesc(hotDesc),
          m_start(start),
          m_iCodeSection(iCodeSection),
          m_addrCodeSection(addrCodeSection),
          m_pMethodRegionInfo(pMethodRegionInfo),
          m_pCodeInfo(pCodeInfo),
          m_pDocNameToOffsetMap(pDocNameToOffsetMap),
          m_isILPDBProvided(isILPDBProvided),
          m_cIlNativeMap(0),
          m_cSeqPoints(0)
    {
        LIMITED_METHOD_CONTRACT;
    }

    HRESULT WritePDBData();
};

// ----------------------------------------------------------------------------
// NGenPdbWriter implementation



//---------------------------------------------------------------------------------------
//
// Coordinates calling all the other classes & methods to generate PDB info for the
// given Module
//
// Arguments:
//      pModule - EE Module to write PDB data for
//

HRESULT NGenPdbWriter::WritePDBDataForModule(Module * pModule)
{
    STANDARD_VM_CONTRACT;
    NGenModulePdbWriter ngenModulePdbWriter(m_Create, m_wszPdbPath, m_dwExtraData, m_pBinder, pModule, m_wszManagedPDBSearchPath);
    return ngenModulePdbWriter.WritePDBData();
}


// ----------------------------------------------------------------------------
// NGenModulePdbWriter implementation


//---------------------------------------------------------------------------------------
//
// Writes out all source files into the string table subsection for the PDB Mod*
// controlled by this NGenModulePdbWriter.  Updates m_docNameToOffsetMap to add string
// table offset for each source file as it gets added.
// 
HRESULT NGenModulePdbWriter::WriteStringTable()
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(m_pWriter != NULL);

    HRESULT hr;
    UINT64 cbStringTableEstimate =
        sizeof(DWORD) +
        sizeof(CV_DebugSSubsectionHeader_t) +
        m_finalPdbDocCount * (MAX_LONGPATH + 1);
    if (!FitsIn<ULONG32>(cbStringTableEstimate))
    {
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }
    
    m_rgbStringTableSubsection = new BYTE[ULONG32(cbStringTableEstimate)];
    LPBYTE pbStringTableSubsectionCur = m_rgbStringTableSubsection;

    // Subsection signature
    *((DWORD *) pbStringTableSubsectionCur) = CV_SIGNATURE_C13;
    pbStringTableSubsectionCur += sizeof(DWORD);

    // Subsection header
    CV_DebugSSubsectionHeader_t * pSubSectHeader = (CV_DebugSSubsectionHeader_t *) pbStringTableSubsectionCur;
    memset(pSubSectHeader, 0, sizeof(*pSubSectHeader));
    pSubSectHeader->type = DEBUG_S_STRINGTABLE;
    pbStringTableSubsectionCur += sizeof(*pSubSectHeader);
    // pSubSectHeader->cbLen counts the number of bytes that appear AFTER the subsection
    // header above (i.e., the size of the string table itself). We'll fill out
    // pSubSectHeader->cbLen below, once it's calculated

    LPBYTE pbStringTableStart = pbStringTableSubsectionCur;

    // The actual strings
    for (ULONG32 i = 0; i < m_finalPdbDocCount; i++)
    {
        // For NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection, we won't write the path info.  
        // In order to let WriteDebugSILLinesSubsection can find "UNKNOWN_SOURCE_FILE_PATH" which is 
        // not existed in m_rgpDocs, no matter we have IL PDB or not, we let m_finalPdbDocCount equals to 
        // m_ilPdbDocCount + 1 and write the extra one path as "UNKNOWN_SOURCE_FILE_PATH". That also explains
        // why we have a inconsistence between m_finalPdbDocCount and m_ilPdbDocCount.
        WCHAR wszURL[MAX_LONGPATH] = UNKNOWN_SOURCE_FILE_PATH;
        ULONG32 cchURL;
        if (i < m_ilPdbDocCount)
        {
            hr = m_rgpDocs[i]->GetURL(_countof(wszURL), &cchURL, wszURL);
            if (FAILED(hr))
                return hr;
        }
        int cbWritten = WideCharToMultiByte(
            CP_UTF8,
            0,                                      // dwFlags
            wszURL,
            -1,                                     // i.e., input is NULL-terminated
            (LPSTR) pbStringTableSubsectionCur,     // output: UTF8 string starts here
            ULONG32(cbStringTableEstimate) - 
                int(pbStringTableSubsectionCur - m_rgbStringTableSubsection),    // Available space
            NULL,                                   // lpDefaultChar
            NULL                                    // lpUsedDefaultChar
            );
        if (cbWritten == 0)
            return HRESULT_FROM_WIN32(GetLastError());

        // Remember the string table offset for later
        m_docNameToOffsetMap.AddOrReplace(
            (LPCSTR) pbStringTableSubsectionCur, 
            DocNameOffsets(
                ULONG32(pbStringTableSubsectionCur - pbStringTableStart),
                (ULONG32) -1));
        
        pbStringTableSubsectionCur += cbWritten;
        if (pbStringTableSubsectionCur >= (m_rgbStringTableSubsection + cbStringTableEstimate))
            return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }

    // Now that we know pSubSectHeader->cbLen, fill it in
    pSubSectHeader->cbLen = CV_off32_t(pbStringTableSubsectionCur - pbStringTableStart);

    // Subsection is now filled out, so use the PDB API to add it
    hr = m_pWriter->ModAddSymbols(
        m_pdbMod.GetModPtr(),
        m_rgbStringTableSubsection, 
        int(pbStringTableSubsectionCur - m_rgbStringTableSubsection));
    if (FAILED(hr))
        return hr;

    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// This takes care of actually loading the IL PDB itself, and initializing the
// ISymUnmanaged* interfaces with module-level data from the IL PDB.
// 
HRESULT NGenModulePdbWriter::InitILPdbData()
{
    // Load the managed PDB
    
    ReleaseHolder<IUnknown> pUnk = NULL;
    HRESULT hr = m_pModule->GetReadablePublicMetaDataInterface(ofReadOnly, IID_IMetaDataImport, (LPVOID *) &pUnk);
    if (FAILED(hr))
    {
        GetSvcLogger()->Printf(
            W("Unable to obtain metadata for '%s'  Error: '0x%x'.\n"),
            LPCWSTR(m_pModule->GetFile()->GetILimage()->GetPath()),
            hr);
        return hr;
    }

    hr = m_pBinder->GetReaderForFile(
        pUnk,
        m_pModule->GetFile()->GetILimage()->GetPath(),
        m_wszManagedPDBSearchPath,
        &m_pReader);
    if (FAILED(hr))
    {
        GetSvcLogger()->Printf(
            W("Unable to find managed PDB matching '%s'.  Managed PDB search path: '%s'\n"),
            LPCWSTR(m_pModule->GetFile()->GetILimage()->GetPath()),
            (((m_wszManagedPDBSearchPath == NULL) || (*m_wszManagedPDBSearchPath == W('\0'))) ?
                W("(not specified)") :
                m_wszManagedPDBSearchPath));
        return hr;
    }

    GetSvcLogger()->Log(W("Loaded managed PDB"));

    // Grab the full path of the managed PDB so we can log it
    WCHAR wszIlPdbPath[MAX_LONGPATH];
    ULONG32 cchIlPdbPath;
    hr = m_pReader->GetSymbolStoreFileName(
        _countof(wszIlPdbPath),
        &cchIlPdbPath,
        wszIlPdbPath);
    if (FAILED(hr))
    {
        GetSvcLogger()->Log(W("\n"));
    }
    else
    {
        GetSvcLogger()->Printf(W(": '%s'\n"), wszIlPdbPath);
    }

    // Read all source files names from the IL PDB
    ULONG32 cDocs;
    hr = m_pReader->GetDocuments(
        0,              // cDocsRequested
        &cDocs,
        NULL            // Array
        );
    if (FAILED(hr))
        return hr;
    
    m_rgpDocs = new ISymUnmanagedDocument * [cDocs];
    hr = m_pReader->GetDocuments(
        cDocs,
        &m_ilPdbDocCount,
        m_rgpDocs);
    if (FAILED(hr))
        return hr;
    m_finalPdbDocCount = m_ilPdbDocCount + 1;
    // Commit m_rgpDocs to calling Release() on each ISymUnmanagedDocument* in the array
    m_rgpDocs.SetElementCount(m_ilPdbDocCount);
    
    return S_OK;
}

NGenModulePdbWriter::~NGenModulePdbWriter()
{
	// Delete any temporary files we created. 
	if (m_tempSourceDllName.GetCount() != 0)
		DeleteFileW(m_tempSourceDllName);
	m_tempSourceDllName.Clear();
}

//---------------------------------------------------------------------------------------
//
// This manages writing all Module-level data to the PDB, including public symbols,
// string table, files checksum, section contribution table, and, indirectly, the lines
// subsection
// 
HRESULT NGenModulePdbWriter::WritePDBData()
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(m_pWriter == NULL);

    HRESULT hr;

    // This will try to open the managed PDB if lines info was requested.  This is a
    // likely failure point, so intentionally do this before creating the NGEN PDB file
    // on disk.
    bool isILPDBProvided = false;
    if ((m_dwExtraData & kPDBLines) != 0)
    {
        hr = InitILPdbData();
        if (FAILED(hr))
            return hr;
        isILPDBProvided = true;
    }

    // Create the PDB file we will write into.

    _ASSERTE(m_Create != NULL);
    _ASSERTE(m_pModule != NULL);

    PEImageLayout * pLoadedLayout = m_pModule->GetFile()->GetLoaded();

	// Currently DiaSymReader does not work properly generating NGEN PDBS unless 
	// the DLL whose PDB is being generated ends in .ni.*.   Unfortunately, readyToRun
	// images do not follow this convention and end up producing bad PDBS.  To fix
	// this (without changing diasymreader.dll which ships indepdendently of .Net Core)
	// we copy the file to somethign with this convention before generating the PDB
	// and delete it when we are done.  
	SString dllPath = pLoadedLayout->GetPath();
	if (!dllPath.EndsWithCaseInsensitive(W(".ni.dll")) && !dllPath.EndsWithCaseInsensitive(W(".ni.exe")))
	{
		SString::Iterator fileNameStart = dllPath.End();
		dllPath.FindBack(fileNameStart, DIRECTORY_SEPARATOR_STR_W);

		SString::Iterator ext = dllPath.End();
		dllPath.FindBack(ext, '.');

		// m_tempSourceDllName = Convertion of  INPUT.dll  to INPUT.ni.dll where the PDB lives.  
		m_tempSourceDllName = m_wszPdbPath;
		m_tempSourceDllName += SString(dllPath, fileNameStart, ext - fileNameStart);
		m_tempSourceDllName += W(".ni");
		m_tempSourceDllName += SString(dllPath, ext, dllPath.End() - ext);
		CopyFileW(dllPath, m_tempSourceDllName, false);
		dllPath = m_tempSourceDllName;
	}

    ReleaseHolder<ISymNGenWriter> pWriter1;
    hr = m_Create(dllPath, m_wszPdbPath, &pWriter1);
    if (FAILED(hr))
        return hr;
    
    hr = pWriter1->QueryInterface(IID_ISymNGenWriter2, (LPVOID*) &m_pWriter);
    if (FAILED(hr))
    {
        GetSvcLogger()->Printf(
            W("An incorrect version of diasymreader.dll was found.  Please ensure that version 11 or greater of diasymreader.dll is on the path.  You can typically find this DLL in the desktop .NET install directory for 4.5 or greater.  Error='0x%x'\n"),
            hr);
        return hr;
    }

    // PDB file is now created.  Get its path and initialize the holder so the PDB file
    // can be deleted if we don't make it successfully to the end

    hr = m_pWriter->QueryPDBNameExW(m_wszPDBFilePath, _countof(m_wszPDBFilePath));
    if (SUCCEEDED(hr))
    {
        // A failure in QueryPDBNameExW above isn't fatal--it just means we can't
        // initialize m_deletePDBFileHolder, and thus may leave the PDB file on disk if
        // there's *another* error later on. And if we do hit another error, NGEN will
        // still return an error exit code, so the worst we'll have is a bogus PDB file
        // that no one should expect works anyway.
        m_deletePDBFileHolder.Assign(m_wszPDBFilePath);
    }


    hr = m_pdbMod.Open(m_pWriter, pLoadedLayout->GetPath(), m_pModule->GetPath());
    if (FAILED(hr))
        return hr;

    hr = WriteStringTable();
    if (FAILED(hr))
        return hr;

    hr = WriteFileChecksums();
    if (FAILED(hr))
        return hr;
    

    COUNT_T sectionCount = pLoadedLayout->GetNumberOfSections();
    IMAGE_SECTION_HEADER *section = pLoadedLayout->FindFirstSection();
    COUNT_T sectionIndex = 0;
    USHORT iCodeSection = 0;
    BYTE *pCodeBase = NULL;
    while (sectionIndex < sectionCount) 
    {
        hr = m_pWriter->AddSection((USHORT)(sectionIndex + 1),
                                 OMF_StandardText, 
                                 0,
                                 section[sectionIndex].SizeOfRawData);
        if (FAILED(hr))
            return hr;

        if (strcmp((const char *)&section[sectionIndex].Name[0], ".text") == 0) {
            _ASSERTE((iCodeSection == 0) && (pCodeBase == NULL));
            iCodeSection = (USHORT)(sectionIndex + 1);
            pCodeBase = (BYTE *)section[sectionIndex].VirtualAddress;
        }

        // In order to support the DIA RVA-to-lines API against the PDB we're
        // generating, we need to update the section contribution table with each
        // section we add.
        hr = m_pWriter->ModAddSecContribEx(
            m_pdbMod.GetModPtr(),
            (USHORT)(sectionIndex + 1),
            0,
            section[sectionIndex].SizeOfRawData,
            section[sectionIndex].Characteristics,
            0,          // dwDataCrc
            0           // dwRelocCrc
            );
        if (FAILED(hr))
            return hr;

        sectionIndex++;
    }

    _ASSERTE(iCodeSection != 0);
    _ASSERTE(pCodeBase != NULL);


    // To support lines info, we need a "dummy" section, indexed as 0, for use as a
    // sentinel when MSPDB sets up its section contribution table
    hr = m_pWriter->AddSection(0,           // Dummy section 0
        OMF_SentinelType, 
        0,
        0xFFFFffff);
    if (FAILED(hr))
        return hr;
    

#ifdef FEATURE_READYTORUN_COMPILER
    if (pLoadedLayout->HasReadyToRunHeader())
    {
        ReadyToRunInfo::MethodIterator mi(m_pModule->GetReadyToRunInfo());
        while (mi.Next())
        {
            MethodDesc *hotDesc = mi.GetMethodDesc();

            hr = WriteMethodPDBData(pLoadedLayout, iCodeSection, pCodeBase, hotDesc, mi.GetMethodStartAddress(), isILPDBProvided);
            if (FAILED(hr))
                return hr;
        }
    }
    else
#endif // FEATURE_READYTORUN_COMPILER
    {
        MethodIterator mi(m_pModule);
        while (mi.Next()) 
        {
            MethodDesc *hotDesc = mi.GetMethodDesc();
            hotDesc->CheckRestore();

            hr = WriteMethodPDBData(pLoadedLayout, iCodeSection, pCodeBase, hotDesc, mi.GetMethodStartAddress(), isILPDBProvided);
            if (FAILED(hr))
                return hr;
        }
    }

    // We made it successfully to the end, so don't delete the PDB file.
    m_deletePDBFileHolder.SuppressRelease();
    return S_OK;
}

HRESULT NGenModulePdbWriter::WriteMethodPDBData(PEImageLayout * pLoadedLayout, USHORT iCodeSection, BYTE *pCodeBase, MethodDesc * hotDesc, PCODE start, bool isILPDBProvided)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr;

    EECodeInfo codeInfo(start);
    _ASSERTE(codeInfo.IsValid());

    IJitManager::MethodRegionInfo methodRegionInfo;
    codeInfo.GetMethodRegionInfo(&methodRegionInfo);

    PCODE pHotCodeStart = methodRegionInfo.hotStartAddress;
    _ASSERTE(pHotCodeStart);

    PCODE pColdCodeStart = methodRegionInfo.coldStartAddress;
	SString mAssemblyName;
	mAssemblyName.SetUTF8(m_pModule->GetAssembly()->GetSimpleName());
    SString assemblyName;
    assemblyName.SetUTF8(hotDesc->GetAssembly()->GetSimpleName());
    SString methodToken;
    methodToken.Printf("%X", hotDesc->GetMemberDef());

    // Hot name
    {
        SString fullName;
        TypeString::AppendMethodInternal(
            fullName, 
            hotDesc, 
            TypeString::FormatNamespace | TypeString::FormatSignature);
		fullName.Append(W("$#"));
		if (!mAssemblyName.Equals(assemblyName))
			fullName.Append(assemblyName);
		fullName.Append(W("#"));
        fullName.Append(methodToken);
        BSTRHolder hotNameHolder(SysAllocString(fullName.GetUnicode()));
        hr = m_pWriter->AddSymbol(hotNameHolder,
                                iCodeSection,
                                (pHotCodeStart - (TADDR)pLoadedLayout->GetBase() - (TADDR)pCodeBase));
        if (FAILED(hr))
            return hr;
    }

    // Cold name
    {
        if (pColdCodeStart) {

            SString fullNameCold;
            fullNameCold.Append(W("[COLD] "));
            TypeString::AppendMethodInternal(
                fullNameCold, 
                hotDesc, 
                TypeString::FormatNamespace | TypeString::FormatSignature);
			fullNameCold.Append(W("$#"));
			if (!mAssemblyName.Equals(assemblyName))
				fullNameCold.Append(assemblyName);
			fullNameCold.Append(W("#"));
            fullNameCold.Append(methodToken);

            BSTRHolder coldNameHolder(SysAllocString(fullNameCold.GetUnicode()));
            hr = m_pWriter->AddSymbol(coldNameHolder,
                                    iCodeSection,
                                    (pColdCodeStart - (TADDR)pLoadedLayout->GetBase() - (TADDR)pCodeBase));
                
            if (FAILED(hr))
                return hr;

        }
    }

    // Offset / lines mapping
    // Skip functions that are too big for PDB lines format
    if (FitsIn<DWORD>(methodRegionInfo.hotSize) &&
        FitsIn<DWORD>(methodRegionInfo.coldSize))
    {
        NGenMethodLinesPdbWriter methodLinesWriter(
            m_pWriter,
            m_pdbMod.GetModPtr(),
            m_pReader,
            hotDesc, 
            start, 
            iCodeSection, 
            (TADDR)pLoadedLayout->GetBase() + (TADDR)pCodeBase, 
            &methodRegionInfo, 
            &codeInfo, 
            &m_docNameToOffsetMap,
            isILPDBProvided);

        hr = methodLinesWriter.WritePDBData();
        if (FAILED(hr))
            return hr;
    }

    return S_OK;
}

// ----------------------------------------------------------------------------
// Handles writing the file checksums subsection to the PDB
// 
HRESULT NGenModulePdbWriter::WriteFileChecksums()
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(m_pWriter != NULL);

    // The file checksums subsection of the PDB (i.e., "DEBUG_S_FILECHKSMS"), is a blob
    // consisting of a few structs stacked one after the other:
    // 
    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
    // * (2) CV_DebugSSubsectionHeader_t -- the usual subsection header, with type =
    //     DEBUG_S_FILECHKSMS
    // * (3) Blob consisting of an array of checksum data -- the format of this piece is
    //     not defined via structs (not sure why), but is defined in
    //     vctools\PDB\doc\lines.docx
    //     
    HRESULT hr;

    // PDB format requires that the checksum size can always be expressed in a BYTE.
    const BYTE kcbEachChecksumEstimate = 0xFF;

    UINT64 cbChecksumSubsectionEstimate =
        sizeof(DWORD) +
        sizeof(CV_DebugSSubsectionHeader_t) +
        m_finalPdbDocCount * kcbEachChecksumEstimate;
    if (!FitsIn<ULONG32>(cbChecksumSubsectionEstimate))
    {
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }

    NewArrayHolder<BYTE> rgbChksumSubsection(new BYTE[ULONG32(cbChecksumSubsectionEstimate)]);
    LPBYTE pbChksumSubsectionCur = rgbChksumSubsection;

    // (1) Subsection signature
    *((DWORD *) pbChksumSubsectionCur) = CV_SIGNATURE_C13;
    pbChksumSubsectionCur += sizeof(DWORD);

    // (2) Subsection header
    CV_DebugSSubsectionHeader_t * pSubSectHeader = (CV_DebugSSubsectionHeader_t *) pbChksumSubsectionCur;
    memset(pSubSectHeader, 0, sizeof(*pSubSectHeader));
    pSubSectHeader->type = DEBUG_S_FILECHKSMS;
    pbChksumSubsectionCur += sizeof(*pSubSectHeader);
    // pSubSectHeader->cblen to be filled in later once we know the size

    LPBYTE pbChksumDataStart = pbChksumSubsectionCur;

    // (3) Iterate through source files, steal their checksum info from the IL PDB, and
    // write it into the NGEN PDB.
    for (ULONG32 i = 0; i < m_finalPdbDocCount; i++)
    {
        WCHAR wszURL[MAX_LONGPATH] = UNKNOWN_SOURCE_FILE_PATH;
        char szURL[MAX_LONGPATH];
        ULONG32 cchURL;


        bool isKnownSourcePath = i < m_ilPdbDocCount;
        if (isKnownSourcePath)
        {
            // For NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection, we won't write the path info.  
            // In order to let WriteDebugSILLinesSubsection can find "UNKNOWN_SOURCE_FILE_PATH" which is 
            // not existed in m_rgpDocs, no matter we have IL PDB or not, we let m_finalPdbDocCount equals to 
            // m_ilPdbDocCount + 1 and write the extra one path as "UNKNOWN_SOURCE_FILE_PATH". That also explains
            // why we have a inconsistence between m_finalPdbDocCount and m_ilPdbDocCount.
            hr = m_rgpDocs[i]->GetURL(_countof(wszURL), &cchURL, wszURL);
            if (FAILED(hr))
                return hr;
        }

        int cbWritten = WideCharToMultiByte(
            CP_UTF8,
            0,                                      // dwFlags
            wszURL,
            -1,                                     // i.e., input is NULL-terminated
            szURL,                                  // output: UTF8 string starts here
            _countof(szURL),                        // Available space
            NULL,                                   // lpDefaultChar
            NULL                                    // lpUsedDefaultChar
            );
        if (cbWritten == 0)
            return HRESULT_FROM_WIN32(GetLastError());

        // find offset into string table and add to blob; meanwhile update hash to
        // remember the offset into the cksum table
        const KeyValuePair<LPCSTR,DocNameOffsets> * pMapEntry = 
            m_docNameToOffsetMap.LookupPtr(szURL);
        if (pMapEntry == NULL)
        {
            // Should never happen, as it implies we found a source file that was never
            // written to the string table
            return E_UNEXPECTED;
        }
        DocNameOffsets docNameOffsets(pMapEntry->Value());
        docNameOffsets.m_dwChksumTableOffset = ULONG32(pbChksumSubsectionCur - pbChksumDataStart);

        // Update the map with the new docNameOffsets that contains the cksum table
        // offset as well. Note that we must ensure the key (LPCSTR) remains the same
        // (thus we explicitly ask for the Key()). This class guarantees that string
        // pointer (which comes from the string table buffer field) will remain allocated
        // as long as the map is.
        m_docNameToOffsetMap.AddOrReplace(pMapEntry->Key(), docNameOffsets);
        * (ULONG32 *) pbChksumSubsectionCur = docNameOffsets.m_dwStrTableOffset;
        pbChksumSubsectionCur += sizeof(ULONG32);

        // Checksum algorithm and bytes

        BYTE rgbChecksum[kcbEachChecksumEstimate];
        ULONG32 cbChecksum = 0;
        BYTE bChecksumAlgorithmType = CHKSUM_TYPE_NONE;
        if (isKnownSourcePath)
        {
            GUID guidChecksumAlgorithm;
            hr = m_rgpDocs[i]->GetCheckSumAlgorithmId(&guidChecksumAlgorithm);
            if (SUCCEEDED(hr))
            {
                // If we got the checksum algorithm, we can write it all out to the buffer. 
                // Else, we'll just omit the checksum info
                if (memcmp(&guidChecksumAlgorithm, &CorSym_SourceHash_MD5, sizeof(GUID)) == 0)
                    bChecksumAlgorithmType = CHKSUM_TYPE_MD5;
                else if (memcmp(&guidChecksumAlgorithm, &CorSym_SourceHash_SHA1, sizeof(GUID)) == 0)
                    bChecksumAlgorithmType = CHKSUM_TYPE_SHA1;
            }
        }

        if (bChecksumAlgorithmType != CHKSUM_TYPE_NONE)
        {
            hr = m_rgpDocs[i]->GetCheckSum(sizeof(rgbChecksum), &cbChecksum, rgbChecksum);
            if (FAILED(hr) || !FitsIn<BYTE>(cbChecksum))
            {
                // Should never happen, but just in case checksum data is invalid, just put
                // no checksum into the NGEN PDB
                bChecksumAlgorithmType = CHKSUM_TYPE_NONE;
                cbChecksum = 0;
            }
        }

        // checksum length & algorithm
        *pbChksumSubsectionCur = (BYTE) cbChecksum;             
        pbChksumSubsectionCur++;
        *pbChksumSubsectionCur = bChecksumAlgorithmType;
        pbChksumSubsectionCur++;

        // checksum data bytes
        memcpy(pbChksumSubsectionCur, rgbChecksum, cbChecksum);
        pbChksumSubsectionCur += cbChecksum;

        // Must align to the next 4-byte boundary
        LPBYTE pbChksumSubsectionCurAligned = (LPBYTE) ALIGN_UP(pbChksumSubsectionCur, 4);
        memset(pbChksumSubsectionCur, 0, pbChksumSubsectionCurAligned-pbChksumSubsectionCur);
        pbChksumSubsectionCur = pbChksumSubsectionCurAligned;
    }

    // Now that we know pSubSectHeader->cbLen, fill it in
    pSubSectHeader->cbLen = CV_off32_t(pbChksumSubsectionCur - pbChksumDataStart);

    // Subsection is now filled out, so add it
    hr = m_pWriter->ModAddSymbols(
        m_pdbMod.GetModPtr(), 
        rgbChksumSubsection, 
        int(pbChksumSubsectionCur - rgbChksumSubsection));
    if (FAILED(hr))
        return hr;

    return S_OK;
}

// ----------------------------------------------------------------------------
// NGenMethodLinesPdbWriter implementation


//---------------------------------------------------------------------------------------
//
// Manages the writing of all lines-file subsections requred for a given method.  if a
// method is hot/cold split, this will write two line-file subsections to the PDB--one
// for the hot region, and one for the cold.
//

HRESULT NGenMethodLinesPdbWriter::WritePDBData()
{
    STANDARD_VM_CONTRACT;

    if (m_hotDesc->IsNoMetadata())
    {
        // IL stubs will not have data in the IL PDB, so just skip them.
        return S_OK;
    }

    //
    // First, we'll need to merge the IL-to-native map from the JIT manager with the
    // IL-to-source map from the IL PDB. This merging is done into a single piece that
    // includes all regions of the code when it's split
    // 

    // Grab the IL-to-native map from the JIT manager
    DebugInfoRequest debugInfoRequest;
    debugInfoRequest.InitFromStartingAddr(m_hotDesc, m_start);
    BOOL fSuccess = m_pCodeInfo->GetJitManager()->GetBoundariesAndVars(
        debugInfoRequest,
        SimpleNew, NULL,            // Allocator
        &m_cIlNativeMap,
        &m_rgIlNativeMap,
        NULL, NULL);
    if (!fSuccess)
    {
        // Shouldn't happen, but just skip this method if it does
        return S_OK;
    }
    HRESULT hr;
    if (FAILED(hr = WriteNativeILMapPDBData()))
    {
        return hr;
    }

    if (!m_isILPDBProvided)
    {
        return S_OK;
    }

    // We will traverse this IL-to-native map (from the JIT) in parallel with the
    // source-to-IL map provided by the IL PDB (below).  Both need to be sorted by IL so
    // we can easily find matching entries in the two maps
    QuickSortILNativeMapByIL sorterByIl(m_rgIlNativeMap, m_cIlNativeMap);
    sorterByIl.Sort();

    // Now grab IL-to-source map from the IL PDBs (just known as "sequence points"
    // according to the IL PDB API)
    
    ReleaseHolder<ISymUnmanagedMethod> pMethod;
    hr = m_pReader->GetMethod(
        m_hotDesc->GetMemberDef(),
        &pMethod);
    if (FAILED(hr))
    {
        // Ignore any methods not included in the IL PDB.  Although we've already
        // excluded LCG & IL stubs from methods we're considering, there can still be
        // methods in the NGEN module that are not in the IL PDB (e.g., implicit ctors).
        return S_OK;
    }

    ULONG32 cSeqPointsExpected;
    hr = pMethod->GetSequencePointCount(&cSeqPointsExpected);
    if (FAILED(hr))
    {
        // Should never happen, but we can just skip this function if the IL PDB can't
        // find sequence point info
        return S_OK;
    }

    ULONG32 cSeqPointsReturned;
    m_rgilOffsets = new ULONG32[cSeqPointsExpected];
    m_rgpDocs = new ISymUnmanagedDocument * [cSeqPointsExpected];
    m_rgnLineStarts = new ULONG32[cSeqPointsExpected];
    
    //  This is guaranteed to return the sequence points sorted in order of the IL
    //  offsets (m_rgilOffsets)
    hr = pMethod->GetSequencePoints(
        cSeqPointsExpected,
        &cSeqPointsReturned,
        m_rgilOffsets,
        m_rgpDocs,
        m_rgnLineStarts,
        NULL,       // ColumnStarts not needed
        NULL,       // LineEnds not needed
        NULL);      // ColumnEnds not needed
    if (FAILED(hr))
    {
        // Shouldn't happen, but just skip this method if it does
        return S_OK;
    }
    // Commit m_rgpDocs to calling Release() on all ISymUnmanagedDocument* returned into
    // the array.
    m_rgpDocs.SetElementCount(cSeqPointsReturned);

    // Now merge the two maps together into an array of MapIndexPair structures. Traverse
    // both maps in parallel (both ordered by IL offset), looking for IL offset matches.
    // Range matching: If an entry in the IL-to-native map has no matching entry in the
    // IL PDB, then seek up in the IL PDB to the previous sequence point and merge to
    // that (assuming that previous sequence point from the IL PDB did not already have
    // an exact match to some other entry in the IL-to-native map).
    ULONG32 cMapIndexPairsMax = m_cIlNativeMap;
    NewArrayHolder<MapIndexPair> rgMapIndexPairs(new MapIndexPair [cMapIndexPairsMax]);
    ULONG32 iSeqPoints = 0;

    // Keep track (via iSeqPointLastUnmatched) of the most recent entry in the IL PDB
    // that we passed over because it had no matching entry in the IL-to-native map. We
    // may use this to do a range-match if necessary. We'll set iSeqPointLastUnmatched to
    // the currently interated IL PDB entry after our cursor in the il-to-native map
    // passed it by, but only if fCurSeqPointMatched is FALSE
    ULONG32 iSeqPointLastUnmatched = (ULONG32) -1;
    BOOL fCurSeqPointMatched = FALSE;
    
    ULONG32 iIlNativeMap = 0;
    ULONG32 iMapIndexPairs = 0;
	
    // Traverse IL PDB entries and IL-to-native map entries (both sorted by IL) in
    // parallel
    // 
    //     * Record matching indices in our output map, rgMapIndexPairs, indexed by
    //         iMapIndexPairs.
    // 
    //     * We will have at most m_cIlNativeMap entries in rgMapIndexPairs by the time
    //         we're done. (Each il-to-native map entry will be considered for inclusion
    //         in this output. Those il-to-native map entries with a match in the il PDB
    //         will be included, the rest skipped.)
    // 
    //     * iSeqPointLastUnmatched != -1 iff it equals a prior entry in the IL PDB that
    //         we skipped over because it could not be exactly matched to an entry in the
    //         il-to-native map.  In such a case, it will be considered for a
    //         range-match to the next il-to-native map entry
    while (iIlNativeMap < m_cIlNativeMap)
    {
        _ASSERTE (iMapIndexPairs < cMapIndexPairsMax);

        // IP addresses that map to "special" places (prolog, epilog, or
        // other hidden code), will just map to 0xFeeFee, as per convention
        if ((m_rgIlNativeMap[iIlNativeMap].ilOffset == NO_MAPPING) ||
            (m_rgIlNativeMap[iIlNativeMap].ilOffset == PROLOG) ||
            (m_rgIlNativeMap[iIlNativeMap].ilOffset == EPILOG))
        {
            rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap = iIlNativeMap;
            rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints = kUnmappedIP;
            iMapIndexPairs++;

            // If we were remembering a prior unmatched entry in the IL PDB, reset it
            iSeqPointLastUnmatched = (ULONG32) -1;

            // Advance il-native map, NOT il-source map
            iIlNativeMap++;
            continue;
        }

        // Cases below actually look at the IL PDB sequence point, so ensure it's still
        // in range; otherwise, we're done.
        if (iSeqPoints >= cSeqPointsReturned)
            break;

        if (m_rgIlNativeMap[iIlNativeMap].ilOffset < m_rgilOffsets[iSeqPoints])
        {
            // Our cursor over the ilnative map is behind the sourceil
            // map
            
            if (iSeqPointLastUnmatched != (ULONG32) -1)
            {
                // Range matching: This ilnative entry is behind our cursor in the
                // sourceil map, but this ilnative entry is also ahead of the previous
                // (unmatched) entry in the sourceil map. So this is a case where the JIT
                // generated sequence points that surround, without matching, that
                // previous entry in the sourceil map. So match to that previous
                // (unmatched) entry in the sourceil map.
                _ASSERTE(m_rgilOffsets[iSeqPointLastUnmatched] < m_rgIlNativeMap[iIlNativeMap].ilOffset);
                rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap = iIlNativeMap;
                rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints = iSeqPointLastUnmatched;
                iMapIndexPairs++;
                
                // Reset our memory of the last unmatched entry in the IL PDB
                iSeqPointLastUnmatched = (ULONG32) -1;
            }
			else if (iMapIndexPairs > 0)
			{
				DWORD lastMatchedilNativeIndex = rgMapIndexPairs[iMapIndexPairs - 1].m_iIlNativeMap;
				if (m_rgIlNativeMap[iIlNativeMap].ilOffset == m_rgIlNativeMap[lastMatchedilNativeIndex].ilOffset &&
					m_rgIlNativeMap[iIlNativeMap].nativeOffset < m_rgIlNativeMap[lastMatchedilNativeIndex].nativeOffset)
				{
					rgMapIndexPairs[iMapIndexPairs - 1].m_iIlNativeMap = iIlNativeMap;
				}

			}
            // Go to next ilnative map entry
            iIlNativeMap++;
            continue;
        }

        if (m_rgilOffsets[iSeqPoints] < m_rgIlNativeMap[iIlNativeMap].ilOffset)
        {
            // Our cursor over the ilnative map is ahead of the sourceil
            // map, so go to next sourceil map entry.  Remember that we're passing over
            // this entry in the sourceil map, in case we choose to match to it later.
            if (!fCurSeqPointMatched)
            {
                iSeqPointLastUnmatched = iSeqPoints;
            }
            iSeqPoints++;
            fCurSeqPointMatched = FALSE;
            continue;
        }

        // At a match
        _ASSERTE(m_rgilOffsets[iSeqPoints] == m_rgIlNativeMap[iIlNativeMap].ilOffset);
        rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap = iIlNativeMap;
        rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints = iSeqPoints;
        
        // If we were remembering a prior unmatched entry in the IL PDB, reset it
        iSeqPointLastUnmatched = (ULONG32) -1;
        
        // Advance il-native map, do not advance il-source map in case the next il-native
        // entry matches this current il-source map entry, but remember that this current
        // il-source map entry has found an exact match
        iMapIndexPairs++;
        iIlNativeMap++;
        fCurSeqPointMatched = TRUE;
    }

    ULONG32 cMapIndexPairs = iMapIndexPairs;

    // PDB format requires the lines array to be sorted by IP offset
    QuickSortMapIndexPairsByNativeOffset sorterByIp(rgMapIndexPairs, cMapIndexPairs, m_rgIlNativeMap, m_cIlNativeMap);
    sorterByIp.Sort();

    //
    // Now that the maps are merged and sorted, determine whether there's a hot/cold
    // split, where that split is, and then call WriteLinesSubsection to write out each
    // region into its own lines-file subsection
    // 

    // Find the point where the code got split
    ULONG32 iMapIndexPairsFirstEntryInColdSection = cMapIndexPairs;
    for (iMapIndexPairs = 0; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
    {
        DWORD dwNativeOffset = m_rgIlNativeMap[rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap].nativeOffset;
        if (dwNativeOffset >= m_pMethodRegionInfo->hotSize)
        {
            iMapIndexPairsFirstEntryInColdSection = iMapIndexPairs;
            break;
        }
    }

    // Adjust the cold offsets (if any) to be relative to the cold start
    for (iMapIndexPairs = iMapIndexPairsFirstEntryInColdSection; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
    {
        DWORD dwNativeOffset = m_rgIlNativeMap[rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap].nativeOffset;
        _ASSERTE (dwNativeOffset >= m_pMethodRegionInfo->hotSize);

        // Adjust offset so it's relative to the cold region start
        dwNativeOffset -= DWORD(m_pMethodRegionInfo->hotSize);
        _ASSERTE(dwNativeOffset < m_pMethodRegionInfo->coldSize);
        m_rgIlNativeMap[rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap].nativeOffset = dwNativeOffset;
    }

    // Write out the hot region into its own lines-file subsection
    hr = WriteDebugSLinesSubsection(
        ULONG32(m_pMethodRegionInfo->hotStartAddress - m_addrCodeSection),
        ULONG32(m_pMethodRegionInfo->hotSize),
        rgMapIndexPairs,
        iMapIndexPairsFirstEntryInColdSection);
    if (FAILED(hr))
        return hr;
    
    // If there was a hot/cold split, write a separate lines-file subsection for the cold
    // region
    if (iMapIndexPairsFirstEntryInColdSection < cMapIndexPairs)
    {
        hr = WriteDebugSLinesSubsection(
            ULONG32(m_pMethodRegionInfo->coldStartAddress - m_addrCodeSection),
            ULONG32(m_pMethodRegionInfo->coldSize),
            &rgMapIndexPairs[iMapIndexPairsFirstEntryInColdSection],
            cMapIndexPairs - iMapIndexPairsFirstEntryInColdSection);
        if (FAILED(hr))
            return hr;
    }

    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// Manages the writing of all native-IL subsections requred for a given method. Almost do
// the same thing as NGenMethodLinesPdbWriter::WritePDBData. But we will write the native-IL 
// map this time.  
//

HRESULT NGenMethodLinesPdbWriter::WriteNativeILMapPDBData()
{
    STANDARD_VM_CONTRACT;

    HRESULT hr;

    QuickSortILNativeMapByNativeOffset sorterByNativeOffset(m_rgIlNativeMap, m_cIlNativeMap);
    sorterByNativeOffset.Sort();

    ULONG32 iIlNativeMap = 0;
    ULONG32 ilNativeMapFirstEntryInColdeSection = m_cIlNativeMap;
    for (iIlNativeMap = 0; iIlNativeMap < m_cIlNativeMap; iIlNativeMap++)
    {
        if (m_rgIlNativeMap[iIlNativeMap].nativeOffset >= m_pMethodRegionInfo->hotSize)
        {
            ilNativeMapFirstEntryInColdeSection = iIlNativeMap;
            break;
        }
    }

    NewArrayHolder<ICorDebugInfo::OffsetMapping> coldRgIlNativeMap(new ICorDebugInfo::OffsetMapping[m_cIlNativeMap - ilNativeMapFirstEntryInColdeSection]);
    // Adjust the cold offsets (if any) to be relative to the cold start
    for (iIlNativeMap = ilNativeMapFirstEntryInColdeSection; iIlNativeMap < m_cIlNativeMap; iIlNativeMap++)
    {
        DWORD dwNativeOffset = m_rgIlNativeMap[iIlNativeMap].nativeOffset;
        _ASSERTE(dwNativeOffset >= m_pMethodRegionInfo->hotSize);

        // Adjust offset so it's relative to the cold region start
        dwNativeOffset -= DWORD(m_pMethodRegionInfo->hotSize);
        _ASSERTE(dwNativeOffset < m_pMethodRegionInfo->coldSize);
        coldRgIlNativeMap[iIlNativeMap - ilNativeMapFirstEntryInColdeSection].ilOffset = m_rgIlNativeMap[iIlNativeMap].ilOffset;
        coldRgIlNativeMap[iIlNativeMap - ilNativeMapFirstEntryInColdeSection].nativeOffset = dwNativeOffset;
        coldRgIlNativeMap[iIlNativeMap - ilNativeMapFirstEntryInColdeSection].source = m_rgIlNativeMap[iIlNativeMap].source;
    }

    // Write out the hot region into its own lines-file subsection
    hr = WriteDebugSILLinesSubsection(
        ULONG32(m_pMethodRegionInfo->hotStartAddress - m_addrCodeSection),
        ULONG32(m_pMethodRegionInfo->hotSize),
        m_rgIlNativeMap,
        ilNativeMapFirstEntryInColdeSection);
    if (FAILED(hr))
        return hr;

    // If there was a hot/cold split, write a separate lines-file subsection for the cold
    // region
    if (ilNativeMapFirstEntryInColdeSection < m_cIlNativeMap)
    {
        hr = WriteDebugSILLinesSubsection(
            ULONG32(m_pMethodRegionInfo->coldStartAddress - m_addrCodeSection),
            ULONG32(m_pMethodRegionInfo->coldSize),
            coldRgIlNativeMap,
            m_cIlNativeMap - ilNativeMapFirstEntryInColdeSection);
        if (FAILED(hr))
            return hr;
    }

    return S_OK;
}


//---------------------------------------------------------------------------------------
//
// Helper called by NGenMethodLinesPdbWriter::WriteDebugSLinesSubsection and 
// NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection to initial the DEBUG_S*_LINE 
// subsection headers.
//
// Arguments:
//      * ulCodeStartOffset - Offset relative to the code section, or where this region
//          of code begins
//      * type - the subsection's type
//      * lineSize - how many lines mapping the subsection will have.
//      * cbCode - Size in bytes of this region of code
//      * ppSubSectHeader -  output value which returns the intialed CV_DebugSLinesHeader_t struct pointer.
//      * ppLinesHeader - output value which returns the initialed CV_DebugSLinesHeader_t struct pointer.
//      * ppbLinesSubsectionCur - output value which points to the address right after the DebugSLinesHeader
//
// Return Value:
//      * Pointer which points the staring address of the SubSection.
//

LPBYTE NGenMethodLinesPdbWriter::InitDebugLinesHeaderSection(
    DEBUG_S_SUBSECTION_TYPE type,
    ULONG32 ulCodeStartOffset,
    ULONG32 cbCode,
    ULONG32 lineSize,
    CV_DebugSSubsectionHeader_t **ppSubSectHeader /*out*/,
    CV_DebugSLinesHeader_t ** ppLinesHeader /*out*/,
    LPBYTE * ppbLinesSubsectionCur /*out*/)
{
    STANDARD_VM_CONTRACT;

    UINT64 cbLinesSubsectionEstimate =
        sizeof(DWORD) +
        sizeof(CV_DebugSSubsectionHeader_t) +
        sizeof(CV_DebugSLinesHeader_t) +
        // Worst case: assume each sequence point will require its own
        // CV_DebugSLinesFileBlockHeader_t
        (lineSize * (sizeof(CV_DebugSLinesFileBlockHeader_t) + sizeof(CV_Line_t)));
    if (!FitsIn<ULONG32>(cbLinesSubsectionEstimate))
    {
        return NULL;
    }

    LPBYTE rgbLinesSubsection = new BYTE[ULONG32(cbLinesSubsectionEstimate)];
    LPBYTE pbLinesSubsectionCur = rgbLinesSubsection;

    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
    *((DWORD *)pbLinesSubsectionCur) = CV_SIGNATURE_C13;
    pbLinesSubsectionCur += sizeof(DWORD);

    // * (2) CV_DebugSSubsectionHeader_t
    CV_DebugSSubsectionHeader_t * pSubSectHeader = (CV_DebugSSubsectionHeader_t *)pbLinesSubsectionCur;
    memset(pSubSectHeader, 0, sizeof(*pSubSectHeader));
    pSubSectHeader->type = type;
    *ppSubSectHeader = pSubSectHeader;
    // pSubSectHeader->cblen to be filled in later once we know the size
    pbLinesSubsectionCur += sizeof(*pSubSectHeader);

    // * (3) CV_DebugSLinesHeader_t
    CV_DebugSLinesHeader_t * pLinesHeader = (CV_DebugSLinesHeader_t *)pbLinesSubsectionCur;
    memset(pLinesHeader, 0, sizeof(*pLinesHeader));
    pLinesHeader->offCon = ulCodeStartOffset;
    pLinesHeader->segCon = m_iCodeSection;
    pLinesHeader->flags = 0;   // 0 means line info, but not column info, is included
    pLinesHeader->cbCon = cbCode;
    *ppLinesHeader = pLinesHeader;
    pbLinesSubsectionCur += sizeof(*pLinesHeader);
    *ppbLinesSubsectionCur = pbLinesSubsectionCur;
    return rgbLinesSubsection;
}

//---------------------------------------------------------------------------------------
//
// Helper called by NGenMethodLinesPdbWriter::WritePDBData to do the actual PDB writing of a single
// lines-subsection.  This is called once for the hot region, and once for the cold
// region, of a given method that has been split.  That means you get two
// lines-subsections for split methods.
//
// Arguments:
//      * ulCodeStartOffset - Offset relative to the code section, or where this region
//          of code begins
//      * cbCode - Size in bytes of this region of code
//      * rgMapIndexPairs - Array of indices forming the merged data from the JIT
//          Manager's IL-to-native map and the IL PDB's IL-to-source map.  It is assumed
//          that this array has indices sorted such that the native offsets increase
//      * cMapIndexPairs - Size in entries of above array.
//
// Assumptions:
//      rgMapIndexPairs must be sorted in order of nativeOffset, i.e.,
//      m_rgIlNativeMap[rgMapIndexPairs[i].m_iIlNativeMap].nativeOffset increases with i.
//

HRESULT NGenMethodLinesPdbWriter::WriteDebugSLinesSubsection(
    ULONG32 ulCodeStartOffset,
    ULONG32 cbCode,
    MapIndexPair * rgMapIndexPairs,
    ULONG32 cMapIndexPairs)
{
    STANDARD_VM_CONTRACT;

    // The lines subsection of the PDB (i.e., "DEBUG_S_LINES"), is a blob consisting of a
    // few structs stacked one after the other:
    // 
    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
    // * (2) CV_DebugSSubsectionHeader_t -- the usual subsection header, with type =
    //     DEBUG_S_LINES
    // * (3) CV_DebugSLinesHeader_t -- a single header for the entire subsection.  Its
    //     purpose is to specify the native function being described, and to specify the
    //     size of the variable-sized "blocks" that follow
    // * (4) CV_DebugSLinesFileBlockHeader_t -- For each block, you get one of these.  A
    //     block is defined by a set of sequence points that map to the same source
    //     file.  While iterating through the offsets, we need to define new blocks
    //     whenever the source file changes.  In C#, this typically only happens when
    //     you advance to (or away from) an unmapped IP (0xFeeFee).
    // * (5) CV_Line_t (Line array entries) -- For each block, you get several line
    //     array entries, one entry for the beginning of each sequence point.

    HRESULT hr;


    CV_DebugSSubsectionHeader_t * pSubSectHeader = NULL;
    CV_DebugSLinesHeader_t * pLinesHeader = NULL;
    CV_DebugSLinesFileBlockHeader_t * LinesFileBlockHeader = NULL;

    // the InitDebugLinesHeaderSection will help us taking care of 
    // * (1) DWORD = CV_SIGNATURE_C13
    // * (2) CV_DebugSSubsectionHeader_t 
    // * (3) CV_DebugSLinesHeader_t 
    LPBYTE pbLinesSubsectionCur;
    LPBYTE prgbLinesSubsection = InitDebugLinesHeaderSection(
        DEBUG_S_LINES,
        ulCodeStartOffset,
        cbCode,
        cMapIndexPairs,
        &pSubSectHeader,
        &pLinesHeader,
        &pbLinesSubsectionCur);

    if (pbLinesSubsectionCur == NULL)
    {
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }

    NewArrayHolder<BYTE> rgbLinesSubsection(prgbLinesSubsection);

    // The loop below takes care of
    //     * (4) CV_DebugSLinesFileBlockHeader_t
    //     * (5) CV_Line_t (Line array entries)
    //
    BOOL fAtLeastOneBlockWritten = FALSE;
    CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader = NULL;
    CV_Line_t * pLineCur = NULL;
	CV_Line_t * pLinePrev = NULL;
    CV_Line_t * pLineBlockStart = NULL;
    BOOL fBeginNewBlock = TRUE;
    ULONG32 iSeqPointsPrev = (ULONG32) -1;
    DWORD dwNativeOffsetPrev = (DWORD) -1;
    DWORD ilOffsetPrev = (DWORD) -1;
    WCHAR wszURLPrev[MAX_LONGPATH];
    memset(&wszURLPrev, 0, sizeof(wszURLPrev));
    LPBYTE pbEnd = NULL;

    for (ULONG32 iMapIndexPairs=0; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)
    {
        ULONG32 iSeqPoints = rgMapIndexPairs[iMapIndexPairs].m_iSeqPoints;
        ULONG32 iIlNativeMap = rgMapIndexPairs[iMapIndexPairs].m_iIlNativeMap;

        // Sometimes the JIT manager will give us duplicate IPs in the IL-to-native
        // offset mapping. PDB format frowns on that. Since rgMapIndexPairs is being
        // iterated in native offset order, it's easy to find these dupes right now, and
        // skip all but the first map containing a given IP offset.
        if (pLinePrev != NULL && m_rgIlNativeMap[iIlNativeMap].nativeOffset == pLinePrev->offset)
        {
			if (ilOffsetPrev == kUnmappedIP)
			{
				// if the previous IL offset is kUnmappedIP, then we should rewrite it. 
				pLineCur = pLinePrev;
			}
			else if (iSeqPoints != kUnmappedIP &&
				m_rgilOffsets[iSeqPoints] < ilOffsetPrev)
			{
				pLineCur = pLinePrev;
			}
			else
			{
				// Found a native offset dupe, ignore the current map entry
				continue;
			}
        }

        if ((iSeqPoints != kUnmappedIP) && (iSeqPoints != iSeqPointsPrev))
        {
            // This is the first iteration where we're looking at this iSeqPoints.  So
            // check whether the document name has changed on us.  If it has, that means
            // we need to start a new block.
            WCHAR wszURL[MAX_LONGPATH];
            ULONG32 cchURL;
            hr = m_rgpDocs[iSeqPoints]->GetURL(_countof(wszURL), &cchURL, wszURL);
            if (FAILED(hr))
            {
                // Skip function if IL PDB has data missing
                return S_OK;
            }

            // wszURL is the best we have for a unique identifier of documents.  See
            // whether the previous document's URL is different
            if (_wcsicmp(wszURL, wszURLPrev) != 0)
            {
                // New document.  Update wszURLPrev, and remember that we need to start a
                // new file block
                if (wcscpy_s(wszURLPrev, _countof(wszURLPrev), wszURL) != 0)
                {
                    continue;
                }
                fBeginNewBlock = TRUE;
            }

            iSeqPointsPrev = iSeqPoints;
        }
        if (fBeginNewBlock)
        {
            // We've determined that we need to start a new block. So perform fixups
            // against the previous block (if any) first
            if (FinalizeLinesFileBlock(pLinesFileBlockHeader, pLineBlockStart, pLineCur))
            {
                fAtLeastOneBlockWritten = TRUE;
            }
            else if (pLinesFileBlockHeader != NULL)
            {
                // Previous block had no usable data.  So rewind back to the previous
                // block header, and we'll start there with the next block
                pbLinesSubsectionCur = LPBYTE(pLinesFileBlockHeader);
                pLineCur = (CV_Line_t *) pbLinesSubsectionCur;
            }

            // Now get the info we'll need for the next block
            char szURL[MAX_LONGPATH];
            int cbWritten = WideCharToMultiByte(
                CP_UTF8,
                0,                                      // dwFlags
                wszURLPrev,
                -1,                                     // i.e., input is NULL-terminated
                szURL,                                  // output: UTF8 string starts here
                _countof(szURL),                        // Available space
                NULL,                                   // lpDefaultChar
                NULL                                    // lpUsedDefaultChar
                );
            if (cbWritten == 0)
                continue;

            DocNameOffsets docNameOffsets;
            BOOL fExists = m_pDocNameToOffsetMap->Lookup(szURL, &docNameOffsets);
            if (fExists)
            {
                _ASSERTE(docNameOffsets.m_dwChksumTableOffset != (ULONG32) -1);
            }
            else
            {
                // We may get back an invalid document in the 0xFeeFee case (i.e., a
                // sequence point that intentionally doesn't map back to a publicly
                // available source code line).  In that case, we'll use the bogus cksum
                // offset of -1 for now, and verify we're in the 0xFeeFee case later on
                // (see code:NGenMethodLinesPdbWriter::FinalizeLinesFileBlock).
                _ASSERTE(szURL[0] == '\0');
                _ASSERTE(docNameOffsets.m_dwChksumTableOffset == (ULONG32) -1);
            }


            // * (4) CV_DebugSLinesFileBlockHeader_t
            if (pLineCur == NULL)
            {
                // First lines file block, so begin the block header immediately after the
                // subsection headers
                pLinesFileBlockHeader = (CV_DebugSLinesFileBlockHeader_t *) pbLinesSubsectionCur;
            }
            else
            {
                // We've had blocks before this one, so add this block at our current
                // location in the blob
                pLinesFileBlockHeader = (CV_DebugSLinesFileBlockHeader_t *) pLineCur;
            }
            
            // PDB structure sizes guarantee this is the case, though their docs are
            // explicit that each lines-file block header must be 4-byte aligned.
            _ASSERTE(IS_ALIGNED(pLinesFileBlockHeader, 4));

            memset(pLinesFileBlockHeader, 0, sizeof(*pLinesFileBlockHeader));
            pLinesFileBlockHeader->offFile = docNameOffsets.m_dwChksumTableOffset;
            // pLinesFileBlockHeader->nLines to be filled in when block is complete
            // pLinesFileBlockHeader->cbBlock to be filled in when block is complete

            pLineCur = (CV_Line_t *) (pLinesFileBlockHeader + 1);
            pLineBlockStart = pLineCur;
            fBeginNewBlock = FALSE;
        }


        pLineCur->offset = m_rgIlNativeMap[iIlNativeMap].nativeOffset;
        pLineCur->linenumStart = 
            (iSeqPoints == kUnmappedIP) ? 
            kUnmappedIP : 
            m_rgnLineStarts[iSeqPoints];
        pLineCur->deltaLineEnd = 0;
        pLineCur->fStatement = 1;
		ilOffsetPrev = (iSeqPoints == kUnmappedIP) ? kUnmappedIP : m_rgilOffsets[iSeqPoints];
		pLinePrev = pLineCur;
        pLineCur++;
    }       // for (ULONG32 iMapIndexPairs=0; iMapIndexPairs < cMapIndexPairs; iMapIndexPairs++)

    if (pLineCur == NULL)
    {
        // There were no lines data for this function, so don't write anything
        return S_OK;
    }

    // Perform fixups against the last block we wrote
    if (FinalizeLinesFileBlock(pLinesFileBlockHeader, pLineBlockStart, pLineCur))
        fAtLeastOneBlockWritten = TRUE;

    if (!fAtLeastOneBlockWritten)
    {
        // There were no valid blocks to write for this function, so don't bother
        // calling PDB writing API.  No problem.
        return S_OK;
    }

    // Now that we know pSubSectHeader->cbLen, fill it in
    pSubSectHeader->cbLen = CV_off32_t(LPBYTE(pLineCur) - LPBYTE(pLinesHeader));

    // Subsection is now filled out, so add it.
    hr = m_pWriter->ModAddSymbols(
        m_pMod,
        rgbLinesSubsection, 

        // The size we pass here is the size of the entire byte array that we pass in.
        int(LPBYTE(pLineCur) - rgbLinesSubsection));

    if (FAILED(hr))
        return hr;

    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// Helper called by NGenMethodLinesPdbWriter::WriteNativeILMapPDBData to do the actual PDB writing of a single
// lines-subsection.  This is called once for the hot region, and once for the cold
// region, of a given method that has been split.  That means you get two
// lines-subsections for split methods.
//
// Arguments:
//      * ulCodeStartOffset - Offset relative to the code section, or where this region
//          of code begins
//      * cbCode - Size in bytes of this region of code
//      * rgIlNativeMap - IL to Native map array.
//      * rgILNativeMapAdjustSize - the number of elements we need to read in rgILNativeMap.
//

HRESULT NGenMethodLinesPdbWriter::WriteDebugSILLinesSubsection(
    ULONG32 ulCodeStartOffset,
    ULONG32 cbCode,
    ICorDebugInfo::OffsetMapping * rgIlNativeMap,
    ULONG32 rgILNativeMapAdjustSize)
{
    STANDARD_VM_CONTRACT;

    // The lines subsection of the PDB (i.e., "DEBUG_S_IL_LINES"), is a blob consisting of a
    // few structs stacked one after the other:
    // 
    // * (1) DWORD = CV_SIGNATURE_C13 -- the usual subsection signature DWORD
    // * (2) CV_DebugSSubsectionHeader_t -- the usual subsection header, with type =
    //     DEBUG_S_LINES
    // * (3) CV_DebugSLinesHeader_t -- a single header for the entire subsection.  Its
    //     purpose is to specify the native function being described, and to specify the
    //     size of the variable-sized "blocks" that follow
    // * (4) CV_DebugSLinesFileBlockHeader_t -- For each block, you get one of these.  A
    //     block is defined by a set of sequence points that map to the same source
    //     file.  While iterating through the offsets, we need to define new blocks
    //     whenever the source file changes.  In C#, this typically only happens when
    //     you advance to (or away from) an unmapped IP (0xFeeFee).
    // * (5) CV_Line_t (Line array entries) -- For each block, you get several line
    //     array entries, one entry for the beginning of each sequence point.

    HRESULT hr;

    CV_DebugSSubsectionHeader_t * pSubSectHeader = NULL;
    CV_DebugSLinesHeader_t * pLinesHeader = NULL;
    CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader = NULL;

    // the InitDebugLinesHeaderSection will help us taking care of 
    // * (1) DWORD = CV_SIGNATURE_C13
    // * (2) CV_DebugSSubsectionHeader_t 
    // * (3) CV_DebugSLinesHeader_t 
    LPBYTE pbLinesSubsectionCur;
    LPBYTE prgbLinesSubsection = InitDebugLinesHeaderSection(
        DEBUG_S_IL_LINES,
        ulCodeStartOffset,
        cbCode,
        rgILNativeMapAdjustSize,
        &pSubSectHeader,
        &pLinesHeader,
        &pbLinesSubsectionCur);

    if (prgbLinesSubsection == NULL)
    {
        return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
    }

    NewArrayHolder<BYTE> rgbLinesSubsection(prgbLinesSubsection);

    // The loop below takes care of
    //     * (4) CV_DebugSLinesFileBlockHeader_t
    //     * (5) CV_Line_t (Line array entries)
    //
    CV_Line_t * pLineCur = NULL;
    CV_Line_t * pLineBlockStart = NULL;
    BOOL fBeginNewBlock = TRUE;
    LPBYTE pbEnd = NULL;

    pLinesFileBlockHeader = (CV_DebugSLinesFileBlockHeader_t *)pbLinesSubsectionCur;
    // PDB structure sizes guarantee this is the case, though their docs are
    // explicit that each lines-file block header must be 4-byte aligned.
    _ASSERTE(IS_ALIGNED(pLinesFileBlockHeader, 4));

    memset(pLinesFileBlockHeader, 0, sizeof(*pLinesFileBlockHeader));
    char szURL[MAX_PATH];
    int cbWritten = WideCharToMultiByte(
        CP_UTF8,
        0,                                      // dwFlags
        UNKNOWN_SOURCE_FILE_PATH,
        -1,                                     // i.e., input is NULL-terminated
        szURL,                                  // output: UTF8 string starts here
        _countof(szURL),                        // Available space
        NULL,                                   // lpDefaultChar
        NULL                                    // lpUsedDefaultChar
        );
    _ASSERTE(cbWritten > 0);
    DocNameOffsets docNameOffsets;
    m_pDocNameToOffsetMap->Lookup(szURL, &docNameOffsets);
    pLinesFileBlockHeader->offFile = docNameOffsets.m_dwChksumTableOffset;
    // pLinesFileBlockHeader->nLines to be filled in when block is complete
    // pLinesFileBlockHeader->cbBlock to be filled in when block is complete

    pLineCur = (CV_Line_t *)(pLinesFileBlockHeader + 1);
    pLineBlockStart = pLineCur;
    CV_Line_t * pLinePrev = NULL;

    for (ULONG32 iINativeMap = 0;iINativeMap < rgILNativeMapAdjustSize; iINativeMap++)
    {
        if ((rgIlNativeMap[iINativeMap].ilOffset == NO_MAPPING) ||
            (rgIlNativeMap[iINativeMap].ilOffset == PROLOG) ||
            (rgIlNativeMap[iINativeMap].ilOffset == EPILOG))
        {
            rgIlNativeMap[iINativeMap].ilOffset = kUnmappedIP;
        }

        // Sometimes the JIT manager will give us duplicate native offset in the IL-to-native
        // offset mapping. PDB format frowns on that. Since rgMapIndexPairs is being
        // iterated in native offset order, it's easy to find these dupes right now, and
        // skip all but the first map containing a given IP offset.
        if (pLinePrev != NULL &&
            rgIlNativeMap[iINativeMap].nativeOffset == pLinePrev->offset)
        {
            if (pLinePrev->linenumStart == kUnmappedIP)
            {
                // if the previous IL offset is kUnmappedIP, then we should rewrite it. 
                pLineCur = pLinePrev;
            }
            else if (rgIlNativeMap[iINativeMap].ilOffset != kUnmappedIP &&
                rgIlNativeMap[iINativeMap].ilOffset < pLinePrev->linenumStart)
            {
                pLineCur = pLinePrev;
            }
            else
            {
                // Found a native offset dupe, ignore the current map entry
                continue;
            }
        }

        pLineCur->linenumStart = rgIlNativeMap[iINativeMap].ilOffset;

        pLineCur->offset = rgIlNativeMap[iINativeMap].nativeOffset;
        pLineCur->fStatement = 1;
        pLineCur->deltaLineEnd = 0;
        pLinePrev = pLineCur;
        pLineCur++;
    }

    if (pLineCur == NULL)
    {
        // There were no lines data for this function, so don't write anything
        return S_OK;
    }

    if (!FinalizeLinesFileBlock(pLinesFileBlockHeader, pLineBlockStart, pLineCur
#ifdef _DEBUG
        , true
#endif
        ))
    {
        return S_OK;
    }

    // Now that we know pSubSectHeader->cbLen, fill it in
    pSubSectHeader->cbLen = CV_off32_t(LPBYTE(pLineCur) - LPBYTE(pLinesHeader));

    // Subsection is now filled out, so add it.
    hr = m_pWriter->ModAddSymbols(
        m_pMod,
        rgbLinesSubsection,

        // The size we pass here is the size of the entire byte array that we pass in.
        long(LPBYTE(pLineCur) - rgbLinesSubsection));

    if (FAILED(hr))
        return hr;

    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// Performs final fixups on the last lines-file block we completed, specifically writing
// in the size of the block, now that it's known.  Also responsible for determining
// whether there is even any data to write in the first place.
//
// Arguments:
//      * pLinesFileBlockHeader - lines-file block header to write to
//      * pLineBlockStart - First CV_Line_t * of this block
//      * pLineBlockAfterEnd - Last CV_Line_t * of this block plus 1
//
// Return Value:
//      * TRUE: lines-file block was nonempty, and is now finalized
//      * FALSE: lines-file block was empty, and caller should toss it out.
//

BOOL NGenMethodLinesPdbWriter::FinalizeLinesFileBlock(
    CV_DebugSLinesFileBlockHeader_t * pLinesFileBlockHeader, 
    CV_Line_t * pLineBlockStart,
    CV_Line_t * pLineBlockAfterEnd
#ifdef _DEBUG
  , BOOL ignorekUnmappedIPCheck
#endif
    )
{
    LIMITED_METHOD_CONTRACT;

    if (pLinesFileBlockHeader == NULL)
    {
        // If a given function has no sequence points at all, pLinesFileBlockHeader can
        // be NULL.  No problem
        return FALSE;
    }

    if (pLineBlockStart == pLineBlockAfterEnd)
    {
        // If we start a lines file block and then realize that there are no entries
        // (i.e., no valid sequence points to map), then we end up with an empty block. 
        // No problem, just skip the block.
        return FALSE;
    }

    _ASSERTE(pLineBlockStart != NULL);
    _ASSERTE(pLineBlockAfterEnd != NULL);
    _ASSERTE(pLineBlockAfterEnd > pLineBlockStart);

    if (pLinesFileBlockHeader->offFile == (ULONG32) -1)
    {
        // The file offset we set for this block is invalid. This should be due to the
        // 0xFeeFee case (i.e., sequence points that intentionally don't map back to a
        // publicly available source code line). Fix up the offset to be valid (point it
        // at the first file), but the offset will generally be ignored by the PDB
        // reader.
#ifdef _DEBUG
    {
        if (!ignorekUnmappedIPCheck)
        {
            for (CV_Line_t * pLineCur = pLineBlockStart; pLineCur < pLineBlockAfterEnd; pLineCur++)
            {
                _ASSERTE(pLineCur->linenumStart == kUnmappedIP);
            }
        }
    }
#endif // _DEBUG
        pLinesFileBlockHeader->offFile = 0;
    }

    // Now that we know the size of the block, finish filling out the lines file block
    // header
    pLinesFileBlockHeader->nLines = CV_off32_t(pLineBlockAfterEnd - pLineBlockStart);
    pLinesFileBlockHeader->cbBlock = pLinesFileBlockHeader->nLines * sizeof(CV_Line_t);
    
    return TRUE;
}
#endif // NO_NGENPDB
#if defined(FEATURE_PERFMAP) || !defined(NO_NGENPDB)
HRESULT __stdcall CreatePdb(CORINFO_ASSEMBLY_HANDLE hAssembly, BSTR pNativeImagePath, BSTR pPdbPath, BOOL pdbLines, BSTR pManagedPdbSearchPath, LPCWSTR pDiasymreaderPath)
{
    STANDARD_VM_CONTRACT;

    Assembly *pAssembly = reinterpret_cast<Assembly *>(hAssembly);
    _ASSERTE(pAssembly);
    _ASSERTE(pNativeImagePath);
    _ASSERTE(pPdbPath);

#if !defined(NO_NGENPDB)
    NGenPdbWriter pdbWriter(
        pNativeImagePath, 
        pPdbPath, 
        pdbLines ? kPDBLines : 0,
        pManagedPdbSearchPath);
    IfFailThrow(pdbWriter.Load(pDiasymreaderPath));
#elif defined(FEATURE_PERFMAP)
    NativeImagePerfMap perfMap(pAssembly, pPdbPath);
#endif

    ModuleIterator moduleIterator = pAssembly->IterateModules();
    Module *pModule = NULL;
    BOOL fAtLeastOneNativeModuleFound = FALSE;
    
    while (moduleIterator.Next()) 
    {
        pModule = moduleIterator.GetModule();

        if (pModule->HasNativeImage() || pModule->IsReadyToRun())
        {
#if !defined(NO_NGENPDB)
            IfFailThrow(pdbWriter.WritePDBDataForModule(pModule));
#elif defined(FEATURE_PERFMAP)
            perfMap.LogDataForModule(pModule);
#endif
            fAtLeastOneNativeModuleFound = TRUE;
        }
    }

    if (!fAtLeastOneNativeModuleFound)
    {
        GetSvcLogger()->Printf(
            W("Loaded image '%s' (for input file '%s') is not a native image.\n"),
            pAssembly->GetManifestFile()->GetPath().GetUnicode(),
            pNativeImagePath);
        return CORDBG_E_NO_IMAGE_AVAILABLE;
    }

    GetSvcLogger()->Printf(
#if !defined(NO_NGENPDB)
        W("Successfully generated PDB for native assembly '%s'.\n"),
#elif defined(FEATURE_PERFMAP)
        W("Successfully generated perfmap for native assembly '%s'.\n"),
#endif
        pNativeImagePath);

    return S_OK;
}
#else
HRESULT __stdcall CreatePdb(CORINFO_ASSEMBLY_HANDLE hAssembly, BSTR pNativeImagePath, BSTR pPdbPath, BOOL pdbLines, BSTR pManagedPdbSearchPath, LPCWSTR pDiasymreaderPath)
{
    return E_NOTIMPL;
}
#endif // defined(FEATURE_PERFMAP) || !defined(NO_NGENPDB)

// End of PDB writing code
// ----------------------------------------------------------------------------


BOOL CEEPreloader::CanPrerestoreEmbedClassHandle(CORINFO_CLASS_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    if (IsReadyToRunCompilation())
        return FALSE;

    TypeHandle th(handle);

    return m_image->CanPrerestoreEagerBindToTypeHandle(th, NULL);
}

BOOL CEEPreloader::CanPrerestoreEmbedMethodHandle(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    if (IsReadyToRunCompilation())
        return FALSE;

    MethodDesc *pMD = (MethodDesc*) handle;

    return m_image->CanPrerestoreEagerBindToMethodDesc(pMD, NULL);
}

ICorCompilePreloader * CEECompileInfo::PreloadModule(CORINFO_MODULE_HANDLE module,
                                                ICorCompileDataStore *pData,
                                                CorProfileData       *profileData)
{
    STANDARD_VM_CONTRACT;

    NewHolder<CEEPreloader> pPreloader(new CEEPreloader((Module *) module, pData));
    
    COOPERATIVE_TRANSITION_BEGIN();

    if (PartialNGenStressPercentage() == 0)
    {
        pPreloader->Preload(profileData);
    }

    COOPERATIVE_TRANSITION_END();

    return pPreloader.Extract();
}

void CEECompileInfo::SetAssemblyHardBindList(
    __in_ecount( cHardBindList )
        LPWSTR *pHardBindList,
    DWORD  cHardBindList)
{
    STANDARD_VM_CONTRACT;

}

HRESULT CEECompileInfo::SetVerboseLevel(
         IN  VerboseLevel            level)
{
    LIMITED_METHOD_CONTRACT;
    HRESULT hr = S_OK;
    g_CorCompileVerboseLevel = level;
    return hr;
}

//
// Preloader:
//
CEEPreloader::CEEPreloader(Module *pModule,
             ICorCompileDataStore *pData)
    : m_pData(pData)
{
    m_image = new DataImage(pModule, this);

    CONSISTENCY_CHECK(pModule == GetAppDomain()->ToCompilationDomain()->GetTargetModule());

    GetAppDomain()->ToCompilationDomain()->SetTargetImage(m_image, this);

    m_methodCompileLimit = pModule->GetMDImport()->GetCountWithTokenKind(mdtMethodDef) * 10;

#ifdef FEATURE_FULL_NGEN
    m_fSpeculativeTriage = FALSE;
    m_fDictionariesPopulated = FALSE;
#endif
}

CEEPreloader::~CEEPreloader()
{
    WRAPPER_NO_CONTRACT;
    delete m_image;
}

void CEEPreloader::Preload(CorProfileData * profileData)
{
    STANDARD_VM_CONTRACT;

    bool doNothingNgen = false;
#ifdef _DEBUG
    static ConfigDWORD fDoNothingNGen;
    doNothingNgen = !!fDoNothingNGen.val(CLRConfig::INTERNAL_ZapDoNothing);
#endif

    if (!doNothingNgen)
    {
        m_image->GetModule()->SetProfileData(profileData);
        m_image->GetModule()->ExpandAll(m_image);
    }

    // Triage all items created by initial expansion. 
    // We will try to accept all items created by initial expansion. 
    TriageForZap(TRUE);
}

//
// ICorCompilerPreloader
//

DWORD CEEPreloader::MapMethodEntryPoint(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc *pMD = GetMethod(handle);
    Precode * pPrecode = pMD->GetSavedPrecode(m_image);

    return m_image->GetRVA(pPrecode);
}

DWORD CEEPreloader::MapClassHandle(CORINFO_CLASS_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    TypeHandle th = TypeHandle::FromPtr(handle);
    if (th.IsTypeDesc())
        return m_image->GetRVA(th.AsTypeDesc()) | 2;
    else
        return m_image->GetRVA(th.AsMethodTable());
}

DWORD CEEPreloader::MapMethodHandle(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    return m_image->GetRVA(handle);
}

DWORD CEEPreloader::MapFieldHandle(CORINFO_FIELD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    return m_image->GetRVA(handle);
}

DWORD CEEPreloader::MapAddressOfPInvokeFixup(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc *pMD = GetMethod(handle);

    _ASSERTE(pMD->IsNDirect());
    NDirectWriteableData * pMDWriteableData = ((NDirectMethodDesc *)pMD)->GetWriteableData();

    return m_image->GetRVA(pMDWriteableData) + offsetof(NDirectWriteableData, m_pNDirectTarget);
}

DWORD CEEPreloader::MapGenericHandle(CORINFO_GENERIC_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    return m_image->GetRVA(handle);
}

DWORD CEEPreloader::MapModuleIDHandle(CORINFO_MODULE_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    return m_image->GetRVA(handle) + (DWORD)Module::GetOffsetOfModuleID();
}

CORINFO_METHOD_HANDLE CEEPreloader::NextUncompiledMethod()
{
    STANDARD_VM_CONTRACT;

    // If we have run out of methods to compile, ensure that we have code for all methods
    // that we are about to save.
    if (m_uncompiledMethods.GetCount() == 0)
    {
#ifdef FEATURE_FULL_NGEN
        if (!m_fSpeculativeTriage)
        {
            // We take one shot at smarter elimination of speculative instantiations
            // that are guaranteed to be found in other modules
            TriageSpeculativeInstantiations();
            m_fSpeculativeTriage = TRUE;
        }
#endif

        if (m_uncompiledMethods.GetCount() == 0)
        {
#ifdef FEATURE_FULL_NGEN
            if (!m_fDictionariesPopulated)
            {
                // Prepopulate dictionaries. Only the first population is done in expansive way.
                m_image->GetModule()->PrepopulateDictionaries(m_image, FALSE);
                m_fDictionariesPopulated = TRUE;
            }
            else
#endif
            {
                // The subsequent populations are done in non-expansive way (won't load new types)
                m_image->GetModule()->PrepopulateDictionaries(m_image, TRUE);
            }
            
            // Make sure that we have generated code for all instantiations that we are going to save
            // The new items that we encounter here were most likely side effects of verification or failed inlining,
            // so do not try to save them eagerly.
            while (TriageForZap(FALSE)) {
                // Loop as long as new types are added
            }
        }
    }

    // Take next uncompiled method
    COUNT_T count = m_uncompiledMethods.GetCount();
    if (count == 0)
        return NULL;

    MethodDesc * pMD = m_uncompiledMethods[count - 1];
    m_uncompiledMethods.SetCount(count - 1);

#ifdef _DEBUG 
    if (LoggingOn(LF_ZAP, LL_INFO10000))
    {
        StackSString methodString;
        TypeString::AppendMethodDebug(methodString, pMD);

        LOG((LF_ZAP, LL_INFO10000, "CEEPreloader::NextUncompiledMethod: %S\n", methodString.GetUnicode()));
    }
#endif // _DEBUG

    return (CORINFO_METHOD_HANDLE) pMD;
}

void CEEPreloader::AddMethodToTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    TriageMethodForZap(GetMethod(handle), TRUE);
}

BOOL CEEPreloader::IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc *pMD = GetMethod(handle);

    return (m_acceptedMethods.Lookup(pMD) != NULL) && (m_rejectedMethods.Lookup(pMD) == NULL);
}

BOOL CEEPreloader::IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    TypeHandle th = (TypeHandle) handle;

    return (m_acceptedTypes.Lookup(th) != NULL) && (m_rejectedTypes.Lookup(th) == NULL);
}

void CEEPreloader::MethodReferencedByCompiledCode(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

#ifndef FEATURE_FULL_NGEN // Unreferenced methods
    //
    // Keep track of methods that are actually referenced by the code. We use this information 
    // to avoid generating code for unreferenced methods not visible outside the assembly.
    // These methods are very unlikely to be ever used at runtime because of they only ever be 
    // called via private reflection.
    //
    MethodDesc *pMD = GetMethod(handle);

    const CompileMethodEntry * pEntry = m_compileMethodsHash.LookupPtr(pMD);
    if (pEntry != NULL)
    {
        if (pEntry->fReferenced)
            return;
        const_cast<CompileMethodEntry *>(pEntry)->fReferenced = true;

        if (pEntry->fScheduled)
            return;        
        AppendUncompiledMethod(pMD);
    }
    else
    {
        CompileMethodEntry entry;
        entry.pMD = pMD;
        entry.fReferenced = true;
        entry.fScheduled = false;
        m_compileMethodsHash.Add(entry);
    }

    if (pMD->IsWrapperStub())
        MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pMD->GetWrappedMethodDesc());
#endif // FEATURE_FULL_NGEN
}

BOOL CEEPreloader::IsUncompiledMethod(CORINFO_METHOD_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    MethodDesc *pMD = GetMethod(handle);

#ifndef FEATURE_FULL_NGEN // Unreferenced methods
    const CompileMethodEntry * pEntry = m_compileMethodsHash.LookupPtr(pMD);
    return (pEntry != NULL) && (pEntry->fScheduled || !pEntry->fReferenced);
#else
    return m_compileMethodsHash.LookupPtr(pMD) != NULL;
#endif
}

static bool IsTypeAccessibleOutsideItsAssembly(TypeHandle th)
{
    STANDARD_VM_CONTRACT;

    if (th.IsTypeDesc())
    {
        if (th.AsTypeDesc()->HasTypeParam())
            return IsTypeAccessibleOutsideItsAssembly(th.AsTypeDesc()->GetTypeParam());

        return true;
    }

    MethodTable * pMT = th.AsMethodTable();

    if (pMT == g_pCanonMethodTableClass)
        return true;

    switch (pMT->GetClass()->GetProtection())
    {
    case tdPublic:
        break;
    case tdNestedPublic:
    case tdNestedFamily:
    case tdNestedFamORAssem:
        {
            MethodTable * pMTEnclosing = pMT->LoadEnclosingMethodTable();
            if (pMTEnclosing == NULL)
                return false;
            if (!IsTypeAccessibleOutsideItsAssembly(pMTEnclosing))
                return false;
        }
        break;

    default:
        return false;
    }

    if (pMT->HasInstantiation())
    {
        Instantiation instantiation = pMT->GetInstantiation();
        for (DWORD i = 0; i < instantiation.GetNumArgs(); i++)
        {
            if (!IsTypeAccessibleOutsideItsAssembly(instantiation[i]))
                return false;
        }
    }

    return true;
}

static bool IsMethodAccessibleOutsideItsAssembly(MethodDesc * pMD)
{
    STANDARD_VM_CONTRACT;

    // Note that this ignores friend access.

    switch (pMD->GetAttrs() & mdMemberAccessMask)
    {
    case mdFamily:
    case mdFamORAssem:
    case mdPublic:
        break;

    default:
        return false;
    }

    if (!IsTypeAccessibleOutsideItsAssembly(pMD->GetMethodTable()))
        return false;

    if (pMD->HasMethodInstantiation())
    {
        Instantiation instantiation = pMD->GetMethodInstantiation();
        for (DWORD i = 0; i < instantiation.GetNumArgs(); i++)
        {
            if (!IsTypeAccessibleOutsideItsAssembly(instantiation[i]))
                return false;
        }
    }

    return true;
}

static bool IsMethodCallableOutsideItsAssembly(MethodDesc * pMD)
{
    STANDARD_VM_CONTRACT;

    // Virtual methods can be called via interfaces, etc. We would need to do
    // more analysis to trim them. For now, assume that they can be referenced outside this assembly.
    if (pMD->IsVirtual())
        return true;

    // Class constructors are often used with reflection. Always generate code for them.
    if (pMD->IsClassConstructorOrCtor())
        return true;

    if (IsMethodAccessibleOutsideItsAssembly(pMD))
        return true;

    return false;
}

BOOL IsGenericTooDeeplyNested(TypeHandle t);
void CEEPreloader::AddToUncompiledMethods(MethodDesc *pMD, BOOL fForStubs)
{
    STANDARD_VM_CONTRACT;

    // TriageTypeForZap() and TriageMethodForZap() should ensure this.
    _ASSERTE(m_image->GetModule() == pMD->GetLoaderModule());

    if (!fForStubs)
    {
        if (!pMD->IsIL())
            return;

        if (!pMD->MayHaveNativeCode() && !pMD->IsWrapperStub())
            return;
    }

    // If it's already been compiled, don't add it to the set of uncompiled methods
    if (m_image->GetCodeAddress(pMD) != NULL)
        return;
    
    // If it's already in the queue to be compiled don't add it again
    const CompileMethodEntry * pEntry = m_compileMethodsHash.LookupPtr(pMD);

#ifndef FEATURE_FULL_NGEN // Unreferenced methods
   if (pEntry != NULL)
    {
        if (pEntry->fScheduled)
            return;

        if (!pEntry->fReferenced)
            return;

        const_cast<CompileMethodEntry *>(pEntry)->fScheduled = true;
    }
    else
    {
        // The unreferenced methods optimization works for generic methods and methods on generic types only. 
        // Non-generic methods take different path.
        //
        // It unclear whether it is worth it to enable it for non-generic methods too. The benefit 
        // for non-generic methods is small, and the non-generic methods are more likely to be called 
        // via private reflection.

        bool fSchedule = fForStubs || IsMethodCallableOutsideItsAssembly(pMD);

        CompileMethodEntry entry;
        entry.pMD = pMD;
        entry.fScheduled = fSchedule;
        entry.fReferenced = false;
        m_compileMethodsHash.Add(entry);

        if (!fSchedule)
            return;
    }
#else // // FEATURE_FULL_NGEN
    // Schedule the method for compilation
    if (pEntry != NULL)
        return;
    CompileMethodEntry entry;
    entry.pMD = pMD;
    m_compileMethodsHash.Add(entry);
#endif // FEATURE_FULL_NGEN

    if (pMD->HasMethodInstantiation())
    {
        Instantiation instantiation = pMD->GetMethodInstantiation();
        for (DWORD i = 0; i < instantiation.GetNumArgs(); i++)
        {
            if (IsGenericTooDeeplyNested(instantiation[i]))
                return;
        }
    }

    // Add it to the set of uncompiled methods
    AppendUncompiledMethod(pMD);
}

//
// Used to validate instantiations produced by the production rules before we actually try to instantiate them.
//
static BOOL CanSatisfyConstraints(Instantiation typicalInst, Instantiation candidateInst)
{
    STANDARD_VM_CONTRACT;

    // The dependency must be of the form C<T> --> D<T>
    _ASSERTE(typicalInst.GetNumArgs() == candidateInst.GetNumArgs());
    if (typicalInst.GetNumArgs() != candidateInst.GetNumArgs())
        return FALSE;

    SigTypeContext typeContext(candidateInst, Instantiation());

    for (DWORD i = 0; i < candidateInst.GetNumArgs(); i++)
    {
        TypeHandle thArg = candidateInst[i];

        // If this is "__Canon" and we are code sharing then we can't rule out that some
        // compatible instantiation may meet the constraints
        if (thArg == TypeHandle(g_pCanonMethodTableClass))
            continue;

        // Otherwise we approximate, and just assume that we have "parametric" constraints
        // of the form "T : IComparable<T>" rather than "odd" constraints such as "T : IComparable<string>".
        // That is, we assume checking the constraint at the canonical type is sufficient
        // to tell us if the constraint holds for all compatible types.
        //
        // For example of where this does not hold, consider if
        //     class C<T>
        //     class D<T> where T : IComparable<T>
        //     struct Struct<T> : IComparable<string>
        // Assume we generate C<Struct<object>>.  Now the constraint
        //     Struct<object> : IComparable<object>
        // does not hold, so we do not generate the instantiation, even though strictly speaking
        // the compatible instantiation C<Struct<string>> will satisfy the constraint
        //     Struct<string> : IComparable<string>

        TypeVarTypeDesc* tyvar = typicalInst[i].AsGenericVariable();

        tyvar->LoadConstraints();

        if (!tyvar->SatisfiesConstraints(&typeContext,thArg)) {
#ifdef _DEBUG
            /*
            // In case we want to know which illegal instantiations we ngen'ed
            StackSString candidateInstName;
            StackScratchBuffer buffer;
            thArg.GetName(candidateInstName);
            char output[1024];
            _snprintf_s(output, _countof(output), _TRUNCATE, "Generics TypeDependencyAttribute processing: Couldn't satisfy a constraint.  Class with Attribute: %s  Bad candidate instantiated type: %s\r\n", pMT->GetDebugClassName(), candidateInstName.GetANSI(buffer));
            OutputDebugStringA(output);
            */
#endif
            return FALSE;
        }
    }

    return TRUE;
}


//
// This method has duplicated logic from bcl\system\collections\generic\comparer.cs
//
static void SpecializeComparer(SString& ss, Instantiation& inst)
{
    STANDARD_VM_CONTRACT;

    if (inst.GetNumArgs() != 1) {
        _ASSERTE(!"Improper use of a TypeDependencyAttribute for Comparer");
        return;
    }

    TypeHandle elemTypeHnd = inst[0];

    //
    // Override the default ObjectComparer for special cases
    //
    if (elemTypeHnd.CanCastTo(
        TypeHandle(MscorlibBinder::GetClass(CLASS__ICOMPARABLEGENERIC)).Instantiate(Instantiation(&elemTypeHnd, 1))))
    {
        ss.Set(W("System.Collections.Generic.GenericComparer`1"));
        return;
    }

    if (Nullable::IsNullableType(elemTypeHnd))
    {
        Instantiation nullableInst = elemTypeHnd.AsMethodTable()->GetInstantiation();
        if (nullableInst[0].CanCastTo(
            TypeHandle(MscorlibBinder::GetClass(CLASS__ICOMPARABLEGENERIC)).Instantiate(nullableInst)))
        {
            ss.Set(W("System.Collections.Generic.NullableComparer`1"));
            inst = nullableInst;
            return;
        }
    }

    if (elemTypeHnd.IsEnum())
    {
        CorElementType et = elemTypeHnd.GetVerifierCorElementType();
        if (et == ELEMENT_TYPE_I1 ||
            et == ELEMENT_TYPE_I2 ||
            et == ELEMENT_TYPE_I4)
        {
            ss.Set(W("System.Collections.Generic.Int32EnumComparer`1"));
            return;
        }
        if (et == ELEMENT_TYPE_U1 ||
            et == ELEMENT_TYPE_U2 ||
            et == ELEMENT_TYPE_U4)
        {
            ss.Set(W("System.Collections.Generic.UInt32EnumComparer`1"));
            return;
        }
        if (et == ELEMENT_TYPE_I8)
        {
            ss.Set(W("System.Collections.Generic.Int64EnumComparer`1"));
            return;
        }
        if (et == ELEMENT_TYPE_U8)
        {
            ss.Set(W("System.Collections.Generic.UInt64EnumComparer`1"));
            return;
        }
    }
}

//
// This method has duplicated logic from bcl\system\collections\generic\equalitycomparer.cs
// and matching logic in jitinterface.cpp
//
static void SpecializeEqualityComparer(SString& ss, Instantiation& inst)
{
    STANDARD_VM_CONTRACT;

    if (inst.GetNumArgs() != 1) {
        _ASSERTE(!"Improper use of a TypeDependencyAttribute for EqualityComparer");
        return;
    }

    TypeHandle elemTypeHnd = inst[0];

    //
    // Override the default ObjectEqualityComparer for special cases
    //
    if (elemTypeHnd.CanCastTo(
        TypeHandle(MscorlibBinder::GetClass(CLASS__IEQUATABLEGENERIC)).Instantiate(Instantiation(&elemTypeHnd, 1))))
    {
        ss.Set(W("System.Collections.Generic.GenericEqualityComparer`1"));
        return;
    }

    if (Nullable::IsNullableType(elemTypeHnd))
    {
        Instantiation nullableInst = elemTypeHnd.AsMethodTable()->GetInstantiation();
        if (nullableInst[0].CanCastTo(
            TypeHandle(MscorlibBinder::GetClass(CLASS__IEQUATABLEGENERIC)).Instantiate(nullableInst)))
        {
            ss.Set(W("System.Collections.Generic.NullableEqualityComparer`1"));
            inst = nullableInst;
            return;
        }
    }

    if (elemTypeHnd.IsEnum())
    {
        // Note: We have different comparers for Short and SByte because for those types we need to make sure we call GetHashCode on the actual underlying type as the 
        // implementation of GetHashCode is more complex than for the other types.
        CorElementType et = elemTypeHnd.GetVerifierCorElementType();
        if (et == ELEMENT_TYPE_I4 ||
            et == ELEMENT_TYPE_U4 ||
            et == ELEMENT_TYPE_U2 ||
            et == ELEMENT_TYPE_I2 ||
            et == ELEMENT_TYPE_U1 ||
            et == ELEMENT_TYPE_I1)
        {
            ss.Set(W("System.Collections.Generic.EnumEqualityComparer`1"));
            return;
        }
        else if (et == ELEMENT_TYPE_I8 ||
                 et == ELEMENT_TYPE_U8)
        {
            ss.Set(W("System.Collections.Generic.LongEnumEqualityComparer`1"));
            return;
        }
    }
}

#ifdef FEATURE_COMINTEROP
// Instantiation of WinRT types defined in non-WinRT module. This check is required to generate marshaling stubs for
// instantiations of shadow WinRT types like EventHandler<ITracingStatusChangedEventArgs> in mscorlib.
static BOOL IsInstantationOfShadowWinRTType(MethodTable * pMT)
{
    STANDARD_VM_CONTRACT;

    Instantiation inst = pMT->GetInstantiation();
    for (DWORD i = 0; i < inst.GetNumArgs(); i++)
    {
        TypeHandle th = inst[i];
        if (th.IsProjectedFromWinRT() && !th.GetModule()->IsWindowsRuntimeModule())
            return TRUE;
    }
    return FALSE;
}
#endif

void CEEPreloader::ApplyTypeDependencyProductionsForType(TypeHandle t)
{
    STANDARD_VM_CONTRACT;

    // Only actual types
    if (t.IsTypeDesc())
        return;

    MethodTable * pMT = t.AsMethodTable();

    if (!pMT->HasInstantiation() || pMT->ContainsGenericVariables())
        return;

#ifdef FEATURE_COMINTEROP
    // At run-time, generic redirected interfaces and delegates need matching instantiations
    // of other types/methods in order to be marshaled across the interop boundary.
    if (m_image->GetModule()->IsWindowsRuntimeModule() || IsInstantationOfShadowWinRTType(pMT))
    {
        // We only apply WinRT dependencies when compiling .winmd assemblies since redirected
        // types are heavily used in non-WinRT code as well and would bloat native images.
        if (pMT->IsLegalNonArrayWinRTType())
        {
            TypeHandle thWinRT;
            WinMDAdapter::RedirectedTypeIndex index;
            if (WinRTInterfaceRedirector::ResolveRedirectedInterface(pMT, &index))
            {
                // redirected interface needs the mscorlib-local definition of the corresponding WinRT type
                MethodTable *pWinRTMT = WinRTInterfaceRedirector::GetWinRTTypeForRedirectedInterfaceIndex(index);
                thWinRT = TypeHandle(pWinRTMT);

                // and matching stub methods
                WORD wNumSlots = pWinRTMT->GetNumVirtuals();
                for (WORD i = 0; i < wNumSlots; i++)
                {
                    MethodDesc *pAdapterMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterface(
                        index,
                        i,
                        TypeHandle::Interop_NativeToManaged,
                        FALSE,
                        pMT->GetInstantiation());

                    TriageMethodForZap(pAdapterMD, TRUE);
                }
            }
            if (WinRTDelegateRedirector::ResolveRedirectedDelegate(pMT, &index))
            {
                // redirected delegate needs the mscorlib-local definition of the corresponding WinRT type
                thWinRT = TypeHandle(WinRTDelegateRedirector::GetWinRTTypeForRedirectedDelegateIndex(index));
            }

            if (!thWinRT.IsNull())
            {
                thWinRT = thWinRT.Instantiate(pMT->GetInstantiation());
                TriageTypeForZap(thWinRT, TRUE);
            }
        }
    }
#endif // FEATURE_COMINTEROP

    pMT = pMT->GetCanonicalMethodTable();

    // The TypeDependencyAttribute attribute is currently only allowed on mscorlib types
    // Don't even look for the attribute on types in other assemblies.
    if(!pMT->GetModule()->IsSystem()) {
        return;
    }

    // Part 1. - check for an NGEN production rule specified by a use of CompilerServices.TypeDependencyAttribute
    //  e.g. C<T> --> D<T>
    //
    // For example, if C<int> is generated then we produce D<int>.
    //
    // Normally NGEN can detect such productions through the process of compilation, but there are some
    // legitimate uses of reflection to generate generic instantiations which NGEN cannot detect.
    // In particular typically D<T> will have more constraints than C<T>, e.g.
    //     class D<T> where T : IComparable<T>
    // Uses of dynamic constraints are an example - consider making a Comparer<T>, where we can have a
    // FastComparer<T> where T : IComparable<T>, and the "slow" version checks for the non-generic
    // IComparer interface.
    // Also, T[] : IList<T>, IReadOnlyList<T>, and both of those interfaces should have a type dependency on SZArrayHelper's generic methods.
    //
    IMDInternalImport *pImport = pMT->GetMDImport();
    HRESULT hr;

    _ASSERTE(pImport);
    //walk all of the TypeDependencyAttributes
    MDEnumHolder hEnum(pImport);
    hr = pImport->EnumCustomAttributeByNameInit(pMT->GetCl(),
                                                g_CompilerServicesTypeDependencyAttribute, &hEnum);
    if (SUCCEEDED(hr))
    {
        mdCustomAttribute tkAttribute;
        const BYTE *pbAttr;
        ULONG cbAttr;

        while (pImport->EnumNext(&hEnum, &tkAttribute))
        {
            //get attribute and validate format
            if (FAILED(pImport->GetCustomAttributeAsBlob(
                tkAttribute,
                reinterpret_cast<const void **>(&pbAttr),
                &cbAttr)))
            {
                continue;
            }

            CustomAttributeParser cap(pbAttr, cbAttr);
            if (FAILED(cap.SkipProlog()))
                continue;

            LPCUTF8 szString;
            ULONG   cbString;
            if (FAILED(cap.GetNonNullString(&szString, &cbString)))
                continue;

            StackSString ss(SString::Utf8, szString, cbString);
            Instantiation inst = pMT->GetInstantiation();

#ifndef FEATURE_FULL_NGEN
            // Do not expand non-canonical instantiations. They are not that expensive to create at runtime 
            // using code:ClassLoader::CreateTypeHandleForNonCanonicalGenericInstantiation if necessary.
            if (!ClassLoader::IsCanonicalGenericInstantiation(inst))
                continue;
#endif

            if (ss.Equals(W("System.Collections.Generic.ObjectComparer`1")))
            {
                SpecializeComparer(ss, inst);
            }
            else
            if (ss.Equals(W("System.Collections.Generic.ObjectEqualityComparer`1")))
            {
                SpecializeEqualityComparer(ss, inst);
            }

            // Try to load the class using its name as a fully qualified name. If that fails,
            // then we try to load it in the assembly of the current class.
            TypeHandle typicalDepTH = TypeName::GetTypeUsingCASearchRules(ss.GetUnicode(), pMT->GetAssembly());

            _ASSERTE(!typicalDepTH.IsNull());
            // This attribute is currently only allowed to refer to mscorlib types
            _ASSERTE(typicalDepTH.GetModule()->IsSystem());
            if (!typicalDepTH.GetModule()->IsSystem())
                continue;

            // For IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T> & IReadOnlyList<T>, include SZArrayHelper's
            // generic methods (or at least the relevant ones) in the ngen image in 
            // case someone casts a T[] to an IList<T> (or ICollection<T> or IEnumerable<T>, etc).
            if (MscorlibBinder::IsClass(typicalDepTH.AsMethodTable(), CLASS__SZARRAYHELPER))
            {
#ifdef FEATURE_FULL_NGEN
                if (pMT->GetNumGenericArgs() != 1 || !pMT->IsInterface()) {
                    _ASSERTE(!"Improper use of a TypeDependencyAttribute for SZArrayHelper");
                    continue;
                }
                TypeHandle elemTypeHnd = pMT->GetInstantiation()[0];
                if (elemTypeHnd.IsValueType())
                    ApplyTypeDependencyForSZArrayHelper(pMT, elemTypeHnd);
#endif
                continue;
            }

            _ASSERTE(typicalDepTH.IsTypicalTypeDefinition());
            if (!typicalDepTH.IsTypicalTypeDefinition())
                continue;

            // It certainly can't be immediately recursive...
            _ASSERTE(!typicalDepTH.GetMethodTable()->HasSameTypeDefAs(pMT));

            // We want to rule out some cases where we know for sure that the generated type
            // won't satisfy its constraints.  However, some generated types may represent
            // canonicals in sets of shared instantaitions,

            if (CanSatisfyConstraints(typicalDepTH.GetInstantiation(), inst))
            {
                TypeHandle instDepTH =
                    ClassLoader::LoadGenericInstantiationThrowing(typicalDepTH.GetModule(), typicalDepTH.GetCl(), inst);

                _ASSERTE(!instDepTH.ContainsGenericVariables());
                _ASSERTE(instDepTH.GetNumGenericArgs() == typicalDepTH.GetNumGenericArgs());
                _ASSERTE(instDepTH.GetMethodTable()->HasSameTypeDefAs(typicalDepTH.GetMethodTable()));

                // OK, add the generated type to the dependency set
                TriageTypeForZap(instDepTH, TRUE);
            }
        }
    }
} // CEEPreloader::ApplyTypeDependencyProductionsForType


// Given IEnumerable<Foo>, we want to add System.SZArrayHelper.GetEnumerator<Foo> 
// to the ngen image.  This way we can cast a T[] to an IList<T> and
// use methods on it (from SZArrayHelper) without pulling in the JIT.
// Do the same for ICollection<T>/IReadOnlyCollection<T> and 
// IList<T>/IReadOnlyList<T>, but only add the relevant methods 
// from those interfaces.  
void CEEPreloader::ApplyTypeDependencyForSZArrayHelper(MethodTable * pInterfaceMT, TypeHandle elemTypeHnd)
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(elemTypeHnd.AsMethodTable()->IsValueType());

    // We expect this to only be called for IList<T>/IReadOnlyList<T>, ICollection<T>/IReadOnlyCollection<T>, IEnumerable<T>.
    _ASSERTE(pInterfaceMT->IsInterface());
    _ASSERTE(pInterfaceMT->GetNumGenericArgs() == 1);

    // This is the list of methods that don't throw exceptions on SZArrayHelper.
    static const BinderMethodID SZArrayHelperMethodIDs[] = { 
        // Read-only methods that are present on both regular and read-only interfaces.
        METHOD__SZARRAYHELPER__GETENUMERATOR,
        METHOD__SZARRAYHELPER__GET_COUNT,
        METHOD__SZARRAYHELPER__GET_ITEM, 
        // The rest of the methods is present on regular interfaces only.
        METHOD__SZARRAYHELPER__SET_ITEM, 
        METHOD__SZARRAYHELPER__COPYTO, 
        METHOD__SZARRAYHELPER__INDEXOF,
        METHOD__SZARRAYHELPER__CONTAINS };

    static const int cReadOnlyMethods = 3;
    static const int cAllMethods = 7;

    static const BinderMethodID LastMethodOnGenericArrayInterfaces[] = {
        METHOD__SZARRAYHELPER__GETENUMERATOR, // Last method of IEnumerable<T>
        METHOD__SZARRAYHELPER__REMOVE, // Last method of ICollection<T>.
        METHOD__SZARRAYHELPER__REMOVEAT, // Last method of IList<T>
    };
    
    // Assuming the binder ID's are properly laid out in mscorlib.h
#if _DEBUG
    for(unsigned int i=0; i < NumItems(LastMethodOnGenericArrayInterfaces) - 1; i++) {
        _ASSERTE(LastMethodOnGenericArrayInterfaces[i] < LastMethodOnGenericArrayInterfaces[i+1]);
    }
#endif

    MethodTable* pExactMT = MscorlibBinder::GetClass(CLASS__SZARRAYHELPER);

    // Subtract one from the non-generic IEnumerable that the generic IEnumerable<T>
    // inherits from.  
    unsigned inheritanceDepth = pInterfaceMT->GetNumInterfaces() - 1;
    PREFIX_ASSUME(0 <= inheritanceDepth && inheritanceDepth < NumItems(LastMethodOnGenericArrayInterfaces));
    
    // Read-only interfaces happen to always have one method
    bool fIsReadOnly = pInterfaceMT->GetNumVirtuals() == 1;

    for(int i=0; i < (fIsReadOnly ? cReadOnlyMethods : cAllMethods); i++)
    {
        // Check whether the method applies for this type.
        if (SZArrayHelperMethodIDs[i] > LastMethodOnGenericArrayInterfaces[inheritanceDepth])
            continue;

        MethodDesc * pPrimaryMD = MscorlibBinder::GetMethod(SZArrayHelperMethodIDs[i]);

        MethodDesc * pInstantiatedMD = MethodDesc::FindOrCreateAssociatedMethodDesc(pPrimaryMD, 
                                           pExactMT, false, Instantiation(&elemTypeHnd, 1), false);

        TriageMethodForZap(pInstantiatedMD, true);
    }
}


void CEEPreloader::AddTypeToTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle)
{
    STANDARD_VM_CONTRACT;

    TriageTypeForZap((TypeHandle) handle, TRUE);
}

const unsigned MAX_ZAP_INSTANTIATION_NESTING = 10;

BOOL IsGenericTooDeeplyNested(TypeHandle t)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;
    //if this type is more than N levels nested deep, do not add it to the
    //closure.  Build a queue for a DFS of the depth of instantiation.

    //the current index in the queue we're visiting
    int currentQueueIdx; //use -1 to indicate that we're done.
    //the current generic arg type.
    TypeHandle currentVisitingType[MAX_ZAP_INSTANTIATION_NESTING];

    //the ordinal in the GetInstantiation for the current type (over [0,
    //GetNumGenericArg())
    unsigned currentGenericArgEdge[MAX_ZAP_INSTANTIATION_NESTING];

    //initialize the DFS.
    memset(currentGenericArgEdge, 0, sizeof(currentGenericArgEdge));
    currentVisitingType[0] = t;
    currentQueueIdx = 0;

    while( currentQueueIdx >= 0 )
    {
        //see if we're done with this node
        if( currentVisitingType[currentQueueIdx].GetNumGenericArgs()
            <= currentGenericArgEdge[currentQueueIdx] )
        {
            --currentQueueIdx;
        }
        else
        {
            //more edges to visit.  So visit one edge
            _ASSERTE(currentGenericArgEdge[currentQueueIdx] < currentVisitingType[currentQueueIdx].GetNumGenericArgs());
            TypeHandle current = currentVisitingType[currentQueueIdx].GetInstantiation()[currentGenericArgEdge[currentQueueIdx]];
            ++currentGenericArgEdge[currentQueueIdx];
            //only value types cause a problem because of "approximate" type
            //loading, so only worry about scanning value type arguments.
            if( current.HasInstantiation() && current.IsValueType()  )
            {
                //new edge.  Make sure there is space in the queue.
                if( (currentQueueIdx + 1) >= (int)NumItems(currentGenericArgEdge) )
                {
                    //exceeded the allowable depth.  Stop processing.
                    return TRUE;
                }
                else
                {
                    ++currentQueueIdx;
                    currentGenericArgEdge[currentQueueIdx] = 0;
                    currentVisitingType[currentQueueIdx] = current;
                }
            }
        }
    }

    return FALSE;
}

void CEEPreloader::TriageTypeForZap(TypeHandle th, BOOL fAcceptIfNotSure, BOOL fExpandDependencies)
{
    STANDARD_VM_CONTRACT;

    // We care about param types only
    if (th.IsTypicalTypeDefinition() && !th.IsTypeDesc())
        return;

    // We care about types from our module only
    if (m_image->GetModule() != th.GetLoaderModule())
        return;

    // Check if we have decided to accept this type already.
    if (m_acceptedTypes.Lookup(th) != NULL)
        return;

    // Check if we have decided to reject this type already.
    if (m_rejectedTypes.Lookup(th) != NULL)
        return;

    enum { Investigate, Accepted, Rejected } triage = Investigate;

    const char * rejectReason = NULL;

    // TypeVarTypeDesc are saved via links from code:Module::m_GenericParamToDescMap
    if (th.IsGenericVariable())
    {
        triage = Rejected;
        rejectReason = "type is a Generic variable";
        goto Done;
    }

    /* Consider this example:

    class A<T> {}
    class B<U> : A<U> {}

    class C<V> : B<V> 
    {
        void foo<W>()
        {
            typeof(C<W>);
            typeof(B<A<W>>);

            typeof(List<V>);
        }
    }

    The open instantiations can be divided into the following 3 categories:

    1. A<T>,  B<U>, A<U>,  C<V>, B<V>, A<V> are open instantiations involving 
       ELEMENT_TYPE_VARs that need to be saved in the ngen image.
    2. List<V> is an instantiations that also involves ELEMENT_TYPE_VARs.
       However, it need not be saved since it will only be needed during the
       verification of foo<W>(). 
    3. C<W>, A<W>, B<A<W>> are open instantiations involving ELEMENT_TYPE_MVARs 
       that need not be saved since they will only be needed during the
       verification of foo<W>().

    Distinguishing between 1 and 2 requires walking C<V> and determining
    which ones are field/parent/interface types required by c<V>. However,
    category 3 is easy to detect, and can easily be pruned out. Hence,
    we pass in methodTypeVarsOnly=TRUE here.
    */
    if (th.ContainsGenericVariables(TRUE/*methodTypeVarsOnly*/))
    {
        triage = Rejected;
        rejectReason = "type contains method generic variables";
        goto Done;
    }

    // Filter out weird cases we do not care about.
    if (!m_image->GetModule()->GetAvailableParamTypes()->ContainsValue(th))
    {
        triage = Rejected;
        rejectReason = "type is not in the current module";
        return;
    }

    // Reject invalid generic instantiations. They will not be fully loaded
    // as they will throw a TypeLoadException before they reach CLASS_LOAD_LEVEL_FINAL.
    if (!th.IsFullyLoaded())
    {
        // This may load new types. May load new types.
        ClassLoader::TryEnsureLoaded(th);

        if (!th.IsFullyLoaded())
        {
            triage = Rejected;
            rejectReason = "type could not be fully loaded, possibly because it does not satisfy its constraints";
            goto Done;
        }
    }

    // Do not save any types containing generic class parameters from another module
    Module *pOpenModule;
    pOpenModule = th.GetDefiningModuleForOpenType();
    if (pOpenModule != NULL && pOpenModule != m_image->GetModule())
    {
        triage = Rejected;
        rejectReason = "type contains generic variables from another module";
        goto Done;
    }

    // Always store items in their preferred zap module even if we are not sure
    if (Module::GetPreferredZapModuleForTypeHandle(th) == m_image->GetModule())
    {
        triage = Accepted;
        goto Done;
    }

#ifdef FEATURE_FULL_NGEN
    // Only save arrays and other param types in their preferred zap modules, 
    // i.e. never duplicate them.
    if (th.IsTypeDesc() || th.IsArrayType())
    {
        triage = Rejected;
        rejectReason = "type is a TypeDesc";
        goto Done;
    }

    {
        // Do not save instantiations found in one of our hardbound dependencies
        PtrHashMap::PtrIterator iter = GetAppDomain()->ToCompilationDomain()->IterateHardBoundModules();
        for (/**/; !iter.end(); ++iter)
        {
            Module * hardBoundModule = (Module*)iter.GetValue();
            if (hardBoundModule->GetAvailableParamTypes()->ContainsValue(th))
            {
                triage = Rejected;
                rejectReason = "type was found in a hardbound dependency";
                goto Done;
            }
        }
    }

    // We are not really sure about this type. Accept it only if we have been asked to.
    if (fAcceptIfNotSure)
    {
        if (!m_fSpeculativeTriage)
        {
            // We will take a look later before we actually start compiling the instantiations
            m_speculativeTypes.Append(th);
            m_acceptedTypes.Add(th);
            return;
        }

        triage = Accepted;
        goto Done;
    }
#else
    rejectReason = "type is not in the preferred module";
    triage = Rejected;
#endif

Done:
    switch (triage)
    {
    case Accepted:
        m_acceptedTypes.Add(th);
        if (fExpandDependencies)
        {
            ExpandTypeDependencies(th);
        }
        break;

    case Rejected:

        m_rejectedTypes.Add(th);

#ifdef LOGGING
        // It is expensive to call th.GetName, only do it when we are actually logging
        if (LoggingEnabled())
        {
            SString typeName;
            th.GetName(typeName);
            LOG((LF_ZAP, LL_INFO10000, "TriageTypeForZap rejects %S (%08x) because %s\n", 
                 typeName.GetUnicode(), th.AsPtr(), rejectReason));
        }
#endif
        break;

    default:
        // We have not found a compeling reason to accept or reject the type yet. Maybe next time...
        break;
    }
}

void CEEPreloader::ExpandTypeDependencies(TypeHandle th)
{
    STANDARD_VM_CONTRACT;

    if (th.IsTypeDesc())
        return;
    
    MethodTable* pMT = th.AsMethodTable();

    if (pMT->IsCanonicalMethodTable())
    {
        // Cutoff infinite recursion.
        if (!IsGenericTooDeeplyNested(th))
        {
            // Make sure all methods are compiled
            // We only want to check the method bodies owned by this type,
            // and not any method bodies owned by a parent type, as the
            // parent type may not get saved in this ngen image.
            MethodTable::IntroducedMethodIterator itr(pMT);
            for (/**/; itr.IsValid(); itr.Next())
            {
                AddToUncompiledMethods(itr.GetMethodDesc(), FALSE);
            }
        }
    }
    else
    {
        // Make sure canonical method table is saved
        TriageTypeForZap(pMT->GetCanonicalMethodTable(), TRUE);
    }
    
    if (pMT->SupportsGenericInterop(TypeHandle::Interop_ManagedToNative))
    {
        MethodTable::IntroducedMethodIterator itr(pMT->GetCanonicalMethodTable());
        for (/**/; itr.IsValid(); itr.Next())
        {
            MethodDesc *pMD = itr.GetMethodDesc();

            if (!pMD->HasMethodInstantiation())
            {
                if (pMT->IsInterface() || !pMD->IsSharedByGenericInstantiations())
                {
                    pMD = MethodDesc::FindOrCreateAssociatedMethodDesc(
                        pMD, 
                        pMT, 
                        FALSE,              // forceBoxedEntryPoint
                        Instantiation(),    // methodInst
                        FALSE,              // allowInstParam
                        TRUE);              // forceRemotableMethod
                }
                else
                {
                    _ASSERTE(pMT->IsDelegate());
                    pMD = InstantiatedMethodDesc::FindOrCreateExactClassMethod(pMT, pMD);
                }

                AddToUncompiledMethods(pMD, TRUE);
            }
        }
    }

    // Make sure parent type is saved
    TriageTypeForZap(pMT->GetParentMethodTable(), TRUE);
    
    // Make sure all instantiation arguments are saved
    Instantiation inst = pMT->GetInstantiation();
    for (DWORD iArg = 0; iArg < inst.GetNumArgs(); iArg++)
    {
        TriageTypeForZap(inst[iArg], TRUE);
    }
    
    // Make sure all interfaces implemeted by the class are saved
    MethodTable::InterfaceMapIterator intIterator = pMT->IterateInterfaceMap();
    while (intIterator.Next())
    {
        TriageTypeForZap(intIterator.GetInterface(), TRUE);
    }
    
    // Make sure aprox types for all fields are saved
    ApproxFieldDescIterator fdIterator(pMT, ApproxFieldDescIterator::ALL_FIELDS);
    FieldDesc* pFD;
    while ((pFD = fdIterator.Next()) != NULL)
    {
        if (pFD->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
        {
            TriageTypeForZap(pFD->GetFieldTypeHandleThrowing(), TRUE);
        }
    }
    
    // Make sure types for all generic static fields are saved
    
    if (pMT->HasGenericsStaticsInfo())
    {
        FieldDesc *pGenStaticFields = pMT->GetGenericsStaticFieldDescs();
        DWORD nFields = pMT->GetNumStaticFields();
        for (DWORD iField = 0; iField < nFields; iField++)
        {
            FieldDesc* pField = &pGenStaticFields[iField];
            if (pField->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
            {
                TriageTypeForZap(pField->GetFieldTypeHandleThrowing(), TRUE);
            }
        }
    }
    
    // Expand type using the custom rules. May load new types.
    ApplyTypeDependencyProductionsForType(th);
}

// Triage instantiations of generic methods

void CEEPreloader::TriageMethodForZap(MethodDesc* pMD, BOOL fAcceptIfNotSure, BOOL fExpandDependencies)
{
    STANDARD_VM_CONTRACT;

    // Submit the method type for triage
    TriageTypeForZap(TypeHandle(pMD->GetMethodTable()), fAcceptIfNotSure);

    // We care about instantiated methods only
    if (pMD->IsTypicalMethodDefinition())
        return;

    // We care about methods from our module only
    if (m_image->GetModule() != pMD->GetLoaderModule())
        return;

    // Check if we have decided to accept this method already.
    if (m_acceptedMethods.Lookup(pMD) != NULL)
        return;

    // Check if we have decided to reject this method already.
    if (m_rejectedMethods.Lookup(pMD) != NULL)
        return;

    enum { Investigate, Accepted, Rejected } triage = Investigate;

    const char * rejectReason = NULL;

    // Do not save open methods
    if (pMD->ContainsGenericVariables())
    {
        triage = Rejected;
        rejectReason = "method contains method generic variables";
        goto Done;
    }

    // Always store items in their preferred zap module even if we are not sure
    if (Module::GetPreferredZapModuleForMethodDesc(pMD) == m_image->GetModule())
    {
        triage = Accepted;
        goto Done;
    }

#ifdef FEATURE_FULL_NGEN
    {
        // Do not save instantiations found in one of our hardbound dependencies
        PtrHashMap::PtrIterator iter = GetAppDomain()->ToCompilationDomain()->IterateHardBoundModules();
        for (/**/; !iter.end(); ++iter)
        {
            Module * hardBoundModule = (Module*)iter.GetValue();
            if (hardBoundModule->GetInstMethodHashTable()->ContainsMethodDesc(pMD))
            {
                triage = Rejected;
                rejectReason = "method was found in a hardbound dependency";
                goto Done;
            }
        }
    }

    // We are not really sure about this method. Accept it only if we have been asked to.
    if (fAcceptIfNotSure)
    {
        // It does not seem worth it to go through extra hoops to eliminate redundant 
        // speculative method instatiations from softbound dependencies like we do for types
        // if (!m_fSpeculativeTriage)
        // {
        //    // We will take a look later before we actually start compiling the instantiations
        //    ...
        // }

        triage = Accepted;
        goto Done;
    }
#else
    triage = Rejected;
#endif

Done:
    switch (triage)
    {
    case Accepted:
        m_acceptedMethods.Add(pMD);
        if (fExpandDependencies)
        {
            ExpandMethodDependencies(pMD);
        }
        break;

    case Rejected:
        m_rejectedMethods.Add(pMD);
        LOG((LF_ZAP, LL_INFO10000, "TriageMethodForZap rejects %s (%08x) because %s\n", 
            pMD->m_pszDebugMethodName, pMD, rejectReason));
        break;

    default:
        // We have not found a compeling reason to accept or reject the method yet. Maybe next time...
        break;
    }
}

void CEEPreloader::ExpandMethodDependencies(MethodDesc * pMD)
{
    STANDARD_VM_CONTRACT;

    AddToUncompiledMethods(pMD, FALSE);

    {
        // Make sure all instantiation arguments are saved
        Instantiation inst = pMD->GetMethodInstantiation();
        for (DWORD iArg = 0; iArg < inst.GetNumArgs(); iArg++)
        {
            TriageTypeForZap(inst[iArg], TRUE);
        }
    }

    // Make sure to add wrapped method desc
    if (pMD->IsWrapperStub())
        TriageMethodForZap(pMD->GetWrappedMethodDesc(), TRUE);
}

void CEEPreloader::TriageTypeFromSoftBoundModule(TypeHandle th, Module * pSoftBoundModule)
{
    STANDARD_VM_CONTRACT;

    // We care about types from our module only
    if (m_image->GetModule() != th.GetLoaderModule())
        return;

    // Nothing to do if we have rejected the type already.
    if (m_rejectedTypes.Lookup(th) != NULL)
        return;

    // We make guarantees about types living in its own PZM only
    if (Module::GetPreferredZapModuleForTypeHandle(th) != pSoftBoundModule)
        return;

    // Reject the type - it is guaranteed to be saved in PZM
    m_rejectedTypes.Add(th);

    if (!th.IsTypeDesc())
    {
        // Reject the canonical method table if possible.
        MethodTable* pMT = th.AsMethodTable();
        if (!pMT->IsCanonicalMethodTable())
            TriageTypeFromSoftBoundModule(pMT->GetCanonicalMethodTable(), pSoftBoundModule);

        // Reject parent method table if possible.
        TriageTypeFromSoftBoundModule(pMT->GetParentMethodTable(), pSoftBoundModule);

        // Reject all interfaces implemented by the type if possible.
        MethodTable::InterfaceMapIterator intIterator = pMT->IterateInterfaceMap();
        while (intIterator.Next())
        {
            TriageTypeFromSoftBoundModule(intIterator.GetInterface(), pSoftBoundModule);
        }

        // It does not seem worth it to reject the remaining items 
        // expanded by CEEPreloader::ExpandTypeDependencies here.
    }
}

#ifdef FEATURE_FULL_NGEN
static TypeHandle TryToLoadTypeSpecHelper(Module * pModule, PCCOR_SIGNATURE pSig, ULONG cSig)
{
    STANDARD_VM_CONTRACT;

    TypeHandle th;

    EX_TRY
    {
        SigPointer p(pSig, cSig);
        SigTypeContext typeContext;    // empty context is OK: encoding should not contain type variables.

        th = p.GetTypeHandleThrowing(pModule, &typeContext, ClassLoader::DontLoadTypes);
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions)

    return th;
}

void CEEPreloader::TriageTypeSpecsFromSoftBoundModule(Module * pSoftBoundModule)
{
    STANDARD_VM_CONTRACT;

    //
    // Reject all typespecs that are guranteed to be found in soft bound PZM
    //

    IMDInternalImport *pInternalImport = pSoftBoundModule->GetMDImport();

    HENUMInternalHolder hEnum(pInternalImport);
    hEnum.EnumAllInit(mdtTypeSpec);

    mdToken tk;
    while (pInternalImport->EnumNext(&hEnum, &tk))
    {
        ULONG cSig;
        PCCOR_SIGNATURE pSig;

        if (FAILED(pInternalImport->GetTypeSpecFromToken(tk, &pSig, &cSig)))
        {
            pSig = NULL;
            cSig = 0;
        }

        // Check all types specs that do not contain variables
        if (SigPointer(pSig, cSig).IsPolyType(NULL) == hasNoVars)
        {
            TypeHandle th = TryToLoadTypeSpecHelper(pSoftBoundModule, pSig, cSig);

            if (th.IsNull())
                continue;

            TriageTypeFromSoftBoundModule(th, pSoftBoundModule);
        }
    }
}

void CEEPreloader::TriageSpeculativeType(TypeHandle th)
{
    STANDARD_VM_CONTRACT;

    // Nothing to do if we have rejected the type already
    if (m_rejectedTypes.Lookup(th) != NULL)
        return;

    Module * pPreferredZapModule = Module::GetPreferredZapModuleForTypeHandle(th);
    BOOL fHardBoundPreferredZapModule = FALSE;

    //
    // Even though we have done this check already earlier, do it again here in case we have picked up
    // any eager-bound dependency in the meantime
    //
    // Do not save instantiations found in one of our eager-bound dependencies
    PtrHashMap::PtrIterator iter = GetAppDomain()->ToCompilationDomain()->IterateHardBoundModules();
    for (/**/; !iter.end(); ++iter)
    {
        Module * hardBoundModule = (Module*)iter.GetValue();
        if (hardBoundModule->GetAvailableParamTypes()->ContainsValue(th))
        {
            m_rejectedTypes.Add(th);
            return;
        }

        if (hardBoundModule == pPreferredZapModule)
        {
            fHardBoundPreferredZapModule = TRUE;
        }
    }

    if (!fHardBoundPreferredZapModule && !pPreferredZapModule->AreTypeSpecsTriaged())
    {
        // Reject all types that are guaranteed to be instantiated in soft bound PZM
        TriageTypeSpecsFromSoftBoundModule(pPreferredZapModule);
        pPreferredZapModule->SetTypeSpecsTriaged();

        if (m_rejectedTypes.Lookup(th) != NULL)
            return;
    }

    // We have to no other option but to accept and expand the type
    ExpandTypeDependencies(th);
}

void CEEPreloader::TriageSpeculativeInstantiations()
{
    STANDARD_VM_CONTRACT;

    // Get definitive triage answer for speculative types that we have run into earlier
    // Note that m_speculativeTypes may be growing as this loop runs
    for (COUNT_T i = 0; i < m_speculativeTypes.GetCount(); i++)
    {
        TriageSpeculativeType(m_speculativeTypes[i]);
    }

    // We are done - the array of speculative types is no longer necessary
    m_speculativeTypes.Clear();
}
#endif // FEATURE_FULL_NGEN

BOOL CEEPreloader::TriageForZap(BOOL fAcceptIfNotSure, BOOL fExpandDependencies)
{
    STANDARD_VM_CONTRACT;

    DWORD dwNumTypes = m_image->GetModule()->GetAvailableParamTypes()->GetCount();
    DWORD dwNumMethods = m_image->GetModule()->GetInstMethodHashTable()->GetCount();

    // Triage types
    {
        // Create a local copy in case the new elements are added to the hashtable during population
        InlineSArray<TypeHandle, 20> pTypes;

        // Make sure the iterator is destroyed before there is a chance of loading new types
        {
            EETypeHashTable* pTable = m_image->GetModule()->GetAvailableParamTypes();

            EETypeHashTable::Iterator it(pTable);
            EETypeHashEntry *pEntry;
            while (pTable->FindNext(&it, &pEntry))
            {
                TypeHandle th = pEntry->GetTypeHandle();
                if (m_acceptedTypes.Lookup(th) == NULL && m_rejectedTypes.Lookup(th) == NULL)
                    pTypes.Append(th);
            }
        }

        for(COUNT_T i = 0; i < pTypes.GetCount(); i ++)
        {
            TriageTypeForZap(pTypes[i], fAcceptIfNotSure, fExpandDependencies);
        }
    }

    // Triage methods
    {
        // Create a local copy in case the new elements are added to the hashtable during population
        InlineSArray<MethodDesc*, 20> pMethods;

        // Make sure the iterator is destroyed before there is a chance of loading new methods
        {
            InstMethodHashTable* pTable = m_image->GetModule()->GetInstMethodHashTable();

            InstMethodHashTable::Iterator it(pTable);
            InstMethodHashEntry *pEntry;
            while (pTable->FindNext(&it, &pEntry))
            {
                MethodDesc* pMD = pEntry->GetMethod();
                if (m_acceptedMethods.Lookup(pMD) == NULL && m_rejectedMethods.Lookup(pMD) == NULL)
                    pMethods.Append(pMD);
            }
        }

        for(COUNT_T i = 0; i < pMethods.GetCount(); i ++)
        {
            TriageMethodForZap(pMethods[i], fAcceptIfNotSure, fExpandDependencies);
        }
    }

    // Returns TRUE if new types or methods has been added by the triage
    return (dwNumTypes != m_image->GetModule()->GetAvailableParamTypes()->GetCount()) ||
           (dwNumMethods != m_image->GetModule()->GetInstMethodHashTable()->GetCount());
}

void CEEPreloader::PrePrepareMethodIfNecessary(CORINFO_METHOD_HANDLE hMethod)
{
    STANDARD_VM_CONTRACT;

}

static void SetStubMethodDescOnInteropMethodDesc(MethodDesc* pInteropMD, MethodDesc* pStubMD, bool fReverseStub)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;

        // We store NGENed stubs on these MethodDesc types
        PRECONDITION(pInteropMD->IsNDirect() || pInteropMD->IsComPlusCall() || pInteropMD->IsGenericComPlusCall() || pInteropMD->IsEEImpl());
    }
    CONTRACTL_END;

    if (pInteropMD->IsNDirect())
    {
        _ASSERTE(!fReverseStub);
        NDirectMethodDesc* pNMD = (NDirectMethodDesc*)pInteropMD;
        pNMD->ndirect.m_pStubMD.SetValue(pStubMD);
    }
#ifdef FEATURE_COMINTEROP
    else if (pInteropMD->IsComPlusCall() || pInteropMD->IsGenericComPlusCall())
    {
        _ASSERTE(!fReverseStub);
        ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pInteropMD);
       pComInfo->m_pStubMD.SetValue(pStubMD);
    }
#endif // FEATURE_COMINTEROP
    else if (pInteropMD->IsEEImpl())
    {
        DelegateEEClass* pDelegateClass = (DelegateEEClass*)pInteropMD->GetClass();
        if (fReverseStub)
        {
            pDelegateClass->m_pReverseStubMD = pStubMD;
        }
        else
        {
#ifdef FEATURE_COMINTEROP
            // We don't currently NGEN both the P/Invoke and WinRT stubs for WinRT delegates.
            // If that changes, this function will need an extra parameter to tell what kind
            // of stub is being passed.
            if (pInteropMD->GetMethodTable()->IsWinRTDelegate())
            {
                pDelegateClass->m_pComPlusCallInfo->m_pStubMD.SetValue(pStubMD);
            }
            else
#endif // FEATURE_COMINTEROP
            {
                pDelegateClass->m_pForwardStubMD = pStubMD;
            }
        }
    }
    else
    {
        UNREACHABLE_MSG("unexpected type of MethodDesc");
    }
}

MethodDesc * CEEPreloader::CompileMethodStubIfNeeded(
        MethodDesc *pMD,
        MethodDesc *pStubMD,
        ICorCompilePreloader::CORCOMPILE_CompileStubCallback pfnCallback,
        LPVOID pCallbackContext)
{
    STANDARD_VM_CONTRACT;

    LOG((LF_ZAP, LL_INFO10000, "NGEN_ILSTUB: %s::%s -> %s::%s\n",
         pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName, pStubMD->m_pszDebugClassName, pStubMD->m_pszDebugMethodName));

    // It is possible that the StubMD is a normal method pointed by InteropStubMethodAttribute,
    // and in that case we don't need to compile it here
    if (pStubMD->IsDynamicMethod())
    {
        if (!pStubMD->AsDynamicMethodDesc()->GetILStubResolver()->IsCompiled())
        {
            CORJIT_FLAGS jitFlags = pStubMD->AsDynamicMethodDesc()->GetILStubResolver()->GetJitFlags();

            pfnCallback(pCallbackContext, (CORINFO_METHOD_HANDLE)pStubMD, jitFlags);
        }

#ifndef FEATURE_FULL_NGEN // Deduplication
        const DuplicateMethodEntry * pDuplicate = m_duplicateMethodsHash.LookupPtr(pStubMD);
        if (pDuplicate != NULL)
            return pDuplicate->pDuplicateMD;
#endif
    }

//We do not store ILStubs so if the compilation failed for them
//It does not make sense to keep the MD corresponding to the IL
    if (pStubMD->IsILStub() && m_image->GetCodeAddress(pStubMD) == NULL)
        pStubMD=NULL;

    return pStubMD;
}

void CEEPreloader::GenerateMethodStubs(
        CORINFO_METHOD_HANDLE hMethod,
        bool                  fNgenProfilerImage,
        CORCOMPILE_CompileStubCallback pfnCallback,
        LPVOID                pCallbackContext)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(hMethod != NULL && pfnCallback != NULL);
    }
    CONTRACTL_END;

    MethodDesc* pMD = GetMethod(hMethod);
    MethodDesc* pStubMD = NULL;

    // Do not generate IL stubs when generating ReadyToRun images
    // This prevents versionability concerns around IL stubs exposing internal
    // implementation details of the CLR.
    if (IsReadyToRunCompilation())
        return;

    DWORD dwNGenStubFlags = NDIRECTSTUB_FL_NGENEDSTUB;

    if (fNgenProfilerImage)
        dwNGenStubFlags |= NDIRECTSTUB_FL_NGENEDSTUBFORPROFILING;

    //
    // Generate IL stubs. If failed, we go through normal NGEN path
    // Catch any exceptions that occur when we try to create the IL_STUB
    //    
    EX_TRY
    {
        //
        // Take care of forward stubs
        //            
        if (pMD->IsNDirect())
        {
            NDirectMethodDesc* pNMD = (NDirectMethodDesc*)pMD;
            PInvokeStaticSigInfo sigInfo;
            NDirect::PopulateNDirectMethodDesc(pNMD, &sigInfo);
            pStubMD = NDirect::GetILStubMethodDesc((NDirectMethodDesc*)pMD, &sigInfo, dwNGenStubFlags);
        }
#ifdef FEATURE_COMINTEROP
        else if (pMD->IsComPlusCall() || pMD->IsGenericComPlusCall())
        {
            if (MethodNeedsForwardComStub(pMD, m_image))
            {
                // Look for predefined IL stubs in forward com interop scenario. 
                // If we've found a stub, that's what we'll use
                DWORD dwStubFlags;
                ComPlusCall::PopulateComPlusCallMethodDesc(pMD, &dwStubFlags);
                if (FAILED(FindPredefinedILStubMethod(pMD, dwStubFlags, &pStubMD)))
                {                    
                    pStubMD = ComPlusCall::GetILStubMethodDesc(pMD, dwStubFlags | dwNGenStubFlags);
                }
            }
        }
#endif // FEATURE_COMINTEROP
        else if (pMD->IsEEImpl())
        {
            MethodTable* pMT = pMD->GetMethodTable();
            CONSISTENCY_CHECK(pMT->IsDelegate());

            // we can filter out non-WinRT generic delegates right off the top
            if (!pMD->HasClassOrMethodInstantiation() || pMT->IsProjectedFromWinRT()
#ifdef FEATURE_COMINTEROP
                || WinRTTypeNameConverter::IsRedirectedType(pMT)
#endif // FEATURE_COMINTEROP
                )
            {
                if (COMDelegate::IsDelegateInvokeMethod(pMD)) // build forward stub
                {
#ifdef FEATURE_COMINTEROP
                    if ((pMT->IsProjectedFromWinRT() || WinRTTypeNameConverter::IsRedirectedType(pMT)) &&
                        (!pMT->HasInstantiation() || pMT->SupportsGenericInterop(TypeHandle::Interop_ManagedToNative))) // filter out shared generics
                    {
                        // Build the stub for all WinRT delegates, these will definitely be used for interop.
                        if (pMT->IsLegalNonArrayWinRTType())
                        {
                            COMDelegate::PopulateComPlusCallInfo(pMT);
                            pStubMD = COMDelegate::GetILStubMethodDesc((EEImplMethodDesc *)pMD, dwNGenStubFlags);
                        }
                    }
                    else
#endif // FEATURE_COMINTEROP
                    {
                        // Build the stub only if the delegate is decorated with UnmanagedFunctionPointerAttribute.
                        // Forward delegate stubs are rare so we require this opt-in to avoid bloating NGEN images.

                        if (S_OK == pMT->GetMDImport()->GetCustomAttributeByName(
                            pMT->GetCl(), g_UnmanagedFunctionPointerAttribute, NULL, NULL))
                        {
                            pStubMD = COMDelegate::GetILStubMethodDesc((EEImplMethodDesc *)pMD, dwNGenStubFlags);
                        }
                    }
                }
            }
        }

        // compile the forward stub
        if (pStubMD != NULL)
        {
            pStubMD = CompileMethodStubIfNeeded(pMD, pStubMD, pfnCallback, pCallbackContext);

            // We store the MethodDesc of the Stub on the NDirectMethodDesc/ComPlusCallMethodDesc/DelegateEEClass
            // that we can recover the stub MethodDesc at prestub time, do the fixups, and wire up the native code
            if (pStubMD != NULL)
            {
                 SetStubMethodDescOnInteropMethodDesc(pMD, pStubMD, false /* fReverseStub */);
                 pStubMD = NULL;
            }

        }
    }
    EX_CATCH
    {
        LOG((LF_ZAP, LL_WARNING, "NGEN_ILSTUB: Generating forward interop stub FAILED: %s::%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
    }
    EX_END_CATCH(RethrowTransientExceptions);

    //
    // Now take care of reverse P/Invoke stubs for delegates
    //
    if (pMD->IsEEImpl() && COMDelegate::IsDelegateInvokeMethod(pMD))
    {
        // Reverse P/Invoke is not supported for generic methods and WinRT delegates
        if (!pMD->HasClassOrMethodInstantiation() && !pMD->GetMethodTable()->IsProjectedFromWinRT())
        {
            EX_TRY
            {
#ifdef _TARGET_X86_
                // on x86, we call the target directly if Invoke has a no-marshal signature
                if (NDirect::MarshalingRequired(pMD))
#endif // _TARGET_X86_
                {
                    PInvokeStaticSigInfo sigInfo(pMD);
                    pStubMD = UMThunkMarshInfo::GetILStubMethodDesc(pMD, &sigInfo, NDIRECTSTUB_FL_DELEGATE | dwNGenStubFlags);

                    if (pStubMD != NULL)
                    {
                        // compile the reverse stub
                        pStubMD = CompileMethodStubIfNeeded(pMD, pStubMD, pfnCallback, pCallbackContext);

                        // We store the MethodDesc of the Stub on the DelegateEEClass
                        if (pStubMD != NULL)
                        {
                            SetStubMethodDescOnInteropMethodDesc(pMD, pStubMD, true /* fReverseStub */);
                        }
                    }
                }
            }
            EX_CATCH
            {
                LOG((LF_ZAP, LL_WARNING, "NGEN_ILSTUB: Generating reverse interop stub for delegate FAILED: %s::%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
            }
            EX_END_CATCH(RethrowTransientExceptions);
        }
    }

#ifdef FEATURE_COMINTEROP
    //
    // And finally generate reverse COM stubs
    //
    EX_TRY
    {
        // The method doesn't have to have a special type to be exposed to COM, in particular it doesn't
        // have to be ComPlusCallMethodDesc. However, it must have certain properties (custom attributes,
        // public visibility, etc.)
        if (MethodNeedsReverseComStub(pMD))
        {
            // initialize ComCallMethodDesc
            ComCallMethodDesc ccmd;
            ComCallMethodDescHolder ccmdHolder(&ccmd);
            ccmd.InitMethod(pMD, NULL);

            // generate the IL stub
            DWORD dwStubFlags;
            ComCall::PopulateComCallMethodDesc(&ccmd, &dwStubFlags);
            pStubMD = ComCall::GetILStubMethodDesc(pMD, dwStubFlags | dwNGenStubFlags);

            if (pStubMD != NULL)
            {
                // compile the reverse stub
                pStubMD = CompileMethodStubIfNeeded(pMD, pStubMD, pfnCallback, pCallbackContext);

                if (pStubMD != NULL)
                {
                    // store the stub in a hash table on the module
                    m_image->GetModule()->GetStubMethodHashTable()->InsertMethodDesc(pMD, pStubMD);
                }
            }
        }
    }
    EX_CATCH
    {
        LOG((LF_ZAP, LL_WARNING, "NGEN_ILSTUB: Generating reverse interop stub FAILED: %s::%s\n", pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
    }
    EX_END_CATCH(RethrowTransientExceptions);
#endif // FEATURE_COMINTEROP
}

bool CEEPreloader::IsDynamicMethod(CORINFO_METHOD_HANDLE hMethod)
{
    STANDARD_VM_CONTRACT;

    MethodDesc* pMD = GetMethod(hMethod);

    if (pMD)
    {
        return pMD->IsDynamicMethod();
    }

    return false;
}

// Set method profiling flags for layout of EE datastructures
void CEEPreloader::SetMethodProfilingFlags(CORINFO_METHOD_HANDLE hMethod, DWORD flags)
{
    STANDARD_VM_CONTRACT;

    _ASSERTE(hMethod != NULL);
    _ASSERTE(flags != 0);

    return m_image->SetMethodProfilingFlags(GetMethod(hMethod), flags);
}

/*********************************************************************/
// canSkipMethodPreparation: Is there a need for all calls from
// NGEN'd code to a particular MethodDesc to go through DoPrestub,
// depending on the method sematics?  If so return FALSE.
//
// This is used to rule out both ngen-hardbinds and intra-ngen-module
// direct calls.
//
// The cases where direct calls are not allowed are typically where
// a stub must be inserted by DoPrestub (we do not save stubs) or where
// we haven't saved the code for some reason or another, or where fixups
// are required in the MethodDesc.
//
// callerHnd=NULL implies any/unspecified caller.
//
// Note that there may be other requirements for going through the prestub
// which vary based on the scenario. These need to be handled separately

bool CEEPreloader::CanSkipMethodPreparation (
        CORINFO_METHOD_HANDLE   callerHnd,
        CORINFO_METHOD_HANDLE   calleeHnd,
        CorInfoIndirectCallReason *pReason,
        CORINFO_ACCESS_FLAGS    accessFlags/*=CORINFO_ACCESS_ANY*/)
{
    STANDARD_VM_CONTRACT;

    bool result = false;

    COOPERATIVE_TRANSITION_BEGIN();

    MethodDesc *  calleeMD    = (MethodDesc *)calleeHnd;
    MethodDesc *  callerMD    = (MethodDesc *)callerHnd;

    {
        result = calleeMD->CanSkipDoPrestub(callerMD, pReason, accessFlags);
    }

    COOPERATIVE_TRANSITION_END();

    return result;
}

CORINFO_METHOD_HANDLE CEEPreloader::LookupMethodDef(mdMethodDef token)
{
    STANDARD_VM_CONTRACT;
    MethodDesc *resultMD = nullptr;

    EX_TRY
    {
        MethodDesc *pMD = MemberLoader::GetMethodDescFromMethodDef(m_image->GetModule(), token, FALSE);

        if (IsReadyToRunCompilation() && pMD->HasClassOrMethodInstantiation())
        {
            _ASSERTE(IsCompilationProcess() && pMD->GetModule_NoLogging() == GetAppDomain()->ToCompilationDomain()->GetTargetModule());
        }

        resultMD = pMD->FindOrCreateTypicalSharedInstantiation();
    }
    EX_CATCH
    {
        this->Error(token, GET_EXCEPTION());
    }
    EX_END_CATCH(SwallowAllExceptions)

    return CORINFO_METHOD_HANDLE(resultMD);
}

bool CEEPreloader::GetMethodInfo(mdMethodDef token, CORINFO_METHOD_HANDLE ftnHnd, CORINFO_METHOD_INFO * methInfo)
{
    STANDARD_VM_CONTRACT;
    bool result = false;

    EX_TRY
    {
        result = GetZapJitInfo()->getMethodInfo(ftnHnd, methInfo);
    }
    EX_CATCH
    {
        result = false;
        this->Error(token, GET_EXCEPTION());
    }
    EX_END_CATCH(SwallowAllExceptions)

    return result;
}

static BOOL MethodIsVisibleOutsideItsAssembly(DWORD dwMethodAttr)
{
    LIMITED_METHOD_CONTRACT;
    return (IsMdPublic(dwMethodAttr) ||
        IsMdFamORAssem(dwMethodAttr) ||
        IsMdFamily(dwMethodAttr));
}

static BOOL ClassIsVisibleOutsideItsAssembly(DWORD dwClassAttr, BOOL fIsGlobalClass)
{
    LIMITED_METHOD_CONTRACT;

    if (fIsGlobalClass)
    {
        return TRUE;
    }

    return (IsTdPublic(dwClassAttr) ||
        IsTdNestedPublic(dwClassAttr) ||
        IsTdNestedFamily(dwClassAttr) ||
        IsTdNestedFamORAssem(dwClassAttr));
}

static BOOL MethodIsVisibleOutsideItsAssembly(MethodDesc * pMD)
{
    LIMITED_METHOD_CONTRACT;

    MethodTable * pMT = pMD->GetMethodTable();

    if (!ClassIsVisibleOutsideItsAssembly(pMT->GetAttrClass(), pMT->IsGlobalClass()))
        return FALSE;

    return MethodIsVisibleOutsideItsAssembly(pMD->GetAttrs());
}

CorCompileILRegion CEEPreloader::GetILRegion(mdMethodDef token)
{
    STANDARD_VM_CONTRACT;

    // Since we are running managed code during NGen the inlining hint may be 
    // changing underneeth us as the code is JITed. We need to prevent the inlining
    // hints from changing once we start to use them to place IL in the image.
    g_pCEECompileInfo->DisableCachingOfInliningHints();

    // Default if there is something completely wrong, e.g. the type failed to load.
    // We may need the IL at runtime.
    CorCompileILRegion region = CORCOMPILE_ILREGION_WARM;

    EX_TRY
    {
        MethodDesc *pMD = m_image->GetModule()->LookupMethodDef(token);

        if (pMD == NULL || !pMD->GetMethodTable()->IsFullyLoaded())
        {
            // Something is completely wrong - use the default
        }
        else
        if (m_image->IsStored(pMD))
        {
            if (pMD->IsNotInline())
            {
                if (pMD->HasClassOrMethodInstantiation())
                {
                    region = CORCOMPILE_ILREGION_GENERICS;
                }
                else
                {
                    region = CORCOMPILE_ILREGION_COLD;
                }
            }
            else
            if (MethodIsVisibleOutsideItsAssembly(pMD))
            {
                // We are inlining only leaf methods, except for mscorlib. Thus we can assume that only methods
                // visible outside its assembly are likely to be inlined.
                region = CORCOMPILE_ILREGION_INLINEABLE;
            }
            else
            {
                // We may still need the IL of the non-nonvisible methods for inlining in certain scenarios:
                // dynamically emitted IL, friend assemblies or JITing of generic instantiations
                region = CORCOMPILE_ILREGION_WARM;
            }
        }
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions)

    return region;
}


CORINFO_METHOD_HANDLE CEEPreloader::FindMethodForProfileEntry(CORBBTPROF_BLOB_PARAM_SIG_ENTRY * profileBlobEntry)
{
    STANDARD_VM_CONTRACT;
    MethodDesc *  pMethod = nullptr;

    _ASSERTE(profileBlobEntry->blob.type == ParamMethodSpec);

    if (PartialNGenStressPercentage() != 0)
        return CORINFO_METHOD_HANDLE( NULL );

    Module * pModule = GetAppDomain()->ToCompilationDomain()->GetTargetModule();
    pMethod = pModule->LoadIBCMethodHelper(m_image, profileBlobEntry);
   
    return CORINFO_METHOD_HANDLE( pMethod );
}

void CEEPreloader::ReportInlining(CORINFO_METHOD_HANDLE inliner, CORINFO_METHOD_HANDLE inlinee)
{
    STANDARD_VM_CONTRACT;
    m_image->ReportInlining(inliner, inlinee);
}

void CEEPreloader::Link()
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    m_image->PreSave();

    m_image->GetModule()->Save(m_image);
    m_image->GetModule()->Arrange(m_image);
    m_image->GetModule()->Fixup(m_image);

    m_image->PostSave();

    COOPERATIVE_TRANSITION_END();
}

void CEEPreloader::FixupRVAs()
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    m_image->FixupRVAs();

    COOPERATIVE_TRANSITION_END();
}

void CEEPreloader::SetRVAsForFields(IMetaDataEmit * pEmit)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    m_image->SetRVAsForFields(pEmit);

    COOPERATIVE_TRANSITION_END();
}

void CEEPreloader::GetRVAFieldData(mdFieldDef fd, PVOID * ppData, DWORD * pcbSize, DWORD * pcbAlignment)
{
    STANDARD_VM_CONTRACT;

    COOPERATIVE_TRANSITION_BEGIN();

    FieldDesc * pFD = m_image->GetModule()->LookupFieldDef(fd);
    if (pFD == NULL)
        ThrowHR(COR_E_TYPELOAD);

    _ASSERTE(pFD->IsRVA());

    UINT size = pFD->LoadSize();

    // 
    // Compute an alignment for the data based on the alignment
    // of the RVA.  We'll align up to 8 bytes.
    //

    UINT align = 1;
    DWORD rva = pFD->GetOffset();
    DWORD rvaTemp = rva;   

    while ((rvaTemp&1) == 0 && align < 8 && align < size)
    {
        align <<= 1;
        rvaTemp >>= 1;
    }


    *ppData = pFD->GetStaticAddressHandle(NULL);
    *pcbSize = size;
    *pcbAlignment = align;

    COOPERATIVE_TRANSITION_END();
}

ULONG CEEPreloader::Release()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    delete this;
    return 0;
}

#ifdef FEATURE_READYTORUN_COMPILER
void CEEPreloader::GetSerializedInlineTrackingMap(SBuffer* pBuffer)
{
    InlineTrackingMap * pInlineTrackingMap = m_image->GetInlineTrackingMap();
    PersistentInlineTrackingMapR2R::Save(m_image->GetHeap(), pBuffer, pInlineTrackingMap);
}
#endif

void CEEPreloader::Error(mdToken token, Exception * pException)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = pException->GetHR();
    UINT    resID = 0;

    StackSString msg;

#ifdef CROSSGEN_COMPILE
    pException->GetMessage(msg);

    // Do we have an EEException with a resID?
    if (EEMessageException::IsEEMessageException(pException))
    {
        EEMessageException * pEEMessageException = (EEMessageException *) pException;
        resID = pEEMessageException->GetResID();
    }
#else
    {
        GCX_COOP();

        // Going though throwable gives more verbose error messages in certain cases that our tests depend on.
        OBJECTREF throwable = NingenEnabled() ? NULL : CLRException::GetThrowableFromException(pException);

        if (throwable != NULL)
        {
            GetExceptionMessage(throwable, msg);
        }
        else
        {
            pException->GetMessage(msg);
        }
    }
#endif
    
    m_pData->Error(token, hr, resID, msg.GetUnicode());
}

CEEInfo *g_pCEEInfo = NULL;

ICorDynamicInfo * __stdcall GetZapJitInfo()
{
    STANDARD_VM_CONTRACT;

    if (g_pCEEInfo == NULL)
    {
        CEEInfo * p = new CEEInfo();
        if (InterlockedCompareExchangeT(&g_pCEEInfo, p, NULL) != NULL)
            delete p;
    }

    return g_pCEEInfo;
}

CEECompileInfo *g_pCEECompileInfo = NULL;

ICorCompileInfo * __stdcall GetCompileInfo()
{
    STANDARD_VM_CONTRACT;

    if (g_pCEECompileInfo == NULL)
    {
        CEECompileInfo * p = new CEECompileInfo();
        if (InterlockedCompareExchangeT(&g_pCEECompileInfo, p, NULL) != NULL)
            delete p;
    }

    return g_pCEECompileInfo;
}

//
// CompilationDomain
//

CompilationDomain::CompilationDomain(BOOL fForceDebug,
                                     BOOL fForceProfiling,
                                     BOOL fForceInstrument)
  : m_fForceDebug(fForceDebug),
    m_fForceProfiling(fForceProfiling),
    m_fForceInstrument(fForceInstrument),
    m_pTargetAssembly(NULL),
    m_pTargetModule(NULL),
    m_pTargetImage(NULL),
    m_pEmit(NULL),
    m_pDependencyRefSpecs(NULL),
    m_pDependencies(NULL),
    m_cDependenciesCount(0),
    m_cDependenciesAlloc(0)
{
    STANDARD_VM_CONTRACT;

}

void CompilationDomain::ReleaseDependencyEmitter()
{
    m_pDependencyRefSpecs.Release();

    m_pEmit.Release();
}

CompilationDomain::~CompilationDomain()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_pDependencies != NULL)
        delete [] m_pDependencies;

    ReleaseDependencyEmitter();

    for (unsigned i = 0; i < m_rRefCaches.Size(); i++)
    {
        delete m_rRefCaches[i];
        m_rRefCaches[i]=NULL;
    }

}

void CompilationDomain::Init()
{
    STANDARD_VM_CONTRACT;

#ifndef CROSSGEN_COMPILE
    AppDomain::Init();
#endif

#ifndef CROSSGEN_COMPILE
    // allocate a Virtual Call Stub Manager for the compilation domain
    InitVSD();
#endif

    SetCompilationDomain();


#ifdef _DEBUG 
    g_pConfig->DisableGenerateStubForHost();
#endif
}

HRESULT CompilationDomain::AddDependencyEntry(PEAssembly *pFile,
                                           mdAssemblyRef ref,
                                           mdAssemblyRef def)
{
#ifdef _DEBUG
    // This method is not multi-thread safe.  This is OK because it is only called by NGen compiling, which is
    // effectively single-threaded.  The following code verifies that we're not called on multiple threads.
    static volatile LONG threadId = 0;
    if (threadId == 0)
    {
        InterlockedCompareExchange(&threadId, GetCurrentThreadId(), 0);
    }
    _ASSERTE((LONG)GetCurrentThreadId() == threadId);
#endif // _DEBUG

    _ASSERTE((pFile == NULL) == (def == mdAssemblyRefNil));

    if (m_cDependenciesCount == m_cDependenciesAlloc)
    {
        // Save the new count in a local variable.  Can't update m_cDependenciesAlloc until the new
        // CORCOMPILE_DEPENDENCY array is allocated, otherwise an out-of-memory exception from new[]
        // operator would put the data in an inconsistent state, causing heap corruption later.
        USHORT cNewDependenciesAlloc = m_cDependenciesAlloc == 0 ? 20 : m_cDependenciesAlloc * 2;

        // Grow m_pDependencies

        NewArrayHolder<CORCOMPILE_DEPENDENCY> pNewDependencies(new CORCOMPILE_DEPENDENCY[cNewDependenciesAlloc]);
        {
            // This block must execute transactionally. No throwing allowed. No bailing allowed.
            FAULT_FORBID();

            memset(pNewDependencies,  0, cNewDependenciesAlloc*sizeof(CORCOMPILE_DEPENDENCY));

            if (m_pDependencies)
            {
                memcpy(pNewDependencies, m_pDependencies,
                       m_cDependenciesCount*sizeof(CORCOMPILE_DEPENDENCY));
    
                delete [] m_pDependencies;
            }
    
            m_pDependencies = pNewDependencies.Extract();
            m_cDependenciesAlloc = cNewDependenciesAlloc;
        }
    }

    CORCOMPILE_DEPENDENCY *pDependency = &m_pDependencies[m_cDependenciesCount++];

    // Clear memory so that we won't write random data into the zapped file
    ZeroMemory(pDependency, sizeof(CORCOMPILE_DEPENDENCY));

    pDependency->dwAssemblyRef = ref;

    pDependency->dwAssemblyDef = def;

    pDependency->signNativeImage = INVALID_NGEN_SIGNATURE;

    if (pFile)
    {
        DomainAssembly *pAssembly = GetAppDomain()->LoadDomainAssembly(NULL, pFile, FILE_LOAD_CREATE);
        // Note that this can trigger an assembly load (of mscorlib)
        pAssembly->GetOptimizedIdentitySignature(&pDependency->signAssemblyDef);



        //
        // This is done in CompilationDomain::CanEagerBindToZapFile with full support for hardbinding
        //
        if (pFile->IsSystem() && pFile->HasNativeImage())
        {
            CORCOMPILE_VERSION_INFO * pNativeVersion = pFile->GetLoadedNative()->GetNativeVersionInfo();
            pDependency->signNativeImage = pNativeVersion->signature;
        }

    }

    return S_OK;
}

HRESULT CompilationDomain::AddDependency(AssemblySpec *pRefSpec,
                                         PEAssembly * pFile)
{
    HRESULT hr;

    //
    // Record the dependency
    //

    // This assert prevents dependencies from silently being loaded without being recorded.
    _ASSERTE(m_pEmit);

    // Normalize any reference to mscorlib; we don't want to record other non-canonical
    // mscorlib references in the ngen image since fusion doesn't understand how to bind them.
    // (Not to mention the fact that they are redundant.)
    AssemblySpec spec;
    if (pRefSpec->IsMscorlib())
    {
        _ASSERTE(pFile); // mscorlib had better not be missing
        if (!pFile)
            return E_UNEXPECTED;

        // Don't store a binding from mscorlib to itself.
        if (m_pTargetAssembly == SystemDomain::SystemAssembly())
            return S_OK;

        spec.InitializeSpec(pFile);
        pRefSpec = &spec;
    }
    else if (m_pTargetAssembly == NULL && pFile)
    {
        // If target assembly is still NULL, we must be loading either the target assembly or mscorlib.
        // Mscorlib is already handled above, so we must be loading the target assembly if we get here.
        // Use the assembly name given in the target assembly so that the native image is deterministic
        // regardless of how the target assembly is specified on the command line.
        spec.InitializeSpec(pFile);
        if (spec.IsStrongNamed() && spec.HasPublicKey())
        {
            spec.ConvertPublicKeyToToken();
        }
        pRefSpec = &spec;
    }
    else if (pRefSpec->IsStrongNamed() && pRefSpec->HasPublicKey())
    {
        // Normalize to always use public key token.  Otherwise we may insert one reference
        // using public key, and another reference using public key token.
        spec.CopyFrom(pRefSpec);
        spec.ConvertPublicKeyToToken();
        pRefSpec = &spec;
    }

#ifdef FEATURE_COMINTEROP
    // Only cache ref specs that have a unique identity. This is needed to avoid caching
    // things like WinRT type specs, which would benefit very little from being cached.
    if (!pRefSpec->HasUniqueIdentity())
    {
        // Successful bind of a reference with a non-unique assembly identity.
        _ASSERTE(pRefSpec->IsContentType_WindowsRuntime());

        AssemblySpec defSpec;
        if (pFile != NULL)
        {
            defSpec.InitializeSpec(pFile);

            // Windows Runtime Native Image binding depends on details exclusively described by the definition winmd file.
            // Therefore we can actually drop the existing ref spec here entirely.
            // Also, Windows Runtime Native Image binding uses the simple name of the ref spec as the
            // resolution rule for PreBind when finding definition assemblies.
            // See comment on CLRPrivBinderWinRT::PreBind for further details.
            pRefSpec = &defSpec;
        }

        // Unfortunately, we don't have any choice regarding failures (pFile == NULL) because
        // there is no value to canonicalize on (i.e., a def spec created from a non-NULL
        // pFile) and so we must cache all non-unique-assembly-id failures.
        const AssemblySpecDefRefMapEntry * pEntry = m_dependencyDefRefMap.LookupPtr(&defSpec);
        if (pFile == NULL || pEntry == NULL)
        {
            mdAssemblyRef refToken = mdAssemblyRefNil;
            IfFailRet(pRefSpec->EmitToken(m_pEmit, &refToken, TRUE, TRUE));

            mdAssemblyRef defToken = mdAssemblyRefNil;
            if (pFile != NULL)
            {
                IfFailRet(defSpec.EmitToken(m_pEmit, &defToken, TRUE, TRUE));

                NewHolder<AssemblySpec> pNewDefSpec = new AssemblySpec();
                pNewDefSpec->CopyFrom(&defSpec);
                pNewDefSpec->CloneFields();

                NewHolder<AssemblySpec> pNewRefSpec = new AssemblySpec();
                pNewRefSpec->CopyFrom(pRefSpec);
                pNewRefSpec->CloneFields();

                _ASSERTE(m_dependencyDefRefMap.LookupPtr(pNewDefSpec) == NULL);

                AssemblySpecDefRefMapEntry e;
                e.m_pDef = pNewDefSpec;
                e.m_pRef = pNewRefSpec;
                m_dependencyDefRefMap.Add(e);

                pNewDefSpec.SuppressRelease();
                pNewRefSpec.SuppressRelease();
            }

            IfFailRet(AddDependencyEntry(pFile, refToken, defToken));
        }
    }
    else
#endif // FEATURE_COMINTEROP
    {
        //
        // See if we've already added the contents of the ref
        // Else, emit token for the ref
        //

        if (m_pDependencyRefSpecs->Store(pRefSpec))
            return S_OK;

        mdAssemblyRef refToken;
        IfFailRet(pRefSpec->EmitToken(m_pEmit, &refToken));

        //
        // Make a spec for the bound assembly
        //

        mdAssemblyRef defToken = mdAssemblyRefNil;

        // All dependencies of a shared assembly need to be shared. So for a shared
        // assembly, we want to remember the missing assembly ref during ngen, so that
        // we can probe eagerly for the dependency at load time, and make sure that
        // it is loaded as shared.
        // In such a case, pFile will be NULL
        if (pFile)
        {
            AssemblySpec assemblySpec;
            assemblySpec.InitializeSpec(pFile);

            IfFailRet(assemblySpec.EmitToken(m_pEmit, &defToken));
        }

        //
        // Add the entry.  Include the PEFile if we are not doing explicit bindings.
        //

        IfFailRet(AddDependencyEntry(pFile, refToken, defToken));
    }

    return S_OK;
}

//----------------------------------------------------------------------------
AssemblySpec* CompilationDomain::FindAssemblyRefSpecForDefSpec(
    AssemblySpec* pDefSpec)
{
    WRAPPER_NO_CONTRACT;

    if (pDefSpec == nullptr)
        return nullptr;

    const AssemblySpecDefRefMapEntry * pEntry = m_dependencyDefRefMap.LookupPtr(pDefSpec);
    _ASSERTE(pEntry != NULL);

    return (pEntry != NULL) ? pEntry->m_pRef : NULL;
}


//----------------------------------------------------------------------------
// Is it OK to embed direct pointers to an ngen dependency?
// true if hardbinding is OK, false otherwise
//
// targetModule - The pointer points into the native image of this Module.
//                If this native image gets relocated, the native image of
//                the source Module is invalidated unless the embedded
//                pointer can be fixed up appropriately.
// limitToHardBindList - Is it OK to hard-bind to a dependency even if it is
//                not asked for explicitly?

BOOL CompilationDomain::CanEagerBindToZapFile(Module *targetModule, BOOL limitToHardBindList)
{
    // We do this check before checking the hashtables because m_cantHardBindModules
    // will contain non-manifest modules. However, we do want them to be able
    // to hard-bind to themselves
    if (targetModule == m_pTargetModule)
    {
        return TRUE;
    }

    //
    // CoreCLR does not have attributes for fine grained eager binding control.
    // We hard bind to mscorlib.dll only.
    //
    return targetModule->IsSystem();
}


void CompilationDomain::SetTarget(Assembly *pAssembly, Module *pModule)
{
    STANDARD_VM_CONTRACT;

    m_pTargetAssembly = pAssembly;
    m_pTargetModule = pModule;
}

void CompilationDomain::SetTargetImage(DataImage *pImage, CEEPreloader * pPreloader)
{
    STANDARD_VM_CONTRACT;

    m_pTargetImage = pImage;
    m_pTargetPreloader = pPreloader;

    _ASSERTE(pImage->GetModule() == GetTargetModule());
}

void ReportMissingDependency(Exception * e)
{
    // Avoid duplicate error messages
    if (FAILED(g_hrFatalError))
        return;

    SString s;

    e->GetMessage(s);
    GetSvcLogger()->Printf(LogLevel_Error, W("Error: %s\n"), s.GetUnicode());

    g_hrFatalError = COR_E_FILELOAD;
}

PEAssembly *CompilationDomain::BindAssemblySpec(
    AssemblySpec *pSpec,
    BOOL fThrowOnFileNotFound,
    BOOL fRaisePrebindEvents,
    StackCrawlMark *pCallerStackMark,
    BOOL fUseHostBinderIfAvailable)
{
    PEAssembly *pFile = NULL;
    //
    // Do the binding
    //

    EX_TRY
    {
        //
        // Use normal binding rules
        // (possibly with our custom IApplicationContext)
        //
        pFile = AppDomain::BindAssemblySpec(
            pSpec,
            fThrowOnFileNotFound,
            fRaisePrebindEvents,
            pCallerStackMark,
            fUseHostBinderIfAvailable);
    }
    EX_HOOK
    {
        if (!g_fNGenMissingDependenciesOk)
        {
            ReportMissingDependency(GET_EXCEPTION());
            EX_RETHROW;
        }

        //
        // Record missing dependencies
        //
#ifdef FEATURE_COMINTEROP                
        if (!g_fNGenWinMDResilient || pSpec->HasUniqueIdentity())
#endif
        {
            IfFailThrow(AddDependency(pSpec, NULL));
        }
    }
    EX_END_HOOK

#ifdef FEATURE_COMINTEROP                
    if (!g_fNGenWinMDResilient || pSpec->HasUniqueIdentity())
#endif
    {
        IfFailThrow(AddDependency(pSpec, pFile));
    }

    return pFile;
}

HRESULT
    CompilationDomain::SetContextInfo(LPCWSTR path, BOOL isExe)
{
    STANDARD_VM_CONTRACT;

    HRESULT hr = S_OK;

    COOPERATIVE_TRANSITION_BEGIN();


    COOPERATIVE_TRANSITION_END();

    return hr;
}

void CompilationDomain::SetDependencyEmitter(IMetaDataAssemblyEmit *pEmit)
{
    STANDARD_VM_CONTRACT;

    pEmit->AddRef();
    m_pEmit = pEmit;

    m_pDependencyRefSpecs = new AssemblySpecHash();
}


HRESULT
    CompilationDomain::GetDependencies(CORCOMPILE_DEPENDENCY **ppDependencies,
                                       DWORD *pcDependencies)
{
    STANDARD_VM_CONTRACT;


    //
    // Return the bindings.
    //

    *ppDependencies = m_pDependencies;
    *pcDependencies = m_cDependenciesCount;

    // Cannot add any more dependencies
    ReleaseDependencyEmitter();

    return S_OK;
}


#ifdef CROSSGEN_COMPILE
HRESULT CompilationDomain::SetPlatformWinmdPaths(LPCWSTR pwzPlatformWinmdPaths)
{
    STANDARD_VM_CONTRACT;

#ifdef FEATURE_COMINTEROP
    // Create the array list on the heap since it will be passed off for the Crossgen RoResolveNamespace mockup to keep for the life of the process
    StringArrayList *saPaths = new StringArrayList();

    SString strPaths(pwzPlatformWinmdPaths);
    if (!strPaths.IsEmpty())
    {
        for (SString::Iterator i = strPaths.Begin(); i != strPaths.End(); )
        {
            // Skip any leading spaces or semicolons
            if (strPaths.Skip(i, W(';')))
            {
                continue;
            }
        
            SString::Iterator iEnd = i;     // Where current assembly name ends
            SString::Iterator iNext;        // Where next assembly name starts
            if (strPaths.Find(iEnd, W(';')))
            {
                iNext = iEnd + 1;
            }
            else
            {
                iNext = iEnd = strPaths.End();
            }
        
            _ASSERTE(i < iEnd);
            if(i != iEnd)
            {
                saPaths->Append(SString(strPaths, i, iEnd));
            }
            i = iNext;
        }
    }
    Crossgen::SetFirstPartyWinMDPaths(saPaths);
#endif // FEATURE_COMINTEROP

    return S_OK;
}
#endif // CROSSGEN_COMPILE


#endif // FEATURE_PREJIT