cmNinjaNormalTargetGenerator.cxx 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmNinjaNormalTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <iterator>
  7. #include <map>
  8. #include <set>
  9. #include <sstream>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cm/optional>
  14. #include <cm/vector>
  15. #include "cmComputeLinkInformation.h"
  16. #include "cmCustomCommand.h" // IWYU pragma: keep
  17. #include "cmCustomCommandGenerator.h"
  18. #include "cmGeneratedFileStream.h"
  19. #include "cmGeneratorTarget.h"
  20. #include "cmGlobalNinjaGenerator.h"
  21. #include "cmLinkLineComputer.h"
  22. #include "cmLinkLineDeviceComputer.h"
  23. #include "cmLocalCommonGenerator.h"
  24. #include "cmLocalGenerator.h"
  25. #include "cmLocalNinjaGenerator.h"
  26. #include "cmMakefile.h"
  27. #include "cmMessageType.h"
  28. #include "cmNinjaLinkLineDeviceComputer.h"
  29. #include "cmNinjaTypes.h"
  30. #include "cmOSXBundleGenerator.h"
  31. #include "cmOutputConverter.h"
  32. #include "cmProperty.h"
  33. #include "cmRulePlaceholderExpander.h"
  34. #include "cmSourceFile.h"
  35. #include "cmState.h"
  36. #include "cmStateDirectory.h"
  37. #include "cmStateSnapshot.h"
  38. #include "cmStateTypes.h"
  39. #include "cmStringAlgorithms.h"
  40. #include "cmSystemTools.h"
  41. cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
  42. cmGeneratorTarget* target)
  43. : cmNinjaTargetGenerator(target)
  44. {
  45. if (target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
  46. // on Windows the output dir is already needed at compile time
  47. // ensure the directory exists (OutDir test)
  48. for (auto const& config : this->GetConfigNames()) {
  49. this->EnsureDirectoryExists(target->GetDirectory(config));
  50. }
  51. }
  52. this->OSXBundleGenerator = cm::make_unique<cmOSXBundleGenerator>(target);
  53. this->OSXBundleGenerator->SetMacContentFolders(&this->MacContentFolders);
  54. }
  55. cmNinjaNormalTargetGenerator::~cmNinjaNormalTargetGenerator() = default;
  56. void cmNinjaNormalTargetGenerator::Generate(const std::string& config)
  57. {
  58. std::string lang = this->GeneratorTarget->GetLinkerLanguage(config);
  59. if (this->TargetLinkLanguage(config).empty()) {
  60. cmSystemTools::Error("CMake can not determine linker language for "
  61. "target: " +
  62. this->GetGeneratorTarget()->GetName());
  63. return;
  64. }
  65. // Write the rules for each language.
  66. this->WriteLanguagesRules(config);
  67. // Write the build statements
  68. bool firstForConfig = true;
  69. for (auto const& fileConfig : this->GetConfigNames()) {
  70. if (!this->GetGlobalGenerator()
  71. ->GetCrossConfigs(fileConfig)
  72. .count(config)) {
  73. continue;
  74. }
  75. this->WriteObjectBuildStatements(config, fileConfig, firstForConfig);
  76. firstForConfig = false;
  77. }
  78. if (this->GetGeneratorTarget()->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  79. this->WriteObjectLibStatement(config);
  80. } else {
  81. firstForConfig = true;
  82. for (auto const& fileConfig : this->GetConfigNames()) {
  83. if (!this->GetGlobalGenerator()
  84. ->GetCrossConfigs(fileConfig)
  85. .count(config)) {
  86. continue;
  87. }
  88. // If this target has cuda language link inputs, and we need to do
  89. // device linking
  90. this->WriteDeviceLinkStatement(config, fileConfig, firstForConfig);
  91. this->WriteLinkStatement(config, fileConfig, firstForConfig);
  92. firstForConfig = false;
  93. }
  94. }
  95. if (this->GetGlobalGenerator()->EnableCrossConfigBuild()) {
  96. this->GetGlobalGenerator()->AddTargetAlias(
  97. this->GetTargetName(), this->GetGeneratorTarget(), "all");
  98. }
  99. // Find ADDITIONAL_CLEAN_FILES
  100. this->AdditionalCleanFiles(config);
  101. }
  102. void cmNinjaNormalTargetGenerator::WriteLanguagesRules(
  103. const std::string& config)
  104. {
  105. #ifdef NINJA_GEN_VERBOSE_FILES
  106. cmGlobalNinjaGenerator::WriteDivider(this->GetRulesFileStream());
  107. this->GetRulesFileStream()
  108. << "# Rules for each languages for "
  109. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  110. << " target " << this->GetTargetName() << "\n\n";
  111. #endif
  112. // Write rules for languages compiled in this target.
  113. std::set<std::string> languages;
  114. std::vector<cmSourceFile const*> sourceFiles;
  115. this->GetGeneratorTarget()->GetObjectSources(sourceFiles, config);
  116. for (cmSourceFile const* sf : sourceFiles) {
  117. std::string const lang = sf->GetLanguage();
  118. if (!lang.empty()) {
  119. languages.insert(lang);
  120. }
  121. }
  122. for (std::string const& language : languages) {
  123. this->WriteLanguageRules(language, config);
  124. }
  125. }
  126. const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
  127. {
  128. switch (this->GetGeneratorTarget()->GetType()) {
  129. case cmStateEnums::STATIC_LIBRARY:
  130. return "static library";
  131. case cmStateEnums::SHARED_LIBRARY:
  132. return "shared library";
  133. case cmStateEnums::MODULE_LIBRARY:
  134. if (this->GetGeneratorTarget()->IsCFBundleOnApple()) {
  135. return "CFBundle shared module";
  136. } else {
  137. return "shared module";
  138. }
  139. case cmStateEnums::EXECUTABLE:
  140. return "executable";
  141. default:
  142. return nullptr;
  143. }
  144. }
  145. std::string cmNinjaNormalTargetGenerator::LanguageLinkerRule(
  146. const std::string& config) const
  147. {
  148. return cmStrCat(
  149. this->TargetLinkLanguage(config), "_",
  150. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()),
  151. "_LINKER__",
  152. cmGlobalNinjaGenerator::EncodeRuleName(
  153. this->GetGeneratorTarget()->GetName()),
  154. "_", config);
  155. }
  156. std::string cmNinjaNormalTargetGenerator::LanguageLinkerDeviceRule(
  157. const std::string& config) const
  158. {
  159. return cmStrCat(
  160. this->TargetLinkLanguage(config), "_",
  161. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()),
  162. "_DEVICE_LINKER__",
  163. cmGlobalNinjaGenerator::EncodeRuleName(
  164. this->GetGeneratorTarget()->GetName()),
  165. "_", config);
  166. }
  167. std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaDeviceRule(
  168. const std::string& config) const
  169. {
  170. return cmStrCat(
  171. this->TargetLinkLanguage(config), "_DEVICE_LINK__",
  172. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  173. '_', config);
  174. }
  175. std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaDeviceCompileRule(
  176. const std::string& config) const
  177. {
  178. return cmStrCat(
  179. this->TargetLinkLanguage(config), "_DEVICE_LINK_COMPILE__",
  180. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  181. '_', config);
  182. }
  183. std::string cmNinjaNormalTargetGenerator::LanguageLinkerCudaFatbinaryRule(
  184. const std::string& config) const
  185. {
  186. return cmStrCat(
  187. this->TargetLinkLanguage(config), "_FATBINARY__",
  188. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  189. '_', config);
  190. }
  191. struct cmNinjaRemoveNoOpCommands
  192. {
  193. bool operator()(std::string const& cmd)
  194. {
  195. return cmd.empty() || cmd[0] == ':';
  196. }
  197. };
  198. void cmNinjaNormalTargetGenerator::WriteNvidiaDeviceLinkRule(
  199. bool useResponseFile, const std::string& config)
  200. {
  201. cmNinjaRule rule(this->LanguageLinkerDeviceRule(config));
  202. if (!this->GetGlobalGenerator()->HasRule(rule.Name)) {
  203. cmRulePlaceholderExpander::RuleVariables vars;
  204. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  205. vars.CMTargetType =
  206. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  207. .c_str();
  208. vars.Language = "CUDA";
  209. // build response file name
  210. std::string responseFlag = this->GetMakefile()->GetSafeDefinition(
  211. "CMAKE_CUDA_RESPONSE_FILE_DEVICE_LINK_FLAG");
  212. if (!useResponseFile || responseFlag.empty()) {
  213. vars.Objects = "$in";
  214. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  215. } else {
  216. rule.RspFile = "$RSP_FILE";
  217. responseFlag += rule.RspFile;
  218. // build response file content
  219. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  220. rule.RspContent = "$in";
  221. } else {
  222. rule.RspContent = "$in_newline";
  223. }
  224. rule.RspContent += " $LINK_LIBRARIES";
  225. vars.Objects = responseFlag.c_str();
  226. vars.LinkLibraries = "";
  227. }
  228. vars.ObjectDir = "$OBJECT_DIR";
  229. vars.Target = "$TARGET_FILE";
  230. vars.SONameFlag = "$SONAME_FLAG";
  231. vars.TargetSOName = "$SONAME";
  232. vars.TargetPDB = "$TARGET_PDB";
  233. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  234. vars.Flags = "$FLAGS";
  235. vars.LinkFlags = "$LINK_FLAGS";
  236. vars.Manifests = "$MANIFESTS";
  237. vars.LanguageCompileFlags = "$LANGUAGE_COMPILE_FLAGS";
  238. std::string launcher;
  239. cmProp val = this->GetLocalGenerator()->GetRuleLauncher(
  240. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  241. if (cmNonempty(val)) {
  242. launcher = cmStrCat(*val, ' ');
  243. }
  244. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  245. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  246. // Rule for linking library/executable.
  247. std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
  248. for (std::string& linkCmd : linkCmds) {
  249. linkCmd = cmStrCat(launcher, linkCmd);
  250. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  251. linkCmd, vars);
  252. }
  253. // If there is no ranlib the command will be ":". Skip it.
  254. cm::erase_if(linkCmds, cmNinjaRemoveNoOpCommands());
  255. rule.Command =
  256. this->GetLocalGenerator()->BuildCommandLine(linkCmds, config, config);
  257. // Write the linker rule with response file if needed.
  258. rule.Comment =
  259. cmStrCat("Rule for linking ", this->TargetLinkLanguage(config), ' ',
  260. this->GetVisibleTypeName(), '.');
  261. rule.Description =
  262. cmStrCat("Linking ", this->TargetLinkLanguage(config), ' ',
  263. this->GetVisibleTypeName(), " $TARGET_FILE");
  264. rule.Restat = "$RESTAT";
  265. this->GetGlobalGenerator()->AddRule(rule);
  266. }
  267. }
  268. void cmNinjaNormalTargetGenerator::WriteDeviceLinkRules(
  269. const std::string& config)
  270. {
  271. const cmMakefile* mf = this->GetMakefile();
  272. cmNinjaRule rule(this->LanguageLinkerCudaDeviceRule(config));
  273. rule.Command = this->GetLocalGenerator()->BuildCommandLine(
  274. { cmStrCat(mf->GetRequiredDefinition("CMAKE_CUDA_DEVICE_LINKER"),
  275. " -arch=$ARCH $REGISTER -o=$out $in") },
  276. config, config);
  277. rule.Comment = "Rule for CUDA device linking.";
  278. rule.Description = "Linking CUDA $out";
  279. this->GetGlobalGenerator()->AddRule(rule);
  280. cmRulePlaceholderExpander::RuleVariables vars;
  281. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  282. vars.CMTargetType =
  283. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  284. vars.Language = "CUDA";
  285. vars.Object = "$out";
  286. vars.Fatbinary = "$FATBIN";
  287. vars.RegisterFile = "$REGISTER";
  288. std::string flags = this->GetFlags("CUDA", config);
  289. vars.Flags = flags.c_str();
  290. std::string compileCmd = this->GetMakefile()->GetRequiredDefinition(
  291. "CMAKE_CUDA_DEVICE_LINK_COMPILE");
  292. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  293. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  294. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  295. compileCmd, vars);
  296. rule.Name = this->LanguageLinkerCudaDeviceCompileRule(config);
  297. rule.Command = this->GetLocalGenerator()->BuildCommandLine({ compileCmd },
  298. config, config);
  299. rule.Comment = "Rule for compiling CUDA device stubs.";
  300. rule.Description = "Compiling CUDA device stub $out";
  301. this->GetGlobalGenerator()->AddRule(rule);
  302. rule.Name = this->LanguageLinkerCudaFatbinaryRule(config);
  303. rule.Command = this->GetLocalGenerator()->BuildCommandLine(
  304. { cmStrCat(mf->GetRequiredDefinition("CMAKE_CUDA_FATBINARY"),
  305. " -64 -cmdline=--compile-only -compress-all -link "
  306. "--embedded-fatbin=$out $PROFILES") },
  307. config, config);
  308. rule.Comment = "Rule for CUDA fatbinaries.";
  309. rule.Description = "Creating fatbinary $out";
  310. this->GetGlobalGenerator()->AddRule(rule);
  311. }
  312. void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile,
  313. const std::string& config)
  314. {
  315. cmStateEnums::TargetType targetType = this->GetGeneratorTarget()->GetType();
  316. std::string linkRuleName = this->LanguageLinkerRule(config);
  317. if (!this->GetGlobalGenerator()->HasRule(linkRuleName)) {
  318. cmNinjaRule rule(std::move(linkRuleName));
  319. cmRulePlaceholderExpander::RuleVariables vars;
  320. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  321. vars.CMTargetType = cmState::GetTargetTypeName(targetType).c_str();
  322. std::string lang = this->TargetLinkLanguage(config);
  323. vars.Language = lang.c_str();
  324. vars.AIXExports = "$AIX_EXPORTS";
  325. if (this->TargetLinkLanguage(config) == "Swift") {
  326. vars.SwiftLibraryName = "$SWIFT_LIBRARY_NAME";
  327. vars.SwiftModule = "$SWIFT_MODULE";
  328. vars.SwiftModuleName = "$SWIFT_MODULE_NAME";
  329. vars.SwiftOutputFileMap = "$SWIFT_OUTPUT_FILE_MAP";
  330. vars.SwiftSources = "$SWIFT_SOURCES";
  331. vars.Defines = "$DEFINES";
  332. vars.Flags = "$FLAGS";
  333. vars.Includes = "$INCLUDES";
  334. }
  335. std::string responseFlag;
  336. std::string cmakeVarLang =
  337. cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
  338. // build response file name
  339. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  340. cmProp flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  341. if (flag) {
  342. responseFlag = *flag;
  343. } else {
  344. responseFlag = "@";
  345. }
  346. if (!useResponseFile || responseFlag.empty()) {
  347. vars.Objects = "$in";
  348. vars.LinkLibraries = "$LINK_PATH $LINK_LIBRARIES";
  349. } else {
  350. rule.RspFile = "$RSP_FILE";
  351. responseFlag += rule.RspFile;
  352. // build response file content
  353. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  354. rule.RspContent = "$in";
  355. } else {
  356. rule.RspContent = "$in_newline";
  357. }
  358. rule.RspContent += " $LINK_PATH $LINK_LIBRARIES";
  359. if (this->TargetLinkLanguage(config) == "Swift") {
  360. vars.SwiftSources = responseFlag.c_str();
  361. } else {
  362. vars.Objects = responseFlag.c_str();
  363. }
  364. vars.LinkLibraries = "";
  365. }
  366. vars.ObjectDir = "$OBJECT_DIR";
  367. vars.Target = "$TARGET_FILE";
  368. vars.SONameFlag = "$SONAME_FLAG";
  369. vars.TargetSOName = "$SONAME";
  370. vars.TargetInstallNameDir = "$INSTALLNAME_DIR";
  371. vars.TargetPDB = "$TARGET_PDB";
  372. // Setup the target version.
  373. std::string targetVersionMajor;
  374. std::string targetVersionMinor;
  375. {
  376. std::ostringstream majorStream;
  377. std::ostringstream minorStream;
  378. int major;
  379. int minor;
  380. this->GetGeneratorTarget()->GetTargetVersion(major, minor);
  381. majorStream << major;
  382. minorStream << minor;
  383. targetVersionMajor = majorStream.str();
  384. targetVersionMinor = minorStream.str();
  385. }
  386. vars.TargetVersionMajor = targetVersionMajor.c_str();
  387. vars.TargetVersionMinor = targetVersionMinor.c_str();
  388. vars.Flags = "$FLAGS";
  389. vars.LinkFlags = "$LINK_FLAGS";
  390. vars.Manifests = "$MANIFESTS";
  391. std::string langFlags;
  392. if (targetType != cmStateEnums::EXECUTABLE) {
  393. langFlags += "$LANGUAGE_COMPILE_FLAGS $ARCH_FLAGS";
  394. vars.LanguageCompileFlags = langFlags.c_str();
  395. }
  396. std::string linkerLauncher = this->GetLinkerLauncher(config);
  397. if (cmNonempty(linkerLauncher)) {
  398. vars.Launcher = linkerLauncher.c_str();
  399. }
  400. std::string launcher;
  401. cmProp val = this->GetLocalGenerator()->GetRuleLauncher(
  402. this->GetGeneratorTarget(), "RULE_LAUNCH_LINK");
  403. if (cmNonempty(val)) {
  404. launcher = cmStrCat(*val, ' ');
  405. }
  406. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  407. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  408. // Rule for linking library/executable.
  409. std::vector<std::string> linkCmds = this->ComputeLinkCmd(config);
  410. for (std::string& linkCmd : linkCmds) {
  411. linkCmd = cmStrCat(launcher, linkCmd);
  412. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  413. linkCmd, vars);
  414. }
  415. // If there is no ranlib the command will be ":". Skip it.
  416. cm::erase_if(linkCmds, cmNinjaRemoveNoOpCommands());
  417. linkCmds.insert(linkCmds.begin(), "$PRE_LINK");
  418. linkCmds.emplace_back("$POST_BUILD");
  419. rule.Command =
  420. this->GetLocalGenerator()->BuildCommandLine(linkCmds, config, config);
  421. // Write the linker rule with response file if needed.
  422. rule.Comment =
  423. cmStrCat("Rule for linking ", this->TargetLinkLanguage(config), ' ',
  424. this->GetVisibleTypeName(), '.');
  425. rule.Description =
  426. cmStrCat("Linking ", this->TargetLinkLanguage(config), ' ',
  427. this->GetVisibleTypeName(), " $TARGET_FILE");
  428. rule.Restat = "$RESTAT";
  429. this->GetGlobalGenerator()->AddRule(rule);
  430. }
  431. auto const tgtNames = this->TargetNames(config);
  432. if (tgtNames.Output != tgtNames.Real &&
  433. !this->GetGeneratorTarget()->IsFrameworkOnApple()) {
  434. std::string cmakeCommand =
  435. this->GetLocalGenerator()->ConvertToOutputFormat(
  436. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  437. if (targetType == cmStateEnums::EXECUTABLE) {
  438. cmNinjaRule rule("CMAKE_SYMLINK_EXECUTABLE");
  439. {
  440. std::vector<std::string> cmd;
  441. cmd.push_back(cmakeCommand + " -E cmake_symlink_executable $in $out");
  442. cmd.emplace_back("$POST_BUILD");
  443. rule.Command =
  444. this->GetLocalGenerator()->BuildCommandLine(cmd, config, config);
  445. }
  446. rule.Description = "Creating executable symlink $out";
  447. rule.Comment = "Rule for creating executable symlink.";
  448. this->GetGlobalGenerator()->AddRule(rule);
  449. } else {
  450. cmNinjaRule rule("CMAKE_SYMLINK_LIBRARY");
  451. {
  452. std::vector<std::string> cmd;
  453. cmd.push_back(cmakeCommand +
  454. " -E cmake_symlink_library $in $SONAME $out");
  455. cmd.emplace_back("$POST_BUILD");
  456. rule.Command =
  457. this->GetLocalGenerator()->BuildCommandLine(cmd, config, config);
  458. }
  459. rule.Description = "Creating library symlink $out";
  460. rule.Comment = "Rule for creating library symlink.";
  461. this->GetGlobalGenerator()->AddRule(rule);
  462. }
  463. }
  464. }
  465. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeDeviceLinkCmd()
  466. {
  467. std::vector<std::string> linkCmds;
  468. // this target requires separable cuda compilation
  469. // now build the correct command depending on if the target is
  470. // an executable or a dynamic library.
  471. std::string linkCmd;
  472. switch (this->GetGeneratorTarget()->GetType()) {
  473. case cmStateEnums::STATIC_LIBRARY:
  474. case cmStateEnums::SHARED_LIBRARY:
  475. case cmStateEnums::MODULE_LIBRARY: {
  476. this->GetMakefile()->GetDefExpandList("CMAKE_CUDA_DEVICE_LINK_LIBRARY",
  477. linkCmds);
  478. } break;
  479. case cmStateEnums::EXECUTABLE: {
  480. this->GetMakefile()->GetDefExpandList(
  481. "CMAKE_CUDA_DEVICE_LINK_EXECUTABLE", linkCmds);
  482. } break;
  483. default:
  484. break;
  485. }
  486. return linkCmds;
  487. }
  488. std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd(
  489. const std::string& config)
  490. {
  491. std::vector<std::string> linkCmds;
  492. cmMakefile* mf = this->GetMakefile();
  493. {
  494. // If we have a rule variable prefer it. In the case of static libraries
  495. // this occurs when things like IPO is enabled, and we need to use the
  496. // CMAKE_<lang>_CREATE_STATIC_LIBRARY_IPO define instead.
  497. std::string linkCmdVar = this->GetGeneratorTarget()->GetCreateRuleVariable(
  498. this->TargetLinkLanguage(config), config);
  499. cmProp linkCmd = mf->GetDefinition(linkCmdVar);
  500. if (linkCmd) {
  501. std::string linkCmdStr = *linkCmd;
  502. if (this->GetGeneratorTarget()->HasImplibGNUtoMS(config)) {
  503. std::string ruleVar =
  504. cmStrCat("CMAKE_", this->GeneratorTarget->GetLinkerLanguage(config),
  505. "_GNUtoMS_RULE");
  506. if (cmProp rule = this->Makefile->GetDefinition(ruleVar)) {
  507. linkCmdStr += *rule;
  508. }
  509. }
  510. cmExpandList(linkCmdStr, linkCmds);
  511. if (this->UseLWYU) {
  512. cmProp lwyuCheck = mf->GetDefinition("CMAKE_LINK_WHAT_YOU_USE_CHECK");
  513. if (lwyuCheck) {
  514. std::string cmakeCommand = cmStrCat(
  515. this->GetLocalGenerator()->ConvertToOutputFormat(
  516. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL),
  517. " -E __run_co_compile --lwyu=");
  518. cmakeCommand +=
  519. this->GetLocalGenerator()->EscapeForShell(*lwyuCheck);
  520. std::string targetOutputReal =
  521. this->ConvertToNinjaPath(this->GetGeneratorTarget()->GetFullPath(
  522. config, cmStateEnums::RuntimeBinaryArtifact,
  523. /*realname=*/true));
  524. cmakeCommand += cmStrCat(" --source=", targetOutputReal);
  525. linkCmds.push_back(std::move(cmakeCommand));
  526. }
  527. }
  528. return linkCmds;
  529. }
  530. }
  531. switch (this->GetGeneratorTarget()->GetType()) {
  532. case cmStateEnums::STATIC_LIBRARY: {
  533. // We have archive link commands set. First, delete the existing archive.
  534. {
  535. std::string cmakeCommand =
  536. this->GetLocalGenerator()->ConvertToOutputFormat(
  537. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  538. linkCmds.push_back(cmakeCommand + " -E rm -f $TARGET_FILE");
  539. }
  540. // TODO: Use ARCHIVE_APPEND for archives over a certain size.
  541. {
  542. std::string linkCmdVar = cmStrCat(
  543. "CMAKE_", this->TargetLinkLanguage(config), "_ARCHIVE_CREATE");
  544. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  545. linkCmdVar, this->TargetLinkLanguage(config), config);
  546. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  547. cmExpandList(linkCmd, linkCmds);
  548. }
  549. {
  550. std::string linkCmdVar = cmStrCat(
  551. "CMAKE_", this->TargetLinkLanguage(config), "_ARCHIVE_FINISH");
  552. linkCmdVar = this->GeneratorTarget->GetFeatureSpecificLinkRuleVariable(
  553. linkCmdVar, this->TargetLinkLanguage(config), config);
  554. std::string const& linkCmd = mf->GetRequiredDefinition(linkCmdVar);
  555. cmExpandList(linkCmd, linkCmds);
  556. }
  557. #ifdef __APPLE__
  558. // On macOS ranlib truncates the fractional part of the static archive
  559. // file modification time. If the archive and at least one contained
  560. // object file were created within the same second this will make look
  561. // the archive older than the object file. On subsequent ninja runs this
  562. // leads to re-achiving and updating dependent targets.
  563. // As a work-around we touch the archive after ranlib (see #19222).
  564. {
  565. std::string cmakeCommand =
  566. this->GetLocalGenerator()->ConvertToOutputFormat(
  567. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  568. linkCmds.push_back(cmakeCommand + " -E touch $TARGET_FILE");
  569. }
  570. #endif
  571. } break;
  572. case cmStateEnums::SHARED_LIBRARY:
  573. case cmStateEnums::MODULE_LIBRARY:
  574. break;
  575. case cmStateEnums::EXECUTABLE:
  576. if (this->TargetLinkLanguage(config) == "Swift") {
  577. if (this->GeneratorTarget->IsExecutableWithExports()) {
  578. this->Makefile->GetDefExpandList("CMAKE_EXE_EXPORTS_Swift_FLAG",
  579. linkCmds);
  580. }
  581. }
  582. break;
  583. default:
  584. assert(false && "Unexpected target type");
  585. }
  586. return linkCmds;
  587. }
  588. void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement(
  589. const std::string& config, const std::string& fileConfig,
  590. bool firstForConfig)
  591. {
  592. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  593. if (!globalGen->GetLanguageEnabled("CUDA")) {
  594. return;
  595. }
  596. cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
  597. bool requiresDeviceLinking = requireDeviceLinking(
  598. *this->GeneratorTarget, *this->GetLocalGenerator(), config);
  599. if (!requiresDeviceLinking) {
  600. return;
  601. }
  602. // First and very important step is to make sure while inside this
  603. // step our link language is set to CUDA
  604. std::string const& objExt =
  605. this->Makefile->GetSafeDefinition("CMAKE_CUDA_OUTPUT_EXTENSION");
  606. std::string targetOutputDir =
  607. cmStrCat(this->GetLocalGenerator()->GetTargetDirectory(genTarget),
  608. globalGen->ConfigDirectory(config), "/");
  609. targetOutputDir = globalGen->ExpandCFGIntDir(targetOutputDir, config);
  610. std::string targetOutputReal =
  611. this->ConvertToNinjaPath(targetOutputDir + "cmake_device_link" + objExt);
  612. if (firstForConfig) {
  613. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
  614. }
  615. this->DeviceLinkObject = targetOutputReal;
  616. // Write comments.
  617. cmGlobalNinjaGenerator::WriteDivider(this->GetCommonFileStream());
  618. this->GetCommonFileStream()
  619. << "# Device Link build statements for "
  620. << cmState::GetTargetTypeName(genTarget->GetType()) << " target "
  621. << this->GetTargetName() << "\n\n";
  622. if (this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID") == "Clang") {
  623. std::string architecturesStr =
  624. this->GeneratorTarget->GetSafeProperty("CUDA_ARCHITECTURES");
  625. if (cmIsOff(architecturesStr)) {
  626. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  627. "CUDA_SEPARABLE_COMPILATION on Clang "
  628. "requires CUDA_ARCHITECTURES to be set.");
  629. return;
  630. }
  631. this->WriteDeviceLinkRules(config);
  632. this->WriteDeviceLinkStatements(config, cmExpandedList(architecturesStr),
  633. targetOutputReal);
  634. } else {
  635. this->WriteNvidiaDeviceLinkStatement(config, fileConfig, targetOutputDir,
  636. targetOutputReal);
  637. }
  638. }
  639. void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatements(
  640. const std::string& config, const std::vector<std::string>& architectures,
  641. const std::string& output)
  642. {
  643. // Ensure there are no duplicates.
  644. const cmNinjaDeps explicitDeps = [&]() -> std::vector<std::string> {
  645. std::unordered_set<std::string> depsSet;
  646. const cmNinjaDeps linkDeps =
  647. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config, true);
  648. const cmNinjaDeps objects = this->GetObjects(config);
  649. depsSet.insert(linkDeps.begin(), linkDeps.end());
  650. depsSet.insert(objects.begin(), objects.end());
  651. std::vector<std::string> deps;
  652. std::copy(depsSet.begin(), depsSet.end(), std::back_inserter(deps));
  653. return deps;
  654. }();
  655. const std::string objectDir =
  656. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  657. this->GetGlobalGenerator()->ConfigDirectory(config));
  658. const std::string ninjaOutputDir = this->ConvertToNinjaPath(objectDir);
  659. cmNinjaBuild fatbinary(this->LanguageLinkerCudaFatbinaryRule(config));
  660. // Link device code for each architecture.
  661. for (const std::string& architectureKind : architectures) {
  662. // Clang always generates real code, so strip the specifier.
  663. const std::string architecture =
  664. architectureKind.substr(0, architectureKind.find('-'));
  665. const std::string cubin =
  666. cmStrCat(ninjaOutputDir, "/sm_", architecture, ".cubin");
  667. fatbinary.Variables["PROFILES"] +=
  668. cmStrCat(" -im=profile=sm_", architecture, ",file=", cubin);
  669. fatbinary.ExplicitDeps.emplace_back(cubin);
  670. cmNinjaBuild dlink(this->LanguageLinkerCudaDeviceRule(config));
  671. dlink.ExplicitDeps = explicitDeps;
  672. dlink.Outputs = { cubin };
  673. dlink.Variables["ARCH"] = cmStrCat("sm_", architecture);
  674. // The generated register file contains macros that when expanded register
  675. // the device routines. Because the routines are the same for all
  676. // architectures the register file will be the same too. Thus generate it
  677. // only on the first invocation to reduce overhead.
  678. if (fatbinary.ExplicitDeps.size() == 1) {
  679. dlink.Variables["REGISTER"] = cmStrCat(
  680. "--register-link-binaries=", ninjaOutputDir, "/cmake_cuda_register.h");
  681. }
  682. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), dlink);
  683. }
  684. // Combine all architectures into a single fatbinary.
  685. fatbinary.Outputs = { cmStrCat(ninjaOutputDir, "/cmake_cuda_fatbin.h") };
  686. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(),
  687. fatbinary);
  688. // Compile the stub that registers the kernels and contains the fatbinaries.
  689. cmNinjaBuild dcompile(this->LanguageLinkerCudaDeviceCompileRule(config));
  690. dcompile.Outputs = { output };
  691. dcompile.ExplicitDeps = { cmStrCat(ninjaOutputDir, "/cmake_cuda_fatbin.h") };
  692. dcompile.Variables["FATBIN"] =
  693. this->GetLocalGenerator()->ConvertToOutputFormat(
  694. cmStrCat(objectDir, "/cmake_cuda_fatbin.h"), cmOutputConverter::SHELL);
  695. dcompile.Variables["REGISTER"] =
  696. this->GetLocalGenerator()->ConvertToOutputFormat(
  697. cmStrCat(objectDir, "/cmake_cuda_register.h"), cmOutputConverter::SHELL);
  698. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(),
  699. dcompile);
  700. }
  701. void cmNinjaNormalTargetGenerator::WriteNvidiaDeviceLinkStatement(
  702. const std::string& config, const std::string& fileConfig,
  703. const std::string& outputDir, const std::string& output)
  704. {
  705. cmGeneratorTarget* genTarget = this->GetGeneratorTarget();
  706. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  707. std::string targetOutputImplib = this->ConvertToNinjaPath(
  708. genTarget->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
  709. if (config != fileConfig) {
  710. std::string targetOutputFileConfigDir =
  711. cmStrCat(this->GetLocalGenerator()->GetTargetDirectory(genTarget),
  712. globalGen->ConfigDirectory(fileConfig), "/");
  713. targetOutputFileConfigDir =
  714. globalGen->ExpandCFGIntDir(outputDir, fileConfig);
  715. if (outputDir == targetOutputFileConfigDir) {
  716. return;
  717. }
  718. if (!genTarget->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
  719. .empty() &&
  720. !genTarget
  721. ->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
  722. .empty() &&
  723. targetOutputImplib ==
  724. this->ConvertToNinjaPath(genTarget->GetFullPath(
  725. fileConfig, cmStateEnums::ImportLibraryArtifact))) {
  726. return;
  727. }
  728. }
  729. // Compute the comment.
  730. cmNinjaBuild build(this->LanguageLinkerDeviceRule(config));
  731. build.Comment =
  732. cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', output);
  733. cmNinjaVars& vars = build.Variables;
  734. // Compute outputs.
  735. build.Outputs.push_back(output);
  736. // Compute specific libraries to link with.
  737. build.ExplicitDeps = this->GetObjects(config);
  738. build.ImplicitDeps =
  739. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
  740. std::string frameworkPath;
  741. std::string linkPath;
  742. std::string createRule =
  743. genTarget->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
  744. const bool useWatcomQuote =
  745. this->GetMakefile()->IsOn(createRule + "_USE_WATCOM_QUOTE");
  746. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  747. vars["TARGET_FILE"] =
  748. localGen.ConvertToOutputFormat(output, cmOutputConverter::SHELL);
  749. std::unique_ptr<cmLinkLineComputer> linkLineComputer(
  750. new cmNinjaLinkLineDeviceComputer(
  751. this->GetLocalGenerator(),
  752. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(),
  753. globalGen));
  754. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  755. linkLineComputer->SetUseNinjaMulti(globalGen->IsMultiConfig());
  756. localGen.GetDeviceLinkFlags(linkLineComputer.get(), config,
  757. vars["LINK_LIBRARIES"], vars["LINK_FLAGS"],
  758. frameworkPath, linkPath, genTarget);
  759. this->addPoolNinjaVariable("JOB_POOL_LINK", genTarget, vars);
  760. vars["LINK_FLAGS"] = globalGen->EncodeLiteral(vars["LINK_FLAGS"]);
  761. vars["MANIFESTS"] = this->GetManifests(config);
  762. vars["LINK_PATH"] = frameworkPath + linkPath;
  763. // Compute language specific link flags.
  764. std::string langFlags;
  765. localGen.AddLanguageFlagsForLinking(langFlags, genTarget, "CUDA", config);
  766. vars["LANGUAGE_COMPILE_FLAGS"] = langFlags;
  767. auto const tgtNames = this->TargetNames(config);
  768. if (genTarget->HasSOName(config)) {
  769. vars["SONAME_FLAG"] =
  770. this->GetMakefile()->GetSONameFlag(this->TargetLinkLanguage(config));
  771. vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
  772. cmOutputConverter::SHELL);
  773. if (genTarget->GetType() == cmStateEnums::SHARED_LIBRARY) {
  774. std::string install_dir =
  775. this->GetGeneratorTarget()->GetInstallNameDirForBuildTree(config);
  776. if (!install_dir.empty()) {
  777. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  778. install_dir, cmOutputConverter::SHELL);
  779. }
  780. }
  781. }
  782. if (!tgtNames.ImportLibrary.empty()) {
  783. const std::string impLibPath = localGen.ConvertToOutputFormat(
  784. targetOutputImplib, cmOutputConverter::SHELL);
  785. vars["TARGET_IMPLIB"] = impLibPath;
  786. this->EnsureParentDirectoryExists(impLibPath);
  787. }
  788. const std::string objPath =
  789. cmStrCat(this->GetGeneratorTarget()->GetSupportDirectory(),
  790. globalGen->ConfigDirectory(config));
  791. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  792. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  793. this->EnsureDirectoryExists(objPath);
  794. this->SetMsvcTargetPdbVariable(vars, config);
  795. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  796. std::string& link_path = vars["LINK_PATH"];
  797. if (globalGen->IsGCCOnWindows()) {
  798. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  799. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  800. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  801. }
  802. // Device linking currently doesn't support response files so
  803. // do not check if the user has explicitly forced a response file.
  804. int const commandLineLengthLimit =
  805. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  806. globalGen->GetRuleCmdLength(build.Rule);
  807. build.RspFile = this->ConvertToNinjaPath(
  808. cmStrCat("CMakeFiles/", genTarget->GetName(),
  809. globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
  810. // Gather order-only dependencies.
  811. this->GetLocalGenerator()->AppendTargetDepends(
  812. this->GetGeneratorTarget(), build.OrderOnlyDeps, config, config,
  813. DependOnTargetArtifact);
  814. // Write the build statement for this target.
  815. bool usedResponseFile = false;
  816. globalGen->WriteBuild(this->GetCommonFileStream(), build,
  817. commandLineLengthLimit, &usedResponseFile);
  818. this->WriteNvidiaDeviceLinkRule(usedResponseFile, config);
  819. }
  820. void cmNinjaNormalTargetGenerator::WriteLinkStatement(
  821. const std::string& config, const std::string& fileConfig,
  822. bool firstForConfig)
  823. {
  824. cmMakefile* mf = this->GetMakefile();
  825. cmGlobalNinjaGenerator* globalGen = this->GetGlobalGenerator();
  826. cmGeneratorTarget* gt = this->GetGeneratorTarget();
  827. std::string targetOutput = this->ConvertToNinjaPath(gt->GetFullPath(config));
  828. std::string targetOutputReal = this->ConvertToNinjaPath(
  829. gt->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact,
  830. /*realname=*/true));
  831. std::string targetOutputImplib = this->ConvertToNinjaPath(
  832. gt->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
  833. if (config != fileConfig) {
  834. if (targetOutput ==
  835. this->ConvertToNinjaPath(gt->GetFullPath(fileConfig))) {
  836. return;
  837. }
  838. if (targetOutputReal ==
  839. this->ConvertToNinjaPath(
  840. gt->GetFullPath(fileConfig, cmStateEnums::RuntimeBinaryArtifact,
  841. /*realname=*/true))) {
  842. return;
  843. }
  844. if (!gt->GetFullName(config, cmStateEnums::ImportLibraryArtifact)
  845. .empty() &&
  846. !gt->GetFullName(fileConfig, cmStateEnums::ImportLibraryArtifact)
  847. .empty() &&
  848. targetOutputImplib ==
  849. this->ConvertToNinjaPath(gt->GetFullPath(
  850. fileConfig, cmStateEnums::ImportLibraryArtifact))) {
  851. return;
  852. }
  853. }
  854. auto const tgtNames = this->TargetNames(config);
  855. if (gt->IsAppBundleOnApple()) {
  856. // Create the app bundle
  857. std::string outpath = gt->GetDirectory(config);
  858. this->OSXBundleGenerator->CreateAppBundle(tgtNames.Output, outpath,
  859. config);
  860. // Calculate the output path
  861. targetOutput = cmStrCat(outpath, '/', tgtNames.Output);
  862. targetOutput = this->ConvertToNinjaPath(targetOutput);
  863. targetOutputReal = cmStrCat(outpath, '/', tgtNames.Real);
  864. targetOutputReal = this->ConvertToNinjaPath(targetOutputReal);
  865. } else if (gt->IsFrameworkOnApple()) {
  866. // Create the library framework.
  867. cmOSXBundleGenerator::SkipParts bundleSkipParts;
  868. if (globalGen->GetName() == "Ninja Multi-Config") {
  869. const auto postFix = this->GeneratorTarget->GetFilePostfix(config);
  870. // Skip creating Info.plist when there are multiple configurations, and
  871. // the current configuration has a postfix. The non-postfix configuration
  872. // Info.plist can be used by all the other configurations.
  873. if (!postFix.empty()) {
  874. bundleSkipParts.infoPlist = true;
  875. }
  876. }
  877. this->OSXBundleGenerator->CreateFramework(
  878. tgtNames.Output, gt->GetDirectory(config), config, bundleSkipParts);
  879. } else if (gt->IsCFBundleOnApple()) {
  880. // Create the core foundation bundle.
  881. this->OSXBundleGenerator->CreateCFBundle(tgtNames.Output,
  882. gt->GetDirectory(config), config);
  883. }
  884. // Write comments.
  885. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  886. const cmStateEnums::TargetType targetType = gt->GetType();
  887. this->GetImplFileStream(fileConfig)
  888. << "# Link build statements for " << cmState::GetTargetTypeName(targetType)
  889. << " target " << this->GetTargetName() << "\n\n";
  890. cmNinjaBuild linkBuild(this->LanguageLinkerRule(config));
  891. cmNinjaVars& vars = linkBuild.Variables;
  892. // Compute the comment.
  893. linkBuild.Comment =
  894. cmStrCat("Link the ", this->GetVisibleTypeName(), ' ', targetOutputReal);
  895. // Compute outputs.
  896. linkBuild.Outputs.push_back(targetOutputReal);
  897. if (firstForConfig) {
  898. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutputReal);
  899. }
  900. if (this->TargetLinkLanguage(config) == "Swift") {
  901. vars["SWIFT_LIBRARY_NAME"] = [this, config]() -> std::string {
  902. cmGeneratorTarget::Names targetNames =
  903. this->GetGeneratorTarget()->GetLibraryNames(config);
  904. return targetNames.Base;
  905. }();
  906. vars["SWIFT_MODULE_NAME"] = [gt]() -> std::string {
  907. if (cmProp name = gt->GetProperty("Swift_MODULE_NAME")) {
  908. return *name;
  909. }
  910. return gt->GetName();
  911. }();
  912. vars["SWIFT_MODULE"] = [this](const std::string& module) -> std::string {
  913. std::string directory =
  914. this->GetLocalGenerator()->GetCurrentBinaryDirectory();
  915. if (cmProp prop = this->GetGeneratorTarget()->GetProperty(
  916. "Swift_MODULE_DIRECTORY")) {
  917. directory = *prop;
  918. }
  919. std::string name = module + ".swiftmodule";
  920. if (cmProp prop =
  921. this->GetGeneratorTarget()->GetProperty("Swift_MODULE")) {
  922. name = *prop;
  923. }
  924. return this->GetLocalGenerator()->ConvertToOutputFormat(
  925. this->ConvertToNinjaPath(directory + "/" + name),
  926. cmOutputConverter::SHELL);
  927. }(vars["SWIFT_MODULE_NAME"]);
  928. const std::string map = cmStrCat(gt->GetSupportDirectory(), '/', config,
  929. '/', "output-file-map.json");
  930. vars["SWIFT_OUTPUT_FILE_MAP"] =
  931. this->GetLocalGenerator()->ConvertToOutputFormat(
  932. this->ConvertToNinjaPath(map), cmOutputConverter::SHELL);
  933. vars["SWIFT_SOURCES"] = [this, config]() -> std::string {
  934. std::vector<cmSourceFile const*> sources;
  935. std::stringstream oss;
  936. this->GetGeneratorTarget()->GetObjectSources(sources, config);
  937. cmLocalGenerator const* LocalGen = this->GetLocalGenerator();
  938. for (const auto& source : sources) {
  939. oss << " "
  940. << LocalGen->ConvertToOutputFormat(
  941. this->GetCompiledSourceNinjaPath(source),
  942. cmOutputConverter::SHELL);
  943. }
  944. return oss.str();
  945. }();
  946. // Since we do not perform object builds, compute the
  947. // defines/flags/includes here so that they can be passed along
  948. // appropriately.
  949. vars["DEFINES"] = this->GetDefines("Swift", config);
  950. vars["FLAGS"] = this->GetFlags("Swift", config);
  951. vars["INCLUDES"] = this->GetIncludes("Swift", config);
  952. }
  953. // Compute specific libraries to link with.
  954. if (this->TargetLinkLanguage(config) == "Swift") {
  955. std::vector<cmSourceFile const*> sources;
  956. gt->GetObjectSources(sources, config);
  957. for (const auto& source : sources) {
  958. linkBuild.Outputs.push_back(
  959. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config)));
  960. linkBuild.ExplicitDeps.emplace_back(
  961. this->GetCompiledSourceNinjaPath(source));
  962. }
  963. linkBuild.Outputs.push_back(vars["SWIFT_MODULE"]);
  964. } else {
  965. linkBuild.ExplicitDeps = this->GetObjects(config);
  966. }
  967. std::vector<std::string> extraISPCObjects =
  968. this->GetGeneratorTarget()->GetGeneratedISPCObjects(config);
  969. std::transform(extraISPCObjects.begin(), extraISPCObjects.end(),
  970. std::back_inserter(linkBuild.ExplicitDeps),
  971. this->MapToNinjaPath());
  972. linkBuild.ImplicitDeps =
  973. this->ComputeLinkDeps(this->TargetLinkLanguage(config), config);
  974. if (!this->DeviceLinkObject.empty()) {
  975. linkBuild.ExplicitDeps.push_back(this->DeviceLinkObject);
  976. }
  977. std::string frameworkPath;
  978. std::string linkPath;
  979. std::string createRule =
  980. gt->GetCreateRuleVariable(this->TargetLinkLanguage(config), config);
  981. bool useWatcomQuote = mf->IsOn(createRule + "_USE_WATCOM_QUOTE");
  982. cmLocalNinjaGenerator& localGen = *this->GetLocalGenerator();
  983. vars["TARGET_FILE"] =
  984. localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
  985. std::unique_ptr<cmLinkLineComputer> linkLineComputer =
  986. globalGen->CreateLinkLineComputer(
  987. this->GetLocalGenerator(),
  988. this->GetLocalGenerator()->GetStateSnapshot().GetDirectory());
  989. linkLineComputer->SetUseWatcomQuote(useWatcomQuote);
  990. linkLineComputer->SetUseNinjaMulti(globalGen->IsMultiConfig());
  991. localGen.GetTargetFlags(linkLineComputer.get(), config,
  992. vars["LINK_LIBRARIES"], vars["FLAGS"],
  993. vars["LINK_FLAGS"], frameworkPath, linkPath, gt);
  994. // Add OS X version flags, if any.
  995. if (this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  996. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  997. this->AppendOSXVerFlag(vars["LINK_FLAGS"],
  998. this->TargetLinkLanguage(config), "COMPATIBILITY",
  999. true);
  1000. this->AppendOSXVerFlag(vars["LINK_FLAGS"],
  1001. this->TargetLinkLanguage(config), "CURRENT", false);
  1002. }
  1003. this->addPoolNinjaVariable("JOB_POOL_LINK", gt, vars);
  1004. this->AddModuleDefinitionFlag(linkLineComputer.get(), vars["LINK_FLAGS"],
  1005. config);
  1006. this->UseLWYU = this->GetLocalGenerator()->AppendLWYUFlags(
  1007. vars["LINK_FLAGS"], this->GetGeneratorTarget(),
  1008. this->TargetLinkLanguage(config));
  1009. vars["LINK_FLAGS"] = globalGen->EncodeLiteral(vars["LINK_FLAGS"]);
  1010. vars["MANIFESTS"] = this->GetManifests(config);
  1011. vars["AIX_EXPORTS"] = this->GetAIXExports(config);
  1012. vars["LINK_PATH"] = frameworkPath + linkPath;
  1013. // Compute architecture specific link flags. Yes, these go into a different
  1014. // variable for executables, probably due to a mistake made when duplicating
  1015. // code between the Makefile executable and library generators.
  1016. if (targetType == cmStateEnums::EXECUTABLE) {
  1017. std::string t = vars["FLAGS"];
  1018. localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
  1019. config);
  1020. vars["FLAGS"] = t;
  1021. } else {
  1022. std::string t = vars["ARCH_FLAGS"];
  1023. localGen.AddArchitectureFlags(t, gt, this->TargetLinkLanguage(config),
  1024. config);
  1025. vars["ARCH_FLAGS"] = t;
  1026. t.clear();
  1027. localGen.AddLanguageFlagsForLinking(
  1028. t, gt, this->TargetLinkLanguage(config), config);
  1029. vars["LANGUAGE_COMPILE_FLAGS"] = t;
  1030. }
  1031. if (gt->HasSOName(config)) {
  1032. vars["SONAME_FLAG"] = mf->GetSONameFlag(this->TargetLinkLanguage(config));
  1033. vars["SONAME"] = localGen.ConvertToOutputFormat(tgtNames.SharedObject,
  1034. cmOutputConverter::SHELL);
  1035. if (targetType == cmStateEnums::SHARED_LIBRARY) {
  1036. std::string install_dir = gt->GetInstallNameDirForBuildTree(config);
  1037. if (!install_dir.empty()) {
  1038. vars["INSTALLNAME_DIR"] = localGen.ConvertToOutputFormat(
  1039. install_dir, cmOutputConverter::SHELL);
  1040. }
  1041. }
  1042. }
  1043. cmGlobalNinjaGenerator::CCOutputs byproducts(this->GetGlobalGenerator());
  1044. if (!tgtNames.ImportLibrary.empty()) {
  1045. const std::string impLibPath = localGen.ConvertToOutputFormat(
  1046. targetOutputImplib, cmOutputConverter::SHELL);
  1047. vars["TARGET_IMPLIB"] = impLibPath;
  1048. this->EnsureParentDirectoryExists(impLibPath);
  1049. if (gt->HasImportLibrary(config)) {
  1050. // Some linkers may update a binary without touching its import lib.
  1051. byproducts.ExplicitOuts.emplace_back(targetOutputImplib);
  1052. if (firstForConfig) {
  1053. globalGen->GetByproductsForCleanTarget(config).push_back(
  1054. targetOutputImplib);
  1055. }
  1056. }
  1057. }
  1058. if (!this->SetMsvcTargetPdbVariable(vars, config)) {
  1059. // It is common to place debug symbols at a specific place,
  1060. // so we need a plain target name in the rule available.
  1061. std::string prefix;
  1062. std::string base;
  1063. std::string suffix;
  1064. gt->GetFullNameComponents(prefix, base, suffix, config);
  1065. std::string dbg_suffix = ".dbg";
  1066. // TODO: Where to document?
  1067. if (cmProp d = mf->GetDefinition("CMAKE_DEBUG_SYMBOL_SUFFIX")) {
  1068. dbg_suffix = *d;
  1069. }
  1070. vars["TARGET_PDB"] = base + suffix + dbg_suffix;
  1071. }
  1072. const std::string objPath =
  1073. cmStrCat(gt->GetSupportDirectory(), globalGen->ConfigDirectory(config));
  1074. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1075. this->ConvertToNinjaPath(objPath), cmOutputConverter::SHELL);
  1076. this->EnsureDirectoryExists(objPath);
  1077. std::string& linkLibraries = vars["LINK_LIBRARIES"];
  1078. std::string& link_path = vars["LINK_PATH"];
  1079. if (globalGen->IsGCCOnWindows()) {
  1080. // ar.exe can't handle backslashes in rsp files (implicitly used by gcc)
  1081. std::replace(linkLibraries.begin(), linkLibraries.end(), '\\', '/');
  1082. std::replace(link_path.begin(), link_path.end(), '\\', '/');
  1083. }
  1084. const std::vector<cmCustomCommand>* cmdLists[3] = {
  1085. &gt->GetPreBuildCommands(), &gt->GetPreLinkCommands(),
  1086. &gt->GetPostBuildCommands()
  1087. };
  1088. std::vector<std::string> preLinkCmdLines;
  1089. std::vector<std::string> postBuildCmdLines;
  1090. std::vector<std::string>* cmdLineLists[3] = { &preLinkCmdLines,
  1091. &preLinkCmdLines,
  1092. &postBuildCmdLines };
  1093. for (unsigned i = 0; i != 3; ++i) {
  1094. for (cmCustomCommand const& cc : *cmdLists[i]) {
  1095. if (config == fileConfig ||
  1096. this->GetLocalGenerator()->HasUniqueByproducts(cc.GetByproducts(),
  1097. cc.GetBacktrace())) {
  1098. cmCustomCommandGenerator ccg(cc, fileConfig, this->GetLocalGenerator(),
  1099. true, config);
  1100. localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
  1101. std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
  1102. byproducts.Add(ccByproducts);
  1103. std::transform(
  1104. ccByproducts.begin(), ccByproducts.end(),
  1105. std::back_inserter(globalGen->GetByproductsForCleanTarget()),
  1106. this->MapToNinjaPath());
  1107. }
  1108. }
  1109. }
  1110. // maybe create .def file from list of objects
  1111. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  1112. gt->GetModuleDefinitionInfo(config);
  1113. if (mdi && mdi->DefFileGenerated) {
  1114. std::string cmakeCommand =
  1115. this->GetLocalGenerator()->ConvertToOutputFormat(
  1116. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  1117. std::string cmd =
  1118. cmStrCat(cmakeCommand, " -E __create_def ",
  1119. this->GetLocalGenerator()->ConvertToOutputFormat(
  1120. mdi->DefFile, cmOutputConverter::SHELL),
  1121. ' ');
  1122. std::string obj_list_file = mdi->DefFile + ".objs";
  1123. cmd += this->GetLocalGenerator()->ConvertToOutputFormat(
  1124. obj_list_file, cmOutputConverter::SHELL);
  1125. cmProp nm_executable = this->GetMakefile()->GetDefinition("CMAKE_NM");
  1126. if (cmNonempty(nm_executable)) {
  1127. cmd += " --nm=";
  1128. cmd += this->LocalCommonGenerator->ConvertToOutputFormat(
  1129. *nm_executable, cmOutputConverter::SHELL);
  1130. }
  1131. preLinkCmdLines.push_back(std::move(cmd));
  1132. // create a list of obj files for the -E __create_def to read
  1133. cmGeneratedFileStream fout(obj_list_file);
  1134. if (mdi->WindowsExportAllSymbols) {
  1135. cmNinjaDeps objs = this->GetObjects(config);
  1136. for (std::string const& obj : objs) {
  1137. if (cmHasLiteralSuffix(obj, ".obj")) {
  1138. fout << obj << "\n";
  1139. }
  1140. }
  1141. }
  1142. for (cmSourceFile const* src : mdi->Sources) {
  1143. fout << src->GetFullPath() << "\n";
  1144. }
  1145. }
  1146. // If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
  1147. // for the link commands.
  1148. if (!preLinkCmdLines.empty()) {
  1149. const std::string homeOutDir = localGen.ConvertToOutputFormat(
  1150. localGen.GetBinaryDirectory(), cmOutputConverter::SHELL);
  1151. preLinkCmdLines.push_back("cd " + homeOutDir);
  1152. }
  1153. vars["PRE_LINK"] = localGen.BuildCommandLine(
  1154. preLinkCmdLines, config, fileConfig, "pre-link", this->GeneratorTarget);
  1155. std::string postBuildCmdLine =
  1156. localGen.BuildCommandLine(postBuildCmdLines, config, fileConfig,
  1157. "post-build", this->GeneratorTarget);
  1158. cmNinjaVars symlinkVars;
  1159. bool const symlinkNeeded =
  1160. (targetOutput != targetOutputReal && !gt->IsFrameworkOnApple());
  1161. if (!symlinkNeeded) {
  1162. vars["POST_BUILD"] = postBuildCmdLine;
  1163. } else {
  1164. vars["POST_BUILD"] = cmGlobalNinjaGenerator::SHELL_NOOP;
  1165. symlinkVars["POST_BUILD"] = postBuildCmdLine;
  1166. }
  1167. std::string cmakeVarLang =
  1168. cmStrCat("CMAKE_", this->TargetLinkLanguage(config));
  1169. // build response file name
  1170. std::string cmakeLinkVar = cmakeVarLang + "_RESPONSE_FILE_LINK_FLAG";
  1171. cmProp flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1172. bool const lang_supports_response =
  1173. !(this->TargetLinkLanguage(config) == "RC" ||
  1174. (this->TargetLinkLanguage(config) == "CUDA" && !flag));
  1175. int commandLineLengthLimit = -1;
  1176. if (!lang_supports_response || !this->ForceResponseFile()) {
  1177. commandLineLengthLimit =
  1178. static_cast<int>(cmSystemTools::CalculateCommandLineLengthLimit()) -
  1179. globalGen->GetRuleCmdLength(linkBuild.Rule);
  1180. }
  1181. linkBuild.RspFile = this->ConvertToNinjaPath(
  1182. cmStrCat("CMakeFiles/", gt->GetName(),
  1183. globalGen->IsMultiConfig() ? cmStrCat('.', config) : "", ".rsp"));
  1184. // Gather order-only dependencies.
  1185. this->GetLocalGenerator()->AppendTargetDepends(
  1186. gt, linkBuild.OrderOnlyDeps, config, fileConfig, DependOnTargetArtifact);
  1187. // Add order-only dependencies on versioning symlinks of shared libs we link.
  1188. if (!this->GeneratorTarget->IsDLLPlatform()) {
  1189. if (cmComputeLinkInformation* cli =
  1190. this->GeneratorTarget->GetLinkInformation(config)) {
  1191. for (auto const& item : cli->GetItems()) {
  1192. if (item.Target &&
  1193. item.Target->GetType() == cmStateEnums::SHARED_LIBRARY &&
  1194. !item.Target->IsFrameworkOnApple()) {
  1195. std::string const& lib =
  1196. this->ConvertToNinjaPath(item.Target->GetFullPath(config));
  1197. if (std::find(linkBuild.ImplicitDeps.begin(),
  1198. linkBuild.ImplicitDeps.end(),
  1199. lib) == linkBuild.ImplicitDeps.end()) {
  1200. linkBuild.OrderOnlyDeps.emplace_back(lib);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }
  1206. // Ninja should restat after linking if and only if there are byproducts.
  1207. vars["RESTAT"] = byproducts.ExplicitOuts.empty() ? "" : "1";
  1208. linkBuild.Outputs.reserve(linkBuild.Outputs.size() +
  1209. byproducts.ExplicitOuts.size());
  1210. std::move(byproducts.ExplicitOuts.begin(), byproducts.ExplicitOuts.end(),
  1211. std::back_inserter(linkBuild.Outputs));
  1212. linkBuild.WorkDirOuts = std::move(byproducts.WorkDirOuts);
  1213. // Write the build statement for this target.
  1214. bool usedResponseFile = false;
  1215. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), linkBuild,
  1216. commandLineLengthLimit, &usedResponseFile);
  1217. this->WriteLinkRule(usedResponseFile, config);
  1218. if (symlinkNeeded) {
  1219. if (targetType == cmStateEnums::EXECUTABLE) {
  1220. cmNinjaBuild build("CMAKE_SYMLINK_EXECUTABLE");
  1221. build.Comment = "Create executable symlink " + targetOutput;
  1222. build.Outputs.push_back(targetOutput);
  1223. if (firstForConfig) {
  1224. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
  1225. }
  1226. build.ExplicitDeps.push_back(targetOutputReal);
  1227. build.Variables = std::move(symlinkVars);
  1228. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1229. } else {
  1230. cmNinjaBuild build("CMAKE_SYMLINK_LIBRARY");
  1231. build.Comment = "Create library symlink " + targetOutput;
  1232. std::string const soName = this->ConvertToNinjaPath(
  1233. this->GetTargetFilePath(tgtNames.SharedObject, config));
  1234. // If one link has to be created.
  1235. if (targetOutputReal == soName || targetOutput == soName) {
  1236. symlinkVars["SONAME"] =
  1237. this->GetLocalGenerator()->ConvertToOutputFormat(
  1238. soName, cmOutputConverter::SHELL);
  1239. } else {
  1240. symlinkVars["SONAME"].clear();
  1241. build.Outputs.push_back(soName);
  1242. if (firstForConfig) {
  1243. globalGen->GetByproductsForCleanTarget(config).push_back(soName);
  1244. }
  1245. }
  1246. build.Outputs.push_back(targetOutput);
  1247. if (firstForConfig) {
  1248. globalGen->GetByproductsForCleanTarget(config).push_back(targetOutput);
  1249. }
  1250. build.ExplicitDeps.push_back(targetOutputReal);
  1251. build.Variables = std::move(symlinkVars);
  1252. globalGen->WriteBuild(this->GetImplFileStream(fileConfig), build);
  1253. }
  1254. }
  1255. // Add aliases for the file name and the target name.
  1256. globalGen->AddTargetAlias(tgtNames.Output, gt, config);
  1257. globalGen->AddTargetAlias(this->GetTargetName(), gt, config);
  1258. }
  1259. void cmNinjaNormalTargetGenerator::WriteObjectLibStatement(
  1260. const std::string& config)
  1261. {
  1262. // Write a phony output that depends on all object files.
  1263. {
  1264. cmNinjaBuild build("phony");
  1265. build.Comment = "Object library " + this->GetTargetName();
  1266. this->GetLocalGenerator()->AppendTargetOutputs(this->GetGeneratorTarget(),
  1267. build.Outputs, config);
  1268. this->GetLocalGenerator()->AppendTargetOutputs(
  1269. this->GetGeneratorTarget(),
  1270. this->GetGlobalGenerator()->GetByproductsForCleanTarget(config), config);
  1271. build.ExplicitDeps = this->GetObjects(config);
  1272. this->GetGlobalGenerator()->WriteBuild(this->GetCommonFileStream(), build);
  1273. }
  1274. // Add aliases for the target name.
  1275. this->GetGlobalGenerator()->AddTargetAlias(
  1276. this->GetTargetName(), this->GetGeneratorTarget(), config);
  1277. }
  1278. cmGeneratorTarget::Names cmNinjaNormalTargetGenerator::TargetNames(
  1279. const std::string& config) const
  1280. {
  1281. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
  1282. return this->GeneratorTarget->GetExecutableNames(config);
  1283. }
  1284. return this->GeneratorTarget->GetLibraryNames(config);
  1285. }
  1286. std::string cmNinjaNormalTargetGenerator::TargetLinkLanguage(
  1287. const std::string& config) const
  1288. {
  1289. return this->GeneratorTarget->GetLinkerLanguage(config);
  1290. }