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
|
//===--- GenHeap.cpp - Layout of heap objects and their metadata ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements routines for arbitrary Swift-native heap objects,
// such as layout and reference-counting.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Path.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Intrinsics.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/SIL/SILModule.h"
#include "ClassTypeInfo.h"
#include "ConstantBuilder.h"
#include "Explosion.h"
#include "GenClass.h"
#include "GenMeta.h"
#include "GenPointerAuth.h"
#include "GenProto.h"
#include "GenType.h"
#include "HeapTypeInfo.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "IndirectTypeInfo.h"
#include "MetadataRequest.h"
#include "GenHeap.h"
using namespace swift;
using namespace irgen;
namespace {
#define NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Nativeness) \
class Nativeness##Name##ReferenceTypeInfo \
: public IndirectTypeInfo<Nativeness##Name##ReferenceTypeInfo, \
FixedTypeInfo> { \
llvm::PointerIntPair<llvm::Type*, 1, bool> ValueTypeAndIsOptional; \
public: \
TypeLayoutEntry \
*buildTypeLayoutEntry(IRGenModule &IGM, \
SILType T, \
bool useStructLayouts) const override { \
if (!useStructLayouts) { \
return IGM.typeLayoutCache.getOrCreateTypeInfoBasedEntry(*this, T); \
} \
return IGM.typeLayoutCache.getOrCreateScalarEntry( \
*this, T, ScalarKind::Nativeness##Name##Reference); \
} \
Nativeness##Name##ReferenceTypeInfo(llvm::Type *valueType, \
llvm::Type *type, \
Size size, Alignment alignment, \
SpareBitVector &&spareBits, \
bool isOptional) \
: IndirectTypeInfo(type, size, std::move(spareBits), alignment, \
IsNotTriviallyDestroyable, IsNotBitwiseTakable, IsCopyable, IsFixedSize), \
ValueTypeAndIsOptional(valueType, isOptional) {} \
void initializeWithCopy(IRGenFunction &IGF, Address destAddr, \
Address srcAddr, SILType T, \
bool isOutlined) const override { \
IGF.emit##Nativeness##Name##CopyInit(destAddr, srcAddr); \
} \
void initializeWithTake(IRGenFunction &IGF, Address destAddr, \
Address srcAddr, SILType T, \
bool isOutlined) const override { \
IGF.emit##Nativeness##Name##TakeInit(destAddr, srcAddr); \
} \
void assignWithCopy(IRGenFunction &IGF, Address destAddr, Address srcAddr, \
SILType T, bool isOutlined) const override { \
IGF.emit##Nativeness##Name##CopyAssign(destAddr, srcAddr); \
} \
void assignWithTake(IRGenFunction &IGF, Address destAddr, Address srcAddr, \
SILType T, bool isOutlined) const override { \
IGF.emit##Nativeness##Name##TakeAssign(destAddr, srcAddr); \
} \
void destroy(IRGenFunction &IGF, Address addr, SILType T, \
bool isOutlined) const override { \
IGF.emit##Nativeness##Name##Destroy(addr); \
} \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
auto count = IGM.getReferenceStorageExtraInhabitantCount( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
return count - ValueTypeAndIsOptional.getInt(); \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
return IGM.getReferenceStorageExtraInhabitantValue(bits, \
index + ValueTypeAndIsOptional.getInt(), \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
return IGF.getReferenceStorageExtraInhabitantIndex(src, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
return IGF.storeReferenceStorageExtraInhabitant(index, dest, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { \
return IGM.getReferenceStorageExtraInhabitantMask( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
llvm::Type *getOptionalIntType() const { \
return llvm::IntegerType::get( \
ValueTypeAndIsOptional.getPointer()->getContext(), \
getFixedSize().getValueInBits()); \
} \
};
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Nativeness) \
class Nativeness##Name##ReferenceTypeInfo \
: public SingleScalarTypeInfo<Nativeness##Name##ReferenceTypeInfo, \
LoadableTypeInfo> { \
llvm::PointerIntPair<llvm::Type*, 1, bool> ValueTypeAndIsOptional; \
public: \
Nativeness##Name##ReferenceTypeInfo(llvm::Type *valueType, \
llvm::Type *type, \
Size size, Alignment alignment, \
SpareBitVector &&spareBits, \
bool isOptional) \
: SingleScalarTypeInfo(type, size, std::move(spareBits), \
alignment, IsNotTriviallyDestroyable, \
IsCopyable, \
IsFixedSize), \
ValueTypeAndIsOptional(valueType, isOptional) {} \
enum { IsScalarTriviallyDestroyable = false }; \
TypeLayoutEntry \
*buildTypeLayoutEntry(IRGenModule &IGM, \
SILType T, \
bool useStructLayouts) const override { \
if (!useStructLayouts) { \
return IGM.typeLayoutCache.getOrCreateTypeInfoBasedEntry(*this, T); \
} \
return IGM.typeLayoutCache.getOrCreateScalarEntry( \
*this, T, ScalarKind::Nativeness##Name##Reference); \
} \
llvm::Type *getScalarType() const { \
return ValueTypeAndIsOptional.getPointer(); \
} \
Address projectScalar(IRGenFunction &IGF, Address addr) const { \
return IGF.Builder.CreateElementBitCast(addr, getScalarType()); \
} \
void emitScalarRetain(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const { \
IGF.emit##Nativeness##Name##Retain(value, atomicity); \
} \
void emitScalarRelease(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const { \
IGF.emit##Nativeness##Name##Release(value, atomicity); \
} \
void emitScalarFixLifetime(IRGenFunction &IGF, llvm::Value *value) const { \
IGF.emitFixLifetime(value); \
} \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
auto count = IGM.getReferenceStorageExtraInhabitantCount( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
return count - ValueTypeAndIsOptional.getInt(); \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
return IGM.getReferenceStorageExtraInhabitantValue(bits, \
index + ValueTypeAndIsOptional.getInt(), \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
return IGF.getReferenceStorageExtraInhabitantIndex(src, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
return IGF.storeReferenceStorageExtraInhabitant(index, dest, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { \
return IGM.getReferenceStorageExtraInhabitantMask( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
};
// The nativeness of a reference storage type is a policy decision.
// Please also see the related ALWAYS_NATIVE and SOMETIMES_UNKNOWN macros
// later in this file that expand to the following boilerplate:
// TypeConverter::create##Name##StorageType
NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Weak, Native)
NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Weak, Unknown)
NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Unowned, Unknown)
ALWAYS_LOADABLE_CHECKED_REF_STORAGE_HELPER(Unowned, Native)
#undef NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER
#undef ALWAYS_LOADABLE_CHECKED_REF_STORAGE_HELPER
#define UNCHECKED_REF_STORAGE(Name, ...) \
class Name##ReferenceTypeInfo \
: public PODSingleScalarTypeInfo<Name##ReferenceTypeInfo, \
LoadableTypeInfo> { \
bool IsOptional; \
public: \
Name##ReferenceTypeInfo(llvm::Type *type, \
const SpareBitVector &spareBits, \
Size size, Alignment alignment, bool isOptional) \
: PODSingleScalarTypeInfo(type, size, spareBits, alignment), \
IsOptional(isOptional) {} \
/* Static types have the same spare bits as managed heap objects. */ \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
return getHeapObjectExtraInhabitantCount(IGM) - IsOptional; \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
return getHeapObjectFixedExtraInhabitantValue(IGM, bits, \
index + IsOptional, 0); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
return getHeapObjectExtraInhabitantIndex(IGF, src); \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
return storeHeapObjectExtraInhabitant(IGF, index, dest); \
} \
};
#include "swift/AST/ReferenceStorage.def"
} // end anonymous namespace
/// Produce a constant to place in a metatype's isa field
/// corresponding to the given metadata kind.
static llvm::ConstantInt *getMetadataKind(IRGenModule &IGM,
MetadataKind kind) {
return llvm::ConstantInt::get(IGM.MetadataKindTy, uint32_t(kind));
}
/// Perform the layout required for a heap object.
HeapLayout::HeapLayout(IRGenModule &IGM, LayoutStrategy strategy,
ArrayRef<SILType> fieldTypes,
ArrayRef<const TypeInfo *> fieldTypeInfos,
llvm::StructType *typeToFill,
NecessaryBindings &&bindings, unsigned bindingsIndex)
: StructLayout(IGM, /*type=*/std::nullopt, LayoutKind::HeapObject, strategy,
fieldTypeInfos, typeToFill),
ElementTypes(fieldTypes.begin(), fieldTypes.end()),
Bindings(std::move(bindings)), BindingsIndex(bindingsIndex) {
#ifndef NDEBUG
assert(fieldTypeInfos.size() == fieldTypes.size()
&& "type infos don't match types");
if (!Bindings.empty()) {
assert(fieldTypeInfos.size() >= (bindingsIndex + 1) &&
"no field for bindings");
auto fixedBindingsField =
dyn_cast<FixedTypeInfo>(fieldTypeInfos[bindingsIndex]);
assert(fixedBindingsField
&& "bindings field is not fixed size");
assert(fixedBindingsField->getFixedSize()
== Bindings.getBufferSize(IGM)
&& fixedBindingsField->getFixedAlignment()
== IGM.getPointerAlignment()
&& "bindings field doesn't fit bindings");
}
#endif
}
static llvm::Value *calcInitOffset(swift::irgen::IRGenFunction &IGF,
unsigned int i,
const swift::irgen::HeapLayout &layout) {
llvm::Value *offset = nullptr;
if (i == 0) {
auto startOffset = layout.getHeaderSize();
offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, startOffset.getValue());
return offset;
}
auto &prevElt = layout.getElement(i - 1);
auto prevType = layout.getElementTypes()[i - 1];
// Start calculating offsets from the last fixed-offset field.
Size lastFixedOffset = layout.getElement(i - 1).getByteOffsetDuringLayout();
if (auto *fixedType = dyn_cast<FixedTypeInfo>(&prevElt.getType())) {
// If the last fixed-offset field is also fixed-size, we can
// statically compute the end of the fixed-offset fields.
auto fixedEnd = lastFixedOffset + fixedType->getFixedSize();
offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, fixedEnd.getValue());
} else {
// Otherwise, we need to add the dynamic size to the fixed start
// offset.
offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, lastFixedOffset.getValue());
offset = IGF.Builder.CreateAdd(
offset, prevElt.getType().getSize(IGF, prevType));
}
return offset;
}
HeapNonFixedOffsets::HeapNonFixedOffsets(IRGenFunction &IGF,
const HeapLayout &layout) {
if (!layout.isFixedLayout()) {
// Calculate all the non-fixed layouts.
// TODO: We could be lazier about this.
llvm::Value *offset = nullptr;
llvm::Value *totalAlign = llvm::ConstantInt::get(IGF.IGM.SizeTy,
layout.getAlignment().getMaskValue());
for (unsigned i : indices(layout.getElements())) {
auto &elt = layout.getElement(i);
auto eltTy = layout.getElementTypes()[i];
switch (elt.getKind()) {
case ElementLayout::Kind::InitialNonFixedSize:
// Factor the non-fixed-size field's alignment into the total alignment.
totalAlign = IGF.Builder.CreateOr(totalAlign,
elt.getType().getAlignmentMask(IGF, eltTy));
LLVM_FALLTHROUGH;
case ElementLayout::Kind::Empty:
case ElementLayout::Kind::EmptyTailAllocatedCType:
case ElementLayout::Kind::Fixed:
// Don't need to dynamically calculate this offset.
Offsets.push_back(nullptr);
break;
case ElementLayout::Kind::NonFixed:
// Start calculating non-fixed offsets from the end of the first fixed
// field.
if (!offset) {
offset = calcInitOffset(IGF, i, layout);
}
// Round up to alignment to get the offset.
auto alignMask = elt.getType().getAlignmentMask(IGF, eltTy);
auto notAlignMask = IGF.Builder.CreateNot(alignMask);
offset = IGF.Builder.CreateAdd(offset, alignMask);
offset = IGF.Builder.CreateAnd(offset, notAlignMask);
Offsets.push_back(offset);
// Advance by the field's size to start the next field.
offset = IGF.Builder.CreateAdd(offset,
elt.getType().getSize(IGF, eltTy));
totalAlign = IGF.Builder.CreateOr(totalAlign, alignMask);
break;
}
}
TotalSize = offset;
TotalAlignMask = totalAlign;
} else {
TotalSize = layout.emitSize(IGF.IGM);
TotalAlignMask = layout.emitAlignMask(IGF.IGM);
}
}
void irgen::emitDeallocateHeapObject(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocObjectFunctionPointer(),
{object, size, alignMask});
}
void emitDeallocateUninitializedHeapObject(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
IGF.Builder.CreateCall(IGF.IGM.getDeallocUninitializedObjectFunctionPointer(),
{object, size, alignMask});
}
void irgen::emitDeallocateClassInstance(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocClassInstanceFunctionPointer(),
{object, size, alignMask});
}
void irgen::emitDeallocatePartialClassInstance(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *metadata,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(
IGF.IGM.getDeallocPartialClassInstanceFunctionPointer(),
{object, metadata, size, alignMask});
}
/// Create the destructor function for a layout.
/// TODO: give this some reasonable name and possibly linkage.
static llvm::Function *createDtorFn(IRGenModule &IGM,
const HeapLayout &layout) {
llvm::Function *fn =
llvm::Function::Create(IGM.DeallocatingDtorTy,
llvm::Function::PrivateLinkage,
"objectdestroy", &IGM.Module);
auto attrs = IGM.constructInitialAttributes();
IGM.addSwiftSelfAttributes(attrs, 0);
fn->setAttributes(attrs);
fn->setCallingConv(IGM.SwiftCC);
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
Address structAddr = layout.emitCastTo(IGF, &*fn->arg_begin());
// Bind necessary bindings, if we have them.
if (layout.hasBindings()) {
// The type metadata bindings should be at a fixed offset, so we can pass
// None for NonFixedOffsets. If we didn't, we'd have a chicken-egg problem.
auto bindingsAddr = layout.getElement(layout.getBindingsIndex())
.project(IGF, structAddr, std::nullopt);
layout.getBindings().restore(IGF, bindingsAddr, MetadataState::Complete);
}
// Figure out the non-fixed offsets.
HeapNonFixedOffsets offsets(IGF, layout);
// Destroy the fields.
for (unsigned i : indices(layout.getElements())) {
auto &field = layout.getElement(i);
auto fieldTy = layout.getElementTypes()[i];
if (field.isTriviallyDestroyable())
continue;
field.getType().destroy(
IGF, field.project(IGF, structAddr, offsets), fieldTy,
true /*Called from metadata constructors: must be outlined*/);
}
emitDeallocateHeapObject(IGF, &*fn->arg_begin(), offsets.getSize(),
offsets.getAlignMask());
IGF.Builder.CreateRetVoid();
return fn;
}
/// Create the size function for a layout.
/// TODO: give this some reasonable name and possibly linkage.
llvm::Constant *HeapLayout::createSizeFn(IRGenModule &IGM) const {
llvm::Function *fn =
llvm::Function::Create(IGM.DeallocatingDtorTy,
llvm::Function::PrivateLinkage,
"objectsize", &IGM.Module);
fn->setAttributes(IGM.constructInitialAttributes());
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
// Ignore the object pointer; we aren't a dynamically-sized array,
// so it's pointless.
llvm::Value *size = emitSize(IGM);
IGF.Builder.CreateRet(size);
return fn;
}
static llvm::Constant *buildPrivateMetadata(IRGenModule &IGM,
const HeapLayout &layout,
llvm::Constant *dtorFn,
llvm::Constant *captureDescriptor,
MetadataKind kind) {
// Build the fields of the private metadata.
ConstantInitBuilder builder(IGM);
// In embedded Swift, heap objects have a different, simple(r) layout:
// superclass pointer + destructor.
if (IGM.Context.LangOpts.hasFeature(Feature::Embedded)) {
auto fields = builder.beginStruct();
fields.addNullPointer(IGM.Int8PtrTy);
fields.addSignedPointer(dtorFn,
IGM.getOptions().PointerAuth.HeapDestructors,
PointerAuthEntity::Special::HeapDestructor);
llvm::GlobalVariable *var = fields.finishAndCreateGlobal(
"metadata", IGM.getPointerAlignment(), /*constant*/ true,
llvm::GlobalVariable::PrivateLinkage);
return var;
}
auto fields = builder.beginStruct(IGM.FullBoxMetadataStructTy);
fields.addSignedPointer(dtorFn, IGM.getOptions().PointerAuth.HeapDestructors,
PointerAuthEntity::Special::HeapDestructor);
fields.addNullPointer(IGM.WitnessTablePtrTy);
{
auto kindStruct = fields.beginStruct(IGM.TypeMetadataStructTy);
kindStruct.add(getMetadataKind(IGM, kind));
kindStruct.finishAndAddTo(fields);
}
// Figure out the offset to the first element, which is necessary to be able
// to polymorphically project as a generic box.
auto elements = layout.getElements();
Size offset;
if (!elements.empty()
&& elements[0].getKind() == ElementLayout::Kind::Fixed)
offset = elements[0].getByteOffset();
else
offset = Size(0);
fields.addInt32(offset.getValue());
fields.add(captureDescriptor);
llvm::GlobalVariable *var =
fields.finishAndCreateGlobal("metadata",
IGM.getPointerAlignment(),
/*constant*/ true,
llvm::GlobalVariable::PrivateLinkage);
llvm::Constant *indices[] = {
llvm::ConstantInt::get(IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGM.Int32Ty, 2)
};
return llvm::ConstantExpr::getInBoundsGetElementPtr(var->getValueType(), var,
indices);
}
llvm::Constant *
HeapLayout::getPrivateMetadata(IRGenModule &IGM,
llvm::Constant *captureDescriptor) const {
if (!privateMetadata)
privateMetadata = buildPrivateMetadata(IGM, *this, createDtorFn(IGM, *this),
captureDescriptor,
MetadataKind::HeapLocalVariable);
return privateMetadata;
}
llvm::Value *IRGenFunction::emitUnmanagedAlloc(const HeapLayout &layout,
const llvm::Twine &name,
llvm::Constant *captureDescriptor,
const HeapNonFixedOffsets *offsets) {
if (layout.isKnownEmpty())
return IGM.RefCountedNull;
llvm::Value *metadata = layout.getPrivateMetadata(IGM, captureDescriptor);
llvm::Value *size, *alignMask;
if (offsets) {
size = offsets->getSize();
alignMask = offsets->getAlignMask();
} else {
size = layout.emitSize(IGM);
alignMask = layout.emitAlignMask(IGM);
}
return emitAllocObjectCall(metadata, size, alignMask, name);
}
namespace {
class BuiltinNativeObjectTypeInfo
: public HeapTypeInfo<BuiltinNativeObjectTypeInfo> {
public:
BuiltinNativeObjectTypeInfo(llvm::PointerType *storage,
Size size, SpareBitVector spareBits,
Alignment align)
: HeapTypeInfo(ReferenceCounting::Native, storage, size, spareBits,
align) {}
/// Builtin.NativeObject uses Swift native reference-counting.
ReferenceCounting getReferenceCounting() const {
return ReferenceCounting::Native;
}
};
} // end anonymous namespace
const LoadableTypeInfo *TypeConverter::convertBuiltinNativeObject() {
return new BuiltinNativeObjectTypeInfo(IGM.RefCountedPtrTy,
IGM.getPointerSize(),
IGM.getHeapObjectSpareBits(),
IGM.getPointerAlignment());
}
unsigned IRGenModule::getReferenceStorageExtraInhabitantCount(
ReferenceOwnership ownership,
ReferenceCounting style) const {
switch (style) {
case ReferenceCounting::Native:
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ownership == ReferenceOwnership::Name) \
break;
#include "swift/AST/ReferenceStorage.def"
if (ObjCInterop)
break;
return getHeapObjectExtraInhabitantCount(*this);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::None:
case ReferenceCounting::Unknown:
case ReferenceCounting::Custom:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior uses pointer semantics, therefore null is the only
// extra inhabitant allowed.
return 1;
}
SpareBitVector IRGenModule::getReferenceStorageSpareBits(
ReferenceOwnership ownership,
ReferenceCounting style) const {
// We have to be conservative (even with native reference-counting) in order
// to interoperate with code that might be working more generically with the
// memory/type.
switch (style) {
case ReferenceCounting::Native:
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ownership == ReferenceOwnership::Name) \
break;
#include "swift/AST/ReferenceStorage.def"
if (ObjCInterop)
break;
return getHeapObjectSpareBits();
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::None:
case ReferenceCounting::Custom:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior uses pointer semantics.
return SpareBitVector::getConstant(getPointerSize().getValueInBits(), false);
}
APInt IRGenModule::getReferenceStorageExtraInhabitantValue(unsigned bits,
unsigned index,
ReferenceOwnership ownership,
ReferenceCounting style) const {
// We have to be conservative (even with native reference-counting) in order
// to interoperate with code that might be working more generically with the
// memory/type.
switch (style) {
case ReferenceCounting::Native:
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ownership == ReferenceOwnership::Name) \
break;
#include "swift/AST/ReferenceStorage.def"
if (ObjCInterop)
break;
return getHeapObjectFixedExtraInhabitantValue(*this, bits, index, 0);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::None:
case ReferenceCounting::Custom:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior allows for only one legal extra inhabitant, therefore
// this must be the null pattern.
assert(index == 0);
return APInt(bits, 0);
}
APInt IRGenModule::getReferenceStorageExtraInhabitantMask(
ReferenceOwnership ownership,
ReferenceCounting style) const {
switch (style) {
case ReferenceCounting::Native:
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::None:
case ReferenceCounting::Custom:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
return APInt::getAllOnes(getPointerSize().getValueInBits());
}
llvm::Value *IRGenFunction::getReferenceStorageExtraInhabitantIndex(Address src,
ReferenceOwnership ownership,
ReferenceCounting style) {
switch (style) {
case ReferenceCounting::Native:
if (IGM.ObjCInterop)
break;
return getHeapObjectExtraInhabitantIndex(*this, src);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::None:
case ReferenceCounting::Custom:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior allows for only one legal extra inhabitant, therefore
// this must be the null pattern.
auto PtrTy =
#define CHECKED_REF_STORAGE(Name, ...) \
ownership == ReferenceOwnership::Name ? IGM.Name##ReferencePtrTy :
#include "swift/AST/ReferenceStorage.def"
nullptr;
(void)PtrTy;
assert(src.getAddress()->getType() == PtrTy);
src = Builder.CreateStructGEP(src, 0, Size(0));
llvm::Value *ptr = Builder.CreateLoad(src);
llvm::Value *isNull = Builder.CreateIsNull(ptr);
llvm::Value *result =
Builder.CreateSelect(isNull, Builder.getInt32(0),
llvm::ConstantInt::getSigned(IGM.Int32Ty, -1));
return result;
}
void IRGenFunction::storeReferenceStorageExtraInhabitant(llvm::Value *index,
Address dest,
ReferenceOwnership ownership,
ReferenceCounting style) {
switch (style) {
case ReferenceCounting::Native:
if (IGM.ObjCInterop)
break;
return storeHeapObjectExtraInhabitant(*this, index, dest);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::None:
case ReferenceCounting::Custom:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior allows for only one legal extra inhabitant, therefore
// this must be the null pattern.
auto PtrTy =
#define CHECKED_REF_STORAGE(Name, ...) \
ownership == ReferenceOwnership::Name ? IGM.Name##ReferencePtrTy :
#include "swift/AST/ReferenceStorage.def"
nullptr;
(void)PtrTy;
assert(dest.getAddress()->getType() == PtrTy);
dest = Builder.CreateStructGEP(dest, 0, Size(0));
llvm::Value *null = llvm::ConstantPointerNull::get(IGM.RefCountedPtrTy);
Builder.CreateStore(null, dest);
}
#define SOMETIMES_UNKNOWN(Name) \
const TypeInfo *TypeConverter::create##Name##StorageType( \
llvm::Type *valueType, ReferenceCounting style, bool isOptional) { \
auto &&spareBits = \
IGM.getReferenceStorageSpareBits(ReferenceOwnership::Name, style); \
switch (style) { \
case ReferenceCounting::Native: \
return new Native##Name##ReferenceTypeInfo( \
valueType, IGM.Name##ReferenceStructTy, IGM.getPointerSize(), \
IGM.getPointerAlignment(), std::move(spareBits), isOptional); \
case ReferenceCounting::ObjC: \
case ReferenceCounting::None: \
case ReferenceCounting::Custom: \
case ReferenceCounting::Block: \
case ReferenceCounting::Unknown: \
return new Unknown##Name##ReferenceTypeInfo( \
valueType, IGM.Name##ReferenceStructTy, IGM.getPointerSize(), \
IGM.getPointerAlignment(), std::move(spareBits), isOptional); \
case ReferenceCounting::Bridge: \
case ReferenceCounting::Error: \
llvm_unreachable("not supported!"); \
} \
llvm_unreachable("bad reference-counting style"); \
}
#define ALWAYS_NATIVE(Name) \
const TypeInfo * \
TypeConverter::create##Name##StorageType(llvm::Type *valueType, \
ReferenceCounting style, \
bool isOptional) { \
assert(style == ReferenceCounting::Native); \
auto &&spareBits = IGM.getReferenceStorageSpareBits( \
ReferenceOwnership::Name, \
ReferenceCounting::Native); \
return new Native##Name##ReferenceTypeInfo(valueType, \
IGM.Name##ReferencePtrTy->getElementType(), \
IGM.getPointerSize(), \
IGM.getPointerAlignment(), \
std::move(spareBits), \
isOptional); \
}
// Always native versus "sometimes unknown" reference storage type policy:
SOMETIMES_UNKNOWN(Weak)
SOMETIMES_UNKNOWN(Unowned)
#undef SOMETIMES_UNKNOWN
#undef ALWAYS_NATIVE
#define CHECKED_REF_STORAGE(Name, ...) \
static_assert(&TypeConverter::create##Name##StorageType != nullptr, \
"Missing reference storage type converter helper constructor");
#define UNCHECKED_REF_STORAGE(Name, ...) \
const TypeInfo * \
TypeConverter::create##Name##StorageType(llvm::Type *valueType, \
ReferenceCounting style, \
bool isOptional) { \
(void)style; /* unused */ \
return new Name##ReferenceTypeInfo(valueType, \
IGM.getHeapObjectSpareBits(), \
IGM.getPointerSize(), \
IGM.getPointerAlignment(), \
isOptional); \
}
#include "swift/AST/ReferenceStorage.def"
/// Does the given value superficially not require reference-counting?
static bool doesNotRequireRefCounting(llvm::Value *value) {
// Constants never require reference-counting.
return isa<llvm::ConstantPointerNull>(value);
}
/// Emit a unary call to perform a ref-counting operation.
///
/// \param fn - expected signature 'void (T)' or 'T (T)'
static void emitUnaryRefCountCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *value) {
auto fun = cast<llvm::Function>(fn);
auto cc = fun->getCallingConv();
// Instead of casting the input, we cast the function type.
// This tends to produce less IR, but might be evil.
auto fnType = cast<llvm::FunctionType>(fun->getValueType());
if (value->getType() != fnType->getParamType(0)) {
auto resultTy = fnType->getReturnType() == IGF.IGM.VoidTy
? IGF.IGM.VoidTy
: value->getType();
fnType = llvm::FunctionType::get(resultTy, value->getType(), false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCallWithoutDbgLoc(fnType, fn, value);
if (fun && fun->hasParamAttribute(0, llvm::Attribute::Returned))
call->addParamAttr(0, llvm::Attribute::Returned);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a copy-like call to perform a ref-counting operation.
///
/// \param fn - expected signature 'void (T, T)' or 'T (T, T)'
static void emitCopyLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *dest,
llvm::Value *src) {
assert(dest->getType() == src->getType() &&
"type mismatch in binary refcounting operation");
auto fun = cast<llvm::Function>(fn);
auto cc = fun->getCallingConv();
// Instead of casting the inputs, we cast the function type.
// This tends to produce less IR, but might be evil.
auto fnType = cast<llvm::FunctionType>(fun->getValueType());
if (dest->getType() != fnType->getParamType(0)) {
llvm::Type *paramTypes[] = { dest->getType(), dest->getType() };
auto resultTy = fnType->getReturnType() == IGF.IGM.VoidTy ? IGF.IGM.VoidTy
: dest->getType();
fnType = llvm::FunctionType::get(resultTy, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call =
IGF.Builder.CreateCallWithoutDbgLoc(fnType, fn, {dest, src});
if (fun && fun->hasParamAttribute(0, llvm::Attribute::Returned))
call->addParamAttr(0, llvm::Attribute::Returned);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a call to a function with a loadWeak-like signature.
///
/// \param fn - expected signature 'T (Weak*)'
static llvm::Value *emitLoadWeakLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *addr,
llvm::Type *resultType) {
assert((addr->getType() == IGF.IGM.WeakReferencePtrTy ||
addr->getType() == IGF.IGM.UnownedReferencePtrTy) &&
"address is not of a weak or unowned reference");
auto fun = cast<llvm::Function>(fn);
auto cc = fun->getCallingConv();
// Instead of casting the output, we cast the function type.
// This tends to produce less IR, but might be evil.
auto fnType = cast<llvm::FunctionType>(fun->getValueType());
if (resultType != fnType->getReturnType()) {
llvm::Type *paramTypes[] = { addr->getType() };
fnType = llvm::FunctionType::get(resultType, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCallWithoutDbgLoc(fnType, fn, addr);
call->setCallingConv(cc);
call->setDoesNotThrow();
return call;
}
/// Emit a call to a function with a storeWeak-like signature.
///
/// \param fn - expected signature 'void (Weak*, T)' or 'Weak* (Weak*, T)'
static void emitStoreWeakLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *addr,
llvm::Value *value) {
assert((addr->getType() == IGF.IGM.WeakReferencePtrTy ||
addr->getType() == IGF.IGM.UnownedReferencePtrTy) &&
"address is not of a weak or unowned reference");
auto fun = cast<llvm::Function>(fn);
auto cc = fun->getCallingConv();
// Instead of casting the inputs, we cast the function type.
// This tends to produce less IR, but might be evil.
auto fnType = cast<llvm::FunctionType>(fun->getValueType());
if (value->getType() != fnType->getParamType(1)) {
llvm::Type *paramTypes[] = { addr->getType(), value->getType() };
auto resultTy = fnType->getReturnType() == IGF.IGM.VoidTy ? IGF.IGM.VoidTy
: addr->getType();
fnType = llvm::FunctionType::get(resultTy, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call =
IGF.Builder.CreateCallWithoutDbgLoc(fnType, fn, {addr, value});
if (fun && fun->hasParamAttribute(0, llvm::Attribute::Returned))
call->addParamAttr(0, llvm::Attribute::Returned);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a call to swift_retain.
void IRGenFunction::emitNativeStrongRetain(llvm::Value *value,
Atomicity atomicity) {
if (doesNotRequireRefCounting(value))
return;
// Make sure the input pointer is the right type.
if (value->getType() != IGM.RefCountedPtrTy)
value = Builder.CreateBitCast(value, IGM.RefCountedPtrTy);
// Emit the call.
llvm::CallInst *call = Builder.CreateCall(
(atomicity == Atomicity::Atomic)
? IGM.getNativeStrongRetainFunctionPointer()
: IGM.getNativeNonAtomicStrongRetainFunctionPointer(),
value);
call->setDoesNotThrow();
call->addParamAttr(0, llvm::Attribute::Returned);
}
/// Emit a store of a live value to the given retaining variable.
void IRGenFunction::emitNativeStrongAssign(llvm::Value *newValue,
Address address) {
// Pull the old value out of the address.
llvm::Value *oldValue = Builder.CreateLoad(address);
// We assume the new value is already retained.
Builder.CreateStore(newValue, address);
// Release the old value.
emitNativeStrongRelease(oldValue, getDefaultAtomicity());
}
/// Emit an initialize of a live value to the given retaining variable.
void IRGenFunction::emitNativeStrongInit(llvm::Value *newValue,
Address address) {
// We assume the new value is already retained.
Builder.CreateStore(newValue, address);
}
/// Emit a release of a live value with the given refcounting implementation.
void IRGenFunction::emitStrongRelease(llvm::Value *value,
ReferenceCounting refcounting,
Atomicity atomicity) {
switch (refcounting) {
case ReferenceCounting::Native:
return emitNativeStrongRelease(value, atomicity);
case ReferenceCounting::ObjC:
return emitObjCStrongRelease(value);
case ReferenceCounting::Block:
return emitBlockRelease(value);
case ReferenceCounting::Unknown:
return emitUnknownStrongRelease(value, atomicity);
case ReferenceCounting::Bridge:
return emitBridgeStrongRelease(value, atomicity);
case ReferenceCounting::Error:
return emitErrorStrongRelease(value);
case ReferenceCounting::Custom:
llvm_unreachable("Ref counting should be handled in TypeInfo.");
case ReferenceCounting::None:
return; // This is a no-op if we don't have any ref-counting.
}
}
void IRGenFunction::emitStrongRetain(llvm::Value *value,
ReferenceCounting refcounting,
Atomicity atomicity) {
switch (refcounting) {
case ReferenceCounting::Native:
emitNativeStrongRetain(value, atomicity);
return;
case ReferenceCounting::Bridge:
emitBridgeStrongRetain(value, atomicity);
return;
case ReferenceCounting::ObjC:
emitObjCStrongRetain(value);
return;
case ReferenceCounting::Block:
emitBlockCopyCall(value);
return;
case ReferenceCounting::Unknown:
emitUnknownStrongRetain(value, atomicity);
return;
case ReferenceCounting::Error:
emitErrorStrongRetain(value);
return;
case ReferenceCounting::Custom:
llvm_unreachable("Ref counting should be handled in TypeInfo.");
case ReferenceCounting::None:
return; // This is a no-op if we don't have any ref-counting.
}
}
llvm::Type *IRGenModule::getReferenceType(ReferenceCounting refcounting) {
switch (refcounting) {
case ReferenceCounting::Native:
return RefCountedPtrTy;
case ReferenceCounting::Bridge:
return BridgeObjectPtrTy;
case ReferenceCounting::ObjC:
return ObjCPtrTy;
case ReferenceCounting::Block:
return ObjCBlockPtrTy;
case ReferenceCounting::Unknown:
return UnknownRefCountedPtrTy;
case ReferenceCounting::Error:
return ErrorPtrTy;
case ReferenceCounting::Custom:
case ReferenceCounting::None:
return OpaquePtrTy;
}
llvm_unreachable("Not a valid ReferenceCounting.");
}
#define DEFINE_BINARY_OPERATION(KIND, RESULT, TYPE1, TYPE2) \
RESULT IRGenFunction::emit##KIND(TYPE1 val1, TYPE2 val2, \
ReferenceCounting style) { \
switch (style) { \
case ReferenceCounting::Native: \
return emitNative##KIND(val1, val2); \
case ReferenceCounting::ObjC: \
case ReferenceCounting::Unknown: \
return emitUnknown##KIND(val1, val2); \
case ReferenceCounting::Bridge: \
case ReferenceCounting::Block: \
case ReferenceCounting::Error: \
case ReferenceCounting::Custom: \
case ReferenceCounting::None: \
llvm_unreachable("unsupported reference kind with reference storage"); \
} \
llvm_unreachable("bad refcounting style"); \
}
#define DEFINE_UNARY_OPERATION(KIND, RESULT, TYPE1) \
RESULT IRGenFunction::emit##KIND(TYPE1 val1, ReferenceCounting style) { \
switch (style) { \
case ReferenceCounting::Native: \
return emitNative##KIND(val1); \
case ReferenceCounting::ObjC: \
case ReferenceCounting::Unknown: \
return emitUnknown##KIND(val1); \
case ReferenceCounting::Bridge: \
case ReferenceCounting::Block: \
case ReferenceCounting::Error: \
case ReferenceCounting::Custom: \
case ReferenceCounting::None: \
llvm_unreachable("unsupported reference kind with reference storage"); \
} \
llvm_unreachable("bad refcounting style"); \
}
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
DEFINE_BINARY_OPERATION(Name##CopyInit, void, Address, Address) \
DEFINE_BINARY_OPERATION(Name##TakeInit, void, Address, Address) \
DEFINE_BINARY_OPERATION(Name##CopyAssign, void, Address, Address) \
DEFINE_BINARY_OPERATION(Name##TakeAssign, void, Address, Address) \
DEFINE_BINARY_OPERATION(Name##Init, void, llvm::Value *, Address) \
DEFINE_BINARY_OPERATION(Name##Assign, void, llvm::Value *, Address) \
DEFINE_BINARY_OPERATION(Name##LoadStrong, llvm::Value *, Address,llvm::Type*)\
DEFINE_BINARY_OPERATION(Name##TakeStrong, llvm::Value *, Address,llvm::Type*)\
DEFINE_UNARY_OPERATION(Name##Destroy, void, Address)
#include "swift/AST/ReferenceStorage.def"
#undef DEFINE_UNARY_OPERATION
#undef DEFINE_BINARY_OPERATION
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \
void IRGenFunction::emit##Name##Retain(llvm::Value *value, \
ReferenceCounting style, \
Atomicity atomicity) { \
assert(style == ReferenceCounting::Native && \
"only native references support scalar reference-counting"); \
emitNative##Name##Retain(value, atomicity); \
} \
void IRGenFunction::emit##Name##Release(llvm::Value *value, \
ReferenceCounting style, \
Atomicity atomicity) { \
assert(style == ReferenceCounting::Native && \
"only native references support scalar reference-counting"); \
emitNative##Name##Release(value, atomicity); \
} \
void IRGenFunction::emitStrongRetain##Name(llvm::Value *value, \
ReferenceCounting style, \
Atomicity atomicity) { \
assert(style == ReferenceCounting::Native && \
"only native references support scalar reference-counting"); \
emitNativeStrongRetain##Name(value, atomicity); \
} \
void IRGenFunction::emitStrongRetainAnd##Name##Release(llvm::Value *value, \
ReferenceCounting style, \
Atomicity atomicity) { \
assert(style == ReferenceCounting::Native && \
"only native references support scalar reference-counting"); \
emitNativeStrongRetainAnd##Name##Release(value, atomicity); \
} \
void IRGenFunction::emitNative##Name##Init(llvm::Value *value, \
Address dest) { \
value = Builder.CreateBitCast(value, IGM.RefCountedPtrTy); \
dest = Builder.CreateStructGEP(dest, 0, Size(0)); \
Builder.CreateStore(value, dest); \
emitNative##Name##Retain(value, getDefaultAtomicity()); \
} \
void IRGenFunction::emitNative##Name##Assign(llvm::Value *value, \
Address dest) { \
value = Builder.CreateBitCast(value, IGM.RefCountedPtrTy); \
dest = Builder.CreateStructGEP(dest, 0, Size(0)); \
auto oldValue = Builder.CreateLoad(dest); \
Builder.CreateStore(value, dest); \
emitNative##Name##Retain(value, getDefaultAtomicity()); \
emitNative##Name##Release(oldValue, getDefaultAtomicity()); \
} \
llvm::Value *IRGenFunction::emitNative##Name##LoadStrong(Address src, \
llvm::Type *type) { \
src = Builder.CreateStructGEP(src, 0, Size(0)); \
llvm::Value *value = Builder.CreateLoad(src); \
value = Builder.CreateBitCast(value, type); \
emitNativeStrongRetain##Name(value, getDefaultAtomicity()); \
return value; \
} \
llvm::Value *IRGenFunction::emitNative##Name##TakeStrong(Address src, \
llvm::Type *type) { \
src = Builder.CreateStructGEP(src, 0, Size(0)); \
llvm::Value *value = Builder.CreateLoad(src); \
value = Builder.CreateBitCast(value, type); \
emitNativeStrongRetainAnd##Name##Release(value, getDefaultAtomicity()); \
return value; \
} \
void IRGenFunction::emitNative##Name##Destroy(Address ref) { \
ref = Builder.CreateStructGEP(ref, 0, Size(0)); \
llvm::Value *value = Builder.CreateLoad(ref); \
emitNative##Name##Release(value, getDefaultAtomicity()); \
} \
void IRGenFunction::emitNative##Name##CopyInit(Address dest, Address src) { \
src = Builder.CreateStructGEP(src, 0, Size(0)); \
dest = Builder.CreateStructGEP(dest, 0, Size(0)); \
llvm::Value *newValue = Builder.CreateLoad(src); \
Builder.CreateStore(newValue, dest); \
emitNative##Name##Retain(newValue, getDefaultAtomicity()); \
} \
void IRGenFunction::emitNative##Name##TakeInit(Address dest, Address src) { \
src = Builder.CreateStructGEP(src, 0, Size(0)); \
dest = Builder.CreateStructGEP(dest, 0, Size(0)); \
llvm::Value *newValue = Builder.CreateLoad(src); \
Builder.CreateStore(newValue, dest); \
} \
void IRGenFunction::emitNative##Name##CopyAssign(Address dest, Address src) { \
src = Builder.CreateStructGEP(src, 0, Size(0)); \
dest = Builder.CreateStructGEP(dest, 0, Size(0)); \
llvm::Value *newValue = Builder.CreateLoad(src); \
llvm::Value *oldValue = Builder.CreateLoad(dest); \
Builder.CreateStore(newValue, dest); \
emitNative##Name##Retain(newValue, getDefaultAtomicity()); \
emitNative##Name##Release(oldValue, getDefaultAtomicity()); \
} \
void IRGenFunction::emitNative##Name##TakeAssign(Address dest, Address src) { \
src = Builder.CreateStructGEP(src, 0, Size(0)); \
dest = Builder.CreateStructGEP(dest, 0, Size(0)); \
llvm::Value *newValue = Builder.CreateLoad(src); \
llvm::Value *oldValue = Builder.CreateLoad(dest); \
Builder.CreateStore(newValue, dest); \
emitNative##Name##Release(oldValue, getDefaultAtomicity()); \
}
#include "swift/AST/ReferenceStorage.def"
/// Emit a release of a live value.
void IRGenFunction::emitNativeStrongRelease(llvm::Value *value,
Atomicity atomicity) {
if (doesNotRequireRefCounting(value))
return;
emitUnaryRefCountCall(*this, (atomicity == Atomicity::Atomic)
? IGM.getNativeStrongReleaseFn()
: IGM.getNativeNonAtomicStrongReleaseFn(),
value);
}
void IRGenFunction::emitNativeSetDeallocating(llvm::Value *value) {
if (doesNotRequireRefCounting(value)) return;
emitUnaryRefCountCall(*this, IGM.getNativeSetDeallocatingFn(), value);
}
llvm::Constant *IRGenModule::getFixLifetimeFn() {
if (FixLifetimeFn)
return FixLifetimeFn;
// Generate a private stub function for the LLVM ARC optimizer to recognize.
auto fixLifetimeTy = llvm::FunctionType::get(VoidTy, RefCountedPtrTy,
/*isVarArg*/ false);
auto fixLifetime = llvm::Function::Create(fixLifetimeTy,
llvm::GlobalValue::PrivateLinkage,
"__swift_fixLifetime",
&Module);
assert(fixLifetime->getName().equals("__swift_fixLifetime")
&& "fixLifetime symbol name got mangled?!");
// Don't inline the function, so it stays as a signal to the ARC passes.
// The ARC passes will remove references to the function when they're
// no longer needed.
fixLifetime->addFnAttr(llvm::Attribute::NoInline);
// Give the function an empty body.
auto entry = llvm::BasicBlock::Create(getLLVMContext(), "", fixLifetime);
llvm::ReturnInst::Create(getLLVMContext(), entry);
FixLifetimeFn = fixLifetime;
return fixLifetime;
}
FunctionPointer IRGenModule::getFixedClassInitializationFn() {
if (FixedClassInitializationFn)
return *FixedClassInitializationFn;
// If ObjC interop is disabled, we don't need to do fixed class
// initialization.
FunctionPointer fn;
if (ObjCInterop) {
// In new enough ObjC runtimes, objc_opt_self provides a direct fast path
// to realize a class.
if (getAvailabilityContext()
.isContainedIn(Context.getSwift51Availability())) {
fn = getObjCOptSelfFunctionPointer();
}
// Otherwise, the Swift runtime always provides a `get
else {
fn = getGetInitializedObjCClassFunctionPointer();
}
}
FixedClassInitializationFn = fn;
return fn;
}
/// Fix the lifetime of a live value. This communicates to the LLVM level ARC
/// optimizer not to touch this value.
void IRGenFunction::emitFixLifetime(llvm::Value *value) {
// If we aren't running the LLVM ARC optimizer, we don't need to emit this.
if (!IGM.IRGen.Opts.shouldOptimize() ||
IGM.IRGen.Opts.DisableSwiftSpecificLLVMOptzns)
return;
if (doesNotRequireRefCounting(value)) return;
emitUnaryRefCountCall(*this, IGM.getFixLifetimeFn(), value);
}
void IRGenFunction::emitUnknownStrongRetain(llvm::Value *value,
Atomicity atomicity) {
if (doesNotRequireRefCounting(value))
return;
emitUnaryRefCountCall(*this,
(atomicity == Atomicity::Atomic)
? IGM.getUnknownObjectRetainFn()
: IGM.getNonAtomicUnknownObjectRetainFn(),
value);
}
void IRGenFunction::emitUnknownStrongRelease(llvm::Value *value,
Atomicity atomicity) {
if (doesNotRequireRefCounting(value))
return;
emitUnaryRefCountCall(*this,
(atomicity == Atomicity::Atomic)
? IGM.getUnknownObjectReleaseFn()
: IGM.getNonAtomicUnknownObjectReleaseFn(),
value);
}
void IRGenFunction::emitBridgeStrongRetain(llvm::Value *value,
Atomicity atomicity) {
emitUnaryRefCountCall(*this,
(atomicity == Atomicity::Atomic)
? IGM.getBridgeObjectStrongRetainFn()
: IGM.getNonAtomicBridgeObjectStrongRetainFn(),
value);
}
void IRGenFunction::emitBridgeStrongRelease(llvm::Value *value,
Atomicity atomicity) {
emitUnaryRefCountCall(*this,
(atomicity == Atomicity::Atomic)
? IGM.getBridgeObjectStrongReleaseFn()
: IGM.getNonAtomicBridgeObjectStrongReleaseFn(),
value);
}
void IRGenFunction::emitErrorStrongRetain(llvm::Value *value) {
emitUnaryRefCountCall(*this, IGM.getErrorStrongRetainFn(), value);
}
void IRGenFunction::emitErrorStrongRelease(llvm::Value *value) {
emitUnaryRefCountCall(*this, IGM.getErrorStrongReleaseFn(), value);
}
llvm::Value *IRGenFunction::emitLoadRefcountedPtr(Address addr,
ReferenceCounting style) {
Address src = Builder.CreateElementBitCast(addr, IGM.getReferenceType(style));
return Builder.CreateLoad(src);
}
llvm::Value *IRGenFunction::
emitIsUniqueCall(llvm::Value *value, ReferenceCounting style, SourceLoc loc, bool isNonNull) {
FunctionPointer fn;
bool nonObjC = !IGM.getAvailabilityContext().isContainedIn(
IGM.Context.getObjCIsUniquelyReferencedAvailability());
switch (style) {
case ReferenceCounting::Native: {
if (isNonNull)
fn = IGM.getIsUniquelyReferenced_nonNull_nativeFunctionPointer();
else
fn = IGM.getIsUniquelyReferenced_nativeFunctionPointer();
}
break;
case ReferenceCounting::Bridge: {
if (!isNonNull)
unimplemented(loc, "optional bridge ref");
if (nonObjC)
fn =
IGM.getIsUniquelyReferencedNonObjC_nonNull_bridgeObjectFunctionPointer();
else
fn = IGM.getIsUniquelyReferenced_nonNull_bridgeObjectFunctionPointer();
}
break;
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown: {
if (nonObjC) {
if (isNonNull)
fn = IGM.getIsUniquelyReferencedNonObjC_nonNullFunctionPointer();
else
fn = IGM.getIsUniquelyReferencedNonObjCFunctionPointer();
} else {
if (isNonNull)
fn = IGM.getIsUniquelyReferenced_nonNullFunctionPointer();
else
fn = IGM.getIsUniquelyReferencedFunctionPointer();
}
}
break;
case ReferenceCounting::Error:
case ReferenceCounting::Block:
case ReferenceCounting::Custom:
case ReferenceCounting::None:
llvm_unreachable("Unexpected LLVM type for a refcounted pointer.");
}
llvm::CallInst *call = Builder.CreateCall(fn, value);
call->setDoesNotThrow();
return call;
}
llvm::Value *IRGenFunction::emitIsEscapingClosureCall(
llvm::Value *value, SourceLoc sourceLoc, unsigned verificationType) {
auto loc = SILLocation::decode(sourceLoc, IGM.Context.SourceMgr);
auto line = llvm::ConstantInt::get(IGM.Int32Ty, loc.line);
auto col = llvm::ConstantInt::get(IGM.Int32Ty, loc.column);
// Only output the filepath in debug mode. It is going to leak into the
// executable. This is the same behavior as asserts.
auto filename = IGM.IRGen.Opts.shouldOptimize()
? IGM.getAddrOfGlobalString("")
: IGM.getAddrOfGlobalString(loc.filename);
auto filenameLength =
llvm::ConstantInt::get(IGM.Int32Ty, loc.filename.size());
auto type = llvm::ConstantInt::get(IGM.Int32Ty, verificationType);
llvm::CallInst *call = Builder.CreateCall(
IGM.getIsEscapingClosureAtFileLocationFunctionPointer(),
{value, filename, filenameLength, line, col, type});
call->setDoesNotThrow();
return call;
}
namespace {
/// Basic layout and common operations for box types.
class BoxTypeInfo : public HeapTypeInfo<BoxTypeInfo> {
public:
BoxTypeInfo(IRGenModule &IGM)
: HeapTypeInfo(ReferenceCounting::Native, IGM.RefCountedPtrTy,
IGM.getPointerSize(), IGM.getHeapObjectSpareBits(),
IGM.getPointerAlignment())
{}
ReferenceCounting getReferenceCounting() const {
// Boxes are always native-refcounted.
return ReferenceCounting::Native;
}
/// Allocate a box of the given type.
virtual OwnedAddress
allocate(IRGenFunction &IGF, SILType boxedType, GenericEnvironment *env,
const llvm::Twine &name) const = 0;
/// Deallocate an uninitialized box.
virtual void
deallocate(IRGenFunction &IGF, llvm::Value *box, SILType boxedType) const = 0;
/// Project the address of the contained value from a box.
virtual Address
project(IRGenFunction &IGF, llvm::Value *box, SILType boxedType) const = 0;
};
/// Common implementation for empty box type info.
class EmptyBoxTypeInfo final : public BoxTypeInfo {
public:
EmptyBoxTypeInfo(IRGenModule &IGM) : BoxTypeInfo(IGM) {}
OwnedAddress
allocate(IRGenFunction &IGF, SILType boxedType, GenericEnvironment *env,
const llvm::Twine &name) const override {
return OwnedAddress(IGF.getTypeInfo(boxedType).getUndefAddress(),
IGF.emitAllocEmptyBoxCall());
}
void
deallocate(IRGenFunction &IGF, llvm::Value *box, SILType boxedType)
const override {
/* Nothing to do; the box should be nil. */
}
Address
project(IRGenFunction &IGF, llvm::Value *box, SILType boxedType)
const override {
return IGF.getTypeInfo(boxedType).getUndefAddress();
}
};
/// Common implementation for non-fixed box type info.
class NonFixedBoxTypeInfo final : public BoxTypeInfo {
public:
NonFixedBoxTypeInfo(IRGenModule &IGM) : BoxTypeInfo(IGM) {}
OwnedAddress
allocate(IRGenFunction &IGF, SILType boxedType, GenericEnvironment *env,
const llvm::Twine &name) const override {
auto &ti = IGF.getTypeInfo(boxedType);
// Use the runtime to allocate a box of the appropriate size.
auto metadata = IGF.emitTypeMetadataRefForLayout(boxedType);
llvm::Value *box, *address;
IGF.emitAllocBoxCall(metadata, box, address);
address = IGF.Builder.CreateBitCast(address,
ti.getStorageType()->getPointerTo());
return {ti.getAddressForPointer(address), box};
}
void
deallocate(IRGenFunction &IGF, llvm::Value *box, SILType boxedType)
const override {
auto metadata = IGF.emitTypeMetadataRefForLayout(boxedType);
IGF.emitDeallocBoxCall(box, metadata);
}
Address
project(IRGenFunction &IGF, llvm::Value *box, SILType boxedType)
const override {
auto &ti = IGF.getTypeInfo(boxedType);
auto metadata = IGF.emitTypeMetadataRefForLayout(boxedType);
llvm::Value *address = IGF.emitProjectBoxCall(box, metadata);
address = IGF.Builder.CreateBitCast(address,
ti.getStorageType()->getPointerTo());
return ti.getAddressForPointer(address);
}
};
/// Base implementation for fixed-sized boxes.
class FixedBoxTypeInfoBase : public BoxTypeInfo {
HeapLayout layout;
public:
FixedBoxTypeInfoBase(IRGenModule &IGM, HeapLayout &&layout)
: BoxTypeInfo(IGM), layout(std::move(layout))
{
// Empty layouts should always use EmptyBoxTypeInfo instead
assert(!layout.isKnownEmpty());
}
OwnedAddress
allocate(IRGenFunction &IGF, SILType boxedType, GenericEnvironment *env,
const llvm::Twine &name)
const override {
// Allocate a new object using the layout.
auto boxedInterfaceType = boxedType;
if (env) {
boxedInterfaceType = boxedType.mapTypeOutOfContext();
}
{
// FIXME: This seems wrong. We used to just mangle opened archetypes as
// their interface type. Let's make that explicit now.
auto astType = boxedInterfaceType.getASTType();
astType =
astType
.transformRec([](Type t) -> std::optional<Type> {
if (auto *openedExistential = t->getAs<OpenedArchetypeType>())
return openedExistential->getInterfaceType();
return std::nullopt;
})
->getCanonicalType();
boxedInterfaceType = SILType::getPrimitiveType(
astType, boxedInterfaceType.getCategory());
}
auto boxDescriptor = IGF.IGM.getAddrOfBoxDescriptor(
boxedInterfaceType,
env ? env->getGenericSignature().getCanonicalSignature()
: CanGenericSignature());
llvm::Value *allocation = IGF.emitUnmanagedAlloc(layout, name,
boxDescriptor);
Address rawAddr = project(IGF, allocation, boxedType);
return {rawAddr, allocation};
}
void
deallocate(IRGenFunction &IGF, llvm::Value *box, SILType _)
const override {
auto size = layout.emitSize(IGF.IGM);
auto alignMask = layout.emitAlignMask(IGF.IGM);
emitDeallocateUninitializedHeapObject(IGF, box, size, alignMask);
}
Address
project(IRGenFunction &IGF, llvm::Value *box, SILType boxedType)
const override {
Address rawAddr = layout.emitCastTo(IGF, box);
rawAddr = layout.getElement(0).project(IGF, rawAddr, std::nullopt);
auto &ti = IGF.getTypeInfo(boxedType);
return IGF.Builder.CreateElementBitCast(rawAddr, ti.getStorageType());
}
};
static HeapLayout getHeapLayoutForSingleTypeInfo(IRGenModule &IGM,
const TypeInfo &ti) {
return HeapLayout(IGM, LayoutStrategy::Optimal, SILType(), &ti);
}
/// Common implementation for POD boxes of a known stride and alignment.
class PODBoxTypeInfo final : public FixedBoxTypeInfoBase {
public:
PODBoxTypeInfo(IRGenModule &IGM, Size stride, Alignment alignment)
: FixedBoxTypeInfoBase(IGM, getHeapLayoutForSingleTypeInfo(IGM,
IGM.getOpaqueStorageTypeInfo(stride, alignment))) {
}
};
/// Common implementation for single-refcounted boxes.
class SingleRefcountedBoxTypeInfo final : public FixedBoxTypeInfoBase {
public:
SingleRefcountedBoxTypeInfo(IRGenModule &IGM, ReferenceCounting refcounting)
: FixedBoxTypeInfoBase(IGM, getHeapLayoutForSingleTypeInfo(IGM,
IGM.getReferenceObjectTypeInfo(refcounting)))
{
}
};
/// Implementation of a box for a specific type.
class FixedBoxTypeInfo final : public FixedBoxTypeInfoBase {
public:
FixedBoxTypeInfo(IRGenModule &IGM, SILType T)
: FixedBoxTypeInfoBase(IGM,
HeapLayout(IGM, LayoutStrategy::Optimal, T, &IGM.getTypeInfo(T)))
{}
};
} // end anonymous namespace
const TypeInfo *TypeConverter::convertBoxType(SILBoxType *T) {
// We can share a type info for all dynamic-sized heap metadata.
// TODO: Multi-field boxes
assert(T->getLayout()->getFields().size() == 1
&& "multi-field boxes not implemented yet");
auto &eltTI = IGM.getTypeInfoForLowered(getSILBoxFieldLoweredType(
IGM.getMaximalTypeExpansionContext(), T, IGM.getSILModule().Types, 0));
if (!eltTI.isFixedSize()) {
if (!NonFixedBoxTI)
NonFixedBoxTI = new NonFixedBoxTypeInfo(IGM);
return NonFixedBoxTI;
}
// For fixed-sized types, we can emit concrete box metadata.
auto &fixedTI = cast<FixedTypeInfo>(eltTI);
// Because we assume in enum's that payloads with a Builtin.NativeReference
// which is also the type for indirect enum cases have extra inhabitants of
// pointers we can't have a nil pointer as a representation for an empty box
// type -- nil conflicts with the extra inhabitants. We return a static
// singleton empty box object instead.
if (fixedTI.isKnownEmpty(ResilienceExpansion::Maximal)) {
if (!EmptyBoxTI)
EmptyBoxTI = new EmptyBoxTypeInfo(IGM);
return EmptyBoxTI;
}
// We can share box info for all similarly-shaped POD types.
if (fixedTI.isTriviallyDestroyable(ResilienceExpansion::Maximal)
&& fixedTI.isCopyable(ResilienceExpansion::Maximal)) {
auto stride = fixedTI.getFixedStride();
auto align = fixedTI.getFixedAlignment();
auto foundPOD = PODBoxTI.find({stride.getValue(),align.getValue()});
if (foundPOD == PODBoxTI.end()) {
auto newPOD = new PODBoxTypeInfo(IGM, stride, align);
PODBoxTI.insert({{stride.getValue(), align.getValue()}, newPOD});
return newPOD;
}
return foundPOD->second;
}
// We can share box info for all single-refcounted types.
if (fixedTI.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) {
if (!SwiftRetainablePointerBoxTI)
SwiftRetainablePointerBoxTI
= new SingleRefcountedBoxTypeInfo(IGM, ReferenceCounting::Native);
return SwiftRetainablePointerBoxTI;
}
// TODO: Other common shapes? Optional-of-Refcounted would be nice.
// Produce a tailored box metadata for the type.
assert(T->getLayout()->getFields().size() == 1
&& "multi-field boxes not implemented yet");
return new FixedBoxTypeInfo(
IGM, getSILBoxFieldType(IGM.getMaximalTypeExpansionContext(),
T, IGM.getSILModule().Types, 0));
}
OwnedAddress
irgen::emitAllocateBox(IRGenFunction &IGF, CanSILBoxType boxType,
GenericEnvironment *env,
const llvm::Twine &name) {
auto &boxTI = IGF.getTypeInfoForLowered(boxType).as<BoxTypeInfo>();
assert(boxType->getLayout()->getFields().size() == 1
&& "multi-field boxes not implemented yet");
return boxTI.allocate(
IGF,
getSILBoxFieldType(
IGF.IGM.getMaximalTypeExpansionContext(),
boxType, IGF.IGM.getSILModule().Types, 0),
env, name);
}
void irgen::emitDeallocateBox(IRGenFunction &IGF,
llvm::Value *box,
CanSILBoxType boxType) {
auto &boxTI = IGF.getTypeInfoForLowered(boxType).as<BoxTypeInfo>();
assert(boxType->getLayout()->getFields().size() == 1
&& "multi-field boxes not implemented yet");
return boxTI.deallocate(
IGF, box,
getSILBoxFieldType(IGF.IGM.getMaximalTypeExpansionContext(), boxType,
IGF.IGM.getSILModule().Types, 0));
}
Address irgen::emitProjectBox(IRGenFunction &IGF,
llvm::Value *box,
CanSILBoxType boxType) {
auto &boxTI = IGF.getTypeInfoForLowered(boxType).as<BoxTypeInfo>();
assert(boxType->getLayout()->getFields().size() == 1
&& "multi-field boxes not implemented yet");
return boxTI.project(
IGF, box,
getSILBoxFieldType(IGF.IGM.getMaximalTypeExpansionContext(), boxType,
IGF.IGM.getSILModule().Types, 0));
}
Address irgen::emitAllocateExistentialBoxInBuffer(
IRGenFunction &IGF, SILType boxedType, Address destBuffer,
GenericEnvironment *env, const llvm::Twine &name, bool isOutlined) {
// Get a box for the boxed value.
auto boxType = SILBoxType::get(boxedType.getASTType());
auto &boxTI = IGF.getTypeInfoForLowered(boxType).as<BoxTypeInfo>();
OwnedAddress owned = boxTI.allocate(IGF, boxedType, env, name);
Explosion box;
box.add(owned.getOwner());
boxTI.initialize(IGF, box,
Address(IGF.Builder.CreateBitCast(
destBuffer.getAddress(),
owned.getOwner()->getType()->getPointerTo()),
owned.getOwner()->getType(),
destBuffer.getAlignment()),
isOutlined);
return owned.getAddress();
}
#define DEFINE_VALUE_OP(ID) \
void IRGenFunction::emit##ID(llvm::Value *value, Atomicity atomicity) { \
if (doesNotRequireRefCounting(value)) return; \
emitUnaryRefCountCall(*this, (atomicity == Atomicity::Atomic) \
? IGM.get##ID##Fn() : IGM.getNonAtomic##ID##Fn(), \
value); \
}
#define DEFINE_ADDR_OP(ID) \
void IRGenFunction::emit##ID(Address addr) { \
emitUnaryRefCountCall(*this, IGM.get##ID##Fn(), addr.getAddress()); \
}
#define DEFINE_COPY_OP(ID) \
void IRGenFunction::emit##ID(Address dest, Address src) { \
emitCopyLikeCall(*this, IGM.get##ID##Fn(), dest.getAddress(), \
src.getAddress()); \
}
#define DEFINE_LOAD_WEAK_OP(ID) \
llvm::Value *IRGenFunction::emit##ID(Address src, llvm::Type *type) { \
return emitLoadWeakLikeCall(*this, IGM.get##ID##Fn(), \
src.getAddress(), type); \
}
#define DEFINE_STORE_WEAK_OP(ID) \
void IRGenFunction::emit##ID(llvm::Value *value, Address src) { \
emitStoreWeakLikeCall(*this, IGM.get##ID##Fn(), \
src.getAddress(), value); \
}
#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Nativeness) \
DEFINE_LOAD_WEAK_OP(Nativeness##Name##LoadStrong) \
DEFINE_LOAD_WEAK_OP(Nativeness##Name##TakeStrong) \
DEFINE_STORE_WEAK_OP(Nativeness##Name##Init) \
DEFINE_STORE_WEAK_OP(Nativeness##Name##Assign) \
DEFINE_ADDR_OP(Nativeness##Name##Destroy) \
DEFINE_COPY_OP(Nativeness##Name##CopyInit) \
DEFINE_COPY_OP(Nativeness##Name##CopyAssign) \
DEFINE_COPY_OP(Nativeness##Name##TakeInit) \
DEFINE_COPY_OP(Nativeness##Name##TakeAssign)
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Unknown) \
NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Native)
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
DEFINE_VALUE_OP(NativeStrongRetain##Name) \
DEFINE_VALUE_OP(NativeStrongRetainAnd##Name##Release) \
DEFINE_VALUE_OP(Native##Name##Release) \
DEFINE_VALUE_OP(Native##Name##Retain)
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Unknown) \
ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, "...")
#include "swift/AST/ReferenceStorage.def"
#undef DEFINE_VALUE_OP
#undef DEFINE_ADDR_OP
#undef DEFINE_COPY_OP
#undef DEFINE_LOAD_WEAK_OP
#undef DEFINE_STORE_WEAK_OP
#undef NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE_HELPER
llvm::Value *IRGenFunction::getDynamicSelfMetadata() {
assert(SelfValue && "no local self metadata");
// If we already have a metatype, just return it.
if (SelfKind == SwiftMetatype)
return SelfValue;
// We need to materialize a metatype. Emit the code for that once at the
// top of the function and cache the result.
// This is a slight optimization in the case of repeated access, but also
// needed for correctness; when an @objc convenience initializer replaces
// the 'self' value, we don't keep track of what the new 'self' value is
// in IRGen, so we can't just grab the first function argument and assume
// it's a valid 'self' at the point where DynamicSelfType metadata is needed.
// Note that if DynamicSelfType was modeled properly as an opened archetype,
// none of this would be an issue since it would be always be associated
// with the correct value.
llvm::IRBuilderBase::InsertPointGuard guard(Builder);
auto insertPt = isa<llvm::Instruction>(SelfValue)
? std::next(llvm::BasicBlock::iterator(
cast<llvm::Instruction>(SelfValue)))
: CurFn->getEntryBlock().begin();
Builder.SetInsertPoint(&CurFn->getEntryBlock(), insertPt);
// Do not inherit the debug location of this insertion point, it could be
// anything (e.g. the location of a dbg.declare).
Builder.SetCurrentDebugLocation(llvm::DebugLoc());
switch (SelfKind) {
case SwiftMetatype:
llvm_unreachable("Already handled");
case ObjCMetatype:
SelfValue = emitObjCMetadataRefForMetadata(*this, SelfValue);
SelfKind = SwiftMetatype;
break;
case ObjectReference:
SelfValue = emitDynamicTypeOfHeapObject(*this, SelfValue,
MetatypeRepresentation::Thick,
SILType::getPrimitiveObjectType(SelfType),
GenericSignature(),
/*allow artificial*/ false);
SelfKind = SwiftMetatype;
break;
}
return SelfValue;
}
/// Given a non-tagged object pointer, load a pointer to its class object.
llvm::Value *irgen::emitLoadOfObjCHeapMetadataRef(IRGenFunction &IGF,
llvm::Value *object) {
if (IGF.IGM.TargetInfo.hasISAMasking()) {
object = IGF.Builder.CreateBitCast(object,
IGF.IGM.IntPtrTy->getPointerTo());
llvm::Value *metadata = IGF.Builder.CreateLoad(
Address(object, IGF.IGM.IntPtrTy, IGF.IGM.getPointerAlignment()));
llvm::Value *mask = IGF.Builder.CreateLoad(IGF.IGM.getAddrOfObjCISAMask());
metadata = IGF.Builder.CreateAnd(metadata, mask);
metadata = IGF.Builder.CreateIntToPtr(metadata, IGF.IGM.TypeMetadataPtrTy);
return metadata;
} else if (IGF.IGM.TargetInfo.hasOpaqueISAs()) {
return emitHeapMetadataRefForUnknownHeapObject(IGF, object);
} else {
object = IGF.Builder.CreateBitCast(object,
IGF.IGM.TypeMetadataPtrTy->getPointerTo());
llvm::Value *metadata = IGF.Builder.CreateLoad(Address(
object, IGF.IGM.TypeMetadataPtrTy, IGF.IGM.getPointerAlignment()));
return metadata;
}
}
/// Given a pointer to a heap object (i.e. definitely not a tagged
/// pointer), load its heap metadata pointer.
static llvm::Value *emitLoadOfHeapMetadataRef(IRGenFunction &IGF,
llvm::Value *object,
IsaEncoding isaEncoding,
bool suppressCast) {
switch (isaEncoding) {
case IsaEncoding::Pointer: {
llvm::Value *slot =
IGF.Builder.CreateBitCast(object, IGF.IGM.TypeMetadataPtrPtrTy);
auto metadata = IGF.Builder.CreateLoad(Address(
slot, IGF.IGM.TypeMetadataPtrTy, IGF.IGM.getPointerAlignment()));
if (IGF.IGM.EnableValueNames && object->hasName())
metadata->setName(llvm::Twine(object->getName()) + ".metadata");
return metadata;
}
case IsaEncoding::ObjC: {
// Feed the object pointer to object_getClass.
llvm::Value *objcClass = emitLoadOfObjCHeapMetadataRef(IGF, object);
objcClass = IGF.Builder.CreateBitCast(objcClass, IGF.IGM.TypeMetadataPtrTy);
return objcClass;
}
}
llvm_unreachable("Not a valid IsaEncoding.");
}
/// Given an object of class type, produce the heap metadata reference
/// as an %objc_class*.
llvm::Value *irgen::emitHeapMetadataRefForHeapObject(IRGenFunction &IGF,
llvm::Value *object,
CanType objectType,
GenericSignature sig,
bool suppressCast) {
ClassDecl *theClass = objectType.getClassOrBoundGenericClass();
if ((theClass && isKnownNotTaggedPointer(IGF.IGM, theClass)) ||
!IGF.IGM.ObjCInterop) {
auto isaEncoding = getIsaEncodingForType(IGF.IGM, objectType, sig);
return emitLoadOfHeapMetadataRef(IGF, object, isaEncoding, suppressCast);
}
// OK, ask the runtime for the class pointer of this potentially-ObjC object.
return emitHeapMetadataRefForUnknownHeapObject(IGF, object);
}
llvm::Value *irgen::emitHeapMetadataRefForHeapObject(IRGenFunction &IGF,
llvm::Value *object,
SILType objectType,
GenericSignature sig,
bool suppressCast) {
return emitHeapMetadataRefForHeapObject(IGF, object,
objectType.getASTType(),
sig,
suppressCast);
}
/// Given an opaque class instance pointer, produce the type metadata reference
/// as a %type*.
///
/// You should only use this if you have an untyped object pointer with absolutely no type information.
/// Generally, it's better to use \c emitDynamicTypeOfHeapObject, which will
/// use the most efficient possible access pattern to get the dynamic type based on
/// the static type information.
static llvm::Value *emitDynamicTypeOfOpaqueHeapObject(IRGenFunction &IGF,
llvm::Value *object,
MetatypeRepresentation repr) {
if (!IGF.IGM.ObjCInterop) {
// Without objc interop, getting the dynamic type of an object is always
// just a load of the isa pointer.
assert(repr == MetatypeRepresentation::Thick
&& "objc metatypes should not occur without objc interop, "
"and thin metadata should not be requested here");
return emitLoadOfHeapMetadataRef(IGF, object, IsaEncoding::Pointer,
/*suppressCast*/ false);
}
object = IGF.Builder.CreateBitCast(object, IGF.IGM.ObjCPtrTy);
llvm::CallInst *metadata;
switch (repr) {
case MetatypeRepresentation::ObjC:
metadata = IGF.Builder.CreateCall(
IGF.IGM.getGetObjCClassFromObjectFunctionPointer(), object);
metadata->setName(object->getName() + ".Type");
break;
case MetatypeRepresentation::Thick:
metadata = IGF.Builder.CreateCall(IGF.IGM.getGetObjectTypeFunctionPointer(),
object);
metadata->setName(object->getName() + ".Type");
break;
case MetatypeRepresentation::Thin:
llvm_unreachable("class metadata can't be thin");
}
metadata->setDoesNotThrow();
metadata->setOnlyReadsMemory();
return metadata;
}
llvm::Value *irgen::
emitHeapMetadataRefForUnknownHeapObject(IRGenFunction &IGF,
llvm::Value *object) {
object = IGF.Builder.CreateBitCast(object, IGF.IGM.ObjCPtrTy);
auto metadata = IGF.Builder.CreateCall(
IGF.IGM.getGetObjectClassFunctionPointer(), object);
metadata->setName(object->getName() + ".Type");
metadata->setCallingConv(IGF.IGM.getOptions().PlatformCCallingConvention);
metadata->setDoesNotThrow();
metadata->setOnlyReadsMemory();
return metadata;
}
/// Given an object of class type, produce the type metadata reference
/// as a %type*.
llvm::Value *irgen::emitDynamicTypeOfHeapObject(IRGenFunction &IGF,
llvm::Value *object,
MetatypeRepresentation repr,
SILType objectType,
GenericSignature sig,
bool allowArtificialSubclasses){
switch (auto isaEncoding =
getIsaEncodingForType(IGF.IGM, objectType.getASTType(), sig)) {
case IsaEncoding::Pointer:
// Directly load the isa pointer from a pure Swift class.
return emitLoadOfHeapMetadataRef(IGF, object, isaEncoding,
/*suppressCast*/ false);
case IsaEncoding::ObjC:
// A class defined in Swift that inherits from an Objective-C class may
// end up dynamically subclassed by ObjC runtime hackery. The artificial
// subclass isn't a formal Swift type, so isn't appropriate as the result
// of `type(of:)`, but is still a physical subtype of the real class object,
// so can be used for some purposes like satisfying type parameters in
// generic signatures.
if (allowArtificialSubclasses
&& hasKnownSwiftMetadata(IGF.IGM, objectType.getASTType()))
return emitLoadOfHeapMetadataRef(IGF, object, isaEncoding,
/*suppressCast*/ false);
// Ask the Swift runtime to find the dynamic type. This will look through
// dynamic subclasses of Swift classes, and use the -class message for
// ObjC classes.
return emitDynamicTypeOfOpaqueHeapObject(IGF, object, repr);
}
llvm_unreachable("unhandled ISA encoding");
}
/// What isa encoding mechanism does a type have?
IsaEncoding irgen::getIsaEncodingForType(IRGenModule &IGM,
CanType type,
GenericSignature outerSignature) {
if (!IGM.ObjCInterop) return IsaEncoding::Pointer;
// This needs to be kept up-to-date with hasKnownSwiftMetadata.
if (auto theClass = type->getClassOrBoundGenericClass()) {
// We can access the isas of pure Swift classes directly.
if (!theClass->checkAncestry(AncestryFlags::ClangImported))
return IsaEncoding::Pointer;
// For ObjC or mixed classes, we need to use object_getClass.
return IsaEncoding::ObjC;
}
// Existentials use the encoding of the enclosed dynamic type.
if (type->isAnyExistentialType()) {
return getIsaEncodingForType(
IGM, OpenedArchetypeType::getAny(type, outerSignature),
outerSignature);
}
if (auto archetype = dyn_cast<ArchetypeType>(type)) {
// If we have a concrete superclass constraint, just recurse.
if (auto superclass = archetype->getSuperclass()) {
return getIsaEncodingForType(IGM, superclass->getCanonicalType(),
outerSignature);
}
// Otherwise, we must just have a class constraint. Use the
// conservative answer.
return IsaEncoding::ObjC;
}
// Non-class heap objects should be pure Swift, so we can access their isas
// directly.
return IsaEncoding::Pointer;
}
|