cmNinjaNormalTargetGenerator.cxx 55 KB

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