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
|
//===--- SILGen.cpp - Implements Lowering of ASTs -> SIL ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "silgen"
#include "ManagedValue.h"
#include "RValue.h"
#include "SILGenFunction.h"
#include "SILGenFunctionBuilder.h"
#include "SILGenTopLevel.h"
#include "Scope.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Evaluator.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ResilienceExpansion.h"
#include "swift/AST/SILGenRequests.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Statistic.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Frontend/Frontend.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILProfiler.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Serialization/SerializedSILLoader.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "llvm/ProfileData/InstrProfReader.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace Lowering;
//===----------------------------------------------------------------------===//
// SILGenModule Class implementation
//===----------------------------------------------------------------------===//
SILGenModule::SILGenModule(SILModule &M, ModuleDecl *SM)
: M(M), Types(M.Types), SwiftModule(SM),
FileIDsByFilePath(SM->computeFileIDMap(/*shouldDiagnose=*/true)) {
const SILOptions &Opts = M.getOptions();
if (!Opts.UseProfile.empty()) {
// FIXME: Create file system to read the profile. In the future, the vfs
// needs to come from CompilerInstance.
auto FS = llvm::vfs::getRealFileSystem();
auto ReaderOrErr =
llvm::IndexedInstrProfReader::create(Opts.UseProfile, *FS);
if (auto E = ReaderOrErr.takeError()) {
diagnose(SourceLoc(), diag::profile_read_error, Opts.UseProfile,
llvm::toString(std::move(E)));
} else {
M.setPGOReader(std::move(ReaderOrErr.get()));
}
}
}
SILGenModule::~SILGenModule() {
// Update the linkage of external private functions to public_external,
// because there is no private_external linkage. External private functions
// can occur in the following cases:
//
// * private class methods which are referenced from the vtable of a derived
// class in a different file/module. Such private methods are always
// generated with public linkage in the other file/module.
//
// * in lldb: lldb can access private declarations in other files/modules
//
// * private functions with a @_silgen_name attribute but without a body
//
// * when compiling with -disable-access-control
//
for (SILFunction &f : M.getFunctionList()) {
if (f.getLinkage() == SILLinkage::Private && f.isExternalDeclaration())
f.setLinkage(SILLinkage::PublicExternal);
}
M.verifyIncompleteOSSA();
}
static SILDeclRef getBridgingFn(std::optional<SILDeclRef> &cacheSlot,
SILGenModule &SGM, Identifier moduleName,
StringRef functionName,
std::initializer_list<Type> inputTypes,
Type outputType) {
if (!cacheSlot) {
ASTContext &ctx = SGM.M.getASTContext();
ModuleDecl *mod = ctx.getLoadedModule(moduleName);
if (!mod) {
SGM.diagnose(SourceLoc(), diag::bridging_module_missing,
moduleName.str(), functionName);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
SmallVector<ValueDecl *, 2> decls;
mod->lookupValue(ctx.getIdentifier(functionName),
NLKind::QualifiedLookup, decls);
if (decls.empty()) {
SGM.diagnose(SourceLoc(), diag::bridging_function_missing,
moduleName.str(), functionName);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
if (decls.size() != 1) {
SGM.diagnose(SourceLoc(), diag::bridging_function_overloaded,
moduleName.str(), functionName);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
auto *fd = dyn_cast<FuncDecl>(decls.front());
if (!fd) {
SGM.diagnose(SourceLoc(), diag::bridging_function_not_function,
moduleName.str(), functionName);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
// Check that the function takes the expected arguments and returns the
// expected result type.
SILDeclRef c(fd);
auto funcTy =
SGM.Types.getConstantFunctionType(TypeExpansionContext::minimal(), c);
SILFunctionConventions fnConv(funcTy, SGM.M);
auto toSILType = [&SGM](Type ty) {
return SGM.Types.getLoweredType(ty, TypeExpansionContext::minimal());
};
if (fnConv.hasIndirectSILResults() ||
funcTy->getNumParameters() != inputTypes.size() ||
!std::equal(
fnConv.getParameterSILTypes(TypeExpansionContext::minimal())
.begin(),
fnConv.getParameterSILTypes(TypeExpansionContext::minimal()).end(),
makeTransformIterator(inputTypes.begin(), toSILType))) {
SGM.diagnose(fd->getLoc(), diag::bridging_function_not_correct_type,
moduleName.str(), functionName);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
if (fnConv.getSingleSILResultType(TypeExpansionContext::minimal()) !=
toSILType(outputType)) {
SGM.diagnose(fd->getLoc(), diag::bridging_function_not_correct_type,
moduleName.str(), functionName);
llvm::report_fatal_error("unable to set up the ObjC bridge!");
}
cacheSlot = c;
}
LLVM_DEBUG(llvm::dbgs() << "bridging function "
<< moduleName << '.' << functionName
<< " mapped to ";
cacheSlot->print(llvm::dbgs()));
return *cacheSlot;
}
#define REQUIRED(X) Types.get##X##Type()
#define OPTIONAL(X) OptionalType::get(Types.get##X##Type())
#define EXISTENTIAL(X) getASTContext().get##X##ExistentialType()
#define GET_BRIDGING_FN(Module, FromKind, FromTy, ToKind, ToTy) \
SILDeclRef SILGenModule::get##FromTy##To##ToTy##Fn() { \
return getBridgingFn(FromTy##To##ToTy##Fn, *this, \
getASTContext().Id_##Module, \
"_convert" #FromTy "To" #ToTy, \
{ FromKind(FromTy) }, \
ToKind(ToTy)); \
}
GET_BRIDGING_FN(Darwin, REQUIRED, Bool, REQUIRED, DarwinBoolean)
GET_BRIDGING_FN(Darwin, REQUIRED, DarwinBoolean, REQUIRED, Bool)
GET_BRIDGING_FN(ObjectiveC, REQUIRED, Bool, REQUIRED, ObjCBool)
GET_BRIDGING_FN(ObjectiveC, REQUIRED, ObjCBool, REQUIRED, Bool)
GET_BRIDGING_FN(Foundation, OPTIONAL, NSError, EXISTENTIAL, Error)
GET_BRIDGING_FN(Foundation, EXISTENTIAL, Error, REQUIRED, NSError)
GET_BRIDGING_FN(WinSDK, REQUIRED, Bool, REQUIRED, WindowsBool)
GET_BRIDGING_FN(WinSDK, REQUIRED, WindowsBool, REQUIRED, Bool)
#undef GET_BRIDGING_FN
#undef REQUIRED
#undef OPTIONAL
static FuncDecl *diagnoseMissingIntrinsic(SILGenModule &sgm,
SILLocation loc,
const char *name) {
sgm.diagnose(loc, diag::bridging_function_missing,
sgm.getASTContext().StdlibModuleName.str(), name);
return nullptr;
}
#define FUNC_DECL(NAME, ID) \
FuncDecl *SILGenModule::get##NAME(SILLocation loc) { \
if (auto fn = getASTContext().get##NAME()) \
return fn; \
return diagnoseMissingIntrinsic(*this, loc, ID); \
}
#include "swift/AST/KnownDecls.def"
#define KNOWN_SDK_FUNC_DECL(MODULE, NAME, ID) \
FuncDecl *SILGenModule::get##NAME(SILLocation loc) { \
if (ModuleDecl *M = getASTContext().getLoadedModule( \
getASTContext().Id_##MODULE)) { \
if (auto fn = getASTContext().get##NAME()) \
return fn; \
} \
return diagnoseMissingIntrinsic(*this, loc, ID); \
}
#include "swift/AST/KnownSDKDecls.def"
ProtocolDecl *SILGenModule::getObjectiveCBridgeable(SILLocation loc) {
if (ObjectiveCBridgeable)
return *ObjectiveCBridgeable;
// Find the _ObjectiveCBridgeable protocol.
auto &ctx = getASTContext();
auto proto = ctx.getProtocol(KnownProtocolKind::ObjectiveCBridgeable);
if (!proto)
diagnose(loc, diag::bridging_objcbridgeable_missing);
ObjectiveCBridgeable = proto;
return proto;
}
FuncDecl *SILGenModule::getBridgeToObjectiveCRequirement(SILLocation loc) {
if (BridgeToObjectiveCRequirement)
return *BridgeToObjectiveCRequirement;
// Find the _ObjectiveCBridgeable protocol.
auto proto = getObjectiveCBridgeable(loc);
if (!proto) {
BridgeToObjectiveCRequirement = nullptr;
return nullptr;
}
// Look for _bridgeToObjectiveC().
auto &ctx = getASTContext();
DeclName name(ctx, ctx.Id_bridgeToObjectiveC, llvm::ArrayRef<Identifier>());
auto *found = dyn_cast_or_null<FuncDecl>(
proto->getSingleRequirement(name));
if (!found)
diagnose(loc, diag::bridging_objcbridgeable_broken, name);
BridgeToObjectiveCRequirement = found;
return found;
}
FuncDecl *SILGenModule::getUnconditionallyBridgeFromObjectiveCRequirement(
SILLocation loc) {
if (UnconditionallyBridgeFromObjectiveCRequirement)
return *UnconditionallyBridgeFromObjectiveCRequirement;
// Find the _ObjectiveCBridgeable protocol.
auto proto = getObjectiveCBridgeable(loc);
if (!proto) {
UnconditionallyBridgeFromObjectiveCRequirement = nullptr;
return nullptr;
}
// Look for _bridgeToObjectiveC().
auto &ctx = getASTContext();
DeclName name(ctx, ctx.getIdentifier("_unconditionallyBridgeFromObjectiveC"),
llvm::ArrayRef(Identifier()));
auto *found = dyn_cast_or_null<FuncDecl>(
proto->getSingleRequirement(name));
if (!found)
diagnose(loc, diag::bridging_objcbridgeable_broken, name);
UnconditionallyBridgeFromObjectiveCRequirement = found;
return found;
}
AssociatedTypeDecl *
SILGenModule::getBridgedObjectiveCTypeRequirement(SILLocation loc) {
if (BridgedObjectiveCType)
return *BridgedObjectiveCType;
// Find the _ObjectiveCBridgeable protocol.
auto proto = getObjectiveCBridgeable(loc);
if (!proto) {
BridgeToObjectiveCRequirement = nullptr;
return nullptr;
}
// Look for _bridgeToObjectiveC().
auto &ctx = getASTContext();
auto *found = proto->getAssociatedType(ctx.Id_ObjectiveCType);
if (!found)
diagnose(loc, diag::bridging_objcbridgeable_broken, ctx.Id_ObjectiveCType);
BridgedObjectiveCType = found;
return found;
}
ProtocolConformance *
SILGenModule::getConformanceToObjectiveCBridgeable(SILLocation loc, Type type) {
auto proto = getObjectiveCBridgeable(loc);
if (!proto) return nullptr;
// Find the conformance to _ObjectiveCBridgeable.
auto result = SwiftModule->lookupConformance(type, proto);
if (result.isInvalid())
return nullptr;
return result.getConcrete();
}
ProtocolDecl *SILGenModule::getBridgedStoredNSError(SILLocation loc) {
if (BridgedStoredNSError)
return *BridgedStoredNSError;
// Find the _BridgedStoredNSError protocol.
auto &ctx = getASTContext();
auto proto = ctx.getProtocol(KnownProtocolKind::BridgedStoredNSError);
BridgedStoredNSError = proto;
return proto;
}
VarDecl *SILGenModule::getNSErrorRequirement(SILLocation loc) {
if (NSErrorRequirement)
return *NSErrorRequirement;
// Find the _BridgedStoredNSError protocol.
auto proto = getBridgedStoredNSError(loc);
if (!proto) {
NSErrorRequirement = nullptr;
return nullptr;
}
// Look for _nsError.
auto &ctx = getASTContext();
auto *found = dyn_cast_or_null<VarDecl>(
proto->getSingleRequirement(ctx.Id_nsError));
NSErrorRequirement = found;
return found;
}
ProtocolConformanceRef
SILGenModule::getConformanceToBridgedStoredNSError(SILLocation loc, Type type) {
auto proto = getBridgedStoredNSError(loc);
if (!proto)
return ProtocolConformanceRef::forInvalid();
// Find the conformance to _BridgedStoredNSError.
return SwiftModule->lookupConformance(type, proto);
}
static FuncDecl *lookupConcurrencyIntrinsic(ASTContext &C, StringRef name) {
auto *module = C.getLoadedModule(C.Id_Concurrency);
if (!module)
return nullptr;
return evaluateOrDefault(
C.evaluator, LookupIntrinsicRequest{module, C.getIdentifier(name)},
/*default=*/nullptr);
}
FuncDecl *SILGenModule::getAsyncLetStart() {
return lookupConcurrencyIntrinsic(getASTContext(), "_asyncLetStart");
}
FuncDecl *SILGenModule::getAsyncLetGet() {
return lookupConcurrencyIntrinsic(getASTContext(), "_asyncLet_get");
}
FuncDecl *SILGenModule::getAsyncLetGetThrowing() {
return lookupConcurrencyIntrinsic(getASTContext(), "_asyncLet_get_throwing");
}
FuncDecl *SILGenModule::getFinishAsyncLet() {
return lookupConcurrencyIntrinsic(getASTContext(), "_asyncLet_finish");
}
FuncDecl *SILGenModule::getTaskFutureGet() {
return lookupConcurrencyIntrinsic(getASTContext(), "_taskFutureGet");
}
FuncDecl *SILGenModule::getTaskFutureGetThrowing() {
return lookupConcurrencyIntrinsic(getASTContext(), "_taskFutureGetThrowing");
}
FuncDecl *SILGenModule::getResumeUnsafeContinuation() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_resumeUnsafeContinuation");
}
FuncDecl *SILGenModule::getResumeUnsafeThrowingContinuation() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_resumeUnsafeThrowingContinuation");
}
FuncDecl *SILGenModule::getResumeUnsafeThrowingContinuationWithError() {
return lookupConcurrencyIntrinsic(
getASTContext(), "_resumeUnsafeThrowingContinuationWithError");
}
FuncDecl *SILGenModule::getRunTaskForBridgedAsyncMethod() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_runTaskForBridgedAsyncMethod");
}
FuncDecl *SILGenModule::getCheckExpectedExecutor() {
return lookupConcurrencyIntrinsic(getASTContext(), "_checkExpectedExecutor");
}
FuncDecl *SILGenModule::getCreateCheckedContinuation() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_createCheckedContinuation");
}
FuncDecl *SILGenModule::getCreateCheckedThrowingContinuation() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_createCheckedThrowingContinuation");
}
FuncDecl *SILGenModule::getResumeCheckedContinuation() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_resumeCheckedContinuation");
}
FuncDecl *SILGenModule::getResumeCheckedThrowingContinuation() {
return lookupConcurrencyIntrinsic(getASTContext(),
"_resumeCheckedThrowingContinuation");
}
FuncDecl *SILGenModule::getResumeCheckedThrowingContinuationWithError() {
return lookupConcurrencyIntrinsic(
getASTContext(), "_resumeCheckedThrowingContinuationWithError");
}
FuncDecl *SILGenModule::getAsyncMainDrainQueue() {
return lookupConcurrencyIntrinsic(getASTContext(), "_asyncMainDrainQueue");
}
FuncDecl *SILGenModule::getSwiftJobRun() {
return lookupConcurrencyIntrinsic(getASTContext(), "_swiftJobRun");
}
FuncDecl *SILGenModule::getExit() {
ASTContext &C = getASTContext();
// Try the most likely modules.
Identifier mostLikelyIdentifier;
const llvm::Triple &triple = C.LangOpts.Target;
if (triple.isOSDarwin()) {
mostLikelyIdentifier = C.getIdentifier("Darwin");
} else if (triple.isOSWASI()) {
mostLikelyIdentifier = C.getIdentifier("SwiftWASILibc");
} else if (triple.isWindowsMSVCEnvironment()) {
mostLikelyIdentifier = C.getIdentifier("ucrt");
} else {
mostLikelyIdentifier = C.getIdentifier("SwiftGlibc");
}
ModuleDecl *exitModule = C.getModuleByIdentifier(mostLikelyIdentifier);
FuncDecl *exitFunction = nullptr;
if (exitModule) {
exitFunction = evaluateOrDefault(
C.evaluator,
LookupIntrinsicRequest{exitModule, C.getIdentifier("exit")},
/*default=*/nullptr);
}
if (!exitFunction) {
// No go, look for it in any loaded module. Several of the internal
// Swift modules or swift-corelibs modules may have absorbed <stdlib.h>
// when buliding without fully specified clang modules in the OS/SDK.
for (const auto &loadedModuleVector : C.getLoadedModules()) {
if (loadedModuleVector.first == mostLikelyIdentifier) {
continue;
}
ModuleDecl *loadedModule = loadedModuleVector.second;
if (loadedModule) {
exitFunction = evaluateOrDefault(
C.evaluator,
LookupIntrinsicRequest{loadedModule, C.getIdentifier("exit")},
/*default=*/nullptr);
}
if (exitFunction) {
break;
}
}
}
return exitFunction;
}
ProtocolConformance *SILGenModule::getNSErrorConformanceToError() {
if (NSErrorConformanceToError)
return *NSErrorConformanceToError;
auto &ctx = getASTContext();
auto nsErrorTy = ctx.getNSErrorType();
if (!nsErrorTy) {
NSErrorConformanceToError = nullptr;
return nullptr;
}
auto error = ctx.getErrorDecl();
if (!error) {
NSErrorConformanceToError = nullptr;
return nullptr;
}
auto conformance =
SwiftModule->lookupConformance(nsErrorTy, cast<ProtocolDecl>(error));
if (conformance.isConcrete())
NSErrorConformanceToError = conformance.getConcrete();
else
NSErrorConformanceToError = nullptr;
return *NSErrorConformanceToError;
}
SILFunction *
SILGenModule::getKeyPathProjectionCoroutine(bool isReadAccess,
KeyPathTypeKind typeKind) {
bool isBaseInout;
bool isResultInout;
StringRef functionName;
NominalTypeDecl *keyPathDecl;
if (isReadAccess) {
assert(typeKind == KPTK_KeyPath ||
typeKind == KPTK_WritableKeyPath ||
typeKind == KPTK_ReferenceWritableKeyPath);
functionName = "swift_readAtKeyPath";
isBaseInout = false;
isResultInout = false;
keyPathDecl = getASTContext().getKeyPathDecl();
} else if (typeKind == KPTK_WritableKeyPath) {
functionName = "swift_modifyAtWritableKeyPath";
isBaseInout = true;
isResultInout = true;
keyPathDecl = getASTContext().getWritableKeyPathDecl();
} else if (typeKind == KPTK_ReferenceWritableKeyPath) {
functionName = "swift_modifyAtReferenceWritableKeyPath";
isBaseInout = false;
isResultInout = true;
keyPathDecl = getASTContext().getReferenceWritableKeyPathDecl();
} else {
llvm_unreachable("bad combination");
}
auto fn = M.lookUpFunction(functionName);
if (fn) return fn;
auto sig = keyPathDecl->getGenericSignature().getCanonicalSignature();
auto rootType = sig.getGenericParams()[0]->getCanonicalType();
auto valueType = sig.getGenericParams()[1]->getCanonicalType();
auto keyPathTy = BoundGenericType::get(keyPathDecl, Type(),
{ rootType, valueType })
->getCanonicalType();
// (@in_guaranteed/@inout Root, @guaranteed KeyPath<Root, Value>)
SILParameterInfo params[] = {
{ rootType,
isBaseInout ? ParameterConvention::Indirect_Inout
: ParameterConvention::Indirect_In_Guaranteed },
{ keyPathTy, ParameterConvention::Direct_Guaranteed },
};
// -> @yields @in_guaranteed/@inout Value
SILYieldInfo yields[] = {
{ valueType,
isResultInout ? ParameterConvention::Indirect_Inout
: ParameterConvention::Indirect_In_Guaranteed },
};
auto extInfo = SILFunctionType::ExtInfo::getThin();
auto functionTy = SILFunctionType::get(sig, extInfo,
SILCoroutineKind::YieldOnce,
ParameterConvention::Direct_Unowned,
params,
yields,
/*results*/ {},
/*error result*/ {},
SubstitutionMap(),
SubstitutionMap(),
getASTContext());
auto env = sig.getGenericEnvironment();
SILGenFunctionBuilder builder(*this);
fn = builder.createFunction(
SILLinkage::PublicExternal, functionName, functionTy, env,
/*location*/ std::nullopt, IsNotBare, IsNotTransparent, IsNotSerialized,
IsNotDynamic, IsNotDistributed, IsNotRuntimeAccessible);
return fn;
}
SILFunction *SILGenModule::getEmittedFunction(SILDeclRef constant,
ForDefinition_t forDefinition) {
auto found = emittedFunctions.find(constant);
if (found != emittedFunctions.end()) {
SILFunction *F = found->second;
if (forDefinition) {
// In all the cases where getConstantLinkage returns something
// different for ForDefinition, it returns an available-externally
// linkage.
if (isAvailableExternally(F->getLinkage())) {
F->setLinkage(constant.getLinkage(ForDefinition));
}
}
return F;
}
return nullptr;
}
static SILFunction *getFunctionToInsertAfter(SILGenModule &SGM,
SILDeclRef insertAfter) {
// If the decl ref was emitted, emit after its function.
while (insertAfter) {
auto found = SGM.emittedFunctions.find(insertAfter);
if (found != SGM.emittedFunctions.end()) {
return found->second;
}
// Otherwise, try to insert after the function we would be transitively
// be inserted after.
auto foundDelayed = SGM.delayedFunctions.find(insertAfter);
if (foundDelayed != SGM.delayedFunctions.end()) {
insertAfter = foundDelayed->second;
} else {
break;
}
}
// If the decl ref is nil, just insert at the beginning.
return nullptr;
}
static bool shouldEmitFunctionBody(const AbstractFunctionDecl *AFD) {
if (!AFD->hasBody())
return false;
if (AFD->isBodySkipped())
return false;
auto &ctx = AFD->getASTContext();
if (ctx.TypeCheckerOpts.EnableLazyTypecheck) {
// Force the function body to be type-checked and then skip it if there
// have been any errors.
(void)AFD->getTypecheckedBody();
// FIXME: Only skip bodies that contain type checking errors.
// It would be ideal to only skip the function body if it is specifically
// the source of an error. However, that information isn't available today
// so instead we avoid emitting all function bodies as soon as any error is
// encountered.
if (ctx.hadError())
return false;
}
return true;
}
static bool isEmittedOnDemand(SILModule &M, SILDeclRef constant) {
if (!constant.hasDecl())
return false;
if (constant.isForeign)
return false;
auto *d = constant.getDecl();
auto *dc = d->getDeclContext();
switch (constant.kind) {
case SILDeclRef::Kind::Func: {
auto *fd = cast<FuncDecl>(d);
if (!shouldEmitFunctionBody(fd))
return false;
if (isa<ClangModuleUnit>(dc->getModuleScopeContext()))
return true;
if (fd->hasForcedStaticDispatch())
return true;
break;
}
case SILDeclRef::Kind::Allocator: {
auto *cd = cast<ConstructorDecl>(d);
// For factories, we don't need to emit a special thunk; the normal
// foreign-to-native thunk is sufficient.
if (isa<ClangModuleUnit>(dc->getModuleScopeContext()) &&
!cd->isFactoryInit() &&
(dc->getSelfClassDecl() || shouldEmitFunctionBody(cd)))
return true;
break;
}
case SILDeclRef::Kind::EnumElement:
return true;
case SILDeclRef::Kind::DefaultArgGenerator: {
// Default arguments of C++ functions are only emitted if used.
if (isa<ClangModuleUnit>(dc->getModuleScopeContext()))
return true;
break;
}
default:
break;
}
return false;
}
SILFunction *SILGenModule::getFunction(SILDeclRef constant,
ForDefinition_t forDefinition) {
// If we already emitted the function, return it.
if (auto emitted = getEmittedFunction(constant, forDefinition))
return emitted;
auto getBestLocation = [](SILDeclRef ref) -> SILLocation {
if (ref.hasDecl())
return ref.getDecl();
if (ref.loc.isNull())
return {(Decl *)nullptr};
if (auto *ace = ref.getAbstractClosureExpr())
return {ace};
return {(Decl *)nullptr};
};
// Note: Do not provide any SILLocation. You can set it afterwards.
SILGenFunctionBuilder builder(*this);
auto &IGM = *this;
auto *F = builder.getOrCreateFunction(
getBestLocation(constant), constant, forDefinition,
[&IGM](SILLocation loc, SILDeclRef constant) -> SILFunction * {
return IGM.getFunction(constant, NotForDefinition);
});
// If we have global actor isolation for our constant, put the isolation onto
// the function.
if (auto isolation =
getActorIsolationOfContext(constant.getInnermostDeclContext())) {
F->setActorIsolation(isolation);
}
assert(F && "SILFunction should have been defined");
emittedFunctions[constant] = F;
auto foundDelayed = delayedFunctions.find(constant);
if (foundDelayed == delayedFunctions.end()) {
if (isEmittedOnDemand(M, constant)) {
if (forcedFunctions.insert(constant).second)
pendingForcedFunctions.push_back(constant);
return F;
}
}
// If we delayed emitting this function previously, we need it now.
if (foundDelayed != delayedFunctions.end()) {
// Move the function to its proper place within the module.
M.functions.remove(F);
SILFunction *insertAfter = getFunctionToInsertAfter(*this,
foundDelayed->second);
if (!insertAfter) {
M.functions.push_front(F);
} else {
M.functions.insertAfter(insertAfter->getIterator(), F);
}
if (forcedFunctions.insert(constant).second)
pendingForcedFunctions.push_back(constant);
delayedFunctions.erase(foundDelayed);
} else {
// We would have registered a delayed function as "last emitted" when we
// enqueued. If the function wasn't delayed, then we're emitting it now.
lastEmittedFunction = constant;
}
return F;
}
bool SILGenModule::hasFunction(SILDeclRef constant) {
return emittedFunctions.count(constant);
}
bool SILGenModule::shouldSkipDecl(Decl *D) {
if (!D->isAvailableDuringLowering())
return true;
if (!getASTContext().SILOpts.SkipNonExportableDecls)
return false;
if (D->isExposedToClients())
return false;
if (isa<AbstractFunctionDecl>(D)) {
// If this function is nested within another function that is exposed to
// clients then it should be emitted.
auto dc = D->getDeclContext();
do {
if (auto afd = dyn_cast<AbstractFunctionDecl>(dc))
if (afd->isExposedToClients())
return false;
} while ((dc = dc->getParent()));
// We didn't find a parent function that is exposed.
return true;
}
return true;
}
void SILGenModule::visit(Decl *D) {
if (shouldSkipDecl(D))
return;
ASTVisitor::visit(D);
}
void SILGenModule::visitFuncDecl(FuncDecl *fd) { emitFunction(fd); }
void SILGenModule::emitFunctionDefinition(SILDeclRef constant, SILFunction *f) {
if (!f->empty()) {
diagnose(constant.getAsRegularLocation(), diag::sil_function_redefinition,
f->getName());
if (f->hasLocation())
diagnose(f->getLocation(), diag::sil_function_redefinition_note);
return;
}
if (constant.isForeignToNativeThunk()) {
f->setThunk(IsThunk);
if (constant.asForeign().isClangGenerated())
f->setSerializedKind(IsSerialized);
auto loc = constant.getAsRegularLocation();
loc.markAutoGenerated();
auto *dc = loc.getAsDeclContext();
assert(dc);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitForeignToNativeThunk", f);
SILGenFunction(*this, *f, dc).emitForeignToNativeThunk(constant);
postEmitFunction(constant, f);
return;
}
if (constant.isNativeToForeignThunk()) {
auto loc = constant.getAsRegularLocation();
loc.markAutoGenerated();
auto *dc = loc.getAsDeclContext();
assert(dc);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitNativeToForeignThunk", f);
f->setBare(IsBare);
f->setThunk(IsThunk);
// If the native function is async, then the foreign entry point is not,
// so it needs to spawn a detached task in which to run the native
// implementation, so the actual thunk logic needs to go into a closure
// implementation function.
if (constant.hasAsync()) {
f = SILGenFunction(*this, *f, dc).emitNativeAsyncToForeignThunk(constant);
}
SILGenFunction(*this, *f, dc).emitNativeToForeignThunk(constant);
postEmitFunction(constant, f);
return;
}
if (constant.isDistributedThunk()) {
auto loc = constant.getAsRegularLocation();
loc.markAutoGenerated();
auto *dc = loc.getAsDeclContext();
assert(dc);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitDistributedThunk", f);
f->setBare(IsBare);
f->setThunk(IsThunk);
f->setIsDistributed();
assert(constant.isDistributedThunk());
SILGenFunction(*this, *f, constant.getFuncDecl())
.emitFunction(constant.getFuncDecl());
postEmitFunction(constant, f);
return;
}
if (constant.isBackDeploymentThunk()) {
auto loc = constant.getAsRegularLocation();
loc.markAutoGenerated();
auto *dc = loc.getAsDeclContext();
assert(dc);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitBackDeploymentThunk", f);
f->setBare(IsBare);
f->setThunk(IsBackDeployedThunk);
SILGenFunction(*this, *f, dc).emitBackDeploymentThunk(constant);
postEmitFunction(constant, f);
return;
}
switch (constant.kind) {
case SILDeclRef::Kind::Func: {
if (auto *ce = constant.getAbstractClosureExpr()) {
preEmitFunction(constant, f, ce);
PrettyStackTraceSILFunction X("silgen closureexpr", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, ce).emitClosure(ce);
postEmitFunction(constant, f);
break;
}
if (constant.isInitAccessor()) {
auto *accessor = cast<AccessorDecl>(constant.getDecl());
preEmitFunction(constant, f, accessor);
PrettyStackTraceSILFunction X("silgen init accessor", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, accessor).emitInitAccessor(accessor);
postEmitFunction(constant, f);
break;
}
auto *fd = cast<FuncDecl>(constant.getDecl());
preEmitFunction(constant, f, fd);
PrettyStackTraceSILFunction X("silgen emitFunction", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, fd).emitFunction(fd);
postEmitFunction(constant, f);
break;
}
case SILDeclRef::Kind::Allocator: {
auto *decl = cast<ConstructorDecl>(constant.getDecl());
if (decl->getDeclContext()->getSelfClassDecl() &&
(decl->isDesignatedInit() ||
decl->isObjC())) {
preEmitFunction(constant, f, decl);
PrettyStackTraceSILFunction X("silgen emitClassConstructorAllocator", f);
SILGenFunction(*this, *f, decl).emitClassConstructorAllocator(decl);
postEmitFunction(constant, f);
} else {
preEmitFunction(constant, f, decl);
PrettyStackTraceSILFunction X("silgen emitValueConstructor", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, decl).emitValueConstructor(decl);
postEmitFunction(constant, f);
}
break;
}
case SILDeclRef::Kind::Initializer: {
auto *decl = cast<ConstructorDecl>(constant.getDecl());
assert(decl->getDeclContext()->getSelfClassDecl());
preEmitFunction(constant, f, decl);
PrettyStackTraceSILFunction X("silgen constructor initializer", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, decl).emitClassConstructorInitializer(decl);
postEmitFunction(constant, f);
break;
}
case SILDeclRef::Kind::DefaultArgGenerator: {
auto *decl = constant.getDecl();
auto *param = getParameterAt(decl, constant.defaultArgIndex);
assert(param);
auto *initDC = param->getDefaultArgumentInitContext();
switch (param->getDefaultArgumentKind()) {
case DefaultArgumentKind::Normal: {
auto arg = param->getTypeCheckedDefaultExpr();
auto loc = RegularLocation::getAutoGeneratedLocation(arg);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen default arg initializer", f);
SILGenFunction SGF(*this, *f, initDC);
SGF.emitGeneratorFunction(constant, arg);
postEmitFunction(constant, f);
break;
}
case DefaultArgumentKind::StoredProperty: {
auto arg = param->getStoredProperty();
auto loc = RegularLocation::getAutoGeneratedLocation(arg);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen stored property initializer", f);
SILGenFunction SGF(*this, *f, initDC);
SGF.emitGeneratorFunction(constant, arg);
postEmitFunction(constant, f);
break;
}
default:
llvm_unreachable("Bad default argument kind");
}
break;
}
case SILDeclRef::Kind::StoredPropertyInitializer: {
auto *var = cast<VarDecl>(constant.getDecl());
auto *pbd = var->getParentPatternBinding();
unsigned idx = pbd->getPatternEntryIndexForVarDecl(var);
auto *initDC = pbd->getInitContext(idx);
auto *init = constant.getInitializationExpr();
assert(init);
auto *parentMod = f->getParentModule();
auto loc = RegularLocation::getAutoGeneratedLocation(init);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitStoredPropertyInitialization", f);
f->createProfiler(constant);
SILGenFunction SGF(*this, *f, initDC);
SGF.emitGeneratorFunction(constant, init, /*EmitProfilerIncrement=*/true);
postEmitFunction(constant, f);
// Ensure that the SIL function has a module associated with it. This
// ensures that SIL serializer serializes the module id for this function
// correctly. The parent module can be reset when the function's location is
// updated to the autogenerated location above.
if (!f->getParentModule())
f->setParentModule(parentMod);
break;
}
case SILDeclRef::Kind::PropertyWrapperBackingInitializer: {
auto *var = cast<VarDecl>(constant.getDecl());
auto loc = RegularLocation::getAutoGeneratedLocation(var);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X(
"silgen emitPropertyWrapperBackingInitializer", f);
auto *init = constant.getInitializationExpr();
assert(init);
f->createProfiler(constant);
auto varDC = var->getInnermostDeclContext();
SILGenFunction SGF(*this, *f, varDC);
SGF.emitGeneratorFunction(constant, init, /*EmitProfilerIncrement*/ true);
postEmitFunction(constant, f);
break;
}
case SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue: {
auto *var = cast<VarDecl>(constant.getDecl());
auto loc = RegularLocation::getAutoGeneratedLocation(var);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X(
"silgen emitPropertyWrapperInitFromProjectedValue", f);
auto *init = constant.getInitializationExpr();
assert(init);
auto varDC = var->getInnermostDeclContext();
SILGenFunction SGF(*this, *f, varDC);
SGF.emitGeneratorFunction(constant, init);
postEmitFunction(constant, f);
break;
}
case SILDeclRef::Kind::GlobalAccessor: {
auto *global = cast<VarDecl>(constant.getDecl());
auto found = delayedGlobals.find(global);
assert(found != delayedGlobals.end());
auto *onceToken = found->second.first;
auto *onceFunc = found->second.second;
auto loc = RegularLocation::getAutoGeneratedLocation(global);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitGlobalAccessor", f);
SILGenFunction(*this, *f, global->getDeclContext())
.emitGlobalAccessor(global, onceToken, onceFunc);
postEmitFunction(constant, f);
break;
}
case SILDeclRef::Kind::EnumElement: {
auto *decl = cast<EnumElementDecl>(constant.getDecl());
auto loc = RegularLocation::getAutoGeneratedLocation(decl);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen enum constructor", f);
SILGenFunction(*this, *f, decl->getDeclContext()).emitEnumConstructor(decl);
postEmitFunction(constant, f);
break;
}
case SILDeclRef::Kind::Destroyer: {
auto *dd = cast<DestructorDecl>(constant.getDecl());
preEmitFunction(constant, f, dd);
PrettyStackTraceSILFunction X("silgen emitDestroyingDestructor", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, dd).emitDestroyingDestructor(dd);
postEmitFunction(constant, f);
return;
}
case SILDeclRef::Kind::Deallocator: {
auto *dd = cast<DestructorDecl>(constant.getDecl());
auto *nom = dd->getDeclContext()->getSelfNominalTypeDecl();
if (auto *cd = dyn_cast<ClassDecl>(nom)) {
if (usesObjCAllocator(cd)) {
preEmitFunction(constant, f, dd);
PrettyStackTraceSILFunction X("silgen emitDestructor -dealloc", f);
f->createProfiler(constant);
SILGenFunction(*this, *f, dd).emitObjCDestructor(constant);
postEmitFunction(constant, f);
return;
}
}
auto loc = RegularLocation::getAutoGeneratedLocation(dd);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitDeallocatingDestructor", f);
SILGenFunction(*this, *f, dd).emitDeallocatingDestructor(dd);
postEmitFunction(constant, f);
return;
}
case SILDeclRef::Kind::IVarInitializer: {
auto *cd = cast<ClassDecl>(constant.getDecl());
auto loc = RegularLocation::getAutoGeneratedLocation(cd);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitDestructor ivar initializer", f);
SILGenFunction(*this, *f, cd).emitIVarInitializer(constant);
postEmitFunction(constant, f);
return;
}
case SILDeclRef::Kind::IVarDestroyer: {
auto *cd = cast<ClassDecl>(constant.getDecl());
auto loc = RegularLocation::getAutoGeneratedLocation(cd);
preEmitFunction(constant, f, loc);
PrettyStackTraceSILFunction X("silgen emitDestructor ivar destroyer", f);
SILGenFunction(*this, *f, cd).emitIVarDestroyer(constant);
postEmitFunction(constant, f);
return;
}
case SILDeclRef::Kind::AsyncEntryPoint:
case SILDeclRef::Kind::EntryPoint: {
f->setBare(IsBare);
if (constant.hasFileUnit()) {
auto *File = constant.getFileUnit();
// In script mode
assert(isa<SourceFile>(File) && "Emitting entry-point of non source file?!");
auto *SF = cast<SourceFile>(File);
emitEntryPoint(SF, f);
return;
}
auto loc = constant.getAsRegularLocation();
preEmitFunction(constant, f, loc);
auto *decl = constant.getDecl();
auto *dc = decl->getDeclContext();
PrettyStackTraceSILFunction X("silgen emitArtificialTopLevel", f);
// In all cases, a constant.kind == EntryPoint indicates the main entrypoint
// to the program, @main.
// In the synchronous case, the decl is not async, so emitArtificialTopLevel
// emits the error unwrapping and call to MainType.$main() into @main.
//
// In the async case, emitAsyncMainThreadStart is responsible for generating
// the contents of @main. This wraps @async_main in a task, passes that task
// to swift_job_run to execute the first thunk, and starts the runloop to
// run any additional continuations. The kind is EntryPoint, and the decl is
// async.
// When the kind is 'AsyncMain', we are generating @async_main. In this
// case, emitArtificialTopLevel emits the code for calling MaintType.$main,
// unwrapping errors, and calling exit(0) into @async_main to run the
// user-specified main function.
if (constant.kind == SILDeclRef::Kind::EntryPoint && isa<FuncDecl>(decl) &&
static_cast<FuncDecl *>(decl)->hasAsync()) {
SILDeclRef mainEntryPoint = SILDeclRef::getAsyncMainDeclEntryPoint(decl);
SILGenFunction(*this, *f, dc).emitAsyncMainThreadStart(mainEntryPoint);
} else {
SILGenFunction(*this, *f, dc).emitArtificialTopLevel(decl);
}
postEmitFunction(constant, f);
return;
}
}
}
void SILGenModule::emitOrDelayFunction(SILDeclRef constant) {
assert(!constant.isThunk());
assert(!constant.isClangImported());
auto emitAfter = lastEmittedFunction;
// Implicit decls may be delayed if they can't be used externally.
auto linkage = constant.getLinkage(ForDefinition);
bool mayDelay = !constant.hasUserWrittenCode() &&
!constant.isDynamicallyReplaceable() &&
!isPossiblyUsedExternally(linkage, M.isWholeModule());
if (!mayDelay) {
emitFunctionDefinition(constant, getFunction(constant, ForDefinition));
return;
}
// If the function is already forced then it was previously delayed and then
// referenced. We don't need to emit or delay it again.
if (forcedFunctions.contains(constant))
return;
if (auto *f = getEmittedFunction(constant, ForDefinition)) {
emitFunctionDefinition(constant, f);
return;
}
// This is a delayable function so remember how to emit it in case it gets
// referenced later.
delayedFunctions.insert({constant, emitAfter});
// Even though we didn't emit the function now, update the
// lastEmittedFunction so that we preserve the original ordering that
// the symbols would have been emitted in.
lastEmittedFunction = constant;
}
void SILGenModule::preEmitFunction(SILDeclRef constant, SILFunction *F,
SILLocation Loc) {
assert(F->empty() && "already emitted function?!");
if (F->getLoweredFunctionType()->isPolymorphic()) {
auto [genericEnv, capturedEnvs, forwardingSubs]
= Types.getForwardingSubstitutionsForLowering(constant);
F->setGenericEnvironment(genericEnv, capturedEnvs, forwardingSubs);
}
// If we have global actor isolation for our constant, put the isolation onto
// the function.
if (auto isolation =
getActorIsolationOfContext(constant.getInnermostDeclContext())) {
F->setActorIsolation(isolation);
}
// Create a debug scope for the function using astNode as source location.
F->setDebugScope(new (M) SILDebugScope(Loc, F));
// Initialize F with the constant we created for it.
F->setDeclRef(constant);
LLVM_DEBUG(llvm::dbgs() << "lowering ";
F->printName(llvm::dbgs());
llvm::dbgs() << " : ";
F->getLoweredType().print(llvm::dbgs());
llvm::dbgs() << '\n';
if (auto *decl = Loc.getAsASTNode<ValueDecl>()) {
decl->dump(llvm::dbgs());
llvm::dbgs() << '\n';
} else if (auto *expr = Loc.getAsASTNode<Expr>()) {
expr->dump(llvm::dbgs());
llvm::dbgs() << "\n";
});
}
void SILGenModule::postEmitFunction(SILDeclRef constant,
SILFunction *F) {
emitLazyConformancesForFunction(F);
auto sig = Types.getGenericSignatureWithCapturedEnvironments(constant);
recontextualizeCapturedLocalArchetypes(F, sig);
assert(!F->isExternalDeclaration() && "did not emit any function body?!");
LLVM_DEBUG(llvm::dbgs() << "lowered sil:\n";
F->print(llvm::dbgs()));
F->verifyIncompleteOSSA();
emitDifferentiabilityWitnessesForFunction(constant, F);
}
void SILGenModule::emitDifferentiabilityWitnessesForFunction(
SILDeclRef constant, SILFunction *F) {
// Visit `@derivative` attributes and generate SIL differentiability
// witnesses.
// Skip if the SILDeclRef is a:
// - Default argument generator function.
// - Thunk.
if (!constant.hasDecl() || !constant.getAbstractFunctionDecl())
return;
if (constant.kind == SILDeclRef::Kind::DefaultArgGenerator ||
constant.isThunk())
return;
auto *AFD = constant.getAbstractFunctionDecl();
auto emitWitnesses = [&](DeclAttributes &Attrs) {
for (auto *diffAttr : Attrs.getAttributes<DifferentiableAttr>()) {
assert((!F->getLoweredFunctionType()->getSubstGenericSignature() ||
diffAttr->getDerivativeGenericSignature()) &&
"Type-checking should resolve derivative generic signatures for "
"all original SIL functions with generic signatures");
auto *resultIndices =
autodiff::getFunctionSemanticResultIndices(AFD,
diffAttr->getParameterIndices());
auto witnessGenSig =
autodiff::getDifferentiabilityWitnessGenericSignature(
AFD->getGenericSignature(),
diffAttr->getDerivativeGenericSignature());
AutoDiffConfig config(diffAttr->getParameterIndices(), resultIndices,
witnessGenSig);
emitDifferentiabilityWitness(AFD, F, DifferentiabilityKind::Reverse,
config, /*jvp*/ nullptr,
/*vjp*/ nullptr, diffAttr);
}
for (auto *derivAttr : Attrs.getAttributes<DerivativeAttr>()) {
SILFunction *jvp = nullptr;
SILFunction *vjp = nullptr;
switch (derivAttr->getDerivativeKind()) {
case AutoDiffDerivativeFunctionKind::JVP:
jvp = F;
break;
case AutoDiffDerivativeFunctionKind::VJP:
vjp = F;
break;
}
auto *origAFD = derivAttr->getOriginalFunction(getASTContext());
auto origDeclRef =
SILDeclRef(origAFD).asForeign(requiresForeignEntryPoint(origAFD));
auto *origFn = getFunction(origDeclRef, NotForDefinition);
auto witnessGenSig =
autodiff::getDifferentiabilityWitnessGenericSignature(
origAFD->getGenericSignature(), AFD->getGenericSignature());
auto *resultIndices =
autodiff::getFunctionSemanticResultIndices(origAFD,
derivAttr->getParameterIndices());
AutoDiffConfig config(derivAttr->getParameterIndices(), resultIndices,
witnessGenSig);
emitDifferentiabilityWitness(origAFD, origFn,
DifferentiabilityKind::Reverse, config, jvp,
vjp, derivAttr);
}
};
if (auto *accessor = dyn_cast<AccessorDecl>(AFD))
if (accessor->isGetter())
emitWitnesses(accessor->getStorage()->getAttrs());
emitWitnesses(AFD->getAttrs());
}
void SILGenModule::emitDifferentiabilityWitness(
AbstractFunctionDecl *originalAFD, SILFunction *originalFunction,
DifferentiabilityKind diffKind, const AutoDiffConfig &config,
SILFunction *jvp, SILFunction *vjp, const DeclAttribute *attr) {
assert(isa<DifferentiableAttr>(attr) || isa<DerivativeAttr>(attr));
auto *origFnType = originalAFD->getInterfaceType()->castTo<AnyFunctionType>();
auto origSilFnType = originalFunction->getLoweredFunctionType();
auto *silParamIndices =
autodiff::getLoweredParameterIndices(config.parameterIndices, origFnType);
// NOTE(TF-893): Extending capacity is necessary when `origSilFnType` has
// parameters corresponding to captured variables. These parameters do not
// appear in the type of `origFnType`.
// TODO: If possible, change `autodiff::getLoweredParameterIndices` to
// take `CaptureInfo` into account.
if (origSilFnType->getNumParameters() > silParamIndices->getCapacity())
silParamIndices = silParamIndices->extendingCapacity(
getASTContext(), origSilFnType->getNumParameters());
// Get or create new SIL differentiability witness.
// Witness already exists when there are two `@derivative` attributes
// (registering JVP and VJP functions) for the same derivative function
// configuration.
// Witness JVP and VJP are set below.
AutoDiffConfig silConfig(silParamIndices, config.resultIndices,
config.derivativeGenericSignature);
SILDifferentiabilityWitnessKey key = {
originalFunction->getName(), diffKind, silConfig};
auto *diffWitness = M.lookUpDifferentiabilityWitness(key);
if (!diffWitness) {
// Differentiability witnesses have the same linkage as the original
// function, stripping external.
auto linkage = stripExternalFromLinkage(originalFunction->getLinkage());
diffWitness = SILDifferentiabilityWitness::createDefinition(
M, linkage, originalFunction, diffKind, silConfig.parameterIndices,
silConfig.resultIndices, config.derivativeGenericSignature,
/*jvp*/ nullptr, /*vjp*/ nullptr,
/*isSerialized*/ hasPublicVisibility(originalFunction->getLinkage()),
attr);
}
// Set derivative function in differentiability witness.
auto setDerivativeInDifferentiabilityWitness =
[&](AutoDiffDerivativeFunctionKind kind, SILFunction *derivative) {
auto derivativeThunk = getOrCreateCustomDerivativeThunk(
originalAFD, originalFunction, derivative, silConfig, kind);
// Check for existing same derivative.
// TODO(TF-835): Remove condition below and simplify assertion to
// `!diffWitness->getDerivative(kind)` after `@derivative` attribute
// type-checking no longer generates implicit `@differentiable`
// attributes.
auto *existingDerivative = diffWitness->getDerivative(kind);
if (existingDerivative && existingDerivative == derivativeThunk)
return;
assert(!existingDerivative &&
"SIL differentiability witness already has a different existing "
"derivative");
diffWitness->setDerivative(kind, derivativeThunk);
};
if (jvp)
setDerivativeInDifferentiabilityWitness(AutoDiffDerivativeFunctionKind::JVP,
jvp);
if (vjp)
setDerivativeInDifferentiabilityWitness(AutoDiffDerivativeFunctionKind::VJP,
vjp);
}
void SILGenModule::emitAbstractFuncDecl(AbstractFunctionDecl *AFD) {
// Emit default arguments and property wrapper initializers.
emitArgumentGenerators(AFD, AFD->getParameters());
// If the declaration is exported as a C function, emit its native-to-foreign
// thunk too, if it wasn't already forced.
if (AFD->getAttrs().hasAttribute<CDeclAttr>()) {
auto thunk = SILDeclRef(AFD).asForeign();
if (!hasFunction(thunk))
emitNativeToForeignThunk(thunk);
}
emitDistributedThunkForDecl(AFD);
if (AFD->isBackDeployed(M.getASTContext())) {
// Emit the fallback function that will be used when the original function
// is unavailable at runtime.
auto fallback = SILDeclRef(AFD).asBackDeploymentKind(
SILDeclRef::BackDeploymentKind::Fallback);
emitFunctionDefinition(fallback, getFunction(fallback, ForDefinition));
// Emit the thunk that either invokes the original function or the fallback
// function depending on the availability of the original.
auto thunk = SILDeclRef(AFD).asBackDeploymentKind(
SILDeclRef::BackDeploymentKind::Thunk);
emitBackDeploymentThunk(thunk);
}
}
void SILGenModule::emitFunction(FuncDecl *fd) {
assert(!shouldSkipDecl(fd));
SILDeclRef::Loc decl = fd;
emitAbstractFuncDecl(fd);
if (shouldEmitFunctionBody(fd)) {
Types.setCaptureTypeExpansionContext(SILDeclRef(fd), M);
emitOrDelayFunction(SILDeclRef(decl));
}
}
void SILGenModule::addGlobalVariable(VarDecl *global) {
// We create SILGlobalVariable here.
getSILGlobalVariable(global, ForDefinition);
}
void SILGenModule::emitConstructor(ConstructorDecl *decl) {
// FIXME: Handle 'self' like any other argument here.
// Emit any default argument getter functions.
emitAbstractFuncDecl(decl);
// We never emit constructors in protocols.
if (isa<ProtocolDecl>(decl->getDeclContext()))
return;
SILDeclRef constant(decl);
DeclContext *declCtx = decl->getDeclContext();
if (declCtx->getSelfClassDecl()) {
// Designated initializers for classes, as well as @objc convenience
// initializers, have separate entry points for allocation and
// initialization.
if (decl->isDesignatedInit() || decl->isObjC()) {
emitOrDelayFunction(constant);
if (shouldEmitFunctionBody(decl)) {
SILDeclRef initConstant(decl, SILDeclRef::Kind::Initializer);
emitOrDelayFunction(initConstant);
}
return;
}
}
// Struct and enum constructors do everything in a single function, as do
// non-@objc convenience initializers for classes.
if (shouldEmitFunctionBody(decl)) {
emitOrDelayFunction(constant);
}
}
SILFunction *SILGenModule::emitClosure(AbstractClosureExpr *e,
const FunctionTypeInfo &closureInfo) {
Types.setCaptureTypeExpansionContext(SILDeclRef(e), M);
SILFunction *f = nullptr;
Types.withClosureTypeInfo(e, closureInfo, [&] {
SILDeclRef constant(e);
f = getFunction(constant, ForDefinition);
// Generate the closure function, if we haven't already.
//
// We may visit the same closure expr multiple times in some cases,
// for instance, when closures appear as in-line initializers of stored
// properties. In these cases the closure will be emitted into every
// initializer of the containing type.
if (!f->isExternalDeclaration())
return;
// Emit property wrapper argument generators.
emitArgumentGenerators(e, e->getParameters());
emitFunctionDefinition(constant, f);
});
return f;
}
/// Determine whether the given class requires a separate instance
/// variable initialization method.
static bool requiresIVarInitialization(SILGenModule &SGM, ClassDecl *cd) {
if (!cd->requiresStoredPropertyInits())
return false;
for (Decl *member : cd->getImplementationContext()->getAllMembers()) {
auto pbd = dyn_cast<PatternBindingDecl>(member);
if (!pbd) continue;
for (auto i : range(pbd->getNumPatternEntries()))
if (pbd->getExecutableInit(i))
return true;
}
return false;
}
bool SILGenModule::hasNonTrivialIVars(ClassDecl *cd) {
for (Decl *member : cd->getImplementationContext()->getAllMembers()) {
auto *vd = dyn_cast<VarDecl>(member);
if (!vd || !vd->hasStorage()) continue;
auto &ti = Types.getTypeLowering(
vd->getTypeInContext(),
TypeExpansionContext::maximalResilienceExpansionOnly());
if (!ti.isTrivial())
return true;
}
return false;
}
bool SILGenModule::requiresIVarDestroyer(ClassDecl *cd) {
// Only needed if we have non-trivial ivars, we're not a root class, and
// the superclass is not @objc.
return (hasNonTrivialIVars(cd) &&
cd->getSuperclassDecl() &&
!cd->getSuperclassDecl()->hasClangNode());
}
/// TODO: This needs a better name.
void SILGenModule::emitObjCAllocatorDestructor(ClassDecl *cd,
DestructorDecl *dd) {
// Emit the native deallocating destructor for -dealloc.
// Destructors are a necessary part of class metadata, so can't be delayed.
if (shouldEmitFunctionBody(dd)) {
SILDeclRef dealloc(dd, SILDeclRef::Kind::Deallocator);
emitFunctionDefinition(dealloc, getFunction(dealloc, ForDefinition));
// Emit the Objective-C -dealloc entry point if it has
// something to do beyond messaging the superclass's -dealloc.
if (!dd->getBody()->empty())
emitObjCDestructorThunk(dd);
}
// Emit the ivar initializer, if needed.
if (requiresIVarInitialization(*this, cd)) {
auto ivarInitializer = SILDeclRef(cd, SILDeclRef::Kind::IVarInitializer)
.asForeign();
emitFunctionDefinition(ivarInitializer,
getFunction(ivarInitializer, ForDefinition));
}
// Emit the ivar destroyer, if needed.
if (hasNonTrivialIVars(cd)) {
auto ivarDestroyer = SILDeclRef(cd, SILDeclRef::Kind::IVarDestroyer)
.asForeign();
emitFunctionDefinition(ivarDestroyer,
getFunction(ivarDestroyer, ForDefinition));
}
}
void SILGenModule::emitDestructor(ClassDecl *cd, DestructorDecl *dd) {
emitAbstractFuncDecl(dd);
// Emit the ivar destroyer, if needed.
if (requiresIVarDestroyer(cd)) {
SILDeclRef ivarDestroyer(cd, SILDeclRef::Kind::IVarDestroyer);
emitFunctionDefinition(ivarDestroyer,
getFunction(ivarDestroyer, ForDefinition));
}
// If the class would use the Objective-C allocator, only emit -dealloc.
if (usesObjCAllocator(cd)) {
emitObjCAllocatorDestructor(cd, dd);
return;
}
// Emit the destroying destructor.
// Destructors are a necessary part of class metadata, so can't be delayed.
if (shouldEmitFunctionBody(dd)) {
SILDeclRef destroyer(dd, SILDeclRef::Kind::Destroyer);
emitFunctionDefinition(destroyer, getFunction(destroyer, ForDefinition));
}
// Emit the deallocating destructor.
{
SILDeclRef deallocator(dd, SILDeclRef::Kind::Deallocator);
emitFunctionDefinition(deallocator,
getFunction(deallocator, ForDefinition));
}
}
void SILGenModule::emitMoveOnlyDestructor(NominalTypeDecl *cd,
DestructorDecl *dd) {
assert(!cd->canBeCopyable());
emitAbstractFuncDecl(dd);
// Emit the deallocating destructor if we have a body.
if (shouldEmitFunctionBody(dd)) {
SILDeclRef deallocator(dd, SILDeclRef::Kind::Deallocator);
emitFunctionDefinition(deallocator,
getFunction(deallocator, ForDefinition));
}
}
void SILGenModule::emitDefaultArgGenerator(SILDeclRef constant,
ParamDecl *param) {
switch (param->getDefaultArgumentKind()) {
case DefaultArgumentKind::None:
llvm_unreachable("No default argument here?");
case DefaultArgumentKind::Normal:
case DefaultArgumentKind::StoredProperty:
emitOrDelayFunction(constant);
break;
case DefaultArgumentKind::Inherited:
#define MAGIC_IDENTIFIER(NAME, STRING, SYNTAX_KIND) \
case DefaultArgumentKind::NAME:
#include "swift/AST/MagicIdentifierKinds.def"
case DefaultArgumentKind::NilLiteral:
case DefaultArgumentKind::EmptyArray:
case DefaultArgumentKind::EmptyDictionary:
case DefaultArgumentKind::ExpressionMacro:
break;
}
}
void SILGenModule::
emitStoredPropertyInitialization(PatternBindingDecl *pbd, unsigned i) {
// The SIL emitted for property init expressions is only needed by clients of
// resilient modules if the property belongs to a frozen type. When
// -experimental-skip-non-exportable-decls is specified, skip emitting
// property inits if possible.
if (M.getOptions().SkipNonExportableDecls &&
!pbd->getAnchoringVarDecl(i)->isInitExposedToClients())
return;
// Force the executable init to be type checked before emission.
if (!pbd->getCheckedAndContextualizedExecutableInit(i))
return;
auto *var = pbd->getAnchoringVarDecl(i);
SILDeclRef constant(var, SILDeclRef::Kind::StoredPropertyInitializer);
emitOrDelayFunction(constant);
}
void SILGenModule::
emitPropertyWrapperBackingInitializer(VarDecl *var) {
if (M.getOptions().SkipNonExportableDecls)
return;
auto initInfo = var->getPropertyWrapperInitializerInfo();
if (initInfo.hasInitFromWrappedValue()) {
// FIXME: Fully typecheck the original property's init expression on-demand
// for lazy typechecking mode.
SILDeclRef constant(var, SILDeclRef::Kind::PropertyWrapperBackingInitializer);
emitOrDelayFunction(constant);
}
if (initInfo.hasInitFromProjectedValue()) {
SILDeclRef constant(var, SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue);
emitOrDelayFunction(constant);
}
}
SILFunction *SILGenModule::emitLazyGlobalInitializer(StringRef funcName,
PatternBindingDecl *binding,
unsigned pbdEntry) {
ASTContext &C = M.getASTContext();
auto *onceBuiltin =
cast<FuncDecl>(getBuiltinValueDecl(C, C.getIdentifier("once")));
auto blockParam = onceBuiltin->getParameters()->get(1);
auto *initType = blockParam->getTypeInContext()->castTo<FunctionType>();
auto initSILType = cast<SILFunctionType>(
Types.getLoweredRValueType(TypeExpansionContext::minimal(), initType));
SILGenFunctionBuilder builder(*this);
auto *f = builder.createFunction(
SILLinkage::Private, funcName, initSILType, nullptr, SILLocation(binding),
IsNotBare, IsNotTransparent, IsNotSerialized, IsNotDynamic,
IsNotDistributed, IsNotRuntimeAccessible);
f->setSpecialPurpose(SILFunction::Purpose::GlobalInitOnceFunction);
f->setDebugScope(new (M) SILDebugScope(RegularLocation(binding), f));
auto dc = binding->getDeclContext();
SILGenFunction(*this, *f, dc).emitLazyGlobalInitializer(binding, pbdEntry);
emitLazyConformancesForFunction(f);
f->verifyIncompleteOSSA();
return f;
}
void SILGenModule::emitGlobalAccessor(VarDecl *global,
SILGlobalVariable *onceToken,
SILFunction *onceFunc) {
SILDeclRef accessor(global, SILDeclRef::Kind::GlobalAccessor);
delayedGlobals[global] = std::make_pair(onceToken, onceFunc);
emitOrDelayFunction(accessor);
}
void SILGenModule::emitArgumentGenerators(SILDeclRef::Loc decl,
ParameterList *paramList) {
unsigned index = 0;
for (auto param : *paramList) {
if (param->isDefaultArgument())
emitDefaultArgGenerator(SILDeclRef::getDefaultArgGenerator(decl, index),
param);
if (param->hasExternalPropertyWrapper())
emitPropertyWrapperBackingInitializer(param);
++index;
}
}
void SILGenModule::emitObjCMethodThunk(FuncDecl *method) {
auto thunk = SILDeclRef(method).asForeign();
// Don't emit the thunk if it already exists.
if (hasFunction(thunk))
return;
// ObjC entry points are always externally usable, so can't be delay-emitted.
emitNativeToForeignThunk(thunk);
}
void SILGenModule::emitObjCPropertyMethodThunks(AbstractStorageDecl *prop) {
auto *getter = prop->getOpaqueAccessor(AccessorKind::Get);
// If we don't actually need an entry point for the getter, do nothing.
if (!getter || !requiresObjCMethodEntryPoint(getter))
return;
auto getterRef = SILDeclRef(getter, SILDeclRef::Kind::Func).asForeign();
// Don't emit the thunks if they already exist.
if (hasFunction(getterRef))
return;
// ObjC entry points are always externally usable, so emitting can't be
// delayed.
emitNativeToForeignThunk(getterRef);
if (!prop->isSettable(prop->getDeclContext()))
return;
// FIXME: Add proper location.
auto *setter = prop->getOpaqueAccessor(AccessorKind::Set);
auto setterRef = SILDeclRef(setter, SILDeclRef::Kind::Func).asForeign();
emitNativeToForeignThunk(setterRef);
}
void SILGenModule::emitObjCConstructorThunk(ConstructorDecl *constructor) {
auto thunk = SILDeclRef(constructor, SILDeclRef::Kind::Initializer)
.asForeign();
// Don't emit the thunk if it already exists.
if (hasFunction(thunk))
return;
// ObjC entry points are always externally usable, so emitting can't be
// delayed.
emitNativeToForeignThunk(thunk);
}
void SILGenModule::emitObjCDestructorThunk(DestructorDecl *destructor) {
auto thunk = SILDeclRef(destructor, SILDeclRef::Kind::Deallocator)
.asForeign();
// Don't emit the thunk if it already exists.
if (hasFunction(thunk))
return;
emitNativeToForeignThunk(thunk);
}
void SILGenModule::visitPatternBindingDecl(PatternBindingDecl *pd) {
for (auto i : range(pd->getNumPatternEntries()))
if (pd->getExecutableInit(i))
emitGlobalInitialization(pd, i);
}
void SILGenModule::visitVarDecl(VarDecl *vd) {
if (vd->hasStorage())
addGlobalVariable(vd);
visitEmittedAccessors(vd, [&](AccessorDecl *accessor) {
emitFunction(accessor);
});
tryEmitPropertyDescriptor(vd);
}
void SILGenModule::visitSubscriptDecl(SubscriptDecl *sd) {
llvm_unreachable("top-level subscript?");
}
void SILGenModule::visitMissingDecl(MissingDecl *sd) {
llvm_unreachable("missing decl in SILGen");
}
void SILGenModule::visitMacroDecl(MacroDecl *d) {
// nothing to emit for macros
}
void SILGenModule::visitMacroExpansionDecl(MacroExpansionDecl *d) {
// Expansion already visited as auxiliary decls.
}
void SILGenModule::visitEmittedAccessors(
AbstractStorageDecl *D, llvm::function_ref<void(AccessorDecl *)> callback) {
D->visitEmittedAccessors([&](AccessorDecl *accessor) {
if (shouldSkipDecl(accessor))
return;
callback(accessor);
});
}
bool
SILGenModule::canStorageUseStoredKeyPathComponent(AbstractStorageDecl *decl,
ResilienceExpansion expansion) {
// If the declaration is resilient, we have to treat the component as
// computed.
if (decl->isResilient(M.getSwiftModule(), expansion))
return false;
auto strategy = decl->getAccessStrategy(AccessSemantics::Ordinary,
decl->supportsMutation()
? AccessKind::ReadWrite
: AccessKind::Read,
M.getSwiftModule(),
expansion);
switch (strategy.getKind()) {
case AccessStrategy::Storage: {
// Keypaths rely on accessors to handle the special behavior of weak or
// unowned properties.
if (decl->getInterfaceType()->is<ReferenceStorageType>())
return false;
// If the field offset depends on the generic instantiation, we have to
// load it from metadata when instantiating the keypath component.
//
// However the metadata offset itself will not be fixed if the superclass
// is resilient. Fall back to treating the property as computed in this
// case.
//
// See the call to getClassFieldOffsetOffset() inside
// emitKeyPathComponent().
if (auto *parentClass = dyn_cast<ClassDecl>(decl->getDeclContext())) {
if (parentClass->isGeneric()) {
auto ancestry = parentClass->checkAncestry();
if (ancestry.contains(AncestryFlags::ResilientOther))
return false;
}
}
// If the stored value would need to be reabstracted in fully opaque
// context, then we have to treat the component as computed.
auto componentObjTy = decl->getValueInterfaceType();
if (auto genericEnv =
decl->getInnermostDeclContext()->getGenericEnvironmentOfContext())
componentObjTy = genericEnv->mapTypeIntoContext(componentObjTy);
auto storageTy = M.Types.getSubstitutedStorageType(
TypeExpansionContext::minimal(), decl, componentObjTy);
auto opaqueTy = M.Types.getLoweredRValueType(
TypeExpansionContext::noOpaqueTypeArchetypesSubstitution(expansion),
AbstractionPattern::getOpaque(), componentObjTy);
return storageTy.getASTType() == opaqueTy;
}
case AccessStrategy::DirectToAccessor:
case AccessStrategy::DispatchToAccessor:
case AccessStrategy::MaterializeToTemporary:
case AccessStrategy::DispatchToDistributedThunk:
return false;
}
llvm_unreachable("unhandled strategy");
}
static bool canStorageUseTrivialDescriptor(SILGenModule &SGM,
AbstractStorageDecl *decl) {
// A property can use a trivial property descriptor if the key path component
// that an external module would form given publicly-exported information
// about the property is never equivalent to the canonical component for the
// key path.
// This means that the property isn't stored (without promising to be always
// stored) and doesn't have a setter with less-than-public visibility.
auto expansion = ResilienceExpansion::Maximal;
if (!SGM.M.getSwiftModule()->isResilient()) {
if (SGM.canStorageUseStoredKeyPathComponent(decl, expansion)) {
// External modules can't directly access storage, unless this is a
// property in a fixed-layout type.
// Assert here as key path component cannot refer to a static var.
assert(!decl->isStatic());
// By this point, decl is a fixed layout or its enclosing type is non-resilient.
return true;
}
// If the type is computed and doesn't have a setter that's hidden from
// the public, then external components can form the canonical key path
// without our help.
auto *setter = decl->getOpaqueAccessor(AccessorKind::Set);
if (!setter)
return true;
if (setter->getFormalAccessScope(nullptr, true).isPublicOrPackage())
return true;
return false;
}
// A resilient module needs to handle binaries compiled against its older
// versions. This means we have to be a bit more conservative, since in
// earlier versions, a settable property may have withheld the setter,
// or a fixed-layout type may not have been.
// Without availability information, only get-only computed properties
// can resiliently use trivial descriptors.
return (!SGM.canStorageUseStoredKeyPathComponent(decl, expansion) &&
!decl->supportsMutation());
}
void SILGenModule::tryEmitPropertyDescriptor(AbstractStorageDecl *decl) {
// TODO: Key path code emission doesn't handle opaque values properly yet.
if (!SILModuleConventions(M).useLoweredAddresses())
return;
if (!decl->exportsPropertyDescriptor())
return;
PrettyStackTraceDecl stackTrace("emitting property descriptor for", decl);
Type baseTy;
if (decl->getDeclContext()->isTypeContext()) {
// TODO: Static properties should eventually be referenceable as
// keypaths from T.Type -> Element, viz `baseTy = MetatypeType::get(baseTy)`
assert(!decl->isStatic());
baseTy = decl->getDeclContext()->getSelfInterfaceType()
->getReducedType(decl->getInnermostDeclContext()
->getGenericSignatureOfContext());
} else {
// TODO: Global variables should eventually be referenceable as
// key paths from (), viz. baseTy = TupleType::getEmpty(getASTContext());
llvm_unreachable("should not export a property descriptor yet");
}
auto genericEnv = decl->getInnermostDeclContext()
->getGenericEnvironmentOfContext();
unsigned baseOperand = 0;
bool needsGenericContext = true;
if (canStorageUseTrivialDescriptor(*this, decl)) {
(void)SILProperty::create(M, /*serializedKind*/ 0, decl, std::nullopt);
return;
}
SubstitutionMap subs;
if (genericEnv)
subs = genericEnv->getForwardingSubstitutionMap();
auto component = emitKeyPathComponentForDecl(SILLocation(decl),
genericEnv,
ResilienceExpansion::Maximal,
baseOperand, needsGenericContext,
subs, decl, {},
baseTy->getCanonicalType(),
M.getSwiftModule(),
/*property descriptor*/ true);
(void)SILProperty::create(M, /*serializedKind*/ 0, decl, component);
}
void SILGenModule::visitIfConfigDecl(IfConfigDecl *ICD) {
// Nothing to do for these kinds of decls - anything active has been added
// to the enclosing declaration.
}
void SILGenModule::visitPoundDiagnosticDecl(PoundDiagnosticDecl *PDD) {
// Nothing to do for #error/#warning; they've already been emitted.
}
namespace {
// An RAII object that constructs a \c SILGenModule instance.
// On destruction, delayed definitions are automatically emitted.
class SILGenModuleRAII {
SILGenModule SGM;
public:
void emitSourceFile(SourceFile *sf) {
// Type-check the file if we haven't already.
performTypeChecking(*sf);
if (sf->isScriptMode()) {
SGM.emitEntryPoint(sf);
}
for (auto *D : sf->getTopLevelDecls()) {
// Emit auxiliary decls.
D->visitAuxiliaryDecls([&](Decl *auxiliaryDecl) {
FrontendStatsTracer StatsTracer(SGM.getASTContext().Stats,
"SILgen-decl", auxiliaryDecl);
SGM.visit(auxiliaryDecl);
});
FrontendStatsTracer StatsTracer(SGM.getASTContext().Stats,
"SILgen-decl", D);
SGM.visit(D);
}
// FIXME: Visit macro-generated extensions separately.
//
// The code below that visits auxiliary decls of the top-level
// decls in the source file does not work for nested types with
// attached conformance macros:
// ```
// struct Outer {
// @AddConformance struct Inner {}
// }
// ```
// Because the attached-to decl is not at the top-level. To fix this,
// visit the macro-generated conformances that are recorded in the
// synthesized file unit to cover all macro-generated extension decls.
if (auto *synthesizedFile = sf->getSynthesizedFile()) {
for (auto *D : synthesizedFile->getTopLevelDecls()) {
if (!isa<ExtensionDecl>(D))
continue;
auto *sf = D->getInnermostDeclContext()->getParentSourceFile();
if (sf->getFulfilledMacroRole() != MacroRole::Conformance &&
sf->getFulfilledMacroRole() != MacroRole::Extension)
continue;
FrontendStatsTracer StatsTracer(SGM.getASTContext().Stats,
"SILgen-decl", D);
SGM.visit(D);
}
}
for (Decl *D : sf->getHoistedDecls()) {
FrontendStatsTracer StatsTracer(SGM.getASTContext().Stats,
"SILgen-decl", D);
SGM.visit(D);
}
for (TypeDecl *TD : sf->getLocalTypeDecls()) {
FrontendStatsTracer StatsTracer(SGM.getASTContext().Stats,
"SILgen-tydecl", TD);
// FIXME: Delayed parsing would prevent these types from being added to
// the module in the first place.
if (TD->getDeclContext()->getInnermostSkippedFunctionContext())
continue;
SGM.visit(TD);
}
// If the source file contains an artificial main, emit the implicit
// top-level code.
if (auto *mainDecl = sf->getMainDecl()) {
if (isa<FuncDecl>(mainDecl) &&
static_cast<FuncDecl *>(mainDecl)->hasAsync())
emitSILFunctionDefinition(
SILDeclRef::getAsyncMainDeclEntryPoint(mainDecl));
emitSILFunctionDefinition(SILDeclRef::getMainDeclEntryPoint(mainDecl));
}
}
void emitSymbolSource(SymbolSource Source) {
switch (Source.kind) {
case SymbolSource::Kind::SIL:
emitSILFunctionDefinition(Source.getSILDeclRef());
break;
case SymbolSource::Kind::Global:
SGM.addGlobalVariable(Source.getGlobal());
break;
case SymbolSource::Kind::IR:
llvm_unreachable("Unimplemented: Emission of LinkEntities");
case SymbolSource::Kind::Unknown:
case SymbolSource::Kind::LinkerDirective:
// Nothing to do
break;
}
}
void emitSILFunctionDefinition(SILDeclRef ref) {
SGM.emitFunctionDefinition(ref, SGM.getFunction(ref, ForDefinition));
}
explicit SILGenModuleRAII(SILModule &M) : SGM{M, M.getSwiftModule()} {}
~SILGenModuleRAII() {
// Emit any delayed definitions that were forced.
// Emitting these may in turn force more definitions, so we have to take
// care to keep pumping the queues.
while (!SGM.pendingForcedFunctions.empty()
|| !SGM.pendingConformances.empty()) {
while (!SGM.pendingForcedFunctions.empty()) {
auto &front = SGM.pendingForcedFunctions.front();
SGM.emitFunctionDefinition(
front, SGM.getEmittedFunction(front, ForDefinition));
SGM.pendingForcedFunctions.pop_front();
}
while (!SGM.pendingConformances.empty()) {
(void)SGM.getWitnessTable(SGM.pendingConformances.front());
SGM.pendingConformances.pop_front();
}
}
}
};
} // end anonymous namespace
std::unique_ptr<SILModule>
ASTLoweringRequest::evaluate(Evaluator &evaluator,
ASTLoweringDescriptor desc) const {
// If we have a .sil file to parse, defer to the parsing request.
if (desc.getSourceFileToParse()) {
return evaluateOrFatal(evaluator, ParseSILModuleRequest{desc});
}
auto silMod = SILModule::createEmptyModule(desc.context, desc.conv,
desc.opts, desc.irgenOptions);
// If all function bodies are being skipped there's no reason to do any
// SIL generation.
if (desc.opts.SkipFunctionBodies == FunctionBodySkipping::All)
return silMod;
// Skip emitting SIL if there's been any compilation errors
if (silMod->getASTContext().hadError() &&
silMod->getASTContext().LangOpts.AllowModuleWithCompilerErrors)
return silMod;
SILGenModuleRAII scope(*silMod);
// Emit a specific set of SILDeclRefs if needed.
if (auto Sources = desc.SourcesToEmit) {
for (auto Source : *Sources)
scope.emitSymbolSource(std::move(Source));
}
// Emit any whole-files needed.
for (auto file : desc.getFilesToEmit()) {
if (auto *nextSF = dyn_cast<SourceFile>(file))
scope.emitSourceFile(nextSF);
}
// Also make sure to process any intermediate files that may contain SIL.
bool shouldDeserialize =
llvm::any_of(desc.getFilesToEmit(), [](const FileUnit *File) -> bool {
return isa<SerializedASTFile>(File);
});
if (shouldDeserialize) {
auto *primary = desc.context.dyn_cast<FileUnit *>();
silMod->getSILLoader()->getAllForModule(silMod->getSwiftModule()->getName(),
primary);
}
return silMod;
}
std::unique_ptr<SILModule>
swift::performASTLowering(ModuleDecl *mod, Lowering::TypeConverter &tc,
const SILOptions &options,
const IRGenOptions *irgenOptions) {
auto desc = ASTLoweringDescriptor::forWholeModule(mod, tc, options,
std::nullopt, irgenOptions);
return evaluateOrFatal(mod->getASTContext().evaluator,
ASTLoweringRequest{desc});
}
std::unique_ptr<SILModule> swift::performASTLowering(CompilerInstance &CI,
SymbolSources Sources) {
auto *M = CI.getMainModule();
const auto &Invocation = CI.getInvocation();
const auto &SILOpts = Invocation.getSILOptions();
const auto &IRGenOpts = Invocation.getIRGenOptions();
auto &TC = CI.getSILTypes();
auto Desc = ASTLoweringDescriptor::forWholeModule(
M, TC, SILOpts, std::move(Sources), &IRGenOpts);
return evaluateOrFatal(M->getASTContext().evaluator,
ASTLoweringRequest{Desc});
}
std::unique_ptr<SILModule>
swift::performASTLowering(FileUnit &sf, Lowering::TypeConverter &tc,
const SILOptions &options,
const IRGenOptions *irgenOptions) {
auto desc =
ASTLoweringDescriptor::forFile(sf, tc, options, std::nullopt, irgenOptions);
return evaluateOrFatal(sf.getASTContext().evaluator,
ASTLoweringRequest{desc});
}
|