1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631
|
/*
* Copyright (C) 2019-2022 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WasmAirIRGenerator.h"
#if ENABLE(WEBASSEMBLY_B3JIT)
#include "AirCode.h"
#include "AirGenerate.h"
#include "AirHelpers.h"
#include "AirOpcodeUtils.h"
#include "AllowMacroScratchRegisterUsageIf.h"
#include "B3CheckSpecial.h"
#include "B3CheckValue.h"
#include "B3Commutativity.h"
#include "B3PatchpointSpecial.h"
#include "B3Procedure.h"
#include "B3ProcedureInlines.h"
#include "B3StackmapGenerationParams.h"
#include "BinarySwitch.h"
#include "JSCJSValueInlines.h"
#include "JSWebAssemblyInstance.h"
#include "ScratchRegisterAllocator.h"
#include "WasmBranchHints.h"
#include "WasmCallingConvention.h"
#include "WasmContextInlines.h"
#include "WasmExceptionType.h"
#include "WasmFunctionParser.h"
#include "WasmIRGeneratorHelpers.h"
#include "WasmInstance.h"
#include "WasmMemory.h"
#include "WasmOSREntryData.h"
#include "WasmOpcodeOrigin.h"
#include "WasmOperations.h"
#include "WasmThunks.h"
#include "WasmTypeDefinitionInlines.h"
#include <limits>
#include <wtf/Box.h>
#include <wtf/StdLibExtras.h>
namespace JSC { namespace Wasm {
using namespace B3::Air;
struct ConstrainedTmp {
ConstrainedTmp() = default;
ConstrainedTmp(Tmp tmp)
: ConstrainedTmp(tmp, tmp.isReg() ? B3::ValueRep::reg(tmp.reg()) : B3::ValueRep::SomeRegister)
{ }
ConstrainedTmp(Tmp tmp, B3::ValueRep rep)
: tmp(tmp)
, rep(rep)
{
}
explicit operator bool() const { return !!tmp; }
Tmp tmp;
B3::ValueRep rep;
};
class TypedTmp {
public:
constexpr TypedTmp()
: m_tmp()
, m_type(Types::Void)
{
}
TypedTmp(Tmp tmp, Type type)
: m_tmp(tmp)
, m_type(type)
{ }
TypedTmp(const TypedTmp&) = default;
TypedTmp(TypedTmp&&) = default;
TypedTmp& operator=(TypedTmp&&) = default;
TypedTmp& operator=(const TypedTmp&) = default;
bool operator==(const TypedTmp& other) const
{
return m_tmp == other.m_tmp && m_type == other.m_type;
}
bool operator!=(const TypedTmp& other) const
{
return !(*this == other);
}
explicit operator bool() const { return !!tmp(); }
operator Tmp() const { return tmp(); }
operator Arg() const { return Arg(tmp()); }
Tmp tmp() const { return m_tmp; }
Type type() const { return m_type; }
void dump(PrintStream& out) const
{
out.print("(", m_tmp, ", ", m_type.kind, ", ", m_type.index, ")");
}
private:
Tmp m_tmp;
Type m_type;
};
class AirIRGenerator {
public:
using ExpressionType = TypedTmp;
using ResultList = Vector<ExpressionType, 8>;
struct ControlData {
ControlData(B3::Origin, BlockSignature result, ResultList resultTmps, BlockType type, BasicBlock* continuation, BasicBlock* special = nullptr)
: controlBlockType(type)
, continuation(continuation)
, special(special)
, results(resultTmps)
, returnType(result)
{
}
ControlData(B3::Origin, BlockSignature result, ResultList resultTmps, BlockType type, BasicBlock* continuation, unsigned tryStart, unsigned tryDepth)
: controlBlockType(type)
, continuation(continuation)
, special(nullptr)
, results(resultTmps)
, returnType(result)
, m_tryStart(tryStart)
, m_tryCatchDepth(tryDepth)
{
}
ControlData()
{
}
static bool isIf(const ControlData& control) { return control.blockType() == BlockType::If; }
static bool isTry(const ControlData& control) { return control.blockType() == BlockType::Try; }
static bool isAnyCatch(const ControlData& control) { return control.blockType() == BlockType::Catch; }
static bool isCatch(const ControlData& control) { return isAnyCatch(control) && control.catchKind() == CatchKind::Catch; }
static bool isTopLevel(const ControlData& control) { return control.blockType() == BlockType::TopLevel; }
static bool isLoop(const ControlData& control) { return control.blockType() == BlockType::Loop; }
static bool isBlock(const ControlData& control) { return control.blockType() == BlockType::Block; }
void dump(PrintStream& out) const
{
switch (blockType()) {
case BlockType::If:
out.print("If: ");
break;
case BlockType::Block:
out.print("Block: ");
break;
case BlockType::Loop:
out.print("Loop: ");
break;
case BlockType::TopLevel:
out.print("TopLevel: ");
break;
case BlockType::Try:
out.print("Try: ");
break;
case BlockType::Catch:
out.print("Catch: ");
break;
}
out.print("Continuation: ", *continuation, ", Special: ");
if (special)
out.print(*special);
else
out.print("None");
CommaPrinter comma(", ", " Result Tmps: [");
for (const auto& tmp : results)
out.print(comma, tmp);
if (comma.didPrint())
out.print("]");
}
BlockType blockType() const { return controlBlockType; }
BlockSignature signature() const { return returnType; }
BasicBlock* targetBlockForBranch()
{
if (blockType() == BlockType::Loop)
return special;
return continuation;
}
void convertIfToBlock()
{
ASSERT(blockType() == BlockType::If);
controlBlockType = BlockType::Block;
special = nullptr;
}
FunctionArgCount branchTargetArity() const
{
if (blockType() == BlockType::Loop)
return returnType->as<FunctionSignature>()->argumentCount();
return returnType->as<FunctionSignature>()->returnCount();
}
Type branchTargetType(unsigned i) const
{
ASSERT(i < branchTargetArity());
if (blockType() == BlockType::Loop)
return returnType->as<FunctionSignature>()->argumentType(i);
return returnType->as<FunctionSignature>()->returnType(i);
}
void convertTryToCatch(unsigned tryEndCallSiteIndex, TypedTmp exception)
{
ASSERT(blockType() == BlockType::Try);
controlBlockType = BlockType::Catch;
m_catchKind = CatchKind::Catch;
m_tryEnd = tryEndCallSiteIndex;
m_exception = exception;
}
void convertTryToCatchAll(unsigned tryEndCallSiteIndex, TypedTmp exception)
{
ASSERT(blockType() == BlockType::Try);
controlBlockType = BlockType::Catch;
m_catchKind = CatchKind::CatchAll;
m_tryEnd = tryEndCallSiteIndex;
m_exception = exception;
}
unsigned tryStart() const
{
ASSERT(controlBlockType == BlockType::Try || controlBlockType == BlockType::Catch);
return m_tryStart;
}
unsigned tryEnd() const
{
ASSERT(controlBlockType == BlockType::Catch);
return m_tryEnd;
}
unsigned tryDepth() const
{
ASSERT(controlBlockType == BlockType::Try || controlBlockType == BlockType::Catch);
return m_tryCatchDepth;
}
CatchKind catchKind() const
{
ASSERT(controlBlockType == BlockType::Catch);
return m_catchKind;
}
TypedTmp exception() const
{
ASSERT(controlBlockType == BlockType::Catch);
return m_exception;
}
private:
friend class AirIRGenerator;
BlockType controlBlockType;
BasicBlock* continuation;
BasicBlock* special;
ResultList results;
BlockSignature returnType;
unsigned m_tryStart;
unsigned m_tryEnd;
unsigned m_tryCatchDepth;
CatchKind m_catchKind;
TypedTmp m_exception;
};
using ControlType = ControlData;
using ControlEntry = FunctionParser<AirIRGenerator>::ControlEntry;
using ControlStack = FunctionParser<AirIRGenerator>::ControlStack;
using Stack = FunctionParser<AirIRGenerator>::Stack;
using TypedExpression = FunctionParser<AirIRGenerator>::TypedExpression;
using ErrorType = String;
using UnexpectedResult = Unexpected<ErrorType>;
using Result = Expected<std::unique_ptr<InternalFunction>, ErrorType>;
using PartialResult = Expected<void, ErrorType>;
static_assert(std::is_same_v<ResultList, FunctionParser<AirIRGenerator>::ResultList>);
static ExpressionType emptyExpression() { return { }; };
template <typename ...Args>
NEVER_INLINE UnexpectedResult WARN_UNUSED_RETURN fail(Args... args) const
{
using namespace FailureHelper; // See ADL comment in WasmParser.h.
return UnexpectedResult(makeString("WebAssembly.Module failed compiling: "_s, makeString(args)...));
}
#define WASM_COMPILE_FAIL_IF(condition, ...) do { \
if (UNLIKELY(condition)) \
return fail(__VA_ARGS__); \
} while (0)
AirIRGenerator(const ModuleInformation&, B3::Procedure&, InternalFunction*, Vector<UnlinkedWasmToWasmCall>&, MemoryMode, unsigned functionIndex, std::optional<bool> hasExceptionHandlers, TierUpCount*, const TypeDefinition&, unsigned& osrEntryScratchBufferSize);
void finalizeEntrypoints();
PartialResult WARN_UNUSED_RETURN addArguments(const TypeDefinition&);
PartialResult WARN_UNUSED_RETURN addLocal(Type, uint32_t);
ExpressionType addConstant(Type, uint64_t);
ExpressionType addConstant(BasicBlock*, Type, uint64_t);
ExpressionType addBottom(BasicBlock*, Type);
// References
PartialResult WARN_UNUSED_RETURN addRefIsNull(ExpressionType value, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addRefFunc(uint32_t index, ExpressionType& result);
// Tables
PartialResult WARN_UNUSED_RETURN addTableGet(unsigned, ExpressionType index, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addTableSet(unsigned, ExpressionType index, ExpressionType value);
PartialResult WARN_UNUSED_RETURN addTableInit(unsigned, unsigned, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length);
PartialResult WARN_UNUSED_RETURN addElemDrop(unsigned);
PartialResult WARN_UNUSED_RETURN addTableSize(unsigned, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addTableGrow(unsigned, ExpressionType fill, ExpressionType delta, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addTableFill(unsigned, ExpressionType offset, ExpressionType fill, ExpressionType count);
PartialResult WARN_UNUSED_RETURN addTableCopy(unsigned, unsigned, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length);
// Locals
PartialResult WARN_UNUSED_RETURN getLocal(uint32_t index, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN setLocal(uint32_t index, ExpressionType value);
// Globals
PartialResult WARN_UNUSED_RETURN getGlobal(uint32_t index, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN setGlobal(uint32_t index, ExpressionType value);
// Memory
PartialResult WARN_UNUSED_RETURN load(LoadOpType, ExpressionType pointer, ExpressionType& result, uint32_t offset);
PartialResult WARN_UNUSED_RETURN store(StoreOpType, ExpressionType pointer, ExpressionType value, uint32_t offset);
PartialResult WARN_UNUSED_RETURN addGrowMemory(ExpressionType delta, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addCurrentMemory(ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addMemoryFill(ExpressionType dstAddress, ExpressionType targetValue, ExpressionType count);
PartialResult WARN_UNUSED_RETURN addMemoryCopy(ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType count);
PartialResult WARN_UNUSED_RETURN addMemoryInit(unsigned, ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType length);
PartialResult WARN_UNUSED_RETURN addDataDrop(unsigned);
// Atomics
PartialResult WARN_UNUSED_RETURN atomicLoad(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType& result, uint32_t offset);
PartialResult WARN_UNUSED_RETURN atomicStore(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType value, uint32_t offset);
PartialResult WARN_UNUSED_RETURN atomicBinaryRMW(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType value, ExpressionType& result, uint32_t offset);
PartialResult WARN_UNUSED_RETURN atomicCompareExchange(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType expected, ExpressionType value, ExpressionType& result, uint32_t offset);
PartialResult WARN_UNUSED_RETURN atomicWait(ExtAtomicOpType, ExpressionType pointer, ExpressionType value, ExpressionType timeout, ExpressionType& result, uint32_t offset);
PartialResult WARN_UNUSED_RETURN atomicNotify(ExtAtomicOpType, ExpressionType pointer, ExpressionType value, ExpressionType& result, uint32_t offset);
PartialResult WARN_UNUSED_RETURN atomicFence(ExtAtomicOpType, uint8_t flags);
// Saturated truncation.
PartialResult WARN_UNUSED_RETURN truncSaturated(Ext1OpType, ExpressionType operand, ExpressionType& result, Type returnType, Type operandType);
// GC
PartialResult WARN_UNUSED_RETURN addI31New(ExpressionType value, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addI31GetS(ExpressionType ref, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addI31GetU(ExpressionType ref, ExpressionType& result);
// Basic operators
template<OpType>
PartialResult WARN_UNUSED_RETURN addOp(ExpressionType arg, ExpressionType& result);
template<OpType>
PartialResult WARN_UNUSED_RETURN addOp(ExpressionType left, ExpressionType right, ExpressionType& result);
PartialResult WARN_UNUSED_RETURN addSelect(ExpressionType condition, ExpressionType nonZero, ExpressionType zero, ExpressionType& result);
// Control flow
ControlData WARN_UNUSED_RETURN addTopLevel(BlockSignature);
PartialResult WARN_UNUSED_RETURN addBlock(BlockSignature, Stack& enclosingStack, ControlType& newBlock, Stack& newStack);
PartialResult WARN_UNUSED_RETURN addLoop(BlockSignature, Stack& enclosingStack, ControlType& block, Stack& newStack, uint32_t loopIndex);
PartialResult WARN_UNUSED_RETURN addIf(ExpressionType condition, BlockSignature, Stack& enclosingStack, ControlType& result, Stack& newStack);
PartialResult WARN_UNUSED_RETURN addElse(ControlData&, const Stack&);
PartialResult WARN_UNUSED_RETURN addElseToUnreachable(ControlData&);
PartialResult WARN_UNUSED_RETURN addTry(BlockSignature, Stack& enclosingStack, ControlType& result, Stack& newStack);
PartialResult WARN_UNUSED_RETURN addCatch(unsigned exceptionIndex, const TypeDefinition&, Stack&, ControlType&, ResultList&);
PartialResult WARN_UNUSED_RETURN addCatchToUnreachable(unsigned exceptionIndex, const TypeDefinition&, ControlType&, ResultList&);
PartialResult WARN_UNUSED_RETURN addCatchAll(Stack&, ControlType&);
PartialResult WARN_UNUSED_RETURN addCatchAllToUnreachable(ControlType&);
PartialResult WARN_UNUSED_RETURN addDelegate(ControlType&, ControlType&);
PartialResult WARN_UNUSED_RETURN addDelegateToUnreachable(ControlType&, ControlType&);
PartialResult WARN_UNUSED_RETURN addThrow(unsigned exceptionIndex, Vector<ExpressionType>& args, Stack&);
PartialResult WARN_UNUSED_RETURN addRethrow(unsigned, ControlType&);
PartialResult WARN_UNUSED_RETURN addReturn(const ControlData&, const Stack& returnValues);
PartialResult WARN_UNUSED_RETURN addBranch(ControlData&, ExpressionType condition, const Stack& returnValues);
PartialResult WARN_UNUSED_RETURN addSwitch(ExpressionType condition, const Vector<ControlData*>& targets, ControlData& defaultTargets, const Stack& expressionStack);
PartialResult WARN_UNUSED_RETURN endBlock(ControlEntry&, Stack& expressionStack);
PartialResult WARN_UNUSED_RETURN addEndToUnreachable(ControlEntry&, const Stack& expressionStack = { });
PartialResult WARN_UNUSED_RETURN endTopLevel(BlockSignature, const Stack&) { return { }; }
// Calls
PartialResult WARN_UNUSED_RETURN addCall(uint32_t calleeIndex, const TypeDefinition&, Vector<ExpressionType>& args, ResultList& results);
PartialResult WARN_UNUSED_RETURN addCallIndirect(unsigned tableIndex, const TypeDefinition&, Vector<ExpressionType>& args, ResultList& results);
PartialResult WARN_UNUSED_RETURN addCallRef(const TypeDefinition&, Vector<ExpressionType>& args, ResultList& results);
PartialResult WARN_UNUSED_RETURN addUnreachable();
PartialResult WARN_UNUSED_RETURN emitIndirectCall(TypedTmp calleeInstance, ExpressionType calleeCode, const TypeDefinition&, const Vector<ExpressionType>& args, ResultList&);
std::pair<B3::PatchpointValue*, PatchpointExceptionHandle> WARN_UNUSED_RETURN emitCallPatchpoint(BasicBlock*, const TypeDefinition&, const ResultList& results, const Vector<TypedTmp>& args, Vector<ConstrainedTmp> extraArgs = { });
PartialResult addShift(Type, B3::Air::Opcode, ExpressionType value, ExpressionType shift, ExpressionType& result);
PartialResult addIntegerSub(B3::Air::Opcode, ExpressionType lhs, ExpressionType rhs, ExpressionType& result);
PartialResult addFloatingPointAbs(B3::Air::Opcode, ExpressionType value, ExpressionType& result);
PartialResult addFloatingPointBinOp(Type, B3::Air::Opcode, ExpressionType lhs, ExpressionType rhs, ExpressionType& result);
void dump(const ControlStack&, const Stack* expressionStack);
void setParser(FunctionParser<AirIRGenerator>* parser) { m_parser = parser; };
void didFinishParsingLocals() { }
void didPopValueFromStack() { }
Tmp emitCatchImpl(CatchKind, ControlType&, unsigned exceptionIndex = 0);
template <size_t inlineCapacity>
PatchpointExceptionHandle preparePatchpointForExceptions(B3::PatchpointValue*, Vector<ConstrainedTmp, inlineCapacity>& args);
const Bag<B3::PatchpointValue*>& patchpoints() const
{
return m_patchpoints;
}
void addStackMap(unsigned callSiteIndex, StackMap&& stackmap)
{
m_stackmaps.add(CallSiteIndex(callSiteIndex), WTFMove(stackmap));
}
StackMaps&& takeStackmaps()
{
return WTFMove(m_stackmaps);
}
Vector<UnlinkedHandlerInfo>&& takeExceptionHandlers()
{
return WTFMove(m_exceptionHandlers);
}
private:
B3::Type toB3ResultType(BlockSignature returnType);
ALWAYS_INLINE void validateInst(Inst& inst)
{
if (ASSERT_ENABLED) {
if (!inst.isValidForm()) {
dataLogLn("Inst validation failed:");
dataLogLn(inst, "\n");
if (inst.origin)
dataLogLn(deepDump(inst.origin), "\n");
CRASH();
}
}
}
static Arg extractArg(const TypedTmp& tmp) { return tmp.tmp(); }
static Arg extractArg(const Tmp& tmp) { return Arg(tmp); }
static Arg extractArg(const Arg& arg) { return arg; }
template<typename... Arguments>
void append(BasicBlock* block, Kind kind, Arguments&&... arguments)
{
// FIXME: Find a way to use origin here.
auto& inst = block->append(kind, nullptr, extractArg(arguments)...);
validateInst(inst);
}
template<typename... Arguments>
void append(Kind kind, Arguments&&... arguments)
{
append(m_currentBlock, kind, std::forward<Arguments>(arguments)...);
}
template<typename... Arguments>
void appendEffectful(B3::Air::Opcode op, Arguments&&... arguments)
{
Kind kind = op;
kind.effects = true;
append(m_currentBlock, kind, std::forward<Arguments>(arguments)...);
}
template<typename... Arguments>
void appendEffectful(BasicBlock* block, B3::Air::Opcode op, Arguments&&... arguments)
{
Kind kind = op;
kind.effects = true;
append(block, kind, std::forward<Arguments>(arguments)...);
}
Tmp newTmp(B3::Bank bank)
{
return m_code.newTmp(bank);
}
TypedTmp g32() { return { newTmp(B3::GP), Types::I32 }; }
TypedTmp g64() { return { newTmp(B3::GP), Types::I64 }; }
TypedTmp gExternref() { return { newTmp(B3::GP), Types::Externref }; }
TypedTmp gFuncref() { return { newTmp(B3::GP), Types::Funcref }; }
TypedTmp gRef(Type type) { return { newTmp(B3::GP), type }; }
TypedTmp f32() { return { newTmp(B3::FP), Types::F32 }; }
TypedTmp f64() { return { newTmp(B3::FP), Types::F64 }; }
TypedTmp tmpForType(Type type)
{
switch (type.kind) {
case TypeKind::I32:
return g32();
case TypeKind::I64:
return g64();
case TypeKind::Funcref:
return gFuncref();
case TypeKind::Ref:
case TypeKind::RefNull:
return gRef(type);
case TypeKind::Externref:
return gExternref();
case TypeKind::F32:
return f32();
case TypeKind::F64:
return f64();
case TypeKind::Void:
return { };
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
ResultList tmpsForSignature(BlockSignature signature)
{
ResultList result(signature->as<FunctionSignature>()->returnCount());
for (unsigned i = 0; i < signature->as<FunctionSignature>()->returnCount(); ++i)
result[i] = tmpForType(signature->as<FunctionSignature>()->returnType(i));
return result;
}
B3::PatchpointValue* addPatchpoint(B3::Type type)
{
auto* result = m_proc.add<B3::PatchpointValue>(type, B3::Origin());
if (UNLIKELY(shouldDumpIRAtEachPhase(B3::AirMode)))
m_patchpoints.add(result);
return result;
}
template <typename ...Args>
void emitPatchpoint(B3::PatchpointValue* patch, Tmp result, Args... theArgs)
{
emitPatchpoint(m_currentBlock, patch, result, std::forward<Args>(theArgs)...);
}
template <typename ...Args>
void emitPatchpoint(BasicBlock* basicBlock, B3::PatchpointValue* patch, Tmp result, Args... theArgs)
{
emitPatchpoint(basicBlock, patch, Vector<Tmp, 8> { result }, Vector<ConstrainedTmp, sizeof...(Args)>::from(theArgs...));
}
void emitPatchpoint(BasicBlock* basicBlock, B3::PatchpointValue* patch, Tmp result)
{
emitPatchpoint(basicBlock, patch, Vector<Tmp, 8> { result }, Vector<ConstrainedTmp>());
}
template <size_t inlineSize>
void emitPatchpoint(BasicBlock* basicBlock, B3::PatchpointValue* patch, Tmp result, Vector<ConstrainedTmp, inlineSize>&& args)
{
emitPatchpoint(basicBlock, patch, Vector<Tmp, 8> { result }, WTFMove(args));
}
template <typename ResultTmpType, size_t inlineSize>
void emitPatchpoint(BasicBlock* basicBlock, B3::PatchpointValue* patch, const Vector<ResultTmpType, 8>& results, Vector<ConstrainedTmp, inlineSize>&& args)
{
if (!m_patchpointSpecial)
m_patchpointSpecial = static_cast<B3::PatchpointSpecial*>(m_code.addSpecial(makeUnique<B3::PatchpointSpecial>()));
auto toTmp = [&] (ResultTmpType tmp) {
if constexpr (std::is_same_v<ResultTmpType, Tmp>)
return tmp;
else
return tmp.tmp();
};
Inst inst(Patch, patch, Arg::special(m_patchpointSpecial));
Vector<Inst, 1> resultMovs;
switch (patch->type().kind()) {
case B3::Void:
break;
default: {
ASSERT(results.size());
for (unsigned i = 0; i < results.size(); ++i) {
switch (patch->resultConstraints[i].kind()) {
case B3::ValueRep::StackArgument: {
Arg arg = Arg::callArg(patch->resultConstraints[i].offsetFromSP());
inst.args.append(arg);
resultMovs.append(Inst(B3::Air::moveForType(m_proc.typeAtOffset(patch->type(), i)), nullptr, arg, toTmp(results[i])));
break;
}
case B3::ValueRep::Register: {
inst.args.append(Tmp(patch->resultConstraints[i].reg()));
resultMovs.append(Inst(B3::Air::relaxedMoveForType(m_proc.typeAtOffset(patch->type(), i)), nullptr, Tmp(patch->resultConstraints[i].reg()), toTmp(results[i])));
break;
}
case B3::ValueRep::SomeRegister: {
inst.args.append(toTmp(results[i]));
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
}
}
for (unsigned i = 0; i < args.size(); ++i) {
ConstrainedTmp& tmp = args[i];
// FIXME: This is less than ideal to create dummy values just to satisfy Air's
// validation. We should abstrcat Patch enough so ValueRep's don't need to be
// backed by Values.
// https://bugs.webkit.org/show_bug.cgi?id=194040
B3::Value* dummyValue = m_proc.addConstant(B3::Origin(), tmp.tmp.isGP() ? B3::Int64 : B3::Double, 0);
patch->append(dummyValue, tmp.rep);
switch (tmp.rep.kind()) {
// B3::Value propagates (Late)ColdAny information and later Air will allocate appropriate stack.
case B3::ValueRep::ColdAny:
case B3::ValueRep::LateColdAny:
case B3::ValueRep::SomeRegister:
inst.args.append(tmp.tmp);
break;
case B3::ValueRep::Register:
patch->earlyClobbered().clear(tmp.rep.reg());
append(basicBlock, tmp.tmp.isGP() ? Move : MoveDouble, tmp.tmp, tmp.rep.reg());
inst.args.append(Tmp(tmp.rep.reg()));
break;
case B3::ValueRep::StackArgument: {
Arg arg = Arg::callArg(tmp.rep.offsetFromSP());
append(basicBlock, tmp.tmp.isGP() ? Move : MoveDouble, tmp.tmp, arg);
ASSERT(arg.canRepresent(patch->child(i)->type()));
inst.args.append(arg);
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
for (auto valueRep : patch->resultConstraints) {
if (valueRep.isReg())
patch->lateClobbered().clear(valueRep.reg());
}
for (unsigned i = patch->numGPScratchRegisters; i--;)
inst.args.append(g64().tmp());
for (unsigned i = patch->numFPScratchRegisters; i--;)
inst.args.append(f64().tmp());
validateInst(inst);
basicBlock->append(WTFMove(inst));
for (Inst result : resultMovs) {
validateInst(result);
basicBlock->append(WTFMove(result));
}
}
template <typename Branch, typename Generator>
void emitCheck(const Branch& makeBranch, const Generator& generator)
{
// We fail along the truthy edge of 'branch'.
Inst branch = makeBranch();
// FIXME: Make a hashmap of these.
B3::CheckSpecial::Key key(branch);
B3::CheckSpecial* special = static_cast<B3::CheckSpecial*>(m_code.addSpecial(makeUnique<B3::CheckSpecial>(key)));
// FIXME: Remove the need for dummy values
// https://bugs.webkit.org/show_bug.cgi?id=194040
B3::Value* dummyPredicate = m_proc.addConstant(B3::Origin(), B3::Int32, 42);
B3::CheckValue* checkValue = m_proc.add<B3::CheckValue>(B3::Check, B3::Origin(), dummyPredicate);
checkValue->setGenerator(generator);
Inst inst(Patch, checkValue, Arg::special(special));
inst.args.appendVector(branch.args);
m_currentBlock->append(WTFMove(inst));
}
template <typename Func, typename ...Args>
void emitCCall(Func func, TypedTmp result, Args... args)
{
emitCCall(m_currentBlock, func, result, std::forward<Args>(args)...);
}
template <typename Func, typename ...Args>
void emitCCall(BasicBlock* block, Func func, TypedTmp result, Args... theArgs)
{
B3::Type resultType = B3::Void;
if (result) {
switch (result.type().kind) {
case TypeKind::I32:
resultType = B3::Int32;
break;
case TypeKind::I64:
case TypeKind::Externref:
case TypeKind::Funcref:
case TypeKind::Ref:
case TypeKind::RefNull:
resultType = B3::Int64;
break;
case TypeKind::F32:
resultType = B3::Float;
break;
case TypeKind::F64:
resultType = B3::Double;
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
auto makeDummyValue = [&] (Tmp tmp) {
// FIXME: This is less than ideal to create dummy values just to satisfy Air's
// validation. We should abstrcat CCall enough so we're not reliant on arguments
// to the B3::CCallValue.
// https://bugs.webkit.org/show_bug.cgi?id=194040
if (tmp.isGP())
return m_proc.addConstant(B3::Origin(), B3::Int64, 0);
return m_proc.addConstant(B3::Origin(), B3::Double, 0);
};
B3::Value* dummyFunc = m_proc.addConstant(B3::Origin(), B3::Int64, bitwise_cast<uintptr_t>(func));
B3::Value* origin = m_proc.add<B3::CCallValue>(resultType, B3::Origin(), B3::Effects::none(), dummyFunc, makeDummyValue(theArgs)...);
Inst inst(CCall, origin);
Tmp callee = g64();
append(block, Move, Arg::immPtr(tagCFunctionPtr<void*, OperationPtrTag>(func)), callee);
inst.args.append(callee);
if (result)
inst.args.append(result.tmp());
for (Tmp tmp : Vector<Tmp, sizeof...(Args)>::from(theArgs.tmp()...))
inst.args.append(tmp);
block->append(WTFMove(inst));
}
static B3::Air::Opcode moveOpForValueType(Type type)
{
switch (type.kind) {
case TypeKind::I32:
return Move32;
case TypeKind::I64:
case TypeKind::Externref:
case TypeKind::Funcref:
case TypeKind::Ref:
case TypeKind::RefNull:
return Move;
case TypeKind::F32:
return MoveFloat;
case TypeKind::F64:
return MoveDouble;
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
void emitLoad(B3::Air::Opcode op, B3::Type type, Tmp base, size_t offset, Tmp result)
{
if (Arg::isValidAddrForm(offset, B3::widthForType(type)))
append(op, Arg::addr(base, offset), result);
else {
auto temp2 = g64();
append(Move, Arg::bigImm(offset), temp2);
append(Add64, temp2, base, temp2);
append(op, Arg::addr(temp2), result);
}
}
void emitLoad(Tmp base, size_t offset, const TypedTmp& result)
{
emitLoad(moveOpForValueType(result.type()), toB3Type(result.type()), base, offset, result.tmp());
}
void emitThrowException(CCallHelpers&, ExceptionType);
void emitEntryTierUpCheck();
void emitLoopTierUpCheck(uint32_t loopIndex, const Vector<TypedTmp>& liveValues);
void emitWriteBarrierForJSWrapper();
ExpressionType emitCheckAndPreparePointer(ExpressionType pointer, uint32_t offset, uint32_t sizeOfOp);
ExpressionType emitLoadOp(LoadOpType, ExpressionType pointer, uint32_t offset);
void emitStoreOp(StoreOpType, ExpressionType pointer, ExpressionType value, uint32_t offset);
ExpressionType emitAtomicLoadOp(ExtAtomicOpType, Type, ExpressionType pointer, uint32_t offset);
void emitAtomicStoreOp(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType value, uint32_t offset);
ExpressionType emitAtomicBinaryRMWOp(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType value, uint32_t offset);
ExpressionType emitAtomicCompareExchange(ExtAtomicOpType, Type, ExpressionType pointer, ExpressionType expected, ExpressionType value, uint32_t offset);
void sanitizeAtomicResult(ExtAtomicOpType, Type, Tmp source, Tmp dest);
void sanitizeAtomicResult(ExtAtomicOpType, Type, Tmp result);
TypedTmp appendGeneralAtomic(ExtAtomicOpType, B3::Air::Opcode nonAtomicOpcode, B3::Commutativity, Arg input, Arg addrArg, TypedTmp result);
TypedTmp appendStrongCAS(ExtAtomicOpType, TypedTmp expected, TypedTmp value, Arg addrArg, TypedTmp result);
void unify(const ExpressionType dst, const ExpressionType source);
void unifyValuesWithBlock(const Stack& resultStack, const ResultList& stack);
template <typename IntType>
void emitChecksForModOrDiv(bool isSignedDiv, ExpressionType left, ExpressionType right);
template <typename IntType>
void emitModOrDiv(bool isDiv, ExpressionType lhs, ExpressionType rhs, ExpressionType& result);
enum class MinOrMax { Min, Max };
PartialResult addFloatingPointMinOrMax(Type, MinOrMax, ExpressionType lhs, ExpressionType rhs, ExpressionType& result);
int32_t WARN_UNUSED_RETURN fixupPointerPlusOffset(ExpressionType&, uint32_t);
ExpressionType WARN_UNUSED_RETURN fixupPointerPlusOffsetForAtomicOps(ExtAtomicOpType, ExpressionType, uint32_t);
void restoreWasmContextInstance(BasicBlock*, TypedTmp);
enum class RestoreCachedStackLimit { No, Yes };
void restoreWebAssemblyGlobalState(RestoreCachedStackLimit, const MemoryInformation&, TypedTmp instance, BasicBlock*);
B3::Origin origin();
uint32_t outerLoopIndex() const
{
if (m_outerLoops.isEmpty())
return UINT32_MAX;
return m_outerLoops.last();
}
template <typename Function>
void forEachLiveValue(Function);
bool useSignalingMemory() const
{
#if ENABLE(WEBASSEMBLY_SIGNALING_MEMORY)
return m_mode == MemoryMode::Signaling;
#else
return false;
#endif
}
FunctionParser<AirIRGenerator>* m_parser { nullptr };
const ModuleInformation& m_info;
const MemoryMode m_mode { MemoryMode::BoundsChecking };
const unsigned m_functionIndex { UINT_MAX };
TierUpCount* m_tierUp { nullptr };
B3::Procedure& m_proc;
Code& m_code;
Vector<uint32_t> m_outerLoops;
BasicBlock* m_currentBlock { nullptr };
BasicBlock* m_rootBlock { nullptr };
BasicBlock* m_mainEntrypointStart { nullptr };
Vector<TypedTmp> m_locals;
Vector<UnlinkedWasmToWasmCall>& m_unlinkedWasmToWasmCalls; // List each call site and the function index whose address it should be patched with.
GPRReg m_memoryBaseGPR { InvalidGPRReg };
GPRReg m_boundsCheckingSizeGPR { InvalidGPRReg };
GPRReg m_wasmContextInstanceGPR { InvalidGPRReg };
GPRReg m_prologueWasmContextGPR { InvalidGPRReg };
bool m_makesCalls { false };
std::optional<bool> m_hasExceptionHandlers;
HashMap<BlockSignature, B3::Type> m_tupleMap;
// This is only filled if we are dumping IR.
Bag<B3::PatchpointValue*> m_patchpoints;
TypedTmp m_instanceValue; // Always use the accessor below to ensure the instance value is materialized when used.
bool m_usesInstanceValue { false };
TypedTmp instanceValue()
{
m_usesInstanceValue = true;
return m_instanceValue;
}
uint32_t m_maxNumJSCallArguments { 0 };
unsigned m_numImportFunctions;
B3::PatchpointSpecial* m_patchpointSpecial { nullptr };
RefPtr<B3::Air::PrologueGenerator> m_prologueGenerator;
Vector<BasicBlock*> m_catchEntrypoints;
Checked<unsigned> m_tryCatchDepth { 0 };
Checked<unsigned> m_callSiteIndex { 0 };
StackMaps m_stackmaps;
Vector<UnlinkedHandlerInfo> m_exceptionHandlers;
Vector<std::pair<BasicBlock*, Vector<TypedTmp>>> m_loopEntryVariableData;
unsigned& m_osrEntryScratchBufferSize;
};
// Memory accesses in WebAssembly have unsigned 32-bit offsets, whereas they have signed 32-bit offsets in B3.
int32_t AirIRGenerator::fixupPointerPlusOffset(ExpressionType& ptr, uint32_t offset)
{
if (static_cast<uint64_t>(offset) > static_cast<uint64_t>(std::numeric_limits<int32_t>::max())) {
auto previousPtr = ptr;
ptr = g64();
auto constant = g64();
append(Move, Arg::bigImm(offset), constant);
append(Add64, constant, previousPtr, ptr);
return 0;
}
return offset;
}
void AirIRGenerator::restoreWasmContextInstance(BasicBlock* block, TypedTmp instance)
{
if (Context::useFastTLS()) {
auto* patchpoint = addPatchpoint(B3::Void);
if (CCallHelpers::storeWasmContextInstanceNeedsMacroScratchRegister())
patchpoint->clobber(RegisterSet::macroScratchRegisters());
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsageIf allowScratch(jit, CCallHelpers::storeWasmContextInstanceNeedsMacroScratchRegister());
jit.storeWasmContextInstance(params[0].gpr());
});
emitPatchpoint(block, patchpoint, Tmp(), instance);
return;
}
// FIXME: Because WasmToWasm call clobbers wasmContextInstance register and does not restore it, we need to restore it in the caller side.
// This prevents us from using ArgumentReg to this (logically) immutable pinned register.
auto* patchpoint = addPatchpoint(B3::Void);
B3::Effects effects = B3::Effects::none();
effects.writesPinned = true;
effects.reads = B3::HeapRange::top();
patchpoint->effects = effects;
patchpoint->clobberLate(RegisterSet(m_wasmContextInstanceGPR));
GPRReg wasmContextInstanceGPR = m_wasmContextInstanceGPR;
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& param) {
jit.move(param[0].gpr(), wasmContextInstanceGPR);
});
emitPatchpoint(block, patchpoint, Tmp(), instance);
}
AirIRGenerator::AirIRGenerator(const ModuleInformation& info, B3::Procedure& procedure, InternalFunction* compilation, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, MemoryMode mode, unsigned functionIndex, std::optional<bool> hasExceptionHandlers, TierUpCount* tierUp, const TypeDefinition& signature, unsigned& osrEntryScratchBufferSize)
: m_info(info)
, m_mode(mode)
, m_functionIndex(functionIndex)
, m_tierUp(tierUp)
, m_proc(procedure)
, m_code(m_proc.code())
, m_unlinkedWasmToWasmCalls(unlinkedWasmToWasmCalls)
, m_hasExceptionHandlers(hasExceptionHandlers)
, m_numImportFunctions(info.importFunctionCount())
, m_osrEntryScratchBufferSize(osrEntryScratchBufferSize)
{
m_currentBlock = m_code.addBlock();
m_rootBlock = m_currentBlock;
// FIXME we don't really need to pin registers here if there's no memory. It makes wasm -> wasm thunks simpler for now. https://bugs.webkit.org/show_bug.cgi?id=166623
const PinnedRegisterInfo& pinnedRegs = PinnedRegisterInfo::get();
m_memoryBaseGPR = pinnedRegs.baseMemoryPointer;
m_code.pinRegister(m_memoryBaseGPR);
m_wasmContextInstanceGPR = pinnedRegs.wasmContextInstancePointer;
if (!Context::useFastTLS())
m_code.pinRegister(m_wasmContextInstanceGPR);
if (mode == MemoryMode::BoundsChecking) {
m_boundsCheckingSizeGPR = pinnedRegs.boundsCheckingSizeRegister;
m_code.pinRegister(m_boundsCheckingSizeGPR);
}
m_prologueWasmContextGPR = Context::useFastTLS() ? wasmCallingConvention().prologueScratchGPRs[1] : m_wasmContextInstanceGPR;
m_prologueGenerator = createSharedTask<B3::Air::PrologueGeneratorFunction>([=, this] (CCallHelpers& jit, B3::Air::Code& code) {
AllowMacroScratchRegisterUsage allowScratch(jit);
code.emitDefaultPrologue(jit);
{
GPRReg calleeGPR = wasmCallingConvention().prologueScratchGPRs[0];
auto moveLocation = jit.moveWithPatch(MacroAssembler::TrustedImmPtr(nullptr), calleeGPR);
jit.addLinkTask([compilation, moveLocation] (LinkBuffer& linkBuffer) {
compilation->calleeMoveLocations.append(linkBuffer.locationOf<WasmEntryPtrTag>(moveLocation));
});
jit.emitPutToCallFrameHeader(calleeGPR, CallFrameSlot::callee);
jit.emitPutToCallFrameHeader(nullptr, CallFrameSlot::codeBlock);
}
{
const Checked<int32_t> wasmFrameSize = m_code.frameSize();
const unsigned minimumParentCheckSize = WTF::roundUpToMultipleOf(stackAlignmentBytes(), 1024);
const unsigned extraFrameSize = WTF::roundUpToMultipleOf(stackAlignmentBytes(), std::max<uint32_t>(
// This allows us to elide stack checks for functions that are terminal nodes in the call
// tree, (e.g they don't make any calls) and have a small enough frame size. This works by
// having any such terminal node have its parent caller include some extra size in its
// own check for it. The goal here is twofold:
// 1. Emit less code.
// 2. Try to speed things up by skipping stack checks.
minimumParentCheckSize,
// This allows us to elide stack checks in the Wasm -> Embedder call IC stub. Since these will
// spill all arguments to the stack, we ensure that a stack check here covers the
// stack that such a stub would use.
Checked<uint32_t>(m_maxNumJSCallArguments) * sizeof(Register) + jsCallingConvention().headerSizeInBytes
));
const int32_t checkSize = m_makesCalls ? (wasmFrameSize + extraFrameSize).value() : wasmFrameSize.value();
bool needUnderflowCheck = static_cast<unsigned>(checkSize) > Options::reservedZoneSize();
bool needsOverflowCheck = m_makesCalls || wasmFrameSize >= static_cast<int32_t>(minimumParentCheckSize) || needUnderflowCheck;
bool mayHaveExceptionHandlers = !m_hasExceptionHandlers || m_hasExceptionHandlers.value();
if ((needsOverflowCheck || m_usesInstanceValue || mayHaveExceptionHandlers) && Context::useFastTLS())
jit.loadWasmContextInstance(m_prologueWasmContextGPR);
// We need to setup JSWebAssemblyInstance in |this| slot first.
if (mayHaveExceptionHandlers) {
GPRReg scratch = wasmCallingConvention().prologueScratchGPRs[0];
jit.loadPtr(CCallHelpers::Address(m_prologueWasmContextGPR, Instance::offsetOfOwner()), scratch);
jit.store64(scratch, CCallHelpers::Address(GPRInfo::callFrameRegister, CallFrameSlot::thisArgument * sizeof(Register)));
}
// This allows leaf functions to not do stack checks if their frame size is within
// certain limits since their caller would have already done the check.
if (needsOverflowCheck) {
if (mayHaveExceptionHandlers)
jit.store32(CCallHelpers::TrustedImm32(PatchpointExceptionHandle::s_invalidCallSiteIndex), CCallHelpers::tagFor(CallFrameSlot::argumentCountIncludingThis));
GPRReg scratch = wasmCallingConvention().prologueScratchGPRs[0];
jit.addPtr(CCallHelpers::TrustedImm32(-checkSize), GPRInfo::callFrameRegister, scratch);
MacroAssembler::JumpList overflow;
if (UNLIKELY(needUnderflowCheck))
overflow.append(jit.branchPtr(CCallHelpers::Above, scratch, GPRInfo::callFrameRegister));
overflow.append(jit.branchPtr(CCallHelpers::Below, scratch, CCallHelpers::Address(m_prologueWasmContextGPR, Instance::offsetOfCachedStackLimit())));
jit.addLinkTask([overflow] (LinkBuffer& linkBuffer) {
linkBuffer.link(overflow, CodeLocationLabel<JITThunkPtrTag>(Thunks::singleton().stub(throwStackOverflowFromWasmThunkGenerator).code()));
});
}
}
});
if (Context::useFastTLS()) {
m_instanceValue = g64();
// FIXME: Would be nice to only do this if we use instance value.
append(Move, Tmp(m_prologueWasmContextGPR), m_instanceValue);
} else
m_instanceValue = { Tmp(m_prologueWasmContextGPR), Types::I64 };
append(EntrySwitch);
m_mainEntrypointStart = m_code.addBlock();
m_currentBlock = m_mainEntrypointStart;
ASSERT(!m_locals.size());
m_locals.grow(signature.as<FunctionSignature>()->argumentCount());
for (unsigned i = 0; i < signature.as<FunctionSignature>()->argumentCount(); ++i) {
Type type = signature.as<FunctionSignature>()->argumentType(i);
m_locals[i] = tmpForType(type);
}
CallInformation wasmCallInfo = wasmCallingConvention().callInformationFor(signature, CallRole::Callee);
for (unsigned i = 0; i < wasmCallInfo.params.size(); ++i) {
B3::ValueRep location = wasmCallInfo.params[i];
Arg arg = location.isReg() ? Arg(Tmp(location.reg())) : Arg::addr(Tmp(GPRInfo::callFrameRegister), location.offsetFromFP());
switch (signature.as<FunctionSignature>()->argumentType(i).kind) {
case TypeKind::I32:
append(Move32, arg, m_locals[i]);
break;
case TypeKind::I64:
case TypeKind::Externref:
case TypeKind::Funcref:
case TypeKind::Ref:
case TypeKind::RefNull:
append(Move, arg, m_locals[i]);
break;
case TypeKind::F32:
append(MoveFloat, arg, m_locals[i]);
break;
case TypeKind::F64:
append(MoveDouble, arg, m_locals[i]);
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
emitEntryTierUpCheck();
}
void AirIRGenerator::finalizeEntrypoints()
{
unsigned numEntrypoints = Checked<unsigned>(1) + m_catchEntrypoints.size() + m_loopEntryVariableData.size();
m_proc.setNumEntrypoints(numEntrypoints);
m_code.setPrologueForEntrypoint(0, Ref<B3::Air::PrologueGenerator>(*m_prologueGenerator));
for (unsigned i = 1 + m_catchEntrypoints.size(); i < numEntrypoints; ++i)
m_code.setPrologueForEntrypoint(i, Ref<B3::Air::PrologueGenerator>(*m_prologueGenerator));
if (m_catchEntrypoints.size()) {
Ref<B3::Air::PrologueGenerator> catchPrologueGenerator = createSharedTask<B3::Air::PrologueGeneratorFunction>([this] (CCallHelpers& jit, B3::Air::Code& code) {
AllowMacroScratchRegisterUsage allowScratch(jit);
emitCatchPrologueShared(code, jit);
if (Context::useFastTLS()) {
// Shared prologue expects this in this register when entering the function using fast TLS.
jit.loadWasmContextInstance(m_prologueWasmContextGPR);
}
});
for (unsigned i = 0; i < m_catchEntrypoints.size(); ++i)
m_code.setPrologueForEntrypoint(1 + i, catchPrologueGenerator.copyRef());
}
BasicBlock::SuccessorList successors;
successors.append(m_mainEntrypointStart);
successors.appendVector(m_catchEntrypoints);
for (auto& pair : m_loopEntryVariableData) {
BasicBlock* loopBody = pair.first;
BasicBlock* entry = m_code.addBlock();
successors.append(entry);
m_currentBlock = entry;
auto& temps = pair.second;
m_osrEntryScratchBufferSize = std::max(m_osrEntryScratchBufferSize, static_cast<unsigned>(temps.size()));
Tmp basePtr = Tmp(GPRInfo::argumentGPR0);
for (size_t i = 0; i < temps.size(); ++i) {
size_t offset = static_cast<size_t>(i) * sizeof(uint64_t);
emitLoad(basePtr, offset, temps[i]);
}
append(Jump);
entry->setSuccessors(loopBody);
}
RELEASE_ASSERT(numEntrypoints == successors.size());
m_rootBlock->successors() = successors;
}
B3::Type AirIRGenerator::toB3ResultType(BlockSignature returnType)
{
if (returnType->as<FunctionSignature>()->returnsVoid())
return B3::Void;
if (returnType->as<FunctionSignature>()->returnCount() == 1)
return toB3Type(returnType->as<FunctionSignature>()->returnType(0));
auto result = m_tupleMap.ensure(returnType, [&] {
Vector<B3::Type> result;
for (unsigned i = 0; i < returnType->as<FunctionSignature>()->returnCount(); ++i)
result.append(toB3Type(returnType->as<FunctionSignature>()->returnType(i)));
return m_proc.addTuple(WTFMove(result));
});
return result.iterator->value;
}
void AirIRGenerator::restoreWebAssemblyGlobalState(RestoreCachedStackLimit restoreCachedStackLimit, const MemoryInformation& memory, TypedTmp instance, BasicBlock* block)
{
restoreWasmContextInstance(block, instance);
if (restoreCachedStackLimit == RestoreCachedStackLimit::Yes) {
// The Instance caches the stack limit, but also knows where its canonical location is.
static_assert(sizeof(std::declval<Instance*>()->cachedStackLimit()) == sizeof(uint64_t), "codegen relies on this size");
RELEASE_ASSERT(Arg::isValidAddrForm(Instance::offsetOfPointerToActualStackLimit(), B3::Width64));
RELEASE_ASSERT(Arg::isValidAddrForm(Instance::offsetOfCachedStackLimit(), B3::Width64));
auto temp = g64();
append(block, Move, Arg::addr(instanceValue(), Instance::offsetOfPointerToActualStackLimit()), temp);
append(block, Move, Arg::addr(temp), temp);
append(block, Move, temp, Arg::addr(instanceValue(), Instance::offsetOfCachedStackLimit()));
}
if (!!memory) {
const PinnedRegisterInfo* pinnedRegs = &PinnedRegisterInfo::get();
RegisterSet clobbers;
clobbers.set(pinnedRegs->baseMemoryPointer);
clobbers.set(pinnedRegs->boundsCheckingSizeRegister);
clobbers.set(RegisterSet::macroScratchRegisters());
auto* patchpoint = addPatchpoint(B3::Void);
B3::Effects effects = B3::Effects::none();
effects.writesPinned = true;
effects.reads = B3::HeapRange::top();
patchpoint->effects = effects;
patchpoint->clobber(clobbers);
patchpoint->numGPScratchRegisters = 1;
patchpoint->setGenerator([pinnedRegs] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
GPRReg baseMemory = pinnedRegs->baseMemoryPointer;
GPRReg scratch = params.gpScratch(0);
jit.loadPtr(CCallHelpers::Address(params[0].gpr(), Instance::offsetOfCachedBoundsCheckingSize()), pinnedRegs->boundsCheckingSizeRegister);
jit.loadPtr(CCallHelpers::Address(params[0].gpr(), Instance::offsetOfCachedMemory()), baseMemory);
jit.cageConditionallyAndUntag(Gigacage::Primitive, baseMemory, pinnedRegs->boundsCheckingSizeRegister, scratch);
});
emitPatchpoint(block, patchpoint, Tmp(), instance);
}
}
void AirIRGenerator::emitThrowException(CCallHelpers& jit, ExceptionType type)
{
jit.move(CCallHelpers::TrustedImm32(static_cast<uint32_t>(type)), GPRInfo::argumentGPR1);
auto jumpToExceptionStub = jit.jump();
jit.addLinkTask([jumpToExceptionStub] (LinkBuffer& linkBuffer) {
linkBuffer.link(jumpToExceptionStub, CodeLocationLabel<JITThunkPtrTag>(Thunks::singleton().stub(throwExceptionFromWasmThunkGenerator).code()));
});
}
template <typename Function>
void AirIRGenerator::forEachLiveValue(Function function)
{
for (const auto& local : m_locals)
function(local);
for (unsigned controlIndex = 0; controlIndex < m_parser->controlStack().size(); ++controlIndex) {
ControlData& data = m_parser->controlStack()[controlIndex].controlData;
Stack& expressionStack = m_parser->controlStack()[controlIndex].enclosedExpressionStack;
for (const auto& tmp : expressionStack)
function(tmp.value());
if (ControlType::isAnyCatch(data))
function(data.exception());
}
}
auto AirIRGenerator::addLocal(Type type, uint32_t count) -> PartialResult
{
size_t newSize = m_locals.size() + count;
ASSERT(!(CheckedUint32(count) + m_locals.size()).hasOverflowed());
ASSERT(newSize <= maxFunctionLocals);
WASM_COMPILE_FAIL_IF(!m_locals.tryReserveCapacity(newSize), "can't allocate memory for ", newSize, " locals");
for (uint32_t i = 0; i < count; ++i) {
auto local = tmpForType(type);
m_locals.uncheckedAppend(local);
switch (type.kind) {
case TypeKind::Externref:
case TypeKind::Funcref:
case TypeKind::Ref:
case TypeKind::RefNull:
append(Move, Arg::imm(JSValue::encode(jsNull())), local);
break;
case TypeKind::I32:
case TypeKind::I64: {
append(Xor64, local, local);
break;
}
case TypeKind::F32:
case TypeKind::F64: {
auto temp = g64();
// IEEE 754 "0" is just int32/64 zero.
append(Xor64, temp, temp);
append(type.isF32() ? Move32ToFloat : Move64ToDouble, temp, local);
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
return { };
}
auto AirIRGenerator::addConstant(Type type, uint64_t value) -> ExpressionType
{
return addConstant(m_currentBlock, type, value);
}
auto AirIRGenerator::addConstant(BasicBlock* block, Type type, uint64_t value) -> ExpressionType
{
auto result = tmpForType(type);
switch (type.kind) {
case TypeKind::I32:
case TypeKind::I64:
case TypeKind::Externref:
case TypeKind::Funcref:
case TypeKind::Ref:
case TypeKind::RefNull:
append(block, Move, Arg::bigImm(value), result);
break;
case TypeKind::F32:
case TypeKind::F64: {
auto tmp = g64();
append(block, Move, Arg::bigImm(value), tmp);
append(block, type.isF32() ? Move32ToFloat : Move64ToDouble, tmp, result);
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
}
return result;
}
auto AirIRGenerator::addBottom(BasicBlock* block, Type type) -> ExpressionType
{
append(block, B3::Air::Oops);
return addConstant(type, 0);
}
auto AirIRGenerator::addArguments(const TypeDefinition& signature) -> PartialResult
{
RELEASE_ASSERT(m_locals.size() == signature.as<FunctionSignature>()->argumentCount()); // We handle arguments in the prologue
return { };
}
auto AirIRGenerator::addRefIsNull(ExpressionType value, ExpressionType& result) -> PartialResult
{
ASSERT(value.tmp());
result = tmpForType(Types::I32);
auto tmp = g64();
append(Move, Arg::bigImm(JSValue::encode(jsNull())), tmp);
append(Compare64, Arg::relCond(MacroAssembler::Equal), value, tmp, result);
return { };
}
auto AirIRGenerator::addRefFunc(uint32_t index, ExpressionType& result) -> PartialResult
{
// FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
if (Options::useWebAssemblyTypedFunctionReferences()) {
TypeIndex typeIndex = m_info.typeIndexFromFunctionIndexSpace(index);
result = tmpForType(Type { TypeKind::Ref, Nullable::No, typeIndex });
} else
result = tmpForType(Types::Funcref);
emitCCall(&operationWasmRefFunc, result, instanceValue(), addConstant(Types::I32, index));
return { };
}
auto AirIRGenerator::addTableGet(unsigned tableIndex, ExpressionType index, ExpressionType& result) -> PartialResult
{
// FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
ASSERT(index.tmp());
ASSERT(index.type().isI32());
result = tmpForType(m_info.tables[tableIndex].wasmType());
emitCCall(&operationGetWasmTableElement, result, instanceValue(), addConstant(Types::I32, tableIndex), index);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTableAccess);
});
return { };
}
auto AirIRGenerator::addTableSet(unsigned tableIndex, ExpressionType index, ExpressionType value) -> PartialResult
{
// FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
ASSERT(index.tmp());
ASSERT(index.type().isI32());
ASSERT(value.tmp());
auto shouldThrow = g32();
emitCCall(&operationSetWasmTableElement, shouldThrow, instanceValue(), addConstant(Types::I32, tableIndex), index, value);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), shouldThrow, shouldThrow);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTableAccess);
});
return { };
}
auto AirIRGenerator::addTableInit(unsigned elementIndex, unsigned tableIndex, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length) -> PartialResult
{
ASSERT(dstOffset.tmp());
ASSERT(dstOffset.type().isI32());
ASSERT(srcOffset.tmp());
ASSERT(srcOffset.type().isI32());
ASSERT(length.tmp());
ASSERT(length.type().isI32());
auto result = tmpForType(Types::I32);
emitCCall(
&operationWasmTableInit, result, instanceValue(),
addConstant(Types::I32, elementIndex),
addConstant(Types::I32, tableIndex),
dstOffset, srcOffset, length);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTableAccess);
});
return { };
}
auto AirIRGenerator::addElemDrop(unsigned elementIndex) -> PartialResult
{
emitCCall(&operationWasmElemDrop, TypedTmp(), instanceValue(), addConstant(Types::I32, elementIndex));
return { };
}
auto AirIRGenerator::addTableSize(unsigned tableIndex, ExpressionType& result) -> PartialResult
{
// FIXME: Emit this inline <https://bugs.webkit.org/show_bug.cgi?id=198506>.
result = tmpForType(Types::I32);
emitCCall(&operationGetWasmTableSize, result, instanceValue(), addConstant(Types::I32, tableIndex));
return { };
}
auto AirIRGenerator::addTableGrow(unsigned tableIndex, ExpressionType fill, ExpressionType delta, ExpressionType& result) -> PartialResult
{
ASSERT(fill.tmp());
ASSERT(isSubtype(fill.type(), m_info.tables[tableIndex].wasmType()));
ASSERT(delta.tmp());
ASSERT(delta.type().isI32());
result = tmpForType(Types::I32);
emitCCall(&operationWasmTableGrow, result, instanceValue(), addConstant(Types::I32, tableIndex), fill, delta);
return { };
}
auto AirIRGenerator::addTableFill(unsigned tableIndex, ExpressionType offset, ExpressionType fill, ExpressionType count) -> PartialResult
{
ASSERT(fill.tmp());
ASSERT(isSubtype(fill.type(), m_info.tables[tableIndex].wasmType()));
ASSERT(offset.tmp());
ASSERT(offset.type().isI32());
ASSERT(count.tmp());
ASSERT(count.type().isI32());
auto result = tmpForType(Types::I32);
emitCCall(&operationWasmTableFill, result, instanceValue(), addConstant(Types::I32, tableIndex), offset, fill, count);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTableAccess);
});
return { };
}
auto AirIRGenerator::addTableCopy(unsigned dstTableIndex, unsigned srcTableIndex, ExpressionType dstOffset, ExpressionType srcOffset, ExpressionType length) -> PartialResult
{
ASSERT(dstOffset.tmp());
ASSERT(dstOffset.type().isI32());
ASSERT(srcOffset.tmp());
ASSERT(srcOffset.type().isI32());
ASSERT(length.tmp());
ASSERT(length.type().isI32());
auto result = tmpForType(Types::I32);
emitCCall(
&operationWasmTableCopy, result, instanceValue(),
addConstant(Types::I32, dstTableIndex),
addConstant(Types::I32, srcTableIndex),
dstOffset, srcOffset, length);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTableAccess);
});
return { };
}
auto AirIRGenerator::getLocal(uint32_t index, ExpressionType& result) -> PartialResult
{
ASSERT(m_locals[index].tmp());
result = tmpForType(m_locals[index].type());
append(moveOpForValueType(m_locals[index].type()), m_locals[index].tmp(), result);
return { };
}
auto AirIRGenerator::addUnreachable() -> PartialResult
{
B3::PatchpointValue* unreachable = addPatchpoint(B3::Void);
unreachable->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::Unreachable);
});
unreachable->effects.terminal = true;
emitPatchpoint(unreachable, Tmp());
return { };
}
auto AirIRGenerator::addGrowMemory(ExpressionType delta, ExpressionType& result) -> PartialResult
{
result = g32();
emitCCall(&operationGrowMemory, result, TypedTmp { Tmp(GPRInfo::callFrameRegister), Types::I64 }, instanceValue(), delta);
restoreWebAssemblyGlobalState(RestoreCachedStackLimit::No, m_info.memory, instanceValue(), m_currentBlock);
return { };
}
auto AirIRGenerator::addCurrentMemory(ExpressionType& result) -> PartialResult
{
static_assert(sizeof(std::declval<Memory*>()->size()) == sizeof(uint64_t), "codegen relies on this size");
auto temp1 = g64();
auto temp2 = g64();
RELEASE_ASSERT(Arg::isValidAddrForm(Instance::offsetOfMemory(), B3::Width64));
RELEASE_ASSERT(Arg::isValidAddrForm(Memory::offsetOfHandle(), B3::Width64));
RELEASE_ASSERT(Arg::isValidAddrForm(MemoryHandle::offsetOfSize(), B3::Width64));
append(Move, Arg::addr(instanceValue(), Instance::offsetOfMemory()), temp1);
append(Move, Arg::addr(temp1, Memory::offsetOfHandle()), temp1);
append(Move, Arg::addr(temp1, MemoryHandle::offsetOfSize()), temp1);
constexpr uint32_t shiftValue = 16;
static_assert(PageCount::pageSize == 1ull << shiftValue, "This must hold for the code below to be correct.");
append(Move, Arg::imm(16), temp2);
addShift(Types::I32, Urshift64, temp1, temp2, result);
append(Move32, result, result);
return { };
}
auto AirIRGenerator::addMemoryFill(ExpressionType dstAddress, ExpressionType targetValue, ExpressionType count) -> PartialResult
{
ASSERT(dstAddress.tmp());
ASSERT(dstAddress.type().isI32());
ASSERT(targetValue.tmp());
ASSERT(targetValue.type().isI32());
ASSERT(count.tmp());
ASSERT(count.type().isI32());
auto result = tmpForType(Types::I32);
emitCCall(
&operationWasmMemoryFill, result, instanceValue(),
dstAddress, targetValue, count);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
return { };
}
auto AirIRGenerator::addMemoryCopy(ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType count) -> PartialResult
{
ASSERT(dstAddress.tmp());
ASSERT(dstAddress.type().isI32());
ASSERT(srcAddress.tmp());
ASSERT(srcAddress.type().isI32());
ASSERT(count.tmp());
ASSERT(count.type().isI32());
auto result = tmpForType(Types::I32);
emitCCall(
&operationWasmMemoryCopy, result, instanceValue(),
dstAddress, srcAddress, count);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
return { };
}
auto AirIRGenerator::addMemoryInit(unsigned dataSegmentIndex, ExpressionType dstAddress, ExpressionType srcAddress, ExpressionType length) -> PartialResult
{
ASSERT(dstAddress.tmp());
ASSERT(dstAddress.type().isI32());
ASSERT(srcAddress.tmp());
ASSERT(srcAddress.type().isI32());
ASSERT(length.tmp());
ASSERT(length.type().isI32());
auto result = tmpForType(Types::I32);
emitCCall(
&operationWasmMemoryInit, result, instanceValue(),
addConstant(Types::I32, dataSegmentIndex),
dstAddress, srcAddress, length);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::Zero), result, result);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
return { };
}
auto AirIRGenerator::addDataDrop(unsigned dataSegmentIndex) -> PartialResult
{
emitCCall(&operationWasmDataDrop, TypedTmp(), instanceValue(), addConstant(Types::I32, dataSegmentIndex));
return { };
}
auto AirIRGenerator::setLocal(uint32_t index, ExpressionType value) -> PartialResult
{
ASSERT(m_locals[index].tmp());
append(moveOpForValueType(m_locals[index].type()), value, m_locals[index].tmp());
return { };
}
auto AirIRGenerator::getGlobal(uint32_t index, ExpressionType& result) -> PartialResult
{
const Wasm::GlobalInformation& global = m_info.globals[index];
Type type = global.type;
result = tmpForType(type);
auto temp = g64();
RELEASE_ASSERT(Arg::isValidAddrForm(Instance::offsetOfGlobals(), B3::Width64));
append(Move, Arg::addr(instanceValue(), Instance::offsetOfGlobals()), temp);
int32_t offset = safeCast<int32_t>(index * sizeof(Register));
switch (global.bindingMode) {
case Wasm::GlobalInformation::BindingMode::EmbeddedInInstance:
if (Arg::isValidAddrForm(offset, B3::widthForType(toB3Type(type))))
append(moveOpForValueType(type), Arg::addr(temp, offset), result);
else {
auto temp2 = g64();
append(Move, Arg::bigImm(offset), temp2);
append(Add64, temp2, temp, temp);
append(moveOpForValueType(type), Arg::addr(temp), result);
}
break;
case Wasm::GlobalInformation::BindingMode::Portable:
ASSERT(global.mutability == Wasm::Mutability::Mutable);
if (Arg::isValidAddrForm(offset, B3::Width64))
append(Move, Arg::addr(temp, offset), temp);
else {
auto temp2 = g64();
append(Move, Arg::bigImm(offset), temp2);
append(Add64, temp2, temp, temp);
append(Move, Arg::addr(temp), temp);
}
append(moveOpForValueType(type), Arg::addr(temp), result);
break;
}
return { };
}
auto AirIRGenerator::setGlobal(uint32_t index, ExpressionType value) -> PartialResult
{
auto temp = g64();
RELEASE_ASSERT(Arg::isValidAddrForm(Instance::offsetOfGlobals(), B3::Width64));
append(Move, Arg::addr(instanceValue(), Instance::offsetOfGlobals()), temp);
const Wasm::GlobalInformation& global = m_info.globals[index];
Type type = global.type;
int32_t offset = safeCast<int32_t>(index * sizeof(Register));
switch (global.bindingMode) {
case Wasm::GlobalInformation::BindingMode::EmbeddedInInstance:
if (Arg::isValidAddrForm(offset, B3::widthForType(toB3Type(type))))
append(moveOpForValueType(type), value, Arg::addr(temp, offset));
else {
auto temp2 = g64();
append(Move, Arg::bigImm(offset), temp2);
append(Add64, temp2, temp, temp);
append(moveOpForValueType(type), value, Arg::addr(temp));
}
if (isRefType(type))
emitWriteBarrierForJSWrapper();
break;
case Wasm::GlobalInformation::BindingMode::Portable:
ASSERT(global.mutability == Wasm::Mutability::Mutable);
if (Arg::isValidAddrForm(offset, B3::Width64))
append(Move, Arg::addr(temp, offset), temp);
else {
auto temp2 = g64();
append(Move, Arg::bigImm(offset), temp2);
append(Add64, temp2, temp, temp);
append(Move, Arg::addr(temp), temp);
}
append(moveOpForValueType(type), value, Arg::addr(temp));
// We emit a write-barrier onto JSWebAssemblyGlobal, not JSWebAssemblyInstance.
if (isRefType(type)) {
auto cell = g64();
auto vm = g64();
auto cellState = g32();
auto threshold = g32();
BasicBlock* fenceCheckPath = m_code.addBlock();
BasicBlock* fencePath = m_code.addBlock();
BasicBlock* doSlowPath = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
append(Move, Arg::addr(instanceValue(), Instance::offsetOfOwner()), cell);
append(Move, Arg::addr(cell, JSWebAssemblyInstance::offsetOfVM()), vm);
append(Move, Arg::addr(temp, Wasm::Global::offsetOfOwner() - Wasm::Global::offsetOfValue()), cell);
append(Load8, Arg::addr(cell, JSCell::cellStateOffset()), cellState);
append(Move32, Arg::addr(vm, VM::offsetOfHeapBarrierThreshold()), threshold);
append(Branch32, Arg::relCond(MacroAssembler::Above), cellState, threshold);
m_currentBlock->setSuccessors(continuation, fenceCheckPath);
m_currentBlock = fenceCheckPath;
append(Load8, Arg::addr(vm, VM::offsetOfHeapMutatorShouldBeFenced()), threshold);
append(BranchTest32, Arg::resCond(MacroAssembler::Zero), threshold, threshold);
m_currentBlock->setSuccessors(doSlowPath, fencePath);
m_currentBlock = fencePath;
auto* doFence = addPatchpoint(B3::Void);
doFence->setGenerator([] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
jit.memoryFence();
});
emitPatchpoint(doFence, Tmp());
append(Load8, Arg::addr(cell, JSCell::cellStateOffset()), cellState);
append(Branch32, Arg::relCond(MacroAssembler::Above), cellState, Arg::imm(blackThreshold));
m_currentBlock->setSuccessors(continuation, doSlowPath);
m_currentBlock = doSlowPath;
emitCCall(&operationWasmWriteBarrierSlowPath, TypedTmp(), cell, vm);
append(Jump);
m_currentBlock->setSuccessors(continuation);
m_currentBlock = continuation;
}
break;
}
return { };
}
inline void AirIRGenerator::emitWriteBarrierForJSWrapper()
{
auto cell = g64();
auto vm = g64();
auto cellState = g32();
auto threshold = g32();
BasicBlock* fenceCheckPath = m_code.addBlock();
BasicBlock* fencePath = m_code.addBlock();
BasicBlock* doSlowPath = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
append(Move, Arg::addr(instanceValue(), Instance::offsetOfOwner()), cell);
append(Move, Arg::addr(cell, JSWebAssemblyInstance::offsetOfVM()), vm);
append(Load8, Arg::addr(cell, JSCell::cellStateOffset()), cellState);
append(Move32, Arg::addr(vm, VM::offsetOfHeapBarrierThreshold()), threshold);
append(Branch32, Arg::relCond(MacroAssembler::Above), cellState, threshold);
m_currentBlock->setSuccessors(continuation, fenceCheckPath);
m_currentBlock = fenceCheckPath;
append(Load8, Arg::addr(vm, VM::offsetOfHeapMutatorShouldBeFenced()), threshold);
append(BranchTest32, Arg::resCond(MacroAssembler::Zero), threshold, threshold);
m_currentBlock->setSuccessors(doSlowPath, fencePath);
m_currentBlock = fencePath;
auto* doFence = addPatchpoint(B3::Void);
doFence->setGenerator([] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
jit.memoryFence();
});
emitPatchpoint(doFence, Tmp());
append(Load8, Arg::addr(cell, JSCell::cellStateOffset()), cellState);
append(Branch32, Arg::relCond(MacroAssembler::Above), cellState, Arg::imm(blackThreshold));
m_currentBlock->setSuccessors(continuation, doSlowPath);
m_currentBlock = doSlowPath;
emitCCall(&operationWasmWriteBarrierSlowPath, TypedTmp(), cell, vm);
append(Jump);
m_currentBlock->setSuccessors(continuation);
m_currentBlock = continuation;
}
inline AirIRGenerator::ExpressionType AirIRGenerator::emitCheckAndPreparePointer(ExpressionType pointer, uint32_t offset, uint32_t sizeOfOperation)
{
ASSERT(m_memoryBaseGPR);
auto result = g64();
append(Move32, pointer, result);
switch (m_mode) {
case MemoryMode::BoundsChecking: {
// In bound checking mode, while shared wasm memory partially relies on signal handler too, we need to perform bound checking
// to ensure that no memory access exceeds the current memory size.
ASSERT(m_boundsCheckingSizeGPR);
ASSERT(sizeOfOperation + offset > offset);
auto temp = g64();
append(Move, Arg::bigImm(static_cast<uint64_t>(sizeOfOperation) + offset - 1), temp);
append(Add64, result, temp);
emitCheck([&] {
return Inst(Branch64, nullptr, Arg::relCond(MacroAssembler::AboveOrEqual), temp, Tmp(m_boundsCheckingSizeGPR));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
break;
}
#if ENABLE(WEBASSEMBLY_SIGNALING_MEMORY)
case MemoryMode::Signaling: {
// We've virtually mapped 4GiB+redzone for this memory. Only the user-allocated pages are addressable, contiguously in range [0, current],
// and everything above is mapped PROT_NONE. We don't need to perform any explicit bounds check in the 4GiB range because WebAssembly register
// memory accesses are 32-bit. However WebAssembly register + offset accesses perform the addition in 64-bit which can push an access above
// the 32-bit limit (the offset is unsigned 32-bit). The redzone will catch most small offsets, and we'll explicitly bounds check any
// register + large offset access. We don't think this will be generated frequently.
//
// We could check that register + large offset doesn't exceed 4GiB+redzone since that's technically the limit we need to avoid overflowing the
// PROT_NONE region, but it's better if we use a smaller immediate because it can codegens better. We know that anything equal to or greater
// than the declared 'maximum' will trap, so we can compare against that number. If there was no declared 'maximum' then we still know that
// any access equal to or greater than 4GiB will trap, no need to add the redzone.
if (offset >= Memory::fastMappedRedzoneBytes()) {
uint64_t maximum = m_info.memory.maximum() ? m_info.memory.maximum().bytes() : std::numeric_limits<uint32_t>::max();
auto temp = g64();
append(Move, Arg::bigImm(static_cast<uint64_t>(sizeOfOperation) + offset - 1), temp);
append(Add64, result, temp);
auto sizeMax = addConstant(Types::I64, maximum);
emitCheck([&] {
return Inst(Branch64, nullptr, Arg::relCond(MacroAssembler::AboveOrEqual), temp, sizeMax);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
}
break;
}
#endif
}
append(Add64, Tmp(m_memoryBaseGPR), result);
return result;
}
inline uint32_t sizeOfLoadOp(LoadOpType op)
{
switch (op) {
case LoadOpType::I32Load8S:
case LoadOpType::I32Load8U:
case LoadOpType::I64Load8S:
case LoadOpType::I64Load8U:
return 1;
case LoadOpType::I32Load16S:
case LoadOpType::I64Load16S:
case LoadOpType::I32Load16U:
case LoadOpType::I64Load16U:
return 2;
case LoadOpType::I32Load:
case LoadOpType::I64Load32S:
case LoadOpType::I64Load32U:
case LoadOpType::F32Load:
return 4;
case LoadOpType::I64Load:
case LoadOpType::F64Load:
return 8;
}
RELEASE_ASSERT_NOT_REACHED();
}
inline TypedTmp AirIRGenerator::emitLoadOp(LoadOpType op, ExpressionType pointer, uint32_t uoffset)
{
uint32_t offset = fixupPointerPlusOffset(pointer, uoffset);
TypedTmp immTmp;
TypedTmp newPtr;
TypedTmp result;
Arg addrArg;
if (Arg::isValidAddrForm(offset, B3::widthForBytes(sizeOfLoadOp(op))))
addrArg = Arg::addr(pointer, offset);
else {
immTmp = g64();
newPtr = g64();
append(Move, Arg::bigImm(offset), immTmp);
append(Add64, immTmp, pointer, newPtr);
addrArg = Arg::addr(newPtr);
}
switch (op) {
case LoadOpType::I32Load8S: {
result = g32();
appendEffectful(Load8SignedExtendTo32, addrArg, result);
break;
}
case LoadOpType::I64Load8S: {
result = g64();
appendEffectful(Load8SignedExtendTo32, addrArg, result);
append(SignExtend32ToPtr, result, result);
break;
}
case LoadOpType::I32Load8U: {
result = g32();
appendEffectful(Load8, addrArg, result);
break;
}
case LoadOpType::I64Load8U: {
result = g64();
appendEffectful(Load8, addrArg, result);
break;
}
case LoadOpType::I32Load16S: {
result = g32();
appendEffectful(Load16SignedExtendTo32, addrArg, result);
break;
}
case LoadOpType::I64Load16S: {
result = g64();
appendEffectful(Load16SignedExtendTo32, addrArg, result);
append(SignExtend32ToPtr, result, result);
break;
}
case LoadOpType::I32Load16U: {
result = g32();
appendEffectful(Load16, addrArg, result);
break;
}
case LoadOpType::I64Load16U: {
result = g64();
appendEffectful(Load16, addrArg, result);
break;
}
case LoadOpType::I32Load:
result = g32();
appendEffectful(Move32, addrArg, result);
break;
case LoadOpType::I64Load32U: {
result = g64();
appendEffectful(Move32, addrArg, result);
break;
}
case LoadOpType::I64Load32S: {
result = g64();
appendEffectful(Move32, addrArg, result);
append(SignExtend32ToPtr, result, result);
break;
}
case LoadOpType::I64Load: {
result = g64();
appendEffectful(Move, addrArg, result);
break;
}
case LoadOpType::F32Load: {
result = f32();
appendEffectful(MoveFloat, addrArg, result);
break;
}
case LoadOpType::F64Load: {
result = f64();
appendEffectful(MoveDouble, addrArg, result);
break;
}
}
return result;
}
auto AirIRGenerator::load(LoadOpType op, ExpressionType pointer, ExpressionType& result, uint32_t offset) -> PartialResult
{
ASSERT(pointer.tmp().isGP());
if (UNLIKELY(sumOverflows<uint32_t>(offset, sizeOfLoadOp(op)))) {
// FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
// as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
auto* patch = addPatchpoint(B3::Void);
patch->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
emitPatchpoint(patch, Tmp());
// We won't reach here, so we just pick a random reg.
switch (op) {
case LoadOpType::I32Load8S:
case LoadOpType::I32Load16S:
case LoadOpType::I32Load:
case LoadOpType::I32Load16U:
case LoadOpType::I32Load8U:
result = g32();
break;
case LoadOpType::I64Load8S:
case LoadOpType::I64Load8U:
case LoadOpType::I64Load16S:
case LoadOpType::I64Load32U:
case LoadOpType::I64Load32S:
case LoadOpType::I64Load:
case LoadOpType::I64Load16U:
result = g64();
break;
case LoadOpType::F32Load:
result = f32();
break;
case LoadOpType::F64Load:
result = f64();
break;
}
} else
result = emitLoadOp(op, emitCheckAndPreparePointer(pointer, offset, sizeOfLoadOp(op)), offset);
return { };
}
inline uint32_t sizeOfStoreOp(StoreOpType op)
{
switch (op) {
case StoreOpType::I32Store8:
case StoreOpType::I64Store8:
return 1;
case StoreOpType::I32Store16:
case StoreOpType::I64Store16:
return 2;
case StoreOpType::I32Store:
case StoreOpType::I64Store32:
case StoreOpType::F32Store:
return 4;
case StoreOpType::I64Store:
case StoreOpType::F64Store:
return 8;
}
RELEASE_ASSERT_NOT_REACHED();
}
inline void AirIRGenerator::emitStoreOp(StoreOpType op, ExpressionType pointer, ExpressionType value, uint32_t uoffset)
{
uint32_t offset = fixupPointerPlusOffset(pointer, uoffset);
TypedTmp immTmp;
TypedTmp newPtr;
Arg addrArg;
if (Arg::isValidAddrForm(offset, B3::widthForBytes(sizeOfStoreOp(op))))
addrArg = Arg::addr(pointer, offset);
else {
immTmp = g64();
newPtr = g64();
append(Move, Arg::bigImm(offset), immTmp);
append(Add64, immTmp, pointer, newPtr);
addrArg = Arg::addr(newPtr);
}
switch (op) {
case StoreOpType::I64Store8:
case StoreOpType::I32Store8:
append(Store8, value, addrArg);
return;
case StoreOpType::I64Store16:
case StoreOpType::I32Store16:
append(Store16, value, addrArg);
return;
case StoreOpType::I64Store32:
case StoreOpType::I32Store:
append(Move32, value, addrArg);
return;
case StoreOpType::I64Store:
append(Move, value, addrArg);
return;
case StoreOpType::F32Store:
append(MoveFloat, value, addrArg);
return;
case StoreOpType::F64Store:
append(MoveDouble, value, addrArg);
return;
}
RELEASE_ASSERT_NOT_REACHED();
}
auto AirIRGenerator::store(StoreOpType op, ExpressionType pointer, ExpressionType value, uint32_t offset) -> PartialResult
{
ASSERT(pointer.tmp().isGP());
if (UNLIKELY(sumOverflows<uint32_t>(offset, sizeOfStoreOp(op)))) {
// FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
// as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
auto* throwException = addPatchpoint(B3::Void);
throwException->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
emitPatchpoint(throwException, Tmp());
} else
emitStoreOp(op, emitCheckAndPreparePointer(pointer, offset, sizeOfStoreOp(op)), value, offset);
return { };
}
#define OPCODE_FOR_WIDTH(opcode, width) ( \
(width) == B3::Width8 ? B3::Air::opcode ## 8 : \
(width) == B3::Width16 ? B3::Air::opcode ## 16 : \
(width) == B3::Width32 ? B3::Air::opcode ## 32 : \
B3::Air::opcode ## 64)
#define OPCODE_FOR_CANONICAL_WIDTH(opcode, width) ( \
(width) == B3::Width64 ? B3::Air::opcode ## 64 : B3::Air::opcode ## 32)
inline B3::Width accessWidth(ExtAtomicOpType op)
{
return static_cast<B3::Width>(memoryLog2Alignment(op));
}
inline uint32_t sizeOfAtomicOpMemoryAccess(ExtAtomicOpType op)
{
return bytesForWidth(accessWidth(op));
}
auto AirIRGenerator::fixupPointerPlusOffsetForAtomicOps(ExtAtomicOpType op, ExpressionType pointer, uint32_t uoffset) -> ExpressionType
{
uint32_t offset = fixupPointerPlusOffset(pointer, uoffset);
if (Arg::isValidAddrForm(offset, B3::widthForBytes(sizeOfAtomicOpMemoryAccess(op)))) {
if (offset == 0)
return pointer;
TypedTmp newPtr = g64();
append(Lea64, Arg::addr(pointer, offset), newPtr);
return newPtr;
}
TypedTmp newPtr = g64();
append(Move, Arg::bigImm(offset), newPtr);
append(Add64, pointer, newPtr);
return newPtr;
}
void AirIRGenerator::sanitizeAtomicResult(ExtAtomicOpType op, Type valueType, Tmp source, Tmp dest)
{
switch (valueType.kind) {
case TypeKind::I64: {
switch (accessWidth(op)) {
case B3::Width8:
append(ZeroExtend8To32, source, dest);
return;
case B3::Width16:
append(ZeroExtend16To32, source, dest);
return;
case B3::Width32:
append(Move32, source, dest);
return;
case B3::Width64:
if (source == dest)
return;
append(Move, source, dest);
return;
}
return;
}
case TypeKind::I32:
switch (accessWidth(op)) {
case B3::Width8:
append(ZeroExtend8To32, source, dest);
return;
case B3::Width16:
append(ZeroExtend16To32, source, dest);
return;
case B3::Width32:
case B3::Width64:
if (source == dest)
return;
append(Move, source, dest);
return;
}
return;
default:
RELEASE_ASSERT_NOT_REACHED();
return;
}
}
void AirIRGenerator::sanitizeAtomicResult(ExtAtomicOpType op, Type valueType, Tmp result)
{
sanitizeAtomicResult(op, valueType, result, result);
}
TypedTmp AirIRGenerator::appendGeneralAtomic(ExtAtomicOpType op, B3::Air::Opcode opcode, B3::Commutativity commutativity, Arg input, Arg address, TypedTmp oldValue)
{
B3::Width accessWidth = Wasm::accessWidth(op);
auto newTmp = [&]() {
if (accessWidth == B3::Width64)
return g64();
return g32();
};
auto tmp = [&](Arg arg) -> TypedTmp {
if (arg.isTmp())
return TypedTmp(arg.tmp(), accessWidth == B3::Width64 ? Types::I64 : Types::I32);
TypedTmp result = newTmp();
append(Move, arg, result);
return result;
};
auto imm = [&](Arg arg) {
if (arg.isImm())
return arg;
return Arg();
};
auto bitImm = [&](Arg arg) {
if (arg.isBitImm())
return arg;
return Arg();
};
Tmp newValue = opcode == B3::Air::Nop ? tmp(input) : newTmp();
// We need a CAS loop or a LL/SC loop. Using prepare/attempt jargon, we want:
//
// Block #reloop:
// Prepare
// opcode
// Attempt
// Successors: Then:#done, Else:#reloop
// Block #done:
// Move oldValue, result
auto* beginBlock = m_currentBlock;
auto* reloopBlock = m_code.addBlock();
auto* doneBlock = m_code.addBlock();
append(B3::Air::Jump);
beginBlock->setSuccessors(reloopBlock);
m_currentBlock = reloopBlock;
B3::Air::Opcode prepareOpcode;
if (isX86()) {
switch (accessWidth) {
case B3::Width8:
prepareOpcode = Load8SignedExtendTo32;
break;
case B3::Width16:
prepareOpcode = Load16SignedExtendTo32;
break;
case B3::Width32:
prepareOpcode = Move32;
break;
case B3::Width64:
prepareOpcode = Move;
break;
}
} else {
RELEASE_ASSERT(isARM64());
prepareOpcode = OPCODE_FOR_WIDTH(LoadLinkAcq, accessWidth);
}
appendEffectful(prepareOpcode, address, oldValue);
if (opcode != B3::Air::Nop) {
// FIXME: If we ever have to write this again, we need to find a way to share the code with
// appendBinOp.
// https://bugs.webkit.org/show_bug.cgi?id=169249
if (commutativity == B3::Commutative && imm(input) && isValidForm(opcode, Arg::Imm, Arg::Tmp, Arg::Tmp))
append(opcode, imm(input), oldValue, newValue);
else if (imm(input) && isValidForm(opcode, Arg::Tmp, Arg::Imm, Arg::Tmp))
append(opcode, oldValue, imm(input), newValue);
else if (commutativity == B3::Commutative && bitImm(input) && isValidForm(opcode, Arg::BitImm, Arg::Tmp, Arg::Tmp))
append(opcode, bitImm(input), oldValue, newValue);
else if (isValidForm(opcode, Arg::Tmp, Arg::Tmp, Arg::Tmp))
append(opcode, oldValue, tmp(input), newValue);
else {
append(Move, oldValue, newValue);
if (imm(input) && isValidForm(opcode, Arg::Imm, Arg::Tmp))
append(opcode, imm(input), newValue);
else
append(opcode, tmp(input), newValue);
}
}
if (isX86()) {
#if CPU(X86) || CPU(X86_64)
Tmp eax(X86Registers::eax);
B3::Air::Opcode casOpcode = OPCODE_FOR_WIDTH(BranchAtomicStrongCAS, accessWidth);
append(Move, oldValue, eax);
appendEffectful(casOpcode, Arg::statusCond(MacroAssembler::Success), eax, newValue, address);
#endif
} else {
RELEASE_ASSERT(isARM64());
TypedTmp boolResult = newTmp();
appendEffectful(OPCODE_FOR_WIDTH(StoreCondRel, accessWidth), newValue, address, boolResult);
append(BranchTest32, Arg::resCond(MacroAssembler::Zero), boolResult, boolResult);
}
reloopBlock->setSuccessors(doneBlock, reloopBlock);
m_currentBlock = doneBlock;
return oldValue;
}
TypedTmp AirIRGenerator::appendStrongCAS(ExtAtomicOpType op, TypedTmp expected, TypedTmp value, Arg address, TypedTmp valueResultTmp)
{
B3::Width accessWidth = Wasm::accessWidth(op);
auto newTmp = [&]() {
if (accessWidth == B3::Width64)
return g64();
return g32();
};
auto tmp = [&](Arg arg) -> TypedTmp {
if (arg.isTmp())
return TypedTmp(arg.tmp(), accessWidth == B3::Width64 ? Types::I64 : Types::I32);
TypedTmp result = newTmp();
append(Move, arg, result);
return result;
};
Tmp successBoolResultTmp = newTmp();
Tmp expectedValueTmp = tmp(expected);
Tmp newValueTmp = tmp(value);
if (isX86()) {
#if CPU(X86) || CPU(X86_64)
Tmp eax(X86Registers::eax);
append(Move, expectedValueTmp, eax);
appendEffectful(OPCODE_FOR_WIDTH(AtomicStrongCAS, accessWidth), eax, newValueTmp, address);
append(Move, eax, valueResultTmp);
#endif
return valueResultTmp;
}
if (isARM64E()) {
append(Move, expectedValueTmp, valueResultTmp);
appendEffectful(OPCODE_FOR_WIDTH(AtomicStrongCAS, accessWidth), valueResultTmp, newValueTmp, address);
return valueResultTmp;
}
RELEASE_ASSERT(isARM64());
// We wish to emit:
//
// Block #reloop:
// LoadLink
// Branch NotEqual
// Successors: Then:#fail, Else: #store
// Block #store:
// StoreCond
// Xor $1, %result <--- only if !invert
// Jump
// Successors: #done
// Block #fail:
// Move $invert, %result
// Jump
// Successors: #done
// Block #done:
auto* reloopBlock = m_code.addBlock();
auto* storeBlock = m_code.addBlock();
auto* strongFailBlock = m_code.addBlock();
auto* doneBlock = m_code.addBlock();
auto* beginBlock = m_currentBlock;
append(B3::Air::Jump);
beginBlock->setSuccessors(reloopBlock);
m_currentBlock = reloopBlock;
appendEffectful(OPCODE_FOR_WIDTH(LoadLinkAcq, accessWidth), address, valueResultTmp);
append(OPCODE_FOR_CANONICAL_WIDTH(Branch, accessWidth), Arg::relCond(MacroAssembler::NotEqual), valueResultTmp, expectedValueTmp);
reloopBlock->setSuccessors(B3::Air::FrequentedBlock(strongFailBlock), storeBlock);
m_currentBlock = storeBlock;
appendEffectful(OPCODE_FOR_WIDTH(StoreCondRel, accessWidth), newValueTmp, address, successBoolResultTmp);
append(BranchTest32, Arg::resCond(MacroAssembler::Zero), successBoolResultTmp, successBoolResultTmp);
storeBlock->setSuccessors(doneBlock, reloopBlock);
m_currentBlock = strongFailBlock;
{
TypedTmp tmp = newTmp();
appendEffectful(OPCODE_FOR_WIDTH(StoreCondRel, accessWidth), valueResultTmp, address, tmp);
append(BranchTest32, Arg::resCond(MacroAssembler::Zero), tmp, tmp);
}
strongFailBlock->setSuccessors(B3::Air::FrequentedBlock(doneBlock), reloopBlock);
m_currentBlock = doneBlock;
return valueResultTmp;
}
inline TypedTmp AirIRGenerator::emitAtomicLoadOp(ExtAtomicOpType op, Type valueType, ExpressionType pointer, uint32_t uoffset)
{
TypedTmp newPtr = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);
Arg addrArg = isX86() ? Arg::addr(newPtr) : Arg::simpleAddr(newPtr);
if (accessWidth(op) != B3::Width8) {
emitCheck([&] {
return Inst(BranchTest64, nullptr, Arg::resCond(MacroAssembler::NonZero), newPtr, isX86() ? Arg::bitImm(sizeOfAtomicOpMemoryAccess(op) - 1) : Arg::bitImm64(sizeOfAtomicOpMemoryAccess(op) - 1));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
}
std::optional<B3::Air::Opcode> opcode;
if (isX86() || isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchgAdd, accessWidth(op));
B3::Air::Opcode nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Add, accessWidth(op));
TypedTmp result = valueType.isI64() ? g64() : g32();
if (opcode) {
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind(), Arg::Tmp)) {
append(Move, Arg::imm(0), result);
appendEffectful(opcode.value(), result, addrArg, result);
sanitizeAtomicResult(op, valueType, result);
return result;
}
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind())) {
append(Move, Arg::imm(0), result);
appendEffectful(opcode.value(), result, addrArg);
sanitizeAtomicResult(op, valueType, result);
return result;
}
}
appendGeneralAtomic(op, nonAtomicOpcode, B3::Commutative, Arg::imm(0), addrArg, result);
sanitizeAtomicResult(op, valueType, result);
return result;
}
auto AirIRGenerator::atomicLoad(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType& result, uint32_t offset) -> PartialResult
{
ASSERT(pointer.tmp().isGP());
if (UNLIKELY(sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op)))) {
// FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
// as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
auto* patch = addPatchpoint(B3::Void);
patch->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
emitPatchpoint(patch, Tmp());
// We won't reach here, so we just pick a random reg.
switch (valueType.kind) {
case TypeKind::I32:
result = g32();
break;
case TypeKind::I64:
result = g64();
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
} else
result = emitAtomicLoadOp(op, valueType, emitCheckAndPreparePointer(pointer, offset, sizeOfAtomicOpMemoryAccess(op)), offset);
return { };
}
inline void AirIRGenerator::emitAtomicStoreOp(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType value, uint32_t uoffset)
{
TypedTmp newPtr = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);
Arg addrArg = isX86() ? Arg::addr(newPtr) : Arg::simpleAddr(newPtr);
if (accessWidth(op) != B3::Width8) {
emitCheck([&] {
return Inst(BranchTest64, nullptr, Arg::resCond(MacroAssembler::NonZero), newPtr, isX86() ? Arg::bitImm(sizeOfAtomicOpMemoryAccess(op) - 1) : Arg::bitImm64(sizeOfAtomicOpMemoryAccess(op) - 1));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
}
std::optional<B3::Air::Opcode> opcode;
if (isX86() || isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchg, accessWidth(op));
B3::Air::Opcode nonAtomicOpcode = B3::Air::Nop;
if (opcode) {
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind(), Arg::Tmp)) {
TypedTmp result = valueType.isI64() ? g64() : g32();
appendEffectful(opcode.value(), value, addrArg, result);
return;
}
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind())) {
TypedTmp result = valueType.isI64() ? g64() : g32();
append(Move, value, result);
appendEffectful(opcode.value(), result, addrArg);
return;
}
}
appendGeneralAtomic(op, nonAtomicOpcode, B3::Commutative, value, addrArg, valueType.isI64() ? g64() : g32());
}
auto AirIRGenerator::atomicStore(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType value, uint32_t offset) -> PartialResult
{
ASSERT(pointer.tmp().isGP());
if (UNLIKELY(sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op)))) {
// FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
// as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
auto* throwException = addPatchpoint(B3::Void);
throwException->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
emitPatchpoint(throwException, Tmp());
} else
emitAtomicStoreOp(op, valueType, emitCheckAndPreparePointer(pointer, offset, sizeOfAtomicOpMemoryAccess(op)), value, offset);
return { };
}
TypedTmp AirIRGenerator::emitAtomicBinaryRMWOp(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType value, uint32_t uoffset)
{
TypedTmp newPtr = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);
Arg addrArg = isX86() ? Arg::addr(newPtr) : Arg::simpleAddr(newPtr);
if (accessWidth(op) != B3::Width8) {
emitCheck([&] {
return Inst(BranchTest64, nullptr, Arg::resCond(MacroAssembler::NonZero), newPtr, isX86() ? Arg::bitImm(sizeOfAtomicOpMemoryAccess(op) - 1) : Arg::bitImm64(sizeOfAtomicOpMemoryAccess(op) - 1));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
}
std::optional<B3::Air::Opcode> opcode;
B3::Air::Opcode nonAtomicOpcode = B3::Air::Nop;
B3::Commutativity commutativity = B3::NotCommutative;
switch (op) {
case ExtAtomicOpType::I32AtomicRmw8AddU:
case ExtAtomicOpType::I32AtomicRmw16AddU:
case ExtAtomicOpType::I32AtomicRmwAdd:
case ExtAtomicOpType::I64AtomicRmw8AddU:
case ExtAtomicOpType::I64AtomicRmw16AddU:
case ExtAtomicOpType::I64AtomicRmw32AddU:
case ExtAtomicOpType::I64AtomicRmwAdd:
if (isX86() || isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchgAdd, accessWidth(op));
nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Add, accessWidth(op));
commutativity = B3::Commutative;
break;
case ExtAtomicOpType::I32AtomicRmw8SubU:
case ExtAtomicOpType::I32AtomicRmw16SubU:
case ExtAtomicOpType::I32AtomicRmwSub:
case ExtAtomicOpType::I64AtomicRmw8SubU:
case ExtAtomicOpType::I64AtomicRmw16SubU:
case ExtAtomicOpType::I64AtomicRmw32SubU:
case ExtAtomicOpType::I64AtomicRmwSub:
if (isX86() || isARM64E()) {
TypedTmp newValue;
if (valueType.isI64()) {
newValue = g64();
append(Move, value, newValue);
append(Neg64, newValue);
} else {
newValue = g32();
append(Move, value, newValue);
append(Neg32, newValue);
}
value = newValue;
opcode = OPCODE_FOR_WIDTH(AtomicXchgAdd, accessWidth(op));
nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Add, accessWidth(op));
commutativity = B3::Commutative;
} else {
nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Sub, accessWidth(op));
commutativity = B3::NotCommutative;
}
break;
case ExtAtomicOpType::I32AtomicRmw8AndU:
case ExtAtomicOpType::I32AtomicRmw16AndU:
case ExtAtomicOpType::I32AtomicRmwAnd:
case ExtAtomicOpType::I64AtomicRmw8AndU:
case ExtAtomicOpType::I64AtomicRmw16AndU:
case ExtAtomicOpType::I64AtomicRmw32AndU:
case ExtAtomicOpType::I64AtomicRmwAnd:
if (isARM64E()) {
TypedTmp newValue;
if (valueType.isI64()) {
newValue = g64();
append(Not64, value, newValue);
} else {
newValue = g32();
append(Not32, value, newValue);
}
value = newValue;
opcode = OPCODE_FOR_WIDTH(AtomicXchgClear, accessWidth(op));
}
nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(And, accessWidth(op));
commutativity = B3::Commutative;
break;
case ExtAtomicOpType::I32AtomicRmw8OrU:
case ExtAtomicOpType::I32AtomicRmw16OrU:
case ExtAtomicOpType::I32AtomicRmwOr:
case ExtAtomicOpType::I64AtomicRmw8OrU:
case ExtAtomicOpType::I64AtomicRmw16OrU:
case ExtAtomicOpType::I64AtomicRmw32OrU:
case ExtAtomicOpType::I64AtomicRmwOr:
if (isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchgOr, accessWidth(op));
nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Or, accessWidth(op));
commutativity = B3::Commutative;
break;
case ExtAtomicOpType::I32AtomicRmw8XorU:
case ExtAtomicOpType::I32AtomicRmw16XorU:
case ExtAtomicOpType::I32AtomicRmwXor:
case ExtAtomicOpType::I64AtomicRmw8XorU:
case ExtAtomicOpType::I64AtomicRmw16XorU:
case ExtAtomicOpType::I64AtomicRmw32XorU:
case ExtAtomicOpType::I64AtomicRmwXor:
if (isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchgXor, accessWidth(op));
nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Xor, accessWidth(op));
commutativity = B3::Commutative;
break;
case ExtAtomicOpType::I32AtomicRmw8XchgU:
case ExtAtomicOpType::I32AtomicRmw16XchgU:
case ExtAtomicOpType::I32AtomicRmwXchg:
case ExtAtomicOpType::I64AtomicRmw8XchgU:
case ExtAtomicOpType::I64AtomicRmw16XchgU:
case ExtAtomicOpType::I64AtomicRmw32XchgU:
case ExtAtomicOpType::I64AtomicRmwXchg:
if (isX86() || isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchg, accessWidth(op));
nonAtomicOpcode = B3::Air::Nop;
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
TypedTmp result = valueType.isI64() ? g64() : g32();
if (opcode) {
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind(), Arg::Tmp)) {
appendEffectful(opcode.value(), value, addrArg, result);
sanitizeAtomicResult(op, valueType, result);
return result;
}
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind())) {
append(Move, value, result);
appendEffectful(opcode.value(), result, addrArg);
sanitizeAtomicResult(op, valueType, result);
return result;
}
}
appendGeneralAtomic(op, nonAtomicOpcode, commutativity, value, addrArg, result);
sanitizeAtomicResult(op, valueType, result);
return result;
}
auto AirIRGenerator::atomicBinaryRMW(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType value, ExpressionType& result, uint32_t offset) -> PartialResult
{
ASSERT(pointer.tmp().isGP());
if (UNLIKELY(sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op)))) {
// FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
// as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
auto* patch = addPatchpoint(B3::Void);
patch->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
emitPatchpoint(patch, Tmp());
switch (valueType.kind) {
case TypeKind::I32:
result = g32();
break;
case TypeKind::I64:
result = g64();
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
} else
result = emitAtomicBinaryRMWOp(op, valueType, emitCheckAndPreparePointer(pointer, offset, sizeOfAtomicOpMemoryAccess(op)), value, offset);
return { };
}
TypedTmp AirIRGenerator::emitAtomicCompareExchange(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType expected, ExpressionType value, uint32_t uoffset)
{
TypedTmp newPtr = fixupPointerPlusOffsetForAtomicOps(op, pointer, uoffset);
Arg addrArg = isX86() ? Arg::addr(newPtr) : Arg::simpleAddr(newPtr);
B3::Width valueWidth = widthForType(toB3Type(valueType));
B3::Width accessWidth = Wasm::accessWidth(op);
if (accessWidth != B3::Width8) {
emitCheck([&] {
return Inst(BranchTest64, nullptr, Arg::resCond(MacroAssembler::NonZero), newPtr, isX86() ? Arg::bitImm(sizeOfAtomicOpMemoryAccess(op) - 1) : Arg::bitImm64(sizeOfAtomicOpMemoryAccess(op) - 1));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
}
TypedTmp result = valueType.isI64() ? g64() : g32();
if (valueWidth == accessWidth) {
appendStrongCAS(op, expected, value, addrArg, result);
sanitizeAtomicResult(op, valueType, result);
return result;
}
BasicBlock* failureCase = m_code.addBlock();
BasicBlock* successCase = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
TypedTmp truncatedExpected = valueType.isI64() ? g64() : g32();
sanitizeAtomicResult(op, valueType, expected, truncatedExpected);
append(OPCODE_FOR_CANONICAL_WIDTH(Branch, valueWidth), Arg::relCond(MacroAssembler::NotEqual), expected, truncatedExpected);
m_currentBlock->setSuccessors(B3::Air::FrequentedBlock(failureCase, B3::FrequencyClass::Rare), successCase);
m_currentBlock = successCase;
appendStrongCAS(op, expected, value, addrArg, result);
append(Jump);
m_currentBlock->setSuccessors(continuation);
m_currentBlock = failureCase;
([&] {
std::optional<B3::Air::Opcode> opcode;
if (isX86() || isARM64E())
opcode = OPCODE_FOR_WIDTH(AtomicXchgAdd, accessWidth);
B3::Air::Opcode nonAtomicOpcode = OPCODE_FOR_CANONICAL_WIDTH(Add, accessWidth);
if (opcode) {
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind(), Arg::Tmp)) {
append(Move, Arg::imm(0), result);
appendEffectful(opcode.value(), result, addrArg, result);
return;
}
if (isValidForm(opcode.value(), Arg::Tmp, addrArg.kind())) {
append(Move, Arg::imm(0), result);
appendEffectful(opcode.value(), result, addrArg);
return;
}
}
appendGeneralAtomic(op, nonAtomicOpcode, B3::Commutative, Arg::imm(0), addrArg, result);
})();
append(Jump);
m_currentBlock->setSuccessors(continuation);
m_currentBlock = continuation;
sanitizeAtomicResult(op, valueType, result);
return result;
}
auto AirIRGenerator::atomicCompareExchange(ExtAtomicOpType op, Type valueType, ExpressionType pointer, ExpressionType expected, ExpressionType value, ExpressionType& result, uint32_t offset) -> PartialResult
{
ASSERT(pointer.tmp().isGP());
if (UNLIKELY(sumOverflows<uint32_t>(offset, sizeOfAtomicOpMemoryAccess(op)))) {
// FIXME: Even though this is provably out of bounds, it's not a validation error, so we have to handle it
// as a runtime exception. However, this may change: https://bugs.webkit.org/show_bug.cgi?id=166435
auto* patch = addPatchpoint(B3::Void);
patch->setGenerator([this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
emitPatchpoint(patch, Tmp());
// We won't reach here, so we just pick a random reg.
switch (valueType.kind) {
case TypeKind::I32:
result = g32();
break;
case TypeKind::I64:
result = g64();
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
} else
result = emitAtomicCompareExchange(op, valueType, emitCheckAndPreparePointer(pointer, offset, sizeOfAtomicOpMemoryAccess(op)), expected, value, offset);
return { };
}
auto AirIRGenerator::atomicWait(ExtAtomicOpType op, ExpressionType pointer, ExpressionType value, ExpressionType timeout, ExpressionType& result, uint32_t offset) -> PartialResult
{
result = g32();
if (op == ExtAtomicOpType::MemoryAtomicWait32)
emitCCall(&operationMemoryAtomicWait32, result, instanceValue(), pointer, addConstant(Types::I32, offset), value, timeout);
else
emitCCall(&operationMemoryAtomicWait64, result, instanceValue(), pointer, addConstant(Types::I32, offset), value, timeout);
emitCheck([&] {
return Inst(Branch32, nullptr, Arg::relCond(MacroAssembler::LessThan), result, Arg::imm(0));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
return { };
}
auto AirIRGenerator::atomicNotify(ExtAtomicOpType, ExpressionType pointer, ExpressionType count, ExpressionType& result, uint32_t offset) -> PartialResult
{
result = g32();
emitCCall(&operationMemoryAtomicNotify, result, instanceValue(), pointer, addConstant(Types::I32, offset), count);
emitCheck([&] {
return Inst(Branch32, nullptr, Arg::relCond(MacroAssembler::LessThan), result, Arg::imm(0));
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsMemoryAccess);
});
return { };
}
auto AirIRGenerator::atomicFence(ExtAtomicOpType, uint8_t) -> PartialResult
{
append(MemoryFence);
return { };
}
auto AirIRGenerator::truncSaturated(Ext1OpType op, ExpressionType arg, ExpressionType& result, Type returnType, Type operandType) -> PartialResult
{
TypedTmp maxFloat;
TypedTmp minFloat;
TypedTmp signBitConstant;
bool requiresMacroScratchRegisters = false;
switch (op) {
case Ext1OpType::I32TruncSatF32S:
maxFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int32_t>::min())));
minFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min())));
break;
case Ext1OpType::I32TruncSatF32U:
maxFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min()) * static_cast<float>(-2.0)));
minFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(-1.0)));
break;
case Ext1OpType::I32TruncSatF64S:
maxFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int32_t>::min())));
minFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) - 1.0));
break;
case Ext1OpType::I32TruncSatF64U:
maxFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) * -2.0));
minFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(-1.0));
break;
case Ext1OpType::I64TruncSatF32S:
maxFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int64_t>::min())));
minFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min())));
break;
case Ext1OpType::I64TruncSatF32U:
maxFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min()) * static_cast<float>(-2.0)));
minFloat = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(-1.0)));
if (isX86())
signBitConstant = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
requiresMacroScratchRegisters = true;
break;
case Ext1OpType::I64TruncSatF64S:
maxFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int64_t>::min())));
minFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min())));
break;
case Ext1OpType::I64TruncSatF64U:
maxFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min()) * -2.0));
minFloat = addConstant(Types::F64, bitwise_cast<uint64_t>(-1.0));
if (isX86())
signBitConstant = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
requiresMacroScratchRegisters = true;
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
uint64_t minResult = 0;
uint64_t maxResult = 0;
switch (op) {
case Ext1OpType::I32TruncSatF32S:
case Ext1OpType::I32TruncSatF64S:
maxResult = bitwise_cast<uint32_t>(INT32_MAX);
minResult = bitwise_cast<uint32_t>(INT32_MIN);
break;
case Ext1OpType::I32TruncSatF32U:
case Ext1OpType::I32TruncSatF64U:
maxResult = bitwise_cast<uint32_t>(UINT32_MAX);
minResult = bitwise_cast<uint32_t>(0U);
break;
case Ext1OpType::I64TruncSatF32S:
case Ext1OpType::I64TruncSatF64S:
maxResult = bitwise_cast<uint64_t>(INT64_MAX);
minResult = bitwise_cast<uint64_t>(INT64_MIN);
break;
case Ext1OpType::I64TruncSatF32U:
case Ext1OpType::I64TruncSatF64U:
maxResult = bitwise_cast<uint64_t>(UINT64_MAX);
minResult = bitwise_cast<uint64_t>(0ULL);
break;
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
result = tmpForType(returnType);
BasicBlock* minCase = m_code.addBlock();
BasicBlock* maxCheckCase = m_code.addBlock();
BasicBlock* maxCase = m_code.addBlock();
BasicBlock* inBoundsCase = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
auto branchOp = operandType == Types::F32 ? BranchFloat : BranchDouble;
append(m_currentBlock, branchOp, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualOrUnordered), arg, minFloat);
m_currentBlock->setSuccessors(minCase, maxCheckCase);
append(maxCheckCase, branchOp, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, maxFloat);
maxCheckCase->setSuccessors(maxCase, inBoundsCase);
if (!minResult) {
append(minCase, Move, Arg::bigImm(minResult), result);
append(minCase, Jump);
minCase->setSuccessors(continuation);
} else {
BasicBlock* minMaterializeCase = m_code.addBlock();
BasicBlock* nanCase = m_code.addBlock();
append(minCase, branchOp, Arg::doubleCond(MacroAssembler::DoubleEqualAndOrdered), arg, arg);
minCase->setSuccessors(minMaterializeCase, nanCase);
append(minMaterializeCase, Move, Arg::bigImm(minResult), result);
append(minMaterializeCase, Jump);
minMaterializeCase->setSuccessors(continuation);
append(nanCase, Move, Arg::bigImm(0), result);
append(nanCase, Jump);
nanCase->setSuccessors(continuation);
}
append(maxCase, Move, Arg::bigImm(maxResult), result);
append(maxCase, Jump);
maxCase->setSuccessors(continuation);
Vector<ConstrainedTmp, 2> args;
auto* patchpoint = addPatchpoint(toB3Type(returnType));
patchpoint->effects = B3::Effects::none();
args.append(arg);
if (requiresMacroScratchRegisters) {
patchpoint->clobber(RegisterSet::macroScratchRegisters());
if (isX86()) {
args.append(signBitConstant);
patchpoint->numFPScratchRegisters = 1;
}
}
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
switch (op) {
case Ext1OpType::I32TruncSatF32S:
jit.truncateFloatToInt32(params[1].fpr(), params[0].gpr());
break;
case Ext1OpType::I32TruncSatF32U:
jit.truncateFloatToUint32(params[1].fpr(), params[0].gpr());
break;
case Ext1OpType::I32TruncSatF64S:
jit.truncateDoubleToInt32(params[1].fpr(), params[0].gpr());
break;
case Ext1OpType::I32TruncSatF64U:
jit.truncateDoubleToUint32(params[1].fpr(), params[0].gpr());
break;
case Ext1OpType::I64TruncSatF32S:
jit.truncateFloatToInt64(params[1].fpr(), params[0].gpr());
break;
case Ext1OpType::I64TruncSatF32U: {
AllowMacroScratchRegisterUsage allowScratch(jit);
ASSERT(requiresMacroScratchRegisters);
FPRReg scratch = InvalidFPRReg;
FPRReg constant = InvalidFPRReg;
if (isX86()) {
scratch = params.fpScratch(0);
constant = params[2].fpr();
}
jit.truncateFloatToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
break;
}
case Ext1OpType::I64TruncSatF64S:
jit.truncateDoubleToInt64(params[1].fpr(), params[0].gpr());
break;
case Ext1OpType::I64TruncSatF64U: {
AllowMacroScratchRegisterUsage allowScratch(jit);
ASSERT(requiresMacroScratchRegisters);
FPRReg scratch = InvalidFPRReg;
FPRReg constant = InvalidFPRReg;
if (isX86()) {
scratch = params.fpScratch(0);
constant = params[2].fpr();
}
jit.truncateDoubleToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
break;
}
default:
RELEASE_ASSERT_NOT_REACHED();
break;
}
});
emitPatchpoint(inBoundsCase, patchpoint, Vector<TypedTmp, 8> { result }, WTFMove(args));
append(inBoundsCase, Jump);
inBoundsCase->setSuccessors(continuation);
m_currentBlock = continuation;
return { };
}
auto AirIRGenerator::addI31New(ExpressionType value, ExpressionType& result) -> PartialResult
{
auto tmp1 = g32();
result = gRef(Type { TypeKind::Ref, Nullable::No, static_cast<TypeIndex>(TypeKind::I31ref) });
append(Move, Arg::bigImm(0x7fffffff), tmp1);
append(And32, tmp1, value, tmp1);
append(Move, Arg::bigImm(JSValue::NumberTag), result);
append(Or64, result, tmp1, result);
return { };
}
auto AirIRGenerator::addI31GetS(ExpressionType ref, ExpressionType& result) -> PartialResult
{
// Trap on null reference.
auto tmpForNull = g64();
append(Move, Arg::bigImm(JSValue::encode(jsNull())), tmpForNull);
emitCheck([&] {
return Inst(Branch64, nullptr, Arg::relCond(MacroAssembler::Equal), ref, tmpForNull);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::NullI31Get);
});
auto tmpForShift = g32();
result = g32();
append(Move, Arg::imm(1), tmpForShift);
append(Move32, ref, result);
addShift(Types::I32, Lshift32, result, tmpForShift, result);
addShift(Types::I32, Rshift32, result, tmpForShift, result);
return { };
}
auto AirIRGenerator::addI31GetU(ExpressionType ref, ExpressionType& result) -> PartialResult
{
// Trap on null reference.
auto tmpForNull = g64();
append(Move, Arg::bigImm(JSValue::encode(jsNull())), tmpForNull);
emitCheck([&] {
return Inst(Branch64, nullptr, Arg::relCond(MacroAssembler::Equal), ref, tmpForNull);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::NullI31Get);
});
result = g32();
append(Move32, ref, result);
return { };
}
auto AirIRGenerator::addSelect(ExpressionType condition, ExpressionType nonZero, ExpressionType zero, ExpressionType& result) -> PartialResult
{
ASSERT(nonZero.type() == zero.type());
result = tmpForType(nonZero.type());
append(moveOpForValueType(nonZero.type()), nonZero, result);
BasicBlock* isZero = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
append(BranchTest32, Arg::resCond(MacroAssembler::Zero), condition, condition);
m_currentBlock->setSuccessors(isZero, continuation);
append(isZero, moveOpForValueType(zero.type()), zero, result);
append(isZero, Jump);
isZero->setSuccessors(continuation);
m_currentBlock = continuation;
return { };
}
void AirIRGenerator::emitEntryTierUpCheck()
{
if (!m_tierUp)
return;
auto countdownPtr = g64();
append(Move, Arg::bigImm(bitwise_cast<uintptr_t>(&m_tierUp->m_counter)), countdownPtr);
auto* patch = addPatchpoint(B3::Void);
B3::Effects effects = B3::Effects::none();
effects.reads = B3::HeapRange::top();
effects.writes = B3::HeapRange::top();
patch->effects = effects;
patch->clobber(RegisterSet::macroScratchRegisters());
patch->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
CCallHelpers::Jump tierUp = jit.branchAdd32(CCallHelpers::PositiveOrZero, CCallHelpers::TrustedImm32(TierUpCount::functionEntryIncrement()), CCallHelpers::Address(params[0].gpr()));
CCallHelpers::Label tierUpResume = jit.label();
params.addLatePath([=, this] (CCallHelpers& jit) {
tierUp.link(&jit);
const unsigned extraPaddingBytes = 0;
RegisterSet registersToSpill = { };
registersToSpill.add(GPRInfo::argumentGPR1);
unsigned numberOfStackBytesUsedForRegisterPreservation = ScratchRegisterAllocator::preserveRegistersToStackForCall(jit, registersToSpill, extraPaddingBytes);
jit.move(MacroAssembler::TrustedImm32(m_functionIndex), GPRInfo::argumentGPR1);
MacroAssembler::Call call = jit.nearCall();
ScratchRegisterAllocator::restoreRegistersFromStackForCall(jit, registersToSpill, RegisterSet(), numberOfStackBytesUsedForRegisterPreservation, extraPaddingBytes);
jit.jump(tierUpResume);
jit.addLinkTask([=] (LinkBuffer& linkBuffer) {
MacroAssembler::repatchNearCall(linkBuffer.locationOfNearCall<NoPtrTag>(call), CodeLocationLabel<JITThunkPtrTag>(Thunks::singleton().stub(triggerOMGEntryTierUpThunkGenerator).code()));
});
});
});
emitPatchpoint(patch, Tmp(), countdownPtr);
}
void AirIRGenerator::emitLoopTierUpCheck(uint32_t loopIndex, const Vector<TypedTmp>& liveValues)
{
uint32_t outerLoopIndex = this->outerLoopIndex();
m_outerLoops.append(loopIndex);
if (!m_tierUp)
return;
ASSERT(m_tierUp->osrEntryTriggers().size() == loopIndex);
m_tierUp->osrEntryTriggers().append(TierUpCount::TriggerReason::DontTrigger);
m_tierUp->outerLoops().append(outerLoopIndex);
auto countdownPtr = g64();
append(Move, Arg::bigImm(bitwise_cast<uintptr_t>(&m_tierUp->m_counter)), countdownPtr);
auto* patch = addPatchpoint(B3::Void);
B3::Effects effects = B3::Effects::none();
effects.reads = B3::HeapRange::top();
effects.writes = B3::HeapRange::top();
effects.exitsSideways = true;
patch->effects = effects;
patch->clobber(RegisterSet::macroScratchRegisters());
RegisterSet clobberLate;
clobberLate.add(GPRInfo::argumentGPR0);
patch->clobberLate(clobberLate);
Vector<ConstrainedTmp> patchArgs;
patchArgs.append(countdownPtr);
for (const TypedTmp& tmp : liveValues)
patchArgs.append(ConstrainedTmp(tmp.tmp(), B3::ValueRep::ColdAny));
TierUpCount::TriggerReason* forceEntryTrigger = &(m_tierUp->osrEntryTriggers().last());
static_assert(!static_cast<uint8_t>(TierUpCount::TriggerReason::DontTrigger), "the JIT code assumes non-zero means 'enter'");
static_assert(sizeof(TierUpCount::TriggerReason) == 1, "branchTest8 assumes this size");
patch->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
CCallHelpers::Jump forceOSREntry = jit.branchTest8(CCallHelpers::NonZero, CCallHelpers::AbsoluteAddress(forceEntryTrigger));
CCallHelpers::Jump tierUp = jit.branchAdd32(CCallHelpers::PositiveOrZero, CCallHelpers::TrustedImm32(TierUpCount::loopIncrement()), CCallHelpers::Address(params[0].gpr()));
MacroAssembler::Label tierUpResume = jit.label();
// First argument is the countdown location.
ASSERT(params.value()->numChildren() >= 1);
StackMap values(params.value()->numChildren() - 1);
for (unsigned i = 1; i < params.value()->numChildren(); ++i)
values[i - 1] = OSREntryValue(params[i], params.value()->child(i)->type());
OSREntryData& osrEntryData = m_tierUp->addOSREntryData(m_functionIndex, loopIndex, WTFMove(values));
OSREntryData* osrEntryDataPtr = &osrEntryData;
params.addLatePath([=] (CCallHelpers& jit) {
AllowMacroScratchRegisterUsage allowScratch(jit);
forceOSREntry.link(&jit);
tierUp.link(&jit);
jit.probe(tagCFunction<JITProbePtrTag>(operationWasmTriggerOSREntryNow), osrEntryDataPtr);
jit.branchTestPtr(CCallHelpers::Zero, GPRInfo::argumentGPR0).linkTo(tierUpResume, &jit);
jit.farJump(GPRInfo::argumentGPR1, WasmEntryPtrTag);
});
});
emitPatchpoint(m_currentBlock, patch, ResultList { }, WTFMove(patchArgs));
}
AirIRGenerator::ControlData AirIRGenerator::addTopLevel(BlockSignature signature)
{
return ControlData(B3::Origin(), signature, tmpsForSignature(signature), BlockType::TopLevel, m_code.addBlock());
}
auto AirIRGenerator::addLoop(BlockSignature signature, Stack& enclosingStack, ControlType& block, Stack& newStack, uint32_t loopIndex) -> PartialResult
{
RELEASE_ASSERT(loopIndex == m_loopEntryVariableData.size());
BasicBlock* body = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
splitStack(signature, enclosingStack, newStack);
Vector<TypedTmp> liveValues;
forEachLiveValue([&] (TypedTmp tmp) {
liveValues.append(tmp);
});
for (auto variable : enclosingStack)
liveValues.append(variable);
for (auto variable : newStack)
liveValues.append(variable);
ResultList results;
results.reserveInitialCapacity(newStack.size());
for (auto item : newStack)
results.uncheckedAppend(item);
block = ControlData(origin(), signature, WTFMove(results), BlockType::Loop, continuation, body);
append(Jump);
m_currentBlock->setSuccessors(body);
m_currentBlock = body;
emitLoopTierUpCheck(loopIndex, liveValues);
m_loopEntryVariableData.append(std::pair<BasicBlock*, Vector<TypedTmp>>(body, WTFMove(liveValues)));
return { };
}
auto AirIRGenerator::addBlock(BlockSignature signature, Stack& enclosingStack, ControlType& newBlock, Stack& newStack) -> PartialResult
{
splitStack(signature, enclosingStack, newStack);
newBlock = ControlData(origin(), signature, tmpsForSignature(signature), BlockType::Block, m_code.addBlock());
return { };
}
auto AirIRGenerator::addIf(ExpressionType condition, BlockSignature signature, Stack& enclosingStack, ControlType& result, Stack& newStack) -> PartialResult
{
BasicBlock* taken = m_code.addBlock();
BasicBlock* notTaken = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
B3::FrequencyClass takenFrequency = B3::FrequencyClass::Normal;
B3::FrequencyClass notTakenFrequency= B3::FrequencyClass::Normal;
if (Options::useWebAssemblyBranchHints()) {
BranchHint hint = m_info.getBranchHint(m_functionIndex, m_parser->currentOpcodeStartingOffset());
switch (hint) {
case BranchHint::Unlikely:
takenFrequency = B3::FrequencyClass::Rare;
break;
case BranchHint::Likely:
notTakenFrequency = B3::FrequencyClass::Rare;
break;
case BranchHint::Invalid:
break;
}
}
// Wasm bools are i32.
append(BranchTest32, Arg::resCond(MacroAssembler::NonZero), condition, condition);
m_currentBlock->setSuccessors(FrequentedBlock(taken, takenFrequency), FrequentedBlock(notTaken, notTakenFrequency));
m_currentBlock = taken;
splitStack(signature, enclosingStack, newStack);
result = ControlData(origin(), signature, tmpsForSignature(signature), BlockType::If, continuation, notTaken);
return { };
}
auto AirIRGenerator::addElse(ControlData& data, const Stack& currentStack) -> PartialResult
{
unifyValuesWithBlock(currentStack, data.results);
append(Jump);
m_currentBlock->setSuccessors(data.continuation);
return addElseToUnreachable(data);
}
auto AirIRGenerator::addElseToUnreachable(ControlData& data) -> PartialResult
{
ASSERT(data.blockType() == BlockType::If);
m_currentBlock = data.special;
data.convertIfToBlock();
return { };
}
auto AirIRGenerator::addTry(BlockSignature signature, Stack& enclosingStack, ControlType& result, Stack& newStack) -> PartialResult
{
++m_tryCatchDepth;
BasicBlock* continuation = m_code.addBlock();
splitStack(signature, enclosingStack, newStack);
result = ControlData(origin(), signature, tmpsForSignature(signature), BlockType::Try, continuation, ++m_callSiteIndex, m_tryCatchDepth);
return { };
}
auto AirIRGenerator::addCatch(unsigned exceptionIndex, const TypeDefinition& signature, Stack& currentStack, ControlType& data, ResultList& results) -> PartialResult
{
unifyValuesWithBlock(currentStack, data.results);
append(Jump);
m_currentBlock->setSuccessors(data.continuation);
return addCatchToUnreachable(exceptionIndex, signature, data, results);
}
auto AirIRGenerator::addCatchAll(Stack& currentStack, ControlType& data) -> PartialResult
{
unifyValuesWithBlock(currentStack, data.results);
append(Jump);
m_currentBlock->setSuccessors(data.continuation);
return addCatchAllToUnreachable(data);
}
auto AirIRGenerator::addCatchToUnreachable(unsigned exceptionIndex, const TypeDefinition& signature, ControlType& data, ResultList& results) -> PartialResult
{
Tmp buffer = emitCatchImpl(CatchKind::Catch, data, exceptionIndex);
for (unsigned i = 0; i < signature.as<FunctionSignature>()->argumentCount(); ++i) {
Type type = signature.as<FunctionSignature>()->argumentType(i);
TypedTmp tmp = tmpForType(type);
emitLoad(buffer, i * sizeof(uint64_t), tmp);
results.append(tmp);
}
return { };
}
auto AirIRGenerator::addCatchAllToUnreachable(ControlType& data) -> PartialResult
{
emitCatchImpl(CatchKind::CatchAll, data);
return { };
}
Tmp AirIRGenerator::emitCatchImpl(CatchKind kind, ControlType& data, unsigned exceptionIndex)
{
m_currentBlock = m_code.addBlock();
m_catchEntrypoints.append(m_currentBlock);
if (ControlType::isTry(data)) {
if (kind == CatchKind::Catch)
data.convertTryToCatch(++m_callSiteIndex, g64());
else
data.convertTryToCatchAll(++m_callSiteIndex, g64());
}
// We convert from "try" to "catch" ControlType above. This doesn't
// happen if ControlType is already a "catch". This can happen when
// we have multiple catches like "try {} catch(A){} catch(B){}...CatchAll(E){}".
// We just convert the first ControlType to a catch, then the others will
// use its fields.
ASSERT(ControlType::isAnyCatch(data));
HandlerType handlerType = kind == CatchKind::Catch ? HandlerType::Catch : HandlerType::CatchAll;
m_exceptionHandlers.append({ handlerType, data.tryStart(), data.tryEnd(), 0, m_tryCatchDepth, exceptionIndex });
restoreWebAssemblyGlobalState(RestoreCachedStackLimit::Yes, m_info.memory, instanceValue(), m_currentBlock);
unsigned indexInBuffer = 0;
auto loadFromScratchBuffer = [&] (TypedTmp result) {
size_t offset = sizeof(uint64_t) * indexInBuffer;
++indexInBuffer;
Tmp bufferPtr = Tmp(GPRInfo::argumentGPR0);
emitLoad(bufferPtr, offset, result);
};
forEachLiveValue([&] (TypedTmp tmp) {
// We set our current ControlEntry's exception below after the patchpoint, it's
// not in the incoming buffer of live values.
auto toIgnore = data.exception();
if (tmp.tmp() != toIgnore.tmp())
loadFromScratchBuffer(tmp);
});
B3::PatchpointValue* patch = addPatchpoint(m_proc.addTuple({ B3::pointerType(), B3::pointerType() }));
patch->effects.exitsSideways = true;
patch->clobber(RegisterSet::macroScratchRegisters());
RegisterSet clobberLate = RegisterSet::volatileRegistersForJSCall();
clobberLate.add(GPRInfo::argumentGPR0);
patch->clobberLate(clobberLate);
patch->resultConstraints.append(B3::ValueRep::reg(GPRInfo::returnValueGPR));
patch->resultConstraints.append(B3::ValueRep::reg(GPRInfo::returnValueGPR2));
patch->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
jit.move(params[2].gpr(), GPRInfo::argumentGPR0);
CCallHelpers::Call call = jit.call(OperationPtrTag);
jit.addLinkTask([call] (LinkBuffer& linkBuffer) {
linkBuffer.link(call, FunctionPtr<OperationPtrTag>(operationWasmRetrieveAndClearExceptionIfCatchable));
});
});
Tmp exception = Tmp(GPRInfo::returnValueGPR);
Tmp buffer = Tmp(GPRInfo::returnValueGPR2);
emitPatchpoint(m_currentBlock, patch, Vector<Tmp, 8>::from(exception, buffer), Vector<ConstrainedTmp, 1>::from(instanceValue()));
append(Move, exception, data.exception());
return buffer;
}
auto AirIRGenerator::addDelegate(ControlType& target, ControlType& data) -> PartialResult
{
return addDelegateToUnreachable(target, data);
}
auto AirIRGenerator::addDelegateToUnreachable(ControlType& target, ControlType& data) -> PartialResult
{
unsigned targetDepth = 0;
if (ControlType::isTry(target))
targetDepth = target.tryDepth();
m_exceptionHandlers.append({ HandlerType::Delegate, data.tryStart(), ++m_callSiteIndex, 0, m_tryCatchDepth, targetDepth });
return { };
}
auto AirIRGenerator::addThrow(unsigned exceptionIndex, Vector<ExpressionType>& args, Stack&) -> PartialResult
{
B3::PatchpointValue* patch = addPatchpoint(B3::Void);
patch->effects.terminal = true;
patch->clobber(RegisterSet::volatileRegistersForJSCall());
Vector<ConstrainedTmp, 8> patchArgs;
patchArgs.append(ConstrainedTmp(instanceValue(), B3::ValueRep::reg(GPRInfo::argumentGPR0)));
patchArgs.append(ConstrainedTmp(Tmp(GPRInfo::callFrameRegister), B3::ValueRep::reg(GPRInfo::argumentGPR1)));
for (unsigned i = 0; i < args.size(); ++i)
patchArgs.append(ConstrainedTmp(args[i], B3::ValueRep::stackArgument(i * sizeof(EncodedJSValue))));
PatchpointExceptionHandle handle = preparePatchpointForExceptions(patch, patchArgs);
patch->setGenerator([this, exceptionIndex, handle] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
handle.generate(jit, params, this);
emitThrowImpl(jit, exceptionIndex);
});
emitPatchpoint(m_currentBlock, patch, Tmp(), WTFMove(patchArgs));
return { };
}
auto AirIRGenerator::addRethrow(unsigned, ControlType& data) -> PartialResult
{
B3::PatchpointValue* patch = addPatchpoint(B3::Void);
patch->clobber(RegisterSet::volatileRegistersForJSCall());
patch->effects.terminal = true;
Vector<ConstrainedTmp, 3> patchArgs;
patchArgs.append(ConstrainedTmp(instanceValue(), B3::ValueRep::reg(GPRInfo::argumentGPR0)));
patchArgs.append(ConstrainedTmp(Tmp(GPRInfo::callFrameRegister), B3::ValueRep::reg(GPRInfo::argumentGPR1)));
patchArgs.append(ConstrainedTmp(data.exception(), B3::ValueRep::reg(GPRInfo::argumentGPR2)));
PatchpointExceptionHandle handle = preparePatchpointForExceptions(patch, patchArgs);
patch->setGenerator([this, handle] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
handle.generate(jit, params, this);
emitRethrowImpl(jit);
});
emitPatchpoint(m_currentBlock, patch, Tmp(), WTFMove(patchArgs));
return { };
}
auto AirIRGenerator::addReturn(const ControlData& data, const Stack& returnValues) -> PartialResult
{
CallInformation wasmCallInfo = wasmCallingConvention().callInformationFor(*data.signature(), CallRole::Callee);
if (!wasmCallInfo.results.size()) {
append(RetVoid);
return { };
}
B3::PatchpointValue* patch = addPatchpoint(B3::Void);
patch->setGenerator([] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
auto calleeSaves = params.code().calleeSaveRegisterAtOffsetList();
jit.emitRestore(calleeSaves);
jit.emitFunctionEpilogue();
jit.ret();
});
patch->effects.terminal = true;
ASSERT(returnValues.size() >= wasmCallInfo.results.size());
unsigned offset = returnValues.size() - wasmCallInfo.results.size();
Vector<ConstrainedTmp, 8> returnConstraints;
for (unsigned i = 0; i < wasmCallInfo.results.size(); ++i) {
B3::ValueRep rep = wasmCallInfo.results[i];
TypedTmp tmp = returnValues[offset + i];
if (rep.isStack()) {
append(moveForType(toB3Type(tmp.type())), tmp, Arg::addr(Tmp(GPRInfo::callFrameRegister), rep.offsetFromFP()));
continue;
}
ASSERT(rep.isReg());
if (data.signature()->as<FunctionSignature>()->returnType(i).isI32())
append(Move32, tmp, tmp);
returnConstraints.append(ConstrainedTmp(tmp, wasmCallInfo.results[i]));
}
emitPatchpoint(m_currentBlock, patch, ResultList { }, WTFMove(returnConstraints));
return { };
}
// NOTE: All branches in Wasm are on 32-bit ints
auto AirIRGenerator::addBranch(ControlData& data, ExpressionType condition, const Stack& returnValues) -> PartialResult
{
unifyValuesWithBlock(returnValues, data.results);
BasicBlock* target = data.targetBlockForBranch();
B3::FrequencyClass targetFrequency = B3::FrequencyClass::Normal;
B3::FrequencyClass continuationFrequency = B3::FrequencyClass::Normal;
if (Options::useWebAssemblyBranchHints()) {
BranchHint hint = m_info.getBranchHint(m_functionIndex, m_parser->currentOpcodeStartingOffset());
switch (hint) {
case BranchHint::Unlikely:
targetFrequency = B3::FrequencyClass::Rare;
break;
case BranchHint::Likely:
continuationFrequency = B3::FrequencyClass::Rare;
break;
case BranchHint::Invalid:
break;
}
}
if (condition) {
BasicBlock* continuation = m_code.addBlock();
append(BranchTest32, Arg::resCond(MacroAssembler::NonZero), condition, condition);
m_currentBlock->setSuccessors(FrequentedBlock(target, targetFrequency), FrequentedBlock(continuation, continuationFrequency));
m_currentBlock = continuation;
} else {
append(Jump);
m_currentBlock->setSuccessors(FrequentedBlock(target, targetFrequency));
}
return { };
}
auto AirIRGenerator::addSwitch(ExpressionType condition, const Vector<ControlData*>& targets, ControlData& defaultTarget, const Stack& expressionStack) -> PartialResult
{
auto& successors = m_currentBlock->successors();
ASSERT(successors.isEmpty());
for (const auto& target : targets) {
unifyValuesWithBlock(expressionStack, target->results);
successors.append(target->targetBlockForBranch());
}
unifyValuesWithBlock(expressionStack, defaultTarget.results);
successors.append(defaultTarget.targetBlockForBranch());
ASSERT(condition.type().isI32());
// FIXME: We should consider dynamically switching between a jump table
// and a binary switch depending on the number of successors.
// https://bugs.webkit.org/show_bug.cgi?id=194477
size_t numTargets = targets.size();
auto* patchpoint = addPatchpoint(B3::Void);
patchpoint->effects = B3::Effects::none();
patchpoint->effects.terminal = true;
patchpoint->clobber(RegisterSet::macroScratchRegisters());
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
Vector<int64_t> cases;
cases.reserveInitialCapacity(numTargets);
for (size_t i = 0; i < numTargets; ++i)
cases.uncheckedAppend(i);
GPRReg valueReg = params[0].gpr();
BinarySwitch binarySwitch(valueReg, cases, BinarySwitch::Int32);
Vector<CCallHelpers::Jump> caseJumps;
caseJumps.resize(numTargets);
while (binarySwitch.advance(jit)) {
unsigned value = binarySwitch.caseValue();
unsigned index = binarySwitch.caseIndex();
ASSERT_UNUSED(value, value == index);
ASSERT(index < numTargets);
caseJumps[index] = jit.jump();
}
CCallHelpers::JumpList fallThrough = binarySwitch.fallThrough();
Vector<Box<CCallHelpers::Label>> successorLabels = params.successorLabels();
ASSERT(successorLabels.size() == caseJumps.size() + 1);
params.addLatePath([=, caseJumps = WTFMove(caseJumps), successorLabels = WTFMove(successorLabels)] (CCallHelpers& jit) {
for (size_t i = 0; i < numTargets; ++i)
caseJumps[i].linkTo(*successorLabels[i], &jit);
fallThrough.linkTo(*successorLabels[numTargets], &jit);
});
});
emitPatchpoint(patchpoint, TypedTmp(), condition);
return { };
}
auto AirIRGenerator::endBlock(ControlEntry& entry, Stack& expressionStack) -> PartialResult
{
ControlData& data = entry.controlData;
if (data.blockType() != BlockType::Loop)
unifyValuesWithBlock(expressionStack, data.results);
append(Jump);
m_currentBlock->setSuccessors(data.continuation);
return addEndToUnreachable(entry, expressionStack);
}
auto AirIRGenerator::addEndToUnreachable(ControlEntry& entry, const Stack& expressionStack) -> PartialResult
{
ControlData& data = entry.controlData;
m_currentBlock = data.continuation;
if (data.blockType() == BlockType::If) {
append(data.special, Jump);
data.special->setSuccessors(m_currentBlock);
} else if (data.blockType() == BlockType::Try || data.blockType() == BlockType::Catch)
--m_tryCatchDepth;
if (data.blockType() == BlockType::Loop) {
m_outerLoops.removeLast();
for (unsigned i = 0; i < data.signature()->as<FunctionSignature>()->returnCount(); ++i) {
if (i < expressionStack.size())
entry.enclosedExpressionStack.append(expressionStack[i]);
else {
Type type = data.signature()->as<FunctionSignature>()->returnType(i);
entry.enclosedExpressionStack.constructAndAppend(type, addBottom(m_currentBlock, type));
}
}
} else {
for (unsigned i = 0; i < data.signature()->as<FunctionSignature>()->returnCount(); ++i)
entry.enclosedExpressionStack.constructAndAppend(data.signature()->as<FunctionSignature>()->returnType(i), data.results[i]);
}
// TopLevel does not have any code after this so we need to make sure we emit a return here.
if (data.blockType() == BlockType::TopLevel)
return addReturn(data, entry.enclosedExpressionStack);
return { };
}
std::pair<B3::PatchpointValue*, PatchpointExceptionHandle> AirIRGenerator::emitCallPatchpoint(BasicBlock* block, const TypeDefinition& signature, const ResultList& results, const Vector<TypedTmp>& args, Vector<ConstrainedTmp> patchArgs)
{
auto* patchpoint = addPatchpoint(toB3ResultType(&signature));
patchpoint->effects.writesPinned = true;
patchpoint->effects.readsPinned = true;
patchpoint->clobberEarly(RegisterSet::macroScratchRegisters());
patchpoint->clobberLate(RegisterSet::volatileRegistersForJSCall());
CallInformation locations = wasmCallingConvention().callInformationFor(signature);
m_code.requestCallArgAreaSizeInBytes(WTF::roundUpToMultipleOf(stackAlignmentBytes(), locations.headerAndArgumentStackSizeInBytes));
size_t offset = patchArgs.size();
Checked<size_t> newSize = checkedSum<size_t>(patchArgs.size(), args.size());
RELEASE_ASSERT(!newSize.hasOverflowed());
patchArgs.grow(newSize);
for (unsigned i = 0; i < args.size(); ++i)
patchArgs[i + offset] = ConstrainedTmp(args[i], locations.params[i]);
if (patchpoint->type() != B3::Void) {
Vector<B3::ValueRep, 1> resultConstraints;
for (auto valueLocation : locations.results)
resultConstraints.append(B3::ValueRep(valueLocation));
patchpoint->resultConstraints = WTFMove(resultConstraints);
}
PatchpointExceptionHandle exceptionHandle = preparePatchpointForExceptions(patchpoint, patchArgs);
emitPatchpoint(block, patchpoint, results, WTFMove(patchArgs));
return { patchpoint, exceptionHandle };
}
auto AirIRGenerator::addCall(uint32_t functionIndex, const TypeDefinition& signature, Vector<ExpressionType>& args, ResultList& results) -> PartialResult
{
ASSERT(signature.as<FunctionSignature>()->argumentCount() == args.size());
m_makesCalls = true;
for (unsigned i = 0; i < signature.as<FunctionSignature>()->returnCount(); ++i)
results.append(tmpForType(signature.as<FunctionSignature>()->returnType(i)));
Vector<UnlinkedWasmToWasmCall>* unlinkedWasmToWasmCalls = &m_unlinkedWasmToWasmCalls;
if (m_info.isImportedFunctionFromFunctionIndexSpace(functionIndex)) {
m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, static_cast<uint32_t>(args.size()));
auto currentInstance = g64();
append(Move, instanceValue(), currentInstance);
auto targetInstance = g64();
// FIXME: We should have better isel here.
// https://bugs.webkit.org/show_bug.cgi?id=193999
append(Move, Arg::bigImm(Instance::offsetOfTargetInstance(functionIndex)), targetInstance);
append(Add64, instanceValue(), targetInstance);
append(Move, Arg::addr(targetInstance), targetInstance);
BasicBlock* isWasmBlock = m_code.addBlock();
BasicBlock* isEmbedderBlock = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
append(BranchTest64, Arg::resCond(MacroAssembler::NonZero), targetInstance, targetInstance);
m_currentBlock->setSuccessors(isWasmBlock, isEmbedderBlock);
{
auto pair = emitCallPatchpoint(isWasmBlock, signature, results, args);
auto* patchpoint = pair.first;
auto exceptionHandle = pair.second;
// We need to clobber all potential pinned registers since we might be leaving the instance.
// We pessimistically assume we could be calling to something that is bounds checking.
// FIXME: We shouldn't have to do this: https://bugs.webkit.org/show_bug.cgi?id=172181
patchpoint->clobberLate(PinnedRegisterInfo::get().toSave(MemoryMode::BoundsChecking));
patchpoint->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
exceptionHandle.generate(jit, params, this);
CCallHelpers::Call call = jit.threadSafePatchableNearCall();
jit.addLinkTask([unlinkedWasmToWasmCalls, call, functionIndex] (LinkBuffer& linkBuffer) {
unlinkedWasmToWasmCalls->append({ linkBuffer.locationOfNearCall<WasmEntryPtrTag>(call), functionIndex });
});
});
append(isWasmBlock, Jump);
isWasmBlock->setSuccessors(continuation);
}
{
auto jumpDestination = g64();
append(isEmbedderBlock, Move, Arg::bigImm(Instance::offsetOfWasmToEmbedderStub(functionIndex)), jumpDestination);
append(isEmbedderBlock, Add64, instanceValue(), jumpDestination);
append(isEmbedderBlock, Move, Arg::addr(jumpDestination), jumpDestination);
Vector<ConstrainedTmp> jumpArgs;
jumpArgs.append({ jumpDestination, B3::ValueRep::SomeRegister });
auto pair = emitCallPatchpoint(isEmbedderBlock, signature, results, args, WTFMove(jumpArgs));
auto* patchpoint = pair.first;
auto exceptionHandle = pair.second;
// We need to clobber all potential pinned registers since we might be leaving the instance.
// We pessimistically assume we could be calling to something that is bounds checking.
// FIXME: We shouldn't have to do this: https://bugs.webkit.org/show_bug.cgi?id=172181
patchpoint->clobberLate(PinnedRegisterInfo::get().toSave(MemoryMode::BoundsChecking));
patchpoint->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
exceptionHandle.generate(jit, params, this);
jit.call(params[params.proc().resultCount(params.value()->type())].gpr(), WasmEntryPtrTag);
});
append(isEmbedderBlock, Jump);
isEmbedderBlock->setSuccessors(continuation);
}
m_currentBlock = continuation;
// The call could have been to another WebAssembly instance, and / or could have modified our Memory.
restoreWebAssemblyGlobalState(RestoreCachedStackLimit::Yes, m_info.memory, currentInstance, continuation);
} else {
auto pair = emitCallPatchpoint(m_currentBlock, signature, results, args);
auto* patchpoint = pair.first;
auto exceptionHandle = pair.second;
// We need to clobber the size register since the LLInt always bounds checks
if (useSignalingMemory() || m_info.memory.isShared())
patchpoint->clobberLate(RegisterSet { PinnedRegisterInfo::get().boundsCheckingSizeRegister });
patchpoint->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
exceptionHandle.generate(jit, params, this);
CCallHelpers::Call call = jit.threadSafePatchableNearCall();
jit.addLinkTask([unlinkedWasmToWasmCalls, call, functionIndex] (LinkBuffer& linkBuffer) {
unlinkedWasmToWasmCalls->append({ linkBuffer.locationOfNearCall<WasmEntryPtrTag>(call), functionIndex });
});
});
}
return { };
}
auto AirIRGenerator::addCallIndirect(unsigned tableIndex, const TypeDefinition& signature, Vector<ExpressionType>& args, ResultList& results) -> PartialResult
{
ExpressionType calleeIndex = args.takeLast();
ASSERT(signature.as<FunctionSignature>()->argumentCount() == args.size());
ASSERT(m_info.tableCount() > tableIndex);
ASSERT(m_info.tables[tableIndex].type() == TableElementType::Funcref);
m_makesCalls = true;
// Note: call indirect can call either WebAssemblyFunction or WebAssemblyWrapperFunction. Because
// WebAssemblyWrapperFunction is like calling into the embedder, we conservatively assume all call indirects
// can be to the embedder for our stack check calculation.
m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, static_cast<uint32_t>(args.size()));
ExpressionType callableFunctionBuffer = g64();
ExpressionType instancesBuffer = g64();
ExpressionType callableFunctionBufferLength = g64();
{
RELEASE_ASSERT(Arg::isValidAddrForm(FuncRefTable::offsetOfFunctions(), B3::Width64));
RELEASE_ASSERT(Arg::isValidAddrForm(FuncRefTable::offsetOfInstances(), B3::Width64));
RELEASE_ASSERT(Arg::isValidAddrForm(FuncRefTable::offsetOfLength(), B3::Width64));
if (UNLIKELY(!Arg::isValidAddrForm(Instance::offsetOfTablePtr(m_numImportFunctions, tableIndex), B3::Width64))) {
append(Move, Arg::bigImm(Instance::offsetOfTablePtr(m_numImportFunctions, tableIndex)), callableFunctionBufferLength);
append(Add64, instanceValue(), callableFunctionBufferLength);
append(Move, Arg::addr(callableFunctionBufferLength), callableFunctionBufferLength);
} else
append(Move, Arg::addr(instanceValue(), Instance::offsetOfTablePtr(m_numImportFunctions, tableIndex)), callableFunctionBufferLength);
append(Move, Arg::addr(callableFunctionBufferLength, FuncRefTable::offsetOfFunctions()), callableFunctionBuffer);
append(Move, Arg::addr(callableFunctionBufferLength, FuncRefTable::offsetOfInstances()), instancesBuffer);
append(Move32, Arg::addr(callableFunctionBufferLength, Table::offsetOfLength()), callableFunctionBufferLength);
}
append(Move32, calleeIndex, calleeIndex);
// Check the index we are looking for is valid.
emitCheck([&] {
return Inst(Branch32, nullptr, Arg::relCond(MacroAssembler::AboveOrEqual), calleeIndex, callableFunctionBufferLength);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsCallIndirect);
});
ExpressionType calleeCode = g64();
{
ExpressionType calleeSignatureIndex = g64();
// Compute the offset in the table index space we are looking for.
append(Move, Arg::imm(sizeof(WasmToWasmImportableFunction)), calleeSignatureIndex);
append(Mul64, calleeIndex, calleeSignatureIndex);
append(Add64, callableFunctionBuffer, calleeSignatureIndex);
append(Move, Arg::addr(calleeSignatureIndex, WasmToWasmImportableFunction::offsetOfEntrypointLoadLocation()), calleeCode); // Pointer to callee code.
// Check that the WasmToWasmImportableFunction is initialized. We trap if it isn't. An "invalid" SignatureIndex indicates it's not initialized.
// FIXME: when we have trap handlers, we can just let the call fail because Signature::invalidIndex is 0. https://bugs.webkit.org/show_bug.cgi?id=177210
static_assert(sizeof(WasmToWasmImportableFunction::typeIndex) == sizeof(uint64_t), "Load codegen assumes i64");
// FIXME: This seems wasteful to do two checks just for a nicer error message.
// We should move just to use a single branch and then figure out what
// error to use in the exception handler.
append(Move, Arg::addr(calleeSignatureIndex, WasmToWasmImportableFunction::offsetOfSignatureIndex()), calleeSignatureIndex);
emitCheck([&] {
static_assert(!TypeDefinition::invalidIndex, "");
return Inst(BranchTest64, nullptr, Arg::resCond(MacroAssembler::Zero), calleeSignatureIndex, calleeSignatureIndex);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::NullTableEntry);
});
ExpressionType expectedSignatureIndex = g64();
append(Move, Arg::bigImm(TypeInformation::get(signature)), expectedSignatureIndex);
emitCheck([&] {
return Inst(Branch64, nullptr, Arg::relCond(MacroAssembler::NotEqual), calleeSignatureIndex, expectedSignatureIndex);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::BadSignature);
});
}
auto calleeInstance = g64();
append(Move, Arg::index(instancesBuffer, calleeIndex, 8, 0), calleeInstance);
return emitIndirectCall(calleeInstance, calleeCode, signature, args, results);
}
auto AirIRGenerator::addCallRef(const TypeDefinition& signature, Vector<ExpressionType>& args, ResultList& results) -> PartialResult
{
m_makesCalls = true;
// Note: call ref can call either WebAssemblyFunction or WebAssemblyWrapperFunction. Because
// WebAssemblyWrapperFunction is like calling into the embedder, we conservatively assume all call indirects
// can be to the embedder for our stack check calculation.
ExpressionType calleeFunction = args.takeLast();
m_maxNumJSCallArguments = std::max(m_maxNumJSCallArguments, static_cast<uint32_t>(args.size()));
// Check the target reference for null.
auto tmpForNull = g64();
append(Move, Arg::bigImm(JSValue::encode(jsNull())), tmpForNull);
emitCheck([&] {
return Inst(Branch64, nullptr, Arg::relCond(MacroAssembler::Equal), calleeFunction, tmpForNull);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::NullReference);
});
ExpressionType calleeCode = g64();
append(Move, Arg::addr(calleeFunction, WebAssemblyFunctionBase::offsetOfEntrypointLoadLocation()), calleeCode); // Pointer to callee code.
auto calleeInstance = g64();
append(Move, Arg::addr(calleeFunction, WebAssemblyFunctionBase::offsetOfInstance()), calleeInstance);
append(Move, Arg::addr(calleeInstance, JSWebAssemblyInstance::offsetOfInstance()), calleeInstance);
return emitIndirectCall(calleeInstance, calleeCode, signature, args, results);
}
auto AirIRGenerator::emitIndirectCall(TypedTmp calleeInstance, ExpressionType calleeCode, const TypeDefinition& signature, const Vector<ExpressionType>& args, ResultList& results) -> PartialResult
{
auto currentInstance = g64();
append(Move, instanceValue(), currentInstance);
// Do a context switch if needed.
{
BasicBlock* doContextSwitch = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
append(Branch64, Arg::relCond(MacroAssembler::Equal), calleeInstance, currentInstance);
m_currentBlock->setSuccessors(continuation, doContextSwitch);
auto* patchpoint = addPatchpoint(B3::Void);
patchpoint->effects.writesPinned = true;
// We pessimistically assume we're calling something with BoundsChecking memory.
// FIXME: We shouldn't have to do this: https://bugs.webkit.org/show_bug.cgi?id=172181
patchpoint->clobber(PinnedRegisterInfo::get().toSave(MemoryMode::BoundsChecking));
patchpoint->clobber(RegisterSet::macroScratchRegisters());
patchpoint->numGPScratchRegisters = 1;
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
GPRReg calleeInstance = params[0].gpr();
GPRReg oldContextInstance = params[1].gpr();
const PinnedRegisterInfo& pinnedRegs = PinnedRegisterInfo::get();
GPRReg baseMemory = pinnedRegs.baseMemoryPointer;
ASSERT(calleeInstance != baseMemory);
jit.loadPtr(CCallHelpers::Address(oldContextInstance, Instance::offsetOfCachedStackLimit()), baseMemory);
jit.storePtr(baseMemory, CCallHelpers::Address(calleeInstance, Instance::offsetOfCachedStackLimit()));
jit.storeWasmContextInstance(calleeInstance);
// FIXME: We should support more than one memory size register
// see: https://bugs.webkit.org/show_bug.cgi?id=162952
ASSERT(pinnedRegs.boundsCheckingSizeRegister != calleeInstance);
GPRReg scratch = params.gpScratch(0);
jit.loadPtr(CCallHelpers::Address(calleeInstance, Instance::offsetOfCachedBoundsCheckingSize()), pinnedRegs.boundsCheckingSizeRegister); // Bound checking size.
jit.loadPtr(CCallHelpers::Address(calleeInstance, Instance::offsetOfCachedMemory()), baseMemory); // Memory::void*.
jit.cageConditionallyAndUntag(Gigacage::Primitive, baseMemory, pinnedRegs.boundsCheckingSizeRegister, scratch);
});
emitPatchpoint(doContextSwitch, patchpoint, Tmp(), calleeInstance, currentInstance);
append(doContextSwitch, Jump);
doContextSwitch->setSuccessors(continuation);
m_currentBlock = continuation;
}
append(Move, Arg::addr(calleeCode), calleeCode);
Vector<ConstrainedTmp> extraArgs;
extraArgs.append(calleeCode);
for (unsigned i = 0; i < signature.as<FunctionSignature>()->returnCount(); ++i)
results.append(tmpForType(signature.as<FunctionSignature>()->returnType(i)));
auto pair = emitCallPatchpoint(m_currentBlock, signature, results, args, WTFMove(extraArgs));
auto* patchpoint = pair.first;
auto exceptionHandle = pair.second;
// We need to clobber all potential pinned registers since we might be leaving the instance.
// We pessimistically assume we're always calling something that is bounds checking so
// because the wasm->wasm thunk unconditionally overrides the size registers.
// FIXME: We should not have to do this, but the wasm->wasm stub assumes it can
// use all the pinned registers as scratch: https://bugs.webkit.org/show_bug.cgi?id=172181
patchpoint->clobberLate(PinnedRegisterInfo::get().toSave(MemoryMode::BoundsChecking));
patchpoint->setGenerator([=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
exceptionHandle.generate(jit, params, this);
jit.call(params[params.proc().resultCount(params.value()->type())].gpr(), WasmEntryPtrTag);
});
// The call could have been to another WebAssembly instance, and / or could have modified our Memory.
restoreWebAssemblyGlobalState(RestoreCachedStackLimit::Yes, m_info.memory, currentInstance, m_currentBlock);
return { };
}
void AirIRGenerator::unify(const ExpressionType dst, const ExpressionType source)
{
ASSERT(isSubtype(source.type(), dst.type()));
append(moveOpForValueType(dst.type()), source, dst);
}
void AirIRGenerator::unifyValuesWithBlock(const Stack& resultStack, const ResultList& result)
{
ASSERT(result.size() <= resultStack.size());
for (size_t i = 0; i < result.size(); ++i)
unify(result[result.size() - 1 - i], resultStack[resultStack.size() - 1 - i]);
}
static void dumpExpressionStack(const CommaPrinter& comma, const AirIRGenerator::Stack& expressionStack)
{
dataLog(comma, "ExpressionStack:");
for (const auto& expression : expressionStack)
dataLog(comma, expression.value());
}
void AirIRGenerator::dump(const ControlStack& controlStack, const Stack* stack)
{
dataLogLn("Processing Graph:");
dataLog(m_code);
dataLogLn("With current block:", *m_currentBlock);
dataLogLn("Control stack:");
for (size_t i = controlStack.size(); i--;) {
dataLog(" ", controlStack[i].controlData, ": ");
CommaPrinter comma(", ", "");
dumpExpressionStack(comma, *stack);
stack = &controlStack[i].enclosedExpressionStack;
dataLogLn();
}
dataLogLn("\n");
}
auto AirIRGenerator::origin() -> B3::Origin
{
// FIXME: We should implement a way to give Inst's an origin, and pipe that
// information into the sampling profiler: https://bugs.webkit.org/show_bug.cgi?id=234182
return B3::Origin();
}
Expected<std::unique_ptr<InternalFunction>, String> parseAndCompileAir(CompilationContext& compilationContext, const FunctionData& function, const TypeDefinition& signature, Vector<UnlinkedWasmToWasmCall>& unlinkedWasmToWasmCalls, const ModuleInformation& info, MemoryMode mode, uint32_t functionIndex, std::optional<bool> hasExceptionHandlers, TierUpCount* tierUp)
{
auto result = makeUnique<InternalFunction>();
compilationContext.wasmEntrypointJIT = makeUnique<CCallHelpers>();
compilationContext.procedure = makeUnique<B3::Procedure>();
auto& procedure = *compilationContext.procedure;
Code& code = procedure.code();
procedure.setOriginPrinter([] (PrintStream& out, B3::Origin origin) {
if (origin.data())
out.print("Wasm: ", OpcodeOrigin(origin));
});
// This means we cannot use either StackmapGenerationParams::usedRegisters() or
// StackmapGenerationParams::unavailableRegisters(). In exchange for this concession, we
// don't strictly need to run Air::reportUsedRegisters(), which saves a bit of CPU time at
// optLevel=1.
procedure.setNeedsUsedRegisters(false);
procedure.setOptLevel(Options::webAssemblyBBQAirOptimizationLevel());
AirIRGenerator irGenerator(info, procedure, result.get(), unlinkedWasmToWasmCalls, mode, functionIndex, hasExceptionHandlers, tierUp, signature, result->osrEntryScratchBufferSize);
FunctionParser<AirIRGenerator> parser(irGenerator, function.data.data(), function.data.size(), signature, info);
WASM_FAIL_IF_HELPER_FAILS(parser.parse());
irGenerator.finalizeEntrypoints();
for (BasicBlock* block : code) {
for (size_t i = 0; i < block->numSuccessors(); ++i)
block->successorBlock(i)->addPredecessor(block);
}
if (UNLIKELY(shouldDumpIRAtEachPhase(B3::AirMode))) {
dataLogLn("Generated patchpoints");
for (B3::PatchpointValue** patch : irGenerator.patchpoints())
dataLogLn(deepDump(procedure, *patch));
}
B3::Air::prepareForGeneration(code);
B3::Air::generate(code, *compilationContext.wasmEntrypointJIT);
compilationContext.wasmEntrypointByproducts = procedure.releaseByproducts();
result->entrypoint.calleeSaveRegisters = code.calleeSaveRegisterAtOffsetList();
result->stackmaps = irGenerator.takeStackmaps();
result->exceptionHandlers = irGenerator.takeExceptionHandlers();
return result;
}
template <typename IntType>
void AirIRGenerator::emitChecksForModOrDiv(bool isSignedDiv, ExpressionType left, ExpressionType right)
{
static_assert(sizeof(IntType) == 4 || sizeof(IntType) == 8);
emitCheck([&] {
return Inst(sizeof(IntType) == 4 ? BranchTest32 : BranchTest64, nullptr, Arg::resCond(MacroAssembler::Zero), right, right);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::DivisionByZero);
});
if (isSignedDiv) {
ASSERT(std::is_signed<IntType>::value);
IntType min = std::numeric_limits<IntType>::min();
// FIXME: Better isel for compare with imms here.
// https://bugs.webkit.org/show_bug.cgi?id=193999
auto minTmp = sizeof(IntType) == 4 ? g32() : g64();
auto negOne = sizeof(IntType) == 4 ? g32() : g64();
B3::Air::Opcode op = sizeof(IntType) == 4 ? Compare32 : Compare64;
append(Move, Arg::bigImm(static_cast<uint64_t>(min)), minTmp);
append(op, Arg::relCond(MacroAssembler::Equal), left, minTmp, minTmp);
append(Move, Arg::isValidImmForm(-1) ? Arg::imm(-1) : Arg::bigImm(-1) , negOne);
append(op, Arg::relCond(MacroAssembler::Equal), right, negOne, negOne);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), minTmp, negOne);
},
[=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::IntegerOverflow);
});
}
}
template <typename IntType>
void AirIRGenerator::emitModOrDiv(bool isDiv, ExpressionType lhs, ExpressionType rhs, ExpressionType& result)
{
static_assert(sizeof(IntType) == 4 || sizeof(IntType) == 8);
result = sizeof(IntType) == 4 ? g32() : g64();
bool isSigned = std::is_signed<IntType>::value;
if (isARM64()) {
B3::Air::Opcode div;
switch (sizeof(IntType)) {
case 4:
div = isSigned ? Div32 : UDiv32;
break;
case 8:
div = isSigned ? Div64 : UDiv64;
break;
}
append(div, lhs, rhs, result);
if (!isDiv) {
append(sizeof(IntType) == 4 ? Mul32 : Mul64, result, rhs, result);
append(sizeof(IntType) == 4 ? Sub32 : Sub64, lhs, result, result);
}
return;
}
#if CPU(X86_64)
Tmp eax(X86Registers::eax);
Tmp edx(X86Registers::edx);
if (isSigned) {
B3::Air::Opcode convertToDoubleWord;
B3::Air::Opcode div;
switch (sizeof(IntType)) {
case 4:
convertToDoubleWord = X86ConvertToDoubleWord32;
div = X86Div32;
break;
case 8:
convertToDoubleWord = X86ConvertToQuadWord64;
div = X86Div64;
break;
default:
RELEASE_ASSERT_NOT_REACHED();
}
// We implement "res = Div<Chill>/Mod<Chill>(num, den)" as follows:
//
// if (den + 1 <=_unsigned 1) {
// if (!den) {
// res = 0;
// goto done;
// }
// if (num == -2147483648) {
// res = isDiv ? num : 0;
// goto done;
// }
// }
// res = num (/ or %) dev;
// done:
BasicBlock* denIsGood = m_code.addBlock();
BasicBlock* denMayBeBad = m_code.addBlock();
BasicBlock* denNotZero = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
auto temp = sizeof(IntType) == 4 ? g32() : g64();
auto one = addConstant(sizeof(IntType) == 4 ? Types::I32 : Types::I64, 1);
append(sizeof(IntType) == 4 ? Add32 : Add64, rhs, one, temp);
append(sizeof(IntType) == 4 ? Branch32 : Branch64, Arg::relCond(MacroAssembler::Above), temp, one);
m_currentBlock->setSuccessors(denIsGood, denMayBeBad);
append(denMayBeBad, Xor64, result, result);
append(denMayBeBad, sizeof(IntType) == 4 ? BranchTest32 : BranchTest64, Arg::resCond(MacroAssembler::Zero), rhs, rhs);
denMayBeBad->setSuccessors(continuation, denNotZero);
auto min = addConstant(denNotZero, sizeof(IntType) == 4 ? Types::I32 : Types::I64, std::numeric_limits<IntType>::min());
if (isDiv)
append(denNotZero, sizeof(IntType) == 4 ? Move32 : Move, min, result);
else {
// Result is zero, as set above...
}
append(denNotZero, sizeof(IntType) == 4 ? Branch32 : Branch64, Arg::relCond(MacroAssembler::Equal), lhs, min);
denNotZero->setSuccessors(continuation, denIsGood);
auto divResult = isDiv ? eax : edx;
append(denIsGood, Move, lhs, eax);
append(denIsGood, convertToDoubleWord, eax, edx);
append(denIsGood, div, eax, edx, rhs);
append(denIsGood, sizeof(IntType) == 4 ? Move32 : Move, divResult, result);
append(denIsGood, Jump);
denIsGood->setSuccessors(continuation);
m_currentBlock = continuation;
return;
}
B3::Air::Opcode div = sizeof(IntType) == 4 ? X86UDiv32 : X86UDiv64;
Tmp divResult = isDiv ? eax : edx;
append(Move, lhs, eax);
append(Xor64, edx, edx);
append(div, eax, edx, rhs);
append(sizeof(IntType) == 4 ? Move32 : Move, divResult, result);
#else
RELEASE_ASSERT_NOT_REACHED();
#endif
}
template<>
auto AirIRGenerator::addOp<OpType::I32DivS>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<int32_t>(true, left, right);
emitModOrDiv<int32_t>(true, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32RemS>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<int32_t>(false, left, right);
emitModOrDiv<int32_t>(false, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32DivU>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<uint32_t>(false, left, right);
emitModOrDiv<uint32_t>(true, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32RemU>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<uint32_t>(false, left, right);
emitModOrDiv<uint32_t>(false, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64DivS>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<int64_t>(true, left, right);
emitModOrDiv<int64_t>(true, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64RemS>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<int64_t>(false, left, right);
emitModOrDiv<int64_t>(false, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64DivU>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<uint64_t>(false, left, right);
emitModOrDiv<uint64_t>(true, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64RemU>(ExpressionType left, ExpressionType right, ExpressionType& result) -> PartialResult
{
emitChecksForModOrDiv<uint64_t>(false, left, right);
emitModOrDiv<uint64_t>(false, left, right, result);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32Ctz>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Int32);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.countTrailingZeros32(params[1].gpr(), params[0].gpr());
});
result = g32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64Ctz>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Int64);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.countTrailingZeros64(params[1].gpr(), params[0].gpr());
});
result = g64();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32Popcnt>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
result = g32();
#if CPU(X86_64)
if (MacroAssembler::supportsCountPopulation()) {
auto* patchpoint = addPatchpoint(B3::Int32);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.countPopulation32(params[1].gpr(), params[0].gpr());
});
emitPatchpoint(patchpoint, result, arg);
return { };
}
#endif
emitCCall(&operationPopcount32, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64Popcnt>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
result = g64();
#if CPU(X86_64)
if (MacroAssembler::supportsCountPopulation()) {
auto* patchpoint = addPatchpoint(B3::Int64);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.countPopulation64(params[1].gpr(), params[0].gpr());
});
emitPatchpoint(patchpoint, result, arg);
return { };
}
#endif
emitCCall(&operationPopcount64, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<F64ConvertUI64>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Double);
patchpoint->effects = B3::Effects::none();
if (isX86())
patchpoint->numGPScratchRegisters = 1;
patchpoint->clobber(RegisterSet::macroScratchRegisters());
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
#if CPU(X86_64)
jit.convertUInt64ToDouble(params[1].gpr(), params[0].fpr(), params.gpScratch(0));
#else
jit.convertUInt64ToDouble(params[1].gpr(), params[0].fpr());
#endif
});
result = f64();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::F32ConvertUI64>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Float);
patchpoint->effects = B3::Effects::none();
if (isX86())
patchpoint->numGPScratchRegisters = 1;
patchpoint->clobber(RegisterSet::macroScratchRegisters());
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
#if CPU(X86_64)
jit.convertUInt64ToFloat(params[1].gpr(), params[0].fpr(), params.gpScratch(0));
#else
jit.convertUInt64ToFloat(params[1].gpr(), params[0].fpr());
#endif
});
result = f32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::F64Nearest>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Double);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.roundTowardNearestIntDouble(params[1].fpr(), params[0].fpr());
});
result = f64();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::F32Nearest>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Float);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.roundTowardNearestIntFloat(params[1].fpr(), params[0].fpr());
});
result = f32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::F64Trunc>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Double);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.roundTowardZeroDouble(params[1].fpr(), params[0].fpr());
});
result = f64();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::F32Trunc>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto* patchpoint = addPatchpoint(B3::Float);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.roundTowardZeroFloat(params[1].fpr(), params[0].fpr());
});
result = f32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32TruncSF64>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F64, bitwise_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int32_t>::min())));
auto min = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) - 1.0));
auto temp1 = g32();
auto temp2 = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualOrUnordered), arg, min, temp1);
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
auto* patchpoint = addPatchpoint(B3::Int32);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.truncateDoubleToInt32(params[1].fpr(), params[0].gpr());
});
result = g32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32TruncSF32>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F32, bitwise_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int32_t>::min())));
auto min = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min())));
auto temp1 = g32();
auto temp2 = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleLessThanOrUnordered), arg, min, temp1);
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
auto* patchpoint = addPatchpoint(B3::Int32);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.truncateFloatToInt32(params[1].fpr(), params[0].gpr());
});
result = g32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32TruncUF64>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int32_t>::min()) * -2.0));
auto min = addConstant(Types::F64, bitwise_cast<uint64_t>(-1.0));
auto temp1 = g32();
auto temp2 = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualOrUnordered), arg, min, temp1);
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
auto* patchpoint = addPatchpoint(B3::Int32);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.truncateDoubleToUint32(params[1].fpr(), params[0].gpr());
});
result = g32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I32TruncUF32>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int32_t>::min()) * static_cast<float>(-2.0)));
auto min = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(-1.0)));
auto temp1 = g32();
auto temp2 = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualOrUnordered), arg, min, temp1);
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
auto* patchpoint = addPatchpoint(B3::Int32);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.truncateFloatToUint32(params[1].fpr(), params[0].gpr());
});
result = g32();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64TruncSF64>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F64, bitwise_cast<uint64_t>(-static_cast<double>(std::numeric_limits<int64_t>::min())));
auto min = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min())));
auto temp1 = g32();
auto temp2 = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleLessThanOrUnordered), arg, min, temp1);
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
auto* patchpoint = addPatchpoint(B3::Int64);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.truncateDoubleToInt64(params[1].fpr(), params[0].gpr());
});
result = g64();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64TruncUF64>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<int64_t>::min()) * -2.0));
auto min = addConstant(Types::F64, bitwise_cast<uint64_t>(-1.0));
auto temp1 = g32();
auto temp2 = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualOrUnordered), arg, min, temp1);
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
TypedTmp signBitConstant;
if (isX86())
signBitConstant = addConstant(Types::F64, bitwise_cast<uint64_t>(static_cast<double>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
Vector<ConstrainedTmp> args;
auto* patchpoint = addPatchpoint(B3::Int64);
patchpoint->effects = B3::Effects::none();
patchpoint->clobber(RegisterSet::macroScratchRegisters());
args.append(arg);
if (isX86()) {
args.append(signBitConstant);
patchpoint->numFPScratchRegisters = 1;
}
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
FPRReg scratch = InvalidFPRReg;
FPRReg constant = InvalidFPRReg;
if (isX86()) {
scratch = params.fpScratch(0);
constant = params[2].fpr();
}
jit.truncateDoubleToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
});
result = g64();
emitPatchpoint(m_currentBlock, patchpoint, Vector<TypedTmp, 8> { result }, WTFMove(args));
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64TruncSF32>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F32, bitwise_cast<uint32_t>(-static_cast<float>(std::numeric_limits<int64_t>::min())));
auto min = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min())));
auto temp1 = g32();
auto temp2 = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleLessThanOrUnordered), arg, min, temp1);
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
auto* patchpoint = addPatchpoint(B3::Int64);
patchpoint->effects = B3::Effects::none();
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
jit.truncateFloatToInt64(params[1].fpr(), params[0].gpr());
});
result = g64();
emitPatchpoint(patchpoint, result, arg);
return { };
}
template<>
auto AirIRGenerator::addOp<OpType::I64TruncUF32>(ExpressionType arg, ExpressionType& result) -> PartialResult
{
auto max = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<int64_t>::min()) * static_cast<float>(-2.0)));
auto min = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(-1.0)));
auto temp1 = g32();
auto temp2 = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualOrUnordered), arg, min, temp1);
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualOrUnordered), arg, max, temp2);
append(Or32, temp1, temp2);
emitCheck([&] {
return Inst(BranchTest32, nullptr, Arg::resCond(MacroAssembler::NonZero), temp2, temp2);
}, [=, this] (CCallHelpers& jit, const B3::StackmapGenerationParams&) {
this->emitThrowException(jit, ExceptionType::OutOfBoundsTrunc);
});
TypedTmp signBitConstant;
if (isX86())
signBitConstant = addConstant(Types::F32, bitwise_cast<uint32_t>(static_cast<float>(std::numeric_limits<uint64_t>::max() - std::numeric_limits<int64_t>::max())));
auto* patchpoint = addPatchpoint(B3::Int64);
patchpoint->effects = B3::Effects::none();
patchpoint->clobber(RegisterSet::macroScratchRegisters());
Vector<ConstrainedTmp, 2> args;
args.append(arg);
if (isX86()) {
args.append(signBitConstant);
patchpoint->numFPScratchRegisters = 1;
}
patchpoint->setGenerator([=] (CCallHelpers& jit, const B3::StackmapGenerationParams& params) {
AllowMacroScratchRegisterUsage allowScratch(jit);
FPRReg scratch = InvalidFPRReg;
FPRReg constant = InvalidFPRReg;
if (isX86()) {
scratch = params.fpScratch(0);
constant = params[2].fpr();
}
jit.truncateFloatToUint64(params[1].fpr(), params[0].gpr(), scratch, constant);
});
result = g64();
emitPatchpoint(m_currentBlock, patchpoint, Vector<TypedTmp, 8> { result }, WTFMove(args));
return { };
}
auto AirIRGenerator::addShift(Type type, B3::Air::Opcode op, ExpressionType value, ExpressionType shift, ExpressionType& result) -> PartialResult
{
ASSERT(type.isI64() || type.isI32());
result = tmpForType(type);
if (isValidForm(op, Arg::Tmp, Arg::Tmp, Arg::Tmp)) {
append(op, value, shift, result);
return { };
}
#if CPU(X86_64)
Tmp ecx = Tmp(X86Registers::ecx);
append(Move, value, result);
append(Move, shift, ecx);
append(op, ecx, result);
#else
RELEASE_ASSERT_NOT_REACHED();
#endif
return { };
}
auto AirIRGenerator::addIntegerSub(B3::Air::Opcode op, ExpressionType lhs, ExpressionType rhs, ExpressionType& result) -> PartialResult
{
ASSERT(op == Sub32 || op == Sub64);
result = op == Sub32 ? g32() : g64();
if (isValidForm(op, Arg::Tmp, Arg::Tmp, Arg::Tmp)) {
append(op, lhs, rhs, result);
return { };
}
RELEASE_ASSERT(isX86());
// Sub a, b
// means
// b = b Sub a
append(Move, lhs, result);
append(op, rhs, result);
return { };
}
auto AirIRGenerator::addFloatingPointAbs(B3::Air::Opcode op, ExpressionType value, ExpressionType& result) -> PartialResult
{
RELEASE_ASSERT(op == AbsFloat || op == AbsDouble);
result = op == AbsFloat ? f32() : f64();
if (isValidForm(op, Arg::Tmp, Arg::Tmp)) {
append(op, value, result);
return { };
}
RELEASE_ASSERT(isX86());
if (op == AbsFloat) {
auto constant = g32();
append(Move, Arg::imm(static_cast<uint32_t>(~(1ull << 31))), constant);
append(Move32ToFloat, constant, result);
append(AndFloat, value, result);
} else {
auto constant = g64();
append(Move, Arg::bigImm(~(1ull << 63)), constant);
append(Move64ToDouble, constant, result);
append(AndDouble, value, result);
}
return { };
}
auto AirIRGenerator::addFloatingPointBinOp(Type type, B3::Air::Opcode op, ExpressionType lhs, ExpressionType rhs, ExpressionType& result) -> PartialResult
{
ASSERT(type.isF32() || type.isF64());
result = tmpForType(type);
if (isValidForm(op, Arg::Tmp, Arg::Tmp, Arg::Tmp)) {
append(op, lhs, rhs, result);
return { };
}
RELEASE_ASSERT(isX86());
// Op a, b
// means
// b = b Op a
append(moveOpForValueType(type), lhs, result);
append(op, rhs, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Ceil>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(CeilFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Mul>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Mul32, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Sub>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addIntegerSub(Sub32, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Le>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32DemoteF64>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(ConvertDoubleToFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Ne>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleNotEqualOrUnordered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Lt>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleLessThanAndOrdered), arg0, arg1, result);
return { };
}
auto AirIRGenerator::addFloatingPointMinOrMax(Type floatType, MinOrMax minOrMax, ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
ASSERT(floatType.isF32() || floatType.isF64());
result = tmpForType(floatType);
if (isARM64()) {
if (floatType.isF32())
append(m_currentBlock, minOrMax == MinOrMax::Max ? FloatMax : FloatMin, arg0, arg1, result);
else
append(m_currentBlock, minOrMax == MinOrMax::Max ? DoubleMax : DoubleMin, arg0, arg1, result);
return { };
}
BasicBlock* isEqual = m_code.addBlock();
BasicBlock* notEqual = m_code.addBlock();
BasicBlock* isLessThan = m_code.addBlock();
BasicBlock* notLessThan = m_code.addBlock();
BasicBlock* isGreaterThan = m_code.addBlock();
BasicBlock* isNaN = m_code.addBlock();
BasicBlock* continuation = m_code.addBlock();
auto branchOp = floatType.isF32() ? BranchFloat : BranchDouble;
append(m_currentBlock, branchOp, Arg::doubleCond(MacroAssembler::DoubleEqualAndOrdered), arg0, arg1);
m_currentBlock->setSuccessors(isEqual, notEqual);
append(notEqual, branchOp, Arg::doubleCond(MacroAssembler::DoubleLessThanAndOrdered), arg0, arg1);
notEqual->setSuccessors(isLessThan, notLessThan);
append(notLessThan, branchOp, Arg::doubleCond(MacroAssembler::DoubleGreaterThanAndOrdered), arg0, arg1);
notLessThan->setSuccessors(isGreaterThan, isNaN);
auto andOp = floatType.isF32() ? AndFloat : AndDouble;
auto orOp = floatType.isF32() ? OrFloat : OrDouble;
append(isEqual, minOrMax == MinOrMax::Max ? andOp : orOp, arg0, arg1, result);
append(isEqual, Jump);
isEqual->setSuccessors(continuation);
auto isLessThanResult = minOrMax == MinOrMax::Max ? arg1 : arg0;
append(isLessThan, moveOpForValueType(floatType), isLessThanResult, result);
append(isLessThan, Jump);
isLessThan->setSuccessors(continuation);
auto isGreaterThanResult = minOrMax == MinOrMax::Max ? arg0 : arg1;
append(isGreaterThan, moveOpForValueType(floatType), isGreaterThanResult, result);
append(isGreaterThan, Jump);
isGreaterThan->setSuccessors(continuation);
auto addOp = floatType.isF32() ? AddFloat : AddDouble;
append(isNaN, addOp, arg0, arg1, result);
append(isNaN, Jump);
isNaN->setSuccessors(continuation);
m_currentBlock = continuation;
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Min>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointMinOrMax(Types::F32, MinOrMax::Min, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32Max>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointMinOrMax(Types::F32, MinOrMax::Max, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Min>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointMinOrMax(Types::F64, MinOrMax::Min, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Max>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointMinOrMax(Types::F64, MinOrMax::Max, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Mul>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointBinOp(Types::F64, MulDouble, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32Div>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointBinOp(Types::F32, DivFloat, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32Clz>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(CountLeadingZeros32, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Copysign>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
// FIXME: We can have better codegen here for the imms and two operand forms on x86
// https://bugs.webkit.org/show_bug.cgi?id=193999
result = f32();
auto temp1 = g32();
auto sign = g32();
auto value = g32();
// FIXME: Try to use Imm where possible:
// https://bugs.webkit.org/show_bug.cgi?id=193999
append(MoveFloatTo32, arg1, temp1);
append(Move, Arg::bigImm(0x80000000), sign);
append(And32, temp1, sign, sign);
append(MoveDoubleTo64, arg0, temp1);
append(Move, Arg::bigImm(0x7fffffff), value);
append(And32, temp1, value, value);
append(Or32, sign, value, value);
append(Move32ToFloat, value, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64ConvertUI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
auto temp = g64();
append(Move32, arg0, temp);
append(ConvertInt64ToDouble, temp, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32ReinterpretI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(Move32ToFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64And>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g64();
append(And64, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Ne>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleNotEqualOrUnordered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Gt>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleGreaterThanAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Sqrt>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(SqrtFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Ge>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64GtS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::GreaterThan), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64GtU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::Above), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Eqz>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(Test64, Arg::resCond(MacroAssembler::Zero), arg0, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Div>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointBinOp(Types::F64, DivDouble, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32Add>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = f32();
append(AddFloat, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Or>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g64();
append(Or64, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32LeU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::BelowOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32LeS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::LessThanOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Ne>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::NotEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Clz>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
append(CountLeadingZeros64, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Neg>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
if (isValidForm(NegateFloat, Arg::Tmp, Arg::Tmp))
append(NegateFloat, arg0, result);
else {
auto constant = addConstant(Types::I32, bitwise_cast<uint32_t>(static_cast<float>(-0.0)));
auto temp = g32();
append(MoveFloatTo32, arg0, temp);
append(Xor32, constant, temp);
append(Move32ToFloat, temp, result);
}
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32And>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(And32, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32LtU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::Below), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Rotr>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I64, RotateRight64, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Abs>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
return addFloatingPointAbs(AbsDouble, arg0, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32LtS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::LessThan), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Eq>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::Equal), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Copysign>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
// FIXME: We can have better codegen here for the imms and two operand forms on x86
// https://bugs.webkit.org/show_bug.cgi?id=193999
result = f64();
auto temp1 = g64();
auto sign = g64();
auto value = g64();
append(MoveDoubleTo64, arg1, temp1);
append(Move, Arg::bigImm(0x8000000000000000), sign);
append(And64, temp1, sign, sign);
append(MoveDoubleTo64, arg0, temp1);
append(Move, Arg::bigImm(0x7fffffffffffffff), value);
append(And64, temp1, value, value);
append(Or64, sign, value, value);
append(Move64ToDouble, value, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32ConvertSI64>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(ConvertInt64ToFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Rotl>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
if (isARM64()) {
// ARM64 doesn't have a rotate left.
auto newShift = g64();
append(Move, arg1, newShift);
append(Neg64, newShift);
return addShift(Types::I64, RotateRight64, arg0, newShift, result);
} else
return addShift(Types::I64, RotateLeft64, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32Lt>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleLessThanAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64ConvertSI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(ConvertInt32ToDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Eq>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareDouble, Arg::doubleCond(MacroAssembler::DoubleEqualAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Le>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleLessThanOrEqualAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Ge>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleGreaterThanOrEqualAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32ShrU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I32, Urshift32, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32ConvertUI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
auto temp = g64();
append(Move32, arg0, temp);
append(ConvertInt64ToFloat, temp, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32ShrS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I32, Rshift32, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32GeU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::AboveOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Ceil>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(CeilDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32GeS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::GreaterThanOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Shl>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I32, Lshift32, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Floor>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(FloorDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Xor>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Xor32, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Abs>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
return addFloatingPointAbs(AbsFloat, arg0, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32Mul>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = f32();
append(MulFloat, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Sub>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addIntegerSub(Sub64, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32ReinterpretF32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(MoveFloatTo32, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Add>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Add32, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Sub>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addFloatingPointBinOp(Types::F64, SubDouble, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32Or>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Or32, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64LtU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::Below), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64LtS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::LessThan), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64ConvertSI64>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(ConvertInt64ToDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Xor>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g64();
append(Xor64, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64GeU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::AboveOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Mul>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g64();
append(Mul64, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Sub>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = f32();
if (isValidForm(SubFloat, Arg::Tmp, Arg::Tmp, Arg::Tmp))
append(SubFloat, arg0, arg1, result);
else {
RELEASE_ASSERT(isX86());
append(MoveFloat, arg0, result);
append(SubFloat, arg1, result);
}
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64PromoteF32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(ConvertFloatToDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Add>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = f64();
append(AddDouble, arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64GeS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::GreaterThanOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64ExtendUI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
append(Move32, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Ne>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
RELEASE_ASSERT(arg0 && arg1);
append(Compare32, Arg::relCond(MacroAssembler::NotEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64ReinterpretI64>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(Move64ToDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Eq>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleEqualAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Eq>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::Equal), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32Floor>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(FloorFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F32ConvertSI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f32();
append(ConvertInt32ToFloat, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Eqz>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(Test32, Arg::resCond(MacroAssembler::Zero), arg0, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64ReinterpretF64>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
append(MoveDoubleTo64, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64ShrS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I64, Rshift64, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I64ShrU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I64, Urshift64, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F64Sqrt>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
append(SqrtDouble, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Shl>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I64, Lshift64, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::F32Gt>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(CompareFloat, Arg::doubleCond(MacroAssembler::DoubleGreaterThanAndOrdered), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32WrapI64>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(Move32, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Rotl>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
if (isARM64()) {
// ARM64 doesn't have a rotate left.
auto newShift = g64();
append(Move, arg1, newShift);
append(Neg64, newShift);
return addShift(Types::I32, RotateRight32, arg0, newShift, result);
} else
return addShift(Types::I32, RotateLeft32, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32Rotr>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
return addShift(Types::I32, RotateRight32, arg0, arg1, result);
}
template<> auto AirIRGenerator::addOp<OpType::I32GtU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::Above), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64ExtendSI32>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
append(SignExtend32ToPtr, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Extend8S>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(SignExtend8To32, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32Extend16S>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g32();
append(SignExtend16To32, arg0, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Extend8S>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
auto temp = g32();
append(Move32, arg0, temp);
append(SignExtend8To32, temp, temp);
append(SignExtend32ToPtr, temp, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Extend16S>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
auto temp = g32();
append(Move32, arg0, temp);
append(SignExtend16To32, temp, temp);
append(SignExtend32ToPtr, temp, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Extend32S>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = g64();
auto temp = g32();
append(Move32, arg0, temp);
append(SignExtend32ToPtr, temp, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I32GtS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare32, Arg::relCond(MacroAssembler::GreaterThan), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::F64Neg>(ExpressionType arg0, ExpressionType& result) -> PartialResult
{
result = f64();
if (isValidForm(NegateDouble, Arg::Tmp, Arg::Tmp))
append(NegateDouble, arg0, result);
else {
auto constant = addConstant(Types::I64, bitwise_cast<uint64_t>(static_cast<double>(-0.0)));
auto temp = g64();
append(MoveDoubleTo64, arg0, temp);
append(Xor64, constant, temp);
append(Move64ToDouble, temp, result);
}
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64LeU>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::BelowOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64LeS>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g32();
append(Compare64, Arg::relCond(MacroAssembler::LessThanOrEqual), arg0, arg1, result);
return { };
}
template<> auto AirIRGenerator::addOp<OpType::I64Add>(ExpressionType arg0, ExpressionType arg1, ExpressionType& result) -> PartialResult
{
result = g64();
append(Add64, arg0, arg1, result);
return { };
}
template <size_t inlineCapacity>
PatchpointExceptionHandle AirIRGenerator::preparePatchpointForExceptions(B3::PatchpointValue* patch, Vector<ConstrainedTmp, inlineCapacity>& args)
{
++m_callSiteIndex;
if (!m_tryCatchDepth)
return { m_hasExceptionHandlers };
unsigned numLiveValues = 0;
forEachLiveValue([&] (Tmp tmp) {
++numLiveValues;
args.append(ConstrainedTmp(tmp, B3::ValueRep::LateColdAny));
});
patch->effects.exitsSideways = true;
return { m_hasExceptionHandlers, m_callSiteIndex, numLiveValues };
}
} } // namespace JSC::Wasm
#endif // ENABLE(WEBASSEMBLY_B3JIT)
|