cmNinjaNormalTargetGenerator.cxx 54 KB

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