cmNinjaNormalTargetGenerator.cxx 66 KB

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