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
|
//===--- IRGen.cpp - Swift LLVM IR Generation -----------------------------===//
//
// 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 the entrypoints into IR generation.
//
//===----------------------------------------------------------------------===//
#include "../Serialization/ModuleFormat.h"
#include "GenValueWitness.h"
#include "IRGenModule.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/ABI/ObjectFile.h"
#include "swift/AST/DiagnosticsIRGen.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/IRGenRequests.h"
#include "swift/AST/LinkLibrary.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SILGenRequests.h"
#include "swift/AST/SILOptimizerRequests.h"
#include "swift/AST/TBDGenRequests.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/MD5Stream.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/IRGen/IRGenPublic.h"
#include "swift/IRGen/IRGenSILPasses.h"
#include "swift/IRGen/TBDGen.h"
#include "swift/LLVMPasses/Passes.h"
#include "swift/LLVMPasses/PassesFwd.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILRemarkStreamer.h"
#include "swift/SILOptimizer/PassManager/PassManager.h"
#include "swift/SILOptimizer/PassManager/PassPipeline.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Subsystems.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Bitcode/BitcodeWriter.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/CodeGen/BasicTTIImpl.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRPrinter/IRPrintingPasses.h"
#include "llvm/Linker/Linker.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Passes/PassBuilder.h"
#include "llvm/Passes/StandardInstrumentations.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualOutputBackend.h"
#include "llvm/Support/VirtualOutputConfig.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/TargetParser/SubtargetFeature.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/AlwaysInliner.h"
#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
#include "llvm/Transforms/ObjCARC.h"
#include "llvm/Transforms/Scalar.h"
#include <thread>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
using namespace swift;
using namespace irgen;
using namespace llvm;
#define DEBUG_TYPE "irgen"
static cl::opt<bool> DisableObjCARCContract(
"disable-objc-arc-contract", cl::Hidden,
cl::desc("Disable running objc arc contract for testing purposes"));
// This option is for performance benchmarking: to ensure a consistent
// performance data, modules are aligned to the page size.
// Warning: this blows up the text segment size. So use this option only for
// performance benchmarking.
static cl::opt<bool> AlignModuleToPageSize(
"align-module-to-page-size", cl::Hidden,
cl::desc("Align the text section of all LLVM modules to the page size"));
std::tuple<llvm::TargetOptions, std::string, std::vector<std::string>,
std::string>
swift::getIRTargetOptions(const IRGenOptions &Opts, ASTContext &Ctx) {
// Things that maybe we should collect from the command line:
// - relocation model
// - code model
// FIXME: We should do this entirely through Clang, for consistency.
TargetOptions TargetOpts;
// Explicitly request debugger tuning for LLDB which is the default
// on Darwin platforms but not on others.
TargetOpts.DebuggerTuning = llvm::DebuggerKind::LLDB;
TargetOpts.FunctionSections = Opts.FunctionSections;
// Set option to UseCASBackend if CAS was enabled on the command line.
TargetOpts.UseCASBackend = Opts.UseCASBackend;
// Set option to select the CASBackendMode.
TargetOpts.MCOptions.CASObjMode = Opts.CASObjMode;
auto *Clang = static_cast<ClangImporter *>(Ctx.getClangModuleLoader());
// Set UseInitArray appropriately.
TargetOpts.UseInitArray = Clang->getCodeGenOpts().UseInitArray;
// WebAssembly doesn't support atomics yet, see
// https://github.com/apple/swift/issues/54533 for more details.
if (Clang->getTargetInfo().getTriple().isOSBinFormatWasm())
TargetOpts.ThreadModel = llvm::ThreadModel::Single;
if (Opts.EnableGlobalISel) {
TargetOpts.EnableGlobalISel = true;
TargetOpts.GlobalISelAbort = GlobalISelAbortMode::DisableWithDiag;
}
switch (Opts.SwiftAsyncFramePointer) {
case SwiftAsyncFramePointerKind::Never:
TargetOpts.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
break;
case SwiftAsyncFramePointerKind::Auto:
TargetOpts.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::DeploymentBased;
break;
case SwiftAsyncFramePointerKind::Always:
TargetOpts.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
break;
}
clang::TargetOptions &ClangOpts = Clang->getTargetInfo().getTargetOpts();
return std::make_tuple(TargetOpts, ClangOpts.CPU, ClangOpts.Features, ClangOpts.Triple);
}
void setModuleFlags(IRGenModule &IGM) {
auto *Module = IGM.getModule();
// These module flags don't affect code generation; they just let us
// error during LTO if the user tries to combine files across ABIs.
Module->addModuleFlag(llvm::Module::Error, "Swift Version",
IRGenModule::swiftVersion);
if (IGM.getOptions().VirtualFunctionElimination ||
IGM.getOptions().WitnessMethodElimination) {
Module->addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 1);
}
}
static void align(llvm::Module *Module) {
// For performance benchmarking: Align the module to the page size by
// aligning the first function of the module.
unsigned pageSize =
#if HAVE_UNISTD_H
sysconf(_SC_PAGESIZE));
#else
4096; // Use a default value
#endif
for (auto I = Module->begin(), E = Module->end(); I != E; ++I) {
if (!I->isDeclaration()) {
I->setAlignment(llvm::MaybeAlign(pageSize));
break;
}
}
}
void swift::performLLVMOptimizations(const IRGenOptions &Opts,
llvm::Module *Module,
llvm::TargetMachine *TargetMachine,
llvm::raw_pwrite_stream *out) {
std::optional<PGOOptions> PGOOpt;
PipelineTuningOptions PTO;
bool RunSwiftSpecificLLVMOptzns =
!Opts.DisableSwiftSpecificLLVMOptzns && !Opts.DisableLLVMOptzns;
PTO.CallGraphProfile = false;
llvm::OptimizationLevel level = llvm::OptimizationLevel::O0;
if (Opts.shouldOptimize() && !Opts.DisableLLVMOptzns) {
// For historical reasons, loop interleaving is set to mirror setting for
// loop unrolling.
PTO.LoopInterleaving = true;
PTO.LoopVectorization = true;
PTO.SLPVectorization = true;
PTO.MergeFunctions = true;
level = llvm::OptimizationLevel::Os;
} else {
level = llvm::OptimizationLevel::O0;
}
LoopAnalysisManager LAM;
FunctionAnalysisManager FAM;
CGSCCAnalysisManager CGAM;
ModuleAnalysisManager MAM;
bool DebugPassStructure = false;
PassInstrumentationCallbacks PIC;
PrintPassOptions PrintPassOpts;
PrintPassOpts.Indent = DebugPassStructure;
PrintPassOpts.SkipAnalyses = DebugPassStructure;
StandardInstrumentations SI(Module->getContext(), DebugPassStructure,
/*VerifyEach*/ false, PrintPassOpts);
SI.registerCallbacks(PIC, &MAM);
PassBuilder PB(TargetMachine, PTO, PGOOpt, &PIC);
// Register the AA manager first so that our version is the one used.
FAM.registerPass([&] {
auto AA = PB.buildDefaultAAPipeline();
if (RunSwiftSpecificLLVMOptzns)
AA.registerFunctionAnalysis<SwiftAA>();
return AA;
});
FAM.registerPass([&] { return SwiftAA(); });
// Register all the basic analyses with the managers.
PB.registerModuleAnalyses(MAM);
PB.registerCGSCCAnalyses(CGAM);
PB.registerFunctionAnalyses(FAM);
PB.registerLoopAnalyses(LAM);
PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
ModulePassManager MPM;
if (RunSwiftSpecificLLVMOptzns) {
PB.registerScalarOptimizerLateEPCallback(
[](FunctionPassManager &FPM, OptimizationLevel Level) {
if (Level != OptimizationLevel::O0)
FPM.addPass(SwiftARCOptPass());
});
PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
OptimizationLevel Level) {
if (Level != OptimizationLevel::O0)
MPM.addPass(createModuleToFunctionPassAdaptor(SwiftARCContractPass()));
if (Level == OptimizationLevel::O0)
MPM.addPass(AlwaysInlinerPass());
});
}
// PassBuilder adds coroutine passes per default.
//
if (Opts.Sanitizers & SanitizerKind::Address) {
PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
OptimizationLevel Level) {
AddressSanitizerOptions ASOpts;
ASOpts.CompileKernel = false;
ASOpts.Recover = bool(Opts.SanitizersWithRecoveryInstrumentation &
SanitizerKind::Address);
ASOpts.UseAfterScope = false;
ASOpts.UseAfterReturn = llvm::AsanDetectStackUseAfterReturnMode::Runtime;
if (Opts.SanitizerUseStableABI) {
ASOpts.MaxInlinePoisoningSize = 0;
ASOpts.InstrumentationWithCallsThreshold = 0;
ASOpts.InsertVersionCheck = false;
}
MPM.addPass(AddressSanitizerPass(
ASOpts, /*UseGlobalGC=*/true, Opts.SanitizeAddressUseODRIndicator,
/*DestructorKind=*/llvm::AsanDtorKind::Global));
});
}
if (Opts.Sanitizers & SanitizerKind::Thread) {
PB.registerOptimizerLastEPCallback(
[&](ModulePassManager &MPM, OptimizationLevel Level) {
MPM.addPass(ModuleThreadSanitizerPass());
MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
});
}
if (Opts.SanitizeCoverage.CoverageType !=
llvm::SanitizerCoverageOptions::SCK_None) {
PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
OptimizationLevel Level) {
std::vector<std::string> allowlistFiles;
std::vector<std::string> ignorelistFiles;
MPM.addPass(SanitizerCoveragePass(Opts.SanitizeCoverage,
allowlistFiles, ignorelistFiles));
});
}
if (RunSwiftSpecificLLVMOptzns) {
PB.registerOptimizerLastEPCallback(
[&](ModulePassManager &MPM, OptimizationLevel Level) {
if (Level != OptimizationLevel::O0) {
const PointerAuthSchema &schema = Opts.PointerAuth.FunctionPointers;
unsigned key = (schema.isEnabled() ? schema.getKey() : 0);
MPM.addPass(SwiftMergeFunctionsPass(schema.isEnabled(), key));
}
});
}
if (Opts.GenerateProfile) {
InstrProfOptions options;
options.Atomic = bool(Opts.Sanitizers & SanitizerKind::Thread);
PB.registerPipelineStartEPCallback(
[options](ModulePassManager &MPM, OptimizationLevel level) {
MPM.addPass(InstrProfiling(options, false));
});
}
bool isThinLTO = Opts.LLVMLTOKind == IRGenLLVMLTOKind::Thin;
bool isFullLTO = Opts.LLVMLTOKind == IRGenLLVMLTOKind::Full;
if (!Opts.shouldOptimize() || Opts.DisableLLVMOptzns) {
MPM = PB.buildO0DefaultPipeline(level, isFullLTO || isThinLTO);
} else if (isThinLTO) {
MPM = PB.buildThinLTOPreLinkDefaultPipeline(level);
} else if (isFullLTO) {
MPM = PB.buildLTOPreLinkDefaultPipeline(level);
} else {
MPM = PB.buildPerModuleDefaultPipeline(level);
}
// Make sure we do ARC contraction under optimization. We don't
// rely on any other LLVM ARC transformations, but we do need ARC
// contraction to add the objc_retainAutoreleasedReturnValue
// assembly markers and remove clang.arc.used.
if (Opts.shouldOptimize() && !DisableObjCARCContract &&
!Opts.DisableLLVMOptzns)
MPM.addPass(createModuleToFunctionPassAdaptor(ObjCARCContractPass()));
if (Opts.Verify) {
// Run verification before we run the pipeline.
ModulePassManager VerifyPM;
VerifyPM.addPass(VerifierPass());
VerifyPM.run(*Module, MAM);
// PB.registerPipelineStartEPCallback(
// [](ModulePassManager &MPM, OptimizationLevel Level) {
// MPM.addPass(VerifierPass());
// });
// Run verification after we ran the pipeline;
MPM.addPass(VerifierPass());
}
if (Opts.PrintInlineTree)
MPM.addPass(InlineTreePrinterPass());
// Add bitcode/ll output passes to pass manager.
switch (Opts.OutputKind) {
case IRGenOutputKind::LLVMAssemblyBeforeOptimization:
llvm_unreachable("Should be handled earlier.");
case IRGenOutputKind::NativeAssembly:
case IRGenOutputKind::ObjectFile:
case IRGenOutputKind::Module:
break;
case IRGenOutputKind::LLVMAssemblyAfterOptimization:
MPM.addPass(PrintModulePass(*out, "", /*ShouldPreserveUseListOrder=*/false,
/*EmitSummaryIndex=*/false));
break;
case IRGenOutputKind::LLVMBitcode: {
// Emit a module summary by default for Regular LTO except ld64-based ones
// (which use the legacy LTO API).
bool EmitRegularLTOSummary =
TargetMachine->getTargetTriple().getVendor() != llvm::Triple::Apple;
if (Opts.LLVMLTOKind == IRGenLLVMLTOKind::Thin) {
MPM.addPass(ThinLTOBitcodeWriterPass(*out, nullptr));
} else {
if (EmitRegularLTOSummary) {
Module->addModuleFlag(llvm::Module::Error, "ThinLTO", uint32_t(0));
// Assume other sources are compiled with -fsplit-lto-unit (it's enabled
// by default when -flto is specified on platforms that support regular
// lto summary.)
Module->addModuleFlag(llvm::Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
}
MPM.addPass(BitcodeWriterPass(
*out, /*ShouldPreserveUseListOrder*/ false, EmitRegularLTOSummary));
}
break;
}
}
MPM.run(*Module, MAM);
if (AlignModuleToPageSize) {
align(Module);
}
}
/// Computes the MD5 hash of the llvm \p Module including the compiler version
/// and options which influence the compilation.
static MD5::MD5Result getHashOfModule(const IRGenOptions &Opts,
const llvm::Module *Module) {
// Calculate the hash of the whole llvm module.
MD5Stream HashStream;
llvm::WriteBitcodeToFile(*Module, HashStream);
// Update the hash with the compiler version. We want to recompile if the
// llvm pipeline of the compiler changed.
HashStream << version::getSwiftFullVersion();
// Add all options which influence the llvm compilation but are not yet
// reflected in the llvm module itself.
Opts.writeLLVMCodeGenOptionsTo(HashStream);
MD5::MD5Result result;
HashStream.final(result);
return result;
}
/// Returns false if the hash of the current module \p HashData matches the
/// hash which is stored in an existing output object file.
static bool needsRecompile(StringRef OutputFilename, ArrayRef<uint8_t> HashData,
llvm::GlobalVariable *HashGlobal,
llvm::sys::Mutex *DiagMutex) {
if (OutputFilename.empty())
return true;
auto BinaryOwner = object::createBinary(OutputFilename);
if (!BinaryOwner) {
consumeError(BinaryOwner.takeError());
return true;
}
auto *ObjectFile = dyn_cast<object::ObjectFile>(BinaryOwner->getBinary());
if (!ObjectFile)
return true;
StringRef HashSectionName = HashGlobal->getSection();
// Strip the segment name. For mach-o the GlobalVariable's section name format
// is <segment>,<section>.
size_t Comma = HashSectionName.find_last_of(',');
if (Comma != StringRef::npos)
HashSectionName = HashSectionName.substr(Comma + 1);
// Search for the section which holds the hash.
for (auto &Section : ObjectFile->sections()) {
llvm::Expected<StringRef> SectionNameOrErr = Section.getName();
if (!SectionNameOrErr) {
llvm::consumeError(SectionNameOrErr.takeError());
continue;
}
StringRef SectionName = *SectionNameOrErr;
if (SectionName == HashSectionName) {
llvm::Expected<llvm::StringRef> SectionData = Section.getContents();
if (!SectionData) {
return true;
}
ArrayRef<uint8_t> PrevHashData(
reinterpret_cast<const uint8_t *>(SectionData->data()),
SectionData->size());
LLVM_DEBUG(if (PrevHashData.size() == sizeof(MD5::MD5Result)) {
if (DiagMutex) DiagMutex->lock();
SmallString<32> HashStr;
MD5::stringifyResult(
*reinterpret_cast<MD5::MD5Result *>(
const_cast<unsigned char *>(PrevHashData.data())),
HashStr);
llvm::dbgs() << OutputFilename << ": prev MD5=" << HashStr <<
(HashData == PrevHashData ? " skipping\n" : " recompiling\n");
if (DiagMutex) DiagMutex->unlock();
});
if (HashData == PrevHashData)
return false;
return true;
}
}
return true;
}
static void countStatsPostIRGen(UnifiedStatsReporter &Stats,
const llvm::Module& Module) {
auto &C = Stats.getFrontendCounters();
// FIXME: calculate these in constant time if possible.
C.NumIRGlobals += Module.global_size();
C.NumIRFunctions += Module.getFunctionList().size();
C.NumIRAliases += Module.alias_size();
C.NumIRIFuncs += Module.ifunc_size();
C.NumIRNamedMetaData += Module.named_metadata_size();
C.NumIRValueSymbols += Module.getValueSymbolTable().size();
C.NumIRComdatSymbols += Module.getComdatSymbolTable().size();
for (auto const &Func : Module) {
for (auto const &BB : Func) {
++C.NumIRBasicBlocks;
C.NumIRInsts += BB.size();
}
}
}
template<typename ...ArgTypes>
void
diagnoseSync(DiagnosticEngine &Diags, llvm::sys::Mutex *DiagMutex,
SourceLoc Loc, Diag<ArgTypes...> ID,
typename swift::detail::PassArgument<ArgTypes>::type... Args) {
if (DiagMutex)
DiagMutex->lock();
Diags.diagnose(Loc, ID, std::move(Args)...);
if (DiagMutex)
DiagMutex->unlock();
}
/// Run the LLVM passes. In multi-threaded compilation this will be done for
/// multiple LLVM modules in parallel.
bool swift::performLLVM(const IRGenOptions &Opts,
DiagnosticEngine &Diags,
llvm::sys::Mutex *DiagMutex,
llvm::GlobalVariable *HashGlobal,
llvm::Module *Module,
llvm::TargetMachine *TargetMachine,
StringRef OutputFilename,
llvm::vfs::OutputBackend &Backend,
UnifiedStatsReporter *Stats) {
if (Opts.UseIncrementalLLVMCodeGen && HashGlobal) {
// Check if we can skip the llvm part of the compilation if we have an
// existing object file which was generated from the same llvm IR.
auto hash = getHashOfModule(Opts, Module);
LLVM_DEBUG(
if (DiagMutex) DiagMutex->lock();
SmallString<32> ResultStr;
MD5::stringifyResult(hash, ResultStr);
llvm::dbgs() << OutputFilename << ": MD5=" << ResultStr << '\n';
if (DiagMutex) DiagMutex->unlock();
);
ArrayRef<uint8_t> HashData(reinterpret_cast<uint8_t *>(&hash),
sizeof(hash));
if (Opts.OutputKind == IRGenOutputKind::ObjectFile &&
!Opts.PrintInlineTree && !Opts.AlwaysCompile &&
!needsRecompile(OutputFilename, HashData, HashGlobal, DiagMutex)) {
// The llvm IR did not change. We don't need to re-create the object file.
return false;
}
// Store the hash in the global variable so that it is written into the
// object file.
auto *HashConstant = ConstantDataArray::get(Module->getContext(), HashData);
HashGlobal->setInitializer(HashConstant);
}
std::optional<llvm::vfs::OutputFile> OutputFile;
SWIFT_DEFER {
if (!OutputFile)
return;
if (auto E = OutputFile->keep()) {
diagnoseSync(Diags, DiagMutex, SourceLoc(), diag::error_closing_output,
OutputFilename, toString(std::move(E)));
}
};
if (!OutputFilename.empty()) {
// Try to open the output file. Clobbering an existing file is fine.
// Open in binary mode if we're doing binary output.
llvm::vfs::OutputConfig Config;
if (auto E =
Backend.createFile(OutputFilename, Config).moveInto(OutputFile)) {
diagnoseSync(Diags, DiagMutex, SourceLoc(), diag::error_opening_output,
OutputFilename, toString(std::move(E)));
return true;
}
if (Opts.OutputKind == IRGenOutputKind::LLVMAssemblyBeforeOptimization) {
Module->print(*OutputFile, nullptr);
return false;
}
} else {
assert(Opts.OutputKind == IRGenOutputKind::Module && "no output specified");
}
performLLVMOptimizations(Opts, Module, TargetMachine,
OutputFile ? &OutputFile->getOS() : nullptr);
if (Stats) {
if (DiagMutex)
DiagMutex->lock();
countStatsPostIRGen(*Stats, *Module);
if (DiagMutex)
DiagMutex->unlock();
}
if (OutputFilename.empty())
return false;
std::unique_ptr<raw_fd_ostream> CASIDFile;
if (Opts.UseCASBackend && Opts.EmitCASIDFile &&
Opts.CASObjMode != llvm::CASBackendMode::CASID &&
Opts.OutputKind == IRGenOutputKind::ObjectFile && OutputFilename != "-") {
std::string OutputFilenameCASID = std::string(OutputFilename);
OutputFilenameCASID.append(".casid");
std::error_code EC;
CASIDFile = std::make_unique<raw_fd_ostream>(OutputFilenameCASID, EC);
if (EC) {
diagnoseSync(Diags, DiagMutex, SourceLoc(), diag::error_opening_output,
OutputFilename, std::move(EC.message()));
return true;
}
}
return compileAndWriteLLVM(Module, TargetMachine, Opts, Stats, Diags,
*OutputFile, DiagMutex,
CASIDFile ? CASIDFile.get() : nullptr);
}
bool swift::compileAndWriteLLVM(
llvm::Module *module, llvm::TargetMachine *targetMachine,
const IRGenOptions &opts, UnifiedStatsReporter *stats,
DiagnosticEngine &diags, llvm::raw_pwrite_stream &out,
llvm::sys::Mutex *diagMutex, llvm::raw_pwrite_stream *casid) {
// Set up the final code emission pass. Bitcode/LLVM IR is emitted as part of
// the optimization pass pipeline.
switch (opts.OutputKind) {
case IRGenOutputKind::LLVMAssemblyBeforeOptimization:
llvm_unreachable("Should be handled earlier.");
case IRGenOutputKind::Module:
break;
case IRGenOutputKind::LLVMAssemblyAfterOptimization:
break;
case IRGenOutputKind::LLVMBitcode: {
break;
}
case IRGenOutputKind::NativeAssembly:
case IRGenOutputKind::ObjectFile: {
legacy::PassManager EmitPasses;
CodeGenFileType FileType;
FileType =
(opts.OutputKind == IRGenOutputKind::NativeAssembly ? CGFT_AssemblyFile
: CGFT_ObjectFile);
EmitPasses.add(createTargetTransformInfoWrapperPass(
targetMachine->getTargetIRAnalysis()));
bool fail = targetMachine->addPassesToEmitFile(
EmitPasses, out, nullptr, FileType, !opts.Verify, nullptr, casid);
if (fail) {
diagnoseSync(diags, diagMutex, SourceLoc(),
diag::error_codegen_init_fail);
return true;
}
EmitPasses.run(*module);
break;
}
}
if (stats) {
if (diagMutex)
diagMutex->lock();
stats->getFrontendCounters().NumLLVMBytesOutput += out.tell();
if (diagMutex)
diagMutex->unlock();
}
return false;
}
static void setPointerAuthOptions(PointerAuthOptions &opts,
const clang::PointerAuthOptions &clangOpts,
const IRGenOptions &irgenOpts) {
// Intentionally do a slice-assignment to copy over the clang options.
static_cast<clang::PointerAuthOptions&>(opts) = clangOpts;
assert(clangOpts.FunctionPointers);
if (clangOpts.FunctionPointers.getKind() != PointerAuthSchema::Kind::ARM8_3)
return;
using Discrimination = PointerAuthSchema::Discrimination;
// A key suitable for code pointers that might be used anywhere in the ABI.
auto codeKey = clangOpts.FunctionPointers.getARM8_3Key();
// A key suitable for data pointers that might be used anywhere in the ABI.
// Using a data key for data pointers and vice-versa is important for
// ABI future-proofing.
auto dataKey = PointerAuthSchema::ARM8_3Key::ASDA;
// A key suitable for code pointers that are only used in private
// situations. Do not use this key for any sort of signature that
// might end up on a global constant initializer.
auto nonABICodeKey = PointerAuthSchema::ARM8_3Key::ASIB;
// A key suitable for data pointers that are only used in private
// situations. Do not use this key for any sort of signature that
// might end up on a global constant initializer.
auto nonABIDataKey = PointerAuthSchema::ARM8_3Key::ASDB;
// If you change anything here, be sure to update <ptrauth.h>.
opts.SwiftFunctionPointers =
PointerAuthSchema(codeKey, /*address*/ false, Discrimination::Type);
opts.KeyPaths =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.ValueWitnesses =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.ProtocolWitnesses =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.ProtocolAssociatedTypeAccessFunctions =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.ProtocolAssociatedTypeWitnessTableAccessFunctions =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.SwiftClassMethods =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.SwiftClassMethodPointers =
PointerAuthSchema(codeKey, /*address*/ false, Discrimination::Decl);
opts.HeapDestructors =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
// Partial-apply captures are not ABI and can use a more aggressive key.
opts.PartialApplyCapture =
PointerAuthSchema(nonABICodeKey, /*address*/ true, Discrimination::Decl);
opts.TypeDescriptors =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.TypeDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.TypeLayoutString =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.SwiftDynamicReplacements =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Decl);
opts.SwiftDynamicReplacementKeys =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.ProtocolConformanceDescriptors =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.ProtocolConformanceDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.ProtocolDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.OpaqueTypeDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.ContextDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.OpaqueTypeDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.ContextDescriptorsAsArguments =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
// Coroutine resumption functions are never stored globally in the ABI,
// so we can do some things that aren't normally okay to do. However,
// we can't use ASIB because that would break ARM64 interoperation.
// The address used in the discrimination is not the address where the
// function pointer is signed, but the address of the coroutine buffer.
opts.YieldManyResumeFunctions =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Type);
opts.YieldOnceResumeFunctions =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Type);
opts.ResilientClassStubInitCallbacks =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Constant,
SpecialPointerAuthDiscriminators::ResilientClassStubInitCallback);
opts.AsyncSwiftFunctionPointers =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Type);
opts.AsyncSwiftClassMethods =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.AsyncProtocolWitnesses =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.AsyncSwiftClassMethodPointers =
PointerAuthSchema(dataKey, /*address*/ false, Discrimination::Decl);
opts.AsyncSwiftDynamicReplacements =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Decl);
opts.AsyncPartialApplyCapture =
PointerAuthSchema(nonABIDataKey, /*address*/ true, Discrimination::Decl);
opts.AsyncContextParent =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Constant,
SpecialPointerAuthDiscriminators::AsyncContextParent);
opts.AsyncContextResume =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Constant,
SpecialPointerAuthDiscriminators::AsyncContextResume);
opts.TaskResumeFunction =
PointerAuthSchema(codeKey, /*address*/ true, Discrimination::Constant,
SpecialPointerAuthDiscriminators::TaskResumeFunction);
opts.TaskResumeContext =
PointerAuthSchema(dataKey, /*address*/ true, Discrimination::Constant,
SpecialPointerAuthDiscriminators::TaskResumeContext);
opts.AsyncContextExtendedFrameEntry = PointerAuthSchema(
dataKey, /*address*/ true, Discrimination::Constant,
SpecialPointerAuthDiscriminators::SwiftAsyncContextExtendedFrameEntry);
opts.ExtendedExistentialTypeShape =
PointerAuthSchema(dataKey, /*address*/ false,
Discrimination::Constant,
SpecialPointerAuthDiscriminators
::ExtendedExistentialTypeShape);
opts.NonUniqueExtendedExistentialTypeShape =
PointerAuthSchema(dataKey, /*address*/ false,
Discrimination::Constant,
SpecialPointerAuthDiscriminators
::NonUniqueExtendedExistentialTypeShape);
opts.ClangTypeTaskContinuationFunction = PointerAuthSchema(
codeKey, /*address*/ false, Discrimination::Constant,
SpecialPointerAuthDiscriminators::ClangTypeTaskContinuationFunction);
opts.GetExtraInhabitantTagFunction = PointerAuthSchema(
codeKey, /*address*/ false, Discrimination::Constant,
SpecialPointerAuthDiscriminators::GetExtraInhabitantTagFunction);
opts.StoreExtraInhabitantTagFunction = PointerAuthSchema(
codeKey, /*address*/ false, Discrimination::Constant,
SpecialPointerAuthDiscriminators::StoreExtraInhabitantTagFunction);
if (irgenOpts.UseRelativeProtocolWitnessTables)
opts.RelativeProtocolWitnessTable = PointerAuthSchema(
dataKey, /*address*/ false, Discrimination::Constant,
SpecialPointerAuthDiscriminators::RelativeProtocolWitnessTable);
}
std::unique_ptr<llvm::TargetMachine>
swift::createTargetMachine(const IRGenOptions &Opts, ASTContext &Ctx) {
CodeGenOpt::Level OptLevel = Opts.shouldOptimize()
? CodeGenOpt::Default // -Os
: CodeGenOpt::None;
// Set up TargetOptions and create the target features string.
TargetOptions TargetOpts;
std::string CPU;
std::string EffectiveClangTriple;
std::vector<std::string> targetFeaturesArray;
std::tie(TargetOpts, CPU, targetFeaturesArray, EffectiveClangTriple)
= getIRTargetOptions(Opts, Ctx);
const llvm::Triple &EffectiveTriple = llvm::Triple(EffectiveClangTriple);
std::string targetFeatures;
if (!targetFeaturesArray.empty()) {
llvm::SubtargetFeatures features;
for (const std::string &feature : targetFeaturesArray)
if (!shouldRemoveTargetFeature(feature)) {
features.AddFeature(feature);
}
targetFeatures = features.getString();
}
// Set up pointer-authentication.
if (auto loader = Ctx.getClangModuleLoader()) {
auto &clangInstance = loader->getClangInstance();
if (clangInstance.getLangOpts().PointerAuthCalls) {
// FIXME: This is gross. This needs to be done in the Frontend
// after the module loaders are set up, and where these options are
// formally not const.
setPointerAuthOptions(const_cast<IRGenOptions &>(Opts).PointerAuth,
clangInstance.getCodeGenOpts().PointerAuth, Opts);
}
}
std::string Error;
const Target *Target =
TargetRegistry::lookupTarget(EffectiveTriple.str(), Error);
if (!Target) {
Ctx.Diags.diagnose(SourceLoc(), diag::no_llvm_target, EffectiveTriple.str(),
Error);
return nullptr;
}
// On Cygwin 64 bit, dlls are loaded above the max address for 32 bits.
// This means that the default CodeModel causes generated code to segfault
// when run.
std::optional<CodeModel::Model> cmodel = std::nullopt;
if (EffectiveTriple.isArch64Bit() && EffectiveTriple.isWindowsCygwinEnvironment())
cmodel = CodeModel::Large;
// Create a target machine.
llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
EffectiveTriple.str(), CPU, targetFeatures, TargetOpts, Reloc::PIC_,
cmodel, OptLevel);
if (!TargetMachine) {
Ctx.Diags.diagnose(SourceLoc(), diag::no_llvm_target,
EffectiveTriple.str(), "no LLVM target machine");
return nullptr;
}
return std::unique_ptr<llvm::TargetMachine>(TargetMachine);
}
IRGenerator::IRGenerator(const IRGenOptions &options, SILModule &module)
: Opts(options), SIL(module), QueueIndex(0) {
}
std::unique_ptr<llvm::TargetMachine> IRGenerator::createTargetMachine() {
return ::createTargetMachine(Opts, SIL.getASTContext());
}
// With -embed-bitcode, save a copy of the llvm IR as data in the
// __LLVM,__bitcode section and save the command-line options in the
// __LLVM,__swift_cmdline section.
static void embedBitcode(llvm::Module *M, const IRGenOptions &Opts)
{
if (Opts.EmbedMode == IRGenEmbedMode::None)
return;
// Save llvm.compiler.used and remove it.
SmallVector<llvm::Constant*, 2> UsedArray;
SmallVector<llvm::GlobalValue*, 4> UsedGlobals;
auto *UsedElementType =
llvm::Type::getInt8Ty(M->getContext())->getPointerTo(0);
llvm::GlobalVariable *Used =
collectUsedGlobalVariables(*M, UsedGlobals, true);
for (auto *GV : UsedGlobals) {
if (GV->getName() != "llvm.embedded.module" &&
GV->getName() != "llvm.cmdline")
UsedArray.push_back(
ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
}
if (Used)
Used->eraseFromParent();
// Embed the bitcode for the llvm module.
std::string Data;
llvm::raw_string_ostream OS(Data);
if (Opts.EmbedMode == IRGenEmbedMode::EmbedBitcode)
llvm::WriteBitcodeToFile(*M, OS);
ArrayRef<uint8_t> ModuleData(
reinterpret_cast<const uint8_t *>(OS.str().data()), OS.str().size());
llvm::Constant *ModuleConstant =
llvm::ConstantDataArray::get(M->getContext(), ModuleData);
llvm::GlobalVariable *GV = new llvm::GlobalVariable(*M,
ModuleConstant->getType(), true,
llvm::GlobalValue::PrivateLinkage,
ModuleConstant);
UsedArray.push_back(
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
GV->setSection("__LLVM,__bitcode");
if (llvm::GlobalVariable *Old =
M->getGlobalVariable("llvm.embedded.module", true)) {
GV->takeName(Old);
Old->replaceAllUsesWith(GV);
delete Old;
} else {
GV->setName("llvm.embedded.module");
}
// Embed command-line options.
ArrayRef<uint8_t>
CmdData(reinterpret_cast<const uint8_t *>(Opts.CmdArgs.data()),
Opts.CmdArgs.size());
llvm::Constant *CmdConstant =
llvm::ConstantDataArray::get(M->getContext(), CmdData);
GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
llvm::GlobalValue::PrivateLinkage,
CmdConstant);
GV->setSection("__LLVM,__swift_cmdline");
UsedArray.push_back(
llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
if (llvm::GlobalVariable *Old = M->getGlobalVariable("llvm.cmdline", true)) {
GV->takeName(Old);
Old->replaceAllUsesWith(GV);
delete Old;
} else {
GV->setName("llvm.cmdline");
}
if (UsedArray.empty())
return;
// Recreate llvm.compiler.used.
auto *ATy = llvm::ArrayType::get(UsedElementType, UsedArray.size());
auto *NewUsed = new GlobalVariable(
*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
NewUsed->setSection("llvm.metadata");
}
static void initLLVMModule(const IRGenModule &IGM, SILModule &SIL) {
auto *Module = IGM.getModule();
assert(Module && "Expected llvm:Module for IR generation!");
Module->setTargetTriple(IGM.Triple.str());
if (IGM.Context.LangOpts.SDKVersion) {
if (Module->getSDKVersion().empty())
Module->setSDKVersion(*IGM.Context.LangOpts.SDKVersion);
else
assert(Module->getSDKVersion() == *IGM.Context.LangOpts.SDKVersion);
}
// Set the module's string representation.
Module->setDataLayout(IGM.DataLayout.getStringRepresentation());
auto *MDNode = IGM.getModule()->getOrInsertNamedMetadata("swift.module.flags");
auto &Context = IGM.getModule()->getContext();
auto *Value = SIL.getSwiftModule()->isStdlibModule()
? llvm::ConstantInt::getTrue(Context)
: llvm::ConstantInt::getFalse(Context);
MDNode->addOperand(llvm::MDTuple::get(Context,
{llvm::MDString::get(Context,
"standard-library"),
llvm::ConstantAsMetadata::get(Value)}));
if (auto *streamer = SIL.getSILRemarkStreamer()) {
streamer->intoLLVMContext(Module->getContext());
}
}
std::pair<IRGenerator *, IRGenModule *>
swift::irgen::createIRGenModule(SILModule *SILMod, StringRef OutputFilename,
StringRef MainInputFilenameForDebugInfo,
StringRef PrivateDiscriminator,
IRGenOptions &Opts) {
IRGenerator *irgen = new IRGenerator(Opts, *SILMod);
auto targetMachine = irgen->createTargetMachine();
if (!targetMachine) {
delete irgen;
return std::make_pair(nullptr, nullptr);
}
// Create the IR emitter.
IRGenModule *IGM = new IRGenModule(
*irgen, std::move(targetMachine), nullptr, "", OutputFilename,
MainInputFilenameForDebugInfo, PrivateDiscriminator);
initLLVMModule(*IGM, *SILMod);
return std::pair<IRGenerator *, IRGenModule *>(irgen, IGM);
}
void swift::irgen::deleteIRGenModule(
std::pair<IRGenerator *, IRGenModule *> &IRGenPair) {
delete IRGenPair.second;
delete IRGenPair.first;
}
/// Run the IRGen preparation SIL pipeline. Passes have access to the
/// IRGenModule.
static void runIRGenPreparePasses(SILModule &Module,
irgen::IRGenModule &IRModule) {
auto &opts = Module.getOptions();
auto plan = SILPassPipelinePlan::getIRGenPreparePassPipeline(opts);
executePassPipelinePlan(&Module, plan, /*isMandatory*/ true, &IRModule);
}
namespace {
using IREntitiesToEmit = SmallVector<LinkEntity, 1>;
struct SymbolSourcesToEmit {
SILRefsToEmit silRefsToEmit;
IREntitiesToEmit irEntitiesToEmit;
};
static std::optional<SymbolSourcesToEmit>
getSymbolSourcesToEmit(const IRGenDescriptor &desc) {
if (!desc.SymbolsToEmit)
return std::nullopt;
assert(!desc.SILMod && "Already emitted SIL?");
// First retrieve the symbol source map to figure out what we need to build,
// making sure to include non-public symbols.
auto &ctx = desc.getParentModule()->getASTContext();
auto tbdDesc = desc.getTBDGenDescriptor();
tbdDesc.getOptions().PublicOrPackageSymbolsOnly = false;
const auto *symbolMap =
evaluateOrFatal(ctx.evaluator, SymbolSourceMapRequest{std::move(tbdDesc)});
// Then split up the symbols so they can be emitted by the appropriate part
// of the pipeline.
SILRefsToEmit silRefsToEmit;
IREntitiesToEmit irEntitiesToEmit;
for (const auto &symbol : *desc.SymbolsToEmit) {
auto itr = symbolMap->find(symbol);
assert(itr != symbolMap->end() && "Couldn't find symbol");
const auto &source = itr->getValue();
switch (source.kind) {
case SymbolSource::Kind::SIL:
silRefsToEmit.push_back(source.getSILDeclRef());
break;
case SymbolSource::Kind::IR:
irEntitiesToEmit.push_back(source.getIRLinkEntity());
break;
case SymbolSource::Kind::LinkerDirective:
case SymbolSource::Kind::Unknown:
case SymbolSource::Kind::Global:
llvm_unreachable("Not supported");
}
}
return SymbolSourcesToEmit{silRefsToEmit, irEntitiesToEmit};
}
} // end of anonymous namespace
/// Generates LLVM IR, runs the LLVM passes and produces the output file.
/// All this is done in a single thread.
GeneratedModule IRGenRequest::evaluate(Evaluator &evaluator,
IRGenDescriptor desc) const {
const auto &Opts = desc.Opts;
const auto &PSPs = desc.PSPs;
auto *M = desc.getParentModule();
auto &Ctx = M->getASTContext();
assert(!Ctx.hadError());
auto symsToEmit = getSymbolSourcesToEmit(desc);
assert(!symsToEmit || symsToEmit->irEntitiesToEmit.empty() &&
"IR symbol emission not implemented yet");
// If we've been provided a SILModule, use it. Otherwise request the lowered
// SIL for the file or module.
auto SILMod = std::unique_ptr<SILModule>(desc.SILMod);
if (!SILMod) {
auto loweringDesc = ASTLoweringDescriptor{desc.Ctx, desc.Conv, desc.SILOpts,
nullptr, std::nullopt};
SILMod = evaluateOrFatal(Ctx.evaluator, LoweredSILRequest{loweringDesc});
// If there was an error, bail.
if (Ctx.hadError())
return GeneratedModule::null();
}
auto filesToEmit = desc.getFilesToEmit();
auto *primaryFile =
dyn_cast_or_null<SourceFile>(desc.Ctx.dyn_cast<FileUnit *>());
IRGenerator irgen(Opts, *SILMod);
auto targetMachine = irgen.createTargetMachine();
if (!targetMachine) return GeneratedModule::null();
// Create the IR emitter.
IRGenModule IGM(irgen, std::move(targetMachine), primaryFile, desc.ModuleName,
PSPs.OutputFilename, PSPs.MainInputFilenameForDebugInfo,
desc.PrivateDiscriminator);
initLLVMModule(IGM, *SILMod);
// Run SIL level IRGen preparation passes.
runIRGenPreparePasses(*SILMod, IGM);
(void)layoutStringsEnabled(IGM, /*diagnose*/ true);
{
FrontendStatsTracer tracer(Ctx.Stats, "IRGen");
// Emit the module contents.
irgen.emitGlobalTopLevel(desc.getLinkerDirectives());
for (auto *file : filesToEmit) {
if (auto *nextSF = dyn_cast<SourceFile>(file)) {
IGM.emitSourceFile(*nextSF);
if (auto *synthSFU = file->getSynthesizedFile()) {
IGM.emitSynthesizedFileUnit(*synthSFU);
}
}
}
IGM.addLinkLibraries();
// Okay, emit any definitions that we suddenly need.
irgen.emitLazyDefinitions();
// Register our info with the runtime if needed.
if (Opts.UseJIT) {
IGM.emitBuiltinReflectionMetadata();
IGM.emitRuntimeRegistration();
} else {
// Emit protocol conformances into a section we can recognize at runtime.
// In JIT mode these are manually registered above.
IGM.emitSwiftProtocols(/*asContiguousArray*/ false);
IGM.emitProtocolConformances(/*asContiguousArray*/ false);
IGM.emitTypeMetadataRecords(/*asContiguousArray*/ false);
IGM.emitAccessibleFunctions();
IGM.emitBuiltinReflectionMetadata();
IGM.emitReflectionMetadataVersion();
irgen.emitEagerClassInitialization();
irgen.emitObjCActorsNeedingSuperclassSwizzle();
irgen.emitDynamicReplacements();
}
// Emit coverage mapping info. This needs to happen after we've emitted
// any lazy definitions, as we need to know whether or not we emitted a
// profiler increment for a given coverage map.
irgen.emitCoverageMapping();
// Emit symbols for eliminated dead methods.
IGM.emitVTableStubs();
// Verify type layout if we were asked to.
if (!Opts.VerifyTypeLayoutNames.empty())
IGM.emitTypeVerifier();
std::for_each(Opts.LinkLibraries.begin(), Opts.LinkLibraries.end(),
[&](LinkLibrary linkLib) {
IGM.addLinkLibrary(linkLib);
});
if (!IGM.finalize())
return GeneratedModule::null();
setModuleFlags(IGM);
}
// Bail out if there are any errors.
if (Ctx.hadError()) return GeneratedModule::null();
// Free the memory occupied by the SILModule.
// Execute this task in parallel to the embedding of bitcode.
auto SILModuleRelease = [&SILMod]() {
SILMod.reset(nullptr);
};
auto Thread = std::thread(SILModuleRelease);
// Wait for the thread to terminate.
SWIFT_DEFER { Thread.join(); };
embedBitcode(IGM.getModule(), Opts);
// TODO: Turn the module hash into an actual output.
if (auto **outModuleHash = desc.outModuleHash) {
*outModuleHash = IGM.ModuleHash;
}
return std::move(IGM).intoGeneratedModule();
}
namespace {
struct LLVMCodeGenThreads {
struct Thread {
LLVMCodeGenThreads &parent;
unsigned threadIndex;
#ifdef __APPLE__
pthread_t threadId;
#else
std::thread thread;
#endif
Thread(LLVMCodeGenThreads &parent, unsigned threadIndex)
: parent(parent), threadIndex(threadIndex)
{}
/// Run llvm codegen.
void run() {
auto *diagMutex = parent.diagMutex;
while (IRGenModule *IGM = parent.irgen->fetchFromQueue()) {
LLVM_DEBUG(diagMutex->lock();
dbgs() << "thread " << threadIndex << ": fetched "
<< IGM->OutputFilename << "\n";
diagMutex->unlock(););
embedBitcode(IGM->getModule(), parent.irgen->Opts);
performLLVM(parent.irgen->Opts, IGM->Context.Diags, diagMutex,
IGM->ModuleHash, IGM->getModule(), IGM->TargetMachine.get(),
IGM->OutputFilename, IGM->Context.getOutputBackend(),
IGM->Context.Stats);
if (IGM->Context.Diags.hadAnyError())
return;
}
LLVM_DEBUG(diagMutex->lock();
dbgs() << "thread " << threadIndex << ": done\n";
diagMutex->unlock(););
return;
}
};
IRGenerator *irgen;
llvm::sys::Mutex *diagMutex;
std::vector<Thread> threads;
LLVMCodeGenThreads(IRGenerator *irgen, llvm::sys::Mutex *diagMutex,
unsigned numThreads)
: irgen(irgen), diagMutex(diagMutex) {
threads.reserve(numThreads);
for (unsigned idx = 0; idx < numThreads; ++idx) {
// the 0-th thread is executed by the main thread.
threads.push_back(Thread(*this, idx + 1));
}
}
static void *runThread(void *arg) {
auto *thread = reinterpret_cast<Thread *>(arg);
thread->run();
return nullptr;
}
void startThreads() {
#ifdef __APPLE__
// Increase the thread stack size on macosx to 8MB (default is 512KB). This
// matches the main thread.
pthread_attr_t stackSizeAttribute;
int err = pthread_attr_init(&stackSizeAttribute);
assert(!err);
err = pthread_attr_setstacksize(&stackSizeAttribute, 8 * 1024 * 1024);
assert(!err);
for (auto &thread : threads) {
pthread_create(&thread.threadId, &stackSizeAttribute,
LLVMCodeGenThreads::runThread, &thread);
}
pthread_attr_destroy(&stackSizeAttribute);
#else
for (auto &thread : threads) {
thread.thread = std::thread(runThread, &thread);
}
#endif
}
void runMainThread() {
Thread mainThread(*this, 0);
mainThread.run();
}
void join() {
#ifdef __APPLE__
for (auto &thread : threads)
pthread_join(thread.threadId, 0);
#else
for (auto &thread: threads) {
thread.thread.join();
}
#endif
}
};
}
/// Generates LLVM IR, runs the LLVM passes and produces the output files.
/// All this is done in multiple threads.
static void performParallelIRGeneration(IRGenDescriptor desc) {
const auto &Opts = desc.Opts;
auto outputFilenames = desc.parallelOutputFilenames;
auto SILMod = std::unique_ptr<SILModule>(desc.SILMod);
auto *M = desc.getParentModule();
IRGenerator irgen(Opts, *SILMod);
// Enter a cleanup to delete all the IGMs and their associated LLVMContexts
// that have been associated with the IRGenerator.
struct IGMDeleter {
IRGenerator &IRGen;
IGMDeleter(IRGenerator &irgen) : IRGen(irgen) {}
~IGMDeleter() {
for (auto it = IRGen.begin(); it != IRGen.end(); ++it) {
IRGenModule *IGM = it->second;
delete IGM;
}
}
} _igmDeleter(irgen);
auto OutputIter = outputFilenames.begin();
bool IGMcreated = false;
auto &Ctx = M->getASTContext();
// Create an IRGenModule for each source file.
bool DidRunSILCodeGenPreparePasses = false;
for (auto *File : M->getFiles()) {
auto nextSF = dyn_cast<SourceFile>(File);
if (!nextSF)
continue;
// There must be an output filename for each source file.
// We ignore additional output filenames.
if (OutputIter == outputFilenames.end()) {
Ctx.Diags.diagnose(SourceLoc(), diag::too_few_output_filenames);
return;
}
auto targetMachine = irgen.createTargetMachine();
if (!targetMachine) continue;
// Create the IR emitter.
IRGenModule *IGM = new IRGenModule(
irgen, std::move(targetMachine), nextSF, desc.ModuleName, *OutputIter++,
nextSF->getFilename(), nextSF->getPrivateDiscriminator().str());
initLLVMModule(*IGM, *SILMod);
if (!DidRunSILCodeGenPreparePasses) {
// Run SIL level IRGen preparation passes on the module the first time
// around.
runIRGenPreparePasses(*SILMod, *IGM);
DidRunSILCodeGenPreparePasses = true;
}
(void)layoutStringsEnabled(*IGM, /*diagnose*/ true);
// Only need to do this once.
if (!IGMcreated)
IGM->addLinkLibraries();
IGMcreated = true;
}
if (!IGMcreated) {
// TODO: Check this already at argument parsing.
Ctx.Diags.diagnose(SourceLoc(), diag::no_input_files_for_mt);
return;
}
// Emit the module contents.
irgen.emitGlobalTopLevel(desc.getLinkerDirectives());
for (auto *File : M->getFiles()) {
if (auto *SF = dyn_cast<SourceFile>(File)) {
{
CurrentIGMPtr IGM = irgen.getGenModule(SF);
IGM->emitSourceFile(*SF);
}
if (auto *synthSFU = File->getSynthesizedFile()) {
CurrentIGMPtr IGM = irgen.getGenModule(synthSFU);
IGM->emitSynthesizedFileUnit(*synthSFU);
}
}
}
// Okay, emit any definitions that we suddenly need.
irgen.emitLazyDefinitions();
irgen.emitSwiftProtocols();
irgen.emitDynamicReplacements();
irgen.emitProtocolConformances();
irgen.emitTypeMetadataRecords();
irgen.emitAccessibleFunctions();
irgen.emitReflectionMetadataVersion();
irgen.emitEagerClassInitialization();
irgen.emitObjCActorsNeedingSuperclassSwizzle();
// Emit reflection metadata for builtin and imported types.
irgen.emitBuiltinReflectionMetadata();
// Emit coverage mapping info. This needs to happen after we've emitted
// any lazy definitions, as we need to know whether or not we emitted a
// profiler increment for a given coverage map.
irgen.emitCoverageMapping();
IRGenModule *PrimaryGM = irgen.getPrimaryIGM();
// Emit symbols for eliminated dead methods.
PrimaryGM->emitVTableStubs();
// Verify type layout if we were asked to.
if (!Opts.VerifyTypeLayoutNames.empty())
PrimaryGM->emitTypeVerifier();
std::for_each(Opts.LinkLibraries.begin(), Opts.LinkLibraries.end(),
[&](LinkLibrary linkLib) {
PrimaryGM->addLinkLibrary(linkLib);
});
llvm::DenseSet<StringRef> referencedGlobals;
for (auto it = irgen.begin(); it != irgen.end(); ++it) {
IRGenModule *IGM = it->second;
llvm::Module *M = IGM->getModule();
auto collectReference = [&](llvm::GlobalValue &G) {
if (G.isDeclaration()
&& (G.getLinkage() == GlobalValue::LinkOnceODRLinkage ||
G.getLinkage() == GlobalValue::ExternalLinkage)) {
referencedGlobals.insert(G.getName());
G.setLinkage(GlobalValue::ExternalLinkage);
}
};
for (llvm::GlobalVariable &G : M->globals()) {
collectReference(G);
}
for (llvm::Function &F : M->getFunctionList()) {
collectReference(F);
}
for (llvm::GlobalAlias &A : M->aliases()) {
collectReference(A);
}
}
for (auto it = irgen.begin(); it != irgen.end(); ++it) {
IRGenModule *IGM = it->second;
llvm::Module *M = IGM->getModule();
// Update the linkage of shared functions/globals.
// If a shared function/global is referenced from another file it must have
// weak instead of linkonce linkage. Otherwise LLVM would remove the
// definition (if it's not referenced in the same file).
auto updateLinkage = [&](llvm::GlobalValue &G) {
if (!G.isDeclaration()
&& G.getLinkage() == GlobalValue::LinkOnceODRLinkage
&& referencedGlobals.count(G.getName()) != 0) {
G.setLinkage(GlobalValue::WeakODRLinkage);
}
};
for (llvm::GlobalVariable &G : M->globals()) {
updateLinkage(G);
}
for (llvm::Function &F : M->getFunctionList()) {
updateLinkage(F);
}
for (llvm::GlobalAlias &A : M->aliases()) {
updateLinkage(A);
}
if (!IGM->finalize())
return;
setModuleFlags(*IGM);
}
// Bail out if there are any errors.
if (Ctx.hadError()) return;
FrontendStatsTracer tracer(Ctx.Stats, "LLVM pipeline");
llvm::sys::Mutex DiagMutex;
// Start all the threads and do the LLVM compilation.
LLVMCodeGenThreads codeGenThreads(&irgen, &DiagMutex, Opts.NumThreads - 1);
codeGenThreads.startThreads();
// Free the memory occupied by the SILModule.
// Execute this task in parallel to the LLVM compilation.
auto SILModuleRelease = [&SILMod]() {
SILMod.reset(nullptr);
};
auto releaseModuleThread = std::thread(SILModuleRelease);
codeGenThreads.runMainThread();
// Wait for all threads.
releaseModuleThread.join();
codeGenThreads.join();
}
GeneratedModule swift::performIRGeneration(
swift::ModuleDecl *M, const IRGenOptions &Opts,
const TBDGenOptions &TBDOpts, std::unique_ptr<SILModule> SILMod,
StringRef ModuleName, const PrimarySpecificPaths &PSPs,
ArrayRef<std::string> parallelOutputFilenames,
llvm::GlobalVariable **outModuleHash) {
// Get a pointer to the SILModule to avoid a potential use-after-move.
const auto *SILModPtr = SILMod.get();
const auto &SILOpts = SILModPtr->getOptions();
auto desc = IRGenDescriptor::forWholeModule(
M, Opts, TBDOpts, SILOpts, SILModPtr->Types, std::move(SILMod),
ModuleName, PSPs, /*symsToEmit*/ std::nullopt, parallelOutputFilenames,
outModuleHash);
if (Opts.shouldPerformIRGenerationInParallel() &&
!parallelOutputFilenames.empty() &&
!Opts.UseSingleModuleLLVMEmission) {
::performParallelIRGeneration(desc);
// TODO: Parallel LLVM compilation cannot be used if a (single) module is
// needed as return value.
return GeneratedModule::null();
}
return evaluateOrFatal(M->getASTContext().evaluator, IRGenRequest{desc});
}
GeneratedModule swift::
performIRGeneration(FileUnit *file, const IRGenOptions &Opts,
const TBDGenOptions &TBDOpts,
std::unique_ptr<SILModule> SILMod,
StringRef ModuleName, const PrimarySpecificPaths &PSPs,
StringRef PrivateDiscriminator,
llvm::GlobalVariable **outModuleHash) {
// Get a pointer to the SILModule to avoid a potential use-after-move.
const auto *SILModPtr = SILMod.get();
const auto &SILOpts = SILModPtr->getOptions();
auto desc = IRGenDescriptor::forFile(
file, Opts, TBDOpts, SILOpts, SILModPtr->Types, std::move(SILMod),
ModuleName, PSPs, PrivateDiscriminator,
/*symsToEmit*/ std::nullopt, outModuleHash);
return evaluateOrFatal(file->getASTContext().evaluator, IRGenRequest{desc});
}
void swift::createSwiftModuleObjectFile(SILModule &SILMod, StringRef Buffer,
StringRef OutputPath) {
auto &Ctx = SILMod.getASTContext();
assert(!Ctx.hadError());
IRGenOptions Opts;
// This tool doesn't pass the necessary runtime library path to
// TypeConverter, because this feature isn't needed.
Opts.DisableLegacyTypeInfo = true;
Opts.OutputKind = IRGenOutputKind::ObjectFile;
IRGenerator irgen(Opts, SILMod);
auto targetMachine = irgen.createTargetMachine();
if (!targetMachine) return;
IRGenModule IGM(irgen, std::move(targetMachine), nullptr,
OutputPath, OutputPath, "", "");
initLLVMModule(IGM, SILMod);
auto *Ty = llvm::ArrayType::get(IGM.Int8Ty, Buffer.size());
auto *Data =
llvm::ConstantDataArray::getString(IGM.getLLVMContext(),
Buffer, /*AddNull=*/false);
auto &M = *IGM.getModule();
auto *ASTSym = new llvm::GlobalVariable(M, Ty, /*constant*/ true,
llvm::GlobalVariable::InternalLinkage,
Data, "__Swift_AST");
std::string Section;
switch (IGM.TargetInfo.OutputObjectFormat) {
case llvm::Triple::DXContainer:
case llvm::Triple::GOFF:
case llvm::Triple::SPIRV:
case llvm::Triple::UnknownObjectFormat:
llvm_unreachable("unknown object format");
case llvm::Triple::XCOFF:
case llvm::Triple::COFF: {
SwiftObjectFileFormatCOFF COFF;
Section = COFF.getSectionName(ReflectionSectionKind::swiftast);
break;
}
case llvm::Triple::ELF:
case llvm::Triple::Wasm: {
SwiftObjectFileFormatELF ELF;
Section = ELF.getSectionName(ReflectionSectionKind::swiftast);
break;
}
case llvm::Triple::MachO: {
SwiftObjectFileFormatMachO MachO;
Section = std::string(*MachO.getSegmentName()) + "," +
MachO.getSectionName(ReflectionSectionKind::swiftast).str();
break;
}
}
IGM.addUsedGlobal(ASTSym);
ASTSym->setSection(Section);
ASTSym->setAlignment(llvm::MaybeAlign(serialization::SWIFTMODULE_ALIGNMENT));
IGM.finalize();
::performLLVM(Opts, Ctx.Diags, nullptr, nullptr, IGM.getModule(),
IGM.TargetMachine.get(),
OutputPath, Ctx.getOutputBackend(), Ctx.Stats);
}
bool swift::performLLVM(const IRGenOptions &Opts, ASTContext &Ctx,
llvm::Module *Module, StringRef OutputFilename) {
// Build TargetMachine.
auto TargetMachine = createTargetMachine(Opts, Ctx);
if (!TargetMachine)
return true;
auto *Clang = static_cast<ClangImporter *>(Ctx.getClangModuleLoader());
// Use clang's datalayout.
Module->setDataLayout(Clang->getTargetInfo().getDataLayoutString());
embedBitcode(Module, Opts);
if (::performLLVM(Opts, Ctx.Diags, nullptr, nullptr, Module,
TargetMachine.get(), OutputFilename, Ctx.getOutputBackend(),
Ctx.Stats))
return true;
return false;
}
GeneratedModule OptimizedIRRequest::evaluate(Evaluator &evaluator,
IRGenDescriptor desc) const {
auto *parentMod = desc.getParentModule();
auto &ctx = parentMod->getASTContext();
// Resolve imports for all the source files.
for (auto *file : parentMod->getFiles()) {
if (auto *SF = dyn_cast<SourceFile>(file))
performImportResolution(*SF);
}
bindExtensions(*parentMod);
if (ctx.hadError())
return GeneratedModule::null();
auto irMod = evaluateOrFatal(ctx.evaluator, IRGenRequest{desc});
if (!irMod)
return irMod;
performLLVMOptimizations(desc.Opts, irMod.getModule(),
irMod.getTargetMachine(), desc.out);
return irMod;
}
StringRef SymbolObjectCodeRequest::evaluate(Evaluator &evaluator,
IRGenDescriptor desc) const {
return "";
#if 0
auto &ctx = desc.getParentModule()->getASTContext();
auto mod = cantFail(evaluator(OptimizedIRRequest{desc}));
auto *targetMachine = mod.getTargetMachine();
// Add the passes to emit the LLVM module as object code.
// TODO: Use compileAndWriteLLVM.
legacy::PassManager emitPasses;
emitPasses.add(createTargetTransformInfoWrapperPass(
targetMachine->getTargetIRAnalysis()));
SmallString<0> output;
raw_svector_ostream os(output);
targetMachine->addPassesToEmitFile(emitPasses, os, nullptr, CGFT_ObjectFile);
emitPasses.run(*mod.getModule());
os << '\0';
return ctx.AllocateCopy(output.str());
#endif
}
|