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
|
//===- SCF.cpp - Structured Control Flow Operations -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Arith/Utils/Utils.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/DeviceMappingInterface.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/FunctionInterfaces.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Support/MathExtras.h"
#include "mlir/Transforms/InliningUtils.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/TypeSwitch.h"
using namespace mlir;
using namespace mlir::scf;
#include "mlir/Dialect/SCF/IR/SCFOpsDialect.cpp.inc"
//===----------------------------------------------------------------------===//
// SCFDialect Dialect Interfaces
//===----------------------------------------------------------------------===//
namespace {
struct SCFInlinerInterface : public DialectInlinerInterface {
using DialectInlinerInterface::DialectInlinerInterface;
// We don't have any special restrictions on what can be inlined into
// destination regions (e.g. while/conditional bodies). Always allow it.
bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
IRMapping &valueMapping) const final {
return true;
}
// Operations in scf dialect are always legal to inline since they are
// pure.
bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
return true;
}
// Handle the given inlined terminator by replacing it with a new operation
// as necessary. Required when the region has only one block.
void handleTerminator(Operation *op,
ArrayRef<Value> valuesToRepl) const final {
auto retValOp = dyn_cast<scf::YieldOp>(op);
if (!retValOp)
return;
for (auto retValue : llvm::zip(valuesToRepl, retValOp.getOperands())) {
std::get<0>(retValue).replaceAllUsesWith(std::get<1>(retValue));
}
}
};
} // namespace
//===----------------------------------------------------------------------===//
// SCFDialect
//===----------------------------------------------------------------------===//
void SCFDialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "mlir/Dialect/SCF/IR/SCFOps.cpp.inc"
>();
addInterfaces<SCFInlinerInterface>();
}
/// Default callback for IfOp builders. Inserts a yield without arguments.
void mlir::scf::buildTerminatedBody(OpBuilder &builder, Location loc) {
builder.create<scf::YieldOp>(loc);
}
/// Verifies that the first block of the given `region` is terminated by a
/// TerminatorTy. Reports errors on the given operation if it is not the case.
template <typename TerminatorTy>
static TerminatorTy verifyAndGetTerminator(Operation *op, Region ®ion,
StringRef errorMessage) {
Operation *terminatorOperation = nullptr;
if (!region.empty() && !region.front().empty()) {
terminatorOperation = ®ion.front().back();
if (auto yield = dyn_cast_or_null<TerminatorTy>(terminatorOperation))
return yield;
}
auto diag = op->emitOpError(errorMessage);
if (terminatorOperation)
diag.attachNote(terminatorOperation->getLoc()) << "terminator here";
return nullptr;
}
//===----------------------------------------------------------------------===//
// ExecuteRegionOp
//===----------------------------------------------------------------------===//
/// Replaces the given op with the contents of the given single-block region,
/// using the operands of the block terminator to replace operation results.
static void replaceOpWithRegion(PatternRewriter &rewriter, Operation *op,
Region ®ion, ValueRange blockArgs = {}) {
assert(llvm::hasSingleElement(region) && "expected single-region block");
Block *block = ®ion.front();
Operation *terminator = block->getTerminator();
ValueRange results = terminator->getOperands();
rewriter.inlineBlockBefore(block, op, blockArgs);
rewriter.replaceOp(op, results);
rewriter.eraseOp(terminator);
}
///
/// (ssa-id `=`)? `execute_region` `->` function-result-type `{`
/// block+
/// `}`
///
/// Example:
/// scf.execute_region -> i32 {
/// %idx = load %rI[%i] : memref<128xi32>
/// return %idx : i32
/// }
///
ParseResult ExecuteRegionOp::parse(OpAsmParser &parser,
OperationState &result) {
if (parser.parseOptionalArrowTypeList(result.types))
return failure();
// Introduce the body region and parse it.
Region *body = result.addRegion();
if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}) ||
parser.parseOptionalAttrDict(result.attributes))
return failure();
return success();
}
void ExecuteRegionOp::print(OpAsmPrinter &p) {
p.printOptionalArrowTypeList(getResultTypes());
p << ' ';
p.printRegion(getRegion(),
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/true);
p.printOptionalAttrDict((*this)->getAttrs());
}
LogicalResult ExecuteRegionOp::verify() {
if (getRegion().empty())
return emitOpError("region needs to have at least one block");
if (getRegion().front().getNumArguments() > 0)
return emitOpError("region cannot have any arguments");
return success();
}
// Inline an ExecuteRegionOp if it only contains one block.
// "test.foo"() : () -> ()
// %v = scf.execute_region -> i64 {
// %x = "test.val"() : () -> i64
// scf.yield %x : i64
// }
// "test.bar"(%v) : (i64) -> ()
//
// becomes
//
// "test.foo"() : () -> ()
// %x = "test.val"() : () -> i64
// "test.bar"(%x) : (i64) -> ()
//
struct SingleBlockExecuteInliner : public OpRewritePattern<ExecuteRegionOp> {
using OpRewritePattern<ExecuteRegionOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ExecuteRegionOp op,
PatternRewriter &rewriter) const override {
if (!llvm::hasSingleElement(op.getRegion()))
return failure();
replaceOpWithRegion(rewriter, op, op.getRegion());
return success();
}
};
// Inline an ExecuteRegionOp if its parent can contain multiple blocks.
// TODO generalize the conditions for operations which can be inlined into.
// func @func_execute_region_elim() {
// "test.foo"() : () -> ()
// %v = scf.execute_region -> i64 {
// %c = "test.cmp"() : () -> i1
// cf.cond_br %c, ^bb2, ^bb3
// ^bb2:
// %x = "test.val1"() : () -> i64
// cf.br ^bb4(%x : i64)
// ^bb3:
// %y = "test.val2"() : () -> i64
// cf.br ^bb4(%y : i64)
// ^bb4(%z : i64):
// scf.yield %z : i64
// }
// "test.bar"(%v) : (i64) -> ()
// return
// }
//
// becomes
//
// func @func_execute_region_elim() {
// "test.foo"() : () -> ()
// %c = "test.cmp"() : () -> i1
// cf.cond_br %c, ^bb1, ^bb2
// ^bb1: // pred: ^bb0
// %x = "test.val1"() : () -> i64
// cf.br ^bb3(%x : i64)
// ^bb2: // pred: ^bb0
// %y = "test.val2"() : () -> i64
// cf.br ^bb3(%y : i64)
// ^bb3(%z: i64): // 2 preds: ^bb1, ^bb2
// "test.bar"(%z) : (i64) -> ()
// return
// }
//
struct MultiBlockExecuteInliner : public OpRewritePattern<ExecuteRegionOp> {
using OpRewritePattern<ExecuteRegionOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ExecuteRegionOp op,
PatternRewriter &rewriter) const override {
if (!isa<FunctionOpInterface, ExecuteRegionOp>(op->getParentOp()))
return failure();
Block *prevBlock = op->getBlock();
Block *postBlock = rewriter.splitBlock(prevBlock, op->getIterator());
rewriter.setInsertionPointToEnd(prevBlock);
rewriter.create<cf::BranchOp>(op.getLoc(), &op.getRegion().front());
for (Block &blk : op.getRegion()) {
if (YieldOp yieldOp = dyn_cast<YieldOp>(blk.getTerminator())) {
rewriter.setInsertionPoint(yieldOp);
rewriter.create<cf::BranchOp>(yieldOp.getLoc(), postBlock,
yieldOp.getResults());
rewriter.eraseOp(yieldOp);
}
}
rewriter.inlineRegionBefore(op.getRegion(), postBlock);
SmallVector<Value> blockArgs;
for (auto res : op.getResults())
blockArgs.push_back(postBlock->addArgument(res.getType(), res.getLoc()));
rewriter.replaceOp(op, blockArgs);
return success();
}
};
void ExecuteRegionOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<SingleBlockExecuteInliner, MultiBlockExecuteInliner>(context);
}
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void ExecuteRegionOp::getSuccessorRegions(
std::optional<unsigned> index, ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> ®ions) {
// If the predecessor is the ExecuteRegionOp, branch into the body.
if (!index) {
regions.push_back(RegionSuccessor(&getRegion()));
return;
}
// Otherwise, the region branches back to the parent operation.
regions.push_back(RegionSuccessor(getResults()));
}
//===----------------------------------------------------------------------===//
// ConditionOp
//===----------------------------------------------------------------------===//
MutableOperandRange
ConditionOp::getMutableSuccessorOperands(std::optional<unsigned> index) {
// Pass all operands except the condition to the successor region.
return getArgsMutable();
}
//===----------------------------------------------------------------------===//
// ForOp
//===----------------------------------------------------------------------===//
void ForOp::build(OpBuilder &builder, OperationState &result, Value lb,
Value ub, Value step, ValueRange iterArgs,
BodyBuilderFn bodyBuilder) {
result.addOperands({lb, ub, step});
result.addOperands(iterArgs);
for (Value v : iterArgs)
result.addTypes(v.getType());
Type t = lb.getType();
Region *bodyRegion = result.addRegion();
bodyRegion->push_back(new Block);
Block &bodyBlock = bodyRegion->front();
bodyBlock.addArgument(t, result.location);
for (Value v : iterArgs)
bodyBlock.addArgument(v.getType(), v.getLoc());
// Create the default terminator if the builder is not provided and if the
// iteration arguments are not provided. Otherwise, leave this to the caller
// because we don't know which values to return from the loop.
if (iterArgs.empty() && !bodyBuilder) {
ForOp::ensureTerminator(*bodyRegion, builder, result.location);
} else if (bodyBuilder) {
OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToStart(&bodyBlock);
bodyBuilder(builder, result.location, bodyBlock.getArgument(0),
bodyBlock.getArguments().drop_front());
}
}
LogicalResult ForOp::verify() {
IntegerAttr step;
if (matchPattern(getStep(), m_Constant(&step)) && step.getInt() <= 0)
return emitOpError("constant step operand must be positive");
auto opNumResults = getNumResults();
if (opNumResults == 0)
return success();
// If ForOp defines values, check that the number and types of
// the defined values match ForOp initial iter operands and backedge
// basic block arguments.
if (getNumIterOperands() != opNumResults)
return emitOpError(
"mismatch in number of loop-carried values and defined values");
return success();
}
LogicalResult ForOp::verifyRegions() {
// Check that the body defines as single block argument for the induction
// variable.
if (getInductionVar().getType() != getLowerBound().getType())
return emitOpError(
"expected induction variable to be same type as bounds and step");
auto opNumResults = getNumResults();
if (opNumResults == 0)
return success();
if (getNumRegionIterArgs() != opNumResults)
return emitOpError(
"mismatch in number of basic block args and defined values");
auto iterOperands = getIterOperands();
auto iterArgs = getRegionIterArgs();
auto opResults = getResults();
unsigned i = 0;
for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
if (std::get<0>(e).getType() != std::get<2>(e).getType())
return emitOpError() << "types mismatch between " << i
<< "th iter operand and defined value";
if (std::get<1>(e).getType() != std::get<2>(e).getType())
return emitOpError() << "types mismatch between " << i
<< "th iter region arg and defined value";
++i;
}
return success();
}
std::optional<Value> ForOp::getSingleInductionVar() {
return getInductionVar();
}
std::optional<OpFoldResult> ForOp::getSingleLowerBound() {
return OpFoldResult(getLowerBound());
}
std::optional<OpFoldResult> ForOp::getSingleStep() {
return OpFoldResult(getStep());
}
std::optional<OpFoldResult> ForOp::getSingleUpperBound() {
return OpFoldResult(getUpperBound());
}
/// Promotes the loop body of a forOp to its containing block if the forOp
/// it can be determined that the loop has a single iteration.
LogicalResult ForOp::promoteIfSingleIteration(RewriterBase &rewriter) {
std::optional<int64_t> tripCount =
constantTripCount(getLowerBound(), getUpperBound(), getStep());
if (!tripCount.has_value() || tripCount != 1)
return failure();
// Replace all results with the yielded values.
auto yieldOp = cast<scf::YieldOp>(getBody()->getTerminator());
rewriter.replaceAllUsesWith(getResults(), yieldOp.getOperands());
// Replace block arguments with lower bound (replacement for IV) and
// iter_args.
SmallVector<Value> bbArgReplacements;
bbArgReplacements.push_back(getLowerBound());
bbArgReplacements.append(getIterOperands().begin(), getIterOperands().end());
// Move the loop body operations to the loop's containing block.
rewriter.inlineBlockBefore(getBody(), getOperation()->getBlock(),
getOperation()->getIterator(), bbArgReplacements);
// Erase the old terminator and the loop.
rewriter.eraseOp(yieldOp);
rewriter.eraseOp(*this);
return success();
}
/// Prints the initialization list in the form of
/// <prefix>(%inner = %outer, %inner2 = %outer2, <...>)
/// where 'inner' values are assumed to be region arguments and 'outer' values
/// are regular SSA values.
static void printInitializationList(OpAsmPrinter &p,
Block::BlockArgListType blocksArgs,
ValueRange initializers,
StringRef prefix = "") {
assert(blocksArgs.size() == initializers.size() &&
"expected same length of arguments and initializers");
if (initializers.empty())
return;
p << prefix << '(';
llvm::interleaveComma(llvm::zip(blocksArgs, initializers), p, [&](auto it) {
p << std::get<0>(it) << " = " << std::get<1>(it);
});
p << ")";
}
void ForOp::print(OpAsmPrinter &p) {
p << " " << getInductionVar() << " = " << getLowerBound() << " to "
<< getUpperBound() << " step " << getStep();
printInitializationList(p, getRegionIterArgs(), getIterOperands(),
" iter_args");
if (!getIterOperands().empty())
p << " -> (" << getIterOperands().getTypes() << ')';
p << ' ';
if (Type t = getInductionVar().getType(); !t.isIndex())
p << " : " << t << ' ';
p.printRegion(getRegion(),
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/hasIterOperands());
p.printOptionalAttrDict((*this)->getAttrs());
}
ParseResult ForOp::parse(OpAsmParser &parser, OperationState &result) {
auto &builder = parser.getBuilder();
Type type;
OpAsmParser::Argument inductionVariable;
OpAsmParser::UnresolvedOperand lb, ub, step;
// Parse the induction variable followed by '='.
if (parser.parseOperand(inductionVariable.ssaName) || parser.parseEqual() ||
// Parse loop bounds.
parser.parseOperand(lb) || parser.parseKeyword("to") ||
parser.parseOperand(ub) || parser.parseKeyword("step") ||
parser.parseOperand(step))
return failure();
// Parse the optional initial iteration arguments.
SmallVector<OpAsmParser::Argument, 4> regionArgs;
SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
regionArgs.push_back(inductionVariable);
bool hasIterArgs = succeeded(parser.parseOptionalKeyword("iter_args"));
if (hasIterArgs) {
// Parse assignment list and results type list.
if (parser.parseAssignmentList(regionArgs, operands) ||
parser.parseArrowTypeList(result.types))
return failure();
}
if (regionArgs.size() != result.types.size() + 1)
return parser.emitError(
parser.getNameLoc(),
"mismatch in number of loop-carried values and defined values");
// Parse optional type, else assume Index.
if (parser.parseOptionalColon())
type = builder.getIndexType();
else if (parser.parseType(type))
return failure();
// Resolve input operands.
regionArgs.front().type = type;
if (parser.resolveOperand(lb, type, result.operands) ||
parser.resolveOperand(ub, type, result.operands) ||
parser.resolveOperand(step, type, result.operands))
return failure();
if (hasIterArgs) {
for (auto argOperandType :
llvm::zip(llvm::drop_begin(regionArgs), operands, result.types)) {
Type type = std::get<2>(argOperandType);
std::get<0>(argOperandType).type = type;
if (parser.resolveOperand(std::get<1>(argOperandType), type,
result.operands))
return failure();
}
}
// Parse the body region.
Region *body = result.addRegion();
if (parser.parseRegion(*body, regionArgs))
return failure();
ForOp::ensureTerminator(*body, builder, result.location);
// Parse the optional attribute list.
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
return success();
}
Region &ForOp::getLoopBody() { return getRegion(); }
ForOp mlir::scf::getForInductionVarOwner(Value val) {
auto ivArg = llvm::dyn_cast<BlockArgument>(val);
if (!ivArg)
return ForOp();
assert(ivArg.getOwner() && "unlinked block argument");
auto *containingOp = ivArg.getOwner()->getParentOp();
return dyn_cast_or_null<ForOp>(containingOp);
}
/// Return operands used when entering the region at 'index'. These operands
/// correspond to the loop iterator operands, i.e., those excluding the
/// induction variable.
OperandRange ForOp::getSuccessorEntryOperands(std::optional<unsigned> index) {
return getInitArgs();
}
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void ForOp::getSuccessorRegions(std::optional<unsigned> index,
ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> ®ions) {
// Both the operation itself and the region may be branching into the body or
// back into the operation itself. It is possible for loop not to enter the
// body.
regions.push_back(RegionSuccessor(&getLoopBody(), getRegionIterArgs()));
regions.push_back(RegionSuccessor(getResults()));
}
Region &ForallOp::getLoopBody() { return getRegion(); }
/// Promotes the loop body of a forallOp to its containing block if it can be
/// determined that the loop has a single iteration.
LogicalResult scf::ForallOp::promoteIfSingleIteration(RewriterBase &rewriter) {
for (auto [lb, ub, step] :
llvm::zip(getMixedLowerBound(), getMixedUpperBound(), getMixedStep())) {
auto tripCount = constantTripCount(lb, ub, step);
if (!tripCount.has_value() || *tripCount != 1)
return failure();
}
promote(rewriter, *this);
return success();
}
/// Promotes the loop body of a scf::ForallOp to its containing block.
void mlir::scf::promote(RewriterBase &rewriter, scf::ForallOp forallOp) {
OpBuilder::InsertionGuard g(rewriter);
scf::InParallelOp terminator = forallOp.getTerminator();
// Replace block arguments with lower bounds (replacements for IVs) and
// outputs.
SmallVector<Value> bbArgReplacements = forallOp.getLowerBound(rewriter);
bbArgReplacements.append(forallOp.getOutputs().begin(),
forallOp.getOutputs().end());
// Move the loop body operations to the loop's containing block.
rewriter.inlineBlockBefore(forallOp.getBody(), forallOp->getBlock(),
forallOp->getIterator(), bbArgReplacements);
// Replace the terminator with tensor.insert_slice ops.
rewriter.setInsertionPointAfter(forallOp);
SmallVector<Value> results;
results.reserve(forallOp.getResults().size());
for (auto &yieldingOp : terminator.getYieldingOps()) {
auto parallelInsertSliceOp =
cast<tensor::ParallelInsertSliceOp>(yieldingOp);
Value dst = parallelInsertSliceOp.getDest();
Value src = parallelInsertSliceOp.getSource();
if (llvm::isa<TensorType>(src.getType())) {
results.push_back(rewriter.create<tensor::InsertSliceOp>(
forallOp.getLoc(), dst.getType(), src, dst,
parallelInsertSliceOp.getOffsets(), parallelInsertSliceOp.getSizes(),
parallelInsertSliceOp.getStrides(),
parallelInsertSliceOp.getStaticOffsets(),
parallelInsertSliceOp.getStaticSizes(),
parallelInsertSliceOp.getStaticStrides()));
} else {
llvm_unreachable("unsupported terminator");
}
}
rewriter.replaceAllUsesWith(forallOp.getResults(), results);
// Erase the old terminator and the loop.
rewriter.eraseOp(terminator);
rewriter.eraseOp(forallOp);
}
LoopNest mlir::scf::buildLoopNest(
OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
ValueRange steps, ValueRange iterArgs,
function_ref<ValueVector(OpBuilder &, Location, ValueRange, ValueRange)>
bodyBuilder) {
assert(lbs.size() == ubs.size() &&
"expected the same number of lower and upper bounds");
assert(lbs.size() == steps.size() &&
"expected the same number of lower bounds and steps");
// If there are no bounds, call the body-building function and return early.
if (lbs.empty()) {
ValueVector results =
bodyBuilder ? bodyBuilder(builder, loc, ValueRange(), iterArgs)
: ValueVector();
assert(results.size() == iterArgs.size() &&
"loop nest body must return as many values as loop has iteration "
"arguments");
return LoopNest{{}, std::move(results)};
}
// First, create the loop structure iteratively using the body-builder
// callback of `ForOp::build`. Do not create `YieldOp`s yet.
OpBuilder::InsertionGuard guard(builder);
SmallVector<scf::ForOp, 4> loops;
SmallVector<Value, 4> ivs;
loops.reserve(lbs.size());
ivs.reserve(lbs.size());
ValueRange currentIterArgs = iterArgs;
Location currentLoc = loc;
for (unsigned i = 0, e = lbs.size(); i < e; ++i) {
auto loop = builder.create<scf::ForOp>(
currentLoc, lbs[i], ubs[i], steps[i], currentIterArgs,
[&](OpBuilder &nestedBuilder, Location nestedLoc, Value iv,
ValueRange args) {
ivs.push_back(iv);
// It is safe to store ValueRange args because it points to block
// arguments of a loop operation that we also own.
currentIterArgs = args;
currentLoc = nestedLoc;
});
// Set the builder to point to the body of the newly created loop. We don't
// do this in the callback because the builder is reset when the callback
// returns.
builder.setInsertionPointToStart(loop.getBody());
loops.push_back(loop);
}
// For all loops but the innermost, yield the results of the nested loop.
for (unsigned i = 0, e = loops.size() - 1; i < e; ++i) {
builder.setInsertionPointToEnd(loops[i].getBody());
builder.create<scf::YieldOp>(loc, loops[i + 1].getResults());
}
// In the body of the innermost loop, call the body building function if any
// and yield its results.
builder.setInsertionPointToStart(loops.back().getBody());
ValueVector results = bodyBuilder
? bodyBuilder(builder, currentLoc, ivs,
loops.back().getRegionIterArgs())
: ValueVector();
assert(results.size() == iterArgs.size() &&
"loop nest body must return as many values as loop has iteration "
"arguments");
builder.setInsertionPointToEnd(loops.back().getBody());
builder.create<scf::YieldOp>(loc, results);
// Return the loops.
ValueVector nestResults;
llvm::copy(loops.front().getResults(), std::back_inserter(nestResults));
return LoopNest{std::move(loops), std::move(nestResults)};
}
LoopNest mlir::scf::buildLoopNest(
OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
ValueRange steps,
function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilder) {
// Delegate to the main function by wrapping the body builder.
return buildLoopNest(builder, loc, lbs, ubs, steps, std::nullopt,
[&bodyBuilder](OpBuilder &nestedBuilder,
Location nestedLoc, ValueRange ivs,
ValueRange) -> ValueVector {
if (bodyBuilder)
bodyBuilder(nestedBuilder, nestedLoc, ivs);
return {};
});
}
namespace {
// Fold away ForOp iter arguments when:
// 1) The op yields the iter arguments.
// 2) The iter arguments have no use and the corresponding outer region
// iterators (inputs) are yielded.
// 3) The iter arguments have no use and the corresponding (operation) results
// have no use.
//
// These arguments must be defined outside of
// the ForOp region and can just be forwarded after simplifying the op inits,
// yields and returns.
//
// The implementation uses `inlineBlockBefore` to steal the content of the
// original ForOp and avoid cloning.
struct ForOpIterArgsFolder : public OpRewritePattern<scf::ForOp> {
using OpRewritePattern<scf::ForOp>::OpRewritePattern;
LogicalResult matchAndRewrite(scf::ForOp forOp,
PatternRewriter &rewriter) const final {
bool canonicalize = false;
Block &block = forOp.getRegion().front();
auto yieldOp = cast<scf::YieldOp>(block.getTerminator());
// An internal flat vector of block transfer
// arguments `newBlockTransferArgs` keeps the 1-1 mapping of original to
// transformed block argument mappings. This plays the role of a
// IRMapping for the particular use case of calling into
// `inlineBlockBefore`.
SmallVector<bool, 4> keepMask;
keepMask.reserve(yieldOp.getNumOperands());
SmallVector<Value, 4> newBlockTransferArgs, newIterArgs, newYieldValues,
newResultValues;
newBlockTransferArgs.reserve(1 + forOp.getNumIterOperands());
newBlockTransferArgs.push_back(Value()); // iv placeholder with null value
newIterArgs.reserve(forOp.getNumIterOperands());
newYieldValues.reserve(yieldOp.getNumOperands());
newResultValues.reserve(forOp.getNumResults());
for (auto it : llvm::zip(forOp.getIterOperands(), // iter from outside
forOp.getRegionIterArgs(), // iter inside region
forOp.getResults(), // op results
yieldOp.getOperands() // iter yield
)) {
// Forwarded is `true` when:
// 1) The region `iter` argument is yielded.
// 2) The region `iter` argument has no use, and the corresponding iter
// operand (input) is yielded.
// 3) The region `iter` argument has no use, and the corresponding op
// result has no use.
bool forwarded = ((std::get<1>(it) == std::get<3>(it)) ||
(std::get<1>(it).use_empty() &&
(std::get<0>(it) == std::get<3>(it) ||
std::get<2>(it).use_empty())));
keepMask.push_back(!forwarded);
canonicalize |= forwarded;
if (forwarded) {
newBlockTransferArgs.push_back(std::get<0>(it));
newResultValues.push_back(std::get<0>(it));
continue;
}
newIterArgs.push_back(std::get<0>(it));
newYieldValues.push_back(std::get<3>(it));
newBlockTransferArgs.push_back(Value()); // placeholder with null value
newResultValues.push_back(Value()); // placeholder with null value
}
if (!canonicalize)
return failure();
scf::ForOp newForOp = rewriter.create<scf::ForOp>(
forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
forOp.getStep(), newIterArgs);
newForOp->setAttrs(forOp->getAttrs());
Block &newBlock = newForOp.getRegion().front();
// Replace the null placeholders with newly constructed values.
newBlockTransferArgs[0] = newBlock.getArgument(0); // iv
for (unsigned idx = 0, collapsedIdx = 0, e = newResultValues.size();
idx != e; ++idx) {
Value &blockTransferArg = newBlockTransferArgs[1 + idx];
Value &newResultVal = newResultValues[idx];
assert((blockTransferArg && newResultVal) ||
(!blockTransferArg && !newResultVal));
if (!blockTransferArg) {
blockTransferArg = newForOp.getRegionIterArgs()[collapsedIdx];
newResultVal = newForOp.getResult(collapsedIdx++);
}
}
Block &oldBlock = forOp.getRegion().front();
assert(oldBlock.getNumArguments() == newBlockTransferArgs.size() &&
"unexpected argument size mismatch");
// No results case: the scf::ForOp builder already created a zero
// result terminator. Merge before this terminator and just get rid of the
// original terminator that has been merged in.
if (newIterArgs.empty()) {
auto newYieldOp = cast<scf::YieldOp>(newBlock.getTerminator());
rewriter.inlineBlockBefore(&oldBlock, newYieldOp, newBlockTransferArgs);
rewriter.eraseOp(newBlock.getTerminator()->getPrevNode());
rewriter.replaceOp(forOp, newResultValues);
return success();
}
// No terminator case: merge and rewrite the merged terminator.
auto cloneFilteredTerminator = [&](scf::YieldOp mergedTerminator) {
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(mergedTerminator);
SmallVector<Value, 4> filteredOperands;
filteredOperands.reserve(newResultValues.size());
for (unsigned idx = 0, e = keepMask.size(); idx < e; ++idx)
if (keepMask[idx])
filteredOperands.push_back(mergedTerminator.getOperand(idx));
rewriter.create<scf::YieldOp>(mergedTerminator.getLoc(),
filteredOperands);
};
rewriter.mergeBlocks(&oldBlock, &newBlock, newBlockTransferArgs);
auto mergedYieldOp = cast<scf::YieldOp>(newBlock.getTerminator());
cloneFilteredTerminator(mergedYieldOp);
rewriter.eraseOp(mergedYieldOp);
rewriter.replaceOp(forOp, newResultValues);
return success();
}
};
/// Util function that tries to compute a constant diff between u and l.
/// Returns std::nullopt when the difference between two AffineValueMap is
/// dynamic.
static std::optional<int64_t> computeConstDiff(Value l, Value u) {
IntegerAttr clb, cub;
if (matchPattern(l, m_Constant(&clb)) && matchPattern(u, m_Constant(&cub))) {
llvm::APInt lbValue = clb.getValue();
llvm::APInt ubValue = cub.getValue();
return (ubValue - lbValue).getSExtValue();
}
// Else a simple pattern match for x + c or c + x
llvm::APInt diff;
if (matchPattern(
u, m_Op<arith::AddIOp>(matchers::m_Val(l), m_ConstantInt(&diff))) ||
matchPattern(
u, m_Op<arith::AddIOp>(m_ConstantInt(&diff), matchers::m_Val(l))))
return diff.getSExtValue();
return std::nullopt;
}
/// Rewriting pattern that erases loops that are known not to iterate, replaces
/// single-iteration loops with their bodies, and removes empty loops that
/// iterate at least once and only return values defined outside of the loop.
struct SimplifyTrivialLoops : public OpRewritePattern<ForOp> {
using OpRewritePattern<ForOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ForOp op,
PatternRewriter &rewriter) const override {
// If the upper bound is the same as the lower bound, the loop does not
// iterate, just remove it.
if (op.getLowerBound() == op.getUpperBound()) {
rewriter.replaceOp(op, op.getIterOperands());
return success();
}
std::optional<int64_t> diff =
computeConstDiff(op.getLowerBound(), op.getUpperBound());
if (!diff)
return failure();
// If the loop is known to have 0 iterations, remove it.
if (*diff <= 0) {
rewriter.replaceOp(op, op.getIterOperands());
return success();
}
std::optional<llvm::APInt> maybeStepValue = op.getConstantStep();
if (!maybeStepValue)
return failure();
// If the loop is known to have 1 iteration, inline its body and remove the
// loop.
llvm::APInt stepValue = *maybeStepValue;
if (stepValue.sge(*diff)) {
SmallVector<Value, 4> blockArgs;
blockArgs.reserve(op.getNumIterOperands() + 1);
blockArgs.push_back(op.getLowerBound());
llvm::append_range(blockArgs, op.getIterOperands());
replaceOpWithRegion(rewriter, op, op.getLoopBody(), blockArgs);
return success();
}
// Now we are left with loops that have more than 1 iterations.
Block &block = op.getRegion().front();
if (!llvm::hasSingleElement(block))
return failure();
// If the loop is empty, iterates at least once, and only returns values
// defined outside of the loop, remove it and replace it with yield values.
auto yieldOp = cast<scf::YieldOp>(block.getTerminator());
auto yieldOperands = yieldOp.getOperands();
if (llvm::any_of(yieldOperands,
[&](Value v) { return !op.isDefinedOutsideOfLoop(v); }))
return failure();
rewriter.replaceOp(op, yieldOperands);
return success();
}
};
/// Perform a replacement of one iter OpOperand of an scf.for to the
/// `replacement` value which is expected to be the source of a tensor.cast.
/// tensor.cast ops are inserted inside the block to account for the type cast.
static SmallVector<Value>
replaceTensorCastForOpIterArg(PatternRewriter &rewriter, OpOperand &operand,
Value replacement) {
Type oldType = operand.get().getType(), newType = replacement.getType();
assert(llvm::isa<RankedTensorType>(oldType) &&
llvm::isa<RankedTensorType>(newType) &&
"expected ranked tensor types");
// 1. Create new iter operands, exactly 1 is replaced.
ForOp forOp = cast<ForOp>(operand.getOwner());
assert(operand.getOperandNumber() >= forOp.getNumControlOperands() &&
"expected an iter OpOperand");
assert(operand.get().getType() != replacement.getType() &&
"Expected a different type");
SmallVector<Value> newIterOperands;
for (OpOperand &opOperand : forOp.getIterOpOperands()) {
if (opOperand.getOperandNumber() == operand.getOperandNumber()) {
newIterOperands.push_back(replacement);
continue;
}
newIterOperands.push_back(opOperand.get());
}
// 2. Create the new forOp shell.
scf::ForOp newForOp = rewriter.create<scf::ForOp>(
forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
forOp.getStep(), newIterOperands);
newForOp->setAttrs(forOp->getAttrs());
Block &newBlock = newForOp.getRegion().front();
SmallVector<Value, 4> newBlockTransferArgs(newBlock.getArguments().begin(),
newBlock.getArguments().end());
// 3. Inject an incoming cast op at the beginning of the block for the bbArg
// corresponding to the `replacement` value.
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(&newBlock, newBlock.begin());
BlockArgument newRegionIterArg = newForOp.getRegionIterArgForOpOperand(
newForOp->getOpOperand(operand.getOperandNumber()));
Value castIn = rewriter.create<tensor::CastOp>(newForOp.getLoc(), oldType,
newRegionIterArg);
newBlockTransferArgs[newRegionIterArg.getArgNumber()] = castIn;
// 4. Steal the old block ops, mapping to the newBlockTransferArgs.
Block &oldBlock = forOp.getRegion().front();
rewriter.mergeBlocks(&oldBlock, &newBlock, newBlockTransferArgs);
// 5. Inject an outgoing cast op at the end of the block and yield it instead.
auto clonedYieldOp = cast<scf::YieldOp>(newBlock.getTerminator());
rewriter.setInsertionPoint(clonedYieldOp);
unsigned yieldIdx =
newRegionIterArg.getArgNumber() - forOp.getNumInductionVars();
Value castOut = rewriter.create<tensor::CastOp>(
newForOp.getLoc(), newType, clonedYieldOp.getOperand(yieldIdx));
SmallVector<Value> newYieldOperands = clonedYieldOp.getOperands();
newYieldOperands[yieldIdx] = castOut;
rewriter.create<scf::YieldOp>(newForOp.getLoc(), newYieldOperands);
rewriter.eraseOp(clonedYieldOp);
// 6. Inject an outgoing cast op after the forOp.
rewriter.setInsertionPointAfter(newForOp);
SmallVector<Value> newResults = newForOp.getResults();
newResults[yieldIdx] = rewriter.create<tensor::CastOp>(
newForOp.getLoc(), oldType, newResults[yieldIdx]);
return newResults;
}
/// Fold scf.for iter_arg/result pairs that go through incoming/ougoing
/// a tensor.cast op pair so as to pull the tensor.cast inside the scf.for:
///
/// ```
/// %0 = tensor.cast %t0 : tensor<32x1024xf32> to tensor<?x?xf32>
/// %1 = scf.for %i = %c0 to %c1024 step %c32 iter_args(%iter_t0 = %0)
/// -> (tensor<?x?xf32>) {
/// %2 = call @do(%iter_t0) : (tensor<?x?xf32>) -> tensor<?x?xf32>
/// scf.yield %2 : tensor<?x?xf32>
/// }
/// use_of(%1)
/// ```
///
/// folds into:
///
/// ```
/// %0 = scf.for %arg2 = %c0 to %c1024 step %c32 iter_args(%arg3 = %arg0)
/// -> (tensor<32x1024xf32>) {
/// %2 = tensor.cast %arg3 : tensor<32x1024xf32> to tensor<?x?xf32>
/// %3 = call @do(%2) : (tensor<?x?xf32>) -> tensor<?x?xf32>
/// %4 = tensor.cast %3 : tensor<?x?xf32> to tensor<32x1024xf32>
/// scf.yield %4 : tensor<32x1024xf32>
/// }
/// %1 = tensor.cast %0 : tensor<32x1024xf32> to tensor<?x?xf32>
/// use_of(%1)
/// ```
struct ForOpTensorCastFolder : public OpRewritePattern<ForOp> {
using OpRewritePattern<ForOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ForOp op,
PatternRewriter &rewriter) const override {
for (auto it : llvm::zip(op.getIterOpOperands(), op.getResults())) {
OpOperand &iterOpOperand = std::get<0>(it);
auto incomingCast = iterOpOperand.get().getDefiningOp<tensor::CastOp>();
if (!incomingCast ||
incomingCast.getSource().getType() == incomingCast.getType())
continue;
// If the dest type of the cast does not preserve static information in
// the source type.
if (!tensor::preservesStaticInformation(
incomingCast.getDest().getType(),
incomingCast.getSource().getType()))
continue;
if (!std::get<1>(it).hasOneUse())
continue;
// Create a new ForOp with that iter operand replaced.
rewriter.replaceOp(
op, replaceTensorCastForOpIterArg(rewriter, iterOpOperand,
incomingCast.getSource()));
return success();
}
return failure();
}
};
/// Canonicalize the iter_args of an scf::ForOp that involve a
/// `bufferization.to_tensor` and for which only the last loop iteration is
/// actually visible outside of the loop. The canonicalization looks for a
/// pattern such as:
/// ```
/// %t0 = ... : tensor_type
/// %0 = scf.for ... iter_args(%bb0 : %t0) -> (tensor_type) {
/// ...
/// // %m is either buffer_cast(%bb00) or defined above the loop
/// %m... : memref_type
/// ... // uses of %m with potential inplace updates
/// %new_tensor = bufferization.to_tensor %m : memref_type
/// ...
/// scf.yield %new_tensor : tensor_type
/// }
/// ```
///
/// `%bb0` may have either 0 or 1 use. If it has 1 use it must be exactly a
/// `%m = buffer_cast %bb0` op that feeds into the yielded
/// `bufferization.to_tensor` op.
///
/// If no aliasing write to the memref `%m`, from which `%new_tensor`is loaded,
/// occurs between `bufferization.to_tensor and yield then the value %0
/// visible outside of the loop is the last `bufferization.to_tensor`
/// produced in the loop.
///
/// For now, we approximate the absence of aliasing by only supporting the case
/// when the bufferization.to_tensor is the operation immediately preceding
/// the yield.
//
/// The canonicalization rewrites the pattern as:
/// ```
/// // %m is either a buffer_cast or defined above
/// %m... : memref_type
/// scf.for ... iter_args(%bb0 : %t0) -> (tensor_type) {
/// ... // uses of %m with potential inplace updates
/// scf.yield %bb0: tensor_type
/// }
/// %0 = bufferization.to_tensor %m : memref_type
/// ```
///
/// A later bbArg canonicalization will further rewrite as:
/// ```
/// // %m is either a buffer_cast or defined above
/// %m... : memref_type
/// scf.for ... { // no iter_args
/// ... // uses of %m with potential inplace updates
/// }
/// %0 = bufferization.to_tensor %m : memref_type
/// ```
struct LastTensorLoadCanonicalization : public OpRewritePattern<ForOp> {
using OpRewritePattern<ForOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ForOp forOp,
PatternRewriter &rewriter) const override {
assert(std::next(forOp.getRegion().begin()) == forOp.getRegion().end() &&
"unexpected multiple blocks");
Location loc = forOp.getLoc();
DenseMap<Value, Value> replacements;
for (BlockArgument bbArg : forOp.getRegionIterArgs()) {
unsigned idx = bbArg.getArgNumber() - /*numIv=*/1;
auto yieldOp =
cast<scf::YieldOp>(forOp.getRegion().front().getTerminator());
Value yieldVal = yieldOp->getOperand(idx);
auto tensorLoadOp = yieldVal.getDefiningOp<bufferization::ToTensorOp>();
bool isTensor = llvm::isa<TensorType>(bbArg.getType());
bufferization::ToMemrefOp tensorToMemref;
// Either bbArg has no use or it has a single buffer_cast use.
if (bbArg.hasOneUse())
tensorToMemref =
dyn_cast<bufferization::ToMemrefOp>(*bbArg.getUsers().begin());
if (!isTensor || !tensorLoadOp || (!bbArg.use_empty() && !tensorToMemref))
continue;
// If tensorToMemref is present, it must feed into the `ToTensorOp`.
if (tensorToMemref && tensorLoadOp.getMemref() != tensorToMemref)
continue;
// TODO: Any aliasing write of tensorLoadOp.memref() nested under `forOp`
// must be before `ToTensorOp` in the block so that the lastWrite
// property is not subject to additional side-effects.
// For now, we only support the case when ToTensorOp appears
// immediately before the terminator.
if (tensorLoadOp->getNextNode() != yieldOp)
continue;
// Clone the optional tensorToMemref before forOp.
if (tensorToMemref) {
rewriter.setInsertionPoint(forOp);
rewriter.replaceOpWithNewOp<bufferization::ToMemrefOp>(
tensorToMemref, tensorToMemref.getMemref().getType(),
tensorToMemref.getTensor());
}
// Clone the tensorLoad after forOp.
rewriter.setInsertionPointAfter(forOp);
Value newTensorLoad = rewriter.create<bufferization::ToTensorOp>(
loc, tensorLoadOp.getMemref());
Value forOpResult = forOp.getResult(bbArg.getArgNumber() - /*iv=*/1);
replacements.insert(std::make_pair(forOpResult, newTensorLoad));
// Make the terminator just yield the bbArg, the old tensorLoadOp + the
// old bbArg (that is now directly yielded) will canonicalize away.
rewriter.startRootUpdate(yieldOp);
yieldOp.setOperand(idx, bbArg);
rewriter.finalizeRootUpdate(yieldOp);
}
if (replacements.empty())
return failure();
// We want to replace a subset of the results of `forOp`. rewriter.replaceOp
// replaces the whole op and erase it unconditionally. This is wrong for
// `forOp` as it generally contains ops with side effects.
// Instead, use `rewriter.replaceOpWithIf`.
SmallVector<Value> newResults;
newResults.reserve(forOp.getNumResults());
for (Value v : forOp.getResults()) {
auto it = replacements.find(v);
newResults.push_back((it != replacements.end()) ? it->second : v);
}
unsigned idx = 0;
rewriter.replaceOpWithIf(forOp, newResults, [&](OpOperand &op) {
return op.get() != newResults[idx++];
});
return success();
}
};
} // namespace
void ForOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<ForOpIterArgsFolder, SimplifyTrivialLoops,
LastTensorLoadCanonicalization, ForOpTensorCastFolder>(context);
}
std::optional<APInt> ForOp::getConstantStep() {
IntegerAttr step;
if (matchPattern(getStep(), m_Constant(&step)))
return step.getValue();
return {};
}
Speculation::Speculatability ForOp::getSpeculatability() {
// `scf.for (I = Start; I < End; I += 1)` terminates for all values of Start
// and End.
if (auto constantStep = getConstantStep())
if (*constantStep == 1)
return Speculation::RecursivelySpeculatable;
// For Step != 1, the loop may not terminate. We can add more smarts here if
// needed.
return Speculation::NotSpeculatable;
}
//===----------------------------------------------------------------------===//
// ForallOp
//===----------------------------------------------------------------------===//
LogicalResult ForallOp::verify() {
unsigned numLoops = getRank();
// Check number of outputs.
if (getNumResults() != getOutputs().size())
return emitOpError("produces ")
<< getNumResults() << " results, but has only "
<< getOutputs().size() << " outputs";
// Check that the body defines block arguments for thread indices and outputs.
auto *body = getBody();
if (body->getNumArguments() != numLoops + getOutputs().size())
return emitOpError("region expects ") << numLoops << " arguments";
for (int64_t i = 0; i < numLoops; ++i)
if (!body->getArgument(i).getType().isIndex())
return emitOpError("expects ")
<< i << "-th block argument to be an index";
for (unsigned i = 0; i < getOutputs().size(); ++i)
if (body->getArgument(i + numLoops).getType() != getOutputs()[i].getType())
return emitOpError("type mismatch between ")
<< i << "-th output and corresponding block argument";
if (getMapping().has_value() && !getMapping()->empty()) {
if (static_cast<int64_t>(getMapping()->size()) != numLoops)
return emitOpError() << "mapping attribute size must match op rank";
for (auto map : getMapping()->getValue()) {
if (!isa<DeviceMappingAttrInterface>(map))
return emitOpError()
<< getMappingAttrName() << " is not device mapping attribute";
}
}
// Verify mixed static/dynamic control variables.
Operation *op = getOperation();
if (failed(verifyListOfOperandsOrIntegers(op, "lower bound", numLoops,
getStaticLowerBound(),
getDynamicLowerBound())))
return failure();
if (failed(verifyListOfOperandsOrIntegers(op, "upper bound", numLoops,
getStaticUpperBound(),
getDynamicUpperBound())))
return failure();
if (failed(verifyListOfOperandsOrIntegers(op, "step", numLoops,
getStaticStep(), getDynamicStep())))
return failure();
return success();
}
void ForallOp::print(OpAsmPrinter &p) {
Operation *op = getOperation();
p << " (" << getInductionVars();
if (isNormalized()) {
p << ") in ";
printDynamicIndexList(p, op, getDynamicUpperBound(), getStaticUpperBound(),
/*valueTypes=*/{}, /*scalables=*/{},
OpAsmParser::Delimiter::Paren);
} else {
p << ") = ";
printDynamicIndexList(p, op, getDynamicLowerBound(), getStaticLowerBound(),
/*valueTypes=*/{}, /*scalables=*/{},
OpAsmParser::Delimiter::Paren);
p << " to ";
printDynamicIndexList(p, op, getDynamicUpperBound(), getStaticUpperBound(),
/*valueTypes=*/{}, /*scalables=*/{},
OpAsmParser::Delimiter::Paren);
p << " step ";
printDynamicIndexList(p, op, getDynamicStep(), getStaticStep(),
/*valueTypes=*/{}, /*scalable=*/{},
OpAsmParser::Delimiter::Paren);
}
printInitializationList(p, getRegionOutArgs(), getOutputs(), " shared_outs");
p << " ";
if (!getRegionOutArgs().empty())
p << "-> (" << getResultTypes() << ") ";
p.printRegion(getRegion(),
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/getNumResults() > 0);
p.printOptionalAttrDict(op->getAttrs(), {getOperandSegmentSizesAttrName(),
getStaticLowerBoundAttrName(),
getStaticUpperBoundAttrName(),
getStaticStepAttrName()});
}
ParseResult ForallOp::parse(OpAsmParser &parser, OperationState &result) {
OpBuilder b(parser.getContext());
auto indexType = b.getIndexType();
// Parse an opening `(` followed by thread index variables followed by `)`
// TODO: when we can refer to such "induction variable"-like handles from the
// declarative assembly format, we can implement the parser as a custom hook.
SmallVector<OpAsmParser::Argument, 4> ivs;
if (parser.parseArgumentList(ivs, OpAsmParser::Delimiter::Paren))
return failure();
DenseI64ArrayAttr staticLbs, staticUbs, staticSteps;
SmallVector<OpAsmParser::UnresolvedOperand> dynamicLbs, dynamicUbs,
dynamicSteps;
if (succeeded(parser.parseOptionalKeyword("in"))) {
// Parse upper bounds.
if (parseDynamicIndexList(parser, dynamicUbs, staticUbs,
/*valueTypes=*/nullptr,
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(dynamicUbs, indexType, result.operands))
return failure();
unsigned numLoops = ivs.size();
staticLbs = b.getDenseI64ArrayAttr(SmallVector<int64_t>(numLoops, 0));
staticSteps = b.getDenseI64ArrayAttr(SmallVector<int64_t>(numLoops, 1));
} else {
// Parse lower bounds.
if (parser.parseEqual() ||
parseDynamicIndexList(parser, dynamicLbs, staticLbs,
/*valueTypes=*/nullptr,
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(dynamicLbs, indexType, result.operands))
return failure();
// Parse upper bounds.
if (parser.parseKeyword("to") ||
parseDynamicIndexList(parser, dynamicUbs, staticUbs,
/*valueTypes=*/nullptr,
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(dynamicUbs, indexType, result.operands))
return failure();
// Parse step values.
if (parser.parseKeyword("step") ||
parseDynamicIndexList(parser, dynamicSteps, staticSteps,
/*valueTypes=*/nullptr,
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(dynamicSteps, indexType, result.operands))
return failure();
}
// Parse out operands and results.
SmallVector<OpAsmParser::Argument, 4> regionOutArgs;
SmallVector<OpAsmParser::UnresolvedOperand, 4> outOperands;
SMLoc outOperandsLoc = parser.getCurrentLocation();
if (succeeded(parser.parseOptionalKeyword("shared_outs"))) {
if (outOperands.size() != result.types.size())
return parser.emitError(outOperandsLoc,
"mismatch between out operands and types");
if (parser.parseAssignmentList(regionOutArgs, outOperands) ||
parser.parseOptionalArrowTypeList(result.types) ||
parser.resolveOperands(outOperands, result.types, outOperandsLoc,
result.operands))
return failure();
}
// Parse region.
SmallVector<OpAsmParser::Argument, 4> regionArgs;
std::unique_ptr<Region> region = std::make_unique<Region>();
for (auto &iv : ivs) {
iv.type = b.getIndexType();
regionArgs.push_back(iv);
}
for (const auto &it : llvm::enumerate(regionOutArgs)) {
auto &out = it.value();
out.type = result.types[it.index()];
regionArgs.push_back(out);
}
if (parser.parseRegion(*region, regionArgs))
return failure();
// Ensure terminator and move region.
ForallOp::ensureTerminator(*region, b, result.location);
result.addRegion(std::move(region));
// Parse the optional attribute list.
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
result.addAttribute("staticLowerBound", staticLbs);
result.addAttribute("staticUpperBound", staticUbs);
result.addAttribute("staticStep", staticSteps);
result.addAttribute("operandSegmentSizes",
parser.getBuilder().getDenseI32ArrayAttr(
{static_cast<int32_t>(dynamicLbs.size()),
static_cast<int32_t>(dynamicUbs.size()),
static_cast<int32_t>(dynamicSteps.size()),
static_cast<int32_t>(outOperands.size())}));
return success();
}
// Builder that takes loop bounds.
void ForallOp::build(
mlir::OpBuilder &b, mlir::OperationState &result,
ArrayRef<OpFoldResult> lbs, ArrayRef<OpFoldResult> ubs,
ArrayRef<OpFoldResult> steps, ValueRange outputs,
std::optional<ArrayAttr> mapping,
function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
SmallVector<int64_t> staticLbs, staticUbs, staticSteps;
SmallVector<Value> dynamicLbs, dynamicUbs, dynamicSteps;
dispatchIndexOpFoldResults(lbs, dynamicLbs, staticLbs);
dispatchIndexOpFoldResults(ubs, dynamicUbs, staticUbs);
dispatchIndexOpFoldResults(steps, dynamicSteps, staticSteps);
result.addOperands(dynamicLbs);
result.addOperands(dynamicUbs);
result.addOperands(dynamicSteps);
result.addOperands(outputs);
result.addTypes(TypeRange(outputs));
result.addAttribute(getStaticLowerBoundAttrName(result.name),
b.getDenseI64ArrayAttr(staticLbs));
result.addAttribute(getStaticUpperBoundAttrName(result.name),
b.getDenseI64ArrayAttr(staticUbs));
result.addAttribute(getStaticStepAttrName(result.name),
b.getDenseI64ArrayAttr(staticSteps));
result.addAttribute(
"operandSegmentSizes",
b.getDenseI32ArrayAttr({static_cast<int32_t>(dynamicLbs.size()),
static_cast<int32_t>(dynamicUbs.size()),
static_cast<int32_t>(dynamicSteps.size()),
static_cast<int32_t>(outputs.size())}));
if (mapping.has_value()) {
result.addAttribute(ForallOp::getMappingAttrName(result.name),
mapping.value());
}
Region *bodyRegion = result.addRegion();
OpBuilder::InsertionGuard g(b);
b.createBlock(bodyRegion);
Block &bodyBlock = bodyRegion->front();
// Add block arguments for indices and outputs.
bodyBlock.addArguments(
SmallVector<Type>(lbs.size(), b.getIndexType()),
SmallVector<Location>(staticLbs.size(), result.location));
bodyBlock.addArguments(
TypeRange(outputs),
SmallVector<Location>(outputs.size(), result.location));
b.setInsertionPointToStart(&bodyBlock);
if (!bodyBuilderFn) {
ForallOp::ensureTerminator(*bodyRegion, b, result.location);
return;
}
bodyBuilderFn(b, result.location, bodyBlock.getArguments());
#ifndef NDEBUG
auto terminator = llvm::dyn_cast<InParallelOp>(bodyBlock.getTerminator());
assert(terminator &&
"expected bodyBuilderFn to create InParallelOp terminator");
#endif // NDEBUG
}
// Builder that takes loop bounds.
void ForallOp::build(
mlir::OpBuilder &b, mlir::OperationState &result,
ArrayRef<OpFoldResult> ubs, ValueRange outputs,
std::optional<ArrayAttr> mapping,
function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
unsigned numLoops = ubs.size();
SmallVector<OpFoldResult> lbs(numLoops, b.getIndexAttr(0));
SmallVector<OpFoldResult> steps(numLoops, b.getIndexAttr(1));
build(b, result, lbs, ubs, steps, outputs, mapping, bodyBuilderFn);
}
// Checks if the lbs are zeros and steps are ones.
bool ForallOp::isNormalized() {
auto allEqual = [](ArrayRef<OpFoldResult> results, int64_t val) {
return llvm::all_of(results, [&](OpFoldResult ofr) {
auto intValue = getConstantIntValue(ofr);
return intValue.has_value() && intValue == val;
});
};
return allEqual(getMixedLowerBound(), 0) && allEqual(getMixedStep(), 1);
}
// The ensureTerminator method generated by SingleBlockImplicitTerminator is
// unaware of the fact that our terminator also needs a region to be
// well-formed. We override it here to ensure that we do the right thing.
void ForallOp::ensureTerminator(Region ®ion, OpBuilder &builder,
Location loc) {
OpTrait::SingleBlockImplicitTerminator<InParallelOp>::Impl<
ForallOp>::ensureTerminator(region, builder, loc);
auto terminator =
llvm::dyn_cast<InParallelOp>(region.front().getTerminator());
if (terminator.getRegion().empty())
builder.createBlock(&terminator.getRegion());
}
InParallelOp ForallOp::getTerminator() {
return cast<InParallelOp>(getBody()->getTerminator());
}
ForallOp mlir::scf::getForallOpThreadIndexOwner(Value val) {
auto tidxArg = llvm::dyn_cast<BlockArgument>(val);
if (!tidxArg)
return ForallOp();
assert(tidxArg.getOwner() && "unlinked block argument");
auto *containingOp = tidxArg.getOwner()->getParentOp();
return dyn_cast<ForallOp>(containingOp);
}
namespace {
/// Fold tensor.dim(forall shared_outs(... = %t)) to tensor.dim(%t).
struct DimOfForallOp : public OpRewritePattern<tensor::DimOp> {
using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
LogicalResult matchAndRewrite(tensor::DimOp dimOp,
PatternRewriter &rewriter) const final {
auto forallOp = dimOp.getSource().getDefiningOp<ForallOp>();
if (!forallOp)
return failure();
Value sharedOut =
forallOp.getTiedOpOperand(llvm::cast<OpResult>(dimOp.getSource()))
->get();
rewriter.updateRootInPlace(
dimOp, [&]() { dimOp.getSourceMutable().assign(sharedOut); });
return success();
}
};
class ForallOpControlOperandsFolder : public OpRewritePattern<ForallOp> {
public:
using OpRewritePattern<ForallOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ForallOp op,
PatternRewriter &rewriter) const override {
SmallVector<OpFoldResult> mixedLowerBound(op.getMixedLowerBound());
SmallVector<OpFoldResult> mixedUpperBound(op.getMixedUpperBound());
SmallVector<OpFoldResult> mixedStep(op.getMixedStep());
if (failed(foldDynamicIndexList(rewriter, mixedLowerBound)) &&
failed(foldDynamicIndexList(rewriter, mixedUpperBound)) &&
failed(foldDynamicIndexList(rewriter, mixedStep)))
return failure();
rewriter.updateRootInPlace(op, [&]() {
SmallVector<Value> dynamicLowerBound, dynamicUpperBound, dynamicStep;
SmallVector<int64_t> staticLowerBound, staticUpperBound, staticStep;
dispatchIndexOpFoldResults(mixedLowerBound, dynamicLowerBound,
staticLowerBound);
op.getDynamicLowerBoundMutable().assign(dynamicLowerBound);
op.setStaticLowerBound(staticLowerBound);
dispatchIndexOpFoldResults(mixedUpperBound, dynamicUpperBound,
staticUpperBound);
op.getDynamicUpperBoundMutable().assign(dynamicUpperBound);
op.setStaticUpperBound(staticUpperBound);
dispatchIndexOpFoldResults(mixedStep, dynamicStep, staticStep);
op.getDynamicStepMutable().assign(dynamicStep);
op.setStaticStep(staticStep);
op->setAttr(ForallOp::getOperandSegmentSizeAttr(),
rewriter.getDenseI32ArrayAttr(
{static_cast<int32_t>(dynamicLowerBound.size()),
static_cast<int32_t>(dynamicUpperBound.size()),
static_cast<int32_t>(dynamicStep.size()),
static_cast<int32_t>(op.getNumResults())}));
});
return success();
}
};
struct ForallOpSingleOrZeroIterationDimsFolder
: public OpRewritePattern<ForallOp> {
using OpRewritePattern<ForallOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ForallOp op,
PatternRewriter &rewriter) const override {
// Do not fold dimensions if they are mapped to processing units.
if (op.getMapping().has_value())
return failure();
Location loc = op.getLoc();
// Compute new loop bounds that omit all single-iteration loop dimensions.
SmallVector<OpFoldResult> newMixedLowerBounds, newMixedUpperBounds,
newMixedSteps;
IRMapping mapping;
for (auto [lb, ub, step, iv] :
llvm::zip(op.getMixedLowerBound(), op.getMixedUpperBound(),
op.getMixedStep(), op.getInductionVars())) {
auto numIterations = constantTripCount(lb, ub, step);
if (numIterations.has_value()) {
// Remove the loop if it performs zero iterations.
if (*numIterations == 0) {
rewriter.replaceOp(op, op.getOutputs());
return success();
}
// Replace the loop induction variable by the lower bound if the loop
// performs a single iteration. Otherwise, copy the loop bounds.
if (*numIterations == 1) {
mapping.map(iv, getValueOrCreateConstantIndexOp(rewriter, loc, lb));
continue;
}
}
newMixedLowerBounds.push_back(lb);
newMixedUpperBounds.push_back(ub);
newMixedSteps.push_back(step);
}
// Exit if none of the loop dimensions perform a single iteration.
if (newMixedLowerBounds.size() == static_cast<unsigned>(op.getRank())) {
return rewriter.notifyMatchFailure(
op, "no dimensions have 0 or 1 iterations");
}
// All of the loop dimensions perform a single iteration. Inline loop body.
if (newMixedLowerBounds.empty()) {
promote(rewriter, op);
return success();
}
// Replace the loop by a lower-dimensional loop.
ForallOp newOp;
newOp = rewriter.create<ForallOp>(loc, newMixedLowerBounds,
newMixedUpperBounds, newMixedSteps,
op.getOutputs(), std::nullopt, nullptr);
newOp.getBodyRegion().getBlocks().clear();
// The new loop needs to keep all attributes from the old one, except for
// "operandSegmentSizes" and static loop bound attributes which capture
// the outdated information of the old iteration domain.
SmallVector<StringAttr> elidedAttrs{newOp.getOperandSegmentSizesAttrName(),
newOp.getStaticLowerBoundAttrName(),
newOp.getStaticUpperBoundAttrName(),
newOp.getStaticStepAttrName()};
for (const auto &namedAttr : op->getAttrs()) {
if (llvm::is_contained(elidedAttrs, namedAttr.getName()))
continue;
rewriter.updateRootInPlace(newOp, [&]() {
newOp->setAttr(namedAttr.getName(), namedAttr.getValue());
});
}
rewriter.cloneRegionBefore(op.getRegion(), newOp.getRegion(),
newOp.getRegion().begin(), mapping);
rewriter.replaceOp(op, newOp.getResults());
return success();
}
};
struct FoldTensorCastOfOutputIntoForallOp
: public OpRewritePattern<scf::ForallOp> {
using OpRewritePattern<scf::ForallOp>::OpRewritePattern;
struct TypeCast {
Type srcType;
Type dstType;
};
LogicalResult matchAndRewrite(scf::ForallOp forallOp,
PatternRewriter &rewriter) const final {
llvm::SmallMapVector<unsigned, TypeCast, 2> tensorCastProducers;
llvm::SmallVector<Value> newOutputTensors = forallOp.getOutputs();
for (auto en : llvm::enumerate(newOutputTensors)) {
auto castOp = en.value().getDefiningOp<tensor::CastOp>();
if (!castOp)
continue;
// Only casts that that preserve static information, i.e. will make the
// loop result type "more" static than before, will be folded.
if (!tensor::preservesStaticInformation(castOp.getDest().getType(),
castOp.getSource().getType())) {
continue;
}
tensorCastProducers[en.index()] =
TypeCast{castOp.getSource().getType(), castOp.getType()};
newOutputTensors[en.index()] = castOp.getSource();
}
if (tensorCastProducers.empty())
return failure();
// Create new loop.
Location loc = forallOp.getLoc();
auto newForallOp = rewriter.create<ForallOp>(
loc, forallOp.getMixedLowerBound(), forallOp.getMixedUpperBound(),
forallOp.getMixedStep(), newOutputTensors, forallOp.getMapping(),
[&](OpBuilder nestedBuilder, Location nestedLoc, ValueRange bbArgs) {
auto castBlockArgs =
llvm::to_vector(bbArgs.take_back(forallOp->getNumResults()));
for (auto [index, cast] : tensorCastProducers) {
Value &oldTypeBBArg = castBlockArgs[index];
oldTypeBBArg = nestedBuilder.create<tensor::CastOp>(
nestedLoc, cast.dstType, oldTypeBBArg);
}
// Move old body into new parallel loop.
SmallVector<Value> ivsBlockArgs =
llvm::to_vector(bbArgs.take_front(forallOp.getRank()));
ivsBlockArgs.append(castBlockArgs);
rewriter.mergeBlocks(forallOp.getBody(),
bbArgs.front().getParentBlock(), ivsBlockArgs);
});
// After `mergeBlocks` happened, the destinations in the terminator were
// mapped to the tensor.cast old-typed results of the output bbArgs. The
// destination have to be updated to point to the output bbArgs directly.
auto terminator = newForallOp.getTerminator();
for (auto [yieldingOp, outputBlockArg] :
llvm::zip(terminator.getYieldingOps(),
newForallOp.getOutputBlockArguments())) {
auto insertSliceOp = cast<tensor::ParallelInsertSliceOp>(yieldingOp);
insertSliceOp.getDestMutable().assign(outputBlockArg);
}
// Cast results back to the original types.
rewriter.setInsertionPointAfter(newForallOp);
SmallVector<Value> castResults = newForallOp.getResults();
for (auto &item : tensorCastProducers) {
Value &oldTypeResult = castResults[item.first];
oldTypeResult = rewriter.create<tensor::CastOp>(loc, item.second.dstType,
oldTypeResult);
}
rewriter.replaceOp(forallOp, castResults);
return success();
}
};
} // namespace
void ForallOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<DimOfForallOp, FoldTensorCastOfOutputIntoForallOp,
ForallOpControlOperandsFolder,
ForallOpSingleOrZeroIterationDimsFolder>(context);
}
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void ForallOp::getSuccessorRegions(std::optional<unsigned> index,
ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> ®ions) {
// Both the operation itself and the region may be branching into the body or
// back into the operation itself. It is possible for loop not to enter the
// body.
regions.push_back(RegionSuccessor(&getRegion()));
regions.push_back(RegionSuccessor());
}
//===----------------------------------------------------------------------===//
// InParallelOp
//===----------------------------------------------------------------------===//
// Build a InParallelOp with mixed static and dynamic entries.
void InParallelOp::build(OpBuilder &b, OperationState &result) {
OpBuilder::InsertionGuard g(b);
Region *bodyRegion = result.addRegion();
b.createBlock(bodyRegion);
}
LogicalResult InParallelOp::verify() {
scf::ForallOp forallOp =
dyn_cast<scf::ForallOp>(getOperation()->getParentOp());
if (!forallOp)
return this->emitOpError("expected forall op parent");
// TODO: InParallelOpInterface.
for (Operation &op : getRegion().front().getOperations()) {
if (!isa<tensor::ParallelInsertSliceOp>(op)) {
return this->emitOpError("expected only ")
<< tensor::ParallelInsertSliceOp::getOperationName() << " ops";
}
// Verify that inserts are into out block arguments.
Value dest = cast<tensor::ParallelInsertSliceOp>(op).getDest();
ArrayRef<BlockArgument> regionOutArgs = forallOp.getRegionOutArgs();
if (!llvm::is_contained(regionOutArgs, dest))
return op.emitOpError("may only insert into an output block argument");
}
return success();
}
void InParallelOp::print(OpAsmPrinter &p) {
p << " ";
p.printRegion(getRegion(),
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/false);
p.printOptionalAttrDict(getOperation()->getAttrs());
}
ParseResult InParallelOp::parse(OpAsmParser &parser, OperationState &result) {
auto &builder = parser.getBuilder();
SmallVector<OpAsmParser::Argument, 8> regionOperands;
std::unique_ptr<Region> region = std::make_unique<Region>();
if (parser.parseRegion(*region, regionOperands))
return failure();
if (region->empty())
OpBuilder(builder.getContext()).createBlock(region.get());
result.addRegion(std::move(region));
// Parse the optional attribute list.
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
return success();
}
OpResult InParallelOp::getParentResult(int64_t idx) {
return getOperation()->getParentOp()->getResult(idx);
}
SmallVector<BlockArgument> InParallelOp::getDests() {
return llvm::to_vector<4>(
llvm::map_range(getYieldingOps(), [](Operation &op) {
// Add new ops here as needed.
auto insertSliceOp = cast<tensor::ParallelInsertSliceOp>(&op);
return llvm::cast<BlockArgument>(insertSliceOp.getDest());
}));
}
llvm::iterator_range<Block::iterator> InParallelOp::getYieldingOps() {
return getRegion().front().getOperations();
}
//===----------------------------------------------------------------------===//
// IfOp
//===----------------------------------------------------------------------===//
bool mlir::scf::insideMutuallyExclusiveBranches(Operation *a, Operation *b) {
assert(a && "expected non-empty operation");
assert(b && "expected non-empty operation");
IfOp ifOp = a->getParentOfType<IfOp>();
while (ifOp) {
// Check if b is inside ifOp. (We already know that a is.)
if (ifOp->isProperAncestor(b))
// b is contained in ifOp. a and b are in mutually exclusive branches if
// they are in different blocks of ifOp.
return static_cast<bool>(ifOp.thenBlock()->findAncestorOpInBlock(*a)) !=
static_cast<bool>(ifOp.thenBlock()->findAncestorOpInBlock(*b));
// Check next enclosing IfOp.
ifOp = ifOp->getParentOfType<IfOp>();
}
// Could not find a common IfOp among a's and b's ancestors.
return false;
}
LogicalResult
IfOp::inferReturnTypes(MLIRContext *ctx, std::optional<Location> loc,
IfOp::Adaptor adaptor,
SmallVectorImpl<Type> &inferredReturnTypes) {
if (adaptor.getRegions().empty())
return failure();
Region *r = &adaptor.getThenRegion();
if (r->empty())
return failure();
Block &b = r->front();
if (b.empty())
return failure();
auto yieldOp = llvm::dyn_cast<YieldOp>(b.back());
if (!yieldOp)
return failure();
TypeRange types = yieldOp.getOperandTypes();
inferredReturnTypes.insert(inferredReturnTypes.end(), types.begin(),
types.end());
return success();
}
void IfOp::build(OpBuilder &builder, OperationState &result,
TypeRange resultTypes, Value cond) {
return build(builder, result, resultTypes, cond, /*addThenBlock=*/false,
/*addElseBlock=*/false);
}
void IfOp::build(OpBuilder &builder, OperationState &result,
TypeRange resultTypes, Value cond, bool addThenBlock,
bool addElseBlock) {
assert((!addElseBlock || addThenBlock) &&
"must not create else block w/o then block");
result.addTypes(resultTypes);
result.addOperands(cond);
// Add regions and blocks.
OpBuilder::InsertionGuard guard(builder);
Region *thenRegion = result.addRegion();
if (addThenBlock)
builder.createBlock(thenRegion);
Region *elseRegion = result.addRegion();
if (addElseBlock)
builder.createBlock(elseRegion);
}
void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
bool withElseRegion) {
build(builder, result, TypeRange{}, cond, withElseRegion);
}
void IfOp::build(OpBuilder &builder, OperationState &result,
TypeRange resultTypes, Value cond, bool withElseRegion) {
result.addTypes(resultTypes);
result.addOperands(cond);
// Build then region.
OpBuilder::InsertionGuard guard(builder);
Region *thenRegion = result.addRegion();
builder.createBlock(thenRegion);
if (resultTypes.empty())
IfOp::ensureTerminator(*thenRegion, builder, result.location);
// Build else region.
Region *elseRegion = result.addRegion();
if (withElseRegion) {
builder.createBlock(elseRegion);
if (resultTypes.empty())
IfOp::ensureTerminator(*elseRegion, builder, result.location);
}
}
void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
function_ref<void(OpBuilder &, Location)> thenBuilder,
function_ref<void(OpBuilder &, Location)> elseBuilder) {
assert(thenBuilder && "the builder callback for 'then' must be present");
result.addOperands(cond);
// Build then region.
OpBuilder::InsertionGuard guard(builder);
Region *thenRegion = result.addRegion();
builder.createBlock(thenRegion);
thenBuilder(builder, result.location);
// Build else region.
Region *elseRegion = result.addRegion();
if (elseBuilder) {
builder.createBlock(elseRegion);
elseBuilder(builder, result.location);
}
// Infer result types.
SmallVector<Type> inferredReturnTypes;
MLIRContext *ctx = builder.getContext();
auto attrDict = DictionaryAttr::get(ctx, result.attributes);
if (succeeded(inferReturnTypes(ctx, std::nullopt, result.operands, attrDict,
/*properties=*/nullptr, result.regions,
inferredReturnTypes))) {
result.addTypes(inferredReturnTypes);
}
}
LogicalResult IfOp::verify() {
if (getNumResults() != 0 && getElseRegion().empty())
return emitOpError("must have an else block if defining values");
return success();
}
ParseResult IfOp::parse(OpAsmParser &parser, OperationState &result) {
// Create the regions for 'then'.
result.regions.reserve(2);
Region *thenRegion = result.addRegion();
Region *elseRegion = result.addRegion();
auto &builder = parser.getBuilder();
OpAsmParser::UnresolvedOperand cond;
Type i1Type = builder.getIntegerType(1);
if (parser.parseOperand(cond) ||
parser.resolveOperand(cond, i1Type, result.operands))
return failure();
// Parse optional results type list.
if (parser.parseOptionalArrowTypeList(result.types))
return failure();
// Parse the 'then' region.
if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
// If we find an 'else' keyword then parse the 'else' region.
if (!parser.parseOptionalKeyword("else")) {
if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
}
// Parse the optional attribute list.
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
return success();
}
void IfOp::print(OpAsmPrinter &p) {
bool printBlockTerminators = false;
p << " " << getCondition();
if (!getResults().empty()) {
p << " -> (" << getResultTypes() << ")";
// Print yield explicitly if the op defines values.
printBlockTerminators = true;
}
p << ' ';
p.printRegion(getThenRegion(),
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/printBlockTerminators);
// Print the 'else' regions if it exists and has a block.
auto &elseRegion = getElseRegion();
if (!elseRegion.empty()) {
p << " else ";
p.printRegion(elseRegion,
/*printEntryBlockArgs=*/false,
/*printBlockTerminators=*/printBlockTerminators);
}
p.printOptionalAttrDict((*this)->getAttrs());
}
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void IfOp::getSuccessorRegions(std::optional<unsigned> index,
ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> ®ions) {
// The `then` and the `else` region branch back to the parent operation.
if (index) {
regions.push_back(RegionSuccessor(getResults()));
return;
}
// Don't consider the else region if it is empty.
Region *elseRegion = &this->getElseRegion();
if (elseRegion->empty())
elseRegion = nullptr;
// Otherwise, the successor is dependent on the condition.
bool condition;
if (auto condAttr = llvm::dyn_cast_or_null<IntegerAttr>(operands.front())) {
condition = condAttr.getValue().isOne();
} else {
// If the condition isn't constant, both regions may be executed.
regions.push_back(RegionSuccessor(&getThenRegion()));
// If the else region does not exist, it is not a viable successor, so the
// control will go back to this operation instead.
if (elseRegion)
regions.push_back(RegionSuccessor(elseRegion));
else
regions.push_back(RegionSuccessor());
return;
}
// Add the successor regions using the condition.
regions.push_back(RegionSuccessor(condition ? &getThenRegion() : elseRegion));
}
LogicalResult IfOp::fold(FoldAdaptor adaptor,
SmallVectorImpl<OpFoldResult> &results) {
// if (!c) then A() else B() -> if c then B() else A()
if (getElseRegion().empty())
return failure();
arith::XOrIOp xorStmt = getCondition().getDefiningOp<arith::XOrIOp>();
if (!xorStmt)
return failure();
if (!matchPattern(xorStmt.getRhs(), m_One()))
return failure();
getConditionMutable().assign(xorStmt.getLhs());
Block *thenBlock = &getThenRegion().front();
// It would be nicer to use iplist::swap, but that has no implemented
// callbacks See: https://llvm.org/doxygen/ilist_8h_source.html#l00224
getThenRegion().getBlocks().splice(getThenRegion().getBlocks().begin(),
getElseRegion().getBlocks());
getElseRegion().getBlocks().splice(getElseRegion().getBlocks().begin(),
getThenRegion().getBlocks(), thenBlock);
return success();
}
void IfOp::getRegionInvocationBounds(
ArrayRef<Attribute> operands,
SmallVectorImpl<InvocationBounds> &invocationBounds) {
if (auto cond = llvm::dyn_cast_or_null<BoolAttr>(operands[0])) {
// If the condition is known, then one region is known to be executed once
// and the other zero times.
invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
invocationBounds.emplace_back(0, cond.getValue() ? 0 : 1);
} else {
// Non-constant condition. Each region may be executed 0 or 1 times.
invocationBounds.assign(2, {0, 1});
}
}
namespace {
// Pattern to remove unused IfOp results.
struct RemoveUnusedResults : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
void transferBody(Block *source, Block *dest, ArrayRef<OpResult> usedResults,
PatternRewriter &rewriter) const {
// Move all operations to the destination block.
rewriter.mergeBlocks(source, dest);
// Replace the yield op by one that returns only the used values.
auto yieldOp = cast<scf::YieldOp>(dest->getTerminator());
SmallVector<Value, 4> usedOperands;
llvm::transform(usedResults, std::back_inserter(usedOperands),
[&](OpResult result) {
return yieldOp.getOperand(result.getResultNumber());
});
rewriter.updateRootInPlace(yieldOp,
[&]() { yieldOp->setOperands(usedOperands); });
}
LogicalResult matchAndRewrite(IfOp op,
PatternRewriter &rewriter) const override {
// Compute the list of used results.
SmallVector<OpResult, 4> usedResults;
llvm::copy_if(op.getResults(), std::back_inserter(usedResults),
[](OpResult result) { return !result.use_empty(); });
// Replace the operation if only a subset of its results have uses.
if (usedResults.size() == op.getNumResults())
return failure();
// Compute the result types of the replacement operation.
SmallVector<Type, 4> newTypes;
llvm::transform(usedResults, std::back_inserter(newTypes),
[](OpResult result) { return result.getType(); });
// Create a replacement operation with empty then and else regions.
auto newOp =
rewriter.create<IfOp>(op.getLoc(), newTypes, op.getCondition());
rewriter.createBlock(&newOp.getThenRegion());
rewriter.createBlock(&newOp.getElseRegion());
// Move the bodies and replace the terminators (note there is a then and
// an else region since the operation returns results).
transferBody(op.getBody(0), newOp.getBody(0), usedResults, rewriter);
transferBody(op.getBody(1), newOp.getBody(1), usedResults, rewriter);
// Replace the operation by the new one.
SmallVector<Value, 4> repResults(op.getNumResults());
for (const auto &en : llvm::enumerate(usedResults))
repResults[en.value().getResultNumber()] = newOp.getResult(en.index());
rewriter.replaceOp(op, repResults);
return success();
}
};
struct RemoveStaticCondition : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp op,
PatternRewriter &rewriter) const override {
BoolAttr condition;
if (!matchPattern(op.getCondition(), m_Constant(&condition)))
return failure();
if (condition.getValue())
replaceOpWithRegion(rewriter, op, op.getThenRegion());
else if (!op.getElseRegion().empty())
replaceOpWithRegion(rewriter, op, op.getElseRegion());
else
rewriter.eraseOp(op);
return success();
}
};
/// Hoist any yielded results whose operands are defined outside
/// the if, to a select instruction.
struct ConvertTrivialIfToSelect : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp op,
PatternRewriter &rewriter) const override {
if (op->getNumResults() == 0)
return failure();
auto cond = op.getCondition();
auto thenYieldArgs = op.thenYield().getOperands();
auto elseYieldArgs = op.elseYield().getOperands();
SmallVector<Type> nonHoistable;
for (auto [trueVal, falseVal] : llvm::zip(thenYieldArgs, elseYieldArgs)) {
if (&op.getThenRegion() == trueVal.getParentRegion() ||
&op.getElseRegion() == falseVal.getParentRegion())
nonHoistable.push_back(trueVal.getType());
}
// Early exit if there aren't any yielded values we can
// hoist outside the if.
if (nonHoistable.size() == op->getNumResults())
return failure();
IfOp replacement = rewriter.create<IfOp>(op.getLoc(), nonHoistable, cond,
/*withElseRegion=*/false);
if (replacement.thenBlock())
rewriter.eraseBlock(replacement.thenBlock());
replacement.getThenRegion().takeBody(op.getThenRegion());
replacement.getElseRegion().takeBody(op.getElseRegion());
SmallVector<Value> results(op->getNumResults());
assert(thenYieldArgs.size() == results.size());
assert(elseYieldArgs.size() == results.size());
SmallVector<Value> trueYields;
SmallVector<Value> falseYields;
rewriter.setInsertionPoint(replacement);
for (const auto &it :
llvm::enumerate(llvm::zip(thenYieldArgs, elseYieldArgs))) {
Value trueVal = std::get<0>(it.value());
Value falseVal = std::get<1>(it.value());
if (&replacement.getThenRegion() == trueVal.getParentRegion() ||
&replacement.getElseRegion() == falseVal.getParentRegion()) {
results[it.index()] = replacement.getResult(trueYields.size());
trueYields.push_back(trueVal);
falseYields.push_back(falseVal);
} else if (trueVal == falseVal)
results[it.index()] = trueVal;
else
results[it.index()] = rewriter.create<arith::SelectOp>(
op.getLoc(), cond, trueVal, falseVal);
}
rewriter.setInsertionPointToEnd(replacement.thenBlock());
rewriter.replaceOpWithNewOp<YieldOp>(replacement.thenYield(), trueYields);
rewriter.setInsertionPointToEnd(replacement.elseBlock());
rewriter.replaceOpWithNewOp<YieldOp>(replacement.elseYield(), falseYields);
rewriter.replaceOp(op, results);
return success();
}
};
/// Allow the true region of an if to assume the condition is true
/// and vice versa. For example:
///
/// scf.if %cmp {
/// print(%cmp)
/// }
///
/// becomes
///
/// scf.if %cmp {
/// print(true)
/// }
///
struct ConditionPropagation : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp op,
PatternRewriter &rewriter) const override {
// Early exit if the condition is constant since replacing a constant
// in the body with another constant isn't a simplification.
if (matchPattern(op.getCondition(), m_Constant()))
return failure();
bool changed = false;
mlir::Type i1Ty = rewriter.getI1Type();
// These variables serve to prevent creating duplicate constants
// and hold constant true or false values.
Value constantTrue = nullptr;
Value constantFalse = nullptr;
for (OpOperand &use :
llvm::make_early_inc_range(op.getCondition().getUses())) {
if (op.getThenRegion().isAncestor(use.getOwner()->getParentRegion())) {
changed = true;
if (!constantTrue)
constantTrue = rewriter.create<arith::ConstantOp>(
op.getLoc(), i1Ty, rewriter.getIntegerAttr(i1Ty, 1));
rewriter.updateRootInPlace(use.getOwner(),
[&]() { use.set(constantTrue); });
} else if (op.getElseRegion().isAncestor(
use.getOwner()->getParentRegion())) {
changed = true;
if (!constantFalse)
constantFalse = rewriter.create<arith::ConstantOp>(
op.getLoc(), i1Ty, rewriter.getIntegerAttr(i1Ty, 0));
rewriter.updateRootInPlace(use.getOwner(),
[&]() { use.set(constantFalse); });
}
}
return success(changed);
}
};
/// Remove any statements from an if that are equivalent to the condition
/// or its negation. For example:
///
/// %res:2 = scf.if %cmp {
/// yield something(), true
/// } else {
/// yield something2(), false
/// }
/// print(%res#1)
///
/// becomes
/// %res = scf.if %cmp {
/// yield something()
/// } else {
/// yield something2()
/// }
/// print(%cmp)
///
/// Additionally if both branches yield the same value, replace all uses
/// of the result with the yielded value.
///
/// %res:2 = scf.if %cmp {
/// yield something(), %arg1
/// } else {
/// yield something2(), %arg1
/// }
/// print(%res#1)
///
/// becomes
/// %res = scf.if %cmp {
/// yield something()
/// } else {
/// yield something2()
/// }
/// print(%arg1)
///
struct ReplaceIfYieldWithConditionOrValue : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp op,
PatternRewriter &rewriter) const override {
// Early exit if there are no results that could be replaced.
if (op.getNumResults() == 0)
return failure();
auto trueYield =
cast<scf::YieldOp>(op.getThenRegion().back().getTerminator());
auto falseYield =
cast<scf::YieldOp>(op.getElseRegion().back().getTerminator());
rewriter.setInsertionPoint(op->getBlock(),
op.getOperation()->getIterator());
bool changed = false;
Type i1Ty = rewriter.getI1Type();
for (auto [trueResult, falseResult, opResult] :
llvm::zip(trueYield.getResults(), falseYield.getResults(),
op.getResults())) {
if (trueResult == falseResult) {
if (!opResult.use_empty()) {
opResult.replaceAllUsesWith(trueResult);
changed = true;
}
continue;
}
BoolAttr trueYield, falseYield;
if (!matchPattern(trueResult, m_Constant(&trueYield)) ||
!matchPattern(falseResult, m_Constant(&falseYield)))
continue;
bool trueVal = trueYield.getValue();
bool falseVal = falseYield.getValue();
if (!trueVal && falseVal) {
if (!opResult.use_empty()) {
Dialect *constDialect = trueResult.getDefiningOp()->getDialect();
Value notCond = rewriter.create<arith::XOrIOp>(
op.getLoc(), op.getCondition(),
constDialect
->materializeConstant(rewriter,
rewriter.getIntegerAttr(i1Ty, 1), i1Ty,
op.getLoc())
->getResult(0));
opResult.replaceAllUsesWith(notCond);
changed = true;
}
}
if (trueVal && !falseVal) {
if (!opResult.use_empty()) {
opResult.replaceAllUsesWith(op.getCondition());
changed = true;
}
}
}
return success(changed);
}
};
/// Merge any consecutive scf.if's with the same condition.
///
/// scf.if %cond {
/// firstCodeTrue();...
/// } else {
/// firstCodeFalse();...
/// }
/// %res = scf.if %cond {
/// secondCodeTrue();...
/// } else {
/// secondCodeFalse();...
/// }
///
/// becomes
/// %res = scf.if %cmp {
/// firstCodeTrue();...
/// secondCodeTrue();...
/// } else {
/// firstCodeFalse();...
/// secondCodeFalse();...
/// }
struct CombineIfs : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp nextIf,
PatternRewriter &rewriter) const override {
Block *parent = nextIf->getBlock();
if (nextIf == &parent->front())
return failure();
auto prevIf = dyn_cast<IfOp>(nextIf->getPrevNode());
if (!prevIf)
return failure();
// Determine the logical then/else blocks when prevIf's
// condition is used. Null means the block does not exist
// in that case (e.g. empty else). If neither of these
// are set, the two conditions cannot be compared.
Block *nextThen = nullptr;
Block *nextElse = nullptr;
if (nextIf.getCondition() == prevIf.getCondition()) {
nextThen = nextIf.thenBlock();
if (!nextIf.getElseRegion().empty())
nextElse = nextIf.elseBlock();
}
if (arith::XOrIOp notv =
nextIf.getCondition().getDefiningOp<arith::XOrIOp>()) {
if (notv.getLhs() == prevIf.getCondition() &&
matchPattern(notv.getRhs(), m_One())) {
nextElse = nextIf.thenBlock();
if (!nextIf.getElseRegion().empty())
nextThen = nextIf.elseBlock();
}
}
if (arith::XOrIOp notv =
prevIf.getCondition().getDefiningOp<arith::XOrIOp>()) {
if (notv.getLhs() == nextIf.getCondition() &&
matchPattern(notv.getRhs(), m_One())) {
nextElse = nextIf.thenBlock();
if (!nextIf.getElseRegion().empty())
nextThen = nextIf.elseBlock();
}
}
if (!nextThen && !nextElse)
return failure();
SmallVector<Value> prevElseYielded;
if (!prevIf.getElseRegion().empty())
prevElseYielded = prevIf.elseYield().getOperands();
// Replace all uses of return values of op within nextIf with the
// corresponding yields
for (auto it : llvm::zip(prevIf.getResults(),
prevIf.thenYield().getOperands(), prevElseYielded))
for (OpOperand &use :
llvm::make_early_inc_range(std::get<0>(it).getUses())) {
if (nextThen && nextThen->getParent()->isAncestor(
use.getOwner()->getParentRegion())) {
rewriter.startRootUpdate(use.getOwner());
use.set(std::get<1>(it));
rewriter.finalizeRootUpdate(use.getOwner());
} else if (nextElse && nextElse->getParent()->isAncestor(
use.getOwner()->getParentRegion())) {
rewriter.startRootUpdate(use.getOwner());
use.set(std::get<2>(it));
rewriter.finalizeRootUpdate(use.getOwner());
}
}
SmallVector<Type> mergedTypes(prevIf.getResultTypes());
llvm::append_range(mergedTypes, nextIf.getResultTypes());
IfOp combinedIf = rewriter.create<IfOp>(
nextIf.getLoc(), mergedTypes, prevIf.getCondition(), /*hasElse=*/false);
rewriter.eraseBlock(&combinedIf.getThenRegion().back());
rewriter.inlineRegionBefore(prevIf.getThenRegion(),
combinedIf.getThenRegion(),
combinedIf.getThenRegion().begin());
if (nextThen) {
YieldOp thenYield = combinedIf.thenYield();
YieldOp thenYield2 = cast<YieldOp>(nextThen->getTerminator());
rewriter.mergeBlocks(nextThen, combinedIf.thenBlock());
rewriter.setInsertionPointToEnd(combinedIf.thenBlock());
SmallVector<Value> mergedYields(thenYield.getOperands());
llvm::append_range(mergedYields, thenYield2.getOperands());
rewriter.create<YieldOp>(thenYield2.getLoc(), mergedYields);
rewriter.eraseOp(thenYield);
rewriter.eraseOp(thenYield2);
}
rewriter.inlineRegionBefore(prevIf.getElseRegion(),
combinedIf.getElseRegion(),
combinedIf.getElseRegion().begin());
if (nextElse) {
if (combinedIf.getElseRegion().empty()) {
rewriter.inlineRegionBefore(*nextElse->getParent(),
combinedIf.getElseRegion(),
combinedIf.getElseRegion().begin());
} else {
YieldOp elseYield = combinedIf.elseYield();
YieldOp elseYield2 = cast<YieldOp>(nextElse->getTerminator());
rewriter.mergeBlocks(nextElse, combinedIf.elseBlock());
rewriter.setInsertionPointToEnd(combinedIf.elseBlock());
SmallVector<Value> mergedElseYields(elseYield.getOperands());
llvm::append_range(mergedElseYields, elseYield2.getOperands());
rewriter.create<YieldOp>(elseYield2.getLoc(), mergedElseYields);
rewriter.eraseOp(elseYield);
rewriter.eraseOp(elseYield2);
}
}
SmallVector<Value> prevValues;
SmallVector<Value> nextValues;
for (const auto &pair : llvm::enumerate(combinedIf.getResults())) {
if (pair.index() < prevIf.getNumResults())
prevValues.push_back(pair.value());
else
nextValues.push_back(pair.value());
}
rewriter.replaceOp(prevIf, prevValues);
rewriter.replaceOp(nextIf, nextValues);
return success();
}
};
/// Pattern to remove an empty else branch.
struct RemoveEmptyElseBranch : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp ifOp,
PatternRewriter &rewriter) const override {
// Cannot remove else region when there are operation results.
if (ifOp.getNumResults())
return failure();
Block *elseBlock = ifOp.elseBlock();
if (!elseBlock || !llvm::hasSingleElement(*elseBlock))
return failure();
auto newIfOp = rewriter.cloneWithoutRegions(ifOp);
rewriter.inlineRegionBefore(ifOp.getThenRegion(), newIfOp.getThenRegion(),
newIfOp.getThenRegion().begin());
rewriter.eraseOp(ifOp);
return success();
}
};
/// Convert nested `if`s into `arith.andi` + single `if`.
///
/// scf.if %arg0 {
/// scf.if %arg1 {
/// ...
/// scf.yield
/// }
/// scf.yield
/// }
/// becomes
///
/// %0 = arith.andi %arg0, %arg1
/// scf.if %0 {
/// ...
/// scf.yield
/// }
struct CombineNestedIfs : public OpRewritePattern<IfOp> {
using OpRewritePattern<IfOp>::OpRewritePattern;
LogicalResult matchAndRewrite(IfOp op,
PatternRewriter &rewriter) const override {
auto nestedOps = op.thenBlock()->without_terminator();
// Nested `if` must be the only op in block.
if (!llvm::hasSingleElement(nestedOps))
return failure();
// If there is an else block, it can only yield
if (op.elseBlock() && !llvm::hasSingleElement(*op.elseBlock()))
return failure();
auto nestedIf = dyn_cast<IfOp>(*nestedOps.begin());
if (!nestedIf)
return failure();
if (nestedIf.elseBlock() && !llvm::hasSingleElement(*nestedIf.elseBlock()))
return failure();
SmallVector<Value> thenYield(op.thenYield().getOperands());
SmallVector<Value> elseYield;
if (op.elseBlock())
llvm::append_range(elseYield, op.elseYield().getOperands());
// A list of indices for which we should upgrade the value yielded
// in the else to a select.
SmallVector<unsigned> elseYieldsToUpgradeToSelect;
// If the outer scf.if yields a value produced by the inner scf.if,
// only permit combining if the value yielded when the condition
// is false in the outer scf.if is the same value yielded when the
// inner scf.if condition is false.
// Note that the array access to elseYield will not go out of bounds
// since it must have the same length as thenYield, since they both
// come from the same scf.if.
for (const auto &tup : llvm::enumerate(thenYield)) {
if (tup.value().getDefiningOp() == nestedIf) {
auto nestedIdx = llvm::cast<OpResult>(tup.value()).getResultNumber();
if (nestedIf.elseYield().getOperand(nestedIdx) !=
elseYield[tup.index()]) {
return failure();
}
// If the correctness test passes, we will yield
// corresponding value from the inner scf.if
thenYield[tup.index()] = nestedIf.thenYield().getOperand(nestedIdx);
continue;
}
// Otherwise, we need to ensure the else block of the combined
// condition still returns the same value when the outer condition is
// true and the inner condition is false. This can be accomplished if
// the then value is defined outside the outer scf.if and we replace the
// value with a select that considers just the outer condition. Since
// the else region contains just the yield, its yielded value is
// defined outside the scf.if, by definition.
// If the then value is defined within the scf.if, bail.
if (tup.value().getParentRegion() == &op.getThenRegion()) {
return failure();
}
elseYieldsToUpgradeToSelect.push_back(tup.index());
}
Location loc = op.getLoc();
Value newCondition = rewriter.create<arith::AndIOp>(
loc, op.getCondition(), nestedIf.getCondition());
auto newIf = rewriter.create<IfOp>(loc, op.getResultTypes(), newCondition);
Block *newIfBlock = rewriter.createBlock(&newIf.getThenRegion());
SmallVector<Value> results;
llvm::append_range(results, newIf.getResults());
rewriter.setInsertionPoint(newIf);
for (auto idx : elseYieldsToUpgradeToSelect)
results[idx] = rewriter.create<arith::SelectOp>(
op.getLoc(), op.getCondition(), thenYield[idx], elseYield[idx]);
rewriter.mergeBlocks(nestedIf.thenBlock(), newIfBlock);
rewriter.setInsertionPointToEnd(newIf.thenBlock());
rewriter.replaceOpWithNewOp<YieldOp>(newIf.thenYield(), thenYield);
if (!elseYield.empty()) {
rewriter.createBlock(&newIf.getElseRegion());
rewriter.setInsertionPointToEnd(newIf.elseBlock());
rewriter.create<YieldOp>(loc, elseYield);
}
rewriter.replaceOp(op, results);
return success();
}
};
} // namespace
void IfOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<CombineIfs, CombineNestedIfs, ConditionPropagation,
ConvertTrivialIfToSelect, RemoveEmptyElseBranch,
RemoveStaticCondition, RemoveUnusedResults,
ReplaceIfYieldWithConditionOrValue>(context);
}
Block *IfOp::thenBlock() { return &getThenRegion().back(); }
YieldOp IfOp::thenYield() { return cast<YieldOp>(&thenBlock()->back()); }
Block *IfOp::elseBlock() {
Region &r = getElseRegion();
if (r.empty())
return nullptr;
return &r.back();
}
YieldOp IfOp::elseYield() { return cast<YieldOp>(&elseBlock()->back()); }
//===----------------------------------------------------------------------===//
// ParallelOp
//===----------------------------------------------------------------------===//
void ParallelOp::build(
OpBuilder &builder, OperationState &result, ValueRange lowerBounds,
ValueRange upperBounds, ValueRange steps, ValueRange initVals,
function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
bodyBuilderFn) {
result.addOperands(lowerBounds);
result.addOperands(upperBounds);
result.addOperands(steps);
result.addOperands(initVals);
result.addAttribute(
ParallelOp::getOperandSegmentSizeAttr(),
builder.getDenseI32ArrayAttr({static_cast<int32_t>(lowerBounds.size()),
static_cast<int32_t>(upperBounds.size()),
static_cast<int32_t>(steps.size()),
static_cast<int32_t>(initVals.size())}));
result.addTypes(initVals.getTypes());
OpBuilder::InsertionGuard guard(builder);
unsigned numIVs = steps.size();
SmallVector<Type, 8> argTypes(numIVs, builder.getIndexType());
SmallVector<Location, 8> argLocs(numIVs, result.location);
Region *bodyRegion = result.addRegion();
Block *bodyBlock = builder.createBlock(bodyRegion, {}, argTypes, argLocs);
if (bodyBuilderFn) {
builder.setInsertionPointToStart(bodyBlock);
bodyBuilderFn(builder, result.location,
bodyBlock->getArguments().take_front(numIVs),
bodyBlock->getArguments().drop_front(numIVs));
}
ParallelOp::ensureTerminator(*bodyRegion, builder, result.location);
}
void ParallelOp::build(
OpBuilder &builder, OperationState &result, ValueRange lowerBounds,
ValueRange upperBounds, ValueRange steps,
function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
// Only pass a non-null wrapper if bodyBuilderFn is non-null itself. Make sure
// we don't capture a reference to a temporary by constructing the lambda at
// function level.
auto wrappedBuilderFn = [&bodyBuilderFn](OpBuilder &nestedBuilder,
Location nestedLoc, ValueRange ivs,
ValueRange) {
bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
};
function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)> wrapper;
if (bodyBuilderFn)
wrapper = wrappedBuilderFn;
build(builder, result, lowerBounds, upperBounds, steps, ValueRange(),
wrapper);
}
LogicalResult ParallelOp::verify() {
// Check that there is at least one value in lowerBound, upperBound and step.
// It is sufficient to test only step, because it is ensured already that the
// number of elements in lowerBound, upperBound and step are the same.
Operation::operand_range stepValues = getStep();
if (stepValues.empty())
return emitOpError(
"needs at least one tuple element for lowerBound, upperBound and step");
// Check whether all constant step values are positive.
for (Value stepValue : stepValues)
if (auto cst = getConstantIntValue(stepValue))
if (*cst <= 0)
return emitOpError("constant step operand must be positive");
// Check that the body defines the same number of block arguments as the
// number of tuple elements in step.
Block *body = getBody();
if (body->getNumArguments() != stepValues.size())
return emitOpError() << "expects the same number of induction variables: "
<< body->getNumArguments()
<< " as bound and step values: " << stepValues.size();
for (auto arg : body->getArguments())
if (!arg.getType().isIndex())
return emitOpError(
"expects arguments for the induction variable to be of index type");
// Check that the yield has no results
auto yield = verifyAndGetTerminator<scf::YieldOp>(
*this, getRegion(), "expects body to terminate with 'scf.yield'");
if (!yield)
return failure();
if (yield->getNumOperands() != 0)
return yield.emitOpError() << "not allowed to have operands inside '"
<< ParallelOp::getOperationName() << "'";
// Check that the number of results is the same as the number of ReduceOps.
SmallVector<ReduceOp, 4> reductions(body->getOps<ReduceOp>());
auto resultsSize = getResults().size();
auto reductionsSize = reductions.size();
auto initValsSize = getInitVals().size();
if (resultsSize != reductionsSize)
return emitOpError() << "expects number of results: " << resultsSize
<< " to be the same as number of reductions: "
<< reductionsSize;
if (resultsSize != initValsSize)
return emitOpError() << "expects number of results: " << resultsSize
<< " to be the same as number of initial values: "
<< initValsSize;
// Check that the types of the results and reductions are the same.
for (auto resultAndReduce : llvm::zip(getResults(), reductions)) {
auto resultType = std::get<0>(resultAndReduce).getType();
auto reduceOp = std::get<1>(resultAndReduce);
auto reduceType = reduceOp.getOperand().getType();
if (resultType != reduceType)
return reduceOp.emitOpError()
<< "expects type of reduce: " << reduceType
<< " to be the same as result type: " << resultType;
}
return success();
}
ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) {
auto &builder = parser.getBuilder();
// Parse an opening `(` followed by induction variables followed by `)`
SmallVector<OpAsmParser::Argument, 4> ivs;
if (parser.parseArgumentList(ivs, OpAsmParser::Delimiter::Paren))
return failure();
// Parse loop bounds.
SmallVector<OpAsmParser::UnresolvedOperand, 4> lower;
if (parser.parseEqual() ||
parser.parseOperandList(lower, ivs.size(),
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(lower, builder.getIndexType(), result.operands))
return failure();
SmallVector<OpAsmParser::UnresolvedOperand, 4> upper;
if (parser.parseKeyword("to") ||
parser.parseOperandList(upper, ivs.size(),
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(upper, builder.getIndexType(), result.operands))
return failure();
// Parse step values.
SmallVector<OpAsmParser::UnresolvedOperand, 4> steps;
if (parser.parseKeyword("step") ||
parser.parseOperandList(steps, ivs.size(),
OpAsmParser::Delimiter::Paren) ||
parser.resolveOperands(steps, builder.getIndexType(), result.operands))
return failure();
// Parse init values.
SmallVector<OpAsmParser::UnresolvedOperand, 4> initVals;
if (succeeded(parser.parseOptionalKeyword("init"))) {
if (parser.parseOperandList(initVals, OpAsmParser::Delimiter::Paren))
return failure();
}
// Parse optional results in case there is a reduce.
if (parser.parseOptionalArrowTypeList(result.types))
return failure();
// Now parse the body.
Region *body = result.addRegion();
for (auto &iv : ivs)
iv.type = builder.getIndexType();
if (parser.parseRegion(*body, ivs))
return failure();
// Set `operandSegmentSizes` attribute.
result.addAttribute(
ParallelOp::getOperandSegmentSizeAttr(),
builder.getDenseI32ArrayAttr({static_cast<int32_t>(lower.size()),
static_cast<int32_t>(upper.size()),
static_cast<int32_t>(steps.size()),
static_cast<int32_t>(initVals.size())}));
// Parse attributes.
if (parser.parseOptionalAttrDict(result.attributes) ||
parser.resolveOperands(initVals, result.types, parser.getNameLoc(),
result.operands))
return failure();
// Add a terminator if none was parsed.
ForOp::ensureTerminator(*body, builder, result.location);
return success();
}
void ParallelOp::print(OpAsmPrinter &p) {
p << " (" << getBody()->getArguments() << ") = (" << getLowerBound()
<< ") to (" << getUpperBound() << ") step (" << getStep() << ")";
if (!getInitVals().empty())
p << " init (" << getInitVals() << ")";
p.printOptionalArrowTypeList(getResultTypes());
p << ' ';
p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
p.printOptionalAttrDict(
(*this)->getAttrs(),
/*elidedAttrs=*/ParallelOp::getOperandSegmentSizeAttr());
}
Region &ParallelOp::getLoopBody() { return getRegion(); }
ParallelOp mlir::scf::getParallelForInductionVarOwner(Value val) {
auto ivArg = llvm::dyn_cast<BlockArgument>(val);
if (!ivArg)
return ParallelOp();
assert(ivArg.getOwner() && "unlinked block argument");
auto *containingOp = ivArg.getOwner()->getParentOp();
return dyn_cast<ParallelOp>(containingOp);
}
namespace {
// Collapse loop dimensions that perform a single iteration.
struct ParallelOpSingleOrZeroIterationDimsFolder
: public OpRewritePattern<ParallelOp> {
using OpRewritePattern<ParallelOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ParallelOp op,
PatternRewriter &rewriter) const override {
Location loc = op.getLoc();
// Compute new loop bounds that omit all single-iteration loop dimensions.
SmallVector<Value> newLowerBounds, newUpperBounds, newSteps;
IRMapping mapping;
for (auto [lb, ub, step, iv] :
llvm::zip(op.getLowerBound(), op.getUpperBound(), op.getStep(),
op.getInductionVars())) {
auto numIterations = constantTripCount(lb, ub, step);
if (numIterations.has_value()) {
// Remove the loop if it performs zero iterations.
if (*numIterations == 0) {
rewriter.replaceOp(op, op.getInitVals());
return success();
}
// Replace the loop induction variable by the lower bound if the loop
// performs a single iteration. Otherwise, copy the loop bounds.
if (*numIterations == 1) {
mapping.map(iv, getValueOrCreateConstantIndexOp(rewriter, loc, lb));
continue;
}
}
newLowerBounds.push_back(lb);
newUpperBounds.push_back(ub);
newSteps.push_back(step);
}
// Exit if none of the loop dimensions perform a single iteration.
if (newLowerBounds.size() == op.getLowerBound().size())
return failure();
if (newLowerBounds.empty()) {
// All of the loop dimensions perform a single iteration. Inline
// loop body and nested ReduceOp's
SmallVector<Value> results;
results.reserve(op.getInitVals().size());
for (auto &bodyOp : op.getLoopBody().front().without_terminator()) {
auto reduce = dyn_cast<ReduceOp>(bodyOp);
if (!reduce) {
rewriter.clone(bodyOp, mapping);
continue;
}
Block &reduceBlock = reduce.getReductionOperator().front();
auto initValIndex = results.size();
mapping.map(reduceBlock.getArgument(0), op.getInitVals()[initValIndex]);
mapping.map(reduceBlock.getArgument(1),
mapping.lookupOrDefault(reduce.getOperand()));
for (auto &reduceBodyOp : reduceBlock.without_terminator())
rewriter.clone(reduceBodyOp, mapping);
auto result = mapping.lookupOrDefault(
cast<ReduceReturnOp>(reduceBlock.getTerminator()).getResult());
results.push_back(result);
}
rewriter.replaceOp(op, results);
return success();
}
// Replace the parallel loop by lower-dimensional parallel loop.
auto newOp =
rewriter.create<ParallelOp>(op.getLoc(), newLowerBounds, newUpperBounds,
newSteps, op.getInitVals(), nullptr);
// Clone the loop body and remap the block arguments of the collapsed loops
// (inlining does not support a cancellable block argument mapping).
rewriter.cloneRegionBefore(op.getRegion(), newOp.getRegion(),
newOp.getRegion().begin(), mapping);
rewriter.replaceOp(op, newOp.getResults());
return success();
}
};
struct MergeNestedParallelLoops : public OpRewritePattern<ParallelOp> {
using OpRewritePattern<ParallelOp>::OpRewritePattern;
LogicalResult matchAndRewrite(ParallelOp op,
PatternRewriter &rewriter) const override {
Block &outerBody = op.getLoopBody().front();
if (!llvm::hasSingleElement(outerBody.without_terminator()))
return failure();
auto innerOp = dyn_cast<ParallelOp>(outerBody.front());
if (!innerOp)
return failure();
for (auto val : outerBody.getArguments())
if (llvm::is_contained(innerOp.getLowerBound(), val) ||
llvm::is_contained(innerOp.getUpperBound(), val) ||
llvm::is_contained(innerOp.getStep(), val))
return failure();
// Reductions are not supported yet.
if (!op.getInitVals().empty() || !innerOp.getInitVals().empty())
return failure();
auto bodyBuilder = [&](OpBuilder &builder, Location /*loc*/,
ValueRange iterVals, ValueRange) {
Block &innerBody = innerOp.getLoopBody().front();
assert(iterVals.size() ==
(outerBody.getNumArguments() + innerBody.getNumArguments()));
IRMapping mapping;
mapping.map(outerBody.getArguments(),
iterVals.take_front(outerBody.getNumArguments()));
mapping.map(innerBody.getArguments(),
iterVals.take_back(innerBody.getNumArguments()));
for (Operation &op : innerBody.without_terminator())
builder.clone(op, mapping);
};
auto concatValues = [](const auto &first, const auto &second) {
SmallVector<Value> ret;
ret.reserve(first.size() + second.size());
ret.assign(first.begin(), first.end());
ret.append(second.begin(), second.end());
return ret;
};
auto newLowerBounds =
concatValues(op.getLowerBound(), innerOp.getLowerBound());
auto newUpperBounds =
concatValues(op.getUpperBound(), innerOp.getUpperBound());
auto newSteps = concatValues(op.getStep(), innerOp.getStep());
rewriter.replaceOpWithNewOp<ParallelOp>(op, newLowerBounds, newUpperBounds,
newSteps, std::nullopt,
bodyBuilder);
return success();
}
};
} // namespace
void ParallelOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results
.add<ParallelOpSingleOrZeroIterationDimsFolder, MergeNestedParallelLoops>(
context);
}
/// Given the region at `index`, or the parent operation if `index` is None,
/// return the successor regions. These are the regions that may be selected
/// during the flow of control. `operands` is a set of optional attributes that
/// correspond to a constant value for each operand, or null if that operand is
/// not a constant.
void ParallelOp::getSuccessorRegions(
std::optional<unsigned> index, ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> ®ions) {
// Both the operation itself and the region may be branching into the body or
// back into the operation itself. It is possible for loop not to enter the
// body.
regions.push_back(RegionSuccessor(&getRegion()));
regions.push_back(RegionSuccessor());
}
//===----------------------------------------------------------------------===//
// ReduceOp
//===----------------------------------------------------------------------===//
void ReduceOp::build(
OpBuilder &builder, OperationState &result, Value operand,
function_ref<void(OpBuilder &, Location, Value, Value)> bodyBuilderFn) {
auto type = operand.getType();
result.addOperands(operand);
OpBuilder::InsertionGuard guard(builder);
Region *bodyRegion = result.addRegion();
Block *body = builder.createBlock(bodyRegion, {}, ArrayRef<Type>{type, type},
{result.location, result.location});
if (bodyBuilderFn)
bodyBuilderFn(builder, result.location, body->getArgument(0),
body->getArgument(1));
}
LogicalResult ReduceOp::verifyRegions() {
// The region of a ReduceOp has two arguments of the same type as its operand.
auto type = getOperand().getType();
Block &block = getReductionOperator().front();
if (block.empty())
return emitOpError("the block inside reduce should not be empty");
if (block.getNumArguments() != 2 ||
llvm::any_of(block.getArguments(), [&](const BlockArgument &arg) {
return arg.getType() != type;
}))
return emitOpError() << "expects two arguments to reduce block of type "
<< type;
// Check that the block is terminated by a ReduceReturnOp.
if (!isa<ReduceReturnOp>(block.getTerminator()))
return emitOpError("the block inside reduce should be terminated with a "
"'scf.reduce.return' op");
return success();
}
ParseResult ReduceOp::parse(OpAsmParser &parser, OperationState &result) {
// Parse an opening `(` followed by the reduced value followed by `)`
OpAsmParser::UnresolvedOperand operand;
if (parser.parseLParen() || parser.parseOperand(operand) ||
parser.parseRParen())
return failure();
Type resultType;
// Parse the type of the operand (and also what reduce computes on).
if (parser.parseColonType(resultType) ||
parser.resolveOperand(operand, resultType, result.operands))
return failure();
// Now parse the body.
Region *body = result.addRegion();
if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}))
return failure();
return success();
}
void ReduceOp::print(OpAsmPrinter &p) {
p << "(" << getOperand() << ") ";
p << " : " << getOperand().getType() << ' ';
p.printRegion(getReductionOperator());
}
//===----------------------------------------------------------------------===//
// ReduceReturnOp
//===----------------------------------------------------------------------===//
LogicalResult ReduceReturnOp::verify() {
// The type of the return value should be the same type as the type of the
// operand of the enclosing ReduceOp.
auto reduceOp = cast<ReduceOp>((*this)->getParentOp());
Type reduceType = reduceOp.getOperand().getType();
if (reduceType != getResult().getType())
return emitOpError() << "needs to have type " << reduceType
<< " (the type of the enclosing ReduceOp)";
return success();
}
//===----------------------------------------------------------------------===//
// WhileOp
//===----------------------------------------------------------------------===//
void WhileOp::build(::mlir::OpBuilder &odsBuilder,
::mlir::OperationState &odsState, TypeRange resultTypes,
ValueRange operands, BodyBuilderFn beforeBuilder,
BodyBuilderFn afterBuilder) {
odsState.addOperands(operands);
odsState.addTypes(resultTypes);
OpBuilder::InsertionGuard guard(odsBuilder);
// Build before region.
SmallVector<Location, 4> beforeArgLocs;
beforeArgLocs.reserve(operands.size());
for (Value operand : operands) {
beforeArgLocs.push_back(operand.getLoc());
}
Region *beforeRegion = odsState.addRegion();
Block *beforeBlock = odsBuilder.createBlock(
beforeRegion, /*insertPt=*/{}, operands.getTypes(), beforeArgLocs);
if (beforeBuilder)
beforeBuilder(odsBuilder, odsState.location, beforeBlock->getArguments());
// Build after region.
SmallVector<Location, 4> afterArgLocs(resultTypes.size(), odsState.location);
Region *afterRegion = odsState.addRegion();
Block *afterBlock = odsBuilder.createBlock(afterRegion, /*insertPt=*/{},
resultTypes, afterArgLocs);
if (afterBuilder)
afterBuilder(odsBuilder, odsState.location, afterBlock->getArguments());
}
OperandRange WhileOp::getSuccessorEntryOperands(std::optional<unsigned> index) {
assert(index && *index == 0 &&
"WhileOp is expected to branch only to the first region");
return getInits();
}
ConditionOp WhileOp::getConditionOp() {
return cast<ConditionOp>(getBefore().front().getTerminator());
}
YieldOp WhileOp::getYieldOp() {
return cast<YieldOp>(getAfter().front().getTerminator());
}
Block::BlockArgListType WhileOp::getBeforeArguments() {
return getBefore().front().getArguments();
}
Block::BlockArgListType WhileOp::getAfterArguments() {
return getAfter().front().getArguments();
}
void WhileOp::getSuccessorRegions(std::optional<unsigned> index,
ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> ®ions) {
// The parent op always branches to the condition region.
if (!index) {
regions.emplace_back(&getBefore(), getBefore().getArguments());
return;
}
assert(*index < 2 && "there are only two regions in a WhileOp");
// The body region always branches back to the condition region.
if (*index == 1) {
regions.emplace_back(&getBefore(), getBefore().getArguments());
return;
}
// Try to narrow the successor to the condition region.
assert(!operands.empty() && "expected at least one operand");
auto cond = llvm::dyn_cast_or_null<BoolAttr>(operands[0]);
if (!cond || !cond.getValue())
regions.emplace_back(getResults());
if (!cond || cond.getValue())
regions.emplace_back(&getAfter(), getAfter().getArguments());
}
/// Parses a `while` op.
///
/// op ::= `scf.while` assignments `:` function-type region `do` region
/// `attributes` attribute-dict
/// initializer ::= /* empty */ | `(` assignment-list `)`
/// assignment-list ::= assignment | assignment `,` assignment-list
/// assignment ::= ssa-value `=` ssa-value
ParseResult scf::WhileOp::parse(OpAsmParser &parser, OperationState &result) {
SmallVector<OpAsmParser::Argument, 4> regionArgs;
SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
Region *before = result.addRegion();
Region *after = result.addRegion();
OptionalParseResult listResult =
parser.parseOptionalAssignmentList(regionArgs, operands);
if (listResult.has_value() && failed(listResult.value()))
return failure();
FunctionType functionType;
SMLoc typeLoc = parser.getCurrentLocation();
if (failed(parser.parseColonType(functionType)))
return failure();
result.addTypes(functionType.getResults());
if (functionType.getNumInputs() != operands.size()) {
return parser.emitError(typeLoc)
<< "expected as many input types as operands "
<< "(expected " << operands.size() << " got "
<< functionType.getNumInputs() << ")";
}
// Resolve input operands.
if (failed(parser.resolveOperands(operands, functionType.getInputs(),
parser.getCurrentLocation(),
result.operands)))
return failure();
// Propagate the types into the region arguments.
for (size_t i = 0, e = regionArgs.size(); i != e; ++i)
regionArgs[i].type = functionType.getInput(i);
return failure(parser.parseRegion(*before, regionArgs) ||
parser.parseKeyword("do") || parser.parseRegion(*after) ||
parser.parseOptionalAttrDictWithKeyword(result.attributes));
}
/// Prints a `while` op.
void scf::WhileOp::print(OpAsmPrinter &p) {
printInitializationList(p, getBefore().front().getArguments(), getInits(),
" ");
p << " : ";
p.printFunctionalType(getInits().getTypes(), getResults().getTypes());
p << ' ';
p.printRegion(getBefore(), /*printEntryBlockArgs=*/false);
p << " do ";
p.printRegion(getAfter());
p.printOptionalAttrDictWithKeyword((*this)->getAttrs());
}
/// Verifies that two ranges of types match, i.e. have the same number of
/// entries and that types are pairwise equals. Reports errors on the given
/// operation in case of mismatch.
template <typename OpTy>
static LogicalResult verifyTypeRangesMatch(OpTy op, TypeRange left,
TypeRange right, StringRef message) {
if (left.size() != right.size())
return op.emitOpError("expects the same number of ") << message;
for (unsigned i = 0, e = left.size(); i < e; ++i) {
if (left[i] != right[i]) {
InFlightDiagnostic diag = op.emitOpError("expects the same types for ")
<< message;
diag.attachNote() << "for argument " << i << ", found " << left[i]
<< " and " << right[i];
return diag;
}
}
return success();
}
LogicalResult scf::WhileOp::verify() {
auto beforeTerminator = verifyAndGetTerminator<scf::ConditionOp>(
*this, getBefore(),
"expects the 'before' region to terminate with 'scf.condition'");
if (!beforeTerminator)
return failure();
auto afterTerminator = verifyAndGetTerminator<scf::YieldOp>(
*this, getAfter(),
"expects the 'after' region to terminate with 'scf.yield'");
return success(afterTerminator != nullptr);
}
namespace {
/// Replace uses of the condition within the do block with true, since otherwise
/// the block would not be evaluated.
///
/// scf.while (..) : (i1, ...) -> ... {
/// %condition = call @evaluate_condition() : () -> i1
/// scf.condition(%condition) %condition : i1, ...
/// } do {
/// ^bb0(%arg0: i1, ...):
/// use(%arg0)
/// ...
///
/// becomes
/// scf.while (..) : (i1, ...) -> ... {
/// %condition = call @evaluate_condition() : () -> i1
/// scf.condition(%condition) %condition : i1, ...
/// } do {
/// ^bb0(%arg0: i1, ...):
/// use(%true)
/// ...
struct WhileConditionTruth : public OpRewritePattern<WhileOp> {
using OpRewritePattern<WhileOp>::OpRewritePattern;
LogicalResult matchAndRewrite(WhileOp op,
PatternRewriter &rewriter) const override {
auto term = op.getConditionOp();
// These variables serve to prevent creating duplicate constants
// and hold constant true or false values.
Value constantTrue = nullptr;
bool replaced = false;
for (auto yieldedAndBlockArgs :
llvm::zip(term.getArgs(), op.getAfterArguments())) {
if (std::get<0>(yieldedAndBlockArgs) == term.getCondition()) {
if (!std::get<1>(yieldedAndBlockArgs).use_empty()) {
if (!constantTrue)
constantTrue = rewriter.create<arith::ConstantOp>(
op.getLoc(), term.getCondition().getType(),
rewriter.getBoolAttr(true));
rewriter.replaceAllUsesWith(std::get<1>(yieldedAndBlockArgs),
constantTrue);
replaced = true;
}
}
}
return success(replaced);
}
};
/// Remove loop invariant arguments from `before` block of scf.while.
/// A before block argument is considered loop invariant if :-
/// 1. i-th yield operand is equal to the i-th while operand.
/// 2. i-th yield operand is k-th after block argument which is (k+1)-th
/// condition operand AND this (k+1)-th condition operand is equal to i-th
/// iter argument/while operand.
/// For the arguments which are removed, their uses inside scf.while
/// are replaced with their corresponding initial value.
///
/// Eg:
/// INPUT :-
/// %res = scf.while <...> iter_args(%arg0_before = %a, %arg1_before = %b,
/// ..., %argN_before = %N)
/// {
/// ...
/// scf.condition(%cond) %arg1_before, %arg0_before,
/// %arg2_before, %arg0_before, ...
/// } do {
/// ^bb0(%arg1_after, %arg0_after_1, %arg2_after, %arg0_after_2,
/// ..., %argK_after):
/// ...
/// scf.yield %arg0_after_2, %b, %arg1_after, ..., %argN
/// }
///
/// OUTPUT :-
/// %res = scf.while <...> iter_args(%arg2_before = %c, ..., %argN_before =
/// %N)
/// {
/// ...
/// scf.condition(%cond) %b, %a, %arg2_before, %a, ...
/// } do {
/// ^bb0(%arg1_after, %arg0_after_1, %arg2_after, %arg0_after_2,
/// ..., %argK_after):
/// ...
/// scf.yield %arg1_after, ..., %argN
/// }
///
/// EXPLANATION:
/// We iterate over each yield operand.
/// 1. 0-th yield operand %arg0_after_2 is 4-th condition operand
/// %arg0_before, which in turn is the 0-th iter argument. So we
/// remove 0-th before block argument and yield operand, and replace
/// all uses of the 0-th before block argument with its initial value
/// %a.
/// 2. 1-th yield operand %b is equal to the 1-th iter arg's initial
/// value. So we remove this operand and the corresponding before
/// block argument and replace all uses of 1-th before block argument
/// with %b.
struct RemoveLoopInvariantArgsFromBeforeBlock
: public OpRewritePattern<WhileOp> {
using OpRewritePattern<WhileOp>::OpRewritePattern;
LogicalResult matchAndRewrite(WhileOp op,
PatternRewriter &rewriter) const override {
Block &afterBlock = op.getAfter().front();
Block::BlockArgListType beforeBlockArgs = op.getBeforeArguments();
ConditionOp condOp = op.getConditionOp();
OperandRange condOpArgs = condOp.getArgs();
Operation *yieldOp = afterBlock.getTerminator();
ValueRange yieldOpArgs = yieldOp->getOperands();
bool canSimplify = false;
for (const auto &it :
llvm::enumerate(llvm::zip(op.getOperands(), yieldOpArgs))) {
auto index = static_cast<unsigned>(it.index());
auto [initVal, yieldOpArg] = it.value();
// If i-th yield operand is equal to the i-th operand of the scf.while,
// the i-th before block argument is a loop invariant.
if (yieldOpArg == initVal) {
canSimplify = true;
break;
}
// If the i-th yield operand is k-th after block argument, then we check
// if the (k+1)-th condition op operand is equal to either the i-th before
// block argument or the initial value of i-th before block argument. If
// the comparison results `true`, i-th before block argument is a loop
// invariant.
auto yieldOpBlockArg = llvm::dyn_cast<BlockArgument>(yieldOpArg);
if (yieldOpBlockArg && yieldOpBlockArg.getOwner() == &afterBlock) {
Value condOpArg = condOpArgs[yieldOpBlockArg.getArgNumber()];
if (condOpArg == beforeBlockArgs[index] || condOpArg == initVal) {
canSimplify = true;
break;
}
}
}
if (!canSimplify)
return failure();
SmallVector<Value> newInitArgs, newYieldOpArgs;
DenseMap<unsigned, Value> beforeBlockInitValMap;
SmallVector<Location> newBeforeBlockArgLocs;
for (const auto &it :
llvm::enumerate(llvm::zip(op.getOperands(), yieldOpArgs))) {
auto index = static_cast<unsigned>(it.index());
auto [initVal, yieldOpArg] = it.value();
// If i-th yield operand is equal to the i-th operand of the scf.while,
// the i-th before block argument is a loop invariant.
if (yieldOpArg == initVal) {
beforeBlockInitValMap.insert({index, initVal});
continue;
} else {
// If the i-th yield operand is k-th after block argument, then we check
// if the (k+1)-th condition op operand is equal to either the i-th
// before block argument or the initial value of i-th before block
// argument. If the comparison results `true`, i-th before block
// argument is a loop invariant.
auto yieldOpBlockArg = llvm::dyn_cast<BlockArgument>(yieldOpArg);
if (yieldOpBlockArg && yieldOpBlockArg.getOwner() == &afterBlock) {
Value condOpArg = condOpArgs[yieldOpBlockArg.getArgNumber()];
if (condOpArg == beforeBlockArgs[index] || condOpArg == initVal) {
beforeBlockInitValMap.insert({index, initVal});
continue;
}
}
}
newInitArgs.emplace_back(initVal);
newYieldOpArgs.emplace_back(yieldOpArg);
newBeforeBlockArgLocs.emplace_back(beforeBlockArgs[index].getLoc());
}
{
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(yieldOp);
rewriter.replaceOpWithNewOp<YieldOp>(yieldOp, newYieldOpArgs);
}
auto newWhile =
rewriter.create<WhileOp>(op.getLoc(), op.getResultTypes(), newInitArgs);
Block &newBeforeBlock = *rewriter.createBlock(
&newWhile.getBefore(), /*insertPt*/ {},
ValueRange(newYieldOpArgs).getTypes(), newBeforeBlockArgLocs);
Block &beforeBlock = op.getBefore().front();
SmallVector<Value> newBeforeBlockArgs(beforeBlock.getNumArguments());
// For each i-th before block argument we find it's replacement value as :-
// 1. If i-th before block argument is a loop invariant, we fetch it's
// initial value from `beforeBlockInitValMap` by querying for key `i`.
// 2. Else we fetch j-th new before block argument as the replacement
// value of i-th before block argument.
for (unsigned i = 0, j = 0, n = beforeBlock.getNumArguments(); i < n; i++) {
// If the index 'i' argument was a loop invariant we fetch it's initial
// value from `beforeBlockInitValMap`.
if (beforeBlockInitValMap.count(i) != 0)
newBeforeBlockArgs[i] = beforeBlockInitValMap[i];
else
newBeforeBlockArgs[i] = newBeforeBlock.getArgument(j++);
}
rewriter.mergeBlocks(&beforeBlock, &newBeforeBlock, newBeforeBlockArgs);
rewriter.inlineRegionBefore(op.getAfter(), newWhile.getAfter(),
newWhile.getAfter().begin());
rewriter.replaceOp(op, newWhile.getResults());
return success();
}
};
/// Remove loop invariant value from result (condition op) of scf.while.
/// A value is considered loop invariant if the final value yielded by
/// scf.condition is defined outside of the `before` block. We remove the
/// corresponding argument in `after` block and replace the use with the value.
/// We also replace the use of the corresponding result of scf.while with the
/// value.
///
/// Eg:
/// INPUT :-
/// %res_input:K = scf.while <...> iter_args(%arg0_before = , ...,
/// %argN_before = %N) {
/// ...
/// scf.condition(%cond) %arg0_before, %a, %b, %arg1_before, ...
/// } do {
/// ^bb0(%arg0_after, %arg1_after, %arg2_after, ..., %argK_after):
/// ...
/// some_func(%arg1_after)
/// ...
/// scf.yield %arg0_after, %arg2_after, ..., %argN_after
/// }
///
/// OUTPUT :-
/// %res_output:M = scf.while <...> iter_args(%arg0 = , ..., %argN = %N) {
/// ...
/// scf.condition(%cond) %arg0, %arg1, ..., %argM
/// } do {
/// ^bb0(%arg0, %arg3, ..., %argM):
/// ...
/// some_func(%a)
/// ...
/// scf.yield %arg0, %b, ..., %argN
/// }
///
/// EXPLANATION:
/// 1. The 1-th and 2-th operand of scf.condition are defined outside the
/// before block of scf.while, so they get removed.
/// 2. %res_input#1's uses are replaced by %a and %res_input#2's uses are
/// replaced by %b.
/// 3. The corresponding after block argument %arg1_after's uses are
/// replaced by %a and %arg2_after's uses are replaced by %b.
struct RemoveLoopInvariantValueYielded : public OpRewritePattern<WhileOp> {
using OpRewritePattern<WhileOp>::OpRewritePattern;
LogicalResult matchAndRewrite(WhileOp op,
PatternRewriter &rewriter) const override {
Block &beforeBlock = op.getBefore().front();
ConditionOp condOp = op.getConditionOp();
OperandRange condOpArgs = condOp.getArgs();
bool canSimplify = false;
for (Value condOpArg : condOpArgs) {
// Those values not defined within `before` block will be considered as
// loop invariant values. We map the corresponding `index` with their
// value.
if (condOpArg.getParentBlock() != &beforeBlock) {
canSimplify = true;
break;
}
}
if (!canSimplify)
return failure();
Block::BlockArgListType afterBlockArgs = op.getAfterArguments();
SmallVector<Value> newCondOpArgs;
SmallVector<Type> newAfterBlockType;
DenseMap<unsigned, Value> condOpInitValMap;
SmallVector<Location> newAfterBlockArgLocs;
for (const auto &it : llvm::enumerate(condOpArgs)) {
auto index = static_cast<unsigned>(it.index());
Value condOpArg = it.value();
// Those values not defined within `before` block will be considered as
// loop invariant values. We map the corresponding `index` with their
// value.
if (condOpArg.getParentBlock() != &beforeBlock) {
condOpInitValMap.insert({index, condOpArg});
} else {
newCondOpArgs.emplace_back(condOpArg);
newAfterBlockType.emplace_back(condOpArg.getType());
newAfterBlockArgLocs.emplace_back(afterBlockArgs[index].getLoc());
}
}
{
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(condOp);
rewriter.replaceOpWithNewOp<ConditionOp>(condOp, condOp.getCondition(),
newCondOpArgs);
}
auto newWhile = rewriter.create<WhileOp>(op.getLoc(), newAfterBlockType,
op.getOperands());
Block &newAfterBlock =
*rewriter.createBlock(&newWhile.getAfter(), /*insertPt*/ {},
newAfterBlockType, newAfterBlockArgLocs);
Block &afterBlock = op.getAfter().front();
// Since a new scf.condition op was created, we need to fetch the new
// `after` block arguments which will be used while replacing operations of
// previous scf.while's `after` blocks. We'd also be fetching new result
// values too.
SmallVector<Value> newAfterBlockArgs(afterBlock.getNumArguments());
SmallVector<Value> newWhileResults(afterBlock.getNumArguments());
for (unsigned i = 0, j = 0, n = afterBlock.getNumArguments(); i < n; i++) {
Value afterBlockArg, result;
// If index 'i' argument was loop invariant we fetch it's value from the
// `condOpInitMap` map.
if (condOpInitValMap.count(i) != 0) {
afterBlockArg = condOpInitValMap[i];
result = afterBlockArg;
} else {
afterBlockArg = newAfterBlock.getArgument(j);
result = newWhile.getResult(j);
j++;
}
newAfterBlockArgs[i] = afterBlockArg;
newWhileResults[i] = result;
}
rewriter.mergeBlocks(&afterBlock, &newAfterBlock, newAfterBlockArgs);
rewriter.inlineRegionBefore(op.getBefore(), newWhile.getBefore(),
newWhile.getBefore().begin());
rewriter.replaceOp(op, newWhileResults);
return success();
}
};
/// Remove WhileOp results that are also unused in 'after' block.
///
/// %0:2 = scf.while () : () -> (i32, i64) {
/// %condition = "test.condition"() : () -> i1
/// %v1 = "test.get_some_value"() : () -> i32
/// %v2 = "test.get_some_value"() : () -> i64
/// scf.condition(%condition) %v1, %v2 : i32, i64
/// } do {
/// ^bb0(%arg0: i32, %arg1: i64):
/// "test.use"(%arg0) : (i32) -> ()
/// scf.yield
/// }
/// return %0#0 : i32
///
/// becomes
/// %0 = scf.while () : () -> (i32) {
/// %condition = "test.condition"() : () -> i1
/// %v1 = "test.get_some_value"() : () -> i32
/// %v2 = "test.get_some_value"() : () -> i64
/// scf.condition(%condition) %v1 : i32
/// } do {
/// ^bb0(%arg0: i32):
/// "test.use"(%arg0) : (i32) -> ()
/// scf.yield
/// }
/// return %0 : i32
struct WhileUnusedResult : public OpRewritePattern<WhileOp> {
using OpRewritePattern<WhileOp>::OpRewritePattern;
LogicalResult matchAndRewrite(WhileOp op,
PatternRewriter &rewriter) const override {
auto term = op.getConditionOp();
auto afterArgs = op.getAfterArguments();
auto termArgs = term.getArgs();
// Collect results mapping, new terminator args and new result types.
SmallVector<unsigned> newResultsIndices;
SmallVector<Type> newResultTypes;
SmallVector<Value> newTermArgs;
SmallVector<Location> newArgLocs;
bool needUpdate = false;
for (const auto &it :
llvm::enumerate(llvm::zip(op.getResults(), afterArgs, termArgs))) {
auto i = static_cast<unsigned>(it.index());
Value result = std::get<0>(it.value());
Value afterArg = std::get<1>(it.value());
Value termArg = std::get<2>(it.value());
if (result.use_empty() && afterArg.use_empty()) {
needUpdate = true;
} else {
newResultsIndices.emplace_back(i);
newTermArgs.emplace_back(termArg);
newResultTypes.emplace_back(result.getType());
newArgLocs.emplace_back(result.getLoc());
}
}
if (!needUpdate)
return failure();
{
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(term);
rewriter.replaceOpWithNewOp<ConditionOp>(term, term.getCondition(),
newTermArgs);
}
auto newWhile =
rewriter.create<WhileOp>(op.getLoc(), newResultTypes, op.getInits());
Block &newAfterBlock = *rewriter.createBlock(
&newWhile.getAfter(), /*insertPt*/ {}, newResultTypes, newArgLocs);
// Build new results list and new after block args (unused entries will be
// null).
SmallVector<Value> newResults(op.getNumResults());
SmallVector<Value> newAfterBlockArgs(op.getNumResults());
for (const auto &it : llvm::enumerate(newResultsIndices)) {
newResults[it.value()] = newWhile.getResult(it.index());
newAfterBlockArgs[it.value()] = newAfterBlock.getArgument(it.index());
}
rewriter.inlineRegionBefore(op.getBefore(), newWhile.getBefore(),
newWhile.getBefore().begin());
Block &afterBlock = op.getAfter().front();
rewriter.mergeBlocks(&afterBlock, &newAfterBlock, newAfterBlockArgs);
rewriter.replaceOp(op, newResults);
return success();
}
};
/// Replace operations equivalent to the condition in the do block with true,
/// since otherwise the block would not be evaluated.
///
/// scf.while (..) : (i32, ...) -> ... {
/// %z = ... : i32
/// %condition = cmpi pred %z, %a
/// scf.condition(%condition) %z : i32, ...
/// } do {
/// ^bb0(%arg0: i32, ...):
/// %condition2 = cmpi pred %arg0, %a
/// use(%condition2)
/// ...
///
/// becomes
/// scf.while (..) : (i32, ...) -> ... {
/// %z = ... : i32
/// %condition = cmpi pred %z, %a
/// scf.condition(%condition) %z : i32, ...
/// } do {
/// ^bb0(%arg0: i32, ...):
/// use(%true)
/// ...
struct WhileCmpCond : public OpRewritePattern<scf::WhileOp> {
using OpRewritePattern<scf::WhileOp>::OpRewritePattern;
LogicalResult matchAndRewrite(scf::WhileOp op,
PatternRewriter &rewriter) const override {
using namespace scf;
auto cond = op.getConditionOp();
auto cmp = cond.getCondition().getDefiningOp<arith::CmpIOp>();
if (!cmp)
return failure();
bool changed = false;
for (auto tup :
llvm::zip(cond.getArgs(), op.getAfter().front().getArguments())) {
for (size_t opIdx = 0; opIdx < 2; opIdx++) {
if (std::get<0>(tup) != cmp.getOperand(opIdx))
continue;
for (OpOperand &u :
llvm::make_early_inc_range(std::get<1>(tup).getUses())) {
auto cmp2 = dyn_cast<arith::CmpIOp>(u.getOwner());
if (!cmp2)
continue;
// For a binary operator 1-opIdx gets the other side.
if (cmp2.getOperand(1 - opIdx) != cmp.getOperand(1 - opIdx))
continue;
bool samePredicate;
if (cmp2.getPredicate() == cmp.getPredicate())
samePredicate = true;
else if (cmp2.getPredicate() ==
arith::invertPredicate(cmp.getPredicate()))
samePredicate = false;
else
continue;
rewriter.replaceOpWithNewOp<arith::ConstantIntOp>(cmp2, samePredicate,
1);
changed = true;
}
}
}
return success(changed);
}
};
/// Remove unused init/yield args.
struct WhileRemoveUnusedArgs : public OpRewritePattern<WhileOp> {
using OpRewritePattern<WhileOp>::OpRewritePattern;
LogicalResult matchAndRewrite(WhileOp op,
PatternRewriter &rewriter) const override {
if (!llvm::any_of(op.getBeforeArguments(),
[](Value arg) { return arg.use_empty(); }))
return rewriter.notifyMatchFailure(op, "No args to remove");
YieldOp yield = op.getYieldOp();
// Collect results mapping, new terminator args and new result types.
SmallVector<Value> newYields;
SmallVector<Value> newInits;
llvm::BitVector argsToErase;
size_t argsCount = op.getBeforeArguments().size();
newYields.reserve(argsCount);
newInits.reserve(argsCount);
argsToErase.reserve(argsCount);
for (auto &&[beforeArg, yieldValue, initValue] : llvm::zip(
op.getBeforeArguments(), yield.getOperands(), op.getInits())) {
if (beforeArg.use_empty()) {
argsToErase.push_back(true);
} else {
argsToErase.push_back(false);
newYields.emplace_back(yieldValue);
newInits.emplace_back(initValue);
}
}
Block &beforeBlock = op.getBefore().front();
Block &afterBlock = op.getAfter().front();
beforeBlock.eraseArguments(argsToErase);
Location loc = op.getLoc();
auto newWhileOp =
rewriter.create<WhileOp>(loc, op.getResultTypes(), newInits,
/*beforeBody*/ nullptr, /*afterBody*/ nullptr);
Block &newBeforeBlock = newWhileOp.getBefore().front();
Block &newAfterBlock = newWhileOp.getAfter().front();
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(yield);
rewriter.replaceOpWithNewOp<YieldOp>(yield, newYields);
rewriter.mergeBlocks(&beforeBlock, &newBeforeBlock,
newBeforeBlock.getArguments());
rewriter.mergeBlocks(&afterBlock, &newAfterBlock,
newAfterBlock.getArguments());
rewriter.replaceOp(op, newWhileOp.getResults());
return success();
}
};
/// Remove duplicated ConditionOp args.
struct WhileRemoveDuplicatedResults : public OpRewritePattern<WhileOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(WhileOp op,
PatternRewriter &rewriter) const override {
ConditionOp condOp = op.getConditionOp();
ValueRange condOpArgs = condOp.getArgs();
llvm::SmallPtrSet<Value, 8> argsSet;
for (Value arg : condOpArgs)
argsSet.insert(arg);
if (argsSet.size() == condOpArgs.size())
return rewriter.notifyMatchFailure(op, "No results to remove");
llvm::SmallDenseMap<Value, unsigned> argsMap;
SmallVector<Value> newArgs;
argsMap.reserve(condOpArgs.size());
newArgs.reserve(condOpArgs.size());
for (Value arg : condOpArgs) {
if (!argsMap.count(arg)) {
auto pos = static_cast<unsigned>(argsMap.size());
argsMap.insert({arg, pos});
newArgs.emplace_back(arg);
}
}
ValueRange argsRange(newArgs);
Location loc = op.getLoc();
auto newWhileOp = rewriter.create<scf::WhileOp>(
loc, argsRange.getTypes(), op.getInits(), /*beforeBody*/ nullptr,
/*afterBody*/ nullptr);
Block &newBeforeBlock = newWhileOp.getBefore().front();
Block &newAfterBlock = newWhileOp.getAfter().front();
SmallVector<Value> afterArgsMapping;
SmallVector<Value> resultsMapping;
for (auto &&[i, arg] : llvm::enumerate(condOpArgs)) {
auto it = argsMap.find(arg);
assert(it != argsMap.end());
auto pos = it->second;
afterArgsMapping.emplace_back(newAfterBlock.getArgument(pos));
resultsMapping.emplace_back(newWhileOp->getResult(pos));
}
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(condOp);
rewriter.replaceOpWithNewOp<ConditionOp>(condOp, condOp.getCondition(),
argsRange);
Block &beforeBlock = op.getBefore().front();
Block &afterBlock = op.getAfter().front();
rewriter.mergeBlocks(&beforeBlock, &newBeforeBlock,
newBeforeBlock.getArguments());
rewriter.mergeBlocks(&afterBlock, &newAfterBlock, afterArgsMapping);
rewriter.replaceOp(op, resultsMapping);
return success();
}
};
} // namespace
void WhileOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<RemoveLoopInvariantArgsFromBeforeBlock,
RemoveLoopInvariantValueYielded, WhileConditionTruth,
WhileCmpCond, WhileUnusedResult, WhileRemoveDuplicatedResults,
WhileRemoveUnusedArgs>(context);
}
//===----------------------------------------------------------------------===//
// IndexSwitchOp
//===----------------------------------------------------------------------===//
/// Parse the case regions and values.
static ParseResult
parseSwitchCases(OpAsmParser &p, DenseI64ArrayAttr &cases,
SmallVectorImpl<std::unique_ptr<Region>> &caseRegions) {
SmallVector<int64_t> caseValues;
while (succeeded(p.parseOptionalKeyword("case"))) {
int64_t value;
Region ®ion = *caseRegions.emplace_back(std::make_unique<Region>());
if (p.parseInteger(value) || p.parseRegion(region, /*arguments=*/{}))
return failure();
caseValues.push_back(value);
}
cases = p.getBuilder().getDenseI64ArrayAttr(caseValues);
return success();
}
/// Print the case regions and values.
static void printSwitchCases(OpAsmPrinter &p, Operation *op,
DenseI64ArrayAttr cases, RegionRange caseRegions) {
for (auto [value, region] : llvm::zip(cases.asArrayRef(), caseRegions)) {
p.printNewline();
p << "case " << value << ' ';
p.printRegion(*region, /*printEntryBlockArgs=*/false);
}
}
LogicalResult scf::IndexSwitchOp::verify() {
if (getCases().size() != getCaseRegions().size()) {
return emitOpError("has ")
<< getCaseRegions().size() << " case regions but "
<< getCases().size() << " case values";
}
DenseSet<int64_t> valueSet;
for (int64_t value : getCases())
if (!valueSet.insert(value).second)
return emitOpError("has duplicate case value: ") << value;
auto verifyRegion = [&](Region ®ion, const Twine &name) -> LogicalResult {
auto yield = dyn_cast<YieldOp>(region.front().back());
if (!yield)
return emitOpError("expected region to end with scf.yield, but got ")
<< region.front().back().getName();
if (yield.getNumOperands() != getNumResults()) {
return (emitOpError("expected each region to return ")
<< getNumResults() << " values, but " << name << " returns "
<< yield.getNumOperands())
.attachNote(yield.getLoc())
<< "see yield operation here";
}
for (auto [idx, result, operand] :
llvm::zip(llvm::seq<unsigned>(0, getNumResults()), getResultTypes(),
yield.getOperandTypes())) {
if (result == operand)
continue;
return (emitOpError("expected result #")
<< idx << " of each region to be " << result)
.attachNote(yield.getLoc())
<< name << " returns " << operand << " here";
}
return success();
};
if (failed(verifyRegion(getDefaultRegion(), "default region")))
return failure();
for (auto [idx, caseRegion] : llvm::enumerate(getCaseRegions()))
if (failed(verifyRegion(caseRegion, "case region #" + Twine(idx))))
return failure();
return success();
}
unsigned scf::IndexSwitchOp::getNumCases() { return getCases().size(); }
Block &scf::IndexSwitchOp::getDefaultBlock() {
return getDefaultRegion().front();
}
Block &scf::IndexSwitchOp::getCaseBlock(unsigned idx) {
assert(idx < getNumCases() && "case index out-of-bounds");
return getCaseRegions()[idx].front();
}
void IndexSwitchOp::getSuccessorRegions(
std::optional<unsigned> index, ArrayRef<Attribute> operands,
SmallVectorImpl<RegionSuccessor> &successors) {
// All regions branch back to the parent op.
if (index) {
successors.emplace_back(getResults());
return;
}
// If a constant was not provided, all regions are possible successors.
auto operandValue = llvm::dyn_cast_or_null<IntegerAttr>(operands.front());
if (!operandValue) {
for (Region &caseRegion : getCaseRegions())
successors.emplace_back(&caseRegion);
successors.emplace_back(&getDefaultRegion());
return;
}
// Otherwise, try to find a case with a matching value. If not, the default
// region is the only successor.
for (auto [caseValue, caseRegion] : llvm::zip(getCases(), getCaseRegions())) {
if (caseValue == operandValue.getInt()) {
successors.emplace_back(&caseRegion);
return;
}
}
successors.emplace_back(&getDefaultRegion());
}
void IndexSwitchOp::getRegionInvocationBounds(
ArrayRef<Attribute> operands, SmallVectorImpl<InvocationBounds> &bounds) {
auto operandValue = llvm::dyn_cast_or_null<IntegerAttr>(operands.front());
if (!operandValue) {
// All regions are invoked at most once.
bounds.append(getNumRegions(), InvocationBounds(/*lb=*/0, /*ub=*/1));
return;
}
unsigned liveIndex = getNumRegions() - 1;
const auto *it = llvm::find(getCases(), operandValue.getInt());
if (it != getCases().end())
liveIndex = std::distance(getCases().begin(), it);
for (unsigned i = 0, e = getNumRegions(); i < e; ++i)
bounds.emplace_back(/*lb=*/0, /*ub=*/i == liveIndex);
}
//===----------------------------------------------------------------------===//
// TableGen'd op method definitions
//===----------------------------------------------------------------------===//
#define GET_OP_CLASSES
#include "mlir/Dialect/SCF/IR/SCFOps.cpp.inc"
|