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
|
//===--- InstOptUtils.cpp - SILOptimizer instruction utilities ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Utils/InstOptUtils.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/SmallPtrSetVector.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBridging.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDebugInfoExpression.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/ScopedAddressUtils.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/Analysis.h"
#include "swift/SILOptimizer/Analysis/ArraySemantic.h"
#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/OptimizerBridging.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/DebugOptUtils.h"
#include "swift/SILOptimizer/Utils/ValueLifetime.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include <deque>
#include <optional>
using namespace swift;
static llvm::cl::opt<bool> EnableExpandAll("enable-expand-all",
llvm::cl::init(false));
static llvm::cl::opt<bool> KeepWillThrowCall(
"keep-will-throw-call", llvm::cl::init(false),
llvm::cl::desc(
"Keep calls to swift_willThrow, even if the throw is optimized away"));
std::optional<SILBasicBlock::iterator>
swift::getInsertAfterPoint(SILValue val) {
if (auto *inst = val->getDefiningInstruction()) {
return std::next(inst->getIterator());
}
if (isa<SILArgument>(val)) {
return cast<SILArgument>(val)->getParentBlock()->begin();
}
return std::nullopt;
}
/// Creates an increment on \p Ptr before insertion point \p InsertPt that
/// creates a strong_retain if \p Ptr has reference semantics itself or a
/// retain_value if \p Ptr is a non-trivial value without reference-semantics.
NullablePtr<SILInstruction>
swift::createIncrementBefore(SILValue ptr, SILInstruction *insertPt) {
// Set up the builder we use to insert at our insertion point.
SILBuilder builder(insertPt);
auto loc = RegularLocation::getAutoGeneratedLocation();
// If we have a trivial type, just bail, there is no work to do.
if (ptr->getType().isTrivial(builder.getFunction()))
return nullptr;
// If Ptr is refcounted itself, create the strong_retain and
// return.
if (ptr->getType().isReferenceCounted(builder.getModule())) {
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ptr->getType().is<Name##StorageType>()) \
return builder.create##Name##Retain(loc, ptr, \
builder.getDefaultAtomicity());
#include "swift/AST/ReferenceStorage.def"
return builder.createStrongRetain(loc, ptr,
builder.getDefaultAtomicity());
}
// Otherwise, create the retain_value.
return builder.createRetainValue(loc, ptr, builder.getDefaultAtomicity());
}
/// Creates a decrement on \p ptr before insertion point \p InsertPt that
/// creates a strong_release if \p ptr has reference semantics itself or
/// a release_value if \p ptr is a non-trivial value without
/// reference-semantics.
NullablePtr<SILInstruction>
swift::createDecrementBefore(SILValue ptr, SILInstruction *insertPt) {
// Setup the builder we will use to insert at our insertion point.
SILBuilder builder(insertPt);
auto loc = RegularLocation::getAutoGeneratedLocation();
if (ptr->getType().isTrivial(builder.getFunction()))
return nullptr;
// If ptr has reference semantics itself, create a strong_release.
if (ptr->getType().isReferenceCounted(builder.getModule())) {
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ptr->getType().is<Name##StorageType>()) \
return builder.create##Name##Release(loc, ptr, \
builder.getDefaultAtomicity());
#include "swift/AST/ReferenceStorage.def"
return builder.createStrongRelease(loc, ptr,
builder.getDefaultAtomicity());
}
// Otherwise create a release value.
return builder.createReleaseValue(loc, ptr, builder.getDefaultAtomicity());
}
/// Returns true if OSSA scope ending instructions end_borrow/destroy_value can
/// be deleted trivially
bool swift::canTriviallyDeleteOSSAEndScopeInst(SILInstruction *i) {
if (!isa<EndBorrowInst>(i) && !isa<DestroyValueInst>(i))
return false;
if (isa<StoreBorrowInst>(i->getOperand(0)))
return false;
auto opValue = i->getOperand(0);
// We can delete destroy_value with operands of none ownership unless
// they are move-only values, which can have custom deinit
return opValue->getOwnershipKind() == OwnershipKind::None &&
!opValue->getType().isMoveOnly();
}
/// Perform a fast local check to see if the instruction is dead.
///
/// This routine only examines the state of the instruction at hand.
bool swift::isInstructionTriviallyDead(SILInstruction *inst) {
// At Onone, consider all uses, including the debug_info.
// This way, debug_info is preserved at Onone.
if (inst->hasUsesOfAnyResult()
&& inst->getFunction()->getEffectiveOptimizationMode()
<= OptimizationMode::NoOptimization)
return false;
if (!onlyHaveDebugUsesOfAllResults(inst) || isa<TermInst>(inst))
return false;
if (auto *bi = dyn_cast<BuiltinInst>(inst)) {
// Although the onFastPath builtin has no side-effects we don't want to
// remove it.
if (bi->getBuiltinInfo().ID == BuiltinValueKind::OnFastPath)
return false;
return !bi->mayHaveSideEffects();
}
// condfail instructions that obviously can't fail are dead.
if (auto *cfi = dyn_cast<CondFailInst>(inst))
if (auto *ili = dyn_cast<IntegerLiteralInst>(cfi->getOperand()))
if (!ili->getValue())
return true;
// mark_uninitialized is never dead.
if (isa<MarkUninitializedInst>(inst))
return false;
if (isa<DebugValueInst>(inst))
return false;
// These invalidate enums so "write" memory, but that is not an essential
// operation so we can remove these if they are trivially dead.
if (isa<UncheckedTakeEnumDataAddrInst>(inst))
return true;
// An ossa end scope instruction is trivially dead if its operand has
// OwnershipKind::None. This can occur after CFG simplification in the
// presence of non-payloaded or trivial payload cases of non-trivial enums.
//
// Examples of ossa end_scope instructions: end_borrow, destroy_value.
if (inst->getFunction()->hasOwnership() &&
canTriviallyDeleteOSSAEndScopeInst(inst))
return true;
if (!inst->mayHaveSideEffects())
return true;
return false;
}
/// Return true if this is a release instruction and the released value
/// is a part of a guaranteed parameter.
bool swift::isIntermediateRelease(SILInstruction *inst,
EpilogueARCFunctionInfo *eafi) {
// Check whether this is a release instruction.
if (!isa<StrongReleaseInst>(inst) && !isa<ReleaseValueInst>(inst))
return false;
// OK. we have a release instruction.
// Check whether this is a release on part of a guaranteed function argument.
SILValue Op = stripValueProjections(inst->getOperand(0));
auto *arg = dyn_cast<SILFunctionArgument>(Op);
if (!arg)
return false;
// This is a release on a guaranteed parameter. Its not the final release.
if (arg->hasConvention(SILArgumentConvention::Direct_Guaranteed))
return true;
// This is a release on an owned parameter and its not the epilogue release.
// Its not the final release.
auto rel = eafi->computeEpilogueARCInstructions(
EpilogueARCContext::EpilogueARCKind::Release, arg);
if (rel.size() && !rel.count(inst))
return true;
// Failed to prove anything.
return false;
}
bool swift::hasOnlyEndOfScopeOrEndOfLifetimeUses(SILInstruction *inst) {
for (SILValue result : inst->getResults()) {
for (Operand *use : result->getUses()) {
SILInstruction *user = use->getUser();
bool isDebugUser = user->isDebugInstruction();
if (!isa<DestroyValueInst>(user) && !isa<EndLifetimeInst>(user)
&& !isa<DeallocStackInst>(user) && !isEndOfScopeMarker(user)
&& !isDebugUser) {
return false;
}
// Include debug uses only in Onone mode.
if (isDebugUser && inst->getFunction()->getEffectiveOptimizationMode() <=
OptimizationMode::NoOptimization)
return false;
}
}
return true;
}
unsigned swift::getNumInOutArguments(FullApplySite applySite) {
assert(applySite);
auto substConv = applySite.getSubstCalleeConv();
unsigned numIndirectResults = substConv.getNumIndirectSILResults();
unsigned numInOutArguments = 0;
for (unsigned argIndex = 0; argIndex < applySite.getNumArguments();
argIndex++) {
// Skip indirect results.
if (argIndex < numIndirectResults) {
continue;
}
auto paramNumber = argIndex - numIndirectResults;
auto ParamConvention =
substConv.getParameters()[paramNumber].getConvention();
switch (ParamConvention) {
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable: {
++numInOutArguments;
break;
default:
break;
}
}
}
return numInOutArguments;
}
/// If the given instruction is dead, delete it along with its dead
/// operands.
///
/// \param inst The instruction to be deleted.
/// \param force If force is set, don't check if the top level instruction is
/// considered dead - delete it regardless.
void swift::recursivelyDeleteTriviallyDeadInstructions(
SILInstruction *inst, bool force, InstModCallbacks callbacks) {
ArrayRef<SILInstruction *> ai = ArrayRef<SILInstruction *>(inst);
recursivelyDeleteTriviallyDeadInstructions(ai, force, callbacks);
}
void swift::collectUsesOfValue(SILValue v,
llvm::SmallPtrSetImpl<SILInstruction *> &insts) {
for (auto ui = v->use_begin(), E = v->use_end(); ui != E; ++ui) {
auto *user = ui->getUser();
// Instruction has been processed.
if (!insts.insert(user).second)
continue;
// Collect the users of this instruction.
for (auto result : user->getResults())
collectUsesOfValue(result, insts);
}
}
void swift::eraseUsesOfValue(SILValue v) {
llvm::SmallPtrSet<SILInstruction *, 4> insts;
// Collect the uses.
collectUsesOfValue(v, insts);
// Erase the uses, we can have instructions that become dead because
// of the removal of these instructions, leave to DCE to cleanup.
// Its not safe to do recursively delete here as some of the SILInstruction
// maybe tracked by this set.
for (auto inst : insts) {
inst->replaceAllUsesOfAllResultsWithUndef();
inst->eraseFromParent();
}
}
bool swift::hasValueDeinit(SILType type) {
// Do not look inside an aggregate type that has a user-deinit, for which
// memberwise-destruction is not equivalent to aggregate destruction.
if (auto *nominal = type.getNominalOrBoundGenericNominal()) {
return nominal->getValueTypeDestructor() != nullptr;
}
return false;
}
SILValue swift::
getConcreteValueOfExistentialBox(AllocExistentialBoxInst *existentialBox,
SILInstruction *ignoreUser) {
StoreInst *singleStore = nullptr;
SmallPtrSetVector<Operand *, 32> worklist;
for (auto *use : getNonDebugUses(existentialBox)) {
worklist.insert(use);
}
while (!worklist.empty()) {
auto *use = worklist.pop_back_val();
SILInstruction *user = use->getUser();
switch (user->getKind()) {
case SILInstructionKind::StrongRetainInst:
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::DestroyValueInst:
case SILInstructionKind::EndBorrowInst:
break;
case SILInstructionKind::CopyValueInst:
case SILInstructionKind::BeginBorrowInst:
// Look through copy_value, begin_borrow
for (SILValue result : user->getResults())
for (auto *transitiveUse : result->getUses())
worklist.insert(transitiveUse);
break;
case SILInstructionKind::ProjectExistentialBoxInst: {
auto *projectedAddr = cast<ProjectExistentialBoxInst>(user);
for (Operand *addrUse : getNonDebugUses(projectedAddr)) {
if (auto *store = dyn_cast<StoreInst>(addrUse->getUser())) {
assert(store->getSrc() != projectedAddr && "cannot store an address");
// Bail if there are multiple stores.
if (singleStore)
return SILValue();
singleStore = store;
continue;
}
// If there are other users to the box value address then bail out.
return SILValue();
}
break;
}
case SILInstructionKind::BuiltinInst: {
auto *builtin = cast<BuiltinInst>(user);
if (KeepWillThrowCall ||
builtin->getBuiltinInfo().ID != BuiltinValueKind::WillThrow) {
return SILValue();
}
break;
}
default:
if (user != ignoreUser)
return SILValue();
break;
}
}
if (!singleStore)
return SILValue();
return singleStore->getSrc();
}
SILValue swift::
getConcreteValueOfExistentialBoxAddr(SILValue addr, SILInstruction *ignoreUser) {
auto *stackLoc = dyn_cast<AllocStackInst>(addr);
if (!stackLoc)
return SILValue();
StoreInst *singleStackStore = nullptr;
for (Operand *stackUse : stackLoc->getUses()) {
SILInstruction *stackUser = stackUse->getUser();
switch (stackUser->getKind()) {
case SILInstructionKind::DestroyAddrInst: {
// Make sure the destroy_addr is the instruction before one of our
// dealloc_stack insts and is directly on the stack location.
auto next = std::next(stackUser->getIterator());
if (auto *dsi = dyn_cast<DeallocStackInst>(next))
if (dsi->getOperand() != stackLoc)
return SILValue();
break;
}
case SILInstructionKind::DeallocStackInst:
case SILInstructionKind::LoadInst:
break;
case SILInstructionKind::DebugValueInst:
if (!DebugValueInst::hasAddrVal(stackUser)) {
if (stackUser != ignoreUser)
return SILValue();
}
break;
case SILInstructionKind::StoreInst: {
auto *store = cast<StoreInst>(stackUser);
assert(store->getSrc() != stackLoc && "cannot store an address");
// Bail if there are multiple stores.
if (singleStackStore)
return SILValue();
singleStackStore = store;
break;
}
default:
if (stackUser != ignoreUser)
return SILValue();
break;
}
}
if (!singleStackStore)
return SILValue();
// Look through copy value insts.
SILValue val = singleStackStore->getSrc();
while (auto *cvi = dyn_cast<CopyValueInst>(val))
val = cvi->getOperand();
auto *box = dyn_cast<AllocExistentialBoxInst>(val);
if (!box)
return SILValue();
return getConcreteValueOfExistentialBox(box, singleStackStore);
}
bool swift::mayBindDynamicSelf(SILFunction *F) {
if (!F->hasDynamicSelfMetadata())
return false;
SILValue mdArg = F->getDynamicSelfMetadata();
for (Operand *mdUse : mdArg->getUses()) {
SILInstruction *mdUser = mdUse->getUser();
for (Operand &typeDepOp : mdUser->getTypeDependentOperands()) {
if (typeDepOp.get() == mdArg)
return true;
}
}
return false;
}
static SILValue skipAddrProjections(SILValue v) {
for (;;) {
switch (v->getKind()) {
case ValueKind::IndexAddrInst:
case ValueKind::IndexRawPointerInst:
case ValueKind::StructElementAddrInst:
case ValueKind::TupleElementAddrInst:
v = cast<SingleValueInstruction>(v)->getOperand(0);
break;
default:
return v;
}
}
llvm_unreachable("there is no escape from an infinite loop");
}
/// Check whether the \p addr is an address of a tail-allocated array element.
bool swift::isAddressOfArrayElement(SILValue addr) {
addr = stripAddressProjections(addr);
if (auto *md = dyn_cast<MarkDependenceInst>(addr))
addr = stripAddressProjections(md->getValue());
// High-level SIL: check for an get_element_address array semantics call.
if (auto *ptrToAddr = dyn_cast<PointerToAddressInst>(addr))
if (auto *sei = dyn_cast<StructExtractInst>(ptrToAddr->getOperand())) {
ArraySemanticsCall call(sei->getOperand());
if (call && call.getKind() == ArrayCallKind::kGetElementAddress)
return true;
}
// Check for an tail-address (of an array buffer object).
if (isa<RefTailAddrInst>(skipAddrProjections(addr)))
return true;
return false;
}
/// Find a new position for an ApplyInst's FuncRef so that it dominates its
/// use. Not that FunctionRefInsts may be shared by multiple ApplyInsts.
void swift::placeFuncRef(ApplyInst *ai, DominanceInfo *domInfo) {
FunctionRefInst *funcRef = cast<FunctionRefInst>(ai->getCallee());
SILBasicBlock *domBB = domInfo->findNearestCommonDominator(
ai->getParent(), funcRef->getParent());
if (domBB == ai->getParent() && domBB != funcRef->getParent())
// Prefer to place the FuncRef immediately before the call. Since we're
// moving FuncRef up, this must be the only call to it in the block.
funcRef->moveBefore(ai);
else
// Otherwise, conservatively stick it at the beginning of the block.
funcRef->moveBefore(&*domBB->begin());
}
/// Add an argument, \p val, to the branch-edge that is pointing into
/// block \p Dest. Return a new instruction and do not erase the old
/// instruction.
TermInst *swift::addArgumentsToBranch(ArrayRef<SILValue> vals,
SILBasicBlock *dest, TermInst *branch) {
SILBuilderWithScope builder(branch);
if (auto *cbi = dyn_cast<CondBranchInst>(branch)) {
SmallVector<SILValue, 8> trueArgs;
SmallVector<SILValue, 8> falseArgs;
for (auto arg : cbi->getTrueArgs())
trueArgs.push_back(arg);
for (auto arg : cbi->getFalseArgs())
falseArgs.push_back(arg);
if (dest == cbi->getTrueBB()) {
for (auto val : vals)
trueArgs.push_back(val);
assert(trueArgs.size() == dest->getNumArguments());
} else {
for (auto val : vals)
falseArgs.push_back(val);
assert(falseArgs.size() == dest->getNumArguments());
}
return builder.createCondBranch(
cbi->getLoc(), cbi->getCondition(), cbi->getTrueBB(), trueArgs,
cbi->getFalseBB(), falseArgs, cbi->getTrueBBCount(),
cbi->getFalseBBCount());
}
if (auto *bi = dyn_cast<BranchInst>(branch)) {
SmallVector<SILValue, 8> args;
for (auto arg : bi->getArgs())
args.push_back(arg);
for (auto val : vals)
args.push_back(val);
assert(args.size() == dest->getNumArguments());
return builder.createBranch(bi->getLoc(), bi->getDestBB(), args);
}
llvm_unreachable("unsupported terminator");
}
SILLinkage swift::getSpecializedLinkage(SILFunction *f, SILLinkage linkage) {
if (hasPrivateVisibility(linkage) && !f->isAnySerialized()) {
// Specializations of private symbols should remain so, unless
// they were serialized, which can only happen when specializing
// definitions from a standard library built with -sil-serialize-all.
return SILLinkage::Private;
}
return SILLinkage::Shared;
}
/// Cast a value into the expected, ABI compatible type if necessary.
/// This may happen e.g. when:
/// - a type of the return value is a subclass of the expected return type.
/// - actual return type and expected return type differ in optionality.
/// - both types are tuple-types and some of the elements need to be casted.
/// Return the cast value and true if a CFG modification was required
/// NOTE: We intentionally combine the checking of the cast's handling
/// possibility and the transformation performing the cast in the same function,
/// to avoid any divergence between the check and the implementation in the
/// future.
///
/// \p usePoints are required when \p value has guaranteed ownership. It must be
/// the last users of the returned, casted value. A usePoint cannot be a
/// BranchInst (a phi is never the last guaranteed user). \p builder's current
/// insertion point must dominate all \p usePoints. \p usePoints must
/// collectively post-dominate \p builder's current insertion point.
///
/// NOTE: The implementation of this function is very closely related to the
/// rules checked by SILVerifier::requireABICompatibleFunctionTypes. It must
/// handle all cases recognized by SILFunctionType::isABICompatibleWith (see
/// areABICompatibleParamsOrReturns()).
std::pair<SILValue, bool /* changedCFG */>
swift::castValueToABICompatibleType(SILBuilder *builder, SILLocation loc,
SILValue value, SILType srcTy,
SILType destTy,
ArrayRef<SILInstruction *> usePoints) {
assert(value->getOwnershipKind() != OwnershipKind::Guaranteed ||
!usePoints.empty() && "guaranteed value must have use points");
// No cast is required if types are the same.
if (srcTy == destTy)
return {value, false};
if (srcTy.isAddress() && destTy.isAddress()) {
// Cast between two addresses and that's it.
return {builder->createUncheckedAddrCast(loc, value, destTy), false};
}
// If both types are classes and dest is the superclass of src,
// simply perform an upcast.
if (destTy.isExactSuperclassOf(srcTy)) {
return {builder->createUpcast(loc, value, destTy), false};
}
if (srcTy.isHeapObjectReferenceType() && destTy.isHeapObjectReferenceType()) {
return {builder->createUncheckedRefCast(loc, value, destTy), false};
}
if (auto mt1 = srcTy.getAs<AnyMetatypeType>()) {
if (auto mt2 = destTy.getAs<AnyMetatypeType>()) {
if (mt1->getRepresentation() == mt2->getRepresentation()) {
// If builder.Type needs to be casted to A.Type and
// A is a superclass of builder, then it can be done by means
// of a simple upcast.
if (mt2.getInstanceType()->isExactSuperclassOf(mt1.getInstanceType())) {
return {builder->createUpcast(loc, value, destTy), false};
}
// Cast between two metatypes and that's it.
return {builder->createUncheckedReinterpretCast(loc, value, destTy),
false};
}
}
}
// Check if src and dest types are optional.
auto optionalSrcTy = srcTy.getOptionalObjectType();
auto optionalDestTy = destTy.getOptionalObjectType();
// Both types are optional.
if (optionalDestTy && optionalSrcTy) {
// If both wrapped types are classes and dest is the superclass of src,
// simply perform an upcast.
if (optionalDestTy.isExactSuperclassOf(optionalSrcTy)) {
// Insert upcast.
return {builder->createUpcast(loc, value, destTy), false};
}
// Unwrap the original optional value.
auto *someDecl = builder->getASTContext().getOptionalSomeDecl();
auto *curBB = builder->getInsertionPoint()->getParent();
auto *contBB = curBB->split(builder->getInsertionPoint());
auto *someBB = builder->getFunction().createBasicBlockAfter(curBB);
auto *noneBB = builder->getFunction().createBasicBlockAfter(someBB);
auto *phi = contBB->createPhiArgument(destTy, value->getOwnershipKind());
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 1> caseBBs;
caseBBs.push_back(std::make_pair(someDecl, someBB));
builder->setInsertionPoint(curBB);
auto *switchEnum = builder->createSwitchEnum(loc, value, noneBB, caseBBs);
// In OSSA switch_enum destinations have terminator results.
//
// TODO: This should be in a switchEnum utility.
SILValue unwrappedValue;
if (builder->hasOwnership()) {
unwrappedValue = switchEnum->createOptionalSomeResult();
builder->setInsertionPoint(someBB);
} else {
builder->setInsertionPoint(someBB);
unwrappedValue = builder->createUncheckedEnumData(loc, value, someDecl);
}
// Cast the unwrapped value.
SILValue castedUnwrappedValue;
std::tie(castedUnwrappedValue, std::ignore) = castValueToABICompatibleType(
builder, loc, unwrappedValue, optionalSrcTy, optionalDestTy, usePoints);
// Wrap into optional. An owned value is forwarded through the cast and into
// the Optional. A borrowed value will have a nested borrow for the
// rewrapped Optional.
SILValue someValue =
builder->createOptionalSome(loc, castedUnwrappedValue, destTy);
builder->createBranch(loc, contBB, {someValue});
// Handle the None case.
builder->setInsertionPoint(noneBB);
SILValue noneValue = builder->createOptionalNone(loc, destTy);
builder->createBranch(loc, contBB, {noneValue});
builder->setInsertionPoint(contBB->begin());
return {phi, true};
}
// Src is not optional, but dest is optional.
if (!optionalSrcTy && optionalDestTy) {
auto optionalSrcCanTy =
OptionalType::get(srcTy.getASTType())->getCanonicalType();
auto loweredOptionalSrcType =
SILType::getPrimitiveObjectType(optionalSrcCanTy);
// Wrap the source value into an optional first.
SILValue wrappedValue =
builder->createOptionalSome(loc, value, loweredOptionalSrcType);
// Cast the wrapped value.
return castValueToABICompatibleType(builder, loc, wrappedValue,
wrappedValue->getType(), destTy,
usePoints);
}
// Handle tuple types.
// Extract elements, cast each of them, create a new tuple.
if (auto srcTupleTy = srcTy.getAs<TupleType>()) {
SmallVector<SILValue, 8> expectedTuple;
bool changedCFG = false;
auto castElement = [&](unsigned idx, SILValue element) {
// Cast the value if necessary.
bool neededCFGChange;
std::tie(element, neededCFGChange) = castValueToABICompatibleType(
builder, loc, element, srcTy.getTupleElementType(idx),
destTy.getTupleElementType(idx), usePoints);
changedCFG |= neededCFGChange;
expectedTuple.push_back(element);
};
builder->emitDestructureValueOperation(loc, value, castElement);
return {builder->createTuple(loc, destTy, expectedTuple), changedCFG};
}
// Function types are interchangeable if they're also ABI-compatible.
if (srcTy.is<SILFunctionType>()) {
if (destTy.is<SILFunctionType>()) {
assert(srcTy.getAs<SILFunctionType>()->isNoEscape()
== destTy.getAs<SILFunctionType>()->isNoEscape()
|| srcTy.getAs<SILFunctionType>()->getRepresentation()
!= SILFunctionType::Representation::Thick
&& "Swift thick functions that differ in escapeness are "
"not ABI "
"compatible");
// Insert convert_function.
return {builder->createConvertFunction(loc, value, destTy,
/*WithoutActuallyEscaping=*/false),
false};
}
}
NominalTypeDecl *srcNominal = srcTy.getNominalOrBoundGenericNominal();
NominalTypeDecl *destNominal = destTy.getNominalOrBoundGenericNominal();
if (srcNominal && srcNominal == destNominal &&
!layoutIsTypeDependent(srcNominal) &&
srcTy.isObject() && destTy.isObject()) {
// This can be a result from whole-module reasoning of protocol conformances.
// If a protocol only has a single conformance where the associated type (`ID`) is some
// concrete type (e.g. `Int`), then the devirtualizer knows that `p.get()`
// can only return an `Int`:
// ```
// public struct X2<ID> {
// let p: any P2<ID>
// public func testit(i: ID, x: ID) -> S2<ID> {
// return p.get(x: x)
// }
// }
// ```
// and after devirtualizing the `get` function, its result must be cast from `Int` to `ID`.
//
// The `layoutIsTypeDependent` utility is basically only used here to assert that this
// cast can only happen between layout compatible types.
return {builder->createUncheckedForwardingCast(loc, value, destTy), false};
}
llvm::errs() << "Source type: " << srcTy << "\n";
llvm::errs() << "Destination type: " << destTy << "\n";
llvm_unreachable("Unknown combination of types for casting");
}
namespace {
class TypeDependentVisitor : public CanTypeVisitor<TypeDependentVisitor, bool> {
public:
// If the type isn't actually dependent, we're okay.
bool visit(CanType type) {
if (!type->hasArchetype() && !type->hasTypeParameter())
return false;
return CanTypeVisitor::visit(type);
}
bool visitStructType(CanStructType type) {
return visitStructDecl(type->getDecl());
}
bool visitBoundGenericStructType(CanBoundGenericStructType type) {
return visitStructDecl(type->getDecl());
}
bool visitStructDecl(StructDecl *decl) {
auto rawLayout = decl->getAttrs().getAttribute<RawLayoutAttr>();
if (rawLayout) {
if (auto likeType = rawLayout->getResolvedScalarLikeType(decl)) {
return visit((*likeType)->getCanonicalType());
} else if (auto likeArray = rawLayout->getResolvedArrayLikeTypeAndCount(decl)) {
return visit(likeArray->first->getCanonicalType());
}
}
for (auto field : decl->getStoredProperties()) {
if (visit(field->getInterfaceType()->getCanonicalType()))
return true;
}
return false;
}
bool visitEnumType(CanEnumType type) {
return visitEnumDecl(type->getDecl());
}
bool visitBoundGenericEnumType(CanBoundGenericEnumType type) {
return visitEnumDecl(type->getDecl());
}
bool visitEnumDecl(EnumDecl *decl) {
if (decl->isIndirect())
return false;
for (auto elt : decl->getAllElements()) {
if (!elt->hasAssociatedValues() || elt->isIndirect())
continue;
if (visit(elt->getArgumentInterfaceType()->getCanonicalType()))
return true;
}
return false;
}
bool visitTupleType(CanTupleType type) {
for (auto eltTy : type.getElementTypes()) {
if (visit(eltTy->getCanonicalType()))
return true;
}
return false;
}
// A class reference does not depend on the layout of the class.
bool visitClassType(CanClassType type) {
return false;
}
bool visitBoundGenericClassType(CanBoundGenericClassType type) {
return false;
}
// The same for non-strong references.
bool visitReferenceStorageType(CanReferenceStorageType type) {
return false;
}
// All function types have the same layout.
bool visitAnyFunctionType(CanAnyFunctionType type) {
return false;
}
// The safe default for types we didn't handle above.
bool visitType(CanType type) {
return true;
}
};
} // end anonymous namespace
bool swift::layoutIsTypeDependent(NominalTypeDecl *decl) {
if (auto *classDecl = dyn_cast<ClassDecl>(decl)) {
return false;
} else if (auto *structDecl = dyn_cast<StructDecl>(decl)) {
return TypeDependentVisitor().visitStructDecl(structDecl);
} else {
auto *enumDecl = cast<EnumDecl>(decl);
return TypeDependentVisitor().visitEnumDecl(enumDecl);
}
}
ProjectBoxInst *swift::getOrCreateProjectBox(AllocBoxInst *abi,
unsigned index) {
SILBasicBlock::iterator iter(abi);
++iter;
assert(iter != abi->getParent()->end()
&& "alloc_box cannot be the last instruction of a block");
SILInstruction *nextInst = &*iter;
if (auto *pbi = dyn_cast<ProjectBoxInst>(nextInst)) {
if (pbi->getOperand() == abi && pbi->getFieldIndex() == index)
return pbi;
}
SILBuilder builder(nextInst);
return builder.createProjectBox(abi->getLoc(), abi, index);
}
// Peek through trivial Enum initialization, typically for pointless
// Optionals.
//
// Given an UncheckedTakeEnumDataAddrInst, check that there are no
// other uses of the Enum value and return the address used to initialized the
// enum's payload:
//
// %stack_adr = alloc_stack
// %data_adr = init_enum_data_addr %stk_adr
// %enum_adr = inject_enum_addr %stack_adr
// %copy_src = unchecked_take_enum_data_addr %enum_adr
// dealloc_stack %stack_adr
// (No other uses of %stack_adr.)
InitEnumDataAddrInst *
swift::findInitAddressForTrivialEnum(UncheckedTakeEnumDataAddrInst *utedai) {
auto *asi = dyn_cast<AllocStackInst>(utedai->getOperand());
if (!asi)
return nullptr;
SILInstruction *singleUser = nullptr;
for (auto use : asi->getUses()) {
auto *user = use->getUser();
if (user == utedai)
continue;
// As long as there's only one UncheckedTakeEnumDataAddrInst and one
// InitEnumDataAddrInst, we don't care how many InjectEnumAddr and
// DeallocStack users there are.
if (isa<InjectEnumAddrInst>(user) || isa<DeallocStackInst>(user))
continue;
if (singleUser)
return nullptr;
singleUser = user;
}
if (!singleUser)
return nullptr;
// Assume, without checking, that the returned InitEnumDataAddr dominates the
// given UncheckedTakeEnumDataAddrInst, because that's how SIL is defined. I
// don't know where this is actually verified.
return dyn_cast<InitEnumDataAddrInst>(singleUser);
}
//===----------------------------------------------------------------------===//
// Closure Deletion
//===----------------------------------------------------------------------===//
/// NOTE: Instructions with transitive ownership kind are assumed to not keep
/// the underlying value alive as well. This is meant for instructions only
/// with non-transitive users.
static bool useDoesNotKeepValueAlive(const SILInstruction *inst) {
switch (inst->getKind()) {
case SILInstructionKind::StrongRetainInst:
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::DestroyValueInst:
case SILInstructionKind::RetainValueInst:
case SILInstructionKind::ReleaseValueInst:
case SILInstructionKind::DebugValueInst:
case SILInstructionKind::EndBorrowInst:
return true;
default:
return false;
}
}
static bool useHasTransitiveOwnership(const SILInstruction *inst) {
// convert_escape_to_noescape is used to convert to a @noescape function type.
// It does not change ownership of the function value.
if (isa<ConvertEscapeToNoEscapeInst>(inst))
return true;
// Look through copy_value, begin_borrow, move_value. They are inert for our
// purposes, but we need to look through it.
return isa<CopyValueInst>(inst) || isa<BeginBorrowInst>(inst) ||
isa<MoveValueInst>(inst);
}
static bool shouldDestroyPartialApplyCapturedArg(SILValue arg,
SILParameterInfo paramInfo,
const SILFunction &F) {
// If we have a non-trivial type and the argument is passed in @inout, we do
// not need to destroy it here. This is something that is implicit in the
// partial_apply design that will be revisited when partial_apply is
// redesigned.
if (paramInfo.isIndirectMutating())
return false;
// If we have a trivial type, we do not need to put in any extra releases.
if (arg->getType().isTrivial(F))
return false;
// We handle all other cases.
return true;
}
void swift::emitDestroyOperation(SILBuilder &builder, SILLocation loc,
SILValue operand, InstModCallbacks callbacks) {
// If we have an address, we insert a destroy_addr and return. Any live range
// issues must have been dealt with by our caller.
if (operand->getType().isAddress()) {
// Then emit the destroy_addr for this operand. This function does not
// delete any instructions
SILInstruction *newInst = builder.emitDestroyAddrAndFold(loc, operand);
if (newInst != nullptr)
callbacks.createdNewInst(newInst);
return;
}
// Otherwise, we have an object. We emit the most optimized form of release
// possible for that value.
// If we have qualified ownership, we should just emit a destroy value.
if (builder.getFunction().hasOwnership()) {
callbacks.createdNewInst(builder.createDestroyValue(loc, operand));
return;
}
if (operand->getType().hasReferenceSemantics()) {
auto u = builder.emitStrongRelease(loc, operand);
if (u.isNull())
return;
if (auto *SRI = u.dyn_cast<StrongRetainInst *>()) {
callbacks.deleteInst(SRI);
return;
}
callbacks.createdNewInst(u.get<StrongReleaseInst *>());
return;
}
auto u = builder.emitReleaseValue(loc, operand);
if (u.isNull())
return;
if (auto *rvi = u.dyn_cast<RetainValueInst *>()) {
callbacks.deleteInst(rvi);
return;
}
callbacks.createdNewInst(u.get<ReleaseValueInst *>());
}
// NOTE: The ownership of the partial_apply argument does not match the
// convention of the closed over function. All non-inout arguments to a
// partial_apply are passed at +1 for regular escaping closures and +0 for
// closures that have been promoted to partial_apply [on_stack]. An escaping
// partial apply stores each capture in an owned box, even for guaranteed and
// in_guaranteed argument convention. A non-escaping/on-stack closure either
// borrows its arguments or takes an inout_aliasable address. Non-escaping
// closures do not support owned arguments.
void swift::releasePartialApplyCapturedArg(SILBuilder &builder, SILLocation loc,
SILValue arg,
SILParameterInfo paramInfo,
InstModCallbacks callbacks) {
if (!shouldDestroyPartialApplyCapturedArg(arg, paramInfo,
builder.getFunction()))
return;
emitDestroyOperation(builder, loc, arg, callbacks);
}
static bool
deadMarkDependenceUser(SILInstruction *inst,
SmallVectorImpl<SILInstruction *> &deleteInsts) {
if (!isa<MarkDependenceInst>(inst))
return false;
deleteInsts.push_back(inst);
for (auto *use : cast<SingleValueInstruction>(inst)->getUses()) {
if (!deadMarkDependenceUser(use->getUser(), deleteInsts))
return false;
}
return true;
}
void swift::getConsumedPartialApplyArgs(PartialApplyInst *pai,
SmallVectorImpl<Operand *> &argOperands,
bool includeTrivialAddrArgs) {
ApplySite applySite(pai);
SILFunctionConventions calleeConv = applySite.getSubstCalleeConv();
unsigned firstCalleeArgIdx = applySite.getCalleeArgIndexOfFirstAppliedArg();
auto argList = pai->getArgumentOperands();
SILFunction *F = pai->getFunction();
for (unsigned i : indices(argList)) {
auto argConv = calleeConv.getSILArgumentConvention(firstCalleeArgIdx + i);
if (argConv.isInoutConvention())
continue;
Operand &argOp = argList[i];
SILType ty = argOp.get()->getType();
if (!ty.isTrivial(*F) || (includeTrivialAddrArgs && ty.isAddress()))
argOperands.push_back(&argOp);
}
}
bool swift::collectDestroys(SingleValueInstruction *inst,
SmallVectorImpl<Operand *> &destroys) {
bool isDead = true;
for (Operand *use : inst->getUses()) {
SILInstruction *user = use->getUser();
if (useHasTransitiveOwnership(user)) {
if (!collectDestroys(cast<SingleValueInstruction>(user), destroys))
isDead = false;
destroys.push_back(use);
} else if (useDoesNotKeepValueAlive(user)) {
destroys.push_back(use);
} else {
isDead = false;
}
}
return isDead;
}
/// Move the original arguments of the partial_apply into newly created
/// temporaries to extend the lifetime of the arguments until the partial_apply
/// is finally destroyed.
///
/// TODO: figure out why this is needed at all. Probably because of some
/// weirdness of the old retain/release ARC model. Most likely this will
/// not be needed anymore with OSSA.
static bool keepArgsOfPartialApplyAlive(PartialApplyInst *pai,
ArrayRef<Operand *> paiUses,
SILBuilderContext &builderCtxt,
InstModCallbacks callbacks) {
SmallVector<Operand *, 8> argsToHandle;
getConsumedPartialApplyArgs(pai, argsToHandle,
/*includeTrivialAddrArgs*/ false);
if (argsToHandle.empty())
return true;
// Compute the set of endpoints, which will be used to insert destroys of
// temporaries. This may fail if the frontier is located on a critical edge
// which we may not split.
ValueLifetimeAnalysis vla(pai, paiUses);
ValueLifetimeAnalysis::Frontier partialApplyFrontier;
if (!vla.computeFrontier(partialApplyFrontier,
ValueLifetimeAnalysis::DontModifyCFG)) {
return false;
}
// We must not introduce copies for move only types.
// TODO: in OSSA, instead of bailing, it's possible to destroy the arguments
// without the need of copies.
for (Operand *argOp : argsToHandle) {
if (argOp->get()->getType().isMoveOnly())
return false;
}
for (Operand *argOp : argsToHandle) {
SILValue arg = argOp->get();
SILValue tmp = arg;
if (arg->getType().isAddress()) {
// Move the value to a stack-allocated temporary.
SILBuilderWithScope builder(pai, builderCtxt);
tmp = builder.createAllocStack(pai->getLoc(), arg->getType());
builder.createCopyAddr(pai->getLoc(), arg, tmp, IsTake_t::IsTake,
IsInitialization_t::IsInitialization);
}
// Delay the destroy of the value (either as SSA value or in the stack-
// allocated temporary) at the end of the partial_apply's lifetime.
endLifetimeAtFrontier(tmp, partialApplyFrontier, builderCtxt, callbacks);
}
return true;
}
bool swift::tryDeleteDeadClosure(SingleValueInstruction *closure,
InstModCallbacks callbacks,
bool needKeepArgsAlive) {
auto *pa = dyn_cast<PartialApplyInst>(closure);
// We currently only handle locally identified values that do not escape. We
// also assume that the partial apply does not capture any addresses.
if (!pa && !isa<ThinToThickFunctionInst>(closure))
return false;
// A stack allocated partial apply does not have any release users. Delete it
// if the only users are the dealloc_stack and mark_dependence instructions.
if (pa && pa->isOnStack()) {
SmallVector<SILInstruction *, 8> deleteInsts;
for (auto *use : pa->getUses()) {
SILInstruction *user = use->getUser();
if (isa<DeallocStackInst>(user)
|| isa<DebugValueInst>(user)
|| isa<DestroyValueInst>(user)) {
deleteInsts.push_back(user);
} else if (!deadMarkDependenceUser(user, deleteInsts)) {
return false;
}
}
for (auto *inst : reverse(deleteInsts))
callbacks.deleteInst(inst);
callbacks.deleteInst(pa);
// Note: the lifetime of the captured arguments is managed outside of the
// trivial closure value i.e: there will already be releases for the
// captured arguments. Releasing captured arguments is not necessary.
return true;
}
// Collect all destroys of the closure (transitively including destroys of
// copies) and check if those are the only uses of the closure.
SmallVector<Operand *, 16> closureDestroys;
if (!collectDestroys(closure, closureDestroys))
return false;
// If we have a partial_apply, release each captured argument at each one of
// the final release locations of the partial apply.
if (auto *pai = dyn_cast<PartialApplyInst>(closure)) {
assert(!pa->isOnStack() &&
"partial_apply [stack] should have been handled before");
SILBuilderContext builderCtxt(pai->getModule());
if (needKeepArgsAlive) {
if (!keepArgsOfPartialApplyAlive(pai, closureDestroys, builderCtxt,
callbacks))
return false;
} else {
// A preceding partial_apply -> apply conversion (done in
// tryOptimizeApplyOfPartialApply) already ensured that the arguments are
// kept alive until the end of the partial_apply's lifetime.
SmallVector<Operand *, 8> argsToHandle;
getConsumedPartialApplyArgs(pai, argsToHandle,
/*includeTrivialAddrArgs*/ false);
// We can just destroy the arguments at the point of the partial_apply
// (remember: partial_apply consumes all arguments).
for (Operand *argOp : argsToHandle) {
SILValue arg = argOp->get();
SILBuilderWithScope builder(pai, builderCtxt);
emitDestroyOperation(builder, pai->getLoc(), arg, callbacks);
}
}
}
// Delete all copy and destroy instructions in order so that leaf uses are
// deleted first.
for (auto *use : closureDestroys) {
auto *user = use->getUser();
assert(
(useDoesNotKeepValueAlive(user) || useHasTransitiveOwnership(user)) &&
"We expect only ARC operations without "
"results or a cast from escape to noescape without users");
callbacks.deleteInst(user);
}
callbacks.deleteInst(closure);
return true;
}
bool swift::simplifyUsers(SingleValueInstruction *inst) {
bool changed = false;
InstModCallbacks callbacks;
for (auto ui = inst->use_begin(), ue = inst->use_end(); ui != ue;) {
SILInstruction *user = ui->getUser();
++ui;
auto svi = dyn_cast<SingleValueInstruction>(user);
if (!svi)
continue;
callbacks.resetHadCallbackInvocation();
simplifyAndReplaceAllSimplifiedUsesAndErase(svi, callbacks);
changed |= callbacks.hadCallbackInvocation();
}
return changed;
}
// True if a type can be expanded without a significant increase to code size.
//
// False if expanding a type is invalid. For example, expanding a
// struct-with-deinit drops the deinit.
bool swift::shouldExpand(SILModule &module, SILType ty) {
// FIXME: Expansion
auto expansion = TypeExpansionContext::minimal();
if (module.Types.getTypeLowering(ty, expansion).isAddressOnly()) {
return false;
}
// A move-only-with-deinit type cannot be SROA.
//
// TODO: we could loosen this requirement if all paths lead to a drop_deinit.
if (auto *nominalTy = ty.getNominalOrBoundGenericNominal()) {
if (nominalTy->getValueTypeDestructor())
return false;
}
if (EnableExpandAll) {
return true;
}
unsigned numFields = module.Types.countNumberOfFields(ty, expansion);
return (numFields <= 6);
}
/// Some support functions for the global-opt and let-properties-opts
// Encapsulate the state used for recursive analysis of a static
// initializer. Discover all the instruction in a use-def graph and return them
// in topological order.
//
// TODO: We should have a DFS utility for this sort of thing so it isn't
// recursive.
class StaticInitializerAnalysis {
SmallVectorImpl<SILInstruction *> &postOrderInstructions;
llvm::SmallDenseSet<SILValue, 8> visited;
int recursionLevel = 0;
public:
StaticInitializerAnalysis(
SmallVectorImpl<SILInstruction *> &postOrderInstructions)
: postOrderInstructions(postOrderInstructions) {}
// Perform a recursive DFS on on the use-def graph rooted at `V`. Insert
// values in the `visited` set in preorder. Insert values in
// `postOrderInstructions` in postorder so that the instructions are
// topologically def-use ordered (in execution order).
bool analyze(SILValue rootValue) {
return recursivelyAnalyzeOperand(rootValue);
}
protected:
bool recursivelyAnalyzeOperand(SILValue v) {
if (!visited.insert(v).second)
return true;
if (++recursionLevel > 50)
return false;
// TODO: For multi-result instructions, we could simply insert all result
// values in the visited set here.
auto *inst = dyn_cast<SingleValueInstruction>(v);
if (!inst)
return false;
if (!recursivelyAnalyzeInstruction(inst))
return false;
postOrderInstructions.push_back(inst);
--recursionLevel;
return true;
}
bool recursivelyAnalyzeInstruction(SILInstruction *inst) {
if (auto *si = dyn_cast<StructInst>(inst)) {
// If it is not a struct which is a simple type, bail.
if (!si->getType().isTrivial(*si->getFunction()))
return false;
return llvm::all_of(si->getAllOperands(), [&](Operand &operand) -> bool {
return recursivelyAnalyzeOperand(operand.get());
});
}
if (auto *ti = dyn_cast<TupleInst>(inst)) {
// If it is not a tuple which is a simple type, bail.
if (!ti->getType().isTrivial(*ti->getFunction()))
return false;
return llvm::all_of(ti->getAllOperands(), [&](Operand &operand) -> bool {
return recursivelyAnalyzeOperand(operand.get());
});
}
if (auto *bi = dyn_cast<BuiltinInst>(inst)) {
switch (bi->getBuiltinInfo().ID) {
case BuiltinValueKind::FPTrunc:
if (auto *li = dyn_cast<LiteralInst>(bi->getArguments()[0])) {
return recursivelyAnalyzeOperand(li);
}
return false;
default:
return false;
}
}
return isa<IntegerLiteralInst>(inst) || isa<FloatLiteralInst>(inst)
|| isa<StringLiteralInst>(inst);
}
};
/// Check if the value of v is computed by means of a simple initialization.
/// Populate `forwardInstructions` with references to all the instructions
/// that participate in the use-def graph required to compute `V`. The
/// instructions will be in def-use topological order.
bool swift::analyzeStaticInitializer(
SILValue v, SmallVectorImpl<SILInstruction *> &forwardInstructions) {
return StaticInitializerAnalysis(forwardInstructions).analyze(v);
}
/// FIXME: This must be kept in sync with replaceLoadSequence()
/// below. What a horrible design.
bool swift::canReplaceLoadSequence(SILInstruction *inst) {
if (auto *cai = dyn_cast<CopyAddrInst>(inst))
return true;
if (auto *li = dyn_cast<LoadInst>(inst))
return true;
if (auto *seai = dyn_cast<StructElementAddrInst>(inst)) {
for (auto seaiUse : seai->getUses()) {
if (!canReplaceLoadSequence(seaiUse->getUser()))
return false;
}
return true;
}
if (auto *teai = dyn_cast<TupleElementAddrInst>(inst)) {
for (auto teaiUse : teai->getUses()) {
if (!canReplaceLoadSequence(teaiUse->getUser()))
return false;
}
return true;
}
if (auto *ba = dyn_cast<BeginAccessInst>(inst)) {
for (auto use : ba->getUses()) {
if (!canReplaceLoadSequence(use->getUser()))
return false;
}
return true;
}
// Incidental uses of an address are meaningless with regard to the loaded
// value.
if (isIncidentalUse(inst) || isa<BeginUnpairedAccessInst>(inst))
return true;
return false;
}
/// Replace load sequence which may contain
/// a chain of struct_element_addr followed by a load.
/// The sequence is traversed inside out, i.e.
/// starting with the innermost struct_element_addr
/// Move into utils.
///
/// FIXME: this utility does not make sense as an API. How can the caller
/// guarantee that the only uses of `I` are struct_element_addr and
/// tuple_element_addr?
void swift::replaceLoadSequence(SILInstruction *inst, SILValue value) {
if (auto *cai = dyn_cast<CopyAddrInst>(inst)) {
SILBuilder builder(cai);
builder.createStore(cai->getLoc(), value, cai->getDest(),
StoreOwnershipQualifier::Unqualified);
return;
}
if (auto *li = dyn_cast<LoadInst>(inst)) {
li->replaceAllUsesWith(value);
return;
}
if (auto *seai = dyn_cast<StructElementAddrInst>(inst)) {
SILBuilder builder(seai);
auto *sei =
builder.createStructExtract(seai->getLoc(), value, seai->getField());
for (auto seaiUse : seai->getUses()) {
replaceLoadSequence(seaiUse->getUser(), sei);
}
return;
}
if (auto *teai = dyn_cast<TupleElementAddrInst>(inst)) {
SILBuilder builder(teai);
auto *tei =
builder.createTupleExtract(teai->getLoc(), value, teai->getFieldIndex());
for (auto teaiUse : teai->getUses()) {
replaceLoadSequence(teaiUse->getUser(), tei);
}
return;
}
if (auto *ba = dyn_cast<BeginAccessInst>(inst)) {
for (auto use : ba->getUses()) {
replaceLoadSequence(use->getUser(), value);
}
return;
}
// Incidental uses of an address are meaningless with regard to the loaded
// value.
if (isIncidentalUse(inst) || isa<BeginUnpairedAccessInst>(inst))
return;
llvm_unreachable("Unknown instruction sequence for reading from a global");
}
std::optional<FindLocalApplySitesResult>
swift::findLocalApplySites(FunctionRefBaseInst *fri) {
SmallVector<Operand *, 32> worklist(fri->use_begin(), fri->use_end());
std::optional<FindLocalApplySitesResult> f;
f.emplace();
// Optimistically state that we have no escapes before our def-use dataflow.
f->escapes = false;
while (!worklist.empty()) {
auto *op = worklist.pop_back_val();
auto *user = op->getUser();
// If we have a full apply site as our user.
if (auto apply = FullApplySite::isa(user)) {
if (apply.getCallee() == op->get()) {
f->fullApplySites.push_back(apply);
continue;
}
}
// If we have a partial apply as a user, start tracking it, but also look at
// its users.
if (auto *pai = dyn_cast<PartialApplyInst>(user)) {
if (pai->getCallee() == op->get()) {
// Track the partial apply that we saw so we can potentially eliminate
// dead closure arguments.
f->partialApplySites.push_back(pai);
// Look to see if we can find a full application of this partial apply
// as well.
llvm::copy(pai->getUses(), std::back_inserter(worklist));
continue;
}
}
// Otherwise, see if we have any function casts to look through...
switch (user->getKind()) {
case SILInstructionKind::ThinToThickFunctionInst:
case SILInstructionKind::ConvertFunctionInst:
case SILInstructionKind::ConvertEscapeToNoEscapeInst:
llvm::copy(cast<SingleValueInstruction>(user)->getUses(),
std::back_inserter(worklist));
continue;
// A partial_apply [stack] marks its captured arguments with
// mark_dependence.
case SILInstructionKind::MarkDependenceInst:
llvm::copy(cast<SingleValueInstruction>(user)->getUses(),
std::back_inserter(worklist));
continue;
// Look through any reference count instructions since these are not
// escapes:
case SILInstructionKind::CopyValueInst:
llvm::copy(cast<CopyValueInst>(user)->getUses(),
std::back_inserter(worklist));
continue;
case SILInstructionKind::StrongRetainInst:
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::RetainValueInst:
case SILInstructionKind::ReleaseValueInst:
case SILInstructionKind::DestroyValueInst:
// A partial_apply [stack] is deallocated with a dealloc_stack.
case SILInstructionKind::DeallocStackInst:
continue;
default:
break;
}
// But everything else is considered an escape.
f->escapes = true;
}
// If we did escape and didn't find any apply sites, then we have no
// information for our users that is interesting.
if (f->escapes && f->partialApplySites.empty() && f->fullApplySites.empty())
return std::nullopt;
return f;
}
/// Insert destroys of captured arguments of partial_apply [stack].
void swift::insertDestroyOfCapturedArguments(
PartialApplyInst *pai, SILBuilder &builder,
llvm::function_ref<SILValue(SILValue)> getValueToDestroy,
SILLocation origLoc) {
assert(pai->isOnStack());
ApplySite site(pai);
SILFunctionConventions calleeConv(site.getSubstCalleeType(),
pai->getModule());
auto loc = CleanupLocation(origLoc);
for (auto &arg : pai->getArgumentOperands()) {
SILValue argValue = getValueToDestroy(arg.get());
if (!argValue)
continue;
assert(!pai->getFunction()->hasOwnership()
|| (argValue->getOwnershipKind().isCompatibleWith(
OwnershipKind::Owned)));
unsigned calleeArgumentIndex = site.getCalleeArgIndex(arg);
assert(calleeArgumentIndex >= calleeConv.getSILArgIndexOfFirstParam());
auto paramInfo = calleeConv.getParamInfoForSILArg(calleeArgumentIndex);
releasePartialApplyCapturedArg(builder, loc, argValue, paramInfo);
}
}
void swift::insertDeallocOfCapturedArguments(
PartialApplyInst *pai,
DominanceInfo *domInfo,
llvm::function_ref<SILValue(SILValue)> getAddressToDealloc)
{
assert(pai->isOnStack());
ApplySite site(pai);
SILFunctionConventions calleeConv(site.getSubstCalleeType(),
pai->getModule());
for (auto &arg : pai->getArgumentOperands()) {
unsigned calleeArgumentIndex = site.getCalleeArgIndex(arg);
assert(calleeArgumentIndex >= calleeConv.getSILArgIndexOfFirstParam());
auto paramInfo = calleeConv.getParamInfoForSILArg(calleeArgumentIndex);
if (!paramInfo.isIndirectInGuaranteed())
continue;
SILValue argValue = getAddressToDealloc(arg.get());
if (!argValue) {
continue;
}
SmallVector<SILBasicBlock *, 4> boundary;
auto *asi = cast<AllocStackInst>(argValue);
computeDominatedBoundaryBlocks(asi->getParent(), domInfo, boundary);
SmallVector<Operand *, 2> uses;
auto useFinding = findTransitiveUsesForAddress(asi, &uses);
InstructionSet users(asi->getFunction());
if (useFinding != AddressUseKind::Unknown) {
for (auto use : uses) {
users.insert(use->getUser());
}
}
for (auto *block : boundary) {
auto *terminator = block->getTerminator();
if (isa<UnreachableInst>(terminator))
continue;
SILInstruction *insertionPoint = nullptr;
if (useFinding != AddressUseKind::Unknown) {
insertionPoint = &block->front();
for (auto &instruction : llvm::reverse(*block)) {
if (users.contains(&instruction)) {
insertionPoint = instruction.getNextInstruction();
break;
}
}
} else {
insertionPoint = terminator;
}
SILBuilderWithScope builder(insertionPoint);
builder.createDeallocStack(CleanupLocation(insertionPoint->getLoc()),
argValue);
}
}
}
AbstractFunctionDecl *swift::getBaseMethod(AbstractFunctionDecl *FD) {
while (FD->getOverriddenDecl()) {
FD = FD->getOverriddenDecl();
}
return FD;
}
FullApplySite
swift::cloneFullApplySiteReplacingCallee(FullApplySite applySite,
SILValue newCallee,
SILBuilderContext &builderCtx) {
SmallVector<SILValue, 16> arguments;
llvm::copy(applySite.getArguments(), std::back_inserter(arguments));
SILBuilderWithScope builder(applySite.getInstruction(), builderCtx);
switch (applySite.getKind()) {
case FullApplySiteKind::TryApplyInst: {
auto *tai = cast<TryApplyInst>(applySite.getInstruction());
return builder.createTryApply(tai->getLoc(), newCallee,
tai->getSubstitutionMap(), arguments,
tai->getNormalBB(), tai->getErrorBB(),
tai->getApplyOptions());
}
case FullApplySiteKind::ApplyInst: {
auto *ai = cast<ApplyInst>(applySite);
auto fTy = newCallee->getType().getAs<SILFunctionType>();
auto options = ai->getApplyOptions();
// The optimizer can generate a thin_to_thick_function from a throwing thin
// to a non-throwing thick function (in case it can prove that the function
// is not throwing).
// Therefore we have to check if the new callee (= the argument of the
// thin_to_thick_function) is a throwing function and set the not-throwing
// flag in this case.
if (fTy->hasErrorResult())
options |= ApplyFlags::DoesNotThrow;
return builder.createApply(applySite.getLoc(), newCallee,
applySite.getSubstitutionMap(), arguments,
options);
}
case FullApplySiteKind::BeginApplyInst: {
llvm_unreachable("begin_apply support not implemented?!");
}
}
llvm_unreachable("Unhandled case?!");
}
// FIXME: For any situation where this may be called on an unbounded number of
// uses, it should perform a single callback invocation to notify the client
// that newValue has new uses rather than a callback for every new use.
//
// FIXME: This should almost certainly replace end_lifetime uses rather than
// deleting them.
SILBasicBlock::iterator swift::replaceAllUses(SILValue oldValue,
SILValue newValue,
SILBasicBlock::iterator nextii,
InstModCallbacks &callbacks) {
assert(oldValue != newValue && "Cannot RAUW a value with itself");
while (!oldValue->use_empty()) {
Operand *use = *oldValue->use_begin();
SILInstruction *user = use->getUser();
// Erase the end of scope marker.
if (isEndOfScopeMarker(user)) {
if (&*nextii == user)
++nextii;
callbacks.deleteInst(user);
continue;
}
callbacks.setUseValue(use, newValue);
}
return nextii;
}
SILBasicBlock::iterator
swift::replaceAllUsesAndErase(SingleValueInstruction *svi, SILValue newValue,
InstModCallbacks &callbacks) {
SILBasicBlock::iterator nextii = replaceAllUses(
svi, newValue, std::next(svi->getIterator()), callbacks);
callbacks.deleteInst(svi);
return nextii;
}
SILBasicBlock::iterator
swift::replaceAllUsesAndErase(SILValue oldValue, SILValue newValue,
InstModCallbacks &callbacks) {
auto *blockArg = dyn_cast<SILPhiArgument>(oldValue);
if (!blockArg) {
// SingleValueInstruction SSA replacement.
return replaceAllUsesAndErase(cast<SingleValueInstruction>(oldValue),
newValue, callbacks);
}
llvm_unreachable("Untested");
#if 0 // FIXME: to be enabled in a following commit
TermInst *oldTerm = blockArg->getTerminatorForResult();
assert(oldTerm && "can only replace and erase terminators, not phis");
// Before:
// oldTerm bb1, bb2
// bb1(%oldValue):
// use %oldValue
// bb2:
//
// After:
// br bb1
// bb1:
// use %newValue
// bb2:
auto nextii = replaceAllUses(blockArg, newValue,
oldTerm->getParent()->end(), callbacks);
// Now that oldValue is replaced, the terminator should have no uses
// left. The caller should have removed uses from other results.
for (auto *succBB : oldTerm->getSuccessorBlocks()) {
assert(succBB->getNumArguments() == 1 && "expected terminator result");
succBB->eraseArgument(0);
}
auto *newBr = SILBuilderWithScope(oldTerm).createBranch(
oldTerm->getLoc(), blockArg->getParent());
callbacks.createdNewInst(newBr);
callbacks.deleteInst(oldTerm);
return nextii;
#endif
}
/// Given that we are going to replace use's underlying value, if the use is a
/// lifetime ending use, insert an end scope use for the underlying value
/// before we RAUW.
static void cleanupUseOldValueBeforeRAUW(Operand *use, SILBuilder &builder,
SILLocation loc,
InstModCallbacks &callbacks) {
if (!use->isLifetimeEnding()) {
return;
}
switch (use->get()->getOwnershipKind()) {
case OwnershipKind::Any:
llvm_unreachable("Invalid ownership for value");
case OwnershipKind::Owned: {
auto *dvi = builder.createDestroyValue(loc, use->get());
callbacks.createdNewInst(dvi);
return;
}
case OwnershipKind::Guaranteed: {
// Should only happen once we model destructures as true reborrows.
auto *ebi = builder.createEndBorrow(loc, use->get());
callbacks.createdNewInst(ebi);
return;
}
case OwnershipKind::None:
return;
case OwnershipKind::Unowned:
llvm_unreachable("Unowned object can never be consumed?!");
}
llvm_unreachable("Covered switch isn't covered");
}
SILBasicBlock::iterator swift::replaceSingleUse(Operand *use, SILValue newValue,
InstModCallbacks &callbacks) {
auto oldValue = use->get();
assert(oldValue != newValue && "Cannot RAUW a value with itself");
auto *user = use->getUser();
auto nextII = std::next(user->getIterator());
// If we have an end of scope marker, just return next. We are done.
if (isEndOfScopeMarker(user)) {
return nextII;
}
// Otherwise, first insert clean up our use's value if we need to and then set
// use to have a new value.
SILBuilderWithScope builder(user);
cleanupUseOldValueBeforeRAUW(use, builder, user->getLoc(), callbacks);
callbacks.setUseValue(use, newValue);
return nextII;
}
SILValue swift::makeCopiedValueAvailable(SILValue value, SILBasicBlock *inBlock) {
if (isa<SILUndef>(value))
return value;
if (!value->getFunction()->hasOwnership())
return value;
if (value->getOwnershipKind() == OwnershipKind::None)
return value;
auto insertPt = getInsertAfterPoint(value).value();
SILBuilderWithScope builder(insertPt);
auto *copy = builder.createCopyValue(
RegularLocation::getAutoGeneratedLocation(), value);
return makeValueAvailable(copy, inBlock);
}
SILValue swift::makeValueAvailable(SILValue value, SILBasicBlock *inBlock) {
if (isa<SILUndef>(value))
return value;
if (!value->getFunction()->hasOwnership())
return value;
if (value->getOwnershipKind() == OwnershipKind::None)
return value;
assert(value->getOwnershipKind() == OwnershipKind::Owned);
SmallVector<SILBasicBlock *, 4> userBBs;
for (auto use : value->getUses()) {
userBBs.push_back(use->getParentBlock());
}
userBBs.push_back(inBlock);
// Use \p jointPostDomComputer to:
// 1. Create a control equivalent copy at \p inBlock if needed
// 2. Insert destroy_value at leaking blocks
SILValue controlEqCopy;
findJointPostDominatingSet(
value->getParentBlock(), userBBs,
[&](SILBasicBlock *loopBlock) {
assert(loopBlock == inBlock);
auto front = loopBlock->begin();
SILBuilderWithScope newBuilder(front);
controlEqCopy = newBuilder.createCopyValue(
RegularLocation::getAutoGeneratedLocation(), value);
},
[&](SILBasicBlock *postDomBlock) {
// Insert a destroy_value in the leaking block
auto front = postDomBlock->begin();
SILBuilderWithScope newBuilder(front);
newBuilder.createDestroyValue(
RegularLocation::getAutoGeneratedLocation(), value);
});
return controlEqCopy ? controlEqCopy : value;
}
bool swift::tryEliminateOnlyOwnershipUsedForwardingInst(
SingleValueInstruction *forwardingInst, InstModCallbacks &callbacks) {
auto fwdOp = ForwardingOperation(forwardingInst);
if (!fwdOp) {
return false;
}
auto *singleFwdOp = fwdOp.getSingleForwardingOperand();
if (!singleFwdOp) {
return false;
}
SmallVector<Operand *, 32> worklist(getNonDebugUses(forwardingInst));
while (!worklist.empty()) {
auto *use = worklist.pop_back_val();
auto *user = use->getUser();
if (isa<EndBorrowInst>(user) || isa<DestroyValueInst>(user) ||
isa<RefCountingInst>(user))
continue;
if (isa<CopyValueInst>(user) || isa<BeginBorrowInst>(user)) {
for (auto result : user->getResults())
for (auto *resultUse : getNonDebugUses(result))
worklist.push_back(resultUse);
continue;
}
return false;
}
// Now that we know we can perform our transform, set all uses of
// forwardingInst to be used of its operand and then delete \p forwardingInst.
auto newValue = singleFwdOp->get();
while (!forwardingInst->use_empty()) {
auto *use = *(forwardingInst->use_begin());
use->set(newValue);
}
callbacks.deleteInst(forwardingInst);
return true;
}
// The consuming use blocks are assumed either not to inside a loop relative to
// \p value or they must have their own copies.
void swift::endLifetimeAtLeakingBlocks(SILValue value,
ArrayRef<SILBasicBlock *> uses) {
if (!value->getFunction()->hasOwnership())
return;
if (value->getOwnershipKind() != OwnershipKind::Owned)
return;
findJointPostDominatingSet(
value->getParentBlock(), uses, [&](SILBasicBlock *loopBlock) {},
[&](SILBasicBlock *postDomBlock) {
// Insert a destroy_value in the leaking block
auto front = postDomBlock->begin();
SILBuilderWithScope newBuilder(front);
newBuilder.createDestroyValue(
RegularLocation::getAutoGeneratedLocation(), value);
});
}
/// Create a new debug value from a store and a debug variable.
static void transferStoreDebugValue(DebugVarCarryingInst DefiningInst,
SILInstruction *SI,
SILValue original) {
auto VarInfo = DefiningInst.getVarInfo();
if (!VarInfo)
return;
// Fix the op_deref.
if (!isa<CopyAddrInst>(SI) && VarInfo->DIExpr.startsWithDeref())
VarInfo->DIExpr.eraseElement(VarInfo->DIExpr.element_begin());
else if (isa<CopyAddrInst>(SI) && !VarInfo->DIExpr.startsWithDeref())
VarInfo->DIExpr.prependElements({
SILDIExprElement::createOperator(SILDIExprOperator::Dereference)});
// Note: The instruction should logically be in the SI's scope.
// However, LLVM does not support variables and stores in different scopes,
// so we use the variable's scope.
SILBuilder(SI, DefiningInst->getDebugScope())
.createDebugValue(SI->getLoc(), original, *VarInfo);
}
void swift::salvageStoreDebugInfo(SILInstruction *SI,
SILValue SrcVal, SILValue DestVal) {
if (auto *ASI = dyn_cast_or_null<AllocStackInst>(
DestVal.getDefiningInstruction())) {
transferStoreDebugValue(ASI, SI, SrcVal);
for (Operand *U : getDebugUses(ASI))
transferStoreDebugValue(U->getUser(), SI, SrcVal);
}
}
// TODO: this currently fails to notify the pass with notifyNewInstruction.
//
// TODO: whenever a debug_value is inserted at a new location, check that no
// other debug_value instructions exist between the old and new location for
// the same variable.
void swift::salvageDebugInfo(SILInstruction *I) {
if (!I)
return;
if (auto *SI = dyn_cast<StoreInst>(I)) {
if (SILValue DestVal = SI->getDest())
salvageStoreDebugInfo(SI, SI->getSrc(), DestVal);
}
if (auto *SI = dyn_cast<StoreBorrowInst>(I)) {
if (SILValue DestVal = SI->getDest())
salvageStoreDebugInfo(SI, SI->getSrc(), DestVal);
for (Operand *U : getDebugUses(SI))
transferStoreDebugValue(U->getUser(), SI, SI->getSrc());
}
// If a `struct` SIL instruction is "unwrapped" and removed,
// for instance, in favor of using its enclosed value directly,
// we need to make sure any of its related `debug_value` instructions
// are preserved.
if (auto *STI = dyn_cast<StructInst>(I)) {
auto STVal = STI->getResult(0);
llvm::ArrayRef<VarDecl *> FieldDecls =
STI->getStructDecl()->getStoredProperties();
for (Operand *U : getDebugUses(STVal)) {
auto *DbgInst = cast<DebugValueInst>(U->getUser());
auto VarInfo = DbgInst->getVarInfo();
if (!VarInfo)
continue;
for (VarDecl *FD : FieldDecls) {
SILDebugVariable NewVarInfo = *VarInfo;
auto FieldVal = STI->getFieldValue(FD);
// Build the corresponding fragment DIExpression
auto FragDIExpr = SILDebugInfoExpression::createFragment(FD);
NewVarInfo.DIExpr.append(FragDIExpr);
if (!NewVarInfo.Type)
NewVarInfo.Type = STI->getType();
// Create a new debug_value
SILBuilder(STI, DbgInst->getDebugScope())
.createDebugValue(DbgInst->getLoc(), FieldVal, NewVarInfo);
}
}
}
// Similarly, if a `tuple` SIL instruction is "unwrapped" and removed,
// we need to make sure any of its related `debug_value` instructions
// are preserved.
if (auto *TTI = dyn_cast<TupleInst>(I)) {
auto TTVal = TTI->getResult(0);
for (Operand *U : getDebugUses(TTVal)) {
auto *DbgInst = cast<DebugValueInst>(U->getUser());
auto VarInfo = DbgInst->getVarInfo();
if (!VarInfo)
continue;
TupleType *TT = TTI->getTupleType();
for (auto i : indices(TT->getElements())) {
SILDebugVariable NewVarInfo = *VarInfo;
auto FragDIExpr = SILDebugInfoExpression::createTupleFragment(TT, i);
NewVarInfo.DIExpr.append(FragDIExpr);
if (!NewVarInfo.Type)
NewVarInfo.Type = TTI->getType();
// Create a new debug_value
SILBuilder(TTI, DbgInst->getDebugScope())
.createDebugValue(DbgInst->getLoc(), TTI->getElement(i), NewVarInfo);
}
}
}
if (auto *IA = dyn_cast<IndexAddrInst>(I)) {
if (IA->getBase() && IA->getIndex())
// Only handle cases where offset is constant.
if (const auto *LiteralInst =
dyn_cast<IntegerLiteralInst>(IA->getIndex())) {
SILValue Base = IA->getBase();
SILValue ResultAddr = IA->getResult(0);
APInt OffsetVal = LiteralInst->getValue();
const SILDIExprElement ExprElements[3] = {
SILDIExprElement::createOperator(OffsetVal.isNegative() ?
SILDIExprOperator::ConstSInt : SILDIExprOperator::ConstUInt),
SILDIExprElement::createConstInt(OffsetVal.getLimitedValue()),
SILDIExprElement::createOperator(SILDIExprOperator::Plus)
};
for (Operand *U : getDebugUses(ResultAddr)) {
auto *DbgInst = cast<DebugValueInst>(U->getUser());
auto VarInfo = DbgInst->getVarInfo();
if (!VarInfo)
continue;
VarInfo->DIExpr.prependElements(ExprElements);
// Create a new debug_value
SILBuilder(IA, DbgInst->getDebugScope())
.createDebugValue(DbgInst->getLoc(), Base, *VarInfo);
}
}
}
if (auto *IL = dyn_cast<IntegerLiteralInst>(I)) {
APInt value = IL->getValue();
const SILDIExprElement ExprElements[2] = {
SILDIExprElement::createOperator(value.isNegative() ?
SILDIExprOperator::ConstSInt : SILDIExprOperator::ConstUInt),
SILDIExprElement::createConstInt(value.getLimitedValue()),
};
for (Operand *U : getDebugUses(IL)) {
auto *DbgInst = cast<DebugValueInst>(U->getUser());
auto VarInfo = DbgInst->getVarInfo();
if (!VarInfo)
continue;
VarInfo->DIExpr.prependElements(ExprElements);
// Create a new debug_value, with undef, and the correct const int
SILBuilder(DbgInst, DbgInst->getDebugScope())
.createDebugValue(DbgInst->getLoc(), SILUndef::get(IL), *VarInfo);
}
}
}
void swift::salvageLoadDebugInfo(LoadOperation load) {
for (Operand *debugUse : getDebugUses(load.getLoadInst())) {
// Create a new debug_value rather than reusing the old one so the
// SILBuilder adds 'expr(deref)' to account for the indirection.
auto *debugInst = cast<DebugValueInst>(debugUse->getUser());
auto varInfo = debugInst->getVarInfo();
if (!varInfo)
continue;
// The new debug_value must be "hoisted" to the load to ensure that the
// address is still valid.
SILBuilder(load.getLoadInst(), debugInst->getDebugScope())
.createDebugValueAddr(debugInst->getLoc(), load.getOperand(),
varInfo.value());
}
}
// TODO: this currently fails to notify the pass with notifyNewInstruction.
void swift::createDebugFragments(SILValue oldValue, Projection proj,
SILValue newValue) {
if (proj.getKind() != ProjectionKind::Struct)
return;
for (auto *use : getDebugUses(oldValue)) {
auto debugVal = dyn_cast<DebugValueInst>(use->getUser());
if (!debugVal)
continue;
auto varInfo = debugVal->getVarInfo();
SILType baseType = oldValue->getType();
// Copy VarInfo and add the corresponding fragment DIExpression.
SILDebugVariable newVarInfo = *varInfo;
newVarInfo.DIExpr.append(
SILDebugInfoExpression::createFragment(proj.getVarDecl(baseType)));
if (!newVarInfo.Type)
newVarInfo.Type = baseType;
// Create a new debug_value
SILBuilder(debugVal, debugVal->getDebugScope())
.createDebugValue(debugVal->getLoc(), newValue, newVarInfo);
}
}
IntegerLiteralInst *swift::optimizeBuiltinCanBeObjCClass(BuiltinInst *bi,
SILBuilder &builder) {
assert(bi->getBuiltinInfo().ID == BuiltinValueKind::CanBeObjCClass);
assert(bi->hasSubstitutions() && "Expected substitutions for canBeClass");
auto const &subs = bi->getSubstitutions();
assert((subs.getReplacementTypes().size() == 1) &&
"Expected one substitution in call to canBeClass");
auto ty = subs.getReplacementTypes()[0]->getCanonicalType();
switch (ty->canBeClass()) {
case TypeTraitResult::IsNot:
return builder.createIntegerLiteral(bi->getLoc(), bi->getType(),
APInt(8, 0));
case TypeTraitResult::Is:
return builder.createIntegerLiteral(bi->getLoc(), bi->getType(),
APInt(8, 1));
case TypeTraitResult::CanBe:
return nullptr;
}
llvm_unreachable("Unhandled TypeTraitResult in switch.");
}
SILValue swift::createEmptyAndUndefValue(SILType ty,
SILInstruction *insertionPoint,
SILBuilderContext &ctx,
bool noUndef) {
auto *function = insertionPoint->getFunction();
if (auto tupleTy = ty.getAs<TupleType>()) {
SmallVector<SILValue, 4> elements;
for (unsigned idx : range(tupleTy->getNumElements())) {
SILType elementTy = ty.getTupleElementType(idx);
auto element = createEmptyAndUndefValue(elementTy, insertionPoint, ctx);
elements.push_back(element);
}
SILBuilderWithScope builder(insertionPoint, ctx);
return builder.createTuple(insertionPoint->getLoc(), ty, elements);
}
if (auto *decl = ty.getStructOrBoundGenericStruct()) {
TypeExpansionContext tec = *function;
auto &module = function->getModule();
if (decl->isResilient(tec.getContext()->getParentModule(),
tec.getResilienceExpansion())) {
llvm::errs() << "Attempting to create value for illegal empty type:\n";
ty.print(llvm::errs());
llvm::report_fatal_error("illegal empty type: resilient struct");
}
SmallVector<SILValue, 4> elements;
for (auto *field : decl->getStoredProperties()) {
auto elementTy = ty.getFieldType(field, module, tec);
auto element = createEmptyAndUndefValue(elementTy, insertionPoint, ctx);
elements.push_back(element);
}
SILBuilderWithScope builder(insertionPoint, ctx);
return builder.createStruct(insertionPoint->getLoc(), ty, elements);
}
assert(!noUndef);
return SILUndef::get(insertionPoint->getFunction(), ty);
}
bool swift::findUnreferenceableStorage(StructDecl *decl, SILType structType,
SILFunction *func) {
if (decl->hasUnreferenceableStorage()) {
return true;
}
// Check if any fields have unreferenceable stoage
for (auto *field : decl->getStoredProperties()) {
TypeExpansionContext tec = *func;
auto fieldTy = structType.getFieldType(field, func->getModule(), tec);
if (auto *fieldStructDecl = fieldTy.getStructOrBoundGenericStruct()) {
if (findUnreferenceableStorage(fieldStructDecl, fieldTy, func)) {
return true;
}
}
}
return false;
}
//===----------------------------------------------------------------------===//
// MARK: Find Initialization Value Of Temporary Alloc Stack
//===----------------------------------------------------------------------===//
namespace {
struct AddressWalkerState {
bool foundError = false;
InstructionSet writes;
AddressWalkerState(SILFunction *fn) : writes(fn) {}
};
} // namespace
static SILValue
findRootValueForNonTupleTempAllocation(AllocationInst *allocInst,
AddressWalkerState &state) {
// These are instructions which we are ok with looking through when
// identifying our allocation. It must always refer to the entire allocation.
auto isAlloc = [&](SILValue value) -> bool {
if (auto *ieai = dyn_cast<InitExistentialAddrInst>(value))
value = ieai->getOperand();
return value == SILValue(allocInst);
};
// Walk from our allocation to one of our writes. Then make sure that the
// write writes to our entire value.
for (auto &inst : allocInst->getParent()->getRangeStartingAtInst(allocInst)) {
// See if we have a full tuple value.
if (!state.writes.contains(&inst))
continue;
if (auto *copyAddr = dyn_cast<CopyAddrInst>(&inst)) {
if (isAlloc(copyAddr->getDest()) && copyAddr->isInitializationOfDest()) {
return copyAddr->getSrc();
}
}
if (auto *si = dyn_cast<StoreInst>(&inst)) {
if (isAlloc(si->getDest()) &&
si->getOwnershipQualifier() != StoreOwnershipQualifier::Assign) {
return si->getSrc();
}
}
if (auto *sbi = dyn_cast<StoreBorrowInst>(&inst)) {
if (isAlloc(sbi->getDest()))
return sbi->getSrc();
}
// If we do not identify the write... return SILValue(). We weren't able
// to understand the write.
break;
}
return SILValue();
}
static SILValue findRootValueForTupleTempAllocation(AllocationInst *allocInst,
AddressWalkerState &state) {
SmallVector<SILValue, 8> tupleValues;
for (unsigned i : range(allocInst->getType().getNumTupleElements())) {
(void)i;
tupleValues.push_back(nullptr);
}
unsigned numEltsLeft = tupleValues.size();
// If we have an empty tuple, just return SILValue() for now.
//
// TODO: What does this pattern look like out of SILGen?
if (!numEltsLeft)
return SILValue();
// Walk from our allocation to one of our writes. Then make sure that the
// write writes to our entire value.
DestructureTupleInst *foundDestructure = nullptr;
SILValue foundRootAddress;
for (auto &inst : allocInst->getParent()->getRangeStartingAtInst(allocInst)) {
if (!state.writes.contains(&inst))
continue;
if (auto *copyAddr = dyn_cast<CopyAddrInst>(&inst)) {
if (copyAddr->isInitializationOfDest()) {
if (auto *tei = dyn_cast<TupleElementAddrInst>(copyAddr->getDest())) {
if (tei->getOperand() == allocInst) {
unsigned i = tei->getFieldIndex();
if (auto *otherTei = dyn_cast_or_null<TupleElementAddrInst>(
copyAddr->getSrc()->getDefiningInstruction())) {
// If we already were processing destructures, then we have a mix
// of struct/destructures... we do not support that, so bail.
if (foundDestructure)
return SILValue();
// Otherwise, update our root address. If we already had a root
// address and it doesn't match our tuple_element_addr's operand,
// bail. There is some sort of mix/match of tuple addresses that
// we do not support. We are looking for a specific SILGen
// pattern.
if (!foundRootAddress) {
foundRootAddress = otherTei->getOperand();
} else if (foundRootAddress != otherTei->getOperand()) {
return SILValue();
}
if (i != otherTei->getFieldIndex())
return SILValue();
if (tupleValues[i])
return SILValue();
tupleValues[i] = otherTei;
// If we have completely covered the tuple, break.
--numEltsLeft;
if (!numEltsLeft)
break;
// Otherwise, continue so we keep processing.
continue;
}
}
}
}
}
if (auto *si = dyn_cast<StoreInst>(&inst)) {
if (si->getOwnershipQualifier() != StoreOwnershipQualifier::Assign) {
// Check if we are updating the entire tuple value.
if (si->getDest() == allocInst) {
// If we already found a root address (meaning we were processing
// tuple_elt_addr), bail. We have some sort of unhandled mix of
// copy_addr and store.
if (foundRootAddress)
return SILValue();
// If we already found a destructure, return SILValue(). We are
// initializing twice.
if (foundDestructure)
return SILValue();
// We are looking for a pattern where we construct a tuple from
// destructured parts.
if (auto *ti = dyn_cast<TupleInst>(si->getSrc())) {
for (auto p : llvm::enumerate(ti->getOperandValues())) {
SILValue value = lookThroughOwnershipInsts(p.value());
if (auto *dti = dyn_cast_or_null<DestructureTupleInst>(
value->getDefiningInstruction())) {
// We should always go through the same dti.
if (foundDestructure && foundDestructure != dti)
return SILValue();
if (!foundDestructure)
foundDestructure = dti;
// If we have a mixmatch of indices, we cannot look through.
if (p.index() != dti->getIndexOfResult(value))
return SILValue();
if (tupleValues[p.index()])
return SILValue();
tupleValues[p.index()] = value;
// If we have completely covered the tuple, break.
--numEltsLeft;
if (!numEltsLeft)
break;
}
}
// If we haven't completely covered the tuple, return SILValue(). We
// should completely cover the tuple.
if (numEltsLeft)
return SILValue();
// Otherwise, break since we are done.
break;
}
}
// If we store to a tuple_element_addr, update for a single value.
if (auto *tei = dyn_cast<TupleElementAddrInst>(si->getDest())) {
if (tei->getOperand() == allocInst) {
unsigned i = tei->getFieldIndex();
if (auto *dti = dyn_cast_or_null<DestructureTupleInst>(
si->getSrc()->getDefiningInstruction())) {
// If we already found a root address (meaning we were processing
// tuple_elt_addr), bail. We have some sort of unhandled mix of
// copy_addr and store [init].
if (foundRootAddress)
return SILValue();
if (!foundDestructure) {
foundDestructure = dti;
} else if (foundDestructure != dti) {
return SILValue();
}
if (i != dti->getIndexOfResult(si->getSrc()))
return SILValue();
if (tupleValues[i])
return SILValue();
tupleValues[i] = si->getSrc();
// If we have completely covered the tuple, break.
--numEltsLeft;
if (!numEltsLeft)
break;
// Otherwise, continue so we keep processing.
continue;
}
}
}
}
}
// Found a write that we did not understand... bail.
break;
}
// Now check if we have a complete tuple with all elements coming from the
// same destructure_tuple. In such a case, we can look through the
// destructure_tuple.
if (numEltsLeft)
return SILValue();
if (foundDestructure)
return foundDestructure->getOperand();
if (foundRootAddress)
return foundRootAddress;
return SILValue();
}
SILValue swift::getInitOfTemporaryAllocStack(AllocStackInst *asi) {
// If we are from a VarDecl, bail.
if (asi->isFromVarDecl())
return SILValue();
struct AddressWalker final : public TransitiveAddressWalker<AddressWalker> {
AddressWalkerState &state;
AddressWalker(AddressWalkerState &state) : state(state) {}
bool visitUse(Operand *use) {
if (use->getUser()->mayWriteToMemory())
state.writes.insert(use->getUser());
return true;
}
TransitiveUseVisitation visitTransitiveUseAsEndPointUse(Operand *use) {
if (auto *sbi = dyn_cast<StoreBorrowInst>(use->getUser()))
return TransitiveUseVisitation::OnlyUser;
return TransitiveUseVisitation::OnlyUses;
}
void onError(Operand *use) { state.foundError = true; }
};
AddressWalkerState state(asi->getFunction());
AddressWalker walker(state);
if (std::move(walker).walk(asi) == AddressUseKind::Unknown ||
state.foundError)
return SILValue();
if (asi->getType().is<TupleType>())
return findRootValueForTupleTempAllocation(asi, state);
return findRootValueForNonTupleTempAllocation(asi, state);
}
|