1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765
|
/*========================== begin_copyright_notice ============================
Copyright (C) 2017-2023 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "GraphColor.h"
#include "BuildIR.h"
#include "DebugInfo.h"
#include "FlagSpillCleanup.h"
#include "FlowGraph.h"
#include "LinearScanRA.h"
#include "LocalRA.h"
#include "Optimizer.h"
#include "PointsToAnalysis.h"
#include "RADebug.h"
#include "RPE.h"
#include "Rematerialization.h"
#include "SCCAnalysis.h"
#include "SpillCleanup.h"
#include "SpillCode.h"
#include "SplitAlignedScalars.h"
#include "Timer.h"
#include <algorithm>
#include <cmath> // sqrt
#include <fstream>
#include <iostream>
#include <list>
#include <sstream>
#include <optional>
#include "common/LLVMWarningsPush.hpp"
#include <llvm/ADT/SmallString.h>
#include <llvm/ADT/StringRef.h>
#include "common/LLVMWarningsPop.hpp"
using namespace vISA;
#define GRAPH_COLOR_MEM_SIZE 16 * 1024
#define SCRATCH_MSG_LIMIT (128 * 1024)
#define SCRATCH_COMPRESS_THRESHOLD (12 * 1024)
const RAVarInfo GlobalRA::defaultValues;
const char GlobalRA::StackCallStr[] = "StackCall";
static const unsigned IN_LOOP_REFERENCE_COUNT_FACTOR = 4;
#define BANK_CONFLICT_HEURISTIC_INST 0.04
#define BANK_CONFLICT_HEURISTIC_REF_COUNT 0.25
#define BANK_CONFLICT_HEURISTIC_LOOP_ITERATION 5
#define BANK_CONFLICT_SEND_INST_CYCLE \
60 // Some send 200, some 400 we choose the small one
#define BANK_CONFLICT_SIMD8_OVERHEAD_CYCLE 1
#define BANK_CONFLICT_SIMD16_OVERHEAD_CYCLE 2
#define INTERNAL_CONFLICT_RATIO_HEURISTIC 0.25
#define NOMASK_BYTE 0x80
Interference::Interference(const LivenessAnalysis *l, GlobalRA &g)
: gra(g), kernel(g.kernel), lrs(gra.incRA.getLRs()),
builder(*g.kernel.fg.builder), maxId(l->getNumSelectedVar()),
rowSize(maxId / BITS_DWORD + 1),
splitStartId(l->getNumSplitStartID()), splitNum(l->getNumSplitVar()),
liveAnalysis(l), aug(*this, *l, g), incRA(g.incRA),
sparseIntf(g.intfStorage.sparseIntf), sparseMatrix(g.intfStorage.sparseMatrix) {
denseMatrixLimit = builder.getuint32Option(vISA_DenseMatrixLimit);
incRA.registerNextIter((G4_RegFileKind)l->getSelectedRF(), l, this);
}
criticalCmpForEndInterval::criticalCmpForEndInterval(GlobalRA &g) : gra(g) {}
bool criticalCmpForEndInterval::operator()(const QueueEntry &A, const QueueEntry &B) const {
return A.interval.end->getLexicalId() > B.interval.end->getLexicalId();
}
AugmentPriorityQueue::AugmentPriorityQueue(criticalCmpForEndInterval cmp)
: std::priority_queue<QueueEntry, std::vector<QueueEntry>,
criticalCmpForEndInterval>(cmp) {}
inline bool Interference::varSplitCheckBeforeIntf(unsigned v1,
unsigned v2) const {
const LiveRange *l1 = lrs[v1];
const LiveRange *l2 = lrs[v2];
if (!l1->getIsPartialDcl() && !l2->getIsPartialDcl()) {
return false;
}
// Don't do interference for two split declares
if (l1->getIsPartialDcl() && l2->getIsPartialDcl()) {
return true;
}
unsigned p1 = v1;
unsigned p2 = v2;
// Don't do inteference for child and parent delcares
if (l1->getIsPartialDcl()) {
p1 = l1->getParentLRID();
}
if (l2->getIsPartialDcl()) {
p2 = l2->getParentLRID();
}
if (p1 == p2) {
return true;
}
return false;
}
BankConflict BankConflictPass::setupBankAccordingToSiblingOperand(
BankConflict assignedBank, unsigned offset, bool oneGRFBank) {
BankConflict tgtBank;
vISA_ASSERT(assignedBank != BANK_CONFLICT_NONE,
"sibling bank is not assigned");
// Set according to sibling
tgtBank = (assignedBank == BANK_CONFLICT_FIRST_HALF_EVEN ||
assignedBank == BANK_CONFLICT_FIRST_HALF_ODD)
? (assignedBank == BANK_CONFLICT_FIRST_HALF_EVEN
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_EVEN)
: (assignedBank == BANK_CONFLICT_SECOND_HALF_EVEN
? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN);
// Adjust according to the offset
if (oneGRFBank) {
if (offset % 2) {
if (tgtBank == BANK_CONFLICT_SECOND_HALF_EVEN ||
tgtBank == BANK_CONFLICT_FIRST_HALF_EVEN) {
tgtBank = (tgtBank == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_ODD;
} else {
tgtBank = (tgtBank == BANK_CONFLICT_FIRST_HALF_ODD)
? BANK_CONFLICT_FIRST_HALF_EVEN
: BANK_CONFLICT_SECOND_HALF_EVEN;
}
}
} else {
if (offset % 4 >= 2) {
if (tgtBank == BANK_CONFLICT_SECOND_HALF_EVEN ||
tgtBank == BANK_CONFLICT_FIRST_HALF_EVEN) {
tgtBank = (tgtBank == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_ODD;
} else {
tgtBank = (tgtBank == BANK_CONFLICT_FIRST_HALF_ODD)
? BANK_CONFLICT_FIRST_HALF_EVEN
: BANK_CONFLICT_SECOND_HALF_EVEN;
}
}
}
return tgtBank;
}
void refNumBasedSort(const unsigned *refNum, unsigned *index) {
if (refNum[2] > refNum[1]) {
index[0] = 2;
index[1] = 1;
} else {
index[0] = 1;
index[1] = 2;
}
index[2] = 0;
return;
}
bool BankConflictPass::hasInternalConflict3Srcs(BankConflict *srcBC) {
if (((srcBC[0] == BANK_CONFLICT_SECOND_HALF_EVEN ||
srcBC[0] == BANK_CONFLICT_FIRST_HALF_EVEN) &&
(srcBC[1] == BANK_CONFLICT_SECOND_HALF_EVEN ||
srcBC[1] == BANK_CONFLICT_FIRST_HALF_EVEN) &&
(srcBC[2] == BANK_CONFLICT_SECOND_HALF_EVEN ||
srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)) ||
((srcBC[0] == BANK_CONFLICT_SECOND_HALF_ODD ||
srcBC[0] == BANK_CONFLICT_FIRST_HALF_ODD) &&
(srcBC[1] == BANK_CONFLICT_SECOND_HALF_ODD ||
srcBC[1] == BANK_CONFLICT_FIRST_HALF_ODD) &&
(srcBC[2] == BANK_CONFLICT_SECOND_HALF_ODD ||
srcBC[2] == BANK_CONFLICT_FIRST_HALF_ODD))) {
return true;
}
if ((srcBC[0] < BANK_CONFLICT_SECOND_HALF_EVEN &&
srcBC[1] < BANK_CONFLICT_SECOND_HALF_EVEN &&
srcBC[2] < BANK_CONFLICT_SECOND_HALF_EVEN) ||
(srcBC[0] >= BANK_CONFLICT_SECOND_HALF_EVEN &&
srcBC[1] >= BANK_CONFLICT_SECOND_HALF_EVEN &&
srcBC[2] >= BANK_CONFLICT_SECOND_HALF_EVEN)) {
return true;
}
return false;
}
void BankConflictPass::setupEvenOddBankConflictsForDecls(
G4_Declare *dcl_1, G4_Declare *dcl_2, unsigned offset1, unsigned offset2,
BankConflict &srcBC1, BankConflict &srcBC2) {
vISA_ASSERT(srcBC1 == BANK_CONFLICT_NONE, "Wrong Bank initial value");
vISA_ASSERT(srcBC2 == BANK_CONFLICT_NONE, "Wrong Bank initial value");
unsigned refNum1 = gra.getNumRefs(dcl_1);
unsigned refNum2 = gra.getNumRefs(dcl_2);
BankConflict bank1 = BANK_CONFLICT_NONE;
BankConflict bank2 = BANK_CONFLICT_NONE;
bank1 = (refNum1 >= refNum2) ? BANK_CONFLICT_FIRST_HALF_EVEN
: BANK_CONFLICT_SECOND_HALF_ODD;
bank2 = (bank1 == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
srcBC1 = bank1;
srcBC2 = bank2;
// Adjust only for the single bank allocation
if ((offset1 + offset2) % 2) {
if (refNum1 >= refNum2) {
bank2 = (bank2 == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
} else {
bank1 = (bank1 == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
gra.setBankConflict(dcl_1, bank1);
gra.setBankConflict(dcl_2, bank2);
return;
}
//
// inst opcode is G4_mad. This function sets up a simple state machine to
// prevent conflict between src 1 and 2 of mad inst. Following is how GRF file
// is divided in to banks: bank-block A = 0, 2, 4, 6, ..., 62 bank-block B = 1,
// 3, 5, 7, ..., 63 bank-block C = 64, 66, 68, ..., 126 bank-block D = 65, 67,
// 69, ..., 127
//
// For ternary ops, if src1 and src2 are to the same bank then there will be an
// access collision. But unary and binary ops will have no collision, no matter
// what registers they use. The reason is second and third src operands are read
// in the same clock cycle, which is different than when src0 operand is read.
// This is true upto pre-SKL.
//
// Bank Conflict Herustics:
// 1. Try to balance the used registers in two banks for the potential
// conflicted registers.
// 2. reference number is used to decide which to be assigned first
// 3. When conflict detected, bank can be updated according to the reference
// count.
//
void BankConflictPass::setupBankConflictsOneGRFOld(G4_INST *inst,
int &bank1RegNum,
int &bank2RegNum,
float GRFRatio,
unsigned &internalConflict) {
BankConflict srcBC[3];
unsigned regNum[3];
unsigned refNum[3];
unsigned offset[3];
G4_Declare *dcls[3];
G4_Declare *opndDcls[3];
int bank_num = 0;
for (int i = 0; i < 3; i++) {
dcls[i] = nullptr;
opndDcls[i] = nullptr;
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion() || src->isAccReg()) {
// bank conflict not possible
return;
}
dcls[i] = GetTopDclFromRegRegion(src);
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
regNum[i] = dcls[i]->getNumRows();
refNum[i] = gra.getNumRefs(dcls[i]);
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
srcBC[i] = gra.getBankConflict(dcls[i]);
if (src->getBase()->asRegVar()->isPhyRegAssigned()) {
unsigned reg =
src->getBase()->asRegVar()->getPhyReg()->asGreg()->getRegNum();
if ((reg + offset[i]) < SECOND_HALF_BANK_START_GRF) {
srcBC[i] = ((reg + offset[i]) % 2) ? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
} else {
srcBC[i] = ((reg + offset[i]) % 2) ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_EVEN;
}
if (reg < SECOND_HALF_BANK_START_GRF) {
bank1RegNum += regNum[i];
} else {
bank2RegNum += regNum[i];
}
gra.setBankConflict(dcls[i], srcBC[i]);
} else if (srcBC[i] != BANK_CONFLICT_NONE) {
if (offset[i] % 2) {
// Get operand's bank from declare's bank
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN ||
srcBC[i] == BANK_CONFLICT_FIRST_HALF_ODD) {
srcBC[i] = (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
} else {
srcBC[i] = (srcBC[i] == BANK_CONFLICT_SECOND_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_EVEN;
}
}
}
if (i > 0) {
bank_num += srcBC[i];
}
}
// In case src1 and src2 share same declare, i.e. use same register
if (bank_num == 0 && dcls[1] == dcls[2]) {
BankConflict bank1 = ((bank1RegNum * GRFRatio) > bank2RegNum)
? BANK_CONFLICT_SECOND_HALF_EVEN
: BANK_CONFLICT_FIRST_HALF_EVEN;
gra.setBankConflict(dcls[1], bank1);
srcBC[1] = bank1;
srcBC[2] = bank1;
bank_num += bank1 * 2;
if (bank1 < BANK_CONFLICT_SECOND_HALF_EVEN) {
bank1RegNum += regNum[1];
} else {
bank2RegNum += regNum[1];
}
}
// No bank assigned to src 1, 2.
// assign the two delcares into different bundles/banks.
if (bank_num == 0) {
BankConflict bank1 = BANK_CONFLICT_NONE;
BankConflict bank2 = BANK_CONFLICT_NONE;
bool bank1First = false;
if (GRFRatio == 1.0) {
// For global RA: Try to reduce the size of bank 2
if ((float)refNum[1] / regNum[1] >= (float)refNum[2] / regNum[2]) {
bank1 = BANK_CONFLICT_SECOND_HALF_EVEN;
bank2 = BANK_CONFLICT_FIRST_HALF_ODD;
bank1First = true;
} else {
bank2 = BANK_CONFLICT_SECOND_HALF_EVEN;
bank1 = BANK_CONFLICT_FIRST_HALF_ODD;
}
} else {
// For local RA: Try to balance two banks
if (refNum[1] >= refNum[2]) {
bank1 = ((bank1RegNum * GRFRatio) > bank2RegNum)
? BANK_CONFLICT_SECOND_HALF_EVEN
: BANK_CONFLICT_FIRST_HALF_EVEN;
bank2 = (bank1 == BANK_CONFLICT_SECOND_HALF_EVEN)
? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_ODD;
bank1First = true;
} else {
bank2 = (bank1RegNum * GRFRatio) > bank2RegNum
? BANK_CONFLICT_SECOND_HALF_EVEN
: BANK_CONFLICT_FIRST_HALF_EVEN;
bank1 = (bank2 == BANK_CONFLICT_SECOND_HALF_EVEN)
? BANK_CONFLICT_FIRST_HALF_ODD
: BANK_CONFLICT_SECOND_HALF_ODD;
}
}
// Adjust only for the single bank allocation
if ((offset[1] + offset[2]) % 2) {
if (bank1First) {
bank2 = (bank2 == BANK_CONFLICT_FIRST_HALF_ODD)
? BANK_CONFLICT_FIRST_HALF_EVEN
: BANK_CONFLICT_SECOND_HALF_EVEN;
} else {
bank1 = (bank1 == BANK_CONFLICT_SECOND_HALF_ODD)
? BANK_CONFLICT_SECOND_HALF_EVEN
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
if (bank1 >= BANK_CONFLICT_SECOND_HALF_EVEN) {
bank2RegNum += regNum[1];
bank1RegNum += regNum[2];
} else {
bank1RegNum += regNum[1];
bank2RegNum += regNum[2];
}
gra.setBankConflict(dcls[1], bank1);
gra.setBankConflict(dcls[2], bank2);
} else {
if (srcBC[1] == BANK_CONFLICT_NONE || srcBC[2] == BANK_CONFLICT_NONE) {
// One source operand is assigned bank already
if (srcBC[2] == BANK_CONFLICT_NONE) {
srcBC[2] =
setupBankAccordingToSiblingOperand(srcBC[1], offset[2], true);
gra.setBankConflict(dcls[2], srcBC[2]);
if (srcBC[2] < BANK_CONFLICT_SECOND_HALF_EVEN)
bank1RegNum += regNum[2];
else
bank2RegNum += regNum[2];
} else {
srcBC[1] =
setupBankAccordingToSiblingOperand(srcBC[2], offset[1], true);
gra.setBankConflict(dcls[1], srcBC[1]);
if (srcBC[1] < BANK_CONFLICT_SECOND_HALF_EVEN)
bank1RegNum += regNum[1];
else
bank2RegNum += regNum[1];
}
} else if (dcls[1] != dcls[2]) {
if (((srcBC[1] == BANK_CONFLICT_SECOND_HALF_EVEN ||
srcBC[1] == BANK_CONFLICT_FIRST_HALF_EVEN) &&
(srcBC[2] == BANK_CONFLICT_SECOND_HALF_EVEN ||
srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)) ||
((srcBC[1] == BANK_CONFLICT_SECOND_HALF_ODD ||
srcBC[1] == BANK_CONFLICT_FIRST_HALF_ODD) &&
(srcBC[2] == BANK_CONFLICT_SECOND_HALF_ODD ||
srcBC[2] == BANK_CONFLICT_FIRST_HALF_ODD))) {
internalConflict++;
}
if ((srcBC[1] < BANK_CONFLICT_SECOND_HALF_EVEN &&
srcBC[2] < BANK_CONFLICT_SECOND_HALF_EVEN) ||
(srcBC[1] >= BANK_CONFLICT_SECOND_HALF_EVEN &&
srcBC[2] >= BANK_CONFLICT_SECOND_HALF_EVEN)) {
internalConflict++;
}
}
}
}
void BankConflictPass::getBanks(G4_INST *inst, BankConflict *srcBC,
G4_Declare **dcls, G4_Declare **opndDcls,
unsigned *offset) {
for (int i = 0; i < 3; i++) {
dcls[i] = nullptr;
opndDcls[i] = nullptr;
srcBC[i] = BANK_CONFLICT_NONE;
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion() || src->isAccReg()) {
return;
}
dcls[i] = GetTopDclFromRegRegion(src);
if (!dcls[i]) {
continue;
}
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
srcBC[i] = gra.getBankConflict(dcls[i]);
if (src->getBase()->asRegVar()->isPhyRegAssigned()) {
unsigned reg =
src->getBase()->asRegVar()->getPhyReg()->asGreg()->getRegNum();
srcBC[i] = ((reg + offset[i]) % 2) ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
} else if (srcBC[i] != BANK_CONFLICT_NONE) {
if (offset[i] % 2) {
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[i] = BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
}
}
return;
}
void BankConflictPass::getPrevBanks(G4_INST *inst, BankConflict *srcBC,
G4_Declare **dcls, G4_Declare **opndDcls,
unsigned *offset) {
// We only care about ALU instructions which have a max number of 3 sources.
int execSize[3];
for (int i = 1; i < 3; i++) {
dcls[i] = nullptr;
opndDcls[i] = nullptr;
srcBC[i] = BANK_CONFLICT_NONE;
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion()) {
return;
}
dcls[i] = GetTopDclFromRegRegion(src);
if (dcls[i]->getRegFile() != G4_GRF) {
return;
}
execSize[i] = src->getLinearizedEnd() - src->getLinearizedStart() + 1;
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
srcBC[i] = gra.getBankConflict(dcls[i]);
if (src->getBase()->asRegVar()->isPhyRegAssigned()) {
unsigned reg =
src->getBase()->asRegVar()->getPhyReg()->asGreg()->getRegNum();
srcBC[i] = ((reg + offset[i]) % 2) ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
} else if (srcBC[i] != BANK_CONFLICT_NONE) {
if (offset[i] % 2) {
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[i] = BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
}
if (execSize[i] > 32) {
srcBC[i] = (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
return;
}
void BankConflictPass::setupBankForSrc0(G4_INST *inst, G4_INST *prevInst) {
BankConflict srcBC[3];
G4_Declare *dcls[3];
G4_Declare *opndDcls[3];
unsigned offset[3];
BankConflict prevSrcBC[3];
G4_Declare *prevDcls[3];
G4_Declare *prevOpndDcls[3];
unsigned prevOffset[3];
if (prevInst->isSend() || prevInst->isMath()) {
return;
}
getBanks(inst, srcBC, dcls, opndDcls, offset);
getPrevBanks(prevInst, prevSrcBC, prevDcls, prevOpndDcls, prevOffset);
if (dcls[0] != nullptr && srcBC[0] == BANK_CONFLICT_NONE &&
prevSrcBC[1] != BANK_CONFLICT_NONE &&
prevSrcBC[2] != BANK_CONFLICT_NONE) {
if (prevSrcBC[1] == prevSrcBC[2]) {
if (prevSrcBC[1] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[0] = offset[0] % 2 ? BANK_CONFLICT_FIRST_HALF_EVEN
: BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[0] = offset[0] % 2 ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[0], srcBC[0]);
}
}
return;
}
void BankConflictPass::setupBankConflictsforTwoGRFs(G4_INST *inst) {
BankConflict srcBC[3];
unsigned refNum[3];
unsigned offset[3];
G4_Declare *dcls[3];
G4_Declare *opndDcls[3];
int bank_num = 0;
int execSize[3];
for (int i = 0; i < 3; i++) {
dcls[i] = nullptr;
opndDcls[i] = nullptr;
execSize[i] = 0;
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion() || src->isAccReg()) {
// bank conflict not possible
return;
}
execSize[i] = src->getLinearizedEnd() - src->getLinearizedStart() + 1;
dcls[i] = GetTopDclFromRegRegion(src);
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
refNum[i] = gra.getNumRefs(dcls[i]);
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
srcBC[i] = gra.getBankConflict(dcls[i]);
if (src->getBase()->asRegVar()->isPhyRegAssigned()) {
unsigned reg =
src->getBase()->asRegVar()->getPhyReg()->asGreg()->getRegNum();
srcBC[i] = ((reg + offset[i]) % 2) ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
gra.setBankConflict(dcls[i], srcBC[i]);
} else if (srcBC[i] != BANK_CONFLICT_NONE) {
if (offset[i] % 2) {
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[i] = BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
}
if (i != 0) {
bank_num += srcBC[i];
}
}
int simd8SrcNum = 0;
for (int i = 0; i < 3; i++) {
if (execSize[i] <= 32) {
simd8SrcNum++;
}
}
// In case (src0) src1 and src2 use same declare, i.e. use same register
if ((dcls[0] == dcls[1]) && (dcls[1] == dcls[2])) {
return;
}
// No bank assigned to src operands,
// assign the two delcares into different bundles/banks.
if (simd8SrcNum <= 1) // All simd16, do even align
{
for (int i = 0; i < 3; i++) {
if (execSize[i] > 32) {
srcBC[i] = offset[i] % 2 ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
gra.setBankConflict(dcls[i], srcBC[i]);
}
}
} else if (bank_num == 0) {
unsigned index[3];
refNumBasedSort(refNum, index);
if (dcls[index[0]] != dcls[index[1]]) {
setupEvenOddBankConflictsForDecls(dcls[index[0]], dcls[index[1]],
offset[index[0]], offset[index[1]],
srcBC[index[0]], srcBC[index[1]]);
}
} else {
if (srcBC[1] != BANK_CONFLICT_NONE) {
srcBC[2] = (srcBC[1] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
if (offset[2] % 2) {
srcBC[2] = (srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[2], srcBC[2]);
} else {
srcBC[1] = (srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
if (offset[1] % 2) {
srcBC[1] = (srcBC[1] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[1], srcBC[1]);
}
}
}
bool BankConflictPass::isOddOffset(unsigned offset) const {
if (gra.kernel.fg.builder->oneGRFBankDivision()) {
return (offset % 2);
} else {
return ((offset % 4) / 2);
}
}
void BankConflictPass::setupBankConflictsforDPAS(G4_INST *inst) {
BankConflict srcBC[3];
unsigned refNum[3];
unsigned offset[3];
G4_Declare *dcls[3];
G4_Declare *opndDcls[3];
int bank_num = 0;
if (!inst->isDpas()) {
return;
}
for (int i = 0; i < 3; i += 1) {
opndDcls[i] = nullptr;
G4_Operand *src = inst->getSrc(i);
dcls[i] = GetTopDclFromRegRegion(src);
if (dcls[i]) {
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
refNum[i] = gra.getNumRefs(dcls[i]);
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
srcBC[i] = gra.getBankConflict(dcls[i]);
if (srcBC[i] != BANK_CONFLICT_NONE) {
if (isOddOffset(offset[i])) {
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[i] = BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
if (i != 1) {
bank_num++;
}
}
}
}
if (dcls[0] && dcls[1]) {
gra.addBundleConflictDcl(dcls[0], dcls[1], offset[0] - offset[1]);
gra.addBundleConflictDcl(dcls[1], dcls[0], offset[1] - offset[0]);
}
if (dcls[1] && dcls[2]) {
gra.addBundleConflictDcl(dcls[2], dcls[1], offset[2] - offset[1]);
gra.addBundleConflictDcl(dcls[1], dcls[2], offset[1] - offset[2]);
}
// In case src0 and src2 are null or use same declare, i.e. use same register
if (dcls[0] == dcls[2] || !dcls[0] || !dcls[2]) {
return;
}
if (bank_num == 0) {
srcBC[0] = refNum[0] > refNum[2] ? BANK_CONFLICT_FIRST_HALF_EVEN
: BANK_CONFLICT_SECOND_HALF_ODD;
srcBC[2] = refNum[0] > refNum[2] ? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
if (isOddOffset(offset[0])) {
srcBC[0] = (srcBC[0] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
if (isOddOffset(offset[2])) {
srcBC[2] = (srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[0], srcBC[0]);
gra.setBankConflict(dcls[2], srcBC[2]);
} else if (bank_num == 1) {
if (srcBC[0] != BANK_CONFLICT_NONE) {
srcBC[2] = (srcBC[0] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
if (isOddOffset(offset[2])) {
srcBC[2] = (srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[2], srcBC[2]);
} else {
srcBC[0] = (srcBC[2] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
if (offset[0] % 2) {
srcBC[0] = (srcBC[0] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[0], srcBC[0]);
}
}
#ifdef DEBUG_VERBOSE_ON
for (int i = 0; i < 3; i += 2) {
if (opndDcls[i]) {
printf("%s, ", opndDcls[i]->getName());
if (gra.getBankConflict(dcls[i]) == BANK_CONFLICT_FIRST_HALF_EVEN) {
printf("%s\n", "EVEN");
} else if (gra.getBankConflict(dcls[i]) ==
BANK_CONFLICT_SECOND_HALF_ODD) {
printf("%s\n", "ODD");
} else {
printf("%s\n", "NONE");
}
}
}
#endif
return;
}
void BankConflictPass::setupBundleConflictsforTwoSrcsInst(G4_INST *inst) {
vISA_ASSERT(inst->getNumSrc() == 2, "Only support two source operands instructions");
G4_Declare *dcls[2];
G4_Declare *opndDcls[2];
unsigned offset[2];
for (int i = 0; i < 2; i += 1) {
dcls[i] = nullptr;
opndDcls[i] = nullptr;
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion() || src->isAreg()) {
// bank conflict not possible
continue;
}
dcls[i] = GetTopDclFromRegRegion(src);
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
}
// Add potential bundle conflicts
if (dcls[0] && dcls[1]) {
gra.addBundleConflictDcl(dcls[0], dcls[1], offset[0] - offset[1]);
gra.addBundleConflictDcl(dcls[1], dcls[0], offset[1] - offset[0]);
}
return;
}
void BankConflictPass::setupBankConflictsforMad(G4_INST *inst) {
BankConflict srcBC[3];
unsigned offset[3];
G4_Declare *dcls[3];
G4_Declare *opndDcls[3];
BankConflict assignedBank = BANK_CONFLICT_NONE; // Flip for next
for (int i = 0; i < 3; i += 1) {
dcls[i] = nullptr;
opndDcls[i] = nullptr;
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion() || src->isAreg()) {
// bank conflict not possible
continue;
}
dcls[i] = GetTopDclFromRegRegion(src);
opndDcls[i] = src->getBase()->asRegVar()->getDeclare();
offset[i] = (opndDcls[i]->getOffsetFromBase() + src->getLeftBound()) /
gra.kernel.numEltPerGRF<Type_UB>();
srcBC[i] = gra.getBankConflict(dcls[i]);
if (srcBC[i] != BANK_CONFLICT_NONE) {
if (isOddOffset(offset[i])) {
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[i] = BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
if (assignedBank != BANK_CONFLICT_SECOND_HALF_EVEN) {
if (assignedBank == BANK_CONFLICT_NONE) {
assignedBank = srcBC[i];
} else if (assignedBank != srcBC[i]) {
assignedBank =
BANK_CONFLICT_SECOND_HALF_EVEN; // BANK_CONFLICT_SECOND_HALF_EVEN
// is used to represent all banks
// are assigned
}
}
}
}
// Add potential bundle conflicts, so that RA can handle it when option
// -enableBundleCR with value 2 or 3
if (gra.kernel.getuInt32Option(vISA_enableBundleCR) & 2) {
if (dcls[0] && dcls[1]) {
gra.addBundleConflictDcl(dcls[0], dcls[1], offset[0] - offset[1]);
gra.addBundleConflictDcl(dcls[1], dcls[0], offset[1] - offset[0]);
}
if (dcls[1] && dcls[2]) {
gra.addBundleConflictDcl(dcls[2], dcls[1], offset[2] - offset[1]);
gra.addBundleConflictDcl(dcls[1], dcls[2], offset[1] - offset[2]);
}
}
for (int k = 0; k < 2; k++) {
for (int i = 2; i != -1; i--) {
if (!dcls[i]) {
continue;
}
LocalLiveRange *lr = gra.getLocalLR(dcls[i]);
if (!lr || (k == 0 && !lr->isLiveRangeLocal())) {
continue;
}
if (k == 1 && lr->isLiveRangeLocal()) {
continue;
}
if (assignedBank == BANK_CONFLICT_SECOND_HALF_EVEN) {
continue;
}
srcBC[i] = gra.getBankConflict(dcls[i]);
if (srcBC[i] != BANK_CONFLICT_NONE) {
if (isOddOffset(offset[i])) {
if (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN) {
srcBC[i] = BANK_CONFLICT_SECOND_HALF_ODD;
} else {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
}
}
if (assignedBank == BANK_CONFLICT_NONE) {
assignedBank = srcBC[i];
} else if (srcBC[i] != assignedBank) {
assignedBank = BANK_CONFLICT_SECOND_HALF_EVEN;
}
continue;
}
if (assignedBank == BANK_CONFLICT_NONE) {
srcBC[i] = BANK_CONFLICT_FIRST_HALF_EVEN;
assignedBank = srcBC[i];
if (isOddOffset(offset[i])) {
srcBC[i] = (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[i], srcBC[i]);
} else {
srcBC[i] = (assignedBank == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
if (isOddOffset(offset[i])) {
srcBC[i] = (srcBC[i] == BANK_CONFLICT_FIRST_HALF_EVEN)
? BANK_CONFLICT_SECOND_HALF_ODD
: BANK_CONFLICT_FIRST_HALF_EVEN;
}
gra.setBankConflict(dcls[i], srcBC[i]);
assignedBank = BANK_CONFLICT_SECOND_HALF_EVEN;
}
}
}
#ifdef DEBUG_VERBOSE_ON
printf("$%d:\n", inst->getVISAId());
for (int i = 0; i < 3; i++) {
if (dcls[i]) {
printf("%s, ", dcls[i]->getName());
if (gra.getBankConflict(dcls[i]) == BANK_CONFLICT_FIRST_HALF_EVEN) {
printf("%s\n", "EVEN");
} else if (gra.getBankConflict(dcls[i]) ==
BANK_CONFLICT_SECOND_HALF_ODD) {
printf("%s\n", "ODD");
} else {
printf("%s\n", "NONE");
}
}
}
printf("\n");
#endif
return;
}
void BankConflictPass::setupBankConflictsForBB(G4_BB *bb,
unsigned &threeSourceInstNum,
unsigned &sendInstNum,
unsigned numRegLRA,
unsigned &internalConflict) {
int bank1RegNum = 0;
int bank2RegNum = 0;
float GRFRatio = 0;
G4_INST *prevInst = nullptr;
if (numRegLRA) {
GRFRatio = ((float)(numRegLRA - SECOND_HALF_BANK_START_GRF)) /
SECOND_HALF_BANK_START_GRF;
}
for (auto i = bb->rbegin(), rend = bb->rend(); i != rend; i++) {
G4_INST *inst = (*i);
if (inst->getNumSrc() == 3 && !inst->isSend()) {
threeSourceInstNum++;
setupBankConflictsOneGRFOld(inst, bank1RegNum, bank2RegNum, GRFRatio,
internalConflict);
}
if (inst->isSend() && !inst->isEOT()) {
// Why only data port read causes issue?
if (inst->getMsgDesc()->isRead()) {
sendInstNum++;
}
}
}
if ((float)threeSourceInstNum / bb->size() > 0.1) {
if (!gra.kernel.fg.builder->lowHighBundle() &&
gra.kernel.fg.builder->hasEarlyGRFRead()) {
for (G4_INST *inst : *bb) {
if (prevInst && inst->getNumSrc() == 3 && !inst->isSend()) {
setupBankForSrc0(inst, prevInst);
}
prevInst = inst;
}
}
}
}
void BankConflictPass::setupBankConflictsForBBTGL(G4_BB *bb,
unsigned &threeSourceInstNum,
unsigned &sendInstNum,
unsigned numRegLRA,
unsigned &internalConflict) {
G4_INST *prevInst = nullptr;
for (auto i = bb->rbegin(), rend = bb->rend(); i != rend; i++) {
G4_INST *inst = (*i);
if (inst->isSend() || inst->isCFInst() || inst->isLabel() ||
inst->isOptBarrier()) {
if (inst->isSend() && !inst->isEOT()) {
// Why only data port read causes issue?
if (inst->getMsgDesc()->isRead()) {
sendInstNum++;
}
}
continue;
}
if (inst->getNumSrc() >= 3) {
threeSourceInstNum++;
if (inst->isDpas()) {
threeSourceInstNum += 8;
hasDpasInst = true;
setupBankConflictsforDPAS(inst);
} else {
setupBankConflictsforMad(inst);
}
} else if (!forGlobal &&
inst->getNumSrc() == 2) {
if (gra.forceBCR) {
threeSourceInstNum++;
setupBankConflictsforMad(inst);
}
if (gra.twoSrcBundleBCR) {
threeSourceInstNum++;
setupBundleConflictsforTwoSrcsInst(inst);
}
}
}
if ((float)threeSourceInstNum / bb->size() > 0.1) {
if (!gra.kernel.fg.builder->lowHighBundle() &&
gra.kernel.fg.builder->hasEarlyGRFRead()) {
for (G4_INST *inst : *bb) {
if (prevInst && inst->getNumSrc() == 3 && !inst->isSend()) {
setupBankForSrc0(inst, prevInst);
}
prevInst = inst;
}
}
}
}
// Use for BB sorting according to the loop nest level and the BB size.
bool compareBBLoopLevel(G4_BB *bb1, G4_BB *bb2) {
if (bb1->getNestLevel() > bb2->getNestLevel()) {
return true;
} else if (bb1->getNestLevel() == bb2->getNestLevel()) {
return bb1->size() > bb2->size();
}
return false;
}
/*
* output:
* threeSourceCandidate, if there are enough three source instructions
* return value, if do bank confliction reduction to RR RA.
*/
bool BankConflictPass::setupBankConflictsForKernel(bool doLocalRR,
bool &threeSourceCandidate,
unsigned numRegLRA,
bool &highInternalConflict) {
unsigned threeSourceInstNumInKernel = 0;
unsigned internalConflict = 0;
unsigned instNumInKernel = 0;
unsigned sendInstNumInKernel = 0;
std::vector<G4_BB *> orderedBBs(gra.kernel.fg.cbegin(), gra.kernel.fg.cend());
std::sort(orderedBBs.begin(), orderedBBs.end(), compareBBLoopLevel);
for (auto bb : orderedBBs) {
unsigned instNum = 0;
unsigned sendInstNum = 0;
unsigned threeSourceInstNum = 0;
unsigned conflicts = 0;
unsigned loopNestLevel = 0;
if (gra.kernel.fg.builder->lowHighBundle()) {
setupBankConflictsForBB(bb, threeSourceInstNum, sendInstNum, numRegLRA,
conflicts);
} else {
setupBankConflictsForBBTGL(bb, threeSourceInstNum, sendInstNum, numRegLRA,
conflicts);
}
loopNestLevel = bb->getNestLevel() + 1;
if (threeSourceInstNum) {
instNum = (uint32_t)bb->size() * loopNestLevel *
BANK_CONFLICT_HEURISTIC_LOOP_ITERATION;
threeSourceInstNum = threeSourceInstNum * loopNestLevel *
BANK_CONFLICT_HEURISTIC_LOOP_ITERATION;
sendInstNum =
sendInstNum * loopNestLevel * BANK_CONFLICT_HEURISTIC_LOOP_ITERATION;
conflicts =
conflicts * loopNestLevel * BANK_CONFLICT_HEURISTIC_LOOP_ITERATION;
internalConflict += conflicts;
threeSourceInstNumInKernel += threeSourceInstNum;
instNumInKernel += instNum;
sendInstNumInKernel += sendInstNum;
}
}
if (!threeSourceInstNumInKernel ||
(float)threeSourceInstNumInKernel / instNumInKernel <
BANK_CONFLICT_HEURISTIC_INST) {
return false;
}
highInternalConflict =
((float)internalConflict / threeSourceInstNumInKernel) >
INTERNAL_CONFLICT_RATIO_HEURISTIC;
// Bank conflict reduction is done only when there is enough three source
// instructions.
threeSourceCandidate = true;
if (doLocalRR && sendInstNumInKernel) {
if (!hasDpasInst && (sendInstNumInKernel > threeSourceInstNumInKernel)) {
return false;
}
}
return true;
}
bool GlobalRA::areAllDefsNoMask(G4_Declare *dcl) {
bool retval = true;
auto &maskUsed = getMask(dcl);
if (maskUsed.size() > 0 &&
getAugmentationMask(dcl) != AugmentationMasks::NonDefault) {
auto byteSize = dcl->getByteSize();
for (unsigned i = 0; i < byteSize; i++) {
if (maskUsed[i] != NOMASK_BYTE) {
retval = false;
break;
}
}
} else {
if (getAugmentationMask(dcl) == AugmentationMasks::NonDefault)
retval = true;
else
retval = false;
}
return retval;
}
BankAlign GlobalRA::getBankAlign(const G4_Declare *dcl) const {
const IR_Builder *builder = kernel.fg.builder;
switch (getBankConflict(dcl)) {
case BANK_CONFLICT_FIRST_HALF_EVEN:
case BANK_CONFLICT_SECOND_HALF_EVEN:
return builder->oneGRFBankDivision() ? BankAlign::Even
: BankAlign::Even2GRF;
case BANK_CONFLICT_FIRST_HALF_ODD:
case BANK_CONFLICT_SECOND_HALF_ODD:
return builder->oneGRFBankDivision() ? BankAlign::Odd : BankAlign::Odd2GRF;
default:
return BankAlign::Either;
}
}
void GlobalRA::emitFGWithLiveness(const LivenessAnalysis &liveAnalysis) const {
VISA_DEBUG_VERBOSE({
for (G4_BB *bb : kernel.fg) {
std::cout << "\n"
<< "-------------------------------------------------------"
"----------";
std::cout << "\nBB" << bb->getId() << ":";
std::cout << "\nPreds: ";
for (const G4_BB *pred : bb->Preds)
std::cout << "BB" << pred->getId() << ", ";
std::cout << "\nSuccs: ";
for (const G4_BB *succ : bb->Succs)
std::cout << "BB" << succ->getId() << ", ";
if (localRAEnable) {
if (auto summary = getBBLRASummary(bb)) {
std::cout << "\nLocal RA: ";
for (unsigned i = 0; i < kernel.getNumRegTotal(); i++) {
if (summary->isGRFBusy(i))
std::cout << "r" << i << ", ";
}
}
}
std::cout << "\nGen: ";
for (const G4_Declare *dcl : kernel.Declares) {
if (dcl->getAliasDeclare())
continue;
if (dcl->getRegVar()->isRegAllocPartaker()) {
if (liveAnalysis.use_gen[bb->getId()].test(
dcl->getRegVar()->getId())) {
std::cout << dcl->getName() << ", ";
}
}
}
std::cout << "\nKill: ";
for (const G4_Declare *dcl : kernel.Declares) {
if (dcl->getAliasDeclare())
continue;
if (dcl->getRegVar()->isRegAllocPartaker()) {
if (liveAnalysis.use_kill[bb->getId()].test(
dcl->getRegVar()->getId())) {
std::cout << dcl->getName() << ", ";
}
}
}
std::cout << "\nLive-in: ";
for (const G4_Declare *dcl : kernel.Declares) {
if (dcl->getAliasDeclare())
continue;
if (dcl->getRegVar()->isRegAllocPartaker()) {
if (liveAnalysis.isLiveAtEntry(bb, dcl->getRegVar()->getId())) {
std::cout << dcl->getName() << ", ";
}
}
}
std::cout << "\nLive-out: ";
for (const G4_Declare *dcl : kernel.Declares) {
if (dcl->getAliasDeclare())
continue;
if (dcl->getRegVar()->isRegAllocPartaker()) {
if (liveAnalysis.isLiveAtExit(bb, dcl->getRegVar()->getId())) {
std::cout << dcl->getName() << ", ";
}
}
}
std::cout << "\n";
bb->emit(COUT_ERROR);
}
});
}
void GlobalRA::reportSpillInfo(const LivenessAnalysis &liveness,
const GraphColor &coloring) const {
// Emit out interference graph of each spill candidate
// and if a spill candidate is a local range, emit its
// start and end line number in file.
const auto& lrs = coloring.getLiveRanges();
for (const vISA::LiveRange *slr : coloring.getSpilledLiveRanges()) {
if (slr->getRegKind() == G4_GRF) {
const G4_RegVar *spillVar = slr->getVar();
VISA_DEBUG_VERBOSE({
std::cout << "Spill candidate " << spillVar->getName() << " intf:";
std::cout << "\t(" << spillVar->getDeclare()->getTotalElems()
<< "):" << TypeSymbol(spillVar->getDeclare()->getElemType())
<< "\n";
});
if (getLocalLR(spillVar->getDeclare())) {
if (getLocalLR(spillVar->getDeclare())->isLiveRangeLocal()) {
[[maybe_unused]] int start, end;
unsigned dummy;
start = getLocalLR(spillVar->getDeclare())
->getFirstRef(dummy)
->getLineNo();
end = getLocalLR(spillVar->getDeclare())
->getLastRef(dummy)
->getLineNo();
VISA_DEBUG_VERBOSE(std::cout
<< "(Liverange is local starting at line #"
<< start << " and ending at line #" << end << ")"
<< "\n");
}
}
const Interference *intf = coloring.getIntf();
unsigned spillVarId = slr->getVar()->getId();
for (int i = 0; i < (int)liveness.getNumSelectedVar(); i++) {
if (intf->interfereBetween(spillVarId, i)) {
const G4_RegVar *intfRangeVar = lrs[i]->getVar();
(void)intfRangeVar;
VISA_DEBUG_VERBOSE(
std::cout << "\t" << intfRangeVar->getName() << "("
<< intfRangeVar->getDeclare()->getTotalElems() << "):"
<< TypeSymbol(
intfRangeVar->getDeclare()->getElemType()));
if (!lrs[i]->getPhyReg()) {
VISA_DEBUG_VERBOSE(std::cout << " --- spilled");
}
VISA_DEBUG_VERBOSE(std::cout << ",\n");
}
}
VISA_DEBUG_VERBOSE(std::cout << "\n\n");
}
}
}
LiveRange::LiveRange(G4_RegVar *v, GlobalRA &g)
: var(v), dcl(v->getDeclare()), regKind(dcl->getRegFile()), gra(g),
numRegNeeded(dcl->getNumRegNeeded()){
isCandidate = true;
}
void LiveRange::initializeForbidden() {
auto rf = gra.incRA.getSelectedRF();
if (LivenessAnalysis::livenessClass(rf, G4_ADDRESS)) {
setForbidden(forbiddenKind::FBD_ADDR);
} else if (LivenessAnalysis::livenessClass(rf, G4_FLAG)) {
setForbidden(forbiddenKind::FBD_FLAG);
} else if (LivenessAnalysis::livenessClass(rf, G4_SCALAR)) {
setForbidden(forbiddenKind::FBD_SCALAR);
} else {
setForbidden(forbiddenKind::FBD_RESERVEDGRF);
};
bool hasStackCall =
gra.kernel.fg.getHasStackCalls() || gra.kernel.fg.getIsStackCallFunc();
setCallerSaveBias(hasStackCall);
if (getRegKind() == G4_GRF) {
if (gra.kernel.fg.isPseudoVCADcl(dcl)) {
setForbidden(forbiddenKind::FBD_CALLERSAVE);
} else if (gra.kernel.fg.isPseudoVCEDcl(dcl)) {
setForbidden(forbiddenKind::FBD_CALLEESAVE);
} else if (dcl == gra.getOldFPDcl()) {
setForbidden(forbiddenKind::FBD_CALLERSAVE);
}
}
}
void LiveRange::initialize() {
if (gra.kernel.fg.isPseudoDcl(dcl)) {
setIsPseudoNode();
}
if (dcl->getIsPartialDcl()) {
if (G4_Declare *parentDcl = gra.getSplittedDeclare(dcl)) {
setParentLRID(parentDcl->getRegVar()->getId());
setIsPartialDcl();
}
}
if (dcl->getIsSplittedDcl()) {
setIsSplittedDcl(true);
}
setBC(gra.getBankConflict(dcl));
initializeForbidden();
}
LiveRange *LiveRange::createNewLiveRange(G4_Declare *dcl, GlobalRA &gra) {
auto &IncRAMem = gra.incRA.mem;
G4_RegVar *var = dcl->getRegVar();
vISA_ASSERT(!dcl->getAliasDeclare(),
"error: attempt to create LiveRange for non-root dcl");
auto *lr = new (IncRAMem) LiveRange(var, gra);
lr->initialize();
return lr;
}
void LiveRange::checkForInfiniteSpillCost(
G4_BB *bb, std::list<G4_INST *>::reverse_iterator &it) {
// G4_INST at *it defines liverange object (this ptr)
// If next instruction of iterator uses same liverange then
// it may be a potential infinite spill cost candidate.
// To confirm, following requirements should be fulfilled:
// a. this liverange is not a global
// b. this liverange is defined/used in these 2 instructions only
//
// The idea is for ranges marked with infinite spill cost,
// coloring will attempt to put them on top of stack so they
// have higher chance of getting a color. If a range that should
// be infinite spill cost is not marked as being so, the only
// downside is extra compile time spent in inserting spill code
// and then punting out when later spilled code will cause
// even more spills.
//
// The assumption is that current live-range is a current register
// allocation candidate.
//
G4_INST *curInst = (*it);
// Skip the check if curInst is a pseudoKill
// Otherwise, it may invalidate a previously marked infinite
// spill cost candidate, e.g.,
// pseudo_kill (1) P1(0,0)[1]:uw [Align1]
// mov (1) P1(0,0)[1]:uw TV1(8,0)[0;1,0]:uw [Align1, NoMask]
// (+P1.0) sel (16) V65(0,0)[1]:f TV0(0,0)[0;1,0]:f 0:f [Align1, H1]
if (curInst->isPseudoKill()) {
return;
}
// Check whether dst variable is a global
if (gra.isBlockLocal(this->getDcl()) == false) {
isCandidate = false;
isInfiniteCost = false;
return;
}
G4_DstRegRegion *dst = curInst->getDst();
// If cur instruction dst is indirect write then return
if (dst && dst->getRegAccess() == IndirGRF &&
dst->getBase()->asRegVar()->getId() == this->getVar()->getId()) {
return;
}
// isCandidate is set to true only for first definition ever seen.
// If more than 1 def if found this gets set to false.
const std::list<G4_INST *>::reverse_iterator rbegin = bb->rbegin();
if (this->isCandidate == true && it != rbegin) {
G4_INST *nextInst = NULL;
if (this->getRefCount() != 2 || (this->getRegKind() == G4_GRF &&
this->getDcl()->getAddressed() == true)) {
// If a liverange has > 2 refs then it
// cannot be a candidate.
// Also an address taken GRF is not a candidate.
// This represents an early exit.
isCandidate = false;
isInfiniteCost = false;
return;
}
// Skip all pseudo kills
std::list<G4_INST *>::reverse_iterator next = it;
while (true) {
if (next == rbegin) {
isCandidate = isInfiniteCost = false;
return;
}
--next;
// This is not a pseudo-kill instruction, then find
// the desired next instruction. Otherwise, continue.
nextInst = *next;
if (!(nextInst->isPseudoKill()))
break;
}
// Check whether this liverange is used in nextInst
for (unsigned i = 0, numSrc = nextInst->getNumSrc(); i < numSrc; i++) {
G4_Operand *src = nextInst->getSrc(i);
if (src && src->isSrcRegRegion() &&
src->getBase()->isRegAllocPartaker()) {
// src can be Direct/Indirect
G4_SrcRegRegion *srcRgn = src->asSrcRegRegion();
if (srcRgn->getRegAccess() == Direct && srcRgn->getBase()->isRegVar() &&
srcRgn->getBase()->asRegVar()->getId() == this->getVar()->getId()) {
// Def-use found back-to-back
isInfiniteCost = true;
// Identify no more candidates
isCandidate = false;
} else if (this->getRegKind() == G4_ADDRESS &&
srcRgn->getRegAccess() == IndirGRF &&
srcRgn->getBase()->isRegVar() &&
srcRgn->getBase()->asRegVar()->getId() ==
this->getVar()->getId()) {
// Def-use found back-to-back
isInfiniteCost = true;
// Identify no more candidates
isCandidate = false;
}
}
}
G4_DstRegRegion *nextDst = nextInst->getDst();
if (isCandidate == true && this->getRegKind() == G4_ADDRESS && nextDst &&
nextDst->getRegAccess() == IndirGRF && nextDst->getBase()->isRegVar() &&
nextDst->getBase()->asRegVar()->isRegAllocPartaker() &&
nextDst->getBase()->asRegVar()->getId() == this->getVar()->getId()) {
// Pattern found:
// A0=
// r[A0]=
isInfiniteCost = true;
// Identify no more candidates
isCandidate = false;
}
if (isCandidate == true && this->getRegKind() == G4_FLAG &&
nextInst->getPredicate() && nextInst->getPredicate()->getBase() &&
nextInst->getPredicate()->getBase()->isRegVar() &&
nextInst->getPredicate()->getBase()->asRegVar()->isRegAllocPartaker() &&
nextInst->getPredicate()->getBase()->asRegVar()->getId() ==
this->getVar()->getId()) {
// Pattern found:
// P0 = or cmp.P0 = <-- P0 defined
// (P0) ... <-- P0 used as predicate
isInfiniteCost = true;
// Identify no more candidates
isCandidate = false;
}
VISA_DEBUG_VERBOSE({
if (isInfiniteCost == true) {
std::cout
<< "Marking " << this->getDcl()->getName()
<< " as having infinite spill cost due to back-to-back def-use"
<< "\n";
}
});
// Once a def is seen, stop looking for more defs
isCandidate = false;
} else {
VISA_DEBUG_VERBOSE({
if (isInfiniteCost == true) {
std::cout << "Unmarking " << this->getDcl()->getName()
<< " as having infinite spill cost"
<< "\n";
}
});
isCandidate = false;
isInfiniteCost = false;
}
}
//
// return true, if live ranges v1 and v2 interfere
//
bool Interference::interfereBetween(unsigned v1, unsigned v2) const {
if (v1 > v2) {
std::swap(v1, v2);
}
if (useDenseMatrix()) {
unsigned col = v2 / BITS_DWORD;
return matrix[v1 * rowSize + col] & (1 << (v2 % BITS_DWORD));
} else {
auto &set1 = sparseMatrix[v1];
return set1.test(v2);
}
}
//
// init live vector with all live ranges that are live at the exit
// also set the next seq use of any live range that is live across to be INT_MAX
// to indicate that this live range does not have exclusive sequential uses and
// hence is not a candidate for being marked with an infinite spill cost.
//
void Interference::buildInterferenceAtBBExit(const G4_BB *bb,
SparseBitVector &live) {
// live must be empty at this point
live = liveAnalysis->use_out[bb->getId()];
live &= liveAnalysis->def_out[bb->getId()];
}
//
// Filter out partial or splitted declares in batch interference.
//
inline void Interference::filterSplitDclares(unsigned startIdx, unsigned endIdx,
unsigned n, unsigned col,
unsigned &elt, bool is_partial) {
if (is_partial) // Don't interference with parent
{
unsigned rowSplited = n / BITS_DWORD;
if (rowSplited == col) {
elt &= ~(1 << (n % BITS_DWORD));
}
}
// if current is splitted dcl, don't interference with any of its child nodes.
// if current is partial dcl, don't interference with any other child nodes.
if (col >= startIdx / BITS_DWORD && col < (endIdx / BITS_DWORD + 1)) {
unsigned selt = 0;
unsigned start_id = col * BITS_DWORD > startIdx ? 0 : startIdx % BITS_DWORD;
unsigned end_id =
(col + 1) * BITS_DWORD > endIdx ? endIdx % BITS_DWORD : BITS_DWORD;
for (unsigned i = start_id; i < end_id; i++) {
selt |= 1 << i;
}
elt &= ~selt;
}
return;
}
//
// set interference for all live ranges that are currently live
// for partial declares, following rules are applied
// a. current partial declare does not interference with any other partial
// declare b. current parent declare does not interference with its children
// declares, can children declare interference with parent declare? c. current
// partial declare does not interference with hybrid declares added by local RA,
// the reason is simple, these declares are assigned register already.
//
void Interference::buildInterferenceWithLive(const SparseBitVector &live,
unsigned i) {
// set interference between variable with index "i" and variable set in "live".
// j is the valid bit index in the live.
for (unsigned j : live) {
if (!varSplitCheckBeforeIntf(i, j)) {
if (j < i) {
safeSetInterference(j, i);
} else if (j > i) {
safeSetInterference(i, j);
}
}
}
const LiveRange *lr = lrs[i];
bool is_partial = lr->getIsPartialDcl();
bool is_splitted = lr->getIsSplittedDcl();
unsigned n = 0;
unsigned start_idx = 0; // The variable index of the first child declare, the
// child variables' indexes are contigious.
unsigned end_idx = 0; // The variable index of the last child declare
if (is_splitted) // if current is splitted dcl, don't interference with all
// its child nodes.
{
start_idx = lr->getDcl()->getSplitVarStartID();
end_idx = start_idx + gra.getSplitVarNum(lr->getDcl());
}
if (is_partial) // if current is partial dcl, don't interference with all
// other partial dcls, and it's parent dcl.
{
// n is the variable ID of the splitted(parent) declare
n = gra.getSplittedDeclare(lr->getDcl())->getRegVar()->getId();
start_idx = splitStartId;
end_idx = splitStartId + splitNum;
}
if (is_partial) { // Don't interference with parent
if (i < n) {
safeClearInterference(i, n);
} else {
safeClearInterference(n, i);
}
}
for (unsigned j = start_idx; j < end_idx; j++) { //Don't inteference with the child
if (j < i) {
safeClearInterference(j, i);
} else {
safeClearInterference(i, j);
}
}
}
void Interference::buildInterferenceWithSubDcl(unsigned lr_id, G4_Operand *opnd,
SparseBitVector &live, bool setLive,
bool setIntf) {
const G4_Declare *dcl = lrs[lr_id]->getDcl();
for (const G4_Declare *subDcl : gra.getSubDclList(dcl)) {
unsigned leftBound = gra.getSubOffset(subDcl);
unsigned rightBound = leftBound + subDcl->getByteSize() - 1;
if (!(opnd->getRightBound() < leftBound ||
rightBound < opnd->getLeftBound())) {
int subID = subDcl->getRegVar()->getId();
if (setIntf) {
buildInterferenceWithLive(live, subID);
}
if (setLive) {
live.set(subID);
}
}
}
return;
}
void Interference::buildInterferenceWithAllSubDcl(unsigned v1, unsigned v2) {
const G4_Declare *d1 = lrs[v1]->getDcl();
const G4_Declare *d2 = lrs[v2]->getDcl();
if (d1->getIsSplittedDcl() && !d2->getIsPartialDcl()) {
for (const G4_Declare *subDcl : gra.getSubDclList(d1)) {
int subID = subDcl->getRegVar()->getId();
checkAndSetIntf(v2, subID);
}
}
if (d2->getIsSplittedDcl() && !d1->getIsPartialDcl()) {
for (const G4_Declare *subDcl : gra.getSubDclList(d2)) {
int subID = subDcl->getRegVar()->getId();
checkAndSetIntf(v1, subID);
}
}
return;
}
//
// Bias the live ranges in "live" to be assigned the callee-save registers as
// they are live through a stack call. Exclude file scope variables as they are
// always save/restore before/after call and are better assigned to the
// caller-save space.
//
void Interference::addCalleeSaveBias(const SparseBitVector &live) {
for (unsigned i = 0; i < maxId; i++) {
if (live.test(i)) {
lrs[i]->setCallerSaveBias(false);
lrs[i]->setCalleeSaveBias(true);
}
}
}
void Interference::buildInterferenceAmongLiveOuts() {
// Mark interference between dcls marked as Output.
//
// Interference computation marks interference for a
// variable only when definition for that variable is
// seen, not otherwise.
//
// This method is useful when definition of such
// "Output" variables are emitted to program post RA.
//
// It is safe to mark interference between all "Output"
// dcls even when their definition is present in the program.
// First gather all Output dcls in a vector to avoid an O(N^2)
// lookup. Number of OutputDcls should be small.
std::vector<G4_Declare *> OutputDcls;
for (auto dcl : kernel.Declares) {
if (!dcl->getRegVar()->isRegAllocPartaker() || !dcl->isOutput())
continue;
OutputDcls.push_back(dcl);
}
for (auto dcl1 : OutputDcls) {
// dcl1 is RA partaker iter and is marked as Output
for (auto dcl2 : OutputDcls) {
if (dcl1 == dcl2)
continue;
checkAndSetIntf(dcl1->getRegVar()->getId(), dcl2->getRegVar()->getId());
}
}
}
void Interference::buildInterferenceAmongLiveIns() {
//
// Build interference between all live-ins. If all live-ins are only
// read then their interference will be skipped in earlier phase.
// For eg, arg and globals are both live-in. And both may only have
// uses in function and no def.
//
const G4_BB *entryBB = kernel.fg.getEntryBB();
for (auto it = liveAnalysis->globalVars.begin();
it != liveAnalysis->globalVars.end(); ++it) {
auto i = (*it);
if (liveAnalysis->isLiveAtEntry(entryBB, i)) {
// Mark reference can not gaurantee all the varaibles are local, update
// here
if (lrs[i]->getDcl()->getIsSplittedDcl()) {
lrs[i]->getDcl()->setIsSplittedDcl(false);
lrs[i]->setIsSplittedDcl(false);
}
auto nextIt = it;
for (auto nit = ++nextIt; nit != liveAnalysis->globalVars.end(); ++nit) {
auto j = (*nit);
if (liveAnalysis->isLiveAtEntry(entryBB, j)) {
if (lrs[i]->getDcl()->getRegFile() == G4_INPUT &&
lrs[i]->getVar()->getPhyReg() != NULL &&
lrs[j]->getDcl()->getRegFile() == G4_INPUT &&
lrs[j]->getVar()->getPhyReg() != NULL) {
continue;
} else {
if (!varSplitCheckBeforeIntf(i, j)) {
checkAndSetIntf(i, j);
}
}
}
}
}
}
}
void Interference::markInterferenceForSend(G4_BB *bb, G4_INST *inst,
G4_DstRegRegion *dst) {
bool isDstRegAllocPartaker = false;
bool isDstLocallyAssigned = false;
unsigned dstId = 0;
int dstPreg = 0, dstNumRows = 0;
if (dst->getBase()->isRegVar()) {
if (dst->getBase()->isRegAllocPartaker()) {
G4_DstRegRegion *dstRgn = dst;
isDstRegAllocPartaker = true;
dstId = ((G4_RegVar *)dstRgn->getBase())->getId();
} else if (gra.useLocalRA) {
LocalLiveRange *localLR = NULL;
G4_Declare *topdcl = GetTopDclFromRegRegion(dst);
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned()) {
int sreg;
G4_VarBase *preg = localLR->getPhyReg(sreg);
vISA_ASSERT(preg->isGreg(), "Register in dst was not GRF");
isDstLocallyAssigned = true;
dstPreg = preg->asGreg()->getRegNum();
dstNumRows = localLR->getTopDcl()->getNumRows();
}
}
if (isDstRegAllocPartaker || isDstLocallyAssigned) {
for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
G4_Operand *src = inst->getSrc(j);
if (src && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
if (src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
unsigned srcId =
src->asSrcRegRegion()->getBase()->asRegVar()->getId();
if (isDstRegAllocPartaker) {
if (!varSplitCheckBeforeIntf(dstId, srcId)) {
checkAndSetIntf(dstId, srcId);
buildInterferenceWithAllSubDcl(dstId, srcId);
}
} else {
for (int j = dstPreg, sum = dstPreg + dstNumRows; j < sum; j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (!varSplitCheckBeforeIntf(k, srcId)) {
checkAndSetIntf(k, srcId);
buildInterferenceWithAllSubDcl(k, srcId);
}
}
}
} else if (gra.useLocalRA && isDstRegAllocPartaker) {
LocalLiveRange *localLR = nullptr;
const G4_Declare *topdcl = GetTopDclFromRegRegion(src);
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned()) {
int sreg;
G4_VarBase *preg = localLR->getPhyReg(sreg);
int numrows = localLR->getTopDcl()->getNumRows();
vISA_ASSERT(preg->isGreg(), "Register in src was not GRF");
int reg = preg->asGreg()->getRegNum();
for (int j = reg, sum = reg + numrows; j < sum; j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (!varSplitCheckBeforeIntf(dstId, k)) {
checkAndSetIntf(dstId, k);
buildInterferenceWithAllSubDcl(dstId, k);
}
}
}
}
}
}
}
}
}
void Interference::setOutOfBoundForbidden(G4_Operand *opnd) {
G4_Declare *dcl = opnd->getBaseRegVarRootDeclare();
vISA_ASSERT(dcl, "NULL declare");
int dclEndGRF = (dcl->getByteSize() - 1) / builder.numEltPerGRF<Type_UB>();
int opndEndGRF = opnd->getLinearizedEnd() / builder.numEltPerGRF<Type_UB>();
unsigned lrId = ((G4_RegVar *)opnd->getBase())->getId();
LiveRange *lr = lrs[lrId];
if (lr && (opndEndGRF > dclEndGRF)) {
vISA_ASSERT((opndEndGRF - dclEndGRF) == 1,
"More register reservation required for svm gather");
lr->setForbidden(forbiddenKind::FBD_LASTGRF);
}
}
void Interference::setForbiddenGRFNumForSVMScatter(G4_INST *inst) {
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getBase()->isRegVar()) {
if (dst->getBase()->isRegAllocPartaker()) {
setOutOfBoundForbidden(dst);
}
}
for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
G4_Operand *src = inst->getSrc(j);
if (src && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
if (src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
setOutOfBoundForbidden(src);
}
}
}
return;
}
void Interference::markInterferenceToAvoidDstSrcOverlap(G4_BB *bb,
G4_INST *inst) {
bool isDstRegAllocPartaker = false;
bool isDstLocallyAssigned = false;
unsigned dstId = 0;
int dstPreg = 0, dstNumRows = 0;
bool dstOpndNumRows = false;
G4_DstRegRegion *dst = inst->getDst();
if (dst->getBase()->isRegVar() &&
(dst->getTopDcl()->getRegFile() == G4_GRF)) {
G4_Declare *dstDcl = dst->getTopDcl();
int dstOffset = dst->getLeftBound() / kernel.numEltPerGRF<Type_UB>();
bool isDstEvenAlign = gra.isEvenAligned(dstDcl);
if (dst->getBase()->isRegAllocPartaker()) {
isDstRegAllocPartaker = true;
dstId = ((G4_RegVar *)dst->getBase())->getId();
dstOpndNumRows = dst->getSubRegOff() * dst->getTypeSize() +
dst->getLinearizedEnd() - dst->getLinearizedStart() +
1 >
kernel.numEltPerGRF<Type_UB>();
} else if (gra.useLocalRA) {
LocalLiveRange *localLR = NULL;
G4_Declare *topdcl = GetTopDclFromRegRegion(dst);
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned()) {
int sreg;
G4_VarBase *preg = localLR->getPhyReg(sreg);
vISA_ASSERT(preg->isGreg(), "Register in dst was not GRF");
isDstLocallyAssigned = true;
dstPreg = preg->asGreg()->getRegNum();
dstNumRows = localLR->getTopDcl()->getNumRows();
dstOpndNumRows = dst->getSubRegOff() * dst->getTypeSize() +
dst->getLinearizedEnd() - dst->getLinearizedStart() + 1 >
kernel.numEltPerGRF<Type_UB>();
isDstEvenAlign = (dstPreg % 2 == 0);
}
}
if (isDstRegAllocPartaker || isDstLocallyAssigned) {
for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
if (inst->isDpas() && j != 1)
continue;
G4_Operand *src = inst->getSrc(j);
if (src != NULL && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
G4_SrcRegRegion *srcRgn = src->asSrcRegRegion();
G4_Declare *srcDcl = src->getTopDcl();
if (srcRgn->getRegAccess() == Direct &&
(src->getTopDcl()->getRegFile() == G4_GRF ||
src->getTopDcl()->getRegFile() == G4_INPUT)) {
int srcOffset =
src->getLeftBound() / kernel.numEltPerGRF<Type_UB>();
bool srcOpndNumRows =
srcRgn->getSubRegOff() * srcRgn->getTypeSize() +
srcRgn->getLinearizedEnd() -
srcRgn->getLinearizedStart() + 1 >
kernel.numEltPerGRF<Type_UB>();
int srcReg = 0;
bool isSrcEvenAlign = gra.isEvenAligned(srcDcl);
if (!src->asSrcRegRegion()->getBase()->isRegAllocPartaker() &&
gra.useLocalRA) {
int sreg;
LocalLiveRange *localLR = NULL;
G4_Declare *topdcl = GetTopDclFromRegRegion(src);
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned()) {
G4_VarBase *preg = localLR->getPhyReg(sreg);
vISA_ASSERT(preg->isGreg(), "Register in src was not GRF");
srcReg = preg->asGreg()->getRegNum();
isSrcEvenAlign = (srcReg % 2 == 0);
}
}
if (srcDcl->getRegFile() == G4_INPUT &&
srcDcl->getRegVar()->getPhyReg() != NULL &&
srcDcl->getRegVar()->getPhyReg()->isGreg()) {
srcReg = srcDcl->getRegVar()->getPhyReg()->asGreg()->getRegNum();
isSrcEvenAlign = (srcReg % 2 == 0);
}
if (dstOpndNumRows || srcOpndNumRows) {
if (!(isDstEvenAlign && isSrcEvenAlign &&
srcOffset % 2 == dstOffset % 2 && dstOpndNumRows &&
srcOpndNumRows)) {
if (src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
unsigned srcId =
src->asSrcRegRegion()->getBase()->asRegVar()->getId();
#ifdef DEBUG_VERBOSE_ON
printf("Src%d ", j);
inst->dump();
#endif
if (isDstRegAllocPartaker) {
if (!varSplitCheckBeforeIntf(dstId, srcId)) {
checkAndSetIntf(dstId, srcId);
buildInterferenceWithAllSubDcl(dstId, srcId);
}
} else {
for (int j = dstPreg, sum = dstPreg + dstNumRows; j < sum;
j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (!varSplitCheckBeforeIntf(k, srcId)) {
checkAndSetIntf(k, srcId);
buildInterferenceWithAllSubDcl(k, srcId);
}
}
}
} else if (gra.useLocalRA &&
isDstRegAllocPartaker) {
LocalLiveRange *localLR = NULL;
G4_Declare *topdcl = GetTopDclFromRegRegion(src);
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned()) {
int reg, sreg, numrows;
G4_VarBase *preg = localLR->getPhyReg(sreg);
numrows = localLR->getTopDcl()->getNumRows();
vISA_ASSERT(preg->isGreg(), "Register in src was not GRF");
reg = preg->asGreg()->getRegNum();
#ifdef DEBUG_VERBOSE_ON
printf("Src%d ", j);
inst->dump();
#endif
for (int j = reg, sum = reg + numrows; j < sum; j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (!varSplitCheckBeforeIntf(dstId, k)) {
checkAndSetIntf(dstId, k);
buildInterferenceWithAllSubDcl(dstId, k);
}
}
}
}
}
}
} else if (srcRgn->getRegAccess() == IndirGRF) {
// make every var in points-to set live
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(
srcRgn, bb);
for (auto &pt : pointsToSet) {
if (pt.var->isRegAllocPartaker()) {
unsigned srcId = pt.var->getId();
if (isDstRegAllocPartaker) {
if (!varSplitCheckBeforeIntf(dstId, srcId)) {
checkAndSetIntf(dstId, srcId);
buildInterferenceWithAllSubDcl(dstId, srcId);
}
} else {
for (int j = dstPreg, sum = dstPreg + dstNumRows; j < sum;
j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (!varSplitCheckBeforeIntf(k, srcId)) {
checkAndSetIntf(k, srcId);
buildInterferenceWithAllSubDcl(k, srcId);
}
}
}
}
}
}
}
}
}
}
}
uint32_t GlobalRA::getRefCount(int loopNestLevel) {
if (loopNestLevel == 0) {
return 1;
}
return (uint32_t)std::pow(IN_LOOP_REFERENCE_COUNT_FACTOR,
std::min(loopNestLevel, 8));
}
// handle return value interference for fcall
void Interference::buildInterferenceForFcall(
G4_BB *bb, SparseBitVector &live, G4_INST *inst,
std::list<G4_INST *>::reverse_iterator i, const G4_VarBase *regVar) {
vISA_ASSERT(inst->opcode() == G4_pseudo_fcall, "expect fcall inst");
if (regVar->isRegAllocPartaker()) {
unsigned id = static_cast<const G4_RegVar *>(regVar)->getId();
buildInterferenceWithLive(live, id);
updateLiveness(live, id, false);
}
}
bool GlobalRA::canIncreaseGRF(unsigned spillSize, bool infCostSpilled) {
// If we estimate insufficient # GRFs early on, we may end up
// spilling an infinite spill cost variable. As last ditch effort,
// we bump up # GRFs and retry compilation. If we estimate GRF
// config well, then we should never see infCostSpilled == true.
// Conditions to increase #GRFs assuming first RA iteration did not succeed:
// - Variable with inf spill cost, or
// - #GRFs selected and next larger one has same number of threads, or
// - Spill size is above threshold
if ((infCostSpilled || kernel.grfMode.hasLargerGRFSameThreads() ||
spillSize > kernel.grfMode.getSpillThreshold()) &&
!didGRFIncrease) {
if (kernel.updateKernelToLargerGRF()) {
// GRF successfully increased
RA_TRACE(std::cout << "\t--new GRF size " << kernel.getNumRegTotal()
<< ". Re-run RA\n ");
didGRFIncrease = true;
return true;
}
}
return false;
}
void Interference::buildInterferenceForDst(
G4_BB *bb, SparseBitVector &live, G4_INST *inst,
std::list<G4_INST *>::reverse_iterator i, G4_DstRegRegion *dst) {
if (dst->getBase()->isRegAllocPartaker()) {
unsigned id = ((G4_RegVar *)dst->getBase())->getId();
//
// In following code,
// pseudo_kill V10
// mov (8) V10, V11
//
// V10 and V11 do not interfere and can be assigned
// same register.
//
// Following condition skips marking interference for
// pseudo_kill nodes.
//
if (!inst->isPseudoKill() && !inst->isLifeTimeEnd()) {
buildInterferenceWithLive(live, id);
if (lrs[id]->getIsSplittedDcl()) {
buildInterferenceWithSubDcl(id, (G4_Operand *)dst, live, false, true);
}
}
//
// if the write does not cover the whole dst region, we should continue let
// the liveness propagate upwards
//
if (liveAnalysis->writeWholeRegion(bb, inst, dst) || inst->isPseudoKill()) {
updateLiveness(live, id, false);
if (lrs[id]->getIsSplittedDcl()) {
for (unsigned i = lrs[id]->getDcl()->getSplitVarStartID();
i < lrs[id]->getDcl()->getSplitVarStartID() +
gra.getSplitVarNum(lrs[id]->getDcl());
i++) {
live.reset(i); // kill all childs, there may be not used childs
// generated due to splitting, killed also.
}
}
}
} else if (dst->isIndirect() && liveAnalysis->livenessClass(G4_GRF)) {
//
// add interferences to the list of potential indirect destination accesses.
//
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(dst, bb);
for (auto &pt : pointsToSet) {
if (pt.var->isRegAllocPartaker()) {
buildInterferenceWithLive(live, pt.var->getId());
}
}
}
}
void Interference::buildInterferenceWithinBB(G4_BB *bb, SparseBitVector &live) {
DebugInfoState state;
for (auto i = bb->rbegin(); i != bb->rend(); i++) {
G4_INST *inst = (*i);
G4_DstRegRegion *dst = inst->getDst();
if (dst) {
buildInterferenceForDst(bb, live, inst, i, dst);
}
if (inst->opcode() == G4_pseudo_fcall) {
if (liveAnalysis->livenessClass(G4_GRF)) {
auto fcall = kernel.fg.builder->getFcallInfo(bb->back());
G4_Declare *arg = kernel.fg.builder->getStackCallArg();
G4_Declare *ret = kernel.fg.builder->getStackCallRet();
vISA_ASSERT(fcall != std::nullopt, "fcall info not found");
uint16_t retSize = fcall->getRetSize();
uint16_t argSize = fcall->getArgSize();
if (ret && retSize > 0 && ret->getRegVar()) {
buildInterferenceForFcall(bb, live, inst, i, ret->getRegVar());
}
if (arg && argSize > 0 && arg->getRegVar()) {
auto id = arg->getRegVar()->getId();
updateLiveness(live, id, true);
}
} else if (liveAnalysis->livenessClass(G4_ADDRESS)) {
// assume callee will use A0
auto A0Dcl = kernel.fg.fcallToPseudoDclMap[inst->asCFInst()].A0;
buildInterferenceWithLive(live, A0Dcl->getRegVar()->getId());
} else if (liveAnalysis->livenessClass(G4_FLAG)) {
// assume callee will use both F0 and F1
auto flagDcl = kernel.fg.fcallToPseudoDclMap[inst->asCFInst()].Flag;
buildInterferenceWithLive(live, flagDcl->getRegVar()->getId());
}
}
if (inst->isSend() && inst->asSendInst()->isSVMScatterRW() &&
inst->getExecSize() < g4::SIMD8) {
setForbiddenGRFNumForSVMScatter(inst);
}
if ((inst->isSend() || inst->isFillIntrinsic()) && !dst->isNullReg() &&
kernel.fg.builder->WaDisableSendSrcDstOverlap()) {
markInterferenceForSend(bb, inst, dst);
} else if (kernel.fg.builder->avoidDstSrcOverlap() && dst &&
!dst->isNullReg()) {
markInterferenceToAvoidDstSrcOverlap(bb, inst);
}
if (inst->isSplitSend() && !inst->getSrc(1)->isNullReg()) {
G4_SrcRegRegion *src0 = inst->getSrc(0)->asSrcRegRegion();
G4_SrcRegRegion *src1 = inst->getSrc(1)->asSrcRegRegion();
if (src0->getBase()->isRegAllocPartaker() &&
src1->getBase()->isRegAllocPartaker()) {
// src0 and src1 of split send may not overlap. In normal cases this is
// handled automatically as we add interference edge when we reach
// src0/src1's def. If one source is an undefined variable (this can
// happen for URB write payload) and the other an input, however, we
// could miss the interference edge between the two. So we add it
// explicitly here
int src0Id = src0->getBase()->asRegVar()->getId();
int src1Id = src1->getBase()->asRegVar()->getId();
checkAndSetIntf(src0Id, src1Id);
buildInterferenceWithAllSubDcl(src0Id, src1Id);
}
}
// DPAS: As part of same instruction, src1 should not have overlap with dst.
// Src0 and src2 are okay to have overlap
if (inst->isDpas() && !inst->getSrc(1)->isNullReg()) {
G4_SrcRegRegion *src1 = inst->getSrc(1)->asSrcRegRegion();
if (dst->getBase()->isRegAllocPartaker() &&
src1->getBase()->isRegAllocPartaker()) {
int dstId = dst->getBase()->asRegVar()->getId();
int src1Id = src1->getBase()->asRegVar()->getId();
checkAndSetIntf(dstId, src1Id);
buildInterferenceWithAllSubDcl(dstId, src1Id);
}
}
//
// process each source operand
//
for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
G4_Operand *src = inst->getSrc(j);
if (!src)
continue;
if (src->isSrcRegRegion()) {
G4_SrcRegRegion *srcRegion = src->asSrcRegRegion();
if (srcRegion->getBase()->isRegAllocPartaker()) {
unsigned id = ((G4_RegVar *)(srcRegion)->getBase())->getId();
if (!inst->isLifeTimeEnd()) {
updateLiveness(live, id, true);
if (lrs[id]->getIsSplittedDcl()) {
buildInterferenceWithSubDcl(id, src, live, true, false);
}
}
} else if (srcRegion->isIndirect() &&
liveAnalysis->livenessClass(G4_GRF)) {
// make every var in points-to set live
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(
srcRegion, bb);
for (auto &pt : pointsToSet) {
if (pt.var->isRegAllocPartaker()) {
updateLiveness(live, pt.var->getId(), true);
}
}
}
}
}
//
// Process register-indirect destination uses of ARF.
//
if (dst) {
if (dst->getBase()->isRegAllocPartaker() &&
dst->getRegAccess() != Direct) {
live.set(dst->getBase()->asRegVar()->getId());
}
}
//
// Process condMod
//
G4_CondMod *mod = inst->getCondMod();
if (mod != NULL) {
G4_VarBase *flagReg = mod->getBase();
if (flagReg != NULL) {
unsigned id = flagReg->asRegVar()->getId();
if (flagReg->asRegVar()->isRegAllocPartaker()) {
buildInterferenceWithLive(live, id);
if (liveAnalysis->writeWholeRegion(bb, inst, flagReg)) {
updateLiveness(live, id, false);
}
}
} else {
vISA_ASSERT((inst->opcode() == G4_sel || inst->opcode() == G4_csel) &&
inst->getCondMod() != NULL,
"Invalid CondMod");
}
}
//
// Process predicate
//
G4_Predicate *predicate = inst->getPredicate();
if (predicate != NULL) {
G4_VarBase *flagReg = predicate->getBase();
unsigned id = flagReg->asRegVar()->getId();
if (flagReg->asRegVar()->isRegAllocPartaker()) {
live.set(id);
}
}
// Update debug info intervals based on live set
if (builder.getOption(vISA_GenerateDebugInfo)) {
updateDebugInfo(kernel, inst, *liveAnalysis, lrs, live, &state,
inst == bb->front());
}
}
}
void Interference::applyPartitionBias() {
// Any variable that interferes with a VCA dcl is live through an fcall.
// This function makes such variables callee save biased to avoid save/restore
// code around fcall. Save/restore may still be needed in case this is a
// stack call function (vs kernel), but a single save/restore sequence can
// free the callee save register throughout the function.
for (auto i : liveAnalysis->globalVars) {
if (kernel.fg.isPseudoVCADcl(lrs[i]->getDcl())) {
const auto &intfs = sparseIntf[i];
for (const auto edge : intfs) {
// no point adding bias to any variable already assigned
if (lrs[edge]->getPhyReg())
continue;
lrs[edge]->setCalleeSaveBias(true);
lrs[edge]->setCallerSaveBias(false);
}
}
}
}
// Any setting of LiveRange property that is discovered during interference
// must be done here. Because with incremental RA, we may not run interference
// computation for all BBs.
void Interference::setupLRs(G4_BB *bb) {
unsigned refCount = GlobalRA::getRefCount(
kernel.getOption(vISA_ConsiderLoopInfoInRA) ? bb->getNestLevel() : 0);
bool incSpillCostAddrTaken = kernel.getOption(vISA_IncSpillCostAllAddrTaken);
for (auto i = bb->rbegin(); i != bb->rend(); i++) {
G4_INST *inst = (*i);
auto dst = inst->getDst();
if (dst) {
if (dst->getBase()->isRegAllocPartaker()) {
unsigned id = ((G4_RegVar *)dst->getBase())->getId();
if (!inst->isPseudoKill() && !inst->isLifeTimeEnd()) {
lrs[id]->setRefCount(lrs[id]->getRefCount() +
refCount); // update reference count
}
lrs[id]->checkForInfiniteSpillCost(bb, i);
} else if (dst->isIndirect() && liveAnalysis->livenessClass(G4_GRF)) {
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(dst,
bb);
for (auto &pt : pointsToSet) {
if (!pt.var->isRegAllocPartaker() || !incSpillCostAddrTaken)
continue;
lrs[pt.var->getId()]->setRefCount(
lrs[pt.var->getId()]->getRefCount() + refCount);
}
}
}
if (inst->opcode() == G4_pseudo_fcall &&
liveAnalysis->livenessClass(G4_GRF)) {
auto fcall = kernel.fg.builder->getFcallInfo(bb->back());
G4_Declare *ret = kernel.fg.builder->getStackCallRet();
vISA_ASSERT(fcall != std::nullopt, "fcall info not found");
uint16_t retSize = fcall->getRetSize();
if (ret && retSize > 0 && ret->getRegVar() &&
ret->getRegVar()->isRegAllocPartaker()) {
unsigned id = static_cast<const G4_RegVar *>(ret->getRegVar())->getId();
lrs[id]->setRefCount(lrs[id]->getRefCount() + refCount);
}
}
bool isSend =
inst->isSend() || inst->isFillIntrinsic() || inst->isSpillIntrinsic();
if (isSend && !dst->isNullReg()) {
// r127 must not be used for return address when there is a src and dest
// overlap in send instruction. This applies to split-send as well
if (kernel.fg.builder->needsToReserveR127() &&
liveAnalysis->livenessClass(G4_GRF) &&
dst->getBase()->isRegAllocPartaker() &&
!dst->getBase()->asRegVar()->isPhyRegAssigned()) {
int dstId = dst->getBase()->asRegVar()->getId();
lrs[dstId]->setForbidden(forbiddenKind::FBD_LASTGRF);
}
}
//
// process each source operand
//
for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
G4_Operand *src = inst->getSrc(j);
if (!src || !src->isSrcRegRegion())
continue;
G4_SrcRegRegion *srcRegion = src->asSrcRegRegion();
if (srcRegion->getBase()->isRegAllocPartaker()) {
unsigned id = ((G4_RegVar *)(srcRegion)->getBase())->getId();
lrs[id]->setRefCount(lrs[id]->getRefCount() + refCount);
if (inst->isEOT() && liveAnalysis->livenessClass(G4_GRF)) {
// mark the liveRange as the EOT source
lrs[id]->setEOTSrc();
if (builder.hasEOTGRFBinding()) {
lrs[id]->setForbidden(forbiddenKind::FBD_EOT);
}
}
if (inst->isReturn()) {
lrs[id]->setRetIp();
}
} else if (srcRegion->isIndirect() &&
liveAnalysis->livenessClass(G4_GRF)) {
// make every var in points-to set live
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(
srcRegion, bb);
for (auto &pt : pointsToSet) {
if (!pt.var->isRegAllocPartaker() || !incSpillCostAddrTaken)
continue;
lrs[pt.var->getId()]->setRefCount(
lrs[pt.var->getId()]->getRefCount() + refCount);
}
}
}
//
// Process condMod
//
if (auto mod = inst->getCondMod()) {
G4_VarBase *flagReg = mod->getBase();
if (flagReg) {
unsigned id = flagReg->asRegVar()->getId();
if (flagReg->asRegVar()->isRegAllocPartaker()) {
lrs[id]->setRefCount(lrs[id]->getRefCount() + refCount);
lrs[id]->checkForInfiniteSpillCost(bb, i);
}
} else {
vISA_ASSERT((inst->opcode() == G4_sel || inst->opcode() == G4_csel) &&
inst->getCondMod() != NULL,
"Invalid CondMod");
}
}
//
// Process predicate
//
if (auto predicate = inst->getPredicate()) {
G4_VarBase *flagReg = predicate->getBase();
unsigned id = flagReg->asRegVar()->getId();
if (flagReg->asRegVar()->isRegAllocPartaker()) {
lrs[id]->setRefCount(lrs[id]->getRefCount() + refCount);
}
}
}
}
void Interference::computeInterference() {
startTimer(TimerID::INTERFERENCE);
for (auto bb : kernel.fg) {
// Initialize LR properties like ref count and forbidden here.
// This method is invoked for all BBs even with incremental RA.
setupLRs(bb);
}
//
// create bool vector, live, to track live ranges that are currently live
//
SparseBitVector live;
buildInterferenceAmongLiveOuts();
for (G4_BB *bb : kernel.fg) {
if (!incRA.intfNeededForBB(bb)) {
continue;
}
//
// mark all live ranges dead
//
live.clear();
//
// start with all live ranges that are live at the exit of BB
//
buildInterferenceAtBBExit(bb, live);
//
// traverse inst in the reverse order
//
buildInterferenceWithinBB(bb, live);
}
buildInterferenceAmongLiveIns();
//
// Build interference with physical registers assigned by local RA
//
if (gra.useLocalRA) {
for (auto curBB : kernel.fg) {
buildInterferenceWithLocalRA(curBB);
}
}
RA_TRACE({
RPE rpe(gra, liveAnalysis);
rpe.run();
std::cout << "\t--max RP: " << rpe.getMaxRP() << "\n";
});
if ((builder.getOption(vISA_RATrace) ||
builder.getOption(vISA_DumpPerfStatsVerbose)) &&
builder.getJitInfo()->statsVerbose.RAIterNum == 1) {
getNormIntfNum();
}
// Augment interference graph to accomodate non-default masks
aug.augmentIntfGraph();
generateSparseIntfGraph();
countNeighbors();
if (IncrementalRA::isEnabled(kernel)) {
// Incremental interference was computed for current iteration.
// Now prepare for incremental temps in next iteration.
gra.incRA.clearCandidates();
}
// apply callee save bias after augmentation as interference graph is
// up-to-date.
if (kernel.fg.getHasStackCalls()) {
applyPartitionBias();
}
stopTimer(TimerID::INTERFERENCE);
}
void Interference::getNormIntfNum() {
unsigned numVars = liveAnalysis->getNumSelectedVar();
uint32_t numEdges = 0;
if (useDenseMatrix()) {
// Iterate over intf graph matrix
for (unsigned row = 0; row < numVars; row++) {
unsigned rowOffset = row * rowSize;
unsigned colStart = (row + 1) / BITS_DWORD;
for (unsigned j = colStart; j < rowSize; j++) {
unsigned intfBlk = getInterferenceBlk(rowOffset + j);
if (intfBlk == 0) {
continue;
}
for (unsigned k = 0; k < BITS_DWORD; k++) {
if (!(intfBlk & (1 << k))) {
continue;
}
unsigned v2 = (j * BITS_DWORD) + k;
if (v2 != row) {
numEdges++;
}
}
}
}
} else {
for (uint32_t v1 = 0; v1 < maxId; ++v1) {
auto &intfSet = sparseMatrix[v1];
numEdges += intfSet.count();
}
}
builder.getJitInfo()->statsVerbose.normIntfNum = numEdges;
RA_TRACE(std::cout << "\t--normal edge #: " << numEdges << "\n");
}
#define SPARSE_INTF_VEC_SIZE 64
void Interference::generateSparseIntfGraph() {
// Generate sparse intf graph from the dense one
unsigned numVars = liveAnalysis->getNumSelectedVar();
sparseIntf.resize(numVars);
for (unsigned row = 0; row < numVars; row++) {
sparseIntf[row].reserve(SPARSE_INTF_VEC_SIZE);
}
if (useDenseMatrix()) {
// Iterate over intf graph matrix
for (unsigned row = 0; row < numVars; row++) {
unsigned rowOffset = row * rowSize;
unsigned colStart = (row + 1) / BITS_DWORD;
for (unsigned j = colStart; j < rowSize; j++) {
unsigned intfBlk = getInterferenceBlk(rowOffset + j);
if (intfBlk != 0) {
for (unsigned k = 0; k < BITS_DWORD; k++) {
if (intfBlk & (1 << k)) {
unsigned v2 = (j * BITS_DWORD) + k;
if (v2 != row) {
sparseIntf[v2].emplace_back(row);
sparseIntf[row].emplace_back(v2);
}
}
}
}
}
}
} else {
for (uint32_t v1 = 0; v1 < maxId; ++v1) {
auto &intfSet = sparseMatrix[v1];
for (uint32_t v2 : intfSet) {
sparseIntf[v1].emplace_back(v2);
sparseIntf[v2].emplace_back(v1);
}
}
}
}
void Interference::countNeighbors() {
if (!builder.getOption(vISA_RATrace) &&
!builder.getOption(vISA_DumpPerfStatsVerbose))
return;
uint32_t numNeighbor = 0;
uint32_t maxNeighbor = 0;
[[maybe_unused]] uint32_t maxIndex = 0;
uint32_t numEdges = 0;
for (int i = 0, numVar = (int)sparseIntf.size(); i < numVar; ++i) {
if (lrs[i]->getPhyReg() == nullptr) {
auto &intf = sparseIntf[i];
numNeighbor += (uint32_t)intf.size();
maxNeighbor = std::max(maxNeighbor, numNeighbor);
if (maxNeighbor == numNeighbor)
maxIndex = i;
}
numEdges += (uint32_t)sparseIntf[i].size();
}
float avgNeighbor = ((float)numNeighbor) / sparseIntf.size();
if (builder.getJitInfo()->statsVerbose.RAIterNum == 1) {
builder.getJitInfo()->statsVerbose.avgNeighbors = avgNeighbor;
builder.getJitInfo()->statsVerbose.maxNeighbors = maxNeighbor;
builder.getJitInfo()->statsVerbose.augIntfNum =
(numEdges / 2) - builder.getJitInfo()->statsVerbose.normIntfNum;
}
RA_TRACE({
std::cout << "\t--avg # neighbors: " << std::setprecision(6) << avgNeighbor
<< "\n";
std::cout << "\t--max # neighbors: " << maxNeighbor << " ("
<< lrs[maxIndex]->getDcl()->getName() << ")\n";
if (builder.getJitInfo()->statsVerbose.RAIterNum == 1) {
std::cout << "\t--aug edge #: "
<< builder.getJitInfo()->statsVerbose.augIntfNum << "\n";
}
});
}
// This function can be invoked before local RA or after augmentation.
// This function will update sub-reg data only for non-NoMask vars and
// leave others unchanged, ie their value will be as per HW conformity
// or earlier phase.
void GlobalRA::updateSubRegAlignment(G4_SubReg_Align subAlign) {
// Update alignment of all GRF declares to sub-align
for (auto dcl : kernel.Declares) {
if (dcl->getRegFile() & G4_GRF && !dcl->getIsPartialDcl()) {
G4_Declare *topdcl = dcl->getRootDeclare();
if (!areAllDefsNoMask(topdcl) &&
getAugmentationMask(topdcl) != AugmentationMasks::NonDefault) {
dcl->setSubRegAlign(subAlign);
setSubRegAlign(dcl, subAlign);
}
}
}
}
int GlobalRA::getAlignFromAugBucket(G4_Declare *dcl) {
if (GlobalRA::useGenericAugAlign(builder.getPlatformGeneration())) {
// Return 0 if no special alignment is needed
// Return 2 if even alignment is needed
// Return 4 if quad alignment is needed
// Even align needed if for given SIMD size and elem type,
// a complete def uses between 1-2 GRFs.
auto kernelSimdSizeToUse = kernel.getSimdSizeWithSlicing();
G4_Declare *topdcl = dcl->getRootDeclare();
auto topdclAugMask = getAugmentationMask(topdcl);
if (!areAllDefsNoMask(topdcl) && !topdcl->getIsPartialDcl() &&
topdclAugMask != AugmentationMasks::NonDefault) {
auto elemSizeToUse = topdcl->getElemSize();
if (elemSizeToUse < 4 && topdclAugMask == AugmentationMasks::Default32Bit)
// :uw with hstride 2 can also be Default32Bit and hence needs even
// alignment
elemSizeToUse = 4;
else if (elemSizeToUse < 8 &&
topdclAugMask == AugmentationMasks::Default64Bit)
elemSizeToUse = 8;
auto totalByteSize = elemSizeToUse * kernelSimdSizeToUse;
auto bucketSpans2GRFs = [&]() {
return totalByteSize > (unsigned)kernel.numEltPerGRF<Type_UB>() &&
totalByteSize <= (unsigned)(2 * kernel.numEltPerGRF<Type_UB>());
};
if (!(!builder.canReadR0() && dcl == kernel.fg.builder->getBuiltinR0())) {
if (use4GRFAlign) {
if (topdclAugMask == AugmentationMasks::Default16Bit ||
topdclAugMask == AugmentationMasks::Default32Bit) {
if (bucketSpans2GRFs())
return 2;
} else if (topdclAugMask == AugmentationMasks::Default64Bit) {
if (bucketSpans2GRFs())
// :df SIMD16
return 2;
// :df SIMD32
return 4;
} else if (topdclAugMask == AugmentationMasks::Undetermined) {
// Local RA will take this path as augmentation buckets are set
// to Undetermined. Although this is conservative, hybrid RA
// will run augmentation and compute buckets to fill in "holes".
// For eg, mov (32|M0) V10<2>:f should use 4GRF alignment as
// it's Default64Bit variable, although elem size is :f.
return 4;
}
} else {
// Even align if size is between 1-2 GRFs, for >2GRF sizes.
if (bucketSpans2GRFs())
return 2;
}
}
}
} else {
if (dcl->getRegFile() & G4_GRF) {
G4_Declare *topdcl = dcl->getRootDeclare();
auto topdclAugMask = getAugmentationMask(topdcl);
if (!areAllDefsNoMask(topdcl) && !topdcl->getIsPartialDcl() &&
topdclAugMask != AugmentationMasks::NonDefault &&
topdclAugMask != AugmentationMasks::Default64Bit) {
if ((topdcl->getElemSize() >= 4 ||
topdclAugMask == AugmentationMasks::Default32Bit) &&
topdcl->getByteSize() >= kernel.numEltPerGRF<Type_UB>() &&
!(!builder.canReadR0() &&
dcl == kernel.fg.builder->getBuiltinR0())) {
return 2;
}
}
}
}
return 0;
}
void GlobalRA::augAlign() {
// Update alignment of all GRF declares based on
// augmentation bucket and platform.
for (auto dcl : kernel.Declares) {
if (dcl->getRegFile() & G4_GRF) {
unsigned int align = getAlignFromAugBucket(dcl);
if (align == 4) {
if (incRA.isEnabled() && !isQuadAligned(dcl)) {
incRA.evenAlignUpdate(dcl);
}
forceQuadAlign(dcl);
} else if (align == 2) {
if (incRA.isEnabled() && !isEvenAligned(dcl)) {
incRA.evenAlignUpdate(dcl);
}
setEvenAligned(dcl, true);
}
}
}
}
void GlobalRA::getBankAlignment(LiveRange *lr, BankAlign &align) {
G4_Declare *dcl = lr->getDcl();
if (kernel.getSimdSize() < g4::SIMD16) {
return;
}
if (dcl->getRegFile() & G4_GRF) {
G4_Declare *topdcl = dcl->getRootDeclare();
auto topdclBC = getBankConflict(topdcl);
if (topdclBC != BANK_CONFLICT_NONE) {
if (topdcl->getElemSize() >= 4 && topdcl->getNumRows() > 1 &&
!(!builder.canReadR0() && dcl == kernel.fg.builder->getBuiltinR0())) {
if (topdclBC == BANK_CONFLICT_SECOND_HALF_EVEN ||
topdclBC == BANK_CONFLICT_SECOND_HALF_ODD) {
align = BankAlign::Odd;
}
}
}
}
}
// Compute homeFunc for dcl. Following rules are used:
// 1. A variable that's defined or used in a single function has
// that function as its home function.
// 2. A variable that's defined or used across functions (eg,
// args, retval) have their home function set to nullptr.
// 3. homeFunc is set only on root G4_Declare.
FuncInfo *Augmentation::computeHomeFunc(G4_Declare *dcl) {
vISA_ASSERT(!dcl->getAliasDeclare(), "root dcl expected");
// If there are no subroutines then all dcls have kernel as home function
if (!hasSubroutines)
return kernel.fg.kernelInfo;
if (hasUniqueFuncHome(dcl))
return getUniqueFuncHome(dcl);
FuncInfo *homeFunction = nullptr;
// Live-ins to kernel are modeled as being implicitly defined in kernel.
if (dcl->isInput())
homeFunction = kernel.fg.kernelInfo;
auto *defs = refs.getDefs(dcl);
if (defs) {
for (auto &def : *defs) {
auto *bb = std::get<1>(def);
auto *curDefFunc = bb->getFuncInfo();
if (!homeFunction) {
homeFunction = curDefFunc;
continue;
} else if (homeFunction != curDefFunc) {
return nullptr;
}
}
}
auto *uses = refs.getUses(dcl);
if (uses) {
for (auto &use : *uses) {
auto *bb = std::get<1>(use);
auto *curUseFunc = bb->getFuncInfo();
if (!homeFunction) {
homeFunction = curUseFunc;
continue;
} else if (homeFunction != curUseFunc) {
return nullptr;
}
}
}
return homeFunction;
}
void Augmentation::populateFuncMaps() {
vISA_ASSERT(kernel.fg.getBBList().back()->size() > 0, "last BB empty");
instToFunc.resize(kernel.fg.getBBList().back()->back()->getLexicalId() + 1);
for (auto &func : kernel.fg.sortedFuncTable) {
for (auto &bb : func->getBBList()) {
for (auto *inst : *bb) {
instToFunc[inst->getLexicalId()] = func;
}
}
}
}
void Augmentation::populateHomeFunc() {
// Assume last G4_Declare has max declId
homeFunc.resize(kernel.Declares.back()->getDeclId() + 1);
for (auto dcl : kernel.Declares) {
if (dcl->getAliasDeclare())
dcl = dcl->getRootDeclare();
auto *func = computeHomeFunc(dcl);
vISA_ASSERT(!hasUniqueFuncHome(dcl) || getUniqueFuncHome(dcl) == func,
"different home func set");
homeFunc[dcl->getDeclId()] = func;
}
}
Augmentation::Augmentation(Interference &i, const LivenessAnalysis &l,
GlobalRA &g)
: kernel(g.kernel), intf(i), gra(g), liveAnalysis(l), lrs(g.incRA.getLRs()),
fcallRetMap(g.fcallRetMap),
refs(g.kernel, false, false, true, &g.pointsToAnalysis),
hasSubroutines(kernel.fg.sortedFuncTable.size() > 0 &&
g.kernel.getOption(vISA_NewAugmentation)) {
useGenericAugAlign =
GlobalRA::useGenericAugAlign(kernel.getPlatformGeneration());
}
// For Scatter read, the channel is not handled as the block read.
// Update the emask according to the definition of VISA
bool Augmentation::updateDstMaskForGather(G4_INST *inst,
std::vector<unsigned char> &mask) {
G4_InstSend *sendInst = reinterpret_cast<G4_InstSend *>(inst);
G4_SendDesc *msgDesc = sendInst->getMsgDesc();
if (msgDesc->isRaw()) {
return updateDstMaskForGatherRaw(
inst, mask, reinterpret_cast<const G4_SendDescRaw *>(msgDesc));
}
vISA_ASSERT_UNREACHABLE("unexpected descriptor");
return false;
}
static void updateMaskSIMT(unsigned char curEMBit, unsigned char execSize,
std::vector<unsigned char> &mask,
unsigned dataSizeBytes, unsigned vecElems) {
unsigned blockSize = dataSizeBytes;
unsigned blockNum = vecElems;
for (unsigned i = 0; i < execSize; i++) {
for (unsigned j = 0; j < blockNum; j++) {
for (unsigned k = 0; k < blockSize; k++) {
mask[(j * execSize + i) * blockSize + k] = curEMBit;
}
}
if (curEMBit != NOMASK_BYTE) {
curEMBit++;
vISA_ASSERT(curEMBit <= 32, "Illegal mask channel");
}
}
}
bool Augmentation::updateDstMaskForGatherRaw(G4_INST *inst,
std::vector<unsigned char> &mask,
const G4_SendDescRaw *msgDesc) {
unsigned char execSize = inst->getExecSize();
const G4_DstRegRegion *dst = inst->getDst();
unsigned char curEMBit = (unsigned char)inst->getMaskOffset();
unsigned short elemSize = dst->getElemSize();
if (inst->isWriteEnableInst() ||
kernel.fg.builder->hasGatherReadSuppressionWARA()) {
curEMBit = NOMASK_BYTE;
}
SFID funcID = msgDesc->getFuncId();
switch (funcID) {
case SFID::RTHW:
// Mark RT send dst to be NonDefault, even when it doesn't have WriteEnable
if (kernel.getPlatform() >= Xe2) {
for (auto &elem : mask)
elem = NOMASK_BYTE;
return true;
}
break;
case SFID::DP_DC1:
switch (msgDesc->getHdcMessageType()) {
case DC1_A64_SCATTERED_READ: // a64 scattered read: svm_gather
{
unsigned blockNum = msgDesc->getElemsPerAddr();
unsigned blockSize = msgDesc->getElemSize();
for (unsigned i = 0; i < execSize; i++) {
for (unsigned j = 0; j < blockNum; j++) {
for (unsigned k = 0; k < blockSize; k++) {
mask[(j * execSize + i) * blockSize + k] = curEMBit;
}
}
if (curEMBit != NOMASK_BYTE) {
curEMBit++;
vISA_ASSERT(curEMBit <= 32, "Illegal mask channel");
}
}
return true;
} break;
case DC1_A64_UNTYPED_SURFACE_READ: // SVM gather 4
case DC1_UNTYPED_SURFACE_READ: // VISA gather 4
case DC1_TYPED_SURFACE_READ: // Gather 4 typed
{
unsigned channelNum = msgDesc->getEnabledChannelNum();
if (channelNum == 0) {
return false;
}
if (elemSize < 4) {
elemSize = 4;
}
for (unsigned i = 0; i < channelNum; i++) {
for (unsigned j = 0; j < execSize; j++) {
for (unsigned k = 0; k < elemSize; k++) {
mask[(i * execSize + j) * elemSize + k] = curEMBit;
}
if (curEMBit != NOMASK_BYTE) {
curEMBit++;
vISA_ASSERT(curEMBit <= 32, "Illegal mask channel");
}
}
if (curEMBit != NOMASK_BYTE) {
curEMBit = (unsigned char)inst->getMaskOffset();
}
}
return true;
} break;
default:
return false;
}
break;
case SFID::DP_DC2:
switch (msgDesc->getHdcMessageType()) {
case DC2_UNTYPED_SURFACE_READ: // gather 4 scaled
case DC2_A64_UNTYPED_SURFACE_READ: // SVM gather 4 scaled
{
unsigned channelNum = msgDesc->getEnabledChannelNum();
if (channelNum == 0) {
return false;
}
if (elemSize < 4) {
elemSize = 4;
}
for (unsigned i = 0; i < channelNum; i++) {
for (unsigned j = 0; j < execSize; j++) {
for (unsigned k = 0; k < elemSize; k++) {
mask[(i * execSize + j) * elemSize + k] = curEMBit;
}
if (curEMBit != NOMASK_BYTE) {
curEMBit++;
vISA_ASSERT(curEMBit <= 32, "Illegal mask channel");
}
}
if (curEMBit != NOMASK_BYTE) {
curEMBit = (unsigned char)inst->getMaskOffset();
}
}
return true;
}
case DC2_BYTE_SCATTERED_READ: // scaled byte scattered read: gather_scaled,
// handled as block read write
default:
return false;
}
break;
case SFID::DP_DC0:
switch (msgDesc->getHdcMessageType()) {
case DC_DWORD_SCATTERED_READ: // dword scattered read: gather(dword),
// handled as block read write
case DC_BYTE_SCATTERED_READ: // byte scattered read: gather(byte), handled
// as block read write
default:
return false;
}
break;
case SFID::SAMPLER: {
unsigned respLength = msgDesc->ResponseLength();
if (respLength * kernel.numEltPerGRF<Type_UB>() !=
dst->getTopDcl()->getByteSize() &&
msgDesc->isFence()) {
// since send dst size is not exactly equal to ResponseLength encoded in
// the descriptor, conservatively treat the send as being non-default
auto sz = dst->getTopDcl()->getByteSize();
for (unsigned int i = 0; i != sz; ++i)
mask[i] = NOMASK_BYTE;
return true;
}
elemSize = msgDesc->is16BitReturn() ? 2 : 4;
unsigned warpNum =
respLength * kernel.numEltPerGRF<Type_UB>() / (execSize * elemSize);
if (inst->isWriteEnableInst()) {
curEMBit = NOMASK_BYTE;
}
for (unsigned i = 0; i < warpNum; i++) {
for (unsigned j = 0; j < execSize; j++) {
for (unsigned k = 0; k < elemSize; k++) {
mask[(i * execSize + j) * elemSize + k] = curEMBit;
}
if (curEMBit != NOMASK_BYTE) {
curEMBit++;
vISA_ASSERT(curEMBit <= 32, "Illegal mask channel");
}
}
if (curEMBit != NOMASK_BYTE) {
curEMBit = (unsigned char)inst->getMaskOffset();
}
}
return true;
}
break;
case SFID::UGM:
case SFID::UGML:
case SFID::SLM: {
uint32_t desc = msgDesc->getDesc();
uint32_t op = (desc & 0x3F); // [5:0]
uint32_t dszEncd = (desc >> 9) & 0x7; // [11:9]
bool isTranspose = ((desc >> 15) & 0x1) != 0; // [15]
if (op == LSC_LOAD && !isTranspose) { // transpose not supported yet
int dataSzReg = 0;
switch (dszEncd) { // dat size [11:9]
case 0:
dataSzReg = 1;
break; // d8
case 1:
dataSzReg = 2;
break; // d16
default:
dataSzReg = 4;
break; // d32, d8u32, d16u32, d16u32h
case 3:
dataSzReg = 8;
break; // d64
}
int vecSz = 0;
int vecSzEncd = (desc >> 12) & 0x7; // [14:12]
if (vecSzEncd <= 3) {
vecSz = vecSzEncd + 1; // V1, V2, V3, V4
} else {
vecSz = 4 << (vecSzEncd - 3); // V8, V16, V32, V64
}
updateMaskSIMT(curEMBit, execSize, mask, (unsigned)dataSzReg,
(unsigned)vecSz);
return true;
}
}
default:
return false;
}
return false;
}
// Value stored at each byte in mask determines which bits
// of EM enable that byte for writing. When checkCmodOnly
// is set dst is ignored and mask only for cmod is set. For
// flag declares, mask is at bit granularity rather than byte.
// Function updates mask field in declaration of correspoing
// variable - dst or cmod.
void Augmentation::updateDstMask(G4_INST *inst, bool checkCmodOnly) {
G4_DstRegRegion *dst = inst->getDst();
G4_CondMod *cmod = inst->getCondMod();
if ((checkCmodOnly == false && dst && dst->getBase() &&
dst->getBase()->isRegVar()) ||
(checkCmodOnly == true && cmod != NULL && cmod->getBase() != NULL)) {
int dclOffset = 0;
G4_Declare *topdcl = NULL;
if (checkCmodOnly == false) {
topdcl = dst->getBase()->asRegVar()->getDeclare();
} else {
topdcl = cmod->asCondMod()->getTopDcl();
}
while (topdcl->getAliasDeclare() != nullptr) {
dclOffset += topdcl->getAliasOffset();
topdcl = topdcl->getAliasDeclare();
}
auto &mask = const_cast<std::vector<unsigned char> &>(gra.getMask(topdcl));
unsigned size = topdcl->getByteSize();
if (checkCmodOnly == true || dst->isFlag()) {
size *= BITS_PER_BYTE;
}
if (mask.size() == 0) {
mask.resize(size);
}
vISA_ASSERT(mask.size() > 0, "Valid mask not found for dcl %s",
topdcl->getName());
unsigned short hstride, elemSize;
short row, subReg;
unsigned startByte;
if (checkCmodOnly == false) {
hstride = dst->getHorzStride();
row = dst->getRegOff();
subReg = dst->getSubRegOff();
elemSize = dst->getElemSize();
if (inst->isSend() && !inst->isEOT()) {
if (updateDstMaskForGather(inst, mask)) {
return;
}
}
if (dst->isFlag()) {
elemSize = 1;
}
startByte = (row * kernel.getGRFSize()) + (subReg * elemSize);
if (dst->isFlag()) {
startByte = (row * 32) + (subReg * 8);
}
} else {
hstride = 1;
row = 0;
elemSize = 1;
startByte = cmod->asCondMod()->getLeftBound();
}
unsigned rb = 0xffffffff;
if (checkCmodOnly == true) {
rb = cmod->asCondMod()->getRightBound();
} else {
rb = dst->getRightBound();
}
unsigned char curEMBit = (unsigned char)inst->getMaskOffset();
if (inst->isWriteEnableInst()) {
curEMBit = NOMASK_BYTE;
}
for (unsigned i = dclOffset + startByte; i <= rb;
i += (hstride * elemSize)) {
for (int j = 0; j < elemSize; j++) {
vISA_ASSERT(i + j < size,
"updateDstMask writing past end of mask array size: %d",
size);
mask[i + j] |= curEMBit;
}
if (curEMBit != NOMASK_BYTE) {
curEMBit++;
}
}
}
}
unsigned Augmentation::getByteSizeFromMask(AugmentationMasks type) {
if (type == AugmentationMasks::Default16Bit) {
return 2;
} else if (type == AugmentationMasks::Default32Bit) {
return 4;
} else if (type == AugmentationMasks::Default64Bit) {
return 8;
}
vISA_ASSERT_UNREACHABLE("Unexpected type of mask");
return 0;
}
bool Augmentation::isDefaultMaskDcl(G4_Declare *dcl, unsigned simdSize,
AugmentationMasks type) {
// default mask is one where dst's hstride is 1 and
// elem size is 4
bool isDefault = false;
auto &mask = gra.getMask(dcl);
unsigned byteSize = getByteSizeFromMask(type);
// treat simd32 as simd16 when the program is split in to 2 simd16.
// when a simd32 program is not split in to 2 simd16, but some sends
// are broken in to 2 simd16 then treat those simd16 sends as non-default.
if (simdSize == 32 && kernel.getChannelSlicing()) {
simdSize = 16;
}
if (mask.size() > 0) {
G4_Declare *topdcl = dcl->getRootDeclare();
bool isFlagDcl = (topdcl->getRegFile() == G4_FLAG);
unsigned size = topdcl->getByteSize();
unsigned char curEMBit = 0;
bool found = true;
unsigned wrapAround = simdSize * byteSize;
if (isFlagDcl == true) {
size *= BITS_PER_BYTE;
wrapAround = 16;
}
for (unsigned i = 0; i < size; i += 1) {
if (isFlagDcl == true) {
curEMBit++;
} else {
if (byteSize && i % byteSize == 0) {
curEMBit++;
}
}
if (i % wrapAround == 0) {
// Wrap around based on simd size
// For SIMD8 wrap around each row,
// for SIMD16 wrap around every other row
curEMBit = 0;
}
if (mask[i] != curEMBit &&
// For flags, we set bytesize = 2 although
// the kernel is SIMD8. This means higher 8
// bits of mask will be set to 0 since those
// bits are never defined. Such masks need
// not be considered non-default.
!(isFlagDcl == true && mask[i] == 0)) {
found = false;
break;
}
}
if (found == true) {
isDefault = true;
}
}
return isDefault;
}
bool Augmentation::isDefaultMaskSubDeclare(unsigned char *mask, unsigned lb,
unsigned rb, G4_Declare *dcl,
unsigned simdSize) {
bool isDefault = false;
// treat simd32 as simd16 as the instruction is always split to 2 simd16
if (simdSize == 32) {
simdSize = 16;
}
if (mask != NULL) {
unsigned size = dcl->getByteSize();
unsigned char curEMBit = 0;
bool found = true;
unsigned wrapAround = simdSize * 4;
unsigned leftBound = gra.getSubOffset(dcl);
unsigned rightBound = leftBound + size - 1;
vISA_ASSERT(rightBound <= rb, "Wrong sub declare right bound!");
for (unsigned i = lb; i < rightBound + 1; i += 1) {
if ((i - lb) % 4 == 0) {
curEMBit++;
}
if ((i - lb) % wrapAround == 0) {
curEMBit = 0;
}
if (i >= leftBound) {
if (mask[i] != curEMBit) {
found = false;
break;
}
}
}
if (found == true) {
isDefault = true;
}
}
return isDefault;
}
bool Augmentation::verifyMaskIfInit(G4_Declare *dcl, AugmentationMasks mask) {
// Return true if dcl mask is either undetermined or same as mask
auto m = gra.getAugmentationMask(dcl);
if (m == mask || m == AugmentationMasks::Undetermined) {
return true;
}
return false;
}
bool Augmentation::checkGRFPattern2(G4_Declare *dcl, G4_DstRegRegion *dst,
unsigned maskOff, unsigned lb, unsigned rb,
unsigned execSize) {
auto opndByteSize = dst->getTypeSize();
unsigned modWith = opndByteSize * kernel.getSimdSize();
if (lb % modWith - (maskOff * opndByteSize * dst->getHorzStride()) <=
opndByteSize) {
if ((lb +
(execSize * opndByteSize * dst->getHorzStride() -
dst->getHorzStride()) -
rb) < opndByteSize) {
if (opndByteSize == 2 &&
verifyMaskIfInit(dcl, AugmentationMasks::Default32Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default32Bit);
return true;
} else if (opndByteSize == 4 &&
verifyMaskIfInit(dcl, AugmentationMasks::Default64Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default64Bit);
return true;
} else {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return true;
}
}
}
return false;
}
// Returns true if dcl mask deemed to be non-default, false otherwise.
bool Augmentation::checkGRFPattern1(G4_Declare *dcl, G4_DstRegRegion *dst,
unsigned maskOff, unsigned lb, unsigned rb,
unsigned execSize) {
auto opndByteSize = dst->getTypeSize();
unsigned modWith = opndByteSize * kernel.getSimdSize();
if (dst->getHorzStride() == 1) {
if ((lb % modWith == (maskOff * opndByteSize) &&
rb == (lb + (execSize * opndByteSize) - 1))) {
// This will be taken only when hstride = 1
if (opndByteSize == 2 &&
verifyMaskIfInit(dcl, AugmentationMasks::Default16Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default16Bit);
return true;
} else if (opndByteSize == 4 &&
verifyMaskIfInit(dcl, AugmentationMasks::Default32Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default32Bit);
return true;
} else if (opndByteSize == 8 &&
verifyMaskIfInit(dcl, AugmentationMasks::Default64Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default64Bit);
return true;
} else {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return true;
}
}
}
return false;
}
void Augmentation::markNonDefaultDstRgn(G4_INST *inst, G4_Operand *opnd) {
if (inst->isPseudoKill()) {
return;
}
G4_DstRegRegion *dst = nullptr;
G4_CondMod *condMod = nullptr;
if (opnd->isDstRegRegion()) {
dst = opnd->asDstRegRegion();
} else if (opnd->isCondMod()) {
condMod = opnd->asCondMod();
} else {
vISA_ASSERT(false, "Don't know how to handle this type of operand");
}
// Handle condMod
if (condMod && condMod->getBase()) {
G4_Declare *dcl = condMod->getTopDcl();
dcl = dcl->getRootDeclare();
if (inst->isWriteEnableInst() ||
opnd->getLeftBound() != inst->getMaskOffset()) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return;
}
if (verifyMaskIfInit(dcl, AugmentationMasks::DefaultPredicateMask)) {
gra.setAugmentationMask(dcl, AugmentationMasks::DefaultPredicateMask);
}
return;
}
// Handle dst
if (dst && (inst->isCall() || inst->isCallerSave())) {
const G4_Declare *dcl = dst->getBase()->asRegVar()->getDeclare();
if (dcl && liveAnalysis.livenessClass(dcl->getRegFile())) {
gra.setAugmentationMask(dcl->getRootDeclare(),
AugmentationMasks::NonDefault);
}
return;
}
bool isFlagRA = liveAnalysis.livenessClass(G4_FLAG);
if (dst && dst->getBase() && dst->getBase()->isRegVar()) {
G4_Declare *dcl = dst->getBase()->asRegVar()->getDeclare();
if (!liveAnalysis.livenessClass(dcl->getRegFile())) {
return;
}
unsigned offTopDcl = 0;
while (dcl->getAliasDeclare()) {
offTopDcl += dcl->getAliasOffset();
dcl = dcl->getAliasDeclare();
}
// NoMask instructions's dst is always non-default
if (inst->isWriteEnableInst()) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return;
}
if (gra.getAugmentationMask(dcl) == AugmentationMasks::NonDefault)
return;
unsigned maskOff = inst->getMaskOffset();
unsigned lb = dst->getLeftBound() + offTopDcl;
unsigned rb = dst->getRightBound() + offTopDcl;
unsigned execSize = inst->getExecSize();
if (dcl->getAddressed()) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return;
}
if (!isFlagRA) {
// Treat send as special case because update mask for scatter
// has some special checks.
if (inst->isSend()) {
if (gra.getAugmentationMask(dcl) == AugmentationMasks::NonDefault) {
return;
}
updateDstMask(inst, false);
if (isDefaultMaskDcl(dcl, kernel.getSimdSize(),
AugmentationMasks::Default16Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default16Bit);
} else if (isDefaultMaskDcl(dcl, kernel.getSimdSize(),
AugmentationMasks::Default32Bit)) {
gra.setAugmentationMask(dcl, AugmentationMasks::Default32Bit);
} else if (isDefaultMaskDcl(dcl, kernel.getSimdSize(),
AugmentationMasks::Default64Bit)) {
bool useNonDefault = false;
// TODO: Why?
useNonDefault |=
(kernel.getSimdSize() >= g4::SIMD16 && dcl->getTotalElems() > 8);
useNonDefault |=
(kernel.getSimdSize() == g4::SIMD8 && dcl->getTotalElems() > 4);
gra.setAugmentationMask(dcl, useNonDefault
? AugmentationMasks::NonDefault
: AugmentationMasks::Default64Bit);
} else {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return;
}
} else {
bool found = false;
// default one
found |= checkGRFPattern1(dcl, dst, maskOff, lb, rb, execSize);
if (!found ||
gra.getAugmentationMask(dcl) == AugmentationMasks::Undetermined) {
// hstride = 2 case
found |= checkGRFPattern2(dcl, dst, maskOff, lb, rb, execSize);
}
if (!found ||
gra.getAugmentationMask(dcl) == AugmentationMasks::Undetermined) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
}
}
} else {
// Handle flag register as destination here
if (!(lb == maskOff && rb == (lb + execSize - 1))) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
return;
}
if (verifyMaskIfInit(dcl, AugmentationMasks::DefaultPredicateMask)) {
gra.setAugmentationMask(dcl, AugmentationMasks::DefaultPredicateMask);
}
}
}
}
// Returns true if any inst found using non-default mask.
// This function sets up lexical id of all instructions.
bool Augmentation::markNonDefaultMaskDef() {
// Iterate dcls list and mark obvious ones as non-default.
// Obvoius non-default is 1 element, ie uniform dcl.
for (auto dcl : kernel.Declares) {
auto dclRegFile = dcl->getRegFile();
if (!liveAnalysis.livenessClass(dclRegFile))
continue;
if (dclRegFile == G4_GRF || dclRegFile == G4_INPUT ||
dclRegFile == G4_ADDRESS) {
if (dcl->getTotalElems() < 8 || dclRegFile == G4_INPUT) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
}
} else if (dclRegFile == G4_FLAG) {
// Flags are processed when processing instructions
}
}
unsigned id = 0;
bool isFlagRA = liveAnalysis.livenessClass(G4_FLAG);
for (auto bb : kernel.fg) {
for (auto inst : *bb) {
inst->setLexicalId(id++);
G4_DstRegRegion *dst = inst->getDst();
if (dst) {
markNonDefaultDstRgn(inst, dst);
}
if (isFlagRA && inst->getCondMod()) {
markNonDefaultDstRgn(inst, inst->getCondMod());
}
}
}
// Update whether each dcl is default/not
AugmentationMasks prevAugMask = AugmentationMasks::Undetermined;
bool nonDefaultMaskDefFound = false;
for (auto dcl : kernel.Declares) {
if (liveAnalysis.livenessClass(dcl->getRegFile())) {
if (gra.getAugmentationMask(dcl) == AugmentationMasks::Undetermined) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
nonDefaultMaskDefFound = true;
}
if (kernel.getOption(vISA_forceBCR) &&
gra.getBankConflict(dcl) != BANK_CONFLICT_NONE) {
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
nonDefaultMaskDefFound = true;
}
if (!nonDefaultMaskDefFound &&
gra.getAugmentationMask(dcl) != prevAugMask &&
prevAugMask != AugmentationMasks::Undetermined) {
nonDefaultMaskDefFound = true;
}
prevAugMask = gra.getAugmentationMask(dcl);
}
bool checkLRAAlign = false;
if (liveAnalysis.livenessClass(G4_GRF)) {
if (GlobalRA::useGenericAugAlign(kernel.getPlatformGeneration()) &&
gra.getAlignFromAugBucket(dcl) > 0)
checkLRAAlign = true;
else if (gra.getAugmentationMask(dcl) ==
AugmentationMasks::Default32Bit &&
kernel.getSimdSize() > kernel.numEltPerGRF<Type_UD>())
checkLRAAlign = true;
}
if (checkLRAAlign) {
auto dclLR = gra.getLocalLR(dcl);
if (dclLR) {
int s;
auto phyReg = dclLR->getPhyReg(s);
unsigned int maxAlign = 2;
if (gra.use4GRFAlign && gra.getAugmentationMask(dcl) == AugmentationMasks::Default64Bit) {
maxAlign = 4;
}
if (phyReg && phyReg->asGreg()->getRegNum() % maxAlign != 0) {
// If LRA assignment is not aligned as expected then
// mark it as non-default. GRA candidates cannot fully
// overlap with such ranges. Partial overlap is illegal.
// TODO: There's a bug here. This branch should execute only if
// dclLR->getAssigned() == true. If this is false, then
// dclLR->getPhyReg() is invalid. Once this is fixed, we can
// re-enable following assert.
//
//vISA_ASSERT(!gra.use4GRFAlign,
// "expecting LRA allocation to be aligned");
gra.setAugmentationMask(dcl, AugmentationMasks::NonDefault);
nonDefaultMaskDefFound = true;
}
}
}
}
return nonDefaultMaskDefFound;
}
void Augmentation::updateStartIntervalForSubDcl(G4_Declare *dcl,
G4_INST *curInst,
G4_Operand *opnd) {
for (const G4_Declare *subDcl : gra.getSubDclList(dcl)) {
unsigned leftBound = gra.getSubOffset(subDcl);
unsigned rightBound = leftBound + subDcl->getByteSize() - 1;
if (!(opnd->getRightBound() < leftBound ||
rightBound < opnd->getLeftBound())) {
auto subDclStartInterval = gra.getLastStartInterval(subDcl);
if (subDclStartInterval == NULL ||
(subDclStartInterval->getLexicalId() > curInst->getLexicalId())) {
gra.setLastStartInterval(subDcl, curInst);
}
auto subDclEndIntrval = gra.getLastEndInterval(subDcl);
if (subDclEndIntrval == NULL ||
(subDclEndIntrval->getLexicalId() < curInst->getLexicalId())) {
gra.setLastEndInterval(subDcl, curInst);
}
}
}
return;
}
void Augmentation::updateEndIntervalForSubDcl(G4_Declare *dcl, G4_INST *curInst,
G4_Operand *opnd) {
for (const G4_Declare *subDcl : gra.getSubDclList(dcl)) {
unsigned leftBound = gra.getSubOffset(subDcl);
unsigned rightBound = leftBound + subDcl->getByteSize() - 1;
if (!(opnd->getRightBound() < leftBound ||
rightBound < opnd->getLeftBound())) {
auto subDclEndInterval = gra.getLastEndInterval(subDcl);
if (subDclEndInterval == NULL ||
(subDclEndInterval->getLexicalId() < curInst->getLexicalId())) {
gra.setLastEndInterval(subDcl, curInst);
}
auto subDclStartInterval = gra.getLastStartInterval(subDcl);
if (subDclStartInterval == NULL ||
(subDclStartInterval->getLexicalId() > curInst->getLexicalId())) {
gra.setLastStartInterval(subDcl, curInst);
}
}
}
return;
}
void Augmentation::updateStartInterval(const G4_Declare *dcl,
G4_INST *curInst) {
auto dclStartInterval = gra.getLastStartInterval(dcl);
if (dclStartInterval && hasSubroutines) {
// If we want to extend dcl in a new subroutine than earlier,
// then we create a new interval for new subroutine. This way
// we ensure an interval never straddles subroutines.
auto *funcCurInst = instToFunc[curInst->getLexicalId()];
auto *funcStartInterval = instToFunc[dclStartInterval->getLexicalId()];
if (funcCurInst != funcStartInterval) {
gra.pushBackNewInterval(dcl);
dclStartInterval = nullptr;
}
}
if (!dclStartInterval ||
(dclStartInterval->getLexicalId() > curInst->getLexicalId())) {
gra.setLastStartInterval(dcl, curInst);
}
auto dclEndInterval = gra.getLastEndInterval(dcl);
if (!dclEndInterval ||
(dclEndInterval->getLexicalId() < curInst->getLexicalId())) {
gra.setLastEndInterval(dcl, curInst);
}
}
void Augmentation::updateEndInterval(const G4_Declare *dcl, G4_INST *curInst) {
auto dclEndInterval = gra.getLastEndInterval(dcl);
if (dclEndInterval && hasSubroutines) {
auto *funcCurInst = instToFunc[curInst->getLexicalId()];
auto *funcEndInterval = instToFunc[dclEndInterval->getLexicalId()];
if (funcCurInst != funcEndInterval) {
gra.pushBackNewInterval(dcl);
dclEndInterval = nullptr;
}
}
if (!dclEndInterval ||
(dclEndInterval->getLexicalId() < curInst->getLexicalId())) {
gra.setLastEndInterval(dcl, curInst);
}
auto dclStartInterval = gra.getLastStartInterval(dcl);
if (!dclStartInterval ||
(dclStartInterval->getLexicalId() > curInst->getLexicalId())) {
gra.setLastStartInterval(dcl, curInst);
}
}
void Augmentation::updateStartIntervalForLocal(G4_Declare *dcl,
G4_INST *curInst,
G4_Operand *opnd) {
updateStartInterval(dcl, curInst);
if (dcl->getIsSplittedDcl()) {
updateStartIntervalForSubDcl(dcl, curInst, opnd);
}
}
void Augmentation::updateEndIntervalForLocal(G4_Declare *dcl, G4_INST *curInst,
G4_Operand *opnd) {
updateEndInterval(dcl, curInst);
if (dcl->getIsSplittedDcl()) {
updateEndIntervalForSubDcl(dcl, curInst, opnd);
}
}
void GlobalRA::printLiveIntervals() {
for (const G4_Declare *dcl : kernel.Declares) {
if (getLastStartInterval(dcl) != nullptr || getLastEndInterval(dcl) != nullptr) {
DEBUG_VERBOSE(dcl->getName() << " (");
if (getLastStartInterval(dcl) != nullptr) {
DEBUG_VERBOSE(getLastStartInterval(dcl)->getLexicalId());
} else {
DEBUG_VERBOSE("*");
}
DEBUG_VERBOSE(", ");
if (getLastEndInterval(dcl) != nullptr) {
DEBUG_VERBOSE(getLastEndInterval(dcl)->getLexicalId());
} else {
DEBUG_VERBOSE("*");
}
DEBUG_VERBOSE("] "
<< "\n");
}
}
}
bool Augmentation::isUnknownArgOrRetval(G4_Declare *dcl) const {
if (!argsRetVal.count(dcl))
return false;
return isUnknownArg(dcl) || isUnknownRetVal(dcl);
}
bool Augmentation::isUnknownRetVal(G4_Declare *dcl) const {
return isRetvalType<RetValType::Unknown>(dcl);
}
bool Augmentation::isRegularRetVal(G4_Declare *dcl) const {
return isRetvalType<RetValType::Regular>(dcl);
}
bool Augmentation::isUnknownArg(G4_Declare *dcl) const {
return isArgType<ArgType::Unknown>(dcl);
}
bool Augmentation::isDefBeforeEachCallArg(G4_Declare *dcl) const {
return isArgType<ArgType::DefBeforeEachCall>(dcl);
}
bool Augmentation::isLiveThroughArg(G4_Declare *dcl) const {
return isArgType<ArgType::LiveThrough>(dcl);
}
void Augmentation::buildUnknownArgRetval() {
// Arg and retval of Unknown type could have inaccurate
// SIMD liveness. So we treat these conservatively by
// extending their liveness throughout the function such
// variables are referenced in. These variables may be
// live through subroutines that don't reference them,
// but that should be captured either by SIMT liveness
// or by SIMD liveness when we mark mayDef of callee
// with overlapping intervals at call sites.
if (!hasSubroutines)
return;
std::unordered_map<FuncInfo *, std::pair<G4_INST *, G4_INST *>> funcStartEnd;
for (auto *func : kernel.fg.sortedFuncTable) {
vISA_ASSERT(!func->getInitBB()->empty(), "expecting non-empty init bb");
vISA_ASSERT(!func->getExitBB()->empty(), "expecting non-empty exit bb");
auto *start = func->getInitBB()->front();
auto *end = func->getExitBB()->back();
funcStartEnd[func] = std::make_pair(start, end);
}
// We've a dcl of unknown arg/retval type and a list of subroutines
// the dcl is referenced in, directly or indirectly. We create live-intervals
// for dcl spanning each subroutine it's referenced in. Since live-intervals
// cannot straddle subroutines, we create 1 entry per subroutine.
auto attachIntervals = [&](G4_Declare *dcl,
std::unordered_set<FuncInfo *> &subroutines) {
vISA_ASSERT(gra.getNumIntervals(dcl) == 0,
"found > 0 intervals for unknown");
for (auto &startEnd : funcStartEnd) {
auto *func = startEnd.first;
if (!subroutines.count(func))
continue;
gra.pushBackNewInterval(dcl);
gra.setLastStartInterval(dcl, startEnd.second.first);
gra.setLastEndInterval(dcl, startEnd.second.second);
}
};
if (!liveAnalysis.livenessClass(G4_GRF)) {
for (auto &var : nonGRFRefs) {
if (var.second.size() < 2)
continue;
// Non-GRF variables that are referenced in multiple subroutines
// are considered as unknown type.
auto dcl = var.first;
gra.clearIntervals(dcl);
attachIntervals(dcl, var.second);
}
} else {
// Now gather all GRF Unknown arg, retval
for (const auto &info : argsRetVal) {
auto dcl = info.first;
if (isUnknownArgOrRetval(dcl)) {
if (!unknownArgRetvalRefs.count(dcl))
continue;
auto &allRefs = unknownArgRetvalRefs.at(dcl);
gra.clearIntervals(dcl);
attachIntervals(dcl, allRefs);
}
}
}
// Verify that no interval straddles function boundaries
if (gra.verifyAugmentation) {
[[maybe_unused]] auto getFunc = [&](G4_INST *inst) {
unsigned int lexId = inst->getLexicalId();
int funcId = 0;
for (auto &func : funcStartEnd) {
if (lexId >= func.second.first->getLexicalId() &&
lexId <= func.second.second->getLexicalId())
return funcId;
funcId++;
}
return funcId;
};
for (G4_Declare *dcl : kernel.Declares) {
auto &allIntervals = gra.getAllIntervals(dcl);
for (auto &interval : allIntervals) {
[[maybe_unused]] auto start = interval.start;
[[maybe_unused]] auto end = interval.end;
vISA_ASSERT(getFunc(start) == getFunc(end),
"interval straddles functions");
}
}
}
}
bool Augmentation::hasUniqueFuncHome(G4_Declare *dcl) const {
// Home functions are computed before computing arg/retval.
// Per definition, arg/retval have no home function.
if (argsRetVal.count(dcl))
return false;
auto *homeFunction = homeFunc[dcl->getDeclId()];
return homeFunction != nullptr;
}
FuncInfo* Augmentation::getUniqueFuncHome(G4_Declare* dcl) const {
vISA_ASSERT(hasUniqueFuncHome(dcl), "expecting unique home func");
return homeFunc[dcl->getDeclId()];
}
void Augmentation::startIntervalForLiveIn(FuncInfo *funcInfo, G4_BB *bb) {
// Start live-in intervals
auto liveInBB = liveAnalysis.getLiveAtEntry(bb) & liveAnalysis.globalVars;
for (auto i : liveInBB) {
G4_Declare *dcl = lrs[i]->getDcl()->getRootDeclare();
if (isUnknownArgOrRetval(dcl))
continue;
if (hasUniqueFuncHome(dcl) && getUniqueFuncHome(dcl) != funcInfo)
continue;
vISA_ASSERT(bb->size() > 0, "empty instlist");
vISA_ASSERT(funcInfo == kernel.fg.kernelInfo ||
argsPerSub.count(funcInfo) > 0 ||
!liveAnalysis.livenessClass(G4_GRF),
"didnt find callee entry");
updateStartInterval(dcl, bb->front());
}
}
void Augmentation::handleCallSite(G4_BB *curBB, unsigned int &funcCnt) {
const char *name =
kernel.fg.builder->getNameString(32, "SCALL_%d", funcCnt++);
G4_Declare *scallDcl =
kernel.fg.builder->createDeclare(name, G4_GRF, 1, 1, Type_UD);
gra.addVarToRA(scallDcl);
auto *inst = curBB->back();
vISA_ASSERT(inst->isCall(), "expecting call instruction");
updateStartInterval(scallDcl, inst);
updateEndInterval(scallDcl, inst);
std::pair<G4_INST *, G4_BB *> callInfo(inst, curBB);
callDclMap.emplace(scallDcl, callInfo);
if (liveAnalysis.livenessClass(G4_GRF)) {
auto *retLocDcl = inst->getDst()->getTopDcl();
// RET__loc dcl starts and ends at call site.
// If a function has multiple call sites to same
// callee then there would be as many trivial
// live-intervals for corresponding RET__loc dcl.
// RET__loc dcl in entryBB is identified as LiveThrough
// rather than DefBeforeEachCall. LiveThrough variable's
// interference is fully handled by SIMT. So we don't
// need to create the short interval for RET__loc at
// call site.
if (isDefBeforeEachCallArg(retLocDcl))
gra.pushBackNewInterval(retLocDcl);
auto *callee = curBB->getCalleeInfo();
vISA_ASSERT(argsPerSub.count(callee) > 0, "didnt find entry for sub");
auto &args = argsPerSub.at(callee);
// Terminate any arg with type DefBeforeEachCall
for (auto *arg : args) {
if (!isDefBeforeEachCallArg(arg))
continue;
updateEndInterval(arg, inst);
}
vISA_ASSERT(retValPerSub.count(callee) > 0, "didnt find callee entry");
// Start regular retval live-interval at call
const auto &retvals = retValPerSub[callee];
for (auto *retvalDcl : retvals) {
if (isRegularRetVal(retvalDcl)) {
gra.pushBackNewInterval(retvalDcl);
updateStartInterval(retvalDcl, curBB->back());
}
}
}
}
void Augmentation::handleDstOpnd(FuncInfo *funcInfo, G4_BB *curBB,
G4_INST *inst) {
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getRegAccess() == Direct && dst->getBase()) {
// Destination
G4_Declare *defdcl = GetTopDclFromRegRegion(dst);
if (dst->getBase()->isRegAllocPartaker()) {
if (defdcl) {
if (!liveAnalysis.livenessClass(G4_GRF))
nonGRFRefs[defdcl].insert(funcInfo);
if (isDefBeforeEachCallArg(defdcl)) {
vISA_ASSERT(!defdcl->getIsSplittedDcl(),
"not expecting to see split on arg");
// Check if previous interval ended at an earlier call.
// If not continue it, otherwise start new one.
auto *prevEnd = gra.getLastEndInterval(defdcl);
if (prevEnd && prevEnd->isCall())
gra.pushBackNewInterval(defdcl);
} else if (isUnknownArgOrRetval(defdcl)) {
unknownArgRetvalRefs[defdcl].insert(funcInfo);
}
if (gra.getLocalLR(defdcl)) {
updateStartIntervalForLocal(defdcl, inst, dst);
} else {
updateStartInterval(defdcl, inst);
}
}
} else if (liveAnalysis.livenessClass(G4_GRF)) {
LocalLiveRange *defdclLR;
// Handle ranges allocated by local RA
if (defdcl && (defdclLR = gra.getLocalLR(defdcl)) &&
defdclLR->getAssigned() == true && !defdclLR->isEOT()) {
vISA_ASSERT(!hasSubroutines || argsRetVal.count(defdcl) > 0,
"didnt expect arg to be allocated by LRA");
updateStartInterval(defdcl, inst);
}
}
} else if (liveAnalysis.livenessClass(G4_ADDRESS) && dst &&
dst->getRegAccess() == IndirGRF && dst->getBase() &&
dst->getBase()->isRegVar()) {
// Destination is indirect
G4_Declare *defdcl = dst->getBaseRegVarRootDeclare();
nonGRFRefs[defdcl].insert(funcInfo);
updateEndInterval(defdcl, inst);
} else if (liveAnalysis.livenessClass(G4_GRF) && dst && dst->isIndirect()) {
const REGVAR_VECTOR &pointsToSet =
liveAnalysis.getPointsToAnalysis().getAllInPointsToOrIndrUse(dst,
curBB);
for (const auto& pointsToVar : pointsToSet) {
if (pointsToVar.var->isRegAllocPartaker()) {
updateStartInterval(pointsToVar.var->getDeclare()->getRootDeclare(),
inst);
auto dcl = pointsToVar.var->getDeclare()->getRootDeclare();
if (isUnknownArgOrRetval(dcl))
unknownArgRetvalRefs[dcl].insert(funcInfo);
}
}
}
}
void Augmentation::handleCondMod(FuncInfo* funcInfo, G4_INST *inst) {
if (liveAnalysis.livenessClass(G4_FLAG)) {
G4_CondMod *cmod = inst->getCondMod();
if (cmod && cmod->getBase()) {
// Conditional modifier
G4_Declare *dcl = cmod->getBaseRegVarRootDeclare();
nonGRFRefs[dcl].insert(funcInfo);
updateStartInterval(dcl, inst);
}
}
}
void Augmentation::handleSrcOpnd(FuncInfo *funcInfo, G4_BB *curBB,
G4_Operand *src) {
G4_SrcRegRegion *srcRegion = src->asSrcRegRegion();
auto *inst = srcRegion->getInst();
if (srcRegion->getRegAccess() == Direct && srcRegion->getBase()) {
G4_Declare *usedcl = GetTopDclFromRegRegion(src);
if (isUnknownArg(usedcl) || isUnknownRetVal(usedcl))
unknownArgRetvalRefs[usedcl].insert(funcInfo);
if (srcRegion->getBase()->isRegAllocPartaker()) {
if (!liveAnalysis.livenessClass(G4_GRF))
nonGRFRefs[usedcl].insert(funcInfo);
if (gra.getLocalLR(usedcl)) {
updateEndIntervalForLocal(usedcl, inst, src);
} else {
updateEndInterval(usedcl, inst);
}
} else if (liveAnalysis.livenessClass(G4_GRF)) {
LocalLiveRange *usedclLR = nullptr;
if (usedcl && (usedclLR = gra.getLocalLR(usedcl)) &&
usedclLR->getAssigned() == true && !usedclLR->isEOT()) {
updateEndInterval(usedcl, inst);
}
}
} else if (liveAnalysis.livenessClass(G4_GRF) && srcRegion->isIndirect()) {
const REGVAR_VECTOR &pointsToSet =
liveAnalysis.getPointsToAnalysis().getAllInPointsToOrIndrUse(srcRegion,
curBB);
for (const auto& pointsToVar : pointsToSet) {
if (pointsToVar.var->isRegAllocPartaker()) {
updateEndInterval(pointsToVar.var->getDeclare()->getRootDeclare(),
inst);
auto dcl = pointsToVar.var->getDeclare()->getRootDeclare();
if (isUnknownArgOrRetval(dcl))
unknownArgRetvalRefs[dcl].insert(funcInfo);
}
}
} else if (liveAnalysis.livenessClass(G4_ADDRESS) &&
srcRegion->getRegAccess() == IndirGRF && srcRegion->getBase() &&
srcRegion->getBase()->isRegVar()) {
G4_Declare *usedcl = src->getBaseRegVarRootDeclare();
nonGRFRefs[usedcl].insert(funcInfo);
updateEndInterval(usedcl, inst);
}
}
void Augmentation::handlePred(FuncInfo* funcInfo, G4_INST *inst) {
if (liveAnalysis.livenessClass(G4_FLAG)) {
G4_Predicate *pred = inst->getPredicate();
if (pred) {
// Predicate
G4_Declare *dcl = pred->getBaseRegVarRootDeclare();
nonGRFRefs[dcl].insert(funcInfo);
updateEndInterval(dcl, inst);
}
}
}
void Augmentation::endIntervalForLiveOut(FuncInfo* funcInfo, G4_BB *bb) {
auto liveOutBB = liveAnalysis.getLiveAtExit(bb) & liveAnalysis.globalVars;
if (bb->isEndWithCall() && liveAnalysis.livenessClass(G4_GRF)) {
// reset bit for RET__loc as we handle it specially later to
// create point intervals at call site.
auto retLocVarId = bb->back()->getDst()->getTopDcl()->getRegVar()->getId();
liveOutBB.reset(retLocVarId);
// Default subroutine argument has to start at definition and
// end at call site. A caller may have multiple call sites for
// a callee. We want to create multiple live-intervals, one
// per call site. Creation of a live-interval per call site
// is handled in handleCallSite() already, so we skip extending
// them here.
auto *callee = bb->getCalleeInfo();
if (callee && argsPerSub.count(callee)) {
auto &argsForCallee = argsPerSub.at(callee);
for (auto *arg : argsForCallee) {
if (isDefBeforeEachCallArg(arg))
liveOutBB.reset(arg->getRegVar()->getId());
}
}
}
// Extend live-out interval to BB
for (auto i : liveOutBB) {
G4_Declare *dcl = lrs[i]->getDcl()->getRootDeclare();
if (isUnknownArgOrRetval(dcl))
continue;
if (hasUniqueFuncHome(dcl) && getUniqueFuncHome(dcl) != funcInfo)
continue;
vISA_ASSERT(bb->size() > 0, "empty instlist");
updateEndInterval(dcl, bb->back());
}
}
// Handle live-range extension for non-reducible CFG
void Augmentation::handleNonReducibleExtension(FuncInfo *funcInfo) {
// use SCC instead
// FIXME: does augmentation work in the presence of subroutine? neither
// SCCAnalysis nor findNaturalLoops considers the call graph
SCCAnalysis SCCFinder(kernel.fg);
SCCFinder.run();
for (auto iter = SCCFinder.SCC_begin(), iterEnd = SCCFinder.SCC_end();
iter != iterEnd; ++iter) {
auto &&anSCC = *iter;
std::unordered_set<G4_BB *> SCCSucc; // any successor BB of the SCC
G4_BB *headBB = anSCC.getEarliestBB();
if (hasSubroutines && headBB->getFuncInfo() != funcInfo)
continue;
for (auto BI = anSCC.body_begin(), BIEnd = anSCC.body_end(); BI != BIEnd;
++BI) {
G4_BB *bb = *BI;
for (auto succ : bb->Succs) {
if (!anSCC.isMember(succ)) {
SCCSucc.insert(succ);
}
}
}
for (auto exitBB : SCCSucc) {
extendVarLiveness(funcInfo, exitBB, headBB->front());
}
}
}
std::unordered_set<G4_BB *>
Augmentation::getAllJIPTargetBBs(FuncInfo *funcInfo) {
// Any BB that has join as first non-label instruction is a JIP target.
std::unordered_set<G4_BB *> JIPTargetBBs;
for (auto *BB : funcInfo->getBBList()) {
if (BB->empty())
continue;
auto InstIt = BB->begin();
if ((*InstIt)->isLabel())
++InstIt;
if (InstIt != BB->end() && (*InstIt)->opcode() == G4_join)
JIPTargetBBs.insert(BB);
}
return JIPTargetBBs;
}
std::vector<std::pair<G4_BB *, G4_BB *>>
Augmentation::getNonLoopBackEdges(FuncInfo *funcInfo) {
auto &LoopBackEdges = kernel.fg.getAllNaturalLoops();
std::vector<std::pair<G4_BB *, G4_BB *>> NonLoopBackEdges;
for (auto *BB : funcInfo->getBBList()) {
if (BB->empty())
continue;
if (BB->back()->opcode() != G4_jmpi && BB->back()->opcode() != G4_goto)
continue;
auto LastInstLexId = BB->back()->getLexicalId();
for (auto *Succ : BB->Succs) {
vISA_ASSERT(!Succ->empty(), "expecting non-empty succ BB");
auto SuccInstLexId = Succ->front()->getLexicalId();
// Forward edge
if (SuccInstLexId > LastInstLexId)
continue;
// Check if this is a loop edge
auto Edge = std::pair(BB, Succ);
if (LoopBackEdges.find(Edge) == LoopBackEdges.end())
NonLoopBackEdges.push_back(Edge);
}
}
return NonLoopBackEdges;
}
void Augmentation::handleNonLoopBackEdges(FuncInfo *funcInfo) {
// up:
// (W) P5 =
// ...
// goto Later
// ...
// <other BBs>
// join down
//
// BB1:
// P21 = ...
// (P38) goto down
//
// otherBB:
// ...
// (W) jmpi (M1, 1) up
//
// down:
// = P21
//
// Later:
//
// In above snippet, following path may be taken:
// BB1, otherBB, up, down, Later
//
// P21 is defined in BB1. If P5 uses same register
// then it can clobber P21 before it gets used in
// down. So P5 and P21 intervals must overlap.
//
// If we've a non-loop backedge in an interval and if
// there's an incoming JIP edge within that interval
// then it means we should extend the interval up to
// the backedge destination. In above snippet, it means
// extending P21 to "up" so that it overlaps with P5.
auto AllJIPTargetBBs = getAllJIPTargetBBs(funcInfo);
// Return true if there's any JIP incoming edge within interval
auto hasIncomingJIPEdge = [&AllJIPTargetBBs](const vISA::Interval &Interval) {
for (auto *JIPTargetBB : AllJIPTargetBBs) {
vISA::Interval Temp(JIPTargetBB->front(), JIPTargetBB->front());
if (Interval.intervalsOverlap(Temp))
return true;
}
return false;
};
auto NonLoopBackEdges = getNonLoopBackEdges(funcInfo);
if (NonLoopBackEdges.empty()) {
VISA_DEBUG_VERBOSE({ std::cout << "No non-loop backedges found\n"; });
return;
}
auto getNonLoopBackEdgesInInterval =
[&NonLoopBackEdges](const vISA::Interval &Interval) {
std::vector<std::pair<G4_BB *, G4_BB *>> NonLoopBackEdgesInInterval;
for (auto &NonLoopBackEdge : NonLoopBackEdges) {
vISA::Interval Temp(NonLoopBackEdge.first->back(),
NonLoopBackEdge.first->back());
if (Interval.intervalsOverlap(Temp))
NonLoopBackEdgesInInterval.push_back(NonLoopBackEdge);
}
return NonLoopBackEdgesInInterval;
};
for (G4_Declare *Dcl : kernel.Declares) {
auto &All = gra.getAllIntervals(Dcl);
// We shouldn't need to consider special variables like args, retval.
// Because such variables are not defined/used in same function.
if (All.size() != 1)
continue;
auto &Interval = All[0];
bool Change = false;
// Handle transitive backwards branches
// TODO: Handle forward branch from interval that later jump backwards
// and cause JIP edge to be taken in the middle of the interval.
do {
Change = false;
auto Start = Interval.start;
if (hasSubroutines && instToFunc[Start->getLexicalId()] != funcInfo)
continue;
if (!hasIncomingJIPEdge(Interval))
continue;
std::vector<std::pair<G4_BB *, G4_BB *>> NonLoopBackEdges =
getNonLoopBackEdgesInInterval(Interval);
for (auto &NonLoopBackEdge : NonLoopBackEdges) {
if (NonLoopBackEdge.second) {
vISA_ASSERT(NonLoopBackEdge.second->size() > 0,
"expecting backedge target to be non-empty");
auto StartLexId = Interval.start->getLexicalId();
if (StartLexId > NonLoopBackEdge.second->front()->getLexicalId()) {
VISA_DEBUG_VERBOSE({
std::cout << "Updating start interval for " << Dcl->getName()
<< " from " << StartLexId << " to "
<< NonLoopBackEdge.second->front()->getLexicalId()
<< " - ";
NonLoopBackEdge.second->front()->dump();
});
auto OldInterval = Interval;
updateStartInterval(Dcl, NonLoopBackEdge.second->front());
Change = (OldInterval != Interval);
}
}
}
} while (Change);
}
}
void Augmentation::handleLoopExtension(FuncInfo *funcInfo) {
// process each natural loop
for (auto &iter : kernel.fg.getAllNaturalLoops()) {
auto &backEdge = iter.first;
// Check whether loop is in current function
if (hasSubroutines &&
funcInfo != backEdge.first->getFuncInfo())
continue;
G4_INST *startInst = (backEdge.second)->front();
const std::set<G4_BB *> &loopBody = iter.second;
for (auto block : loopBody) {
// FIXME: this may process a BB multiple times
for (auto succBB : block->Succs) {
// A subroutine call BB's successor is callee's INIT BB.
// Loop data structure doesn't include callee BB. So
// succBB not part of loop may still be INIT BB of callee.
// Such an INIT BB shouldn't be treated as a loop exit
// for live-range extension. If we don't check for INIT BB
// we end up extending RET__loc range to loop header
// which isn't correct.
if (loopBody.find(succBB) == loopBody.end() &&
(succBB->getBBType() & G4_BB_INIT_TYPE) == 0) {
G4_BB *exitBB = succBB;
unsigned latchBBId = (backEdge.first)->getId();
unsigned exitBBId = succBB->getId();
if (exitBBId < latchBBId && succBB->Succs.size() == 1) {
exitBB = succBB->Succs.front();
}
VISA_DEBUG_VERBOSE({
std::cout << "==> Extend live-in for BB" << exitBB->getId() << "\n";
exitBB->emit(std::cout);
});
extendVarLiveness(funcInfo, exitBB, startInst);
}
}
}
G4_BB *startBB = backEdge.second;
G4_BB *endBB = backEdge.first;
auto liveInStartBB = liveAnalysis.getLiveAtEntry(startBB);
auto liveOutEndBB = liveAnalysis.getLiveAtExit(endBB);
auto globalsLiveInAndLiveOut =
liveInStartBB & liveOutEndBB & liveAnalysis.globalVars;
for (auto i : globalsLiveInAndLiveOut) {
auto *dcl = lrs[i]->getDcl()->getRootDeclare();
// If dcl has non-nullptr home function then extend liveness only
// in same function.
if (hasUniqueFuncHome(dcl) && getUniqueFuncHome(dcl) != funcInfo)
continue;
updateEndInterval(dcl, endBB->back());
VISA_DEBUG_VERBOSE({
unsigned oldEnd = gra.getLastEndInterval(dcl)->getLexicalId();
if (oldEnd < gra.getLastEndInterval(dcl)->getLexicalId()) {
std::cout << "Extending " << dcl->getName() << " from old end "
<< oldEnd << " to "
<< gra.getEndInterval(dcl)->getLexicalId()
<< " due to back-edge"
<< "\n";
}
});
}
}
}
// Extend all variables that are live at bb entry to the given inst
void Augmentation::extendVarLiveness(FuncInfo *funcInfo, G4_BB *bb,
G4_INST *inst) {
auto liveAtEntryBB =
liveAnalysis.getLiveAtEntry(bb) & liveAnalysis.globalVars;
for (auto i : liveAtEntryBB) {
G4_Declare *dcl = lrs[i]->getDcl()->getRootDeclare();
// If dcl has non-nullptr home function then extend liveness only
// in same function.
if (hasUniqueFuncHome(dcl) && getUniqueFuncHome(dcl) != funcInfo)
continue;
if (!kernel.fg.isPseudoDcl(dcl)) {
// Extend ith live-interval
updateStartInterval(dcl, inst);
VISA_DEBUG_VERBOSE({
unsigned oldStart = gra.getLastStartInterval(dcl)->getLexicalId();
if (oldStart > gra.getLastStartInterval(dcl)->getLexicalId()) {
std::cout << "Extending " << dcl->getName() << " from old start "
<< oldStart << " to "
<< gra.getLastStartInterval(dcl)->getLexicalId()
<< " due to back-edge"
<< "\n";
}
});
}
}
}
// Build live-intervals for given subroutine and store them per subroutine.
// Arg/Retval are specially treated. We construct live-intervals with holes
// for such special variables to avoid unnecessary overlaps.
void Augmentation::buildLiveIntervals(FuncInfo* funcInfo) {
unsigned funcCnt = 0;
for (G4_BB *curBB : funcInfo->getBBList()) {
if (!curBB->empty()) {
startIntervalForLiveIn(funcInfo, curBB);
endIntervalForLiveOut(funcInfo, curBB);
}
for (G4_INST *inst : *curBB) {
if (inst->isPseudoKill() == true)
continue;
if (inst->isCall()) {
handleCallSite(curBB, funcCnt);
continue;
}
handleDstOpnd(funcInfo, curBB, inst);
handleCondMod(funcInfo, inst);
for (unsigned i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion()) {
continue;
}
handleSrcOpnd(funcInfo, curBB, src);
}
handlePred(funcInfo, inst);
}
}
handleNonLoopBackEdges(funcInfo);
// A variable may be defined in each divergent loop iteration and used
// outside the loop. SIMT liveness can detect the variable as KILL and
// this makes the variable non-loop carried. However, channel enable
// behavior may differ across loop iterations. So a channel be be defined
// in an earlier iteration and that channel could be disabled till end of
// the loop, while getting re-enabled outside the loop. This means we
// need to preserve value of the variable in each loop iteration and
// treat the variable as loop carried. Following is pseudo-code:
//
// loop_header:
// (W) V1 =
// = V1
// V2:d = {Q1}
// (P) goto loop_header
//
// outside_loop:
// = V2
//
// In above case, V2 should be treated as loop carried as it's defined using
// Q1 EM and belongs to Default32Bit bucket. It cannot share storage with
// V1 because V1 uses (W) and that could destroy value of V2 computed in an
// earlier iteration.
if (!kernel.fg.isReducible()) {
handleNonReducibleExtension(funcInfo);
} else {
handleLoopExtension(funcInfo);
}
#ifdef DEBUG_VERBOSE_ON
// Print calculated live-ranges
gra.printLiveIntervals();
#endif
}
// FIXME: Used by old augmentation only where no holes are modeled.
void Augmentation::buildLiveIntervals() {
// Treat variables live-in to program first
G4_BB *entryBB = kernel.fg.getEntryBB();
// Live-in variables have their start interval start with
// first instruction of entry BB
for (auto i : liveAnalysis.globalVars) {
if (liveAnalysis.isLiveAtEntry(entryBB, i)) {
const G4_Declare *dcl = lrs[i]->getDcl()->getRootDeclare();
updateStartInterval(dcl, entryBB->front());
}
}
unsigned funcCnt = 0;
for (G4_BB *curBB : kernel.fg) {
for (G4_INST *inst : *curBB) {
if (inst->isPseudoKill() == true) {
continue;
}
G4_DstRegRegion *dst = inst->getDst();
if (inst->isCall()) {
const char *name =
kernel.fg.builder->getNameString(32, "SCALL_%d", funcCnt++);
G4_Declare *scallDcl =
kernel.fg.builder->createDeclare(name, G4_GRF, 1, 1, Type_UD);
gra.addVarToRA(scallDcl);
updateStartInterval(scallDcl, inst);
updateEndInterval(scallDcl, inst);
std::pair<G4_INST *, G4_BB *> callInfo(inst, curBB);
callDclMap.emplace(scallDcl, callInfo);
continue;
}
if (dst && dst->getRegAccess() == Direct && dst->getBase()) {
// Destination
G4_Declare *defdcl = GetTopDclFromRegRegion(dst);
if (dst->getBase()->isRegAllocPartaker()) {
if (defdcl) {
if (gra.getLocalLR(defdcl)) {
updateStartIntervalForLocal(defdcl, inst, dst);
} else {
updateStartInterval(defdcl, inst);
}
}
} else if (liveAnalysis.livenessClass(G4_GRF)) {
LocalLiveRange *defdclLR;
// Handle ranges allocated by local RA
if (defdcl && (defdclLR = gra.getLocalLR(defdcl)) &&
defdclLR->getAssigned() == true && !defdclLR->isEOT()) {
updateStartInterval(defdcl, inst);
}
}
} else if (liveAnalysis.livenessClass(G4_ADDRESS) && dst &&
dst->getRegAccess() == IndirGRF && dst->getBase() &&
dst->getBase()->isRegVar()) {
// Destination is indirect
G4_Declare *defdcl = dst->getBaseRegVarRootDeclare();
updateEndInterval(defdcl, inst);
} else if (liveAnalysis.livenessClass(G4_GRF) && dst &&
dst->isIndirect()) {
const REGVAR_VECTOR &pointsToSet =
liveAnalysis.getPointsToAnalysis().getAllInPointsToOrIndrUse(dst,
curBB);
for (const auto &pointsToVar : pointsToSet) {
if (pointsToVar.var->isRegAllocPartaker()) {
updateStartInterval(pointsToVar.var->getDeclare()->getRootDeclare(),
inst);
}
}
}
if (liveAnalysis.livenessClass(G4_FLAG)) {
G4_CondMod *cmod = inst->getCondMod();
if (cmod != nullptr && cmod->getBase() != nullptr) {
// Conditional modifier
G4_Declare *dcl = cmod->getBaseRegVarRootDeclare();
updateStartInterval(dcl, inst);
}
}
for (unsigned i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
G4_Operand *src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion()) {
continue;
}
G4_SrcRegRegion *srcRegion = src->asSrcRegRegion();
if (srcRegion->getRegAccess() == Direct && srcRegion->getBase()) {
G4_Declare *usedcl = GetTopDclFromRegRegion(src);
if (srcRegion->getBase()->isRegAllocPartaker()) {
if (gra.getLocalLR(usedcl)) {
updateEndIntervalForLocal(usedcl, inst, src);
} else {
updateEndInterval(usedcl, inst);
}
} else if (liveAnalysis.livenessClass(G4_GRF)) {
LocalLiveRange *usedclLR = nullptr;
if (usedcl && (usedclLR = gra.getLocalLR(usedcl)) &&
usedclLR->getAssigned() == true && !usedclLR->isEOT()) {
updateEndInterval(usedcl, inst);
}
}
} else if (liveAnalysis.livenessClass(G4_GRF) &&
srcRegion->isIndirect()) {
const REGVAR_VECTOR &pointsToSet =
liveAnalysis.getPointsToAnalysis().getAllInPointsToOrIndrUse(
srcRegion, curBB);
for (const auto &pointsToVar : pointsToSet) {
if (pointsToVar.var->isRegAllocPartaker()) {
updateEndInterval(pointsToVar.var->getDeclare()->getRootDeclare(),
inst);
}
}
} else if (liveAnalysis.livenessClass(G4_ADDRESS) &&
srcRegion->getRegAccess() == IndirGRF &&
srcRegion->getBase() && srcRegion->getBase()->isRegVar()) {
G4_Declare *usedcl = src->getBaseRegVarRootDeclare();
updateEndInterval(usedcl, inst);
}
}
if (liveAnalysis.livenessClass(G4_FLAG)) {
G4_Predicate *pred = inst->getPredicate();
if (pred != NULL) {
// Predicate
G4_Declare *dcl = pred->getBaseRegVarRootDeclare();
updateEndInterval(dcl, inst);
}
}
}
}
// extend all variables that are live at bb entry to the given inst
// ToDo: this seems very slow when # variable is large, should look for sparse
// implementation
auto extendVarLiveness = [this](G4_BB *bb, G4_INST *inst) {
for (auto i : liveAnalysis.globalVars) {
if (liveAnalysis.isLiveAtEntry(bb, i) == true &&
!kernel.fg.isPseudoDcl(lrs[i]->getDcl())) {
// Extend ith live-interval
G4_Declare *dcl = lrs[i]->getDcl()->getRootDeclare();
updateStartInterval(dcl, inst);
VISA_DEBUG_VERBOSE({
unsigned oldStart = gra.getStartInterval(dcl)->getLexicalId();
if (oldStart > gra.getStartInterval(dcl)->getLexicalId()) {
std::cout << "Extending " << dcl->getName() << " from old start "
<< oldStart << " to "
<< gra.getStartInterval(dcl)->getLexicalId()
<< " due to back-edge"
<< "\n";
}
});
}
}
};
if (!kernel.fg.isReducible()) {
// use SCC instead
// FIXME: does augmentation work in the presence of subroutine? neither
// SCCAnalysis nor findNaturalLoops considers the call graph
SCCAnalysis SCCFinder(kernel.fg);
SCCFinder.run();
for (auto iter = SCCFinder.SCC_begin(), iterEnd = SCCFinder.SCC_end();
iter != iterEnd; ++iter) {
auto &&anSCC = *iter;
std::unordered_set<G4_BB *> SCCSucc; // any successor BB of the SCC
G4_BB *headBB = anSCC.getEarliestBB();
for (auto BI = anSCC.body_begin(), BIEnd = anSCC.body_end(); BI != BIEnd;
++BI) {
G4_BB *bb = *BI;
for (auto succ : bb->Succs) {
if (!anSCC.isMember(succ)) {
SCCSucc.insert(succ);
}
}
}
for (auto exitBB : SCCSucc) {
extendVarLiveness(exitBB, headBB->front());
}
}
} else {
// process each natural loop
for (auto &&iter : kernel.fg.getAllNaturalLoops()) {
auto &&backEdge = iter.first;
G4_INST *startInst = (backEdge.second)->front();
const std::set<G4_BB *> &loopBody = iter.second;
for (auto block : loopBody) {
// FIXME: this may process a BB multiple times
for (auto succBB : block->Succs) {
// A subroutine call BB's successor is callee's INIT BB.
// Loop data structure doesn't include callee BB. So
// succBB not part of loop may still be INIT BB of callee.
// Such an INIT BB shouldn't be treated as a loop exit
// for live-range extension. If we don't check for INIT BB
// we end up extending RET__loc range to loop header
// which isn't correct.
if (loopBody.find(succBB) == loopBody.end() &&
(succBB->getBBType() & G4_BB_INIT_TYPE) == 0) {
G4_BB *exitBB = succBB;
unsigned latchBBId = (backEdge.first)->getId();
unsigned exitBBId = succBB->getId();
if (exitBBId < latchBBId && succBB->Succs.size() == 1) {
exitBB = succBB->Succs.front();
}
VISA_DEBUG_VERBOSE({
std::cout << "==> Extend live-in for BB" << exitBB->getId()
<< "\n";
exitBB->emit(std::cout);
});
extendVarLiveness(exitBB, startInst);
}
}
}
G4_BB *startBB = backEdge.second;
G4_BB *EndBB = backEdge.first;
for (auto i : liveAnalysis.globalVars) {
if (liveAnalysis.isLiveAtEntry(startBB, i) == true &&
liveAnalysis.isLiveAtExit(EndBB, i) == true) {
const G4_Declare *dcl = lrs[i]->getDcl()->getRootDeclare();
unsigned oldEnd = gra.getEndInterval(dcl)->getLexicalId();
(void)oldEnd;
updateEndInterval(dcl, EndBB->back());
VISA_DEBUG_VERBOSE({
if (oldEnd < gra.getEndInterval(dcl)->getLexicalId()) {
std::cout << "Extending " << dcl->getName() << " from old end "
<< oldEnd << " to "
<< gra.getEndInterval(dcl)->getLexicalId()
<< " due to back-edge"
<< "\n";
}
});
}
}
}
}
#ifdef DEBUG_VERBOSE_ON
// Print calculated live-ranges
gra.printLiveIntervals();
#endif
}
Augmentation::~Augmentation() {
// Clear out calculated information so that subsequent RA
// iterations don't have stale information
for (DECLARE_LIST_ITER dcl_it = kernel.Declares.begin(),
end = kernel.Declares.end();
dcl_it != end; dcl_it++) {
gra.clearIntervals(*dcl_it);
gra.setMask(*dcl_it, {});
gra.setAugmentationMask(*dcl_it, AugmentationMasks::Undetermined);
}
}
class compareInterval {
public:
GlobalRA &gra;
compareInterval(GlobalRA &g) : gra(g) {}
// Used to store live-intervals in stable sorted order. Sorting is
// done first on start lexical id, so live-ranges are stored in
// ascending order of start. For stable order, we use secondary
// check on dcl id.
bool operator()(const QueueEntry &s1, const QueueEntry &s2) {
auto s1Start = gra.getIntervalStart(s1.interval)->getLexicalId();
auto s2Start = gra.getIntervalStart(s2.interval)->getLexicalId();
if (s1Start == s2Start)
return s1.dcl->getDeclId() < s2.dcl->getDeclId();
return s1Start < s2Start;
}
};
void Augmentation::sortLiveIntervals() {
// Sort all intervals in kernel based on their starting point in
// ascending order and return them in sortedIntervals vector
// This is actually more efficient (at least according to vTune) than the O(N)
// bucket sort algorithm below, since it avoids most of the malloc/free
// overhead from the vector.resize()
for (G4_Declare *dcl : kernel.Declares) {
auto &all = gra.getAllIntervals(dcl);
for (auto &interval : all) {
if (gra.getIntervalEnd(interval))
sortedIntervals.push_back(QueueEntry(dcl, interval));
}
}
std::sort(sortedIntervals.begin(), sortedIntervals.end(),
compareInterval(gra));
VISA_DEBUG_VERBOSE({
std::cout << "Live-intervals in sorted order:\n";
for (auto &entry : sortedIntervals) {
auto *dcl = entry.first;
const auto &interval = entry.second;
std::cout << dcl->getName() << " - "
<< "(" << gra.getIntervalStart(interval)->getLexicalId() << ", "
<< gra.getIntervalEnd(interval)->getLexicalId() << "]"
<< "\n";
}
});
if (kernel.getOption(vISA_VerifyAugmentation)) {
dumpSortedIntervals();
}
}
unsigned Augmentation::getEnd(const G4_Declare *dcl) const {
return gra.getLastEndInterval(dcl)->getLexicalId();
}
// Mark interference between dcls. Either one of dcls may have
// register assigned by local RA so handle those cases too.
// Re-entrant function.
void Augmentation::handleSIMDIntf(G4_Declare *firstDcl, G4_Declare *secondDcl,
bool isCall) {
auto markIntfWithLRAAssignment = [](const G4_Declare *firstDcl,
const G4_Declare *lraAssigned,
Interference &intf) {
unsigned numRows = lraAssigned->getNumRows();
const G4_VarBase *preg = lraAssigned->getRegVar()->getPhyReg();
vISA_ASSERT(preg->isGreg(),
"Expecting a physical register during building interference "
"among incompatible masks");
unsigned start = preg->asGreg()->getRegNum();
for (unsigned i = start; i < (start + numRows); i++) {
auto GRFDcl = intf.getGRFDclForHRA(i);
intf.checkAndSetIntf(firstDcl->getRegVar()->getId(),
GRFDcl->getRegVar()->getId());
VISA_DEBUG_VERBOSE(std::cout << "Marking interference between "
<< firstDcl->getName() << " and "
<< GRFDcl->getName() << "\n");
}
};
auto firstRegVar = firstDcl->getRegVar();
auto secondRegVar = secondDcl->getRegVar();
if (firstDcl->getRegFile() == G4_INPUT && firstRegVar->getPhyReg() &&
secondDcl->getRegFile() == G4_INPUT && secondRegVar->getPhyReg()) {
return;
}
bool isFirstDcl = true;
bool isPseudoVCADcl = kernel.fg.isPseudoVCADcl(firstDcl);
if (!isPseudoVCADcl){
isPseudoVCADcl = kernel.fg.isPseudoVCADcl(secondDcl);
isFirstDcl = false;
}
if (isPseudoVCADcl) {
// Mark intf for following pattern:
// V33 =
// ...
// if
// = V33
// fcall
// ...
// else
// = V33
// endif
//
// V33 will interfere with VCA_SAVE pseudo node.
// It also needs to interfere with retval to
// ensure V33 and retval don't get same allocation.
// Note that if V33 is actually live after fcall
// then graph coloring will do this for us. In this
// case however we need to rely on augmentation.
auto retIter =
isFirstDcl ? fcallRetMap.find(firstDcl) : fcallRetMap.find(secondDcl);
if (retIter != fcallRetMap.end()) {
G4_Declare *retVar = retIter->second;
LocalLiveRange *otherDclLR;
G4_Declare *otherDcl = isFirstDcl ? secondDcl : firstDcl;
if (otherDcl->getRegVar()->isRegAllocPartaker())
intf.checkAndSetIntf(otherDcl->getRegVar()->getId(),
retVar->getRegVar()->getId());
else if ((otherDclLR = gra.getLocalLR(otherDcl)) &&
otherDclLR->getAssigned() && !otherDclLR->isEOT()) {
markIntfWithLRAAssignment(retVar, otherDcl, intf);
}
}
}
if (firstRegVar->isRegAllocPartaker() &&
secondRegVar->isRegAllocPartaker()) {
if (!intf.varSplitCheckBeforeIntf(firstRegVar->getId(),
secondRegVar->getId())) {
intf.checkAndSetIntf(firstRegVar->getId(),
secondRegVar->getId());
if (isCall) {
intf.buildInterferenceWithAllSubDcl(firstRegVar->getId(),
secondRegVar->getId());
}
VISA_DEBUG_VERBOSE(std::cout << "Marking interference between "
<< firstDcl->getName() << " and "
<< secondDcl->getName() << "\n");
}
} else if (liveAnalysis.livenessClass(G4_GRF)) {
LocalLiveRange *secondDclLR = nullptr, *firstDclLR = nullptr;
if (firstRegVar->isRegAllocPartaker() &&
(secondDclLR = gra.getLocalLR(secondDcl)) &&
secondDclLR->getAssigned() && !secondDclLR->isEOT()) {
// secondDcl was assigned by local RA and it uses
markIntfWithLRAAssignment(firstDcl, secondDcl, intf);
} else if (secondRegVar->isRegAllocPartaker() &&
(firstDclLR = gra.getLocalLR(firstDcl)) &&
firstDclLR->getAssigned() && !firstDclLR->isEOT()) {
// Call self with reversed parameters instead of re-implementing
// above code
handleSIMDIntf(secondDcl, firstDcl, isCall);
}
}
}
bool Augmentation::isNoMask(const G4_Declare *dcl, unsigned size) const {
auto &mask = gra.getMask(dcl);
bool result = false;
if (mask.size() > 0) {
result = true;
for (unsigned i = 0; i < size; i++) {
if (mask[i] != NOMASK_BYTE) {
result = false;
}
}
}
return result;
}
bool Augmentation::isConsecutiveBits(const G4_Declare *dcl,
unsigned size) const {
auto &mask = gra.getMask(dcl);
bool result = false;
if (mask.size() > 0) {
result = true;
for (unsigned i = 0; i < size; i++) {
if (mask[i] != i) {
result = false;
}
}
}
return result;
}
bool Augmentation::isCompatible(const G4_Declare *testDcl,
const G4_Declare *biggerDcl) const {
bool compatible = false;
unsigned testSize = testDcl->getRegVar()->isFlag()
? testDcl->getNumberFlagElements()
: testDcl->getByteSize();
unsigned biggerSize = biggerDcl->getRegVar()->isFlag()
? biggerDcl->getNumberFlagElements()
: biggerDcl->getByteSize();
unsigned size = (testSize < biggerSize ? testSize : biggerSize);
// Masks are compatible when:
// i. Both decls have exactly 1 EM bit defining each byte
// (This means a dcl with Q1 in one inst and Q2 in another
// instruction writing same subregisters is not a candidate
// for next step).
// ii. Bytes at common indices are enabled by same EM bit
// (This means NoMask dcl is compatible with NoMask dcl and
// not with any other dcl).
// UPDATE: (ii) above is now altered such that NoMask dcls
// that overlap are considered to be incompatible. This is to
// handle removal of JIP edges (then->else edge).
auto &testMask = gra.getMask(testDcl);
auto &biggerMask = gra.getMask(biggerDcl);
if (testMask.size() > 0 && biggerMask.size() > 0) {
// Lets pattern match
if (testDcl->getRegFile() == G4_FLAG) {
if (isConsecutiveBits(testDcl, size) &&
isConsecutiveBits(biggerDcl, size)) {
compatible = true;
}
} else {
// Add another pattern to check here
}
}
return compatible;
}
void Augmentation::expireIntervals(unsigned startIdx) {
// Expire elements from both lists
while (defaultMaskQueue.size() > 0) {
if (defaultMaskQueue.top().interval.end->getLexicalId() <=
startIdx) {
VISA_DEBUG_VERBOSE(std::cout << "Expiring "
<< defaultMaskQueue.top().first->getName()
<< "\n");
defaultMaskQueue.pop();
} else {
break;
}
}
while (nonDefaultMaskQueue.size() > 0) {
if (nonDefaultMaskQueue.top().interval.end->getLexicalId() <=
startIdx) {
VISA_DEBUG_VERBOSE(std::cout << "Expiring "
<< nonDefaultMaskQueue.top().first->getName()
<< "\n");
nonDefaultMaskQueue.pop();
} else {
break;
}
}
}
// Return true if edge between dcl1 and dcl2 is strong.
bool Interference::isStrongEdgeBetween(const G4_Declare *dcl1,
const G4_Declare *dcl2) const {
auto dcl1RegVar = dcl1->getRegVar();
auto dcl2RegVar = dcl2->getRegVar();
auto dcl1RAPartaker = dcl1RegVar->isRegAllocPartaker();
auto dcl2RAPartaker = dcl2RegVar->isRegAllocPartaker();
if (dcl1RAPartaker && dcl2RAPartaker) {
if (interfereBetween(dcl1RegVar->getId(), dcl2RegVar->getId())) {
return true;
} else {
return false;
}
}
if (dcl1RAPartaker) {
auto dcl2NumRows = dcl2->getNumRows();
auto startPhyReg = dcl2RegVar->getPhyReg()->asGreg()->getRegNum();
auto dcl2LR = gra.getLocalLR(dcl2);
if (dcl2LR && dcl2LR->getAssigned()) {
bool allEdgesStrong = true;
for (unsigned i = startPhyReg; i < (startPhyReg + dcl2NumRows); i++) {
const G4_Declare *lraPreg = getGRFDclForHRA(i);
allEdgesStrong &= interfereBetween(lraPreg->getRegVar()->getId(),
dcl1RegVar->getId());
}
if (allEdgesStrong)
return true;
}
} else {
return isStrongEdgeBetween(dcl2, dcl1);
}
return false;
}
bool Augmentation::weakEdgeNeeded(AugmentationMasks defaultDclMask,
AugmentationMasks newDclMask) {
if (gra.use4GRFAlign)
return false;
if (useGenericAugAlign) {
// Weak edge needed in case #GRF exceeds 2
if (newDclMask == AugmentationMasks::Default64Bit)
return (TypeSize(Type_Q) * kernel.getSimdSizeWithSlicing()) >
(unsigned)(2 * kernel.numEltPerGRF<Type_UB>());
if (newDclMask == AugmentationMasks::Default32Bit) {
// Even align up to 2 GRFs size variable, use weak edges beyond
return (TypeSize(Type_D) * kernel.getSimdSizeWithSlicing()) >
(unsigned)(2 * kernel.numEltPerGRF<Type_UB>());
}
} else {
return (defaultDclMask == AugmentationMasks::Default64Bit &&
newDclMask == AugmentationMasks::Default64Bit);
}
return false;
}
// This method is invoked when building SIMD intf and current variable
// is the artificial variable created to model call. Live-intervals in
// default set and non-default set are ones that overlap with call site
// at end of callBB. The idea here is to mark every such active interval
// with mask associated with func. Later, we'll mark interference with
// each live-interval bit set here and maydef of func.
void Augmentation::addSIMDIntfDclForCallSite(
G4_BB *callBB, const std::vector<bool> &globalVars) {
FuncInfo *func = callBB->getCalleeInfo();
auto isLiveThroughFunc = [&](unsigned int id) {
if (liveAnalysis.isLiveAtExit(callBB, id)) {
auto retBB = func->getExitBB();
if (liveAnalysis.isLiveAtExit(retBB, id))
return true;
}
return false;
};
auto &overlapDeclares = overlapDclsWithFunc[func];
for (auto &defaultEntry : defaultMaskQueue) {
auto defaultDcl = defaultEntry.dcl;
auto id = defaultDcl->getRegVar()->getId();
if (!isLiveThroughFunc(id) && globalVars[id])
overlapDeclares.first.insert(id);
}
for (auto &nonDefaultEntry : nonDefaultMaskQueue) {
auto nonDefaultDcl = nonDefaultEntry.dcl;
auto id = nonDefaultDcl->getRegVar()->getId();
if (!isLiveThroughFunc(id) && globalVars[id])
overlapDeclares.second.insert(id);
}
}
void Augmentation::addSIMDIntfForRetDclares(
G4_Declare *newDcl, const std::vector<bool> &globalVars) {
auto dclIt = retDeclares.find(newDcl);
MaskDeclares *mask = nullptr;
if (dclIt == retDeclares.end()) {
MaskDeclares newMask;
retDeclares[newDcl] = std::move(newMask);
mask = &retDeclares[newDcl];
} else {
mask = &dclIt->second;
}
for (auto& defaultSeg : defaultMaskQueue) {
auto defaultDcl = defaultSeg.dcl;
auto id = defaultDcl->getRegVar()->getId();
if (globalVars[id])
mask->first.insert(id);
}
for (auto& nonDefaultSeg : nonDefaultMaskQueue) {
auto nonDefaultDcl = nonDefaultSeg.dcl;
auto id = nonDefaultDcl->getRegVar()->getId();
if (globalVars[id])
mask->second.insert(id);
}
}
Augmentation::RetValType Augmentation::computeRetValType(FuncInfo *func,
G4_Declare *retVal) {
if (retVal->getAddressed())
return Augmentation::RetValType::Unknown;
const auto *defs = refs.getDefs(retVal);
if (defs) {
// All defs must be in func only
for (const auto &def : *defs) {
auto *bb = std::get<1>(def);
if (!func->contains(bb))
return Augmentation::RetValType::Unknown;
}
}
// All uses must be in BB immediately following call site
const auto *uses = refs.getUses(retVal);
if (uses) {
for (const auto &use : *uses) {
auto *bb = std::get<1>(use);
auto *pred = bb->getPhysicalPred();
if (pred->isSpecialEmptyBB())
pred = pred->getPhysicalPred();
if (!pred->isEndWithCall() || pred->getCalleeInfo() != func)
return Augmentation::RetValType::Unknown;
}
}
return Augmentation::RetValType::Regular;
}
Augmentation::ArgType Augmentation::computeArgType(FuncInfo *func,
G4_Declare *arg) {
if (arg->getAddressed())
return Augmentation::ArgType::Unknown;
// Trivial case where argument is input to kernel and no defs of
// the variable exist in the program.
const auto *defs = refs.getDefs(arg);
if (!defs || defs->size() == 0)
return Augmentation::ArgType::LiveThrough;
// Check if all defs of arg are in kernel entry BB
bool allDefsInEntryBB = true;
for (const auto &def : *defs) {
auto *bb = std::get<1>(def);
if (kernel.fg.getEntryBB() != bb) {
allDefsInEntryBB = false;
break;
}
}
if (allDefsInEntryBB)
return Augmentation::ArgType::LiveThrough;
// Check if use of subroutine arg exists in a BB that doesn't belong
// to the subroutine.
const auto *uses = refs.getUses(arg);
if (uses) {
for (const auto &use : *uses) {
auto bb = std::get<1>(use);
if (!func->contains(bb))
return Augmentation::ArgType::Unknown;
}
}
// Check if all defs are in same BB as call site
std::unordered_set<G4_BB *> funcCallSitesMatched;
for (auto bb : kernel.fg.getBBList()) {
if (!bb->isEndWithCall() || bb->getCalleeInfo() != func)
continue;
funcCallSitesMatched.insert(bb);
}
bool killFound = false;
for (const auto &def : *defs) {
auto *bb = std::get<1>(def);
if (bb->isEndWithCall() && bb->getCalleeInfo() == func) {
auto *inst = std::get<0>(def);
if (liveAnalysis.isLiveAtEntry(bb, arg->getRegVar()->getId())) {
return Augmentation::ArgType::Unknown;
}
if (inst->isPseudoKill() ||
liveAnalysis.writeWholeRegion(bb, inst, inst->getDst())) {
funcCallSitesMatched.erase(bb);
killFound = true;
}
continue;
}
return Augmentation::ArgType::Unknown;
}
if (!killFound || funcCallSitesMatched.size() > 0)
return Augmentation::ArgType::Unknown;
return Augmentation::ArgType::DefBeforeEachCall;
}
void Augmentation::discoverRetVal(FuncInfo *func) {
if (!liveAnalysis.livenessClass(G4_GRF))
return;
vISA_ASSERT(retValPerSub.count(func) == 0, "already saw sub");
retValPerSub[func] = {};
if (func == kernel.fg.kernelInfo)
return;
SparseBitVector subRetVal = liveAnalysis.retVal.at(func);
for (auto i : subRetVal) {
auto *dcl = lrs[i]->getDcl();
auto &retValInfo = argsRetVal[dcl];
retValInfo.subroutines.insert(func);
if (retValInfo.retValType != RetValType::Unknown)
retValInfo.retValType = computeRetValType(func, dcl);
vISA_ASSERT(retValInfo.retValType != RetValType::Init,
"expecting non-init retval type");
retValPerSub[func].insert(dcl);
if (retValInfo.subroutines.size() > 1)
retValInfo.retValType = RetValType::Unknown;
vISA_ASSERT(!hasUniqueFuncHome(dcl),
"retval cannot have non-nullptr home function");
}
if (kernel.getOption(vISA_VerifyAugmentation)) {
dumpRetVal(subRetVal);
}
}
void Augmentation::discoverArgs(FuncInfo *func) {
if (!liveAnalysis.livenessClass(G4_GRF))
return;
vISA_ASSERT(argsPerSub.count(func) == 0, "already saw sub");
argsPerSub[func] = {};
SparseBitVector subArgs;
if (func == kernel.fg.kernelInfo)
subArgs = liveAnalysis.use_in[kernel.fg.getEntryBB()->getId()] &
liveAnalysis.def_in[kernel.fg.getEntryBB()->getId()];
else
subArgs = liveAnalysis.args.at(func);
for (auto i : subArgs) {
auto *dcl = lrs[i]->getDcl();
auto &argInfo = argsRetVal[dcl];
argInfo.subroutines.insert(func);
if (argInfo.argType != ArgType::Unknown)
argInfo.argType = computeArgType(func, dcl);
vISA_ASSERT(argInfo.argType != ArgType::Init,
"expecting non-init arg type");
argsPerSub[func].insert(dcl);
// Same arg cannot be shared between 2 subroutines
if (argInfo.subroutines.size() > 1 &&
argInfo.argType == ArgType::DefBeforeEachCall)
argInfo.argType = ArgType::Unknown;
vISA_ASSERT(
argInfo.argType != ArgType::DefBeforeEachCall ||
!hasUniqueFuncHome(dcl),
"def before each call arg cannot have non-nullptr home function");
}
if (kernel.getOption(vISA_VerifyAugmentation)) {
func->dump(std::cout);
dumpArgs(subArgs);
}
}
void Augmentation::dumpSortedIntervals() {
if (kernel.getOption(vISA_DumpProgramWithLexicalId)) {
for (auto bb : kernel.fg.getBBList()) {
for (auto inst : *bb) {
std::cout << inst->getLexicalId() << ":\t";
inst->print(std::cout);
}
}
}
std::cout << "Started dumping sorted intervals:\n";
std::unordered_map<G4_Declare *, std::vector<Interval>> intervalsPerVar;
for (auto &entry : sortedIntervals) {
intervalsPerVar[entry.dcl].push_back(entry.interval);
}
for (auto &entry : sortedIntervals) {
auto &interval = entry.interval;
auto *dcl = entry.dcl;
std::cout << dcl->getName();
if (isUnknownArg(dcl))
std::cout << " (Unknown arg)";
else if (isUnknownRetVal(dcl))
std::cout << " (Unknown retval)";
else if (isDefBeforeEachCallArg(dcl))
std::cout << " (DefBeforeEachCallArg)";
else if (isLiveThroughArg(dcl))
std::cout << " (LiveThroughArg)";
else if (isRegularRetVal(dcl))
std::cout << " (RegularRetVal)";
if (dcl->getDeclId() >= homeFunc.size()) {
std::cout << " @ (new var)";
}
else {
auto *homeFunction = homeFunc[dcl->getDeclId()];
if (!homeFunction)
std::cout << " @ (global)";
else
std::cout << " @ (func " << (int)homeFunction->getId() << ")";
}
std::cout << " - (" << gra.getIntervalStart(interval)->getLexicalId()
<< ", " << gra.getIntervalEnd(interval)->getLexicalId() << "]";
if (intervalsPerVar[dcl].size() > 1) {
auto &allIntervals = intervalsPerVar[dcl];
std::cout << " other intervals: ";
for (auto &otherInterval : allIntervals) {
if (otherInterval == interval)
continue;
std::cout << "(" << gra.getIntervalStart(otherInterval)->getLexicalId()
<< ", " << gra.getIntervalEnd(otherInterval)->getLexicalId()
<< "] ";
}
}
std::cout << "\n";
}
std::cout << "Ended dumping sorted intervals:\n";
}
void Augmentation::dumpRetVal(SparseBitVector &subRetVal) {
auto getRetValType = [](RetValType retValType) {
if (retValType == Augmentation::RetValType::Init)
return "Init";
else if (retValType == Augmentation::RetValType::Regular)
return "Regular";
else if (retValType == Augmentation::RetValType::Unknown)
return "Unknown";
return "???";
};
for (auto i : subRetVal) {
printf("Retval = %s (%d) - %s\n",
gra.incRA.getLRs()[i]->getDcl()->getName(), i,
getRetValType(argsRetVal[lrs[i]->getDcl()].retValType));
}
printf("\n\n");
}
void Augmentation::dumpArgs(SparseBitVector& subArgs)
{
printf("\n");
printf("\n");
auto getArgType = [](ArgType argType) {
if (argType == Augmentation::ArgType::DefBeforeEachCall)
return "DefBeforeCall";
else if (argType == Augmentation::ArgType::Init)
return "Init";
else if (argType == Augmentation::ArgType::LiveThrough)
return "LiveThrough";
else if (argType == Augmentation::ArgType::Unknown)
return "Unknown";
return "???";
};
for (auto i : subArgs) {
printf("Arg = %s (%d) - %s\n", gra.incRA.getLRs()[i]->getDcl()->getName(),
i, getArgType(argsRetVal[lrs[i]->getDcl()].argType));
}
printf("\n");
}
//
// Mark interference between newDcl and other incompatible dcls in current
// active lists.
//
void Augmentation::buildSIMDIntfDcl(G4_Declare *newDcl) {
auto newDclAugMask = gra.getAugmentationMask(newDcl);
auto intfNeededForNewDcl =
(gra.incRA.isEnabled() && gra.incRA.hasAnyCandidates())
? gra.incRA.intfNeededForVar(newDcl)
: true;
auto id1 = newDcl->getRegVar()->getId();
auto newDclRAPartaker = newDcl->getRegVar()->isRegAllocPartaker();
auto intfNeeded = [&](G4_Declare *otherDcl) {
if (!intfNeededForNewDcl && !gra.incRA.intfNeededForVar(otherDcl)) {
return false;
}
auto otherRegVar = otherDcl->getRegVar();
if (newDclRAPartaker && otherRegVar->isRegAllocPartaker()) {
auto id2 = otherRegVar->getId();
if (intf.interfereBetween(id1, id2)) {
return false;
}
}
return true;
};
if (newDclAugMask == AugmentationMasks::NonDefault)
{
for (auto& defaultEntry : defaultMaskQueue) {
auto defaultDcl = defaultEntry.dcl;
if (!intfNeeded(defaultDcl))
continue;
handleSIMDIntf(defaultDcl, newDcl, false);
}
} else {
for (auto &defaultEntry : defaultMaskQueue) {
auto defaultDcl = defaultEntry.dcl;
auto defaultDclAugMask = gra.getAugmentationMask(defaultDcl);
if (defaultDclAugMask != newDclAugMask) {
if (!intfNeeded(defaultDcl))
continue;
handleSIMDIntf(defaultDcl, newDcl, false);
} else {
if (liveAnalysis.livenessClass(G4_GRF) &&
// Populate compatible sparse intf data structure
// only for weak edges.
weakEdgeNeeded(defaultDclAugMask, newDclAugMask)) {
if (defaultDcl->getRegVar()->isPhyRegAssigned() &&
newDcl->getRegVar()->isPhyRegAssigned()) {
continue;
}
if (intf.isStrongEdgeBetween(defaultDcl, newDcl)) {
// No need to add weak edge
continue;
}
// defaultDcl and newDcl are compatible live-ranges and can have weak
// edge in intf graph
intf.compatibleSparseIntf[defaultDcl].insert(newDcl);
intf.compatibleSparseIntf[newDcl].insert(defaultDcl);
}
}
}
}
// Mark interference among non-default mask variables
for (auto &nonDefaultEntry : nonDefaultMaskQueue) {
auto nonDefaultDcl = nonDefaultEntry.dcl;
auto isAugNeeded = [&]() {
if (newDclAugMask != AugmentationMasks::NonDefault)
return true;
// Skip augmentation check if both dcls are infinite spill cost tmp dcls
// generated by RA. Such dcls have their interference correctly computed
// by conventional interference computation. In case of address taken
// spill/fill dcls, applying augmentation on them causes unexpected
// interference edges.
//
// Unexpected intf shows up because we reuse dcl for address taken
// spill/fill across BBs. As per generated code, such address taken
// spill/fill dcl ranges are live only around the indirect operand. Also,
// these ranges are never live across BBs. As augmentation models
// live-intervals without holes, it ends up with unnecessary
// interferences. Here is such an example of unnecessary interference
// edge:
//
// BB1:
// A0 = &ADDR_SP_FL_1 + offset
// (W) Fill ADDR_SP_FL_1
// r[A0] = ...
// (W) Spill ADD_SP_FL_1
//
// BB2:
// (W) Fill FL_V10
// = FL_V10
//
// BB10:
// (W) Fill ADDR_SP_FL_1
// r[A0] = ...
// (W) Spill ADD_SP_FL_1
//
// ADDR_SP_FL_1 and FL_V10 shouldnt interfere. Without logic below, they
// would interfere making RA results worse.
auto regVar1 = nonDefaultDcl->getRegVar();
auto regVar2 = newDcl->getRegVar();
if (!((regVar1->isRegVarTmp() || regVar1->isRegVarTransient() ||
regVar1->isRegVarCoalesced()) &&
(regVar2->isRegVarTmp() || regVar2->isRegVarTransient() ||
regVar2->isRegVarCoalesced())))
return true;
// Both dcls are RA tmps. Ordinarily they're never live-out of any BB. If
// any of them is live across BBs then it's possible they don't interfere
// as per scalar liveness but they may interfere due to divergent CF.
// For example:
//
// if(cond)
// (W) V1 = ...
// else
// (W) V2 = ...
// = V2
// endif
//
// = V1
//
// In above example, V1 doesnt interfere with V2 as per scalar liveness
// but it should if the branch were divergent. For correctness we need to
// mark V1 and V2 as interfering. Since they're never live together as per
// scalar liveness, they need to be handled in augmentation. This case
// shouldnt occur for RA tmps as RA generated spill/fill tmps are
// transient and never live-out of any BB. Still adding check to be safe.
auto id1 = regVar1->getId();
auto id2 = regVar2->getId();
for (auto bb : kernel.fg.getBBList()) {
if (liveAnalysis.isLiveAtExit(bb, id1) ||
liveAnalysis.isLiveAtExit(bb, id2))
return true;
}
// Conventional intf construction correctly handles the scenario when V1
// and V2 are referenced in single (same) BB.
return false;
};
if (!isAugNeeded())
continue;
if (!intfNeeded(nonDefaultDcl))
continue;
// Non-default masks are different so mark interference.
// SIMD interference for call sites is handled separately.
handleSIMDIntf(nonDefaultDcl, newDcl, false);
}
}
//
// Mark interference between newDcl and other incompatible dcls in current
// active lists. If newDcl was created for a subroutine call, do this for all
// varaibles in function summary.
//
void Augmentation::storeOverlapWithCallRet(G4_Declare *newDcl,
const std::vector<bool>& globalVars) {
vISA_ASSERT(callDclMap.count(newDcl) > 0, "expecting newDcl in map");
auto& callDclData = callDclMap[newDcl];
if (liveAnalysis.livenessClass(G4_GRF)) // For return value
{
G4_INST *callInst = callDclData.first;
auto* varDcl = callInst->getDst()->getTopDcl();
addSIMDIntfForRetDclares(varDcl, globalVars);
}
auto *callBB = callDclData.second;
addSIMDIntfDclForCallSite(callBB, globalVars);
}
//
// Perform linear scan and mark interference between conflicting dcls with
// incompatible masks.
//
void Augmentation::buildInterferenceIncompatibleMask() {
// Collect global vars in unordered_set for quick lookup
std::vector<bool> globalVars(liveAnalysis.getNumSelectedVar(), false);
if (!kernel.fg.funcInfoTable.empty()) {
for (auto bit : liveAnalysis.globalVars)
globalVars[bit] = true;
}
// Create 2 active lists - 1 for holding active live-intervals
// with non-default mask and other for default mask
for (auto &interval : sortedIntervals) {
auto *newDcl = interval.dcl;
unsigned startIdx = interval.interval.start->getLexicalId();
VISA_DEBUG_VERBOSE(std::cout << "New idx " << startIdx << "\n");
expireIntervals(startIdx);
if (callDclMap.count(newDcl) > 0) {
storeOverlapWithCallRet(newDcl, globalVars);
} else {
buildSIMDIntfDcl(newDcl);
}
// Add newDcl to correct list
if (gra.getHasNonDefaultMaskDef(newDcl) || newDcl->getAddressed() == true) {
nonDefaultMaskQueue.push(interval);
VISA_DEBUG_VERBOSE(std::cout << "Adding " << newDcl->getName()
<< " to non-default list\n");
} else {
defaultMaskQueue.push(interval);
VISA_DEBUG_VERBOSE(std::cout << "Adding " << newDcl->getName()
<< " to default list\n");
}
}
for (auto func : kernel.fg.funcInfoTable) {
buildInteferenceForCallsite(func);
}
buildInteferenceForRetDeclares();
}
void Augmentation::buildInteferenceForCallSiteOrRetDeclare(std::vector<G4_Declare*>& dcls,
MaskDeclares *mask) {
for (auto newDcl : dcls) {
auto newDclAugMask = gra.getAugmentationMask(newDcl);
auto intfNeededForNewDcl =
(gra.incRA.isEnabled() && gra.incRA.hasAnyCandidates())
? gra.incRA.intfNeededForVar(newDcl)
: true;
auto id1 = newDcl->getRegVar()->getId();
auto newDclRAPartaker = newDcl->getRegVar()->isRegAllocPartaker();
auto intfNeeded = [&](G4_Declare *otherDcl) {
if (!intfNeededForNewDcl && !gra.incRA.intfNeededForVar(otherDcl)) {
return false;
}
auto otherRegVar = otherDcl->getRegVar();
if (newDclRAPartaker && otherRegVar->isRegAllocPartaker()) {
auto id2 = otherRegVar->getId();
if (intf.interfereBetween(id1, id2)) {
return false;
}
}
return true;
};
if (newDclAugMask == AugmentationMasks::NonDefault) {
for (auto i : mask->first) {
G4_Declare *defaultDcl = lrs[i]->getDcl();
if (!intfNeeded(defaultDcl))
continue;
handleSIMDIntf(defaultDcl, newDcl, true);
}
} else {
for (auto i : mask->first) {
G4_Declare *defaultDcl = lrs[i]->getDcl();
if (gra.getAugmentationMask(defaultDcl) != newDclAugMask) {
if (!intfNeeded(defaultDcl))
continue;
handleSIMDIntf(defaultDcl, newDcl, true);
} else {
if (liveAnalysis.livenessClass(G4_GRF) &&
// Populate compatible sparse intf data structure
// only for weak edges.
weakEdgeNeeded(gra.getAugmentationMask(defaultDcl),
newDclAugMask)) {
if (defaultDcl->getRegVar()->isPhyRegAssigned() &&
newDcl->getRegVar()->isPhyRegAssigned()) {
continue;
}
if (intf.isStrongEdgeBetween(defaultDcl, newDcl)) {
// No need to add weak edge
continue;
}
// defaultDcl and newDcl are compatible live-ranges and can have
// weak edge in intf graph
intf.compatibleSparseIntf[defaultDcl].insert(newDcl);
intf.compatibleSparseIntf[newDcl].insert(defaultDcl);
}
}
}
}
for (auto i : mask->second) {
if (!intfNeeded(lrs[i]->getDcl()))
continue;
// Mark interference among non-default mask variables
G4_Declare *nonDefaultDcl = lrs[i]->getDcl();
// Non-default masks are different so mark interference
handleSIMDIntf(nonDefaultDcl, newDcl, true);
}
}
}
std::vector<G4_Declare *> SBitToVector(SparseBitVector *sparseBitVector,
const LiveRangeVec &lrs) {
std::vector<G4_Declare *> retVector;
for (auto bit : *sparseBitVector) {
auto *varDcl = lrs[bit]->getDcl();
retVector.push_back(varDcl);
}
return retVector;
}
// This method is invoked once per subroutine func.
void Augmentation::buildInteferenceForCallsite(FuncInfo *func) {
auto maydefConst = liveAnalysis.subroutineMaydef.find(func);
if (maydefConst != liveAnalysis.subroutineMaydef.end()) {
auto *maydef = const_cast<SparseBitVector *>(&maydefConst->second);
std::vector<G4_Declare *> maydefDcls(SBitToVector(maydef, lrs));
buildInteferenceForCallSiteOrRetDeclare(maydefDcls, &overlapDclsWithFunc[func]);
}
if (gra.useLocalRA) {
std::vector<G4_Declare *> lraDcls;
for (uint32_t j = 0; j < kernel.getNumRegTotal(); j++) {
if (localSummaryOfCallee[func].isGRFBusy(j)) {
G4_Declare *varDcl = gra.getGRFDclForHRA(j);
lraDcls.push_back(varDcl);
}
}
buildInteferenceForCallSiteOrRetDeclare(lraDcls, &overlapDclsWithFunc[func]);
}
}
void Augmentation::buildInteferenceForRetDeclares() {
for (auto &retDclIt : retDeclares) {
std::vector<G4_Declare *> retDclVec({retDclIt.first});
buildInteferenceForCallSiteOrRetDeclare(retDclVec, &retDclIt.second);
}
}
void Augmentation::buildSummaryForCallees() {
int totalGRFNum = kernel.getNumRegTotal();
for (auto func : kernel.fg.sortedFuncTable) {
unsigned fid = func->getId();
if (fid == UINT_MAX) {
// entry kernel
continue;
}
PhyRegSummary funcSummary(kernel.fg.builder, totalGRFNum);
for (auto &&bb : func->getBBList()) {
if (auto summary = gra.getBBLRASummary(bb)) {
for (int i = 0; i < totalGRFNum; i++) {
if (summary->isGRFBusy(i)) {
funcSummary.setGRFBusy(i);
}
}
}
}
for (auto &&callee : func->getCallees()) {
PhyRegSummary *summary = &localSummaryOfCallee[callee];
if (summary) {
for (int i = 0; i < totalGRFNum; i++) {
if (summary->isGRFBusy(i)) {
funcSummary.setGRFBusy(i);
}
}
}
}
localSummaryOfCallee[func] = std::move(funcSummary);
}
}
void Augmentation::augmentIntfGraph() {
if (!(kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
!liveAnalysis.livenessClass(G4_ADDRESS) && kernel.fg.size() > 2)) {
if (!kernel.getOption(vISA_DumpRegChart)) {
return;
}
}
if (gra.useLocalRA) {
buildSummaryForCallees();
}
bool augWithHoles = kernel.getOption(vISA_NewAugmentation);
// First check whether any definitions exist with incompatible mask
bool nonDefaultMaskDef = markNonDefaultMaskDef();
if (nonDefaultMaskDef == true) {
if (augWithHoles) {
if (kernel.fg.getNumFuncs() > 0)
populateFuncMaps();
populateHomeFunc();
// Atleast one definition with non-default mask was found so
// perform steps to augment intf graph with such defs
// Discover and store subroutine arguments
if (hasSubroutines) {
for (auto &subroutine : kernel.fg.sortedFuncTable) {
discoverArgs(subroutine);
discoverRetVal(subroutine);
// Now build live-intervals per subroutine. This function will
// calculate live-intervals and assign start/end inst for
// respective declares.
buildLiveIntervals(subroutine);
}
} else {
buildLiveIntervals(kernel.fg.kernelInfo);
}
// Create live-intervals for Unknown arg and retval
buildUnknownArgRetval();
} else {
buildLiveIntervals();
}
// Sort live-intervals based on their start
sortLiveIntervals();
if (kernel.getOption(vISA_DumpLiveRanges)) {
dumpLiveRanges(gra, sortedIntervals);
}
if (kernel.getOption(vISA_DumpRegChart)) {
gra.regChart = std::make_unique<RegChartDump>(gra);
gra.regChart->recordLiveIntervals(sortedIntervals);
}
if (gra.verifyAugmentation) {
gra.verifyAugmentation->loadAugData(
sortedIntervals, lrs, callDclMap,
intf.liveAnalysis->getNumSelectedVar(), &intf, gra);
}
if (kernel.getOption(vISA_SpillAnalysis)) {
if (gra.spillAnalysis.get())
gra.spillAnalysis->LoadAugIntervals(sortedIntervals, gra);
}
if (kernel.fg.builder->getOption(vISA_GenerateDebugInfo)) {
// Following is done to prevent passing GlobalRA to debug info function
// for clear interface.
std::vector<std::tuple<G4_Declare *, G4_INST *, G4_INST *>> dclIntervals;
dclIntervals.reserve(sortedIntervals.size());
for (auto &interval : sortedIntervals) {
auto dcl = interval.dcl;
dclIntervals.push_back(std::make_tuple(dcl, interval.interval.start,
interval.interval.end));
}
updateDebugInfo(kernel, std::move(dclIntervals));
}
// Perform linear scan to augment graph
buildInterferenceIncompatibleMask();
if (liveAnalysis.livenessClass(G4_GRF)) {
if ((GlobalRA::useGenericAugAlign(kernel.getPlatformGeneration()) &&
kernel.getSimdSize() >= kernel.numEltPerGRF<Type_UD>()) ||
(!GlobalRA::useGenericAugAlign(kernel.getPlatformGeneration()) &&
kernel.getSimdSize() > kernel.numEltPerGRF<Type_UD>())) {
// Set alignment of all GRF candidates
// to 2GRF except for NoMask variables
VISA_DEBUG_VERBOSE(std::cout
<< "Kernel size is SIMD" << kernel.getSimdSize()
<< " so updating all GRFs to aug align"
<< "\n");
gra.augAlign();
}
gra.updateSubRegAlignment(kernel.getGRFAlign());
}
}
}
void Interference::buildInterferenceWithLocalRA(G4_BB *bb) {
auto LRASummary = gra.getBBLRASummary(bb);
if (LRASummary == nullptr) {
return;
}
BitSet cur(kernel.getNumRegTotal(), true);
SparseBitVector live;
std::vector<int> curUpdate;
buildInterferenceAtBBExit(bb, live);
VISA_DEBUG_VERBOSE(std::cout << "BB" << bb->getId() << "\n");
for (INST_LIST_RITER rit = bb->rbegin(), rend = bb->rend(); rit != rend;
rit++) {
bool update = false;
G4_INST *inst = (*rit);
curUpdate.clear();
VISA_DEBUG_VERBOSE({
inst->emit(std::cout);
std::cout << "\n";
});
// Any physical registers defined will be marked available if
// current inst is first def or if complete region is written
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getBase()->isRegVar()) {
LocalLiveRange *localLR = NULL;
G4_Declare *topdcl = GetTopDclFromRegRegion(dst);
unsigned t;
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned() && !localLR->isEOT()) {
int reg, sreg, numrows;
G4_VarBase *preg = localLR->getPhyReg(sreg);
numrows = localLR->getTopDcl()->getNumRows();
vISA_ASSERT(preg->isGreg(), "Register in dst was not GRF");
reg = preg->asGreg()->getRegNum();
// Check whether the dst physical register is busy/available.
// If it is available, and we still see a def that means there was no
// corresponding use. In such cases mark the physical register as
// busy, so interference building can take place correctly.
for (int j = reg, sum = reg + numrows; j < sum; j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (cur.isSet(j) == true) {
buildInterferenceWithLive(live, k);
VISA_DEBUG_VERBOSE(
std::cout << "Found no use for r" << j
<< ".0 so marking it as interfering with live set"
<< "\n");
}
}
if ((localLR->getFirstRef(t) == inst) ||
liveAnalysis->writeWholeRegion(bb, inst, dst)) {
// Last row may be only partially used by the current dcl
// so we still need to pessimistically mark last range as
// busy. Because some other src opnd that is live may still
// be using the remaining GRF.
if (localLR->getSizeInWords() % kernel.numEltPerGRF<Type_UW>() != 0)
numrows--;
for (int j = reg, sum = reg + numrows; j < sum; j++) {
cur.set(j, true);
VISA_DEBUG_VERBOSE(std::cout << "Setting r" << j << ".0 available"
<< "\n");
}
// Build interference only for point ranges, ideally which shouldnt
// exist These are ranges that have a def, but no use
if (localLR->getFirstRef(t) == localLR->getLastRef(t)) {
for (int j = reg; j < reg + localLR->getTopDcl()->getNumRows();
j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
buildInterferenceWithLive(live, k);
}
}
}
} else if (dst->getBase()->isRegAllocPartaker()) {
// Global range
// In bottom-up order if the live-range has not started then
// a use was not seen for this def. But we need to ensure this
// variable interferes with all other live vars.
bool isPointRange = !live.test(dst->getBase()->asRegVar()->getId());
if (isPointRange) {
// Mark interference with all busy physical registers
for (unsigned i = 0; i < kernel.getNumRegTotal(); i++) {
if (cur.isSet(i) == false) {
int k = getGRFDclForHRA(i)->getRegVar()->getId();
checkAndSetIntf(dst->getBase()->asRegVar()->getId(), k);
}
}
}
if (liveAnalysis->writeWholeRegion(bb, inst, dst) ||
inst->isPseudoKill()) {
// Whole write or first def found so mark this operand as not live for
// earlier instructions
auto id = dst->getBase()->asRegVar()->getId();
updateLiveness(live, id, false);
}
} else if (dst->isIndirect() && liveAnalysis->livenessClass(G4_GRF)) {
// make every var in points-to set live
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(dst,
bb);
for (auto &pt : pointsToSet) {
if (pt.var->isRegAllocPartaker()) {
updateLiveness(live, pt.var->getId(), true);
}
}
}
}
// Any physical registers used by src opnds will be busy before the current
// inst
for (int i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
G4_Operand *src = inst->getSrc(i);
if (src && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
LocalLiveRange *localLR = NULL;
G4_Declare *topdcl = GetTopDclFromRegRegion(src);
if (topdcl)
localLR = gra.getLocalLR(topdcl);
if (localLR && localLR->getAssigned() && !localLR->isEOT()) {
int sreg;
G4_VarBase *preg = localLR->getPhyReg(sreg);
int numrows = localLR->getTopDcl()->getNumRows();
vISA_ASSERT(preg->isGreg(), "Register in src was not GRF");
int reg = preg->asGreg()->getRegNum();
for (int j = reg, sum = reg + numrows; j < sum; j++) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
if (cur.isSet(j) == true) {
// G4_RegVar with id k was marked free, but becomes
// busy at this instruction. For incremental updates
// push this to a vector and use it while updating
// interference graph incrementally.
curUpdate.push_back(k);
}
cur.set(j, false);
VISA_DEBUG_VERBOSE(std::cout << "Setting r" << j << ".0 busy\n");
}
} else if (src->asSrcRegRegion()->getBase()->isRegAllocPartaker()) {
if (live.test(
src->asSrcRegRegion()->getBase()->asRegVar()->getId()) ==
false)
update = true;
// Mark operand as live from this inst upwards
auto id = src->asSrcRegRegion()->getBase()->asRegVar()->getId();
updateLiveness(live, id, true);
} else if (src->asSrcRegRegion()->isIndirect() &&
liveAnalysis->livenessClass(G4_GRF)) {
// make every var in points-to set live
const REGVAR_VECTOR &pointsToSet =
liveAnalysis->getPointsToAnalysis().getAllInPointsToOrIndrUse(
src->asSrcRegRegion(), bb);
for (auto &pt : pointsToSet) {
if (pt.var->isRegAllocPartaker()) {
if (live.test(pt.var->getId()) == false)
update = true;
updateLiveness(live, pt.var->getId(), true);
}
}
}
}
}
if (update == true) {
// Mark interference with all live
for (unsigned i = 0; i < kernel.getNumRegTotal(); i++) {
if (cur.isSet(i) == false) {
int k = getGRFDclForHRA(i)->getRegVar()->getId();
buildInterferenceWithLive(live, k);
}
}
} else {
if (curUpdate.size() > 0) {
// Perform incremental update. This code is executed when:
// 1) live set is unchanged, ie no new global range was started in inst
// 2) cur set has changed, ie an earlier free GRF has become busy
// Any new busy GRFs will have to be marked as interfering with
// currently live-ranges. There is no need to iterate over all
// busy GRFs. Instead only those GRFs that have got busy in this
// iteration can be considered for incremental updates.
for (int k : curUpdate) {
buildInterferenceWithLive(live, k);
}
}
}
}
for (unsigned i = 0; i < maxId; i++) {
bool isAddrSensitive = liveAnalysis->isAddressSensitive(i);
// If a range is Address taken AND (live-in or live-out or killed)
// mark it to interfere with all physical registers used by local RA
// FIXME: need to check if this is actually needed
if (isAddrSensitive) {
bool assigned = (lrs[i]->getVar()->getPhyReg() != NULL);
if (!assigned) {
bool isLiveIn = liveAnalysis->isLiveAtEntry(bb, i);
bool isLiveOut = liveAnalysis->isLiveAtExit(bb, i);
bool isKilled = liveAnalysis->use_kill[bb->getId()].test(i);
if (isLiveIn || isLiveOut || isKilled) {
// Make it to interfere with all physical registers used in the BB
for (uint32_t j = 0, numReg = kernel.getNumRegTotal(); j < numReg;
j++) {
if (LRASummary->isGRFBusy(j)) {
int k = getGRFDclForHRA(j)->getRegVar()->getId();
checkAndSetIntf(i, k);
}
}
}
}
}
}
}
GraphColor::GraphColor(LivenessAnalysis &live, bool hybrid, bool forceSpill_)
: gra(live.gra), totalGRFRegCount(gra.kernel.getNumRegTotal()),
numVar(live.getNumSelectedVar()), intf(&live, gra), regPool(gra.regPool),
builder(gra.builder), lrs(live.gra.incRA.getLRs()), isHybrid(hybrid),
forceSpill(forceSpill_), GCMem(GRAPH_COLOR_MEM_SIZE), kernel(gra.kernel),
liveAnalysis(live)
{
spAddrRegSig.resize(builder.getNumAddrRegisters(), 0);
m_options = builder.getOptions();
}
//
// lrs[i] gives the live range whose id is i
//
void GraphColor::createLiveRanges() {
lrs.resize(numVar);
for (auto dcl : gra.kernel.Declares) {
G4_RegVar *var = dcl->getRegVar();
// Do not include alias var in liverange creation
if (!var->isRegAllocPartaker() || dcl->getAliasDeclare() != NULL) {
continue;
}
lrs[var->getId()] = LiveRange::createNewLiveRange(dcl, gra);
}
}
template<bool Support4GRFAlign>
void GraphColor::computeDegreeForGRF() {
for (unsigned i = 0; i < numVar; i++) {
unsigned degree = 0;
if (!(lrs[i]->getIsPseudoNode()) && !(lrs[i]->getIsPartialDcl())) {
const std::vector<unsigned> &intfs = intf.getSparseIntfForVar(i);
unsigned bankDegree = 0;
auto lraBC = lrs[i]->getBC();
bool isOdd = (lraBC == BANK_CONFLICT_SECOND_HALF_EVEN ||
lraBC == BANK_CONFLICT_SECOND_HALF_ODD);
auto computeDegree = [&](LiveRange *lr1) {
if (!lr1->getIsPartialDcl()) {
unsigned edgeDegree = edgeWeightGRF<Support4GRFAlign>(lrs[i], lr1);
degree += edgeDegree;
auto lrsitBC = lr1->getBC();
bool isOddBC = (lrsitBC == BANK_CONFLICT_SECOND_HALF_EVEN ||
lrsitBC == BANK_CONFLICT_SECOND_HALF_ODD);
if ((isOdd && isOddBC) || (!isOdd && !isOddBC)) {
bankDegree += edgeDegree;
}
}
};
for (auto it : intfs) {
computeDegree(lrs[it]);
}
// consider weak edges in degree computation
auto *weakEdges = intf.getCompatibleSparseIntf(lrs[i]->getDcl());
if (weakEdges) {
vISA_ASSERT(!gra.use4GRFAlign, "not expecting weak edges");
for (auto weakNeighbor : *weakEdges) {
if (!weakNeighbor->getRegVar()->isRegAllocPartaker())
continue;
computeDegree(lrs[weakNeighbor->getRegVar()->getId()]);
}
}
if (isOdd) {
oddTotalDegree += bankDegree; // std::max(bankDegree, oddMaxDegree);
oddTotalRegNum += lrs[i]->getNumRegNeeded();
oddMaxRegNum = std::max(oddMaxRegNum, lrs[i]->getNumRegNeeded());
} else {
evenTotalDegree += bankDegree; // std::max(bankDegree, evenMaxDegree);
evenTotalRegNum += lrs[i]->getNumRegNeeded();
evenMaxRegNum = std::max(evenMaxRegNum, lrs[i]->getNumRegNeeded());
}
}
lrs[i]->setDegree(degree);
}
if (kernel.getOption(vISA_SpillAnalysis)) {
for (unsigned int i = 0; i != numVar; ++i) {
auto dcl = lrs[i]->getDcl();
auto degree = lrs[i]->getDegree();
gra.spillAnalysis->LoadDegree(dcl, degree);
}
}
}
void GraphColor::computeDegreeForARF() {
for (unsigned i = 0; i < numVar; i++) {
unsigned degree = 0;
if (!(lrs[i]->getIsPseudoNode())) {
const std::vector<unsigned> &intfs = intf.getSparseIntfForVar(i);
for (auto it : intfs) {
degree += edgeWeightARF(lrs[i], lrs[it]);
}
}
lrs[i]->setDegree(degree);
}
}
void GraphColor::computeSpillCosts(bool useSplitLLRHeuristic, const RPE *rpe) {
LiveRangeVec addressSensitiveVars;
float maxNormalCost = 0.0f;
VarReferences directRefs(kernel, true, false);
std::unordered_map<G4_Declare *, std::list<std::pair<G4_INST *, G4_BB *>>>
indirectRefs;
// when reg pressure is not very high in iter0, use spill cost function
// that favors allocating large variables
bool useNewSpillCost =
(builder.getOption(vISA_NewSpillCostFunctionISPC) ||
builder.getOption(vISA_NewSpillCostFunction)) &&
rpe &&
!(gra.getIterNo() == 0 &&
(float)rpe->getMaxRP() < (float)kernel.getNumRegTotal() * 0.80f);
RA_TRACE({
if (useNewSpillCost)
std::cout << "\t--using new spill cost function\n";
});
if (useNewSpillCost && liveAnalysis.livenessClass(G4_GRF)) {
// gather all instructions with indirect operands
// for ref count computation once.
for (auto bb : kernel.fg.getBBList()) {
for (auto inst : *bb) {
auto dst = inst->getDst();
if (dst && dst->isIndirect()) {
auto pointsTo = liveAnalysis.getPointsToAnalysis().getAllInPointsTo(
dst->getBase()
->asRegVar()
->getDeclare()
->getRootDeclare()
->getRegVar());
if (pointsTo) {
for (auto &pointee : *pointsTo)
indirectRefs[pointee.var->getDeclare()->getRootDeclare()]
.push_back(std::make_pair(inst, bb));
}
continue;
}
for (unsigned int i = 0; i != inst->getNumSrc(); ++i) {
auto src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion() ||
!src->asSrcRegRegion()->isIndirect()) {
continue;
}
auto pointsTo = liveAnalysis.getPointsToAnalysis().getAllInPointsTo(
src->asSrcRegRegion()
->getBase()
->asRegVar()
->getDeclare()
->getRootDeclare()
->getRegVar());
if (pointsTo) {
for (auto &pointee : *pointsTo)
indirectRefs[pointee.var->getDeclare()->getRootDeclare()]
.push_back(std::make_pair(inst, bb));
}
continue;
}
}
}
}
auto getWeightedRefCount = [&](G4_Declare *dcl, unsigned int useWt = 1,
unsigned int defWt = 1) {
auto defs = directRefs.getDefs(dcl);
auto uses = directRefs.getUses(dcl);
auto &loops = kernel.fg.getLoops();
unsigned int refCount = 0;
const unsigned int assumeLoopIter = 10;
if (defs) {
for (auto &def : *defs) {
auto *bb = std::get<1>(def);
auto *innerMostLoop = loops.getInnerMostLoop(bb);
if (innerMostLoop) {
auto nestingLevel = innerMostLoop->getNestingLevel();
refCount += (unsigned int)std::pow(assumeLoopIter, nestingLevel);
} else
refCount += defWt;
}
}
if (uses) {
for (auto &use : *uses) {
auto *bb = std::get<1>(use);
auto *innerMostLoop = loops.getInnerMostLoop(bb);
if (innerMostLoop) {
auto nestingLevel = innerMostLoop->getNestingLevel();
refCount += (unsigned int)std::pow(assumeLoopIter, nestingLevel);
} else
refCount += useWt;
}
}
if (dcl->getAddressed()) {
auto indirectRefsIt = indirectRefs.find(dcl);
if (indirectRefsIt != indirectRefs.end()) {
auto &dclIndirRefs = (*indirectRefsIt).second;
for (auto &item : dclIndirRefs) {
auto bb = item.second;
auto *innerMostLoop = loops.getInnerMostLoop(bb);
if (innerMostLoop) {
auto nestingLevel = innerMostLoop->getNestingLevel();
refCount += (unsigned int)std::pow(assumeLoopIter, nestingLevel);
} else
refCount += useWt;
}
}
}
return refCount == 0 ? 1 : refCount;
};
std::unordered_map<const G4_Declare *, std::vector<G4_Declare *>>
addrTakenMap;
std::unordered_map<G4_Declare *, std::vector<const G4_Declare *>>
revAddrTakenMap;
bool addrMapsComputed = false;
auto incSpillCostCandidate = [&](LiveRange *lr) {
if (kernel.getOption(vISA_IncSpillCostAllAddrTaken))
return true;
if (!addrMapsComputed) {
const_cast<PointsToAnalysis &>(liveAnalysis.getPointsToAnalysis())
.getPointsToMap(addrTakenMap);
const_cast<PointsToAnalysis &>(liveAnalysis.getPointsToAnalysis())
.getRevPointsToMap(revAddrTakenMap);
addrMapsComputed = true;
}
// this condition is a safety measure and isnt expected to be true.
auto it = revAddrTakenMap.find(lr->getDcl());
if (it == revAddrTakenMap.end())
return true;
for (auto &addrVar : (*it).second) {
if (addrTakenMap.count(addrVar) > 1)
return true;
}
return false;
};
for (unsigned i = 0; i < numVar; i++) {
G4_Declare *dcl = lrs[i]->getDcl();
if (dcl->getIsPartialDcl()) {
continue;
}
//
// The spill cost of pseudo nodes inserted to aid generation of save/restore
// code must be the minimum so that such nodes go to the bootom of the color
// stack.
//
if (builder.kernel.fg.isPseudoDcl(dcl)) {
if (builder.kernel.fg.isPseudoVCADcl(dcl)) {
lrs[i]->setSpillCost(MINSPILLCOST + 1);
} else {
lrs[i]->setSpillCost(MINSPILLCOST);
}
}
auto dclLR = gra.getLocalLR(dcl);
if (dclLR != NULL && dclLR->getSplit()) {
lrs[i]->setSpillCost(MINSPILLCOST + 2);
}
//
// Give the tiny spill/fill ranges an infinite spill cost, so that they are
// picked first for coloring.
// Also ARF live ranges with exclusively sequential references within the
// code are assigned an infinite spill cost as spilling them will not lower
// the register pressure in the region they are referenced. This does not
// necessarily hold for GRF live ranges are these are potentially large in
// size but the portions accessed by each sequential use are limited to 2
// registers for general instructions and 8 registers for SEND instructions.
//
else if (gra.isAddrFlagSpillDcl(dcl) || lrs[i]->isRetIp() ||
lrs[i]->getIsInfiniteSpillCost() == true ||
((lrs[i]->getVar()->isRegVarTransient() == true ||
lrs[i]->getVar()->isRegVarTmp() == true) &&
lrs[i]->getVar()->isSpilled() == false) ||
dcl == gra.getOldFPDcl() ||
(!builder.canReadR0() && dcl == builder.getBuiltinR0())) {
lrs[i]->setSpillCost(MAXSPILLCOST);
} else if (dcl->isDoNotSpill()) {
lrs[i]->setSpillCost(MAXSPILLCOST);
}
//
// Calculate spill costs of regular nodes.
//
else {
float spillCost = 0.0f;
// NOTE: Add 1 to degree to avoid divide-by-0, as a live range may have no
// neighbors
if (builder.kernel.getInt32KernelAttr(Attributes::ATTR_Target) ==
VISA_3D) {
if (useSplitLLRHeuristic) {
spillCost = 1.0f * lrs[i]->getRefCount() / (lrs[i]->getDegree() + 1);
} else {
vASSERT(lrs[i]->getDcl()->getTotalElems() > 0);
if (!liveAnalysis.livenessClass(G4_GRF) || !useNewSpillCost) {
// address or flag variables
unsigned short numRows = lrs[i]->getDcl()->getNumRows();
spillCost = 1.0f * lrs[i]->getRefCount() * lrs[i]->getRefCount() *
lrs[i]->getDcl()->getByteSize() *
(float)sqrt(lrs[i]->getDcl()->getByteSize()) /
((float)sqrt(lrs[i]->getDegree() + 1) *
(float)(sqrt(sqrt(numRows))));
} else {
// GRF variables
auto refCount = getWeightedRefCount(lrs[i]->getDcl());
spillCost = 1.0f * refCount * refCount * refCount /
((float)(lrs[i]->getDegree() + 1) *
(float)(lrs[i]->getDegree() + 1));
}
}
} else {
if (!useNewSpillCost) {
spillCost = liveAnalysis.livenessClass(G4_GRF)
? lrs[i]->getDegree()
: 1.0f * lrs[i]->getRefCount() *
lrs[i]->getRefCount() /
(lrs[i]->getDegree() + 1);
} else {
auto refCount = getWeightedRefCount(lrs[i]->getDcl());
spillCost = 1.0f * refCount * refCount * refCount /
((float)(lrs[i]->getDegree() + 1) *
(float)(lrs[i]->getDegree() + 1));
}
}
lrs[i]->setSpillCost(spillCost);
// Track address sensitive live range.
if (liveAnalysis.isAddressSensitive(i) && incSpillCostCandidate(lrs[i])) {
addressSensitiveVars.push_back(lrs[i]);
} else {
// Set the spill cost of all other normal live ranges, and
// track the max normal cost.
if (maxNormalCost < spillCost) {
maxNormalCost = spillCost;
}
}
}
}
//
// Set the spill cost of address sensitive live ranges above all the
// normal live ranges, so that they get colored before all the normal
// live ranges.
//
for (LiveRange *lr : addressSensitiveVars) {
if (lr->getSpillCost() != MAXSPILLCOST) {
lr->setSpillCost(maxNormalCost + lr->getSpillCost());
}
}
}
//
// subtract lr's neighbors that are still in work list
//
void GraphColor::relaxNeighborDegreeGRF(LiveRange *lr) {
if (lr->getIsPseudoNode() || lr->getIsPartialDcl())
return;
unsigned lr_id = lr->getVar()->getId();
unsigned lr2_nreg = lr->getNumRegNeeded();
const std::vector<unsigned> &intfs = intf.getSparseIntfForVar(lr_id);
if (gra.use4GRFAlign) {
unsigned int lr2AugAlign = gra.getAugAlign(lr->getDcl());
for (auto it : intfs) {
LiveRange *lr1 = lrs[it];
if (lr1->getActive() && !lr1->getIsPseudoNode() &&
!(lr1->getIsPartialDcl())) {
unsigned lr1_nreg = lr1->getNumRegNeeded();
unsigned int lr1AugAlign = gra.getAugAlign(lr1->getDcl());
auto w =
edgeWeightWith4GRF(lr1AugAlign, lr2AugAlign, lr1_nreg, lr2_nreg);
relax(lr1, w);
}
}
return;
}
// Handle case where 4GRF align is unsupported
bool lr2EvenAlign = gra.isEvenAligned(lr->getDcl());
for (auto it : intfs) {
LiveRange *lr1 = lrs[it];
if (lr1->getActive() && !lr1->getIsPseudoNode() &&
!(lr1->getIsPartialDcl())) {
unsigned lr1_nreg = lr1->getNumRegNeeded();
unsigned w = 0;
bool lr1EvenAlign = gra.isEvenAligned(lr1->getDcl());
w = edgeWeightGRF(lr1EvenAlign, lr2EvenAlign, lr1_nreg, lr2_nreg);
relax(lr1, w);
}
}
// Weak edges are supported only when 4GRF align is unsupported
auto *weakEdges = intf.getCompatibleSparseIntf(lr->getDcl());
if (weakEdges) {
for (auto weakNeighbor : *weakEdges) {
if (!weakNeighbor->getRegVar()->isRegAllocPartaker())
continue;
auto lr1 = lrs[weakNeighbor->getRegVar()->getId()];
if (lr1->getActive() && !lr1->getIsPseudoNode() &&
!(lr1->getIsPartialDcl())) {
unsigned lr1_nreg = lr1->getNumRegNeeded();
bool lr1EvenAlign = gra.isEvenAligned(lr1->getDcl());
auto w = edgeWeightGRF(lr1EvenAlign, lr2EvenAlign, lr1_nreg, lr2_nreg);
relax(lr1, w);
}
}
}
}
void GraphColor::relaxNeighborDegreeARF(LiveRange *lr) {
if (!(lr->getIsPseudoNode())) {
unsigned lr_id = lr->getVar()->getId();
const std::vector<unsigned> &intfs = intf.getSparseIntfForVar(lr_id);
for (auto it : intfs) {
LiveRange *lrs_it = lrs[it];
if (lrs_it->getActive() && !lrs_it->getIsPseudoNode()) {
unsigned w = edgeWeightARF(lrs_it, lr);
VISA_DEBUG_VERBOSE({
std::cout << "\t relax ";
lrs_it->dump();
std::cout << " degree(" << lrs_it->getDegree() << ") - " << w << "\n";
});
lrs_it->subtractDegree(w);
unsigned availColor = numColor;
if (lrs_it->getDegree() + lrs_it->getNumRegNeeded() <= availColor) {
unconstrainedWorklist.push_back(lrs_it);
lrs_it->setActive(false);
}
}
}
}
}
static bool compareSpillCost(LiveRange *lr1, LiveRange *lr2) {
return lr1->getSpillCost() < lr2->getSpillCost() ||
(lr1->getSpillCost() == lr2->getSpillCost() &&
lr1->getVar()->getId() < lr2->getVar()->getId());
}
//
// All nodes in work list are all contrained (whose degree > max color)
// find one contrained node and move it to order list
//
void GraphColor::removeConstrained() {
if (!constrainedWorklist.empty()) {
LiveRange *lr = constrainedWorklist.front();
constrainedWorklist.pop_front();
if (lr->getActive()) {
VISA_DEBUG_VERBOSE({
std::cout << ".... Remove Constrained ";
lr->dump();
std::cout << "\n";
});
if (liveAnalysis.livenessClass(G4_GRF)) {
relaxNeighborDegreeGRF(lr);
} else {
relaxNeighborDegreeARF(lr);
}
colorOrder.push_back(lr);
lr->setActive(false);
}
}
}
void GraphColor::determineColorOrdering() {
numColor = 0;
if (liveAnalysis.livenessClass(G4_GRF))
numColor = totalGRFRegCount;
else if (liveAnalysis.livenessClass(G4_ADDRESS))
numColor = builder.getNumAddrRegisters();
else if (liveAnalysis.livenessClass(G4_FLAG))
numColor = builder.getNumFlagRegisters();
unsigned numUnassignedVar = liveAnalysis.getNumUnassignedVar();
//
// create an array for sorting live ranges
//
LiveRangeVec sorted;
sorted.reserve(numUnassignedVar);
unsigned j = 0;
for (unsigned i = 0; i < numVar; i++) {
if (lrs[i]->getPhyReg() == nullptr && !lrs[i]->getIsPartialDcl()) {
sorted.push_back(lrs[i]);
j++;
}
}
if (gra.incRA.isEnabledWithVerification(kernel)) {
gra.incRA.computeLeftOverUnassigned(sorted, liveAnalysis);
}
vISA_ASSERT(j == numUnassignedVar, ERROR_GRAPHCOLOR);
//
// sort the live range array
//
std::sort(sorted.begin(), sorted.end(), compareSpillCost);
//This will not change the order unless SPGSS is turned on
builder.getFreqInfoManager().sortBasedOnFreq(sorted);
for (unsigned i = 0; i < numUnassignedVar; i++) {
LiveRange *lr = sorted[i];
unsigned availColor = numColor;
availColor = numColor - lr->getNumForbidden();
if (lr->getDegree() + lr->getNumRegNeeded() <= availColor) {
unconstrainedWorklist.push_back(lr);
lr->setActive(false);
if (lr->getRegKind() == G4_GRF) {
// Mark current lr as unconstrained, which means RR algorithm can always
// be applied to the variable.
lr->setUnconstrained(true);
}
} else {
constrainedWorklist.push_back(lr);
lr->setActive(true);
}
}
VISA_DEBUG_VERBOSE({
std::cout << "\nSPILL COST\n";
for (unsigned i = 0; i < numUnassignedVar; i++) {
sorted[i]->dump();
std::cout << "\t spillCost=" << sorted[i]->getSpillCost();
std::cout << "\t degree=" << sorted[i]->getDegree();
std::cout << "\t refCnt=" << sorted[i]->getRefCount();
std::cout << "\t size=" << sorted[i]->getDcl()->getByteSize();
std::cout << "\t active=" << sorted[i]->getActive();
std::cout << "\n";
}
std::cout << "\n";
});
while (!constrainedWorklist.empty() || !unconstrainedWorklist.empty()) {
while (!unconstrainedWorklist.empty()) {
LiveRange *lr = unconstrainedWorklist.front();
unconstrainedWorklist.pop_front();
VISA_DEBUG_VERBOSE({
std::cout << ".... Remove Unconstrained ";
lr->dump();
std::cout << "\n";
});
if (liveAnalysis.livenessClass(G4_GRF)) {
relaxNeighborDegreeGRF(lr);
} else {
relaxNeighborDegreeARF(lr);
}
colorOrder.push_back(lr);
}
removeConstrained();
}
}
void PhyRegUsage::updateRegUsage(LiveRange *lr) {
G4_Declare *dcl = lr->getDcl();
G4_VarBase *pr;
if (lr->getIsPartialDcl()) {
pr = lrs[lr->getParentLRID()]->getPhyReg();
} else {
pr = lr->getPhyReg();
}
if (!pr) {
return;
}
if (pr->isGreg()) {
if (dcl->getIsPartialDcl()) {
// Assumptions:
// 1. the offset of the sub declare must be G4_WSIZE aligned
// 2. the size of the subdeclare must be G4_WSIZE aligned
markBusyForDclSplit(G4_GRF, ((G4_Greg *)pr)->getRegNum(),
(lrs[lr->getParentLRID()]->getPhyRegOff() *
TypeSize(dcl->getElemType()) +
gra.getSubOffset(dcl)) /
G4_WSIZE,
dcl->getByteSize() / G4_WSIZE, dcl->getNumRows());
} else {
markBusyGRF(
((G4_Greg *)pr)->getRegNum(),
PhyRegUsage::offsetAllocUnit(lr->getPhyRegOff(), dcl->getElemType()),
dcl->getWordSize(), lr->getNumRegNeeded(), dcl->isPreDefinedVar());
}
} else if (pr->isFlag()) {
auto flagWordOffset = lr->getPhyReg()->asAreg()->getFlagNum() * 2;
markBusyFlag(
0,
PhyRegUsage::offsetAllocUnit(flagWordOffset + lr->getPhyRegOff(),
dcl->getElemType()),
PhyRegUsage::numAllocUnit(dcl->getNumElems(), dcl->getElemType()),
dcl->getNumRows());
} else if (pr->isA0()) {
markBusyAddress(
0, PhyRegUsage::offsetAllocUnit(lr->getPhyRegOff(), dcl->getElemType()),
PhyRegUsage::numAllocUnit(dcl->getNumElems(), dcl->getElemType()),
dcl->getNumRows());
}
else if (pr->isS0()) {
markBusyScalar(
0, PhyRegUsage::offsetAllocUnit(lr->getPhyRegOff(), dcl->getElemType()),
PhyRegUsage::numAllocUnit(dcl->getNumElems(), dcl->getElemType()),
dcl->getNumRows());
}
else {
vISA_ASSERT(false, ERROR_GRAPHCOLOR); // un-handled reg type
}
}
bool GraphColor::assignColors(ColorHeuristic colorHeuristicGRF,
bool doBankConflict, bool highInternalConflict,
bool doBundleConflict) {
RA_TRACE(std::cout << "\t--"
<< (colorHeuristicGRF == ROUND_ROBIN ? "round-robin"
: "first-fit")
<< (doBankConflict ? " BCR" : "") << " graph coloring\n");
unsigned bank1_end = 0;
unsigned bank2_end = totalGRFRegCount - 1;
unsigned bank1_start = 0;
unsigned bank2_start = totalGRFRegCount - 1;
unsigned totalGRFNum = kernel.getNumRegTotal();
bool oneGRFBankDivision = gra.kernel.fg.builder->oneGRFBankDivision();
bool allocFromBanks =
liveAnalysis.livenessClass(G4_GRF) && builder.lowHighBundle() &&
!builder.getOptions()->getuInt32Option(vISA_ReservedGRFNum) &&
doBankConflict &&
((oneGRFBankDivision && gra.kernel.getSimdSize() >= g4::SIMD16) ||
(!oneGRFBankDivision && highInternalConflict));
if (allocFromBanks && (colorHeuristicGRF == ROUND_ROBIN)) {
bank1_end = (unsigned)((totalGRFRegCount - 1) *
(((float)evenTotalDegree / evenTotalRegNum) /
(((float)evenTotalDegree / evenTotalRegNum) +
((float)oddTotalDegree / oddTotalRegNum))));
if (bank1_end < evenMaxRegNum ||
totalGRFRegCount - bank1_end < oddMaxRegNum ||
bank1_end == totalGRFRegCount - 1 || bank1_end == 0) {
// FIXME: How can we early return without assigning???
return false;
}
bank2_end = bank1_end + 1;
}
G4_RegFileKind rFile = G4_GRF;
if (liveAnalysis.livenessClass(G4_FLAG))
rFile = G4_FLAG;
else if (liveAnalysis.livenessClass(G4_ADDRESS))
rFile = G4_ADDRESS;
else if (liveAnalysis.livenessClass(G4_SCALAR))
rFile = G4_SCALAR;
FreePhyRegs FPR(kernel);
unsigned maxGRFCanBeUsed = totalGRFRegCount;
// FIXME: the bank configs should be computed in PhyRegAllocationState instead
// of pased in, but the strange early return from above prevents this..
PhyRegAllocationState parms(gra, lrs, rFile, maxGRFCanBeUsed, bank1_start,
bank1_end, bank2_start, bank2_end, doBankConflict,
doBundleConflict);
bool noIndirForceSpills = builder.getOption(vISA_NoIndirectForceSpills);
// Returns true when valid assignment is found or when lr is added to spilled
// set. Adding to spill set happens only if heuristic is not round_robin (FF
// may not spill). Parameter returnFalseOnFail is set when the function is
// required to return false on assignment failure. When parameter spillAllowed
// is set to true, this function adds lr to spilled set. If spillAllowed is
// false, the lr is not added to spill set. This logic is useful to try
// re-allocation of a child/parent dcl when split is enabled.
// ignoreChildrenIntf is set to true when all children are assigned to
// consecutive ranges and we want to get fully coalesceable assignment for
// parent. In such circumstance, we don't want to account for interference
// between parent/child since doing so cannot result in a coalesceable
// assignment.
auto assignColor = [&](LiveRange *lr) {
auto lrVar = lr->getVar();
//
// assign register to live ranges
//
if (lr->getPhyReg() == NULL && !lrVar->isSpilled() &&
!lr->getIsPartialDcl()) // no assigned register yet and not spilled
{
unsigned lr_id = lrVar->getId();
//
// compute what registers are already assigned
//
PhyRegUsage regUsage(parms, FPR);
const std::vector<unsigned> &intfs = intf.getSparseIntfForVar(lr_id);
auto weakEdgeSet =
intf.getCompatibleSparseIntf(lrVar->getDeclare()->getRootDeclare());
for (auto it : intfs) {
LiveRange *lrTemp = lrs[it];
if (lrTemp->getPhyReg() != nullptr || lrTemp->getIsPartialDcl()) {
if (lrTemp->getIsSplittedDcl()) {
// Only interfere with children declares
continue;
}
regUsage.updateRegUsage(lrTemp);
}
}
if (weakEdgeSet) {
regUsage.runOverlapTest(true);
for (auto weakDcl : *weakEdgeSet) {
auto regVar = weakDcl->getRootDeclare()->getRegVar();
unsigned pvar = 0, numRegs = 0;
if (regVar->isPhyRegAssigned()) {
// This branch will be taken for dcls assigned
// regs by LRA.
pvar = regVar->getPhyReg()->asGreg()->getRegNum();
numRegs = weakDcl->getNumRows();
} else {
// For dcls not assigned regs by LRA, lookup temp
// registers assigned to LiveRange instances.
auto id = regVar->getId();
auto lr = lrs[id];
auto phyReg = lr->getPhyReg();
if (phyReg) {
pvar = phyReg->asGreg()->getRegNum();
numRegs = weakDcl->getNumRows();
}
}
// For now it is assumed only 8-byte types will appear
// here. If other sized types will also appear then
// augmentation mask also needs to be sent in
// weak edge data structure below.
for (unsigned r = pvar; r < (pvar + numRegs); r++) {
auto use = regUsage.getWeakEdgeUse(r);
if (use == 0 || use == (r - pvar + 1)) {
regUsage.setWeakEdgeUse(r, r - pvar + 1);
} else {
// Indiates two neighbors use a physical
// register with different overlap.
regUsage.setWeakEdgeUse(r, 0xff);
}
}
}
}
ColorHeuristic heuristic = colorHeuristicGRF;
bool failed_alloc = false;
G4_Declare *dcl = lrVar->getDeclare();
if (!(noIndirForceSpills && liveAnalysis.isAddressSensitive(lr_id)) &&
forceSpill &&
(dcl->getRegFile() == G4_GRF || dcl->getRegFile() == G4_FLAG) &&
lr->getRefCount() != 0 && lr->getSpillCost() != MAXSPILLCOST) {
failed_alloc = true;
}
if ((dcl->getNumRows() > totalGRFNum) ||
(dcl->isForceSpilled() && (lr->getSpillCost() != MAXSPILLCOST))) {
// we sure as hell won't get an assignment
failed_alloc = true;
}
if (kernel.getOption(vISA_GCRRInFF)) {
if (lr->getRegKind() != G4_GRF) {
// None GRF assignment, keep single FF or RR algorithm
if (heuristic == FIRST_FIT) {
parms.setStartGRF(0);
}
} else if (heuristic == FIRST_FIT && !lr->getIsUnconstrained()) {
// GRF assignment, start GRF is always 0 if first fit algorithm is
// used and the variable is constrainted
parms.setStartGRF(0);
}
}
if (!failed_alloc) {
// When evenAlignNeeded is true, it is binding for correctness
bool evenAlignNeeded = gra.isEvenAligned(lrVar->getDeclare());
bool quadAlignNeeded = gra.isQuadAligned(lrVar->getDeclare());
BankAlign align = BankAlign::Either;
if (quadAlignNeeded)
align = BankAlign::QuadGRF;
else if (evenAlignNeeded)
align = BankAlign::Even;
if (allocFromBanks) {
vISA_ASSERT(align != BankAlign::QuadGRF, "unexpected value");
if (!isHybrid && oneGRFBankDivision &&
(!evenAlignNeeded ||
builder.getPlatformGeneration() == PlatformGen::GEN9)) {
gra.getBankAlignment(lr, align);
}
failed_alloc |= !regUsage.assignGRFRegsFromBanks(
lr, align, lr->getForbidden(), heuristic, oneGRFBankDivision);
} else {
failed_alloc |= !regUsage.assignRegs(
highInternalConflict, lr, lr->getForbidden(), align,
gra.getSubRegAlign(lrVar->getDeclare()), heuristic,
lr->getSpillCost());
}
}
//
// assign unused color
//
if (failed_alloc) {
//
// for GRF register assignment, if we are performing round-robin (1st
// pass) then abort on spill
//
if ((heuristic == ROUND_ROBIN ||
(doBankConflict && !kernel.getOption(vISA_forceBCR))) &&
(lr->getRegKind() == G4_GRF || lr->getRegKind() == G4_FLAG)) {
return false;
} else if (kernel.fg.isPseudoDcl(dcl)) {
// these pseudo dcls are not (and cannot be) spilled, but instead
// save/restore code will be inserted in stack call prolog/epilog
} else {
// for first-fit register assignment track spilled live ranges
spilledLRs.push_back(lr);
lr->setSpilled(true);
}
}
}
VISA_DEBUG_VERBOSE({
lr->dump();
std::cout << "\n";
});
return true;
};
// colorOrder is in reverse order (unconstrained at front)
for (auto iter = colorOrder.rbegin(), iterEnd = colorOrder.rend();
iter != iterEnd; ++iter) {
auto lr = (*iter);
// in case child/parent was already spilled earlier, don't recolor
if (lr->isSpilled())
continue;
bool ret = assignColor(lr);
// early exit
if (!ret)
return false;
}
if (failSafeIter) {
// As per spec, EOT has to be allocated to r112+.
// When fail safe iteration is run, upper GRFs are
// reserved. It's possible that # of reserved
// GRFs are too many and r112+ allocation restriction
// on EOT cannot be fulfilled (eg, r116-r127 are reserved
// EOT src operand size is 8 GRFs). This causes EOT var
// to spill and then the spill range faces the same
// restriction. The fix here is to check whether
// reserved GRF restriction can be eased for EOT.
auto hasSpilledNeighbor = [&](unsigned int id) {
for (const auto *spillLR : spilledLRs) {
if (id != spillLR->getVar()->getId() &&
getIntf()->interfereBetween(id, spillLR->getVar()->getId()))
return true;
}
return false;
};
if (gra.useHybridRAwithSpill) {
// This local analysis is skipped in favor of
// compile time in global RA loop, so run it here
// when needed.
gra.markGraphBlockLocalVars();
}
for (auto lrIt = spilledLRs.begin(); lrIt != spilledLRs.end(); ++lrIt) {
auto lr = (*lrIt);
bool needsEOTGRF = lr->getEOTSrc() && builder.hasEOTGRFBinding();
if (needsEOTGRF && gra.isBlockLocal(lr->getDcl()) &&
(totalGRFRegCount - reserveSpillGRFCount + lr->getNumRegNeeded()) <=
kernel.getNumRegTotal() &&
!hasSpilledNeighbor(lr->getVar()->getId())) {
// Following conditions true:
// 1. EOT range spilled that needs r112-r127 assignment,
// 2. Variable is local to a BB,
// 3. Reserved GRF start + # EOT GRFs fits within total GRFs,
// 4. Has no spilled neighbor
//
// This makes it safe to directly assign a reserved GRF to this
// variable than spill it.
lr->setPhyReg(builder.phyregpool.getGreg(kernel.getNumRegTotal() -
lr->getNumRegNeeded()),
0);
spilledLRs.erase(lrIt);
break;
}
}
}
// record RA type
if (liveAnalysis.livenessClass(G4_GRF)) {
if (colorHeuristicGRF == ROUND_ROBIN) {
kernel.setRAType(doBankConflict ? RA_Type::GRAPH_COLORING_RR_BC_RA
: RA_Type::GRAPH_COLORING_RR_RA);
} else {
kernel.setRAType(doBankConflict ? RA_Type::GRAPH_COLORING_FF_BC_RA
: RA_Type::GRAPH_COLORING_FF_RA);
}
}
#ifdef _DEBUG
// Verify that spilledLRs has no duplicate
for (auto item : spilledLRs) {
unsigned count = 0;
for (auto checkItem : spilledLRs) {
if (checkItem == item) {
vISA_ASSERT(count == 0, "Duplicate entry found in spilledLRs");
count++;
}
}
}
// Verify that none of spilledLRs have an allocation
for (auto lr : spilledLRs) {
vISA_ASSERT(lr->getPhyReg() == nullptr,
"Spilled LR contains valid allocation");
}
// Verify that all spilled LRs are synced
for (auto lr : spilledLRs) {
vISA_ASSERT(lr->isSpilled(),
"LR not marked as spilled, but inserted in spilledLRs list");
}
// Verify if all LRs have either an allocation or are spilled
for (auto lr : colorOrder) {
if (!kernel.fg.isPseudoDcl(lr->getDcl())) {
vISA_ASSERT(lr->isSpilled() || lr->getPhyReg() ||
lr->getDcl()->isSpilled(),
"Range without allocation and not spilled");
}
}
#endif
return true;
}
template <class REGION_TYPE>
unsigned GlobalRA::getRegionDisp(REGION_TYPE *region, const IR_Builder &irb) {
unsigned rowOffset = irb.numEltPerGRF<Type_UB>() * region->getRegOff();
unsigned columnOffset = region->getSubRegOff() * region->getElemSize();
return rowOffset + columnOffset;
}
void GlobalRA::addEUFusionCallWAInst(G4_INST *inst) {
if (EUFusionCallWANeeded())
EUFusionCallWAInsts.insert(inst);
}
void GlobalRA::addEUFusionNoMaskWAInst(G4_BB *BB, G4_INST *Inst) {
if (EUFusionNoMaskWANeeded() && (BB->getBBType() & G4_BB_NM_WA_TYPE) != 0) {
EUFusionNoMaskWAInsts.insert(Inst);
Inst->setNeedPostRA(true);
}
}
void GlobalRA::removeEUFusionNoMaskWAInst(G4_INST *Inst) {
if (EUFusionNoMaskWANeeded()) {
if (EUFusionNoMaskWAInsts.erase(Inst) > 0) {
Inst->setNeedPostRA(false);
}
}
}
unsigned GlobalRA::getRegionByteSize(G4_DstRegRegion *region,
unsigned execSize) {
unsigned size =
region->getHorzStride() * region->getElemSize() * (execSize - 1) +
region->getElemSize();
return size;
}
#define OWORD_BYTE_SIZE 16
template <class REGION_TYPE>
bool GlobalRA::isUnalignedRegion(REGION_TYPE *region, unsigned execSize) {
unsigned regionDisp = getRegionDisp(region, builder);
unsigned regionByteSize = getRegionByteSize(region, execSize);
if (regionDisp % kernel.numEltPerGRF<Type_UB>() == 0 &&
regionByteSize % kernel.numEltPerGRF<Type_UB>() == 0) {
return regionByteSize / kernel.numEltPerGRF<Type_UB>() != 1 &&
regionByteSize / kernel.numEltPerGRF<Type_UB>() != 2 &&
regionByteSize / kernel.numEltPerGRF<Type_UB>() != 4;
}
return true;
}
bool GlobalRA::shouldPreloadDst(G4_INST *instContext, G4_BB *curBB) {
// Check for partial and unaligned regions and add pre-load code, if
// necessary.
auto spilledRangeRegion = instContext->getDst();
uint8_t execSize = instContext->getExecSize();
if (isPartialRegion(spilledRangeRegion, execSize) ||
isUnalignedRegion(spilledRangeRegion, execSize) ||
instContext->isPartialWriteForSpill(!curBB->isAllLaneActive(),
useLscForNonStackCallSpillFill)) {
return true;
}
// No pre-load for whole and aligned region writes
else {
return false;
}
}
bool GlobalRA::livenessCandidate(const G4_Declare *decl) const {
if (decl->getAliasDeclare()) {
return false;
}
if ((G4_GRF & decl->getRegFile())) {
if ((decl->getRegFile() & G4_INPUT) &&
decl->getRegVar()->isPhyRegAssigned() && !decl->getRegVar()->isGreg()) {
return false;
}
if (decl->getByteSize() == 0) {
// regrettably, this can happen for arg/retval pre-defined variable
return false;
}
return true;
} else {
return false;
}
}
void GlobalRA::determineSpillRegSize(unsigned &spillRegSize,
unsigned &indrSpillRegSize) {
// Iterate over all BBs
for (auto curBB : kernel.fg) {
// Iterate over all insts
for (INST_LIST_ITER inst_it = curBB->begin(), iend = curBB->end();
inst_it != iend; ++inst_it) {
unsigned currentSpillRegSize = 0;
unsigned currentIndrSpillRegSize = 0;
G4_INST *curInst = (*inst_it);
if (curInst->isPseudoKill() || curInst->isLifeTimeEnd() ||
curInst->opcode() == G4_pseudo_fcall ||
curInst->opcode() == G4_pseudo_fret) {
continue;
}
if (curInst->isSend()) {
G4_SendDesc *msgDesc = curInst->getMsgDesc();
unsigned dstSpillRegSize = 0;
dstSpillRegSize = msgDesc->getDstLenRegs();
unsigned src0FillRegSize = 0;
src0FillRegSize = msgDesc->getSrc0LenRegs();
unsigned src1FillRegSize = 0;
if (curInst->isSplitSend()) {
src1FillRegSize = msgDesc->getSrc1LenRegs();
}
if (!kernel.fg.builder->useSends()) {
dstSpillRegSize++;
}
currentSpillRegSize =
dstSpillRegSize + src0FillRegSize + src1FillRegSize;
} else if (curInst->isDpas()) {
unsigned dstSpillRegSize = 0;
G4_DstRegRegion *dst = curInst->getDst();
if (dst && dst->getBase()->isRegVar()) {
dstSpillRegSize =
dst->getBase()->asRegVar()->getDeclare()->getNumRows();
}
unsigned srcFillRegSize = 0;
for (int i = 0, srcNum = curInst->getNumSrc(); i < srcNum; i++) {
G4_Operand *src = curInst->getSrc(i);
if (src && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
if (src->asSrcRegRegion()
->getBase()
->asRegVar()
->getDeclare()
->getRegFile() == G4_GRF) {
unsigned srcSize =
src->getBase()->asRegVar()->getDeclare()->getNumRows();
// FIXME, currently we only use the max src size.
// To save the spill registers, it's better the space can be
// determined by checking if the variable is really spilled or
// not.
srcFillRegSize += srcSize;
}
}
}
currentSpillRegSize = srcFillRegSize + dstSpillRegSize;
} else {
ORG_REGVAR_VECTOR indrVars;
unsigned dstSpillRegSize = 0;
unsigned indrDstSpillRegSize = 0;
if (G4_Inst_Table[curInst->opcode()].n_dst == 1) {
G4_DstRegRegion *dst = curInst->getDst();
if (dst && dst->getBase()->isRegVar()) {
if (dst->getBase()->asRegVar()->getDeclare()->getRegFile() ==
G4_GRF) {
if (dst->isCrossGRFDst(builder)) {
dstSpillRegSize = 2;
} else {
dstSpillRegSize = 1;
}
if (shouldPreloadDst(curInst, curBB)) {
dstSpillRegSize *= 3;
} else {
dstSpillRegSize *= 2;
}
if (!kernel.fg.builder->useSends()) {
dstSpillRegSize++;
}
} else if (dst->getRegAccess() == IndirGRF) {
auto pointsToSet =
pointsToAnalysis.getAllInPointsTo(dst->getBase()->asRegVar());
if (pointsToSet != nullptr) {
for (const auto& pt : *pointsToSet) {
if (pt.var->isRegAllocPartaker() ||
((useFastRA || useHybridRAwithSpill) &&
livenessCandidate(pt.var->getDeclare()))) {
indrVars.push_back(pt.var);
indrDstSpillRegSize += pt.var->getDeclare()->getNumRows();
}
}
}
}
}
}
unsigned srcFillRegSize = 0;
unsigned indirSrcFillRegSize = 0;
// Scan srcs
for (int i = 0, srcNum = curInst->getNumSrc(); i < srcNum; i++) {
G4_Operand *src = curInst->getSrc(i);
if (src && src->isSrcRegRegion() &&
src->asSrcRegRegion()->getBase()->isRegVar()) {
if (src->asSrcRegRegion()
->getBase()
->asRegVar()
->getDeclare()
->getRegFile() == G4_GRF) {
if (src->asSrcRegRegion()->crossGRF(builder)) {
srcFillRegSize += 2;
} else {
srcFillRegSize += 1;
}
} else if (src->asSrcRegRegion()->getRegAccess() == IndirGRF) {
auto pointsToSet = pointsToAnalysis.getAllInPointsTo(
src->asSrcRegRegion()->getBase()->asRegVar());
if (pointsToSet != nullptr) {
for (const auto& pt : *pointsToSet) {
if (pt.var->isRegAllocPartaker() ||
((useFastRA || useHybridRAwithSpill) &&
livenessCandidate(pt.var->getDeclare()))) {
if (std::find(indrVars.begin(), indrVars.end(), pt.var) ==
indrVars.end()) {
indrVars.push_back(pt.var);
indirSrcFillRegSize += pt.var->getDeclare()->getNumRows();
}
}
}
}
}
}
}
if (builder.avoidDstSrcOverlap()) {
currentSpillRegSize = srcFillRegSize + dstSpillRegSize;
} else {
currentSpillRegSize = srcFillRegSize > dstSpillRegSize
? srcFillRegSize
: dstSpillRegSize;
}
currentIndrSpillRegSize = indrDstSpillRegSize + indirSrcFillRegSize;
}
spillRegSize = std::max(spillRegSize, currentSpillRegSize);
indrSpillRegSize = std::max(indrSpillRegSize, currentIndrSpillRegSize);
}
}
}
void GraphColor::gatherScatterForbiddenWA() {
if (!liveAnalysis.livenessClass(G4_GRF))
return;
// VISA spec supports gather.1 and scatter.1 instructions.
// But they're not natively supported across platforms. When
// lowering gather.1 (scatter.1) on unsupported platforms, we
// use rsp len (msg len) = 2 while actual dst (payload) may be
// smaller in size. This could cause a problem if dst (payload)
// gets assigned to r127 as rsp len (msg len) = 2 could make
// it access beyond last GRF. For eg,
//
// VISA:
//.decl Rsp v_type=G type=q num_elts=1
//.decl Addr v_type=G type=q num_elts=1
// svm_gather.8.1 (M1, 1) Addr Rsp
//
// asm:
// send.dc1 (1|M0) r127 r4 null:0 exMSD MSD // wr:2+0, rd:2; a64
// qword gathering read
//
// This asm instruction is illegal as Rsp (size = 8 bytes) was assigned r127
// but send response length = 2.
//
// We fix such cases by looking them up and marking upper GRFs
// as forbidden for allocation.
for (auto bb : kernel.fg.getBBList()) {
for (auto inst : *bb) {
if (!inst->isSend() || inst->getExecSize().value >= 8)
continue;
// dstLen is actual # of GRFs written based on rb, lb
// src0Len is actual # of GRFs read based on rb, lb
// src1Len is actual # of GRFs read based on rb, lb
unsigned int dstLen = 0, src0Len = 0, src1Len = 0;
auto sendDst = inst->getDst();
auto sendHdr = inst->getSrc(0);
auto sendPayload = inst->getSrc(1);
auto getLenInGRF = [&](G4_Operand *opnd) {
unsigned int sz = 0;
if (opnd && !opnd->isNullReg() && opnd->getTopDcl())
sz = (opnd->getRightBound() - opnd->getLeftBound() +
kernel.getGRFSize() - 1) /
kernel.getGRFSize();
return sz;
};
dstLen = getLenInGRF(sendDst);
src0Len = getLenInGRF(sendHdr);
src1Len = getLenInGRF(sendPayload);
auto sendRspLen = inst->asSendInst()->getMsgDesc()->getDstLenRegs();
auto headerLen = inst->asSendInst()->getMsgDesc()->getSrc0LenRegs();
auto payloadLen = inst->asSendInst()->getMsgDesc()->getSrc1LenRegs();
// For gather.[1|2|4] (scatter.[1|2|4]) difference in actual dst
// (src0/src1) size and rspLen (msg len/ext msg len) should not exceed 1
// GRF.
auto markForbiddenForDcl = [&](unsigned int opndLen, G4_Declare *dcl,
unsigned int lenInSend) {
if (opndLen > 0 && dcl && dcl->getRegVar() &&
dcl->getRegVar()->isRegAllocPartaker()) {
if (lenInSend == (opndLen + 1)) {
lrs[dcl->getRegVar()->getId()]->setForbidden(
forbiddenKind::FBD_LASTGRF);
} else if (lenInSend > opndLen) {
vISA_ASSERT(false,
"mismatch between len in send and that of operand");
}
}
};
markForbiddenForDcl(dstLen, sendDst->getTopDcl(), sendRspLen);
markForbiddenForDcl(src0Len, sendHdr->getTopDcl(), headerLen);
markForbiddenForDcl(src1Len, sendPayload->getTopDcl(), payloadLen);
}
}
}
bool GraphColor::regAlloc(bool doBankConflictReduction,
bool highInternalConflict, const RPE *rpe) {
bool useSplitLLRHeuristic = false;
// FIXME: This whole bundle thing is a mess, the flag is an int but we
// treat it as a bool when passing to assignColors, and it's not clear if it
// works for non-DPAS instructions.
unsigned doBundleConflictReduction = kernel.getuInt32Option(vISA_enableBundleCR);
RA_TRACE(std::cout << "\t--# variables: " << liveAnalysis.getNumSelectedVar()
<< "\n");
// Copy over alignment for vars inserted by RA
gra.copyMissingAlignment();
//
// create an array of live ranges.
//
if (!IncrementalRA::isEnabled(kernel) || lrs.size() == 0) {
// Create vector of live ranges if we're not using
// incremental RA or if this is 1st iteration.
// With incremental RA, live-ranges are created right when
// new temp var is created in RA.
createLiveRanges();
}
//
// set the pre-assigned registers
//
for (unsigned i = 0; i < numVar; i++) {
if (lrs[i]->getVar()->getPhyReg()) {
lrs[i]->setPhyReg(lrs[i]->getVar()->getPhyReg(),
lrs[i]->getVar()->getPhyRegOff());
}
G4_Declare *dcl = lrs[i]->getDcl();
if (!useSplitLLRHeuristic) {
auto dclLR = gra.getLocalLR(dcl);
if (dclLR != nullptr && dclLR->getSplit()) {
useSplitLLRHeuristic = true;
}
}
}
//
// compute interference matrix
//
intf.init();
intf.computeInterference();
if (reserveSpillGRFCount) {
preAssignSpillHeader();
}
builder.getFreqInfoManager().initForRegAlloc(&liveAnalysis);
// If option is true, try to get extra interference info from file
if (liveAnalysis.livenessClass(G4_GRF) &&
kernel.getOption(vISA_AddExtraIntfInfo)) {
getExtraInterferenceInfo();
}
TIME_SCOPE(COLORING);
//
// compute degree and spill costs for each live range
//
if (liveAnalysis.livenessClass(G4_GRF)) {
if (gra.use4GRFAlign)
computeDegreeForGRF<true>();
else
computeDegreeForGRF<false>();
} else {
computeDegreeForARF();
}
computeSpillCosts(useSplitLLRHeuristic, rpe);
builder.getFreqInfoManager().computeFreqSpillCosts(gra, useSplitLLRHeuristic, rpe);
if (kernel.getOption(vISA_DumpRAIntfGraph))
intf.dumpInterference();
//
// determine coloring order
//
determineColorOrdering();
//
// Set up the sub-reg alignment from declare information
// FIXME: Why is this called after degrees are computed? Wouldn't the
// alignment affect degree computation?
//
for (unsigned i = 0; i < numVar; i++) {
G4_Declare *dcl = lrs[i]->getDcl();
if (gra.getSubRegAlign(dcl) == Any && !dcl->getIsPartialDcl()) {
//
// multi-row, subreg alignment = 16 words
//
if (dcl->getNumRows() > 1) {
gra.setSubRegAlign(lrs[i]->getVar()->getDeclare(),
kernel.getGRFAlign());
}
//
// single-row
//
else if (gra.getSubRegAlign(lrs[i]->getVar()->getDeclare()) == Any) {
//
// set up Odd word or Even word sub reg alignment
//
unsigned nbytes = dcl->getNumElems() * TypeSize(dcl->getElemType());
unsigned nwords = nbytes / G4_WSIZE + nbytes % G4_WSIZE;
if (nwords >= 2 && lrs[i]->getRegKind() == G4_GRF) {
gra.setSubRegAlign(lrs[i]->getVar()->getDeclare(), Even_Word);
}
}
}
}
gatherScatterForbiddenWA();
//
// assign registers for GRFs, GRFs are first attempted to be assigned using
// round-robin and if it fails then we retry using a first-fit heuristic.
//
if (liveAnalysis.livenessClass(G4_GRF)) {
bool hasStackCall =
kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc();
bool willSpill =
((gra.useFastRA || gra.useHybridRAwithSpill) &&
(!hasStackCall ||
builder.getOption(vISA_PartitionWithFastHybridRA))) ||
(kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
rpe->getMaxRP() >= kernel.getNumRegTotal() + 24);
if (willSpill) {
// go straight to first_fit to save compile time since we are definitely
// spilling we do this for 3D only since with indirect/subroutine the RP
// pressure can be very unreliable
// FIXME: due to factors like local split and scalar variables that are
// not accurately modeled in RP estimate, RA may succeed even when RP is >
// total #GRF. We should investigate these cases and fix RPE
assignColors(FIRST_FIT);
// assert(requireSpillCode() && "inaccurate GRF pressure estimate");
return !requireSpillCode();
}
if (kernel.getOption(vISA_RoundRobin) && !hasStackCall) {
if (assignColors(ROUND_ROBIN, doBankConflictReduction,
highInternalConflict,
doBundleConflictReduction) == false) {
resetTemporaryRegisterAssignments();
bool success = assignColors(FIRST_FIT, doBankConflictReduction,
highInternalConflict, doBundleConflictReduction);
if (!success && doBankConflictReduction && isHybrid) {
return false;
}
if (!kernel.getOption(vISA_forceBCR)) {
if (!success && doBankConflictReduction) {
resetTemporaryRegisterAssignments();
assignColors(FIRST_FIT);
}
}
}
} else {
bool success = assignColors(FIRST_FIT, true, highInternalConflict,
doBundleConflictReduction);
if (!success) {
resetTemporaryRegisterAssignments();
assignColors(FIRST_FIT);
}
}
} else if (liveAnalysis.livenessClass(G4_FLAG)) {
if (kernel.getOption(vISA_RoundRobin)) {
if (assignColors(ROUND_ROBIN) == false) {
resetTemporaryRegisterAssignments();
assignColors(FIRST_FIT);
}
} else {
assignColors(FIRST_FIT);
}
} else {
// assign registers for ARFs using a first-fit heuristic
assignColors(FIRST_FIT, false, false);
}
return (requireSpillCode() == false);
}
void GraphColor::confirmRegisterAssignments() {
for (unsigned i = 0; i < numVar; i++) {
if (lrs[i]->getPhyReg()) {
if (lrs[i]->getVar()->getPhyReg()) {
vISA_ASSERT((lrs[i]->getVar()->getPhyReg() == lrs[i]->getPhyReg()),
ERROR_GRAPHCOLOR);
} else {
lrs[i]->getVar()->setPhyReg(lrs[i]->getPhyReg(),
lrs[i]->getPhyRegOff());
}
}
}
}
void GraphColor::resetTemporaryRegisterAssignments() {
for (unsigned i = 0; i < numVar; i++) {
if (lrs[i]->getVar()->getPhyReg() == NULL) {
lrs[i]->resetPhyReg();
lrs[i]->setSpilled(false);
}
}
spilledLRs.clear();
}
void GraphColor::cleanupRedundantARFFillCode() {
for (G4_BB *bb : builder.kernel.fg) {
clearSpillAddrLocSignature();
for (std::list<G4_INST *>::iterator i = bb->begin(); i != bb->end();) {
G4_INST *inst = (*i);
//
// process writes to spill storage (GRF) of addr regs
//
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getBase() && dst->getBase()->isRegVar() &&
(kernel.fg.isPseudoA0Dcl(dst->getBase()->asRegVar()->getDeclare()) ||
inst->isPseudoKill())) {
i++;
continue;
}
if (dst != NULL && dst->getRegAccess() == Direct) {
if (dst->getBase()->isRegVar() &&
dst->getBase()->asRegVar()->isRegVarAddrSpillLoc()) {
pruneActiveSpillAddrLocs(dst, inst->getExecSize(),
inst->getExecType());
}
//
// process writes to (allocated) addr regs
//
else if (dst->getBase()->isRegAllocPartaker()) {
G4_RegVar *addrReg = dst->getBase()->asRegVar();
if (gra.isAddrFlagSpillDcl(addrReg->getDeclare())) {
G4_SrcRegRegion *srcRgn = inst->getSrc(0)->asSrcRegRegion();
if (redundantAddrFill(dst, srcRgn, inst->getExecSize())) {
std::list<G4_INST *>::iterator j = i++;
bb->erase(j);
continue;
} else {
updateActiveSpillAddrLocs(dst, srcRgn, inst->getExecSize());
}
} else {
pruneActiveSpillAddrLocs(dst, inst->getExecSize(),
inst->getExecType());
}
}
}
i++;
}
}
}
void GraphColor::pruneActiveSpillAddrLocs(G4_DstRegRegion *dstRegion,
unsigned exec_size,
G4_Type exec_type) {
if (dstRegion->getBase()->asRegVar()->isRegVarAddrSpillLoc()) {
vISA_ASSERT(((exec_type == Type_UW || exec_type == Type_W) &&
exec_size <= builder.getNumAddrRegisters()) ||
(exec_size == 1),
"Unexpected ADDR spill loc update format!");
vISA_ASSERT(dstRegion->getRegAccess() == Direct,
"Unexpected ADDR spill loc");
G4_RegVarAddrSpillLoc *spillLocReg =
static_cast<G4_RegVarAddrSpillLoc *>(dstRegion->getBase());
unsigned startId = spillLocReg->getLocId() + dstRegion->getSubRegOff();
unsigned endId = startId + exec_size * dstRegion->getHorzStride();
for (unsigned i = 0, horzStride = dstRegion->getHorzStride();
i < builder.getNumAddrRegisters(); i += horzStride) {
if (spAddrRegSig[i] >= startId && spAddrRegSig[i] < endId) {
spAddrRegSig[i] = 0;
}
}
} else if (dstRegion->getBase()->asRegVar()->isPhyRegAssigned()) {
G4_RegVar *addrReg = dstRegion->getBase()->asRegVar();
vISA_ASSERT(addrReg->getPhyReg()->isA0(),
"Unknown error in ADDR reg spill code cleanup!");
unsigned startId = addrReg->getPhyRegOff();
unsigned endId = startId + exec_size * dstRegion->getHorzStride();
vISA_ASSERT(endId <= builder.getNumAddrRegisters(),
"Unknown error in ADDR reg spill code cleanup!");
for (unsigned i = startId; i < endId; i += dstRegion->getHorzStride()) {
spAddrRegSig[i] = 0;
}
} else {
vISA_ASSERT(false, "Unknown error in ADDR reg spill code cleanup!");
}
}
void GraphColor::updateActiveSpillAddrLocs(G4_DstRegRegion *tmpDstRegion,
G4_SrcRegRegion *srcRegion,
unsigned exec_size) {
vISA_ASSERT(
gra.isAddrFlagSpillDcl(tmpDstRegion->getBase()->asRegVar()->getDeclare()),
"Unknown error in ADDR reg spill code cleanup!");
G4_RegVar *addrReg = tmpDstRegion->getBase()->asRegVar();
vISA_ASSERT(addrReg->getPhyReg()->isA0(),
"Unknown error in ADDR reg spill code cleanup!");
unsigned startAddrId = addrReg->getPhyRegOff();
unsigned endAddrId = startAddrId + exec_size * tmpDstRegion->getHorzStride();
vISA_ASSERT(endAddrId <= builder.getNumAddrRegisters(),
"Unknown error in ADDR reg spill code cleanup!");
vISA_ASSERT(srcRegion->getBase()->asRegVar()->isRegVarAddrSpillLoc(),
"Unknown error in ADDR reg spill code cleanup!");
G4_RegVarAddrSpillLoc *spillLocReg =
static_cast<G4_RegVarAddrSpillLoc *>(srcRegion->getBase());
unsigned startLocId = spillLocReg->getLocId() + srcRegion->getSubRegOff();
for (unsigned i = startAddrId, j = startLocId; i < endAddrId;
i += tmpDstRegion->getHorzStride(),
j += srcRegion->getRegion()->horzStride) {
spAddrRegSig[i] = j;
}
}
bool GraphColor::redundantAddrFill(G4_DstRegRegion *tmpDstRegion,
G4_SrcRegRegion *srcRegion,
unsigned exec_size) {
bool match = true;
vISA_ASSERT(
gra.isAddrFlagSpillDcl(tmpDstRegion->getBase()->asRegVar()->getDeclare()),
"Unknown error in ADDR reg spill code cleanup!");
G4_RegVar *addrReg = tmpDstRegion->getBase()->asRegVar();
vISA_ASSERT(addrReg->getPhyReg()->isA0(),
"Unknown error in ADDR reg spill code cleanup!");
unsigned startAddrId = addrReg->getPhyRegOff();
unsigned endAddrId = startAddrId + exec_size * tmpDstRegion->getHorzStride();
vISA_ASSERT(endAddrId <= builder.getNumAddrRegisters(),
"Unknown error in ADDR reg spill code cleanup!");
vISA_ASSERT(srcRegion->getBase()->asRegVar()->isRegVarAddrSpillLoc(),
"Unknown error in ADDR reg spill code cleanup!");
G4_RegVarAddrSpillLoc *spillLocReg =
static_cast<G4_RegVarAddrSpillLoc *>(srcRegion->getBase());
unsigned startLocId = spillLocReg->getLocId() + srcRegion->getSubRegOff();
for (unsigned i = startAddrId, j = startLocId; i < endAddrId;
i += tmpDstRegion->getHorzStride(),
j += srcRegion->getRegion()->horzStride) {
if (spAddrRegSig[i] != j) {
match = false;
break;
}
}
return match;
}
unsigned GlobalRA::sendBlockSizeCode(unsigned owordSize) {
unsigned code;
switch (owordSize) {
case 1:
code = 0;
break;
case 2:
code = 2;
break;
case 4:
code = 3;
break;
case 8:
code = 4;
break;
case 16:
code = 5;
break;
default:
vISA_ASSERT_UNREACHABLE(ERROR_REGALLOC);
code = 0;
}
return code;
}
#define STATELESS_SURFACE_INDEX 0xFF
#define HEADER_PRESENT 0x80000
#define SEND_OWORD_READ_TYPE 0
#define SEND_OWORD_WRITE_TYPE 8
#define SEND_MSG_TYPE_BIT_OFFSET 14
#define SEND_RSP_LENGTH_BIT_OFFSET 20
#define SEND_MSG_LENGTH_BIT_OFFSET 25
#define SEND_DESC_DATA_SIZE_BIT_OFFSET 8
G4_Imm *GlobalRA::createMsgDesc(unsigned owordSize, bool writeType,
bool isSplitSend) {
// If isSplitSend = true then messageLength = 1 and extMesLength =
// (owordSize/2) GRFs
unsigned message = STATELESS_SURFACE_INDEX;
message |= HEADER_PRESENT;
if (writeType) {
unsigned messageType = SEND_OWORD_WRITE_TYPE;
message |= messageType << SEND_MSG_TYPE_BIT_OFFSET;
unsigned messageLength = 1;
if (!isSplitSend) {
messageLength += owordToGRFSize(
ROUND(owordSize, kernel.numEltPerGRF<Type_UB>() / OWORD_BYTE_SIZE),
builder);
}
message |= messageLength << SEND_MSG_LENGTH_BIT_OFFSET;
} else {
unsigned messageType = SEND_OWORD_READ_TYPE;
message |= messageType << SEND_MSG_TYPE_BIT_OFFSET;
unsigned responseLength = owordToGRFSize(
ROUND(owordSize, kernel.numEltPerGRF<Type_UB>() / OWORD_BYTE_SIZE),
builder);
message |= responseLength << SEND_RSP_LENGTH_BIT_OFFSET;
unsigned messageLength = 1;
message |= messageLength << SEND_MSG_LENGTH_BIT_OFFSET;
}
unsigned writeOwordSize = sendBlockSizeCode(owordSize);
message |= writeOwordSize << SEND_DESC_DATA_SIZE_BIT_OFFSET;
return builder.createImm(message, Type_UD);
}
void GlobalRA::stackCallProlog() {
G4_BB *entryBB = builder.kernel.fg.getEntryBB();
// Used for creating inst to initialize address for immediate offset usage.
auto AddrComputeInst = [this](G4_Declare *srcDcl) {
auto addSrc0 = builder.createSrc(srcDcl->getRegVar(), 0, 0,
builder.getRegionScalar(), Type_UD);
auto immSrc1 = builder.createImm(SPILL_FILL_IMMOFF_MAX, Type_UD);
auto addInst = builder.createBinOp(
G4_add, g4::SIMD1,
builder.createDstRegRegion(builder.kernel.fg.scratchRegDcl, 1), addSrc0,
immSrc1, InstOpt_WriteEnable, false);
return addInst;
};
// Initialize address for immediate offset usage for spill/fill messages
// except for frame descriptor save message.
// This is for common cases which uses %be_fp as address.
{
// Turn off immediate offset if frame size is 0 or exceeds threshhold
if ((kernel.fg.frameSizeInOWord == 0) ||
(kernel.fg.frameSizeInOWord * 16 > SPILL_FILL_IMMOFF_MAX * 2))
canUseLscImmediateOffsetSpillFill = false;
if (canUseLscImmediateOffsetSpillFill) {
// copy (%be_fp + 0x10000) to r126.0 for immediate offset usage in
// stackcall spill/fill
// add(1) r126.0 %be_fp 0x10000
auto insertIt = std::find(entryBB->begin(), entryBB->end(),
builder.kernel.getBEFPSetupInst());
vISA_ASSERT(insertIt != entryBB->end(), "Can't find BE_FP setup inst");
entryBB->insertBefore(++insertIt, AddrComputeInst(builder.getBEFP()));
// Each stack function has its own r126.0, so need resume r126.0 after
// function call as the value has been changed in the callee.
// See below example:
// Foo()
// mov r125.3 r125.2
// add r126.0 r125.3 0x10000
// add r125.2 r125.2 frameSizeFoo
// spill [r126.0 offset1-0x10000]
// Bar()
// mov r125.3 r125.2
// add r126.0 r125.3 0x10000
// add r125.2 r125.2 frameSizeBar
// spill [r126.0 offset2-0x10000]
// ...
// add r126.0 r125.3 0x10000
// spill [r126.0 offset3-0x10000]
// After Bar() return, we should re-compute r126.0
for (auto bb : kernel.fg) {
if (bb->isEndWithFCall()) {
G4_BB *succ = bb->Succs.front();
insertIt =
std::find_if(succ->begin(), succ->end(),
[](G4_INST *inst) { return inst->isLabel(); });
vISA_ASSERT(insertIt != succ->end(), "Can't find label");
succ->insertBefore(++insertIt, AddrComputeInst(builder.getBEFP()));
}
}
}
}
// Emit frame descriptor
if (kernel.fg.getIsStackCallFunc()) {
if (canSkipFDE())
return;
auto payload = builder.createHardwiredDeclare(
8, Type_UD, kernel.stackCall.getFPSPGRF(), 0);
payload->setName(builder.getNameString(24, "FrameDescriptorGRF"));
auto payloadSrc =
builder.createSrcRegRegion(payload, builder.getRegionStride1());
const unsigned execSize = 8;
G4_DstRegRegion *postDst = builder.createNullDst(Type_UD);
G4_INST *store = nullptr;
if (builder.supportsLSC()) {
auto headerOpnd = getSpillFillHeader(*kernel.fg.builder, nullptr);
store = builder.createSpill(
postDst, headerOpnd, payloadSrc, G4_ExecSize(execSize), 1, 0,
builder.getBESP(), InstOpt_WriteEnable, false);
} else {
store =
builder.createSpill(postDst, payloadSrc, G4_ExecSize(execSize), 1, 0,
builder.getBESP(), InstOpt_WriteEnable, false);
}
builder.setFDSpillInst(store);
auto iter = std::find_if(entryBB->begin(), entryBB->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
iter = entryBB->insertBefore(iter, store);
if (EUFusionCallWANeeded()) {
auto oldSaveInst = builder.getPartFDSaveInst();
builder.setPartFDSaveInst(store);
entryBB->remove(oldSaveInst);
}
addEUFusionCallWAInst(store);
// Initialize address for immediate offset usage for frame descriptor store
// message. This is a special case as it uses %be_sp as address.
{
if (canUseLscImmediateOffsetSpillFill) {
// copy (%be_sp + 0x10000) to r126.0 for immediate offset usage
// for frame descriptor save instruction
// add(1) r126.0<1>:ud %be_sp<1;0,1>:ud 0x10000:ud
entryBB->insertBefore(iter, AddrComputeInst(builder.getBESP()));
}
}
return;
}
// Make r126 a copy of r0 only up to VISA ABI v2
if (kernel.stackCall.getVersion() >= StackCallABI::StackCallABIVersion::VER_3)
return;
// mov (8) r126.0<1>:ud r0.0<1;1,1>:ud
auto dstRgn = builder.createDstRegRegion(builder.kernel.fg.scratchRegDcl, 1);
auto srcRgn = builder.createSrcRegRegion(builder.getBuiltinR0(),
builder.getRegionStride1());
G4_INST *mov = builder.createMov(G4_ExecSize(kernel.numEltPerGRF<Type_UD>()),
dstRgn, srcRgn, InstOpt_WriteEnable, false);
auto iter = std::find_if(entryBB->begin(), entryBB->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
entryBB->insertBefore(iter, mov);
}
//
// Generate the save code for startReg to startReg+owordSize/2.
//
void GlobalRA::saveRegs(unsigned startReg, unsigned owordSize,
G4_Declare *scratchRegDcl, G4_Declare *framePtr,
unsigned frameOwordOffset, G4_BB *bb,
INST_LIST_ITER insertIt,
std::unordered_set<G4_INST *> &group) {
vISA_ASSERT(builder.getPlatform() >= GENX_SKL,
"stack call only supported on SKL+");
if ((useLscForSpillFill && owordSize == 16) || owordSize == 8 ||
owordSize == 4 || owordSize == 2) {
// add (1) r126.2<1>:ud r125.3<0;1,0>:ud 0x2:ud
// sends (8) null<1>:ud r126.0 r1.0 ...
G4_ExecSize execSize = (owordSize > 2) ? g4::SIMD16 : g4::SIMD8;
unsigned messageLength = GlobalRA::owordToGRFSize(owordSize, builder);
G4_Declare *msgDcl =
builder.createTempVar(messageLength * builder.getGenxDataportIOSize(),
Type_UD, builder.getGRFAlign(), StackCallStr);
msgDcl->getRegVar()->setPhyReg(regPool.getGreg(startReg), 0);
auto sendSrc2 = builder.createSrc(msgDcl->getRegVar(), 0, 0,
builder.getRegionStride1(), Type_UD);
G4_DstRegRegion *dst =
builder.createNullDst((execSize > 8) ? Type_UW : Type_UD);
G4_INST *spillIntrinsic = nullptr;
if (builder.supportsLSC()) {
auto headerOpnd = getSpillFillHeader(*kernel.fg.builder, nullptr);
spillIntrinsic = builder.createSpill(
dst, headerOpnd, sendSrc2, execSize, messageLength,
frameOwordOffset / 2, framePtr, InstOpt_WriteEnable, false);
} else
spillIntrinsic = builder.createSpill(
dst, sendSrc2, execSize, messageLength, frameOwordOffset / 2,
framePtr, InstOpt_WriteEnable, false);
spillIntrinsic->inheritDIFrom(*insertIt);
bb->insertBefore(insertIt, spillIntrinsic);
group.insert(spillIntrinsic);
} else if ((useLscForSpillFill && owordSize > 16)) {
saveRegs(startReg, 16, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group);
saveRegs(startReg + GlobalRA::owordToGRFSize(16, builder), owordSize - 16,
scratchRegDcl, framePtr, frameOwordOffset + 16, bb, insertIt,
group);
} else if (owordSize > 8) {
saveRegs(startReg, 8, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group);
saveRegs(startReg + GlobalRA::owordToGRFSize(8, builder), owordSize - 8,
scratchRegDcl, framePtr, frameOwordOffset + 8, bb, insertIt,
group);
}
//
// Split into chunks of sizes 4 and remaining owords.
//
else if (owordSize > 4) {
saveRegs(startReg, 4, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group);
saveRegs(startReg + GlobalRA::owordToGRFSize(4, builder), owordSize - 4,
scratchRegDcl, framePtr, frameOwordOffset + 4, bb, insertIt,
group);
}
//
// Split into chunks of sizes 2 and remaining owords.
//
else if (owordSize > 2) {
saveRegs(startReg, 2, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group);
saveRegs(startReg + GlobalRA::owordToGRFSize(2, builder), owordSize - 2,
scratchRegDcl, framePtr, frameOwordOffset + 2, bb, insertIt,
group);
} else {
vISA_ASSERT(false, ERROR_REGALLOC);
}
}
//
// Generate the save code for the i/p saveRegs.
//
void GlobalRA::saveActiveRegs(std::vector<bool> &saveRegs, unsigned startReg,
unsigned frameOffset, G4_BB *bb,
INST_LIST_ITER insertIt,
std::unordered_set<G4_INST *> &group) {
G4_Declare *scratchRegDcl = builder.kernel.fg.scratchRegDcl;
G4_Declare *framePtr = builder.kernel.fg.framePtrDcl;
unsigned frameOwordPos = frameOffset;
unsigned startPos = 0;
while (startPos < saveRegs.size()) {
for (; startPos < saveRegs.size() && saveRegs[startPos] == false;
startPos++)
;
if (startPos < saveRegs.size() && saveRegs[startPos]) {
unsigned endPos = startPos + 1;
for (; endPos < saveRegs.size() && saveRegs[endPos] == true; endPos++)
;
unsigned owordSize =
(endPos - startPos) * GlobalRA::GRFSizeToOwords(1, builder);
owordSize = std::max(owordSize, GlobalRA::GRFSizeToOwords(1, builder));
this->saveRegs(startPos + startReg, owordSize, scratchRegDcl, framePtr,
frameOwordPos, bb, insertIt, group);
frameOwordPos += owordSize;
startPos = endPos;
}
}
}
G4_SrcRegRegion *GraphColor::getScratchSurface() const {
if (builder.hasScratchSurface()) {
return builder.createSrcRegRegion(builder.getBuiltinScratchSurface(),
builder.getRegionScalar());
}
return nullptr; // use stateless access
}
//
// Generate the restore code for startReg to startReg+owordSize/2.
//
void GlobalRA::restoreRegs(unsigned startReg, unsigned owordSize,
G4_Declare *scratchRegDcl, G4_Declare *framePtr,
unsigned frameOwordOffset, G4_BB *bb,
INST_LIST_ITER insertIt,
std::unordered_set<G4_INST *> &group, bool caller) {
//
// Process chunks of size 8, 4, 2 and 1.
//
if ((useLscForSpillFill && owordSize == 16) || owordSize == 8 ||
owordSize == 4 || owordSize == 2) {
G4_ExecSize execSize = (owordSize > 2) ? g4::SIMD16 : g4::SIMD8;
unsigned responseLength = GlobalRA::owordToGRFSize(owordSize, builder);
G4_Declare *dstDcl =
builder.createTempVar(responseLength * builder.getGenxDataportIOSize(),
Type_UD, builder.getGRFAlign(), StackCallStr);
if (caller) {
kernel.callerRestoreDecls.push_back(dstDcl);
}
dstDcl->getRegVar()->setPhyReg(regPool.getGreg(startReg), 0);
G4_DstRegRegion *dstRgn = builder.createDst(
dstDcl->getRegVar(), 0, 0, 1, (execSize > 8) ? Type_UW : Type_UD);
G4_INST *fillIntrinsic = nullptr;
if (builder.supportsLSC()) {
auto headerOpnd = getSpillFillHeader(*kernel.fg.builder, nullptr);
fillIntrinsic = builder.createFill(headerOpnd, dstRgn, execSize,
responseLength, frameOwordOffset / 2,
framePtr, InstOpt_WriteEnable, false);
} else
fillIntrinsic = builder.createFill(dstRgn, execSize, responseLength,
frameOwordOffset / 2, framePtr,
InstOpt_WriteEnable, false);
fillIntrinsic->inheritDIFrom(*insertIt);
bb->insertBefore(insertIt, fillIntrinsic);
group.insert(fillIntrinsic);
}
//
// Split into chunks of sizes 8 and remaining owords.
//
else if ((useLscForSpillFill && owordSize > 16)) {
restoreRegs(startReg, 16, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group, caller);
restoreRegs(startReg + GlobalRA::owordToGRFSize(16, builder),
owordSize - 16, scratchRegDcl, framePtr, frameOwordOffset + 16,
bb, insertIt, group, caller);
} else if (owordSize > 8) {
restoreRegs(startReg, 8, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group, caller);
restoreRegs(startReg + GlobalRA::owordToGRFSize(8, builder), owordSize - 8,
scratchRegDcl, framePtr, frameOwordOffset + 8, bb, insertIt,
group, caller);
}
//
// Split into chunks of sizes 4 and remaining owords.
//
else if (owordSize > 4) {
restoreRegs(startReg, 4, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group, caller);
restoreRegs(startReg + GlobalRA::owordToGRFSize(4, builder), owordSize - 4,
scratchRegDcl, framePtr, frameOwordOffset + 4, bb, insertIt,
group, caller);
}
//
// Split into chunks of sizes 2 and remaining owords.
//
else if (owordSize > 2) {
restoreRegs(startReg, 2, scratchRegDcl, framePtr, frameOwordOffset, bb,
insertIt, group, caller);
restoreRegs(startReg + GlobalRA::owordToGRFSize(2, builder), owordSize - 2,
scratchRegDcl, framePtr, frameOwordOffset + 2, bb, insertIt,
group, caller);
} else {
vISA_ASSERT(false, ERROR_REGALLOC);
}
}
//
// Generate the restore code for the i/p restoreRegs.
//
void GlobalRA::restoreActiveRegs(std::vector<bool> &restoreRegs,
unsigned startReg, unsigned frameOffset,
G4_BB *bb, INST_LIST_ITER insertIt,
std::unordered_set<G4_INST *> &group,
bool caller) {
G4_Declare *scratchRegDcl = builder.kernel.fg.scratchRegDcl;
G4_Declare *framePtr = builder.kernel.fg.framePtrDcl;
unsigned frameOwordPos = frameOffset;
unsigned startPos = 0;
while (startPos < restoreRegs.size()) {
for (; startPos < restoreRegs.size() && restoreRegs[startPos] == false;
startPos++)
;
if (startPos < restoreRegs.size() && restoreRegs[startPos]) {
unsigned endPos = startPos + 1;
for (; endPos < restoreRegs.size() && restoreRegs[endPos] == true;
endPos++)
;
unsigned owordSize =
(endPos - startPos) * GlobalRA::GRFSizeToOwords(1, builder);
owordSize = std::max(owordSize, GlobalRA::GRFSizeToOwords(1, builder));
this->restoreRegs(startPos + startReg, owordSize, scratchRegDcl, framePtr,
frameOwordPos, bb, insertIt, group, caller);
frameOwordPos += owordSize;
startPos = endPos;
}
}
}
//
// Optimize the reg footprint so as to reduce the number of "send" instructions
// required for save/restore, at the cost of a little additional save/restore
// memory (if any). Since we are using oword read/write for save/restore, we can
// only read/write only in units of 1, 2 or 4 regs per "send" instruction.
//
void GlobalRA::OptimizeActiveRegsFootprint(std::vector<bool> &saveRegs) {
unsigned startPos = 0;
while (startPos < saveRegs.size()) {
for (; startPos < saveRegs.size() && !saveRegs[startPos]; ++startPos)
;
if (startPos == saveRegs.size()) {
break;
}
if (startPos + 4 <= saveRegs.size()) {
if (saveRegs[startPos] & saveRegs[startPos + 2] &
!saveRegs[startPos + 3]) {
saveRegs[startPos + 1] = saveRegs[startPos + 3] = true;
} else if (saveRegs[startPos] & saveRegs[startPos + 3]) {
if (startPos + 4 < saveRegs.size()) {
if (!saveRegs[startPos + 4]) {
saveRegs[startPos + 1] = saveRegs[startPos + 2] = true;
}
} else {
saveRegs[startPos + 1] = saveRegs[startPos + 2] = true;
}
}
}
unsigned winBound =
std::min(static_cast<unsigned>(saveRegs.size()), startPos + 4);
for (; startPos < winBound && saveRegs[startPos]; ++startPos)
;
}
}
void GlobalRA::OptimizeActiveRegsFootprint(std::vector<bool> &saveRegs,
std::vector<bool> &retRegs) {
unsigned startPos = 0;
while (startPos < saveRegs.size()) {
for (; startPos < saveRegs.size() && !saveRegs[startPos]; ++startPos)
;
if (startPos == saveRegs.size()) {
break;
}
if (startPos + 4 <= saveRegs.size()) {
if (saveRegs[startPos] & saveRegs[startPos + 2]) {
if (!saveRegs[startPos + 1] & !retRegs[startPos + 1]) {
saveRegs[startPos + 1] = true;
}
if (!saveRegs[startPos + 3] & !retRegs[startPos + 3]) {
saveRegs[startPos + 3] = true;
}
} else if (saveRegs[startPos] & saveRegs[startPos + 3]) {
if (startPos + 4 < saveRegs.size()) {
if (!saveRegs[startPos + 4]) {
if (!saveRegs[startPos + 1] & !retRegs[startPos + 1]) {
saveRegs[startPos + 1] = true;
}
if (!saveRegs[startPos + 2] & !retRegs[startPos + 2]) {
saveRegs[startPos + 2] = true;
}
}
} else {
if (!saveRegs[startPos + 1] & !retRegs[startPos + 1]) {
saveRegs[startPos + 1] = true;
}
if (!saveRegs[startPos + 2] & !retRegs[startPos + 2]) {
saveRegs[startPos + 2] = true;
}
}
}
}
unsigned winBound =
std::min(static_cast<unsigned>(saveRegs.size()), startPos + 4);
for (; startPos < winBound && saveRegs[startPos]; ++startPos)
;
}
}
void GraphColor::getCallerSaveRegisters() {
unsigned callerSaveNumGRF = kernel.stackCall.getCallerSaveLastGRF() + 1;
for (BB_LIST_ITER it = builder.kernel.fg.begin();
it != builder.kernel.fg.end(); ++it) {
if ((*it)->isEndWithFCall()) {
//
// Determine the caller-save registers per call site.
//
gra.callerSaveRegsMap[(*it)].resize(callerSaveNumGRF, false);
gra.retRegsMap[(*it)].resize(callerSaveNumGRF, false);
unsigned callerSaveRegCount = 0;
G4_INST *callInst = (*it)->back();
unsigned pseudoVCAId =
builder.kernel.fg.fcallToPseudoDclMap[callInst->asCFInst()]
.VCA->getRegVar()
->getId();
vISA_ASSERT((*it)->Succs.size() == 1,
"fcall basic block cannot have more than 1 successor");
for (unsigned i = 0; i < numVar; i++) {
if (i != pseudoVCAId &&
kernel.fg.isPseudoVCEDcl(lrs[i]->getDcl()) != true &&
intf.interfereBetween(pseudoVCAId, i) == true) {
if (!builder.isPreDefArg(lrs[i]->getDcl())) {
// It is possible that we end up with unallocated spill variable
// when using new fail safe RA.
if (lrs[i]->getDcl()->isSpilled() &&
kernel.getOption(vISA_NewFailSafeRA))
continue;
// NOTE: Spilled live ranges should not be caller-save.
vISA_ASSERT(lrs[i]->getPhyReg()->isGreg(), ERROR_REGALLOC);
unsigned startReg = lrs[i]->getPhyReg()->asGreg()->getRegNum();
unsigned endReg = startReg + lrs[i]->getDcl()->getNumRows();
startReg =
(startReg < callerSaveNumGRF) ? startReg : callerSaveNumGRF;
startReg = (startReg > 0) ? startReg : 1;
endReg = (endReg < callerSaveNumGRF) ? endReg : callerSaveNumGRF;
endReg = (endReg > 0) ? endReg : 1;
for (unsigned j = startReg; j < endReg; j++) {
if (builder.isPreDefRet(lrs[i]->getDcl())) {
if (gra.retRegsMap[(*it)][j] == false) {
gra.retRegsMap[(*it)][j] = true;
}
} else {
if (gra.callerSaveRegsMap[(*it)][j] == false) {
gra.callerSaveRegsMap[(*it)][j] = true;
callerSaveRegCount++;
}
}
}
}
}
}
gra.callerSaveRegCountMap[(*it)] = callerSaveRegCount;
VISA_DEBUG_VERBOSE({
std::cout << "Caller save size: "
<< callerSaveRegCount * builder.getGRFSize()
<< " bytes for fcall at cisa id "
<< (*it)->back()->getVISAId() << "\n";
});
}
}
}
//
// Add caller save/restore code before/after each stack call.
//
void GlobalRA::addCallerSaveRestoreCode() {
uint32_t maxCallerSaveSize = 0;
for (G4_BB *bb : builder.kernel.fg) {
if (bb->isEndWithFCall()) {
//
// Determine the caller-save registers per call site.
//
G4_INST *callInst = bb->back();
G4_BB *afterFCallBB = bb->Succs.front();
OptimizeActiveRegsFootprint(callerSaveRegsMap[bb], retRegsMap[bb]);
unsigned callerSaveRegsWritten = 0;
for (bool csr : callerSaveRegsMap[bb])
callerSaveRegsWritten += (csr ? 1 : 0);
INST_LIST_ITER insertSaveIt = bb->end();
--insertSaveIt, --insertSaveIt;
while ((*insertSaveIt)->isPseudoKill()) {
--insertSaveIt;
}
vISA_ASSERT((*insertSaveIt)->isCallerSave(), ERROR_REGALLOC);
INST_LIST_ITER rmIt = insertSaveIt;
if (insertSaveIt == bb->begin()) {
insertSaveIt = bb->end();
}
if (insertSaveIt != bb->end()) {
++insertSaveIt;
} else {
insertSaveIt = bb->begin();
}
if (callerSaveRegCountMap[bb] > 0) {
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
builder.kernel.getKernelDebugInfo()->clearOldInstList();
builder.kernel.getKernelDebugInfo()->setOldInstList(bb);
}
saveActiveRegs(callerSaveRegsMap[bb], 0,
builder.kernel.fg.callerSaveAreaOffset, bb, insertSaveIt,
callerSaveInsts[callInst]);
// mark instructions for EU Fusion WA
for (auto save : callerSaveInsts[callInst])
addEUFusionCallWAInst(save);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
auto deltaInstList =
builder.kernel.getKernelDebugInfo()->getDeltaInstructions(bb);
for (auto jt : deltaInstList) {
builder.kernel.getKernelDebugInfo()->addCallerSaveInst(bb, jt);
}
}
}
bb->erase(rmIt);
INST_LIST_ITER insertRestIt = afterFCallBB->begin();
for (; !(*insertRestIt)->isCallerRestore(); ++insertRestIt)
;
if (callerSaveRegCountMap[bb] > 0) {
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
builder.kernel.getKernelDebugInfo()->clearOldInstList();
builder.kernel.getKernelDebugInfo()->setOldInstList(afterFCallBB);
}
restoreActiveRegs(callerSaveRegsMap[bb], 0,
builder.kernel.fg.callerSaveAreaOffset, afterFCallBB,
insertRestIt, callerRestoreInsts[callInst], true);
// mark instructions for EU Fusion WA
for (auto restore : callerRestoreInsts[callInst])
addEUFusionCallWAInst(restore);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
auto deltaInsts =
builder.kernel.getKernelDebugInfo()->getDeltaInstructions(
afterFCallBB);
for (auto jt : deltaInsts) {
builder.kernel.getKernelDebugInfo()->addCallerRestoreInst(bb, jt);
}
}
}
afterFCallBB->erase(insertRestIt);
maxCallerSaveSize = std::max(maxCallerSaveSize, callerSaveRegsWritten *
builder.getGRFSize());
}
}
auto byteOffset =
builder.kernel.fg.callerSaveAreaOffset * 16 + maxCallerSaveSize;
builder.kernel.fg.frameSizeInOWord = ROUND(byteOffset, 64) / 16;
builder.instList.clear();
}
void GraphColor::getCalleeSaveRegisters() {
unsigned callerSaveNumGRF = kernel.stackCall.getCallerSaveLastGRF() + 1;
unsigned numCalleeSaveRegs = kernel.stackCall.getNumCalleeSaveRegs();
// Determine the callee-save registers.
gra.calleeSaveRegs.resize(numCalleeSaveRegs, false);
gra.calleeSaveRegCount = 0;
unsigned pseudoVCEId = builder.kernel.fg.pseudoVCEDcl->getRegVar()->getId();
unsigned stackCallStartReg = kernel.stackCall.getStackCallStartReg();
for (unsigned i = 0; i < numVar; i++) {
if (pseudoVCEId != i && intf.interfereBetween(pseudoVCEId, i)) {
if (lrs[i]->getPhyReg()) {
vISA_ASSERT(lrs[i]->getPhyReg()->isGreg(), ERROR_REGALLOC);
unsigned startReg = lrs[i]->getPhyReg()->asGreg()->getRegNum();
unsigned endReg = startReg + lrs[i]->getDcl()->getNumRows();
startReg = (startReg >= callerSaveNumGRF) ? startReg : callerSaveNumGRF;
startReg =
(startReg < stackCallStartReg) ? startReg : stackCallStartReg;
endReg = (endReg >= callerSaveNumGRF) ? endReg : callerSaveNumGRF;
endReg = (endReg < stackCallStartReg) ? endReg : stackCallStartReg;
for (unsigned j = startReg; j < endReg; j++) {
if (gra.calleeSaveRegs[j - callerSaveNumGRF] == false) {
gra.calleeSaveRegs[j - callerSaveNumGRF] = true;
gra.calleeSaveRegCount++;
}
}
}
}
}
}
//
// Add callee save/restore code at stack call function entry/exit.
//
void GlobalRA::addCalleeSaveRestoreCode() {
unsigned callerSaveNumGRF = kernel.stackCall.getCallerSaveLastGRF() + 1;
OptimizeActiveRegsFootprint(calleeSaveRegs);
unsigned calleeSaveRegsWritten = 0;
for (bool b : calleeSaveRegs)
calleeSaveRegsWritten += (b ? 1 : 0);
INST_LIST_ITER insertSaveIt = builder.kernel.fg.getEntryBB()->end();
for (--insertSaveIt; !(*insertSaveIt)->isCalleeSave(); --insertSaveIt)
;
if (calleeSaveRegCount > 0) {
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
// Store old inst list so we can separate callee save
// instructions that get inserted.
builder.kernel.getKernelDebugInfo()->clearOldInstList();
builder.kernel.getKernelDebugInfo()->setOldInstList(
builder.kernel.fg.getEntryBB());
}
vISA_ASSERT(calleeSaveInsts.size() == 0,
"Unexpected size of callee save set");
saveActiveRegs(calleeSaveRegs, callerSaveNumGRF,
builder.kernel.fg.calleeSaveAreaOffset,
builder.kernel.fg.getEntryBB(), insertSaveIt,
calleeSaveInsts);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
// Delta of oldInstList and current instList are all
// callee save instructions.
auto instList = builder.kernel.getKernelDebugInfo()->getDeltaInstructions(
builder.kernel.fg.getEntryBB());
for (auto inst : instList) {
builder.kernel.getKernelDebugInfo()->addCalleeSaveInst(inst);
}
}
}
builder.kernel.fg.getEntryBB()->erase(insertSaveIt);
INST_LIST_ITER insertRestIt = builder.kernel.fg.getUniqueReturnBlock()->end();
for (--insertRestIt; !(*insertRestIt)->isCalleeRestore(); --insertRestIt)
;
INST_LIST_ITER eraseIt = insertRestIt++;
if (calleeSaveRegCount > 0) {
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
// Store old inst list so we can separate callee save
// instructions that get inserted.
builder.kernel.getKernelDebugInfo()->clearOldInstList();
builder.kernel.getKernelDebugInfo()->setOldInstList(
builder.kernel.fg.getUniqueReturnBlock());
}
vISA_ASSERT(calleeRestoreInsts.size() == 0,
"Unexpected size of callee restore set");
restoreActiveRegs(calleeSaveRegs, callerSaveNumGRF,
builder.kernel.fg.calleeSaveAreaOffset,
builder.kernel.fg.getUniqueReturnBlock(), insertRestIt,
calleeRestoreInsts, false);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
auto instList = builder.kernel.getKernelDebugInfo()->getDeltaInstructions(
builder.kernel.fg.getUniqueReturnBlock());
for (auto inst : instList) {
builder.kernel.getKernelDebugInfo()->addCalleeRestoreInst(inst);
}
}
}
builder.kernel.fg.getUniqueReturnBlock()->erase(eraseIt);
builder.instList.clear();
// mark instructions for EU Fusion WA
for (auto save : calleeSaveInsts)
addEUFusionCallWAInst(save);
for (auto restore : calleeRestoreInsts)
addEUFusionCallWAInst(restore);
// caller-save starts after callee-save and is 64-byte aligned
auto byteOffset = builder.kernel.fg.calleeSaveAreaOffset * 16 +
calleeSaveRegsWritten * builder.getGRFSize();
builder.kernel.fg.callerSaveAreaOffset = ROUND(byteOffset, 64) / 16;
VISA_DEBUG({
std::cout << "Callee save size: "
<< calleeSaveRegCount * builder.getGRFSize() << " bytes"
<< "\n";
});
}
//
// Add code to setup the stack frame in callee.
//
void GlobalRA::addGenxMainStackSetupCode() {
uint32_t fpInitVal =
(uint32_t)kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);
// FIXME: a potential failure here is that frameSizeInOword is already the
// offset based on GlobalSratchOffset, which is the value of fpInitVal. So
// below we generate code to do SP = fpInitVal + frameSize, which does not
// make sense. It is correct now since when there's stack call, IGC will not
// use scratch, so fpInitVal will be 0.
unsigned frameSize = builder.kernel.fg.frameSizeInOWord;
uint16_t factor = 1;
if (useLscForSpillFill)
factor = 16;
G4_Declare *framePtr = builder.kernel.fg.framePtrDcl;
G4_Declare *stackPtr = builder.kernel.fg.stackPtrDcl;
auto entryBB = builder.kernel.fg.getEntryBB();
auto insertIt = std::find_if(entryBB->begin(), entryBB->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
//
// FP = spillMemOffset
//
{
G4_DstRegRegion *dst =
builder.createDst(framePtr->getRegVar(), 0, 0, 1, Type_UD);
G4_Imm *src = builder.createImm(fpInitVal, Type_UD);
G4_INST *fpInst =
builder.createMov(g4::SIMD1, dst, src, InstOpt_WriteEnable, false);
insertIt = entryBB->insertBefore(insertIt, fpInst);
builder.kernel.setBEFPSetupInst(fpInst);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
builder.kernel.getKernelDebugInfo()->setBEFPSetupInst(fpInst);
builder.kernel.getKernelDebugInfo()->setFrameSize(frameSize * 16);
}
}
//
// SP = FP + FrameSize (overflow-area offset + overflow-area size)
//
{
G4_DstRegRegion *dst =
builder.createDst(stackPtr->getRegVar(), 0, 0, 1, Type_UD);
G4_Imm *src = builder.createImm(fpInitVal + frameSize * factor, Type_UD);
G4_INST *spIncInst =
builder.createMov(g4::SIMD1, dst, src, InstOpt_WriteEnable, false);
builder.kernel.setBESPSetupInst(spIncInst);
entryBB->insertBefore(++insertIt, spIncInst);
}
VISA_DEBUG(std::cout << "Total frame size: " << frameSize * 16 << " bytes"
<< "\n");
}
//
// Add code to setup the stack frame in callee.
//
void GlobalRA::addCalleeStackSetupCode() {
int frameSize = (int)builder.kernel.fg.frameSizeInOWord;
uint16_t factor = 1;
// convert framesize to bytes from oword for LSC
if (useLscForSpillFill)
factor = 16;
G4_Declare *framePtr = builder.kernel.fg.framePtrDcl;
G4_Declare *stackPtr = builder.kernel.fg.stackPtrDcl;
vISA_ASSERT(frameSize > 0, "frame size cannot be 0");
//
// BE_FP = BE_SP
// BE_SP += FrameSize
//
{
G4_DstRegRegion *dst =
builder.createDst(stackPtr->getRegVar(), 0, 0, 1, Type_UD);
G4_DstRegRegion *fp_dst =
builder.createDst(framePtr->getRegVar(), 0, 0, 1, Type_UD);
const RegionDesc *rDesc = builder.getRegionScalar();
G4_Operand *src0 =
builder.createSrc(stackPtr->getRegVar(), 0, 0, rDesc, Type_UD);
G4_Operand *sp_src =
builder.createSrc(stackPtr->getRegVar(), 0, 0, rDesc, Type_UD);
G4_Imm *src1 = builder.createImm(frameSize * factor, Type_UD);
auto createBEFP = builder.createMov(g4::SIMD1, fp_dst, sp_src,
InstOpt_WriteEnable, false);
createBEFP->addComment("vISA_FP = vISA_SP");
auto addInst = builder.createBinOp(G4_add, g4::SIMD1, dst, src0, src1,
InstOpt_WriteEnable, false);
addInst->addComment("vISA_SP += vISA_frameSize");
G4_BB *entryBB = builder.kernel.fg.getEntryBB();
auto insertIt =
std::find(entryBB->begin(), entryBB->end(), getSaveBE_FPInst());
vISA_ASSERT(insertIt != entryBB->end(), "Can't find BE_FP store inst");
builder.kernel.setBEFPSetupInst(createBEFP);
builder.kernel.setBESPSetupInst(addInst);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
builder.kernel.getKernelDebugInfo()->setBEFPSetupInst(createBEFP);
builder.kernel.getKernelDebugInfo()->setFrameSize(frameSize * 16);
}
addEUFusionCallWAInst(createBEFP);
addEUFusionCallWAInst(addInst);
if (EUFusionCallWANeeded()) {
builder.kernel.getKernelDebugInfo()->setCallerBEFPSaveInst(createBEFP);
}
insertIt++;
entryBB->insertBefore(insertIt, createBEFP);
entryBB->insertBefore(insertIt, addInst);
}
// Stack is destroyed in function addStoreRestoreToReturn() where part FDE is
// restored before fret. This is an optimization as 1 SIMD4 instruction
// restores ret %ip, ret EM, caller's BE_FP, BE_SP.
builder.instList.clear();
VISA_DEBUG(std::cout << "\nTotal frame size: " << frameSize * 16
<< " bytes\n");
}
//
// Add A0 save/restore code for stack calls.
//
void GraphColor::addA0SaveRestoreCode() {
uint8_t numA0Elements = (uint8_t)builder.getNumAddrRegisters();
int count = 0;
for (auto bb : builder.kernel.fg) {
if (bb->isEndWithFCall()) {
G4_BB *succ = bb->Succs.front();
auto fcallInst = bb->back()->asCFInst();
G4_RegVar *assocPseudoA0 =
bb->getParent().fcallToPseudoDclMap[fcallInst].A0->getRegVar();
if (!assocPseudoA0->getPhyReg()) {
// Insert save/restore code because the pseudo node did not get an
// allocation
const char *name = builder.getNameString(20, "SA0_%d", count++);
G4_Declare *savedDcl =
builder.createDeclare(name, G4_GRF, numA0Elements, 1, Type_UW);
{
//
// (W) mov (16) TMP_GRF<1>:uw a0.0<16;16,1>:uw
//
G4_DstRegRegion *dst =
builder.createDst(savedDcl->getRegVar(), 0, 0, 1, Type_UW);
const RegionDesc *rDesc = builder.getRegionStride1();
G4_Operand *src =
builder.createSrc(regPool.getAddrReg(), 0, 0, rDesc, Type_UW);
G4_INST *saveInst = builder.createMov(
G4_ExecSize(numA0Elements), dst, src, InstOpt_WriteEnable, false);
INST_LIST_ITER insertIt = std::prev(bb->end());
bb->insertBefore(insertIt, saveInst);
gra.addEUFusionCallWAInst(saveInst);
}
{
//
// (W) mov (16) a0.0<1>:uw TMP_GRF<16;16,1>:uw
//
G4_DstRegRegion *dst =
builder.createDst(regPool.getAddrReg(), 0, 0, 1, Type_UW);
const RegionDesc *rDesc = builder.getRegionStride1();
G4_Operand *src =
builder.createSrc(savedDcl->getRegVar(), 0, 0, rDesc, Type_UW);
G4_INST *restoreInst = builder.createMov(
G4_ExecSize(numA0Elements), dst, src, InstOpt_WriteEnable, false);
auto insertIt =
std::find_if(succ->begin(), succ->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
succ->insertBefore(insertIt, restoreInst);
gra.addEUFusionCallWAInst(restoreInst);
}
}
}
}
builder.instList.clear();
}
//
// Add Flag save/restore code for stack calls.
//
void GraphColor::addFlagSaveRestoreCode() {
int count = 0;
int num32BitFlags = builder.getNumFlagRegisters() / 2;
// each 32-bit flag gets a declare
// ToDo: should we use flag ARF directly here?
std::vector<G4_Declare *> tmpFlags;
for (int i = 0; i < num32BitFlags; ++i) {
G4_Declare *tmpFlag = builder.createTempFlag(2);
tmpFlag->getRegVar()->setPhyReg(regPool.getFlagAreg(i), 0);
tmpFlags.push_back(tmpFlag);
}
for (auto bb : builder.kernel.fg) {
if (bb->isEndWithFCall()) {
G4_BB *succ = bb->Succs.front();
auto fcallInst = bb->back()->asCFInst();
G4_RegVar *assocPseudoFlag =
bb->getParent().fcallToPseudoDclMap[fcallInst].Flag->getRegVar();
if (!assocPseudoFlag->getPhyReg()) {
// Insert save/restore code because the pseudo node did not get an
// allocation
const char *name = builder.getNameString(32, "SFLAG_%d", count++);
G4_Declare *savedDcl1 =
builder.createDeclare(name, G4_GRF, num32BitFlags, 1, Type_UD);
{
//
// (W) mov (1) TMP_GRF.0<1>:ud f0.0:ud
// (W) mov (1) TMP_GRF.1<1>:ud f1.0:ud
//
auto createFlagSaveInst = [&](int index) {
auto flagDcl = tmpFlags[index];
G4_DstRegRegion *dst =
builder.createDst(savedDcl1->getRegVar(), 0, index, 1, Type_UD);
G4_Operand *src = builder.createSrc(
flagDcl->getRegVar(), 0, 0, builder.getRegionScalar(), Type_UD);
return builder.createMov(g4::SIMD1, dst, src, InstOpt_WriteEnable,
false);
};
auto iter = std::prev(bb->end());
for (int i = 0; i < num32BitFlags; ++i) {
auto saveInst = createFlagSaveInst(i);
bb->insertBefore(iter, saveInst);
gra.addEUFusionCallWAInst(saveInst);
}
}
{
//
// mov (1) f0.0:ud TMP_GRF.0<0;1,0>:ud
// mov (1) f1.0:ud TMP_GRF.1<0;1,0>:ud
//
auto createRestoreFlagInst = [&](int index) {
auto flagDcl = tmpFlags[index];
G4_DstRegRegion *dst =
builder.createDst(flagDcl->getRegVar(), 0, 0, 1, Type_UD);
const RegionDesc *rDesc = builder.getRegionScalar();
G4_Operand *src = builder.createSrc(savedDcl1->getRegVar(), 0,
index, rDesc, Type_UD);
return builder.createMov(g4::SIMD1, dst, src, InstOpt_WriteEnable,
false);
};
auto insertIt =
std::find_if(succ->begin(), succ->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
for (int i = 0; i < num32BitFlags; ++i) {
auto restoreInst = createRestoreFlagInst(i);
succ->insertBefore(insertIt, restoreInst);
gra.addEUFusionCallWAInst(restoreInst);
}
}
}
}
}
builder.instList.clear();
}
void GraphColor::getSaveRestoreRegister() {
if (!builder.getIsKernel()) {
getCalleeSaveRegisters();
}
getCallerSaveRegisters();
}
//
// Get the forbidden vector size
//
unsigned ForbiddenRegs::getForbiddenVectorSize(G4_RegFileKind regKind) const {
switch (regKind) {
case G4_GRF:
case G4_INPUT:
return builder.kernel.getNumRegTotal();
case G4_ADDRESS:
return builder.getNumAddrRegisters();
case G4_FLAG:
return builder.getNumFlagRegisters();
case G4_SCALAR:
return builder.kernel.getSRFInWords();
default:
vISA_ASSERT_UNREACHABLE("illegal reg file");
return 0;
}
}
//
// Get the forbidden vectors of reserved GRFs
// May be reserved for user, stack call, and spill
// This is the default RC for all GRF live ranges.
//
void ForbiddenRegs::generateReservedGRFForbidden(
unsigned reserveSpillSize) {
bool hasStackCall = builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc();
uint32_t reservedGRFNum = builder.getuint32Option(vISA_ReservedGRFNum);
uint32_t reservedFromFrontGRFNum =
builder.getuint32Option(vISA_ReservedFromFrontGRFNum);
unsigned int stackCallRegSize =
hasStackCall ? builder.kernel.stackCall.numReservedABIGRF() : 0;
// r0 - Forbidden when platform is not 3d
// The last 1-3 GRFs may be reserved for stack call ABIs.
int index = static_cast<int>(forbiddenKind::FBD_RESERVEDGRF);
unsigned totalGRFNum = builder.kernel.getNumRegTotal();
forbiddenVec[index].resize(getForbiddenVectorSize(G4_GRF));
forbiddenVec[index].clear();
if (builder.kernel.getKernelType() != VISA_3D || !builder.canWriteR0() ||
reserveSpillSize > 0 || builder.kernel.getOption(vISA_PreserveR0InR0)) {
forbiddenVec[index].set(0, true);
}
if (builder.mustReserveR1()) {
// r1 is reserved for SIP kernel
forbiddenVec[index].set(1, true);
}
unsigned reservedRegSize = stackCallRegSize + reserveSpillSize;
for (unsigned int i = 0; i < reservedRegSize; i++) {
forbiddenVec[index].set(totalGRFNum - 1 - i, true);
}
unsigned largestNoneReservedReg = totalGRFNum - reservedRegSize - 1;
if (totalGRFNum - reservedRegSize >= totalGRFNum - 16) {
largestNoneReservedReg = totalGRFNum - 16 - 1;
}
if (totalGRFNum - reservedRegSize < reservedGRFNum) {
vISA_ASSERT(false, "After reservation, there is not enough regiser!");
}
for (unsigned int i = 0; i < reservedGRFNum; i++) {
forbiddenVec[index].set(largestNoneReservedReg - i, true);
}
for (unsigned int i = 0; i < reservedFromFrontGRFNum; i++) {
forbiddenVec[index].set(i, true);
}
auto &fg = builder.kernel.fg;
if (fg.reserveSR) {
forbiddenVec[index].set(
fg.scratchRegDcl->getRegVar()->getPhyReg()->asGreg()->getRegNum(),
true);
}
}
// ETO use only last 16 registers
void ForbiddenRegs::generateEOTGRFForbidden() {
forbiddenVec[(size_t)forbiddenKind::FBD_EOT].resize(
getForbiddenVectorSize(G4_GRF));
forbiddenVec[(size_t)forbiddenKind::FBD_EOT].clear();
for (unsigned i = 0; i < builder.kernel.getNumRegTotal() - 16; i++) {
forbiddenVec[(size_t)forbiddenKind::FBD_EOT].set(i, true);
}
forbiddenVec[(size_t)forbiddenKind::FBD_EOT] |=
forbiddenVec[(size_t)forbiddenKind::FBD_RESERVEDGRF];
}
void ForbiddenRegs::generateLastGRFForbidden() {
forbiddenVec[(size_t)forbiddenKind::FBD_LASTGRF].resize(
getForbiddenVectorSize(G4_GRF));
forbiddenVec[(size_t)forbiddenKind::FBD_LASTGRF].clear();
forbiddenVec[(size_t)forbiddenKind::FBD_LASTGRF].set(
builder.kernel.getNumRegTotal() - 1, true);
forbiddenVec[(size_t)forbiddenKind::FBD_LASTGRF] |=
forbiddenVec[(size_t)forbiddenKind::FBD_RESERVEDGRF];
}
void ForbiddenRegs::generateEOTLastGRFForbidden() {
forbiddenVec[(size_t)forbiddenKind::FBD_EOTLASTGRF].resize(
getForbiddenVectorSize(G4_GRF));
forbiddenVec[(size_t)forbiddenKind::FBD_EOTLASTGRF].clear();
forbiddenVec[(size_t)forbiddenKind::FBD_EOTLASTGRF] |=
forbiddenVec[(size_t)forbiddenKind::FBD_EOT];
forbiddenVec[(size_t)forbiddenKind::FBD_EOTLASTGRF] |=
forbiddenVec[(size_t)forbiddenKind::FBD_LASTGRF];
}
//
// mark forbidden registers for caller-save pseudo var
//
void ForbiddenRegs::generateCallerSaveGRFForbidden() {
unsigned int startCalleeSave = builder.kernel.stackCall.calleeSaveStart();
unsigned int endCalleeSave =
startCalleeSave + builder.kernel.stackCall.getNumCalleeSaveRegs();
// r60-r124 are caller save regs for SKL
forbiddenVec[(size_t)forbiddenKind::FBD_CALLERSAVE].resize(
getForbiddenVectorSize(G4_GRF));
forbiddenVec[(size_t)forbiddenKind::FBD_CALLERSAVE].clear();
for (unsigned int i = startCalleeSave; i < endCalleeSave; i++) {
forbiddenVec[(size_t)forbiddenKind::FBD_CALLERSAVE].set(i, true);
}
forbiddenVec[(size_t)forbiddenKind::FBD_CALLERSAVE] |=
forbiddenVec[(size_t)forbiddenKind::FBD_RESERVEDGRF];
}
//
// mark forbidden registers for callee-save pseudo var
//
void ForbiddenRegs::generateCalleeSaveGRFForbidden() {
unsigned int numCallerSaveGRFs =
builder.kernel.stackCall.getCallerSaveLastGRF() + 1;
forbiddenVec[(size_t)forbiddenKind::FBD_CALLEESAVE].resize(
getForbiddenVectorSize(G4_GRF));
forbiddenVec[(size_t)forbiddenKind::FBD_CALLEESAVE].clear();
for (unsigned int i = 1; i < numCallerSaveGRFs; i++) {
forbiddenVec[(size_t)forbiddenKind::FBD_CALLEESAVE].set(i, true);
}
forbiddenVec[(size_t)forbiddenKind::FBD_CALLEESAVE] |=
forbiddenVec[(size_t)forbiddenKind::FBD_RESERVEDGRF];
}
//
// Add GRF caller/callee save/restore code for stack calls.
// localSpillAreaOwordsize specifices the starting offset of the
// caller/callee-save area in this frame. It is 64-byte aligned.
//
void GlobalRA::addSaveRestoreCode(unsigned localSpillAreaOwordSize) {
if (builder.getIsKernel()) {
builder.kernel.fg.callerSaveAreaOffset = localSpillAreaOwordSize;
} else {
builder.kernel.fg.calleeSaveAreaOffset = localSpillAreaOwordSize;
addCalleeSaveRestoreCode();
}
addCallerSaveRestoreCode();
if (builder.getIsKernel()) {
addGenxMainStackSetupCode();
} else {
addCalleeStackSetupCode();
}
stackCallProlog();
builder.instList.clear();
}
//
// If the graph has stack calls, then add the caller-save pseudo code
// immediately before and after the stack call. The pseudo code is either
// converted to actual save/restore code or is eliminated at the end of
// coloringRegAlloc().
//
void GlobalRA::addCallerSavePseudoCode() {
unsigned retID = 0;
for (G4_BB *bb : builder.kernel.fg) {
if (bb->isEndWithFCall()) {
// GRF caller save/restore
auto fcallInst = bb->back()->asCFInst();
G4_Declare *pseudoVCADcl =
bb->getParent().fcallToPseudoDclMap[fcallInst].VCA;
G4_DstRegRegion *dst =
builder.createDst(pseudoVCADcl->getRegVar(), 0, 0, 1, Type_UD);
G4_INST *saveInst = builder.createInternalIntrinsicInst(
nullptr, Intrinsic::CallerSave, g4::SIMD1, dst, nullptr, nullptr,
nullptr, InstOpt_WriteEnable);
saveInst->inheritDIFrom(fcallInst);
INST_LIST_ITER callBBIt = bb->end();
bb->insertBefore(--callBBIt, saveInst);
auto fcall = builder.getFcallInfo(bb->back());
vISA_ASSERT(fcall != std::nullopt, "fcall info not found");
uint16_t retSize = fcall->getRetSize();
if (retSize > 0) {
const char *name =
builder.getNameString(32, "FCALL_RETVAL_%d", retID++);
auto retDcl = builder.createHardwiredDeclare(
kernel.numEltPerGRF<Type_UD>() * retSize, Type_UD,
kernel.stackCall.retReg, 0);
retDcl->setName(name);
addVarToRA(retDcl);
fcallRetMap.emplace(pseudoVCADcl, retDcl);
}
vISA_ASSERT(bb->Succs.size() == 1,
"fcall basic block cannot have more than 1 successor node");
G4_BB *retBB = bb->Succs.front();
const RegionDesc *rd = builder.getRegionScalar();
G4_Operand *src =
builder.createSrc(pseudoVCADcl->getRegVar(), 0, 0, rd, Type_UD);
INST_LIST_ITER retBBIt = retBB->begin();
for (; retBBIt != retBB->end() && (*retBBIt)->isLabel(); ++retBBIt)
;
G4_INST *restoreInst = builder.createInternalIntrinsicInst(
nullptr, Intrinsic::CallerRestore, g4::SIMD1, nullptr, src, nullptr,
nullptr, InstOpt_WriteEnable);
restoreInst->inheritDIFrom(fcallInst);
retBB->insertBefore(retBBIt, restoreInst);
}
}
builder.instList.clear();
}
//
// If the graph has stack calls, then add the callee-save pseudo code at the
// entry/exit blocks of the function. The pseudo code is either converted to
// actual save/restore code or is eliminated at the end of coloringRegAlloc().
//
void GlobalRA::addCalleeSavePseudoCode() {
G4_Declare *pseudoVCEDcl = builder.kernel.fg.pseudoVCEDcl;
G4_DstRegRegion *dst =
builder.createDst(pseudoVCEDcl->getRegVar(), 0, 0, 1, Type_UD);
auto saveInst = builder.createInternalIntrinsicInst(
nullptr, Intrinsic::CalleeSave, g4::SIMD1, dst, nullptr, nullptr, nullptr,
InstOpt_WriteEnable);
INST_LIST_ITER insertIt = builder.kernel.fg.getEntryBB()->begin();
for (; insertIt != builder.kernel.fg.getEntryBB()->end() &&
(*insertIt)->isLabel();
++insertIt) { /* void */
};
builder.kernel.fg.getEntryBB()->insertBefore(insertIt, saveInst);
G4_BB *exitBB = builder.kernel.fg.getUniqueReturnBlock();
const RegionDesc *rDesc = builder.getRegionScalar();
G4_Operand *src =
builder.createSrc(pseudoVCEDcl->getRegVar(), 0, 0, rDesc, Type_UD);
G4_INST *restoreInst = builder.createInternalIntrinsicInst(
nullptr, Intrinsic::CalleeRestore, g4::SIMD1, nullptr, src, nullptr,
nullptr, InstOpt_WriteEnable);
INST_LIST_ITER exitBBIt = exitBB->end();
--exitBBIt;
vISA_ASSERT((*exitBBIt)->isFReturn(), ERROR_REGALLOC);
exitBB->insertBefore(exitBBIt, restoreInst);
builder.instList.clear();
}
void GlobalRA::storeCEInProlog() {
if (!kernel.getOption(vISA_storeCE))
return;
// If we've to store CE in prolog, we emit:
// TmpReg (GRF_Aligned) = CE0.0
// Store TmpReg @ FP+Offset
//
// Where Offset = 1 GRF size in bytes
// Create new variable equal to GRF size so it's always GRF aligned.
// It's transitory so shouldn't impact register pressure. We want to
// write CE0.0 in 0th location of this variable so that it can be
// used as send payload.
auto TmpReg = builder.createDeclare(
"TmpCEReg", G4_GRF, builder.numEltPerGRF<Type_UD>(), 1, Type_UD);
auto *DstRgn = builder.createDstRegRegion(TmpReg, 1);
auto *CEReg = regPool.getMask0Reg();
auto *SrcOpnd = builder.createSrc(
CEReg, 0, 0, kernel.fg.builder->getRegionScalar(), Type_UD);
auto Mov = builder.createMov(g4::SIMD1, DstRgn, SrcOpnd,
G4_InstOption::InstOpt_WriteEnable, false);
auto nextPos = kernel.fg.getEntryBB()->insertBefore(
kernel.fg.getEntryBB()->getFirstInsertPos(), Mov);
auto payloadSrc =
builder.createSrcRegRegion(TmpReg, builder.getRegionStride1());
const unsigned execSize = 8;
G4_DstRegRegion *postDst = builder.createNullDst(Type_UD);
G4_INST *store = nullptr;
unsigned int HWOffset = builder.numEltPerGRF<Type_UB>() / getHWordByteSize();
vISA_ASSERT(kernel.stackCall.getFrameDescriptorByteSize() <=
builder.numEltPerGRF<Type_UB>(),
"ce0 overwrote FDE");
kernel.getKernelDebugInfo()->setCESaveOffset(HWOffset * getHWordByteSize());
if (builder.supportsLSC()) {
auto headerOpnd = getSpillFillHeader(*kernel.fg.builder, nullptr);
store = builder.createSpill(postDst, headerOpnd, payloadSrc,
G4_ExecSize(execSize), 1, HWOffset,
builder.getBEFP(), InstOpt_WriteEnable, false);
} else {
store = builder.createSpill(postDst, payloadSrc, G4_ExecSize(execSize), 1,
HWOffset, builder.getBEFP(),
InstOpt_WriteEnable, false);
}
kernel.fg.getEntryBB()->insertAfter(nextPos, store);
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
builder.kernel.getKernelDebugInfo()->setSaveCEInst(store);
}
}
//
// Insert store r125.[0-4] at entry and restore before return.
// Dst of store will be a hardwired temp at upper end of caller save area.
// This method emits:
// (W) mov (4) SR_BEStack<1>:ud r125.0<4;4,1>:ud <-- in prolog
// (W) mov (4) r125.0<1>:ud SR_BEStack<4;4,1>:ud <-- in epilog
void GlobalRA::addStoreRestoreToReturn() {
unsigned int size = 4;
if (kernel.stackCall.getVersion() ==
StackCallABI::StackCallABIVersion::VER_3)
size = 8;
unsigned regNum = kernel.stackCall.getCallerSaveLastGRF();
unsigned subRegNum = kernel.numEltPerGRF<Type_UD>() - size;
oldFPDcl = builder.createHardwiredDeclare(size, Type_UD, regNum, subRegNum);
oldFPDcl->setName(builder.getNameString(24, "CallerSaveRetIp_BE_FP"));
G4_DstRegRegion *oldFPDst =
builder.createDst(oldFPDcl->getRegVar(), 0, 0, 1, Type_UD);
const RegionDesc *rd = builder.getRegionStride1();
G4_Operand *oldFPSrc =
builder.createSrc(oldFPDcl->getRegVar(), 0, 0, rd, Type_UD);
unsigned saveRestoreSubReg =
kernel.stackCall.getVersion() == StackCallABI::StackCallABIVersion::VER_3
? kernel.stackCall.subRegs.BE_FP
: kernel.stackCall.subRegs.Ret_IP;
auto saveRestoreDecl = builder.createHardwiredDeclare(
size, Type_UD, kernel.stackCall.getFPSPGRF(), saveRestoreSubReg);
addVarToRA(saveRestoreDecl);
saveRestoreDecl->setName(builder.getNameString(24, "SR_BEStack"));
G4_DstRegRegion *FPdst =
builder.createDst(saveRestoreDecl->getRegVar(), 0, 0, 1, Type_UD);
rd = builder.getRegionStride1();
G4_Operand *FPsrc =
builder.createSrc(saveRestoreDecl->getRegVar(), 0, 0, rd, Type_UD);
saveBE_FPInst = builder.createMov(size == 4 ? g4::SIMD4 : g4::SIMD8, oldFPDst,
FPsrc, InstOpt_WriteEnable, false);
saveBE_FPInst->addComment("save vISA SP/FP to temp");
builder.setPartFDSaveInst(saveBE_FPInst);
auto entryBB = builder.kernel.fg.getEntryBB();
auto insertIt = std::find_if(entryBB->begin(), entryBB->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
entryBB->insertBefore(insertIt, saveBE_FPInst);
auto fretBB = builder.kernel.fg.getUniqueReturnBlock();
auto iter = std::prev(fretBB->end());
vISA_ASSERT((*iter)->isFReturn(), "fret BB must end with fret");
// Following 4 cases exist for combination of EU fusion WA value, -skipFDE:
// 1. No WA needed, no -skipFDE: restore r127 from r59
// 2. No WA needed, -skipFDE: restore r127 from r59 and skip FDE store in
// leaf function
// 3. WA needed, no -skipFDE: restore r127 using load reading FDE
// 4. WA needed, -skipFDE: restore r127 from r59 in leaf function. In
// non-lead, use load to read stored FDE.
if (!EUFusionCallWANeeded() || canSkipFDE()) {
restoreBE_FPInst =
builder.createMov(size == 4 ? g4::SIMD4 : g4::SIMD8, FPdst, oldFPSrc,
InstOpt_WriteEnable, false);
fretBB->insertBefore(iter, restoreBE_FPInst);
} else {
// emit frame descriptor
auto dstDcl =
builder.createHardwiredDeclare(8, Type_UD, kernel.stackCall.getFPSPGRF(), 0);
dstDcl->setName(builder.getNameString(24, "FrameDescriptorGRF"));
auto dstData = builder.createDstRegRegion(dstDcl, 1);
const unsigned execSize = 8;
G4_INST *load = nullptr;
if (builder.supportsLSC()) {
auto headerOpnd = getSpillFillHeader(*kernel.fg.builder, nullptr);
load =
builder.createFill(headerOpnd, dstData, G4_ExecSize(execSize), 1, 0,
builder.getBEFP(), InstOpt_WriteEnable, false);
} else {
load = builder.createFill(dstData, G4_ExecSize(execSize), 1, 0,
builder.getBEFP(), InstOpt_WriteEnable, false);
}
fretBB->insertBefore(iter, load);
addEUFusionCallWAInst(load);
restoreBE_FPInst = load;
}
restoreBE_FPInst->addComment("restore vISA SP/FP from temp");
if (builder.kernel.getOption(vISA_GenerateDebugInfo)) {
builder.kernel.getKernelDebugInfo()->setCallerBEFPRestoreInst(
restoreBE_FPInst);
builder.kernel.getKernelDebugInfo()->setCallerSPRestoreInst(
restoreBE_FPInst);
if (!EUFusionCallWANeeded())
builder.kernel.getKernelDebugInfo()->setCallerBEFPSaveInst(saveBE_FPInst);
}
}
void GlobalRA::updateDefSet(std::set<G4_Declare *> &defs,
G4_Declare *referencedDcl) {
// Get topmost dcl
while (referencedDcl->getAliasDeclare() != NULL) {
referencedDcl = referencedDcl->getAliasDeclare();
}
defs.insert(referencedDcl);
}
void GlobalRA::detectUndefinedUses(LivenessAnalysis &liveAnalysis,
G4_Kernel &kernel) {
// This function iterates over each inst and checks whether there is
// a reaching def for each src operand.
VISA_DEBUG_VERBOSE({
std::cout << "\n";
if (liveAnalysis.livenessClass(G4_FLAG)) {
std::cout << "=== Uses with reaching def - Flags ===\n";
} else if (liveAnalysis.livenessClass(G4_ADDRESS)) {
std::cout << "=== Uses with reaching def - Address ===\n";
} else {
std::cout << "=== Uses with reaching def - GRF ===\n";
}
if (useLocalRA) {
std::cout
<< "(Use -nolocalra switch for accurate results of uses without "
"reaching defs)\n";
}
});
for (G4_BB *bb : kernel.fg) {
std::set<G4_Declare *> defs;
std::set<G4_Declare *>::iterator defs_it;
G4_Declare *referencedDcl = nullptr;
for (G4_INST *inst : *bb) {
// Src/predicate opnds are uses
if (inst->getPredicate() && inst->getPredicate()->getBase() &&
inst->getPredicate()->getBase()->isRegVar() &&
inst->getPredicate()->getBase()->isRegAllocPartaker()) {
referencedDcl = inst->getPredicate()
->asPredicate()
->getBase()
->asRegVar()
->getDeclare();
reportUndefinedUses(liveAnalysis, bb, inst, referencedDcl, defs,
Opnd_pred);
}
for (unsigned i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
G4_Operand *opnd = inst->getSrc(i);
if (opnd && opnd->isAddrExp() == false && opnd->getBase() &&
opnd->getBase()->isRegVar() &&
opnd->getBase()->isRegAllocPartaker()) {
referencedDcl = opnd->getBase()->asRegVar()->getDeclare();
reportUndefinedUses(liveAnalysis, bb, inst, referencedDcl, defs,
(Gen4_Operand_Number)(i + Opnd_src0));
}
}
// Dst/cond modifier opnds are defs
if (inst->getCondModBase() && inst->getCondMod()->getBase()->isRegVar() &&
inst->getCondMod()->getBase()->isRegAllocPartaker()) {
referencedDcl = inst->getCondMod()
->asCondMod()
->getBase()
->asRegVar()
->getDeclare();
updateDefSet(defs, referencedDcl);
}
if (inst->getDst() && inst->getDst()->getBase() &&
inst->getDst()->getBase()->isRegVar() &&
inst->getDst()->getBase()->isRegAllocPartaker()) {
referencedDcl = inst->getDst()->getBase()->asRegVar()->getDeclare();
updateDefSet(defs, referencedDcl);
}
}
}
VISA_DEBUG_VERBOSE(std::cout << "\n\n");
}
void GlobalRA::detectNeverDefinedUses() {
// Detect variables that are used but never defined in entire CFG.
// This does not use liveness information.
// Hold all decls from symbol table as key.
// Boolean mapped value determines whether the dcl is
// defined in kernel or not.
std::map<G4_Declare *, bool> vars;
std::map<G4_Declare *, bool>::iterator map_it;
for (auto bb : kernel.fg) {
for (G4_INST *inst : *bb) {
G4_Declare *referencedDcl = nullptr;
if (inst->getDst() && inst->getDst()->getBase() &&
inst->getDst()->getBase()->isRegVar()) {
referencedDcl = inst->getDst()->getBaseRegVarRootDeclare();
// Always insert top-most dcl
map_it = vars.find(referencedDcl);
if (map_it == vars.end()) {
vars.emplace(referencedDcl, true);
} else {
map_it->second = true;
}
}
if (inst->getCondModBase() && inst->getCondMod()->getBase()->isRegVar()) {
referencedDcl = inst->getCondMod()->getBaseRegVarRootDeclare();
map_it = vars.find(referencedDcl);
if (map_it == vars.end()) {
vars.emplace(referencedDcl, true);
} else {
map_it->second = true;
}
}
if (inst->getPredicate() && inst->getPredicate()->getBase() &&
inst->getPredicate()->getBase()->isRegVar()) {
referencedDcl = inst->getPredicate()->getBaseRegVarRootDeclare();
// Check whether dcl was already added to list.
// If not, add it with flag set to false to indicate
// that a use was found but a def hasnt been seen yet.
map_it = vars.find(referencedDcl);
if (map_it == vars.end()) {
vars.emplace(referencedDcl, false);
}
}
for (unsigned i = 0, numSrc = inst->getNumSrc(); i < numSrc; i++) {
G4_Operand *opnd = inst->getSrc(i);
if (opnd && opnd->getBase() && opnd->getBase()->isRegVar()) {
referencedDcl = opnd->getBaseRegVarRootDeclare();
map_it = vars.find(referencedDcl);
if (map_it == vars.end()) {
vars.emplace(referencedDcl, false);
}
}
}
}
}
VISA_DEBUG_VERBOSE(std::cout
<< "\n=== Variables used but never defined ===\n\n");
for (auto dcl : kernel.Declares) {
while (dcl->getAliasDeclare())
dcl = dcl->getAliasDeclare();
map_it = vars.find(dcl);
if (map_it != vars.end()) {
if (map_it->second == false && dcl->getRegFile() != G4_INPUT &&
dcl->getAddressed() == false) {
// No def found for this non-input variable in
// entire CFG so report it.
VISA_DEBUG_VERBOSE({
std::cout << dcl->getName();
if (dcl->getRegFile() == G4_GRF) {
std::cout << " (General)";
} else if (dcl->getRegFile() == G4_ADDRESS) {
std::cout << " (Address)";
} else if (dcl->getRegFile() == G4_FLAG) {
std::cout << " (Flag)";
}
std::cout << "\n";
});
}
}
}
VISA_DEBUG_VERBOSE(std::cout << "\n\n");
}
//
// Check the overlap of two sources' ranges and do range splitting
// Such as, range1: 0~63, range2: 32~95 --> 0~31,32~63,64~95
// or, range1: 0~63, range2: 32~63 --> 0~31,32~63
//
VarRange *VarSplit::splitVarRange(VarRange *src1, VarRange *src2,
std::stack<VarRange *> *toDelete) {
VarRange *new_var_range = nullptr;
vISA_ASSERT(!(src1->leftBound == src2->leftBound &&
src1->rightBound == src2->rightBound),
"Same ranges can not be spiltted");
if (src1->leftBound > src2->rightBound ||
src1->rightBound < src2->leftBound) // No overlap
{
return NULL;
}
unsigned left1 = std::min(src1->leftBound, src2->leftBound); // left
unsigned right1 = std::max(src1->leftBound, src2->leftBound);
unsigned left2 = std::min(src1->rightBound, src2->rightBound); // right
unsigned right2 = std::max(src1->rightBound, src2->rightBound);
if (left1 == right1) // Same left
{
src1->leftBound = left1;
src1->rightBound = left2;
src2->leftBound = left2 + 1;
src2->rightBound = right2;
} else if (left2 == right2) // Same right
{
src1->leftBound = left1;
src1->rightBound = right1 - 1;
src2->leftBound = right1;
src2->rightBound = right2;
} else // No same boundary
{
src1->leftBound = left1; // Left one: in list already
src1->rightBound = right1 - 1;
src2->leftBound = left2 + 1; // Right one: keep in list
src2->rightBound = right2;
new_var_range = new VarRange;
new_var_range->leftBound = right1; // Middle one: need add one range object
new_var_range->rightBound = left2;
toDelete->push(new_var_range);
}
return new_var_range;
}
//
// Scan the range list, Insert the new range into the range list.
// Range splitting is applied if required.
//
void VarSplit::rangeListSpliting(VAR_RANGE_LIST *rangeList, G4_Operand *opnd,
std::stack<VarRange *> *toDelete) {
VarRange *range = new VarRange;
range->leftBound = opnd->getLeftBound();
range->rightBound = opnd->getRightBound();
toDelete->push(range);
VAR_RANGE_LIST_ITER it = rangeList->begin();
// The ranges in the list are ordered from low to high
while (it != rangeList->end()) {
if ((*it)->leftBound == range->leftBound &&
((*it)->rightBound == range->rightBound)) {
// Same range exists in the list already
return;
}
if ((*it)->leftBound > range->rightBound) {
// The range item in the list is on the right of current range, insert it
// before the postion. Since the whole range is inserted first, all the
// ranges should be continuous.
vISA_ASSERT((*it)->leftBound - range->rightBound == 1,
"none continuous spliting happened\n");
rangeList->insert(it, range);
return;
}
// Overlap happened, do splitting.
//(*lt) is updated to the left range
//"range" is updated to the right range
// If "newRange" is not NULL, it's the middle range.
VarRange *newRange = splitVarRange((*it), range, toDelete);
// Insert the middle one
it++;
if (newRange) {
it = rangeList->insert(it, newRange);
}
}
rangeList->push_back(range); // Insert the right one
return;
}
void VarSplit::getHeightWidth(G4_Type type, unsigned numberElements,
unsigned short &dclWidth,
unsigned short &dclHeight,
int &totalByteSize) const {
dclWidth = 1, dclHeight = 1;
totalByteSize = numberElements * TypeSize(type);
if (totalByteSize <= (int)kernel.numEltPerGRF<Type_UB>()) {
dclWidth = (uint16_t)numberElements;
} else {
// here we assume that the start point of the var is the beginning of a GRF?
// so subregister must be 0?
dclWidth = kernel.numEltPerGRF<Type_UB>() / TypeSize(type);
dclHeight = totalByteSize / kernel.numEltPerGRF<Type_UB>();
if (totalByteSize % kernel.numEltPerGRF<Type_UB>() != 0) {
dclHeight++;
}
}
}
void VarSplit::createSubDcls(G4_Kernel &kernel, G4_Declare *oldDcl,
std::vector<G4_Declare *> &splitDclList) {
if (oldDcl->getByteSize() <= kernel.numEltPerGRF<Type_UB>() ||
oldDcl->getByteSize() % kernel.numEltPerGRF<Type_UB>()) {
return;
}
int splitVarSize = kernel.getSimdSize() == g4::SIMD8 ? 1 : 2;
for (unsigned i = 0, bSizePerGRFSize = (oldDcl->getByteSize() /
kernel.numEltPerGRF<Type_UB>());
i < bSizePerGRFSize; i += splitVarSize) {
G4_Declare *splitDcl = NULL;
unsigned leftBound = i * kernel.numEltPerGRF<Type_UB>();
unsigned rightBound =
(i + splitVarSize) * kernel.numEltPerGRF<Type_UB>() - 1;
unsigned short dclWidth = 0;
unsigned short dclHeight = 0;
int dclTotalSize = 0;
getHeightWidth(oldDcl->getElemType(),
(rightBound - leftBound + 1) / oldDcl->getElemSize(),
dclWidth, dclHeight, dclTotalSize);
const char *splitDclName = kernel.fg.builder->getNameString(
16, "split_%d_%s", i, oldDcl->getName());
splitDcl = kernel.fg.builder->createDeclare(
splitDclName, G4_GRF, dclWidth, dclHeight, oldDcl->getElemType());
gra.setSubOffset(splitDcl, leftBound);
splitDcl->copyAlign(oldDcl);
gra.copyAlignment(splitDcl, oldDcl);
unsigned nElementSize =
(rightBound - leftBound + 1) / oldDcl->getElemSize();
if ((rightBound - leftBound + 1) % oldDcl->getElemSize()) {
nElementSize++;
}
splitDcl->setTotalElems(nElementSize);
splitDclList.push_back(splitDcl);
}
return;
}
void VarSplit::insertMovesToTemp(IR_Builder &builder, G4_Declare *oldDcl,
G4_Operand *dstOpnd, G4_BB *bb,
INST_LIST_ITER instIter,
std::vector<G4_Declare *> &splitDclList) {
G4_INST *inst = (*instIter);
INST_LIST_ITER iter = instIter;
iter++;
for (size_t i = 0, size = splitDclList.size(); i < size; i++) {
G4_Declare *subDcl = splitDclList[i];
unsigned leftBound = gra.getSubOffset(subDcl);
unsigned rightBound = leftBound + subDcl->getByteSize() - 1;
if (!(dstOpnd->getRightBound() < leftBound ||
rightBound < dstOpnd->getLeftBound())) {
unsigned maskFlag = (inst->getOption() & 0xFFF010C);
G4_DstRegRegion *dst = builder.createDstRegRegion(subDcl, 1);
auto src = builder.createSrc(
oldDcl->getRegVar(),
(gra.getSubOffset(subDcl)) / kernel.numEltPerGRF<Type_UB>(), 0,
builder.getRegionStride1(), oldDcl->getElemType());
G4_INST *splitInst = builder.createMov(
G4_ExecSize(subDcl->getTotalElems()), dst, src, maskFlag, false);
bb->insertBefore(iter, splitInst);
if (splitInst->isWriteEnableInst() && gra.EUFusionNoMaskWANeeded()) {
gra.addEUFusionNoMaskWAInst(bb, splitInst);
}
}
}
return;
}
void VarSplit::insertMovesFromTemp(G4_Kernel &kernel, G4_Declare *oldDcl,
int index, G4_Operand *srcOpnd, int pos,
G4_BB *bb, INST_LIST_ITER instIter,
std::vector<G4_Declare *> &splitDclList) {
G4_INST *inst = (*instIter);
int sizeInGRF = (srcOpnd->getRightBound() - srcOpnd->getLeftBound() +
kernel.numEltPerGRF<Type_UB>() - 1) /
kernel.numEltPerGRF<Type_UB>();
int splitSize = kernel.getSimdSize() == g4::SIMD8 ? 1 : 2;
if (sizeInGRF != splitSize) {
unsigned short dclWidth = 0;
unsigned short dclHeight = 0;
int dclTotalSize = 0;
G4_SrcRegRegion *oldSrc = srcOpnd->asSrcRegRegion();
getHeightWidth(oldSrc->getType(),
(srcOpnd->getRightBound() - srcOpnd->getLeftBound() + 1) /
oldSrc->getElemSize(),
dclWidth, dclHeight, dclTotalSize);
const char *newDclName = kernel.fg.builder->getNameString(
16, "copy_%d_%s", index, oldDcl->getName());
G4_Declare *newDcl = kernel.fg.builder->createDeclare(
newDclName, G4_GRF, dclWidth, dclHeight, oldSrc->getType());
newDcl->copyAlign(oldDcl);
gra.copyAlignment(newDcl, oldDcl);
unsigned newLeftBound = 0;
for (size_t i = 0, size = splitDclList.size(); i < size; i++) {
G4_Declare *subDcl = splitDclList[i];
unsigned leftBound = gra.getSubOffset(subDcl);
unsigned rightBound = leftBound + subDcl->getByteSize() - 1;
if (!(srcOpnd->getRightBound() < leftBound ||
rightBound < srcOpnd->getLeftBound())) {
G4_DstRegRegion *dst = kernel.fg.builder->createDst(
newDcl->getRegVar(), newLeftBound / kernel.numEltPerGRF<Type_UB>(),
0, 1, oldSrc->getType());
newLeftBound += subDcl->getByteSize();
G4_SrcRegRegion *src = kernel.fg.builder->createSrc(
subDcl->getRegVar(), 0, 0, kernel.fg.builder->getRegionStride1(),
oldSrc->getType());
G4_INST *movInst =
kernel.fg.builder->createMov(G4_ExecSize(subDcl->getTotalElems()),
dst, src, InstOpt_WriteEnable, false);
bb->insertBefore(instIter, movInst);
if (gra.EUFusionNoMaskWANeeded()) {
gra.addEUFusionNoMaskWAInst(bb, movInst);
}
}
}
auto newSrc = kernel.fg.builder->createSrcRegRegion(
oldSrc->getModifier(), Direct, newDcl->getRegVar(), 0,
oldSrc->getSubRegOff(), oldSrc->getRegion(), newDcl->getElemType());
inst->setSrc(newSrc, pos);
} else {
for (size_t i = 0, size = splitDclList.size(); i < size; i++) {
G4_Declare *subDcl = splitDclList[i];
unsigned leftBound = gra.getSubOffset(subDcl);
unsigned rightBound = leftBound + subDcl->getByteSize() - 1;
if (!(srcOpnd->getRightBound() < leftBound ||
rightBound < srcOpnd->getLeftBound())) {
G4_SrcRegRegion *oldSrc = srcOpnd->asSrcRegRegion();
G4_SrcRegRegion *newSrc = kernel.fg.builder->createSrcRegRegion(
oldSrc->getModifier(), Direct, subDcl->getRegVar(), 0,
oldSrc->getSubRegOff(), oldSrc->getRegion(), oldSrc->getType());
inst->setSrc(newSrc, pos);
break;
}
}
}
return;
}
bool VarSplit::canDoGlobalSplit(IR_Builder &builder, G4_Kernel &kernel,
uint32_t sendSpillRefCount) {
if (!builder.getOption(vISA_GlobalSendVarSplit)) {
return false;
}
if (!builder.getOption(vISA_Debug) && // Not work in debug mode
kernel.getInt32KernelAttr(Attributes::ATTR_Target) ==
VISA_3D && // Only works for 3D/OCL/OGL
sendSpillRefCount) {
return true;
}
return false;
}
void VarSplit::globalSplit(IR_Builder &builder, G4_Kernel &kernel) {
typedef std::list<
std::tuple<G4_BB *, G4_Operand *, int, unsigned, INST_LIST_ITER>>
SPLIT_OPERANDS;
typedef std::list<std::tuple<G4_BB *, G4_Operand *, int, unsigned,
INST_LIST_ITER>>::iterator SPLIT_OPERANDS_ITER;
typedef std::map<G4_RegVar *, SPLIT_OPERANDS> SPLIT_DECL_OPERANDS;
typedef std::map<G4_RegVar *, SPLIT_OPERANDS>::iterator
SPLIT_DECL_OPERANDS_ITER;
SPLIT_DECL_OPERANDS splitDcls;
unsigned instIndex = 0;
int splitSize = kernel.getSimdSize() == g4::SIMD8 ? 1 : 2;
for (auto bb : kernel.fg) {
for (INST_LIST_ITER it = bb->begin(), iend = bb->end(); it != iend;
++it, ++instIndex) {
G4_INST *inst = (*it);
G4_DstRegRegion *dst = inst->getDst();
if (inst->isLifeTimeEnd() || inst->isPseudoKill()) {
continue;
}
//
// process send destination operand
//
if (inst->isSend() &&
inst->getMsgDesc()->getDstLenRegs() > (size_t)splitSize &&
inst->asSendInst()->isDirectSplittableSend()) {
G4_DstRegRegion *dstrgn = dst;
G4_Declare *topdcl = GetTopDclFromRegRegion(dstrgn);
if (topdcl && dstrgn->getRegAccess() == Direct &&
!topdcl->getAddressed() && topdcl->getRegFile() != G4_INPUT &&
(dstrgn->getRightBound() - dstrgn->getLeftBound() + 1) ==
topdcl->getByteSize() &&
(dstrgn->getRightBound() - dstrgn->getLeftBound()) >
kernel.numEltPerGRF<Type_UB>()) {
// The tuple<G4_BB*, G4_Operand*, int pos, unsigned instIndex,
// INST_LIST_ITER>, these info are tuning and split
// operand/instruction generation
splitDcls[topdcl->getRegVar()].push_front(
make_tuple(bb, dst, 0, instIndex, it));
}
}
}
}
instIndex = 0;
for (auto bb : kernel.fg) {
for (INST_LIST_ITER it = bb->begin(), end = bb->end(); it != end;
++it, ++instIndex) {
G4_INST *inst = (*it);
if (inst->isLifeTimeEnd() || inst->isPseudoKill()) {
continue;
}
//
// process each source operand
//
for (unsigned j = 0, numSrc = inst->getNumSrc(); j < numSrc; j++) {
G4_Operand *src = inst->getSrc(j);
if (src == NULL) {
continue;
}
if (src->isSrcRegRegion()) {
G4_Declare *topdcl = GetTopDclFromRegRegion(src);
if (topdcl && topdcl->getRegFile() != G4_INPUT &&
!topdcl->getAddressed() &&
splitDcls.find(topdcl->getRegVar()) != splitDcls.end() &&
((src->asSrcRegRegion()->getRightBound() -
src->asSrcRegRegion()->getLeftBound() + 1) <
topdcl->getByteSize()) &&
src->asSrcRegRegion()->getRegAccess() ==
Direct) // We don't split the indirect access
{
splitDcls[topdcl->getRegVar()].push_back(
make_tuple(bb, src, j, instIndex, it));
}
}
}
}
}
for (SPLIT_DECL_OPERANDS_ITER it = splitDcls.begin();
it != splitDcls.end();) {
unsigned srcIndex = 0xFFFFFFFF;
unsigned dstIndex = 0;
SPLIT_DECL_OPERANDS_ITER succIt = it;
succIt++;
G4_Declare *topDcl = it->first->getDeclare();
if (topDcl->getByteSize() <= kernel.numEltPerGRF<Type_UB>() * 2u) {
splitDcls.erase(it);
it = succIt;
continue;
}
bool hasSrcOpearnd = false;
for (SPLIT_OPERANDS_ITER vt = it->second.begin(); vt != it->second.end();
vt++) {
G4_BB *bb = nullptr;
G4_Operand *opnd = nullptr;
INST_LIST_ITER instIter;
int pos = 0;
unsigned iIndex = 0;
std::tie(bb, opnd, pos, iIndex, instIter) = (*vt);
if (opnd == nullptr) {
continue;
}
if (opnd->isDstRegRegion()) {
dstIndex = std::max(dstIndex, iIndex);
}
if (opnd->isSrcRegRegion()) {
srcIndex = std::min(srcIndex, iIndex);
hasSrcOpearnd = true;
}
}
if (!hasSrcOpearnd ||
(dstIndex > srcIndex && dstIndex - srcIndex < it->second.size() + 1)) {
splitDcls.erase(it);
it = succIt;
continue;
}
it++;
}
for (SPLIT_DECL_OPERANDS_ITER it = splitDcls.begin(); it != splitDcls.end();
it++) {
G4_Declare *topDcl = it->first->getDeclare();
std::vector<G4_Declare *> splitDclList;
splitDclList.clear();
createSubDcls(kernel, topDcl, splitDclList);
int srcIndex = 0;
for (SPLIT_OPERANDS_ITER vt = it->second.begin(); vt != it->second.end();
vt++) {
G4_BB *bb = nullptr;
G4_Operand *opnd = nullptr;
INST_LIST_ITER instIter;
int pos = 0;
unsigned instIndex = 0;
std::tie(bb, opnd, pos, instIndex, instIter) = (*vt);
if (opnd == nullptr) {
continue;
}
if (opnd->isDstRegRegion()) {
insertMovesToTemp(builder, topDcl, opnd, bb, instIter, splitDclList);
}
if (opnd->isSrcRegRegion()) {
insertMovesFromTemp(kernel, topDcl, srcIndex, opnd, pos, bb, instIter,
splitDclList);
}
srcIndex++;
}
}
return;
}
void VarSplit::localSplit(IR_Builder &builder, G4_BB *bb) {
class CmpRegVarId {
public:
bool operator()(G4_RegVar *first, G4_RegVar *second) const {
return first->getDeclare()->getDeclId() <
second->getDeclare()->getDeclId();
}
};
std::map<G4_RegVar *, std::vector<std::pair<G4_Operand *, INST_LIST_ITER>>,
CmpRegVarId>
localRanges;
std::map<G4_RegVar *, std::vector<std::pair<G4_Operand *, INST_LIST_ITER>>,
CmpRegVarId>::iterator localRangesIt;
std::map<G4_RegVar *, VarRangeListPackage, CmpRegVarId> varRanges;
std::map<G4_RegVar *, VarRangeListPackage, CmpRegVarId>::iterator varRangesIt;
std::stack<VarRange *> toDelete;
// Skip BB if there are no sends.
bool hasSends = std::any_of(bb->begin(), bb->end(),
[](G4_INST *inst) { return inst->isSend(); });
if (!hasSends)
return;
//
// Iterate instruction in BB from back to front
//
for (INST_LIST::reverse_iterator rit = bb->rbegin(), rend = bb->rend();
rit != rend; ++rit) {
G4_INST *i = (*rit);
G4_DstRegRegion *dst = i->getDst();
if (i->isLifeTimeEnd() || i->isPseudoKill()) {
continue;
}
//
// process destination operand
//
if (dst) {
// It's RA candidate
G4_Declare *topdcl = GetTopDclFromRegRegion(dst);
LocalLiveRange *topdclLR = nullptr;
// Local only
if ((topdcl && (topdclLR = gra.getLocalLR(topdcl)) &&
topdcl->getIsRefInSendDcl() && topdclLR->isLiveRangeLocal()) &&
topdcl->getRegFile() == G4_GRF) {
varRangesIt = varRanges.find(topdcl->getRegVar());
INST_LIST_ITER iterToInsert = rit.base();
iterToInsert--; // Point to the iterator of current instruction
if (varRangesIt == varRanges.end()) {
VarRange *new_range = new VarRange;
new_range->leftBound = 0;
new_range->rightBound = topdcl->getByteSize() - 1;
toDelete.push(new_range);
varRanges[topdcl->getRegVar()].list.push_back(new_range);
} else {
rangeListSpliting(&(varRanges[topdcl->getRegVar()].list), dst,
&toDelete);
}
localRanges[topdcl->getRegVar()].emplace_back(
dst, iterToInsert); // Ordered from back to front.
}
}
//
// process each source operand
//
for (unsigned j = 0, numSrc = i->getNumSrc(); j < numSrc; j++) {
G4_Operand *src = i->getSrc(j);
if (src == NULL) {
continue;
}
// Local only
if (src->isSrcRegRegion()) {
G4_Declare *topdcl = GetTopDclFromRegRegion(src);
LocalLiveRange *topdclLR = nullptr;
if (topdcl && (topdclLR = gra.getLocalLR(topdcl)) &&
topdcl->getIsRefInSendDcl() && topdclLR->isLiveRangeLocal() &&
topdcl->getRegFile() == G4_GRF) {
G4_VarBase *base = topdcl->getRegVar();
INST_LIST_ITER iterToInsert = rit.base();
iterToInsert--;
varRangesIt = varRanges.find(base->asRegVar());
if (varRangesIt == varRanges.end()) {
VarRange *new_range = new VarRange;
new_range->leftBound = 0;
new_range->rightBound = topdcl->getByteSize() - 1;
toDelete.push(new_range);
varRanges[topdcl->getRegVar()].list.push_back(new_range);
}
rangeListSpliting(&(varRanges[topdcl->getRegVar()].list), src,
&toDelete);
localRanges[topdcl->getRegVar()].emplace_back(
src, iterToInsert); // Ordered from back to front.
}
}
}
}
// Clean the varaibles without no partial usage, or whose partial live range
// is too short
std::map<G4_RegVar *, VarRangeListPackage>::iterator it = varRanges.begin();
while (it != varRanges.end()) {
std::map<G4_RegVar *, VarRangeListPackage>::iterator succ_it = it;
succ_it++;
// No partial
if (it->second.list.size() <= 1) {
varRanges.erase(it);
it = succ_it;
continue;
}
// If total GRF size divides partial number is less than 16 bytes (half
// GRF), remove it
if (((*it->second.list.rbegin())->rightBound -
(*it->second.list.begin())->leftBound) /
it->second.list.size() <
kernel.numEltPerGRF<Type_UW>() * 2 / 2) {
varRanges.erase(it);
it = succ_it;
continue;
}
G4_Declare *topDcl = it->first->getDeclare();
bool aligned = true;
for (const VarRange *vr : it->second.list) {
unsigned leftBound = vr->leftBound;
unsigned rightBound = vr->rightBound;
int elementSize =
topDcl->getElemSize() > G4_WSIZE ? topDcl->getElemSize() : G4_WSIZE;
unsigned short elemsNum = (rightBound - leftBound + 1) / elementSize;
if (!elemsNum) {
aligned = false;
break;
}
// TODO: we can merge serveral unaligned sub declares into one aligned.
// Such as [0-1], [2-63] --> [0-63]
if (leftBound % kernel.numEltPerGRF<Type_UW>() ||
(rightBound + 1) % kernel.numEltPerGRF<Type_UW>()) {
aligned = false;
break;
}
}
if (!aligned) {
varRanges.erase(it);
it = succ_it;
continue;
}
it = succ_it;
}
int splitid = 0;
for (std::map<G4_RegVar *, VarRangeListPackage>::iterator it =
varRanges.begin();
it != varRanges.end(); it++) {
G4_Declare *topDcl = it->first->getDeclare();
const char *dclName = topDcl->getName();
topDcl->setIsSplittedDcl(true);
// Vertical split: varaible split
unsigned splitVarNum = 0;
unsigned pre_rightBound = 0;
for (VAR_RANGE_LIST_ITER vt = it->second.list.begin();
vt != it->second.list.end(); vt++) {
unsigned leftBound = (*vt)->leftBound;
unsigned rightBound = (*vt)->rightBound;
int elementSize =
topDcl->getElemSize() > G4_WSIZE ? topDcl->getElemSize() : G4_WSIZE;
unsigned short elemsNum = (rightBound - leftBound + 1) / elementSize;
if (!elemsNum) {
vASSERT(false);
pre_rightBound = rightBound;
continue;
}
if (leftBound && pre_rightBound + 1 != leftBound) {
vASSERT(false);
}
pre_rightBound = rightBound;
std::stringstream nameStrm;
nameStrm << dclName << "_" << splitid << "_" << leftBound << "_"
<< rightBound << std::ends;
int nameLen = unsigned(nameStrm.str().length()) + 1;
const char *name = builder.getNameString(nameLen, "%s_%d_%d_%d", dclName,
splitid, leftBound, rightBound);
unsigned short dclWidth = 0;
unsigned short dclHeight = 0;
int dclTotalSize = 0;
getHeightWidth(topDcl->getElemType(),
(rightBound - leftBound + 1) / topDcl->getElemSize(),
dclWidth, dclHeight, dclTotalSize);
G4_Declare *partialDcl = builder.createDeclare(
name, G4_GRF, dclWidth, dclHeight, topDcl->getElemType());
gra.setSubOffset(partialDcl, leftBound);
partialDcl->setIsPartialDcl(true);
gra.setSplittedDeclare(partialDcl, topDcl);
unsigned nElementSize =
(rightBound - leftBound + 1) / topDcl->getElemSize();
if ((rightBound - leftBound + 1) % topDcl->getElemSize()) {
nElementSize++;
}
partialDcl->setTotalElems(nElementSize);
gra.addSubDcl(topDcl, partialDcl);
splitVarNum++;
VISA_DEBUG_VERBOSE(std::cout << "==> Sub Declare: " << splitid
<< "::" << name << "\n");
splitid++;
}
if (splitVarNum) {
gra.setSplitVarNum(topDcl, splitVarNum);
}
}
while (toDelete.size() > 0) {
delete toDelete.top();
toDelete.pop();
}
return;
}
void GlobalRA::addrRegAlloc() {
uint32_t addrSpillId = 0;
unsigned maxRAIterations = builder.getuint32Option(vISA_MaxRAIterations);
unsigned iterationNo = 0;
while (iterationNo < maxRAIterations) {
RA_TRACE(std::cout << "--address RA iteration " << iterationNo << "\n");
//
// choose reg vars whose reg file kind is ARF
//
LivenessAnalysis liveAnalysis(*this, G4_ADDRESS);
liveAnalysis.computeLiveness();
//
// if no reg var needs to reg allocated, then skip reg allocation
//
if (liveAnalysis.getNumSelectedVar() > 0) {
GraphColor coloring(liveAnalysis, false, false);
if (!coloring.regAlloc(false, false, nullptr)) {
SpillManager spillARF(*this, coloring.getSpilledLiveRanges(),
addrSpillId);
spillARF.insertSpillCode();
addrSpillId = spillARF.getNextTempDclId();
//
// if new addr temps are created, we need to do RA again so that newly
// created temps can get registers. If there are no more newly created
// temps, we then commit reg assignments
//
if (spillARF.isAnyNewTempCreated() == false) {
coloring.confirmRegisterAssignments();
coloring.cleanupRedundantARFFillCode();
if ((builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc())) {
coloring.addA0SaveRestoreCode();
}
break; // no more new addr temps; done with ARF allocation
}
} else // successfully allocate register without spilling
{
coloring.confirmRegisterAssignments();
coloring.cleanupRedundantARFFillCode();
if ((builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc())) {
coloring.addA0SaveRestoreCode();
}
VISA_DEBUG_VERBOSE(detectUndefinedUses(liveAnalysis, kernel));
break; // done with ARF allocation
}
} else {
break; // no ARF allocation needed
}
kernel.dumpToFile("after.Address_RA." + std::to_string(iterationNo));
iterationNo++;
}
// Addr spill/fill
addVarToRA(kernel.Declares.back());
vISA_ASSERT(iterationNo < maxRAIterations, "Address RA has failed.");
}
void GlobalRA::flagRegAlloc() {
uint32_t flagSpillId = 0;
unsigned maxRAIterations = builder.getuint32Option(vISA_MaxRAIterations);
uint32_t iterationNo = 0;
bool spillingFlag = false;
while (iterationNo < maxRAIterations) {
RA_TRACE(std::cout << "--flag RA iteration " << iterationNo << "\n");
//
// choose reg vars whose reg file kind is FLAG
//
LivenessAnalysis liveAnalysis(*this, G4_FLAG);
liveAnalysis.computeLiveness();
//
// if no reg var needs to reg allocated, then skip reg allocation
//
if (liveAnalysis.getNumSelectedVar() > 0) {
GraphColor coloring(liveAnalysis, false, false);
if (!coloring.regAlloc(false, false, nullptr)) {
SpillManager spillFlag(*this, coloring.getSpilledLiveRanges(),
flagSpillId);
spillFlag.insertSpillCode();
VISA_DEBUG_VERBOSE({
printf("FLAG Spill inst count: %d\n",
spillFlag.getNumFlagSpillStore());
printf("FLAG Fill inst count: %d\n", spillFlag.getNumFlagSpillLoad());
printf("*************************\n");
});
flagSpillId = spillFlag.getNextTempDclId();
spillingFlag = true;
if (spillFlag.isAnyNewTempCreated() == false) {
coloring.confirmRegisterAssignments();
if ((builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc())) {
coloring.addFlagSaveRestoreCode();
}
break;
}
builder.getJitInfo()->stats.numFlagSpillStore +=
spillFlag.getNumFlagSpillStore();
builder.getJitInfo()->stats.numFlagSpillLoad +=
spillFlag.getNumFlagSpillLoad();
} else // successfully allocate register without spilling
{
coloring.confirmRegisterAssignments();
if ((builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc())) {
coloring.addFlagSaveRestoreCode();
}
if (spillingFlag && builder.getOption(vISA_FlagSpillCodeCleanup)) {
CLEAN_NUM_PROFILE clean_num_profile;
FlagSpillCleanup f(*this);
f.spillFillCodeCleanFlag(builder, kernel, &clean_num_profile);
#ifdef DEBUG_VERBOSE_ON1
for (int i = 0; i < 3; i++) {
printf("Profiler %d Spill clean: %d\n", i,
clean_num_profile.spill_clean_num[i]);
printf("Profiler %d Fill clean: %d\n", i,
clean_num_profile.fill_clean_num[i]);
clean_num += clean_num_profile.spill_clean_num[i];
clean_num += clean_num_profile.fill_clean_num[i];
}
printf("**Flag clean num: %d\n", clean_num);
#endif
}
VISA_DEBUG_VERBOSE(detectUndefinedUses(liveAnalysis, kernel));
break; // done with FLAG allocation
}
} else {
break; // no FLAG allocation needed
}
kernel.dumpToFile("after.Flag_RA." + std::to_string(iterationNo));
iterationNo++;
}
// Flag spill/fill
addVarToRA(kernel.Declares.back());
vISA_ASSERT(iterationNo < maxRAIterations, "Flag RA has failed.");
}
void GlobalRA::scalarRegAlloc() {
uint32_t scalarSpillId = 0;
unsigned maxRAIterations = builder.getuint32Option(vISA_MaxRAIterations);
unsigned iterationNo = 0;
std::set<G4_Declare *> PreAssigned;
for (auto dcl : kernel.Declares) {
if (dcl->getRegFile() == G4_SCALAR) {
auto regVar = dcl->getRegVar();
if (regVar->isS0())
PreAssigned.insert(dcl);
}
}
while (iterationNo < maxRAIterations) {
RA_TRACE(std::cout << "--scalar RA iteration " << iterationNo << "\n");
//
// choose reg vars whose reg file kind is ARF
//
LivenessAnalysis liveAnalysis(*this, G4_SCALAR);
liveAnalysis.computeLiveness();
//
// if no reg var needs to reg allocated, then skip reg allocation
//
if (liveAnalysis.getNumSelectedVar() > 0) {
GraphColor coloring(liveAnalysis, false, false);
if (!coloring.regAlloc(false, false, nullptr)) {
SpillManager spillScalar(*this, coloring.getSpilledLiveRanges(),
scalarSpillId);
spillScalar.insertSpillCode();
scalarSpillId = spillScalar.getNextTempDclId();
//
// if new scalar temps are created, we need to do RA again so that newly
// created temps can get registers. If there are no more newly created
// temps, we then commit reg assignments
//
if (spillScalar.isAnyNewTempCreated() == false) {
coloring.confirmRegisterAssignments();
if ((builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc())) {
vASSERT(false &&
"missing code"); // coloring.addA0SaveRestoreCode();
}
break; // no more new scalar temps; done with scalar allocation
}
} else // successfully allocate register without spilling
{
coloring.confirmRegisterAssignments();
if ((builder.kernel.fg.getHasStackCalls() ||
builder.kernel.fg.getIsStackCallFunc())) {
vASSERT(false && "missing code"); // coloring.addA0SaveRestoreCode();
}
VISA_DEBUG_VERBOSE(detectUndefinedUses(liveAnalysis, kernel));
break; // done with scalar allocation
}
} else {
break; // no scalar allocation needed
}
iterationNo++;
}
kernel.dumpToFile("after.Scalar_RA." + std::to_string(iterationNo));
constexpr unsigned ScalarRegisterGRFBase = 96;
// change scalar-register assignment back to fixed GRF location so that
// the code can be simulated on platform without scalar pipe
for (G4_Declare *dcl : kernel.Declares) {
if (dcl->getRegFile() == G4_SCALAR && !PreAssigned.count(dcl)) {
auto regVar = dcl->getRegVar();
if (regVar->isS0()) {
auto offset = regVar->getPhyRegOff() * dcl->getElemSize();
unsigned int regNum = offset / builder.getGRFSize();
unsigned int subRegNum =
(offset % builder.getGRFSize()) / dcl->getElemSize();
regVar->setPhyReg(regPool.getGreg(regNum + ScalarRegisterGRFBase),
subRegNum);
dcl->setRegFile(G4_GRF);
}
}
}
kernel.dumpToFile("after.Scalar_Rename." + std::to_string(iterationNo));
vISA_ASSERT(iterationNo < maxRAIterations, "Scalar RA has failed.");
}
void GlobalRA::assignRegForAliasDcl() {
//
// assign Reg for Alias DCL
//
for (G4_Declare *dcl : kernel.Declares) {
G4_RegVar *AliasRegVar;
G4_RegVar *CurrentRegVar;
unsigned tempoffset;
if (dcl->getAliasDeclare() != NULL) {
AliasRegVar = dcl->getAliasDeclare()->getRegVar();
CurrentRegVar = dcl->getRegVar();
tempoffset = AliasRegVar->getPhyRegOff() *
AliasRegVar->getDeclare()->getElemSize() +
dcl->getAliasOffset();
if (AliasRegVar->getPhyReg() != NULL) {
//
// alias register assignment for A0
//
if (CurrentRegVar->getDeclare()->useGRF()) {
// if the tempoffset is one grf
if (tempoffset < kernel.numEltPerGRF<Type_UW>() * 2u) {
CurrentRegVar->setPhyReg(
AliasRegVar->getPhyReg(),
tempoffset / CurrentRegVar->getDeclare()->getElemSize());
}
// tempoffset covers several GRFs
else {
unsigned addtionalrow =
tempoffset / (kernel.numEltPerGRF<Type_UW>() * 2);
unsigned actualoffset =
tempoffset % (kernel.numEltPerGRF<Type_UW>() * 2);
bool valid = false;
unsigned orignalrow = AliasRegVar->ExRegNum(valid);
vISA_ASSERT(valid == true, ERROR_REGALLOC);
CurrentRegVar->setPhyReg(
regPool.getGreg(orignalrow + addtionalrow),
actualoffset / CurrentRegVar->getDeclare()->getElemSize());
}
} else if (CurrentRegVar->getDeclare()->getRegFile() == G4_ADDRESS) {
vISA_ASSERT(tempoffset < builder.getNumAddrRegisters() * 2,
ERROR_REGALLOC); // Must hold tempoffset in one A0 reg
CurrentRegVar->setPhyReg(
AliasRegVar->getPhyReg(),
tempoffset / CurrentRegVar->getDeclare()->getElemSize());
} else if (CurrentRegVar->getDeclare()->getRegFile() == G4_SCALAR) {
if (builder.getuint32Option(vISA_ScalarPipe))
vISA_ASSERT(tempoffset < kernel.getSRFInWords() *2,
ERROR_REGALLOC);
else
vISA_ASSERT(tempoffset < builder.getScalarRegisterSizeInBytes(),
ERROR_REGALLOC);
CurrentRegVar->setPhyReg(
AliasRegVar->getPhyReg(),
tempoffset / CurrentRegVar->getDeclare()->getElemSize());
} else {
vISA_ASSERT(false, ERROR_REGALLOC);
}
} else {
if (dcl->isSpilled() == false)
dcl->setSpillFlag();
}
}
}
return;
}
void GlobalRA::removeSplitDecl() {
for (auto dcl : kernel.Declares) {
if (!getSubDclList(dcl).empty()) {
clearSubDcl(dcl);
dcl->setIsSplittedDcl(false);
}
}
kernel.Declares.erase(
std::remove_if(kernel.Declares.begin(), kernel.Declares.end(),
[](G4_Declare *dcl) { return dcl->getIsPartialDcl(); }),
kernel.Declares.end());
}
void GlobalRA::fastRADecision()
{
if (builder.getOption(vISA_SelectiveFastRA)) {
unsigned instNum = 0;
for (auto bb : kernel.fg) {
instNum += (int)bb->size();
}
if (instNum > builder.getOptions()->getuInt32Option(vISA_SelectiveRAInstThreshold)) {
useFastRA = true;
useHybridRAwithSpill = true;
} else {
useFastRA = false;
useHybridRAwithSpill = false;
}
RA_TRACE(std::cout << "\t--SelectiveFastRA decision: " << useFastRA << "\n");
} else {
useFastRA = builder.getOption(vISA_FastCompileRA);
useHybridRAwithSpill = builder.getOption(vISA_HybridRAWithSpill);
}
}
bool GlobalRA::tryHybridRA() {
copyMissingAlignment();
BankConflictPass bc(*this, false);
LocalRA lra(bc, *this);
if (lra.localRA()) {
return true;
}
if (useHybridRAwithSpill) {
insertPhyRegDecls();
} else {
if (hybridRA(lra)) {
return true;
}
}
return false;
}
bool GlobalRA::hybridRA(LocalRA &lra) {
RA_TRACE(std::cout << "--hybrid RA--\n");
uint32_t numOrigDcl = (uint32_t)kernel.Declares.size();
insertPhyRegDecls();
LivenessAnalysis liveAnalysis(*this, G4_GRF | G4_INPUT);
liveAnalysis.computeLiveness();
if (liveAnalysis.getNumSelectedVar() > 0) {
RPE rpe(*this, &liveAnalysis);
rpe.run();
bool spillLikely =
kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
rpe.getMaxRP() >= kernel.getNumRegTotal() - 16;
if (spillLikely) {
RA_TRACE(std::cout << "\t--skip hybrid RA due to high pressure: "
<< rpe.getMaxRP() << "\n");
kernel.Declares.resize(numOrigDcl);
lra.undoLocalRAAssignments(false);
// We check src/dst overlap WA because here to keep intf graph simple.
// When LRA is run, it sets augmentation alignment conservatively so
// that LRA assignments can co-exist with HRA assignments after
// augmentation is run. If we reset alignment here, it means that
// augmentation buckets are reset and alignment is copied over
// from original G4_Declare. This is correct behavior. However, when
// avoidSrcDstOverlap WA sees that src/dst of an instruction have no
// alignment, it forces an interference edge between them. This causes
// extra interferences in graph compared to case when we use conservative
// alignment computed in LRA. So when the WA is enabled, we avoid
// resetting alignment as it may produce better code.
if (!builder.avoidDstSrcOverlap() || use4GRFAlign)
copyAlignment();
return false;
}
GraphColor coloring(liveAnalysis, /*isHybrid*/ true, /*forceSpill*/ false);
generateForbiddenTemplates(0);
// FIXME: doBankConflictReduction and highInternalConflict are computed by
// local RA, they should be moved to some common code.
bool isColoringGood =
coloring.regAlloc(lra.doHybridBCR(), lra.hasHighInternalBC(), &rpe);
if (!isColoringGood) {
if (!kernel.getOption(vISA_Debug)) {
// Why?? Keep LRA results when -debug is passed
kernel.Declares.resize(numOrigDcl);
lra.undoLocalRAAssignments(false);
}
// Restore alignment in case LRA modified it
copyAlignment();
return false;
}
coloring.confirmRegisterAssignments();
if (kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc()) {
coloring.getSaveRestoreRegister();
addSaveRestoreCode(0);
}
if (verifyAugmentation) {
assignRegForAliasDcl();
verifyAugmentation->verify();
}
}
kernel.setRAType(lra.doHybridBCR() ? RA_Type::HYBRID_BC_RA
: RA_Type::HYBRID_RA);
return true;
}
//
// change single-element dcl for G4_GRF to G4_SCALAR
//
void GlobalRA::selectScalarCandidates() {
// collect root-declares that may be changed to scalar
std::set<G4_Declare *> candidates;
for (auto bb : kernel.fg) {
for (auto inst : *bb) {
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getTopDcl()) {
auto rootDcl = dst->getTopDcl();
if (rootDcl->getRegFile() == G4_GRF && !candidates.count(rootDcl) &&
rootDcl->getNumRows() <= 1) {
bool isNoMaskInst =
(inst->isWriteEnableInst() || bb->isAllLaneActive());
if (inst->getExecSize() == g4::SIMD1 && isNoMaskInst) {
candidates.insert(rootDcl);
}
}
}
}
}
// filter candidates that we cannot handle
std::set<G4_Declare *> multiUseInputs;
std::set<G4_Declare *> visitedInputs;
for (auto bb : kernel.fg) {
for (auto inst : *bb) {
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getTopDcl()) {
auto rootDcl = dst->getTopDcl();
if (candidates.count(rootDcl)) {
// when there is only one SRF, it is unrealistic to allow
// send to write to SRF
if (inst->isSend() && kernel.getSRFInWords()*2
<= builder.getScalarRegisterSizeInBytes()) {
candidates.erase(rootDcl);
}
bool isNoMaskInst =
(inst->isWriteEnableInst() || bb->isAllLaneActive());
// all writes to that top-dcl have to be simd1-nomask
if (!(inst->getExecSize() == g4::SIMD1 && isNoMaskInst)) {
candidates.erase(rootDcl);
}
}
}
// when there is only one SRF, it is also unrealistic to allow
// SRF as regular send source because it has to be 64-byte aligned
if (inst->isSend() && kernel.getSRFInWords() * 2 <=
builder.getScalarRegisterSizeInBytes()) {
for (int i = 0; i < inst->getNumSrc(); i++) {
auto src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion())
continue;
auto srcDcl = src->getTopDcl();
if (srcDcl && candidates.count(srcDcl))
candidates.erase(srcDcl);
}
}
// Also find all the input dcls that is used inside a loop,
// or used more than once. Skip moves and sends
if (inst->isRawMov() || inst->isSend())
continue;
for (int i = 0; i < inst->getNumSrc(); i++) {
auto src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion())
continue;
G4_SrcRegRegion *origSrc = src->asSrcRegRegion();
auto srcDcl = src->getTopDcl();
if (srcDcl && srcDcl->getRegFile() == G4_INPUT &&
srcDcl->getTotalElems() == 1 && origSrc && origSrc->isScalar()) {
// mark multi-use
if (bb->getNestLevel() > 0)
multiUseInputs.insert(srcDcl);
else if (visitedInputs.find(srcDcl) != visitedInputs.end())
multiUseInputs.insert(srcDcl);
// mark any use
visitedInputs.insert(srcDcl);
}
}
}
}
// update declares
for (auto dcl : kernel.Declares) {
auto rootDcl = dcl->getRootDeclare();
if (candidates.count(rootDcl)) {
dcl->setRegFile(G4_SCALAR);
}
}
G4_BB *entryBB = kernel.fg.getEntryBB();
auto insertIt = entryBB->begin();
for (INST_LIST_ITER IB = entryBB->end(); insertIt != IB; ++insertIt) {
G4_INST *tI = (*insertIt);
if (tI->isFlowControl() || tI == entryBB->back())
break;
}
std::map<G4_Declare *, G4_Declare *> inputMap;
for (auto bb : kernel.fg) {
INST_LIST_ITER it = bb->begin(), iEnd = bb->end();
INST_LIST_ITER next_iter = it;
for (; it != iEnd; it = next_iter) {
++next_iter;
G4_INST *inst = *it;
// skip moves and sends
if (inst->isRawMov() || inst->isSend())
continue;
// Add move for scalar-iput with multiple-uses to save power.
// The move should be inserted into the entry-block before the first use.
for (int i = 0; i < inst->getNumSrc(); i++) {
auto src = inst->getSrc(i);
if (!src || !src->isSrcRegRegion())
continue;
G4_SrcRegRegion *origSrc = src->asSrcRegRegion();
auto srcDcl = src->getTopDcl();
if (srcDcl && origSrc && origSrc->isScalar() &&
multiUseInputs.find(srcDcl) != multiUseInputs.end()) {
vISA_ASSERT(!candidates.count(srcDcl),
"input-variable cannot be a scalar candidate");
// insert a move to a scalar-register candidate
auto subAlign = Get_G4_SubRegAlign_From_Size(
(uint16_t)origSrc->getElemSize(), builder.getPlatform(),
builder.getGRFAlign());
G4_Declare *tmpDcl = nullptr;
G4_SrcModifier modifier = origSrc->getModifier();
if (inputMap.find(srcDcl) != inputMap.end())
tmpDcl = inputMap[srcDcl];
else {
// create dcl for scalar
tmpDcl =
builder.createTempVar(g4::SIMD1, origSrc->getType(), subAlign);
tmpDcl->setRegFile(G4_SCALAR);
candidates.insert(tmpDcl);
inputMap[srcDcl] = tmpDcl;
addVarToRA(tmpDcl);
// create mov
origSrc->setModifier(Mod_src_undef);
G4_DstRegRegion *dst = builder.createDstRegRegion(tmpDcl, 1);
G4_INST *movInst = builder.createMov(g4::SIMD1, dst, origSrc,
InstOpt_WriteEnable, false);
// insert mov
if (bb == entryBB)
bb->insertBefore(it, movInst);
else
entryBB->insertBefore(insertIt, movInst);
}
G4_SrcRegRegion *newSrc = builder.createSrcRegRegion(
modifier, Direct, tmpDcl->getRegVar(), 0, 0,
builder.getRegionScalar(), tmpDcl->getElemType());
inst->setSrc(newSrc, i);
}
}
}
}
// flag and address spill location now should be scalar registers.
// scalar registers can be spilled into GRF
// need this? addrFlagSpillDcls.clear();
kernel.dumpToFile("after.select_scalar.");
}
std::pair<unsigned, unsigned> GlobalRA::reserveGRFSpillReg(GraphColor &coloring) {
coloring.markFailSafeIter(true);
unsigned spillRegSize = 0;
unsigned indrSpillRegSize = 0;
if (kernel.getOption(vISA_NewFailSafeRA)) {
spillRegSize = getNumReservedGRFs();
} else {
determineSpillRegSize(spillRegSize, indrSpillRegSize);
}
if (builder.usesStack())
vISA_ASSERT(spillRegSize + indrSpillRegSize <
kernel.stackCall.getNumCalleeSaveRegs(),
"Invalid reserveSpillSize in fail-safe RA!");
coloring.setReserveSpillGRFCount(spillRegSize + indrSpillRegSize);
return std::make_pair(spillRegSize, indrSpillRegSize);
}
void GraphColor::preAssignSpillHeader() {
// If spill header is used for spill/fill offset, it must have infinite spill
// cost. When running fail safe RA, if we assign this range to middle of free
// GRF space, it could cause fragmentation and other spilled ranges may not
// get an allocation. So, we pre-assign this variable at first candidate GRF
// to avoid fragmentation. This is relevant only in fail safe RA iteration.
if (!builder.hasValidSpillFillHeader())
return;
std::vector<bool> FreeGRFs(kernel.getNumRegTotal(), true);
auto *spillHeader = builder.getSpillFillHeader();
if (spillHeader->getRegVar()->getPhyReg())
return;
unsigned spillHeaderId = spillHeader->getRootDeclare()->getRegVar()->getId();
// Compute free GRFs
const auto *intf = getIntf();
for (auto neighbor : intf->getSparseIntfForVar(spillHeaderId)) {
auto *neighborLR = getLiveRanges()[neighbor];
auto *neighborGRF = neighborLR->getPhyReg();
if (!neighborGRF)
continue;
unsigned int neighborGRFStart = neighborGRF->asGreg()->getRegNum();
unsigned int neighborLastGRF =
neighborGRFStart + neighborLR->getNumRegNeeded();
for (unsigned int i = neighborGRFStart; i != neighborLastGRF; ++i) {
FreeGRFs[i] = false;
}
}
// Find a GRF r1 onwards that can be pre-assigned to spillHeader.
// r0 is usually reserved.
for (unsigned int i = 1; i != FreeGRFs.size(); ++i) {
if (FreeGRFs[i]) {
// Attach assignment to temp LR and to G4_RegVar
getLiveRanges()[spillHeaderId]->setPhyReg(regPool.getGreg(i), 0);
spillHeader->getRegVar()->setPhyReg(regPool.getGreg(i), 0);
// Decrement counter as this is used later in determineColorOrdering
liveAnalysis.reduceNumUnassignedVar();
break;
}
}
}
// pre-allocate the bits for forbidden registers which will not be used in
// register assignment.
// Note that the order of the calls matters, as all RCs inherit from RESERVEDGRF
// for example.
void GlobalRA::generateForbiddenTemplates(unsigned reserveSpillSize) {
fbdRegs.generateReservedGRFForbidden(reserveSpillSize);
fbdRegs.generateCallerSaveGRFForbidden();
fbdRegs.generateCalleeSaveGRFForbidden();
fbdRegs.generateEOTGRFForbidden();
fbdRegs.generateLastGRFForbidden();
fbdRegs.generateEOTLastGRFForbidden();
}
//
// Create variables will be used in fail safe RA
//
void GlobalRA::createVariablesForHybridRAWithSpill() {
// To conduct fail safe in iteration 0, some variables need be allocated
// first so that they can join RA and be used in the spill/fill directly.
addVarToRA(builder.getSpillFillHeader());
addVarToRA(builder.getOldA0Dot2Temp());
if (builder.hasScratchSurface() && !builder.getSpillSurfaceOffset()) {
vISA_ASSERT(builder.instList.empty(),
"Inst list should be empty at this point before creating "
"instruction that initializes SSO");
builder.initScratchSurfaceOffset();
addVarToRA(builder.getSpillSurfaceOffset());
if (!builder.instList.empty()) {
// If SSO is not yet initialized, insert the created
// instruction into the entry BB.
auto entryBB = builder.kernel.fg.getEntryBB();
auto iter = std::find_if(entryBB->begin(), entryBB->end(),
[](G4_INST *inst) { return !inst->isLabel(); });
entryBB->splice(iter, builder.instList);
}
}
// BuiltinR0 may be spilled which is not allowed.
// FIXME: BuiltinR0 spill cost has been set to MAX already,
// keep spilling means there is some issue in cost model
builder.getBuiltinR0()->setLiveOut();
builder.getBuiltinR0()->getRegVar()->setPhyReg(builder.phyregpool.getGreg(0),
0);
}
void GlobalRA::initSRAsScratch() const {
// Verify old scratch dcl assignment before changing it
vISA_ASSERT(kernel.fg.scratchRegDcl->getRegVar()
->getPhyReg()
->asGreg()
->getRegNum() == kernel.stackCall.getSpillHeaderGRF(),
"unexpected assignment");
vISA_ASSERT(kernel.stackCall.getSpillHeaderGRF() ==
kernel.stackCall.getFPSPGRF(),
"expecting same GRF");
// Use last caller save GRF for spill/fill addr computation. Since this
// address is used as LSC header, we must use 0th sub-reg of reserved
// GRF.
kernel.fg.scratchRegDcl->getRegVar()->setPhyReg(
regPool.getGreg(kernel.stackCall.getCallerSaveLastGRF()), 0);
// Mark SR assignment as reserved so other variables don't try to
// use it.
kernel.fg.reserveSR = true;
}
void GlobalRA::stackCallSaveRestore(bool hasStackCall) {
//
// If the graph has stack calls, then add the caller-save/callee-save pseudo
// declares and code. This currently must be done after flag/addr RA due to
// the assumption about the location of the pseudo save/restore instructions
//
if (hasStackCall) {
addCallerSavePseudoCode();
// Only GENX sub-graphs require callee-save code.
if (builder.getIsKernel() == false) {
storeCEInProlog();
addCalleeSavePseudoCode();
addStoreRestoreToReturn();
}
if (!kernel.getOption(vISA_PreserveR0InR0)) {
// bind builtinR0 to the reserved stack call ABI GRF so that caller and
// callee can agree on which GRF to use for r0
builder.getBuiltinR0()->getRegVar()->setPhyReg(
builder.phyregpool.getGreg(kernel.stackCall.getThreadHeaderGRF()), 0);
}
}
}
int GlobalRA::doGlobalLinearScanRA() {
copyMissingAlignment();
BankConflictPass bc(*this, false);
LivenessAnalysis liveAnalysis(*this, G4_GRF | G4_INPUT);
liveAnalysis.computeLiveness();
TIME_SCOPE(LINEARSCAN_RA);
LinearScanRA lra(bc, *this, liveAnalysis);
int ret = lra.doLinearScanRA();
if (ret == VISA_SUCCESS) {
expandSpillFillIntrinsics(nextSpillOffset);
assignRegForAliasDcl();
if (builder.getOption(vISA_verifyLinearScan)) {
resetGlobalRAStates();
markGraphBlockLocalVars();
LivenessAnalysis live(*this, G4_GRF | G4_INPUT, false, true);
live.computeLiveness();
GraphColor coloring(live, false, false);
coloring.createLiveRanges();
Interference intf(&live, *this);
intf.init();
intf.computeInterference();
if (kernel.getOption(vISA_DumpRAIntfGraph))
intf.dumpInterference();
intf.linearScanVerify();
}
return VISA_SUCCESS;
}
return ret;
}
void GlobalRA::incRABookKeeping() {
// Reset state of incremental RA here as we move from hybrid RA
// to global RA. Note that when moving from flag->address or from
// address->GRF RA, we don't need to explicitly reset state because
// incremental RA can deduce we're moving to RA for different
// variable class. But it cannot deduce so when moving from hybrid
// to global RA.
incRA.moveFromHybridToGlobalGRF();
// This part makes incremental RA a non-NFC change. The reason we need
// to do this is because variables that spill intrinsics use may end up
// getting extended in each RA iteration. Given that those variables
// are either r0 or scalars, we mark them as Output here so they're
// live-out throughout. To make this an NFC change, we can enable this
// block even when incremental RA is not enabled.
if (incRA.isEnabled()) {
builder.getBuiltinR0()->getRootDeclare()->setLiveOut();
builder.getSpillFillHeader();
bool initSS = builder.hasScratchSurface();
if (initSS) {
builder.initScratchSurfaceOffset();
builder.getOldA0Dot2Temp();
}
}
}
std::pair<bool, bool> GlobalRA::remat(bool fastCompile, bool rematDone,
LivenessAnalysis &liveAnalysis,
GraphColor &coloring, RPE &rpe) {
bool runRemat = kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_CM
? true
: kernel.getSimdSize() < kernel.numEltPerGRF<Type_UB>();
// -noremat takes precedence over -forceremat
bool rematOn = !kernel.getOption(vISA_Debug) &&
!kernel.getOption(vISA_NoRemat) &&
!kernel.getOption(vISA_FastSpill) && !fastCompile &&
(kernel.getOption(vISA_ForceRemat) || runRemat);
if (!rematDone && rematOn) {
RA_TRACE(std::cout << "\t--rematerialize\n");
Rematerialization remat(kernel, liveAnalysis, coloring, rpe, *this);
remat.run();
// Re-run GRA loop only if remat caused changes to IR
return std::make_pair(remat.getChangesMade(), true);
}
return std::make_pair(false, rematDone);
}
std::tuple<bool, bool, bool>
GlobalRA ::alignedScalarSplit(bool fastCompile, bool alignedScalarSplitDone,
GraphColor &coloring) {
bool isEarlyExit = false;
if (kernel.getOption(vISA_SplitGRFAlignedScalar) && !fastCompile &&
!kernel.getOption(vISA_FastSpill) && !alignedScalarSplitDone) {
SplitAlignedScalars split(*this, coloring);
split.run();
// Re-run GRA loop if changes were made to IR
bool rerunGRA = split.getChangesMade();
kernel.dumpToFile("after.Split_Aligned_Scalar." +
std::to_string(getIterNo()));
#ifndef DLL_MODE
if (stopAfter("Split_Aligned_Scalar")) {
isEarlyExit = true;
}
#endif // DLL_MODE
return std::make_tuple(rerunGRA, true, isEarlyExit);
}
return std::make_tuple(false, alignedScalarSplitDone, false);
}
bool GlobalRA::globalSplit(VarSplit& splitPass, GraphColor& coloring) {
unsigned int sendAssociatedGRFSpillFillCount = 0;
// Calculate the spill caused by send to decide if global splitting is
// required or not
for (auto spilled : coloring.getSpilledLiveRanges()) {
auto spillDcl = spilled->getDcl();
if (spillDcl->getIsRefInSendDcl() && spillDcl->getNumRows() > 1) {
sendAssociatedGRFSpillFillCount += spilled->getRefCount();
}
}
if (getIterNo() ==
0 && // Only works when first iteration of Global RA failed.
!splitPass.didGlobalSplit && // Do only one time.
splitPass.canDoGlobalSplit(builder, kernel,
sendAssociatedGRFSpillFillCount)) {
RA_TRACE(std::cout << "\t--global send split\n");
splitPass.globalSplit(builder, kernel);
splitPass.didGlobalSplit = true;
// TODO: Since global split is rarely enabled, for now we skip
// incremental RA whenever it is enabled.
incRA.skipIncrementalRANextIter();
return true;
}
return false;
}
void GlobalRA::localSplit(bool fastCompile, VarSplit& splitPass) {
// Do variable splitting in each iteration
// Don't do when fast compile is required
if (builder.getOption(vISA_LocalDeclareSplitInGlobalRA) && !fastCompile) {
RA_TRACE(std::cout << "\t--split local send--\n");
for (auto bb : kernel.fg) {
splitPass.localSplit(builder, bb);
}
}
}
std::pair<bool, bool> GlobalRA::bankConflict() {
bool doBankConflictReduction = false, highInternalConflict = false;
if (builder.getOption(vISA_LocalBankConflictReduction) &&
builder.hasBankCollision()) {
bool reduceBCInRR = false;
bool reduceBCInTAandFF = false;
BankConflictPass bc(*this, true);
reduceBCInRR = bc.setupBankConflictsForKernel(
true, reduceBCInTAandFF, SECOND_HALF_BANK_START_GRF * 2,
highInternalConflict);
doBankConflictReduction = reduceBCInRR && reduceBCInTAandFF;
}
return std::make_pair(doBankConflictReduction, highInternalConflict);
}
bool GlobalRA::setupFailSafeIfNeeded(bool fastCompile, bool hasStackCall,
unsigned int maxRAIterations,
unsigned int failSafeRAIteration) {
bool reserveSpillReg = false;
bool allowAddrTaken = builder.getOption(vISA_FastSpill) || fastCompile ||
!kernel.getHasAddrTaken();
if (builder.getOption(vISA_FailSafeRA) &&
kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
kernel.getNumRegTotal() > 32 &&
!hasStackCall &&
((getIterNo() == maxRAIterations - 1) ||
(allowAddrTaken && getIterNo() == failSafeRAIteration))) {
RA_TRACE(std::cout << "\t--enable failSafe RA\n");
reserveSpillReg = true;
if (incRA.isEnabled()) {
incRA.skipIncrementalRANextIter();
}
if (builder.hasScratchSurface() && !hasStackCall) {
// Since this is fail safe RA iteration, we ensure the 2 special
// variables are created before coloring so spill code can use
// them, if needed.
auto a0Dot2Temp = kernel.fg.builder->getOldA0Dot2Temp();
addVarToRA(a0Dot2Temp);
if (builder.supportsLSC()) {
auto spillFillHdr = kernel.fg.builder->getSpillFillHeader();
addVarToRA(spillFillHdr);
}
}
}
return reserveSpillReg;
}
void GlobalRA::undefinedUses(bool rematDone, LivenessAnalysis& liveAnalysis) {
if (builder.getOption(vISA_DumpUndefUsesFromLiveness) && getIterNo() == 0 &&
!rematDone) {
liveAnalysis.reportUndefinedUses();
}
}
void GlobalRA::writeVerboseStatsNumVars(LivenessAnalysis &liveAnalysis,
FINALIZER_INFO *jitInfo) {
if (builder.getOption(vISA_DumpPerfStatsVerbose)) {
jitInfo->statsVerbose.varNum = liveAnalysis.getNumSelectedVar();
jitInfo->statsVerbose.globalVarNum = liveAnalysis.getNumSelectedGlobalVar();
}
}
void GlobalRA::writeVerboseRPEStats(RPE &rpe) {
if (builder.getOption(vISA_DumpPerfStatsVerbose) &&
builder.getJitInfo()->statsVerbose.RAIterNum == 1) {
builder.getJitInfo()->statsVerbose.maxRP = rpe.getMaxRP();
}
if (builder.getOption(vISA_DumpPerfStats)) {
builder.getJitInfo()->stats.maxGRFPressure = rpe.getMaxRP();
}
}
bool GlobalRA::VRTIncreasedGRF(GraphColor &coloring) {
if (kernel.useAutoGRFSelection()) {
bool infCostSpilled =
coloring.getSpilledLiveRanges().end() !=
std::find_if(coloring.getSpilledLiveRanges().begin(),
coloring.getSpilledLiveRanges().end(),
[](const LiveRange *spilledLR) {
return spilledLR->getSpillCost() == MAXSPILLCOST;
});
// Check if GRF can be increased to avoid large spills
if (canIncreaseGRF(computeSpillSize(coloring.getSpilledLiveRanges()),
infCostSpilled))
return true;
}
return false;
}
void GlobalRA::splitOnSpill(bool fastCompile, GraphColor &coloring,
LivenessAnalysis &liveAnalysis) {
if (!kernel.getOption(vISA_Debug) && getIterNo() == 0 && !fastCompile &&
kernel.getOption(vISA_DoSplitOnSpill)) {
RA_TRACE(std::cout << "\t--var split around loop\n");
LoopVarSplit loopSplit(kernel, &coloring, &liveAnalysis);
kernel.fg.getLoops().computePreheaders();
loopSplit.run();
}
}
bool GlobalRA::convertToFailSafe(bool reserveSpillReg, GraphColor &coloring,
LivenessAnalysis &liveAnalysis,
unsigned int nextSpillOffset) {
// Very few spills in this iter. Check if we can convert this to fail
// safe iter. By converting this iter to fail safe we can save (at
// least) 1 additional iter to allocate spilled temps. But converting to
// fail safe needs extra checks because no reserved GRF may exist at
// this point. So push/pop needs to succeed without additional GRF
// potentially.
if (!kernel.getOption(vISA_Debug) && getIterNo() >= 1 &&
kernel.getOption(vISA_NewFailSafeRA) && !reserveSpillReg &&
coloring.getSpilledLiveRanges().size() <= BoundedRA::MaxSpillNumVars &&
liveAnalysis.getNumSelectedVar() > BoundedRA::LargeProgramSize) {
// Stack call always has free GRF so it is safe to convert this iter
// to fail safe
if (builder.usesStack() ||
// If LSC has to be used for spill/fill then we need to ensure
// spillHeader is created
(useLscForNonStackCallSpillFill && builder.hasValidSpillFillHeader()) ||
// or if immediate can be folded in to LSC
canUseLscImmediateOffsetSpillFill ||
// If scratch is to be used then max spill offset must be within
// addressable range and r0 must be available as reserved. If r0
// is not reserved, we cannot conver current iteration to fail
// safe because r0 may get assigned to other virtual variables.
((kernel.getOption(vISA_PreserveR0InR0) ||
builder.getBuiltinR0()->isOutput()) &&
(nextSpillOffset + BoundedRA::getNumPhyVarSlots(kernel)) <
SCRATCH_MSG_LIMIT)) {
// Few ranges are spilled but this was not executed as fail
// safe iteration. However, we've the capability of doing
// push/pop with new fail safe RA implementation. So for very
// few spills, we insert push/pop to free up some GRFs rather
// than executing a new RA iteration. When doing so, we mark
// this RA iteration as fail safe.
coloring.markFailSafeIter(true);
// No reserved GRFs
setNumReservedGRFsFailSafe(0);
RA_TRACE(std::cout << "\t--enabling new fail safe RA\n");
return true;
}
}
return reserveSpillReg;
}
std::tuple<bool, unsigned int, unsigned int>
GlobalRA::abortOnSpill(unsigned int GRFSpillFillCount, unsigned int spillSize,
GraphColor &coloring) {
// Calculate the spill caused by send to decide if global splitting is
// required or not
for (auto spilled : coloring.getSpilledLiveRanges()) {
GRFSpillFillCount += spilled->getRefCount();
}
spillSize += computeSpillSize(coloring.getSpilledLiveRanges());
// vISA_AbortOnSpillThreshold is defined as [0..200]
// where 0 means abort on any spill and 200 means never abort
auto underSpillThreshold = [this](int numSpill, unsigned spillSize,
int asmCount, GraphColor &coloring) {
int threshold = std::min(
builder.getOptions()->getuInt32Option(vISA_AbortOnSpillThreshold),
200u);
return (numSpill * 200) < (threshold * asmCount) ||
spillSize < kernel.grfMode.getSpillThreshold();
};
unsigned int instNum = instCount();
bool isUnderThreshold =
underSpillThreshold(GRFSpillFillCount, spillSize, instNum, coloring);
isUnderThreshold = builder.getFreqInfoManager().underFreqSpillThreshold(
coloring.getSpilledLiveRanges(), instNum, GRFSpillFillCount,
isUnderThreshold);
if (isUnderThreshold) {
if (auto jitInfo = builder.getJitInfo()) {
jitInfo->avoidRetry = true;
}
}
if (builder.getOption(vISA_AbortOnSpill) && !isUnderThreshold) {
// update jit metadata information
if (auto jitInfo = builder.getJitInfo()) {
jitInfo->stats.spillMemUsed = 0;
jitInfo->stats.numAsmCountUnweighted = instNum;
jitInfo->stats.numGRFSpillFillWeighted = GRFSpillFillCount;
}
return std::make_tuple(true, GRFSpillFillCount, spillSize);
}
return std::make_tuple(false, GRFSpillFillCount, spillSize);
}
unsigned GlobalRA::computeSpillSize(std::list<LSLiveRange *> &spilledLRs) {
unsigned spillSize = 0;
for (auto lr : spilledLRs) {
spillSize += lr->getTopDcl()->getByteSize();
}
return spillSize;
}
unsigned GlobalRA::computeSpillSize(const LIVERANGE_LIST &spilledLRs) {
unsigned spillSize = 0;
for (auto lr : spilledLRs) {
spillSize += lr->getDcl()->getByteSize();
}
return spillSize;
}
bool GlobalRA::spillSpaceCompression(int spillSize,
const int globalScratchOffset) {
if (builder.getOption(vISA_ForceSpillSpaceCompression) &&
(builder.getuint32Option(vISA_SpillSpaceCompressionThreshold) == 0))
return true;
int spillcompressionThreshold =
(int)builder.getuint32Option(vISA_SpillSpaceCompressionThreshold) * 1024;
// user disabled vISA_ForceSpillSpaceCompression and no threshold override.
if (spillcompressionThreshold == 0) {
spillcompressionThreshold = SCRATCH_COMPRESS_THRESHOLD;
}
// factor 1.2 is used to count in the space used for the following
// iterations. Generally, the most spill will happen in first iteration.
if ((spillSize * 1.2) <
(spillcompressionThreshold - globalScratchOffset)) {
return false;
}
return true;
}
void GlobalRA::verifyNoInfCostSpill(GraphColor& coloring, bool reserveSpillReg)
{
vISA_ASSERT(std::all_of(coloring.getSpilledLiveRanges().begin(),
coloring.getSpilledLiveRanges().end(),
[&](const LiveRange *spilledLR) {
// EOT spills even of infinite cost are
// specially handled in spill insertion when
// using old fail safe RA. So don't assert for
// such spills.
if (isEOTSpillWithFailSafeRA(builder, spilledLR,
reserveSpillReg) &&
!builder.getOption(vISA_NewFailSafeRA))
return true;
return spilledLR->getSpillCost() != MAXSPILLCOST;
}),
"Spilled inf spill cost range");
}
void GlobalRA::setupA0Dot2OnSpill(bool hasStackCall,
unsigned int nextSpillOffset,
int globalScratchOffset) {
if (builder.hasScratchSurface() && !hasStackCall &&
(nextSpillOffset + globalScratchOffset) >= SCRATCH_MSG_LIMIT) {
// create temp variable to store old a0.2 - this is marked as live-in
// and live-out. because the variable is emitted only post RA to
// preserve old value of a0.2.
kernel.fg.builder->getOldA0Dot2Temp();
} else if (useLscForNonStackCallSpillFill || useLscForScatterSpill) {
// Xe2+ LSC-based spill/fill needs the same as above
{
kernel.fg.builder->getOldA0Dot2Temp();
}
}
}
bool GlobalRA::spillCleanup(bool fastCompile, bool useScratchMsgForSpill,
bool hasStackCall, bool reserveSpillReg, RPE &rpe,
GraphColor &coloring,
LivenessAnalysis &liveAnalysis,
SpillManagerGRF &spillGRF) {
bool disableSpillCoalecse = builder.getOption(vISA_DisableSpillCoalescing) ||
builder.getOption(vISA_FastSpill) ||
fastCompile || builder.getOption(vISA_Debug) ||
// spill cleanup is not support when we use oword
// msg for spill/fill for non-stack calls.
(!useScratchMsgForSpill && !hasStackCall);
if (!reserveSpillReg && !disableSpillCoalecse && builder.useSends()) {
RA_TRACE(std::cout << "\t--spill/fill cleanup\n");
CoalesceSpillFills c(kernel, liveAnalysis, coloring, spillGRF, getIterNo(),
rpe, *this);
c.run();
#ifndef DLL_MODE
if (stopAfter("spillCleanup")) {
return true;
}
#endif // DLL_MODE
}
return false;
}
std::tuple<bool, bool, bool, unsigned int, unsigned int>
GlobalRA::insertSpillCode(bool enableSpillSpaceCompression,
GraphColor &coloring, LivenessAnalysis &liveAnalysis,
RPE &rpe, unsigned int scratchOffset,
bool fastCompile, bool hasStackCall,
int globalScratchOffset, unsigned int nextSpillOffset,
bool reserveSpillReg, unsigned int spillRegSize,
unsigned int indrSpillRegSize,
bool useScratchMsgForSpill) {
if (getIterNo() == 0 && enableSpillSpaceCompression &&
kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D &&
!hasStackCall) {
enableSpillSpaceCompression = spillSpaceCompression(
computeSpillSize(coloring.getSpilledLiveRanges()), globalScratchOffset);
}
startTimer(TimerID::SPILL);
SpillManagerGRF spillGRF(*this, nextSpillOffset, &liveAnalysis,
coloring.getIntf(), &coloring.getSpilledLiveRanges(),
reserveSpillReg, spillRegSize, indrSpillRegSize,
enableSpillSpaceCompression, useScratchMsgForSpill);
if (kernel.getOption(vISA_SpillAnalysis)) {
spillAnalysis->Do(&liveAnalysis, &coloring, &spillGRF);
}
verifyNoInfCostSpill(coloring, reserveSpillReg);
bool success = spillGRF.insertSpillFillCode(&kernel, pointsToAnalysis);
nextSpillOffset = spillGRF.getNextOffset();
if (kernel.getOption(vISA_VerifyRA)) {
// For least false positives, turn off RMW opt and spill cleanup
verifySpillFill();
}
setupA0Dot2OnSpill(hasStackCall, nextSpillOffset, globalScratchOffset);
RA_TRACE({
auto &&spills = coloring.getSpilledLiveRanges();
std::cout << "\t--# variables spilled: " << spills.size() << "\n";
if (spills.size() < 100) {
std::cout << "\t--spilled variables: ";
for (auto &&lr : spills) {
std::cout << lr->getDcl()->getName() << " ";
}
std::cout << "\n";
}
std::cout << "\t--current spill size: " << nextSpillOffset << "\n";
});
if (!success) {
return std::make_tuple(false, enableSpillSpaceCompression, false,
scratchOffset, nextSpillOffset);
}
kernel.dumpToFile("after.Spill_GRF." + std::to_string(getIterNo() + 1));
#ifndef DLL_MODE
if (stopAfter("Spill_GRF")) {
return std::make_tuple(true, enableSpillSpaceCompression, true,
scratchOffset, nextSpillOffset);
}
#endif // DLL_MODE
scratchOffset = std::max(scratchOffset, spillGRF.getNextScratchOffset());
bool isEarlyExit =
spillCleanup(fastCompile, useScratchMsgForSpill, hasStackCall,
reserveSpillReg, rpe, coloring, liveAnalysis, spillGRF);
return std::make_tuple(true, enableSpillSpaceCompression, isEarlyExit,
scratchOffset, nextSpillOffset);
}
bool GlobalRA::rerunGRAIter(bool rerunGRA)
{
if (getIterNo() == 0 && (rerunGRA || kernel.getOption(vISA_forceBCR))) {
if (kernel.getOption(vISA_forceBCR)) {
// FIXME: We shouldn't modify options. Use local bool flag instead.
kernel.getOptions()->setOption(vISA_forceBCR, false);
}
return true;
}
return false;
}
//
// graph coloring entry point. returns nonzero if RA fails
//
int GlobalRA::coloringRegAlloc() {
VISA_DEBUG_VERBOSE({
std::cout << "\n=== Register Allocation ===\n";
if (builder.getIsKernel() == false) {
std::cout << "Function: " << kernel.getName() << "\n";
} else {
std::cout << "Kernel: " << kernel.getName() << "\n";
}
detectNeverDefinedUses();
});
#ifndef DLL_MODE
// Points-to analysis is done in RegAlloc.cpp just before constructing
// GlobalRA instance.
if (stopAfter("p2a")) {
pointsToAnalysis.dump(std::cout);
return VISA_EARLY_EXIT;
}
#endif // DLL_MODE
bool hasStackCall =
kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc();
fastRADecision();
bool hybridWithSpill = useHybridRAwithSpill &&
(!hasStackCall || builder.getOption(vISA_PartitionWithFastHybridRA));
useLocalRA = builder.getOption(vISA_LocalRA)
&& (kernel.fg.funcInfoTable.size() == 0
|| kernel.getInt32KernelAttr(Attributes::ATTR_Target) != VISA_3D
|| hybridWithSpill);
// this needs to be called before addr/flag RA since it changes their
// alignment as well
fixAlignment();
{
TIME_SCOPE(ADDR_FLAG_RA);
addVarToRA(kernel.Declares.back());
addrRegAlloc();
flagRegAlloc();
}
if (builder.getuint32Option(vISA_ScalarPipe)) {
selectScalarCandidates();
scalarRegAlloc();
}
// LSC messages are used when:
// a. Stack call is used on PVC+,
// b. Spill size exceeds what can be represented using hword msg on PVC+
// c. Xe2+ requires LSC stack (can force on DG2+ via -lscNonStackSpill)
if (builder.supportsLSC()) {
canUseLscImmediateOffsetSpillFill = LSCUsesImmOff(builder);
}
stackCallSaveRestore(hasStackCall);
if (kernel.getOption(vISA_SpillAnalysis)) {
spillAnalysis = std::make_unique<SpillAnalysis>();
}
if (kernel.fg.getIsStackCallFunc()) {
// Allocate space to store Frame Descriptor
nextSpillOffset += builder.numEltPerGRF<Type_UB>();
scratchOffset += builder.numEltPerGRF<Type_UB>();
if (kernel.getOption(vISA_storeCE)) {
nextSpillOffset += builder.numEltPerGRF<Type_UB>();
scratchOffset += builder.numEltPerGRF<Type_UB>();
}
}
// Global linear scan RA
if (builder.getOption(vISA_LinearScan) &&
builder.kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_3D) {
int success = doGlobalLinearScanRA();
if (success == VISA_SUCCESS)
return success;
else if (success == VISA_SPILL) {
return VISA_SPILL;
}
} else if (useLocalRA && !hasStackCall) {
if (tryHybridRA()) {
assignRegForAliasDcl();
return VISA_SUCCESS;
}
}
startTimer(TimerID::GRF_GLOBAL_RA);
unsigned maxRAIterations = builder.getuint32Option(vISA_MaxRAIterations);
unsigned iterationNo = 0;
int globalScratchOffset =
kernel.getInt32KernelAttr(Attributes::ATTR_SpillMemOffset);
bool useScratchMsgForSpill =
!hasStackCall &&
(globalScratchOffset < (int)(SCRATCH_MSG_LIMIT * 0.6)
// useScratchMsgForSpill is true for
// * scratch msg
// * LSC msg
// Spill insertion module decides whether to expand a fill/spill to
// scratch or LSC depending on spill offset. oword is supported for PVC
// but it is not emitted in favor of LSC.
|| builder.supportsLSC());
bool enableSpillSpaceCompression =
builder.getOption(vISA_SpillSpaceCompression);
uint32_t GRFSpillFillCount = 0;
uint32_t spillSize = 0;
if (builder.getFreqInfoManager().isFreqBasedSpillSelectionEnabled())
builder.getFreqInfoManager().initGRFSpillFillFreq();
unsigned fastCompileIter = 1;
bool fastCompile =
(useFastRA || useHybridRAwithSpill) &&
(!hasStackCall || builder.getOption(vISA_PartitionWithFastHybridRA));
if (fastCompile) {
fastCompileIter = 0;
}
if (kernel.getInt32KernelAttr(Attributes::ATTR_Target) == VISA_CM) {
maxRAIterations = 12;
}
unsigned failSafeRAIteration =
(builder.getOption(vISA_FastSpill) || fastCompile)
? fastCompileIter
: builder.getuint32Option(vISA_FailSafeRALimit);
if (failSafeRAIteration == 0) { // Fail safe RA directly in iteration 0, used
// for hybrid RA with spill
createVariablesForHybridRAWithSpill();
}
bool rematDone = false, alignedScalarSplitDone = false;
bool reserveSpillReg = false;
VarSplit splitPass(*this);
DynPerfModel perfModel(kernel);
FINALIZER_INFO *jitInfo = builder.getJitInfo();
incRABookKeeping();
while (iterationNo < maxRAIterations) {
jitInfo->statsVerbose.RAIterNum++;
if (builder.getOption(vISA_DynPerfModel)) {
perfModel.NumRAIters++;
}
RA_TRACE(std::cout << "--GRF RA iteration " << iterationNo << "--"
<< kernel.getName() << "\n");
setIterNo(iterationNo);
if (builder.getOption(vISA_clearScratchWritesBeforeEOT) &&
(globalScratchOffset + nextSpillOffset) > 0) {
// we need to set r0 be live out for this WA
builder.getBuiltinR0()->setLiveOut();
}
if (!useHybridRAwithSpill) {
resetGlobalRAStates();
// Identify the local variables to speedup following analysis
markGraphBlockLocalVars();
}
if (kernel.getOption(vISA_SpillAnalysis)) {
spillAnalysis->Clear();
}
localSplit(fastCompile, splitPass);
const auto [doBankConflictReduction, highInternalConflict] = bankConflict();
reserveSpillReg = setupFailSafeIfNeeded(
fastCompile, hasStackCall, maxRAIterations, failSafeRAIteration);
LivenessAnalysis liveAnalysis(*this, G4_GRF | G4_INPUT);
liveAnalysis.computeLiveness();
#ifndef DLL_MODE
if (stopAfter("Global_RA_liveness")) {
return VISA_EARLY_EXIT;
}
#endif // DLL_MODE
if (builder.getOption(vISA_dumpLiveness)) {
liveAnalysis.dump();
}
if (jitInfo->statsVerbose.RAIterNum == 1) {
writeVerboseStatsNumVars(liveAnalysis, jitInfo);
RA_TRACE(std::cout << "\t--# global variable: "
<< jitInfo->statsVerbose.globalVarNum << "\n");
}
#ifdef DEBUG_VERBOSE_ON
emitFGWithLiveness(liveAnalysis);
#endif
// if no reg var needs to reg allocated, then skip reg allocation
if (liveAnalysis.getNumSelectedVar() == 0)
break;
undefinedUses(rematDone, liveAnalysis);
// force spill should be done only for the 1st iteration
bool forceSpill =
iterationNo > 0 ? false : builder.getOption(vISA_ForceSpills);
RPE rpe(*this, &liveAnalysis);
if (!fastCompile) {
rpe.run();
writeVerboseRPEStats(rpe);
}
GraphColor coloring(liveAnalysis, false, forceSpill);
if (builder.getOption(vISA_dumpRPE) && iterationNo == 0 && !rematDone) {
coloring.dumpRPEToFile();
// dump pressure the first time we enter global RA
coloring.dumpRegisterPressure(std::cerr);
}
// Get the size of register which are reserved for spill
unsigned spillRegSize = 0;
unsigned indrSpillRegSize = 0;
if (reserveSpillReg) {
std::tie(spillRegSize, indrSpillRegSize) = reserveGRFSpillReg(coloring);
}
generateForbiddenTemplates(spillRegSize + indrSpillRegSize);
bool isColoringGood =
coloring.regAlloc(doBankConflictReduction, highInternalConflict, &rpe);
if (!isColoringGood) {
// When there are spills and -abortonspill is set, vISA will bump up the
// number of GRFs first and try to compile without spills under one of
// the following conditions:
// - Variable with inf spill cost, or
// - #GRFs selected and next larger one has same number of threads, or
// - Spill ratio is above threshold
// If none of the conditions is met, vISA will abort and return VISA_SPILL.
if (VRTIncreasedGRF(coloring))
continue;
bool rerunGRA1 = false, rerunGRA2 = false, rerunGRA3 = false,
isEarlyExit = false, abort = false, success = false;
std::tie(rerunGRA1, rematDone) = remat(fastCompile, rematDone, liveAnalysis, coloring, rpe);
std::tie(rerunGRA2, alignedScalarSplitDone, isEarlyExit) =
alignedScalarSplit(fastCompile, alignedScalarSplitDone, coloring);
#ifndef DLL_MODE
if (isEarlyExit) {
return VISA_EARLY_EXIT;
}
#endif // DLL_MODE
rerunGRA3 = globalSplit(splitPass, coloring);
if (rerunGRAIter(rerunGRA1 || rerunGRA2 || rerunGRA3))
continue;
splitOnSpill(fastCompile, coloring, liveAnalysis);
reserveSpillReg = convertToFailSafe(reserveSpillReg, coloring, liveAnalysis,
nextSpillOffset);
if (iterationNo == 0) {
// Dump out interference graph information of spill candidates
VISA_DEBUG_VERBOSE(reportSpillInfo(liveAnalysis, coloring));
}
std::tie(abort, GRFSpillFillCount, spillSize) =
abortOnSpill(GRFSpillFillCount, spillSize, coloring);
if (abort) {
// Early exit when -abortonspill is passed, instead of
// spending time inserting spill code and then aborting.
stopTimer(TimerID::GRF_GLOBAL_RA);
return VISA_SPILL;
}
std::tie(success, enableSpillSpaceCompression, isEarlyExit, scratchOffset,
nextSpillOffset) =
insertSpillCode(enableSpillSpaceCompression, coloring, liveAnalysis,
rpe, scratchOffset, fastCompile, hasStackCall,
globalScratchOffset, nextSpillOffset, reserveSpillReg,
spillRegSize, indrSpillRegSize,
useScratchMsgForSpill);
if (!success) {
iterationNo = maxRAIterations;
break;
}
#ifndef DLL_MODE
if (isEarlyExit)
return VISA_EARLY_EXIT;
#endif // DLL_MODE
++iterationNo;
if (iterationNo == builder.getuint32Option(vISA_FailSafeRALimit)) {
if (coloring.getSpilledLiveRanges().size() < 2) {
// give regular RA one more try as we are close to success
failSafeRAIteration++;
}
}
stopTimer(TimerID::SPILL);
}
// RA successfully allocates regs
if (isColoringGood == true || reserveSpillReg) {
coloring.confirmRegisterAssignments();
if (hasStackCall) {
// spill/fill intrinsics expect offset in HWord, so round up to 64
// byte but maintain it in OWord unit ToDo: we really need to change
// everything to byte for everyone's sanity..
unsigned localSpillAreaOwordSize = ROUND(scratchOffset, 64) / 16;
coloring.getSaveRestoreRegister();
addSaveRestoreCode(localSpillAreaOwordSize);
}
if (kernel.getOption(vISA_DumpRegChart)) {
assignRegForAliasDcl();
// invoke before expanding spill/fill since
// it modifies IR
regChart->dumpRegChart(std::cerr, {}, 0);
}
if (builder.getOption(vISA_DynPerfModel)) {
perfModel.run();
}
expandSpillFillIntrinsics(nextSpillOffset);
VISA_DEBUG_VERBOSE(detectUndefinedUses(liveAnalysis, kernel));
if (nextSpillOffset) {
switch (kernel.getRAType()) {
case RA_Type::GRAPH_COLORING_RR_BC_RA:
kernel.setRAType(RA_Type::GRAPH_COLORING_SPILL_RR_BC_RA);
break;
case RA_Type::GRAPH_COLORING_FF_BC_RA:
kernel.setRAType(RA_Type::GRAPH_COLORING_SPILL_FF_BC_RA);
break;
case RA_Type::GRAPH_COLORING_RR_RA:
kernel.setRAType(RA_Type::GRAPH_COLORING_SPILL_RR_RA);
break;
case RA_Type::GRAPH_COLORING_FF_RA:
kernel.setRAType(RA_Type::GRAPH_COLORING_SPILL_FF_RA);
break;
default:
vISA_ASSERT_UNREACHABLE("invalid ra type");
break;
}
}
if (verifyAugmentation) {
assignRegForAliasDcl();
verifyAugmentation->verify();
}
break; // done
}
}
assignRegForAliasDcl();
stopTimer(TimerID::GRF_GLOBAL_RA);
//
// Report failure to allocate due to excessive register pressure.
//
if (!reserveSpillReg && (iterationNo == maxRAIterations)) {
std::stringstream spilledVars;
for (auto dcl : kernel.Declares) {
if (dcl->isSpilled() && dcl->getRegFile() == G4_GRF) {
spilledVars << dcl->getName() << "\t";
}
}
vISA_ASSERT(false, "%d GRF registers are NOT enough to compile kernel %s \
The maximum register pressure in the kernel is higher than the available \
physical registers in hardware (even with spill code). Please consider \
rewriting the kernel. Compiling with the symbolic register option and \
inspecting the spilled registers may help in determinig the region of high \
pressure. The spilling virtual registers are as follows %s.",
(kernel.getNumRegTotal() -
builder.getOptions()->getuInt32Option(vISA_ReservedGRFNum)),
kernel.getName(), spilledVars.str().c_str());
return VISA_SPILL;
}
// this includes vISA's scratch space use only and does not include whatever
// IGC may use for private memory
uint32_t spillMemUsed = builder.kernel.fg.frameSizeInOWord ?
(builder.kernel.fg.frameSizeInOWord * 16) : nextSpillOffset;
spillMemUsed = ROUND(spillMemUsed, kernel.numEltPerGRF<Type_UB>());
if (spillMemUsed &&
!(kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc())) {
builder.criticalMsgStream()
<< "Spill memory used = " << spillMemUsed << " bytes for kernel "
<< kernel.getName()
<< "\n Compiling kernel with spill code may degrade performance."
<< " Please consider rewriting the kernel to use less registers.\n";
}
// update jit metadata information for spill
if (auto jitInfo = builder.getJitInfo()) {
// jitInfo->spillMemUsed is the entire visa stack size. Consider the
// caller/callee save size if having caller/callee save
// globalScratchOffset in unit of byte, others in Oword
//
// FIXME: globalScratchOffset must be 0 when having stack call, or
// there is a problem at stack setup
// (see GlobalRA::addGenxMainStackSetupCode)
//
// vISA stack
// globalScratchOffset -> ---------------------
// | spill |
// calleeSaveAreaOffset -> ---------------------
// | callee save |
// callerSaveAreaOffset -> ---------------------
// | caller save |
// frameSizeInOWord -> ---------------------
jitInfo->hasStackcalls = kernel.fg.getHasStackCalls();
// Each function reports its required stack size.
// We will summarize the final stack size of entire vISA module into
// the main functions (ref: CISA_IR_Builder::summarizeFunctionInfo)
jitInfo->stats.spillMemUsed = spillMemUsed;
kernel.getGTPinData()->setScratchNextFree(spillMemUsed +
globalScratchOffset);
jitInfo->stats.numGRFSpillFillWeighted = GRFSpillFillCount;
}
if (builder.getOption(vISA_LocalDeclareSplitInGlobalRA)) {
removeSplitDecl();
}
if (builder.getOption(vISA_DynPerfModel)) {
perfModel.dump();
}
return VISA_SUCCESS;
}
// Insert declarations with pre-assigned registers in kernel
// this is needed for HRA, and the fake declares will be removed at the end of
// HRA
void GlobalRA::insertPhyRegDecls() {
int numGRF = kernel.getNumRegTotal();
std::vector<bool> grfUsed(numGRF, false);
GRFDclsForHRA.resize(numGRF);
for (auto curBB : kernel.fg) {
if (auto summary = getBBLRASummary(curBB)) {
for (int i = 0; i < numGRF; i++) {
if (summary->isGRFBusy(i)) {
grfUsed[i] = true;
}
}
}
}
// Insert declarations for each GRF that is used
unsigned numGRFsUsed = 0;
for (int i = 0; i < numGRF; i++) {
if (grfUsed[i] == true) {
const char *dclName = builder.getNameString(10, "r%d", i);
G4_Declare *phyRegDcl =
builder.createDeclare(dclName, G4_GRF, kernel.numEltPerGRF<Type_UD>(),
1, Type_D, Regular, NULL, NULL);
G4_Greg *phyReg = builder.phyregpool.getGreg(i);
phyRegDcl->getRegVar()->setPhyReg(phyReg, 0);
GRFDclsForHRA[i] = phyRegDcl;
addVarToRA(phyRegDcl);
numGRFsUsed++;
}
}
VISA_DEBUG(std::cout << "Local RA used " << numGRFsUsed << " GRFs\n");
}
void GraphColor::dumpRPEToFile() {
// Dump RPE output to file if asmName is set
auto *asmOutput = builder.getOptions()->getOptionCstr(VISA_AsmFileName);
if (asmOutput) {
std::string FN(asmOutput);
FN += ".rpe";
std::ofstream OF;
OF.open(FN, std::ofstream::out);
dumpRegisterPressure(OF);
OF.close();
}
}
void GraphColor::dumpRegisterPressure(std::ostream &OS) {
RPE rpe(gra, &liveAnalysis);
uint32_t max = 0;
std::vector<G4_INST *> maxInst;
rpe.run();
for (auto bb : builder.kernel.fg) {
OS << "BB " << bb->getId() << ": (Pred: ";
for (auto pred : bb->Preds) {
OS << pred->getId() << ",";
}
OS << " Succ: ";
for (auto succ : bb->Succs) {
OS << succ->getId() << ",";
}
OS << ")\n";
for (auto instIt = bb->begin(); instIt != bb->end(); ++instIt) {
auto *inst = *instIt;
uint32_t pressure = rpe.getRegisterPressure(inst);
if (pressure > max) {
max = pressure;
maxInst.clear();
maxInst.push_back(inst);
} else if (pressure == max) {
maxInst.push_back(inst);
}
if (kernel.getOption(vISA_EmitSrcFileLineToRPE))
bb->emitInstructionSourceLineMapping(OS, instIt);
OS << "[" << pressure << "] ";
inst->print(OS);
}
}
OS << "max pressure: " << max << ", " << maxInst.size() << " inst(s)\n";
for (auto inst : maxInst) {
inst->print(OS);
}
}
void GlobalRA::fixAlignment() {
// Copy over alignment from G4_RegVar to GlobalRA instance
// Rest of RA shouldnt have to read/modify alignment of G4_RegVar
copyAlignment();
for (auto dcl : kernel.Declares) {
if (dcl->getRegFile() & G4_FLAG) {
if (dcl->getByteSize() > 2 ||
(kernel.getSimdSize() == g4::SIMD32 &&
kernel.getInt32KernelAttr(Attributes::ATTR_Target) != VISA_CM))
setSubRegAlign(dcl, G4_SubReg_Align::Even_Word);
}
}
if (builder.getPlatform() == GENX_BDW) {
// BDW requires even_word alignment for scalar HF variables
for (auto dcl : kernel.Declares) {
if (dcl->getElemType() == Type_HF && dcl->getSubRegAlign() == Any) {
setSubRegAlign(dcl, Even_Word);
}
}
}
// ToDo: remove these as it should be done by HWConformity
for (auto BB : kernel.fg) {
for (auto inst : *BB) {
G4_DstRegRegion *dst = inst->getDst();
if (dst && dst->getTopDcl()) {
G4_RegVar *var = dst->getBase()->asRegVar();
if (inst->isSend() && dst->getRegAccess() == Direct) {
if (!var->isPhyRegAssigned()) {
setSubRegAlign(dst->getTopDcl(), builder.getGRFAlign());
}
}
if (!var->isPhyRegAssigned() && var->getDeclare()->getNumRows() <= 1 &&
dst->getRegAccess() == Direct &&
var->getDeclare()->getSubRegAlign() == Any) {
if (inst->isAccSrcInst()) {
setSubRegAlign(dst->getTopDcl(),
var->getDeclare()->getRegFile() != G4_ADDRESS
? builder.getGRFAlign()
: Eight_Word);
}
}
}
}
}
}
//
// DFS to check if there is any conflict in subroutine return location
//
bool GlobalRA::isSubRetLocConflict(G4_BB *bb, std::vector<unsigned> &usedLoc,
unsigned stackTop) {
auto &fg = kernel.fg;
if (bb->isAlreadyTraversed(fg.getTraversalNum()))
return false;
bb->markTraversed(fg.getTraversalNum());
G4_INST *lastInst = bb->size() == 0 ? NULL : bb->back();
if (lastInst && lastInst->isReturn()) {
if (lastInst->getPredicate() == NULL)
return false;
else {
return isSubRetLocConflict(bb->fallThroughBB(), usedLoc, stackTop);
}
} else if (lastInst && lastInst->isCall()) // need to traverse to next level
{
unsigned curSubRetLoc = getSubRetLoc(bb);
//
// check conflict firstly
//
for (unsigned i = 0; i < stackTop; i++)
if (usedLoc[i] == curSubRetLoc)
return true;
//
// then traverse all the subroutines and return BB
//
usedLoc[stackTop] = curSubRetLoc;
unsigned afterCallId = bb->BBAfterCall()->getId();
// call can have 1 or 2 successors
// If it has 1 then it is sub-entry block, if it has 2
// then call has to be predicated. In case of predication,
// 1st successor is physically following BB, 2nd is
// sub-entry.
if (lastInst->getPredicate()) {
vISA_ASSERT(bb->Succs.size() == 2,
"Expecting 2 successor BBs for predicated call");
if (isSubRetLocConflict(bb->Succs.back(), usedLoc, stackTop))
return true;
}
if (bb->BBAfterCall()->getId() == afterCallId) {
if (isSubRetLocConflict(bb->BBAfterCall(), usedLoc, stackTop))
return true;
}
} else {
for (G4_BB *succ : bb->Succs)
if (isSubRetLocConflict(succ, usedLoc, stackTop))
return true;
}
return false;
}
//
// The routine traverses all BBs that can be reached from the entry of a
// subroutine (not traversing into nested subroutine calls). Mark retLoc[bb] =
// entryId (to associate bb with the subroutine entry. When two subroutines
// share code, we return the location of the subroutine that was previously
// traversed so that the two routines can then use the same location to save
// their return addresses.
//
unsigned GlobalRA::determineReturnAddrLoc(unsigned entryId,
std::vector<unsigned> &retLoc,
G4_BB *bb) {
auto &fg = kernel.fg;
if (bb->isAlreadyTraversed(fg.getTraversalNum()))
return retLoc[bb->getId()];
bb->markTraversed(fg.getTraversalNum());
if (retLoc[bb->getId()] != UNDEFINED_VAL)
return retLoc[bb->getId()];
retLoc[bb->getId()] = entryId;
G4_INST *lastInst = bb->size() == 0 ? NULL : bb->back();
if (lastInst && lastInst->isReturn()) {
if (!lastInst->getPredicate())
return entryId;
return determineReturnAddrLoc(entryId, retLoc, bb->fallThroughBB());
} else if (lastInst && lastInst->isCall()) {
// skip nested subroutine calls
return determineReturnAddrLoc(entryId, retLoc, bb->BBAfterCall());
}
unsigned sharedId = entryId;
for (G4_BB *succ : bb->Succs) {
unsigned loc = determineReturnAddrLoc(entryId, retLoc, succ);
if (loc != entryId) {
while (retLoc[loc] != loc) // find the root of subroutine loc
loc = retLoc[loc]; // follow the link to reach the root
if (sharedId == entryId) {
sharedId = loc;
} else if (sharedId != loc) {
//
// The current subroutine share code with two other subroutines, we
// force all three of them to use the same location by linking them
// togethers.
//
retLoc[loc] = sharedId;
}
}
}
return sharedId;
}
void GlobalRA::assignLocForReturnAddr() {
auto &fg = kernel.fg;
std::vector<unsigned> retLoc(fg.getNumBB(), UNDEFINED_VAL);
// a data structure for doing a quick map[id] ---> block
// FIXME: I have no idea why we need this vector, do we have to iterate the
// blocks by their id for some reason?
std::vector<G4_BB *> BBs(fg.getNumBB());
for (G4_BB *bb : fg) {
unsigned i = bb->getId();
BBs[i] = bb; // BBs are sorted by ID
}
//
// Firstly, keep the original algorithm unchanged to mark the retLoc
//
std::vector<G4_BB *> caller; // just to accelerate the algorithm later
for (unsigned i = 0, bbNum = fg.getNumBB(); i < bbNum; i++) {
G4_BB *bb = BBs[i];
if (bb->isEndWithCall() == false) {
continue;
}
#ifdef _DEBUG
G4_INST *last = bb->empty() ? NULL : bb->back();
vISA_ASSERT(last, ERROR_FLOWGRAPH);
#endif
caller.push_back(
bb); // record the callers, just to accelerate the algorithm
G4_BB *subEntry = bb->getCalleeInfo()->getInitBB();
if (retLoc[subEntry->getId()] !=
UNDEFINED_VAL) // a loc has been assigned to the subroutine
{
// Need to setSubRetLoc if subEntry is part of another subRoutine because,
// in the final phase, we use SubRetLoc != UNDEFINED_VAL to indicate
// a block is an entry of a subroutine.
setSubRetLoc(subEntry, retLoc[subEntry->getId()]);
} else {
fg.prepareTraversal();
unsigned loc =
determineReturnAddrLoc(subEntry->getId(), retLoc, subEntry);
if (loc != subEntry->getId()) {
retLoc[subEntry->getId()] = loc;
}
setSubRetLoc(subEntry, loc);
//
// We do not merge indirect call here, because it will createt additional
// (bb->getSubRetLoc() != bb->getId()) cases that kill the share code
// detection
//
}
// retBB is the exit basic block of callee, ie the block with return
// statement at end
G4_BB *retBB = bb->getCalleeInfo()->getExitBB();
if (retLoc[retBB->getId()] == UNDEFINED_VAL) {
// retBB block was unreachable so retLoc element corresponding to that
// block was left undefined
retLoc[retBB->getId()] = getSubRetLoc(subEntry);
}
}
VISA_DEBUG_VERBOSE({
std::cout << "\nBefore merge indirect call:\n";
for (unsigned i = 0; i < fg.getNumBB(); i++)
if (retLoc[i] == UNDEFINED_VAL) {
std::cout << "BB" << i << ": X ";
} else {
std::cout << "BB" << i << ": " << retLoc[i] << " ";
}
std::cout << "\n";
});
//
// this final phase is needed. Consider the following scenario. Sub2 shared
// code with both Sub1 and Sub3. All three must use the same location to save
// return addresses. If we traverse Sub1 then Sub3, retLoc[Sub1] and
// retLoc[Sub3] all point to their own roots. As we traverse Sub2, code
// sharing is detected, we need to this phase to make sure that Sub1 and Sub3
// use the same location.
//
for (unsigned i = 0, bbNum = fg.getNumBB(); i < bbNum; i++) {
G4_BB *bb = BBs[i];
if (getSubRetLoc(bb) != UNDEFINED_VAL) {
if (getSubRetLoc(bb) != bb->getId()) {
unsigned loc = bb->getId();
while (retLoc[loc] != loc) // not root
loc = retLoc[loc]; // follow the link to reach the root
}
}
}
//
// Merge the retLoc in indirect call cases
//
for (G4_BB *bb : caller) {
G4_INST *last = bb->empty() ? NULL : bb->back();
vISA_ASSERT(last, ERROR_FLOWGRAPH);
unsigned fallThroughId = bb->fallThroughBB() == NULL
? UNDEFINED_VAL
: bb->fallThroughBB()->getId();
if ((last && last->getPredicate() == NULL && bb->Succs.size() > 1) ||
(last && last->getPredicate() != NULL && bb->Succs.size() > 2)) {
//
// merge all subroutines to the last one, it is a trick to conduct the
// conditional call by using last one instead of first one
//
unsigned masterEntryId = bb->Succs.back()->getId();
//
// find the root of the master subroutine
//
unsigned masterRetLoc = masterEntryId;
while (retLoc[masterRetLoc] != masterRetLoc)
masterRetLoc = retLoc[masterRetLoc];
//
// check other subroutines in one vertex
//
for (G4_BB *subBB : bb->Succs) {
if (subBB->getId() != masterEntryId &&
subBB->getId() != fallThroughId) {
//
// find the root of the current subroutine
//
unsigned loc = subBB->getId();
while (retLoc[loc] != loc)
loc = retLoc[loc];
//
// Merge: let all the items in retLoc with value loc pointing to
// masterRetLoc Suppose indirect call X calls subroutine A and B,
// indirect call Y calls B and C, and indirect call Z calls C and D.
// Before merge, the A~D will be assigned different return location.
// Suppose we process the callers in order X-->Z-->Y in the merge, if
// we just modified the return locations of one indirect call, we will
// fail to merge the return locations of A~D.
//
if (loc != masterRetLoc) {
for (unsigned i = 0; i < fg.getNumBB(); i++)
if (retLoc[i] == loc)
retLoc[i] = masterRetLoc;
}
}
}
}
}
VISA_DEBUG_VERBOSE({
std::cout << "\nAfter merge indirect call:\n";
for (unsigned i = 0; i < fg.getNumBB(); i++)
if (retLoc[i] == UNDEFINED_VAL) {
std::cout << "BB" << i << ": X ";
} else {
std::cout << "BB" << i << ": " << retLoc[i] << " ";
}
std::cout << "\n";
});
//
// Assign ret loc for subroutines firstly, and then check if it is wrong (due
// to circle in call graph).
//
for (unsigned i = 0, bbNum = fg.getNumBB(); i < bbNum; i++) {
//
// reset the return BB's retLoc
//
unsigned loc = i;
if (retLoc[i] != UNDEFINED_VAL) {
while (retLoc[loc] != loc)
loc = retLoc[loc];
retLoc[i] = loc;
setSubRetLoc(BBs[i], retLoc[loc]);
}
}
for (G4_BB *bb : caller) {
//
// set caller BB's retLoc
//
#ifdef _DEBUG
G4_INST *last = bb->empty() ? NULL : bb->back();
vISA_ASSERT(last, ERROR_FLOWGRAPH);
#endif
G4_BB *subBB = bb->getCalleeInfo()->getInitBB();
//
// 1: Must use retLoc here, because some subBB is also the caller of another
// subroutine, so the entry loc in BB may be changed in this step 2: In some
// cases, the caller BB is also the entry BB. At this time, the associated
// entry BB ID will be overwritten. However, it will not impact the conflict
// detection and return location assignment, since we only check the return
// BB and/or caller BB in these two moudles.
//
setSubRetLoc(bb, retLoc[subBB->getId()]);
}
VISA_DEBUG_VERBOSE({
for (unsigned i = 0; i < fg.getNumBB(); i++) {
G4_BB *bb = BBs[i];
if (getSubRetLoc(bb) != UNDEFINED_VAL) {
if (!bb->empty() && bb->front()->isLabel()) {
std::cout << ((G4_Label *)bb->front()->getSrc(0))->getLabel()
<< " assigned location " << getSubRetLoc(bb) << "\n";
}
}
}
});
//
// detect the conflict (circle) at last
//
std::vector<unsigned> usedLoc(fg.getNumBB());
unsigned stackTop = 0;
for (G4_BB *bb : caller) {
//
// Must re-start the traversal from each caller, otherwise will lose some
// circle cases like TestRA_Call_1_1_3B, D, F, G, H
//
fg.prepareTraversal();
usedLoc[stackTop] = getSubRetLoc(bb);
G4_BB *subEntry = bb->Succs.back();
if (isSubRetLocConflict(subEntry, usedLoc, stackTop + 1)) {
vISA_ASSERT(false, "ERROR: Fail to assign call-return variables due to "
"cycle in call graph!");
}
}
insertCallReturnVar();
}
void GlobalRA::insertCallReturnVar() {
for (auto bb : kernel.fg) {
G4_INST *last = bb->empty() ? NULL : bb->back();
if (last) {
if (last->isCall()) {
insertSaveAddr(bb);
} else {
if (last->isReturn()) {
// G4_BB_EXIT_TYPE is just a dummy BB, and the return will be the last
// inst in each of its predecessors
insertRestoreAddr(bb);
}
}
}
}
}
void GlobalRA::insertSaveAddr(G4_BB *bb) {
vISA_ASSERT(bb != NULL, ERROR_INTERNAL_ARGUMENT);
vISA_ASSERT(getSubRetLoc(bb) != UNDEFINED_VAL,
ERROR_FLOWGRAPH); // must have a assigned loc
G4_INST *last = bb->back();
vASSERT(last->isCall());
if (last->getDst() == NULL) {
unsigned loc = getSubRetLoc(bb);
G4_Declare *dcl = getRetDecl(loc);
last->setDest(builder.createDst(dcl->getRegVar(), 0, 0, 1,
Type_UD)); // RET__loc12<1>:ud
last->setExecSize(g4::SIMD2);
}
}
void GlobalRA::insertRestoreAddr(G4_BB *bb) {
vISA_ASSERT(bb != NULL, ERROR_INTERNAL_ARGUMENT);
G4_INST *last = bb->back();
vASSERT(last->isReturn());
if (last->getSrc(0) == NULL) {
unsigned loc = getSubRetLoc(bb);
G4_Declare *dcl = getRetDecl(loc);
G4_SrcRegRegion *new_src = builder.createSrc(
dcl->getRegVar(), 0, 0, builder.createRegionDesc(0, 2, 1), Type_UD);
last->setSrc(new_src, 0);
last->setDest(builder.createNullDst(Type_UD));
last->setExecSize(g4::SIMD2);
}
}
// This function returns the weight of interference edge lr1--lr2,
// which is used for computing the degree of lr1.
//
// When there is no alignment restriction, we should use the normal weight,
// which is lr1_nreg + lr2_nreg - 1.
//
// Otherewise, we need to take into account additional space that may be
// required because of the alignment restriction. For example,
// if lr1 has even alignment and lr2 has no alignment restriction,
// we need to consider the following cases that would require the
// maximal available GRF space for successful allocation:
// 1) lr1's size is odd, lr2's size is odd and lr2's start position is even,
// the total space required would be (lr1_nreg + lr2_nreg + 1)
// 2) lr1's size is odd, lr2's size is even and lr2's start position is even,
// the total space required would be (lr1_nreg + lr2_nreg)
// 3) lr1's size is even, lr2's size is odd and lr2's start position is odd,
// the total space required would be (lr1_nreg + lr2_nreg)
// 4) lr1's size is even, lr2's size is even and lr2's start position is odd,
// the total space required would be (lr1_nreg + lr2_nreg + 1)
// The above logic can be simplified to the following formula:
// lr1_nreg + lr2_nreg + 1 - ((lr1_nreg + lr2_nreg) % 2)
//
// If both lr1 and lr2 have even alignment restriction,
// we need to consider the following cases that would require the
// maximal available GRF space for successful allocation:
// 1) lr1's size is odd, lr2's size is odd and lr2's start position is even,
// the total space required would be (lr1_nreg + lr2_nreg + 1)
// 2) lr1's size is odd, lr2's size is even and lr2's start position is even,
// the total space required would be (lr1_nreg + lr2_nreg)
// 3) lr1's size is even, lr2's size is odd and lr2's start position is even,
// the total space required would be (lr1_nreg + lr2_nreg)
// 4) lr1's size is even, lr2's size is even and lr2's start position is even,
// the total space required would be (lr1_nreg + lr2_nreg - 1)
// The above logic can be simplified to the following formula:
// lr1_nreg + lr2_nreg - 1 + (lr1_nreg % 2) + (lr2_nreg % 2)
//
// Note: Edge weight between 2 nodes is asymmetric and depends on ordering
// of nodes. Swapping lr1, lr2 and invoking edgeWeightGRF() may return
// different result. So using the correct order of lr1, lr2 during edge
// weight computation and later during simplification is necessary for
// correctness.
//
template <bool Support4GRFAlign>
unsigned GraphColor::edgeWeightGRF(const LiveRange *lr1, const LiveRange *lr2) {
unsigned lr1_nreg = lr1->getNumRegNeeded();
unsigned lr2_nreg = lr2->getNumRegNeeded();
if constexpr (Support4GRFAlign) {
auto lr1Align = gra.getAugAlign(lr1->getDcl());
auto lr2Align = gra.getAugAlign(lr2->getDcl());
return edgeWeightWith4GRF(lr1Align, lr2Align, lr1_nreg, lr2_nreg);
} else {
bool lr1EvenAlign = gra.isEvenAligned<false>(lr1->getDcl());
bool lr2EvenAlign = gra.isEvenAligned<false>(lr2->getDcl());
return edgeWeightGRF(lr1EvenAlign, lr2EvenAlign, lr1_nreg, lr2_nreg);
}
}
unsigned GraphColor::edgeWeightARF(const LiveRange *lr1, const LiveRange *lr2) {
if (lr1->getRegKind() == G4_FLAG) {
G4_SubReg_Align lr1_align = gra.getSubRegAlign(lr1->getVar()->getDeclare());
G4_SubReg_Align lr2_align = gra.getSubRegAlign(lr2->getVar()->getDeclare());
unsigned lr1_nreg = lr1->getNumRegNeeded();
unsigned lr2_nreg = lr2->getNumRegNeeded();
if (lr1_align == Any) {
return lr1_nreg + lr2_nreg - 1;
} else if (lr1_align == Even_Word && lr2_align == Any) {
return lr1_nreg + lr2_nreg + 1 - ((lr1_nreg + lr2_nreg) % 2);
} else if (lr1_align == Even_Word && lr2_align == Even_Word) {
if (lr1_nreg % 2 == 0 && lr2_nreg % 2 == 0) {
return lr1_nreg + lr2_nreg - 2;
} else {
return lr1_nreg + lr2_nreg - 1 + (lr1_nreg % 2) + (lr2_nreg % 2);
}
} else {
vISA_ASSERT_UNREACHABLE(
"Found unsupported subRegAlignment in flag register allocation!");
return 0;
}
} else if (lr1->getRegKind() == G4_ADDRESS) {
G4_SubReg_Align lr1_align = gra.getSubRegAlign(lr1->getVar()->getDeclare());
G4_SubReg_Align lr2_align = gra.getSubRegAlign(lr2->getVar()->getDeclare());
unsigned lr1_nreg = lr1->getNumRegNeeded();
unsigned lr2_nreg = lr2->getNumRegNeeded();
if (lr1_align < lr2_align) {
G4_SubReg_Align tmp_align = lr1_align;
unsigned tmp_nreg = lr1_nreg;
lr1_align = lr2_align;
lr2_align = tmp_align;
lr1_nreg = lr2_nreg;
lr2_nreg = tmp_nreg;
}
if (lr1_align == Any) {
// Any vs
return lr1_nreg + lr2_nreg - 1;
} else if (lr1_align == Four_Word && lr2_align == Any) {
// 4 vs Any
return lr1_nreg + lr2_nreg + 3 - (lr1_nreg + lr2_nreg) % 4;
} else if (lr1_align == Four_Word && lr2_align == Four_Word) {
// 4 vs 4
return lr1_nreg + lr2_nreg - 1 + (4 - lr1_nreg % 4) % 4 +
(4 - lr2_nreg % 4) % 4;
} else if (lr1_align == Eight_Word && lr2_align == Any) {
// 8 vs Any
return lr1_nreg + lr2_nreg + 7 - (lr1_nreg + lr2_nreg) % 8;
} else if (lr1_align == Eight_Word && lr2_align == Four_Word) {
// 8 vs 4
if (((8 - lr1_nreg % 8) % 8) >= 4)
return lr1_nreg + lr2_nreg - 1 + (8 - lr1_nreg % 8) % 8 - 4;
return lr1_nreg + lr2_nreg - 1 + (8 - lr1_nreg % 8) % 8 +
(4 - lr2_nreg % 4) % 4;
} else if (lr1_align == Eight_Word && lr2_align == Eight_Word) {
// 8 vs 8
return lr1_nreg + lr2_nreg - 1 + (8 - lr1_nreg % 8) % 8 +
(8 - lr2_nreg % 8) % 8;
} else if (lr1_align == Sixteen_Word && lr2_align == Any) {
// 16 vs Any
return lr1_nreg + lr2_nreg + 15 - (lr1_nreg + lr2_nreg) % 16;
} else if (lr1_align == Sixteen_Word && lr2_align == Four_Word) {
// 16 vs 4
if (((16 - lr1_nreg % 16) % 16) >= 4)
return lr1_nreg + lr2_nreg - 1 + (16 - lr1_nreg % 16) % 16 - 4;
return lr1_nreg + lr2_nreg - 1 + (16 - lr1_nreg % 16) % 16 +
(4 - lr2_nreg % 4) % 4;
} else if (lr1_align == Sixteen_Word && lr2_align == Eight_Word) {
// 16 vs 8
if (((16 - lr1_nreg % 16) % 16) >= 8)
return lr1_nreg + lr2_nreg - 1 + (16 - lr1_nreg % 16) % 16 - 8;
return lr1_nreg + lr2_nreg - 1 + (16 - lr1_nreg % 16) % 16 +
(8 - lr2_nreg % 8) % 8;
} else if (lr1_align == Sixteen_Word && lr2_align == Sixteen_Word) {
// 16 vs 16
return lr1_nreg + lr2_nreg - 1 + (16 - lr1_nreg % 16) % 16 +
(16 - lr2_nreg % 16) % 16;
} else {
vISA_ASSERT_UNREACHABLE(
"Found unsupported subRegAlignment in address register allocation!");
return 0;
}
}
else if (lr1->getRegKind() == G4_SCALAR) {
return edgeWeightGRF<false>(lr1, lr2); // treat scalar just like GRF
}
vISA_ASSERT_UNREACHABLE(
"Found unsupported ARF reg type in register allocation!");
return 0;
}
void GlobalRA::fixSrc0IndirFcall() {
// Indirect calls look like:
// mov (1|NM) V10 0x123456:ud
// fcall (1) dst V10 <-- V10 which is src0 contains %ip to jump to
//
// In this function, we want to set V10 to r125.0 which is same as dst of
// fcall as per ABI. This way, when inserting save/restore code around fcall,
// no special checks are needed to handle V10.
//
// But this works only if V10 is a local. If it not a local we create a mov
// that copies V10 in to a new temp variable. And then we map this temp
// variable to r125.0. Hopefully V10 being global would be a rare occurence.
for (auto bb : kernel.fg) {
if (bb->isEndWithFCall()) {
auto fcall = bb->back()->asCFInst();
if (!fcall->getSrc(0) || !fcall->getSrc(0)->isSrcRegRegion())
continue;
auto src0Rgn = fcall->getSrc(0)->asSrcRegRegion();
auto src0TypeSize = src0Rgn->getTypeSize();
auto src0Dcl = src0Rgn->getBase()->asRegVar()->getDeclare();
auto src0TopDcl = src0Rgn->getTopDcl();
if (src0Dcl != src0TopDcl || !isBlockLocal(src0TopDcl) ||
src0TopDcl->getNumElems() > 1) {
// create a copy
auto tmpDcl = kernel.fg.builder->createHardwiredDeclare(
1, src0Rgn->getType(), kernel.stackCall.getFPSPGRF(),
kernel.stackCall.subRegs.Ret_IP * TypeSize(Type_UD) / src0TypeSize);
auto dst = kernel.fg.builder->createDst(tmpDcl->getRegVar(),
src0Rgn->getType());
auto src = kernel.fg.builder->duplicateOperand(src0Rgn);
auto copy = kernel.fg.builder->createMov(g4::SIMD1, dst, src,
InstOpt_WriteEnable, false);
auto iter = std::find_if(bb->begin(), bb->end(),
[](G4_INST *inst) { return inst->isFCall(); });
bb->insertBefore(iter, copy);
auto newSrc = kernel.fg.builder->createSrc(
tmpDcl->getRegVar(), 0, 0, kernel.fg.builder->getRegionScalar(),
Type_UD);
fcall->setSrc(newSrc, 0);
} else {
auto fcallDstTypeSize = fcall->getDst()->getTypeSize();
vISA_ASSERT(fcallDstTypeSize == 4, "expecting DW type dst");
src0TopDcl->getRegVar()->setPhyReg(
fcall->getDst()->getBase()->asRegVar()->getPhyReg(),
fcall->getDst()->getBase()->asRegVar()->getPhyRegOff() *
fcallDstTypeSize / src0TypeSize);
}
}
}
}
|