DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (7fd12a78625c)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "gc/Marking-inl.h"

#include "mozilla/ArrayUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerRange.h"
#include "mozilla/ReentrancyGuard.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/TypeTraits.h"

#include "jsfriendapi.h"

#include "builtin/ModuleObject.h"
#include "debugger/DebugAPI.h"
#include "gc/GCInternals.h"
#include "gc/Policy.h"
#include "jit/IonCode.h"
#include "js/SliceBudget.h"
#include "vm/ArgumentsObject.h"
#include "vm/ArrayObject.h"
#include "vm/BigIntType.h"
#include "vm/EnvironmentObject.h"
#include "vm/GeneratorObject.h"
#include "vm/RegExpShared.h"
#include "vm/Scope.h"
#include "vm/Shape.h"
#include "vm/SymbolType.h"
#include "vm/TypedArrayObject.h"
#include "wasm/WasmJS.h"

#include "gc/GC-inl.h"
#include "gc/Nursery-inl.h"
#include "gc/PrivateIterators-inl.h"
#include "gc/Zone-inl.h"
#include "vm/GeckoProfiler-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Realm-inl.h"
#include "vm/StringType-inl.h"

using namespace js;
using namespace js::gc;

using JS::MapTypeToTraceKind;

using mozilla::DebugOnly;
using mozilla::IntegerRange;
using mozilla::IsBaseOf;
using mozilla::IsSame;
using mozilla::PodCopy;

// [SMDOC] GC Tracing
//
// Tracing Overview
// ================
//
// Tracing, in this context, refers to an abstract visitation of some or all of
// the GC-controlled heap. The effect of tracing an edge of the graph depends
// on the subclass of the JSTracer on whose behalf we are tracing.
//
// Marking
// -------
//
// The primary JSTracer is the GCMarker. The marking tracer causes the target
// of each traversed edge to be marked black and the target edge's children to
// be marked either gray (in the gc algorithm sense) or immediately black.
//
// Callback
// --------
//
// The secondary JSTracer is the CallbackTracer. This simply invokes a callback
// on each edge in a child.
//
// The following is a rough outline of the general struture of the tracing
// internals.
//
/* clang-format off */
//                                                                                              //
//   .---------.    .---------.    .--------------------------.       .----------.              //
//   |TraceEdge|    |TraceRoot|    |TraceManuallyBarrieredEdge|  ...  |TraceRange|   ... etc.   //
//   '---------'    '---------'    '--------------------------'       '----------'              //
//        \              \                        /                        /                    //
//         \              \  .-----------------. /                        /                     //
//          o------------->o-|TraceEdgeInternal|-o<----------------------o                      //
//                           '-----------------'                                                //
//                              /          \                                                    //
//                             /            \                                                   //
//                       .---------.   .----------.         .-----------------.                 //
//                       |DoMarking|   |DoCallback|-------> |<JSTraceCallback>|----------->     //
//                       '---------'   '----------'         '-----------------'                 //
//                            |                                                                 //
//                            |                                                                 //
//                     .-----------.                                                            //
//      o------------->|traverse(T)| .                                                          //
//     /_\             '-----------'   ' .                                                      //
//      |                   .       .      ' .                                                  //
//      |                   .         .        ' .                                              //
//      |                   .           .          ' .                                          //
//      |          .--------------.  .--------------.  ' .     .-----------------------.        //
//      |          |markAndScan(T)|  |markAndPush(T)|      ' - |markAndTraceChildren(T)|        //
//      |          '--------------'  '--------------'          '-----------------------'        //
//      |                   |                  \                               |                //
//      |                   |                   \                              |                //
//      |       .----------------------.     .----------------.         .------------------.    //
//      |       |eagerlyMarkChildren(T)|     |pushMarkStackTop|<===Oo   |T::traceChildren()|--> //
//      |       '----------------------'     '----------------'    ||   '------------------'    //
//      |                  |                         ||            ||                           //
//      |                  |                         ||            ||                           //
//      |                  |                         ||            ||                           //
//      o<-----------------o<========================OO============Oo                           //
//                                                                                              //
//                                                                                              //
//   Legend:                                                                                    //
//     ------  Direct calls                                                                     //
//     . . .   Static dispatch                                                                  //
//     ======  Dispatch through a manual stack.                                                 //
//                                                                                              //
/* clang-format on */

/*** Tracing Invariants *****************************************************/

#if defined(DEBUG)
template <typename T>
static inline bool IsThingPoisoned(T* thing) {
  const uint8_t poisonBytes[] = {
      JS_FRESH_NURSERY_PATTERN,      JS_SWEPT_NURSERY_PATTERN,
      JS_ALLOCATED_NURSERY_PATTERN,  JS_FRESH_TENURED_PATTERN,
      JS_MOVED_TENURED_PATTERN,      JS_SWEPT_TENURED_PATTERN,
      JS_ALLOCATED_TENURED_PATTERN,  JS_FREED_HEAP_PTR_PATTERN,
      JS_FREED_CHUNK_PATTERN,        JS_FREED_ARENA_PATTERN,
      JS_SWEPT_TI_PATTERN,           JS_SWEPT_CODE_PATTERN,
      JS_RESET_VALUE_PATTERN,        JS_POISONED_JSSCRIPT_DATA_PATTERN,
      JS_OOB_PARSE_NODE_PATTERN,     JS_LIFO_UNDEFINED_PATTERN,
      JS_LIFO_UNINITIALIZED_PATTERN,
  };
  const int numPoisonBytes = sizeof(poisonBytes) / sizeof(poisonBytes[0]);
  uint32_t* p =
      reinterpret_cast<uint32_t*>(reinterpret_cast<FreeSpan*>(thing) + 1);
  // Note: all free patterns are odd to make the common, not-poisoned case a
  // single test.
  if ((*p & 1) == 0) {
    return false;
  }
  for (int i = 0; i < numPoisonBytes; ++i) {
    const uint8_t pb = poisonBytes[i];
    const uint32_t pw = pb | (pb << 8) | (pb << 16) | (pb << 24);
    if (*p == pw) {
      return true;
    }
  }
  return false;
}

bool js::IsTracerKind(JSTracer* trc, JS::CallbackTracer::TracerKind kind) {
  return trc->isCallbackTracer() &&
         trc->asCallbackTracer()->getTracerKind() == kind;
}
#endif

