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
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file LICENSE.rst or https://cmake.org/licensing for details. */
#include "cmNinjaNormalTargetGenerator.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <set>
#include <sstream>
#include <unordered_set>
#include <utility>
#include <cm/memory>
#include <cm/optional>
#include <cm/vector>
#include "cmComputeLinkInformation.h"
#include "cmCustomCommand.h" // IWYU pragma: keep
#include "cmCustomCommandGenerator.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorOptions.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalNinjaGenerator.h"
#include "cmLinkLineComputer.h"
#include "cmLinkLineDeviceComputer.h"
#include "cmList.h"
#include "cmLocalCommonGenerator.h"
#include "cmLocalGenerator.h"
#include "cmLocalNinjaGenerator.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmNinjaLinkLineDeviceComputer.h"
#include "cmNinjaTypes.h"
#include "cmOSXBundleGenerator.h"
#include "cmOutputConverter.h"
#include "cmRulePlaceholderExpander.h"
#include "cmSourceFile.h"
#include "cmState.h"
#include "cmStateDirectory.h"
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmValue.h"
cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
cmGeneratorTarget* target)
: cmNinjaTargetGenerator(target)
{
if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
// on Windows the output dir is already needed at compile time
// ensure the directory exists (OutDir test)
for (auto const& config : this->GetConfigNames()) {
this->EnsureDirectoryExists(target->GetDirectory(config));
}
}
this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(target);
this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
}
cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() = default;
void cmNinjaNormalTargetGenerator::Generate(std::string const& config)
{
if (this->GetGeneratorTarget()->GetType() !=
cmStateEnums::INTERFACE_LIBRARY) {
std::string lang = this->GeneratorTarget->GetLinkerLanguage(config);
if (this->TargetLinkLanguage(config).empty()) {
cmSystemTools::Error(
cmStrCat("CMake can not determine linker language for target: ",
this->GetGeneratorTarget()->GetName()));
return;
}
}
// Write the rules for each language.
this->WriteLanguagesRules(config);
// Write the build statements
bool firstForConfig = true;
for (auto const& fileConfig : this->GetConfigNames()) {
if (!this->GetGlobalGenerator()
->GetCrossConfigs(fileConfig)
.count(config)) {
continue;
}
this->WriteObjectBuildStatements(config, fileConfig, firstForConfig);
firstForConfig = false;
}
if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
this->WriteObjectLibStatement(config);
} else if (this->GetGeneratorTarget()->GetType() ==
cmStateEnums::INTERFACE_LIBRARY) {
bool haveCxxModuleSources = false;
if (this->GetGeneratorTarget()->HaveCxx20ModuleSources()) {
haveCxxModuleSources = true;
}
if (!haveCxxModuleSources) {
cmSystemTools::Error(cmStrCat(
"Ninja does not support INTERFACE libraries without C++ module "
"sources as a normal target: ",
this->GetGeneratorTarget()->GetName()));
return;
}
firstForConfig = true;
for (auto const& fileConfig : this->GetConfigNames()) {
if (!this->GetGlobalGenerator()
->GetCrossConfigs(fileConfig)
.count(config)) {
continue;
}
if (haveCxxModuleSources) {
this->WriteCxxModuleLibraryStatement(config, fileConfig,
firstForConfig);
}
firstForConfig = false;
}
} else {
firstForConfig = true;
for (auto const& fileConfig : this->GetConfigNames()) {
if (!this->GetGlobalGenerator()
->GetCrossConfigs(fileConfig)
.count(config)) {
continue;
}
// If this target has cuda language link inputs, and we need to do
// device linking
this->WriteDeviceLinkStatement(config, fileConfig, firstForConfig);
this->WriteLinkStatement(config, fileConfig, firstForConfig);
firstForConfig = false;
}
}
if (this->GetGlobalGenerator()->EnableCrossConfigBuild()) {
this->GetGlobalGenerator()->AddTargetAlias(
this->GetTargetName(), this->GetGeneratorTarget(), "all");
}
// Find ADDITIONAL_CLEAN_FILES
this->AdditionalCleanFiles(config);
}
void cmNinjaNormalTargetGenerator::WriteLanguagesRules(
std::string const& config)
{
#ifdef NINJA_GEN_VERBOSE_FILES
cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
this->GetRulesFileStream()
<< "# Rules for each language for "
<< cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
<< " target " << this->GetTargetName() << "\n\n";
#endif
// Write rules for languages compiled in this target.
{
std::set<std::string> languages;
std::vector<cmSourceFile const*> sourceFiles;
this->GetGeneratorTarget()->GetObjectSources(sourceFiles, config);
if (this->HaveRequiredLanguages(sourceFiles, languages)) {
for (std::string const& language : languages) {
this->WriteLanguageRules(language, config);
}
}
}
// Write rules for languages in BMI-only rules.
{
std::set<std::string> languages;
std::vector<cmSourceFile const*> sourceFiles;
this->GetGeneratorTarget()->GetCxxModuleSources(sourceFiles, config);
if (this->HaveRequiredLanguages(sourceFiles, languages)) {
for (std::string const& language : languages) {
this->WriteLanguageRules(language, config);
}
}
}
}
char const* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
{
switch (this->GetGeneratorTarget()->GetType()) {
case cmStateEnums::STATIC_LIBRARY:
return "static library";
case cmStateEnums::SHARED_LIBRARY:
return "shared library";
case cmStateEnums::MODULE_LIBRARY:
if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
return "CFBundle shared module";
} else {
return "shared module";
}
case cmStateEnums::EXECUTABLE:
return "executable";
default:
return nullptr;
}
}
std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule(
std::string const& config) const
{
return cmStrCat(
this->TargetLinkLanguage(config), '_',
cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()),
"_LINKER__",
cmGlobalNinjaGenerator::EncodeRuleName(
this->GetGeneratorTarget()->GetName()),
'_', config);
}
std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule(
std::string const& config) const
{
return cmStrCat(
this->TargetLinkLanguage(config), '_',
cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()),
"_DEVICE_LINKER__",
cmGlobalNinjaGenerator::EncodeRuleName(
this->GetGeneratorTarget()->GetName()),
'_', config);
}
std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaDeviceRule(
std::string const& config) const
{
return cmStrCat(
this->TargetLinkLanguage(config), "_DEVICE_LINK__",
cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
'_', config);
}
std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaDeviceCompileRule(
std::string const& config) const
{
return cmStrCat(
this->TargetLinkLanguage(config), "_DEVICE_LINK_COMPILE__",
cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
'_', config);
}
std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaFatbinaryRule(
std::string const& config) const
{
return cmStrCat(
this->TargetLinkLanguage(config), "_FATBINARY__",
cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
'_', config);
}
std::string cmNinjaNormalTargetGenerator::TextStubsGeneratorRule(
std::string const& config) const
{
return cmStrCat(
"TEXT_STUBS_GENERATOR__",
cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
'_', config);
}
bool cmNinjaNormalTargetGenerator::CheckUseResponseFileForLibraries(
std::string const& l) const
{
// Check for an explicit setting one way or the other.
std::string const responseVar =
"CMAKE_" + l + "_USE_RESPONSE_FILE_FOR_LIBRARIES";
// If the option is defined, read it's value
if (cmValue val = this->Makefile->GetDefinition(responseVar)) {
return val.IsOn();
}
// Default to true
return true;
}
struct cmNinjaRemoveNoOpCommands
{
bool operator()(std::string const& cmd)
{
return cmd.empty() || cmd[0] == ':';
}
};
void cmNinjaNormalTargetGenerator::WriteNvidiaDeviceLinkRule(
bool useResponseFile, std::string const& config)
{
cmNinjaRule rule(this->LanguageLinkerDeviceRule(config));
if (!this->GetGlobalGenerator()->HasRule(rule.Name)) {
cmRulePlaceholderExpander::RuleVariables vars;
vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
vars.CMTargetType =
cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
.c_str();
vars.CMTargetLabels =
this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
vars.Language = "CUDA";
std::string linker =
this->GetGeneratorTarget()->GetLinkerTool("CUDA", config);
vars.Linker = linker.c_str();
// build response file name
std::string responseFlag = this->GetMakefile()->GetSafeDefinition(
"CMAKE_CUDA_RESPONSE_FILE_DEVICE_LINK_FLAG");
if (!useResponseFile || responseFlag.empty()) {
vars.Objects = "$in";
vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
} else {
rule.RspFile = "$RSP_FILE";
responseFlag += rule.RspFile;
// build response file content
if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
rule.RspContent = "$in";
} else {
rule.RspContent = "$in_newline";
}
// add the link command in the file if necessary
if (this->CheckUseResponseFileForLibraries("CUDA")) {
rule.RspContent += " $LINK_LIBRARIES";
vars.LinkLibraries = "";
} else {
vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
}
vars.Objects = responseFlag.c_str();
}
vars.ObjectDir = "$OBJECT_DIR";
vars.Target = "$TARGET_FILE";
vars.SONameFlag = "$SONAME_FLAG";
vars.TargetSOName = "$SONAME";
vars.TargetPDB = "$TARGET_PDB";
vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
vars.Flags = "$FLAGS";
vars.LinkFlags = "$LINK_FLAGS";
vars.Manifests = "$MANIFESTS";
vars.Config = "$CONFIG";
vars.LanguageCompileFlags = "$LANGUAGE_COMPILE_FLAGS";
std::string launcher;
std::string val = this->GetLocalGenerator()->GetRuleLauncher(
this->GetGeneratorTarget(), "RULE_LAUNCH_LINK", config);
if (cmNonempty(val)) {
launcher = cmStrCat(val, ' ');
}
auto rulePlaceholderExpander =
this->GetLocalGenerator()->CreateRulePlaceholderExpander(
cmBuildStep::Link);
// Rule for linking library/executable.
std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
for (std::string& linkCmd : linkCmds) {
linkCmd = cmStrCat(launcher, linkCmd);
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
linkCmd, vars);
}
// If there is no ranlib the command will be ":". Skip it.
cm::erase_if(linkCmds, cmNinjaRemoveNoOpCommands());
rule.Command =
this->GetLocalGenerator()->BuildCommandLine(linkCmds, config, config);
// Write the linker rule with response file if needed.
rule.Comment =
cmStrCat("Rule for linking ", this->TargetLinkLanguage(config), ' ',
this->GetVisibleTypeName(), '.');
rule.Description =
cmStrCat("Linking ", this->TargetLinkLanguage(config), ' ',
this->GetVisibleTypeName(), " $TARGET_FILE");
rule.Restat = "$RESTAT";
this->GetGlobalGenerator()->AddRule(rule);
}
}
void cmNinjaNormalTargetGenerator::WriteDeviceLinkRules(
std::string const& config)
{
cmMakefile const* mf = this->GetMakefile();
cmNinjaRule rule(this->LanguageLinkerCudaDeviceRule(config));
rule.Command = this->GetLocalGenerator()->BuildCommandLine(
{ cmStrCat(mf->GetRequiredDefinition("CMAKE_CUDA_DEVICE_LINKER"),
" -arch=$ARCH $REGISTER -o=$out $in") },
config, config);
rule.Comment = "Rule for CUDA device linking.";
rule.Description = "Linking CUDA $out";
this->GetGlobalGenerator()->AddRule(rule);
cmRulePlaceholderExpander::RuleVariables vars;
vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
vars.CMTargetType =
cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
vars.CMTargetLabels =
this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
vars.Language = "CUDA";
vars.Object = "$out";
vars.Fatbinary = "$FATBIN";
vars.RegisterFile = "$REGISTER";
vars.LinkFlags = "$LINK_FLAGS";
std::string linker =
this->GetGeneratorTarget()->GetLinkerTool("CUDA", config);
vars.Linker = linker.c_str();
std::string flags = this->GetFlags("CUDA", config);
vars.Flags = flags.c_str();
vars.Config = "$CONFIG";
std::string compileCmd = this->GetMakefile()->GetRequiredDefinition(
"CMAKE_CUDA_DEVICE_LINK_COMPILE");
auto rulePlaceholderExpander =
this->GetLocalGenerator()->CreateRulePlaceholderExpander(
cmBuildStep::Link);
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
compileCmd, vars);
rule.Name = this->LanguageLinkerCudaDeviceCompileRule(config);
rule.Command = this->GetLocalGenerator()->BuildCommandLine({ compileCmd },
config, config);
rule.Comment = "Rule for compiling CUDA device stubs.";
rule.Description = "Compiling CUDA device stub $out";
this->GetGlobalGenerator()->AddRule(rule);
rule.Name = this->LanguageLinkerCudaFatbinaryRule(config);
rule.Command = this->GetLocalGenerator()->BuildCommandLine(
{ cmStrCat(mf->GetRequiredDefinition("CMAKE_CUDA_FATBINARY"),
" -64 -cmdline=--compile-only -compress-all -link "
"--embedded-fatbin=$out $PROFILES") },
config, config);
rule.Comment = "Rule for CUDA fatbinaries.";
rule.Description = "Creating fatbinary $out";
this->GetGlobalGenerator()->AddRule(rule);
}
static void NinjaSafeComment(std::string& comment)
{
// Replace control characters in comments.
cmSystemTools::ReplaceString(comment, "\n", " / ");
cmSystemTools::ReplaceString(comment, "$", "$$");
}
void cmNinjaNormalTargetGenerator::WriteLinkRule(
bool useResponseFile, std::string const& config,
std::vector<std::string> const& preLinkComments,
std::vector<std::string> const& postBuildComments)
{
cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
std::string linkRuleName = this->LanguageLinkerRule(config);
if (!this->GetGlobalGenerator()->HasRule(linkRuleName)) {
cmNinjaRule rule(std::move(linkRuleName));
cmRulePlaceholderExpander::RuleVariables vars;
vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
vars.CMTargetType = cmState::GetTargetTypeName(targetType).c_str();
vars.CMTargetLabels =
this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
std::string linker = this->GetGeneratorTarget()->GetLinkerTool(config);
vars.Linker = linker.c_str();
std::string lang = this->TargetLinkLanguage(config);
vars.Language = lang.c_str();
vars.AIXExports = "$AIX_EXPORTS";
if (!this->GetLocalGenerator()->IsSplitSwiftBuild() &&
this->TargetLinkLanguage(config) == "Swift") {
vars.SwiftLibraryName = "$SWIFT_LIBRARY_NAME";
vars.SwiftModule = "$SWIFT_MODULE";
vars.SwiftModuleName = "$SWIFT_MODULE_NAME";
vars.SwiftSources = "$SWIFT_SOURCES";
vars.Defines = "$DEFINES";
vars.Flags = "$FLAGS";
vars.Includes = "$INCLUDES";
}
std::string responseFlag;
std::string cmakeVarLang =
cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
if (this->GeneratorTarget->HasLinkDependencyFile(config)) {
auto DepFileFormat = this->GetMakefile()->GetDefinition(
cmStrCat(cmakeVarLang, "_LINKER_DEPFILE_FORMAT"));
rule.DepType = DepFileFormat;
rule.DepFile = "$DEP_FILE";
}
// build response file name
std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
if (flag) {
responseFlag = *flag;
} else {
responseFlag = "@";
}
if (!useResponseFile || responseFlag.empty()) {
vars.Objects = "$in";
vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
} else {
rule.RspFile = "$RSP_FILE";
responseFlag += rule.RspFile;
// build response file content
if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
rule.RspContent = "$in";
} else {
rule.RspContent = "$in_newline";
}
// If libraries in rsp is enable
if (this->CheckUseResponseFileForLibraries(lang)) {
rule.RspContent += " $LINK_PATH $LINK_LIBRARIES";
vars.LinkLibraries = "";
} else {
vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
}
if (!this->GetLocalGenerator()->IsSplitSwiftBuild() &&
this->TargetLinkLanguage(config) == "Swift") {
vars.SwiftSources = responseFlag.c_str();
} else {
vars.Objects = responseFlag.c_str();
}
}
vars.ObjectDir = "$OBJECT_DIR";
vars.Target = "$TARGET_FILE";
vars.SONameFlag = "$SONAME_FLAG";
vars.TargetSOName = "$SONAME";
vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
vars.TargetPDB = "$TARGET_PDB";
// Setup the target version.
std::string targetVersionMajor;
std::string targetVersionMinor;
{
std::ostringstream majorStream;
std::ostringstream minorStream;
int major;
int minor;
this->GetGeneratorTarget()->GetTargetVersion(major, minor);
majorStream << major;
minorStream << minor;
targetVersionMajor = majorStream.str();
targetVersionMinor = minorStream.str();
}
vars.TargetVersionMajor = targetVersionMajor.c_str();
vars.TargetVersionMinor = targetVersionMinor.c_str();
vars.Flags = "$FLAGS";
vars.LinkFlags = "$LINK_FLAGS";
vars.Manifests = "$MANIFESTS";
vars.Config = "$CONFIG";
std::string langFlags;
if (targetType != cmStateEnums::EXECUTABLE) {
langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
vars.LanguageCompileFlags = langFlags.c_str();
}
std::string linkerLauncher = this->GetLinkerLauncher(config);
if (cmNonempty(linkerLauncher)) {
vars.Launcher = linkerLauncher.c_str();
}
std::string launcher;
std::string val = this->GetLocalGenerator()->GetRuleLauncher(
this->GetGeneratorTarget(), "RULE_LAUNCH_LINK", config);
if (cmNonempty(val)) {
launcher = cmStrCat(val, ' ');
}
auto rulePlaceholderExpander =
this->GetLocalGenerator()->CreateRulePlaceholderExpander(
cmBuildStep::Link);
// Rule for linking library/executable.
std::vector<std::string> linkCmds = this->ComputeLinkCmd(config);
for (std::string& linkCmd : linkCmds) {
linkCmd = cmStrCat(launcher, linkCmd);
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
linkCmd, vars);
}
// If there is no ranlib the command will be ":". Skip it.
cm::erase_if(linkCmds, cmNinjaRemoveNoOpCommands());
linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
linkCmds.emplace_back("$POST_BUILD");
rule.Command =
this->GetLocalGenerator()->BuildCommandLine(linkCmds, config, config);
// Write the linker rule with response file if needed.
rule.Comment =
cmStrCat("Rule for linking ", this->TargetLinkLanguage(config), ' ',
this->GetVisibleTypeName(), '.');
char const* presep = "";
char const* postsep = "";
auto prelink = cmJoin(preLinkComments, "; ");
NinjaSafeComment(prelink);
if (!prelink.empty()) {
presep = "; ";
}
auto postbuild = cmJoin(postBuildComments, "; ");
NinjaSafeComment(postbuild);
if (!postbuild.empty()) {
postsep = "; ";
}
rule.Description = cmStrCat(
prelink, presep, "Linking ", this->TargetLinkLanguage(config), ' ',
this->GetVisibleTypeName(), " $TARGET_FILE", postsep, postbuild);
rule.Restat = "$RESTAT";
this->GetGlobalGenerator()->AddRule(rule);
}
auto const tgtNames = this->TargetNames(config);
if (tgtNames.Output != tgtNames.Real &&
!this->GetGeneratorTarget()->IsFrameworkOnApple()) {
std::string cmakeCommand =
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
if (targetType == cmStateEnums::EXECUTABLE) {
cmNinjaRule rule("CMAKE_SYMLINK_EXECUTABLE");
{
std::vector<std::string> cmd;
cmd.push_back(cmakeCommand + " -E cmake_symlink_executable $in $out");
cmd.emplace_back("$POST_BUILD");
rule.Command =
this->GetLocalGenerator()->BuildCommandLine(cmd, config, config);
}
rule.Description = "Creating executable symlink $out";
rule.Comment = "Rule for creating executable symlink.";
this->GetGlobalGenerator()->AddRule(rule);
} else {
cmNinjaRule rule("CMAKE_SYMLINK_LIBRARY");
{
std::vector<std::string> cmd;
cmd.push_back(cmakeCommand +
" -E cmake_symlink_library $in $SONAME $out");
cmd.emplace_back("$POST_BUILD");
rule.Command =
this->GetLocalGenerator()->BuildCommandLine(cmd, config, config);
}
rule.Description = "Creating library symlink $out";
rule.Comment = "Rule for creating library symlink.";
this->GetGlobalGenerator()->AddRule(rule);
}
}
if (this->GetGeneratorTarget()->IsApple() &&
this->GetGeneratorTarget()->HasImportLibrary(config)) {
cmNinjaRule rule(this->TextStubsGeneratorRule(config));
rule.Comment = cmStrCat("Rule for generating text-based stubs for ",
this->GetVisibleTypeName(), '.');
rule.Description = "Creating text-based stubs $out";
std::string cmd =
this->GetMakefile()->GetDefinition("CMAKE_CREATE_TEXT_STUBS");
auto rulePlaceholderExpander =
this->GetLocalGenerator()->CreateRulePlaceholderExpander();
cmRulePlaceholderExpander::RuleVariables vars;
vars.Target = "$in";
rulePlaceholderExpander->SetTargetImpLib("$out");
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
cmd, vars);
rule.Command =
this->GetLocalGenerator()->BuildCommandLine({ cmd }, config, config);
this->GetGlobalGenerator()->AddRule(rule);
if (tgtNames.ImportOutput != tgtNames.ImportReal &&
!this->GetGeneratorTarget()->IsFrameworkOnApple()) {
cmNinjaRule slRule("CMAKE_SYMLINK_IMPORT_LIBRARY");
{
std::string cmakeCommand =
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
std::string slCmd =
cmStrCat(cmakeCommand, " -E cmake_symlink_library $in $SONAME $out");
slRule.Command = this->GetLocalGenerator()->BuildCommandLine(
{ slCmd }, config, config);
}
slRule.Description = "Creating import library symlink $out";
slRule.Comment = "Rule for creating import library symlink.";
this->GetGlobalGenerator()->AddRule(slRule);
}
}
}
std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
{
cmList linkCmds;
// this target requires separable cuda compilation
// now build the correct command depending on if the target is
// an executable or a dynamic library.
switch (this->GetGeneratorTarget()->GetType()) {
case cmStateEnums::STATIC_LIBRARY:
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY: {
linkCmds.assign(
this->GetMakefile()->GetDefinition("CMAKE_CUDA_DEVICE_LINK_LIBRARY"));
} break;
case cmStateEnums::EXECUTABLE: {
linkCmds.assign(this->GetMakefile()->GetDefinition(
"CMAKE_CUDA_DEVICE_LINK_EXECUTABLE"));
} break;
default:
break;
}
return std::move(linkCmds.data());
}
std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd(
std::string const& config)
{
cmList linkCmds;
cmMakefile* mf = this->GetMakefile();
{
// If we have a rule variable prefer it. In the case of static libraries
// this occurs when things like IPO is enabled, and we need to use the
// CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
this->TargetLinkLanguage(config), config);
cmValue linkCmd = mf->GetDefinition(linkCmdVar);
if (linkCmd) {
std::string linkCmdStr = *linkCmd;
if (this->GetGeneratorTarget()->HasImplibGNUtoMS(config)) {
std::string ruleVar =
cmStrCat("CMAKE_", this->GeneratorTarget->GetLinkerLanguage(config),
"_GNUtoMS_RULE");
if (cmValue rule = this->Makefile->GetDefinition(ruleVar)) {
linkCmdStr += *rule;
}
}
linkCmds.assign(linkCmdStr);
if (this->UseLWYU) {
cmValue lwyuCheck = mf->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
if (lwyuCheck) {
std::string cmakeCommand = cmStrCat(
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
" -E __run_co_compile --lwyu=");
cmakeCommand +=
this->GetLocalGenerator()->EscapeForShell(*lwyuCheck);
std::string targetOutputReal =
this->ConvertToNinjaPath(this->GetGeneratorTarget()->GetFullPath(
config, cmStateEnums::RuntimeBinaryArtifact,
/*realname=*/true));
cmakeCommand += cmStrCat(" --source=", targetOutputReal);
linkCmds.push_back(std::move(cmakeCommand));
}
}
return std::move(linkCmds.data());
}
}
switch (this->GetGeneratorTarget()->GetType()) {
case cmStateEnums::STATIC_LIBRARY: {
// We have archive link commands set. First, delete the existing archive.
{
std::string cmakeCommand =
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
linkCmds.push_back(cmakeCommand + " -E rm -f $TARGET_FILE");
}
// TODO: Use ARCHIVE_APPEND for archives over a certain size.
{
std::string linkCmdVar = cmStrCat(
"CMAKE_", this->TargetLinkLanguage(config), "_ARCHIVE_CREATE");
linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
linkCmdVar, this->TargetLinkLanguage(config), config);
std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
linkCmds.append(linkCmd);
}
{
std::string linkCmdVar = cmStrCat(
"CMAKE_", this->TargetLinkLanguage(config), "_ARCHIVE_FINISH");
linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
linkCmdVar, this->TargetLinkLanguage(config), config);
std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
linkCmds.append(linkCmd);
}
#ifdef __APPLE__
// On macOS ranlib truncates the fractional part of the static archive
// file modification time. If the archive and at least one contained
// object file were created within the same second this will make look
// the archive older than the object file. On subsequent ninja runs this
// leads to re-archiving and updating dependent targets.
// As a work-around we touch the archive after ranlib (see #19222).
{
std::string cmakeCommand =
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
linkCmds.push_back(cmakeCommand + " -E touch $TARGET_FILE");
}
#endif
} break;
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::EXECUTABLE:
break;
default:
assert(false && "Unexpected target type");
}
return std::move(linkCmds.data());
}
void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement(
std::string const& config, std::string const& fileConfig,
bool firstForConfig)
{
cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
if (!globalGen->GetLanguageEnabled("CUDA")) {
return;
}
cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
bool requiresDeviceLinking = requireDeviceLinking(
*this->GeneratorTarget, *this->GetLocalGenerator(), config);
if (!requiresDeviceLinking) {
return;
}
// First and very important step is to make sure while inside this
// step our link language is set to CUDA
std::string const& objExt =
this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
std::string targetOutputDir =
this->GetLocalGenerator()->MaybeRelativeToTopBinDir(
cmStrCat(genTarget->GetSupportDirectory(),
globalGen->ConfigDirectory(config), '/'));
targetOutputDir = globalGen->ExpandCFGIntDir(targetOutputDir, config);
std::string targetOutputReal =
this->ConvertToNinjaPath(targetOutputDir + "cmake_device_link" + objExt);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
}
this->DeviceLinkObject = targetOutputReal;
// Write comments.
cmGlobalNinjaGenerator::WriteDivider(this->GetCommonFileStream());
this->GetCommonFileStream()
<< "# Device Link build statements for "
<< cmState::GetTargetTypeName(genTarget->GetType()) << " target "
<< this->GetTargetName() << "\n\n";
if (this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID") == "Clang") {
std::string architecturesStr =
this->GeneratorTarget->GetSafeProperty("CUDA_ARCHITECTURES");
if (cmIsOff(architecturesStr)) {
this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
"CUDA_SEPARABLE_COMPILATION on Clang "
"requires CUDA_ARCHITECTURES to be set.");
return;
}
this->WriteDeviceLinkRules(config);
this->WriteDeviceLinkStatements(config, cmList{ architecturesStr },
targetOutputReal);
} else {
this->WriteNvidiaDeviceLinkStatement(config, fileConfig, targetOutputDir,
targetOutputReal);
}
}
void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatements(
std::string const& config, std::vector<std::string> const& architectures,
std::string const& output)
{
// Ensure there are no duplicates.
cmNinjaDeps const explicitDeps = [&]() -> std::vector<std::string> {
std::unordered_set<std::string> depsSet;
cmNinjaDeps const linkDeps =
this->ComputeLinkDeps(this->TargetLinkLanguage(config), config, true);
cmNinjaDeps const objects = this->GetObjects(config);
depsSet.insert(linkDeps.begin(), linkDeps.end());
depsSet.insert(objects.begin(), objects.end());
std::vector<std::string> deps;
std::copy(depsSet.begin(), depsSet.end(), std::back_inserter(deps));
return deps;
}();
cmGlobalNinjaGenerator* globalGen{ this->GetGlobalGenerator() };
std::string const objectDir =
cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
globalGen->ConfigDirectory(config));
std::string const ninjaOutputDir = this->ConvertToNinjaPath(objectDir);
cmNinjaBuild fatbinary(this->LanguageLinkerCudaFatbinaryRule(config));
// Link device code for each architecture.
for (std::string const& architectureKind : architectures) {
// Clang always generates real code, so strip the specifier.
std::string const architecture =
architectureKind.substr(0, architectureKind.find('-'));
std::string const cubin =
cmStrCat(ninjaOutputDir, "/sm_", architecture, ".cubin");
cmNinjaBuild dlink(this->LanguageLinkerCudaDeviceRule(config));
dlink.ExplicitDeps = explicitDeps;
dlink.Outputs = { cubin };
dlink.Variables["ARCH"] = cmStrCat("sm_", architecture);
// The generated register file contains macros that when expanded register
// the device routines. Because the routines are the same for all
// architectures the register file will be the same too. Thus generate it
// only on the first invocation to reduce overhead.
if (fatbinary.ExplicitDeps.empty()) {
dlink.Variables["REGISTER"] = cmStrCat(
"--register-link-binaries=", ninjaOutputDir, "/cmake_cuda_register.h");
}
fatbinary.Variables["PROFILES"] +=
cmStrCat(" -im=profile=sm_", architecture, ",file=", cubin);
fatbinary.ExplicitDeps.emplace_back(cubin);
globalGen->WriteBuild(this->GetCommonFileStream(), dlink);
}
// Combine all architectures into a single fatbinary.
fatbinary.Outputs = { cmStrCat(ninjaOutputDir, "/cmake_cuda_fatbin.h") };
globalGen->WriteBuild(this->GetCommonFileStream(), fatbinary);
// Compile the stub that registers the kernels and contains the fatbinaries.
cmLocalNinjaGenerator* localGen{ this->GetLocalGenerator() };
cmNinjaBuild dcompile(this->LanguageLinkerCudaDeviceCompileRule(config));
dcompile.Outputs = { output };
dcompile.ExplicitDeps = { cmStrCat(ninjaOutputDir, "/cmake_cuda_fatbin.h") };
dcompile.Variables["FATBIN"] = localGen->ConvertToOutputFormat(
cmStrCat(objectDir, "/cmake_cuda_fatbin.h"), cmOutputConverter::SHELL);
dcompile.Variables["REGISTER"] = localGen->ConvertToOutputFormat(
cmStrCat(objectDir, "/cmake_cuda_register.h"), cmOutputConverter::SHELL);
cmNinjaLinkLineDeviceComputer linkLineComputer(
localGen, localGen->GetStateSnapshot().GetDirectory(), globalGen);
linkLineComputer.SetUseNinjaMulti(globalGen->IsMultiConfig());
// Link libraries and paths are only used during the final executable/library
// link.
std::string frameworkPath;
std::string linkPath;
std::string linkLibs;
localGen->GetDeviceLinkFlags(linkLineComputer, config, linkLibs,
dcompile.Variables["LINK_FLAGS"], frameworkPath,
linkPath, this->GetGeneratorTarget());
globalGen->WriteBuild(this->GetCommonFileStream(), dcompile);
}
void cmNinjaNormalTargetGenerator::WriteNvidiaDeviceLinkStatement(
std::string const& config, std::string const& fileConfig,
std::string const& outputDir, std::string const& output)
{
cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
std::string targetOutputImplib = this->ConvertToNinjaPath(
genTarget->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
if (config != fileConfig) {
std::string targetOutputFileConfigDir =
this->GetLocalGenerator()->MaybeRelativeToTopBinDir(
cmStrCat(genTarget->GetSupportDirectory(),
globalGen->ConfigDirectory(config), '/'));
targetOutputFileConfigDir =
globalGen->ExpandCFGIntDir(outputDir, fileConfig);
if (outputDir == targetOutputFileConfigDir) {
return;
}
if (!genTarget->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
.empty() &&
!genTarget
->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
.empty() &&
targetOutputImplib ==
this->ConvertToNinjaPath(genTarget->GetFullPath(
fileConfig, cmStateEnums::ImportLibraryArtifact))) {
return;
}
}
// Compute the comment.
cmNinjaBuild build(this->LanguageLinkerDeviceRule(config));
build.Comment =
cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', output);
cmNinjaVars& vars = build.Variables;
// Compute outputs.
build.Outputs.push_back(output);
// Compute specific libraries to link with.
build.ExplicitDeps = this->GetObjects(config);
build.ImplicitDeps =
this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
std::string frameworkPath;
std::string linkPath;
std::string createRule =
genTarget->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
vars["TARGET_FILE"] =
localGen.ConvertToOutputFormat(output, cmOutputConverter::SHELL);
cmNinjaLinkLineDeviceComputer linkLineComputer(
this->GetLocalGenerator(),
this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(), globalGen);
linkLineComputer.SetUseNinjaMulti(globalGen->IsMultiConfig());
localGen.GetDeviceLinkFlags(linkLineComputer, config, vars["LINK_LIBRARIES"],
vars["LINK_FLAGS"], frameworkPath, linkPath,
genTarget);
this->addPoolNinjaVariable("JOB_POOL_LINK", genTarget, vars);
vars["MANIFESTS"] = this->GetManifests(config);
vars["LINK_PATH"] = frameworkPath + linkPath;
// Compute language specific link flags.
std::string langFlags;
localGen.AddLanguageFlagsForLinking(langFlags, genTarget, "CUDA", config);
vars["LANGUAGE_COMPILE_FLAGS"] = langFlags;
auto const tgtNames = this->TargetNames(config);
if (genTarget->HasSOName(config) ||
genTarget->IsArchivedAIXSharedLibrary()) {
vars["SONAME_FLAG"] =
this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage(config));
vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
cmOutputConverter::SHELL);
if (genTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
std::string install_dir =
this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(config);
if (!install_dir.empty()) {
vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
install_dir, cmOutputConverter::SHELL);
}
}
}
if (!tgtNames.ImportLibrary.empty()) {
std::string const impLibPath = localGen.ConvertToOutputFormat(
targetOutputImplib, cmOutputConverter::SHELL);
vars["TARGET_IMPLIB"] = impLibPath;
this->EnsureParentDirectoryExists(targetOutputImplib);
}
std::string const objPath =
cmStrCat(this->GetGeneratorTarget()->GetSupportDirectory(),
globalGen->ConfigDirectory(config));
vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
this->EnsureDirectoryExists(objPath);
this->SetMsvcTargetPdbVariable(vars, config);
std::string& linkLibraries = vars["LINK_LIBRARIES"];
std::string& link_path = vars["LINK_PATH"];
if (globalGen->IsGCCOnWindows()) {
// ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
std::replace(link_path.begin(), link_path.end(), '\\', '/');
}
// Device linking currently doesn't support response files so
// do not check if the user has explicitly forced a response file.
int const commandLineLengthLimit =
static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
globalGen->GetRuleCmdLength(build.Rule);
build.RspFile = this->ConvertToNinjaPath(
cmStrCat("CMakeFiles/", genTarget->GetName(),
globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
// Gather order-only dependencies.
this->GetLocalGenerator()->AppendTargetDepends(
this->GetGeneratorTarget(), build.OrderOnlyDeps, config, config,
DependOnTargetArtifact);
// Write the build statement for this target.
bool usedResponseFile = false;
globalGen->WriteBuild(this->GetCommonFileStream(), build,
commandLineLengthLimit, &usedResponseFile);
this->WriteNvidiaDeviceLinkRule(usedResponseFile, config);
}
void cmNinjaNormalTargetGenerator::WriteLinkStatement(
std::string const& config, std::string const& fileConfig,
bool firstForConfig)
{
cmMakefile* mf = this->GetMakefile();
cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
cmGeneratorTarget* gt = this->GetGeneratorTarget();
std::string targetOutput = this->ConvertToNinjaPath(gt->GetFullPath(config));
std::string targetOutputReal = this->ConvertToNinjaPath(
gt->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
/*realname=*/true));
std::string targetOutputImplib = this->ConvertToNinjaPath(
gt->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
if (config != fileConfig) {
if (targetOutput ==
this->ConvertToNinjaPath(gt->GetFullPath(fileConfig))) {
return;
}
if (targetOutputReal ==
this->ConvertToNinjaPath(
gt->GetFullPath(fileConfig, cmStateEnums::RuntimeBinaryArtifact,
/*realname=*/true))) {
return;
}
if (!gt->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
.empty() &&
!gt->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
.empty() &&
targetOutputImplib ==
this->ConvertToNinjaPath(gt->GetFullPath(
fileConfig, cmStateEnums::ImportLibraryArtifact))) {
return;
}
}
auto const tgtNames = this->TargetNames(config);
if (gt->IsAppBundleOnApple()) {
// Create the app bundle
std::string outpath = gt->GetDirectory(config);
this->OSXBundleGenerator->CreateAppBundle(tgtNames.Output, outpath,
config);
// Calculate the output path
targetOutput = cmStrCat(outpath, '/', tgtNames.Output);
targetOutput = this->ConvertToNinjaPath(targetOutput);
targetOutputReal = cmStrCat(outpath, '/', tgtNames.Real);
targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
} else if (gt->IsFrameworkOnApple()) {
// Create the library framework.
cmOSXBundleGenerator::SkipParts bundleSkipParts;
if (globalGen->GetName() == "Ninja Multi-Config") {
auto const postFix = this->GeneratorTarget->GetFilePostfix(config);
// Skip creating Info.plist when there are multiple configurations, and
// the current configuration has a postfix. The non-postfix configuration
// Info.plist can be used by all the other configurations.
if (!postFix.empty()) {
bundleSkipParts.InfoPlist = true;
}
}
if (gt->HasImportLibrary(config)) {
bundleSkipParts.TextStubs = false;
}
this->OSXBundleGenerator->CreateFramework(
tgtNames.Output, gt->GetDirectory(config), config, bundleSkipParts);
} else if (gt->IsCFBundleOnApple()) {
// Create the core foundation bundle.
this->OSXBundleGenerator->CreateCFBundle(tgtNames.Output,
gt->GetDirectory(config), config);
}
// Write comments.
cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
cmStateEnums::TargetType const targetType = gt->GetType();
this->GetImplFileStream(fileConfig)
<< "# Link build statements for " << cmState::GetTargetTypeName(targetType)
<< " target " << this->GetTargetName() << "\n\n";
cmNinjaBuild linkBuild(this->LanguageLinkerRule(config));
cmNinjaVars& vars = linkBuild.Variables;
if (this->GeneratorTarget->HasLinkDependencyFile(config)) {
this->AddDepfileBinding(vars,
this->ConvertToNinjaPath(
this->GetLocalGenerator()->GetLinkDependencyFile(
this->GeneratorTarget, config)));
}
// Compute the comment.
linkBuild.Comment =
cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', targetOutputReal);
// Compute outputs.
linkBuild.Outputs.push_back(targetOutputReal);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
}
// If we can't split the Swift build model (CMP0157 is OLD or unset), fall
// back on the old one-step "build/link" logic.
if (!this->GetLocalGenerator()->IsSplitSwiftBuild() &&
this->TargetLinkLanguage(config) == "Swift") {
vars["SWIFT_LIBRARY_NAME"] = [this, config]() -> std::string {
cmGeneratorTarget::Names targetNames =
this->GetGeneratorTarget()->GetLibraryNames(config);
return targetNames.Base;
}();
vars["SWIFT_MODULE_NAME"] = gt->GetSwiftModuleName();
vars["SWIFT_MODULE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
this->ConvertToNinjaPath(gt->GetSwiftModulePath(config)),
cmOutputConverter::SHELL);
vars["SWIFT_SOURCES"] = [this, config]() -> std::string {
std::vector<cmSourceFile const*> sourceFiles;
std::stringstream oss;
this->GetGeneratorTarget()->GetObjectSources(sourceFiles, config);
cmLocalGenerator const* LocalGen = this->GetLocalGenerator();
for (auto const& source : sourceFiles) {
std::string const sourcePath = source->GetLanguage() == "Swift"
? this->GetCompiledSourceNinjaPath(source)
: this->GetObjectFilePath(source, config);
oss << " "
<< LocalGen->ConvertToOutputFormat(sourcePath,
cmOutputConverter::SHELL);
}
return oss.str();
}();
// Since we do not perform object builds, compute the
// defines/flags/includes here so that they can be passed along
// appropriately.
vars["DEFINES"] = this->GetDefines("Swift", config);
vars["FLAGS"] = this->GetFlags("Swift", config);
vars["INCLUDES"] = this->GetIncludes("Swift", config);
this->GenerateSwiftOutputFileMap(config, vars["FLAGS"]);
// Compute specific libraries to link with.
std::vector<cmSourceFile const*> sources;
gt->GetObjectSources(sources, config);
for (auto const& source : sources) {
if (source->GetLanguage() == "Swift") {
linkBuild.Outputs.push_back(
this->ConvertToNinjaPath(this->GetObjectFilePath(source, config)));
linkBuild.ExplicitDeps.emplace_back(
this->GetCompiledSourceNinjaPath(source));
} else {
linkBuild.ExplicitDeps.emplace_back(
this->GetObjectFilePath(source, config));
}
}
if (targetType != cmStateEnums::EXECUTABLE ||
gt->IsExecutableWithExports()) {
linkBuild.Outputs.push_back(vars["SWIFT_MODULE"]);
}
} else {
linkBuild.ExplicitDeps = this->GetObjects(config);
}
std::vector<std::string> extraISPCObjects =
this->GetGeneratorTarget()->GetGeneratedISPCObjects(config);
std::transform(extraISPCObjects.begin(), extraISPCObjects.end(),
std::back_inserter(linkBuild.ExplicitDeps),
this->MapToNinjaPath());
linkBuild.ImplicitDeps =
this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
if (!this->DeviceLinkObject.empty()) {
linkBuild.ExplicitDeps.push_back(this->DeviceLinkObject);
}
std::string frameworkPath;
std::string linkPath;
std::string createRule =
gt->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
vars["TARGET_FILE"] =
localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
std::unique_ptr<cmLinkLineComputer> linkLineComputer =
globalGen->CreateLinkLineComputer(
this->GetLocalGenerator(),
this->GetLocalGenerator()->GetStateSnapshot().GetDirectory());
linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
linkLineComputer->SetUseNinjaMulti(globalGen->IsMultiConfig());
localGen.GetTargetFlags(linkLineComputer.get(), config,
vars["LINK_LIBRARIES"], vars["FLAGS"],
vars["LINK_FLAGS"], frameworkPath, linkPath, gt);
localGen.AppendDependencyInfoLinkerFlags(vars["LINK_FLAGS"], gt, config,
this->TargetLinkLanguage(config));
// Add OS X version flags, if any.
if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
this->AppendOSXVerFlag(vars["LINK_FLAGS"],
this->TargetLinkLanguage(config), "COMPATIBILITY",
true);
this->AppendOSXVerFlag(vars["LINK_FLAGS"],
this->TargetLinkLanguage(config), "CURRENT", false);
}
this->addPoolNinjaVariable("JOB_POOL_LINK", gt, vars);
this->UseLWYU = this->GetLocalGenerator()->AppendLWYUFlags(
vars["LINK_FLAGS"], this->GetGeneratorTarget(),
this->TargetLinkLanguage(config));
vars["MANIFESTS"] = this->GetManifests(config);
vars["AIX_EXPORTS"] = this->GetAIXExports(config);
vars["LINK_PATH"] = frameworkPath + linkPath;
vars["CONFIG"] = config;
// Compute architecture specific link flags. Yes, these go into a different
// variable for executables, probably due to a mistake made when duplicating
// code between the Makefile executable and library generators.
if (targetType == cmStateEnums::EXECUTABLE) {
std::string t = vars["FLAGS"];
localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
config);
vars["FLAGS"] = t;
} else {
std::string t = vars["ARCH_FLAGS"];
localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
config);
vars["ARCH_FLAGS"] = t;
t.clear();
localGen.AddLanguageFlagsForLinking(
t, gt, this->TargetLinkLanguage(config), config);
vars["LANGUAGE_COMPILE_FLAGS"] = t;
}
if (gt->HasSOName(config) || gt->IsArchivedAIXSharedLibrary()) {
vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage(config));
vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
cmOutputConverter::SHELL);
if (targetType == cmStateEnums::SHARED_LIBRARY) {
std::string install_dir = gt->GetInstallNameDirForBuildTree(config);
if (!install_dir.empty()) {
vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
install_dir, cmOutputConverter::SHELL);
}
}
}
cmGlobalNinjaGenerator::CCOutputs byproducts(this->GetGlobalGenerator());
if (!gt->IsApple() && !tgtNames.ImportLibrary.empty()) {
std::string const impLibPath = localGen.ConvertToOutputFormat(
targetOutputImplib, cmOutputConverter::SHELL);
vars["TARGET_IMPLIB"] = impLibPath;
this->EnsureParentDirectoryExists(targetOutputImplib);
if (gt->HasImportLibrary(config)) {
// Some linkers may update a binary without touching its import lib.
byproducts.ExplicitOuts.emplace_back(targetOutputImplib);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(
targetOutputImplib);
}
}
}
if (!this->SetMsvcTargetPdbVariable(vars, config)) {
// It is common to place debug symbols at a specific place,
// so we need a plain target name in the rule available.
cmGeneratorTarget::NameComponents const& components =
gt->GetFullNameComponents(config);
std::string dbg_suffix = ".dbg";
// TODO: Where to document?
if (cmValue d = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
dbg_suffix = *d;
}
vars["TARGET_PDB"] = components.base + components.suffix + dbg_suffix;
}
std::string const objPath =
cmStrCat(gt->GetSupportDirectory(), globalGen->ConfigDirectory(config));
vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
this->EnsureDirectoryExists(objPath);
std::string& linkLibraries = vars["LINK_LIBRARIES"];
std::string& link_path = vars["LINK_PATH"];
if (globalGen->IsGCCOnWindows()) {
// ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
std::replace(link_path.begin(), link_path.end(), '\\', '/');
}
std::vector<cmCustomCommand> const* cmdLists[3] = {
>->GetPreBuildCommands(), >->GetPreLinkCommands(),
>->GetPostBuildCommands()
};
std::vector<std::string> preLinkComments;
std::vector<std::string> postBuildComments;
std::vector<std::string> preLinkCmdLines;
std::vector<std::string> postBuildCmdLines;
std::vector<std::string>* cmdComments[3] = { &preLinkComments,
&preLinkComments,
&postBuildComments };
std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
&preLinkCmdLines,
&postBuildCmdLines };
cmGeneratorExpression ge(*this->GetLocalGenerator()->GetCMakeInstance());
for (unsigned i = 0; i != 3; ++i) {
for (cmCustomCommand const& cc : *cmdLists[i]) {
if (config == fileConfig ||
this->GetLocalGenerator()->HasUniqueByproducts(cc.GetByproducts(),
cc.GetBacktrace())) {
cmCustomCommandGenerator ccg(cc, fileConfig, this->GetLocalGenerator(),
true, config);
localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
if (cc.GetComment()) {
auto cge = ge.Parse(cc.GetComment());
cmdComments[i]->emplace_back(
cge->Evaluate(this->GetLocalGenerator(), config));
}
std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
byproducts.Add(ccByproducts);
std::transform(
ccByproducts.begin(), ccByproducts.end(),
std::back_inserter(globalGen->GetByproductsForCleanTarget()),
this->MapToNinjaPath());
}
}
}
// If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
// for the link commands.
if (!preLinkCmdLines.empty()) {
std::string const homeOutDir = localGen.ConvertToOutputFormat(
localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
preLinkCmdLines.push_back("cd " + homeOutDir);
}
// maybe create .def file from list of objects
cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
gt->GetModuleDefinitionInfo(config);
if (mdi && mdi->DefFileGenerated) {
std::string cmakeCommand =
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
std::string cmd =
cmStrCat(cmakeCommand, " -E __create_def ",
this->GetLocalGenerator()->ConvertToOutputFormat(
mdi->DefFile, cmOutputConverter::SHELL),
' ');
std::string obj_list_file = mdi->DefFile + ".objs";
cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
obj_list_file, cmOutputConverter::SHELL);
cmValue nm_executable = this->GetMakefile()->GetDefinition("CMAKE_NM");
if (cmNonempty(nm_executable)) {
cmd += " --nm=";
cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
*nm_executable, cmOutputConverter::SHELL);
}
preLinkCmdLines.push_back(std::move(cmd));
// create a list of obj files for the -E __create_def to read
cmGeneratedFileStream fout(obj_list_file);
if (mdi->WindowsExportAllSymbols) {
cmNinjaDeps objs = this->GetObjects(config);
for (std::string const& obj : objs) {
if (cmHasLiteralSuffix(obj, ".obj")) {
fout << obj << "\n";
}
}
}
for (cmSourceFile const* src : mdi->Sources) {
fout << src->GetFullPath() << "\n";
}
}
vars["PRE_LINK"] = localGen.BuildCommandLine(
preLinkCmdLines, config, fileConfig, "pre-link", this->GeneratorTarget);
std::string postBuildCmdLine =
localGen.BuildCommandLine(postBuildCmdLines, config, fileConfig,
"post-build", this->GeneratorTarget);
cmNinjaVars symlinkVars;
bool const symlinkNeeded =
(targetOutput != targetOutputReal && !gt->IsFrameworkOnApple() &&
!gt->IsArchivedAIXSharedLibrary());
if (!symlinkNeeded) {
vars["POST_BUILD"] = postBuildCmdLine;
} else {
vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
symlinkVars["POST_BUILD"] = postBuildCmdLine;
}
std::string cmakeVarLang =
cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
// build response file name
std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
bool const lang_supports_response =
!(this->TargetLinkLanguage(config) == "RC" ||
(this->TargetLinkLanguage(config) == "CUDA" && !flag));
int commandLineLengthLimit = -1;
if (!lang_supports_response || !this->ForceResponseFile()) {
commandLineLengthLimit =
static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
globalGen->GetRuleCmdLength(linkBuild.Rule);
}
linkBuild.RspFile = this->ConvertToNinjaPath(
cmStrCat("CMakeFiles/", gt->GetName(),
globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
// Gather order-only dependencies.
this->GetLocalGenerator()->AppendTargetDepends(
gt, linkBuild.OrderOnlyDeps, config, fileConfig, DependOnTargetArtifact);
// Add order-only dependencies on versioning symlinks of shared libs we link.
// If our target is not producing a runtime binary, it doesn't need the
// symlinks (anything that links to the target might, but that consumer will
// get its own order-only dependency).
if (!gt->IsDLLPlatform() && gt->IsRuntimeBinary()) {
if (cmComputeLinkInformation* cli = gt->GetLinkInformation(config)) {
for (auto const& item : cli->GetItems()) {
if (item.Target &&
item.Target->GetType() == cmStateEnums::SHARED_LIBRARY &&
!item.Target->IsFrameworkOnApple()) {
std::string const& lib =
this->ConvertToNinjaPath(item.Target->GetFullPath(config));
if (std::find(linkBuild.ImplicitDeps.begin(),
linkBuild.ImplicitDeps.end(),
lib) == linkBuild.ImplicitDeps.end()) {
linkBuild.OrderOnlyDeps.emplace_back(lib);
}
}
}
}
}
// Add dependencies on swiftmodule files when using the swift linker
if (this->TargetLinkLanguage(config) == "Swift") {
if (cmComputeLinkInformation* cli =
this->GeneratorTarget->GetLinkInformation(config)) {
for (auto const& dependency : cli->GetItems()) {
// Both the current target and the linked target must be swift targets
// in order for there to be a swiftmodule to depend on
if (dependency.Target &&
dependency.Target->GetLinkerLanguage(config) == "Swift") {
std::string swiftmodule = this->ConvertToNinjaPath(
dependency.Target->GetSwiftModulePath(config));
linkBuild.ImplicitDeps.emplace_back(swiftmodule);
}
}
}
}
// Ninja should restat after linking if and only if there are byproducts.
vars["RESTAT"] = byproducts.ExplicitOuts.empty() ? "" : "1";
linkBuild.Outputs.reserve(linkBuild.Outputs.size() +
byproducts.ExplicitOuts.size());
std::move(byproducts.ExplicitOuts.begin(), byproducts.ExplicitOuts.end(),
std::back_inserter(linkBuild.Outputs));
linkBuild.WorkDirOuts = std::move(byproducts.WorkDirOuts);
// Write the build statement for this target.
bool usedResponseFile = false;
globalGen->WriteBuild(this->GetImplFileStream(fileConfig), linkBuild,
commandLineLengthLimit, &usedResponseFile);
this->WriteLinkRule(usedResponseFile, config, preLinkComments,
postBuildComments);
if (symlinkNeeded) {
if (targetType == cmStateEnums::EXECUTABLE) {
cmNinjaBuild build("CMAKE_SYMLINK_EXECUTABLE");
build.Comment = "Create executable symlink " + targetOutput;
build.Outputs.push_back(targetOutput);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
}
build.ExplicitDeps.push_back(targetOutputReal);
build.Variables = std::move(symlinkVars);
globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
} else {
cmNinjaBuild build("CMAKE_SYMLINK_LIBRARY");
build.Comment = "Create library symlink " + targetOutput;
std::string const soName = this->ConvertToNinjaPath(
this->GetTargetFilePath(tgtNames.SharedObject, config));
// If one link has to be created.
if (targetOutputReal == soName || targetOutput == soName) {
symlinkVars["SONAME"] =
this->GetLocalGenerator()->ConvertToOutputFormat(
soName, cmOutputConverter::SHELL);
} else {
symlinkVars["SONAME"].clear();
build.Outputs.push_back(soName);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(soName);
}
}
build.Outputs.push_back(targetOutput);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
}
build.ExplicitDeps.push_back(targetOutputReal);
build.Variables = std::move(symlinkVars);
globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
}
}
// Add aliases for the file name and the target name.
globalGen->AddTargetAlias(tgtNames.Output, gt, config);
globalGen->AddTargetAlias(this->GetTargetName(), gt, config);
if (this->GetGeneratorTarget()->IsApple() &&
this->GetGeneratorTarget()->HasImportLibrary(config)) {
auto dirTBD =
gt->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
auto targetTBD =
this->ConvertToNinjaPath(cmStrCat(dirTBD, '/', tgtNames.ImportReal));
this->EnsureParentDirectoryExists(targetTBD);
cmNinjaBuild build(this->TextStubsGeneratorRule(config));
build.Comment = cmStrCat("Generate the text-based stubs file ", targetTBD);
build.Outputs.push_back(targetTBD);
build.ExplicitDeps.push_back(targetOutputReal);
globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
if (tgtNames.ImportOutput != tgtNames.ImportReal &&
!this->GetGeneratorTarget()->IsFrameworkOnApple()) {
auto outputTBD =
this->ConvertToNinjaPath(cmStrCat(dirTBD, '/', tgtNames.ImportOutput));
std::string const soNameTBD = this->ConvertToNinjaPath(
cmStrCat(dirTBD, '/', tgtNames.ImportLibrary));
cmNinjaBuild slBuild("CMAKE_SYMLINK_IMPORT_LIBRARY");
slBuild.Comment = cmStrCat("Create import library symlink ", outputTBD);
cmNinjaVars slVars;
// If one link has to be created.
if (targetTBD == soNameTBD || outputTBD == soNameTBD) {
slVars["SONAME"] = this->GetLocalGenerator()->ConvertToOutputFormat(
soNameTBD, cmOutputConverter::SHELL);
} else {
slVars["SONAME"].clear();
slBuild.Outputs.push_back(soNameTBD);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(soNameTBD);
}
}
slBuild.Outputs.push_back(outputTBD);
if (firstForConfig) {
globalGen->GetByproductsForCleanTarget(config).push_back(outputTBD);
}
slBuild.ExplicitDeps.push_back(targetTBD);
slBuild.Variables = std::move(slVars);
globalGen->WriteBuild(this->GetImplFileStream(fileConfig), slBuild);
}
// Add alias for the import file name
globalGen->AddTargetAlias(tgtNames.ImportOutput, gt, config);
}
}
void cmNinjaNormalTargetGenerator::WriteObjectLibStatement(
std::string const& config)
{
// Write a phony output that depends on all object files.
{
cmNinjaBuild build("phony");
build.Comment = "Object library " + this->GetTargetName();
this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
build.Outputs, config);
this->GetLocalGenerator()->AppendTargetOutputs(
this->GetGeneratorTarget(),
this->GetGlobalGenerator()->GetByproductsForCleanTarget(config), config);
build.ExplicitDeps = this->GetObjects(config);
this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
}
// Add aliases for the target name.
this->GetGlobalGenerator()->AddTargetAlias(
this->GetTargetName(), this->GetGeneratorTarget(), config);
}
void cmNinjaNormalTargetGenerator::WriteCxxModuleLibraryStatement(
std::string const& config, std::string const& /*fileConfig*/,
bool firstForConfig)
{
// TODO: How to use `fileConfig` properly?
// Write a phony output that depends on the scanning output.
{
cmNinjaBuild build("phony");
build.Comment =
cmStrCat("Imported C++ module library ", this->GetTargetName());
this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
build.Outputs, config);
if (firstForConfig) {
this->GetLocalGenerator()->AppendTargetOutputs(
this->GetGeneratorTarget(),
this->GetGlobalGenerator()->GetByproductsForCleanTarget(config),
config);
}
build.ExplicitDeps.emplace_back(this->GetDyndepFilePath("CXX", config));
this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
}
// Add aliases for the target name.
this->GetGlobalGenerator()->AddTargetAlias(
this->GetTargetName(), this->GetGeneratorTarget(), config);
}
cmGeneratorTarget::Names cmNinjaNormalTargetGenerator::TargetNames(
std::string const& config) const
{
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
return this->GeneratorTarget->GetExecutableNames(config);
}
return this->GeneratorTarget->GetLibraryNames(config);
}
std::string cmNinjaNormalTargetGenerator::TargetLinkLanguage(
std::string const& config) const
{
return this->GeneratorTarget->GetLinkerLanguage(config);
}
|