cmNinjaNormalTargetGenerator.cxx 64 KB

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