cmNinjaNormalTargetGenerator.cxx 61 KB

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