1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086
|
//===--- SILFunctionType.cpp - Giving SIL types to AST functions ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// This file defines the native Swift ownership transfer conventions
// and works in concert with the importer to give the correct
// conventions to imported functions and types.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/ForeignInfo.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/LocalArchetypeRequirementCollector.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/AbstractionPatternGenerators.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace swift::Lowering;
SILType SILFunctionType::substInterfaceType(SILModule &M,
SILType interfaceType,
TypeExpansionContext context) const {
// Apply pattern substitutions first, then invocation substitutions.
if (auto subs = getPatternSubstitutions())
interfaceType = interfaceType.subst(M, subs, context);
if (auto subs = getInvocationSubstitutions())
interfaceType = interfaceType.subst(M, subs, context);
return interfaceType;
}
CanSILFunctionType SILFunctionType::getUnsubstitutedType(SILModule &M) const {
auto mutableThis = const_cast<SILFunctionType*>(this);
// If we have no substitutions, there's nothing to do.
if (!hasPatternSubstitutions() && !hasInvocationSubstitutions())
return CanSILFunctionType(mutableThis);
// Otherwise, substitute the component types.
SmallVector<SILParameterInfo, 4> params;
SmallVector<SILYieldInfo, 4> yields;
SmallVector<SILResultInfo, 4> results;
std::optional<SILResultInfo> errorResult;
auto subs = getCombinedSubstitutions();
auto substComponentType = [&](CanType type) {
if (!type->hasTypeParameter()) return type;
return SILType::getPrimitiveObjectType(type)
.subst(M, subs).getASTType();
};
for (auto param : getParameters()) {
params.push_back(param.map(substComponentType));
}
for (auto yield : getYields()) {
yields.push_back(yield.map(substComponentType));
}
for (auto result : getResults()) {
results.push_back(result.map(substComponentType));
}
if (auto error = getOptionalErrorResult()) {
errorResult = error->map(substComponentType);
}
auto signature = isPolymorphic() ? getInvocationGenericSignature()
: CanGenericSignature();
return SILFunctionType::get(signature,
getExtInfo(),
getCoroutineKind(),
getCalleeConvention(),
params, yields, results, errorResult,
SubstitutionMap(),
SubstitutionMap(),
mutableThis->getASTContext(),
getWitnessMethodConformanceOrInvalid());
}
CanType SILParameterInfo::getArgumentType(SILModule &M,
const SILFunctionType *t,
TypeExpansionContext context) const {
// TODO: We should always require a function type.
if (t)
return t
->substInterfaceType(
M, SILType::getPrimitiveAddressType(getInterfaceType()), context)
.getASTType();
return getInterfaceType();
}
CanType SILResultInfo::getReturnValueType(SILModule &M,
const SILFunctionType *t,
TypeExpansionContext context) const {
// TODO: We should always require a function type.
if (t)
return t
->substInterfaceType(
M, SILType::getPrimitiveAddressType(getInterfaceType()), context)
.getASTType();
return getInterfaceType();
}
SILType
SILFunctionType::getDirectFormalResultsType(SILModule &M,
TypeExpansionContext context) {
CanType type;
if (getNumDirectFormalResults() == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (getNumDirectFormalResults() == 1) {
type = getSingleDirectFormalResult().getReturnValueType(M, this, context);
} else {
auto &cache = getMutableFormalResultsCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getResults())
if (!result.isFormalIndirect())
elts.push_back(result.getReturnValueType(M, this, context));
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getAllResultsInterfaceType() {
CanType type;
if (getNumResults() == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (getNumResults() == 1) {
type = getResults()[0].getInterfaceType();
} else {
auto &cache = getMutableAllResultsCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getResults())
elts.push_back(result.getInterfaceType());
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getAllResultsSubstType(SILModule &M,
TypeExpansionContext context) {
return substInterfaceType(M, getAllResultsInterfaceType(), context);
}
SILType SILFunctionType::getFormalCSemanticResult(SILModule &M) {
assert(getLanguage() == SILFunctionLanguage::C);
assert(getNumResults() <= 1);
return getDirectFormalResultsType(M, TypeExpansionContext::minimal());
}
CanType
SILFunctionType::getSelfInstanceType(SILModule &M,
TypeExpansionContext context) const {
auto selfTy = getSelfParameter().getArgumentType(M, this, context);
// If this is a static method, get the instance type.
if (auto metaTy = dyn_cast<AnyMetatypeType>(selfTy))
return metaTy.getInstanceType();
return selfTy;
}
ClassDecl *
SILFunctionType::getWitnessMethodClass(SILModule &M,
TypeExpansionContext context) const {
// TODO: When witnesses use substituted types, we'd get this from the
// substitution map.
auto selfTy = getSelfInstanceType(M, context);
auto genericSig = getSubstGenericSignature();
if (auto paramTy = dyn_cast<GenericTypeParamType>(selfTy)) {
assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0);
auto superclass = genericSig->getSuperclassBound(paramTy);
if (superclass)
return superclass->getClassOrBoundGenericClass();
}
return nullptr;
}
IndexSubset *
SILFunctionType::getDifferentiabilityParameterIndices() {
assert(isDifferentiable() && "Must be a differentiable function");
SmallVector<unsigned, 8> paramIndices;
for (auto paramAndIndex : enumerate(getParameters()))
if (!paramAndIndex.value().hasOption(SILParameterInfo::NotDifferentiable))
paramIndices.push_back(paramAndIndex.index());
return IndexSubset::get(getASTContext(), getNumParameters(), paramIndices);
}
IndexSubset *SILFunctionType::getDifferentiabilityResultIndices() {
assert(isDifferentiable() && "Must be a differentiable function");
SmallVector<unsigned, 8> resultIndices;
// Check formal results.
for (auto resultAndIndex : enumerate(getResults()))
if (!resultAndIndex.value().hasOption(SILResultInfo::NotDifferentiable))
resultIndices.push_back(resultAndIndex.index());
auto numSemanticResults = getNumResults();
// Check semantic results (`inout`) parameters.
for (auto resultParamAndIndex : enumerate(getAutoDiffSemanticResultsParameters()))
// Currently, an `inout` parameter can either be:
// 1. Both a differentiability parameter and a differentiability result.
// 2. `@noDerivative`: neither a differentiability parameter nor a
// differentiability result.
// However, there is no way to represent an `inout` parameter that:
// 3. Is a differentiability result but not a differentiability parameter.
// 4. Is a differentiability parameter but not a differentiability result.
// This case is not currently expressible and does not yet have clear use
// cases, so supporting it is a non-goal.
//
// See TF-1305 for solution ideas. For now, `@noDerivative` `inout`
// parameters are not treated as differentiability results.
if (!resultParamAndIndex.value().hasOption(
SILParameterInfo::NotDifferentiable))
resultIndices.push_back(getNumResults() + resultParamAndIndex.index());
numSemanticResults += getNumAutoDiffSemanticResultsParameters();
return IndexSubset::get(getASTContext(), numSemanticResults, resultIndices);
}
CanSILFunctionType SILFunctionType::getDifferentiableComponentType(
NormalDifferentiableFunctionTypeComponent component, SILModule &module) {
assert(getDifferentiabilityKind() == DifferentiabilityKind::Reverse &&
"Must be a `@differentiable(reverse)` function");
auto originalFnTy = getWithoutDifferentiability();
if (auto derivativeKind = component.getAsDerivativeFunctionKind()) {
return originalFnTy->getAutoDiffDerivativeFunctionType(
getDifferentiabilityParameterIndices(),
getDifferentiabilityResultIndices(), *derivativeKind, module.Types,
LookUpConformanceInModule(module.getSwiftModule()));
}
return originalFnTy;
}
CanSILFunctionType SILFunctionType::getLinearComponentType(
LinearDifferentiableFunctionTypeComponent component, SILModule &module) {
assert(getDifferentiabilityKind() == DifferentiabilityKind::Linear &&
"Must be a `@differentiable(linear)` function");
auto originalFnTy = getWithoutDifferentiability();
switch (component) {
case LinearDifferentiableFunctionTypeComponent::Original:
return originalFnTy;
case LinearDifferentiableFunctionTypeComponent::Transpose:
return originalFnTy->getAutoDiffTransposeFunctionType(
getDifferentiabilityParameterIndices(), module.Types,
LookUpConformanceInModule(module.getSwiftModule()));
}
}
CanSILFunctionType
SILFunctionType::getWithDifferentiability(DifferentiabilityKind kind,
IndexSubset *parameterIndices,
IndexSubset *resultIndices) {
assert(kind != DifferentiabilityKind::NonDifferentiable &&
"Differentiability kind must be normal or linear");
SmallVector<SILParameterInfo, 8> newParameters;
for (auto paramAndIndex : enumerate(getParameters())) {
auto param = paramAndIndex.value();
unsigned index = paramAndIndex.index();
newParameters.push_back(index < parameterIndices->getCapacity() &&
parameterIndices->contains(index)
? param - SILParameterInfo::NotDifferentiable
: param | SILParameterInfo::NotDifferentiable);
}
SmallVector<SILResultInfo, 8> newResults;
for (auto resultAndIndex : enumerate(getResults())) {
auto result = resultAndIndex.value();
unsigned index = resultAndIndex.index();
newResults.push_back(index < resultIndices->getCapacity() &&
resultIndices->contains(index)
? result - SILResultInfo::NotDifferentiable
: result | SILResultInfo::NotDifferentiable);
}
auto newExtInfo =
getExtInfo().intoBuilder().withDifferentiabilityKind(kind).build();
return get(getInvocationGenericSignature(), newExtInfo, getCoroutineKind(),
getCalleeConvention(), newParameters, getYields(), newResults,
getOptionalErrorResult(), getPatternSubstitutions(),
getInvocationSubstitutions(), getASTContext(),
getWitnessMethodConformanceOrInvalid());
}
CanSILFunctionType SILFunctionType::getWithoutDifferentiability() {
if (!isDifferentiable())
return CanSILFunctionType(this);
auto nondiffExtInfo =
getExtInfo()
.intoBuilder()
.withDifferentiabilityKind(DifferentiabilityKind::NonDifferentiable)
.build();
SmallVector<SILParameterInfo, 8> newParams;
for (SILParameterInfo param : getParameters())
newParams.push_back(param - SILParameterInfo::NotDifferentiable);
SmallVector<SILResultInfo, 8> newResults;
for (SILResultInfo result : getResults())
newResults.push_back(result - SILResultInfo::NotDifferentiable);
return SILFunctionType::get(
getInvocationGenericSignature(), nondiffExtInfo, getCoroutineKind(),
getCalleeConvention(), newParams, getYields(), newResults,
getOptionalErrorResult(), getPatternSubstitutions(),
getInvocationSubstitutions(), getASTContext());
}
/// Collects the differentiability parameters of the given original function
/// type in `diffParams`.
static void
getDifferentiabilityParameters(SILFunctionType *originalFnTy,
IndexSubset *parameterIndices,
SmallVectorImpl<SILParameterInfo> &diffParams) {
// Returns true if `index` is a differentiability parameter index.
auto isDiffParamIndex = [&](unsigned index) -> bool {
return index < parameterIndices->getCapacity() &&
parameterIndices->contains(index);
};
// Calculate differentiability parameter infos.
for (auto valueAndIndex : enumerate(originalFnTy->getParameters()))
if (isDiffParamIndex(valueAndIndex.index()))
diffParams.push_back(valueAndIndex.value());
}
static CanGenericSignature buildDifferentiableGenericSignature(CanGenericSignature sig,
CanType tanType,
CanType origTypeOfAbstraction) {
if (!sig)
return sig;
llvm::DenseSet<CanType> types;
auto &ctx = tanType->getASTContext();
(void) tanType.findIf([&](Type t) -> bool {
if (auto *dmt = t->getAs<DependentMemberType>()) {
if (dmt->getName() == ctx.Id_TangentVector)
types.insert(dmt->getBase()->getCanonicalType());
}
return false;
});
SmallVector<Requirement, 2> reqs;
auto *proto = ctx.getProtocol(KnownProtocolKind::Differentiable);
assert(proto != nullptr);
for (auto type : types) {
if (!sig->requiresProtocol(type, proto)) {
reqs.push_back(Requirement(RequirementKind::Conformance, type,
proto->getDeclaredInterfaceType()));
}
}
if (origTypeOfAbstraction) {
(void) origTypeOfAbstraction.findIf([&](Type t) -> bool {
if (auto *at = t->getAs<ArchetypeType>()) {
auto interfaceTy = at->getInterfaceType();
auto genericParams = sig.getGenericParams();
// The GSB used to drop requirements which reference non-existent
// generic parameters, whereas the RequirementMachine asserts now.
// Filter these requirements out explicitly to preserve the old
// behavior.
if (std::find_if(genericParams.begin(), genericParams.end(),
[interfaceTy](CanGenericTypeParamType t) -> bool {
return t->isEqual(interfaceTy->getRootGenericParam());
}) != genericParams.end()) {
types.insert(interfaceTy->getCanonicalType());
for (auto *proto : at->getConformsTo()) {
reqs.push_back(Requirement(RequirementKind::Conformance,
interfaceTy,
proto->getDeclaredInterfaceType()));
}
// The GSB would add conformance requirements if a nested type
// requirement involving a resolved DependentMemberType was added;
// eg, if you start with <T> and add T.[P]A == Int, it would also
// add the conformance requirement T : P.
//
// This was not an intended behavior on the part of the GSB, and the
// logic here is a complete mess, so just simulate the old behavior
// here.
auto parentTy = interfaceTy;
while (parentTy) {
if (auto memberTy = parentTy->getAs<DependentMemberType>()) {
parentTy = memberTy->getBase();
if (auto *assocTy = memberTy->getAssocType()) {
reqs.push_back(Requirement(RequirementKind::Conformance,
parentTy,
assocTy->getProtocol()->getDeclaredInterfaceType()));
}
} else
parentTy = Type();
}
}
}
return false;
});
}
return buildGenericSignature(ctx, sig, {}, reqs, /*allowInverses=*/false)
.getCanonicalSignature();
}
/// Given an original type, computes its tangent type for the purpose of
/// building a linear map using this type. When the original type is an
/// archetype or contains a type parameter, appends a new generic parameter and
/// a corresponding replacement type to the given containers.
static CanType getAutoDiffTangentTypeForLinearMap(
Type originalType,
LookupConformanceFn lookupConformance,
SmallVectorImpl<GenericTypeParamType *> &substGenericParams,
SmallVectorImpl<Type> &substReplacements,
ASTContext &context
) {
auto maybeTanType = originalType->getAutoDiffTangentSpace(lookupConformance);
assert(maybeTanType && "Type does not have a tangent space?");
auto tanType = maybeTanType->getCanonicalType();
// If concrete, the tangent type is concrete.
if (!tanType->hasArchetype() && !tanType->hasTypeParameter())
return tanType;
// Otherwise, the tangent type is a new generic parameter substituted for the
// tangent type.
auto gpIndex = substGenericParams.size();
auto gpType = CanGenericTypeParamType::get(/*isParameterPack*/ false,
0, gpIndex, context);
substGenericParams.push_back(gpType);
substReplacements.push_back(tanType);
return gpType;
}
/// Returns the differential type for the given original function type,
/// parameter indices, and result index.
static CanSILFunctionType getAutoDiffDifferentialType(
SILFunctionType *originalFnTy, IndexSubset *parameterIndices,
IndexSubset *resultIndices, LookupConformanceFn lookupConformance,
CanType origTypeOfAbstraction,
TypeConverter &TC) {
// Given the tangent type and the corresponding original parameter's
// convention, returns the tangent parameter's convention.
auto getTangentParameterConvention =
[&](CanType tanType,
ParameterConvention origParamConv) -> ParameterConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
// When the tangent type is address only, we must ensure that the tangent
// parameter's convention is indirect.
if (tl.isAddressOnly() && !isIndirectFormalParameter(origParamConv)) {
switch (origParamConv) {
case ParameterConvention::Direct_Guaranteed:
return ParameterConvention::Indirect_In_Guaranteed;
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Unowned:
return ParameterConvention::Indirect_In;
default:
llvm_unreachable("unhandled parameter convention");
}
}
return origParamConv;
};
// Given the tangent type and the corresponding original result's convention,
// returns the tangent result's convention.
auto getTangentResultConvention =
[&](CanType tanType,
ResultConvention origResConv) -> ResultConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
// When the tangent type is address only, we must ensure that the tangent
// result's convention is indirect.
if (tl.isAddressOnly() && !isIndirectFormalResult(origResConv)) {
switch (origResConv) {
case ResultConvention::Unowned:
case ResultConvention::Owned:
return ResultConvention::Indirect;
default:
llvm_unreachable("unhandled result convention");
}
}
return origResConv;
};
auto &ctx = originalFnTy->getASTContext();
SmallVector<GenericTypeParamType *, 4> substGenericParams;
SmallVector<Requirement, 4> substRequirements;
SmallVector<Type, 4> substReplacements;
SmallVector<ProtocolConformanceRef, 4> substConformances;
SmallVector<SILResultInfo, 2> originalResults;
autodiff::getSemanticResults(originalFnTy, parameterIndices, originalResults);
SmallVector<SILParameterInfo, 4> diffParams;
getDifferentiabilityParameters(originalFnTy, parameterIndices, diffParams);
SmallVector<SILParameterInfo, 8> differentialParams;
for (auto ¶m : diffParams) {
auto paramTanType = getAutoDiffTangentTypeForLinearMap(
param.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto paramConv = getTangentParameterConvention(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
param.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
param.getConvention());
differentialParams.push_back({paramTanType, paramConv});
}
SmallVector<SILResultInfo, 1> differentialResults;
for (auto resultIndex : resultIndices->getIndices()) {
// Handle formal original result.
if (resultIndex < originalFnTy->getNumResults()) {
auto &result = originalResults[resultIndex];
auto resultTanType = getAutoDiffTangentTypeForLinearMap(
result.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto resultConv = getTangentResultConvention(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
result.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
result.getConvention());
differentialResults.push_back({resultTanType, resultConv});
continue;
}
// Handle original semantic result parameters.
auto resultParamIndex = resultIndex - originalFnTy->getNumResults();
auto resultParamIt = std::next(
originalFnTy->getAutoDiffSemanticResultsParameters().begin(),
resultParamIndex);
auto paramIndex =
std::distance(originalFnTy->getParameters().begin(), &*resultParamIt);
// If the original semantic result parameter is a differentiability
// parameter, then it already has a corresponding differential
// parameter. Skip adding a corresponding differential result.
if (parameterIndices->contains(paramIndex))
continue;
auto resultParam = originalFnTy->getParameters()[paramIndex];
auto resultParamTanType = getAutoDiffTangentTypeForLinearMap(
resultParam.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
differentialResults.emplace_back(resultParamTanType,
ResultConvention::Indirect);
}
SubstitutionMap substitutions;
if (!substGenericParams.empty()) {
auto genericSig =
GenericSignature::get(substGenericParams, substRequirements)
.getCanonicalSignature();
substitutions =
SubstitutionMap::get(genericSig, llvm::ArrayRef(substReplacements),
llvm::ArrayRef(substConformances));
}
return SILFunctionType::get(
GenericSignature(), SILFunctionType::ExtInfo(), SILCoroutineKind::None,
ParameterConvention::Direct_Guaranteed, differentialParams, {},
differentialResults, std::nullopt, substitutions,
/*invocationSubstitutions*/ SubstitutionMap(), ctx);
}
/// Returns the pullback type for the given original function type, parameter
/// indices, and result index.
static CanSILFunctionType getAutoDiffPullbackType(
SILFunctionType *originalFnTy, IndexSubset *parameterIndices,
IndexSubset *resultIndices, LookupConformanceFn lookupConformance,
CanType origTypeOfAbstraction, TypeConverter &TC) {
auto &ctx = originalFnTy->getASTContext();
SmallVector<GenericTypeParamType *, 4> substGenericParams;
SmallVector<Requirement, 4> substRequirements;
SmallVector<Type, 4> substReplacements;
SmallVector<ProtocolConformanceRef, 4> substConformances;
SmallVector<SILResultInfo, 2> originalResults;
autodiff::getSemanticResults(originalFnTy, parameterIndices, originalResults);
// Given a type, returns its formal SIL parameter info.
auto getTangentParameterConventionForOriginalResult =
[&](CanType tanType,
ResultConvention origResConv) -> ParameterConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
ParameterConvention conv;
switch (origResConv) {
case ResultConvention::Unowned:
case ResultConvention::UnownedInnerPointer:
case ResultConvention::Owned:
case ResultConvention::Autoreleased:
if (tl.isAddressOnly()) {
conv = ParameterConvention::Indirect_In_Guaranteed;
} else {
conv = tl.isTrivial() ? ParameterConvention::Direct_Unowned
: ParameterConvention::Direct_Guaranteed;
}
break;
case ResultConvention::Pack:
conv = ParameterConvention::Pack_Guaranteed;
break;
case ResultConvention::Indirect:
conv = ParameterConvention::Indirect_In_Guaranteed;
break;
}
return conv;
};
// Given a type, returns its formal SIL result info.
auto getTangentResultConventionForOriginalParameter =
[&](CanType tanType,
ParameterConvention origParamConv) -> ResultConvention {
auto sig = buildDifferentiableGenericSignature(
originalFnTy->getSubstGenericSignature(), tanType, origTypeOfAbstraction);
tanType = tanType->getReducedType(sig);
AbstractionPattern pattern(sig, tanType);
auto &tl =
TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal());
ResultConvention conv;
switch (origParamConv) {
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Direct_Unowned:
if (tl.isAddressOnly()) {
conv = ResultConvention::Indirect;
} else {
conv = tl.isTrivial() ? ResultConvention::Unowned
: ResultConvention::Owned;
}
break;
case ParameterConvention::Pack_Owned:
case ParameterConvention::Pack_Guaranteed:
case ParameterConvention::Pack_Inout:
conv = ResultConvention::Pack;
break;
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Indirect_InoutAliasable:
conv = ResultConvention::Indirect;
break;
}
return conv;
};
// Collect pullback parameters.
SmallVector<SILParameterInfo, 1> pullbackParams;
for (auto resultIndex : resultIndices->getIndices()) {
// Handle formal original result.
if (resultIndex < originalFnTy->getNumResults()) {
auto &origRes = originalResults[resultIndex];
auto resultTanType = getAutoDiffTangentTypeForLinearMap(
origRes.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto paramConv = getTangentParameterConventionForOriginalResult(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
origRes.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
origRes.getConvention());
pullbackParams.emplace_back(resultTanType, paramConv);
continue;
}
// Handle original semantic result parameters.
auto resultParamIndex = resultIndex - originalFnTy->getNumResults();
auto resultParamIt = std::next(
originalFnTy->getAutoDiffSemanticResultsParameters().begin(),
resultParamIndex);
auto paramIndex =
std::distance(originalFnTy->getParameters().begin(), &*resultParamIt);
auto resultParam = originalFnTy->getParameters()[paramIndex];
// The pullback parameter convention depends on whether the original `inout`
// parameter is a differentiability parameter.
// - If yes, the pullback parameter convention is `@inout`.
// - If no, the pullback parameter convention is `@in_guaranteed`.
auto resultParamTanType = getAutoDiffTangentTypeForLinearMap(
resultParam.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
ParameterConvention paramTanConvention = resultParam.getConvention();
if (!parameterIndices->contains(paramIndex))
paramTanConvention = ParameterConvention::Indirect_In_Guaranteed;
pullbackParams.emplace_back(resultParamTanType, paramTanConvention);
}
// Collect pullback results.
SmallVector<SILParameterInfo, 4> diffParams;
getDifferentiabilityParameters(originalFnTy, parameterIndices, diffParams);
SmallVector<SILResultInfo, 8> pullbackResults;
for (auto ¶m : diffParams) {
// Skip semantic result parameters, which semantically behave as original
// results and always appear as pullback parameters.
if (param.isAutoDiffSemanticResult())
continue;
auto paramTanType = getAutoDiffTangentTypeForLinearMap(
param.getInterfaceType(), lookupConformance,
substGenericParams, substReplacements, ctx);
auto resultTanConvention = getTangentResultConventionForOriginalParameter(
// FIXME(rdar://82549134): Use `resultTanType` to compute it instead.
param.getInterfaceType()
->getAutoDiffTangentSpace(lookupConformance)
->getCanonicalType(),
param.getConvention());
pullbackResults.push_back({paramTanType, resultTanConvention});
}
SubstitutionMap substitutions;
if (!substGenericParams.empty()) {
auto genericSig =
GenericSignature::get(substGenericParams, substRequirements)
.getCanonicalSignature();
substitutions =
SubstitutionMap::get(genericSig, llvm::ArrayRef(substReplacements),
llvm::ArrayRef(substConformances));
}
return SILFunctionType::get(
GenericSignature(), SILFunctionType::ExtInfo(),
originalFnTy->getCoroutineKind(), ParameterConvention::Direct_Guaranteed,
pullbackParams, {}, pullbackResults, std::nullopt, substitutions,
/*invocationSubstitutions*/ SubstitutionMap(), ctx);
}
/// Constrains the `original` function type according to differentiability
/// requirements:
/// - All differentiability parameters are constrained to conform to
/// `Differentiable`.
/// - The invocation generic signature is replaced by the
/// `constrainedInvocationGenSig` argument.
static SILFunctionType *getConstrainedAutoDiffOriginalFunctionType(
SILFunctionType *original, IndexSubset *parameterIndices, IndexSubset *resultIndices,
LookupConformanceFn lookupConformance,
CanGenericSignature constrainedInvocationGenSig) {
auto originalInvocationGenSig = original->getInvocationGenericSignature();
if (!originalInvocationGenSig) {
assert(!constrainedInvocationGenSig ||
constrainedInvocationGenSig->areAllParamsConcrete() &&
"derivative function cannot have invocation generic signature "
"when original function doesn't");
if (auto patternSig = original->getPatternGenericSignature()) {
auto constrainedPatternSig =
autodiff::getConstrainedDerivativeGenericSignature(
original, parameterIndices, resultIndices,
patternSig, lookupConformance).getCanonicalSignature();
auto constrainedPatternSubs =
SubstitutionMap::get(constrainedPatternSig,
QuerySubstitutionMap{original->getPatternSubstitutions()},
lookupConformance);
return SILFunctionType::get(GenericSignature(),
original->getExtInfo(), original->getCoroutineKind(),
original->getCalleeConvention(),
original->getParameters(), original->getYields(),
original->getResults(), original->getOptionalErrorResult(),
constrainedPatternSubs,
/*invocationSubstitutions*/ SubstitutionMap(), original->getASTContext(),
original->getWitnessMethodConformanceOrInvalid());
}
return original;
}
assert(!original->getPatternSubstitutions() &&
"cannot constrain substituted function type");
if (!constrainedInvocationGenSig)
constrainedInvocationGenSig = originalInvocationGenSig;
if (!constrainedInvocationGenSig)
return original;
constrainedInvocationGenSig =
autodiff::getConstrainedDerivativeGenericSignature(
original, parameterIndices, resultIndices,
constrainedInvocationGenSig,
lookupConformance).getCanonicalSignature();
SmallVector<SILParameterInfo, 4> newParameters;
newParameters.reserve(original->getNumParameters());
for (auto ¶m : original->getParameters()) {
newParameters.push_back(
param.getWithInterfaceType(param.getInterfaceType()->getReducedType(
constrainedInvocationGenSig)));
}
SmallVector<SILResultInfo, 4> newResults;
newResults.reserve(original->getNumResults());
for (auto &result : original->getResults()) {
newResults.push_back(
result.getWithInterfaceType(result.getInterfaceType()->getReducedType(
constrainedInvocationGenSig)));
}
return SILFunctionType::get(
constrainedInvocationGenSig->areAllParamsConcrete()
? GenericSignature()
: constrainedInvocationGenSig,
original->getExtInfo(), original->getCoroutineKind(),
original->getCalleeConvention(), newParameters, original->getYields(),
newResults, original->getOptionalErrorResult(),
original->getPatternSubstitutions(),
/*invocationSubstitutions*/ SubstitutionMap(), original->getASTContext(),
original->getWitnessMethodConformanceOrInvalid());
}
CanSILFunctionType SILFunctionType::getAutoDiffDerivativeFunctionType(
IndexSubset *parameterIndices, IndexSubset *resultIndices,
AutoDiffDerivativeFunctionKind kind, TypeConverter &TC,
LookupConformanceFn lookupConformance,
CanGenericSignature derivativeFnInvocationGenSig,
bool isReabstractionThunk,
CanType origTypeOfAbstraction) {
assert(parameterIndices);
assert(!parameterIndices->isEmpty() && "Parameter indices must not be empty");
assert(resultIndices);
assert(!resultIndices->isEmpty() && "Result indices must not be empty");
auto &ctx = getASTContext();
// Look up result in cache.
SILAutoDiffDerivativeFunctionKey key{this,
parameterIndices,
resultIndices,
kind,
derivativeFnInvocationGenSig,
isReabstractionThunk};
auto insertion =
ctx.SILAutoDiffDerivativeFunctions.try_emplace(key, CanSILFunctionType());
auto &cachedResult = insertion.first->getSecond();
if (!insertion.second)
return cachedResult;
SILFunctionType *constrainedOriginalFnTy =
getConstrainedAutoDiffOriginalFunctionType(this, parameterIndices, resultIndices,
lookupConformance,
derivativeFnInvocationGenSig);
// Compute closure type.
CanSILFunctionType closureType;
switch (kind) {
case AutoDiffDerivativeFunctionKind::JVP:
closureType =
getAutoDiffDifferentialType(constrainedOriginalFnTy, parameterIndices,
resultIndices, lookupConformance,
origTypeOfAbstraction, TC);
break;
case AutoDiffDerivativeFunctionKind::VJP:
closureType =
getAutoDiffPullbackType(constrainedOriginalFnTy, parameterIndices,
resultIndices, lookupConformance,
origTypeOfAbstraction, TC);
break;
}
// Compute the derivative function parameters.
SmallVector<SILParameterInfo, 4> newParameters;
newParameters.reserve(constrainedOriginalFnTy->getNumParameters());
for (auto ¶m : constrainedOriginalFnTy->getParameters()) {
newParameters.push_back(param);
}
// Reabstraction thunks have a function-typed parameter (the function to
// reabstract) as their last parameter. Reabstraction thunk JVPs/VJPs have a
// `@differentiable` function-typed last parameter instead.
if (isReabstractionThunk) {
assert(!parameterIndices->contains(getNumParameters() - 1) &&
"Function-typed parameter should not be wrt");
auto fnParam = newParameters.back();
auto fnParamType = dyn_cast<SILFunctionType>(fnParam.getInterfaceType());
assert(fnParamType);
auto diffFnType = fnParamType->getWithDifferentiability(
DifferentiabilityKind::Reverse, parameterIndices, resultIndices);
newParameters.back() = fnParam.getWithInterfaceType(diffFnType);
}
// Compute the derivative function results.
SmallVector<SILResultInfo, 4> newResults;
newResults.reserve(getNumResults() + 1);
for (auto &result : constrainedOriginalFnTy->getResults()) {
newResults.push_back(result);
}
newResults.push_back({closureType, ResultConvention::Owned});
// Compute the derivative function ExtInfo.
// If original function is `@convention(c)`, the derivative function should
// have `@convention(thin)`. IRGen does not support `@convention(c)` functions
// with multiple results.
auto extInfo = constrainedOriginalFnTy->getExtInfo();
if (getRepresentation() == SILFunctionTypeRepresentation::CFunctionPointer)
extInfo = extInfo.withRepresentation(SILFunctionTypeRepresentation::Thin);
// Put everything together to get the derivative function type. Then, store in
// cache and return.
cachedResult = SILFunctionType::get(
constrainedOriginalFnTy->getInvocationGenericSignature(), extInfo,
constrainedOriginalFnTy->getCoroutineKind(),
constrainedOriginalFnTy->getCalleeConvention(), newParameters,
constrainedOriginalFnTy->getYields(), newResults,
constrainedOriginalFnTy->getOptionalErrorResult(),
constrainedOriginalFnTy->getPatternSubstitutions(),
/*invocationSubstitutions*/ SubstitutionMap(),
constrainedOriginalFnTy->getASTContext(),
constrainedOriginalFnTy->getWitnessMethodConformanceOrInvalid());
return cachedResult;
}
CanSILFunctionType SILFunctionType::getAutoDiffTransposeFunctionType(
IndexSubset *parameterIndices, Lowering::TypeConverter &TC,
LookupConformanceFn lookupConformance,
CanGenericSignature transposeFnGenSig) {
auto &ctx = getASTContext();
// Get the "constrained" transpose function generic signature.
if (!transposeFnGenSig)
transposeFnGenSig = getSubstGenericSignature();
transposeFnGenSig = autodiff::getConstrainedDerivativeGenericSignature(
this, parameterIndices, IndexSubset::getDefault(ctx, 0),
transposeFnGenSig,
lookupConformance, /*isLinear*/ true)
.getCanonicalSignature();
// Given a type, returns its formal SIL parameter info.
auto getParameterInfoForOriginalResult =
[&](const SILResultInfo &result) -> SILParameterInfo {
AbstractionPattern pattern(transposeFnGenSig, result.getInterfaceType());
auto &tl = TC.getTypeLowering(pattern, result.getInterfaceType(),
TypeExpansionContext::minimal());
ParameterConvention newConv;
switch (result.getConvention()) {
case ResultConvention::Owned:
case ResultConvention::Autoreleased:
newConv = tl.isTrivial() ? ParameterConvention::Direct_Unowned
: ParameterConvention::Direct_Guaranteed;
break;
case ResultConvention::Unowned:
case ResultConvention::UnownedInnerPointer:
newConv = ParameterConvention::Direct_Unowned;
break;
case ResultConvention::Pack:
newConv = ParameterConvention::Pack_Guaranteed;
break;
case ResultConvention::Indirect:
newConv = ParameterConvention::Indirect_In_Guaranteed;
break;
}
return {result.getInterfaceType(), newConv};
};
// Given a type, returns its formal SIL result info.
auto getResultInfoForOriginalParameter =
[&](const SILParameterInfo ¶m) -> SILResultInfo {
AbstractionPattern pattern(transposeFnGenSig, param.getInterfaceType());
auto &tl = TC.getTypeLowering(pattern, param.getInterfaceType(),
TypeExpansionContext::minimal());
ResultConvention newConv;
switch (param.getConvention()) {
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Direct_Unowned:
newConv =
tl.isTrivial() ? ResultConvention::Unowned : ResultConvention::Owned;
break;
case ParameterConvention::Pack_Owned:
case ParameterConvention::Pack_Guaranteed:
case ParameterConvention::Pack_Inout:
newConv = ResultConvention::Pack;
break;
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Indirect_InoutAliasable:
newConv = ResultConvention::Indirect;
break;
}
return {param.getInterfaceType(), newConv};
};
SmallVector<SILParameterInfo, 4> newParameters;
SmallVector<SILResultInfo, 4> newResults;
for (auto pair : llvm::enumerate(getParameters())) {
auto index = pair.index();
auto param = pair.value();
if (parameterIndices->contains(index))
newResults.push_back(getResultInfoForOriginalParameter(param));
else
newParameters.push_back(param);
}
for (auto &res : getResults())
newParameters.push_back(getParameterInfoForOriginalResult(res));
return SILFunctionType::get(
getInvocationGenericSignature(), getExtInfo(), getCoroutineKind(),
getCalleeConvention(), newParameters, getYields(), newResults,
getOptionalErrorResult(), getPatternSubstitutions(),
/*invocationSubstitutions*/ {}, getASTContext());
}
static CanType getKnownType(std::optional<CanType> &cacheSlot, ASTContext &C,
StringRef moduleName, StringRef typeName) {
if (!cacheSlot) {
cacheSlot = ([&] {
ModuleDecl *mod = C.getLoadedModule(C.getIdentifier(moduleName));
if (!mod)
return CanType();
// Do a general qualified lookup instead of a direct lookupValue because
// some of the types we want are reexported through overlays and
// lookupValue would only give us types actually declared in the overlays
// themselves.
SmallVector<ValueDecl *, 2> decls;
mod->lookupQualified(mod, DeclNameRef(C.getIdentifier(typeName)),
SourceLoc(), NL_QualifiedDefault, decls);
if (decls.size() != 1)
return CanType();
const auto *typeDecl = dyn_cast<TypeDecl>(decls.front());
if (!typeDecl)
return CanType();
return typeDecl->getDeclaredInterfaceType()->getCanonicalType();
})();
}
CanType t = *cacheSlot;
// It is possible that we won't find a bridging type (e.g. String) when we're
// parsing the stdlib itself.
if (t) {
LLVM_DEBUG(llvm::dbgs() << "Bridging type " << moduleName << '.' << typeName
<< " mapped to ";
if (t)
t->print(llvm::dbgs());
else
llvm::dbgs() << "<null>";
llvm::dbgs() << '\n');
}
return t;
}
#define BRIDGING_KNOWN_TYPE(BridgedModule,BridgedType) \
CanType TypeConverter::get##BridgedType##Type() { \
return getKnownType(BridgedType##Ty, Context, \
#BridgedModule, #BridgedType); \
}
#include "swift/SIL/BridgedTypes.def"
/// Adjust a function type to have a slightly different type.
CanAnyFunctionType
Lowering::adjustFunctionType(CanAnyFunctionType t,
AnyFunctionType::ExtInfo extInfo) {
if (t->getExtInfo().isEqualTo(extInfo, useClangTypes(t)))
return t;
return CanAnyFunctionType(t->withExtInfo(extInfo));
}
/// Adjust a function type to have a slightly different type.
CanSILFunctionType
Lowering::adjustFunctionType(CanSILFunctionType type,
SILFunctionType::ExtInfo extInfo,
ParameterConvention callee,
ProtocolConformanceRef witnessMethodConformance) {
if (type->getExtInfo().isEqualTo(extInfo, useClangTypes(type)) &&
type->getCalleeConvention() == callee &&
type->getWitnessMethodConformanceOrInvalid() == witnessMethodConformance)
return type;
return SILFunctionType::get(type->getInvocationGenericSignature(),
extInfo, type->getCoroutineKind(), callee,
type->getParameters(), type->getYields(),
type->getResults(),
type->getOptionalErrorResult(),
type->getPatternSubstitutions(),
type->getInvocationSubstitutions(),
type->getASTContext(),
witnessMethodConformance);
}
CanSILFunctionType
SILFunctionType::getWithRepresentation(Representation repr) {
return getWithExtInfo(getExtInfo().withRepresentation(repr));
}
CanSILFunctionType SILFunctionType::getWithExtInfo(ExtInfo newExt) {
auto oldExt = getExtInfo();
if (newExt.isEqualTo(oldExt, useClangTypes(this)))
return CanSILFunctionType(this);
auto calleeConvention =
(newExt.hasContext()
? (oldExt.hasContext()
? getCalleeConvention()
: Lowering::DefaultThickCalleeConvention)
: ParameterConvention::Direct_Unowned);
return get(getInvocationGenericSignature(), newExt, getCoroutineKind(),
calleeConvention, getParameters(), getYields(), getResults(),
getOptionalErrorResult(), getPatternSubstitutions(),
getInvocationSubstitutions(), getASTContext(),
getWitnessMethodConformanceOrInvalid());
}
namespace {
enum class ConventionsKind : uint8_t {
Default = 0,
DefaultBlock = 1,
ObjCMethod = 2,
CFunctionType = 3,
CFunction = 4,
ObjCSelectorFamily = 5,
Deallocator = 6,
Capture = 7,
CXXMethod = 8,
};
class Conventions {
ConventionsKind kind;
protected:
virtual ~Conventions() = default;
public:
Conventions(ConventionsKind k) : kind(k) {}
ConventionsKind getKind() const { return kind; }
virtual ParameterConvention
getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const = 0;
virtual ParameterConvention
getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const = 0;
virtual ParameterConvention getCallee() const = 0;
virtual ResultConvention getResult(const TypeLowering &resultTL) const = 0;
virtual ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const = 0;
virtual ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const = 0;
virtual ParameterConvention getPackParameter(unsigned index) const = 0;
// Helpers that branch based on a value ownership.
ParameterConvention getIndirect(ValueOwnership ownership, bool forSelf,
unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const {
switch (ownership) {
case ValueOwnership::Default:
if (forSelf)
return getIndirectSelfParameter(type);
return getIndirectParameter(index, type, substTL);
case ValueOwnership::InOut:
return ParameterConvention::Indirect_Inout;
case ValueOwnership::Shared:
return ParameterConvention::Indirect_In_Guaranteed;
case ValueOwnership::Owned:
return ParameterConvention::Indirect_In;
}
llvm_unreachable("unhandled ownership");
}
ParameterConvention getPack(ValueOwnership ownership,
unsigned index) const {
switch (ownership) {
case ValueOwnership::Default:
return getPackParameter(index);
case ValueOwnership::InOut:
return ParameterConvention::Pack_Inout;
case ValueOwnership::Shared:
return ParameterConvention::Pack_Guaranteed;
case ValueOwnership::Owned:
return ParameterConvention::Pack_Owned;
}
llvm_unreachable("unhandled ownership");
}
ParameterConvention getDirect(ValueOwnership ownership, bool forSelf,
unsigned index, const AbstractionPattern &type,
const TypeLowering &substTL) const {
switch (ownership) {
case ValueOwnership::Default: {
if (forSelf)
return getDirectSelfParameter(type);
auto convention = getDirectParameter(index, type, substTL);
// Nonescaping closures can only be borrowed across calls currently.
if (convention == ParameterConvention::Direct_Owned) {
if (auto fnTy = substTL.getLoweredType().getAs<SILFunctionType>()) {
if (fnTy->isTrivialNoEscape()) {
return ParameterConvention::Direct_Guaranteed;
}
}
}
return convention;
}
case ValueOwnership::InOut:
return ParameterConvention::Indirect_Inout;
case ValueOwnership::Shared:
return ParameterConvention::Direct_Guaranteed;
case ValueOwnership::Owned:
return ParameterConvention::Direct_Owned;
}
llvm_unreachable("unhandled ownership");
}
};
/// A visitor for breaking down formal result types into a SILResultInfo
/// and possibly some number of indirect-out SILParameterInfos,
/// matching the abstraction patterns of the original type.
class DestructureResults {
TypeConverter &TC;
const Conventions &Convs;
SmallVectorImpl<SILResultInfo> &Results;
TypeExpansionContext context;
bool hasSendingResult;
public:
DestructureResults(TypeExpansionContext context, TypeConverter &TC,
const Conventions &conventions,
SmallVectorImpl<SILResultInfo> &results,
bool hasSendingResult)
: TC(TC), Convs(conventions), Results(results), context(context),
hasSendingResult(hasSendingResult) {}
void destructure(AbstractionPattern origType, CanType substType) {
// Recur into tuples.
if (origType.isTuple()) {
origType.forEachTupleElement(substType,
[&](TupleElementGenerator &elt) {
// If the original element type is not a pack expansion, just
// pull off the next substituted element type.
if (!elt.isOrigPackExpansion()) {
destructure(elt.getOrigType(), elt.getSubstTypes()[0]);
return;
}
// If the original element type is a pack expansion, build a
// lowered pack type for the substituted components it expands to.
auto origExpansionType = elt.getOrigType();
bool indirect = origExpansionType.arePackElementsPassedIndirectly(TC);
SmallVector<CanType, 4> packElts;
for (auto substEltType : elt.getSubstTypes()) {
auto origComponentType
= origExpansionType.getPackExpansionComponentType(substEltType);
CanType loweredEltTy =
TC.getLoweredRValueType(context, origComponentType, substEltType);
packElts.push_back(loweredEltTy);
};
SILPackType::ExtInfo extInfo(indirect);
auto packType = SILPackType::get(TC.Context, extInfo, packElts);
SILResultInfo result(packType, ResultConvention::Pack);
if (hasSendingResult)
result = result.addingOption(SILResultInfo::IsSending);
Results.push_back(result);
});
return;
}
auto &substResultTLForConvention = TC.getTypeLowering(
origType, substType, TypeExpansionContext::minimal());
auto &substResultTL = TC.getTypeLowering(origType, substType,
context);
// Determine the result convention.
ResultConvention convention;
if (isFormallyReturnedIndirectly(origType, substType,
substResultTLForConvention)) {
convention = ResultConvention::Indirect;
} else {
convention = Convs.getResult(substResultTLForConvention);
// Reduce conventions for trivial types to an unowned convention.
if (substResultTL.isTrivial()) {
switch (convention) {
case ResultConvention::Indirect:
case ResultConvention::Unowned:
case ResultConvention::UnownedInnerPointer:
// Leave these as-is.
break;
case ResultConvention::Pack:
llvm_unreachable("pack convention for non-pack");
case ResultConvention::Autoreleased:
case ResultConvention::Owned:
// These aren't distinguishable from unowned for trivial types.
convention = ResultConvention::Unowned;
break;
}
}
}
SILResultInfo result(substResultTL.getLoweredType().getASTType(),
convention);
if (hasSendingResult)
result = result.addingOption(SILResultInfo::IsSending);
Results.push_back(result);
}
/// Query whether the original type is returned indirectly for the purpose
/// of reabstraction given complete lowering information about its
/// substitution.
bool isFormallyReturnedIndirectly(AbstractionPattern origType,
CanType substType,
const TypeLowering &substTL) {
// If the substituted type is returned indirectly, so must the
// unsubstituted type.
if ((origType.isTypeParameter()
&& !origType.isConcreteType()
&& !origType.requiresClass())
|| substTL.isAddressOnly()) {
return true;
// Functions are always returned directly.
} else if (origType.isOpaqueFunctionOrOpaqueDerivativeFunction()) {
return false;
// If the substitution didn't change the type, then a negative
// response to the above is determinative as well.
} else if (origType.getType() == substType &&
!origType.getType()->hasTypeParameter()) {
return false;
// Otherwise, query specifically for the original type.
} else {
return SILType::isFormallyReturnedIndirectly(
origType.getType(), TC, origType.getGenericSignature());
}
}
};
static bool isClangTypeMoreIndirectThanSubstType(TypeConverter &TC,
const clang::Type *clangTy,
CanType substTy) {
// A const pointer argument might have been imported as
// UnsafePointer, COpaquePointer, or a CF foreign class.
// (An ObjC class type wouldn't be const-qualified.)
if (clangTy->isPointerType()
&& clangTy->getPointeeType().isConstQualified()) {
// Peek through optionals.
if (auto substObjTy = substTy.getOptionalObjectType())
substTy = substObjTy;
// Void pointers aren't usefully indirectable.
if (clangTy->isVoidPointerType())
return false;
if (auto eltTy = substTy->getAnyPointerElementType())
return isClangTypeMoreIndirectThanSubstType(TC,
clangTy->getPointeeType().getTypePtr(), CanType(eltTy));
if (substTy->isOpaquePointer())
// TODO: We could conceivably have an indirect opaque ** imported
// as COpaquePointer. That shouldn't ever happen today, though,
// since we only ever indirect the 'self' parameter of functions
// imported as methods.
return false;
if (clangTy->getPointeeType()->getAs<clang::RecordType>()) {
// CF type as foreign class
if (substTy->getClassOrBoundGenericClass() &&
substTy->getClassOrBoundGenericClass()->getForeignClassKind() ==
ClassDecl::ForeignKind::CFType) {
return false;
}
}
// swift_newtypes are always passed directly
if (auto typedefTy = clangTy->getAs<clang::TypedefType>()) {
if (typedefTy->getDecl()->getAttr<clang::SwiftNewTypeAttr>())
return false;
}
return true;
}
// Pass C++ const reference types indirectly. Right now there's no way to
// express immutable borrowed params, so we have to have this hack.
// Eventually, we should just express these correctly: rdar://89647503
if (importer::isCxxConstReferenceType(clangTy))
return true;
return false;
}
static bool isFormallyPassedIndirectly(TypeConverter &TC,
AbstractionPattern origType,
CanType substType,
const TypeLowering &substTL) {
// If this is a native Swift class that's passed directly to C/C++, treat it
// as indirect.
if (origType.isClangType()) {
if (auto *classDecl = substType->lookThroughAllOptionalTypes()
->getClassOrBoundGenericClass()) {
if (!classDecl->isForeignReferenceType()) {
if (origType.getClangType()
->getUnqualifiedDesugaredType()
->getAsCXXRecordDecl())
return true;
}
}
}
// If the C type of the argument is a const pointer, but the Swift type
// isn't, treat it as indirect.
if (origType.isClangType()
&& isClangTypeMoreIndirectThanSubstType(TC, origType.getClangType(),
substType)) {
return true;
}
// If the substituted type is passed indirectly, so must the
// unsubstituted type.
if ((origType.isTypeParameter() && !origType.isConcreteType()
&& !origType.requiresClass())
|| substTL.isAddressOnly()) {
return true;
// If the substitution didn't change the type, then a negative
// response to the above is determinative as well.
} else if (origType.getType() == substType &&
!origType.getType()->hasTypeParameter()) {
return false;
// Otherwise, query specifically for the original type.
} else {
return SILType::isFormallyPassedIndirectly(
origType.getType(), TC, origType.getGenericSignature());
}
}
/// A visitor for turning formal input types into SILParameterInfos, matching
/// the abstraction patterns of the original type.
///
/// If the original abstraction pattern is fully opaque, we must pass the
/// function's parameters and results indirectly, as if the original type were
/// the most general function signature (expressed entirely in generic
/// parameters) which can be substituted to equal the given signature.
///
/// See the comment in AbstractionPattern.h for details.
class DestructureInputs {
TypeExpansionContext expansion;
TypeConverter &TC;
const Conventions &Convs;
const ForeignInfo &Foreign;
struct ForeignSelfInfo {
AbstractionPattern OrigSelfParam;
AnyFunctionType::CanParam SubstSelfParam;
};
std::optional<ForeignSelfInfo> ForeignSelf;
AbstractionPattern TopLevelOrigType = AbstractionPattern::getInvalid();
SmallVectorImpl<SILParameterInfo> &Inputs;
unsigned NextOrigParamIndex = 0;
public:
DestructureInputs(TypeExpansionContext expansion, TypeConverter &TC,
const Conventions &conventions, const ForeignInfo &foreign,
SmallVectorImpl<SILParameterInfo> &inputs)
: expansion(expansion), TC(TC), Convs(conventions), Foreign(foreign),
Inputs(inputs) {}
void destructure(AbstractionPattern origType,
CanAnyFunctionType::CanParamArrayRef params,
SILExtInfoBuilder extInfoBuilder,
bool &unimplementable) {
visitTopLevelParams(origType, params, extInfoBuilder, unimplementable);
}
private:
/// Query whether the original type is address-only given complete
/// lowering information about its substitution.
bool isFormallyPassedIndirectly(AbstractionPattern origType,
CanType substType,
const TypeLowering &substTL) {
return ::isFormallyPassedIndirectly(TC, origType, substType, substTL);
}
/// Destructure the top-level parameters. There are two things
/// we have to handle differently here from the normal recursive
/// walk into parameter types that expands tuples:
/// - self, especially if it's a foreign-imported self, because
/// it has different conventions and the foreign self needs to be
/// inserted in the right place
/// - the possibility of an opaque abstraction pattern, because
/// a significant amount of the structure of the parameter list
/// is still preserved under opaque abstraction
void visitTopLevelParams(AbstractionPattern origType,
CanAnyFunctionType::CanParamArrayRef params,
SILExtInfoBuilder extInfoBuilder,
bool &unimplementable) {
// If we're working with an opaque abstraction pattern, we never
// have to worry about pack expansions, so we can go 1-1 with the
// substituted parameters.
unsigned numOrigParams =
origType.isTypeParameter()
? params.size()
: origType.getNumFunctionParams();
// If we're importing a freestanding foreign function as a member
// function, the formal types (subst and orig) will conspire to
// pretend that there is a self parameter in the position Swift
// expects it: the end of the parameter lists. In the lowered type,
// we need to put this in its proper place, which for static methods
// generally means dropping it entirely.
bool hasForeignSelf = Foreign.self.isImportAsMember();
// Is there a self parameter in the formal parameter lists?
bool hasSelf =
(extInfoBuilder.hasSelfParam() || hasForeignSelf);
TopLevelOrigType = origType;
// If we have a foreign self parameter, set up the ForeignSelfInfo
// for the use of maybeAddForeignParameters.
if (Foreign.self.isInstance()) {
assert(hasSelf && numOrigParams > 0);
ForeignSelf = ForeignSelfInfo{
origType.getFunctionParamType(numOrigParams - 1),
params.back()
};
}
// Add any foreign parameters that are positioned at the start
// of the sequence. visit() will add foreign parameters that are
// positioned after any parameters it adds.
maybeAddForeignParameters();
// Process all the non-self parameters.
origType.forEachFunctionParam(params.drop_back(hasSelf ? 1 : 0),
/*ignore final orig param*/ hasSelf,
[&](FunctionParamGenerator ¶m) {
// If the parameter is unimplementable because the orig function
// type is opaque and the next substituted param is a pack
// expansion, handle that first.
if (param.isUnimplementablePackExpansion()) {
// Record that we have an unimplementable parameter; this will
// ultimately end up in the function type, and then SILGen
// is supposed to diagnose any attempt to actually emit or
// call functions of such types.
unimplementable = true;
// Also, hack up a pack parameter defensively just in case we
// *do* try to actually use or emit a function with this type.
auto substParam = param.getSubstParams()[0];
auto loweredParamTy =
TC.getLoweredRValueType(expansion, param.getOrigType(),
substParam.getParameterType());
SILPackType::ExtInfo extInfo(/*address*/ true);
auto packTy = SILPackType::get(TC.Context, extInfo, {loweredParamTy});
auto origFlags = param.getOrigFlags();
addPackParameter(packTy, origFlags.getValueOwnership(), origFlags);
return;
}
// If the parameter is not a pack expansion, just pull off the
// next parameter and destructure it in parallel with the abstraction
// pattern for the type.
if (!param.isOrigPackExpansion()) {
visit(param.getOrigType(), param.getSubstParams()[0],
/*forSelf*/false);
return;
}
// Otherwise, collect the substituted components into a pack.
auto origExpansionType = param.getOrigType();
SmallVector<CanType, 8> packElts;
for (auto substParam : param.getSubstParams()) {
auto substParamType = substParam.getParameterType();
auto origParamType =
origExpansionType.getPackExpansionComponentType(substParamType);
auto loweredParamTy = TC.getLoweredRValueType(expansion,
origParamType, substParamType);
packElts.push_back(loweredParamTy);
}
bool indirect = origExpansionType.arePackElementsPassedIndirectly(TC);
SILPackType::ExtInfo extInfo(/*address*/ indirect);
auto packTy = SILPackType::get(TC.Context, extInfo, packElts);
auto origFlags = param.getOrigFlags();
addPackParameter(packTy, origFlags.getValueOwnership(), origFlags);
});
// Process the self parameter. But if we have a formal foreign self
// parameter, we should have processed it earlier in a call to
// maybeAddForeignParameters().
if (hasSelf && !hasForeignSelf) {
auto origParamType = origType.getFunctionParamType(numOrigParams - 1);
auto substParam = params.back();
visit(origParamType, substParam, /*forSelf*/true);
}
TopLevelOrigType = AbstractionPattern::getInvalid();
ForeignSelf = std::nullopt;
}
void visit(AbstractionPattern origType, AnyFunctionType::Param substParam,
bool forSelf) {
// FIXME: we should really be using the flags from the original
// parameter here, right?
auto flags = substParam.getParameterFlags();
auto substType = substParam.getParameterType()->getCanonicalType();
// If we see a pack expansion here, that should only happen because
// we're lowering a function type with a parameter expansion in an
// opaque context. We can't actually support this configuration,
// but we need to make sure we don't crash at this level of the API
// so we can diagnose it later.
if (isa<PackExpansionType>(substType)) {
bool indirect = true;
SILPackType::ExtInfo extInfo(/*address*/ indirect);
auto packTy = SILPackType::get(TC.Context, extInfo, {substType});
return addPackParameter(packTy, flags.getValueOwnership(), flags);
}
visit(flags.getValueOwnership(), forSelf, origType, substType, flags);
}
void visit(ValueOwnership ownership, bool forSelf,
AbstractionPattern origType, CanType substType,
ParameterTypeFlags origFlags) {
assert(!isa<InOutType>(substType));
// Tuples get expanded unless they're inout.
if (origType.isTuple() && ownership != ValueOwnership::InOut) {
expandTuple(ownership, forSelf, origType, substType, origFlags);
return;
}
unsigned origParamIndex = NextOrigParamIndex++;
auto &substTLConv = TC.getTypeLowering(origType, substType,
TypeExpansionContext::minimal());
auto &substTL = TC.getTypeLowering(origType, substType, expansion);
CanType loweredType = substTL.getLoweredType().getASTType();
ParameterConvention convention;
if (ownership == ValueOwnership::InOut) {
convention = ParameterConvention::Indirect_Inout;
} else if (isFormallyPassedIndirectly(origType, substType, substTLConv)) {
convention = Convs.getIndirect(ownership, forSelf, origParamIndex,
origType, substTLConv);
assert(isIndirectFormalParameter(convention));
} else if (substTL.isTrivial() ||
// Foreign reference types are passed trivially.
(substType->getClassOrBoundGenericClass() &&
substType->isForeignReferenceType())) {
convention = ParameterConvention::Direct_Unowned;
} else {
// If we are no implicit copy, our ownership is always Owned.
convention = Convs.getDirect(ownership, forSelf, origParamIndex, origType,
substTLConv);
assert(!isIndirectFormalParameter(convention));
}
addParameter(loweredType, convention, origFlags);
}
/// Recursively expand a tuple type into separate parameters.
void expandTuple(ValueOwnership ownership, bool forSelf,
AbstractionPattern origType, CanType substType,
ParameterTypeFlags oldFlags) {
assert(ownership != ValueOwnership::InOut);
assert(origType.isTuple());
origType.forEachTupleElement(substType, [&](TupleElementGenerator &elt) {
if (!elt.isOrigPackExpansion()) {
visit(ownership, forSelf, elt.getOrigType(), elt.getSubstTypes()[0],
oldFlags);
return;
}
auto origExpansionType = elt.getOrigType();
SmallVector<CanType, 8> packElts;
for (auto substEltType : elt.getSubstTypes()) {
auto origComponentType
= origExpansionType.getPackExpansionComponentType(substEltType);
auto loweredEltTy =
TC.getLoweredRValueType(expansion, origComponentType, substEltType);
packElts.push_back(loweredEltTy);
};
bool indirect = origExpansionType.arePackElementsPassedIndirectly(TC);
SILPackType::ExtInfo extInfo(/*address*/ indirect);
auto packTy = SILPackType::get(TC.Context, extInfo, packElts);
addPackParameter(packTy, ownership, oldFlags);
});
}
/// Add a parameter that we derived from deconstructing the
/// formal type.
void addParameter(CanType loweredType, ParameterConvention convention,
ParameterTypeFlags origFlags) {
SILParameterInfo param(loweredType, convention);
if (origFlags.isNoDerivative())
param = param.addingOption(SILParameterInfo::NotDifferentiable);
if (origFlags.isSending())
param = param.addingOption(SILParameterInfo::Sending);
if (origFlags.isIsolated())
param = param.addingOption(SILParameterInfo::Isolated);
Inputs.push_back(param);
maybeAddForeignParameters();
}
void addPackParameter(CanSILPackType packTy, ValueOwnership ownership,
ParameterTypeFlags origFlags) {
unsigned origParamIndex = NextOrigParamIndex++;
auto convention = Convs.getPack(ownership, origParamIndex);
addParameter(packTy, convention, origFlags);
}
/// Given that we've just reached an argument index for the
/// first time, add any foreign parameters.
void maybeAddForeignParameters() {
while (maybeAddForeignAsyncParameter() ||
maybeAddForeignErrorParameter() ||
maybeAddForeignSelfParameter()) {
// Continue to see, just in case there are more parameters to add.
}
}
bool maybeAddForeignAsyncParameter() {
if (!Foreign.async ||
NextOrigParamIndex != Foreign.async->completionHandlerParamIndex())
return false;
CanType foreignCHTy =
TopLevelOrigType.getObjCMethodAsyncCompletionHandlerForeignType(
Foreign.async.value(), TC);
auto completionHandlerOrigTy = TopLevelOrigType.getObjCMethodAsyncCompletionHandlerType(foreignCHTy);
auto completionHandlerTy = TC.getLoweredType(completionHandlerOrigTy,
foreignCHTy, expansion)
.getASTType();
Inputs.push_back(SILParameterInfo(completionHandlerTy,
ParameterConvention::Direct_Unowned));
++NextOrigParamIndex;
return true;
}
bool maybeAddForeignErrorParameter() {
if (!Foreign.error ||
NextOrigParamIndex != Foreign.error->getErrorParameterIndex())
return false;
auto foreignErrorTy = TC.getLoweredRValueType(
expansion, Foreign.error->getErrorParameterType());
// Assume the error parameter doesn't have interesting lowering.
Inputs.push_back(SILParameterInfo(foreignErrorTy,
ParameterConvention::Direct_Unowned));
++NextOrigParamIndex;
return true;
}
bool maybeAddForeignSelfParameter() {
if (!Foreign.self.isInstance() ||
NextOrigParamIndex != Foreign.self.getSelfIndex())
return false;
if (ForeignSelf) {
// This is a "self", but it's not a Swift self, we handle it differently.
visit(ForeignSelf->SubstSelfParam.getValueOwnership(),
/*forSelf=*/false, ForeignSelf->OrigSelfParam,
ForeignSelf->SubstSelfParam.getParameterType(), {});
}
return true;
}
};
} // end anonymous namespace
static bool isPseudogeneric(SILDeclRef c) {
// FIXME: should this be integrated in with the Sema check that prevents
// illegal use of type arguments in pseudo-generic method bodies?
// The implicitly-generated native initializer thunks for imported
// initializers are never pseudo-generic, because they may need
// to use their type arguments to bridge their value arguments.
if (!c.isForeign &&
(c.kind == SILDeclRef::Kind::Allocator ||
c.kind == SILDeclRef::Kind::Initializer) &&
c.getDecl()->hasClangNode())
return false;
// Otherwise, we have to look at the entity's context.
DeclContext *dc;
if (c.hasDecl()) {
dc = c.getDecl()->getDeclContext();
} else if (auto closure = c.getAbstractClosureExpr()) {
dc = closure->getParent();
} else {
return false;
}
dc = dc->getInnermostTypeContext();
if (!dc) return false;
auto classDecl = dc->getSelfClassDecl();
return (classDecl && classDecl->isTypeErasedGenericClass());
}
/// Update the result type given the foreign error convention that we will be
/// using.
void updateResultTypeForForeignInfo(
const ForeignInfo &foreignInfo, CanGenericSignature genericSig,
AbstractionPattern &origResultType, CanType &substFormalResultType) {
// If there's no error or async convention, the return type is unchanged.
if (!foreignInfo.async && !foreignInfo.error) {
return;
}
// A foreign async convention without an error convention means our lowered
// return type is Void, since the imported semantic return map to the
// completion callback's argument(s).
if (!foreignInfo.error) {
auto &C = substFormalResultType->getASTContext();
substFormalResultType = TupleType::getEmpty(C);
origResultType = AbstractionPattern(genericSig, substFormalResultType);
return;
}
// Otherwise, adjust the return type to match the foreign error convention.
auto convention = *foreignInfo.error;
switch (convention.getKind()) {
// These conventions replace the result type.
case ForeignErrorConvention::ZeroResult:
case ForeignErrorConvention::NonZeroResult:
assert(substFormalResultType->isVoid() || foreignInfo.async);
substFormalResultType = convention.getResultType();
origResultType = AbstractionPattern(genericSig, substFormalResultType);
return;
// These conventions wrap the result type in a level of optionality.
case ForeignErrorConvention::NilResult:
assert(!substFormalResultType->getOptionalObjectType());
substFormalResultType =
OptionalType::get(substFormalResultType)->getCanonicalType();
origResultType =
AbstractionPattern::getOptional(origResultType);
return;
// These conventions don't require changes to the formal error type.
case ForeignErrorConvention::ZeroPreservedResult:
case ForeignErrorConvention::NonNilError:
return;
}
llvm_unreachable("unhandled kind");
}
/// Captured values become SIL function parameters in this function.
static void
lowerCaptureContextParameters(TypeConverter &TC, SILDeclRef function,
CanGenericSignature genericSig,
TypeExpansionContext expansion,
SmallVectorImpl<SILParameterInfo> &inputs) {
// If the function is a closure being converted to an @isolated(any) type,
// add the implicit isolation parameter.
if (auto closureInfo = TC.getClosureTypeInfo(function)) {
if (closureInfo->ExpectedLoweredType->hasErasedIsolation()) {
auto isolationTy = SILType::getOpaqueIsolationType(TC.Context);
inputs.push_back({isolationTy.getASTType(),
ParameterConvention::Direct_Guaranteed});
}
}
// NB: The generic signature may be elided from the lowered function type
// if the function is in a fully-specialized context, but we still need to
// canonicalize references to the generic parameters that may appear in
// non-canonical types in that context. We need the original generic
// signature from the AST for that.
auto origGenericSig = function.getAnyFunctionRef()->getGenericSignature();
auto loweredCaptures = TC.getLoweredLocalCaptures(function);
auto capturedEnvs = loweredCaptures.getGenericEnvironments();
auto *isolatedParam = loweredCaptures.getIsolatedParamCapture();
auto mapTypeOutOfContext = [&](Type t) -> CanType {
LLVM_DEBUG(llvm::dbgs() << "-- capture with contextual type " << t << "\n");
t = t.subst(MapLocalArchetypesOutOfContext(origGenericSig, capturedEnvs),
MakeAbstractConformanceForGenericType(),
SubstFlags::PreservePackExpansionLevel);
LLVM_DEBUG(llvm::dbgs() << "-- maps to " << t->getCanonicalType() << "\n");
return t->getCanonicalType();
};
for (auto capture : loweredCaptures.getCaptures()) {
if (capture.isDynamicSelfMetadata()) {
ParameterConvention convention = ParameterConvention::Direct_Unowned;
auto dynamicSelfInterfaceType =
mapTypeOutOfContext(loweredCaptures.getDynamicSelfType());
auto selfMetatype = CanMetatypeType::get(dynamicSelfInterfaceType,
MetatypeRepresentation::Thick);
SILParameterInfo param(selfMetatype, convention);
inputs.push_back(param);
continue;
}
if (capture.isOpaqueValue()) {
OpaqueValueExpr *opaqueValue = capture.getOpaqueValue();
auto canType = mapTypeOutOfContext(opaqueValue->getType());
auto &loweredTL =
TC.getTypeLowering(AbstractionPattern(genericSig, canType),
canType, expansion);
auto loweredTy = loweredTL.getLoweredType();
ParameterConvention convention;
if (loweredTL.isAddressOnly()) {
convention = ParameterConvention::Indirect_In;
} else {
convention = ParameterConvention::Direct_Owned;
}
SILParameterInfo param(loweredTy.getASTType(), convention);
inputs.push_back(param);
continue;
}
auto options = SILParameterInfo::Options();
Type type;
VarDecl *varDecl = nullptr;
if (auto *expr = capture.getPackElement()) {
type = expr->getType();
} else {
varDecl = cast<VarDecl>(capture.getDecl());
type = varDecl->getTypeInContext();
// If we're capturing a parameter pack, wrap it in a tuple.
if (type->is<PackExpansionType>()) {
assert(!cast<ParamDecl>(varDecl)->supportsMutation() &&
"Cannot capture a pack as an lvalue");
SmallVector<TupleTypeElt, 1> elts;
elts.push_back(type);
type = TupleType::get(elts, TC.Context);
}
if (isolatedParam == varDecl) {
options |= SILParameterInfo::Isolated;
isolatedParam = nullptr;
}
}
assert(!type->hasLocalArchetype() ||
(genericSig && origGenericSig &&
!genericSig->isEqual(origGenericSig)));
auto interfaceType = mapTypeOutOfContext(type)->getReducedType(
genericSig ? genericSig : origGenericSig);
auto &loweredTL =
TC.getTypeLowering(AbstractionPattern(genericSig, interfaceType),
interfaceType, expansion);
auto loweredTy = loweredTL.getLoweredType();
switch (TC.getDeclCaptureKind(capture, expansion)) {
case CaptureKind::Constant: {
// Constants are captured by value.
ParameterConvention convention;
assert (!loweredTL.isAddressOnly());
if (loweredTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = ParameterConvention::Direct_Guaranteed;
}
SILParameterInfo param(loweredTy.getASTType(), convention, options);
if (function.isAsyncLetClosure)
param = param.addingOption(SILParameterInfo::Sending);
inputs.push_back(param);
break;
}
case CaptureKind::Box: {
assert(varDecl);
// The type in the box is lowered in the minimal context.
auto minimalLoweredTy =
TC.getTypeLowering(AbstractionPattern(type), type,
TypeExpansionContext::minimal())
.getLoweredType();
// Lvalues are captured as a box that owns the captured value.
auto boxTy = TC.getInterfaceBoxTypeForCapture(
varDecl, minimalLoweredTy.getASTType(),
genericSig, capturedEnvs,
/*mutable*/ true);
auto convention = ParameterConvention::Direct_Guaranteed;
auto param = SILParameterInfo(boxTy, convention, options);
if (function.isAsyncLetClosure)
param = param.addingOption(SILParameterInfo::Sending);
inputs.push_back(param);
break;
}
case CaptureKind::ImmutableBox: {
assert(varDecl);
// The type in the box is lowered in the minimal context.
auto minimalLoweredTy =
TC.getTypeLowering(AbstractionPattern(type), type,
TypeExpansionContext::minimal())
.getLoweredType();
// Lvalues are captured as a box that owns the captured value.
auto boxTy = TC.getInterfaceBoxTypeForCapture(
varDecl, minimalLoweredTy.getASTType(),
genericSig, capturedEnvs,
/*mutable*/ false);
auto convention = ParameterConvention::Direct_Guaranteed;
auto param = SILParameterInfo(boxTy, convention, options);
if (function.isAsyncLetClosure)
param = param.addingOption(SILParameterInfo::Sending);
inputs.push_back(param);
break;
}
case CaptureKind::StorageAddress: {
// Non-escaping lvalues are captured as the address of the value.
SILType ty = loweredTy.getAddressType();
auto param = SILParameterInfo(
ty.getASTType(), ParameterConvention::Indirect_InoutAliasable,
options);
if (function.isAsyncLetClosure)
param = param.addingOption(SILParameterInfo::Sending);
inputs.push_back(param);
break;
}
case CaptureKind::Immutable: {
// 'let' constants that are address-only are captured as the address of
// the value and will be consumed by the closure.
SILType ty = loweredTy.getAddressType();
auto param = SILParameterInfo(ty.getASTType(),
ParameterConvention::Indirect_In_Guaranteed,
options);
if (function.isAsyncLetClosure)
param = param.addingOption(SILParameterInfo::Sending);
inputs.push_back(param);
break;
}
}
}
assert(!isolatedParam &&
"If we had an isolated capture, we should have visited it when "
"iterating over loweredCaptures.getCaptures().");
}
static AccessorDecl *
getAsCoroutineAccessor(std::optional<SILDeclRef> constant) {
if (!constant || !constant->hasDecl())
return nullptr;;
auto accessor = dyn_cast<AccessorDecl>(constant->getDecl());
if (!accessor || !accessor->isCoroutine())
return nullptr;
return accessor;
}
static void destructureYieldsForReadAccessor(TypeConverter &TC,
TypeExpansionContext expansion,
AbstractionPattern origType,
CanType valueType,
SmallVectorImpl<SILYieldInfo> &yields){
// Recursively destructure tuples.
if (origType.isTuple()) {
auto valueTupleType = cast<TupleType>(valueType);
for (auto i : indices(valueTupleType.getElementTypes())) {
auto origEltType = origType.getTupleElementType(i);
auto valueEltType = valueTupleType.getElementType(i);
destructureYieldsForReadAccessor(TC, expansion, origEltType, valueEltType,
yields);
}
return;
}
auto &tlConv =
TC.getTypeLowering(origType, valueType,
TypeExpansionContext::minimal());
auto &tl =
TC.getTypeLowering(origType, valueType, expansion);
auto convention = [&] {
if (isFormallyPassedIndirectly(TC, origType, valueType, tlConv))
return ParameterConvention::Indirect_In_Guaranteed;
if (tlConv.isTrivial())
return ParameterConvention::Direct_Unowned;
return ParameterConvention::Direct_Guaranteed;
}();
yields.push_back(SILYieldInfo(tl.getLoweredType().getASTType(),
convention));
}
static void destructureYieldsForCoroutine(TypeConverter &TC,
TypeExpansionContext expansion,
std::optional<SILDeclRef> constant,
AbstractionPattern origType,
CanType canValueType,
SmallVectorImpl<SILYieldInfo> &yields,
SILCoroutineKind &coroutineKind) {
auto accessor = getAsCoroutineAccessor(constant);
if (!accessor)
return;
// 'modify' yields an inout of the target type.
if (accessor->getAccessorKind() == AccessorKind::Modify) {
auto loweredValueTy =
TC.getLoweredType(origType, canValueType, expansion);
yields.push_back(SILYieldInfo(loweredValueTy.getASTType(),
ParameterConvention::Indirect_Inout));
} else {
// 'read' yields a borrowed value of the target type, destructuring
// tuples as necessary.
assert(accessor->getAccessorKind() == AccessorKind::Read);
destructureYieldsForReadAccessor(TC, expansion, origType, canValueType,
yields);
}
}
/// Create the appropriate SIL function type for the given formal type
/// and conventions.
///
/// The lowering of function types is generally sensitive to the
/// declared abstraction pattern. We want to be able to take
/// advantage of declared type information in order to, say, pass
/// arguments separately and directly; but we also want to be able to
/// call functions from generic code without completely embarrassing
/// performance. Therefore, different abstraction patterns induce
/// different argument-passing conventions, and we must introduce
/// implicit reabstracting conversions where necessary to map one
/// convention to another.
///
/// However, we actually can't reabstract arbitrary thin function
/// values while still leaving them thin, at least without costly
/// page-mapping tricks. Therefore, the representation must remain
/// consistent across all abstraction patterns.
///
/// We could reabstract block functions in theory, but (1) we don't
/// really need to and (2) doing so would be problematic because
/// stuffing something in an Optional currently forces it to be
/// reabstracted to the most general type, which means that we'd
/// expect the wrong abstraction conventions on bridged block function
/// types.
///
/// Therefore, we only honor abstraction patterns on thick or
/// polymorphic functions.
///
/// FIXME: we shouldn't just drop the original abstraction pattern
/// when we can't reabstract. Instead, we should introduce
/// dynamic-indirect argument-passing conventions and map opaque
/// archetypes to that, then respect those conventions in IRGen by
/// using runtime call construction.
///
/// \param conventions - conventions as expressed for the original type
static CanSILFunctionType getSILFunctionType(
TypeConverter &TC, TypeExpansionContext expansionContext,
AbstractionPattern origType, CanAnyFunctionType substFnInterfaceType,
SILExtInfoBuilder extInfoBuilder, const Conventions &conventions,
const ForeignInfo &foreignInfo, std::optional<SILDeclRef> origConstant,
std::optional<SILDeclRef> constant, std::optional<SubstitutionMap> reqtSubs,
ProtocolConformanceRef witnessMethodConformance) {
// Find the generic parameters.
CanGenericSignature genericSig =
substFnInterfaceType.getOptGenericSignature();
std::optional<TypeConverter::GenericContextRAII> contextRAII;
if (genericSig) contextRAII.emplace(TC, genericSig);
bool unimplementable = false;
// Per above, only fully honor opaqueness in the abstraction pattern
// for thick or polymorphic functions. We don't need to worry about
// non-opaque patterns because the type-checker forbids non-thick
// function types from having generic parameters or results.
if (!constant &&
origType.isTypeParameter() &&
substFnInterfaceType->getExtInfo().getSILRepresentation()
!= SILFunctionType::Representation::Thick &&
isa<FunctionType>(substFnInterfaceType)) {
origType = AbstractionPattern(genericSig,
substFnInterfaceType);
}
std::optional<SILResultInfo> errorResult;
assert(
(!foreignInfo.error || substFnInterfaceType->getExtInfo().isThrowing()) &&
"foreignError was set but function type does not throw?");
assert((!foreignInfo.async || substFnInterfaceType->getExtInfo().isAsync()) &&
"foreignAsync was set but function type is not async?");
// Map '@Sendable' to the appropriate `@Sendable` modifier.
bool isSendable = substFnInterfaceType->getExtInfo().isSendable();
// Map 'async' to the appropriate `@async` modifier.
bool isAsync = false;
if (substFnInterfaceType->getExtInfo().isAsync() && !foreignInfo.async) {
assert(!origType.isForeign()
&& "using native Swift async for foreign type!");
isAsync = true;
}
bool hasSendingResult = substFnInterfaceType->getExtInfo().hasSendingResult();
// Get the yield type for an accessor coroutine.
SILCoroutineKind coroutineKind = SILCoroutineKind::None;
AbstractionPattern coroutineOrigYieldType = AbstractionPattern::getInvalid();
CanType coroutineSubstYieldType;
if (auto accessor = getAsCoroutineAccessor(constant)) {
auto origAccessor = cast<AccessorDecl>(origConstant->getDecl());
coroutineKind = SILCoroutineKind::YieldOnce;
// Coroutine accessors are always native, so fetch the native
// abstraction pattern.
auto origStorage = origAccessor->getStorage();
coroutineOrigYieldType = TC.getAbstractionPattern(origStorage,
/*nonobjc*/ true)
.getReferenceStorageReferentType();
auto storage = accessor->getStorage();
auto valueType = storage->getValueInterfaceType();
if (reqtSubs) {
valueType = valueType.subst(*reqtSubs);
coroutineSubstYieldType = valueType->getReducedType(
genericSig);
} else {
coroutineSubstYieldType = valueType->getReducedType(
accessor->getGenericSignature());
}
}
bool shouldBuildSubstFunctionType = [&]{
if (TC.Context.LangOpts.DisableSubstSILFunctionTypes)
return false;
// If there is no genericity in the abstraction pattern we're lowering
// against, we don't need to introduce substitutions into the lowered
// type.
if (!origType.isTypeParameterOrOpaqueArchetype()
&& !origType.isOpaqueFunctionOrOpaqueDerivativeFunction()
&& !origType.getType()->hasArchetype()
&& !origType.getType()->hasOpaqueArchetype()
&& !origType.getType()->hasTypeParameter()
&& !isa<GenericFunctionType>(origType.getType())) {
return false;
}
// We always use substituted function types for coroutines that are
// being lowered in the context of another coroutine, which is to say,
// for class override thunks. This is required to make the yields
// match in abstraction to the base method's yields, which is necessary
// to make the extracted continuation-function signatures match.
if (constant != origConstant && getAsCoroutineAccessor(constant))
return true;
// We don't currently use substituted function types for generic function
// type lowering, though we should for generic methods on classes and
// protocols.
if (genericSig)
return false;
// We only currently use substituted function types for function values,
// which will have standard thin or thick representation. (Per the previous
// comment, it would be useful to do so for generic methods on classes and
// protocols too.)
auto rep = extInfoBuilder.getRepresentation();
return (rep == SILFunctionTypeRepresentation::Thick ||
rep == SILFunctionTypeRepresentation::Thin);
}();
SubstitutionMap substFunctionTypeSubs;
if (shouldBuildSubstFunctionType) {
// Generalize the generic signature in the abstraction pattern, so that
// abstraction patterns with the same general shape produce equivalent
// lowered function types.
AbstractionPattern origSubstPat = AbstractionPattern::getInvalid();
AbstractionPattern substYieldType = AbstractionPattern::getInvalid();
std::tie(origSubstPat, substFunctionTypeSubs, substYieldType)
= origType.getSubstFunctionTypePattern(substFnInterfaceType, TC,
coroutineOrigYieldType,
coroutineSubstYieldType,
unimplementable);
// We'll lower the abstraction pattern type against itself, and then apply
// those substitutions to form the substituted lowered function type.
origType = origSubstPat;
substFnInterfaceType = cast<AnyFunctionType>(origType.getType());
if (substYieldType.isValid()) {
coroutineOrigYieldType = substYieldType;
coroutineSubstYieldType = substYieldType.getType();
}
}
// Map 'throws' to the appropriate error convention.
// Give the type an error argument whether the substituted type semantically
// `throws` or if the abstraction pattern specifies a Swift function type
// that also throws. This prevents the need for a second possibly-thunking
// conversion when using a non-throwing function in more abstract throwing
// context.
bool isThrowing = substFnInterfaceType->getExtInfo().isThrowing();
if (auto origFnType = origType.getAs<AnyFunctionType>()) {
isThrowing |= origFnType->getExtInfo().isThrowing();
}
if (isThrowing && !foreignInfo.error &&
!foreignInfo.async) {
assert(!origType.isForeign()
&& "using native Swift error convention for foreign type!");
auto optPair = origType.getFunctionThrownErrorType(substFnInterfaceType);
assert(optPair &&
"Lowering a throwing function type against non-throwing pattern");
auto origErrorType = optPair->first;
auto errorType = optPair->second;
auto &errorTLConv = TC.getTypeLowering(origErrorType, errorType,
TypeExpansionContext::minimal());
bool isFormallyIndirectError =
origErrorType.isTypeParameter() || errorTLConv.isAddressOnly();
errorResult = SILResultInfo(errorTLConv.getLoweredType().getASTType(),
isFormallyIndirectError
? ResultConvention::Indirect
: ResultConvention::Owned);
}
// Lower the result type.
AbstractionPattern origResultType = origType.getFunctionResultType();
CanType substFormalResultType = substFnInterfaceType.getResult();
// If we have a foreign error and/or async convention, adjust the
// lowered result type.
updateResultTypeForForeignInfo(foreignInfo, genericSig, origResultType,
substFormalResultType);
// Destructure the input tuple type.
SmallVector<SILParameterInfo, 8> inputs;
{
DestructureInputs destructurer(expansionContext, TC, conventions,
foreignInfo, inputs);
destructurer.destructure(origType, substFnInterfaceType.getParams(),
extInfoBuilder, unimplementable);
}
// Destructure the coroutine yields.
SmallVector<SILYieldInfo, 8> yields;
destructureYieldsForCoroutine(TC, expansionContext, constant,
coroutineOrigYieldType, coroutineSubstYieldType,
yields, coroutineKind);
// Destructure the result tuple type.
SmallVector<SILResultInfo, 8> results;
{
DestructureResults destructurer(expansionContext, TC, conventions, results,
hasSendingResult);
destructurer.destructure(origResultType, substFormalResultType);
}
// Lower the capture context parameters, if any.
if (constant && constant->getAnyFunctionRef()) {
// Lower in the context of the closure. Since the set of captures is a
// private contract between the closure and its enclosing context, we
// don't need to keep its capture types opaque.
lowerCaptureContextParameters(TC, *constant, genericSig,
TC.getCaptureTypeExpansionContext(*constant),
inputs);
}
auto calleeConvention = ParameterConvention::Direct_Unowned;
if (extInfoBuilder.hasContext())
calleeConvention = conventions.getCallee();
bool pseudogeneric = genericSig && constant
? isPseudogeneric(*constant)
: false;
auto silRep = extInfoBuilder.getRepresentation();
const clang::Type *clangType = extInfoBuilder.getClangTypeInfo().getType();
if (shouldStoreClangType(silRep) && !clangType) {
// If we have invalid code in the source like
// do { let x = 0; let _ : @convention(c) () -> Int = { x } }
// we will fail to convert the corresponding SIL function type, as it will
// have a sil_box_type { Int } parameter reflecting the capture. So we
// convert the AST type instead.
// N.B. The `do` is necessary; the code compiles at global scope.
SmallVector<AnyFunctionType::Param, 4> params;
for (auto ty : substFnInterfaceType.getParams())
params.push_back(ty);
clangType = TC.Context.getClangFunctionType(
params, substFnInterfaceType.getResult(),
convertRepresentation(silRep).value());
}
auto silExtInfo = extInfoBuilder.withClangFunctionType(clangType)
.withIsPseudogeneric(pseudogeneric)
.withSendable(isSendable)
.withAsync(isAsync)
.withUnimplementable(unimplementable)
.withLifetimeDependenceInfo(
extInfoBuilder.getLifetimeDependenceInfo())
.build();
return SILFunctionType::get(genericSig, silExtInfo, coroutineKind,
calleeConvention, inputs, yields,
results, errorResult,
substFunctionTypeSubs, SubstitutionMap(),
TC.Context, witnessMethodConformance);
}
static CanSILFunctionType getSILFunctionTypeForInitAccessor(
TypeConverter &TC, TypeExpansionContext context,
AbstractionPattern origType, CanAnyFunctionType substAccessorType,
SILExtInfoBuilder extInfoBuilder, const Conventions &conventions,
SILDeclRef accessorRef) {
auto *accessor = cast<AccessorDecl>(accessorRef.getDecl());
CanGenericSignature genericSig = substAccessorType.getOptGenericSignature();
std::optional<TypeConverter::GenericContextRAII> contextRAII;
if (genericSig)
contextRAII.emplace(TC, genericSig);
SmallVector<SILParameterInfo, 8> inputs;
// First compute `initialValue` input.
{
bool unimplementable = false;
ForeignInfo foreignInfo;
DestructureInputs destructurer(context, TC, conventions, foreignInfo,
inputs);
destructurer.destructure(
origType, substAccessorType.getParams(),
extInfoBuilder.withRepresentation(SILFunctionTypeRepresentation::Thin),
unimplementable);
assert(!unimplementable && "should never have an opaque AP here");
}
// Drop `self` parameter.
inputs.pop_back();
auto getLoweredTypeOfProperty = [&](VarDecl *property) {
auto type = property->getInterfaceType();
AbstractionPattern pattern(genericSig, type->getCanonicalType());
auto loweredTy = TC.getLoweredType(pattern, type, context);
return loweredTy.getASTType();
};
// accessed properties appear as `inout` parameters because they could be
// read from and modified.
for (auto *property : accessor->getAccessedProperties()) {
inputs.push_back(SILParameterInfo(getLoweredTypeOfProperty(property),
ParameterConvention::Indirect_Inout));
}
// Make a new 'self' parameter.
auto selfInterfaceType = MetatypeType::get(
accessor->getDeclContext()->getSelfInterfaceType());
AbstractionPattern origSelfType(genericSig,
selfInterfaceType->getCanonicalType());
auto loweredSelfType = TC.getLoweredType(
origSelfType, selfInterfaceType->getCanonicalType(), context);
inputs.push_back(SILParameterInfo(loweredSelfType.getASTType(),
ParameterConvention::Direct_Unowned));
SmallVector<SILResultInfo, 8> results;
// initialized properties appear as `@out` results because they are
// initialized by the accessor.
for (auto *property : accessor->getInitializedProperties()) {
results.push_back(SILResultInfo(getLoweredTypeOfProperty(property),
ResultConvention::Indirect));
}
auto calleeConvention = ParameterConvention::Direct_Unowned;
if (extInfoBuilder.hasContext())
calleeConvention = conventions.getCallee();
// Map '@Sendable' to the appropriate `@Sendable` modifier.
auto silExtInfo =
SILExtInfoBuilder()
.withRepresentation(SILFunctionTypeRepresentation::Thin)
.withSendable(substAccessorType->getExtInfo().isSendable())
.build();
return SILFunctionType::get(
/*genericSig=*/genericSig, silExtInfo, SILCoroutineKind::None,
calleeConvention, inputs,
/*yields=*/{}, results, /*errorResult=*/std::nullopt,
/*patternSubs=*/SubstitutionMap(),
/*invocationSubs=*/SubstitutionMap(), TC.Context);
}
//===----------------------------------------------------------------------===//
// Deallocator SILFunctionTypes
//===----------------------------------------------------------------------===//
namespace {
// The convention for general deallocators.
struct DeallocatorConventions : Conventions {
DeallocatorConventions() : Conventions(ConventionsKind::Deallocator) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
llvm_unreachable("Deallocators do not have indirect parameters");
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
llvm_unreachable("Deallocators do not have non-self direct parameters");
}
ParameterConvention getCallee() const override {
llvm_unreachable("Deallocators do not have callees");
}
ParameterConvention getPackParameter(unsigned index) const override {
llvm_unreachable("Deallocators do not have pack parameters");
}
ResultConvention getResult(const TypeLowering &tl) const override {
// TODO: Put an unreachable here?
return ResultConvention::Owned;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
// TODO: Investigate whether or not it is
return ParameterConvention::Direct_Owned;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Indirect_In;
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::Deallocator;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Default Convention FunctionTypes
//===----------------------------------------------------------------------===//
namespace {
enum class NormalParameterConvention { Owned, Guaranteed };
/// The default Swift conventions.
class DefaultConventions : public Conventions {
NormalParameterConvention normalParameterConvention;
ResultConvention resultConvention;
public:
DefaultConventions(
NormalParameterConvention normalParameterConvention,
ResultConvention resultConvention = ResultConvention::Owned)
: Conventions(ConventionsKind::Default),
normalParameterConvention(normalParameterConvention),
resultConvention(resultConvention) {}
bool isNormalParameterConventionGuaranteed() const {
return normalParameterConvention == NormalParameterConvention::Guaranteed;
}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
if (isNormalParameterConventionGuaranteed()) {
return ParameterConvention::Indirect_In_Guaranteed;
}
return ParameterConvention::Indirect_In;
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
if (isNormalParameterConventionGuaranteed())
return ParameterConvention::Direct_Guaranteed;
return ParameterConvention::Direct_Owned;
}
ParameterConvention getPackParameter(unsigned index) const override {
if (isNormalParameterConventionGuaranteed())
return ParameterConvention::Pack_Guaranteed;
return ParameterConvention::Pack_Owned;
}
ParameterConvention getCallee() const override {
return DefaultThickCalleeConvention;
}
ResultConvention getResult(const TypeLowering &tl) const override {
return resultConvention;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Direct_Guaranteed;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Indirect_In_Guaranteed;
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::Default;
}
};
/// The default conventions for Swift initializing constructors.
///
/// Initializing constructors take all parameters (including) self at +1. This
/// is because:
///
/// 1. We are likely to be initializing fields of self implying that the
/// parameters are likely to be forwarded into memory without further
/// copies.
/// 2. Initializers must take 'self' at +1, since they will return it back
/// at +1, and may chain onto Objective-C initializers that replace the
/// instance.
struct DefaultInitializerConventions : DefaultConventions {
DefaultInitializerConventions()
: DefaultConventions(NormalParameterConvention::Owned) {}
/// Initializers must take 'self' at +1, since they will return it back at +1,
/// and may chain onto Objective-C initializers that replace the instance.
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Direct_Owned;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Indirect_In;
}
};
/// The convention used for allocating inits. Allocating inits take their normal
/// parameters at +1 and do not have a self parameter.
struct DefaultAllocatorConventions : DefaultConventions {
DefaultAllocatorConventions()
: DefaultConventions(NormalParameterConvention::Owned) {}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("Allocating inits do not have self parameters");
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("Allocating inits do not have self parameters");
}
};
/// The default conventions for Swift setter accessories.
///
/// These take self at +0, but all other parameters at +1. This is because we
/// assume that setter parameters are likely to be values to be forwarded into
/// memory. Thus by passing in the +1 value, we avoid a potential copy in that
/// case.
struct DefaultSetterConventions : DefaultConventions {
DefaultSetterConventions()
: DefaultConventions(NormalParameterConvention::Owned) {}
};
/// The default conventions for ObjC blocks.
struct DefaultBlockConventions : Conventions {
DefaultBlockConventions() : Conventions(ConventionsKind::DefaultBlock) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
llvm_unreachable("indirect block parameters unsupported");
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
return ParameterConvention::Direct_Unowned;
}
ParameterConvention getPackParameter(unsigned index) const override {
llvm_unreachable("objc blocks do not have pack parameters");
}
ParameterConvention getCallee() const override {
return ParameterConvention::Direct_Unowned;
}
ResultConvention getResult(const TypeLowering &substTL) const override {
return ResultConvention::Autoreleased;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("objc blocks do not have a self parameter");
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("objc blocks do not have a self parameter");
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::DefaultBlock;
}
};
} // end anonymous namespace
static CanSILFunctionType getSILFunctionTypeForAbstractCFunction(
TypeConverter &TC, AbstractionPattern origType,
CanAnyFunctionType substType, SILExtInfoBuilder extInfoBuilder,
std::optional<SILDeclRef> constant);
static CanSILFunctionType getNativeSILFunctionType(
TypeConverter &TC, TypeExpansionContext context,
AbstractionPattern origType, CanAnyFunctionType substInterfaceType,
SILExtInfoBuilder extInfoBuilder, std::optional<SILDeclRef> origConstant,
std::optional<SILDeclRef> constant, std::optional<SubstitutionMap> reqtSubs,
ProtocolConformanceRef witnessMethodConformance) {
assert(bool(origConstant) == bool(constant));
auto getSILFunctionTypeForConventions =
[&](const Conventions &convs) -> CanSILFunctionType {
return getSILFunctionType(TC, context, origType, substInterfaceType,
extInfoBuilder, convs, ForeignInfo(),
origConstant, constant, reqtSubs,
witnessMethodConformance);
};
switch (extInfoBuilder.getRepresentation()) {
case SILFunctionType::Representation::Block:
case SILFunctionType::Representation::CFunctionPointer:
case SILFunctionTypeRepresentation::CXXMethod:
return getSILFunctionTypeForAbstractCFunction(
TC, origType, substInterfaceType, extInfoBuilder, constant);
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::Thick:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::Closure:
case SILFunctionType::Representation::KeyPathAccessorGetter:
case SILFunctionType::Representation::KeyPathAccessorSetter:
case SILFunctionType::Representation::KeyPathAccessorEquals:
case SILFunctionType::Representation::KeyPathAccessorHash:
case SILFunctionType::Representation::WitnessMethod: {
switch (origConstant ? origConstant->kind : SILDeclRef::Kind::Func) {
case SILDeclRef::Kind::Initializer:
case SILDeclRef::Kind::EnumElement:
return getSILFunctionTypeForConventions(DefaultInitializerConventions());
case SILDeclRef::Kind::Allocator:
return getSILFunctionTypeForConventions(DefaultAllocatorConventions());
case SILDeclRef::Kind::Func: {
// If we have a setter, use the special setter convention. This ensures
// that we take normal parameters at +1.
if (constant) {
if (constant->isSetter()) {
return getSILFunctionTypeForConventions(DefaultSetterConventions());
} else if (constant->isInitAccessor()) {
return getSILFunctionTypeForInitAccessor(
TC, context, origType, substInterfaceType, extInfoBuilder,
DefaultSetterConventions(), *constant);
}
}
return getSILFunctionTypeForConventions(
DefaultConventions(NormalParameterConvention::Guaranteed));
}
case SILDeclRef::Kind::Destroyer:
case SILDeclRef::Kind::GlobalAccessor:
case SILDeclRef::Kind::DefaultArgGenerator:
case SILDeclRef::Kind::StoredPropertyInitializer:
case SILDeclRef::Kind::PropertyWrapperBackingInitializer:
case SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue:
case SILDeclRef::Kind::IVarInitializer:
case SILDeclRef::Kind::IVarDestroyer:
return getSILFunctionTypeForConventions(
DefaultConventions(NormalParameterConvention::Guaranteed));
case SILDeclRef::Kind::Deallocator:
return getSILFunctionTypeForConventions(DeallocatorConventions());
case SILDeclRef::Kind::AsyncEntryPoint:
return getSILFunctionTypeForConventions(
DefaultConventions(NormalParameterConvention::Guaranteed));
case SILDeclRef::Kind::EntryPoint:
llvm_unreachable("Handled by getSILFunctionTypeForAbstractCFunction");
}
}
}
llvm_unreachable("Unhandled SILDeclRefKind in switch.");
}
CanSILFunctionType swift::getNativeSILFunctionType(
TypeConverter &TC, TypeExpansionContext context,
AbstractionPattern origType, CanAnyFunctionType substType,
SILExtInfo silExtInfo, std::optional<SILDeclRef> origConstant,
std::optional<SILDeclRef> substConstant,
std::optional<SubstitutionMap> reqtSubs,
ProtocolConformanceRef witnessMethodConformance) {
return ::getNativeSILFunctionType(
TC, context, origType, substType, silExtInfo.intoBuilder(), origConstant,
substConstant, reqtSubs, witnessMethodConformance);
}
namespace {
struct OldLocalArchetypeRequirementCollector {
const ASTContext &Context;
unsigned Depth;
/// The lists of new parameters and requirements to add to the signature.
SmallVector<GenericTypeParamType *, 2> Params;
SmallVector<Requirement, 2> Requirements;
/// The list of contextual types from the original function to use as
/// substitutions for the new parameters; parallel to Params.
SmallVector<Type, 4> ParamSubs;
/// A mapping of local archetypes to the corresponding type parameters
/// created for them.
llvm::DenseMap<CanType, Type> ParamsForLocalArchetypes;
/// The set of element environments we've processed.
llvm::SmallPtrSet<GenericEnvironment*, 4> ElementEnvs;
OldLocalArchetypeRequirementCollector(const ASTContext &ctx, unsigned depth)
: Context(ctx), Depth(depth) {}
void collect(CanLocalArchetypeType archetype) {
if (auto openedExistential = dyn_cast<OpenedArchetypeType>(archetype)) {
collect(openedExistential);
} else {
collect(cast<ElementArchetypeType>(archetype));
}
}
void collect(CanOpenedArchetypeType archetype) {
auto param = addParameter(archetype);
assert(archetype->isRoot());
auto constraint = archetype->getExistentialType();
if (auto existential = constraint->getAs<ExistentialType>())
constraint = existential->getConstraintType();
addRequirement(RequirementKind::Conformance, param, constraint);
}
void collect(CanElementArchetypeType archetype) {
size_t startingIndex = Params.size();
// Check whether we've already handled this environment.
// This can happen with opened-element environments because
// they can open multiple archetypes.
auto env = archetype->getGenericEnvironment();
if (!ElementEnvs.insert(env).second) return;
// Add a parameter for each of the opened elements in this environment.
auto sig = env->getGenericSignature();
auto elementParams = sig.getInnermostGenericParams();
#ifndef NDEBUG
unsigned nextIndex = 0;
#endif
for (auto elementParam : elementParams) {
assert(elementParam->getIndex() == nextIndex++);
auto elementArchetype = env->mapTypeIntoContext(elementParam);
addParameter(cast<LocalArchetypeType>(CanType(elementArchetype)));
}
// Clone the element requirements.
// The element parameters should all have the same depth, and their
// index values are dense and in order from 0..<N in that depth.
// We asserted that above, and we'll use it below to map them to
// their new parameters in Params.
auto elementDepth = elementParams.front()->getDepth();
// Helper function: does the given type refer to an opened element
// parameter from the opened element generic signature?
auto refersToElementType = [=](Type type) {
return type.findIf([&](Type t) {
if (auto *param = t->getAs<GenericTypeParamType>())
return (param->getDepth() == elementDepth);
return false;
});
};
// Helper function: replace references to opened element parameters
// with one of the type parameters we just created for this
// environment.
auto rewriteElementType = [=](Type type) {
return type.transformRec([&](Type t) -> std::optional<Type> {
if (auto *param = t->getAs<GenericTypeParamType>()) {
if (param->getDepth() == elementDepth)
return Type(Params[startingIndex + param->getIndex()]);
}
return std::nullopt;
});
};
for (auto req : sig.getRequirements()) {
switch (req.getKind()) {
case RequirementKind::SameShape:
// These never involve element types.
break;
case RequirementKind::Conformance:
if (refersToElementType(req.getFirstType())) {
addRequirement(RequirementKind::Conformance,
rewriteElementType(req.getFirstType()),
req.getSecondType());
}
break;
case RequirementKind::Superclass:
case RequirementKind::SameType:
if (refersToElementType(req.getFirstType()) ||
refersToElementType(req.getSecondType())) {
addRequirement(req.getKind(),
rewriteElementType(req.getFirstType()),
rewriteElementType(req.getSecondType()));
}
break;
break;
case RequirementKind::Layout:
if (refersToElementType(req.getFirstType())) {
addRequirement(RequirementKind::Layout,
rewriteElementType(req.getFirstType()),
req.getLayoutConstraint());
}
break;
}
}
}
GenericTypeParamType *addParameter(CanLocalArchetypeType localArchetype) {
auto *param = GenericTypeParamType::get(/*pack*/ false, Depth,
Params.size(), Context);
Params.push_back(param);
ParamSubs.push_back(localArchetype);
ParamsForLocalArchetypes.insert(std::make_pair(localArchetype, param));
return param;
}
template <class... Args>
void addRequirement(Args &&... args) {
Requirements.emplace_back(std::forward<Args>(args)...);
}
};
} // end anonymous namespace
/// Build a generic signature and environment for a re-abstraction thunk.
///
/// Most thunks share the generic environment with their original function.
/// The one exception is if the thunk type involves an open existential,
/// in which case we "promote" the opened existential to a new generic parameter.
///
/// \param localArchetypes - the list of local archetypes to promote
/// into the signature, if any
/// \param inheritGenericSig - whether to inherit the generic signature from the
/// parent function.
/// \param genericEnv - the new generic environment
/// \param contextSubs - map non-local archetypes from the original function
/// to archetypes in the thunk
/// \param interfaceSubs - map interface types to old archetypes
static CanGenericSignature
buildThunkSignature(SILFunction *fn,
bool inheritGenericSig,
ArrayRef<CanLocalArchetypeType> localArchetypes,
GenericEnvironment *&genericEnv,
SubstitutionMap &contextSubs,
SubstitutionMap &interfaceSubs,
llvm::DenseMap<ArchetypeType*, Type> &contextLocalArchetypes) {
auto *mod = fn->getModule().getSwiftModule();
auto &ctx = mod->getASTContext();
// If there are no local archetypes, we just inherit the generic
// environment from the parent function.
if (localArchetypes.empty()) {
auto genericSig =
fn->getLoweredFunctionType()->getInvocationGenericSignature();
genericEnv = fn->getGenericEnvironment();
interfaceSubs = fn->getForwardingSubstitutionMap();
contextSubs = interfaceSubs;
return genericSig;
}
// Add the existing generic signature.
unsigned depth = 0;
GenericSignature baseGenericSig;
if (inheritGenericSig) {
if (auto genericSig =
fn->getLoweredFunctionType()->getInvocationGenericSignature()) {
baseGenericSig = genericSig;
depth = genericSig.getGenericParams().back()->getDepth() + 1;
}
}
// Add new generic parameters to replace the local archetypes.
OldLocalArchetypeRequirementCollector collector(ctx, depth);
for (auto archetype : localArchetypes) {
collector.collect(archetype);
}
auto genericSig = buildGenericSignature(ctx, baseGenericSig,
collector.Params,
collector.Requirements,
/*allowInverses=*/false);
genericEnv = genericSig.getGenericEnvironment();
// Map the local archetypes to their new parameter types.
for (auto localArchetype : localArchetypes) {
auto param =
collector.ParamsForLocalArchetypes.find(localArchetype)->second;
auto thunkArchetype = genericEnv->mapTypeIntoContext(param);
contextLocalArchetypes.insert(std::make_pair(localArchetype,
thunkArchetype));
}
// Calculate substitutions to map the caller's archetypes to the thunk's
// archetypes.
if (auto calleeGenericSig = fn->getLoweredFunctionType()
->getInvocationGenericSignature()) {
contextSubs = SubstitutionMap::get(
calleeGenericSig,
[&](SubstitutableType *type) -> Type {
return genericEnv->mapTypeIntoContext(type);
},
MakeAbstractConformanceForGenericType());
}
// Calculate substitutions to map interface types to the caller's archetypes.
interfaceSubs = SubstitutionMap::get(
genericSig,
[&](SubstitutableType *type) -> Type {
if (auto param = dyn_cast<GenericTypeParamType>(type)) {
if (param->getDepth() == depth) {
return collector.ParamSubs[param->getIndex()];
}
}
return fn->mapTypeIntoContext(type);
},
MakeAbstractConformanceForGenericType());
return genericSig.getCanonicalSignature();
}
/// Build the type of a function transformation thunk.
CanSILFunctionType swift::buildSILFunctionThunkType(
SILFunction *fn, CanSILFunctionType &sourceType,
CanSILFunctionType &expectedType, CanType &inputSubstType,
CanType &outputSubstType, GenericEnvironment *&genericEnv,
SubstitutionMap &interfaceSubs, CanType &dynamicSelfType,
bool withoutActuallyEscaping,
std::optional<DifferentiationThunkKind> differentiationThunkKind) {
// We shouldn't be thunking generic types here, and substituted function types
// ought to have their substitutions applied before we get here.
assert(!expectedType->isPolymorphic() &&
!expectedType->getCombinedSubstitutions());
assert(!sourceType->isPolymorphic() &&
!sourceType->getCombinedSubstitutions());
// This may inherit @noescape from the expectedType. The @noescape attribute
// is only stripped when using this type to materialize a new decl.
auto extInfoBuilder = expectedType->getExtInfo().intoBuilder();
if (!differentiationThunkKind ||
*differentiationThunkKind == DifferentiationThunkKind::Reabstraction ||
extInfoBuilder.hasContext()) {
// Can't build a reabstraction thunk without context, so we require
// ownership semantics on the result type.
assert(expectedType->getExtInfo().hasContext());
extInfoBuilder = extInfoBuilder.withRepresentation(
SILFunctionType::Representation::Thin);
}
if (withoutActuallyEscaping)
extInfoBuilder = extInfoBuilder.withNoEscape(false);
// Does the thunk type involve archetypes other than local archetypes?
bool hasArchetypes = false;
// Does the thunk type involve a local archetype type?
SmallVector<CanLocalArchetypeType, 8> localArchetypes;
auto archetypeVisitor = [&](CanType t) {
if (auto archetypeTy = dyn_cast<ArchetypeType>(t)) {
if (auto opened = dyn_cast<LocalArchetypeType>(archetypeTy)) {
auto root = opened.getRoot();
if (llvm::find(localArchetypes, root) == localArchetypes.end())
localArchetypes.push_back(root);
} else {
hasArchetypes = true;
}
}
};
// Use the generic signature from the context if the thunk involves
// generic parameters.
CanGenericSignature genericSig;
SubstitutionMap contextSubs;
llvm::DenseMap<ArchetypeType*, Type> contextLocalArchetypes;
if (expectedType->hasArchetype() || sourceType->hasArchetype()) {
expectedType.visit(archetypeVisitor);
sourceType.visit(archetypeVisitor);
genericSig = buildThunkSignature(fn,
hasArchetypes,
localArchetypes,
genericEnv,
contextSubs,
interfaceSubs,
contextLocalArchetypes);
}
auto substTypeHelper = [&](SubstitutableType *type) -> Type {
// If it's a local archetype, do an ad-hoc mapping through the
// map produced by buildThunkSignature.
if (auto *archetype = dyn_cast<LocalArchetypeType>(type)) {
assert(!contextLocalArchetypes.empty());
// Decline to map non-root archetypes; subst() will come back
// to us later and ask about the root.
if (!archetype->isRoot())
return Type();
auto it = contextLocalArchetypes.find(archetype);
assert(it != contextLocalArchetypes.end());
return it->second;
}
// Otherwise, use the context substitutions.
return Type(type).subst(contextSubs);
};
auto substConformanceHelper =
LookUpConformanceInSubstitutionMap(contextSubs);
// Utility function to apply contextSubs, and also replace the
// opened existential with the new archetype.
auto substFormalTypeIntoThunkContext =
[&](CanType t) -> CanType {
return t.subst(substTypeHelper, substConformanceHelper)
->getCanonicalType();
};
auto substLoweredTypeIntoThunkContext =
[&](CanSILFunctionType t) -> CanSILFunctionType {
return SILType::getPrimitiveObjectType(t)
.subst(fn->getModule(), substTypeHelper, substConformanceHelper)
.castTo<SILFunctionType>();
};
sourceType = substLoweredTypeIntoThunkContext(sourceType);
expectedType = substLoweredTypeIntoThunkContext(expectedType);
bool hasDynamicSelf = false;
if (inputSubstType) {
inputSubstType = substFormalTypeIntoThunkContext(inputSubstType);
hasDynamicSelf |= inputSubstType->hasDynamicSelfType();
}
if (outputSubstType) {
outputSubstType = substFormalTypeIntoThunkContext(outputSubstType);
hasDynamicSelf |= outputSubstType->hasDynamicSelfType();
}
hasDynamicSelf |= sourceType->hasDynamicSelfType();
hasDynamicSelf |= expectedType->hasDynamicSelfType();
// If our parent function was pseudogeneric, this thunk must also be
// pseudogeneric, since we have no way to pass generic parameters.
if (genericSig)
if (fn->getLoweredFunctionType()->isPseudogeneric())
extInfoBuilder = extInfoBuilder.withIsPseudogeneric();
// Add the formal parameters of the expected type to the thunk.
auto contextConvention =
fn->getTypeLowering(sourceType).isTrivial()
? ParameterConvention::Direct_Unowned
: ParameterConvention::Direct_Guaranteed;
SmallVector<SILParameterInfo, 4> params;
params.append(expectedType->getParameters().begin(),
expectedType->getParameters().end());
// Thunk functions can never be @isolated(any); we have to erase to that
// by partial application. Remove the attribute and add the capture
// parameter. This must always be the first capture.
if (extInfoBuilder.hasErasedIsolation()) {
extInfoBuilder = extInfoBuilder.withErasedIsolation(false);
auto paramTy = SILType::getOpaqueIsolationType(fn->getASTContext());
params.push_back({paramTy.getASTType(),
ParameterConvention::Direct_Guaranteed});
}
// The next capture is the source function.
if (!differentiationThunkKind ||
*differentiationThunkKind == DifferentiationThunkKind::Reabstraction) {
params.push_back({sourceType,
sourceType->getExtInfo().hasContext()
? contextConvention
: ParameterConvention::Direct_Unowned});
}
// If this thunk involves DynamicSelfType in any way, add a capture for it
// in case we need to recover metadata.
if (hasDynamicSelf) {
dynamicSelfType = fn->getDynamicSelfMetadata()->getType().getASTType();
if (!isa<MetatypeType>(dynamicSelfType)) {
dynamicSelfType = CanMetatypeType::get(dynamicSelfType,
MetatypeRepresentation::Thick);
}
params.push_back({dynamicSelfType, ParameterConvention::Direct_Unowned});
}
auto mapTypeOutOfContext = [&](CanType type) -> CanType {
return type->mapTypeOutOfContext()->getCanonicalType();
};
// Map the parameter and expected types out of context to get the interface
// type of the thunk.
SmallVector<SILParameterInfo, 4> interfaceParams;
interfaceParams.reserve(params.size());
for (auto ¶m : params) {
auto interfaceParam = param.map(mapTypeOutOfContext);
interfaceParams.push_back(interfaceParam);
}
SmallVector<SILYieldInfo, 4> interfaceYields;
for (auto &yield : expectedType->getYields()) {
auto interfaceYield = yield.map(mapTypeOutOfContext);
interfaceYields.push_back(interfaceYield);
}
SmallVector<SILResultInfo, 4> interfaceResults;
for (auto &result : expectedType->getResults()) {
auto interfaceResult = result.map(mapTypeOutOfContext);
interfaceResults.push_back(interfaceResult);
}
std::optional<SILResultInfo> interfaceErrorResult;
if (expectedType->hasErrorResult()) {
auto errorResult = expectedType->getErrorResult();
interfaceErrorResult = errorResult.map(mapTypeOutOfContext);;
}
// The type of the thunk function.
return SILFunctionType::get(
genericSig, extInfoBuilder.build(), expectedType->getCoroutineKind(),
ParameterConvention::Direct_Unowned, interfaceParams, interfaceYields,
interfaceResults, interfaceErrorResult,
expectedType->getPatternSubstitutions(), SubstitutionMap(),
fn->getASTContext());
}
//===----------------------------------------------------------------------===//
// Foreign SILFunctionTypes
//===----------------------------------------------------------------------===//
static bool isCFTypedef(const TypeLowering &tl, clang::QualType type) {
// If we imported a C pointer type as a non-trivial type, it was
// a foreign class type.
return !tl.isTrivial() && type->isPointerType();
}
/// Given nothing but a formal C parameter type that's passed
/// indirectly, deduce the convention for it.
///
/// Generally, whether the parameter is +1 is handled before this.
static ParameterConvention getIndirectCParameterConvention(clang::QualType type) {
// Non-trivial C++ types would be Indirect_Inout (at least in Itanium).
// A trivial const * parameter in C should be considered @in.
if (importer::isCxxConstReferenceType(type.getTypePtr()))
return ParameterConvention::Indirect_In_Guaranteed;
return ParameterConvention::Indirect_In;
}
/// Given a C parameter declaration whose type is passed indirectly,
/// deduce the convention for it.
///
/// Generally, whether the parameter is +1 is handled before this.
static ParameterConvention
getIndirectCParameterConvention(const clang::ParmVarDecl *param) {
return getIndirectCParameterConvention(param->getType());
}
/// Given nothing but a formal C parameter type that's passed
/// directly, deduce the convention for it.
///
/// Generally, whether the parameter is +1 is handled before this.
static ParameterConvention getDirectCParameterConvention(clang::QualType type) {
if (auto *cxxRecord = type->getAsCXXRecordDecl()) {
// Directly passed non-trivially destroyed C++ record is consumed by the
// callee.
if (!cxxRecord->hasTrivialDestructor())
return ParameterConvention::Direct_Owned;
}
return ParameterConvention::Direct_Unowned;
}
/// Given a C parameter declaration whose type is passed directly,
/// deduce the convention for it.
static ParameterConvention
getDirectCParameterConvention(const clang::ParmVarDecl *param) {
if (param->hasAttr<clang::NSConsumedAttr>() ||
param->hasAttr<clang::CFConsumedAttr>())
return ParameterConvention::Direct_Owned;
return getDirectCParameterConvention(param->getType());
}
// FIXME: that should be Direct_Guaranteed
const auto ObjCSelfConvention = ParameterConvention::Direct_Unowned;
namespace {
class ObjCMethodConventions : public Conventions {
const clang::ObjCMethodDecl *Method;
public:
const clang::ObjCMethodDecl *getMethod() const { return Method; }
ObjCMethodConventions(const clang::ObjCMethodDecl *method)
: Conventions(ConventionsKind::ObjCMethod), Method(method) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
return getIndirectCParameterConvention(Method->param_begin()[index]);
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
return getDirectCParameterConvention(Method->param_begin()[index]);
}
ParameterConvention getPackParameter(unsigned index) const override {
llvm_unreachable("objc methods do not have pack parameters");
}
ParameterConvention getCallee() const override {
// Always thin.
return ParameterConvention::Direct_Unowned;
}
/// Given that a method returns a CF type, infer its method
/// family. Unfortunately, Clang's getMethodFamily() never
/// considers a method to be in a special family if its result
/// doesn't satisfy isObjCRetainable().
clang::ObjCMethodFamily getMethodFamilyForCFResult() const {
// Trust an explicit attribute.
if (auto attr = Method->getAttr<clang::ObjCMethodFamilyAttr>()) {
switch (attr->getFamily()) {
case clang::ObjCMethodFamilyAttr::OMF_None:
return clang::OMF_None;
case clang::ObjCMethodFamilyAttr::OMF_alloc:
return clang::OMF_alloc;
case clang::ObjCMethodFamilyAttr::OMF_copy:
return clang::OMF_copy;
case clang::ObjCMethodFamilyAttr::OMF_init:
return clang::OMF_init;
case clang::ObjCMethodFamilyAttr::OMF_mutableCopy:
return clang::OMF_mutableCopy;
case clang::ObjCMethodFamilyAttr::OMF_new:
return clang::OMF_new;
}
llvm_unreachable("bad attribute value");
}
return Method->getSelector().getMethodFamily();
}
bool isImplicitPlusOneCFResult() const {
switch (getMethodFamilyForCFResult()) {
case clang::OMF_None:
case clang::OMF_dealloc:
case clang::OMF_finalize:
case clang::OMF_retain:
case clang::OMF_release:
case clang::OMF_autorelease:
case clang::OMF_retainCount:
case clang::OMF_self:
case clang::OMF_initialize:
case clang::OMF_performSelector:
return false;
case clang::OMF_alloc:
case clang::OMF_new:
case clang::OMF_mutableCopy:
case clang::OMF_copy:
return true;
case clang::OMF_init:
return Method->isInstanceMethod();
}
llvm_unreachable("bad method family");
}
ResultConvention getResult(const TypeLowering &tl) const override {
// If we imported the result as something trivial, we need to
// use one of the unowned conventions.
if (tl.isTrivial()) {
if (Method->hasAttr<clang::ObjCReturnsInnerPointerAttr>())
return ResultConvention::UnownedInnerPointer;
auto type = tl.getLoweredType();
if (type.unwrapOptionalType().getASTType()->isUnmanaged())
return ResultConvention::UnownedInnerPointer;
return ResultConvention::Unowned;
}
// Otherwise, the return type had better be a retainable object pointer.
auto resultType = Method->getReturnType();
assert(resultType->isObjCRetainableType() || isCFTypedef(tl, resultType));
// If it's retainable for the purposes of ObjC ARC, we can trust
// the presence of ns_returns_retained, because Clang will add
// that implicitly based on the method family.
if (resultType->isObjCRetainableType()) {
if (Method->hasAttr<clang::NSReturnsRetainedAttr>())
return ResultConvention::Owned;
return ResultConvention::Autoreleased;
}
// Otherwise, it's a CF return type, which unfortunately means
// we can't just trust getMethodFamily(). We should really just
// change that, but that's an annoying change to make to Clang
// right now.
assert(isCFTypedef(tl, resultType));
// Trust the explicit attributes.
if (Method->hasAttr<clang::CFReturnsRetainedAttr>())
return ResultConvention::Owned;
if (Method->hasAttr<clang::CFReturnsNotRetainedAttr>())
return ResultConvention::Autoreleased;
// Otherwise, infer based on the method family.
if (isImplicitPlusOneCFResult())
return ResultConvention::Owned;
return ResultConvention::Autoreleased;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
if (Method->hasAttr<clang::NSConsumesSelfAttr>())
return ParameterConvention::Direct_Owned;
// The caller is supposed to take responsibility for ensuring
// that 'self' survives a method call.
return ObjCSelfConvention;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("objc methods do not support indirect self parameters");
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::ObjCMethod;
}
};
/// Conventions based on a C function type.
class CFunctionTypeConventions : public Conventions {
const clang::FunctionType *FnType;
clang::QualType getParamType(unsigned i) const {
return FnType->castAs<clang::FunctionProtoType>()->getParamType(i);
}
protected:
/// Protected constructor for subclasses to override the kind passed to the
/// super class.
CFunctionTypeConventions(ConventionsKind kind,
const clang::FunctionType *type)
: Conventions(kind), FnType(type) {}
public:
CFunctionTypeConventions(const clang::FunctionType *type)
: Conventions(ConventionsKind::CFunctionType), FnType(type) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
if (type.isClangType()) {
if (type.getClangType()
->getUnqualifiedDesugaredType()
->getAsCXXRecordDecl()) {
auto t = substTL.getLoweredType().getASTType();
if (auto *classDecl = t.getPointer()
->lookThroughAllOptionalTypes()
->getClassOrBoundGenericClass()) {
if (!classDecl->isForeignReferenceType()) {
assert(!classDecl->hasClangNode() &&
"unexpected imported class type in C function");
assert(!classDecl->isGeneric());
return ParameterConvention::Indirect_In_Guaranteed;
}
}
}
}
return getIndirectCParameterConvention(getParamType(index));
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
if (cast<clang::FunctionProtoType>(FnType)->isParamConsumed(index))
return ParameterConvention::Direct_Owned;
return getDirectCParameterConvention(getParamType(index));
}
ParameterConvention getPackParameter(unsigned index) const override {
llvm_unreachable("C functions do not have pack parameters");
}
ParameterConvention getCallee() const override {
// FIXME: blocks should be Direct_Guaranteed.
return ParameterConvention::Direct_Unowned;
}
ResultConvention getResult(const TypeLowering &tl) const override {
if (tl.isTrivial())
return ResultConvention::Unowned;
if (FnType->getExtInfo().getProducesResult())
return ResultConvention::Owned;
if (tl.getLoweredType().isForeignReferenceType())
return ResultConvention::Unowned;
if (FnType->getReturnType()
->getUnqualifiedDesugaredType()
->getAsCXXRecordDecl()) {
auto t = tl.getLoweredType().getASTType();
if (auto *classDecl = t.getPointer()
->lookThroughAllOptionalTypes()
->getClassOrBoundGenericClass()) {
assert(!classDecl->hasClangNode() &&
"unexpected imported class type in C function");
assert(!classDecl->isGeneric());
return ResultConvention::Owned;
}
}
return ResultConvention::Autoreleased;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("c function types do not have a self parameter");
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("c function types do not have a self parameter");
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::CFunctionType;
}
};
/// Conventions based on C function declarations.
class CFunctionConventions : public CFunctionTypeConventions {
using super = CFunctionTypeConventions;
const clang::FunctionDecl *TheDecl;
public:
CFunctionConventions(const clang::FunctionDecl *decl)
: CFunctionTypeConventions(ConventionsKind::CFunction,
decl->getType()->castAs<clang::FunctionType>()),
TheDecl(decl) {}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
if (auto param = TheDecl->getParamDecl(index))
if (param->hasAttr<clang::CFConsumedAttr>())
return ParameterConvention::Direct_Owned;
return super::getDirectParameter(index, type, substTL);
}
ParameterConvention getPackParameter(unsigned index) const override {
llvm_unreachable("C functions do not have pack parameters");
}
ResultConvention getResult(const TypeLowering &tl) const override {
// C++ constructors return indirectly.
// TODO: this may be different depending on the ABI, so we may have to
// check with clang here.
if (isa<clang::CXXConstructorDecl>(TheDecl)) {
return ResultConvention::Indirect;
}
if (isCFTypedef(tl, TheDecl->getReturnType())) {
// The CF attributes aren't represented in the type, so we need
// to check them here.
if (TheDecl->hasAttr<clang::CFReturnsRetainedAttr>()) {
return ResultConvention::Owned;
} else if (TheDecl->hasAttr<clang::CFReturnsNotRetainedAttr>()) {
// Probably not actually autoreleased.
return ResultConvention::Autoreleased;
// The CF Create/Copy rule only applies to functions that return
// a CF-runtime type; it does not apply to methods, and it does
// not apply to functions returning ObjC types.
} else if (clang::ento::coreFoundation::followsCreateRule(TheDecl)) {
return ResultConvention::Owned;
} else if (tl.getLoweredType().isForeignReferenceType()) {
return ResultConvention::Unowned;
} else {
return ResultConvention::Autoreleased;
}
}
// Otherwise, fall back on the ARC annotations, which are part
// of the type.
return super::getResult(tl);
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::CFunction;
}
};
/// Conventions based on C++ method declarations.
class CXXMethodConventions : public CFunctionTypeConventions {
using super = CFunctionTypeConventions;
const clang::CXXMethodDecl *TheDecl;
bool isMutating;
public:
CXXMethodConventions(const clang::CXXMethodDecl *decl, bool isMutating)
: CFunctionTypeConventions(
ConventionsKind::CXXMethod,
decl->getType()->castAs<clang::FunctionType>()),
TheDecl(decl), isMutating(isMutating) {}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
if (isMutating)
return ParameterConvention::Indirect_Inout;
return ParameterConvention::Indirect_In_Guaranteed;
}
ParameterConvention
getIndirectParameter(unsigned int index, const AbstractionPattern &type,
const TypeLowering &substTL) const override {
// `self` is the last parameter.
if (index == TheDecl->getNumParams()) {
return getIndirectSelfParameter(type);
}
return super::getIndirectParameter(index, type, substTL);
}
ResultConvention getResult(const TypeLowering &resultTL) const override {
if (isa<clang::CXXConstructorDecl>(TheDecl)) {
// Represent the `this` pointer as an indirectly returned result.
// This gets us most of the way towards representing the ABI of a
// constructor correctly, but it's not guaranteed to be entirely correct.
// C++ constructor ABIs are complicated and can require passing additional
// "implicit" arguments that depend not only on the signature of the
// constructor but on the class on which it's defined (e.g. whether that
// class has a virtual base class).
// Effectively, we're making an assumption here that there are no implicit
// arguments and that the return type of the constructor ABI is void (and
// indeed we have no way to represent anything else here). If this assumed
// ABI doesn't match the actual ABI, we insert a thunk in IRGen. On some
// ABIs (e.g. Itanium x64), we get lucky and the ABI for a complete
// constructor call always matches the ABI we assume here. Even if the
// actual ABI doesn't match the assumed ABI, we try to get as close as
// possible to make it easy for LLVM to optimize away the thunk.
return ResultConvention::Indirect;
}
if (TheDecl->hasAttr<clang::CFReturnsRetainedAttr>() &&
resultTL.getLoweredType().isForeignReferenceType()) {
return ResultConvention::Owned;
}
return CFunctionTypeConventions::getResult(resultTL);
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::CXXMethod;
}
};
} // end anonymous namespace
/// Given that we have an imported Clang declaration, deduce the
/// ownership conventions for calling it and build the SILFunctionType.
static CanSILFunctionType getSILFunctionTypeForClangDecl(
TypeConverter &TC, const clang::Decl *clangDecl,
CanAnyFunctionType origType, CanAnyFunctionType substInterfaceType,
SILExtInfoBuilder extInfoBuilder, const ForeignInfo &foreignInfo,
std::optional<SILDeclRef> constant) {
if (auto method = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) {
auto origPattern = AbstractionPattern::getObjCMethod(
origType, method, foreignInfo.error, foreignInfo.async);
return getSILFunctionType(
TC, TypeExpansionContext::minimal(), origPattern, substInterfaceType,
extInfoBuilder, ObjCMethodConventions(method), foreignInfo, constant,
constant, std::nullopt, ProtocolConformanceRef());
}
if (auto method = dyn_cast<clang::CXXMethodDecl>(clangDecl)) {
// Static methods and ctors should be lowered like plane functions
// (case below).
if (!isa<clang::CXXConstructorDecl>(method) || method->isStatic()) {
AbstractionPattern origPattern = AbstractionPattern::getCXXMethod(origType, method,
foreignInfo.self);
bool isMutating =
TC.Context.getClangModuleLoader()->isCXXMethodMutating(method);
auto conventions = CXXMethodConventions(method, isMutating);
return getSILFunctionType(TC, TypeExpansionContext::minimal(),
origPattern, substInterfaceType, extInfoBuilder,
conventions, foreignInfo, constant, constant,
std::nullopt, ProtocolConformanceRef());
}
}
if (auto func = dyn_cast<clang::FunctionDecl>(clangDecl)) {
auto clangType = func->getType().getTypePtr();
AbstractionPattern origPattern =
foreignInfo.self.isImportAsMember()
? AbstractionPattern::getCFunctionAsMethod(origType, clangType,
foreignInfo.self)
: AbstractionPattern(origType, clangType);
return getSILFunctionType(TC, TypeExpansionContext::minimal(), origPattern,
substInterfaceType, extInfoBuilder,
CFunctionConventions(func), foreignInfo, constant,
constant, std::nullopt, ProtocolConformanceRef());
}
llvm_unreachable("call to unknown kind of C function");
}
static CanSILFunctionType getSILFunctionTypeForAbstractCFunction(
TypeConverter &TC, AbstractionPattern origType,
CanAnyFunctionType substType, SILExtInfoBuilder extInfoBuilder,
std::optional<SILDeclRef> constant) {
const clang::Type *clangType = nullptr;
if (origType.isClangType())
clangType = origType.getClangType();
else
clangType = extInfoBuilder.getClangTypeInfo().getType();
if (clangType) {
const clang::FunctionType *fnType;
if (auto blockPtr = clangType->getAs<clang::BlockPointerType>()) {
fnType = blockPtr->getPointeeType()->castAs<clang::FunctionType>();
} else if (auto ptr = clangType->getAs<clang::PointerType>()) {
fnType = ptr->getPointeeType()->getAs<clang::FunctionType>();
} else if (auto ref = clangType->getAs<clang::ReferenceType>()) {
fnType = ref->getPointeeType()->getAs<clang::FunctionType>();
} else if (auto fn = clangType->getAs<clang::FunctionType>()) {
fnType = fn;
} else {
llvm_unreachable("unexpected type imported as a function type");
}
if (fnType) {
return getSILFunctionType(
TC, TypeExpansionContext::minimal(), origType, substType,
extInfoBuilder, CFunctionTypeConventions(fnType), ForeignInfo(),
constant, constant, std::nullopt, ProtocolConformanceRef());
}
}
// TODO: Ought to support captures in block funcs.
return getSILFunctionType(TC, TypeExpansionContext::minimal(), origType,
substType, extInfoBuilder,
DefaultBlockConventions(), ForeignInfo(), constant,
constant, std::nullopt, ProtocolConformanceRef());
}
/// Try to find a clang method declaration for the given function.
static const clang::Decl *findClangMethod(ValueDecl *method) {
if (auto *methodFn = dyn_cast<FuncDecl>(method)) {
if (auto *decl = methodFn->getClangDecl())
return decl;
if (auto overridden = methodFn->getOverriddenDecl())
return findClangMethod(overridden);
}
if (auto *constructor = dyn_cast<ConstructorDecl>(method)) {
if (auto *decl = constructor->getClangDecl())
return decl;
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// Selector Family SILFunctionTypes
//===----------------------------------------------------------------------===//
/// Derive the ObjC selector family from an identifier.
///
/// Note that this will never derive the Init family, which is too dangerous
/// to leave to chance. Swift functions starting with "init" are always
/// emitted as if they are part of the "none" family.
static ObjCSelectorFamily getObjCSelectorFamily(ObjCSelector name) {
auto result = name.getSelectorFamily();
if (result == ObjCSelectorFamily::Init)
return ObjCSelectorFamily::None;
return result;
}
/// Get the ObjC selector family a foreign SILDeclRef belongs to.
static ObjCSelectorFamily getObjCSelectorFamily(SILDeclRef c) {
assert(c.isForeign);
switch (c.kind) {
case SILDeclRef::Kind::Func: {
if (!c.hasDecl())
return ObjCSelectorFamily::None;
auto *FD = cast<FuncDecl>(c.getDecl());
if (auto accessor = dyn_cast<AccessorDecl>(FD)) {
switch (accessor->getAccessorKind()) {
case AccessorKind::Get:
case AccessorKind::Set:
break;
#define OBJC_ACCESSOR(ID, KEYWORD)
#define ACCESSOR(ID) \
case AccessorKind::ID:
case AccessorKind::DistributedGet:
#include "swift/AST/AccessorKinds.def"
llvm_unreachable("Unexpected AccessorKind of foreign FuncDecl");
}
}
return getObjCSelectorFamily(FD->getObjCSelector());
}
case SILDeclRef::Kind::Initializer:
case SILDeclRef::Kind::IVarInitializer:
return ObjCSelectorFamily::Init;
/// Currently IRGen wraps alloc/init methods into Swift constructors
/// with Swift conventions.
case SILDeclRef::Kind::Allocator:
/// These constants don't correspond to method families we care about yet.
case SILDeclRef::Kind::Destroyer:
case SILDeclRef::Kind::Deallocator:
case SILDeclRef::Kind::IVarDestroyer:
return ObjCSelectorFamily::None;
case SILDeclRef::Kind::EnumElement:
case SILDeclRef::Kind::GlobalAccessor:
case SILDeclRef::Kind::DefaultArgGenerator:
case SILDeclRef::Kind::StoredPropertyInitializer:
case SILDeclRef::Kind::PropertyWrapperBackingInitializer:
case SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue:
case SILDeclRef::Kind::EntryPoint:
case SILDeclRef::Kind::AsyncEntryPoint:
llvm_unreachable("Unexpected Kind of foreign SILDeclRef");
}
llvm_unreachable("Unhandled SILDeclRefKind in switch.");
}
namespace {
class ObjCSelectorFamilyConventions : public Conventions {
ObjCSelectorFamily Family;
bool pseudogeneric;
public:
ObjCSelectorFamilyConventions(ObjCSelectorFamily family, bool pseudogeneric)
: Conventions(ConventionsKind::ObjCSelectorFamily), Family(family),
pseudogeneric(pseudogeneric) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
return ParameterConvention::Indirect_In;
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type,
const TypeLowering &substTL) const override {
return ParameterConvention::Direct_Unowned;
}
ParameterConvention getPackParameter(unsigned index) const override {
llvm_unreachable("objc methods do not have pack parameters");
}
ParameterConvention getCallee() const override {
// Always thin.
return ParameterConvention::Direct_Unowned;
}
ResultConvention getResult(const TypeLowering &tl) const override {
switch (Family) {
case ObjCSelectorFamily::Alloc:
case ObjCSelectorFamily::Copy:
case ObjCSelectorFamily::Init:
case ObjCSelectorFamily::MutableCopy:
case ObjCSelectorFamily::New:
return ResultConvention::Owned;
case ObjCSelectorFamily::None:
// Defaults below.
break;
}
// Get the underlying AST type, potentially stripping off one level of
// optionality while we do it.
CanType type = tl.getLoweredType().unwrapOptionalType().getASTType();
if (type->hasRetainablePointerRepresentation() ||
(type->getSwiftNewtypeUnderlyingType() && !tl.isTrivial()) ||
(isa<GenericTypeParamType>(type) && pseudogeneric))
return ResultConvention::Autoreleased;
return ResultConvention::Unowned;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
if (Family == ObjCSelectorFamily::Init)
return ParameterConvention::Direct_Owned;
return ObjCSelfConvention;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("selector family objc function types do not support "
"indirect self parameters");
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::ObjCSelectorFamily;
}
};
} // end anonymous namespace
static CanSILFunctionType getSILFunctionTypeForObjCSelectorFamily(
TypeConverter &TC, ObjCSelectorFamily family, CanAnyFunctionType origType,
CanAnyFunctionType substInterfaceType, SILExtInfoBuilder extInfoBuilder,
const ForeignInfo &foreignInfo, std::optional<SILDeclRef> constant) {
CanGenericSignature genericSig = substInterfaceType.getOptGenericSignature();
bool pseudogeneric =
genericSig && constant ? isPseudogeneric(*constant) : false;
return getSILFunctionType(
TC, TypeExpansionContext::minimal(), AbstractionPattern(origType),
substInterfaceType, extInfoBuilder,
ObjCSelectorFamilyConventions(family, pseudogeneric), foreignInfo,
constant, constant,
/*requirement subs*/ std::nullopt, ProtocolConformanceRef());
}
static bool isImporterGeneratedAccessor(const clang::Decl *clangDecl,
SILDeclRef constant) {
// Must be an accessor.
auto accessor = dyn_cast<AccessorDecl>(constant.getDecl());
if (!accessor)
return false;
// Must be a type member.
if (!accessor->hasImplicitSelfDecl())
return false;
// Must be imported from a function.
if (!isa<clang::FunctionDecl>(clangDecl))
return false;
return true;
}
static CanSILFunctionType getUncachedSILFunctionTypeForConstant(
TypeConverter &TC, TypeExpansionContext context, SILDeclRef constant,
TypeConverter::LoweredFormalTypes bridgedTypes) {
auto silRep = TC.getDeclRefRepresentation(constant);
assert(silRep != SILFunctionTypeRepresentation::Thick &&
silRep != SILFunctionTypeRepresentation::Block);
auto origLoweredInterfaceType = bridgedTypes.Uncurried;
auto extInfo = origLoweredInterfaceType->getExtInfo();
auto extInfoBuilder =
SILExtInfo(extInfo, false).intoBuilder().withRepresentation(silRep);
if (shouldStoreClangType(silRep)) {
const clang::Type *clangType = nullptr;
if (bridgedTypes.Pattern.isClangType()) {
clangType = bridgedTypes.Pattern.getClangType();
}
if (clangType) {
// According to [NOTE: ClangTypeInfo-contents], we need to wrap a function
// type in an additional clang::PointerType.
if (clangType->isFunctionType()) {
clangType =
static_cast<ClangImporter *>(TC.Context.getClangModuleLoader())
->getClangASTContext()
.getPointerType(clang::QualType(clangType, 0))
.getTypePtr();
}
extInfoBuilder = extInfoBuilder.withClangFunctionType(clangType);
}
}
if (!constant.isForeign) {
ProtocolConformanceRef witnessMethodConformance;
if (silRep == SILFunctionTypeRepresentation::WitnessMethod) {
auto proto = constant.getDecl()->getDeclContext()->getSelfProtocolDecl();
witnessMethodConformance = ProtocolConformanceRef(proto);
}
// Does this constant have a preferred abstraction pattern set?
AbstractionPattern origType = [&]{
if (auto closureInfo = TC.getClosureTypeInfo(constant)) {
return closureInfo->OrigType;
} else {
return AbstractionPattern(origLoweredInterfaceType);
}
}();
return ::getNativeSILFunctionType(
TC, context, origType, origLoweredInterfaceType, extInfoBuilder,
constant, constant, std::nullopt, witnessMethodConformance);
}
ForeignInfo foreignInfo;
// If we have a clang decl associated with the Swift decl, derive its
// ownership conventions.
if (constant.hasDecl()) {
auto decl = constant.getDecl();
if (auto funcDecl = dyn_cast<AbstractFunctionDecl>(decl)) {
foreignInfo = ForeignInfo{
funcDecl->getImportAsMemberStatus(),
funcDecl->getForeignErrorConvention(),
funcDecl->getForeignAsyncConvention(),
};
}
if (auto clangDecl = findClangMethod(decl)) {
// The importer generates accessors that are not actually
// import-as-member but do involve the same gymnastics with the
// formal type. That's all that SILFunctionType cares about, so
// pretend that it's import-as-member.
if (!foreignInfo.self.isImportAsMember() &&
isImporterGeneratedAccessor(clangDecl, constant)) {
unsigned selfIndex = cast<AccessorDecl>(decl)->isSetter() ? 1 : 0;
foreignInfo.self.setSelfIndex(selfIndex);
}
return getSILFunctionTypeForClangDecl(
TC, clangDecl, origLoweredInterfaceType, origLoweredInterfaceType,
extInfoBuilder, foreignInfo, constant);
}
}
// The type of the native-to-foreign thunk for a swift closure.
if (constant.isForeign && constant.hasClosureExpr() &&
shouldStoreClangType(TC.getDeclRefRepresentation(constant))) {
auto clangType = TC.Context.getClangFunctionType(
origLoweredInterfaceType->getParams(),
origLoweredInterfaceType->getResult(),
FunctionTypeRepresentation::CFunctionPointer);
AbstractionPattern pattern =
AbstractionPattern(origLoweredInterfaceType, clangType);
return getSILFunctionTypeForAbstractCFunction(
TC, pattern, origLoweredInterfaceType, extInfoBuilder, constant);
}
// If the decl belongs to an ObjC method family, use that family's
// ownership conventions.
return getSILFunctionTypeForObjCSelectorFamily(
TC, getObjCSelectorFamily(constant), origLoweredInterfaceType,
origLoweredInterfaceType, extInfoBuilder, foreignInfo, constant);
}
CanSILFunctionType TypeConverter::getUncachedSILFunctionTypeForConstant(
TypeExpansionContext context, SILDeclRef constant,
CanAnyFunctionType origInterfaceType) {
// This entrypoint is only used for computing a type for dynamic dispatch.
assert(!constant.getAbstractClosureExpr());
auto bridgedTypes = getLoweredFormalTypes(constant, origInterfaceType);
return ::getUncachedSILFunctionTypeForConstant(*this, context, constant,
bridgedTypes);
}
static bool isObjCMethod(ValueDecl *vd) {
if (!vd->getDeclContext())
return false;
Type contextType = vd->getDeclContext()->getDeclaredInterfaceType();
if (!contextType)
return false;
bool isRefCountedClass = contextType->getClassOrBoundGenericClass() &&
!contextType->isForeignReferenceType();
return isRefCountedClass || contextType->isClassExistentialType();
}
SILFunctionTypeRepresentation
TypeConverter::getDeclRefRepresentation(SILDeclRef c) {
// If this is a foreign thunk, it always has the foreign calling convention.
if (c.isForeign) {
if (!c.hasDecl())
return SILFunctionTypeRepresentation::CFunctionPointer;
if (auto method =
dyn_cast_or_null<clang::CXXMethodDecl>(c.getDecl()->getClangDecl()))
return isa<clang::CXXConstructorDecl>(method) || method->isStatic()
? SILFunctionTypeRepresentation::CFunctionPointer
: SILFunctionTypeRepresentation::CXXMethod;
// For example, if we have a function in a namespace:
if (c.getDecl()->isImportAsMember())
return SILFunctionTypeRepresentation::CFunctionPointer;
if (isObjCMethod(c.getDecl()) ||
c.kind == SILDeclRef::Kind::IVarInitializer ||
c.kind == SILDeclRef::Kind::IVarDestroyer)
return SILFunctionTypeRepresentation::ObjCMethod;
return SILFunctionTypeRepresentation::CFunctionPointer;
}
// Anonymous functions currently always have Freestanding CC.
if (c.getAbstractClosureExpr())
return SILFunctionTypeRepresentation::Thin;
// FIXME: Assert that there is a native entry point
// available. There's no great way to do this.
// Protocol witnesses are called using the witness calling convention.
if (c.hasDecl()) {
if (auto proto = dyn_cast<ProtocolDecl>(c.getDecl()->getDeclContext())) {
// Use the regular method convention for foreign-to-native thunks.
if (c.isForeignToNativeThunk())
return SILFunctionTypeRepresentation::Method;
assert(!c.isNativeToForeignThunk() && "shouldn't be possible");
return getProtocolWitnessRepresentation(proto);
}
}
switch (c.kind) {
case SILDeclRef::Kind::GlobalAccessor:
case SILDeclRef::Kind::DefaultArgGenerator:
case SILDeclRef::Kind::StoredPropertyInitializer:
case SILDeclRef::Kind::PropertyWrapperBackingInitializer:
case SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue:
return SILFunctionTypeRepresentation::Thin;
case SILDeclRef::Kind::Func:
if (c.getDecl()->getDeclContext()->isTypeContext())
return SILFunctionTypeRepresentation::Method;
if (ExternAttr::find(c.getDecl()->getAttrs(), ExternKind::C))
return SILFunctionTypeRepresentation::CFunctionPointer;
return SILFunctionTypeRepresentation::Thin;
case SILDeclRef::Kind::Destroyer:
case SILDeclRef::Kind::Deallocator:
case SILDeclRef::Kind::Allocator:
case SILDeclRef::Kind::Initializer:
case SILDeclRef::Kind::EnumElement:
case SILDeclRef::Kind::IVarInitializer:
case SILDeclRef::Kind::IVarDestroyer:
return SILFunctionTypeRepresentation::Method;
case SILDeclRef::Kind::AsyncEntryPoint:
return SILFunctionTypeRepresentation::Thin;
case SILDeclRef::Kind::EntryPoint:
return SILFunctionTypeRepresentation::CFunctionPointer;
}
llvm_unreachable("Unhandled SILDeclRefKind in switch.");
}
// Provide the ability to turn off the type converter cache to ease debugging.
static llvm::cl::opt<bool>
DisableConstantInfoCache("sil-disable-typelowering-constantinfo-cache",
llvm::cl::init(false));
static IndexSubset *
getLoweredResultIndices(const SILFunctionType *functionType,
const IndexSubset *parameterIndices) {
SmallVector<unsigned, 2> resultIndices;
// Check formal results.
for (auto resultAndIndex : enumerate(functionType->getResults()))
if (!resultAndIndex.value().hasOption(SILResultInfo::NotDifferentiable))
resultIndices.push_back(resultAndIndex.index());
auto numResults = functionType->getNumResults();
// Collect semantic result parameters.
unsigned semResultParamIdx = 0;
for (auto resultParamAndIndex
: enumerate(functionType->getParameters())) {
if (!resultParamAndIndex.value().isAutoDiffSemanticResult())
continue;
if (!resultParamAndIndex.value().hasOption(
SILParameterInfo::NotDifferentiable) &&
parameterIndices->contains(resultParamAndIndex.index()))
resultIndices.push_back(numResults + semResultParamIdx);
semResultParamIdx += 1;
}
numResults += semResultParamIdx;
return IndexSubset::get(functionType->getASTContext(),
numResults, resultIndices);
}
const SILConstantInfo &
TypeConverter::getConstantInfo(TypeExpansionContext expansion,
SILDeclRef constant) {
if (!DisableConstantInfoCache) {
auto found = ConstantTypes.find(std::make_pair(expansion, constant));
if (found != ConstantTypes.end())
return *found->second;
}
// First, get a function type for the constant. This creates the
// right type for a getter or setter.
auto formalInterfaceType = makeConstantInterfaceType(constant);
// The lowered type is the formal type, but uncurried and with
// parameters automatically turned into their bridged equivalents.
auto bridgedTypes = getLoweredFormalTypes(constant, formalInterfaceType);
CanAnyFunctionType loweredInterfaceType = bridgedTypes.Uncurried;
// The SIL type encodes conventions according to the original type.
CanSILFunctionType silFnType = ::getUncachedSILFunctionTypeForConstant(
*this, expansion, constant, bridgedTypes);
// If the constant refers to a derivative function, get the SIL type of the
// original function and use it to compute the derivative SIL type.
//
// This is necessary because the "lowered AST derivative function type" (bc)
// may differ from the "derivative type of the lowered original function type"
// (ad):
//
// ┌────────────────────┐ lowering ┌────────────────────┐
// │ AST orig. fn type │ ───────(a)──────► │ SIL orig. fn type │
// └────────────────────┘ └────────────────────┘
// │ │
// (b, Sema) getAutoDiffDerivativeFunctionType (d, here)
// │ │
// ▼ ▼
// ┌────────────────────┐ lowering ┌────────────────────┐
// │ AST deriv. fn type │ ───────(c)──────► │ SIL deriv. fn type │
// └────────────────────┘ └────────────────────┘
//
// (ad) does not always commute with (bc):
// - (bc) is the result of computing the AST derivative type (Sema), then
// lowering it via SILGen. This is the default lowering behavior, but may
// break SIL typing invariants because expected lowered derivative types are
// computed from lowered original function types.
// - (ad) is the result of lowering the original function type, then computing
// its derivative type. This is the expected lowered derivative type,
// preserving SIL typing invariants.
//
// Always use (ad) to compute lowered derivative function types.
if (auto *derivativeId = constant.getDerivativeFunctionIdentifier()) {
// Get lowered original function type.
auto origFnConstantInfo = getConstantInfo(
TypeExpansionContext::minimal(), constant.asAutoDiffOriginalFunction());
// Use it to compute lowered derivative function type.
auto *loweredParamIndices = autodiff::getLoweredParameterIndices(
derivativeId->getParameterIndices(), formalInterfaceType);
auto *loweredResultIndices
= getLoweredResultIndices(origFnConstantInfo.SILFnType, loweredParamIndices);
silFnType = origFnConstantInfo.SILFnType->getAutoDiffDerivativeFunctionType(
loweredParamIndices, loweredResultIndices, derivativeId->getKind(),
*this, LookUpConformanceInModule(&M));
}
LLVM_DEBUG(llvm::dbgs() << "lowering type for constant ";
constant.print(llvm::dbgs());
llvm::dbgs() << "\n formal type: ";
formalInterfaceType.print(llvm::dbgs());
llvm::dbgs() << "\n lowered AST type: ";
loweredInterfaceType.print(llvm::dbgs());
llvm::dbgs() << "\n SIL type: ";
silFnType.print(llvm::dbgs());
llvm::dbgs() << "\n Expansion context: "
<< expansion.shouldLookThroughOpaqueTypeArchetypes();
llvm::dbgs() << "\n");
auto resultBuf = Context.Allocate(sizeof(SILConstantInfo),
alignof(SILConstantInfo));
auto result = ::new (resultBuf) SILConstantInfo{formalInterfaceType,
bridgedTypes.Pattern,
loweredInterfaceType,
silFnType};
if (DisableConstantInfoCache)
return *result;
auto inserted =
ConstantTypes.insert({std::make_pair(expansion, constant), result});
assert(inserted.second);
(void)inserted;
return *result;
}
/// Returns the SILParameterInfo for the given declaration's `self` parameter.
/// `constant` must refer to a method.
SILParameterInfo
TypeConverter::getConstantSelfParameter(TypeExpansionContext context,
SILDeclRef constant) {
auto ty = getConstantFunctionType(context, constant);
// In most cases the "self" parameter is lowered as the back parameter.
// The exception is C functions imported as methods.
if (!constant.isForeign)
return ty->getParameters().back();
if (!constant.hasDecl())
return ty->getParameters().back();
auto fn = dyn_cast<AbstractFunctionDecl>(constant.getDecl());
if (!fn)
return ty->getParameters().back();
if (fn->isImportAsStaticMember())
return SILParameterInfo();
if (fn->isImportAsInstanceMember())
return ty->getParameters()[fn->getSelfIndex()];
return ty->getParameters().back();
}
// This check duplicates TypeConverter::checkForABIDifferences(),
// but on AST types. The issue is we only want to introduce a new
// vtable thunk if the AST type changes, but an abstraction change
// is OK; we don't want a new entry if an @in parameter became
// @guaranteed or whatever.
static bool checkASTTypeForABIDifferences(CanType type1,
CanType type2) {
return !type1->matches(type2, TypeMatchFlags::AllowABICompatible);
}
// FIXME: This makes me very upset. Can we do without this?
static CanType copyOptionalityFromDerivedToBase(TypeConverter &tc,
CanType derived,
CanType base) {
// Unwrap optionals, but remember that we did.
bool derivedWasOptional = false;
if (auto object = derived.getOptionalObjectType()) {
derivedWasOptional = true;
derived = object;
}
if (auto object = base.getOptionalObjectType()) {
base = object;
}
// T? +> S = (T +> S)?
// T? +> S? = (T +> S)?
if (derivedWasOptional) {
base = copyOptionalityFromDerivedToBase(tc, derived, base);
auto optDecl = tc.Context.getOptionalDecl();
return CanType(BoundGenericEnumType::get(optDecl, Type(), base));
}
// (T1, T2, ...) +> (S1, S2, ...) = (T1 +> S1, T2 +> S2, ...)
if (auto derivedTuple = dyn_cast<TupleType>(derived)) {
if (auto baseTuple = dyn_cast<TupleType>(base)) {
assert(derivedTuple->getNumElements() == baseTuple->getNumElements());
SmallVector<TupleTypeElt, 4> elements;
for (unsigned i = 0, e = derivedTuple->getNumElements(); i < e; i++) {
elements.push_back(
baseTuple->getElement(i).getWithType(
copyOptionalityFromDerivedToBase(
tc,
derivedTuple.getElementType(i),
baseTuple.getElementType(i))));
}
return CanType(TupleType::get(elements, tc.Context));
}
}
// (T1 -> T2) +> (S1 -> S2) = (T1 +> S1) -> (T2 +> S2)
if (auto derivedFunc = dyn_cast<AnyFunctionType>(derived)) {
if (auto baseFunc = dyn_cast<AnyFunctionType>(base)) {
SmallVector<FunctionType::Param, 8> params;
auto derivedParams = derivedFunc.getParams();
auto baseParams = baseFunc.getParams();
assert(derivedParams.size() == baseParams.size());
for (unsigned i = 0, e = derivedParams.size(); i < e; ++i) {
assert(derivedParams[i].getParameterFlags() ==
baseParams[i].getParameterFlags());
params.emplace_back(
copyOptionalityFromDerivedToBase(
tc,
derivedParams[i].getPlainType(),
baseParams[i].getPlainType()),
Identifier(),
baseParams[i].getParameterFlags());
}
auto result = copyOptionalityFromDerivedToBase(tc,
derivedFunc.getResult(),
baseFunc.getResult());
return CanAnyFunctionType::get(baseFunc.getOptGenericSignature(),
llvm::ArrayRef(params), result,
baseFunc->getExtInfo());
}
}
return base;
}
/// Returns the ConstantInfo corresponding to the VTable thunk for overriding.
/// Will be the same as getConstantInfo if the declaration does not override.
const SILConstantInfo &
TypeConverter::getConstantOverrideInfo(TypeExpansionContext context,
SILDeclRef derived, SILDeclRef base) {
// Foreign overrides currently don't need reabstraction.
if (derived.isForeign)
return getConstantInfo(context, derived);
auto found = ConstantOverrideTypes.find({derived, base});
if (found != ConstantOverrideTypes.end())
return *found->second;
assert(base.requiresNewVTableEntry() && "base must not be an override");
auto derivedSig = derived.getDecl()->getAsGenericContext()
->getGenericSignature();
auto genericSig = Context.getOverrideGenericSignature(base.getDecl(),
derived.getDecl());
// Figure out the generic signature for the class method call. This is the
// signature of the derived class, with requirements transplanted from
// the base method. The derived method is allowed to have fewer
// requirements, in which case the thunk will translate the calling
// convention appropriately before calling the derived method.
bool hasGenericRequirementDifference =
!genericSig.requirementsNotSatisfiedBy(derivedSig).empty();
auto baseInfo = getConstantInfo(context, base);
auto derivedInfo = getConstantInfo(context, derived);
auto params = derivedInfo.FormalType.getParams();
assert(params.size() == 1);
auto selfInterfaceTy = params[0].getPlainType()->getMetatypeInstanceType();
auto overrideInterfaceTy =
cast<AnyFunctionType>(
selfInterfaceTy->adjustSuperclassMemberDeclType(
base.getDecl(), derived.getDecl(), baseInfo.FormalType)
->getCanonicalType());
// Build the formal AST function type for the class method call.
auto basePattern = AbstractionPattern(baseInfo.LoweredType);
if (!hasGenericRequirementDifference &&
!checkASTTypeForABIDifferences(derivedInfo.FormalType,
overrideInterfaceTy)) {
// The derived method is ABI-compatible with the base method. Let's
// just use the derived method's formal type.
basePattern = AbstractionPattern(
copyOptionalityFromDerivedToBase(
*this,
derivedInfo.LoweredType,
baseInfo.LoweredType));
overrideInterfaceTy = derivedInfo.FormalType;
}
if (genericSig && !genericSig->areAllParamsConcrete()) {
overrideInterfaceTy =
cast<AnyFunctionType>(
GenericFunctionType::get(genericSig,
overrideInterfaceTy->getParams(),
overrideInterfaceTy->getResult(),
overrideInterfaceTy->getExtInfo())
->getCanonicalType());
}
// Build the lowered AST function type for the class method call.
auto bridgedTypes = getLoweredFormalTypes(derived, overrideInterfaceTy);
// Build the SILFunctionType for the class method call.
CanSILFunctionType fnTy = getNativeSILFunctionType(
*this, context, basePattern, bridgedTypes.Uncurried,
derivedInfo.SILFnType->getExtInfo(), base, derived,
/*reqt subs*/ std::nullopt, ProtocolConformanceRef());
// Build the SILConstantInfo and cache it.
auto resultBuf = Context.Allocate(sizeof(SILConstantInfo),
alignof(SILConstantInfo));
auto result = ::new (resultBuf) SILConstantInfo{
overrideInterfaceTy,
basePattern,
bridgedTypes.Uncurried,
fnTy};
auto inserted = ConstantOverrideTypes.insert({{derived, base}, result});
assert(inserted.second);
(void)inserted;
return *result;
}
/// Fast path for bridging types in a function type without uncurrying.
CanAnyFunctionType TypeConverter::getBridgedFunctionType(
AbstractionPattern pattern, CanAnyFunctionType t, Bridgeability bridging,
SILFunctionTypeRepresentation rep) {
// Pull out the generic signature.
CanGenericSignature genericSig = t.getOptGenericSignature();
switch (getSILFunctionLanguage(rep)) {
case SILFunctionLanguage::Swift: {
// No bridging needed for native functions.
return t;
}
case SILFunctionLanguage::C: {
SmallVector<AnyFunctionType::Param, 8> params;
getBridgedParams(rep, pattern, t->getParams(), params, bridging);
bool suppressOptional = pattern.hasForeignErrorStrippingResultOptionality();
auto result = getBridgedResultType(rep,
pattern.getFunctionResultType(),
t.getResult(),
bridging,
suppressOptional);
return CanAnyFunctionType::get(genericSig, llvm::ArrayRef(params), result,
t->getExtInfo());
}
}
llvm_unreachable("bad calling convention");
}
static AbstractFunctionDecl *getBridgedFunction(SILDeclRef declRef) {
switch (declRef.kind) {
case SILDeclRef::Kind::Func:
case SILDeclRef::Kind::Allocator:
case SILDeclRef::Kind::Initializer:
return (declRef.hasDecl()
? cast<AbstractFunctionDecl>(declRef.getDecl())
: nullptr);
case SILDeclRef::Kind::EnumElement:
case SILDeclRef::Kind::Destroyer:
case SILDeclRef::Kind::Deallocator:
case SILDeclRef::Kind::GlobalAccessor:
case SILDeclRef::Kind::DefaultArgGenerator:
case SILDeclRef::Kind::StoredPropertyInitializer:
case SILDeclRef::Kind::PropertyWrapperBackingInitializer:
case SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue:
case SILDeclRef::Kind::IVarInitializer:
case SILDeclRef::Kind::IVarDestroyer:
case SILDeclRef::Kind::EntryPoint:
case SILDeclRef::Kind::AsyncEntryPoint:
return nullptr;
}
llvm_unreachable("bad SILDeclRef kind");
}
static AbstractionPattern
getAbstractionPatternForConstant(ASTContext &ctx, SILDeclRef constant,
CanAnyFunctionType fnType,
unsigned numParameterLists) {
if (!constant.isForeign)
return AbstractionPattern(fnType);
auto bridgedFn = getBridgedFunction(constant);
if (!bridgedFn)
return AbstractionPattern(fnType);
const clang::Decl *clangDecl = bridgedFn->getClangDecl();
if (!clangDecl)
return AbstractionPattern(fnType);
// Don't implicitly turn non-optional results to optional if
// we're going to apply a foreign error convention that checks
// for nil results.
if (auto method = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) {
assert(numParameterLists == 2 && "getting curried ObjC method type?");
return AbstractionPattern::getCurriedObjCMethod(fnType, method,
bridgedFn->getForeignErrorConvention(),
bridgedFn->getForeignAsyncConvention());
} else if (auto value = dyn_cast<clang::ValueDecl>(clangDecl)) {
if (numParameterLists == 1) {
// C function imported as a function.
return AbstractionPattern(fnType, value->getType().getTypePtr());
} else {
assert(numParameterLists == 2);
if (auto method = dyn_cast<clang::CXXMethodDecl>(clangDecl)) {
// C++ method.
return AbstractionPattern::getCurriedCXXMethod(fnType, bridgedFn);
} else {
// C function imported as a method.
return AbstractionPattern::getCurriedCFunctionAsMethod(fnType,
bridgedFn);
}
}
}
return AbstractionPattern(fnType);
}
TypeConverter::LoweredFormalTypes
TypeConverter::getLoweredFormalTypes(SILDeclRef constant,
CanAnyFunctionType fnType) {
// We always use full bridging when importing a constant because we can
// directly bridge its arguments and results when calling it.
auto bridging = Bridgeability::Full;
unsigned numParameterLists = constant.getParameterListCount();
// Form an abstraction pattern for bridging purposes.
AbstractionPattern bridgingFnPattern =
getAbstractionPatternForConstant(Context, constant, fnType,
numParameterLists);
auto extInfo = fnType->getExtInfo();
SILFunctionTypeRepresentation rep = getDeclRefRepresentation(constant);
assert(rep != SILFunctionType::Representation::Block &&
"objc blocks cannot be curried");
// Fast path: no uncurrying required.
if (numParameterLists == 1) {
auto bridgedFnType =
getBridgedFunctionType(bridgingFnPattern, fnType, bridging, rep);
bridgingFnPattern.rewriteType(bridgingFnPattern.getGenericSignature(),
bridgedFnType);
return { bridgingFnPattern, bridgedFnType };
}
// The dependent generic signature.
CanGenericSignature genericSig = fnType.getOptGenericSignature();
// The 'self' parameter.
assert(fnType.getParams().size() == 1);
AnyFunctionType::Param selfParam = fnType.getParams()[0];
// The formal method parameters.
// If we actually partially-apply this, assume we'll need a thick function.
fnType = cast<FunctionType>(fnType.getResult());
auto innerExtInfo =
fnType->getExtInfo().withRepresentation(FunctionTypeRepresentation::Swift);
auto methodParams = fnType->getParams();
auto resultType = fnType.getResult();
bool suppressOptionalResult =
bridgingFnPattern.hasForeignErrorStrippingResultOptionality();
// Bridge input and result types.
SmallVector<AnyFunctionType::Param, 8> bridgedParams;
CanType bridgedResultType;
switch (rep) {
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
// Native functions don't need bridging.
bridgedParams.append(methodParams.begin(), methodParams.end());
bridgedResultType = resultType;
break;
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::CFunctionPointer: {
if (rep == SILFunctionTypeRepresentation::ObjCMethod) {
// The "self" parameter should not get bridged unless it's a metatype.
if (selfParam.getPlainType()->is<AnyMetatypeType>()) {
auto selfPattern = bridgingFnPattern.getFunctionParamType(0);
selfParam = getBridgedParam(rep, selfPattern, selfParam, bridging);
}
}
auto partialFnPattern = bridgingFnPattern.getFunctionResultType();
for (unsigned i : indices(methodParams)) {
auto paramPattern = partialFnPattern.getFunctionParamType(i);
auto bridgedParam =
getBridgedParam(rep, paramPattern, methodParams[i], bridging);
bridgedParams.push_back(bridgedParam);
}
bridgedResultType =
getBridgedResultType(rep,
partialFnPattern.getFunctionResultType(),
resultType, bridging, suppressOptionalResult);
break;
}
case SILFunctionTypeRepresentation::Block:
llvm_unreachable("Cannot uncurry native representation");
}
// Build the curried function type.
auto inner = CanFunctionType::get(llvm::ArrayRef(bridgedParams),
bridgedResultType, innerExtInfo);
auto curried =
CanAnyFunctionType::get(genericSig, {selfParam}, inner, extInfo);
// Replace the type in the abstraction pattern with the curried type.
bridgingFnPattern.rewriteType(genericSig, curried);
// Build the uncurried function type.
if (innerExtInfo.isThrowing())
extInfo = extInfo.withThrows(true, innerExtInfo.getThrownError());
if (innerExtInfo.isAsync())
extInfo = extInfo.withAsync(true);
// Distributed thunks are always `async throws`
if (constant.isDistributedThunk()) {
extInfo = extInfo.withAsync(true).withThrows(true, Type());
}
// The uncurried function is parameter-isolated if the inner type is.
if (innerExtInfo.getIsolation().isParameter())
extInfo = extInfo.withIsolation(innerExtInfo.getIsolation());
// If this is a C++ constructor, don't add the metatype "self" parameter
// because we'll never use it and it will cause problems in IRGen.
if (isa_and_nonnull<clang::CXXConstructorDecl>(
constant.getDecl()->getClangDecl())) {
// But, make sure it is actually a metatype that we're not adding. If
// changes to the self parameter are made in the future, this logic may
// need to be updated.
assert(selfParam.getParameterType()->is<MetatypeType>());
} else {
bridgedParams.push_back(selfParam);
}
if (innerExtInfo.hasSendingResult())
extInfo = extInfo.withSendingResult();
auto uncurried = CanAnyFunctionType::get(
genericSig, llvm::ArrayRef(bridgedParams), bridgedResultType, extInfo);
return { bridgingFnPattern, uncurried };
}
// TODO: We should compare generic signatures. Class and witness methods
// allow variance in "self"-fulfilled parameters; other functions must
// match exactly.
// TODO: More sophisticated param and return ABI compatibility rules could
// diverge.
//
// Note: all cases recognized here must be handled in the SILOptimizer's
// castValueToABICompatibleType().
static bool areABICompatibleParamsOrReturns(SILType a, SILType b,
SILFunction *inFunction) {
// Address parameters are all ABI-compatible, though the referenced
// values may not be. Assume whoever's doing this knows what they're
// doing.
if (a.isAddress() && b.isAddress())
return true;
// Addresses aren't compatible with values.
// TODO: An exception for pointerish types?
if (a.isAddress() || b.isAddress())
return false;
// Tuples are ABI compatible if their elements are.
// TODO: Should destructure recursively.
SmallVector<CanType, 1> aElements, bElements;
if (auto tup = a.getAs<TupleType>()) {
auto types = tup.getElementTypes();
aElements.append(types.begin(), types.end());
} else {
aElements.push_back(a.getASTType());
}
if (auto tup = b.getAs<TupleType>()) {
auto types = tup.getElementTypes();
bElements.append(types.begin(), types.end());
} else {
bElements.push_back(b.getASTType());
}
if (aElements.size() != bElements.size())
return false;
for (unsigned i : indices(aElements)) {
auto aa = SILType::getPrimitiveObjectType(aElements[i]);
auto bb = SILType::getPrimitiveObjectType(bElements[i]);
// Equivalent types are always ABI-compatible.
if (aa == bb)
continue;
// Opaque types are compatible with their substitution.
if (inFunction) {
auto opaqueTypesSubstituted = aa;
auto *dc = inFunction->getDeclContext();
auto *currentModule = inFunction->getModule().getSwiftModule();
if (!dc || !dc->isChildContextOf(currentModule))
dc = currentModule;
ReplaceOpaqueTypesWithUnderlyingTypes replacer(
dc, inFunction->getResilienceExpansion(),
inFunction->getModule().isWholeModule());
if (aa.getASTType()->hasOpaqueArchetype())
opaqueTypesSubstituted = aa.subst(inFunction->getModule(), replacer,
replacer, CanGenericSignature(),
SubstFlags::SubstituteOpaqueArchetypes);
auto opaqueTypesSubstituted2 = bb;
if (bb.getASTType()->hasOpaqueArchetype())
opaqueTypesSubstituted2 =
bb.subst(inFunction->getModule(), replacer, replacer,
CanGenericSignature(),
SubstFlags::SubstituteOpaqueArchetypes);
if (opaqueTypesSubstituted == opaqueTypesSubstituted2)
continue;
}
// FIXME: If one or both types are dependent, we can't accurately assess
// whether they're ABI-compatible without a generic context. We can
// do a better job here when dependent types are related to their
// generic signatures.
if (aa.hasTypeParameter() || bb.hasTypeParameter())
continue;
// Bridgeable object types are interchangeable.
if (aa.isBridgeableObjectType() && bb.isBridgeableObjectType())
continue;
// Optional and IUO are interchangeable if their elements are.
auto aObject = aa.getOptionalObjectType();
auto bObject = bb.getOptionalObjectType();
if (aObject && bObject &&
areABICompatibleParamsOrReturns(aObject, bObject, inFunction))
continue;
// Optional objects are ABI-interchangeable with non-optionals;
// None is represented by a null pointer.
if (aObject && aObject.isBridgeableObjectType() &&
bb.isBridgeableObjectType())
continue;
if (bObject && bObject.isBridgeableObjectType() &&
aa.isBridgeableObjectType())
continue;
// Optional thick metatypes are ABI-interchangeable with non-optionals
// too.
if (aObject)
if (auto aObjMeta = aObject.getAs<MetatypeType>())
if (auto bMeta = bb.getAs<MetatypeType>())
if (aObjMeta->getRepresentation() == bMeta->getRepresentation() &&
bMeta->getRepresentation() != MetatypeRepresentation::Thin)
continue;
if (bObject)
if (auto aMeta = aa.getAs<MetatypeType>())
if (auto bObjMeta = bObject.getAs<MetatypeType>())
if (aMeta->getRepresentation() == bObjMeta->getRepresentation() &&
aMeta->getRepresentation() != MetatypeRepresentation::Thin)
continue;
// Function types are interchangeable if they're also ABI-compatible.
if (auto aFunc = aa.getAs<SILFunctionType>()) {
if (auto bFunc = bb.getAs<SILFunctionType>()) {
// *NOTE* We swallow the specific error here for now. We will still get
// that the function types are incompatible though, just not more
// specific information.
return aFunc->isABICompatibleWith(bFunc, *inFunction).isCompatible();
}
}
// Metatypes are interchangeable with metatypes with the same
// representation.
if (auto aMeta = aa.getAs<MetatypeType>()) {
if (auto bMeta = bb.getAs<MetatypeType>()) {
if (aMeta->getRepresentation() == bMeta->getRepresentation())
continue;
}
}
// Other types must match exactly.
return false;
}
return true;
}
namespace {
using ABICompatibilityCheckResult =
SILFunctionType::ABICompatibilityCheckResult;
} // end anonymous namespace
ABICompatibilityCheckResult
SILFunctionType::isABICompatibleWith(CanSILFunctionType other,
SILFunction &context) const {
// Most of the checks here are symmetric, but for those that aren't,
// the question is whether the ABI makes it safe to use a value of
// this type as if it had type `other`.
// The calling convention and function representation can't be changed.
if (getRepresentation() != other->getRepresentation())
return ABICompatibilityCheckResult::DifferentFunctionRepresentations;
if (isAsync() != other->isAsync())
return ABICompatibilityCheckResult::DifferentAsyncness;
// `() async -> ()` is not compatible with `() async -> @error Error` and
// vice versa.
if (hasErrorResult() != other->hasErrorResult() && isAsync()) {
return ABICompatibilityCheckResult::DifferentErrorResultConventions;
}
// @isolated(any) imposes an additional requirement on the context
// storage and cannot be added. It can safely be removed, however.
if (other->hasErasedIsolation() && !hasErasedIsolation())
return ABICompatibilityCheckResult::DifferentErasedIsolation;
// Check the results.
if (getNumResults() != other->getNumResults())
return ABICompatibilityCheckResult::DifferentNumberOfResults;
for (unsigned i : indices(getResults())) {
auto result1 = getResults()[i];
auto result2 = other->getResults()[i];
if (result1.getConvention() != result2.getConvention())
return ABICompatibilityCheckResult::DifferentReturnValueConventions;
if (!areABICompatibleParamsOrReturns(
result1.getSILStorageType(context.getModule(), this,
context.getTypeExpansionContext()),
result2.getSILStorageType(context.getModule(), other,
context.getTypeExpansionContext()),
&context)) {
return ABICompatibilityCheckResult::ABIIncompatibleReturnValues;
}
}
// Our error result conventions are designed to be ABI compatible
// with functions lacking error results. Just make sure that the
// actual conventions match up.
if (hasErrorResult() && other->hasErrorResult()) {
auto error1 = getErrorResult();
auto error2 = other->getErrorResult();
if (error1.getConvention() != error2.getConvention())
return ABICompatibilityCheckResult::DifferentErrorResultConventions;
if (!areABICompatibleParamsOrReturns(
error1.getSILStorageType(context.getModule(), this,
context.getTypeExpansionContext()),
error2.getSILStorageType(context.getModule(), other,
context.getTypeExpansionContext()),
&context))
return ABICompatibilityCheckResult::ABIIncompatibleErrorResults;
}
// Check the parameters.
// TODO: Could allow known-empty types to be inserted or removed, but SIL
// doesn't know what empty types are yet.
if (getParameters().size() != other->getParameters().size())
return ABICompatibilityCheckResult::DifferentNumberOfParameters;
for (unsigned i : indices(getParameters())) {
auto param1 = getParameters()[i];
auto param2 = other->getParameters()[i];
if (param1.getConvention() != param2.getConvention())
return {ABICompatibilityCheckResult::DifferingParameterConvention, i};
// Note that the diretionality here is reversed from the other cases
// because of contravariance: parameters of the *second* type will be
// trivially converted to be parameters of the *first* type.
if (!areABICompatibleParamsOrReturns(
param2.getSILStorageType(context.getModule(), other,
context.getTypeExpansionContext()),
param1.getSILStorageType(context.getModule(), this,
context.getTypeExpansionContext()),
&context))
return {ABICompatibilityCheckResult::ABIIncompatibleParameterType, i};
}
// This needs to be checked last because the result implies everying else has
// already been checked and this is the only difference.
if (isNoEscape() != other->isNoEscape() &&
(getRepresentation() == SILFunctionType::Representation::Thick))
return ABICompatibilityCheckResult::ABIEscapeToNoEscapeConversion;
return ABICompatibilityCheckResult::None;
}
StringRef SILFunctionType::ABICompatibilityCheckResult::getMessage() const {
switch (kind) {
case innerty::None:
return "None";
case innerty::DifferentFunctionRepresentations:
return "Different function representations";
case innerty::DifferentNumberOfResults:
return "Different number of results";
case innerty::DifferentReturnValueConventions:
return "Different return value conventions";
case innerty::ABIIncompatibleReturnValues:
return "ABI incompatible return values";
case innerty::DifferentErrorResultConventions:
return "Different error result conventions";
case innerty::ABIIncompatibleErrorResults:
return "ABI incompatible error results";
case innerty::DifferentNumberOfParameters:
return "Different number of parameters";
case innerty::DifferentAsyncness:
return "sync/async mismatch";
case innerty::DifferentErasedIsolation:
return "Different @isolated(any) values";
// These two have to do with specific parameters, so keep the error message
// non-plural.
case innerty::DifferingParameterConvention:
return "Differing parameter convention";
case innerty::ABIIncompatibleParameterType:
return "ABI incompatible parameter type.";
case innerty::ABIEscapeToNoEscapeConversion:
return "Escape to no escape conversion";
}
llvm_unreachable("Covered switch isn't completely covered?!");
}
TypeExpansionContext::TypeExpansionContext(const SILFunction &f)
: expansion(f.getResilienceExpansion()),
inContext(f.getModule().getAssociatedContext()),
isContextWholeModule(f.getModule().isWholeModule()) {}
CanSILFunctionType SILFunction::getLoweredFunctionTypeInContext(
TypeExpansionContext context) const {
auto origFunTy = getLoweredFunctionType();
auto &M = getModule();
auto funTy = M.Types.getLoweredType(origFunTy , context);
return cast<SILFunctionType>(funTy.getASTType());
}
bool SILFunctionConventions::isTypedError() const {
return !funcTy->getErrorResult()
.getInterfaceType()->isEqual(
funcTy->getASTContext().getErrorExistentialType()) ||
hasIndirectSILErrorResults();
}
|