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
|
//===--- SILGenConstructor.cpp - SILGen for constructors ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "ArgumentSource.h"
#include "Conversion.h"
#include "ExecutorBreadcrumb.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "SILGenFunction.h"
#include "SILGenFunctionBuilder.h"
#include "Scope.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Generators.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include <map>
using namespace swift;
using namespace Lowering;
namespace {
class LoweredParamsInContextGenerator {
SILGenFunction &SGF;
ArrayRefGenerator<ArrayRef<SILParameterInfo>> loweredParams;
public:
LoweredParamsInContextGenerator(SILGenFunction &SGF)
: SGF(SGF),
loweredParams(SGF.F.getLoweredFunctionType()->getParameters()) {
}
using reference = SILType;
/// Get the original (unsubstituted into context) lowered parameter
/// type information.
SILParameterInfo getOrigInfo() const {
return loweredParams.get();
}
SILType get() const {
return SGF.getSILTypeInContext(loweredParams.get(),
SGF.F.getLoweredFunctionType());
}
SILType claimNext() {
auto param = get();
advance();
return param;
}
bool isFinished() const {
return loweredParams.isFinished();
}
void advance() {
loweredParams.advance();
}
void finish() {
loweredParams.finish();
}
};
} // end anonymous namespace
static ManagedValue emitManagedParameter(SILGenFunction &SGF,
SILValue value, bool isOwned) {
if (isOwned) {
return SGF.emitManagedRValueWithCleanup(value);
} else {
return ManagedValue::forBorrowedRValue(value);
}
}
static SILValue emitConstructorMetatypeArg(SILGenFunction &SGF,
ValueDecl *decl) {
// In addition to the declared arguments, the constructor implicitly takes
// the metatype as its first argument, like a static function.
auto metatypeTy = MetatypeType::get(
decl->getDeclContext()->getSelfInterfaceType());
auto *DC = decl->getInnermostDeclContext();
auto &ctx = SGF.getASTContext();
auto VD =
new (ctx) ParamDecl(SourceLoc(), SourceLoc(),
ctx.getIdentifier("$metatype"), SourceLoc(),
ctx.getIdentifier("$metatype"), DC);
VD->setSpecifier(ParamSpecifier::Default);
VD->setInterfaceType(metatypeTy);
return SGF.F.begin()->createFunctionArgument(
SGF.getLoweredTypeForFunctionArgument(DC->mapTypeIntoContext(metatypeTy)),
VD);
}
// FIXME: Consolidate this with SILGenProlog
static RValue emitImplicitValueConstructorArg(SILGenFunction &SGF,
SILLocation loc,
CanType interfaceType,
DeclContext *DC,
LoweredParamsInContextGenerator &loweredParamTypes,
Initialization *argInit = nullptr) {
auto type = DC->mapTypeIntoContext(interfaceType)->getCanonicalType();
// Restructure tuple arguments.
if (auto tupleIfaceTy = dyn_cast<TupleType>(interfaceType)) {
// If we don't have a context to emit into, but we have a tuple
// that contains pack expansions, create a temporary.
TemporaryInitializationPtr tempInit;
if (!argInit && tupleIfaceTy.containsPackExpansionType()) {
tempInit = SGF.emitTemporary(loc, SGF.getTypeLowering(type));
argInit = tempInit.get();
}
// Split the initialization into element initializations if we have
// one. We should never have to deal with an initialization that
// can't be split here.
assert(!argInit || argInit->canSplitIntoTupleElements());
SmallVector<InitializationPtr> initsBuf;
MutableArrayRef<InitializationPtr> eltInits;
if (argInit) {
eltInits = argInit->splitIntoTupleElements(SGF, loc, type, initsBuf);
assert(eltInits.size() == tupleIfaceTy->getNumElements());
}
RValue tuple(type);
for (auto eltIndex : range(tupleIfaceTy->getNumElements())) {
auto eltIfaceType = tupleIfaceTy.getElementType(eltIndex);
auto eltInit = (argInit ? eltInits[eltIndex].get() : nullptr);
RValue element = emitImplicitValueConstructorArg(SGF, loc, eltIfaceType,
DC, loweredParamTypes,
eltInit);
if (argInit) {
assert(element.isInContext());
} else {
tuple.addElement(std::move(element));
}
}
// If we created a temporary initializer above, finish it and claim
// the managed buffer.
if (tempInit) {
tempInit->finishInitialization(SGF);
auto tupleValue = tempInit->getManagedAddress();
if (tupleValue.getType().isLoadable(SGF.F)) {
tupleValue = SGF.B.createLoadTake(loc, tupleValue);
}
return RValue(SGF, loc, type, tupleValue);
// Otherwise, if we have an emitInto, return forInContext().
} else if (argInit) {
argInit->finishInitialization(SGF);
return RValue::forInContext();
}
return tuple;
}
auto &AC = SGF.getASTContext();
auto VD = new (AC) ParamDecl(SourceLoc(), SourceLoc(),
AC.getIdentifier("$implicit_value"),
SourceLoc(),
AC.getIdentifier("$implicit_value"),
DC);
VD->setSpecifier(ParamSpecifier::Default);
VD->setInterfaceType(interfaceType);
auto origParamInfo = loweredParamTypes.getOrigInfo();
auto argType = loweredParamTypes.claimNext();
auto *arg = SGF.F.begin()->createFunctionArgument(argType, VD);
bool argIsConsumed = origParamInfo.isConsumed();
// If the lowered parameter is a pack expansion, copy/move the pack
// into the initialization, which we assume is there.
if (auto packTy = argType.getAs<SILPackType>()) {
assert(isa<PackExpansionType>(interfaceType));
assert(packTy->getNumElements() == 1);
assert(argInit);
assert(argInit->canPerformPackExpansionInitialization());
auto expansionTy = packTy->getSILElementType(0);
auto openedEnvAndEltTy =
SGF.createOpenedElementValueEnvironment(expansionTy);
auto openedEnv = openedEnvAndEltTy.first;
auto eltTy = openedEnvAndEltTy.second;
auto formalPackType = CanPackType::get(SGF.getASTContext(), {type});
SGF.emitDynamicPackLoop(loc, formalPackType, /*component*/0, openedEnv,
[&](SILValue indexWithinComponent,
SILValue packExpansionIndex,
SILValue packIndex) {
argInit->performPackExpansionInitialization(SGF, loc,
indexWithinComponent,
[&](Initialization *eltInit) {
auto eltAddr =
SGF.B.createPackElementGet(loc, packIndex, arg, eltTy);
ManagedValue eltMV = emitManagedParameter(SGF, eltAddr, argIsConsumed);
eltMV = SGF.B.createLoadIfLoadable(loc, eltMV);
eltInit->copyOrInitValueInto(SGF, loc, eltMV, argIsConsumed);
eltInit->finishInitialization(SGF);
});
});
argInit->finishInitialization(SGF);
return RValue::forInContext();
}
ManagedValue mvArg = emitManagedParameter(SGF, arg, argIsConsumed);
// This can happen if the value is resilient in the calling convention
// but not resilient locally.
if (argType.isAddress()) {
mvArg = SGF.B.createLoadIfLoadable(loc, mvArg);
}
if (argInit) {
argInit->copyOrInitValueInto(SGF, loc, mvArg, argIsConsumed);
argInit->finishInitialization(SGF);
return RValue::forInContext();
}
return RValue(SGF, loc, type, mvArg);
}
/// If the field has a property wrapper for which we will need to call the
/// wrapper type's init(wrappedValue:, ...), call the function that performs
/// that initialization and return the result. Otherwise, return \c arg.
static RValue maybeEmitPropertyWrapperInitFromValue(
SILGenFunction &SGF,
SILLocation loc,
VarDecl *field,
SubstitutionMap subs,
RValue &&arg) {
auto originalProperty = field->getOriginalWrappedProperty();
if (!originalProperty ||
!originalProperty->isPropertyMemberwiseInitializedWithWrappedType())
return std::move(arg);
auto initInfo = originalProperty->getPropertyWrapperInitializerInfo();
if (!initInfo.hasInitFromWrappedValue())
return std::move(arg);
return SGF.emitApplyOfPropertyWrapperBackingInitializer(loc, originalProperty,
subs, std::move(arg));
}
static void
emitApplyOfInitAccessor(SILGenFunction &SGF, SILLocation loc,
AccessorDecl *accessor, SILValue selfValue,
Type selfIfaceTy, SILType selfTy,
RValue &&initialValue) {
SmallVector<SILValue> arguments;
auto emitFieldReference = [&](VarDecl *field, bool forInit = false) {
auto fieldTy =
selfTy.getFieldType(field, SGF.SGM.M, SGF.getTypeExpansionContext());
return SGF.B.createStructElementAddr(loc, selfValue, field,
fieldTy.getAddressType());
};
// First, let's emit all of the indirect results.
for (auto *property : accessor->getInitializedProperties()) {
arguments.push_back(emitFieldReference(property, /*forInit=*/true));
}
// `initialValue`
std::move(initialValue).forwardAll(SGF, arguments);
// And finally, all of the properties in `accesses` list which are
// `inout` arguments.
for (auto *property : accessor->getAccessedProperties()) {
arguments.push_back(emitFieldReference(property));
}
// The `self` metatype.
auto metatypeTy = MetatypeType::get(accessor->mapTypeIntoContext(selfIfaceTy));
arguments.push_back(SGF.B.createMetatype(loc, SGF.getLoweredType(metatypeTy)));
SubstitutionMap subs;
if (auto *env =
accessor->getDeclContext()->getGenericEnvironmentOfContext()) {
subs = env->getForwardingSubstitutionMap();
}
SILValue accessorRef =
SGF.emitGlobalFunctionRef(loc, SGF.getAccessorDeclRef(accessor));
(void)SGF.B.createApply(loc, accessorRef, subs, arguments, ApplyOptions());
}
static SubstitutionMap getSubstitutionsForPropertyInitializer(
DeclContext *dc,
NominalTypeDecl *nominal) {
// We want a substitution list written in terms of the generic
// signature of the type, with replacement archetypes from the
// constructor's context (which might be in an extension of
// the type, which adds additional generic requirements).
if (auto *genericEnv = dc->getGenericEnvironmentOfContext()) {
// Generate a set of substitutions for the initialization function,
// whose generic signature is that of the type context, and whose
// replacement types are the archetypes of the initializer itself.
return SubstitutionMap::get(
nominal->getGenericSignatureOfContext(),
QuerySubstitutionMap{genericEnv->getForwardingSubstitutionMap()},
LookUpConformanceInModule(dc->getParentModule()));
}
return SubstitutionMap();
}
static void emitImplicitValueConstructor(SILGenFunction &SGF,
ConstructorDecl *ctor) {
RegularLocation Loc(ctor);
Loc.markAutoGenerated();
if (ctor->requiresUnavailableDeclABICompatibilityStubs())
SGF.emitApplyOfUnavailableCodeReached();
AssertingManualScope functionLevelScope(SGF.Cleanups,
CleanupLocation(Loc));
auto loweredFunctionTy = SGF.F.getLoweredFunctionType();
// FIXME: Handle 'self' along with the other arguments.
assert(loweredFunctionTy->getNumResults() == 1);
auto selfResultInfo = loweredFunctionTy->getResults()[0];
auto *paramList = ctor->getParameters();
auto *selfDecl = ctor->getImplicitSelfDecl();
auto selfIfaceTy = selfDecl->getInterfaceType();
SILType selfTy = SGF.getSILTypeInContext(selfResultInfo, loweredFunctionTy);
auto *decl = selfTy.getStructOrBoundGenericStruct();
assert(decl && "not a struct?!");
std::multimap<VarDecl *, VarDecl *> initializedViaAccessor;
decl->collectPropertiesInitializableByInitAccessors(initializedViaAccessor);
// Emit the indirect return argument, if any.
bool hasInitAccessors = !decl->getInitAccessorProperties().empty();
SILValue resultSlot;
if (selfTy.isAddress()) {
auto &AC = SGF.getASTContext();
auto VD = new (AC) ParamDecl(SourceLoc(), SourceLoc(),
AC.getIdentifier("$return_value"),
SourceLoc(),
AC.getIdentifier("$return_value"),
ctor);
VD->setSpecifier(ParamSpecifier::InOut);
VD->setInterfaceType(selfIfaceTy);
resultSlot = SGF.F.begin()->createFunctionArgument(selfTy, VD);
} else if (hasInitAccessors) {
// Allocate "self" on stack which we are going to use to
// reference/init fields and then load to return.
resultSlot = SGF.emitTemporaryAllocation(Loc, selfTy);
}
LoweredParamsInContextGenerator loweredParams(SGF);
// Emit the elementwise arguments.
SmallVector<RValue, 4> elements;
for (size_t i = 0, size = paramList->size(); i < size; ++i) {
auto ¶m = paramList->get(i);
elements.push_back(
emitImplicitValueConstructorArg(
SGF, Loc, param->getInterfaceType()->getCanonicalType(), ctor,
loweredParams));
}
SGF.AllocatorMetatype = emitConstructorMetatypeArg(SGF, ctor);
(void) loweredParams.claimNext();
loweredParams.finish();
auto subs = getSubstitutionsForPropertyInitializer(decl, decl);
// If we have an indirect return slot, initialize it in-place.
if (resultSlot) {
auto elti = elements.begin(), eltEnd = elements.end();
llvm::SmallPtrSet<VarDecl *, 4> storedProperties;
{
auto properties = decl->getStoredProperties();
storedProperties.insert(properties.begin(), properties.end());
}
for (auto *member : decl->getAllMembers()) {
auto *field = dyn_cast<VarDecl>(member);
if (!field)
continue;
if (initializedViaAccessor.count(field))
continue;
// Handle situations where this stored propery is initialized
// via a call to an init accessor on some other property.
if (auto *initAccessor = field->getAccessor(AccessorKind::Init)) {
if (field->isMemberwiseInitialized(/*preferDeclaredProperties=*/true)) {
assert(elti != eltEnd &&
"number of args does not match number of fields");
emitApplyOfInitAccessor(SGF, Loc, initAccessor, resultSlot,
selfIfaceTy, selfTy, std::move(*elti));
++elti;
continue;
}
}
// If this is not one of the stored properties, let's move on.
if (!storedProperties.count(field))
continue;
auto fieldTy =
selfTy.getFieldType(field, SGF.SGM.M, SGF.getTypeExpansionContext());
SILValue slot =
SGF.B.createStructElementAddr(Loc, resultSlot, field,
fieldTy.getAddressType());
if (SGF.getOptions().EnableImportPtrauthFieldFunctionPointers &&
field->getPointerAuthQualifier().isPresent()) {
slot = SGF.B.createBeginAccess(
Loc, slot, SILAccessKind::Init, SILAccessEnforcement::Signed,
/* noNestedConflict */ false, /* fromBuiltin */ false);
}
InitializationPtr init(new KnownAddressInitialization(slot));
// If it's memberwise initialized, do so now.
if (field->isMemberwiseInitialized(/*preferDeclaredProperties=*/false)) {
assert(elti != eltEnd &&
"number of args does not match number of fields");
(void)eltEnd;
FullExpr scope(SGF.Cleanups, field->getParentPatternBinding());
RValue arg = std::move(*elti);
// If the stored property has an attached result builder and its
// type is not a function type, the argument is a noescape closure
// that needs to be called.
if (field->getResultBuilderType()) {
if (!field->getValueInterfaceType()
->lookThroughAllOptionalTypes()->is<AnyFunctionType>()) {
auto resultTy = cast<FunctionType>(arg.getType()).getResult();
arg = SGF.emitMonomorphicApply(
Loc, std::move(arg).getAsSingleValue(SGF, Loc), {}, resultTy,
resultTy, ApplyOptions(), std::nullopt, std::nullopt);
}
}
maybeEmitPropertyWrapperInitFromValue(SGF, Loc, field, subs,
std::move(arg))
.forwardInto(SGF, Loc, init.get());
++elti;
} else {
// TODO: This doesn't correctly take into account destructuring
// pattern bindings on `let`s, for example `let (a, b) = foo()`. In
// cases like that, we ought to evaluate the initializer expression once
// and then do a pattern assignment to the variables in the pattern.
// That case is currently forbidden with an "unsupported" error message
// in Sema.
assert(field->getTypeInContext()->getReferenceStorageReferent()->isEqual(
field->getParentExecutableInitializer()->getType()) &&
"Initialization of field with mismatched type!");
// Cleanup after this initialization.
FullExpr scope(SGF.Cleanups, field->getParentPatternBinding());
// If this is a property wrapper backing storage var that isn't
// memberwise initialized and has an original wrapped value, apply
// the property wrapper backing initializer.
if (auto *wrappedVar = field->getOriginalWrappedProperty()) {
auto initInfo = wrappedVar->getPropertyWrapperInitializerInfo();
auto *placeholder = initInfo.getWrappedValuePlaceholder();
if (placeholder && placeholder->getOriginalWrappedValue()) {
auto arg = SGF.emitRValue(placeholder->getOriginalWrappedValue());
maybeEmitPropertyWrapperInitFromValue(SGF, Loc, field, subs,
std::move(arg))
.forwardInto(SGF, Loc, init.get());
continue;
}
}
SGF.emitExprInto(field->getParentExecutableInitializer(), init.get());
}
if (SGF.getOptions().EnableImportPtrauthFieldFunctionPointers &&
field->getPointerAuthQualifier().isPresent()) {
SGF.B.createEndAccess(Loc, slot, /* aborted */ false);
}
}
// Load as "take" from our stack allocation and return.
if (!selfTy.isAddress() && hasInitAccessors) {
auto resultValue = SGF.B.emitLoadValueOperation(
Loc, resultSlot, LoadOwnershipQualifier::Take);
SGF.B.createReturn(ImplicitReturnLocation(Loc), resultValue,
std::move(functionLevelScope));
return;
}
SGF.B.createReturn(ImplicitReturnLocation(Loc),
SGF.emitEmptyTuple(Loc), std::move(functionLevelScope));
return;
}
// Otherwise, build a struct value directly from the elements.
SmallVector<SILValue, 4> eltValues;
auto elti = elements.begin(), eltEnd = elements.end();
for (VarDecl *field : decl->getStoredProperties()) {
auto fieldTy =
selfTy.getFieldType(field, SGF.SGM.M, SGF.getTypeExpansionContext());
RValue value;
FullExpr scope(SGF.Cleanups, field->getParentPatternBinding());
// If it's memberwise initialized, do so now.
if (field->isMemberwiseInitialized(/*preferDeclaredProperties=*/false)) {
assert(elti != eltEnd && "number of args does not match number of fields");
(void)eltEnd;
value = std::move(*elti);
++elti;
} else {
// Otherwise, use its initializer.
// TODO: This doesn't correctly take into account destructuring
// pattern bindings on `let`s, for example `let (a, b) = foo()`. In
// cases like that, we ought to evaluate the initializer expression once
// and then do a pattern assignment to the variables in the pattern.
// That case is currently forbidden with an "unsupported" error message
// in Sema.
assert(field->isParentExecutabledInitialized());
Expr *init = field->getParentExecutableInitializer();
// If this is a property wrapper backing storage var that isn't
// memberwise initialized, use the original wrapped value if it exists.
if (auto *wrappedVar = field->getOriginalWrappedProperty()) {
auto initInfo = wrappedVar->getPropertyWrapperInitializerInfo();
auto *placeholder = initInfo.getWrappedValuePlaceholder();
if (placeholder && placeholder->getOriginalWrappedValue()) {
init = placeholder->getOriginalWrappedValue();
}
}
value = SGF.emitRValue(init);
}
// Cleanup after this initialization.
SILValue v = maybeEmitPropertyWrapperInitFromValue(SGF, Loc, field, subs,
std::move(value))
.forwardAsSingleStorageValue(SGF, fieldTy, Loc);
eltValues.push_back(v);
}
SILValue selfValue = SGF.B.createStruct(Loc, selfTy, eltValues);
SGF.B.createReturn(ImplicitReturnLocation(Loc),
selfValue, std::move(functionLevelScope));
return;
}
// FIXME: the callers of ctorHopsInjectedByDefiniteInit is not correct (rdar://87485045)
// we must still set the SGF.ExpectedExecutor field to say that we must
// hop to the executor after every apply in the constructor. This seems to
// happen for the main actor isolated async inits, but not for the plain ones,
// where 'self' is not going to directly be the instance. We have to extend the
// ExecutorBreadcrumb class to detect whether it needs to do a load or not
// in it's emit method.
//
// So, the big problem right now is that for a delegating async actor init,
// after calling an async function, no hop-back is being emitted.
/// Returns true if the given async constructor will have its
/// required actor hops injected later by definite initialization.
static bool ctorHopsInjectedByDefiniteInit(ConstructorDecl *ctor,
ActorIsolation const& isolation) {
// must be async, but we can assume that.
assert(ctor->hasAsync());
auto *dc = ctor->getDeclContext();
auto selfClassDecl = dc->getSelfClassDecl();
// must be an actor
if (!selfClassDecl || !selfClassDecl->isAnyActor())
return false;
// must be instance isolated
switch (isolation) {
case ActorIsolation::ActorInstance:
return true;
case ActorIsolation::Erased:
llvm_unreachable("constructor cannot have erased isolation");
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
case ActorIsolation::GlobalActor:
return false;
}
}
void SILGenFunction::emitValueConstructor(ConstructorDecl *ctor) {
MagicFunctionName = SILGenModule::getMagicFunctionName(ctor);
if (ctor->isMemberwiseInitializer())
return emitImplicitValueConstructor(*this, ctor);
// True if this constructor delegates to a peer constructor with self.init().
bool isDelegating = ctor->getDelegatingOrChainedInitKind().initKind ==
BodyInitKind::Delegating;
if (ctor->requiresUnavailableDeclABICompatibilityStubs())
emitApplyOfUnavailableCodeReached();
// Get the 'self' decl and type.
VarDecl *selfDecl = ctor->getImplicitSelfDecl();
auto &lowering = getTypeLowering(selfDecl->getTypeInContext());
// Decide if we need to do extra work to warn on unsafe behavior in pre-Swift-5
// modes.
MarkUninitializedInst::Kind MUIKind;
if (isDelegating) {
MUIKind = MarkUninitializedInst::DelegatingSelf;
} else if (getASTContext().isSwiftVersionAtLeast(5)) {
MUIKind = MarkUninitializedInst::RootSelf;
} else {
auto *dc = ctor->getParent();
if (isa<ExtensionDecl>(dc) &&
dc->getSelfStructDecl()->getParentModule() != dc->getParentModule()) {
MUIKind = MarkUninitializedInst::CrossModuleRootSelf;
} else {
MUIKind = MarkUninitializedInst::RootSelf;
}
}
// Allocate the local variable for 'self'.
emitLocalVariableWithCleanup(selfDecl, MUIKind)->finishInitialization(*this);
ManagedValue selfLV =
maybeEmitValueOfLocalVarDecl(selfDecl, AccessKind::ReadWrite);
assert(selfLV);
// Emit the prolog.
emitBasicProlog(ctor,
ctor->getParameters(),
/*selfParam=*/nullptr,
ctor->getResultInterfaceType(),
ctor->getEffectiveThrownErrorType(),
ctor->getThrowsLoc(),
/*ignored parameters*/ 1);
AllocatorMetatype = emitConstructorMetatypeArg(*this, ctor);
// Make sure we've hopped to the right global actor, if any.
if (ctor->hasAsync()) {
auto isolation = getActorIsolation(ctor);
// if it's not injected by definite init, we do it in the prologue now.
if (!ctorHopsInjectedByDefiniteInit(ctor, isolation)) {
SILLocation prologueLoc(selfDecl);
prologueLoc.markAsPrologue();
emitConstructorPrologActorHop(prologueLoc, isolation);
}
}
// Create a basic block to jump to for the implicit 'self' return.
// We won't emit this until after we've emitted the body.
// The epilog takes a void return because the return of 'self' is implicit.
prepareEpilog(ctor, std::nullopt, ctor->getEffectiveThrownErrorType(),
CleanupLocation(ctor));
// If the constructor can fail, set up an alternative epilog for constructor
// failure.
SILBasicBlock *failureExitBB = nullptr;
SILArgument *failureExitArg = nullptr;
auto resultType = ctor->mapTypeIntoContext(ctor->getResultInterfaceType());
auto &resultLowering = getTypeLowering(resultType);
if (ctor->isFailable()) {
SILBasicBlock *failureBB = createBasicBlock(FunctionSection::Postmatter);
// On failure, we'll clean up everything (except self, which should have
// been cleaned up before jumping here) and return nil instead.
SILGenSavedInsertionPoint savedIP(*this, failureBB,
FunctionSection::Postmatter);
failureExitBB = createBasicBlock();
Cleanups.emitCleanupsForReturn(ctor, IsForUnwind);
// Return nil.
if (F.getConventions().hasIndirectSILResults()) {
// Inject 'nil' into the indirect return.
assert(F.getIndirectResults().size() == 1);
B.createInjectEnumAddr(ctor, F.getIndirectResults()[0],
getASTContext().getOptionalNoneDecl());
B.createBranch(ctor, failureExitBB);
B.setInsertionPoint(failureExitBB);
B.createReturn(ctor, emitEmptyTuple(ctor));
} else {
// Pass 'nil' as the return value to the exit BB.
failureExitArg = failureExitBB->createPhiArgument(
resultLowering.getLoweredType(), OwnershipKind::Owned);
SILValue nilResult =
B.createEnum(ctor, SILValue(), getASTContext().getOptionalNoneDecl(),
resultLowering.getLoweredType());
B.createBranch(ctor, failureExitBB, nilResult);
B.setInsertionPoint(failureExitBB);
B.createReturn(ctor, failureExitArg);
}
FailDest = JumpDest(failureBB, Cleanups.getCleanupsDepth(), ctor);
}
// If this is not a delegating constructor, emit member initializers.
if (!isDelegating) {
auto *typeDC = ctor->getDeclContext();
auto *nominal = typeDC->getSelfNominalTypeDecl();
// If we have an empty move only struct, then we will not initialize it with
// any member initializers, breaking SIL. So in that case, just construct a
// SIL struct value and initialize the memory with that.
//
// DISCUSSION: This only happens with noncopyable types since the memory
// lifetime checker doesn't seem to process trivial locations. But empty
// move only structs are non-trivial, so we need to handle this here.
if (nominal->getAttrs().hasAttribute<RawLayoutAttr>()) {
auto *module = ctor->getParentModule();
// Raw memory is not directly decomposable, but we still want to mark
// it as initialized. Use a zero initializer.
auto &C = ctor->getASTContext();
auto zeroInit = getBuiltinValueDecl(C, C.getIdentifier("zeroInitializer"));
B.createBuiltin(ctor, zeroInit->getBaseIdentifier(),
SILType::getEmptyTupleType(C),
SubstitutionMap::get(zeroInit->getInnermostDeclContext()
->getGenericSignatureOfContext(),
{selfDecl->getTypeInContext()},
LookUpConformanceInModule(module)),
selfLV.getLValueAddress());
} else if (isa<StructDecl>(nominal)
&& lowering.getLoweredType().isMoveOnly()
&& nominal->getStoredProperties().empty()) {
auto *si = B.createStruct(ctor, lowering.getLoweredType(), {});
B.emitStoreValueOperation(ctor, si, selfLV.getLValueAddress(),
StoreOwnershipQualifier::Init);
} else {
emitMemberInitializers(ctor, selfDecl, nominal);
}
}
emitProfilerIncrement(ctor->getTypecheckedBody());
// Emit the constructor body.
emitStmt(ctor->getTypecheckedBody());
// Build a custom epilog block, since the AST representation of the
// constructor decl (which has no self in the return type) doesn't match the
// SIL representation.
SILValue selfValue;
{
SILGenSavedInsertionPoint savedIP(*this, ReturnDest.getBlock());
assert(B.getInsertionBB()->empty() && "Epilog already set up?");
auto cleanupLoc = CleanupLocation(ctor);
if (!F.getConventions().hasIndirectSILResults()) {
// Otherwise, load and return the final 'self' value.
if (selfLV.getType().isMoveOnly()) {
selfLV = B.createMarkUnresolvedNonCopyableValueInst(
cleanupLoc, selfLV,
MarkUnresolvedNonCopyableValueInst::CheckKind::
AssignableButNotConsumable);
}
selfValue = lowering.emitLoad(B, cleanupLoc, selfLV.getValue(),
LoadOwnershipQualifier::Copy);
// Inject the self value into an optional if the constructor is failable.
if (ctor->isFailable()) {
selfValue = B.createEnum(cleanupLoc, selfValue,
getASTContext().getOptionalSomeDecl(),
getLoweredLoadableType(resultType));
}
} else {
// If 'self' is address-only, copy 'self' into the indirect return slot.
assert(F.getConventions().getNumIndirectSILResults() == 1
&& "no indirect return for address-only ctor?!");
// Get the address to which to store the result.
SILValue completeReturnAddress = F.getIndirectResults()[0];
SILValue returnAddress;
if (!ctor->isFailable()) {
// For non-failable initializers, store to the return address directly.
returnAddress = completeReturnAddress;
} else {
// If this is a failable initializer, project out the payload.
returnAddress = B.createInitEnumDataAddr(
cleanupLoc, completeReturnAddress,
getASTContext().getOptionalSomeDecl(), selfLV.getType());
}
// We have to do a non-take copy because someone else may be using the
// box (e.g. someone could have closed over it).
B.createCopyAddr(cleanupLoc, selfLV.getLValueAddress(), returnAddress,
IsNotTake, IsInitialization);
// Inject the enum tag if the result is optional because of failability.
if (ctor->isFailable()) {
// Inject the 'Some' tag.
B.createInjectEnumAddr(cleanupLoc, completeReturnAddress,
getASTContext().getOptionalSomeDecl());
}
}
}
// Finally, emit the epilog and post-matter.
auto returnLoc = emitEpilog(ctor, /*UsesCustomEpilog*/true);
// Finish off the epilog by returning. If this is a failable ctor, then we
// actually jump to the failure epilog to keep the invariant that there is
// only one SIL return instruction per SIL function.
if (B.hasValidInsertionPoint()) {
if (!failureExitBB) {
// If we're not returning self, then return () since we're returning Void.
if (!selfValue) {
CleanupLocation loc(ctor);
loc.markAutoGenerated();
selfValue = emitEmptyTuple(loc);
}
B.createReturn(returnLoc, selfValue);
} else {
if (selfValue)
B.createBranch(returnLoc, failureExitBB, selfValue);
else
B.createBranch(returnLoc, failureExitBB);
}
}
}
void SILGenFunction::emitEnumConstructor(EnumElementDecl *element) {
Type enumIfaceTy = element->getParentEnum()->getDeclaredInterfaceType();
Type enumTy = F.mapTypeIntoContext(enumIfaceTy);
auto &enumTI =
SGM.Types.getTypeLowering(enumTy, TypeExpansionContext::minimal());
if (element->requiresUnavailableDeclABICompatibilityStubs())
emitApplyOfUnavailableCodeReached();
RegularLocation Loc(element);
CleanupLocation CleanupLoc(element);
Loc.markAutoGenerated();
// Emit the indirect return slot.
std::unique_ptr<Initialization> dest;
if (enumTI.isAddressOnly() && silConv.useLoweredAddresses()) {
auto &AC = getASTContext();
auto VD = new (AC) ParamDecl(SourceLoc(), SourceLoc(),
AC.getIdentifier("$return_value"),
SourceLoc(),
AC.getIdentifier("$return_value"),
element->getDeclContext());
VD->setSpecifier(ParamSpecifier::InOut);
VD->setInterfaceType(enumIfaceTy);
auto resultSlot =
F.begin()->createFunctionArgument(enumTI.getLoweredType(), VD);
dest = std::unique_ptr<Initialization>(
new KnownAddressInitialization(resultSlot));
}
Scope scope(Cleanups, CleanupLoc);
LoweredParamsInContextGenerator loweredParams(*this);
// Emit the exploded constructor argument.
SmallVector<ArgumentSource, 2> payloads;
if (element->hasAssociatedValues()) {
auto elementFnTy =
cast<AnyFunctionType>(
cast<AnyFunctionType>(element->getInterfaceType()->getCanonicalType())
.getResult());
auto elementParams = elementFnTy.getParams();
payloads.reserve(elementParams.size());
for (auto param: elementParams) {
auto paramType = param.getParameterType();
RValue arg = emitImplicitValueConstructorArg(*this, Loc, paramType,
element, loweredParams);
payloads.emplace_back(Loc, std::move(arg));
}
}
// Emit the metatype argument.
AllocatorMetatype = emitConstructorMetatypeArg(*this, element);
(void) loweredParams.claimNext();
loweredParams.finish();
// If possible, emit the enum directly into the indirect return.
SGFContext C = (dest ? SGFContext(dest.get()) : SGFContext());
ManagedValue mv = emitInjectEnum(Loc, payloads,
enumTI.getLoweredType(),
element, C);
// Return the enum.
auto ReturnLoc = ImplicitReturnLocation(Loc);
if (dest) {
if (!mv.isInContext()) {
dest->copyOrInitValueInto(*this, Loc, mv, /*isInit*/ true);
dest->finishInitialization(*this);
}
scope.pop();
B.createReturn(ReturnLoc, emitEmptyTuple(CleanupLocation(Loc)));
} else {
assert(enumTI.isLoadable() || !silConv.useLoweredAddresses());
SILValue result = mv.ensurePlusOne(*this, ReturnLoc).forward(*this);
scope.pop();
B.createReturn(ReturnLoc, result);
}
}
void SILGenFunction::emitClassConstructorAllocator(ConstructorDecl *ctor) {
assert(!ctor->isFactoryInit() && "factories should not be emitted here");
// Emit the prolog. Since we're just going to forward our args directly
// to the initializer, don't allocate local variables for them.
RegularLocation Loc(ctor);
Loc.markAutoGenerated();
// Forward the constructor arguments.
// FIXME: Handle 'self' along with the other body patterns.
SmallVector<SILValue, 8> args;
// If the function we're calling has an indirect error result, create an
// argument for it.
if (F.getConventions().hasIndirectSILErrorResults()) {
assert(F.getConventions().getNumIndirectSILErrorResults() == 1);
auto paramTy = F.mapTypeIntoContext(
F.getConventions().getSILErrorType(getTypeExpansionContext()));
auto inContextParamTy = F.getLoweredType(paramTy.getASTType())
.getCategoryType(paramTy.getCategory());
SILArgument *arg = F.begin()->createFunctionArgument(inContextParamTy);
IndirectErrorResult = arg;
args.push_back(arg);
}
bindParametersForForwarding(ctor->getParameters(), args);
if (ctor->requiresUnavailableDeclABICompatibilityStubs())
emitApplyOfUnavailableCodeReached();
AllocatorMetatype = emitConstructorMetatypeArg(*this, ctor);
SILValue selfMetaValue = AllocatorMetatype;
// Allocate the "self" value.
VarDecl *selfDecl = ctor->getImplicitSelfDecl();
SILType selfTy = getLoweredType(selfDecl->getTypeInContext());
assert(selfTy.hasReferenceSemantics() &&
"can't emit a value type ctor here");
// Use alloc_ref to allocate the object.
// TODO: allow custom allocation?
// FIXME: should have a cleanup in case of exception
auto selfClassDecl = ctor->getDeclContext()->getSelfClassDecl();
SILValue selfValue;
// Allocate the 'self' value.
bool useObjCAllocation = usesObjCAllocator(selfClassDecl);
if (ctor->hasClangNode() ||
ctor->shouldUseObjCDispatch() ||
ctor->isConvenienceInit()) {
assert(ctor->hasClangNode() || ctor->isObjC());
// For an allocator thunk synthesized for an @objc convenience initializer
// or imported Objective-C init method, allocate using the metatype.
SILValue allocArg = selfMetaValue;
// When using Objective-C allocation, convert the metatype
// argument to an Objective-C metatype.
if (useObjCAllocation) {
auto metaTy = allocArg->getType().castTo<MetatypeType>();
metaTy = CanMetatypeType::get(metaTy.getInstanceType(),
MetatypeRepresentation::ObjC);
allocArg = B.createThickToObjCMetatype(Loc, allocArg,
getLoweredType(metaTy));
}
selfValue = B.createAllocRefDynamic(Loc, allocArg, selfTy,
useObjCAllocation, false, {}, {});
} else {
assert(ctor->isDesignatedInit());
// For a designated initializer, we know that the static type being
// allocated is the type of the class that defines the designated
// initializer.
F.setIsExactSelfClass(IsExactSelfClass);
selfValue = B.createAllocRef(Loc, selfTy, useObjCAllocation, false, false,
ArrayRef<SILType>(), ArrayRef<SILValue>());
}
args.push_back(selfValue);
// Call the initializer. Always use the Swift entry point, which will be a
// bridging thunk if we're calling ObjC.
auto initConstant = SILDeclRef(ctor, SILDeclRef::Kind::Initializer);
ManagedValue initVal;
SILType initTy;
// Call the initializer.
auto subMap = F.getForwardingSubstitutionMap();
std::tie(initVal, initTy)
= emitSiblingMethodRef(Loc, selfValue, initConstant, subMap);
SILValue initedSelfValue = emitApplyWithRethrow(
CleanupLocation(Loc), initVal.forward(*this), initTy, subMap, args);
// Return the initialized 'self'.
B.createReturn(ImplicitReturnLocation(Loc), initedSelfValue);
}
static void emitDefaultActorInitialization(
SILGenFunction &SGF, SILLocation loc, ManagedValue self) {
auto &ctx = SGF.getASTContext();
auto builtinName = ctx.getIdentifier(
getBuiltinName(BuiltinValueKind::InitializeDefaultActor));
auto resultTy = SGF.SGM.Types.getEmptyTupleType();
FullExpr scope(SGF.Cleanups, CleanupLocation(loc));
SGF.B.createBuiltin(loc, builtinName, resultTy, /*subs*/{},
{ self.borrow(SGF, loc).getValue() });
}
static void emitNonDefaultDistributedActorInitialization(
SILGenFunction &SGF, SILLocation loc, ManagedValue self) {
auto &ctx = SGF.getASTContext();
auto builtinName = ctx.getIdentifier(
getBuiltinName(BuiltinValueKind::InitializeNonDefaultDistributedActor));
auto resultTy = SGF.SGM.Types.getEmptyTupleType();
FullExpr scope(SGF.Cleanups, CleanupLocation(loc));
SGF.B.createBuiltin(loc, builtinName, resultTy, /*subs*/{},
{ self.borrow(SGF, loc).getValue() });
}
// MARK: class constructor
void SILGenFunction::emitClassConstructorInitializer(ConstructorDecl *ctor) {
MagicFunctionName = SILGenModule::getMagicFunctionName(ctor);
assert(ctor->getTypecheckedBody() && "Class constructor without a body?");
if (ctor->requiresUnavailableDeclABICompatibilityStubs())
emitApplyOfUnavailableCodeReached();
// True if this constructor delegates to a peer constructor with self.init().
bool isDelegating = false;
if (!ctor->hasStubImplementation()) {
isDelegating = ctor->getDelegatingOrChainedInitKind().initKind ==
BodyInitKind::Delegating;
}
// Set up the 'self' argument. If this class has a superclass, we set up
// self as a box. This allows "self reassignment" to happen in super init
// method chains, which is important for interoperating with Objective-C
// classes. We also use a box for delegating constructors, since the
// delegated-to initializer may also replace self.
//
// TODO: If we could require Objective-C classes to have an attribute to get
// this behavior, we could avoid runtime overhead here.
VarDecl *selfDecl = ctor->getImplicitSelfDecl();
auto *dc = ctor->getDeclContext();
auto selfClassDecl = dc->getSelfClassDecl();
bool NeedsBoxForSelf = isDelegating ||
(selfClassDecl->hasSuperclass() && !ctor->hasStubImplementation());
bool usesObjCAllocator = Lowering::usesObjCAllocator(selfClassDecl);
// If needed, mark 'self' as uninitialized so that DI knows to
// enforce its DI properties on stored properties.
MarkUninitializedInst::Kind MUKind;
if (isDelegating) {
if (ctor->isObjC())
MUKind = MarkUninitializedInst::DelegatingSelfAllocated;
else
MUKind = MarkUninitializedInst::DelegatingSelf;
} else if (selfClassDecl->requiresStoredPropertyInits() &&
usesObjCAllocator) {
// Stored properties will be initialized in a separate
// .cxx_construct method called by the Objective-C runtime.
assert(selfClassDecl->hasSuperclass() &&
"Cannot use ObjC allocation without a superclass");
MUKind = MarkUninitializedInst::DerivedSelfOnly;
} else if (selfClassDecl->hasSuperclass())
MUKind = MarkUninitializedInst::DerivedSelf;
else
MUKind = MarkUninitializedInst::RootSelf;
if (NeedsBoxForSelf) {
// Allocate the local variable for 'self'.
emitLocalVariableWithCleanup(selfDecl, MUKind)->finishInitialization(*this);
}
// Emit the prolog for the non-self arguments.
// FIXME: Handle self along with the other body patterns.
uint16_t ArgNo = emitBasicProlog(ctor,
ctor->getParameters(), /*selfParam=*/nullptr,
TupleType::getEmpty(F.getASTContext()),
ctor->getEffectiveThrownErrorType(),
ctor->getThrowsLoc(),
/*ignored parameters*/ 1);
SILType selfTy = getLoweredLoadableType(selfDecl->getTypeInContext());
ManagedValue selfArg = B.createInputFunctionArgument(selfTy, selfDecl);
// is this a designated initializer for a distributed actor?
const bool isDesignatedDistActorInit =
selfClassDecl->isDistributedActor() && !isDelegating;
// Make sure we've hopped to the right global actor, if any.
if (ctor->hasAsync()) {
auto isolation = getActorIsolation(ctor);
// if it's not injected by definite init, we do it in the prologue now.
if (!ctorHopsInjectedByDefiniteInit(ctor, isolation)) {
SILLocation prologueLoc(selfDecl);
prologueLoc.markAsPrologue();
emitConstructorPrologActorHop(prologueLoc, isolation);
}
}
if (!NeedsBoxForSelf) {
SILLocation PrologueLoc(selfDecl);
PrologueLoc.markAsPrologue();
SILDebugVariable DbgVar(selfDecl->isLet(), ++ArgNo);
B.createDebugValue(PrologueLoc, selfArg.getValue(), DbgVar);
}
if (selfClassDecl->isRootDefaultActor() && !isDelegating) {
// Initialize the default-actor instance.
SILLocation PrologueLoc(selfDecl);
PrologueLoc.markAsPrologue();
emitDefaultActorInitialization(*this, PrologueLoc, selfArg);
} else if (selfClassDecl->isNonDefaultExplicitDistributedActor() && !isDelegating) {
// Initialize the distributed local actor with custom executor,
// with additional storage such that we can store the local/remote bit.
//
// We do this because normally non-default actors do not get any synthesized storage,
// as their executor is provided via user implementation. However, a distributed actor
// always needs additional storage for e.g. the isRemote/isLocal information.
SILLocation PrologueLoc(selfDecl);
PrologueLoc.markAsPrologue();
emitNonDefaultDistributedActorInitialization(*this, PrologueLoc, selfArg);
}
if (!ctor->hasStubImplementation()) {
assert(selfTy.hasReferenceSemantics() &&
"can't emit a value type ctor here");
if (NeedsBoxForSelf) {
SILLocation prologueLoc = RegularLocation(ctor);
prologueLoc.markAsPrologue();
B.emitStoreValueOperation(prologueLoc, selfArg.forward(*this),
VarLocs[selfDecl].value,
StoreOwnershipQualifier::Init);
} else {
selfArg = B.createMarkUninitialized(selfDecl, selfArg, MUKind);
if (selfArg.getType().isMoveOnly()) {
assert(selfArg.getOwnershipKind() == OwnershipKind::Owned);
selfArg = B.createMarkUnresolvedNonCopyableValueInst(
selfDecl, selfArg,
MarkUnresolvedNonCopyableValueInst::CheckKind::
ConsumableAndAssignable);
}
VarLocs[selfDecl] = VarLoc::get(selfArg.getValue());
}
}
// Some distributed actor initializers need to init the actorSystem & id now
if (isDesignatedDistActorInit) {
emitDistributedActorImplicitPropertyInits(ctor, selfArg);
}
// Prepare the end of initializer location.
SILLocation endOfInitLoc = RegularLocation(ctor);
endOfInitLoc.pointToEnd();
// Create a basic block to jump to for the implicit 'self' return.
// We won't emit the block until after we've emitted the body.
prepareEpilog(ctor, std::nullopt, ctor->getEffectiveThrownErrorType(),
CleanupLocation(endOfInitLoc));
auto resultType = ctor->mapTypeIntoContext(ctor->getResultInterfaceType());
// If the constructor can fail, set up an alternative epilog for constructor
// failure.
SILBasicBlock *failureExitBB = nullptr;
SILArgument *failureExitArg = nullptr;
auto &resultLowering = getTypeLowering(resultType);
if (ctor->isFailable()) {
SILBasicBlock *failureBB = createBasicBlock(FunctionSection::Postmatter);
RegularLocation loc(ctor);
loc.markAutoGenerated();
// On failure, we'll clean up everything and return nil instead.
SILGenSavedInsertionPoint savedIP(*this, failureBB,
FunctionSection::Postmatter);
failureExitBB = createBasicBlock();
failureExitArg = failureExitBB->createPhiArgument(
resultLowering.getLoweredType(), OwnershipKind::Owned);
Cleanups.emitCleanupsForReturn(ctor, IsForUnwind);
SILValue nilResult =
B.createEnum(loc, SILValue(), getASTContext().getOptionalNoneDecl(),
resultLowering.getLoweredType());
B.createBranch(loc, failureExitBB, nilResult);
B.setInsertionPoint(failureExitBB);
B.createReturn(loc, failureExitArg);
FailDest = JumpDest(failureBB, Cleanups.getCleanupsDepth(), ctor);
}
// Handle member initializers.
if (isDelegating) {
// A delegating initializer does not initialize instance
// variables.
} else if (ctor->hasStubImplementation()) {
// Nor does a stub implementation.
} else if (selfClassDecl->requiresStoredPropertyInits() &&
usesObjCAllocator) {
// When the class requires all stored properties to have initial
// values and we're using Objective-C's allocation, stored
// properties are initialized via the .cxx_construct method, which
// will be called by the runtime.
// Note that 'self' has been fully initialized at this point.
} else {
// Emit the member initializers.
emitMemberInitializers(ctor, selfDecl, selfClassDecl);
}
emitProfilerIncrement(ctor->getTypecheckedBody());
// Emit the constructor body.
emitStmt(ctor->getTypecheckedBody());
// Emit the call to super.init() right before exiting from the initializer.
if (NeedsBoxForSelf) {
if (auto *SI = ctor->getSuperInitCall()) {
B.setInsertionPoint(ReturnDest.getBlock());
emitRValue(SI);
B.emitBlock(B.splitBlockForFallthrough(), ctor);
ReturnDest = JumpDest(B.getInsertionBB(),
ReturnDest.getDepth(),
ReturnDest.getCleanupLocation());
B.clearInsertionPoint();
}
}
// For distributed actors, their synchronous initializers invoke "actor ready"
// at the very end, just before returning on a successful initialization.
if (isDesignatedDistActorInit && !ctor->hasAsync()) {
RegularLocation loc(ctor);
loc.markAutoGenerated();
SILGenSavedInsertionPoint savedIP(*this, ReturnDest.getBlock());
emitDistributedActorReady(loc, ctor, selfArg);
}
CleanupStateRestorationScope SelfCleanupSave(Cleanups);
// Build a custom epilog block, since the AST representation of the
// constructor decl (which has no self in the return type) doesn't match the
// SIL representation.
{
// Ensure that before we add additional cleanups, that we have emitted all
// cleanups at this point.
assert(!Cleanups.hasAnyActiveCleanups(getCleanupsDepth(),
ReturnDest.getDepth()) &&
"emitting epilog in wrong scope");
SILGenSavedInsertionPoint savedIP(*this, ReturnDest.getBlock());
auto cleanupLoc = CleanupLocation(ctor);
// If we're using a box for self, reload the value at the end of the init
// method.
if (NeedsBoxForSelf) {
ManagedValue storedSelf =
ManagedValue::forBorrowedAddressRValue(VarLocs[selfDecl].value);
selfArg = B.createLoadCopy(cleanupLoc, storedSelf);
} else {
// We have to do a retain because we are returning the pointer +1.
//
// SEMANTIC ARC TODO: When the verifier is complete, we will need to
// change this to selfArg = B.emitCopyValueOperation(...). Currently due
// to the way that SILGen performs folding of copy_value, destroy_value,
// the returned selfArg may be deleted causing us to have a
// dead-pointer. Instead just use the old self value since we have a
// class.
selfArg = B.createCopyValue(cleanupLoc, selfArg);
}
// Inject the self value into an optional if the constructor is failable.
if (ctor->isFailable())
selfArg = B.createEnum(cleanupLoc, selfArg,
getASTContext().getOptionalSomeDecl(),
getLoweredLoadableType(resultType));
// Save our cleanup state. We want all other potential cleanups to fire, but
// not this one.
if (selfArg.hasCleanup())
SelfCleanupSave.pushCleanupState(selfArg.getCleanup(),
CleanupState::Dormant);
// Translate our cleanup to the new top cleanup.
//
// This is needed to preserve the invariant in getEpilogBB that when
// cleanups are emitted, everything above ReturnDest.getDepth() has been
// emitted. This is not true if we use ManagedValue and friends in the
// epilogBB, thus the translation. We perform the same check above that
// getEpilogBB performs to ensure that we still do not have the same
// problem.
ReturnDest = std::move(ReturnDest).translate(getTopCleanup());
}
// Emit the epilog and post-matter.
auto returnLoc = emitEpilog(ctor, /*UsesCustomEpilog*/true);
// Unpop our selfArg cleanup, so we can forward.
std::move(SelfCleanupSave).pop();
// Finish off the epilog by returning. If this is a failable ctor, then we
// actually jump to the failure epilog to keep the invariant that there is
// only one SIL return instruction per SIL function.
if (B.hasValidInsertionPoint()) {
if (failureExitBB)
B.createBranch(returnLoc, failureExitBB, selfArg.forward(*this));
else
B.createReturn(returnLoc, selfArg.forward(*this));
}
}
static ManagedValue emitSelfForMemberInit(SILGenFunction &SGF, SILLocation loc,
VarDecl *selfDecl) {
CanType selfFormalType = selfDecl->getTypeInContext()->getCanonicalType();
if (selfFormalType->hasReferenceSemantics()) {
return SGF.emitRValueForDecl(loc, selfDecl, selfFormalType,
AccessSemantics::DirectToStorage,
SGFContext::AllowImmediatePlusZero)
.getAsSingleValue(SGF, loc);
} else {
return SGF.emitAddressOfLocalVarDecl(loc, selfDecl, selfFormalType,
SGFAccessKind::Write);
}
}
// FIXME: Can emitMemberInit() share code with InitializationForPattern in
// SILGenDecl.cpp? Note that this version operates on stored properties of
// types, whereas the former only knows how to handle local bindings, but
// we could generalize it.
static InitializationPtr
emitMemberInit(SILGenFunction &SGF, VarDecl *selfDecl, Pattern *pattern) {
switch (pattern->getKind()) {
case PatternKind::Paren:
return emitMemberInit(SGF, selfDecl,
cast<ParenPattern>(pattern)->getSubPattern());
case PatternKind::Tuple: {
TupleInitialization *init = new TupleInitialization(
cast<TupleType>(pattern->getType()->getCanonicalType()));
auto tuple = cast<TuplePattern>(pattern);
for (auto &elt : tuple->getElements()) {
init->SubInitializations.push_back(
emitMemberInit(SGF, selfDecl, elt.getPattern()));
}
return InitializationPtr(init);
}
case PatternKind::Named: {
auto named = cast<NamedPattern>(pattern);
auto self = emitSelfForMemberInit(SGF, pattern, selfDecl);
auto *field = named->getDecl();
auto selfTy = self.getType();
auto fieldTy =
selfTy.getFieldType(field, SGF.SGM.M, SGF.getTypeExpansionContext());
SILValue slot;
if (auto *structDecl = dyn_cast<StructDecl>(field->getDeclContext())) {
slot = SGF.B.createStructElementAddr(pattern, self.forward(SGF), field,
fieldTy.getAddressType());
} else {
assert(isa<ClassDecl>(field->getDeclContext()->
getImplementedObjCContext()));
slot = SGF.B.createRefElementAddr(pattern, self.forward(SGF), field,
fieldTy.getAddressType());
}
return InitializationPtr(new KnownAddressInitialization(slot));
}
case PatternKind::Any:
return InitializationPtr(new BlackHoleInitialization());;
case PatternKind::Typed:
return emitMemberInit(SGF, selfDecl,
cast<TypedPattern>(pattern)->getSubPattern());
case PatternKind::Binding:
return emitMemberInit(SGF, selfDecl,
cast<BindingPattern>(pattern)->getSubPattern());
#define PATTERN(Name, Parent)
#define REFUTABLE_PATTERN(Name, Parent) case PatternKind::Name:
#include "swift/AST/PatternNodes.def"
llvm_unreachable("Refutable pattern in stored property pattern binding");
}
llvm_unreachable("covered switch");
}
static std::pair<AbstractionPattern, CanType>
getInitializationTypeInContext(
DeclContext *fromDC, DeclContext *toDC,
Pattern *pattern) {
auto interfaceType = pattern->getType()->mapTypeOutOfContext();
// If this pattern is initializing the backing storage for a property
// with an attached wrapper that is initialized with `=`, the
// initialization type is the original property type.
if (auto singleVar = pattern->getSingleVar()) {
if (auto originalProperty = singleVar->getOriginalWrappedProperty()) {
if (originalProperty->isPropertyMemberwiseInitializedWithWrappedType())
interfaceType = originalProperty->getPropertyWrapperInitValueInterfaceType();
}
}
AbstractionPattern origType(
fromDC->getGenericSignatureOfContext().getCanonicalSignature(),
interfaceType->getCanonicalType());
auto substType = toDC->mapTypeIntoContext(interfaceType)->getCanonicalType();
return std::make_pair(origType, substType);
}
static void
emitAndStoreInitialValueInto(SILGenFunction &SGF,
SILLocation loc,
PatternBindingDecl *pbd, unsigned i,
SubstitutionMap subs,
AbstractionPattern origType,
CanType substType,
Initialization *init) {
bool injectIntoWrapper = false;
if (auto singleVar = pbd->getSingleVar()) {
auto originalVar = singleVar->getOriginalWrappedProperty();
if (originalVar &&
originalVar->isPropertyMemberwiseInitializedWithWrappedType()) {
injectIntoWrapper = true;
}
}
SGFContext C = (injectIntoWrapper ? SGFContext() : SGFContext(init));
RValue result = SGF.emitApplyOfStoredPropertyInitializer(
pbd->getExecutableInit(i),
pbd->getAnchoringVarDecl(i),
subs, substType, origType, C);
// need to store result into the init if its in context
// If we have the backing storage for a property with an attached
// property wrapper initialized with `=`, inject the value into an
// instance of the wrapper.
if (injectIntoWrapper) {
auto *singleVar = pbd->getSingleVar();
result = maybeEmitPropertyWrapperInitFromValue(
SGF, pbd->getExecutableInit(i),
singleVar, subs, std::move(result));
}
if (!result.isInContext())
std::move(result).forwardInto(SGF, loc, init);
}
void SILGenFunction::emitMemberInitializationViaInitAccessor(
DeclContext *dc, VarDecl *selfDecl, PatternBindingDecl *member,
SubstitutionMap subs) {
auto *var = member->getSingleVar();
assert(var->hasInitAccessor());
auto init = member->getExecutableInit(0);
if (!init)
return;
auto *varPattern = member->getPattern(0);
// Cleanup after this initialization.
FullExpr scope(Cleanups, varPattern);
auto resultType =
getInitializationTypeInContext(member->getDeclContext(), dc, varPattern);
RValue initResult = emitApplyOfStoredPropertyInitializer(
init, var, subs, resultType.second, resultType.first, SGFContext());
SILLocation loc(init);
loc.markAutoGenerated();
auto selfValue = emitSelfForMemberInit(*this, varPattern, selfDecl);
ManagedValue selfRef = selfValue;
if (selfValue.isLValue()) {
auto accessToSelf =
B.createBeginAccess(loc, selfValue.getValue(), SILAccessKind::Modify,
SILAccessEnforcement::Unknown,
/*noNestedConflict=*/false,
/*fromBuiltin=*/false);
selfRef = ManagedValue::forBorrowedAddressRValue(accessToSelf);
}
emitAssignOrInit(loc, selfRef, var,
std::move(initResult).getAsSingleValue(*this, loc), subs);
if (selfValue.isLValue())
B.createEndAccess(loc, selfRef.getValue(), /*aborted=*/false);
}
void SILGenFunction::emitMemberInitializer(DeclContext *dc, VarDecl *selfDecl,
PatternBindingDecl *field,
SubstitutionMap substitutions) {
assert(!field->isStatic());
for (auto i : range(field->getNumPatternEntries())) {
auto init = field->getExecutableInit(i);
if (!init)
continue;
// Member initializer expressions are only used in a constructor with
// matching actor isolation. If the isolation prohibits the member
// initializer from being evaluated synchronously (or propagating required
// isolation through closure bodies), then the default value cannot be used
// and the member must be explicitly initialized in the constructor.
auto *var = field->getAnchoringVarDecl(i);
auto requiredIsolation = var->getInitializerIsolation();
auto contextIsolation = getActorIsolationOfContext(dc);
switch (requiredIsolation) {
// 'nonisolated' expressions can be evaluated from anywhere
case ActorIsolation::Unspecified:
case ActorIsolation::Nonisolated:
case ActorIsolation::NonisolatedUnsafe:
break;
case ActorIsolation::Erased:
llvm_unreachable("context cannot have erased isolation");
case ActorIsolation::GlobalActor:
case ActorIsolation::ActorInstance: {
if (requiredIsolation != contextIsolation) {
// Implicit initializers diagnose actor isolation violations
// for property initializers in Sema. Still emit the invalid
// member initializer here to avoid duplicate diagnostics and
// to preserve warn-until-Swift-6 behavior.
auto *init =
dyn_cast_or_null<ConstructorDecl>(dc->getAsDecl());
if (init && init->isImplicit())
break;
continue;
}
}
}
auto *varPattern = field->getPattern(i);
// Cleanup after this initialization.
FullExpr scope(Cleanups, varPattern);
// Get the type of the initialization result, in terms
// of the constructor context's archetypes.
auto resultType =
getInitializationTypeInContext(field->getDeclContext(), dc, varPattern);
AbstractionPattern origType = resultType.first;
CanType substType = resultType.second;
// Figure out what we're initializing.
auto memberInit = emitMemberInit(*this, selfDecl, varPattern);
// This whole conversion thing is about eliminating the
// paired orig-to-subst subst-to-orig conversions that
// will happen if the storage is at a different abstraction
// level than the constructor. When emitApply() is used
// to call the stored property initializer, it naturally
// wants to convert the result back to the most substituted
// abstraction level. To undo this, we use a converting
// initialization and rely on the peephole that optimizes
// out the redundant conversion.
SILType loweredResultTy;
SILType loweredSubstTy;
// A converting initialization isn't necessary if the member is
// a property wrapper. Though the initial value can have a
// reabstractable type, the result of the initialization is
// always the property wrapper type, which is never reabstractable.
bool needsConvertingInit = false;
auto *singleVar = varPattern->getSingleVar();
if (!(singleVar && singleVar->getOriginalWrappedProperty())) {
loweredResultTy = getLoweredType(origType, substType);
loweredSubstTy = getLoweredType(substType);
needsConvertingInit = loweredResultTy != loweredSubstTy;
}
if (needsConvertingInit) {
Conversion conversion =
Conversion::getSubstToOrig(origType, substType,
loweredSubstTy, loweredResultTy);
ConvertingInitialization convertingInit(conversion,
SGFContext(memberInit.get()));
emitAndStoreInitialValueInto(*this, varPattern, field, i, substitutions,
origType, substType, &convertingInit);
auto finalValue = convertingInit.finishEmission(
*this, varPattern, ManagedValue::forInContext());
if (!finalValue.isInContext())
finalValue.forwardInto(*this, varPattern, memberInit.get());
} else {
emitAndStoreInitialValueInto(*this, varPattern, field, i, substitutions,
origType, substType, memberInit.get());
}
}
}
void SILGenFunction::emitMemberInitializers(DeclContext *dc,
VarDecl *selfDecl,
NominalTypeDecl *nominal) {
auto subs = getSubstitutionsForPropertyInitializer(dc, nominal);
llvm::SmallPtrSet<PatternBindingDecl *, 4> alreadyInitialized;
for (auto member : nominal->getImplementationContext()->getAllMembers()) {
// Find instance pattern binding declarations that have initializers.
if (auto pbd = dyn_cast<PatternBindingDecl>(member)) {
if (pbd->isStatic()) continue;
if (alreadyInitialized.count(pbd))
continue;
// Emit default initialization for an init accessor property.
if (auto *var = pbd->getSingleVar()) {
if (var->hasInitAccessor()) {
auto initAccessor = var->getAccessor(AccessorKind::Init);
// Make sure that initializations for the accessed properties
// are emitted before the init accessor that uses them.
for (auto *property : initAccessor->getAccessedProperties()) {
auto *PBD = property->getParentPatternBinding();
if (alreadyInitialized.insert(PBD).second)
emitMemberInitializer(dc, selfDecl, PBD, subs);
}
emitMemberInitializationViaInitAccessor(dc, selfDecl, pbd, subs);
continue;
}
}
emitMemberInitializer(dc, selfDecl, pbd, subs);
}
}
}
void SILGenFunction::emitIVarInitializer(SILDeclRef ivarInitializer) {
auto cd = cast<ClassDecl>(ivarInitializer.getDecl());
RegularLocation loc(cd);
loc.markAutoGenerated();
// Emit 'self', then mark it uninitialized.
auto selfDecl = cd->getDestructor()->getImplicitSelfDecl();
SILType selfTy = getLoweredLoadableType(selfDecl->getTypeInContext());
SILValue selfArg = F.begin()->createFunctionArgument(selfTy, selfDecl);
SILLocation PrologueLoc(selfDecl);
PrologueLoc.markAsPrologue();
// Hard-code self as argument number 1.
SILDebugVariable DbgVar(selfDecl->isLet(), 1);
B.createDebugValue(PrologueLoc, selfArg, DbgVar);
selfArg = B.createMarkUninitialized(selfDecl, selfArg,
MarkUninitializedInst::RootSelf);
assert(selfTy.hasReferenceSemantics() && "can't emit a value type ctor here");
VarLocs[selfDecl] = VarLoc::get(selfArg);
auto cleanupLoc = CleanupLocation(loc);
prepareEpilog(cd, std::nullopt, std::nullopt, cleanupLoc);
// Emit the initializers.
emitMemberInitializers(cd, selfDecl, cd);
// Return 'self'.
B.createReturn(loc, selfArg);
emitEpilog(loc);
}
void SILGenFunction::emitInitAccessor(AccessorDecl *accessor) {
RegularLocation loc(accessor);
loc.markAutoGenerated();
auto accessorTy = F.getLoweredFunctionType();
auto createArgument = [&](VarDecl *property, SILType type,
bool markUninitialized = false) {
auto *arg = ParamDecl::createImplicit(
getASTContext(), property->getBaseIdentifier(),
property->getBaseIdentifier(), property->getInterfaceType(), accessor,
ParamSpecifier::InOut);
RegularLocation loc(property);
loc.markAutoGenerated();
SILValue argValue = F.begin()->createFunctionArgument(type, arg);
VarLocs[arg] =
markUninitialized
? VarLoc::get(B.createMarkUninitializedOut(loc, argValue))
: VarLoc::get(argValue);
InitAccessorArgumentMappings[property] = arg;
};
// First, emit results, this is our "initializes" properties and
// require DI to check that each property is fully initialized.
auto initializedProperties = accessor->getInitializedProperties();
for (unsigned i = 0, n = initializedProperties.size(); i != n; ++i) {
auto *property = initializedProperties[i];
auto propertyTy =
getSILTypeInContext(accessorTy->getResults()[i], accessorTy);
createArgument(property, propertyTy, /*markUninitialized=*/true);
}
// Collect all of the parameters that represent properties listed by
// "accesses" attribute. They have to be emitted in order of arguments which
// means after the "newValue" which is emitted by \c emitBasicProlog.
auto accessedProperties = accessor->getAccessedProperties();
// Emit `newValue` argument.
emitBasicProlog(accessor, accessor->getParameters(),
/*selfParam=*/nullptr, TupleType::getEmpty(F.getASTContext()),
/*errorType=*/std::nullopt,
/*throwsLoc=*/SourceLoc(),
/*ignored parameters*/
accessedProperties.size() + 1);
// Emit arguments for all `accesses` properties.
if (!accessedProperties.empty()) {
auto propertyIter = accessedProperties.begin();
auto propertyArgs = accessorTy->getParameters().slice(
accessorTy->getNumParameters() - accessedProperties.size() - 1,
accessedProperties.size());
for (const auto &argument : propertyArgs) {
createArgument(*propertyIter, getSILTypeInContext(argument, accessorTy));
++propertyIter;
}
}
// Emit `self` argument.
emitConstructorMetatypeArg(*this, accessor);
prepareEpilog(accessor,
accessor->getResultInterfaceType(),
accessor->getEffectiveThrownErrorType(),
CleanupLocation(accessor));
emitProfilerIncrement(accessor->getTypecheckedBody());
// Emit the actual function body as usual
emitStmt(accessor->getTypecheckedBody());
emitEpilog(accessor);
mergeCleanupBlocks();
}
|