bool ThingIsPermanentAtomOrWellKnownSymbol(JSString* str) {
  return str->isPermanentAtom();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JSFlatString* str) {
  return str->isPermanentAtom();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JSLinearString* str) {
  return str->isPermanentAtom();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JSAtom* atom) {
  return atom->isPermanent();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(PropertyName* name) {
  return name->isPermanent();
}
bool ThingIsPermanentAtomOrWellKnownSymbol(JS::Symbol* sym) {
  return sym->isWellKnownSymbol();
}

template <typename T>
static inline bool IsOwnedByOtherRuntime(JSRuntime* rt, T thing) {
  bool other = thing->runtimeFromAnyThread() != rt;
  MOZ_ASSERT_IF(other, ThingIsPermanentAtomOrWellKnownSymbol(thing) ||
                           thing->zoneFromAnyThread()->isSelfHostingZone());
  return other;
}

template <typename T>
void js::CheckTracedThing(JSTracer* trc, T* thing) {
#ifdef DEBUG
  MOZ_ASSERT(trc);
  MOZ_ASSERT(thing);

  if (!trc->checkEdges()) {
    return;
  }

  if (IsForwarded(thing)) {
    thing = Forwarded(thing);
  }

  /* This function uses data that's not available in the nursery. */
  if (IsInsideNursery(thing)) {
    return;
  }

  MOZ_ASSERT_IF(!IsTracerKind(trc, JS::CallbackTracer::TracerKind::Moving) &&
                    !trc->isTenuringTracer(),
                !IsForwarded(thing));

  /*
   * Permanent atoms and things in the self-hosting zone are not associated
   * with this runtime, but will be ignored during marking.
   */
  if (IsOwnedByOtherRuntime(trc->runtime(), thing)) {
    return;
  }

  Zone* zone = thing->zoneFromAnyThread();
  JSRuntime* rt = trc->runtime();

  if (!IsTracerKind(trc, JS::CallbackTracer::TracerKind::Moving) &&
      !IsTracerKind(trc, JS::CallbackTracer::TracerKind::GrayBuffering) &&
      !IsTracerKind(trc, JS::CallbackTracer::TracerKind::ClearEdges) &&
      !IsTracerKind(trc, JS::CallbackTracer::TracerKind::Sweeping)) {
    MOZ_ASSERT(CurrentThreadCanAccessZone(zone));
    MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
  }

  MOZ_ASSERT(zone->runtimeFromAnyThread() == trc->runtime());

  // It shouldn't be possible to trace into zones used by helper threads, except
  // for use of ClearEdgesTracer by GCManagedDeletePolicy on a helper thread.
  MOZ_ASSERT_IF(!IsTracerKind(trc, JS::CallbackTracer::TracerKind::ClearEdges),
                !zone->usedByHelperThread());

  MOZ_ASSERT(thing->isAligned());
  MOZ_ASSERT(
      MapTypeToTraceKind<typename mozilla::RemovePointer<T>::Type>::kind ==
      thing->getTraceKind());

  bool isGcMarkingTracer = trc->isMarkingTracer();

  MOZ_ASSERT_IF(
      zone->requireGCTracer(),
      isGcMarkingTracer ||
          IsTracerKind(trc, JS::CallbackTracer::TracerKind::GrayBuffering) ||
          IsTracerKind(trc, JS::CallbackTracer::TracerKind::UnmarkGray) ||
          IsTracerKind(trc, JS::CallbackTracer::TracerKind::ClearEdges) ||
          IsTracerKind(trc, JS::CallbackTracer::TracerKind::Sweeping));

  if (isGcMarkingTracer) {
    GCMarker* gcMarker = GCMarker::fromTracer(trc);
    MOZ_ASSERT_IF(gcMarker->shouldCheckCompartments(),
                  zone->isCollecting() || zone->isAtomsZone());

    MOZ_ASSERT_IF(gcMarker->markColor() == MarkColor::Gray,
                  !zone->isGCMarkingBlackOnly() || zone->isAtomsZone());

    MOZ_ASSERT(!(zone->isGCSweeping() || zone->isGCFinished() ||
                 zone->isGCCompacting()));
  }

  /*
   * Try to assert that the thing is allocated.
   *
   * We would like to assert that the thing is not in the free list, but this
   * check is very slow. Instead we check whether the thing has been poisoned:
   * if it has not then we assume it is allocated, but if it has then it is
   * either free or uninitialized in which case we check the free list.
   *
   * Further complications are that background sweeping may be running and
   * concurrently modifiying the free list and that tracing is done off
   * thread during compacting GC and reading the contents of the thing by
   * IsThingPoisoned would be racy in this case.
   */
  MOZ_ASSERT_IF(JS::RuntimeHeapIsBusy() && !zone->isGCSweeping() &&
                    !zone->isGCFinished() && !zone->isGCCompacting(),
                !IsThingPoisoned(thing) ||
                    !InFreeList(thing->asTenured().arena(), thing));
#endif
}

template <typename T>
void js::CheckTracedThing(JSTracer* trc, T thing) {
  ApplyGCThingTyped(thing, [](auto t) { CheckTracedThing(t); });
}

namespace js {
#define IMPL_CHECK_TRACED_THING(_, type, _1, _2) \
  template void CheckTracedThing<type>(JSTracer*, type*);
JS_FOR_EACH_TRACEKIND(IMPL_CHECK_TRACED_THING);
#undef IMPL_CHECK_TRACED_THING
}  // namespace js

static bool UnmarkGrayGCThing(JSRuntime* rt, JS::GCCellPtr thing);

static inline bool ShouldMarkCrossCompartment(GCMarker* marker, JSObject* src,
                                              Cell* dstCell) {
  MarkColor color = marker->markColor();

  if (!dstCell->isTenured()) {
    MOZ_ASSERT(color == MarkColor::Black);
    return false;
  }
  TenuredCell& dst = dstCell->asTenured();

  JS::Zone* dstZone = dst.zone();
  if (!src->zone()->isGCMarking() && !dstZone->isGCMarking()) {
    return false;
  }

  if (color == MarkColor::Black) {
    // Check our sweep groups are correct: we should never have to
    // mark something in a zone that we have started sweeping.
    MOZ_ASSERT_IF(!dst.isMarkedBlack(), !dstZone->isGCSweeping());

    /*
     * Having black->gray edges violates our promise to the cycle collector so
     * we ensure that gray things we encounter when marking black end up getting
     * marked black.
     *
     * This can happen for two reasons:
     *
     * 1) If we're collecting a compartment and it has an edge to an uncollected
     * compartment it's possible that the source and destination of the
     * cross-compartment edge should be gray, but the source was marked black by
     * the write barrier.
     *
     * 2) If we yield during gray marking and the write barrier marks a gray
     * thing black.
     *
     * We handle the first case before returning whereas the second case happens
     * as part of normal marking.
     */
    if (dst.isMarkedGray() && !dstZone->isGCMarking()) {
      UnmarkGrayGCThing(marker->runtime(),
                        JS::GCCellPtr(&dst, dst.getTraceKind()));
      return false;
    }

    return dstZone->isGCMarking();
  } else {
    // Check our sweep groups are correct as above.
    MOZ_ASSERT_IF(!dst.isMarkedAny(), !dstZone->isGCSweeping());

    if (dstZone->isGCMarkingBlackOnly()) {
      /*
       * The destination compartment is being not being marked gray now,
       * but it will be later, so record the cell so it can be marked gray
       * at the appropriate time.
       */
      if (!dst.isMarkedAny()) {
        DelayCrossCompartmentGrayMarking(src);
      }
      return false;
    }

    return dstZone->isGCMarkingBlackAndGray();
  }
}

static bool ShouldTraceCrossCompartment(JSTracer* trc, JSObject* src,
                                        Cell* dstCell) {
  if (!trc->isMarkingTracer()) {
    return true;
  }

  return ShouldMarkCrossCompartment(GCMarker::fromTracer(trc), src, dstCell);
}

static bool ShouldTraceCrossCompartment(JSTracer* trc, JSObject* src,
                                        const Value& val) {
  return val.isGCThing() &&
         ShouldTraceCrossCompartment(trc, src, val.toGCThing());
}

static void AssertShouldMarkInZone(Cell* thing) {
  MOZ_ASSERT(thing->asTenured().zone()->shouldMarkInZone());
}

static void AssertShouldMarkInZone(JSString* str) {
#ifdef DEBUG
  Zone* zone = str->zone();
  MOZ_ASSERT(zone->shouldMarkInZone() || zone->isAtomsZone());
#endif
}

static void AssertShouldMarkInZone(JS::Symbol* sym) {
#ifdef DEBUG
  Zone* zone = sym->asTenured().zone();
  MOZ_ASSERT(zone->shouldMarkInZone() || zone->isAtomsZone());
#endif
}

#ifdef DEBUG
void js::gc::AssertRootMarkingPhase(JSTracer* trc) {
  MOZ_ASSERT_IF(trc->isMarkingTracer(),
                trc->runtime()->gc.state() == State::NotActive ||
                    trc->runtime()->gc.state() == State::MarkRoots);
}
#endif

/*** Tracing Interface ******************************************************/

template <typename T>
bool DoCallback(JS::CallbackTracer* trc, T** thingp, const char* name);
template <typename T>
bool DoCallback(JS::CallbackTracer* trc, T* thingp, const char* name);
template <typename T>
void DoMarking(GCMarker* gcmarker, T* thing);
template <typename T>
void DoMarking(GCMarker* gcmarker, const T& thing);

template <typename T>
JS_PUBLIC_API void js::gc::TraceExternalEdge(JSTracer* trc, T* thingp,
                                             const char* name) {
  MOZ_ASSERT(InternalBarrierMethods<T>::isMarkable(*thingp));
  TraceEdgeInternal(trc, ConvertToBase(thingp), name);
}

template <typename T>
JS_PUBLIC_API void js::UnsafeTraceManuallyBarrieredEdge(JSTracer* trc,
                                                        T* thingp,
                                                        const char* name) {
  TraceEdgeInternal(trc, ConvertToBase(thingp), name);
}

template <typename T>
JS_PUBLIC_API void JS::UnsafeTraceRoot(JSTracer* trc, T* thingp,
                                       const char* name) {
  MOZ_ASSERT(thingp);
  js::TraceNullableRoot(trc, thingp, name);
}

namespace js {
class SavedFrame;
class AbstractGeneratorObject;
}  // namespace js

// Instantiate a copy of the Tracing templates for each public GC pointer type.
#define INSTANTIATE_PUBLIC_TRACE_FUNCTIONS(type)                          \
  template JS_PUBLIC_API void JS::UnsafeTraceRoot<type>(JSTracer*, type*, \
                                                        const char*);     \
  template JS_PUBLIC_API void js::UnsafeTraceManuallyBarrieredEdge<type>( \
      JSTracer*, type*, const char*);                                     \
  template JS_PUBLIC_API void js::gc::TraceExternalEdge<type>(            \
      JSTracer*, type*, const char*);
FOR_EACH_PUBLIC_GC_POINTER_TYPE(INSTANTIATE_PUBLIC_TRACE_FUNCTIONS)
FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(INSTANTIATE_PUBLIC_TRACE_FUNCTIONS)
INSTANTIATE_PUBLIC_TRACE_FUNCTIONS(SavedFrame*);
INSTANTIATE_PUBLIC_TRACE_FUNCTIONS(AbstractGeneratorObject*);
#undef INSTANTIATE_PUBLIC_TRACE_FUNCTIONS

namespace js {
namespace gc {

#define INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(type)                      \
  template bool TraceEdgeInternal<type>(JSTracer*, type*, const char*); \
  template void TraceRangeInternal<type>(JSTracer*, size_t len, type*,  \
                                         const char*);

#define INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND(_1, type, _2, _3) \
  INSTANTIATE_INTERNAL_TRACE_FUNCTIONS(type*)

JS_FOR_EACH_TRACEKIND(INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND)
FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(INSTANTIATE_INTERNAL_TRACE_FUNCTIONS)

#undef INSTANTIATE_INTERNAL_TRACE_FUNCTIONS_FROM_TRACEKIND
#undef INSTANTIATE_INTERNAL_TRACE_FUNCTIONS

}  // namespace gc
}  // namespace js

template <typename T>
void js::TraceManuallyBarrieredCrossCompartmentEdge(JSTracer* trc,
                                                    JSObject* src, T* dst,
                                                    const char* name) {
  if (ShouldTraceCrossCompartment(trc, src, *dst)) {
    TraceEdgeInternal(trc, dst, name);
  }
}
template void js::TraceManuallyBarrieredCrossCompartmentEdge<JSObject*>(
    JSTracer*, JSObject*, JSObject**, const char*);
template void js::TraceManuallyBarrieredCrossCompartmentEdge<JSScript*>(
    JSTracer*, JSObject*, JSScript**, const char*);
template void js::TraceManuallyBarrieredCrossCompartmentEdge<LazyScript*>(
    JSTracer*, JSObject*, LazyScript**, const char*);

template <typename T>
void js::TraceCrossCompartmentEdge(JSTracer* trc, JSObject* src,
                                   WriteBarriered<T>* dst, const char* name) {
  if (ShouldTraceCrossCompartment(trc, src, dst->get())) {
    TraceEdgeInternal(trc, dst->unsafeUnbarrieredForTracing(), name);
  }
}

template void js::TraceCrossCompartmentEdge<Value>(JSTracer* trc, JSObject* src,
                                                   WriteBarriered<Value>* dst,
                                                   const char* name);
template void js::TraceCrossCompartmentEdge<JSScript*>(
    JSTracer* trc, JSObject* src, WriteBarriered<JSScript*>* dst,
    const char* name);

template <typename T>
void js::TraceProcessGlobalRoot(JSTracer* trc, T* thing, const char* name) {
  AssertRootMarkingPhase(trc);
  MOZ_ASSERT(ThingIsPermanentAtomOrWellKnownSymbol(thing));

  // We have to mark permanent atoms and well-known symbols through a special
  // method because the default DoMarking implementation automatically skips
  // them. Fortunately, atoms (permanent and non) cannot refer to other GC
  // things so they do not need to go through the mark stack and may simply
  // be marked directly.  Moreover, well-known symbols can refer only to
  // permanent atoms, so likewise require no subsquent marking.
  CheckTracedThing(trc, *ConvertToBase(&thing));
  if (trc->isMarkingTracer()) {
    thing->asTenured().markIfUnmarked(gc::MarkColor::Black);
  } else {
    DoCallback(trc->asCallbackTracer(), ConvertToBase(&thing), name);
  }
}
template void js::TraceProcessGlobalRoot<JSAtom>(JSTracer*, JSAtom*,
                                                 const char*);
template void js::TraceProcessGlobalRoot<JS::Symbol>(JSTracer*, JS::Symbol*,
                                                     const char*);

void js::TraceGenericPointerRoot(JSTracer* trc, Cell** thingp,
                                 const char* name) {
  MOZ_ASSERT(thingp);
  Cell* thing = *thingp;
  if (!thing) {
    return;
  }

  auto traced = MapGCThingTyped(thing, thing->getTraceKind(),
                                [trc, name](auto t) -> Cell* {
                                  TraceRoot(trc, &t, name);
                                  return t;
                                });
  if (traced != thing) {
    *thingp = traced;
  }
}

void js::TraceManuallyBarrieredGenericPointerEdge(JSTracer* trc, Cell** thingp,
                                                  const char* name) {
  MOZ_ASSERT(thingp);
  Cell* thing = *thingp;
  if (!*thingp) {
    return;
  }

  auto traced = MapGCThingTyped(thing, thing->getTraceKind(),
                                [trc, name](auto t) -> Cell* {
                                  TraceManuallyBarrieredEdge(trc, &t, name);
                                  return t;
                                });
  if (traced != thing) {
    *thingp = traced;
  }
}

void StackGCCellPtr::trace(JSTracer* trc) {
  Cell* thing = ptr_.asCell();
  TraceGenericPointerRoot(trc, &thing, "stack-gc-cell-ptr");
  if (thing != ptr_.asCell()) {
    ptr_ = JS::GCCellPtr(thing, ptr_.kind());
  }
}

// This method is responsible for dynamic dispatch to the real tracer
// implementation. Consider replacing this choke point with virtual dispatch:
// a sufficiently smart C++ compiler may be able to devirtualize some paths.
template <typename T>
bool js::gc::TraceEdgeInternal(JSTracer* trc, T* thingp, const char* name) {
#define IS_SAME_TYPE_OR(name, type, _, _1) mozilla::IsSame<type*, T>::value ||
  static_assert(JS_FOR_EACH_TRACEKIND(IS_SAME_TYPE_OR)
                        mozilla::IsSame<T, JS::Value>::value ||
                    mozilla::IsSame<T, jsid>::value ||
                    mozilla::IsSame<T, TaggedProto>::value,
                "Only the base cell layout types are allowed into "
                "marking/tracing internals");
#undef IS_SAME_TYPE_OR
  if (trc->isMarkingTracer()) {
    DoMarking(GCMarker::fromTracer(trc), *thingp);
    return true;
  }
  if (trc->isTenuringTracer()) {
    static_cast<TenuringTracer*>(trc)->traverse(thingp);
    return true;
  }
  MOZ_ASSERT(trc->isCallbackTracer());
  return DoCallback(trc->asCallbackTracer(), thingp, name);
}

template <typename T>
void js::gc::TraceRangeInternal(JSTracer* trc, size_t len, T* vec,
                                const char* name) {
  JS::AutoTracingIndex index(trc);
  for (auto i : IntegerRange(len)) {
    if (InternalBarrierMethods<T>::isMarkable(vec[i])) {
      TraceEdgeInternal(trc, &vec[i], name);
    }
    ++index;
  }
}

/*** GC Marking Interface ***************************************************/

namespace js {

typedef bool HasNoImplicitEdgesType;

template <typename T>
struct ImplicitEdgeHolderType {
  typedef HasNoImplicitEdgesType Type;
};

// For now, we only handle JSObject* and JSScript* keys, but the linear time
// algorithm can be easily extended by adding in more types here, then making
// GCMarker::traverse<T> call markPotentialEphemeronKey.
template <>
struct ImplicitEdgeHolderType<JSObject*> {
  typedef JSObject* Type;
};

template <>
struct ImplicitEdgeHolderType<JSScript*> {
  typedef JSScript* Type;
};

template <>
struct ImplicitEdgeHolderType<LazyScript*> {
  typedef LazyScript* Type;
};

void GCMarker::markEphemeronValues(gc::Cell* markedCell,
                                   WeakEntryVector& values) {
  DebugOnly<size_t> initialLen = values.length();

  for (const auto& markable : values) {
    if (color == gc::MarkColor::Black &&
        markable.weakmap->markColor == gc::MarkColor::Gray) {
      continue;
    }

    markable.weakmap->markEntry(this, markedCell, markable.key);
  }

  // The vector should not be appended to during iteration because the key is
  // already marked, and even in cases where we have a multipart key, we
  // should only be inserting entries for the unmarked portions.
  MOZ_ASSERT(values.length() == initialLen);
}

template <typename T>
void GCMarker::markImplicitEdgesHelper(T markedThing) {
  if (!isWeakMarkingTracer()) {
    return;
  }

  Zone* zone = gc::TenuredCell::fromPointer(markedThing)->zone();
  MOZ_ASSERT(zone->isGCMarking());
  MOZ_ASSERT(!zone->isGCSweeping());

  auto p = zone->gcWeakKeys().get(markedThing);
  if (!p) {
    return;
  }
  WeakEntryVector& markables = p->value;

  markEphemeronValues(markedThing, markables);
  markables.clear();  // If key address is reused, it should do nothing
}

template <>
void GCMarker::markImplicitEdgesHelper(HasNoImplicitEdgesType) {}

template <typename T>
void GCMarker::markImplicitEdges(T* thing) {
  markImplicitEdgesHelper<typename ImplicitEdgeHolderType<T*>::Type>(thing);
}

template void GCMarker::markImplicitEdges(JSObject*);
template void GCMarker::markImplicitEdges(JSScript*);
template void GCMarker::markImplicitEdges(LazyScript*);

}  // namespace js

template <typename T>
static inline bool ShouldMark(GCMarker* gcmarker, T thing) {
  // Don't trace things that are owned by another runtime.
  if (IsOwnedByOtherRuntime(gcmarker->runtime(), thing)) {
    return false;
  }

  // Don't mark things outside a zone if we are in a per-zone GC.
  return thing->zone()->shouldMarkInZone();
}

template <>
bool ShouldMark<JSObject*>(GCMarker* gcmarker, JSObject* obj) {
  // Don't trace things that are owned by another runtime.
  if (IsOwnedByOtherRuntime(gcmarker->runtime(), obj)) {
    return false;
  }

  // We may mark a Nursery thing outside the context of the
  // MinorCollectionTracer because of a pre-barrier. The pre-barrier is not
  // needed in this case because we perform a minor collection before each
  // incremental slice.
  if (IsInsideNursery(obj)) {
    return false;
  }

  // Don't mark things outside a zone if we are in a per-zone GC. It is
  // faster to check our own arena, which we can do since we know that
  // the object is tenured.
  return obj->asTenured().zone()->shouldMarkInZone();
}

// JSStrings can also be in the nursery. See ShouldMark<JSObject*> for comments.
template <>
bool ShouldMark<JSString*>(GCMarker* gcmarker, JSString* str) {
  if (IsOwnedByOtherRuntime(gcmarker->runtime(), str)) {
    return false;
  }
  if (IsInsideNursery(str)) {
    return false;
  }
  return str->asTenured().zone()->shouldMarkInZone();
}

template <typename T>
void DoMarking(GCMarker* gcmarker, T* thing) {
  // Do per-type marking precondition checks.
  if (!ShouldMark(gcmarker, thing)) {
    return;
  }

  CheckTracedThing(gcmarker, thing);
  gcmarker->traverse(thing);

  // Mark the compartment as live.
  SetMaybeAliveFlag(thing);
}

template <typename T>
void DoMarking(GCMarker* gcmarker, const T& thing) {
  ApplyGCThingTyped(thing, [gcmarker](auto t) { DoMarking(gcmarker, t); });
}

JS_PUBLIC_API void js::gc::PerformIncrementalReadBarrier(JS::GCCellPtr thing) {
  // Optimized marking for read barriers. This is called from
  // ExposeGCThingToActiveJS which has already checked the prerequisites for
  // performing a read barrier. This means we can skip a bunch of checks and
  // call info the tracer directly.

  MOZ_ASSERT(thing);
  MOZ_ASSERT(!JS::RuntimeHeapIsMajorCollecting());

  TenuredCell* cell = &thing.asCell()->asTenured();
  Zone* zone = cell->zone();
  MOZ_ASSERT(zone->needsIncrementalBarrier());

  // Skip disptaching on known tracer type.
  GCMarker* gcmarker = GCMarker::fromTracer(zone->barrierTracer());

  // Mark the argument, as DoMarking above.
  ApplyGCThingTyped(thing, [gcmarker](auto thing) {
    MOZ_ASSERT(ShouldMark(gcmarker, thing));
    CheckTracedThing(gcmarker, thing);
    gcmarker->traverse(thing);
  });
}

// The simplest traversal calls out to the fully generic traceChildren function
// to visit the child edges. In the absence of other traversal mechanisms, this
// function will rapidly grow the stack past its bounds and crash the process.
// Thus, this generic tracing should only be used in cases where subsequent
// tracing will not recurse.
template <typename T>
void js::GCMarker::markAndTraceChildren(T* thing) {
  if (ThingIsPermanentAtomOrWellKnownSymbol(thing)) {
    return;
  }
  if (mark(thing)) {
    thing->traceChildren(this);
  }
}
namespace js {
template <>
void GCMarker::traverse(BaseShape* thing) {
  markAndTraceChildren(thing);
}
template <>
void GCMarker::traverse(JS::Symbol* thing) {
  markAndTraceChildren(thing);
}
template <>
void GCMarker::traverse(JS::BigInt* thing) {
  markAndTraceChildren(thing);
}
template <>
void GCMarker::traverse(RegExpShared* thing) {
  markAndTraceChildren(thing);
}
}  // namespace js

// Strings, LazyScripts, Shapes, and Scopes are extremely common, but have
// simple patterns of recursion. We traverse trees of these edges immediately,
// with aggressive, manual inlining, implemented by eagerlyTraceChildren.
template <typename T>
void js::GCMarker::markAndScan(T* thing) {
  if (ThingIsPermanentAtomOrWellKnownSymbol(thing)) {
    return;
  }
  if (mark(thing)) {
    eagerlyMarkChildren(thing);
  }
}
namespace js {
template <>
void GCMarker::traverse(JSString* thing) {
  markAndScan(thing);
}
template <>
void GCMarker::traverse(LazyScript* thing) {
  markAndScan(thing);
}
template <>
void GCMarker::traverse(Shape* thing) {
  markAndScan(thing);
}
template <>
void GCMarker::traverse(js::Scope* thing) {
  markAndScan(thing);
}
}  // namespace js

// Object and ObjectGroup are extremely common and can contain arbitrarily
// nested graphs, so are not trivially inlined. In this case we use a mark
// stack to control recursion. JitCode shares none of these properties, but is
// included for historical reasons. JSScript normally cannot recurse, but may
// be used as a weakmap key and thereby recurse into weakmapped values.
template <typename T>
void js::GCMarker::markAndPush(T* thing) {
  if (!mark(thing)) {
    return;
  }
  pushTaggedPtr(thing);
}
namespace js {
template <>
void GCMarker::traverse(JSObject* thing) {
  markAndPush(thing);
}
template <>
void GCMarker::traverse(ObjectGroup* thing) {
  markAndPush(thing);
}
template <>
void GCMarker::traverse(jit::JitCode* thing) {
  markAndPush(thing);
}
template <>
void GCMarker::traverse(JSScript* thing) {
  markAndPush(thing);
}
}  // namespace js

namespace js {
template <>
void GCMarker::traverse(AccessorShape* thing) {
  MOZ_CRASH("AccessorShape must be marked as a Shape");
}
}  // namespace js

template <typename S, typename T>
static void CheckTraversedEdge(S source, T* target) {
  // Atoms and Symbols do not have or mark their internal pointers,
  // respectively.
  MOZ_ASSERT(!ThingIsPermanentAtomOrWellKnownSymbol(source));

  // The Zones must match, unless the target is an atom.
  MOZ_ASSERT_IF(
      !ThingIsPermanentAtomOrWellKnownSymbol(target),
      target->zone()->isAtomsZone() || target->zone() == source->zone());

  // If we are marking an atom, that atom must be marked in the source zone's
  // atom bitmap.
  MOZ_ASSERT_IF(!ThingIsPermanentAtomOrWellKnownSymbol(target) &&
                    target->zone()->isAtomsZone() &&
                    !source->zone()->isAtomsZone(),
                target->runtimeFromAnyThread()->gc.atomMarking.atomIsMarked(
                    source->zone(), reinterpret_cast<TenuredCell*>(target)));

  // Atoms and Symbols do not have access to a compartment pointer, or we'd need
  // to adjust the subsequent check to catch that case.
  MOZ_ASSERT_IF(ThingIsPermanentAtomOrWellKnownSymbol(target),
                !target->maybeCompartment());
  MOZ_ASSERT_IF(target->zoneFromAnyThread()->isAtomsZone(),
                !target->maybeCompartment());
  // If we have access to a compartment pointer for both things, they must
  // match.
  MOZ_ASSERT_IF(source->maybeCompartment() && target->maybeCompartment(),
                source->maybeCompartment() == target->maybeCompartment());
}

template <typename S, typename T>
void js::GCMarker::traverseEdge(S source, T* target) {
  CheckTraversedEdge(source, target);
  traverse(target);
}

template <typename S, typename T>
void js::GCMarker::traverseEdge(S source, const T& thing) {
  ApplyGCThingTyped(thing,
                    [this, source](auto t) { this->traverseEdge(source, t); });
}

namespace {

template <typename T>
struct TraceKindCanBeGray {};
#define EXPAND_TRACEKIND_DEF(_, type, canBeGray, _1) \
  template <>                                        \
  struct TraceKindCanBeGray<type> {                  \
    static const bool value = canBeGray;             \
  };
JS_FOR_EACH_TRACEKIND(EXPAND_TRACEKIND_DEF)
#undef EXPAND_TRACEKIND_DEF

}  // namespace

struct TraceKindCanBeGrayFunctor {
  template <typename T>
  bool operator()() {
    return TraceKindCanBeGray<T>::value;
  }
};

static bool TraceKindCanBeMarkedGray(JS::TraceKind kind) {
  return DispatchTraceKindTyped(TraceKindCanBeGrayFunctor(), kind);
}

template <typename T>
bool js::GCMarker::mark(T* thing) {
  if (IsInsideNursery(thing)) {
    return false;
  }
  AssertShouldMarkInZone(thing);
  TenuredCell* cell = TenuredCell::fromPointer(thing);

  MarkColor color =
      TraceKindCanBeGray<T>::value ? markColor() : MarkColor::Black;
  markCount++;
  return cell->markIfUnmarked(color);
}

/*** Inline, Eager GC Marking ***********************************************/

// Each of the eager, inline marking paths is directly preceeded by the
// out-of-line, generic tracing code for comparison. Both paths must end up
// traversing equivalent subgraphs.

void BaseScript::traceChildren(JSTracer* trc) {
  TraceEdge(trc, &functionOrGlobal_, "function");
  TraceNullableEdge(trc, &sourceObject_, "sourceObject");
}

void LazyScript::traceChildren(JSTracer* trc) {
  // Trace base class fields.
  BaseScript::traceChildren(trc);

  if (trc->traceWeakEdges()) {
    TraceNullableEdge(trc, &script_, "script");
  }

  if (enclosingLazyScriptOrScope_) {
    TraceGenericPointerRoot(
        trc,
        reinterpret_cast<Cell**>(
            enclosingLazyScriptOrScope_.unsafeUnbarrieredForTracing()),
        "enclosingScope or enclosingLazyScript");
  }

  // We rely on the fact that atoms are always tenured.
  for (GCPtrAtom& closedOverBinding : closedOverBindings()) {
    if (closedOverBinding) {
      TraceEdge(trc, &closedOverBinding, "closedOverBinding");
    }
  }

  for (GCPtrFunction& innerFunction : innerFunctions()) {
    if (innerFunction) {
      TraceEdge(trc, &innerFunction, "lazyScriptInnerFunction");
    }
  }

  if (trc->isMarkingTracer()) {
    GCMarker::fromTracer(trc)->markImplicitEdges(this);
  }
}
inline void js::GCMarker::eagerlyMarkChildren(LazyScript* thing) {
  traverseEdge(thing, static_cast<JSObject*>(thing->functionOrGlobal_));

  if (thing->sourceObject_) {
    traverseEdge(thing, static_cast<JSObject*>(thing->sourceObject_));
  }

  // script_ is weak so is not traced here.

  if (thing->enclosingLazyScriptOrScope_) {
    TraceManuallyBarrieredGenericPointerEdge(
        this,
        reinterpret_cast<Cell**>(
            thing->enclosingLazyScriptOrScope_.unsafeUnbarrieredForTracing()),
        "enclosingScope or enclosingLazyScript");
  }

  // We rely on the fact that atoms are always tenured.
  for (GCPtrAtom& closedOverBinding : thing->closedOverBindings()) {
    if (closedOverBinding) {
      traverseEdge(thing, static_cast<JSString*>(closedOverBinding));
    }
  }

  for (GCPtrFunction& innerFunction : thing->innerFunctions()) {
    if (innerFunction) {
      traverseEdge(thing, static_cast<JSObject*>(innerFunction));
    }
  }

  markImplicitEdges(thing);
}

void Shape::traceChildren(JSTracer* trc) {
  TraceEdge(trc, &base_, "base");
  TraceEdge(trc, &propidRef(), "propid");
  if (parent) {
    TraceEdge(trc, &parent, "parent");
  }

  if (hasGetterObject()) {
    TraceManuallyBarrieredEdge(trc, &asAccessorShape().getterObj, "getter");
  }
  if (hasSetterObject()) {
    TraceManuallyBarrieredEdge(trc, &asAccessorShape().setterObj, "setter");
  }
}
inline void js::GCMarker::eagerlyMarkChildren(Shape* shape) {
  MOZ_ASSERT(shape->isMarked(markColor()));

  do {
    // Special case: if a base shape has a shape table then all its pointers
    // must point to this shape or an anscestor.  Since these pointers will
    // be traced by this loop they do not need to be traced here as well.
    BaseShape* base = shape->base();
    CheckTraversedEdge(shape, base);
    if (mark(base)) {
      MOZ_ASSERT(base->canSkipMarkingShapeCache(shape));
      base->traceChildrenSkipShapeCache(this);
    }

    traverseEdge(shape, shape->propidRef().get());

    // When triggered between slices on behalf of a barrier, these
    // objects may reside in the nursery, so require an extra check.
    // FIXME: Bug 1157967 - remove the isTenured checks.
    if (shape->hasGetterObject() && shape->getterObject()->isTenured()) {
      traverseEdge(shape, shape->getterObject());
    }
    if (shape->hasSetterObject() && shape->setterObject()->isTenured()) {
      traverseEdge(shape, shape->setterObject());
    }

    shape = shape->previous();
  } while (shape && mark(shape));
}

void JSString::traceChildren(JSTracer* trc) {
  if (hasBase()) {
    traceBase(trc);
  } else if (isRope()) {
    asRope().traceChildren(trc);
  }
}
inline void GCMarker::eagerlyMarkChildren(JSString* str) {
  if (str->isLinear()) {
    eagerlyMarkChildren(&str->asLinear());
  } else {
    eagerlyMarkChildren(&str->asRope());
  }
}

void JSString::traceBase(JSTracer* trc) {
  MOZ_ASSERT(hasBase());
  TraceManuallyBarrieredEdge(trc, &d.s.u3.base, "base");
}
inline void js::GCMarker::eagerlyMarkChildren(JSLinearString* linearStr) {
  AssertShouldMarkInZone(linearStr);
  MOZ_ASSERT(linearStr->isMarkedAny());
  MOZ_ASSERT(linearStr->JSString::isLinear());

  // Use iterative marking to avoid blowing out the stack.
  while (linearStr->hasBase()) {
    linearStr = linearStr->base();
    MOZ_ASSERT(linearStr->JSString::isLinear());
    if (linearStr->isPermanentAtom()) {
      break;
    }
    AssertShouldMarkInZone(linearStr);
    if (!mark(static_cast<JSString*>(linearStr))) {
      break;
    }
  }
}

void JSRope::traceChildren(JSTracer* trc) {
  js::TraceManuallyBarrieredEdge(trc, &d.s.u2.left, "left child");
  js::TraceManuallyBarrieredEdge(trc, &d.s.u3.right, "right child");
}
inline void js::GCMarker::eagerlyMarkChildren(JSRope* rope) {
  // This function tries to scan the whole rope tree using the marking stack
  // as temporary storage. If that becomes full, the unscanned ropes are
  // added to the delayed marking list. When the function returns, the
  // marking stack is at the same depth as it was on entry. This way we avoid
  // using tags when pushing ropes to the stack as ropes never leak to other
  // users of the stack. This also assumes that a rope can only point to
  // other ropes or linear strings, it cannot refer to GC things of other
  // types.
  size_t savedPos = stack.position();
  JS_DIAGNOSTICS_ASSERT(rope->getTraceKind() == JS::TraceKind::String);
#ifdef JS_DEBUG
  static const size_t DEEP_ROPE_THRESHOLD = 100000;
  static const size_t ROPE_CYCLE_HISTORY = 100;
  DebugOnly<size_t> ropeDepth = 0;
  JSRope* history[ROPE_CYCLE_HISTORY];
#endif
  while (true) {
#ifdef JS_DEBUG
    if (++ropeDepth >= DEEP_ROPE_THRESHOLD) {
      // Bug 1011786 comment 294 - detect cyclic ropes. There are some
      // legitimate deep ropes, at least in tests. So if we hit a deep
      // rope, start recording the nodes we visit and check whether we
      // repeat. But do it on a finite window size W so that we're not
      // scanning the full history for every node. And only check every
      // Wth push, to add only constant overhead per node. This will only
      // catch cycles of size up to W (but it seems most likely that any
      // cycles will be size 1 or maybe 2.)
      if ((ropeDepth > DEEP_ROPE_THRESHOLD + ROPE_CYCLE_HISTORY) &&
          (ropeDepth % ROPE_CYCLE_HISTORY) == 0) {
        for (size_t i = 0; i < ROPE_CYCLE_HISTORY; i++) {
          MOZ_ASSERT(history[i] != rope, "cycle detected in rope");
        }
      }
      history[ropeDepth % ROPE_CYCLE_HISTORY] = rope;
    }
#endif

    JS_DIAGNOSTICS_ASSERT(rope->getTraceKind() == JS::TraceKind::String);
    JS_DIAGNOSTICS_ASSERT(rope->JSString::isRope());
    AssertShouldMarkInZone(rope);
    MOZ_ASSERT(rope->isMarkedAny());
    JSRope* next = nullptr;

    JSString* right = rope->rightChild();
    if (!right->isPermanentAtom() && mark(right)) {
      if (right->isLinear()) {
        eagerlyMarkChildren(&right->asLinear());
      } else {
        next = &right->asRope();
      }
    }

    JSString* left = rope->leftChild();
    if (!left->isPermanentAtom() && mark(left)) {
      if (left->isLinear()) {
        eagerlyMarkChildren(&left->asLinear());
      } else {
        // When both children are ropes, set aside the right one to
        // scan it later.
        if (next && !stack.pushTempRope(next)) {
          delayMarkingChildren(next);
        }
        next = &left->asRope();
      }
    }
    if (next) {
      rope = next;
    } else if (savedPos != stack.position()) {
      MOZ_ASSERT(savedPos < stack.position());
      rope = stack.popPtr().asTempRope();
    } else {
      break;
    }
  }
  MOZ_ASSERT(savedPos == stack.position());
}

static inline void TraceBindingNames(JSTracer* trc, BindingName* names,
                                     uint32_t length) {
  for (uint32_t i = 0; i < length; i++) {
    JSAtom* name = names[i].name();
    MOZ_ASSERT(name);
    TraceManuallyBarrieredEdge(trc, &name, "scope name");
  }
};
static inline void TraceNullableBindingNames(JSTracer* trc, BindingName* names,
                                             uint32_t length) {
  for (uint32_t i = 0; i < length; i++) {
    if (JSAtom* name = names[i].name()) {
      TraceManuallyBarrieredEdge(trc, &name, "scope name");
    }
  }
};
void BindingName::trace(JSTracer* trc) {
  if (JSAtom* atom = name()) {
    TraceManuallyBarrieredEdge(trc, &atom, "binding name");
  }
}
void BindingIter::trace(JSTracer* trc) {
  TraceNullableBindingNames(trc, names_, length_);
}
void LexicalScope::Data::trace(JSTracer* trc) {
  TraceBindingNames(trc, trailingNames.start(), length);
}
void FunctionScope::Data::trace(JSTracer* trc) {
  TraceNullableEdge(trc, &canonicalFunction, "scope canonical function");
  TraceNullableBindingNames(trc, trailingNames.start(), length);
}
void VarScope::Data::trace(JSTracer* trc) {
  TraceBindingNames(trc, trailingNames.start(), length);
}
void GlobalScope::Data::trace(JSTracer* trc) {
  TraceBindingNames(trc, trailingNames.start(), length);
}
void EvalScope::Data::trace(JSTracer* trc) {
  TraceBindingNames(trc, trailingNames.start(), length);
}
void ModuleScope::Data::trace(JSTracer* trc) {
  TraceNullableEdge(trc, &module, "scope module");
  TraceBindingNames(trc, trailingNames.start(), length);
}
void WasmInstanceScope::Data::trace(JSTracer* trc) {
  TraceNullableEdge(trc, &instance, "wasm instance");
  TraceBindingNames(trc, trailingNames.start(), length);
}
void WasmFunctionScope::Data::trace(JSTracer* trc) {
  TraceBindingNames(trc, trailingNames.start(), length);
}
void Scope::traceChildren(JSTracer* trc) {
  TraceNullableEdge(trc, &enclosing_, "scope enclosing");
  TraceNullableEdge(trc, &environmentShape_, "scope env shape");
  applyScopeDataTyped([trc](auto data) { data->trace(trc); });
}
inline void js::GCMarker::eagerlyMarkChildren(Scope* scope) {
  do {
    if (scope->environmentShape_) {
      traverseEdge(scope, scope->environmentShape_.get());
    }
    TrailingNamesArray* names = nullptr;
    uint32_t length = 0;
    switch (scope->kind()) {
      case ScopeKind::Function: {
        FunctionScope::Data& data = scope->as<FunctionScope>().data();
        traverseObjectEdge(scope, data.canonicalFunction);
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::FunctionBodyVar:
      case ScopeKind::ParameterExpressionVar: {
        VarScope::Data& data = scope->as<VarScope>().data();
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::Lexical:
      case ScopeKind::SimpleCatch:
      case ScopeKind::Catch:
      case ScopeKind::NamedLambda:
      case ScopeKind::StrictNamedLambda:
      case ScopeKind::FunctionLexical: {
        LexicalScope::Data& data = scope->as<LexicalScope>().data();
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::Global:
      case ScopeKind::NonSyntactic: {
        GlobalScope::Data& data = scope->as<GlobalScope>().data();
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::Eval:
      case ScopeKind::StrictEval: {
        EvalScope::Data& data = scope->as<EvalScope>().data();
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::Module: {
        ModuleScope::Data& data = scope->as<ModuleScope>().data();
        traverseObjectEdge(scope, data.module);
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::With:
        break;

      case ScopeKind::WasmInstance: {
        WasmInstanceScope::Data& data = scope->as<WasmInstanceScope>().data();
        traverseObjectEdge(scope, data.instance);
        names = &data.trailingNames;
        length = data.length;
        break;
      }

      case ScopeKind::WasmFunction: {
        WasmFunctionScope::Data& data = scope->as<WasmFunctionScope>().data();
        names = &data.trailingNames;
        length = data.length;
        break;
      }
    }
    if (scope->kind_ == ScopeKind::Function) {
      for (uint32_t i = 0; i < length; i++) {
        if (JSAtom* name = names->get(i).name()) {
          traverseStringEdge(scope, name);
        }
      }
    } else {
      for (uint32_t i = 0; i < length; i++) {
        traverseStringEdge(scope, names->get(i).name());
      }
    }
    scope = scope->enclosing_;
  } while (scope && mark(scope));
}

void js::ObjectGroup::traceChildren(JSTracer* trc) {
  AutoSweepObjectGroup sweep(this);

  if (!trc->canSkipJsids()) {
    unsigned count = getPropertyCount(sweep);
    for (unsigned i = 0; i < count; i++) {
      if (ObjectGroup::Property* prop = getProperty(sweep, i)) {
        TraceEdge(trc, &prop->id, "group_property");
      }
    }
  }

  if (proto().isObject()) {
    TraceEdge(trc, &proto(), "group_proto");
  }

  // Note: the realm's global can be nullptr if we GC while creating the global.
  if (JSObject* global = realm()->unsafeUnbarrieredMaybeGlobal()) {
    TraceManuallyBarrieredEdge(trc, &global, "group_global");
  }

  if (newScript(sweep)) {
    newScript(sweep)->trace(trc);
  }

  if (maybePreliminaryObjects(sweep)) {
    maybePreliminaryObjects(sweep)->trace(trc);
  }

  if (JSObject* descr = maybeTypeDescr()) {
    TraceManuallyBarrieredEdge(trc, &descr, "group_type_descr");
    setTypeDescr(&descr->as<TypeDescr>());
  }

  if (JSObject* fun = maybeInterpretedFunction()) {
    TraceManuallyBarrieredEdge(trc, &fun, "group_function");
    setInterpretedFunction(&fun->as<JSFunction>());
  }
}
void js::GCMarker::lazilyMarkChildren(ObjectGroup* group) {
  AutoSweepObjectGroup sweep(group);
  unsigned count = group->getPropertyCount(sweep);
  for (unsigned i = 0; i < count; i++) {
    if (ObjectGroup::Property* prop = group->getProperty(sweep, i)) {
      traverseEdge(group, prop->id.get());
    }
  }

  if (group->proto().isObject()) {
    traverseEdge(group, group->proto().toObject());
  }

  // Note: the realm's global can be nullptr if we GC while creating the global.
  if (GlobalObject* global = group->realm()->unsafeUnbarrieredMaybeGlobal()) {
    traverseEdge(group, static_cast<JSObject*>(global));
  }

  if (group->newScript(sweep)) {
    group->newScript(sweep)->trace(this);
  }

  if (group->maybePreliminaryObjects(sweep)) {
    group->maybePreliminaryObjects(sweep)->trace(this);
  }

  if (TypeDescr* descr = group->maybeTypeDescr()) {
    traverseEdge(group, static_cast<JSObject*>(descr));
  }

  if (JSFunction* fun = group->maybeInterpretedFunction()) {
    traverseEdge(group, static_cast<JSObject*>(fun));
  }
}

void JS::BigInt::traceChildren(JSTracer* trc) { return; }

template <typename Functor>
static void VisitTraceList(const Functor& f, const uint32_t* traceList,
                           uint8_t* memory);

// Call the trace hook set on the object, if present. If further tracing of
// NativeObject fields is required, this will return the native object.
enum class CheckGeneration { DoChecks, NoChecks };
template <typename Functor>
static inline NativeObject* CallTraceHook(Functor&& f, JSTracer* trc,
                                          JSObject* obj,
                                          CheckGeneration check) {
  const JSClass* clasp = obj->getClass();
  MOZ_ASSERT(clasp);
  MOZ_ASSERT(obj->isNative() == clasp->isNative());

  if (!clasp->hasTrace()) {
    return &obj->as<NativeObject>();
  }

  if (clasp->isTrace(InlineTypedObject::obj_trace)) {
    Shape** pshape = obj->as<InlineTypedObject>().addressOfShapeFromGC();
    f(pshape);

    InlineTypedObject& tobj = obj->as<InlineTypedObject>();
    if (tobj.typeDescr().hasTraceList()) {
      VisitTraceList(f, tobj.typeDescr().traceList(),
                     tobj.inlineTypedMemForGC());
    }

    return nullptr;
  }

  clasp->doTrace(trc, obj);

  if (!clasp->isNative()) {
    return nullptr;
  }
  return &obj->as<NativeObject>();
}

template <typename Functor>
static void VisitTraceList(const Functor& f, const uint32_t* traceList,
                           uint8_t* memory) {
  size_t stringCount = *traceList++;
  size_t objectCount = *traceList++;
  size_t valueCount = *traceList++;
  for (size_t i = 0; i < stringCount; i++) {
    f(reinterpret_cast<JSString**>(memory + *traceList));
    traceList++;
  }
  for (size_t i = 0; i < objectCount; i++) {
    JSObject** objp = reinterpret_cast<JSObject**>(memory + *traceList);
    if (*objp) {
      f(objp);
    }
    traceList++;
  }
  for (size_t i = 0; i < valueCount; i++) {
    f(reinterpret_cast<Value*>(memory + *traceList));
    traceList++;
  }
}

/*** Mark-stack Marking *****************************************************/

GCMarker::MarkQueueProgress GCMarker::processMarkQueue() {
#ifdef DEBUG
  if (markQueue.empty()) {
    return QueueComplete;
  }

  GCRuntime& gcrt = runtime()->gc;
  if (queueMarkColor == mozilla::Some(MarkColor::Gray) &&
      gcrt.state() != State::Sweep) {
    return QueueSuspended;
  }

  // If the queue wants to be gray marking, but we've pushed a black object
  // since set-color-gray was processed, then we can't switch to gray and must
  // again wait until gray marking is possible.
  //
  // Remove this code if the restriction against marking gray during black is
  // relaxed.
  if (queueMarkColor == mozilla::Some(MarkColor::Gray) && hasBlackEntries()) {
    return QueueSuspended;
  }

  // If the queue wants to be marking a particular color, switch to that color.
  // In any case, restore the mark color to whatever it was when we entered
  // this function.
  AutoSetMarkColor autoRevertColor(*this, queueMarkColor.valueOr(markColor()));

  // Process the mark queue by taking each object in turn, pushing it onto the
  // mark stack, and processing just the top element with processMarkStackTop
  // without recursing into reachable objects.
  while (queuePos < markQueue.length()) {
    Value val = markQueue[queuePos++].get().unbarrieredGet();
    if (val.isObject()) {
      JSObject* obj = &val.toObject();
      JS::Zone* zone = obj->zone();
      if (!zone->isGCMarking() || obj->isMarkedAtLeast(markColor())) {
        continue;
      }

      // If we have started sweeping, obey sweep group ordering. But note that
      // we will first be called during the initial sweep slice, when the sweep
      // group indexes have not yet been computed. In that case, we can mark
      // freely.
      if (gcrt.state() == State::Sweep && gcrt.initialState != State::Sweep) {
        if (zone->gcSweepGroupIndex < gcrt.getCurrentSweepGroupIndex()) {
          // Too late. This must have been added after we started collecting,
          // and we've already processed its sweep group. Skip it.
          continue;
        }
        if (zone->gcSweepGroupIndex > gcrt.getCurrentSweepGroupIndex()) {
          // Not ready yet. Wait until we reach the object's sweep group.
          queuePos--;
          return QueueSuspended;
        }
      }

      if (markColor() == MarkColor::Gray && zone->isGCMarkingBlackOnly()) {
        // Have not yet reached the point where we can mark this object, so
        // continue with the GC.
        queuePos--;
        return QueueSuspended;
      }

      // Mark the object and push it onto the stack.
      traverse(obj);

      // Process just the one object that is now on top of the mark stack,
      // possibly pushing more stuff onto the stack.
      if (isMarkStackEmpty()) {
        MOZ_ASSERT(obj->asTenured().arena()->onDelayedMarkingList());
        // If we overflow the stack here and delay marking, then we won't be
        // testing what we think we're testing.
        AutoEnterOOMUnsafeRegion oomUnsafe;
        oomUnsafe.crash("Overflowed stack while marking test queue");
      }

      SliceBudget unlimited = SliceBudget::unlimited();
      processMarkStackTop(unlimited);
    } else if (val.isString()) {
      JSLinearString* str = &val.toString()->asLinear();
      if (js::StringEqualsLiteral(str, "yield") && gcrt.isIncrementalGc()) {
        return QueueYielded;
      } else if (js::StringEqualsLiteral(str, "enter-weak-marking-mode") ||
                 js::StringEqualsLiteral(str, "abort-weak-marking-mode")) {
        if (!isWeakMarkingTracer() && !linearWeakMarkingDisabled_) {
          // We can't enter weak marking mode at just any time, so instead
          // we'll stop processing the queue and continue on with the GC. Once
          // we enter weak marking mode, we can continue to the rest of the
          // queue. Note that we will also suspend for aborting, and then abort
          // the earliest following weak marking mode.
          queuePos--;
          return QueueSuspended;
        }
        if (js::StringEqualsLiteral(str, "abort-weak-marking-mode")) {
          abortLinearWeakMarking();
        }
      } else if (js::StringEqualsLiteral(str, "drain")) {
        auto unlimited = SliceBudget::unlimited();
        MOZ_RELEASE_ASSERT(markUntilBudgetExhausted(unlimited));
      } else if (js::StringEqualsLiteral(str, "set-color-gray")) {
        queueMarkColor = mozilla::Some(MarkColor::Gray);
        if (gcrt.state() != State::Sweep) {
          // Cannot mark gray yet, so continue with the GC.
          queuePos--;
          return QueueSuspended;
        }
        setMarkColor(MarkColor::Gray);
      } else if (js::StringEqualsLiteral(str, "set-color-black")) {
        queueMarkColor = mozilla::Some(MarkColor::Black);
        setMarkColor(MarkColor::Black);
      } else if (js::StringEqualsLiteral(str, "unset-color")) {
        queueMarkColor.reset();
      }
    }
  }
#endif

  return QueueComplete;
}

bool GCMarker::markUntilBudgetExhausted(SliceBudget& budget) {
#ifdef DEBUG
  MOZ_ASSERT(!strictCompartmentChecking);
  strictCompartmentChecking = true;
  auto acc = mozilla::MakeScopeExit([&] { strictCompartmentChecking = false; });
#endif

  if (budget.isOverBudget()) {
    return false;
  }

  // This method leaves the mark color as it found it.
  AutoSetMarkColor autoSetBlack(*this, MarkColor::Black);

  // Change representation of value arrays on the stack while the mutator
  // runs.
  auto svr = mozilla::MakeScopeExit([&] { saveValueRanges(); });

  for (;;) {
    while (hasBlackEntries()) {
      MOZ_ASSERT(markColor() == MarkColor::Black);
      processMarkStackTop(budget);
      if (budget.isOverBudget()) {
        return false;
      }
    }

    if (hasGrayEntries()) {
      AutoSetMarkColor autoSetGray(*this, MarkColor::Gray);
      do {
        MOZ_ASSERT(!hasBlackEntries());
        processMarkStackTop(budget);
        if (budget.isOverBudget()) {
          return false;
        }
      } while (hasGrayEntries());
    }

    if (!hasDelayedChildren()) {
      break;
    }

    /*
     * Mark children of things that caused too deep recursion during the
     * above tracing. Don't do this until we're done with everything
     * else.
     */
    if (!markAllDelayedChildren(budget)) {
      return false;
    }
  }

  return true;
}

inline static bool ObjectDenseElementsMayBeMarkable(NativeObject* nobj) {
  /*
   * For arrays that are large enough it's worth checking the type information
   * to see if the object's elements contain any GC pointers.  If not, we
   * don't need to trace them.
   */
  const unsigned MinElementsLength = 32;
  if (nobj->getDenseInitializedLength() < MinElementsLength ||
      nobj->isSingleton()) {
    return true;
  }

  ObjectGroup* group = nobj->group();
  if (group->needsSweep() || group->unknownPropertiesDontCheckGeneration()) {
    return true;
  }

  // This typeset doesn't escape this function so avoid sweeping here.
  HeapTypeSet* typeSet = group->maybeGetPropertyDontCheckGeneration(JSID_VOID);
  if (!typeSet) {
    return true;
  }

  static const uint32_t flagMask = TYPE_FLAG_STRING | TYPE_FLAG_SYMBOL |
                                   TYPE_FLAG_LAZYARGS | TYPE_FLAG_ANYOBJECT |
                                   TYPE_FLAG_BIGINT;
  bool mayBeMarkable =
      typeSet->hasAnyFlag(flagMask) || typeSet->getObjectCount() != 0;

#ifdef DEBUG
  if (!mayBeMarkable) {
    const Value* elements = nobj->getDenseElementsAllowCopyOnWrite();
    for (unsigned i = 0; i < nobj->getDenseInitializedLength(); i++) {
      MOZ_ASSERT(!elements[i].isGCThing());
    }
  }
#endif

  return mayBeMarkable;
}

static inline void CheckForCompartmentMismatch(JSObject* obj, JSObject* obj2) {
#ifdef DEBUG
  if (MOZ_UNLIKELY(obj->compartment() != obj2->compartment())) {
    fprintf(
        stderr,
        "Compartment mismatch in pointer from %s object slot to %s object\n",
        obj->getClass()->name, obj2->getClass()->name);
    MOZ_CRASH("Compartment mismatch");
  }
#endif
}

inline void GCMarker::processMarkStackTop(SliceBudget& budget) {
  /*
   * The function uses explicit goto and implements the scanning of the
   * object directly. It allows to eliminate the tail recursion and
   * significantly improve the marking performance, see bug 641025.
   */
  HeapSlot* vp;
  HeapSlot* end;
  JSObject* obj;

  switch (stack.peekTag()) {
    case MarkStack::ValueArrayTag: {
      auto array = stack.popValueArray();
      obj = array.ptr.asValueArrayObject();
      vp = array.start;
      end = array.end;
      goto scan_value_array;
    }

    case MarkStack::ObjectTag: {
      obj = stack.popPtr().as<JSObject>();
      AssertShouldMarkInZone(obj);
      goto scan_obj;
    }

    case MarkStack::GroupTag: {
      auto group = stack.popPtr().as<ObjectGroup>();
      return lazilyMarkChildren(group);
    }

    case MarkStack::JitCodeTag: {
      auto code = stack.popPtr().as<jit::JitCode>();
      return code->traceChildren(this);
    }

    case MarkStack::ScriptTag: {
      auto script = stack.popPtr().as<JSScript>();
      return script->traceChildren(this);
    }

    case MarkStack::SavedValueArrayTag: {
      auto savedArray = stack.popSavedValueArray();
      JSObject* obj = savedArray.ptr.asSavedValueArrayObject();
      if (restoreValueArray(savedArray, &vp, &end)) {
        pushValueArray(obj, vp, end);
      } else {
        repush(obj);
      }
      return;
    }

    default:
      MOZ_CRASH("Invalid tag in mark stack");
  }
  return;

scan_value_array:
  MOZ_ASSERT(vp <= end);
  while (vp != end) {
    budget.step();
    if (budget.isOverBudget()) {
      pushValueArray(obj, vp, end);
      return;
    }

    const Value& v = *vp++;
    if (v.isString()) {
      traverseEdge(obj, v.toString());
    } else if (v.isObject()) {
      JSObject* obj2 = &v.toObject();
#ifdef DEBUG
      if (!obj2) {
        fprintf(stderr,
                "processMarkStackTop found ObjectValue(nullptr) "
                "at %zu Values from end of array in object:\n",
                size_t(end - (vp - 1)));
        DumpObject(obj);
      }
#endif
      CheckForCompartmentMismatch(obj, obj2);
      if (mark(obj2)) {
        // Save the rest of this value array for later and start scanning obj2's
        // children.
        pushValueArray(obj, vp, end);
        obj = obj2;
        goto scan_obj;
      }
    } else if (v.isSymbol()) {
      traverseEdge(obj, v.toSymbol());
    } else if (v.isBigInt()) {
      traverseEdge(obj, v.toBigInt());
    } else if (v.isPrivateGCThing()) {
      // v.toGCCellPtr cannot be inlined, so construct one manually.
      Cell* cell = v.toGCThing();
      traverseEdge(obj, JS::GCCellPtr(cell, cell->getTraceKind()));
    }
  }
  return;

scan_obj : {
  AssertShouldMarkInZone(obj);

  budget.step();
  if (budget.isOverBudget()) {
    repush(obj);
    return;
  }

  markImplicitEdges(obj);
  ObjectGroup* group = obj->groupFromGC();
  traverseEdge(obj, group);

  NativeObject* nobj = CallTraceHook(
      [this, obj](auto thingp) { this->traverseEdge(obj, *thingp); }, this, obj,
      CheckGeneration::DoChecks);
  if (!nobj) {
    return;
  }

  Shape* shape = nobj->lastProperty();
  traverseEdge(obj, shape);

  unsigned nslots = nobj->slotSpan();

  do {
    if (nobj->hasEmptyElements()) {
      break;
    }

    if (nobj->denseElementsAreCopyOnWrite()) {
      JSObject* owner = nobj->getElementsHeader()->ownerObject();
      if (owner != nobj) {
        traverseEdge(obj, owner);
        break;
      }
    }

    if (!ObjectDenseElementsMayBeMarkable(nobj)) {
      break;
    }

    vp = nobj->getDenseElementsAllowCopyOnWrite();
    end = vp + nobj->getDenseInitializedLength();

    if (!nslots) {
      goto scan_value_array;
    }
    pushValueArray(nobj, vp, end);
  } while (false);

  vp = nobj->fixedSlots();
  if (nobj->slots_) {
    unsigned nfixed = nobj->numFixedSlots();
    if (nslots > nfixed) {
      pushValueArray(nobj, vp, vp + nfixed);
      vp = nobj->slots_;
      end = vp + (nslots - nfixed);
      goto scan_value_array;
    }
  }
  MOZ_ASSERT(nslots <= nobj->numFixedSlots());
  end = vp + nslots;
  goto scan_value_array;
}
}

/*
 * During incremental GC, we return from drainMarkStack without having processed
 * the entire stack. At that point, JS code can run and reallocate slot arrays
 * that are stored on the stack. To prevent this from happening, we replace all
 * ValueArrayTag stack items with SavedValueArrayTag. In the latter, slots
 * pointers are replaced with slot indexes, and slot array end pointers are
 * replaced with the kind of index (properties vs. elements).
 */

void GCMarker::saveValueRanges() {
  MarkStackIter iter(stack);
  while (!iter.done()) {
    auto tag = iter.peekTag();
    if (tag == MarkStack::ValueArrayTag) {
      const auto& array = iter.peekValueArray();
      auto savedArray = saveValueRange(array);
      iter.saveValueArray(savedArray);
      iter.nextArray();
    } else if (tag == MarkStack::SavedValueArrayTag) {
      iter.nextArray();
    } else {
      iter.nextPtr();
    }
  }

  // This is also a convenient point to poison unused stack memory.
  stack.poisonUnused();
}

bool GCMarker::restoreValueArray(const MarkStack::SavedValueArray& savedArray,
                                 HeapSlot** vpp, HeapSlot** endp) {
  JSObject* objArg = savedArray.ptr.asSavedValueArrayObject();
  if (!objArg->isNative()) {
    return false;
  }

  auto array = restoreValueArray(savedArray);
  *vpp = array.start;
  *endp = array.end;
  return true;
}

MarkStack::SavedValueArray GCMarker::saveValueRange(
    const MarkStack::ValueArray& array) {
  NativeObject* obj = &array.ptr.asValueArrayObject()->as<NativeObject>();
  MOZ_ASSERT(obj->isNative());

  uintptr_t index;
  HeapSlot::Kind kind;
  HeapSlot* vp = obj->getDenseElementsAllowCopyOnWrite();
  if (array.end == vp + obj->getDenseInitializedLength()) {
    MOZ_ASSERT(array.start >= vp);
    // Add the number of shifted elements here (and subtract in
    // restoreValueArray) to ensure shift() calls on the array
    // are handled correctly.
    index = obj->unshiftedIndex(array.start - vp);
    kind = HeapSlot::Element;
  } else {
    HeapSlot* vp = obj->fixedSlots();
    unsigned nfixed = obj->numFixedSlots();
    if (array.start == array.end) {
      index = obj->slotSpan();
    } else if (array.start >= vp && array.start < vp + nfixed) {
      MOZ_ASSERT(array.end == vp + Min(nfixed, obj->slotSpan()));
      index = array.start - vp;
    } else {
      MOZ_ASSERT(array.start >= obj->slots_ &&
                 array.end == obj->slots_ + obj->slotSpan() - nfixed);
      index = (array.start - obj->slots_) + nfixed;
    }
    kind = HeapSlot::Slot;
  }

  return MarkStack::SavedValueArray(obj, index, kind);
}

MarkStack::ValueArray GCMarker::restoreValueArray(
    const MarkStack::SavedValueArray& savedArray) {
  NativeObject* obj =
      &savedArray.ptr.asSavedValueArrayObject()->as<NativeObject>();
  HeapSlot* start = nullptr;
  HeapSlot* end = nullptr;

  uintptr_t index = savedArray.index;
  if (savedArray.kind == HeapSlot::Element) {
    uint32_t initlen = obj->getDenseInitializedLength();

    // Account for shifted elements.
    uint32_t numShifted = obj->getElementsHeader()->numShiftedElements();
    index = (numShifted < index) ? index - numShifted : 0;

    HeapSlot* vp = obj->getDenseElementsAllowCopyOnWrite();
    if (index < initlen) {
      start = vp + index;
      end = vp + initlen;
    } else {
      /* The object shrunk, in which case no scanning is needed. */
      start = end = vp;
    }
  } else {
    MOZ_ASSERT(savedArray.kind == HeapSlot::Slot);
    HeapSlot* vp = obj->fixedSlots();
    unsigned nfixed = obj->numFixedSlots();
    unsigned nslots = obj->slotSpan();
    if (index < nslots) {
      if (index < nfixed) {
        start = vp + index;
        end = vp + Min(nfixed, nslots);
      } else {
        start = obj->slots_ + index - nfixed;
        end = obj->slots_ + nslots - nfixed;
      }
    } else {
      /* The object shrunk, in which case no scanning is needed. */
      start = end = vp;
    }
  }

  return MarkStack::ValueArray(obj, start, end);
}

/*** Mark Stack *************************************************************/

static_assert(sizeof(MarkStack::TaggedPtr) == sizeof(uintptr_t),
              "A TaggedPtr should be the same size as a pointer");
static_assert(sizeof(MarkStack::ValueArray) ==
                  sizeof(MarkStack::SavedValueArray),
              "ValueArray and SavedValueArray should be the same size");
static_assert(
    (sizeof(MarkStack::ValueArray) % sizeof(uintptr_t)) == 0,
    "ValueArray and SavedValueArray should be multiples of the pointer size");

static const size_t ValueArrayWords =
    sizeof(MarkStack::ValueArray) / sizeof(uintptr_t);

template <typename T>
struct MapTypeToMarkStackTag {};
template <>
struct MapTypeToMarkStackTag<JSObject*> {
  static const auto value = MarkStack::ObjectTag;
};
template <>
struct MapTypeToMarkStackTag<ObjectGroup*> {
  static const auto value = MarkStack::GroupTag;
};
template <>
struct MapTypeToMarkStackTag<jit::JitCode*> {
  static const auto value = MarkStack::JitCodeTag;
};
template <>
struct MapTypeToMarkStackTag<JSScript*> {
  static const auto value = MarkStack::ScriptTag;
};

static inline bool TagIsArrayTag(MarkStack::Tag tag) {
  return tag == MarkStack::ValueArrayTag ||
         tag == MarkStack::SavedValueArrayTag;
}

inline MarkStack::TaggedPtr::TaggedPtr(Tag tag, Cell* ptr)
    : bits(tag | uintptr_t(ptr)) {
  assertValid();
}

inline MarkStack::Tag MarkStack::TaggedPtr::tag() const {
  auto tag = Tag(bits & TagMask);
  MOZ_ASSERT(tag <= LastTag);
  return tag;
}

inline Cell* MarkStack::TaggedPtr::ptr() const {
  return reinterpret_cast<Cell*>(bits & ~TagMask);
}

inline void MarkStack::TaggedPtr::assertValid() const {
  mozilla::Unused << tag();
  MOZ_ASSERT(IsCellPointerValid(ptr()));
}

template <typename T>
inline T* MarkStack::TaggedPtr::as() const {
  MOZ_ASSERT(tag() == MapTypeToMarkStackTag<T*>::value);
  MOZ_ASSERT(ptr()->isTenured());
  MOZ_ASSERT(ptr()->is<T>());
  return static_cast<T*>(ptr());
}

inline JSObject* MarkStack::TaggedPtr::asValueArrayObject() const {
  MOZ_ASSERT(tag() == ValueArrayTag);
  MOZ_ASSERT(ptr()->isTenured());
  MOZ_ASSERT(ptr()->is<JSObject>());
  return static_cast<JSObject*>(ptr());
}

inline JSObject* MarkStack::TaggedPtr::asSavedValueArrayObject() const {
  MOZ_ASSERT(tag() == SavedValueArrayTag);
  MOZ_ASSERT(ptr()->isTenured());
  MOZ_ASSERT(ptr()->is<JSObject>());
  return static_cast<JSObject*>(ptr());
}

inline JSRope* MarkStack::TaggedPtr::asTempRope() const {
  MOZ_ASSERT(tag() == TempRopeTag);
  MOZ_ASSERT(ptr()->is<JSString>());
  return static_cast<JSRope*>(ptr());
}

inline MarkStack::ValueArray::ValueArray(JSObject* obj, HeapSlot* startArg,
                                         HeapSlot* endArg)
    : end(endArg), start(startArg), ptr(ValueArrayTag, obj) {
  assertValid();
}

inline void MarkStack::ValueArray::assertValid() const {
  ptr.assertValid();
  MOZ_ASSERT(ptr.tag() == MarkStack::ValueArrayTag);
  MOZ_ASSERT(start);
  MOZ_ASSERT(end);
  MOZ_ASSERT(uintptr_t(start) <= uintptr_t(end));
  MOZ_ASSERT((uintptr_t(end) - uintptr_t(start)) % sizeof(Value) == 0);
}

inline MarkStack::SavedValueArray::SavedValueArray(JSObject* obj,
                                                   size_t indexArg,
                                                   HeapSlot::Kind kindArg)
    : kind(kindArg), index(indexArg), ptr(SavedValueArrayTag, obj) {
  assertValid();
}

inline void MarkStack::SavedValueArray::assertValid() const {
  ptr.assertValid();
  MOZ_ASSERT(ptr.tag() == MarkStack::SavedValueArrayTag);
  MOZ_ASSERT(kind == HeapSlot::Slot || kind == HeapSlot::Element);
}

MarkStack::MarkStack(size_t maxCapacity)
    : topIndex_(0),
      maxCapacity_(maxCapacity)
#ifdef DEBUG
      ,
      iteratorCount_(0)
#endif
{
}

MarkStack::~MarkStack() {
  MOZ_ASSERT(isEmpty());
  MOZ_ASSERT(iteratorCount_ == 0);
}

bool MarkStack::init(JSGCMode gcMode) {
  MOZ_ASSERT(isEmpty());

  return setCapacityForMode(gcMode);
}

void MarkStack::setGCMode(JSGCMode gcMode) {
  // Ignore failure to resize the stack and keep using the existing stack.
  mozilla::Unused << setCapacityForMode(gcMode);
}

bool MarkStack::setCapacityForMode(JSGCMode mode) {
  size_t capacity;

  switch (mode) {
    case JSGC_MODE_GLOBAL:
    case JSGC_MODE_ZONE:
      capacity = NON_INCREMENTAL_MARK_STACK_BASE_CAPACITY;
      break;
    case JSGC_MODE_INCREMENTAL:
    case JSGC_MODE_ZONE_INCREMENTAL:
      capacity = INCREMENTAL_MARK_STACK_BASE_CAPACITY;
      break;
    default:
      MOZ_CRASH("bad gc mode");
  }

  if (capacity > maxCapacity_) {
    capacity = maxCapacity_;
  }

  return resize(capacity);
}

void MarkStack::setMaxCapacity(size_t maxCapacity) {
  MOZ_ASSERT(maxCapacity != 0);
  MOZ_ASSERT(isEmpty());

  maxCapacity_ = maxCapacity;
  if (capacity() > maxCapacity_) {
    // If the realloc fails, just keep using the existing stack; it's
    // not ideal but better than failing.
    mozilla::Unused << resize(maxCapacity_);
  }
}

inline MarkStack::TaggedPtr* MarkStack::topPtr() { return &stack()[topIndex_]; }

inline bool MarkStack::pushTaggedPtr(Tag tag, Cell* ptr) {
  if (!ensureSpace(1)) {
    return false;
  }

  *topPtr() = TaggedPtr(tag, ptr);
  topIndex_++;
  return true;
}

template <typename T>
inline bool MarkStack::push(T* ptr) {
  return pushTaggedPtr(MapTypeToMarkStackTag<T*>::value, ptr);
}

inline bool MarkStack::pushTempRope(JSRope* rope) {
  return pushTaggedPtr(TempRopeTag, rope);
}

inline bool MarkStack::push(JSObject* obj, HeapSlot* start, HeapSlot* end) {
  return push(ValueArray(obj, start, end));
}

inline bool MarkStack::push(const ValueArray& array) {
  array.assertValid();

  if (!ensureSpace(ValueArrayWords)) {
    return false;
  }

  *reinterpret_cast<ValueArray*>(topPtr()) = array;
  topIndex_ += ValueArrayWords;
  MOZ_ASSERT(position() <= capacity());
  MOZ_ASSERT(peekTag() == ValueArrayTag);
  return true;
}

inline bool MarkStack::push(const SavedValueArray& array) {
  array.assertValid();

  if (!ensureSpace(ValueArrayWords)) {
    return false;
  }

  *reinterpret_cast<SavedValueArray*>(topPtr()) = array;
  topIndex_ += ValueArrayWords;
  MOZ_ASSERT(position() <= capacity());
  MOZ_ASSERT(peekTag() == SavedValueArrayTag);
  return true;
}

inline const MarkStack::TaggedPtr& MarkStack::peekPtr() const {
  return stack()[topIndex_ - 1];
}

inline MarkStack::Tag MarkStack::peekTag() const { return peekPtr().tag(); }

inline MarkStack::TaggedPtr MarkStack::popPtr() {
  MOZ_ASSERT(!isEmpty());
  MOZ_ASSERT(!TagIsArrayTag(peekTag()));
  peekPtr().assertValid();
  topIndex_--;
  return *topPtr();
}

inline MarkStack::ValueArray MarkStack::popValueArray() {
  MOZ_ASSERT(peekTag() == ValueArrayTag);
  MOZ_ASSERT(position() >= ValueArrayWords);

  topIndex_ -= ValueArrayWords;
  const auto& array = *reinterpret_cast<ValueArray*>(topPtr());
  array.assertValid();
  return array;
}

inline MarkStack::SavedValueArray MarkStack::popSavedValueArray() {
  MOZ_ASSERT(peekTag() == SavedValueArrayTag);
  MOZ_ASSERT(position() >= ValueArrayWords);

  topIndex_ -= ValueArrayWords;
  const auto& array = *reinterpret_cast<SavedValueArray*>(topPtr());
  array.assertValid();
  return array;
}

inline bool MarkStack::ensureSpace(size_t count) {
  if ((topIndex_ + count) <= capacity()) {
    return !js::oom::ShouldFailWithOOM();
  }

  return enlarge(count);
}

bool MarkStack::enlarge(size_t count) {
  size_t newCapacity = Min(maxCapacity_.ref(), capacity() * 2);
  if (newCapacity < capacity() + count) {
    return false;
  }

  return resize(newCapacity);
}

bool MarkStack::resize(size_t newCapacity) {
  MOZ_ASSERT(newCapacity != 0);
  if (!stack().resize(newCapacity)) {
    return false;
  }

  poisonUnused();
  return true;
}

inline void MarkStack::poisonUnused() {
  static_assert((JS_FRESH_MARK_STACK_PATTERN & TagMask) > LastTag,
                "The mark stack poison pattern must not look like a valid "
                "tagged pointer");

  AlwaysPoison(stack().begin() + topIndex_, JS_FRESH_MARK_STACK_PATTERN,
               stack().capacity() - topIndex_, MemCheckKind::MakeUndefined);
}

size_t MarkStack::sizeOfExcludingThis(
    mozilla::MallocSizeOf mallocSizeOf) const {
  return stack().sizeOfExcludingThis(mallocSizeOf);
}

MarkStackIter::MarkStackIter(MarkStack& stack)
    : stack_(stack), pos_(stack.position()) {
#ifdef DEBUG
  stack.iteratorCount_++;
#endif
}

MarkStackIter::~MarkStackIter() {
#ifdef DEBUG
  MOZ_ASSERT(stack_.iteratorCount_);
  stack_.iteratorCount_--;
#endif
}

inline size_t MarkStackIter::position() const { return pos_; }

inline bool MarkStackIter::done() const { return position() == 0; }

inline MarkStack::TaggedPtr MarkStackIter::peekPtr() const {
  MOZ_ASSERT(!done());
  return stack_.stack()[pos_ - 1];
}

inline MarkStack::Tag MarkStackIter::peekTag() const { return peekPtr().tag(); }

inline MarkStack::ValueArray MarkStackIter::peekValueArray() const {
  MOZ_ASSERT(peekTag() == MarkStack::ValueArrayTag);
  MOZ_ASSERT(position() >= ValueArrayWords);

  const MarkStack::TaggedPtr* ptr = &stack_.stack()[pos_ - ValueArrayWords];
  const auto& array = *reinterpret_cast<const MarkStack::ValueArray*>(ptr);
  array.assertValid();
  return array;
}

inline void MarkStackIter::nextPtr() {
  MOZ_ASSERT(!done());
  MOZ_ASSERT(!TagIsArrayTag(peekTag()));
  pos_--;
}

inline void MarkStackIter::next() {
  if (TagIsArrayTag(peekTag())) {
    nextArray();
  } else {
    nextPtr();
  }
}

inline void MarkStackIter::nextArray() {
  MOZ_ASSERT(TagIsArrayTag(peekTag()));
  MOZ_ASSERT(position() >= ValueArrayWords);
  pos_ -= ValueArrayWords;
}

void MarkStackIter::saveValueArray(
    const MarkStack::SavedValueArray& savedArray) {
  MOZ_ASSERT(peekTag() == MarkStack::ValueArrayTag);
  MOZ_ASSERT(peekPtr().asValueArrayObject() ==
             savedArray.ptr.asSavedValueArrayObject());
  MOZ_ASSERT(position() >= ValueArrayWords);

  MarkStack::TaggedPtr* ptr = &stack_.stack()[pos_ - ValueArrayWords];
  auto dest = reinterpret_cast<MarkStack::SavedValueArray*>(ptr);
  *dest = savedArray;
  MOZ_ASSERT(peekTag() == MarkStack::SavedValueArrayTag);
}

/*** GCMarker ***************************************************************/

/*
 * ExpandWeakMaps: the GC is recomputing the liveness of WeakMap entries by
 * expanding each live WeakMap into its constituent key->value edges, a table
 * of which will be consulted in a later phase whenever marking a potential
 * key.
 */
GCMarker::GCMarker(JSRuntime* rt)
    : JSTracer(rt, JSTracer::TracerKindTag::Marking, ExpandWeakMaps),
      stack(),
      grayPosition(0),
      color(MarkColor::Black),
      delayedMarkingList(nullptr),
      delayedMarkingWorkAdded(false)
#ifdef DEBUG
      ,
      markLaterArenas(0),
      started(false),
      strictCompartmentChecking(false),
      markQueue(rt),
      queuePos(0)
#endif
{
}

bool GCMarker::init(JSGCMode gcMode) { return stack.init(gcMode); }

void GCMarker::start() {
#ifdef DEBUG
  MOZ_ASSERT(!started);
  started = true;
#endif
  color = MarkColor::Black;
  linearWeakMarkingDisabled_ = false;

#ifdef DEBUG
  queuePos = 0;
  queueMarkColor.reset();
#endif

  MOZ_ASSERT(!delayedMarkingList);
  MOZ_ASSERT(markLaterArenas == 0);
}

void GCMarker::stop() {
#ifdef DEBUG
  MOZ_ASSERT(isDrained());

  MOZ_ASSERT(started);
  started = false;

  MOZ_ASSERT(!delayedMarkingList);
  MOZ_ASSERT(markLaterArenas == 0);
#endif

  /* Free non-ballast stack memory. */
  stack.clear();
  AutoEnterOOMUnsafeRegion oomUnsafe;
  for (GCZonesIter zone(runtime()); !zone.done(); zone.next()) {
    if (!zone->gcWeakKeys().clear()) {
      oomUnsafe.crash("clearing weak keys in GCMarker::stop()");
    }
    if (!zone->gcNurseryWeakKeys().clear()) {
      oomUnsafe.crash("clearing (nursery) weak keys in GCMarker::stop()");
    }
  }
}

template <typename F>
inline void GCMarker::forEachDelayedMarkingArena(F&& f) {
  Arena* arena = delayedMarkingList;
  Arena* next;
  while (arena) {
    next = arena->getNextDelayedMarking();
    f(arena);
    arena = next;
  }
}

void GCMarker::reset() {
  color = MarkColor::Black;

  stack.clear();
  MOZ_ASSERT(isMarkStackEmpty());

  forEachDelayedMarkingArena([&](Arena* arena) {
    MOZ_ASSERT(arena->onDelayedMarkingList());
    arena->clearDelayedMarkingState();
#ifdef DEBUG
    MOZ_ASSERT(markLaterArenas);
    markLaterArenas--;
#endif
  });
  delayedMarkingList = nullptr;

  MOZ_ASSERT(isDrained());
  MOZ_ASSERT(!markLaterArenas);
}

void GCMarker::setMarkColor(gc::MarkColor newColor) {
  if (color == newColor) {
    return;
  }
  if (newColor == gc::MarkColor::Black) {
    setMarkColorBlack();
  } else {
    setMarkColorGray();
  }
}

void GCMarker::setMarkColorGray() {
  MOZ_ASSERT(!hasBlackEntries());
  MOZ_ASSERT(color == gc::MarkColor::Black);
  MOZ_ASSERT(runtime()->gc.state() == State::Sweep);

  color = gc::MarkColor::Gray;
  grayPosition = SIZE_MAX;
}

void GCMarker::setMarkColorBlack() {
  MOZ_ASSERT(!hasBlackEntries());
  MOZ_ASSERT(color == gc::MarkColor::Gray);
  MOZ_ASSERT(runtime()->gc.state() == State::Sweep);

  color = gc::MarkColor::Black;
  grayPosition = stack.position();
}

template <typename T>
void GCMarker::pushTaggedPtr(T* ptr) {
  checkZone(ptr);
  if (!stack.push(ptr)) {
    delayMarkingChildren(ptr);
  }
}

void GCMarker::pushValueArray(JSObject* obj, HeapSlot* start, HeapSlot* end) {
  checkZone(obj);

  if (start == end) {
    return;
  }

  if (!stack.push(obj, start, end)) {
    delayMarkingChildren(obj);
  }
}

void GCMarker::repush(JSObject* obj) {
  MOZ_ASSERT(obj->asTenured().isMarkedAtLeast(markColor()));
  pushTaggedPtr(obj);
}

void GCMarker::enterWeakMarkingMode() {
  MOZ_ASSERT(runtime()->gc.nursery().isEmpty());

  MOZ_ASSERT(tag_ == TracerKindTag::Marking);
  if (linearWeakMarkingDisabled_) {
    return;
  }

  // During weak marking mode, we maintain a table mapping weak keys to
  // entries in known-live weakmaps. Initialize it with the keys of marked
  // weakmaps -- or more precisely, the keys of marked weakmaps that are
  // mapped to not yet live values. (Once bug 1167452 implements incremental
  // weakmap marking, this initialization step will become unnecessary, as
  // the table will already hold all such keys.)
  if (weakMapAction() == ExpandWeakMaps) {
    tag_ = TracerKindTag::WeakMarking;

    // If there was an 'enter-weak-marking-mode' token in the queue, then it
    // and everything after it will still be in the queue so we can process
    // them now.
    while (processMarkQueue() == QueueYielded) {
    };

    for (SweepGroupZonesIter zone(runtime()); !zone.done(); zone.next()) {
      for (WeakMapBase* m : zone->gcWeakMapList()) {
        if (m->marked) {
          (void)m->markEntries(this);
        }
      }
    }
  }
}

void GCMarker::leaveWeakMarkingMode() {
  MOZ_ASSERT_IF(
      weakMapAction() == ExpandWeakMaps && !linearWeakMarkingDisabled_,
      tag_ == TracerKindTag::WeakMarking);
  tag_ = TracerKindTag::Marking;

  // Table is expensive to maintain when not in weak marking mode, so we'll
  // rebuild it upon entry rather than allow it to contain stale data.
  AutoEnterOOMUnsafeRegion oomUnsafe;
  for (GCZonesIter zone(runtime()); !zone.done(); zone.next()) {
    if (!zone->gcWeakKeys().clear()) {
      oomUnsafe.crash("clearing weak keys in GCMarker::leaveWeakMarkingMode()");
    }
  }
}

void GCMarker::delayMarkingChildren(Cell* cell) {
  Arena* arena = cell->asTenured().arena();
  if (!arena->onDelayedMarkingList()) {
    arena->setNextDelayedMarkingArena(delayedMarkingList);
    delayedMarkingList = arena;
#ifdef DEBUG
    markLaterArenas++;
#endif
  }
  JS::TraceKind kind = MapAllocToTraceKind(arena->getAllocKind());
  MarkColor colorToMark =
      TraceKindCanBeMarkedGray(kind) ? color : MarkColor::Black;
  if (!arena->hasDelayedMarking(colorToMark)) {
    arena->setHasDelayedMarking(colorToMark, true);
    delayedMarkingWorkAdded = true;
  }
}

void GCMarker::markDelayedChildren(Arena* arena, MarkColor color) {
  JS::TraceKind kind = MapAllocToTraceKind(arena->getAllocKind());
  MOZ_ASSERT_IF(color == MarkColor::Gray, TraceKindCanBeMarkedGray(kind));

  AutoSetMarkColor setColor(*this, color);
  for (ArenaCellIterUnderGC i(arena); !i.done(); i.next()) {
    TenuredCell* t = i.getCell();
    if (t->isMarked(color)) {
      js::TraceChildren(this, t, kind);
    }
  }
}

/*
 * Process arenas from |delayedMarkingList| by marking the unmarked children of
 * marked cells of color |color|. Return early if the |budget| is exceeded.
 *
 * This is called twice, first to mark gray children and then to mark black
 * children.
 */
bool GCMarker::processDelayedMarkingList(MarkColor color, SliceBudget& budget) {
  // Marking delayed children may add more arenas to the list, including arenas
  // we are currently processing or have previously processed. Handle this by
  // clearing a flag on each arena before marking its children. This flag will
  // be set again if the arena is re-added. Iterate the list until no new arenas
  // were added.

  do {
    delayedMarkingWorkAdded = false;
    for (Arena* arena = delayedMarkingList; arena;
         arena = arena->getNextDelayedMarking()) {
      if (!arena->hasDelayedMarking(color)) {
        continue;
      }
      arena->setHasDelayedMarking(color, false);
      markDelayedChildren(arena, color);
      budget.step(150);
      if (budget.isOverBudget()) {
        return false;
      }
    }
  } while (delayedMarkingWorkAdded);

  return true;
}

bool GCMarker::markAllDelayedChildren(SliceBudget& budget) {
  MOZ_ASSERT(!hasBlackEntries());
  MOZ_ASSERT(markColor() == MarkColor::Black);

  GCRuntime& gc = runtime()->gc;
  gcstats::AutoPhase ap(gc.stats(), gc.state() == State::Mark,
                        gcstats::PhaseKind::MARK_DELAYED);

  // We have a list of arenas containing marked cells with unmarked children
  // where we ran out of stack space during marking.
  //
  // Both black and gray cells in these arenas may have unmarked children, and
  // we must mark gray children first as gray entries always sit before black
  // entries on the mark stack. Therefore the list is processed in two stages.

  MOZ_ASSERT(delayedMarkingList);

  bool finished;
  finished = processDelayedMarkingList(MarkColor::Gray, budget);
  rebuildDelayedMarkingList();
  if (!finished) {
    return false;
  }

  finished = processDelayedMarkingList(MarkColor::Black, budget);
  rebuildDelayedMarkingList();

  MOZ_ASSERT_IF(finished, !delayedMarkingList);
  MOZ_ASSERT_IF(finished, !markLaterArenas);

  return finished;
}

void GCMarker::rebuildDelayedMarkingList() {
  // Rebuild the delayed marking list, removing arenas which do not need further
  // marking.

  Arena* listTail = nullptr;
  forEachDelayedMarkingArena([&](Arena* arena) {
    if (!arena->hasAnyDelayedMarking()) {
      arena->clearDelayedMarkingState();
#ifdef DEBUG
      MOZ_ASSERT(markLaterArenas);
      markLaterArenas--;
#endif
      return;
    }

    appendToDelayedMarkingList(&listTail, arena);
  });
  appendToDelayedMarkingList(&listTail, nullptr);
}

inline void GCMarker::appendToDelayedMarkingList(Arena** listTail,
                                                 Arena* arena) {
  if (*listTail) {
    (*listTail)->updateNextDelayedMarkingArena(arena);
  } else {
    delayedMarkingList = arena;
  }
  *listTail = arena;
}

template <typename T>
static void PushArenaTyped(GCMarker* gcmarker, Arena* arena) {
  for (ArenaCellIterUnderGC i(arena); !i.done(); i.next()) {
    gcmarker->traverse(i.get<T>());
  }
}

struct PushArenaFunctor {
  template <typename T>
  void operator()(GCMarker* gcmarker, Arena* arena) {
    PushArenaTyped<T>(gcmarker, arena);
  }
};

void gc::PushArena(GCMarker* gcmarker, Arena* arena) {
  DispatchTraceKindTyped(PushArenaFunctor(),
                         MapAllocToTraceKind(arena->getAllocKind()), gcmarker,
                         arena);
}

#ifdef DEBUG
void GCMarker::checkZone(void* p) {
  MOZ_ASSERT(started);
  DebugOnly<Cell*> cell = static_cast<Cell*>(p);
  MOZ_ASSERT_IF(cell->isTenured(), cell->asTenured().zone()->isCollecting());
}
#endif

size_t GCMarker::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
  size_t size = stack.sizeOfExcludingThis(mallocSizeOf);
  for (ZonesIter zone(runtime(), WithAtoms); !zone.done(); zone.next()) {
    size += zone->gcGrayRoots().SizeOfExcludingThis(mallocSizeOf);
  }
  return size;
}

/*** Tenuring Tracer ********************************************************/

namespace js {
template <typename T>
void TenuringTracer::traverse(T** tp) {}

template <>
void TenuringTracer::traverse(JSObject** objp) {
  // We only ever visit the internals of objects after moving them to tenured.
  MOZ_ASSERT(!nursery().isInside(objp));

  Cell** cellp = reinterpret_cast<Cell**>(objp);
  if (!IsInsideNursery(*cellp) || nursery().getForwardedPointer(cellp)) {
    return;
  }

  // Take a fast path for tenuring a plain object which is by far the most
  // common case.
  JSObject* obj = *objp;
  if (obj->is<PlainObject>()) {
    *objp = movePlainObjectToTenured(&obj->as<PlainObject>());
    return;
  }

  *objp = moveToTenuredSlow(obj);
}

template <>
void TenuringTracer::traverse(JSString** strp) {
  // We only ever visit the internals of strings after moving them to tenured.
  MOZ_ASSERT(!nursery().isInside(strp));

  Cell** cellp = reinterpret_cast<Cell**>(strp);
  if (IsInsideNursery(*cellp) && !nursery().getForwardedPointer(cellp)) {
    *strp = moveToTenured(*strp);
  }
}

template <typename T>
void TenuringTracer::traverse(T* thingp) {
  auto tenured = MapGCThingTyped(*thingp, [this](auto t) {
    this->traverse(&t);
    return TaggedPtr<T>::wrap(t);
  });
  if (tenured.isSome() && tenured.value() != *thingp) {
    *thingp = tenured.value();
  }
}

}  // namespace js

template <typename T>
void js::gc::StoreBuffer::MonoTypeBuffer<T>::trace(TenuringTracer& mover) {
  mozilla::ReentrancyGuard g(*owner_);
  MOZ_ASSERT(owner_->isEnabled());
  if (last_) {
    last_.trace(mover);
  }
  for (typename StoreSet::Range r = stores_.all(); !r.empty(); r.popFront()) {
    r.front().trace(mover);
  }
}

namespace js {
namespace gc {
template void StoreBuffer::MonoTypeBuffer<StoreBuffer::ValueEdge>::trace(
    TenuringTracer&);
template void StoreBuffer::MonoTypeBuffer<StoreBuffer::SlotsEdge>::trace(
    TenuringTracer&);
template struct StoreBuffer::MonoTypeBuffer<StoreBuffer::StringPtrEdge>;
template struct StoreBuffer::MonoTypeBuffer<StoreBuffer::ObjectPtrEdge>;
}  // namespace gc
}  // namespace js

void js::gc::StoreBuffer::SlotsEdge::trace(TenuringTracer& mover) const {
  NativeObject* obj = object();
  MOZ_ASSERT(IsCellPointerValid(obj));

  // Beware JSObject::swap exchanging a native object for a non-native one.
  if (!obj->isNative()) {
    return;
  }

  MOZ_ASSERT(!IsInsideNursery(obj), "obj shouldn't live in nursery.");

  if (kind() == ElementKind) {
    uint32_t initLen = obj->getDenseInitializedLength();
    uint32_t numShifted = obj->getElementsHeader()->numShiftedElements();
    uint32_t clampedStart = start_;
    clampedStart = numShifted < clampedStart ? clampedStart - numShifted : 0;
    clampedStart = Min(clampedStart, initLen);
    uint32_t clampedEnd = start_ + count_;
    clampedEnd = numShifted < clampedEnd ? clampedEnd - numShifted : 0;
    clampedEnd = Min(clampedEnd, initLen);
    MOZ_ASSERT(clampedStart <= clampedEnd);
    mover.traceSlots(
        static_cast<HeapSlot*>(obj->getDenseElements() + clampedStart)
            ->unsafeUnbarrieredForTracing(),
        clampedEnd - clampedStart);
  } else {
    uint32_t start = Min(start_, obj->slotSpan());
    uint32_t end = Min(start_ + count_, obj->slotSpan());
    MOZ_ASSERT(start <= end);
    mover.traceObjectSlots(obj, start, end - start);
  }
}

static inline void TraceWholeCell(TenuringTracer& mover, JSObject* object) {
  mover.traceObject(object);
}

static inline void TraceWholeCell(TenuringTracer& mover, JSString* str) {
  str->traceChildren(&mover);
}

static inline void TraceWholeCell(TenuringTracer& mover, JSScript* script) {
  script->traceChildren(&mover);
}

static inline void TraceWholeCell(TenuringTracer& mover,
                                  jit::JitCode* jitcode) {
  jitcode->traceChildren(&mover);
}

template <typename T>
static void TraceBufferedCells(TenuringTracer& mover, Arena* arena,
                               ArenaCellSet* cells) {
  for (size_t i = 0; i < MaxArenaCellIndex; i += cells->BitsPerWord) {
    ArenaCellSet::WordT bitset = cells->getWord(i / cells->BitsPerWord);
    while (bitset) {
      size_t bit = i + js::detail::CountTrailingZeroes(bitset);
      auto cell =
          reinterpret_cast<T*>(uintptr_t(arena) + ArenaCellIndexBytes * bit);
      TraceWholeCell(mover, cell);
      bitset &= bitset - 1;  // Clear the low bit.
    }
  }
}

void js::gc::StoreBuffer::WholeCellBuffer::trace(TenuringTracer& mover) {
  MOZ_ASSERT(owner_->isEnabled());

  for (ArenaCellSet* cells = head_; cells; cells = cells->next) {
    cells->check();

    Arena* arena = cells->arena;
    arena->bufferedCells() = &ArenaCellSet::Empty;

    JS::TraceKind kind = MapAllocToTraceKind(arena->getAllocKind());
    switch (kind) {
      case JS::TraceKind::Object:
        TraceBufferedCells<JSObject>(mover, arena, cells);
        break;
      case JS::TraceKind::String:
        TraceBufferedCells<JSString>(mover, arena, cells);
        break;
      case JS::TraceKind::Script:
        TraceBufferedCells<JSScript>(mover, arena, cells);
        break;
      case JS::TraceKind::JitCode:
        TraceBufferedCells<jit::JitCode>(mover, arena, cells);
        break;
      default:
        MOZ_CRASH("Unexpected trace kind");
    }
  }

  head_ = nullptr;
}

template <typename T>
void js::gc::StoreBuffer::CellPtrEdge<T>::trace(TenuringTracer& mover) const {
  static_assert(std::is_base_of<Cell, T>::value, "T must be a Cell type");
  static_assert(!std::is_base_of<TenuredCell, T>::value,
                "T must not be a tenured Cell type");

  if (!*edge) {
    return;
  }

  MOZ_ASSERT(IsCellPointerValid(*edge));
  MOZ_ASSERT((*edge)->getTraceKind() == JS::MapTypeToTraceKind<T>::kind);

  mover.traverse(edge);
}

void js::gc::StoreBuffer::ValueEdge::trace(TenuringTracer& mover) const {
  if (deref()) {
    mover.traverse(edge);
  }
}

// Visit all object children of the object and trace them.
void js::TenuringTracer::traceObject(JSObject* obj) {
  NativeObject* nobj =
      CallTraceHook([this](auto thingp) { this->traverse(thingp); }, this, obj,
                    CheckGeneration::NoChecks);
  if (!nobj) {
    return;
  }

  // Note: the contents of copy on write elements pointers are filled in
  // during parsing and cannot contain nursery pointers.
  if (!nobj->hasEmptyElements() && !nobj->denseElementsAreCopyOnWrite() &&
      ObjectDenseElementsMayBeMarkable(nobj)) {
    Value* elems = static_cast<HeapSlot*>(nobj->getDenseElements())
                       ->unsafeUnbarrieredForTracing();
    traceSlots(elems, elems + nobj->getDenseInitializedLength());
  }

  traceObjectSlots(nobj, 0, nobj->slotSpan());
}

void js::TenuringTracer::traceObjectSlots(NativeObject* nobj, uint32_t start,
                                          uint32_t length) {
  HeapSlot* fixedStart;
  HeapSlot* fixedEnd;
  HeapSlot* dynStart;
  HeapSlot* dynEnd;
  nobj->getSlotRange(start, length, &fixedStart, &fixedEnd, &dynStart, &dynEnd);
  if (fixedStart) {
    traceSlots(fixedStart->unsafeUnbarrieredForTracing(),
               fixedEnd->unsafeUnbarrieredForTracing());
  }
  if (dynStart) {
    traceSlots(dynStart->unsafeUnbarrieredForTracing(),
               dynEnd->unsafeUnbarrieredForTracing());
  }
}

void js::TenuringTracer::traceSlots(Value* vp, Value* end) {
  for (; vp != end; ++vp) {
    traverse(vp);
  }
}

inline void js::TenuringTracer::traceSlots(JS::Value* vp, uint32_t nslots) {
  traceSlots(vp, vp + nslots);
}

void js::TenuringTracer::traceString(JSString* str) {
  str->traceChildren(this);
}

#ifdef DEBUG
static inline ptrdiff_t OffsetToChunkEnd(void* p) {
  return ChunkLocationOffset - (uintptr_t(p) & gc::ChunkMask);
}
#endif

/* Insert the given relocation entry into the list of things to visit. */
inline void js::TenuringTracer::insertIntoObjectFixupList(
    RelocationOverlay* entry) {
  *objTail = entry;
  objTail = &entry->nextRef();
  *objTail = nullptr;
}

template <typename T>
inline T* js::TenuringTracer::allocTenured(Zone* zone, AllocKind kind) {
  return static_cast<T*>(static_cast<Cell*>(AllocateCellInGC(zone, kind)));
}

JSObject* js::TenuringTracer::moveToTenuredSlow(JSObject* src) {
  MOZ_ASSERT(IsInsideNursery(src));
  MOZ_ASSERT(!src->zone()->usedByHelperThread());
  MOZ_ASSERT(!src->is<PlainObject>());

  AllocKind dstKind = src->allocKindForTenure(nursery());
  auto dst = allocTenured<JSObject>(src->zone(), dstKind);

  size_t srcSize = Arena::thingSize(dstKind);
  size_t dstSize = srcSize;

  /*
   * Arrays do not necessarily have the same AllocKind between src and dst.
   * We deal with this by copying elements manually, possibly re-inlining
   * them if there is adequate room inline in dst.
   *
   * For Arrays we're reducing tenuredSize to the smaller srcSize
   * because moveElementsToTenured() accounts for all Array elements,
   * even if they are inlined.
   */
  if (src->is<ArrayObject>()) {
    dstSize = srcSize = sizeof(NativeObject);
  } else if (src->is<TypedArrayObject>()) {
    TypedArrayObject* tarray = &src->as<TypedArrayObject>();
    // Typed arrays with inline data do not necessarily have the same
    // AllocKind between src and dst. The nursery does not allocate an
    // inline data buffer that has the same size as the slow path will do.
    // In the slow path, the Typed Array Object stores the inline data
    // in the allocated space that fits the AllocKind. In the fast path,
    // the nursery will allocate another buffer that is directly behind the
    // minimal JSObject. That buffer size plus the JSObject size is not
    // necessarily as large as the slow path's AllocKind size.
    if (tarray->hasInlineElements()) {
      AllocKind srcKind = GetGCObjectKind(TypedArrayObject::FIXED_DATA_START);
      size_t headerSize = Arena::thingSize(srcKind);
      srcSize = headerSize + tarray->byteLength();
    }
  }

  tenuredSize += dstSize;
  tenuredCells++;

  // Copy the Cell contents.
  MOZ_ASSERT(OffsetToChunkEnd(src) >= ptrdiff_t(srcSize));
  js_memcpy(dst, src, srcSize);

  // Move the slots and elements, if we need to.
  if (src->isNative()) {
    NativeObject* ndst = &dst->as<NativeObject>();
    NativeObject* nsrc = &src->as<NativeObject>();
    tenuredSize += moveSlotsToTenured(ndst, nsrc);
    tenuredSize += moveElementsToTenured(ndst, nsrc, dstKind);

    // There is a pointer into a dictionary mode object from the head of its
    // shape list. This is updated in Nursery::sweepDictionaryModeObjects().
  }

  JSObjectMovedOp op = dst->getClass()->extObjectMovedOp();
  MOZ_ASSERT_IF(src->is<ProxyObject>(), op == proxy_ObjectMoved);
  if (op) {
    // Tell the hazard analysis that the object moved hook can't GC.
    JS::AutoSuppressGCAnalysis nogc;
    tenuredSize += op(dst, src);
  } else {
    MOZ_ASSERT_IF(src->getClass()->hasFinalize(),
                  CanNurseryAllocateFinalizedClass(src->getClass()));
  }

  RelocationOverlay* overlay = RelocationOverlay::fromCell(src);
  overlay->forwardTo(dst);
  insertIntoObjectFixupList(overlay);

  gcTracer.tracePromoteToTenured(src, dst);
  return dst;
}

inline JSObject* js::TenuringTracer::movePlainObjectToTenured(
    PlainObject* src) {
  // Fast path version of moveToTenuredSlow() for specialized for PlainObject.

  MOZ_ASSERT(IsInsideNursery(src));
  MOZ_ASSERT(!src->zone()->usedByHelperThread());

  AllocKind dstKind = src->allocKindForTenure();
  auto dst = allocTenured<PlainObject>(src->zone(), dstKind);

  size_t srcSize = Arena::thingSize(dstKind);
  tenuredSize += srcSize;
  tenuredCells++;

  // Copy the Cell contents.
  MOZ_ASSERT(OffsetToChunkEnd(src) >= ptrdiff_t(srcSize));
  js_memcpy(dst, src, srcSize);

  // Move the slots and elements.
  tenuredSize += moveSlotsToTenured(dst, src);
  tenuredSize += moveElementsToTenured(dst, src, dstKind);

  MOZ_ASSERT(!dst->getClass()->extObjectMovedOp());

  RelocationOverlay* overlay = RelocationOverlay::fromCell(src);
  overlay->forwardTo(dst);
  insertIntoObjectFixupList(overlay);

  gcTracer.tracePromoteToTenured(src, dst);
  return dst;
}

size_t js::TenuringTracer::moveSlotsToTenured(NativeObject* dst,
                                              NativeObject* src) {
  /* Fixed slots have already been copied over. */
  if (!src->hasDynamicSlots()) {
    return 0;
  }

  Zone* zone = src->zone();
  size_t count = src->numDynamicSlots();

  if (!nursery().isInside(src->slots_)) {
    AddCellMemory(dst, count * sizeof(HeapSlot), MemoryUse::ObjectSlots);
    nursery().removeMallocedBuffer(src->slots_);
    return 0;
  }

  {
    AutoEnterOOMUnsafeRegion oomUnsafe;
    dst->slots_ = zone->pod_malloc<HeapSlot>(count);
    if (!dst->slots_) {
      oomUnsafe.crash(sizeof(HeapSlot) * count,
                      "Failed to allocate slots while tenuring.");
    }
  }

  AddCellMemory(dst, count * sizeof(HeapSlot), MemoryUse::ObjectSlots);

  PodCopy(dst->slots_, src->slots_, count);
  nursery().setSlotsForwardingPointer(src->slots_, dst->slots_, count);
  return count * sizeof(HeapSlot);
}

size_t js::TenuringTracer::moveElementsToTenured(NativeObject* dst,
                                                 NativeObject* src,
                                                 AllocKind dstKind) {
  if (src->hasEmptyElements() || src->denseElementsAreCopyOnWrite()) {
    return 0;
  }

  Zone* zone = src->zone();

  ObjectElements* srcHeader = src->getElementsHeader();
  size_t nslots = srcHeader->numAllocatedElements();

  void* srcAllocatedHeader = src->getUnshiftedElementsHeader();

  /* TODO Bug 874151: Prefer to put element data inline if we have space. */
  if (!nursery().isInside(srcAllocatedHeader)) {
    MOZ_ASSERT(src->elements_ == dst->elements_);
    nursery().removeMallocedBuffer(srcAllocatedHeader);

    AddCellMemory(dst, nslots * sizeof(HeapSlot), MemoryUse::ObjectElements);

    return 0;
  }

  // Shifted elements are copied too.
  uint32_t numShifted = srcHeader->numShiftedElements();

  /* Unlike other objects, Arrays can have fixed elements. */
  if (src->is<ArrayObject>() && nslots <= GetGCKindSlots(dstKind)) {
    dst->as<ArrayObject>().setFixedElements();
    js_memcpy(dst->getElementsHeader(), srcAllocatedHeader,
              nslots * sizeof(HeapSlot));
    dst->elements_ += numShifted;
    nursery().setElementsForwardingPointer(srcHeader, dst->getElementsHeader(),
                                           srcHeader->capacity);
    return nslots * sizeof(HeapSlot);
  }

  MOZ_ASSERT(nslots >= 2);

  ObjectElements* dstHeader;
  {
    AutoEnterOOMUnsafeRegion oomUnsafe;
    dstHeader =
        reinterpret_cast<ObjectElements*>(zone->pod_malloc<HeapSlot>(nslots));
    if (!dstHeader) {
      oomUnsafe.crash(sizeof(HeapSlot) * nslots,
                      "Failed to allocate elements while tenuring.");
    }
  }

  AddCellMemory(dst, nslots * sizeof(HeapSlot), MemoryUse::ObjectElements);

  js_memcpy(dstHeader, srcAllocatedHeader, nslots * sizeof(HeapSlot));
  dst->elements_ = dstHeader->elements() + numShifted;
  nursery().setElementsForwardingPointer(srcHeader, dst->getElementsHeader(),
                                         srcHeader->capacity);
  return nslots * sizeof(HeapSlot);
}

inline void js::TenuringTracer::insertIntoStringFixupList(
    RelocationOverlay* entry) {
  *stringTail = entry;
  stringTail = &entry->nextRef();
  *stringTail = nullptr;
}

JSString* js::TenuringTracer::moveToTenured(JSString* src) {
  MOZ_ASSERT(IsInsideNursery(src));
  MOZ_ASSERT(!src->zone()->usedByHelperThread());

  AllocKind dstKind = src->getAllocKind();
  Zone* zone = src->zone();
  zone->tenuredStrings++;

  JSString* dst = allocTenured<JSString>(zone, dstKind);
  tenuredSize += moveStringToTenured(dst, src, dstKind);
  tenuredCells++;

  RelocationOverlay* overlay = RelocationOverlay::fromCell(src);
  overlay->forwardTo(dst);
  insertIntoStringFixupList(overlay);

  gcTracer.tracePromoteToTenured(src, dst);
  return dst;
}

void js::Nursery::collectToFixedPoint(TenuringTracer& mover,
                                      TenureCountCache& tenureCounts) {
  for (RelocationOverlay* p = mover.objHead; p; p = p->next()) {
    JSObject* obj = static_cast<JSObject*>(p->forwardingAddress());
    mover.traceObject(obj);

    TenureCount& entry = tenureCounts.findEntry(obj->groupRaw());
    if (entry.group == obj->groupRaw()) {
      entry.count++;
    } else if (!entry.group) {
      entry.group = obj->groupRaw();
      entry.count = 1;
    }
  }

  for (RelocationOverlay* p = mover.stringHead; p; p = p->next()) {
    mover.traceString(static_cast<JSString*>(p->forwardingAddress()));
  }
}

size_t js::TenuringTracer::moveStringToTenured(JSString* dst, JSString* src,
                                               AllocKind dstKind) {
  size_t size = Arena::thingSize(dstKind);

  // At the moment, strings always have the same AllocKind between src and
  // dst. This may change in the future.
  MOZ_ASSERT(dst->asTenured().getAllocKind() == src->getAllocKind());

  // Copy the Cell contents.
  MOZ_ASSERT(OffsetToChunkEnd(src) >= ptrdiff_t(size));
  js_memcpy(dst, src, size);

  if (!src->isInline() && src->isLinear()) {
    if (src->isUndepended() || !src->hasBase()) {
      void* chars = src->asLinear().nonInlineCharsRaw();
      nursery().removeMallocedBuffer(chars);
    }
  }

  if (dst->isFlat() && !dst->isInline()) {
    AddCellMemory(dst, dst->asFlat().allocSize(), MemoryUse::StringContents);
  }

  return size;
}

/*** IsMarked / IsAboutToBeFinalized ****************************************/

template <typename T>
static inline void CheckIsMarkedThing(T* thingp) {
#define IS_SAME_TYPE_OR(name, type, _, _1) mozilla::IsSame<type*, T>::value ||
  static_assert(JS_FOR_EACH_TRACEKIND(IS_SAME_TYPE_OR) false,
                "Only the base cell layout types are allowed into "
                "marking/tracing internals");
#undef IS_SAME_TYPE_OR

#ifdef DEBUG
  MOZ_ASSERT(thingp);
  MOZ_ASSERT(*thingp);

  // Allow any thread access to uncollected things.
  T thing = *thingp;
  if (ThingIsPermanentAtomOrWellKnownSymbol(thing)) {
    return;
  }

  // Allow the current thread access if it is sweeping, but try to check the
  // zone. Some threads have access to all zones when sweeping.
  JSContext* cx = TlsContext.get();
  if (cx->gcSweeping) {
    Zone* zone = thing->zoneFromAnyThread();
    MOZ_ASSERT_IF(cx->gcSweepingZone,
                  cx->gcSweepingZone == zone || zone->isAtomsZone());
    return;
  }

  // Otherwise only allow access from the main thread or this zone's associated
  // thread.
  MOZ_ASSERT(CurrentThreadCanAccessRuntime(thing->runtimeFromAnyThread()) ||
             CurrentThreadCanAccessZone(thing->zoneFromAnyThread()));
#endif
}

template <typename T>
static inline bool ShouldCheckMarkState(JSRuntime* rt, T** thingp) {
  CheckIsMarkedThing(thingp);
  MOZ_ASSERT(!IsInsideNursery(*thingp));

  TenuredCell& thing = (*thingp)->asTenured();
  Zone* zone = thing.zoneFromAnyThread();
  if (!zone->isCollectingFromAnyThread() || zone->isGCFinished()) {
    return false;
  }

  if (zone->isGCCompacting() && IsForwarded(*thingp)) {
    *thingp = Forwarded(*thingp);
    return false;
  }

  return true;
}

template <typename T>
struct MightBeNurseryAllocated {
  static const bool value = mozilla::IsBaseOf<JSObject, T>::value ||
                            mozilla::IsBaseOf<JSString, T>::value;
};

template <typename T>
bool js::gc::IsMarkedInternal(JSRuntime* rt, T** thingp) {
  if (IsOwnedByOtherRuntime(rt, *thingp)) {
    return true;
  }

  if (MightBeNurseryAllocated<T>::value && IsInsideNursery(*thingp)) {
    MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
    Cell** cellp = reinterpret_cast<Cell**>(thingp);
    return Nursery::getForwardedPointer(cellp);
  }

  if (!ShouldCheckMarkState(rt, thingp)) {
    return true;
  }

  return (*thingp)->asTenured().isMarkedAny();
}

template <typename T>
bool js::gc::IsMarkedBlackInternal(JSRuntime* rt, T** thingp) {
  if (IsOwnedByOtherRuntime(rt, *thingp)) {
    return true;
  }

  if (MightBeNurseryAllocated<T>::value && IsInsideNursery(*thingp)) {
    MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
    Cell** cellp = reinterpret_cast<Cell**>(thingp);
    return Nursery::getForwardedPointer(cellp);
  }

  if (!ShouldCheckMarkState(rt, thingp)) {
    return true;
  }

  return (*thingp)->asTenured().isMarkedBlack();
}

template <typename T>
bool js::gc::IsMarkedInternal(JSRuntime* rt, T* thingp) {
  bool marked = true;
  auto thing = MapGCThingTyped(*thingp, [rt, &marked](auto t) {
    marked = IsMarkedInternal(rt, &t);
    return TaggedPtr<T>::wrap(t);
  });
  if (thing.isSome() && thing.value() != *thingp) {
    *thingp = thing.value();
  }
  return marked;
}

template <typename T>
bool js::gc::IsMarkedBlackInternal(JSRuntime* rt, T* thingp) {
  bool marked = true;
  auto thing = MapGCThingTyped(*thingp, [rt, &marked](auto t) {
    marked = IsMarkedBlackInternal(rt, &t);
    return TaggedPtr<T>::wrap(t);
  });
  if (thing.isSome() && thing.value() != *thingp) {
    *thingp = thing.value();
  }
  return marked;
}

bool js::gc::IsAboutToBeFinalizedDuringSweep(TenuredCell& tenured) {
  MOZ_ASSERT(!IsInsideNursery(&tenured));
  MOZ_ASSERT(tenured.zoneFromAnyThread()->isGCSweeping());
  return !tenured.isMarkedAny();
}

template <typename T>
bool js::gc::IsAboutToBeFinalizedInternal(T** thingp) {
  CheckIsMarkedThing(thingp);
  T* thing = *thingp;
  JSRuntime* rt = thing->runtimeFromAnyThread();

  /* Permanent atoms are never finalized by non-owning runtimes. */
  if (ThingIsPermanentAtomOrWellKnownSymbol(thing) &&
      TlsContext.get()->runtime() != rt) {
    return false;
  }

  if (IsInsideNursery(thing)) {
    return JS::RuntimeHeapIsMinorCollecting() &&
           !Nursery::getForwardedPointer(reinterpret_cast<Cell**>(thingp));
  }

  Zone* zone = thing->asTenured().zoneFromAnyThread();
  if (zone->isGCSweeping()) {
    return IsAboutToBeFinalizedDuringSweep(thing->asTenured());
  } else if (zone->isGCCompacting() && IsForwarded(thing)) {
    *thingp = Forwarded(thing);
    return false;
  }

  return false;
}

template <typename T>
bool js::gc::IsAboutToBeFinalizedInternal(T* thingp) {
  bool dying = false;
  auto thing = MapGCThingTyped(*thingp, [&dying](auto t) {
    dying = IsAboutToBeFinalizedInternal(&t);
    return TaggedPtr<T>::wrap(t);
  });
  if (thing.isSome() && thing.value() != *thingp) {
    *thingp = thing.value();
  }
  return dying;
}

template <typename T>
inline bool SweepingTracer::sweepEdge(T** thingp) {
  CheckIsMarkedThing(thingp);
  T* thing = *thingp;
  JSRuntime* rt = thing->runtimeFromAnyThread();

  if (ThingIsPermanentAtomOrWellKnownSymbol(thing) && runtime() != rt) {
    return true;
  }

  // TODO: We should assert the zone of the tenured cell is in Sweeping state,
  // however we need to fix atoms and JitcodeGlobalTable first.
  // Bug 1501334 : IsAboutToBeFinalized doesn't work for atoms
  // Bug 1071218 : Refactor Debugger::sweepAll and
  //               JitRuntime::SweepJitcodeGlobalTable to work per sweep group
  TenuredCell& tenured = thing->asTenured();
  if (!tenured.isMarkedAny()) {
    *thingp = nullptr;
    return false;
  }

  return true;
}

bool SweepingTracer::onObjectEdge(JSObject** objp) { return sweepEdge(objp); }
bool SweepingTracer::onShapeEdge(Shape** shapep) { return sweepEdge(shapep); }
bool SweepingTracer::onStringEdge(JSString** stringp) {
  return sweepEdge(stringp);
}
bool SweepingTracer::onScriptEdge(JSScript** scriptp) {
  return sweepEdge(scriptp);
}
bool SweepingTracer::onLazyScriptEdge(LazyScript** lazyp) {
  return sweepEdge(lazyp);
}
bool SweepingTracer::onBaseShapeEdge(BaseShape** basep) {
  return sweepEdge(basep);
}
bool SweepingTracer::onJitCodeEdge(jit::JitCode** jitp) {
  return sweepEdge(jitp);
}
bool SweepingTracer::onScopeEdge(Scope** scopep) { return sweepEdge(scopep); }
bool SweepingTracer::onRegExpSharedEdge(RegExpShared** sharedp) {
  return sweepEdge(sharedp);
}
bool SweepingTracer::onObjectGroupEdge(ObjectGroup** groupp) {
  return sweepEdge(groupp);
}
bool SweepingTracer::onBigIntEdge(BigInt** bip) { return sweepEdge(bip); }

namespace js {
namespace gc {

template <typename T>
JS_PUBLIC_API bool EdgeNeedsSweep(JS::Heap<T>* thingp) {
  return IsAboutToBeFinalizedInternal(ConvertToBase(thingp->unsafeGet()));
}

template <typename T>
JS_PUBLIC_API bool EdgeNeedsSweepUnbarrieredSlow(T* thingp) {
  return IsAboutToBeFinalizedInternal(ConvertToBase(thingp));
}

// Instantiate a copy of the Tracing templates for each public GC type.
#define INSTANTIATE_ALL_VALID_HEAP_TRACE_FUNCTIONS(type)             \
  template JS_PUBLIC_API bool EdgeNeedsSweep<type>(JS::Heap<type>*); \
  template JS_PUBLIC_API bool EdgeNeedsSweepUnbarrieredSlow<type>(type*);
FOR_EACH_PUBLIC_GC_POINTER_TYPE(INSTANTIATE_ALL_VALID_HEAP_TRACE_FUNCTIONS)
FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(
    INSTANTIATE_ALL_VALID_HEAP_TRACE_FUNCTIONS)

#define INSTANTIATE_INTERNAL_MARKING_FUNCTIONS(type)               \
  template bool IsMarkedInternal(JSRuntime* rt, type* thing);      \
  template bool IsMarkedBlackInternal(JSRuntime* rt, type* thing); \
  template bool IsAboutToBeFinalizedInternal(type* thingp);

#define INSTANTIATE_INTERNAL_MARKING_FUNCTIONS_FROM_TRACEKIND(_1, type, _2, \
                                                              _3)           \
  INSTANTIATE_INTERNAL_MARKING_FUNCTIONS(type*)

JS_FOR_EACH_TRACEKIND(INSTANTIATE_INTERNAL_MARKING_FUNCTIONS_FROM_TRACEKIND)
FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(INSTANTIATE_INTERNAL_MARKING_FUNCTIONS)

#undef INSTANTIATE_INTERNAL_MARKING_FUNCTIONS_FROM_TRACEKIND
#undef INSTANTIATE_INTERNAL_MARKING_FUNCTIONS

} /* namespace gc */
} /* namespace js */

/*** Cycle Collector Barrier Implementation *********************************/

/*
 * The GC and CC are run independently. Consequently, the following sequence of
 * events can occur:
 * 1. GC runs and marks an object gray.
 * 2. The mutator runs (specifically, some C++ code with access to gray
 *    objects) and creates a pointer from a JS root or other black object to
 *    the gray object. If we re-ran a GC at this point, the object would now be
 *    black.
 * 3. Now we run the CC. It may think it can collect the gray object, even
 *    though it's reachable from the JS heap.
 *
 * To prevent this badness, we unmark the gray bit of an object when it is
 * accessed by callers outside XPConnect. This would cause the object to go
 * black in step 2 above. This must be done on everything reachable from the
 * object being returned. The following code takes care of the recursive
 * re-coloring.
 *
 * There is an additional complication for certain kinds of edges that are not
 * contained explicitly in the source object itself, such as from a weakmap key
 * to its value. These "implicit edges" are represented in some other
 * container object, such as the weakmap itself. In these
 * cases, calling unmark gray on an object won't find all of its children.
 *
 * Handling these implicit edges has two parts:
 * - A special pass enumerating all of the containers that know about the
 *   implicit edges to fix any black-gray edges that have been created. This
 *   is implemented in nsXPConnect::FixWeakMappingGrayBits.
 * - To prevent any incorrectly gray objects from escaping to live JS outside
 *   of the containers, we must add unmark-graying read barriers to these
 *   containers.
 */

#ifdef DEBUG
struct AssertNonGrayTracer final : public JS::CallbackTracer {
  explicit AssertNonGrayTracer(JSRuntime* rt) : JS::CallbackTracer(rt) {}
  bool onChild(const JS::GCCellPtr& thing) override {
    MOZ_ASSERT(!thing.asCell()->isMarkedGray());
    return true;
  }
  // This is used by the UnmarkGray tracer only, and needs to report itself
  // as the non-gray tracer to not trigger assertions.  Do not use it in another
  // context without making this more generic.
  TracerKind getTracerKind() const override { return TracerKind::UnmarkGray; }
};
#endif

class UnmarkGrayTracer final : public JS::CallbackTracer {
 public:
  // We set weakMapAction to DoNotTraceWeakMaps because the cycle collector
  // will fix up any color mismatches involving weakmaps when it runs.
  explicit UnmarkGrayTracer(JSRuntime* rt)
      : JS::CallbackTracer(rt, DoNotTraceWeakMaps),
        unmarkedAny(false),
        oom(false),
        stack(rt->gc.unmarkGrayStack) {}

  void unmark(JS::GCCellPtr cell);

  // Whether we unmarked anything.
  bool unmarkedAny;

  // Whether we ran out of memory.
  bool oom;

 private:
  // Stack of cells to traverse.
  Vector<JS::GCCellPtr, 0, SystemAllocPolicy>& stack;

  bool onChild(const JS::GCCellPtr& thing) override;

#ifdef DEBUG
  TracerKind getTracerKind() const override { return TracerKind::UnmarkGray; }
#endif
};

bool UnmarkGrayTracer::onChild(const JS::GCCellPtr& thing) {
  Cell* cell = thing.asCell();

  // Cells in the nursery cannot be gray, and nor can certain kinds of tenured
  // cells. These must necessarily point only to black edges.
  if (!cell->isTenured() ||
      !TraceKindCanBeMarkedGray(cell->asTenured().getTraceKind())) {
#ifdef DEBUG
    MOZ_ASSERT(!cell->isMarkedGray());
    AssertNonGrayTracer nongray(runtime());
    TraceChildren(&nongray, cell, thing.kind());
#endif
    return true;
  }

  TenuredCell& tenured = cell->asTenured();

  // If the cell is in a zone that we're currently marking, then it's possible
  // that it is currently white but will end up gray. To handle this case, push
  // any cells in zones that are currently being marked onto the mark stack and
  // they will eventually get marked black.
  Zone* zone = tenured.zone();
  if (zone->isGCMarking()) {
    if (!cell->isMarkedBlack()) {
      Cell* tmp = cell;
      JSTracer* trc = &runtime()->gc.marker;
      TraceManuallyBarrieredGenericPointerEdge(trc, &tmp, "read barrier");
      MOZ_ASSERT(tmp == cell);
      unmarkedAny = true;
    }
    return true;
  }

  if (!tenured.isMarkedGray()) {
    return true;
  }

  tenured.markBlack();
  unmarkedAny = true;

  if (!stack.append(thing)) {
    oom = true;
  }
  return true;
}

void UnmarkGrayTracer::unmark(JS::GCCellPtr cell) {
  MOZ_ASSERT(stack.empty());

  onChild(cell);

  while (!stack.empty() && !oom) {
    TraceChildren(this, stack.popCopy());
  }

  if (oom) {
    // If we run out of memory, we take a drastic measure: require that we
    // GC again before the next CC.
    stack.clear();
    runtime()->gc.setGrayBitsInvalid();
    return;
  }
}

static bool UnmarkGrayGCThing(JSRuntime* rt, JS::GCCellPtr thing) {
  MOZ_ASSERT(thing);
  MOZ_ASSERT(thing.asCell()->isMarkedGray());

  // Gray cell unmarking can occur at different points between recording and
  // replay, so disallow recorded events from occurring in the tracer.
  mozilla::recordreplay::AutoDisallowThreadEvents d;

  AutoGeckoProfilerEntry profilingStackFrame(rt->mainContextFromOwnThread(),
                                             "UnmarkGrayGCThing",
                                             JS::ProfilingCategoryPair::GCCC);

  UnmarkGrayTracer unmarker(rt);
  gcstats::AutoPhase innerPhase(rt->gc.stats(),
                                gcstats::PhaseKind::UNMARK_GRAY);
  unmarker.unmark(thing);
  return unmarker.unmarkedAny;
}

JS_FRIEND_API bool JS::UnmarkGrayGCThingRecursively(JS::GCCellPtr thing) {
  MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
  MOZ_ASSERT(!JS::RuntimeHeapIsCycleCollecting());

  JSRuntime* rt = thing.asCell()->runtimeFromMainThread();
  gcstats::AutoPhase outerPhase(rt->gc.stats(), gcstats::PhaseKind::BARRIER);
  return UnmarkGrayGCThing(rt, thing);
}

bool js::UnmarkGrayShapeRecursively(Shape* shape) {
  return JS::UnmarkGrayGCThingRecursively(JS::GCCellPtr(shape));
}

namespace js {
namespace debug {

MarkInfo GetMarkInfo(Cell* rawCell) {
  if (!rawCell->isTenured()) {
    return MarkInfo::NURSERY;
  }

  TenuredCell* cell = &rawCell->asTenured();
  if (cell->isMarkedGray()) {
    return MarkInfo::GRAY;
  }
  if (cell->isMarkedBlack()) {
    return MarkInfo::BLACK;
  }
  return MarkInfo::UNMARKED;
}

uintptr_t* GetMarkWordAddress(Cell* cell) {
  if (!cell->isTenured()) {
    return nullptr;
  }

  uintptr_t* wordp;
  uintptr_t mask;
  js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), ColorBit::BlackBit,
                                            &wordp, &mask);
  return wordp;
}

uintptr_t GetMarkMask(Cell* cell, uint32_t colorBit) {
  MOZ_ASSERT(colorBit == 0 || colorBit == 1);

  if (!cell->isTenured()) {
    return 0;
  }

  ColorBit bit = colorBit == 0 ? ColorBit::BlackBit : ColorBit::GrayOrBlackBit;
  uintptr_t* wordp;
  uintptr_t mask;
  js::gc::detail::GetGCThingMarkWordAndMask(uintptr_t(cell), bit, &wordp,
                                            &mask);
  return mask;
}

}  // namespace debug
}  // namespace js