cmNinjaNormalTargetGenerator.cxx 65 KB

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