cmNinjaNormalTargetGenerator.cxx 66 KB

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