cmNinjaNormalTargetGenerator.cxx 64 KB

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