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
|
//===--- RegionAnalysis.cpp -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "send-non-sendable"
#include "swift/SILOptimizer/Analysis/RegionAnalysis.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Type.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/FrozenMultiMap.h"
#include "swift/Basic/ImmutablePointerSet.h"
#include "swift/Basic/SmallBitVector.h"
#include "swift/SIL/BasicBlockData.h"
#include "swift/SIL/BasicBlockDatastructures.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/NodeDatastructures.h"
#include "swift/SIL/OperandDatastructures.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/PatternMatch.h"
#include "swift/SIL/PrunedLiveness.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/Test.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/SILOptimizer/Utils/PartitionUtils.h"
#include "swift/SILOptimizer/Utils/VariableNameUtils.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::PartitionPrimitives;
using namespace swift::PatternMatch;
using namespace swift::regionanalysisimpl;
bool swift::regionanalysisimpl::AbortOnUnknownPatternMatchError = false;
static llvm::cl::opt<bool, true> AbortOnUnknownPatternMatchErrorCmdLine(
"sil-region-isolation-assert-on-unknown-pattern",
llvm::cl::desc("Abort if SIL region isolation detects an unknown pattern. "
"Intended only to be used when debugging the compiler!"),
llvm::cl::Hidden,
llvm::cl::location(
swift::regionanalysisimpl::AbortOnUnknownPatternMatchError));
//===----------------------------------------------------------------------===//
// MARK: Utilities
//===----------------------------------------------------------------------===//
namespace {
using OperandRefRangeTransform = std::function<Operand *(Operand &)>;
using OperandRefRange =
iterator_range<llvm::mapped_iterator<MutableArrayRef<Operand>::iterator,
OperandRefRangeTransform>>;
} // anonymous namespace
static OperandRefRange makeOperandRefRange(MutableArrayRef<Operand> input) {
auto toOperand = [](Operand &operand) { return &operand; };
auto baseRange = llvm::make_range(input.begin(), input.end());
return llvm::map_range(baseRange, OperandRefRangeTransform(toOperand));
}
std::optional<ApplyIsolationCrossing>
regionanalysisimpl::getApplyIsolationCrossing(SILInstruction *inst) {
if (ApplyExpr *apply = inst->getLoc().getAsASTNode<ApplyExpr>())
if (auto crossing = apply->getIsolationCrossing())
return crossing;
if (auto fas = FullApplySite::isa(inst)) {
if (auto crossing = fas.getIsolationCrossing())
return crossing;
}
return {};
}
namespace {
struct UseDefChainVisitor
: public AccessUseDefChainVisitor<UseDefChainVisitor, SILValue> {
bool isMerge = false;
/// The actor isolation that we found while walking from use->def. Always set
/// to the first one encountered.
std::optional<ActorIsolation> actorIsolation;
SILValue visitAll(SILValue sourceAddr) {
SILValue result = visit(sourceAddr);
if (!result)
return sourceAddr;
while (SILValue nextAddr = visit(result))
result = nextAddr;
return result;
}
SILValue visitBase(SILValue base, AccessStorage::Kind kind) {
// If we are passed a project_box, we want to return the box itself. The
// reason for this is that the project_box is considered to be non-aliasing
// memory. We want to treat it as part of the box which is
// aliasing... meaning that we need to merge.
if (kind == AccessStorage::Box)
return cast<ProjectBoxInst>(base)->getOperand();
return SILValue();
}
SILValue visitNonAccess(SILValue) { return SILValue(); }
SILValue visitPhi(SILPhiArgument *phi) {
llvm_unreachable("Should never hit this");
}
// Override AccessUseDefChainVisitor to ignore access markers and find the
// outer access base.
SILValue visitNestedAccess(BeginAccessInst *access) {
return visitAll(access->getSource());
}
SILValue visitStorageCast(SingleValueInstruction *cast, Operand *sourceAddr,
AccessStorageCast castType) {
// If this is a type case, see if the result of the cast is sendable. In
// such a case, we do not want to look through this cast.
if (castType == AccessStorageCast::Type &&
!SILIsolationInfo::isNonSendableType(cast->getType(),
cast->getFunction()))
return SILValue();
// Do not look through begin_borrow [var_decl]. They are start new semantic
// values.
//
// This only comes up if a codegen pattern occurs where the debug
// information is place on a debug_value instead of the alloc_box.
if (auto *bbi = dyn_cast<BeginBorrowInst>(cast)) {
if (bbi->isFromVarDecl())
return SILValue();
}
// If we do not have an identity cast, mark this as a merge.
isMerge |= castType != AccessStorageCast::Identity;
return sourceAddr->get();
}
SILValue visitAccessProjection(SingleValueInstruction *inst,
Operand *sourceAddr) {
// See if this access projection is into a single element value. If so, we
// do not want to treat this as a merge.
if (auto p = Projection(inst)) {
switch (p.getKind()) {
// Currently if we load and then project_box from a memory location,
// we treat that as a projection. This follows the semantics/notes in
// getAccessProjectionOperand.
case ProjectionKind::Box:
return cast<ProjectBoxInst>(inst)->getOperand();
case ProjectionKind::Upcast:
case ProjectionKind::RefCast:
case ProjectionKind::BlockStorageCast:
case ProjectionKind::BitwiseCast:
case ProjectionKind::Class:
case ProjectionKind::TailElems:
llvm_unreachable("Shouldn't see this here");
case ProjectionKind::Index:
// Index is always a merge.
isMerge = true;
break;
case ProjectionKind::Enum: {
auto op = cast<UncheckedTakeEnumDataAddrInst>(inst)->getOperand();
// See if our operand type is a sendable type. In such a case, we do not
// want to look through our operand.
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
break;
}
case ProjectionKind::Tuple: {
// These are merges if we have multiple fields.
auto op = cast<TupleElementAddrInst>(inst)->getOperand();
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
isMerge |= op->getType().getNumTupleElements() > 1;
break;
}
case ProjectionKind::Struct:
auto op = cast<StructElementAddrInst>(inst)->getOperand();
// See if our result type is a sendable type. In such a case, we do not
// want to look through the struct_element_addr since we do not want to
// identify the sendable type with the non-sendable operand. These we
// are always going to ignore anyways since a sendable let/var field of
// a struct can always be used.
if (!SILIsolationInfo::isNonSendableType(op->getType(),
op->getFunction()))
return SILValue();
// These are merges if we have multiple fields.
isMerge |= op->getType().getNumNominalFields() > 1;
break;
}
}
return sourceAddr->get();
}
};
} // namespace
/// Classify an instructions as look through when we are looking through
/// values. We assert that all instructions that are CONSTANT_TRANSLATION
/// LookThrough to make sure they stay in sync.
static bool isStaticallyLookThroughInst(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::BeginAccessInst:
case SILInstructionKind::BeginCOWMutationInst:
case SILInstructionKind::BeginDeallocRefInst:
case SILInstructionKind::BridgeObjectToRefInst:
case SILInstructionKind::CopyValueInst:
case SILInstructionKind::CopyableToMoveOnlyWrapperAddrInst:
case SILInstructionKind::CopyableToMoveOnlyWrapperValueInst:
case SILInstructionKind::DestructureStructInst:
case SILInstructionKind::DestructureTupleInst:
case SILInstructionKind::DifferentiableFunctionExtractInst:
case SILInstructionKind::DropDeinitInst:
case SILInstructionKind::EndCOWMutationInst:
case SILInstructionKind::EndInitLetRefInst:
case SILInstructionKind::ExplicitCopyValueInst:
case SILInstructionKind::InitEnumDataAddrInst:
case SILInstructionKind::LinearFunctionExtractInst:
case SILInstructionKind::MarkDependenceInst:
case SILInstructionKind::MarkUninitializedInst:
case SILInstructionKind::MarkUnresolvedNonCopyableValueInst:
case SILInstructionKind::MarkUnresolvedReferenceBindingInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableAddrInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableBoxInst:
case SILInstructionKind::MoveOnlyWrapperToCopyableValueInst:
case SILInstructionKind::OpenExistentialAddrInst:
case SILInstructionKind::OpenExistentialValueInst:
case SILInstructionKind::ProjectBlockStorageInst:
case SILInstructionKind::ProjectBoxInst:
case SILInstructionKind::RefToBridgeObjectInst:
case SILInstructionKind::RefToUnownedInst:
case SILInstructionKind::UncheckedRefCastInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
case SILInstructionKind::UnownedCopyValueInst:
case SILInstructionKind::UnownedToRefInst:
case SILInstructionKind::UpcastInst:
case SILInstructionKind::ValueToBridgeObjectInst:
case SILInstructionKind::WeakCopyValueInst:
case SILInstructionKind::StrongCopyWeakValueInst:
case SILInstructionKind::StrongCopyUnmanagedValueInst:
case SILInstructionKind::RefToUnmanagedInst:
case SILInstructionKind::UnmanagedToRefInst:
case SILInstructionKind::InitExistentialValueInst:
return true;
case SILInstructionKind::MoveValueInst:
// Look through if it isn't from a var decl.
return !cast<MoveValueInst>(inst)->isFromVarDecl();
case SILInstructionKind::BeginBorrowInst:
// Look through if it isn't from a var decl.
return !cast<BeginBorrowInst>(inst)->isFromVarDecl();
case SILInstructionKind::UnconditionalCheckedCastInst: {
auto cast = SILDynamicCastInst::getAs(inst);
assert(cast);
if (cast.isRCIdentityPreserving())
return true;
return false;
}
}
}
static bool isLookThroughIfResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::RawPointerToRefInst:
return true;
}
}
static bool isLookThroughIfOperandNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::RefToRawPointerInst:
return true;
}
}
static bool isLookThroughIfOperandAndResultNonSendable(SILInstruction *inst) {
switch (inst->getKind()) {
default:
return false;
case SILInstructionKind::UncheckedTrivialBitCastInst:
case SILInstructionKind::UncheckedBitwiseCastInst:
case SILInstructionKind::UncheckedValueCastInst:
case SILInstructionKind::StructElementAddrInst:
case SILInstructionKind::TupleElementAddrInst:
case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
return true;
}
}
namespace {
struct TermArgSources {
SmallFrozenMultiMap<SILValue, Operand *, 8> argSources;
template <typename ValueRangeTy = ArrayRef<Operand *>>
void addValues(ValueRangeTy valueRange, SILBasicBlock *destBlock) {
for (auto pair : llvm::enumerate(valueRange))
argSources.insert(destBlock->getArgument(pair.index()), pair.value());
}
TermArgSources() {}
void init(SILInstruction *inst) {
switch (cast<TermInst>(inst)->getTermKind()) {
case TermKind::UnreachableInst:
case TermKind::ReturnInst:
case TermKind::ThrowInst:
case TermKind::ThrowAddrInst:
case TermKind::YieldInst:
case TermKind::UnwindInst:
case TermKind::TryApplyInst:
case TermKind::SwitchValueInst:
case TermKind::SwitchEnumInst:
case TermKind::SwitchEnumAddrInst:
case TermKind::AwaitAsyncContinuationInst:
case TermKind::CheckedCastAddrBranchInst:
llvm_unreachable("Unsupported?!");
case TermKind::BranchInst:
return init(cast<BranchInst>(inst));
case TermKind::CondBranchInst:
return init(cast<CondBranchInst>(inst));
case TermKind::DynamicMethodBranchInst:
return init(cast<DynamicMethodBranchInst>(inst));
case TermKind::CheckedCastBranchInst:
return init(cast<CheckedCastBranchInst>(inst));
}
llvm_unreachable("Covered switch isn't covered?!");
}
private:
void init(BranchInst *bi) {
addValues(makeOperandRefRange(bi->getAllOperands()), bi->getDestBB());
}
void init(CondBranchInst *cbi) {
addValues(makeOperandRefRange(cbi->getTrueOperands()), cbi->getTrueBB());
addValues(makeOperandRefRange(cbi->getFalseOperands()), cbi->getFalseBB());
}
void init(DynamicMethodBranchInst *dmBranchInst) {
addValues({&dmBranchInst->getAllOperands()[0]},
dmBranchInst->getHasMethodBB());
}
void init(CheckedCastBranchInst *ccbi) {
addValues({&ccbi->getAllOperands()[0]}, ccbi->getSuccessBB());
}
};
} // namespace
static bool isProjectedFromAggregate(SILValue value) {
assert(value->getType().isAddress());
UseDefChainVisitor visitor;
visitor.visitAll(value);
return visitor.isMerge;
}
namespace {
using AsyncLetSourceValue =
llvm::PointerUnion<PartialApplyInst *, ThinToThickFunctionInst *>;
} // namespace
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromStart(SILValue value) {
// If our operand is Sendable then we want to return nullptr. We only want to
// return a value if we are not
auto fType = value->getType().castTo<SILFunctionType>();
if (fType->isSendable())
return {};
SILValue temp = value;
while (true) {
if (isa<ConvertEscapeToNoEscapeInst>(temp) ||
isa<ConvertFunctionInst>(temp)) {
temp = cast<SingleValueInstruction>(temp)->getOperand(0);
}
if (temp == value)
break;
value = temp;
}
// We can also get a thin_to_thick_function here if we do not capture
// anything. In such a case, we just do not process the partial apply get
if (auto *ttfi = dyn_cast<ThinToThickFunctionInst>(value))
return {{ttfi}};
// Ok, we could still have a reabstraction thunk. In such a case, we want the
// partial_apply that we process to be the original partial_apply (or
// thin_to_thick)... so in that case process recursively.
auto *pai = cast<PartialApplyInst>(value);
if (auto *calleeFunction = pai->getCalleeFunction()) {
if (calleeFunction->isThunk() == IsReabstractionThunk) {
return findAsyncLetPartialApplyFromStart(pai->getArgument(0));
}
}
// Otherwise, this is the right partial_apply... apply it!
return {{pai}};
}
/// This recurses through reabstraction thunks.
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromStart(BuiltinInst *bi) {
return findAsyncLetPartialApplyFromStart(bi->getOperand(1));
}
/// This recurses through reabstraction thunks.
static std::optional<AsyncLetSourceValue>
findAsyncLetPartialApplyFromGet(ApplyInst *ai) {
auto *bi = cast<BuiltinInst>(FullApplySite(ai).getArgument(0));
assert(*bi->getBuiltinKind() ==
BuiltinValueKind::StartAsyncLetWithLocalBuffer);
return findAsyncLetPartialApplyFromStart(bi);
}
static bool isAsyncLetBeginPartialApply(PartialApplyInst *pai) {
if (auto *fas = pai->getCalleeFunction())
if (fas->isThunk())
return false;
// Look through reabstraction thunks.
SILValue result = pai;
while (true) {
SILValue iter = result;
if (auto *use = iter->getSingleUse()) {
if (auto *maybeThunk = dyn_cast<PartialApplyInst>(use->getUser())) {
if (auto *fas = maybeThunk->getCalleeFunction()) {
if (fas->isThunk()) {
iter = maybeThunk;
}
}
}
}
if (auto *cfi = iter->getSingleUserOfType<ConvertFunctionInst>())
iter = cfi;
if (auto *cvt = iter->getSingleUserOfType<ConvertEscapeToNoEscapeInst>())
iter = cvt;
if (iter == result)
break;
result = iter;
}
auto *bi = result->getSingleUserOfType<BuiltinInst>();
if (!bi)
return false;
auto kind = bi->getBuiltinKind();
if (!kind)
return false;
return *kind == BuiltinValueKind::StartAsyncLetWithLocalBuffer;
}
/// Returns true if this is a function argument that is able to be sent in the
/// body of our function.
static bool canFunctionArgumentBeSent(SILFunctionArgument *arg) {
// Indirect out parameters can never be sent.
if (arg->isIndirectResult() || arg->isIndirectErrorResult())
return false;
// If we have a function argument that is closure captured by a Sendable
// closure, allow for the argument to be sent.
//
// DISCUSSION: The reason that we do this is that in the case of us
// having an actual Sendable closure there are two cases we can see:
//
// 1. If we have an actual Sendable closure, the AST will emit an
// earlier error saying that we are capturing a non-Sendable value in a
// Sendable closure. So we want to squelch the error that we would emit
// otherwise. This only occurs when we are not in swift-6 mode since in
// swift-6 mode we will error on the earlier error... but in the case of
// us not being in swift 6 mode lets not emit extra errors.
//
// 2. If we have an async-let based Sendable closure, we want to allow
// for the argument to be sent in the async let's statement and
// not emit an error.
//
// TODO: Once the async let refactoring change this will no longer be needed
// since closure captures will have sending parameters and be
// non-Sendable.
if (arg->isClosureCapture() &&
arg->getFunction()->getLoweredFunctionType()->isSendable())
return true;
// Otherwise, we only allow for the argument to be sent if it is explicitly
// marked as a 'sending' parameter.
return arg->isSending();
}
//===----------------------------------------------------------------------===//
// MARK: RegionAnalysisValueMap
//===----------------------------------------------------------------------===//
SILInstruction *RegionAnalysisValueMap::maybeGetActorIntroducingInst(
Element trackableValueID) const {
if (auto value = getValueForId(trackableValueID)) {
auto rep = value->getRepresentative();
if (rep.hasRegionIntroducingInst())
return rep.getActorRegionIntroducingInst();
}
return nullptr;
}
std::optional<TrackableValue>
RegionAnalysisValueMap::getValueForId(Element id) const {
auto iter = stateIndexToEquivalenceClass.find(id);
if (iter == stateIndexToEquivalenceClass.end())
return {};
auto iter2 = equivalenceClassValuesToState.find(iter->second);
if (iter2 == equivalenceClassValuesToState.end())
return {};
return {{iter2->first, iter2->second}};
}
SILValue
RegionAnalysisValueMap::getRepresentative(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative().getValue();
}
SILValue
RegionAnalysisValueMap::maybeGetRepresentative(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative().maybeGetValue();
}
RepresentativeValue
RegionAnalysisValueMap::getRepresentativeValue(Element trackableValueID) const {
return getValueForId(trackableValueID)->getRepresentative();
}
SILIsolationInfo
RegionAnalysisValueMap::getIsolationRegion(Element trackableValueID) const {
auto iter = getValueForId(trackableValueID);
if (!iter)
return {};
return iter->getValueState().getIsolationRegionInfo();
}
SILIsolationInfo
RegionAnalysisValueMap::getIsolationRegion(SILValue value) const {
auto iter = equivalenceClassValuesToState.find(RepresentativeValue(value));
if (iter == equivalenceClassValuesToState.end())
return {};
return iter->getSecond().getIsolationRegionInfo();
}
std::pair<TrackableValue, bool>
RegionAnalysisValueMap::initializeTrackableValue(
SILValue value, SILIsolationInfo newInfo) const {
auto info = getUnderlyingTrackedValue(value);
value = info.value;
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
value, TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {{iter.first->first, iter.first->second}, false};
}
// If we did not insert, just return the already stored value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] = value;
// Before we do anything, see if we have a Sendable value.
if (!SILIsolationInfo::isNonSendableType(value->getType(), fn)) {
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {{iter.first->first, iter.first->second}, true};
}
// Otherwise, we have a non-Sendable type... so wire up the isolation.
iter.first->getSecond().setIsolationRegionInfo(newInfo);
return {{iter.first->first, iter.first->second}, true};
}
/// If \p isAddressCapturedByPartialApply is set to true, then this value is
/// an address that is captured by a partial_apply and we want to treat it as
/// may alias.
TrackableValue RegionAnalysisValueMap::getTrackableValue(
SILValue value, bool isAddressCapturedByPartialApply) const {
auto info = getUnderlyingTrackedValue(value);
value = info.value;
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
value, TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {iter.first->first, iter.first->second};
}
// If we did not insert, just return the already stored value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] = value;
// Otherwise, we need to compute our flags.
// Treat function ref and class method as either actor isolated or
// sendable. Formally they are non-Sendable, so we do the check before we
// check the oracle.
if (isa<FunctionRefInst, ClassMethodInst>(value)) {
if (auto isolation = SILIsolationInfo::get(value)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
return {iter.first->first, iter.first->second};
}
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {iter.first->first, iter.first->second};
}
// Then check our oracle to see if the value is actually sendable. If we have
// a Sendable value, just return early.
if (!SILIsolationInfo::isNonSendableType(value->getType(), fn)) {
iter.first->getSecond().addFlag(TrackableValueFlag::isSendable);
return {iter.first->first, iter.first->second};
}
// Ok, at this point we have a non-Sendable value. First process addresses.
if (value->getType().isAddress()) {
// If we were able to find this was actor isolated from finding our
// underlying object, use that. It is never wrong.
if (info.actorIsolation) {
SILIsolationInfo isolation;
if (info.value->getType().isAnyActor()) {
isolation = SILIsolationInfo::getActorInstanceIsolated(
value, info.value, info.actorIsolation->getActor());
} else if (info.actorIsolation->isGlobalActor()) {
isolation = SILIsolationInfo::getGlobalActorIsolated(
value, info.actorIsolation->getGlobalActor());
}
if (isolation) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
auto storage = AccessStorageWithBase::compute(value);
if (storage.storage) {
// Check if we have a uniquely identified address that was not captured
// by a partial apply... in such a case, we treat it as no-alias.
if (storage.storage.isUniquelyIdentified() &&
!isAddressCapturedByPartialApply) {
iter.first->getSecond().removeFlag(TrackableValueFlag::isMayAlias);
}
if (auto isolation = SILIsolationInfo::get(storage.base)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
}
// Check if we have a load or load_borrow from an address. In that case, we
// want to look through the load and find a better root from the address we
// loaded from.
if (isa<LoadInst, LoadBorrowInst>(iter.first->first.getValue())) {
auto *svi = cast<SingleValueInstruction>(iter.first->first.getValue());
// See if we can use get underlying tracked value to find if it is actor
// isolated.
//
// TODO: Instead of using AccessStorageBase, just use our own visitor
// everywhere. Just haven't done it due to possible perturbations.
auto parentAddrInfo = getUnderlyingTrackedValue(svi);
if (parentAddrInfo.actorIsolation) {
iter.first->getSecond().setIsolationRegionInfo(
SILIsolationInfo::getActorInstanceIsolated(
svi, parentAddrInfo.value,
parentAddrInfo.actorIsolation->getActor()));
}
auto storage = AccessStorageWithBase::compute(svi->getOperand(0));
if (storage.storage) {
if (auto isolation = SILIsolationInfo::get(storage.base)) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
}
}
return {iter.first->first, iter.first->second};
}
// Ok, we have a non-Sendable type, see if we do not have any isolation
// yet. If we don't, attempt to infer its isolation.
if (!iter.first->getSecond().hasIsolationRegionInfo()) {
if (auto isolation = SILIsolationInfo::get(iter.first->first.getValue())) {
iter.first->getSecond().setIsolationRegionInfo(isolation);
return {iter.first->first, iter.first->second};
}
}
return {iter.first->first, iter.first->second};
}
std::optional<TrackableValue>
RegionAnalysisValueMap::getTrackableValueForActorIntroducingInst(
SILInstruction *inst) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.find(inst);
if (iter == self->equivalenceClassValuesToState.end())
return {};
// Otherwise, we need to compute our flags.
return {{iter->first, iter->second}};
}
std::optional<TrackableValue>
RegionAnalysisValueMap::tryToTrackValue(SILValue value) const {
auto state = getTrackableValue(value);
if (state.isNonSendable())
return state;
return {};
}
TrackableValue RegionAnalysisValueMap::getActorIntroducingRepresentative(
SILInstruction *introducingInst, SILIsolationInfo actorIsolation) const {
auto *self = const_cast<RegionAnalysisValueMap *>(this);
auto iter = self->equivalenceClassValuesToState.try_emplace(
introducingInst,
TrackableValueState(equivalenceClassValuesToState.size()));
// If we did not insert, just return the already stored value.
if (!iter.second) {
return {iter.first->first, iter.first->second};
}
// Otherwise, wire up the value.
self->stateIndexToEquivalenceClass[iter.first->second.getID()] =
introducingInst;
iter.first->getSecond().setIsolationRegionInfo(actorIsolation);
return {iter.first->first, iter.first->second};
}
bool RegionAnalysisValueMap::valueHasID(SILValue value, bool dumpIfHasNoID) {
assert(getTrackableValue(value).isNonSendable() &&
"Can only accept non-Sendable values");
bool hasID = equivalenceClassValuesToState.count(value);
if (!hasID && dumpIfHasNoID) {
llvm::errs() << "FAILURE: valueHasID of ";
value->print(llvm::errs());
llvm::report_fatal_error("standard compiler error");
}
return hasID;
}
Element RegionAnalysisValueMap::lookupValueID(SILValue value) {
auto state = getTrackableValue(value);
assert(state.isNonSendable() &&
"only non-Sendable values should be entered in the map");
return state.getID();
}
void RegionAnalysisValueMap::print(llvm::raw_ostream &os) const {
#ifndef NDEBUG
// Since this is just used for debug output, be inefficient to make nicer
// output.
std::vector<std::pair<unsigned, RepresentativeValue>> temp;
for (auto p : stateIndexToEquivalenceClass) {
temp.emplace_back(p.first, p.second);
}
std::sort(temp.begin(), temp.end());
for (auto p : temp) {
os << "%%" << p.first << ": ";
auto value = getValueForId(Element(p.first));
value->print(os);
}
#endif
}
static SILValue getUnderlyingTrackedObjectValue(SILValue value) {
auto *fn = value->getFunction();
SILValue result = value;
while (true) {
SILValue temp = result;
if (auto *svi = dyn_cast<SingleValueInstruction>(temp)) {
if (isStaticallyLookThroughInst(svi)) {
temp = svi->getOperand(0);
}
// If we have a cast and our operand and result are non-Sendable, treat it
// as a look through.
if (isLookThroughIfOperandAndResultNonSendable(svi)) {
if (SILIsolationInfo::isNonSendableType(svi->getType(), fn) &&
SILIsolationInfo::isNonSendableType(svi->getOperand(0)->getType(),
fn)) {
temp = svi->getOperand(0);
}
}
if (isLookThroughIfResultNonSendable(svi)) {
if (SILIsolationInfo::isNonSendableType(svi->getType(), fn)) {
temp = svi->getOperand(0);
}
}
if (isLookThroughIfOperandNonSendable(svi)) {
// If our operand is a non-Sendable type, look through this instruction.
if (SILIsolationInfo::isNonSendableType(svi->getOperand(0)->getType(),
fn)) {
temp = svi->getOperand(0);
}
}
}
if (auto *inst = temp->getDefiningInstruction()) {
if (isStaticallyLookThroughInst(inst)) {
temp = inst->getOperand(0);
}
}
if (temp != result) {
result = temp;
continue;
}
return result;
}
}
RegionAnalysisValueMap::UnderlyingTrackedValueInfo
RegionAnalysisValueMap::getUnderlyingTrackedValueHelper(SILValue value) const {
// Before a check if the value we are attempting to access is Sendable. In
// such a case, just return early.
if (!SILIsolationInfo::isNonSendableType(value))
return UnderlyingTrackedValueInfo(value);
// Look through a project_box, so that we process it like its operand object.
if (auto *pbi = dyn_cast<ProjectBoxInst>(value)) {
value = pbi->getOperand();
}
if (!value->getType().isAddress()) {
SILValue underlyingValue = getUnderlyingTrackedObjectValue(value);
// If we do not have a load inst, just return the value.
if (!isa<LoadInst, LoadBorrowInst>(underlyingValue)) {
return UnderlyingTrackedValueInfo(underlyingValue);
}
// If we got an address, lets see if we can do even better by looking at the
// address.
value = cast<SingleValueInstruction>(underlyingValue)->getOperand(0);
}
assert(value->getType().isAddress());
UseDefChainVisitor visitor;
SILValue base = visitor.visitAll(value);
assert(base);
if (base->getType().isObject()) {
// NOTE: We purposely recurse into the cached version of our computation
// rather than recurse into getUnderlyingTrackedObjectValueHelper. This is
// safe since we know that value was previously an address so if our base is
// an object, it cannot be the same object.
return {getUnderlyingTrackedValue(base).value, visitor.actorIsolation};
}
return {base, visitor.actorIsolation};
}
//===----------------------------------------------------------------------===//
// MARK: TrackableValue
//===----------------------------------------------------------------------===//
bool TrackableValue::isSendingParameter() const {
// First get our alloc_stack.
//
// TODO: We should just put a flag on the alloc_stack, so we /know/ 100% that
// it is from a consuming parameter. We don't have that so we pattern match.
auto *asi =
dyn_cast_or_null<AllocStackInst>(representativeValue.maybeGetValue());
if (!asi)
return false;
if (asi->getParent() != asi->getFunction()->getEntryBlock())
return false;
// See if we are initialized from a 'sending' parameter and are the only
// use of the parameter.
OperandWorklist worklist(asi->getFunction());
worklist.pushResultOperandsIfNotVisited(asi);
while (auto *use = worklist.pop()) {
auto *user = use->getUser();
// Look through instructions that we don't care about.
if (isa<MarkUnresolvedNonCopyableValueInst,
MoveOnlyWrapperToCopyableAddrInst>(user)) {
worklist.pushResultOperandsIfNotVisited(user);
}
if (auto *si = dyn_cast<StoreInst>(user)) {
// Check if our store inst is from a 'sending' function argument and for
// which the store is the only use of the function argument.
auto *fArg = dyn_cast<SILFunctionArgument>(si->getSrc());
if (!fArg || !fArg->isSending())
return false;
return fArg->getSingleUse();
}
if (auto *copyAddr = dyn_cast<CopyAddrInst>(user)) {
// Check if our copy_addr is from a 'sending' function argument and for
// which the copy_addr is the only use of the function argument.
auto *fArg = dyn_cast<SILFunctionArgument>(copyAddr->getSrc());
if (!fArg || !fArg->isSending())
return false;
return fArg->getSingleUse();
}
}
// Otherwise, this isn't a consuming parameter.
return false;
}
//===----------------------------------------------------------------------===//
// MARK: Partial Apply Reachability
//===----------------------------------------------------------------------===//
namespace {
/// We need to be able to know if instructions that extract sendable fields from
/// non-sendable addresses are reachable from a partial_apply that captures the
/// non-sendable value or its underlying object by reference. In such a case, we
/// need to require the value to not be sent when the extraction happens since
/// we could race on extracting the value.
///
/// The reason why we use a dataflow to do this is that:
///
/// 1. We do not want to recompute this for each individual instruction that
/// might be reachable from the partial apply.
///
/// 2. Just computing reachability early is a very easy way to do this.
struct PartialApplyReachabilityDataflow {
RegionAnalysisValueMap &valueMap;
PostOrderFunctionInfo *pofi;
llvm::DenseMap<SILValue, unsigned> valueToBit;
std::vector<std::pair<SILValue, SILInstruction *>> valueToGenInsts;
struct BlockState {
SmallBitVector entry;
SmallBitVector exit;
SmallBitVector gen;
bool needsUpdate = true;
};
BasicBlockData<BlockState> blockData;
bool propagatedReachability = false;
PartialApplyReachabilityDataflow(SILFunction *fn,
RegionAnalysisValueMap &valueMap,
PostOrderFunctionInfo *pofi)
: valueMap(valueMap), pofi(pofi), blockData(fn) {}
/// Begin tracking an operand of a partial apply.
void add(Operand *op);
/// Once we have finished adding data to the data, propagate reachability.
void propagateReachability();
bool isReachable(SILValue value, SILInstruction *user) const;
bool isReachable(Operand *op) const {
return isReachable(op->get(), op->getUser());
}
bool isGenInstruction(SILValue value, SILInstruction *inst) const {
assert(propagatedReachability && "Only valid once propagated reachability");
auto iter =
std::lower_bound(valueToGenInsts.begin(), valueToGenInsts.end(),
std::make_pair(value, nullptr),
[](const std::pair<SILValue, SILInstruction *> &p1,
const std::pair<SILValue, SILInstruction *> &p2) {
return p1 < p2;
});
return iter != valueToGenInsts.end() && iter->first == value &&
iter->second == inst;
}
void print(llvm::raw_ostream &os) const;
SWIFT_DEBUG_DUMP { print(llvm::dbgs()); }
private:
SILValue getRootValue(SILValue value) const {
return valueMap.getRepresentative(value);
}
unsigned getBitForValue(SILValue value) const {
unsigned size = valueToBit.size();
auto &self = const_cast<PartialApplyReachabilityDataflow &>(*this);
auto iter = self.valueToBit.try_emplace(value, size);
return iter.first->second;
}
};
} // namespace
void PartialApplyReachabilityDataflow::add(Operand *op) {
assert(!propagatedReachability &&
"Cannot add more operands once reachability is computed");
SILValue underlyingValue = getRootValue(op->get());
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< "PartialApplyReachability::add.\nValue: "
<< underlyingValue << "User: " << *op->getUser());
unsigned bit = getBitForValue(underlyingValue);
auto &state = blockData[op->getParentBlock()];
state.gen.resize(bit + 1);
state.gen.set(bit);
valueToGenInsts.emplace_back(underlyingValue, op->getUser());
}
bool PartialApplyReachabilityDataflow::isReachable(SILValue value,
SILInstruction *user) const {
assert(
propagatedReachability &&
"Can only check for reachability once reachability has been propagated");
SILValue baseValue = getRootValue(value);
auto iter = valueToBit.find(baseValue);
// If we aren't tracking this value... just bail.
if (iter == valueToBit.end())
return false;
unsigned bitNum = iter->second;
auto &state = blockData[user->getParent()];
// If we are reachable at entry, then we are done.
if (state.entry.test(bitNum)) {
return true;
}
// Otherwise, check if we are reachable at exit. If we are not, then we are
// not reachable.
if (!state.exit.test(bitNum)) {
return false;
}
// We were not reachable at entry but are at our exit... walk the block and
// see if our user is before a gen instruction.
auto genStart = std::lower_bound(
valueToGenInsts.begin(), valueToGenInsts.end(),
std::make_pair(baseValue, nullptr),
[](const std::pair<SILValue, SILInstruction *> &p1,
const std::pair<SILValue, SILInstruction *> &p2) { return p1 < p2; });
if (genStart == valueToGenInsts.end() || genStart->first != baseValue)
return false;
auto genEnd = genStart;
while (genEnd != valueToGenInsts.end() && genEnd->first == baseValue)
++genEnd;
// Walk forward from the beginning of the block to user. If we do not find a
// gen instruction, then we know the gen occurs after the op.
return llvm::any_of(
user->getParent()->getRangeEndingAtInst(user), [&](SILInstruction &inst) {
auto iter = std::lower_bound(
genStart, genEnd, std::make_pair(baseValue, &inst),
[](const std::pair<SILValue, SILInstruction *> &p1,
const std::pair<SILValue, SILInstruction *> &p2) {
return p1 < p2;
});
return iter != valueToGenInsts.end() && iter->first == baseValue &&
iter->second == &inst;
});
}
void PartialApplyReachabilityDataflow::propagateReachability() {
assert(!propagatedReachability && "Cannot propagate reachability twice");
propagatedReachability = true;
// Now that we have finished initializing, resize all of our bitVectors to the
// final number of bits.
unsigned numBits = valueToBit.size();
// If numBits is none, we have nothing to process.
if (numBits == 0)
return;
for (auto iter : blockData) {
iter.data.entry.resize(numBits);
iter.data.exit.resize(numBits);
iter.data.gen.resize(numBits);
iter.data.needsUpdate = true;
}
// Freeze our value to gen insts map so we can perform in block checks.
sortUnique(valueToGenInsts);
// We perform a simple gen-kill dataflow with union. Since we are just
// propagating reachability, there isn't any kill.
bool anyNeedUpdate = true;
SmallBitVector temp(numBits);
blockData[&*blockData.getFunction()->begin()].needsUpdate = true;
while (anyNeedUpdate) {
anyNeedUpdate = false;
for (auto *block : pofi->getReversePostOrder()) {
auto &state = blockData[block];
if (!state.needsUpdate) {
continue;
}
state.needsUpdate = false;
temp.reset();
for (auto *predBlock : block->getPredecessorBlocks()) {
auto &predState = blockData[predBlock];
temp |= predState.exit;
}
state.entry = temp;
temp |= state.gen;
if (temp != state.exit) {
state.exit = temp;
for (auto *succBlock : block->getSuccessorBlocks()) {
anyNeedUpdate = true;
blockData[succBlock].needsUpdate = true;
}
}
}
}
REGIONBASEDISOLATION_LOG(llvm::dbgs() << "Propagating Captures Result!\n";
print(llvm::dbgs()));
}
void PartialApplyReachabilityDataflow::print(llvm::raw_ostream &os) const {
// This is only invoked for debugging purposes, so make nicer output.
std::vector<std::pair<unsigned, SILValue>> data;
for (auto [value, bitNo] : valueToBit) {
data.emplace_back(bitNo, value);
}
std::sort(data.begin(), data.end());
os << "(BitNo, Value):\n";
for (auto [bitNo, value] : data) {
os << " " << bitNo << ": " << value;
}
os << "(Block,GenBits):\n";
for (auto [block, state] : blockData) {
os << " bb" << block.getDebugID() << ".\n"
<< " Entry: " << state.entry << '\n'
<< " Gen: " << state.gen << '\n'
<< " Exit: " << state.exit << '\n';
}
}
//===----------------------------------------------------------------------===//
// MARK: Expr/Type Inference for Diagnostics
//===----------------------------------------------------------------------===//
namespace {
struct InferredCallerArgumentTypeInfo {
Type baseInferredType;
SmallVector<std::pair<Type, std::optional<ApplyIsolationCrossing>>, 4>
applyUses;
void init(const Operand *op);
/// Init for an apply that does not have an associated apply expr.
///
/// This should only occur when writing SIL test cases today. In the future,
/// we may represent all of the actor isolation information at the SIL level,
/// but we are not there yet today.
void initForApply(ApplyIsolationCrossing isolationCrossing);
void initForApply(const Operand *op, ApplyExpr *expr);
void initForAutoclosure(const Operand *op, AutoClosureExpr *expr);
Expr *getFoundExprForSelf(ApplyExpr *sourceApply) {
if (auto callExpr = dyn_cast<CallExpr>(sourceApply))
if (auto calledExpr =
dyn_cast<DotSyntaxCallExpr>(callExpr->getDirectCallee()))
return calledExpr->getBase();
return nullptr;
}
Expr *getFoundExprForParam(ApplyExpr *sourceApply, unsigned argNum) {
auto *expr = sourceApply->getArgs()->getExpr(argNum);
// If we have an erasure expression, lets use the original type. We do
// this since we are not saying the specific parameter that is the
// issue and we are using the type to explain it to the user.
if (auto *erasureExpr = dyn_cast<ErasureExpr>(expr))
expr = erasureExpr->getSubExpr();
return expr;
}
};
} // namespace
void InferredCallerArgumentTypeInfo::initForApply(
ApplyIsolationCrossing isolationCrossing) {
applyUses.emplace_back(baseInferredType, isolationCrossing);
}
void InferredCallerArgumentTypeInfo::initForApply(const Operand *op,
ApplyExpr *sourceApply) {
auto isolationCrossing = sourceApply->getIsolationCrossing();
assert(isolationCrossing && "Should have valid isolation crossing?!");
// Grab out full apply site and see if we can find a better expr.
SILInstruction *i = const_cast<SILInstruction *>(op->getUser());
auto fai = FullApplySite::isa(i);
Expr *foundExpr = nullptr;
// If we have self, then infer it.
if (fai.hasSelfArgument() && op == &fai.getSelfArgumentOperand()) {
foundExpr = getFoundExprForSelf(sourceApply);
} else {
// Otherwise, try to infer using the operand of the ApplyExpr.
unsigned argNum = [&]() -> unsigned {
if (fai.isCalleeOperand(*op))
return op->getOperandNumber();
return fai.getAppliedArgIndexWithoutIndirectResults(*op);
}();
// If something funny happened and we get an arg num that is larger than our
// num args... just return nullptr so we emit an error using our initial
// foundExpr.
//
// TODO: We should emit a "I don't understand error" so this gets reported
// to us.
if (argNum < sourceApply->getArgs()->size()) {
foundExpr = getFoundExprForParam(sourceApply, argNum);
}
}
auto inferredArgType =
foundExpr ? foundExpr->findOriginalType() : baseInferredType;
applyUses.emplace_back(inferredArgType, isolationCrossing);
}
namespace {
struct Walker : ASTWalker {
InferredCallerArgumentTypeInfo &foundTypeInfo;
ValueDecl *targetDecl;
SmallPtrSet<Expr *, 8> visitedCallExprDeclRefExprs;
Walker(InferredCallerArgumentTypeInfo &foundTypeInfo, ValueDecl *targetDecl)
: foundTypeInfo(foundTypeInfo), targetDecl(targetDecl) {}
Expr *lookThroughExpr(Expr *expr) {
while (true) {
if (auto *memberRefExpr = dyn_cast<MemberRefExpr>(expr)) {
expr = memberRefExpr->getBase();
continue;
}
if (auto *cvt = dyn_cast<ImplicitConversionExpr>(expr)) {
expr = cvt->getSubExpr();
continue;
}
if (auto *e = dyn_cast<ForceValueExpr>(expr)) {
expr = e->getSubExpr();
continue;
}
if (auto *t = dyn_cast<TupleElementExpr>(expr)) {
expr = t->getBase();
continue;
}
return expr;
}
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (auto *declRef = dyn_cast<DeclRefExpr>(expr)) {
// If this decl ref expr was not visited as part of a callExpr, add it as
// something without isolation crossing.
if (!visitedCallExprDeclRefExprs.count(declRef)) {
if (declRef->getDecl() == targetDecl) {
visitedCallExprDeclRefExprs.insert(declRef);
foundTypeInfo.applyUses.emplace_back(declRef->findOriginalType(),
std::nullopt);
return Action::Continue(expr);
}
}
}
if (auto *callExpr = dyn_cast<CallExpr>(expr)) {
if (auto isolationCrossing = callExpr->getIsolationCrossing()) {
// Search callExpr's arguments to see if we have our targetDecl.
auto *argList = callExpr->getArgs();
for (auto pair : llvm::enumerate(argList->getArgExprs())) {
auto *arg = lookThroughExpr(pair.value());
if (auto *declRef = dyn_cast<DeclRefExpr>(arg)) {
if (declRef->getDecl() == targetDecl) {
// Found our target!
visitedCallExprDeclRefExprs.insert(declRef);
foundTypeInfo.applyUses.emplace_back(declRef->findOriginalType(),
isolationCrossing);
return Action::Continue(expr);
}
}
}
}
}
return Action::Continue(expr);
}
};
} // namespace
void InferredCallerArgumentTypeInfo::init(const Operand *op) {
baseInferredType = op->get()->getType().getASTType();
auto *nonConstOp = const_cast<Operand *>(op);
auto loc = op->getUser()->getLoc();
if (auto *sourceApply = loc.getAsASTNode<ApplyExpr>()) {
return initForApply(op, sourceApply);
}
if (auto fas = FullApplySite::isa(nonConstOp->getUser())) {
if (auto isolationCrossing = fas.getIsolationCrossing()) {
return initForApply(*isolationCrossing);
}
}
auto *autoClosureExpr = loc.getAsASTNode<AutoClosureExpr>();
if (!autoClosureExpr) {
llvm::report_fatal_error("Unknown node");
}
auto *i = const_cast<SILInstruction *>(op->getUser());
auto pai = ApplySite::isa(i);
unsigned captureIndex = pai.getAppliedArgIndex(*op);
auto captureInfo =
autoClosureExpr->getCaptureInfo().getCaptures()[captureIndex];
auto *captureDecl = captureInfo.getDecl();
Walker walker(*this, captureDecl);
autoClosureExpr->walk(walker);
}
//===----------------------------------------------------------------------===//
// MARK: Instruction Level Model
//===----------------------------------------------------------------------===//
namespace {
constexpr StringLiteral SEP_STR = "╾──────────────────────────────╼\n";
constexpr StringLiteral PER_FUNCTION_SEP_STR =
"╾++++++++++++++++++++++++++++++╼\n";
} // namespace
//===----------------------------------------------------------------------===//
// MARK: PartitionOpBuilder
//===----------------------------------------------------------------------===//
namespace {
struct PartitionOpBuilder {
/// Parent translator that contains state.
PartitionOpTranslator *translator;
/// Used to statefully track the instruction currently being translated, for
/// insertion into generated PartitionOps.
SILInstruction *currentInst = nullptr;
/// List of partition ops mapped to the current instruction. Used when
/// generating partition ops.
SmallVector<PartitionOp, 8> currentInstPartitionOps;
void reset(SILInstruction *inst) {
currentInst = inst;
currentInstPartitionOps.clear();
}
Element lookupValueID(SILValue value);
bool valueHasID(SILValue value, bool dumpIfHasNoID = false);
Element getActorIntroducingRepresentative(SILIsolationInfo actorIsolation);
void addAssignFresh(SILValue value) {
std::array<Element, 1> values = {lookupValueID(value)};
currentInstPartitionOps.emplace_back(
PartitionOp::AssignFresh(values, currentInst));
}
void addAssignFresh(ArrayRef<SILValue> values) {
auto transformedCollection = makeTransformRange(
values, [&](SILValue value) { return lookupValueID(value); });
currentInstPartitionOps.emplace_back(
PartitionOp::AssignFresh(transformedCollection, currentInst));
}
void addAssign(SILValue destValue, Operand *srcOperand) {
assert(valueHasID(srcOperand->get(), /*dumpIfHasNoID=*/true) &&
"source value of assignment should already have been encountered");
Element srcID = lookupValueID(srcOperand->get());
if (lookupValueID(destValue) == srcID) {
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< " Skipping assign since tgt and src have "
"the same representative.\n");
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< " Rep ID: %%" << srcID.num << ".\n");
return;
}
currentInstPartitionOps.emplace_back(
PartitionOp::Assign(lookupValueID(destValue),
lookupValueID(srcOperand->get()), srcOperand));
}
void addSend(SILValue representative, Operand *op) {
assert(valueHasID(representative) &&
"sent value should already have been encountered");
currentInstPartitionOps.emplace_back(
PartitionOp::Send(lookupValueID(representative), op));
}
void addUndoSend(SILValue representative, SILInstruction *unsendingInst) {
assert(valueHasID(representative) &&
"value should already have been encountered");
currentInstPartitionOps.emplace_back(
PartitionOp::UndoSend(lookupValueID(representative), unsendingInst));
}
void addMerge(SILValue destValue, Operand *srcOperand) {
assert(valueHasID(destValue, /*dumpIfHasNoID=*/true) &&
valueHasID(srcOperand->get(), /*dumpIfHasNoID=*/true) &&
"merged values should already have been encountered");
if (lookupValueID(destValue) == lookupValueID(srcOperand->get()))
return;
currentInstPartitionOps.emplace_back(
PartitionOp::Merge(lookupValueID(destValue),
lookupValueID(srcOperand->get()), srcOperand));
}
/// Mark \p value artifically as being part of an actor isolated region by
/// introducing a new fake actor introducing representative and merging them.
void addActorIntroducingInst(SILValue sourceValue, Operand *sourceOperand,
SILIsolationInfo actorIsolation) {
assert(valueHasID(sourceValue, /*dumpIfHasNoID=*/true) &&
"merged values should already have been encountered");
auto elt = getActorIntroducingRepresentative(actorIsolation);
currentInstPartitionOps.emplace_back(
PartitionOp::AssignFresh(elt, currentInst));
currentInstPartitionOps.emplace_back(
PartitionOp::Merge(lookupValueID(sourceValue), elt, sourceOperand));
}
void addRequire(SILValue value) {
assert(valueHasID(value, /*dumpIfHasNoID=*/true) &&
"required value should already have been encountered");
currentInstPartitionOps.emplace_back(
PartitionOp::Require(lookupValueID(value), currentInst));
}
void addInOutSendingAtFunctionExit(SILValue value) {
assert(valueHasID(value, /*dumpIfHasNoID=*/true) &&
"required value should already have been encountered");
currentInstPartitionOps.emplace_back(
PartitionOp::InOutSendingAtFunctionExit(lookupValueID(value),
currentInst));
}
void addUnknownPatternError(SILValue value) {
if (shouldAbortOnUnknownPatternMatchError()) {
llvm::report_fatal_error(
"RegionIsolation: Aborting on unknown pattern match error");
}
currentInstPartitionOps.emplace_back(
PartitionOp::UnknownPatternError(lookupValueID(value), currentInst));
}
SWIFT_DEBUG_DUMP { print(llvm::dbgs()); }
void print(llvm::raw_ostream &os) const;
};
} // namespace
//===----------------------------------------------------------------------===//
// MARK: Top Level Translator Struct
//===----------------------------------------------------------------------===//
namespace {
enum class TranslationSemantics {
/// An instruction that does not affect region based state or if it does we
/// would like to error on some other use. An example would be something
/// like end_borrow, inject_enum_addr, or alloc_global. We do not produce
/// any partition op.
Ignored,
/// An instruction whose result produces a completely new region. E.x.:
/// alloc_box, alloc_pack, key_path. This results in the translator
/// producing a partition op that introduces the new region.
AssignFresh,
/// An instruction that merges together all of its operands regions and
/// assigns all of its results to be that new merged region. If the
/// instruction does not have any non-Sendable operands, we produce a new
/// singular region that all of the results are assigned to.
///
/// From a partition op perspective, we emit require partition ops for each
/// of the operands of the instruction, then merge the operand partition
/// ops. If we do not have any non-Sendable operands, we then create an
/// assign fresh op for the first result. If we do, we assign the first
/// result to that merged region. Regardless of the case, we then assign all
/// of the rest of the results to the region of the first operand.
Assign,
/// An instruction that getUnderlyingTrackedValue looks through and thus we
/// look through from a region translation perspective. The result of this
/// is we do not produce a new partition op and just assert that
/// getUnderlyingTrackedValue can look through the instruction.
LookThrough,
/// Require that the region associated with a value not be consumed at this
/// program point.
Require,
/// A "CopyLikeInstruction" with a Dest and Src operand value. If the store
/// is considered to be to unaliased store (computed through a combination
/// of AccessStorage's isUniquelyIdentified check and a custom search for
/// captures by partial apply), then we treat this like an assignment of src
/// to dest and emit assign partition ops. Otherwise, we emit merge
/// partition ops so that we merge the old region of dest into the new src
/// region. This ensures in the case of our value being captured by a
/// closure, we do not lose that the closure could affect the memory
/// location.
Store,
/// An instruction that is not handled in a standardized way. Examples:
///
/// 1. Select insts.
/// 2. Instructions without a constant way of being handled that change
/// their behavior depending on some state on the instruction itself.
Special,
/// An instruction that is a full apply site. Can cause sending or
/// unsending of regions.
Apply,
/// A terminator instruction that acts like a phi in terms of its region.
TerminatorPhi,
/// An instruction that we should never see and if we do see, we should assert
/// upon. This is generally used for non-Ownership SSA instructions and
/// instructions that can only appear in Lowered SIL. Even if we should never
/// see one of these instructions, we would still like to ensure that we
/// handle every instruction to ensure we cover the IR.
Asserting,
/// An instruction that the checker thinks it can ignore as long as all of its
/// operands are Sendable. If we see that such an instruction has a
/// non-Sendable parameter, then someone added an instruction to the compiler
/// without updating this code correctly. This is most likely driver error and
/// should be caught in testing when we assert.
AssertingIfNonSendable,
/// Instructions that always unconditionally send all of their non-Sendable
/// parameters and that do not have any results.
SendingNoResult,
};
} // namespace
namespace llvm {
llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
TranslationSemantics semantics) {
switch (semantics) {
case TranslationSemantics::Ignored:
os << "ignored";
return os;
case TranslationSemantics::AssignFresh:
os << "assign_fresh";
return os;
case TranslationSemantics::Assign:
os << "assign";
return os;
case TranslationSemantics::LookThrough:
os << "look_through";
return os;
case TranslationSemantics::Require:
os << "require";
return os;
case TranslationSemantics::Store:
os << "store";
return os;
case TranslationSemantics::Special:
os << "special";
return os;
case TranslationSemantics::Apply:
os << "apply";
return os;
case TranslationSemantics::TerminatorPhi:
os << "terminator_phi";
return os;
case TranslationSemantics::Asserting:
os << "asserting";
return os;
case TranslationSemantics::AssertingIfNonSendable:
os << "asserting_if_nonsendable";
return os;
case TranslationSemantics::SendingNoResult:
os << "sending_no_result";
return os;
}
llvm_unreachable("Covered switch isn't covered?!");
}
} // namespace llvm
namespace swift {
namespace regionanalysisimpl {
/// PartitionOpTranslator is responsible for performing the translation from
/// SILInstructions to PartitionOps. Not all SILInstructions have an effect on
/// the region partition, and some have multiple effects - such as an
/// application pairwise merging its arguments - so the core functions like
/// translateSILBasicBlock map SILInstructions to std::vectors of PartitionOps.
/// No more than a single instance of PartitionOpTranslator should be used for
/// each SILFunction, as SILValues are assigned unique IDs through the
/// nodeIDMap. Some special correspondences between SIL values are also tracked
/// statefully by instances of this class, such as the "projection"
/// relationship: instructions like begin_borrow and begin_access create
/// effectively temporary values used for alternative access to base "projected"
/// values. These are tracked to implement "write-through" semantics for
/// assignments to projections when they're addresses.
///
/// TODO: when translating basic blocks, optimizations might be possible
/// that reduce lists of PartitionOps to smaller, equivalent lists
class PartitionOpTranslator {
friend PartitionOpBuilder;
SILFunction *function;
/// A cache of argument IDs.
std::optional<Partition> functionArgPartition;
/// A builder struct that we use to convert individual instructions into lists
/// of PartitionOps.
PartitionOpBuilder builder;
PartialApplyReachabilityDataflow partialApplyReachabilityDataflow;
RegionAnalysisValueMap &valueMap;
void gatherFlowInsensitiveInformationBeforeDataflow() {
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< SEP_STR
<< "Performing pre-dataflow scan to gather "
"flow insensitive information "
<< function->getName() << ":\n"
<< SEP_STR);
for (auto &block : *function) {
for (auto &inst : block) {
if (auto *pai = dyn_cast<PartialApplyInst>(&inst)) {
ApplySite applySite(pai);
for (Operand &op : applySite.getArgumentOperands()) {
// See if this operand is inout_aliasable or is passed as a box. In
// such a case, we are passing by reference so we need to add it to
// the reachability.
if (applySite.getArgumentConvention(op) ==
SILArgumentConvention::Indirect_InoutAliasable ||
op.get()->getType().is<SILBoxType>())
partialApplyReachabilityDataflow.add(&op);
// See if this instruction is a partial apply whose non-sendable
// address operands we need to mark as captured_uniquely identified.
//
// If we find an address or a box of a non-Sendable type that is
// passed to a partial_apply, mark the value's representative as
// being uniquely identified and captured.
SILValue val = op.get();
if (val->getType().isAddress() &&
isNonSendableType(val->getType())) {
auto trackVal = getTrackableValue(val, true);
(void)trackVal;
REGIONBASEDISOLATION_LOG(trackVal.print(llvm::dbgs()));
continue;
}
if (auto *pbi = dyn_cast<ProjectBoxInst>(val)) {
if (isNonSendableType(pbi->getType())) {
auto trackVal = getTrackableValue(val, true);
(void)trackVal;
continue;
}
}
}
}
}
}
// Once we have finished processing all blocks, propagate reachability.
partialApplyReachabilityDataflow.propagateReachability();
}
public:
PartitionOpTranslator(SILFunction *function, PostOrderFunctionInfo *pofi,
RegionAnalysisValueMap &valueMap,
IsolationHistory::Factory &historyFactory)
: function(function), functionArgPartition(), builder(),
partialApplyReachabilityDataflow(function, valueMap, pofi),
valueMap(valueMap) {
builder.translator = this;
REGIONBASEDISOLATION_LOG(
llvm::dbgs()
<< PER_FUNCTION_SEP_STR
<< "Beginning processing: " << function->getName() << '\n'
<< "Demangled: "
<< Demangle::demangleSymbolAsString(
function->getName(),
Demangle::DemangleOptions::SimplifiedUIDemangleOptions())
<< '\n'
<< PER_FUNCTION_SEP_STR << "Dump:\n";
function->print(llvm::dbgs()));
gatherFlowInsensitiveInformationBeforeDataflow();
REGIONBASEDISOLATION_LOG(llvm::dbgs() << "Initializing Function Args:\n");
auto functionArguments = function->getArguments();
if (functionArguments.empty()) {
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " None.\n");
functionArgPartition = Partition::singleRegion(SILLocation::invalid(), {},
historyFactory.get());
return;
}
llvm::SmallVector<Element, 8> nonSendableJoinedIndices;
llvm::SmallVector<Element, 8> nonSendableSeparateIndices;
for (SILArgument *arg : functionArguments) {
// This will decide what the isolation region is.
if (auto state = tryToTrackValue(arg)) {
// If we can send our parameter, just add it to
// nonSendableSeparateIndices.
//
// NOTE: We do not support today the ability to have multiple parameters
// send together as part of the same region.
if (canFunctionArgumentBeSent(cast<SILFunctionArgument>(arg))) {
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " %%" << state->getID()
<< " (sending): " << *arg);
nonSendableSeparateIndices.push_back(state->getID());
continue;
}
// Otherwise, it is one of our merged parameters. Add it to the never
// send list and to the region join list.
REGIONBASEDISOLATION_LOG(
llvm::dbgs() << " %%" << state->getID() << ": ";
state->print(llvm::dbgs()); llvm::dbgs() << *arg);
nonSendableJoinedIndices.push_back(state->getID());
} else {
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " Sendable: " << *arg);
}
}
functionArgPartition = Partition::singleRegion(
SILLocation::invalid(), nonSendableJoinedIndices, historyFactory.get());
for (Element elt : nonSendableSeparateIndices) {
functionArgPartition->trackNewElement(elt);
}
}
bool isClosureCaptured(SILValue value, SILInstruction *inst) const {
return partialApplyReachabilityDataflow.isReachable(value, inst);
}
std::optional<TrackableValue> getValueForId(Element id) const {
return valueMap.getValueForId(id);
}
RegionAnalysisValueMap &getValueMap() const { return valueMap; }
private:
/// Check if the passed in type is NonSendable.
///
/// NOTE: We special case RawPointer and NativeObject to ensure they are
/// treated as non-Sendable and strict checking is applied to it.
bool isNonSendableType(SILType type) const {
return SILIsolationInfo::isNonSendableType(type, function);
}
TrackableValue
getTrackableValue(SILValue value,
bool isAddressCapturedByPartialApply = false) {
return valueMap.getTrackableValue(value, isAddressCapturedByPartialApply);
}
std::optional<TrackableValue> tryToTrackValue(SILValue value) const {
return valueMap.tryToTrackValue(value);
}
/// If \p value already has state associated with it, return that. Otherwise
/// begin tracking \p value and initialize its isolation info to be \p.
///
/// This is in contrast to tryToTrackValue which infers isolation
/// information. This should only be used in exceptional cases when one 100%
/// knows what the isolation is already. E.x.: a partial_apply.
std::optional<std::pair<TrackableValue, bool>>
initializeTrackedValue(SILValue value, SILIsolationInfo info) const {
auto trackedValuePair = valueMap.initializeTrackableValue(value, info);
// If we have a Sendable value return none.
if (!trackedValuePair.first.isNonSendable())
return {};
return trackedValuePair;
}
TrackableValue
getActorIntroducingRepresentative(SILInstruction *introducingInst,
SILIsolationInfo actorIsolation) const {
return valueMap.getActorIntroducingRepresentative(introducingInst,
actorIsolation);
}
bool valueHasID(SILValue value, bool dumpIfHasNoID = false) {
return valueMap.valueHasID(value, dumpIfHasNoID);
}
Element lookupValueID(SILValue value) {
return valueMap.lookupValueID(value);
}
public:
/// Return the partition consisting of all function arguments.
///
/// Used to initialize the entry blocko of our analysis.
const Partition &getEntryPartition() const { return *functionArgPartition; }
/// Get the results of an apply instruction.
///
/// This is the single result value for most apply instructions, but for try
/// apply it is the two arguments to each succ block.
void getApplyResults(const SILInstruction *inst,
SmallVectorImpl<SILValue> &foundResults) {
if (isa<ApplyInst, BeginApplyInst, BuiltinInst, PartialApplyInst>(inst)) {
copy(inst->getResults(), std::back_inserter(foundResults));
return;
}
if (auto tryApplyInst = dyn_cast<TryApplyInst>(inst)) {
foundResults.emplace_back(tryApplyInst->getNormalBB()->getArgument(0));
if (tryApplyInst->getErrorBB()->getNumArguments() > 0) {
foundResults.emplace_back(tryApplyInst->getErrorBB()->getArgument(0));
}
return;
}
llvm::report_fatal_error("all apply instructions should be covered");
}
/// Require all non-sendable sources, merge their regions, and assign the
/// resulting region to all non-sendable targets, or assign non-sendable
/// targets to a fresh region if there are no non-sendable sources.
///
/// \arg isolationInfo An isolation info that can be specified as the true
/// base isolation of results. Otherwise, results are assumed to have a
/// element isolation of disconnected. NOTE: The results will still be in the
/// region of the non-Sendable arguments so at the region level they will have
/// the same value.
template <typename TargetRange, typename SourceRange>
void
translateSILMultiAssign(const TargetRange &resultValues,
const SourceRange &sourceValues,
SILIsolationInfo resultIsolationInfoOverride = {},
bool requireSrcValues = true) {
SmallVector<std::pair<Operand *, SILValue>, 8> assignOperands;
SmallVector<SILValue, 8> assignResults;
// A helper we use to emit an unknown patten error if our merge is
// invalid. This ensures we guarantee that if we find an actor merge error,
// the compiler halts. Importantly this lets our users know 100% that if the
// compiler exits successfully, actor merge errors could not have happened.
std::optional<SILDynamicMergedIsolationInfo> mergedInfo;
if (resultIsolationInfoOverride) {
mergedInfo = SILDynamicMergedIsolationInfo(resultIsolationInfoOverride);
} else {
mergedInfo = SILDynamicMergedIsolationInfo::getDisconnected(false);
}
for (Operand *srcOperand : sourceValues) {
auto src = srcOperand->get();
if (auto value = tryToTrackValue(src)) {
assignOperands.push_back(
{srcOperand, value->getRepresentative().getValue()});
auto originalMergedInfo = mergedInfo;
(void)originalMergedInfo;
if (mergedInfo)
mergedInfo = mergedInfo->merge(value->getIsolationRegionInfo());
// If we fail to merge, then we have an incompatibility in between some
// of our arguments (consider isolated to different actors) or with the
// isolationInfo we specified. Emit an unknown patten error.
if (!mergedInfo) {
REGIONBASEDISOLATION_LOG(
llvm::dbgs() << "Merge Failure!\n"
<< "Original Info: ";
if (originalMergedInfo)
originalMergedInfo->printForDiagnostics(llvm::dbgs());
else llvm::dbgs() << "nil";
llvm::dbgs() << "\nValue Rep: "
<< value->getRepresentative().getValue();
llvm::dbgs() << "Original Src: " << src;
llvm::dbgs() << "Value Info: ";
value->getIsolationRegionInfo().printForDiagnostics(llvm::dbgs());
llvm::dbgs() << "\n");
builder.addUnknownPatternError(src);
continue;
}
}
}
for (SILValue result : resultValues) {
// If we had isolation info explicitly passed in... use our
// resultIsolationInfoError. Otherwise, we want to infer.
if (resultIsolationInfoOverride) {
// We only get back result if it is non-Sendable.
if (auto nonSendableValue =
initializeTrackedValue(result, resultIsolationInfoOverride)) {
// If we did not insert, emit an unknown patten error.
if (!nonSendableValue->second) {
builder.addUnknownPatternError(result);
}
assignResults.push_back(
nonSendableValue->first.getRepresentative().getValue());
}
} else {
if (auto value = tryToTrackValue(result)) {
assignResults.push_back(value->getRepresentative().getValue());
}
}
}
// Require all srcs if we are supposed to. (By default we do).
//
// DISCUSSION: The reason that this may be useful is for special
// instructions like store_borrow. On the one hand, we want store_borrow to
// act like a store in the sense that we want to combine the regions of its
// src and dest... but at the same time, we do not want to treat the store
// itself as a use of its parent value. We want that to be any subsequent
// uses of the store_borrow.
if (requireSrcValues)
for (auto src : assignOperands)
builder.addRequire(src.second);
// Merge all srcs.
for (unsigned i = 1; i < assignOperands.size(); i++) {
builder.addMerge(assignOperands[i - 1].second, assignOperands[i].first);
}
// If we do not have any non sendable results, return early.
if (assignResults.empty()) {
// If we did not have any non-Sendable results and we did have
// non-Sendable operands and we are supposed to mark value as actor
// derived, introduce a fake element so we just propagate the actor
// region.
//
// NOTE: Here we check if we have resultIsolationInfoOverride rather than
// isolationInfo since we want to do this regardless of whether or not we
// passed in a specific isolation info unlike earlier when processing
// actual results.
if (assignOperands.size() && resultIsolationInfoOverride) {
builder.addActorIntroducingInst(assignOperands.back().second,
assignOperands.back().first,
resultIsolationInfoOverride);
}
return;
}
// If we do not have any non-Sendable srcs, then all of our results get one
// large fresh region.
if (assignOperands.empty()) {
builder.addAssignFresh(assignResults);
return;
}
// Otherwise, we need to assign all of the results to be in the same region
// as the operands. Without losing generality, we just use the first
// non-Sendable one.
for (auto result : assignResults) {
builder.addAssign(result, assignOperands.front().first);
}
}
/// Send the parameters of our partial_apply.
///
/// Handling async let has three-four parts:
///
/// %partial_apply = partial_apply()
/// %reabstraction = maybe reabstraction thunk of partial_apply
/// builtin "async let start"(%reabstraction | %partial_apply)
/// call %asyncLetGet()
///
/// We send the captured parameters of %partial_apply at the async let
/// start and then unsend them at async let get.
void translateAsyncLetStart(BuiltinInst *bi) {
// Just track the result of the builtin inst as an assign fresh. We do this
// so we properly track the partial_apply get. We already sent the
// parameters.
builder.addAssignFresh(bi);
}
/// For discussion on how we handle async let, please see the comment on
/// translateAsyncLetStart.
void translateAsyncLetGet(ApplyInst *ai) {
// This looks through reabstraction thunks.
auto source = findAsyncLetPartialApplyFromGet(ai);
assert(source.has_value());
// If we didn't find a partial_apply, then we must have had a
// thin_to_thick_function meaning we did not capture anything.
if (source->is<ThinToThickFunctionInst *>())
return;
// If our partial_apply was Sendable, then Sema should have checked that
// none of our captures were non-Sendable and we should have emitted an
// error earlier.
assert(bool(source.value()) &&
"AsyncLet Get should always have a derivable partial_apply");
auto *pai = source->get<PartialApplyInst *>();
if (pai->getFunctionType()->isSendable())
return;
ApplySite applySite(pai);
// For each of our partial apply operands...
for (auto pair : llvm::enumerate(applySite.getArgumentOperands())) {
Operand &op = pair.value();
// If we are tracking the value...
if (auto trackedArgValue = tryToTrackValue(op.get())) {
// Gather the isolation info from the AST for this operand...
InferredCallerArgumentTypeInfo typeInfo;
typeInfo.init(&op);
// Then see if /any/ of our uses are passed to over a isolation boundary
// that is actor isolated... if we find one continue so we do not undo
// the send for that element.
if (llvm::any_of(
typeInfo.applyUses,
[](const std::pair<Type, std::optional<ApplyIsolationCrossing>>
&data) {
// If we do not have an apply isolation crossing, we just use
// undefined crossing since that is considered nonisolated.
ApplyIsolationCrossing crossing;
return data.second.value_or(crossing)
.CalleeIsolation.isActorIsolated();
}))
continue;
builder.addUndoSend(trackedArgValue->getRepresentative().getValue(),
ai);
}
}
}
void translateSILPartialApplyAsyncLetBegin(PartialApplyInst *pai) {
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< "Translating Async Let Begin Partial Apply!\n");
// Grab our partial apply and send all of its non-sendable
// parameters. We do not merge the parameters since each individual capture
// of the async let at the program level is viewed as still being in
// separate regions. Otherwise, we would need to error on the following
// code:
//
// let x = NonSendable(), x2 = NonSendable()
// async let y = sendToActor(x) + sendToNonIsolated(x2)
// _ = await y
// useValue(x2)
for (auto &op : ApplySite(pai).getArgumentOperands()) {
if (auto trackedArgValue = tryToTrackValue(op.get())) {
builder.addRequire(trackedArgValue->getRepresentative().getValue());
builder.addSend(trackedArgValue->getRepresentative().getValue(), &op);
}
}
// Then mark our partial_apply result as being returned fresh.
builder.addAssignFresh(pai);
}
/// Handles the semantics for SIL applies that cross isolation.
///
/// Semantically this causes all arguments of the applysite to be sent.
void translateIsolatedPartialApply(PartialApplyInst *pai,
SILIsolationInfo actorIsolation) {
ApplySite applySite(pai);
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< "Translating Isolated Partial Apply!\n");
// For each argument operand.
for (auto &op : applySite.getArgumentOperands()) {
// See if we tracked it.
if (auto value = tryToTrackValue(op.get())) {
// If we are tracking it, sent it and if it is actor derived, mark
// our partial apply as actor derived.
builder.addRequire(value->getRepresentative().getValue());
builder.addSend(value->getRepresentative().getValue(), &op);
}
}
// Now that we have sent everything into the partial_apply, perform
// an assign fresh for the partial_apply if it is non-Sendable. If we use
// any of the sent values later, we will error, so it is safe to just
// create a new value.
if (pai->getFunctionType()->isSendable())
return;
auto trackedValue = initializeTrackedValue(pai, actorIsolation);
assert(trackedValue && "Should not have happened already");
assert(
trackedValue->second &&
"Insert should have happened since this could not happen before this");
translateSILAssignFresh(trackedValue->first.getRepresentative().getValue());
}
void translateSILPartialApply(PartialApplyInst *pai) {
// First check if our partial apply is Sendable and not global actor
// isolated. In such a case, we will have emitted an earlier warning in Sema
// and can return early. If we have a global actor isolated partial_apply,
// we can be looser and can use region isolation since we know that the
// Sendable closure will be executed serially due to the closure having to
// run on the global actor queue meaning that we do not have to worry about
// the Sendable closure being run concurrency.
if (pai->getFunctionType()->isSendableType()) {
auto isolationInfo = SILIsolationInfo::get(pai);
if (!isolationInfo || !isolationInfo.hasActorIsolation() ||
!isolationInfo.getActorIsolation().isGlobalActor())
return;
}
// Then check if our partial_apply is fed into an async let begin. If so,
// handle it especially.
//
// NOTE: If it is an async_let, then the closure itself will be Sendable. We
// treat passing in a value into the async Sendable closure as sending
// it into the closure.
if (isAsyncLetBeginPartialApply(pai)) {
return translateSILPartialApplyAsyncLetBegin(pai);
}
// See if we have a reabstraction thunk. In such a case, just do an assign.
if (auto *calleeFn = pai->getCalleeFunction()) {
if (calleeFn->isThunk() == IsReabstractionThunk) {
return translateSILAssign(pai);
}
}
if (auto isolationRegionInfo = SILIsolationInfo::get(pai)) {
return translateIsolatedPartialApply(pai, isolationRegionInfo);
}
SmallVector<SILValue, 8> applyResults;
getApplyResults(pai, applyResults);
translateSILMultiAssign(applyResults,
makeOperandRefRange(pai->getAllOperands()));
}
void translateCreateAsyncTask(BuiltinInst *bi) {
if (auto value = tryToTrackValue(bi->getOperand(1))) {
builder.addRequire(value->getRepresentative().getValue());
builder.addSend(value->getRepresentative().getValue(),
&bi->getAllOperands()[1]);
}
}
void translateSILBuiltin(BuiltinInst *bi) {
if (auto kind = bi->getBuiltinKind()) {
if (kind == BuiltinValueKind::StartAsyncLetWithLocalBuffer) {
return translateAsyncLetStart(bi);
}
if (kind == BuiltinValueKind::CreateAsyncTask) {
return translateCreateAsyncTask(bi);
}
}
// If we do not have a special builtin, just do a multi-assign. Builtins do
// not cross async boundaries.
return translateSILMultiAssign(bi->getResults(),
makeOperandRefRange(bi->getAllOperands()));
}
void translateNonIsolationCrossingSILApply(FullApplySite fas) {
// For non-self parameters, gather all of the sending parameters and
// gather our non-sending parameters.
SmallVector<Operand *, 8> nonSendingParameters;
SmallVector<Operand *, 8> sendingIndirectResults;
if (fas.getNumArguments()) {
// NOTE: We want to process indirect parameters as if they are
// parameters... so we process them in nonSendingParameters.
for (auto &op : fas.getOperandsWithoutSelf()) {
// If op is the callee operand, skip it.
if (fas.isCalleeOperand(op))
continue;
if (fas.isSending(op)) {
if (fas.isIndirectResultOperand(op)) {
sendingIndirectResults.push_back(&op);
continue;
}
if (auto value = tryToTrackValue(op.get())) {
builder.addRequire(value->getRepresentative().getValue());
builder.addSend(value->getRepresentative().getValue(), &op);
continue;
}
} else {
nonSendingParameters.push_back(&op);
}
}
}
// If our self parameter was sending, send it. Otherwise, just
// stick it in the non self operand values array and run multiassign on
// it.
if (fas.hasSelfArgument()) {
auto &selfOperand = fas.getSelfArgumentOperand();
if (fas.getArgumentParameterInfo(selfOperand)
.hasOption(SILParameterInfo::Sending)) {
if (auto value = tryToTrackValue(selfOperand.get())) {
builder.addRequire(value->getRepresentative().getValue());
builder.addSend(value->getRepresentative().getValue(), &selfOperand);
}
} else {
nonSendingParameters.push_back(&selfOperand);
}
}
// Require our callee operand if it is non-Sendable.
//
// DISCUSSION: Even though we do not include our callee operand in the same
// region as our operands/results, we still need to require that it is live
// at the point of application. Otherwise, we will not emit errors if the
// closure before this function application is already in the same region as
// a sent value. In such a case, the function application must error.
if (auto value = tryToTrackValue(fas.getCallee())) {
builder.addRequire(value->getRepresentative().getValue());
}
SmallVector<SILValue, 8> applyResults;
getApplyResults(*fas, applyResults);
auto type = fas.getSubstCalleeSILType().castTo<SILFunctionType>();
auto isolationInfo = SILIsolationInfo::get(*fas);
// If our result is not a 'sending' result, just do the normal multi-assign.
if (!type->hasSendingResult()) {
return translateSILMultiAssign(applyResults, nonSendingParameters,
isolationInfo);
}
// If our result is a 'sending' result, then pass in empty as our results,
// no override isolation, then perform assign fresh.
ArrayRef<SILValue> empty;
translateSILMultiAssign(empty, nonSendingParameters, {});
// Sending direct results.
for (SILValue result : applyResults) {
if (auto value = tryToTrackValue(result)) {
builder.addAssignFresh(value->getRepresentative().getValue());
}
}
// Sending indirect results.
for (Operand *op : sendingIndirectResults) {
if (auto value = tryToTrackValue(op->get())) {
builder.addAssignFresh(value->getRepresentative().getValue());
}
}
}
void translateSILApply(SILInstruction *inst) {
// Handles normal builtins and async let start.
if (auto *bi = dyn_cast<BuiltinInst>(inst)) {
return translateSILBuiltin(bi);
}
auto fas = FullApplySite::isa(inst);
assert(bool(fas) && "Builtins should be handled above");
// Handle async let get.
if (auto *f = fas.getCalleeFunction()) {
if (f->getName() == "swift_asyncLet_get") {
return translateAsyncLetGet(cast<ApplyInst>(*fas));
}
}
// If this apply does not cross isolation domains, it has normal
// non-sending multi-assignment semantics
if (!getApplyIsolationCrossing(*fas))
return translateNonIsolationCrossingSILApply(fas);
if (auto cast = dyn_cast<ApplyInst>(inst))
return translateIsolationCrossingSILApply(cast);
if (auto cast = dyn_cast<BeginApplyInst>(inst))
return translateIsolationCrossingSILApply(cast);
if (auto cast = dyn_cast<TryApplyInst>(inst)) {
return translateIsolationCrossingSILApply(cast);
}
llvm_unreachable("Only ApplyInst, BeginApplyInst, and TryApplyInst should "
"cross isolation domains");
}
/// Handles the semantics for SIL applies that cross isolation.
///
/// Semantically this causes all arguments of the applysite to be sent.
void translateIsolationCrossingSILApply(FullApplySite applySite) {
// Require all operands first before we emit a send.
for (auto op : applySite.getArguments())
if (auto value = tryToTrackValue(op))
builder.addRequire(value->getRepresentative().getValue());
auto handleSILOperands = [&](MutableArrayRef<Operand> operands) {
for (auto &op : operands) {
if (auto value = tryToTrackValue(op.get())) {
builder.addSend(value->getRepresentative().getValue(), &op);
}
}
};
auto handleSILSelf = [&](Operand *self) {
if (auto value = tryToTrackValue(self->get())) {
builder.addSend(value->getRepresentative().getValue(), self);
}
};
if (applySite.hasSelfArgument()) {
handleSILOperands(applySite.getOperandsWithoutIndirectResultsOrSelf());
handleSILSelf(&applySite.getSelfArgumentOperand());
} else {
handleSILOperands(applySite.getOperandsWithoutIndirectResults());
}
// non-sendable results can't be returned from cross-isolation calls without
// a diagnostic emitted elsewhere. Here, give them a fresh value for better
// diagnostics hereafter
SmallVector<SILValue, 8> applyResults;
getApplyResults(*applySite, applyResults);
for (auto result : applyResults)
if (auto value = tryToTrackValue(result))
builder.addAssignFresh(value->getRepresentative().getValue());
}
template <typename DestValues>
void translateSILLookThrough(DestValues destValues, SILValue src) {
auto srcID = tryToTrackValue(src);
for (SILValue dest : destValues) {
auto destID = tryToTrackValue(dest);
assert(((!destID || !srcID) || destID->getID() == srcID->getID()) &&
"srcID and dstID are different?!");
}
}
/// Add a look through operation. This asserts that dest and src map to the
/// same ID. Should only be used on instructions that are always guaranteed to
/// have this property due to getUnderlyingTrackedValue looking through them.
///
/// DISCUSSION: We use this to ensure that the connection in between
/// getUnderlyingTrackedValue and these instructions is enforced and
/// explicit. Previously, we always called translateSILAssign and relied on
/// the builder to recognize these cases and not create an assign
/// PartitionOp. Doing such a thing obscures what is actually happening.
template <>
void translateSILLookThrough<SILValue>(SILValue dest, SILValue src) {
auto srcID = tryToTrackValue(src);
auto destID = tryToTrackValue(dest);
assert(((!destID || !srcID) || destID->getID() == srcID->getID()) &&
"srcID and dstID are different?!");
}
void translateSILLookThrough(SingleValueInstruction *svi) {
assert(svi->getNumRealOperands() == 1);
auto srcID = tryToTrackValue(svi->getOperand(0));
auto destID = tryToTrackValue(svi);
assert(((!destID || !srcID) || destID->getID() == srcID->getID()) &&
"srcID and dstID are different?!");
}
template <typename Collection>
void translateSILAssign(SILValue dest, Collection collection) {
return translateSILMultiAssign(TinyPtrVector<SILValue>(dest), collection);
}
template <>
void translateSILAssign<Operand *>(SILValue dest, Operand *srcOperand) {
return translateSILAssign(dest, TinyPtrVector<Operand *>(srcOperand));
}
void translateSILAssign(SILInstruction *inst) {
return translateSILMultiAssign(inst->getResults(),
makeOperandRefRange(inst->getAllOperands()));
}
/// If the passed SILValue is NonSendable, then create a fresh region for it,
/// otherwise do nothing.
///
/// By default this is initialized with disconnected isolation info unless \p
/// isolationInfo is set.
void translateSILAssignFresh(SILValue val) {
return translateSILMultiAssign(TinyPtrVector<SILValue>(val),
TinyPtrVector<Operand *>());
}
void translateSILAssignFresh(SILValue val, SILIsolationInfo info) {
auto v = initializeTrackedValue(val, info);
if (!v)
return translateSILAssignFresh(val);
if (!v->second)
return translateUnknownPatternError(val);
return translateSILAssignFresh(v->first.getRepresentative().getValue());
}
template <typename Collection>
void translateSILMerge(SILValue dest, Collection srcCollection,
bool requireOperands = true) {
auto trackableDest = tryToTrackValue(dest);
if (!trackableDest)
return;
for (Operand *op : srcCollection) {
if (auto trackableSrc = tryToTrackValue(op->get())) {
if (requireOperands) {
builder.addRequire(trackableSrc->getRepresentative().getValue());
builder.addRequire(trackableDest->getRepresentative().getValue());
}
builder.addMerge(trackableDest->getRepresentative().getValue(), op);
}
}
}
template <>
void translateSILMerge<Operand *>(SILValue dest, Operand *src,
bool requireOperands) {
return translateSILMerge(dest, TinyPtrVector<Operand *>(src),
requireOperands);
}
void translateSILMerge(MutableArrayRef<Operand> array,
bool requireOperands = true) {
if (array.size() < 2)
return;
auto trackableDest = tryToTrackValue(array.front().get());
if (!trackableDest)
return;
for (Operand &op : array.drop_front()) {
if (auto trackableSrc = tryToTrackValue(op.get())) {
if (requireOperands) {
builder.addRequire(trackableSrc->getRepresentative().getValue());
builder.addRequire(trackableDest->getRepresentative().getValue());
}
builder.addMerge(trackableDest->getRepresentative().getValue(), &op);
}
}
}
void translateSILAssignmentToSendingParameter(TrackableValue destRoot,
Operand *destOperand,
TrackableValue srcRoot,
Operand *srcOperand) {
assert(isa<AllocStackInst>(destRoot.getRepresentative().getValue()) &&
"Destination should always be an alloc_stack");
// Send src. This ensures that we cannot use src again locally in this
// function... which makes sense since its value is now in the 'sending'
// parameter.
builder.addRequire(srcRoot.getRepresentative().getValue());
builder.addSend(srcRoot.getRepresentative().getValue(), srcOperand);
// Then check if we are assigning into an aggregate projection. In such a
// case, we want to ensure that we keep tracking the elements already in the
// region of sending. This is more conservative than we need to be
// (since we could forget anything reachable from the aggregate
// field)... but being more conservative is ok.
if (isProjectedFromAggregate(destOperand->get()))
return;
// If we are assigning over the entire value though, we perform an assign
// fresh since we are guaranteed that any value that could be referenced via
// the old value is gone.
builder.addAssignFresh(destRoot.getRepresentative().getValue());
}
/// If \p dest is known to be unaliased (computed through a combination of
/// AccessStorage's inUniquelyIdenfitied check and a custom search for
/// captures by applications), then these can be treated as assignments of \p
/// dest to src. If the \p dest could be aliased, then we must instead treat
/// them as merges, to ensure any aliases of \p dest are also updated.
void translateSILStore(Operand *dest, Operand *src) {
SILValue destValue = dest->get();
if (auto nonSendableDest = tryToTrackValue(destValue)) {
// In the following situations, we can perform an assign:
//
// 1. A store to unaliased storage.
// 2. A store that is to an entire value.
//
// DISCUSSION: If we have case 2, we need to merge the regions since we
// are not overwriting the entire region of the value. This does mean that
// we artificially include the previous region that was stored
// specifically in this projection... but that is better than
// miscompiling. For memory like this, we probably need to track it on a
// per field basis to allow for us to assign.
if (nonSendableDest.value().isNoAlias() &&
!isProjectedFromAggregate(destValue))
return translateSILAssign(destValue, src);
// Stores to possibly aliased storage must be treated as merges.
return translateSILMerge(destValue, src);
}
// Stores to storage of non-Sendable type can be ignored.
}
void translateSILTupleAddrConstructor(TupleAddrConstructorInst *inst) {
SILValue dest = inst->getDest();
if (auto nonSendableTgt = tryToTrackValue(dest)) {
// In the following situations, we can perform an assign:
//
// 1. A store to unaliased storage.
// 2. A store that is to an entire value.
//
// DISCUSSION: If we have case 2, we need to merge the regions since we
// are not overwriting the entire region of the value. This does mean that
// we artificially include the previous region that was stored
// specifically in this projection... but that is better than
// miscompiling. For memory like this, we probably need to track it on a
// per field basis to allow for us to assign.
if (nonSendableTgt.value().isNoAlias() && !isProjectedFromAggregate(dest))
return translateSILAssign(
dest, makeOperandRefRange(inst->getElementOperands()));
// Stores to possibly aliased storage must be treated as merges.
return translateSILMerge(dest,
makeOperandRefRange(inst->getElementOperands()));
}
// Stores to storage of non-Sendable type can be ignored.
}
void translateSILRequire(SILValue val) {
if (auto nonSendableVal = tryToTrackValue(val))
return builder.addRequire(nonSendableVal->getRepresentative().getValue());
}
/// An enum select is just a multi assign.
void translateSILSelectEnum(SelectEnumOperation selectEnumInst) {
SmallVector<Operand *, 8> enumOperands;
for (unsigned i = 0; i < selectEnumInst.getNumCases(); i++)
enumOperands.push_back(selectEnumInst.getCaseOperand(i).second);
if (selectEnumInst.hasDefault())
enumOperands.push_back(selectEnumInst.getDefaultResultOperand());
return translateSILMultiAssign(
TinyPtrVector<SILValue>(selectEnumInst->getResult(0)), enumOperands);
}
void translateSILSwitchEnum(SwitchEnumInst *switchEnumInst) {
TermArgSources argSources;
// accumulate each switch case that branches to a basic block with an arg
for (unsigned i = 0; i < switchEnumInst->getNumCases(); i++) {
SILBasicBlock *dest = switchEnumInst->getCase(i).second;
if (dest->getNumArguments() > 0) {
assert(dest->getNumArguments() == 1 &&
"expected at most one bb arg in dest of enum switch");
argSources.addValues({&switchEnumInst->getOperandRef()}, dest);
}
}
translateSILPhi(argSources);
}
// translate a SIL instruction corresponding to possible branches with args
// to one or more basic blocks. This is the SIL equivalent of SSA Phi nodes.
// each element of `branches` corresponds to the arguments passed to a bb,
// and a pointer to the bb being branches to itself.
// this is handled as assigning to each possible arg being branched to the
// merge of all values that could be passed to it from this basic block.
void translateSILPhi(TermArgSources &argSources) {
argSources.argSources.setFrozen();
for (auto pair : argSources.argSources.getRange()) {
translateSILMultiAssign(TinyPtrVector<SILValue>(pair.first), pair.second);
}
}
/// Instructions that send all of their non-Sendable parameters
/// unconditionally and that do not have a result.
void translateSILSendingNoResult(MutableArrayRef<Operand> values) {
for (auto &op : values) {
if (auto ns = tryToTrackValue(op.get())) {
builder.addRequire(ns->getRepresentative().getValue());
builder.addSend(ns->getRepresentative().getValue(), &op);
}
}
}
/// Emit an unknown pattern error.
void translateUnknownPatternError(SILValue value) {
builder.addUnknownPatternError(value);
}
/// Translate the instruction's in \p basicBlock to a vector of PartitionOps
/// that define the block's dataflow.
void translateSILBasicBlock(SILBasicBlock *basicBlock,
std::vector<PartitionOp> &foundPartitionOps) {
REGIONBASEDISOLATION_LOG(
llvm::dbgs() << SEP_STR << "Compiling basic block for function "
<< basicBlock->getFunction()->getName() << ": ";
basicBlock->printID(llvm::dbgs()); llvm::dbgs() << SEP_STR;
basicBlock->print(llvm::dbgs());
llvm::dbgs() << SEP_STR << "Results:\n";);
// Translate each SIL instruction to the PartitionOps that it represents if
// any.
for (auto &instruction : *basicBlock) {
REGIONBASEDISOLATION_LOG(llvm::dbgs() << "Visiting: " << instruction);
translateSILInstruction(&instruction);
copy(builder.currentInstPartitionOps,
std::back_inserter(foundPartitionOps));
}
}
#define INST(INST, PARENT) TranslationSemantics visit##INST(INST *inst);
#include "swift/SIL/SILNodes.def"
/// Adds requires for all sending inout parameters to make sure that they are
/// properly updated before the end of the function.
void addEndOfFunctionChecksForInOutSendingParameters(TermInst *inst) {
assert(inst->isFunctionExiting() && "Must be function exiting term inst?!");
for (auto *arg : inst->getFunction()->getArguments()) {
auto *fArg = cast<SILFunctionArgument>(arg);
if (fArg->getArgumentConvention().isInoutConvention() &&
fArg->getKnownParameterInfo().hasOption(SILParameterInfo::Sending)) {
if (auto ns = tryToTrackValue(arg)) {
auto rep = ns->getRepresentative().getValue();
builder.addInOutSendingAtFunctionExit(rep);
}
}
}
}
/// Top level switch that translates SIL instructions.
void translateSILInstruction(SILInstruction *inst) {
builder.reset(inst);
SWIFT_DEFER { REGIONBASEDISOLATION_LOG(builder.print(llvm::dbgs())); };
auto computeOpKind = [&]() -> TranslationSemantics {
switch (inst->getKind()) {
#define INST(ID, PARENT) \
case SILInstructionKind::ID: \
return visit##ID(cast<ID>(inst));
#include "swift/SIL/SILNodes.def"
}
};
auto kind = computeOpKind();
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " Semantics: " << kind << '\n');
switch (kind) {
case TranslationSemantics::Ignored:
return;
case TranslationSemantics::AssignFresh:
for (auto result : inst->getResults())
translateSILAssignFresh(result);
return;
case TranslationSemantics::Assign:
return translateSILMultiAssign(
inst->getResults(), makeOperandRefRange(inst->getAllOperands()));
case TranslationSemantics::Require:
for (auto op : inst->getOperandValues())
translateSILRequire(op);
return;
case TranslationSemantics::LookThrough:
assert(inst->getNumRealOperands() == 1);
assert((isStaticallyLookThroughInst(inst) ||
isLookThroughIfResultNonSendable(inst) ||
isLookThroughIfOperandNonSendable(inst) ||
isLookThroughIfOperandAndResultNonSendable(inst)) &&
"Out of sync... should return true for one of these categories!");
return translateSILLookThrough(inst->getResults(), inst->getOperand(0));
case TranslationSemantics::Store:
return translateSILStore(
&inst->getAllOperands()[CopyLikeInstruction::Dest],
&inst->getAllOperands()[CopyLikeInstruction::Src]);
case TranslationSemantics::Special:
return;
case TranslationSemantics::Apply:
return translateSILApply(inst);
case TranslationSemantics::TerminatorPhi: {
TermArgSources sources;
sources.init(inst);
return translateSILPhi(sources);
}
case TranslationSemantics::Asserting:
llvm::errs() << "BannedInst: " << *inst;
llvm::report_fatal_error("send-non-sendable: Found banned instruction?!");
return;
case TranslationSemantics::AssertingIfNonSendable:
// Do not error if all of our operands are sendable.
if (llvm::none_of(inst->getOperandValues(), [&](SILValue value) {
return ::SILIsolationInfo::isNonSendableType(value->getType(),
inst->getFunction());
}))
return;
llvm::errs() << "BadInst: " << *inst;
llvm::report_fatal_error(
"send-non-sendable: Found instruction that is not allowed to "
"have non-Sendable parameters with such parameters?!");
return;
case TranslationSemantics::SendingNoResult:
return translateSILSendingNoResult(inst->getAllOperands());
}
llvm_unreachable("Covered switch isn't covered?!");
}
};
} // namespace regionanalysisimpl
} // namespace swift
Element PartitionOpBuilder::lookupValueID(SILValue value) {
return translator->lookupValueID(value);
}
Element PartitionOpBuilder::getActorIntroducingRepresentative(
SILIsolationInfo actorIsolation) {
return translator
->getActorIntroducingRepresentative(currentInst, actorIsolation)
.getID();
}
bool PartitionOpBuilder::valueHasID(SILValue value, bool dumpIfHasNoID) {
auto v = translator->valueMap.getTrackableValue(value);
if (auto m = v.getRepresentative().maybeGetValue())
return translator->valueHasID(m, dumpIfHasNoID);
return true;
}
void PartitionOpBuilder::print(llvm::raw_ostream &os) const {
#ifndef NDEBUG
// If we do not have anything to dump, just return.
if (currentInstPartitionOps.empty())
return;
// First line.
llvm::dbgs() << " ┌─┬─╼";
currentInst->print(llvm::dbgs());
// Second line.
llvm::dbgs() << " │ └─╼ ";
currentInst->getLoc().getSourceLoc().printLineAndColumn(
llvm::dbgs(), currentInst->getFunction()->getASTContext().SourceMgr);
auto ops = llvm::ArrayRef(currentInstPartitionOps);
// First op on its own line.
llvm::dbgs() << "\n ├─────╼ ";
ops.front().print(llvm::dbgs());
// Rest of ops each on their own line.
for (const PartitionOp &op : ops.drop_front()) {
llvm::dbgs() << " │ └╼ ";
op.print(llvm::dbgs());
}
// Now print out a translation from region to equivalence class value.
llvm::dbgs() << " └─────╼ Used Values\n";
llvm::SmallVector<Element, 8> opsToPrint;
SWIFT_DEFER { opsToPrint.clear(); };
for (const PartitionOp &op : ops) {
// Now dump our the root value we map.
for (unsigned opArg : op.getOpArgs()) {
// If we didn't insert, skip this. We only emit this once.
opsToPrint.push_back(Element(opArg));
}
}
sortUnique(opsToPrint);
for (Element opArg : opsToPrint) {
llvm::dbgs() << " └╼ ";
auto trackableValue = translator->getValueForId(opArg);
assert(trackableValue);
llvm::dbgs() << "State: %%" << opArg << ". ";
trackableValue->getValueState().print(llvm::dbgs());
llvm::dbgs() << "\n Rep Value: "
<< trackableValue->getRepresentative();
if (auto value = trackableValue->getRepresentative().maybeGetValue()) {
llvm::dbgs() << " Type: " << value->getType() << '\n';
}
}
#endif
}
//===----------------------------------------------------------------------===//
// MARK: Translator - Instruction To Op Kind
//===----------------------------------------------------------------------===//
#ifdef CONSTANT_TRANSLATION
#error "CONSTANT_TRANSLATION already defined?!"
#endif
#define CONSTANT_TRANSLATION(INST, Kind) \
TranslationSemantics PartitionOpTranslator::visit##INST(INST *inst) { \
assert((TranslationSemantics::Kind != TranslationSemantics::LookThrough || \
isStaticallyLookThroughInst(inst)) && \
"Out of sync?!"); \
assert((TranslationSemantics::Kind == TranslationSemantics::LookThrough || \
!isStaticallyLookThroughInst(inst)) && \
"Out of sync?!"); \
return TranslationSemantics::Kind; \
}
//===---
// Assign Fresh
//
CONSTANT_TRANSLATION(AllocBoxInst, AssignFresh)
CONSTANT_TRANSLATION(AllocPackInst, AssignFresh)
CONSTANT_TRANSLATION(AllocRefDynamicInst, AssignFresh)
CONSTANT_TRANSLATION(AllocRefInst, AssignFresh)
CONSTANT_TRANSLATION(AllocVectorInst, AssignFresh)
CONSTANT_TRANSLATION(KeyPathInst, AssignFresh)
CONSTANT_TRANSLATION(FunctionRefInst, AssignFresh)
CONSTANT_TRANSLATION(DynamicFunctionRefInst, AssignFresh)
CONSTANT_TRANSLATION(PreviousDynamicFunctionRefInst, AssignFresh)
CONSTANT_TRANSLATION(GlobalAddrInst, AssignFresh)
CONSTANT_TRANSLATION(GlobalValueInst, AssignFresh)
CONSTANT_TRANSLATION(HasSymbolInst, AssignFresh)
CONSTANT_TRANSLATION(ObjCProtocolInst, AssignFresh)
CONSTANT_TRANSLATION(WitnessMethodInst, AssignFresh)
// TODO: These should always be sendable.
CONSTANT_TRANSLATION(IntegerLiteralInst, AssignFresh)
CONSTANT_TRANSLATION(FloatLiteralInst, AssignFresh)
CONSTANT_TRANSLATION(StringLiteralInst, AssignFresh)
// Metatypes are Sendable, but AnyObject isn't
CONSTANT_TRANSLATION(ObjCMetatypeToObjectInst, AssignFresh)
CONSTANT_TRANSLATION(ObjCExistentialMetatypeToObjectInst, AssignFresh)
//===---
// Assign
//
// These are instructions that we treat as true assigns since we want to
// error semantically upon them if there is a use of one of these. For
// example, a cast would be inappropriate here. This is implemented by
// propagating the operand's region into the result's region and by
// requiring all operands.
CONSTANT_TRANSLATION(LoadWeakInst, Assign)
CONSTANT_TRANSLATION(StrongCopyUnownedValueInst, Assign)
CONSTANT_TRANSLATION(ClassMethodInst, Assign)
CONSTANT_TRANSLATION(ObjCMethodInst, Assign)
CONSTANT_TRANSLATION(SuperMethodInst, Assign)
CONSTANT_TRANSLATION(ObjCSuperMethodInst, Assign)
CONSTANT_TRANSLATION(LoadUnownedInst, Assign)
// These instructions are in between look through and a true assign. We should
// probably eventually treat them as look through but we haven't done the work
// yet of validating that everything fits together in terms of
// getUnderlyingTrackedObject.
CONSTANT_TRANSLATION(AddressToPointerInst, Assign)
CONSTANT_TRANSLATION(BaseAddrForOffsetInst, Assign)
CONSTANT_TRANSLATION(ConvertEscapeToNoEscapeInst, Assign)
CONSTANT_TRANSLATION(ConvertFunctionInst, Assign)
CONSTANT_TRANSLATION(ThunkInst, Assign)
CONSTANT_TRANSLATION(CopyBlockInst, Assign)
CONSTANT_TRANSLATION(CopyBlockWithoutEscapingInst, Assign)
CONSTANT_TRANSLATION(IndexAddrInst, Assign)
CONSTANT_TRANSLATION(InitBlockStorageHeaderInst, Assign)
CONSTANT_TRANSLATION(InitExistentialAddrInst, Assign)
CONSTANT_TRANSLATION(InitExistentialRefInst, Assign)
CONSTANT_TRANSLATION(OpenExistentialBoxInst, Assign)
CONSTANT_TRANSLATION(OpenExistentialRefInst, Assign)
CONSTANT_TRANSLATION(TailAddrInst, Assign)
CONSTANT_TRANSLATION(ThickToObjCMetatypeInst, Assign)
CONSTANT_TRANSLATION(ThinToThickFunctionInst, Assign)
CONSTANT_TRANSLATION(UncheckedAddrCastInst, Assign)
CONSTANT_TRANSLATION(UncheckedEnumDataInst, Assign)
CONSTANT_TRANSLATION(UncheckedOwnershipConversionInst, Assign)
CONSTANT_TRANSLATION(IndexRawPointerInst, Assign)
// These are used by SIL to aggregate values together in a gep like way. We
// want to look at uses of structs, not the struct uses itself. So just
// propagate.
CONSTANT_TRANSLATION(ObjectInst, Assign)
CONSTANT_TRANSLATION(StructInst, Assign)
CONSTANT_TRANSLATION(TupleInst, Assign)
//===---
// Look Through
//
// Instructions that getUnderlyingTrackedValue is guaranteed to look through
// and whose operand and result are guaranteed to be mapped to the same
// underlying region.
CONSTANT_TRANSLATION(BeginAccessInst, LookThrough)
CONSTANT_TRANSLATION(BorrowedFromInst, LookThrough)
CONSTANT_TRANSLATION(BeginDeallocRefInst, LookThrough)
CONSTANT_TRANSLATION(BridgeObjectToRefInst, LookThrough)
CONSTANT_TRANSLATION(CopyValueInst, LookThrough)
CONSTANT_TRANSLATION(ExplicitCopyValueInst, LookThrough)
CONSTANT_TRANSLATION(EndCOWMutationInst, LookThrough)
CONSTANT_TRANSLATION(ProjectBoxInst, LookThrough)
CONSTANT_TRANSLATION(EndInitLetRefInst, LookThrough)
CONSTANT_TRANSLATION(InitEnumDataAddrInst, LookThrough)
CONSTANT_TRANSLATION(OpenExistentialAddrInst, LookThrough)
CONSTANT_TRANSLATION(UncheckedRefCastInst, LookThrough)
CONSTANT_TRANSLATION(UpcastInst, LookThrough)
CONSTANT_TRANSLATION(MarkUnresolvedNonCopyableValueInst, LookThrough)
CONSTANT_TRANSLATION(MarkUnresolvedReferenceBindingInst, LookThrough)
CONSTANT_TRANSLATION(CopyableToMoveOnlyWrapperValueInst, LookThrough)
CONSTANT_TRANSLATION(MoveOnlyWrapperToCopyableValueInst, LookThrough)
CONSTANT_TRANSLATION(MoveOnlyWrapperToCopyableBoxInst, LookThrough)
CONSTANT_TRANSLATION(MoveOnlyWrapperToCopyableAddrInst, LookThrough)
CONSTANT_TRANSLATION(CopyableToMoveOnlyWrapperAddrInst, LookThrough)
CONSTANT_TRANSLATION(MarkUninitializedInst, LookThrough)
// We identify destructured results with their operand's region.
CONSTANT_TRANSLATION(DestructureTupleInst, LookThrough)
CONSTANT_TRANSLATION(DestructureStructInst, LookThrough)
CONSTANT_TRANSLATION(ProjectBlockStorageInst, LookThrough)
CONSTANT_TRANSLATION(RefToUnownedInst, LookThrough)
CONSTANT_TRANSLATION(UnownedToRefInst, LookThrough)
CONSTANT_TRANSLATION(UnownedCopyValueInst, LookThrough)
CONSTANT_TRANSLATION(DropDeinitInst, LookThrough)
CONSTANT_TRANSLATION(ValueToBridgeObjectInst, LookThrough)
CONSTANT_TRANSLATION(BeginCOWMutationInst, LookThrough)
CONSTANT_TRANSLATION(OpenExistentialValueInst, LookThrough)
CONSTANT_TRANSLATION(WeakCopyValueInst, LookThrough)
CONSTANT_TRANSLATION(StrongCopyWeakValueInst, LookThrough)
CONSTANT_TRANSLATION(StrongCopyUnmanagedValueInst, LookThrough)
CONSTANT_TRANSLATION(RefToUnmanagedInst, LookThrough)
CONSTANT_TRANSLATION(UnmanagedToRefInst, LookThrough)
CONSTANT_TRANSLATION(InitExistentialValueInst, LookThrough)
//===---
// Store
//
// These are treated as stores - meaning that they could write values into
// memory. The beahvior of this depends on whether the tgt addr is aliased,
// but conservative behavior is to treat these as merges of the regions of
// the src value and tgt addr
CONSTANT_TRANSLATION(CopyAddrInst, Store)
CONSTANT_TRANSLATION(ExplicitCopyAddrInst, Store)
CONSTANT_TRANSLATION(StoreInst, Store)
CONSTANT_TRANSLATION(StoreWeakInst, Store)
CONSTANT_TRANSLATION(MarkUnresolvedMoveAddrInst, Store)
CONSTANT_TRANSLATION(UncheckedRefCastAddrInst, Store)
CONSTANT_TRANSLATION(UnconditionalCheckedCastAddrInst, Store)
CONSTANT_TRANSLATION(StoreUnownedInst, Store)
//===---
// Ignored
//
// These instructions are ignored because they cannot affect the region that a
// value is within or because even though they are technically a use we would
// rather emit an error on a better instruction.
CONSTANT_TRANSLATION(AllocGlobalInst, Ignored)
CONSTANT_TRANSLATION(AutoreleaseValueInst, Ignored)
CONSTANT_TRANSLATION(DeallocBoxInst, Ignored)
CONSTANT_TRANSLATION(DeallocPartialRefInst, Ignored)
CONSTANT_TRANSLATION(DeallocRefInst, Ignored)
CONSTANT_TRANSLATION(DeallocStackInst, Ignored)
CONSTANT_TRANSLATION(DeallocStackRefInst, Ignored)
CONSTANT_TRANSLATION(DebugValueInst, Ignored)
CONSTANT_TRANSLATION(DeinitExistentialAddrInst, Ignored)
CONSTANT_TRANSLATION(DeinitExistentialValueInst, Ignored)
CONSTANT_TRANSLATION(DestroyAddrInst, Ignored)
CONSTANT_TRANSLATION(DestroyValueInst, Ignored)
CONSTANT_TRANSLATION(EndAccessInst, Ignored)
CONSTANT_TRANSLATION(EndBorrowInst, Ignored)
CONSTANT_TRANSLATION(EndLifetimeInst, Ignored)
CONSTANT_TRANSLATION(ExtendLifetimeInst, Ignored)
CONSTANT_TRANSLATION(EndUnpairedAccessInst, Ignored)
CONSTANT_TRANSLATION(HopToExecutorInst, Ignored)
CONSTANT_TRANSLATION(InjectEnumAddrInst, Ignored)
CONSTANT_TRANSLATION(IsEscapingClosureInst, Ignored)
CONSTANT_TRANSLATION(MetatypeInst, Ignored)
CONSTANT_TRANSLATION(EndApplyInst, Ignored)
CONSTANT_TRANSLATION(AbortApplyInst, Ignored)
CONSTANT_TRANSLATION(DebugStepInst, Ignored)
CONSTANT_TRANSLATION(IncrementProfilerCounterInst, Ignored)
CONSTANT_TRANSLATION(SpecifyTestInst, Ignored)
CONSTANT_TRANSLATION(TypeValueInst, Ignored)
//===---
// Require
//
// Instructions that only require that the region of the value be live:
CONSTANT_TRANSLATION(FixLifetimeInst, Require)
CONSTANT_TRANSLATION(ClassifyBridgeObjectInst, Require)
CONSTANT_TRANSLATION(BridgeObjectToWordInst, Require)
CONSTANT_TRANSLATION(IsUniqueInst, Require)
CONSTANT_TRANSLATION(MarkFunctionEscapeInst, Require)
CONSTANT_TRANSLATION(UnmanagedRetainValueInst, Require)
CONSTANT_TRANSLATION(UnmanagedReleaseValueInst, Require)
CONSTANT_TRANSLATION(UnmanagedAutoreleaseValueInst, Require)
CONSTANT_TRANSLATION(RebindMemoryInst, Require)
CONSTANT_TRANSLATION(BindMemoryInst, Require)
CONSTANT_TRANSLATION(BeginUnpairedAccessInst, Require)
// Require of the value we extract the metatype from.
CONSTANT_TRANSLATION(ValueMetatypeInst, Require)
// Require of the value we extract the metatype from.
CONSTANT_TRANSLATION(ExistentialMetatypeInst, Require)
// These can take a parameter. If it is non-Sendable, use a require.
CONSTANT_TRANSLATION(GetAsyncContinuationAddrInst, Require)
//===---
// Asserting If Non Sendable Parameter
//
// Takes metatypes as parameters and metatypes today are always sendable.
CONSTANT_TRANSLATION(InitExistentialMetatypeInst, AssertingIfNonSendable)
CONSTANT_TRANSLATION(OpenExistentialMetatypeInst, AssertingIfNonSendable)
CONSTANT_TRANSLATION(ObjCToThickMetatypeInst, AssertingIfNonSendable)
//===---
// Terminators
//
// Ignored terminators.
CONSTANT_TRANSLATION(CondFailInst, Ignored)
// Switch value inst is ignored since we only switch over integers and
// function_ref/class_method which are considered sendable.
CONSTANT_TRANSLATION(SwitchValueInst, Ignored)
CONSTANT_TRANSLATION(UnreachableInst, Ignored)
// Terminators that only need require.
CONSTANT_TRANSLATION(SwitchEnumAddrInst, Require)
CONSTANT_TRANSLATION(YieldInst, Require)
// Terminators that act as phis.
CONSTANT_TRANSLATION(BranchInst, TerminatorPhi)
CONSTANT_TRANSLATION(CondBranchInst, TerminatorPhi)
CONSTANT_TRANSLATION(CheckedCastBranchInst, TerminatorPhi)
CONSTANT_TRANSLATION(DynamicMethodBranchInst, TerminatorPhi)
// Function exiting terminators.
//
// We handle these especially since we want to make sure that inout parameters
// that are sent are forced to be reinitialized.
//
// There is an assert in TermInst::isFunctionExiting that makes sure we do this
// correctly.
//
// NOTE: We purposely do not require reinitialization along paths that end in
// unreachable.
#ifdef FUNCTION_EXITING_TERMINATOR_TRANSLATION
#error "FUNCTION_EXITING_TERMINATOR_TRANSLATION already defined?!"
#endif
#define FUNCTION_EXITING_TERMINATOR_CONSTANT(INST, Kind) \
TranslationSemantics PartitionOpTranslator::visit##INST(INST *inst) { \
assert(inst->isFunctionExiting() && "Must be function exiting?!"); \
addEndOfFunctionChecksForInOutSendingParameters(inst); \
return TranslationSemantics::Kind; \
}
FUNCTION_EXITING_TERMINATOR_CONSTANT(UnwindInst, Ignored)
FUNCTION_EXITING_TERMINATOR_CONSTANT(ThrowAddrInst, Ignored)
FUNCTION_EXITING_TERMINATOR_CONSTANT(ThrowInst, Require)
#undef FUNCTION_EXITING_TERMINATOR_CONSTANT
// Today, await_async_continuation just takes Sendable values
// (UnsafeContinuation and UnsafeThrowingContinuation).
CONSTANT_TRANSLATION(AwaitAsyncContinuationInst, AssertingIfNonSendable)
CONSTANT_TRANSLATION(GetAsyncContinuationInst, AssertingIfNonSendable)
CONSTANT_TRANSLATION(ExtractExecutorInst, AssertingIfNonSendable)
CONSTANT_TRANSLATION(FunctionExtractIsolationInst, Require)
//===---
// Existential Box
//
// NOTE: Today these can only be used with Errors. Since Error is a sub-protocol
// of Sendable, we actually do not have any way to truly test them. These are
// just hypothetical assignments so we are complete.
CONSTANT_TRANSLATION(AllocExistentialBoxInst, AssignFresh)
CONSTANT_TRANSLATION(ProjectExistentialBoxInst, Assign)
CONSTANT_TRANSLATION(OpenExistentialBoxValueInst, Assign)
CONSTANT_TRANSLATION(DeallocExistentialBoxInst, Ignored)
//===---
// Differentiable
//
CONSTANT_TRANSLATION(DifferentiabilityWitnessFunctionInst, AssignFresh)
CONSTANT_TRANSLATION(DifferentiableFunctionExtractInst, LookThrough)
CONSTANT_TRANSLATION(LinearFunctionExtractInst, LookThrough)
CONSTANT_TRANSLATION(LinearFunctionInst, Assign)
CONSTANT_TRANSLATION(DifferentiableFunctionInst, Assign)
//===---
// Packs
//
CONSTANT_TRANSLATION(DeallocPackInst, Ignored)
CONSTANT_TRANSLATION(DynamicPackIndexInst, Ignored)
CONSTANT_TRANSLATION(OpenPackElementInst, Ignored)
CONSTANT_TRANSLATION(PackLengthInst, Ignored)
CONSTANT_TRANSLATION(PackPackIndexInst, Ignored)
CONSTANT_TRANSLATION(ScalarPackIndexInst, Ignored)
//===---
// Apply
//
CONSTANT_TRANSLATION(ApplyInst, Apply)
CONSTANT_TRANSLATION(BeginApplyInst, Apply)
CONSTANT_TRANSLATION(BuiltinInst, Apply)
CONSTANT_TRANSLATION(TryApplyInst, Apply)
//===---
// Asserting
//
// Non-OSSA instructions that we should never see since we bail on non-OSSA
// functions early.
CONSTANT_TRANSLATION(ReleaseValueAddrInst, Asserting)
CONSTANT_TRANSLATION(ReleaseValueInst, Asserting)
CONSTANT_TRANSLATION(RetainValueAddrInst, Asserting)
CONSTANT_TRANSLATION(RetainValueInst, Asserting)
CONSTANT_TRANSLATION(StrongReleaseInst, Asserting)
CONSTANT_TRANSLATION(StrongRetainInst, Asserting)
CONSTANT_TRANSLATION(StrongRetainUnownedInst, Asserting)
CONSTANT_TRANSLATION(UnownedReleaseInst, Asserting)
CONSTANT_TRANSLATION(UnownedRetainInst, Asserting)
// Instructions only valid in lowered SIL. Please only add instructions here
// after adding an assert into the SILVerifier that this property is true.
CONSTANT_TRANSLATION(AllocPackMetadataInst, Asserting)
CONSTANT_TRANSLATION(DeallocPackMetadataInst, Asserting)
// All of these instructions should be removed by DI which runs before us in the
// pass pipeline.
CONSTANT_TRANSLATION(AssignInst, Asserting)
CONSTANT_TRANSLATION(AssignByWrapperInst, Asserting)
CONSTANT_TRANSLATION(AssignOrInitInst, Asserting)
// We should never hit this since it can only appear as a final instruction in a
// global variable static initializer list.
CONSTANT_TRANSLATION(VectorInst, Asserting)
#undef CONSTANT_TRANSLATION
#define IGNORE_IF_SENDABLE_RESULT_ASSIGN_OTHERWISE(INST) \
TranslationSemantics PartitionOpTranslator::visit##INST(INST *inst) { \
return TranslationSemantics::Assign; \
}
IGNORE_IF_SENDABLE_RESULT_ASSIGN_OTHERWISE(TupleExtractInst)
IGNORE_IF_SENDABLE_RESULT_ASSIGN_OTHERWISE(StructExtractInst)
#undef IGNORE_IF_SENDABLE_RESULT_ASSIGN_OTHERWISE
#ifdef LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND
#error "LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND already defined"
#endif
#define LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(INST) \
\
TranslationSemantics PartitionOpTranslator::visit##INST(INST *cast) { \
assert(isLookThroughIfOperandAndResultNonSendable(cast) && "Out of sync"); \
bool isOperandNonSendable = \
isNonSendableType(cast->getOperand()->getType()); \
bool isResultNonSendable = isNonSendableType(cast->getType()); \
\
if (isOperandNonSendable) { \
if (isResultNonSendable) { \
return TranslationSemantics::LookThrough; \
} \
\
return TranslationSemantics::Require; \
} \
\
/* We always use assign fresh here regardless of whether or not a */ \
/* type is sendable. */ \
/* */ \
/* DISCUSSION: Since the typechecker is lazy, if there is a bug */ \
/* that causes us to not look up enough type information it is */ \
/* possible for a type to move from being Sendable to being */ \
/* non-Sendable. For example, we could call isNonSendableType and */ \
/* get that the type is non-Sendable, but as a result of calling */ \
/* that API, the type checker could get more information that the */ \
/* next time we call isNonSendableType, we will get that the type */ \
/* is non-Sendable. */ \
return TranslationSemantics::AssignFresh; \
}
LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(UncheckedTrivialBitCastInst)
LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(UncheckedBitwiseCastInst)
LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(UncheckedValueCastInst)
LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(TupleElementAddrInst)
LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(StructElementAddrInst)
LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND(UncheckedTakeEnumDataAddrInst)
#undef LOOKTHROUGH_IF_NONSENDABLE_RESULT_AND_OPERAND
//===---
// Custom Handling
//
TranslationSemantics
PartitionOpTranslator::visitStoreBorrowInst(StoreBorrowInst *sbi) {
// A store_borrow is an interesting instruction since we are essentially
// temporarily binding an object value to an address... so really any uses of
// the address, we want to consider to be uses of the parent object. So we
// basically put source/dest into the same region, but do not consider the
// store_borrow itself to be a require use. This prevents the store_borrow
// from causing incorrect diagnostics.
SILValue destValue = sbi->getDest();
auto nonSendableDest = tryToTrackValue(destValue);
if (!nonSendableDest)
return TranslationSemantics::Ignored;
// In the following situations, we can perform an assign:
//
// 1. A store to unaliased storage.
// 2. A store that is to an entire value.
//
// DISCUSSION: If we have case 2, we need to merge the regions since we
// are not overwriting the entire region of the value. This does mean that
// we artificially include the previous region that was stored
// specifically in this projection... but that is better than
// miscompiling. For memory like this, we probably need to track it on a
// per field basis to allow for us to assign.
if (nonSendableDest.value().isNoAlias() &&
!isProjectedFromAggregate(destValue)) {
translateSILMultiAssign(sbi->getResults(),
makeOperandRefRange(sbi->getAllOperands()),
SILIsolationInfo(), false /*require src*/);
} else {
// Stores to possibly aliased storage must be treated as merges.
translateSILMerge(destValue, &sbi->getAllOperands()[StoreBorrowInst::Src],
false /*require src*/);
}
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitAllocStackInst(AllocStackInst *asi) {
// Before we do anything, see if asi is Sendable or if it is non-Sendable,
// that it is from a var decl. In both cases, we can just return assign fresh
// and exit early.
if (!SILIsolationInfo::isNonSendableType(asi) || asi->isFromVarDecl())
return TranslationSemantics::AssignFresh;
// Ok at this point we know that our value is a non-Sendable temporary.
auto isolationInfo = SILIsolationInfo::get(asi);
if (!bool(isolationInfo) || isolationInfo.isDisconnected()) {
return TranslationSemantics::AssignFresh;
}
// Ok, we can handle this and have a valid isolation. Initialize the value.
auto v = initializeTrackedValue(asi, isolationInfo);
assert(v && "Only return none if we have a sendable value, but we checked "
"that earlier!");
// If we already had a value for this alloc_stack (which we shouldn't
// ever)... emit an unknown pattern error.
if (!v->second) {
translateUnknownPatternError(asi);
return TranslationSemantics::Special;
}
// NOTE: To prevent an additional reinitialization by the canned AssignFresh
// code, we do our own assign fresh and return special.
builder.addAssignFresh(v->first.getRepresentative().getValue());
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitMoveValueInst(MoveValueInst *mvi) {
if (mvi->isFromVarDecl())
return TranslationSemantics::Assign;
return TranslationSemantics::LookThrough;
}
TranslationSemantics
PartitionOpTranslator::visitBeginBorrowInst(BeginBorrowInst *bbi) {
if (bbi->isFromVarDecl())
return TranslationSemantics::Assign;
return TranslationSemantics::LookThrough;
}
/// LoadInst is technically a statically look through instruction, but we want
/// to handle it especially in the infrastructure, so we cannot mark it as
/// such. This makes marking it as a normal lookthrough instruction impossible
/// since the routine checks that invariant.
TranslationSemantics PartitionOpTranslator::visitLoadInst(LoadInst *limvi) {
return TranslationSemantics::Special;
}
/// LoadBorrowInst is technically a statically look through instruction, but we
/// want to handle it especially in the infrastructure, so we cannot mark it as
/// such. This makes marking it as a normal lookthrough instruction impossible
/// since the routine checks that invariant.
TranslationSemantics
PartitionOpTranslator::visitLoadBorrowInst(LoadBorrowInst *lbi) {
return TranslationSemantics::Special;
}
TranslationSemantics PartitionOpTranslator::visitReturnInst(ReturnInst *ri) {
addEndOfFunctionChecksForInOutSendingParameters(ri);
if (ri->getFunction()->getLoweredFunctionType()->hasSendingResult()) {
return TranslationSemantics::SendingNoResult;
}
return TranslationSemantics::Require;
}
TranslationSemantics
PartitionOpTranslator::visitRefToBridgeObjectInst(RefToBridgeObjectInst *r) {
translateSILLookThrough(
SILValue(r), r->getOperand(RefToBridgeObjectInst::ConvertedOperand));
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitPackElementGetInst(PackElementGetInst *r) {
if (!isNonSendableType(r->getType()))
return TranslationSemantics::Require;
translateSILAssign(SILValue(r), r->getPackOperand());
return TranslationSemantics::Special;
}
TranslationSemantics PartitionOpTranslator::visitTuplePackElementAddrInst(
TuplePackElementAddrInst *r) {
if (!isNonSendableType(r->getType())) {
translateSILRequire(r->getTuple());
} else {
translateSILAssign(SILValue(r), r->getTupleOperand());
}
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitTuplePackExtractInst(TuplePackExtractInst *r) {
if (!isNonSendableType(r->getType())) {
translateSILRequire(r->getTuple());
} else {
translateSILAssign(SILValue(r), r->getTupleOperand());
}
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitPackElementSetInst(PackElementSetInst *r) {
// If the value we are storing is sendable, treat this as a require.
if (!isNonSendableType(r->getValue()->getType())) {
return TranslationSemantics::Require;
}
// Otherwise, this is a store.
translateSILStore(r->getPackOperand(), r->getValueOperand());
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitRawPointerToRefInst(RawPointerToRefInst *r) {
assert(isLookThroughIfResultNonSendable(r) && "Out of sync");
// If our result is non sendable, perform a look through.
if (isNonSendableType(r->getType()))
return TranslationSemantics::LookThrough;
// Otherwise to be conservative, we need to treat this as a require.
return TranslationSemantics::Require;
}
TranslationSemantics
PartitionOpTranslator::visitRefToRawPointerInst(RefToRawPointerInst *r) {
assert(isLookThroughIfOperandNonSendable(r) && "Out of sync");
// If our source ref is non sendable, perform a look through.
if (isNonSendableType(r->getOperand()->getType()))
return TranslationSemantics::LookThrough;
// Otherwise to be conservative, we need to treat the raw pointer as a fresh
// sendable value.
return TranslationSemantics::AssignFresh;
}
TranslationSemantics
PartitionOpTranslator::visitMarkDependenceInst(MarkDependenceInst *mdi) {
assert(isStaticallyLookThroughInst(mdi) && "Out of sync");
translateSILLookThrough(mdi->getResults(), mdi->getValue());
translateSILRequire(mdi->getBase());
return TranslationSemantics::Special;
}
TranslationSemantics PartitionOpTranslator::visitMergeIsolationRegionInst(
MergeIsolationRegionInst *mir) {
// But we want to require and merge the base into the result.
translateSILMerge(mir->getAllOperands(), true /*require operands*/);
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitPointerToAddressInst(PointerToAddressInst *ptai) {
if (!isNonSendableType(ptai->getType())) {
return TranslationSemantics::Require;
}
return TranslationSemantics::Assign;
}
TranslationSemantics PartitionOpTranslator::visitUnconditionalCheckedCastInst(
UnconditionalCheckedCastInst *ucci) {
if (SILDynamicCastInst(ucci).isRCIdentityPreserving()) {
assert(isStaticallyLookThroughInst(ucci) && "Out of sync");
return TranslationSemantics::LookThrough;
}
assert(!isStaticallyLookThroughInst(ucci) && "Out of sync");
return TranslationSemantics::Assign;
}
// RefElementAddrInst is not considered to be a lookThrough since we want to
// consider the address projected from the class to be a separate value that
// is in the same region as the parent operand. The reason that we want to
// do this is to ensure that if we assign into the ref_element_addr memory,
// we do not consider writes into the struct that contains the
// ref_element_addr to be merged into.
TranslationSemantics
PartitionOpTranslator::visitRefElementAddrInst(RefElementAddrInst *reai) {
// If our field is a NonSendableType...
if (!isNonSendableType(reai->getType())) {
// And the field is a let... then ignore it. We know that we cannot race on
// any writes to the field.
if (reai->getField()->isLet()) {
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< " Found a let! Not tracking!\n");
return TranslationSemantics::Ignored;
}
// Otherwise, we need to treat the access to the field as a require since we
// could have a race on assignment to the class.
return TranslationSemantics::Require;
}
return TranslationSemantics::Assign;
}
TranslationSemantics
PartitionOpTranslator::visitRefTailAddrInst(RefTailAddrInst *reai) {
// If our trailing type is Sendable...
if (!isNonSendableType(reai->getType())) {
// And our ref_tail_addr is immutable... we can ignore the access since we
// cannot race against a write to any of these fields.
if (reai->isImmutable()) {
REGIONBASEDISOLATION_LOG(
llvm::dbgs()
<< " Found an immutable Sendable ref_tail_addr! Not tracking!\n");
return TranslationSemantics::Ignored;
}
// Otherwise, we need a require since the value maybe alive.
return TranslationSemantics::Require;
}
// If we have a NonSendable type, treat the address as a separate Element from
// our base value.
return TranslationSemantics::Assign;
}
/// Enum inst is handled specially since if it does not have an argument,
/// we must assign fresh. Otherwise, we must propagate.
TranslationSemantics PartitionOpTranslator::visitEnumInst(EnumInst *ei) {
if (ei->getNumOperands() == 0)
return TranslationSemantics::AssignFresh;
return TranslationSemantics::Assign;
}
TranslationSemantics
PartitionOpTranslator::visitSelectEnumAddrInst(SelectEnumAddrInst *inst) {
translateSILSelectEnum(inst);
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitSelectEnumInst(SelectEnumInst *inst) {
translateSILSelectEnum(inst);
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitSwitchEnumInst(SwitchEnumInst *inst) {
translateSILSwitchEnum(inst);
return TranslationSemantics::Special;
}
TranslationSemantics PartitionOpTranslator::visitTupleAddrConstructorInst(
TupleAddrConstructorInst *inst) {
translateSILTupleAddrConstructor(inst);
return TranslationSemantics::Special;
}
TranslationSemantics
PartitionOpTranslator::visitPartialApplyInst(PartialApplyInst *pai) {
translateSILPartialApply(pai);
return TranslationSemantics::Special;
}
TranslationSemantics PartitionOpTranslator::visitCheckedCastAddrBranchInst(
CheckedCastAddrBranchInst *ccabi) {
assert(ccabi->getSuccessBB()->getNumArguments() <= 1);
// checked_cast_addr_br does not have any arguments in its resulting
// block. We should just use a multi-assign on its operands.
//
// TODO: We should be smarter and treat the success/fail branches
// differently depending on what the result of checked_cast_addr_br
// is. For now just keep the current behavior. It is more conservative,
// but still correct.
translateSILMultiAssign(ArrayRef<SILValue>(),
makeOperandRefRange(ccabi->getAllOperands()));
return TranslationSemantics::Special;
}
//===----------------------------------------------------------------------===//
// MARK: Block Level Model
//===----------------------------------------------------------------------===//
BlockPartitionState::BlockPartitionState(
SILBasicBlock *basicBlock, PartitionOpTranslator &translator,
SendingOperandSetFactory &ptrSetFactory,
IsolationHistory::Factory &isolationHistoryFactory,
SendingOperandToStateMap &sendingOpToStateMap)
: entryPartition(isolationHistoryFactory.get()),
exitPartition(isolationHistoryFactory.get()), basicBlock(basicBlock),
ptrSetFactory(ptrSetFactory), sendingOpToStateMap(sendingOpToStateMap) {
translator.translateSILBasicBlock(basicBlock, blockPartitionOps);
}
bool BlockPartitionState::recomputeExitFromEntry(
PartitionOpTranslator &translator) {
Partition workingPartition = entryPartition;
struct ComputeEvaluator final
: PartitionOpEvaluatorBaseImpl<ComputeEvaluator> {
PartitionOpTranslator &translator;
ComputeEvaluator(Partition &workingPartition,
SendingOperandSetFactory &ptrSetFactory,
PartitionOpTranslator &translator,
SendingOperandToStateMap &sendingOpToStateMap)
: PartitionOpEvaluatorBaseImpl(workingPartition, ptrSetFactory,
sendingOpToStateMap),
translator(translator) {}
SILIsolationInfo getIsolationRegionInfo(Element elt) const {
return translator.getValueMap().getIsolationRegion(elt);
}
std::optional<Element> getElement(SILValue value) const {
return translator.getValueMap().getTrackableValue(value).getID();
}
SILValue getRepresentative(SILValue value) const {
return translator.getValueMap()
.getTrackableValue(value)
.getRepresentative()
.maybeGetValue();
}
RepresentativeValue getRepresentativeValue(Element element) const {
return translator.getValueMap().getRepresentativeValue(element);
}
bool isClosureCaptured(Element elt, Operand *op) const {
auto iter = translator.getValueForId(elt);
if (!iter)
return false;
auto value = iter->getRepresentative().maybeGetValue();
if (!value)
return false;
return translator.isClosureCaptured(value, op->getUser());
}
};
ComputeEvaluator eval(workingPartition, ptrSetFactory, translator,
sendingOpToStateMap);
for (const auto &partitionOp : blockPartitionOps) {
// By calling apply without providing any error handling callbacks, errors
// will be surpressed. will be suppressed
eval.apply(partitionOp);
}
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " Working Partition: ";
workingPartition.print(llvm::dbgs()));
bool exitUpdated = !Partition::equals(exitPartition, workingPartition);
exitPartition = workingPartition;
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " Exit Partition: ";
exitPartition.print(llvm::dbgs()));
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " Updated Partition: "
<< (exitUpdated ? "yes\n" : "no\n"));
return exitUpdated;
}
void BlockPartitionState::print(llvm::raw_ostream &os) const {
os << SEP_STR << "BlockPartitionState[needsUpdate=" << needsUpdate
<< "]\nid: ";
basicBlock->printID(os);
os << "entry partition: ";
entryPartition.print(os);
os << "exit partition: ";
exitPartition.print(os);
os << "instructions:\n┌──────────╼\n";
for (const auto &op : blockPartitionOps) {
os << "│ ";
op.print(os, true /*extra space*/);
}
os << "└──────────╼\nSuccs:\n";
for (auto succ : basicBlock->getSuccessorBlocks()) {
os << "→";
succ->printID(os);
}
os << "Preds:\n";
for (auto pred : basicBlock->getPredecessorBlocks()) {
os << "←";
pred->printID(os);
}
os << SEP_STR;
}
//===----------------------------------------------------------------------===//
// MARK: Dataflow Entrypoint
//===----------------------------------------------------------------------===//
static bool canComputeRegionsForFunction(SILFunction *fn) {
if (!fn->getASTContext().LangOpts.hasFeature(Feature::RegionBasedIsolation))
return false;
assert(fn->getASTContext().LangOpts.StrictConcurrencyLevel ==
StrictConcurrency::Complete &&
"Need strict concurrency to be enabled for RegionBasedIsolation to be "
"enabled as well");
// If this function does not correspond to a syntactic declContext and it
// doesn't have a parent module, don't check it since we cannot check if a
// type is sendable.
if (!fn->getDeclContext() && !fn->getParentModule()) {
return false;
}
if (!fn->hasOwnership()) {
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< "Only runs on Ownership SSA, skipping!\n");
return false;
}
// The sendable protocol should /always/ be available if SendNonSendable
// is enabled. If not, there is a major bug in the compiler and we should
// fail loudly.
if (!fn->getASTContext().getProtocol(KnownProtocolKind::Sendable))
return false;
return true;
}
RegionAnalysisFunctionInfo::RegionAnalysisFunctionInfo(
SILFunction *fn, PostOrderFunctionInfo *pofi)
: allocator(), fn(fn), valueMap(fn), translator(), ptrSetFactory(allocator),
isolationHistoryFactory(allocator),
sendingOperandToStateMap(isolationHistoryFactory), blockStates(),
pofi(pofi), solved(false), supportedFunction(true) {
// Before we do anything, make sure that we support processing this function.
//
// NOTE: See documentation on supportedFunction for criteria.
if (!canComputeRegionsForFunction(fn)) {
supportedFunction = false;
return;
}
translator = new (allocator)
PartitionOpTranslator(fn, pofi, valueMap, isolationHistoryFactory);
blockStates.emplace(fn, [this](SILBasicBlock *block) -> BlockPartitionState {
return BlockPartitionState(block, *translator, ptrSetFactory,
isolationHistoryFactory,
sendingOperandToStateMap);
});
// Mark all blocks as needing to be updated.
for (auto &block : *fn) {
(*blockStates)[&block].needsUpdate = true;
}
// Set our entry partition to have the "entry partition".
(*blockStates)[fn->getEntryBlock()].entryPartition =
translator->getEntryPartition();
runDataflow();
}
RegionAnalysisFunctionInfo::~RegionAnalysisFunctionInfo() {
// If we had a non-supported function, we didn't create a translator, so we do
// not need to tear anything down.
if (!supportedFunction)
return;
// Tear down translator before we tear down the allocator.
translator->~PartitionOpTranslator();
}
bool RegionAnalysisFunctionInfo::isClosureCaptured(SILValue value,
Operand *op) {
assert(supportedFunction && "Unsupported Function?!");
return translator->isClosureCaptured(value, op->getUser());
}
void RegionAnalysisFunctionInfo::runDataflow() {
assert(!solved && "solve should only be called once");
solved = true;
REGIONBASEDISOLATION_LOG(llvm::dbgs() << SEP_STR << "Performing Dataflow!\n"
<< SEP_STR);
REGIONBASEDISOLATION_LOG(llvm::dbgs() << "Values!\n";
translator->getValueMap().print(llvm::dbgs()));
bool anyNeedUpdate = true;
while (anyNeedUpdate) {
anyNeedUpdate = false;
for (auto *block : pofi->getReversePostOrder()) {
auto &blockState = (*blockStates)[block];
blockState.isLive = true;
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< "Block: bb" << block->getDebugID() << "\n");
if (!blockState.needsUpdate) {
REGIONBASEDISOLATION_LOG(llvm::dbgs()
<< " Doesn't need update! Skipping!\n");
continue;
}
// Mark this block as no longer needing an update.
blockState.needsUpdate = false;
// Compute the new entry partition to this block.
Partition newEntryPartition = blockState.entryPartition;
REGIONBASEDISOLATION_LOG(llvm::dbgs() << " Visiting Preds!\n");
// This loop computes the union of the exit partitions of all
// predecessors of this block
for (SILBasicBlock *predBlock : block->getPredecessorBlocks()) {
BlockPartitionState &predState = (*blockStates)[predBlock];
// Predecessors that have not been reached yet will have an empty pred
// state... so just merge them all. Also our initial value of
REGIONBASEDISOLATION_LOG(
llvm::dbgs() << " Pred. bb" << predBlock->getDebugID() << ": ";
predState.exitPartition.print(llvm::dbgs()));
newEntryPartition =
Partition::join(newEntryPartition, predState.exitPartition);
}
// Update the entry partition. We need to still try to
// recomputeExitFromEntry before we know if we made a difference to the
// exit partition after applying the instructions of the block.
blockState.entryPartition = newEntryPartition;
// recompute this block's exit partition from its (updated) entry
// partition, and if this changed the exit partition notify all
// successor blocks that they need to update as well
if (blockState.recomputeExitFromEntry(*translator)) {
for (SILBasicBlock *succBlock : block->getSuccessorBlocks()) {
anyNeedUpdate = true;
(*blockStates)[succBlock].needsUpdate = true;
}
}
}
}
}
//===----------------------------------------------------------------------===//
// Main Entry Point
//===----------------------------------------------------------------------===//
void RegionAnalysis::initialize(SILPassManager *pm) {
poa = pm->getAnalysis<PostOrderAnalysis>();
}
SILAnalysis *swift::createRegionAnalysis(SILModule *) {
return new RegionAnalysis();
}
|