cmNinjaTargetGenerator.cxx 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539
  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 "cmNinjaTargetGenerator.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <functional>
  8. #include <iterator>
  9. #include <map>
  10. #include <ostream>
  11. #include <unordered_map>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/string_view>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include <cm3p/json/value.h>
  20. #include <cm3p/json/writer.h>
  21. #include "cmBuildDatabase.h"
  22. #include "cmComputeLinkInformation.h"
  23. #include "cmCustomCommandGenerator.h"
  24. #include "cmDyndepCollation.h"
  25. #include "cmFileSet.h"
  26. #include "cmGeneratedFileStream.h"
  27. #include "cmGeneratorExpression.h"
  28. #include "cmGeneratorOptions.h"
  29. #include "cmGeneratorTarget.h"
  30. #include "cmGlobalCommonGenerator.h"
  31. #include "cmGlobalNinjaGenerator.h"
  32. #include "cmList.h"
  33. #include "cmListFileCache.h"
  34. #include "cmLocalGenerator.h"
  35. #include "cmLocalNinjaGenerator.h"
  36. #include "cmMakefile.h"
  37. #include "cmMessageType.h"
  38. #include "cmNinjaNormalTargetGenerator.h"
  39. #include "cmNinjaUtilityTargetGenerator.h"
  40. #include "cmOutputConverter.h"
  41. #include "cmPolicies.h"
  42. #include "cmRange.h"
  43. #include "cmRulePlaceholderExpander.h"
  44. #include "cmSourceFile.h"
  45. #include "cmState.h"
  46. #include "cmStateTypes.h"
  47. #include "cmStringAlgorithms.h"
  48. #include "cmSystemTools.h"
  49. #include "cmTarget.h"
  50. #include "cmTargetDepend.h"
  51. #include "cmValue.h"
  52. #include "cmake.h"
  53. class cmCustomCommand;
  54. std::unique_ptr<cmNinjaTargetGenerator> cmNinjaTargetGenerator::New(
  55. cmGeneratorTarget* target)
  56. {
  57. switch (target->GetType()) {
  58. case cmStateEnums::EXECUTABLE:
  59. case cmStateEnums::SHARED_LIBRARY:
  60. case cmStateEnums::STATIC_LIBRARY:
  61. case cmStateEnums::MODULE_LIBRARY:
  62. case cmStateEnums::OBJECT_LIBRARY:
  63. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  64. case cmStateEnums::INTERFACE_LIBRARY:
  65. if (target->HaveCxx20ModuleSources()) {
  66. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  67. }
  68. CM_FALLTHROUGH;
  69. case cmStateEnums::UTILITY:
  70. case cmStateEnums::GLOBAL_TARGET:
  71. return cm::make_unique<cmNinjaUtilityTargetGenerator>(target);
  72. default:
  73. return std::unique_ptr<cmNinjaTargetGenerator>();
  74. }
  75. }
  76. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  77. : cmCommonTargetGenerator(target)
  78. , OSXBundleGenerator(nullptr)
  79. , LocalGenerator(
  80. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  81. {
  82. for (auto const& fileConfig : this->LocalGenerator->GetConfigNames()) {
  83. this->Configs[fileConfig].MacOSXContentGenerator =
  84. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  85. }
  86. }
  87. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  88. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  89. std::string const& config) const
  90. {
  91. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  92. }
  93. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  94. {
  95. return *this->GetGlobalGenerator()->GetCommonFileStream();
  96. }
  97. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  98. {
  99. return *this->GetGlobalGenerator()->GetRulesFileStream();
  100. }
  101. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  102. {
  103. return this->LocalGenerator->GetGlobalNinjaGenerator();
  104. }
  105. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  106. std::string const& lang, std::string const& config,
  107. WithScanning withScanning) const
  108. {
  109. return cmStrCat(
  110. lang, "_COMPILER__",
  111. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  112. withScanning == WithScanning::Yes ? "_scanned_" : "_unscanned_", config);
  113. }
  114. std::string cmNinjaTargetGenerator::LanguagePreprocessAndScanRule(
  115. std::string const& lang, std::string const& config) const
  116. {
  117. return cmStrCat(
  118. lang, "_PREPROCESS_SCAN__",
  119. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  120. '_', config);
  121. }
  122. std::string cmNinjaTargetGenerator::LanguageScanRule(
  123. std::string const& lang, std::string const& config) const
  124. {
  125. return cmStrCat(
  126. lang, "_SCAN__",
  127. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  128. '_', config);
  129. }
  130. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  131. std::string const& lang) const
  132. {
  133. return lang == "Fortran" || lang == "Swift";
  134. }
  135. bool cmNinjaTargetGenerator::CompileWithDefines(std::string const& lang) const
  136. {
  137. return this->Makefile->IsOn(
  138. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  139. }
  140. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  141. std::string const& lang, std::string const& config) const
  142. {
  143. return cmStrCat(
  144. lang, "_DYNDEP__",
  145. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  146. '_', config);
  147. }
  148. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  149. std::string const& config)
  150. {
  151. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  152. this->GeneratorTarget, config);
  153. }
  154. std::string cmNinjaTargetGenerator::OrderDependsTargetForTargetPrivate(
  155. std::string const& config)
  156. {
  157. return this->GetGlobalGenerator()->OrderDependsTargetForTargetPrivate(
  158. this->GeneratorTarget, config);
  159. }
  160. // TODO: Most of the code is picked up from
  161. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  162. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  163. // Refactor it.
  164. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  165. cmSourceFile const* source, std::string const& language,
  166. std::string const& config, std::string const& objectFileName)
  167. {
  168. std::unordered_map<std::string, std::string> pchSources;
  169. std::vector<std::string> pchArchs =
  170. this->GeneratorTarget->GetPchArchs(config, language);
  171. std::string filterArch;
  172. for (std::string const& arch : pchArchs) {
  173. std::string const pchSource =
  174. this->GeneratorTarget->GetPchSource(config, language, arch);
  175. if (pchSource == source->GetFullPath()) {
  176. filterArch = arch;
  177. }
  178. if (!pchSource.empty()) {
  179. pchSources.insert(std::make_pair(pchSource, arch));
  180. }
  181. }
  182. std::string flags;
  183. // Explicitly add the explicit language flag before any other flag
  184. // so user flags can override it.
  185. this->GeneratorTarget->AddExplicitLanguageFlags(flags, *source);
  186. if (!flags.empty()) {
  187. flags += " ";
  188. }
  189. flags += this->GetFlags(language, config, filterArch);
  190. // Add Fortran format flags.
  191. if (language == "Fortran") {
  192. this->AppendFortranFormatFlags(flags, *source);
  193. this->AppendFortranPreprocessFlags(flags, *source,
  194. PreprocessFlagsRequired::NO);
  195. }
  196. // Add source file specific flags.
  197. cmGeneratorExpressionInterpreter genexInterpreter(
  198. this->LocalGenerator, config, this->GeneratorTarget, language);
  199. std::string const COMPILE_FLAGS("COMPILE_FLAGS");
  200. if (cmValue cflags = source->GetProperty(COMPILE_FLAGS)) {
  201. this->LocalGenerator->AppendFlags(
  202. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  203. }
  204. std::string const COMPILE_OPTIONS("COMPILE_OPTIONS");
  205. if (cmValue coptions = source->GetProperty(COMPILE_OPTIONS)) {
  206. this->LocalGenerator->AppendCompileOptions(
  207. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  208. }
  209. // Add precompile headers compile options.
  210. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  211. std::string pchOptions;
  212. auto pchIt = pchSources.find(source->GetFullPath());
  213. if (pchIt != pchSources.end()) {
  214. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  215. config, language, pchIt->second);
  216. } else {
  217. pchOptions =
  218. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  219. }
  220. this->LocalGenerator->AppendCompileOptions(
  221. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  222. }
  223. auto const* fs = this->GeneratorTarget->GetFileSetForSource(config, source);
  224. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  225. if (source->GetLanguage() != "CXX"_s) {
  226. this->GetMakefile()->IssueMessage(
  227. MessageType::FATAL_ERROR,
  228. cmStrCat("Target \"", this->GeneratorTarget->Target->GetName(),
  229. "\" contains the source\n ", source->GetFullPath(),
  230. "\nin a file set of type \"", fs->GetType(),
  231. R"(" but the source is not classified as a "CXX" source.)"));
  232. }
  233. if (!this->GeneratorTarget->Target->IsNormal()) {
  234. auto flag = this->GetMakefile()->GetSafeDefinition(
  235. "CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  236. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  237. compileObjectVars.Object = objectFileName.c_str();
  238. auto rulePlaceholderExpander =
  239. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  240. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  241. flag, compileObjectVars);
  242. this->LocalGenerator->AppendCompileOptions(flags, flag);
  243. }
  244. }
  245. return flags;
  246. }
  247. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  248. std::string const& language,
  249. std::string const& config)
  250. {
  251. std::vector<std::string> includes;
  252. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  253. language, config);
  254. // Add include directory flags.
  255. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  256. includes, this->GeneratorTarget, language, config, false);
  257. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  258. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  259. }
  260. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  261. }
  262. // TODO: Refactor with
  263. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  264. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  265. std::string const& language,
  266. std::string const& config)
  267. {
  268. std::set<std::string> defines;
  269. cmGeneratorExpressionInterpreter genexInterpreter(
  270. this->LocalGenerator, config, this->GeneratorTarget, language);
  271. // Seriously??
  272. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  273. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  274. }
  275. std::string const COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  276. if (cmValue compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  277. this->LocalGenerator->AppendDefines(
  278. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  279. }
  280. std::string defPropName =
  281. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  282. if (cmValue config_compile_defs = source->GetProperty(defPropName)) {
  283. this->LocalGenerator->AppendDefines(
  284. defines,
  285. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  286. }
  287. std::string definesString = this->GetDefines(language, config);
  288. this->LocalGenerator->JoinDefines(defines, definesString, language);
  289. return definesString;
  290. }
  291. std::string cmNinjaTargetGenerator::ComputeIncludes(
  292. cmSourceFile const* source, std::string const& language,
  293. std::string const& config)
  294. {
  295. std::vector<std::string> includes;
  296. cmGeneratorExpressionInterpreter genexInterpreter(
  297. this->LocalGenerator, config, this->GeneratorTarget, language);
  298. std::string const INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  299. if (cmValue cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  300. this->LocalGenerator->AppendIncludeDirectories(
  301. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  302. *source);
  303. }
  304. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  305. includes, this->GeneratorTarget, language, config, false);
  306. this->LocalGenerator->AppendFlags(includesString,
  307. this->GetIncludes(language, config));
  308. return includesString;
  309. }
  310. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  311. std::string const& linkLanguage, std::string const& config,
  312. bool ignoreType) const
  313. {
  314. // Static libraries never depend on other targets for linking.
  315. if (!ignoreType &&
  316. (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  317. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  318. return cmNinjaDeps();
  319. }
  320. cmComputeLinkInformation* cli =
  321. this->GeneratorTarget->GetLinkInformation(config);
  322. if (!cli) {
  323. return cmNinjaDeps();
  324. }
  325. std::vector<std::string> const& deps = cli->GetDepends();
  326. cmNinjaDeps result(deps.size());
  327. std::transform(deps.begin(), deps.end(), result.begin(),
  328. this->MapToNinjaPath());
  329. // Add a dependency on the link definitions file, if any.
  330. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  331. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  332. for (cmSourceFile const* src : mdi->Sources) {
  333. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  334. }
  335. }
  336. // Add a dependency on user-specified manifest files, if any.
  337. std::vector<cmSourceFile const*> manifest_srcs;
  338. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  339. for (cmSourceFile const* manifest_src : manifest_srcs) {
  340. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  341. }
  342. // Add user-specified dependencies.
  343. std::vector<std::string> linkDeps;
  344. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  345. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  346. this->MapToNinjaPath());
  347. return result;
  348. }
  349. std::string cmNinjaTargetGenerator::GetCompiledSourceNinjaPath(
  350. cmSourceFile const* source) const
  351. {
  352. // Pass source files to the compiler by absolute path.
  353. return this->ConvertToNinjaAbsPath(source->GetFullPath());
  354. }
  355. std::string cmNinjaTargetGenerator::GetObjectFileDir(
  356. std::string const& config) const
  357. {
  358. return this->LocalGenerator->MaybeRelativeToTopBinDir(
  359. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  360. this->GetGlobalGenerator()->GetConfigDirectory(config)));
  361. }
  362. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  363. cmSourceFile const* source, std::string const& config) const
  364. {
  365. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  366. return cmStrCat(this->GetObjectFileDir(config), '/', objectName);
  367. }
  368. std::string cmNinjaTargetGenerator::GetBmiFilePath(
  369. cmSourceFile const* source, std::string const& config) const
  370. {
  371. auto& importedConfigInfo = this->Configs.at(config).ImportedCxxModules;
  372. if (!importedConfigInfo.Initialized()) {
  373. std::string configUpper = cmSystemTools::UpperCase(config);
  374. std::string propName = cmStrCat("IMPORTED_CXX_MODULES_", configUpper);
  375. auto value = this->GeneratorTarget->GetSafeProperty(propName);
  376. importedConfigInfo.Initialize(value);
  377. }
  378. std::string bmiName =
  379. importedConfigInfo.BmiNameForSource(source->GetFullPath());
  380. return cmStrCat(this->GetObjectFileDir(config), '/', bmiName);
  381. }
  382. std::string cmNinjaTargetGenerator::GetClangTidyReplacementsFilePath(
  383. std::string const& directory, cmSourceFile const& source,
  384. std::string const& config) const
  385. {
  386. auto const& objectName = this->GeneratorTarget->GetObjectName(&source);
  387. return cmStrCat(directory, '/',
  388. this->LocalGenerator->CreateSafeObjectFileName(
  389. this->GetObjectFileDir(config)),
  390. '/', objectName, ".yaml");
  391. }
  392. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  393. cmSourceFile const* source, std::string const& config) const
  394. {
  395. // Choose an extension to compile already-preprocessed source.
  396. std::string ppExt = source->GetExtension();
  397. if (cmHasLiteralPrefix(ppExt, "F")) {
  398. // Some Fortran compilers automatically enable preprocessing for
  399. // upper-case extensions. Since the source is already preprocessed,
  400. // use a lower-case extension.
  401. ppExt = cmSystemTools::LowerCase(ppExt);
  402. }
  403. if (ppExt == "fpp") {
  404. // Some Fortran compilers automatically enable preprocessing for
  405. // the ".fpp" extension. Since the source is already preprocessed,
  406. // use the ".f" extension.
  407. ppExt = "f";
  408. }
  409. // Take the object file name and replace the extension.
  410. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  411. std::string const& objExt =
  412. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  413. assert(objName.size() >= objExt.size());
  414. std::string const ppName =
  415. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  416. return cmStrCat(this->GetObjectFileDir(config), '/', ppName);
  417. }
  418. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  419. std::string const& lang, std::string const& config) const
  420. {
  421. return cmStrCat(this->GetObjectFileDir(config), '/', lang, ".dd");
  422. }
  423. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  424. std::string const& lang, std::string const& config) const
  425. {
  426. return cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  427. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  428. lang, "DependInfo.json");
  429. }
  430. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  431. std::string const& config) const
  432. {
  433. std::string dir = this->GeneratorTarget->GetDirectory(config);
  434. return this->ConvertToNinjaPath(dir);
  435. }
  436. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  437. std::string const& name, std::string const& config) const
  438. {
  439. std::string path = this->GetTargetOutputDir(config);
  440. if (path.empty() || path == ".") {
  441. return name;
  442. }
  443. path += cmStrCat('/', name);
  444. return path;
  445. }
  446. std::string cmNinjaTargetGenerator::GetTargetName() const
  447. {
  448. return this->GeneratorTarget->GetName();
  449. }
  450. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  451. cmNinjaVars& vars, std::string const& config) const
  452. {
  453. cmMakefile* mf = this->GetMakefile();
  454. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  455. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  456. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  457. std::string pdbPath;
  458. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  459. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  460. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  461. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  462. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  463. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  464. this->GeneratorTarget->GetPDBName(config));
  465. }
  466. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  467. this->ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  468. vars["TARGET_COMPILE_PDB"] =
  469. this->GetLocalGenerator()->ConvertToOutputFormat(
  470. this->ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  471. this->EnsureParentDirectoryExists(pdbPath);
  472. this->EnsureParentDirectoryExists(compilePdbPath);
  473. return true;
  474. }
  475. return false;
  476. }
  477. void cmNinjaTargetGenerator::WriteLanguageRules(std::string const& language,
  478. std::string const& config)
  479. {
  480. #ifdef NINJA_GEN_VERBOSE_FILES
  481. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  482. #endif
  483. this->WriteCompileRule(language, config);
  484. }
  485. namespace {
  486. // Create the command to run the dependency scanner
  487. std::string GetScanCommand(
  488. cm::string_view cmakeCmd, cm::string_view tdi, cm::string_view lang,
  489. cm::string_view srcFile, cm::string_view ddiFile,
  490. cm::optional<cm::string_view> srcOrigFile = cm::nullopt)
  491. {
  492. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  493. " --lang=", lang, " --src=", srcFile,
  494. " --out=$out"
  495. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=",
  496. ddiFile,
  497. srcOrigFile ? cmStrCat(" --src-orig=", *srcOrigFile) : "");
  498. }
  499. // Helper function to create dependency scanning rule that may or may
  500. // not perform explicit preprocessing too.
  501. cmNinjaRule GetScanRule(
  502. std::string const& ruleName, std::string const& ppFileName,
  503. std::string const& deptype,
  504. cmRulePlaceholderExpander::RuleVariables const& vars,
  505. std::string const& responseFlag, std::string const& flags,
  506. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  507. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds,
  508. std::string const& outputConfig)
  509. {
  510. cmNinjaRule rule(ruleName);
  511. // Scanning always uses a depfile for preprocessor dependencies.
  512. if (deptype == "msvc"_s) {
  513. rule.DepType = deptype;
  514. rule.DepFile.clear();
  515. } else {
  516. rule.DepType.clear(); // no deps= for multiple outputs
  517. rule.DepFile = "$DEP_FILE";
  518. }
  519. cmRulePlaceholderExpander::RuleVariables scanVars;
  520. scanVars.CMTargetName = vars.CMTargetName;
  521. scanVars.CMTargetType = vars.CMTargetType;
  522. scanVars.CMTargetLabels = vars.CMTargetLabels;
  523. scanVars.Language = vars.Language;
  524. scanVars.Object = "$OBJ_FILE";
  525. scanVars.PreprocessedSource = ppFileName.c_str();
  526. scanVars.DynDepFile = "$DYNDEP_INTERMEDIATE_FILE";
  527. scanVars.DependencyFile = rule.DepFile.c_str();
  528. scanVars.DependencyTarget = "$out";
  529. scanVars.Config = vars.Config;
  530. // Scanning needs the same preprocessor settings as direct compilation would.
  531. scanVars.Source = vars.Source;
  532. scanVars.Defines = vars.Defines;
  533. scanVars.Includes = vars.Includes;
  534. // Scanning needs the compilation flags too.
  535. std::string scanFlags = flags;
  536. // If using a response file, move defines, includes, and flags into it.
  537. if (!responseFlag.empty()) {
  538. rule.RspFile = "$RSP_FILE";
  539. rule.RspContent =
  540. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  541. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  542. scanVars.Defines = "";
  543. scanVars.Includes = "";
  544. }
  545. scanVars.Flags = scanFlags.c_str();
  546. // Rule for scanning a source file.
  547. for (std::string& scanCmd : scanCmds) {
  548. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  549. }
  550. rule.Command =
  551. generator->BuildCommandLine(scanCmds, outputConfig, outputConfig);
  552. return rule;
  553. }
  554. }
  555. void cmNinjaTargetGenerator::WriteCompileRule(std::string const& lang,
  556. std::string const& config)
  557. {
  558. // For some cases we scan to dynamically discover dependencies.
  559. bool const needDyndep = this->GetGeneratorTarget()->NeedDyndep(lang, config);
  560. if (needDyndep) {
  561. this->WriteCompileRule(lang, config, WithScanning::Yes);
  562. }
  563. this->WriteCompileRule(lang, config, WithScanning::No);
  564. }
  565. void cmNinjaTargetGenerator::WriteCompileRule(std::string const& lang,
  566. std::string const& config,
  567. WithScanning withScanning)
  568. {
  569. cmRulePlaceholderExpander::RuleVariables vars;
  570. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  571. vars.CMTargetType =
  572. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  573. vars.CMTargetLabels =
  574. this->GetGeneratorTarget()->GetTargetLabelsString().c_str();
  575. vars.Language = lang.c_str();
  576. vars.Source = "$in";
  577. vars.Object = "$out";
  578. vars.Defines = "$DEFINES";
  579. vars.Includes = "$INCLUDES";
  580. vars.TargetPDB = "$TARGET_PDB";
  581. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  582. vars.ObjectDir = "$OBJECT_DIR";
  583. vars.TargetSupportDir = "$TARGET_SUPPORT_DIR";
  584. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  585. vars.CudaCompileMode = "$CUDA_COMPILE_MODE";
  586. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  587. vars.Config = "$CONFIG";
  588. cmMakefile* mf = this->GetMakefile();
  589. // For some cases we scan to dynamically discover dependencies.
  590. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  591. std::string flags = "$FLAGS";
  592. std::string responseFlag;
  593. bool const lang_supports_response = lang != "RC";
  594. if (lang_supports_response && this->ForceResponseFile()) {
  595. std::string const responseFlagVar =
  596. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  597. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  598. if (responseFlag.empty() && lang != "CUDA") {
  599. responseFlag = "@";
  600. }
  601. }
  602. std::string const modmapFormatVar =
  603. cmStrCat("CMAKE_", lang, "_MODULE_MAP_FORMAT");
  604. std::string const modmapFormat =
  605. this->Makefile->GetSafeDefinition(modmapFormatVar);
  606. auto rulePlaceholderExpander =
  607. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  608. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  609. this->ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  610. cmLocalGenerator::SHELL);
  611. std::string launcher;
  612. std::string val = this->GetLocalGenerator()->GetRuleLauncher(
  613. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE", config);
  614. if (cmNonempty(val)) {
  615. launcher = cmStrCat(val, ' ');
  616. }
  617. std::string const cmakeCmd =
  618. this->GetLocalGenerator()->ConvertToOutputFormat(
  619. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  620. if (withScanning == WithScanning::Yes) {
  621. auto const& scanDepType = this->GetMakefile()->GetSafeDefinition(
  622. cmStrCat("CMAKE_", lang, "_SCANDEP_DEPFILE_FORMAT"));
  623. // Rule to scan dependencies of sources that need preprocessing.
  624. {
  625. cmList scanCommands;
  626. std::string scanRuleName;
  627. std::string ppFileName;
  628. if (compilationPreprocesses) {
  629. scanRuleName = this->LanguageScanRule(lang, config);
  630. ppFileName = "$PREPROCESSED_OUTPUT_FILE";
  631. std::string const& scanCommand = mf->GetRequiredDefinition(
  632. cmStrCat("CMAKE_", lang, "_SCANDEP_SOURCE"));
  633. scanCommands.assign(scanCommand);
  634. for (auto& i : scanCommands) {
  635. i = cmStrCat(launcher, i);
  636. }
  637. } else {
  638. scanRuleName = this->LanguagePreprocessAndScanRule(lang, config);
  639. ppFileName = "$out";
  640. std::string const& ppCommand = mf->GetRequiredDefinition(
  641. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  642. scanCommands.assign(ppCommand);
  643. for (auto& i : scanCommands) {
  644. i = cmStrCat(launcher, i);
  645. }
  646. scanCommands.emplace_back(GetScanCommand(
  647. cmakeCmd, tdi, lang, "$out", "$DYNDEP_INTERMEDIATE_FILE", "$in"));
  648. }
  649. auto scanRule = GetScanRule(
  650. scanRuleName, ppFileName, scanDepType, vars, responseFlag, flags,
  651. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  652. std::move(scanCommands), config);
  653. scanRule.Comment =
  654. cmStrCat("Rule for generating ", lang, " dependencies.");
  655. if (compilationPreprocesses) {
  656. scanRule.Description =
  657. cmStrCat("Scanning $in for ", lang, " dependencies");
  658. } else {
  659. scanRule.Description =
  660. cmStrCat("Building ", lang, " preprocessed $out");
  661. }
  662. this->GetGlobalGenerator()->AddRule(scanRule);
  663. }
  664. if (!compilationPreprocesses) {
  665. // Compilation will not preprocess, so it does not need the defines
  666. // unless the compiler wants them for some other purpose.
  667. if (!this->CompileWithDefines(lang)) {
  668. vars.Defines = "";
  669. }
  670. // Rule to scan dependencies of sources that do not need preprocessing.
  671. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  672. std::vector<std::string> scanCommands;
  673. scanCommands.emplace_back(
  674. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  675. auto scanRule =
  676. GetScanRule(scanRuleName, "", scanDepType, vars, "", flags,
  677. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  678. std::move(scanCommands), config);
  679. // Write the rule for generating dependencies for the given language.
  680. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  681. " dependencies on non-preprocessed files.");
  682. scanRule.Description =
  683. cmStrCat("Generating ", lang, " dependencies for $in");
  684. this->GetGlobalGenerator()->AddRule(scanRule);
  685. }
  686. // Write the rule for ninja dyndep file generation.
  687. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  688. // Command line length is almost always limited -> use response file for
  689. // dyndep rules
  690. rule.RspFile = "$out.rsp";
  691. rule.RspContent = "$in";
  692. // Ninja's collator writes all outputs using `cmGeneratedFileStream`, so
  693. // they are only updated if contents actually change. Avoid running
  694. // dependent jobs if the contents don't change by telling `ninja` to check
  695. // the timestamp again.
  696. rule.Restat = "1";
  697. // Run CMake dependency scanner on the source file (using the preprocessed
  698. // source if that was performed).
  699. std::string ddModmapArg;
  700. if (!modmapFormat.empty()) {
  701. ddModmapArg += cmStrCat(" --modmapfmt=", modmapFormat);
  702. }
  703. {
  704. std::vector<std::string> ddCmds;
  705. {
  706. std::string ccmd = cmStrCat(
  707. cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, " --lang=", lang,
  708. ddModmapArg, " --dd=$out @", rule.RspFile);
  709. ddCmds.emplace_back(std::move(ccmd));
  710. }
  711. rule.Command =
  712. this->GetLocalGenerator()->BuildCommandLine(ddCmds, config, config);
  713. }
  714. rule.Comment =
  715. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  716. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  717. this->GetGlobalGenerator()->AddRule(rule);
  718. }
  719. cmNinjaRule rule(this->LanguageCompilerRule(lang, config, withScanning));
  720. // If using a response file, move defines, includes, and flags into it.
  721. if (!responseFlag.empty()) {
  722. rule.RspFile = "$RSP_FILE";
  723. rule.RspContent =
  724. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  725. flags = cmStrCat(responseFlag, rule.RspFile);
  726. vars.Defines = "";
  727. vars.Includes = "";
  728. // Swift consumes all source files in a module at once, which reaches
  729. // command line length limits pretty quickly. Inject source files into the
  730. // response file in this case as well.
  731. if (lang == "Swift") {
  732. rule.RspContent = cmStrCat(rule.RspContent, ' ', vars.Source);
  733. vars.Source = "";
  734. }
  735. }
  736. // Tell ninja dependency format so all deps can be loaded into a database
  737. std::string cldeps;
  738. if (!compilationPreprocesses) {
  739. // The compiler will not do preprocessing, so it has no such dependencies.
  740. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  741. // For the MS resource compiler we need cmcldeps, but skip dependencies
  742. // for source-file try_compile cases because they are always fresh.
  743. if (!mf->GetIsSourceFileTryCompile()) {
  744. rule.DepType = "gcc";
  745. rule.DepFile = "$DEP_FILE";
  746. cmValue d = mf->GetDefinition("CMAKE_C_COMPILER");
  747. std::string const cl =
  748. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  749. std::string cmcldepsPath;
  750. cmSystemTools::GetShortPath(cmSystemTools::GetCMClDepsCommand(),
  751. cmcldepsPath);
  752. cldeps = cmStrCat(cmcldepsPath, ' ', lang, ' ', vars.Source,
  753. " $DEP_FILE $out \"",
  754. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  755. "\" \"", cl, "\" ");
  756. }
  757. } else {
  758. auto const& depType = this->GetMakefile()->GetSafeDefinition(
  759. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  760. if (depType == "msvc"_s) {
  761. rule.DepType = "msvc";
  762. rule.DepFile.clear();
  763. } else {
  764. rule.DepType = "gcc";
  765. rule.DepFile = "$DEP_FILE";
  766. }
  767. vars.DependencyFile = rule.DepFile.c_str();
  768. vars.DependencyTarget = "$out";
  769. std::string const flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  770. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  771. if (!depfileFlags.empty()) {
  772. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  773. depfileFlags, vars);
  774. flags += cmStrCat(' ', depfileFlags);
  775. }
  776. }
  777. if (withScanning == WithScanning::Yes && !modmapFormat.empty()) {
  778. std::string modmapFlags =
  779. mf->GetRequiredDefinition(cmStrCat("CMAKE_", lang, "_MODULE_MAP_FLAG"));
  780. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  781. "$DYNDEP_MODULE_MAP_FILE");
  782. flags += cmStrCat(' ', modmapFlags);
  783. }
  784. vars.Flags = flags.c_str();
  785. vars.DependencyFile = rule.DepFile.c_str();
  786. std::string cudaCompileMode;
  787. if (lang == "CUDA") {
  788. if (this->GeneratorTarget->GetPropertyAsBool(
  789. "CUDA_SEPARABLE_COMPILATION")) {
  790. std::string const& rdcFlag =
  791. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  792. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, ' ');
  793. }
  794. static std::array<cm::string_view, 4> const compileModes{
  795. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  796. };
  797. bool useNormalCompileMode = true;
  798. for (cm::string_view mode : compileModes) {
  799. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  800. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  801. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  802. std::string const& flag =
  803. this->Makefile->GetRequiredDefinition(defName);
  804. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  805. useNormalCompileMode = false;
  806. break;
  807. }
  808. }
  809. if (useNormalCompileMode) {
  810. std::string const& wholeFlag =
  811. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  812. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  813. }
  814. vars.CudaCompileMode = cudaCompileMode.c_str();
  815. }
  816. // Rule for compiling object file.
  817. std::string const cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  818. std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
  819. cmList compileCmds(compileCmd);
  820. if (!compileCmds.empty()) {
  821. compileCmds.front().insert(0, "${CODE_CHECK}");
  822. compileCmds.front().insert(0, "${LAUNCHER}");
  823. }
  824. if (!compileCmds.empty()) {
  825. compileCmds.front().insert(0, cldeps);
  826. }
  827. auto const& extraCommands = this->GetMakefile()->GetSafeDefinition(
  828. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  829. if (!extraCommands.empty()) {
  830. compileCmds.append(extraCommands);
  831. }
  832. for (auto& i : compileCmds) {
  833. i = cmStrCat(launcher, i);
  834. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  835. vars);
  836. }
  837. rule.Command =
  838. this->GetLocalGenerator()->BuildCommandLine(compileCmds, config, config);
  839. // Write the rule for compiling file of the given language.
  840. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  841. rule.Description = cmStrCat("Building ", lang, " object $out");
  842. this->GetGlobalGenerator()->AddRule(rule);
  843. }
  844. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  845. std::string const& config, std::string const& fileConfig,
  846. bool firstForConfig)
  847. {
  848. this->GeneratorTarget->CheckCxxModuleStatus(config);
  849. // Write comments.
  850. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  851. this->GetImplFileStream(fileConfig)
  852. << "# Object build statements for "
  853. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  854. << " target " << this->GetTargetName() << "\n\n";
  855. std::vector<cmCustomCommand const*> customCommands;
  856. {
  857. std::vector<cmSourceFile const*> customCommandSources;
  858. this->GeneratorTarget->GetCustomCommands(customCommandSources, config);
  859. for (cmSourceFile const* sf : customCommandSources) {
  860. cmCustomCommand const* cc = sf->GetCustomCommand();
  861. this->GetLocalGenerator()->AddCustomCommandTarget(
  862. cc, this->GetGeneratorTarget());
  863. customCommands.push_back(cc);
  864. }
  865. }
  866. {
  867. std::vector<cmSourceFile const*> headerSources;
  868. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  869. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  870. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  871. config);
  872. }
  873. {
  874. std::vector<cmSourceFile const*> extraSources;
  875. this->GeneratorTarget->GetExtraSources(extraSources, config);
  876. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  877. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  878. config);
  879. }
  880. if (firstForConfig) {
  881. cmValue pchExtension =
  882. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  883. std::vector<cmSourceFile const*> externalObjects;
  884. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  885. for (cmSourceFile const* sf : externalObjects) {
  886. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  887. this->ConvertToNinjaPath(sf->GetFullPath()), config);
  888. if (!cmHasSuffix(objectFileName, pchExtension)) {
  889. this->Configs[config].Objects.push_back(objectFileName);
  890. }
  891. }
  892. }
  893. if (!this->GetGlobalGenerator()->SupportsCWDDepend()) {
  894. // Ensure that the object directory exists. If there are no objects in the
  895. // target (e.g., an empty `OBJECT` library), the directory is still listed
  896. // as an order-only depends in the build files. Alternate `ninja`
  897. // implementations may not allow this (such as `samu`). See #25526.
  898. auto const objectDir = this->GetObjectFileDir(config);
  899. this->EnsureDirectoryExists(objectDir);
  900. }
  901. {
  902. cmNinjaBuild build("phony");
  903. build.Comment =
  904. cmStrCat("Order-only phony target for ", this->GetTargetName());
  905. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  906. // Gather order-only dependencies on custom command outputs.
  907. std::vector<std::string> ccouts;
  908. std::vector<std::string> ccouts_private;
  909. bool usePrivateGeneratedSources = false;
  910. if (this->GeneratorTarget->Target->HasFileSets()) {
  911. switch (this->GetGeneratorTarget()->GetPolicyStatusCMP0154()) {
  912. case cmPolicies::WARN:
  913. case cmPolicies::OLD:
  914. break;
  915. case cmPolicies::NEW:
  916. usePrivateGeneratedSources = true;
  917. break;
  918. }
  919. }
  920. for (cmCustomCommand const* cc : customCommands) {
  921. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  922. std::vector<std::string> const& ccoutputs = ccg.GetOutputs();
  923. std::vector<std::string> const& ccbyproducts = ccg.GetByproducts();
  924. auto const nPreviousOutputs = ccouts.size();
  925. ccouts.insert(ccouts.end(), ccoutputs.begin(), ccoutputs.end());
  926. ccouts.insert(ccouts.end(), ccbyproducts.begin(), ccbyproducts.end());
  927. if (usePrivateGeneratedSources) {
  928. auto it = ccouts.begin();
  929. // Skip over outputs that were already detected.
  930. std::advance(it, nPreviousOutputs);
  931. while (it != ccouts.end()) {
  932. cmFileSet const* fileset =
  933. this->GeneratorTarget->GetFileSetForSource(
  934. config, this->Makefile->GetOrCreateGeneratedSource(*it));
  935. bool isVisible = fileset &&
  936. cmFileSetVisibilityIsForInterface(fileset->GetVisibility());
  937. bool isIncludeable =
  938. !fileset || cmFileSetTypeCanBeIncluded(fileset->GetType());
  939. if (fileset && isVisible && isIncludeable) {
  940. ++it;
  941. continue;
  942. }
  943. if (!fileset || isIncludeable) {
  944. ccouts_private.push_back(*it);
  945. }
  946. it = ccouts.erase(it);
  947. }
  948. }
  949. }
  950. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  951. this->GetLocalGenerator()->AppendTargetDepends(
  952. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  953. DependOnTargetOrdering);
  954. // Add order-only dependencies on other files associated with the target.
  955. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  956. // Add order-only dependencies on custom command outputs.
  957. std::transform(ccouts.begin(), ccouts.end(),
  958. std::back_inserter(orderOnlyDeps), this->MapToNinjaPath());
  959. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  960. orderOnlyDeps.erase(
  961. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  962. orderOnlyDeps.end());
  963. // The phony target must depend on at least one input or ninja will explain
  964. // that "output ... of phony edge with no inputs doesn't exist" and
  965. // consider the phony output "dirty".
  966. if (orderOnlyDeps.empty()) {
  967. std::string tgtDir;
  968. if (this->GetGlobalGenerator()->SupportsCWDDepend()) {
  969. tgtDir = ".";
  970. } else {
  971. // Any path that always exists will work here.
  972. tgtDir = this->GetObjectFileDir(config);
  973. }
  974. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  975. }
  976. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  977. build);
  978. // Add order-only dependencies on custom command outputs that are
  979. // private to this target.
  980. this->HasPrivateGeneratedSources = !ccouts_private.empty();
  981. if (this->HasPrivateGeneratedSources) {
  982. cmNinjaBuild buildPrivate("phony");
  983. cmNinjaDeps& orderOnlyDepsPrivate = buildPrivate.OrderOnlyDeps;
  984. orderOnlyDepsPrivate.push_back(
  985. this->OrderDependsTargetForTarget(config));
  986. buildPrivate.Outputs.push_back(
  987. this->OrderDependsTargetForTargetPrivate(config));
  988. std::transform(ccouts_private.begin(), ccouts_private.end(),
  989. std::back_inserter(orderOnlyDepsPrivate),
  990. this->MapToNinjaPath());
  991. std::sort(orderOnlyDepsPrivate.begin(), orderOnlyDepsPrivate.end());
  992. orderOnlyDepsPrivate.erase(
  993. std::unique(orderOnlyDepsPrivate.begin(), orderOnlyDepsPrivate.end()),
  994. orderOnlyDepsPrivate.end());
  995. this->GetGlobalGenerator()->WriteBuild(
  996. this->GetImplFileStream(fileConfig), buildPrivate);
  997. }
  998. }
  999. {
  1000. std::vector<cmSourceFile const*> objectSources;
  1001. this->GeneratorTarget->GetObjectSources(objectSources, config);
  1002. std::vector<cmSourceFile const*> swiftSources;
  1003. for (cmSourceFile const* sf : objectSources) {
  1004. if (this->GetLocalGenerator()->IsSplitSwiftBuild() &&
  1005. sf->GetLanguage() == "Swift") {
  1006. swiftSources.push_back(sf);
  1007. } else {
  1008. this->WriteObjectBuildStatement(sf, config, fileConfig,
  1009. firstForConfig);
  1010. }
  1011. }
  1012. WriteSwiftObjectBuildStatement(swiftSources, config, fileConfig,
  1013. firstForConfig);
  1014. }
  1015. {
  1016. std::vector<cmSourceFile const*> bmiOnlySources;
  1017. this->GeneratorTarget->GetCxxModuleSources(bmiOnlySources, config);
  1018. for (cmSourceFile const* sf : bmiOnlySources) {
  1019. this->WriteCxxModuleBmiBuildStatement(sf, config, fileConfig,
  1020. firstForConfig);
  1021. }
  1022. }
  1023. // Detect sources in `CXX_MODULES` which are not compiled.
  1024. {
  1025. std::vector<cmSourceFile*> sources;
  1026. this->GeneratorTarget->GetSourceFiles(sources, config);
  1027. for (cmSourceFile const* sf : sources) {
  1028. cmFileSet const* fs =
  1029. this->GeneratorTarget->GetFileSetForSource(config, sf);
  1030. if (!fs) {
  1031. continue;
  1032. }
  1033. if (fs->GetType() != "CXX_MODULES"_s) {
  1034. continue;
  1035. }
  1036. if (sf->GetLanguage().empty()) {
  1037. this->GeneratorTarget->Makefile->IssueMessage(
  1038. MessageType::FATAL_ERROR,
  1039. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  1040. "\" has source file\n ", sf->GetFullPath(),
  1041. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  1042. "scheduled for compilation."));
  1043. }
  1044. }
  1045. }
  1046. // Check if there are Fortran objects which need to participate in forwarding
  1047. // module requirements.
  1048. if (this->GeneratorTarget->HaveFortranSources(config) &&
  1049. !this->Configs[config].ScanningInfo.count("Fortran")) {
  1050. ScanningFiles files;
  1051. this->Configs[config].ScanningInfo["Fortran"].emplace_back(files);
  1052. this->WriteCompileRule("Fortran", config, WithScanning::Yes);
  1053. }
  1054. for (auto const& langScanningFiles : this->Configs[config].ScanningInfo) {
  1055. std::string const& language = langScanningFiles.first;
  1056. std::vector<ScanningFiles> const& scanningFiles = langScanningFiles.second;
  1057. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  1058. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  1059. build.ImplicitOuts.emplace_back(
  1060. cmStrCat(this->GetObjectFileDir(config), '/', language, "Modules.json"));
  1061. build.ImplicitDeps.emplace_back(
  1062. this->GetTargetDependInfoPath(language, config));
  1063. {
  1064. auto bdb_path =
  1065. this->GeneratorTarget->BuildDatabasePath(language, config);
  1066. if (!bdb_path.empty()) {
  1067. build.ImplicitOuts.emplace_back(this->ConvertToNinjaPath(bdb_path));
  1068. }
  1069. }
  1070. auto bdb_path = this->GeneratorTarget->BuildDatabasePath(language, config);
  1071. if (!bdb_path.empty()) {
  1072. auto db = cmBuildDatabase::ForTarget(this->GeneratorTarget, config);
  1073. auto mcdb_template_path = cmStrCat(bdb_path, ".in");
  1074. db.Write(mcdb_template_path);
  1075. build.ImplicitDeps.emplace_back(std::move(mcdb_template_path));
  1076. build.ImplicitOuts.emplace_back(std::move(bdb_path));
  1077. }
  1078. for (auto const& scanFiles : scanningFiles) {
  1079. if (!scanFiles.ScanningOutput.empty()) {
  1080. build.ExplicitDeps.push_back(scanFiles.ScanningOutput);
  1081. }
  1082. if (!scanFiles.ModuleMapFile.empty()) {
  1083. build.ImplicitOuts.push_back(scanFiles.ModuleMapFile);
  1084. }
  1085. }
  1086. this->WriteTargetDependInfo(language, config);
  1087. auto const linked_directories =
  1088. this->GetLinkedTargetDirectories(language, config);
  1089. for (std::string const& l : linked_directories.Direct) {
  1090. build.ImplicitDeps.emplace_back(
  1091. this->ConvertToNinjaPath(cmStrCat(l, '/', language, "Modules.json")));
  1092. }
  1093. for (std::string const& l : linked_directories.Forward) {
  1094. build.ImplicitDeps.emplace_back(
  1095. this->ConvertToNinjaPath(cmStrCat(l, '/', language, "Modules.json")));
  1096. }
  1097. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1098. build);
  1099. }
  1100. this->GetImplFileStream(fileConfig) << '\n';
  1101. }
  1102. void cmNinjaTargetGenerator::GenerateSwiftOutputFileMap(
  1103. std::string const& config, std::string& flags)
  1104. {
  1105. if (this->Configs[config].SwiftOutputMap.empty()) {
  1106. return;
  1107. }
  1108. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  1109. cmGeneratorTarget const* target = this->GeneratorTarget;
  1110. if (cmValue name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1111. return *name;
  1112. }
  1113. return this->ConvertToNinjaPath(cmStrCat(target->GetSupportDirectory(),
  1114. '/', config, '/',
  1115. target->GetName(), ".swiftdeps"));
  1116. }();
  1117. std::string mapFilePath =
  1118. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config,
  1119. "/"
  1120. "output-file-map.json");
  1121. // build the global target dependencies
  1122. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1123. Json::Value deps(Json::objectValue);
  1124. deps["swift-dependencies"] = targetSwiftDepsPath;
  1125. this->Configs[config].SwiftOutputMap[""] = deps;
  1126. cmGeneratedFileStream output(mapFilePath);
  1127. output << this->Configs[config].SwiftOutputMap;
  1128. // Add flag
  1129. this->LocalGenerator->AppendFlags(flags, "-output-file-map");
  1130. this->LocalGenerator->AppendFlags(
  1131. flags,
  1132. this->GetLocalGenerator()->ConvertToOutputFormat(
  1133. ConvertToNinjaPath(mapFilePath), cmOutputConverter::SHELL));
  1134. }
  1135. namespace {
  1136. cmNinjaBuild GetScanBuildStatement(std::string const& ruleName,
  1137. std::string const& ppFileName,
  1138. bool compilePP, bool compilePPWithDefines,
  1139. bool compilationPreprocesses,
  1140. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  1141. std::string const& objectFileName,
  1142. cmNinjaTargetGenerator* tg)
  1143. {
  1144. cmNinjaBuild scanBuild(ruleName);
  1145. if (compilePP) {
  1146. // Move compilation dependencies to the scan/preprocessing build statement.
  1147. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  1148. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  1149. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  1150. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  1151. // The actual compilation will now use the preprocessed source.
  1152. objBuild.ExplicitDeps.push_back(ppFileName);
  1153. } else {
  1154. // Copy compilation dependencies to the scan/preprocessing build statement.
  1155. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1156. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1157. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1158. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1159. }
  1160. // Scanning and compilation generally use the same flags.
  1161. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  1162. if (compilePP && !compilePPWithDefines) {
  1163. // Move preprocessor definitions to the scan/preprocessor build statement.
  1164. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  1165. } else {
  1166. // Copy preprocessor definitions to the scan/preprocessor build statement.
  1167. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1168. }
  1169. // Copy include directories to the preprocessor build statement. The
  1170. // Fortran compilation build statement still needs them for the INCLUDE
  1171. // directive.
  1172. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1173. // Tell dependency scanner the object file that will result from
  1174. // compiling the source.
  1175. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1176. // Tell dependency scanner where to store dyndep intermediate results.
  1177. std::string ddiFileName = cmStrCat(objectFileName, ".ddi");
  1178. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFileName;
  1179. scanBuild.RspFile = cmStrCat(ddiFileName, ".rsp");
  1180. // Outputs of the scan/preprocessor build statement.
  1181. if (compilePP) {
  1182. scanBuild.Outputs.push_back(ppFileName);
  1183. scanBuild.ImplicitOuts.push_back(ddiFileName);
  1184. } else {
  1185. scanBuild.Outputs.push_back(ddiFileName);
  1186. scanBuild.Variables["PREPROCESSED_OUTPUT_FILE"] = ppFileName;
  1187. if (!compilationPreprocesses) {
  1188. // Compilation does not preprocess and we are not compiling an
  1189. // already-preprocessed source. Make compilation depend on the scan
  1190. // results to honor implicit dependencies discovered during scanning
  1191. // (such as Fortran INCLUDE directives).
  1192. objBuild.ImplicitDeps.emplace_back(ddiFileName);
  1193. }
  1194. }
  1195. // Scanning always provides a depfile for preprocessor dependencies. This
  1196. // variable is unused in `msvc`-deptype scanners.
  1197. tg->AddDepfileBinding(scanBuild.Variables,
  1198. cmStrCat(scanBuild.Outputs.front(), ".d"));
  1199. if (compilePP) {
  1200. // The actual compilation does not need a depfile because it
  1201. // depends on the already-preprocessed source.
  1202. tg->RemoveDepfileBinding(vars);
  1203. }
  1204. return scanBuild;
  1205. }
  1206. }
  1207. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1208. cmSourceFile const* source, std::string const& config,
  1209. std::string const& fileConfig, bool firstForConfig)
  1210. {
  1211. std::string const language = source->GetLanguage();
  1212. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1213. std::string const targetSupportDir =
  1214. this->ConvertToNinjaPath(this->GeneratorTarget->GetCMFSupportDirectory());
  1215. std::string const objectDir =
  1216. this->ConvertToNinjaPath(this->GetObjectFileDir(config));
  1217. std::string const objectFileName =
  1218. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1219. std::string const objectFileDir =
  1220. cmSystemTools::GetFilenamePath(objectFileName);
  1221. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1222. // build response file name
  1223. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1224. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1225. bool const lang_supports_response =
  1226. !(language == "RC" || (language == "CUDA" && !flag));
  1227. int const commandLineLengthLimit =
  1228. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1229. cmValue pchExtension =
  1230. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1231. bool const isPch = cmHasSuffix(objectFileName, pchExtension);
  1232. bool const needDyndep = !isPch &&
  1233. this->GeneratorTarget->NeedDyndepForSource(language, config, source);
  1234. WithScanning withScanning =
  1235. needDyndep ? WithScanning::Yes : WithScanning::No;
  1236. cmNinjaBuild objBuild(
  1237. this->LanguageCompilerRule(language, config, withScanning));
  1238. cmNinjaVars& vars = objBuild.Variables;
  1239. vars["FLAGS"] =
  1240. this->ComputeFlagsForObject(source, language, config, objectFileName);
  1241. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1242. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1243. vars["CONFIG"] = config;
  1244. if (this->GetGeneratorTarget()->GetUseShortObjectNames()) {
  1245. vars.emplace(
  1246. "description",
  1247. cmStrCat("Compiling object ", objectFileName, " from source ",
  1248. this->GetLocalGenerator()->GetRelativeSourceFileName(*source)));
  1249. }
  1250. auto compilerLauncher = this->GetCompilerLauncher(language, config);
  1251. cmValue const skipCodeCheck = source->GetProperty("SKIP_LINTING");
  1252. if (!skipCodeCheck.IsOn()) {
  1253. auto const cmakeCmd = this->GetLocalGenerator()->ConvertToOutputFormat(
  1254. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  1255. vars["CODE_CHECK"] =
  1256. this->GenerateCodeCheckRules(*source, compilerLauncher, cmakeCmd, config,
  1257. [this](std::string const& path) {
  1258. return this->ConvertToNinjaPath(path);
  1259. });
  1260. }
  1261. // If compiler launcher was specified and not consumed above, it
  1262. // goes to the beginning of the command line.
  1263. if (!compilerLauncher.empty()) {
  1264. cmList args{ compilerLauncher, cmList::EmptyElements::Yes };
  1265. if (!args.empty()) {
  1266. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  1267. args[0], cmOutputConverter::SHELL);
  1268. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  1269. i = this->LocalGenerator->EscapeForShell(i);
  1270. }
  1271. vars["LAUNCHER"] = args.join(" ") + " ";
  1272. }
  1273. }
  1274. if (this->GetMakefile()->GetSafeDefinition(
  1275. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1276. bool replaceExt = false;
  1277. if (!language.empty()) {
  1278. std::string repVar =
  1279. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1280. replaceExt = this->Makefile->IsOn(repVar);
  1281. }
  1282. this->AddDepfileBinding(
  1283. vars,
  1284. replaceExt ? cmStrCat(objectFileDir, '/',
  1285. cmSystemTools::GetFilenameWithoutLastExtension(
  1286. objectFileName),
  1287. ".d")
  1288. : cmStrCat(objectFileName, ".d"));
  1289. }
  1290. this->SetMsvcTargetPdbVariable(vars, config);
  1291. if (firstForConfig) {
  1292. this->ExportObjectCompileCommand(
  1293. language, sourceFilePath, objectDir, targetSupportDir, objectFileName,
  1294. objectFileDir, vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"],
  1295. vars["TARGET_COMPILE_PDB"], vars["TARGET_PDB"], config, withScanning);
  1296. }
  1297. objBuild.Outputs.push_back(objectFileName);
  1298. if (firstForConfig && !isPch) {
  1299. // Add this object to the list of object files.
  1300. this->Configs[config].Objects.push_back(objectFileName);
  1301. }
  1302. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1303. // Add precompile headers dependencies
  1304. std::vector<std::string> depList;
  1305. std::vector<std::string> pchArchs =
  1306. this->GeneratorTarget->GetPchArchs(config, language);
  1307. std::unordered_set<std::string> pchSources;
  1308. for (std::string const& arch : pchArchs) {
  1309. std::string const pchSource =
  1310. this->GeneratorTarget->GetPchSource(config, language, arch);
  1311. if (!pchSource.empty()) {
  1312. pchSources.insert(pchSource);
  1313. }
  1314. }
  1315. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1316. for (std::string const& arch : pchArchs) {
  1317. depList.push_back(
  1318. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1319. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1320. depList.push_back(
  1321. this->GeneratorTarget->GetPchFile(config, language, arch));
  1322. }
  1323. }
  1324. }
  1325. if (cmValue objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1326. cmList objDepList{ *objectDeps };
  1327. std::copy(objDepList.begin(), objDepList.end(),
  1328. std::back_inserter(depList));
  1329. }
  1330. if (!depList.empty()) {
  1331. for (std::string& odi : depList) {
  1332. if (cmSystemTools::FileIsFullPath(odi)) {
  1333. odi = cmSystemTools::CollapseFullPath(odi);
  1334. }
  1335. }
  1336. std::transform(depList.begin(), depList.end(),
  1337. std::back_inserter(objBuild.ImplicitDeps),
  1338. this->MapToNinjaPath());
  1339. }
  1340. if (this->HasPrivateGeneratedSources) {
  1341. objBuild.OrderOnlyDeps.push_back(
  1342. this->OrderDependsTargetForTargetPrivate(config));
  1343. } else {
  1344. objBuild.OrderOnlyDeps.push_back(
  1345. this->OrderDependsTargetForTarget(config));
  1346. }
  1347. // If the source file is GENERATED and does not have a custom command
  1348. // (either attached to this source file or another one), assume that one of
  1349. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1350. // will rebuild the file.
  1351. if (source->GetIsGenerated() &&
  1352. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1353. !source->GetCustomCommand() &&
  1354. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFilePath)) {
  1355. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1356. sourceFilePath, objBuild.OrderOnlyDeps);
  1357. }
  1358. // For some cases we scan to dynamically discover dependencies.
  1359. bool const compilationPreprocesses =
  1360. !this->NeedExplicitPreprocessing(language);
  1361. std::string modmapFormat;
  1362. if (needDyndep) {
  1363. std::string const modmapFormatVar =
  1364. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1365. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1366. }
  1367. if (needDyndep) {
  1368. // If source/target has preprocessing turned off, we still need to
  1369. // generate an explicit dependency step
  1370. auto const srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1371. cmOutputConverter::FortranPreprocess preprocess =
  1372. cmOutputConverter::GetFortranPreprocess(srcpp);
  1373. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1374. auto const& tgtpp =
  1375. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1376. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1377. }
  1378. bool const compilePP = !compilationPreprocesses &&
  1379. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1380. bool const compilePPWithDefines =
  1381. compilePP && this->CompileWithDefines(language);
  1382. std::string scanRuleName;
  1383. std::string ppFileName;
  1384. if (compilePP) {
  1385. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1386. ppFileName = this->ConvertToNinjaPath(
  1387. this->GetPreprocessedFilePath(source, config));
  1388. } else {
  1389. scanRuleName = this->LanguageScanRule(language, config);
  1390. ppFileName = cmStrCat(objectFileName, ".ddi.i");
  1391. }
  1392. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1393. scanRuleName, ppFileName, compilePP, compilePPWithDefines,
  1394. compilationPreprocesses, objBuild, vars, objectFileName, this);
  1395. if (compilePP) {
  1396. // In case compilation requires flags that are incompatible with
  1397. // preprocessing, include them here.
  1398. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1399. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1400. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1401. // Prepend source file's original directory as an include directory
  1402. // so e.g. Fortran INCLUDE statements can look for files in it.
  1403. std::vector<std::string> sourceDirectory;
  1404. sourceDirectory.push_back(
  1405. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1406. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1407. sourceDirectory, this->GeneratorTarget, language, config, false);
  1408. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1409. }
  1410. ScanningFiles scanningFiles;
  1411. if (firstForConfig) {
  1412. scanningFiles.ScanningOutput = cmStrCat(objectFileName, ".ddi");
  1413. }
  1414. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1415. source, ppBuild.Variables);
  1416. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1417. ppBuild, commandLineLengthLimit);
  1418. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1419. objBuild.OrderOnlyDeps.push_back(dyndep);
  1420. vars["dyndep"] = dyndep;
  1421. if (!modmapFormat.empty()) {
  1422. // XXX(modmap): If changing this path construction, change
  1423. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1424. // `cmNinjaTargetGenerator::ExportObjectCompileCommand` to expect the
  1425. // corresponding file path.
  1426. std::string ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1427. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1428. objBuild.ImplicitDeps.push_back(ddModmapFile);
  1429. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1430. }
  1431. if (!scanningFiles.IsEmpty()) {
  1432. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1433. }
  1434. }
  1435. this->EnsureParentDirectoryExists(objectFileName);
  1436. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1437. objectDir, cmOutputConverter::SHELL);
  1438. vars["TARGET_SUPPORT_DIR"] =
  1439. this->GetLocalGenerator()->ConvertToOutputFormat(targetSupportDir,
  1440. cmOutputConverter::SHELL);
  1441. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1442. objectFileDir, cmOutputConverter::SHELL);
  1443. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1444. source, vars);
  1445. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1446. auto pchIt = pchSources.find(source->GetFullPath());
  1447. if (pchIt != pchSources.end()) {
  1448. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1449. this->GetGeneratorTarget(), nullptr, vars);
  1450. }
  1451. }
  1452. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1453. if (language == "ISPC") {
  1454. std::string const& objectName =
  1455. this->GeneratorTarget->GetObjectName(source);
  1456. std::string ispcSource =
  1457. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1458. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1459. cmValue ispcSuffixProp =
  1460. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1461. assert(ispcSuffixProp);
  1462. std::string ispcHeaderDirectory =
  1463. this->GeneratorTarget->GetObjectDirectory(config);
  1464. if (cmValue prop =
  1465. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1466. ispcHeaderDirectory =
  1467. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1468. }
  1469. std::string ispcHeader =
  1470. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1471. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1472. // Make sure ninja knows what command generates the header
  1473. objBuild.ImplicitOuts.push_back(ispcHeader);
  1474. // Make sure ninja knows how to clean the generated header
  1475. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1476. auto ispcSuffixes =
  1477. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1478. if (ispcSuffixes.size() > 1) {
  1479. std::string rootObjectDir =
  1480. this->GeneratorTarget->GetObjectDirectory(config);
  1481. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1482. objectName, rootObjectDir, ispcSuffixes);
  1483. for (auto sideEffect : ispcSideEfffectObjects) {
  1484. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1485. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1486. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1487. }
  1488. }
  1489. vars["ISPC_HEADER_FILE"] =
  1490. this->GetLocalGenerator()->ConvertToOutputFormat(
  1491. ispcHeader, cmOutputConverter::SHELL);
  1492. } else {
  1493. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1494. if (!headers.empty()) {
  1495. std::transform(headers.begin(), headers.end(), headers.begin(),
  1496. this->MapToNinjaPath());
  1497. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1498. headers.begin(), headers.end());
  1499. }
  1500. }
  1501. if (language == "Swift") {
  1502. this->EmitSwiftDependencyInfo(source, config);
  1503. } else {
  1504. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1505. objBuild, commandLineLengthLimit);
  1506. }
  1507. if (cmValue objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1508. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1509. *objectOutputs, this->LocalGenerator, config);
  1510. if (!evaluatedObjectOutputs.empty()) {
  1511. cmNinjaBuild build("phony");
  1512. build.Comment = "Additional output files.";
  1513. build.Outputs = cmList{ evaluatedObjectOutputs }.data();
  1514. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1515. build.Outputs.begin(), this->MapToNinjaPath());
  1516. build.ExplicitDeps = objBuild.Outputs;
  1517. this->GetGlobalGenerator()->WriteBuild(
  1518. this->GetImplFileStream(fileConfig), build);
  1519. }
  1520. }
  1521. }
  1522. void cmNinjaTargetGenerator::WriteCxxModuleBmiBuildStatement(
  1523. cmSourceFile const* source, std::string const& config,
  1524. std::string const& fileConfig, bool firstForConfig)
  1525. {
  1526. std::string const language = source->GetLanguage();
  1527. if (language != "CXX"_s) {
  1528. this->GetMakefile()->IssueMessage(
  1529. MessageType::FATAL_ERROR,
  1530. cmStrCat("Source file '", source->GetFullPath(), "' of target '",
  1531. this->GetTargetName(), "' is a '", language,
  1532. "' source but must be 'CXX' in order to have a BMI build "
  1533. "statement generated."));
  1534. return;
  1535. }
  1536. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1537. std::string const targetSupportDir =
  1538. this->ConvertToNinjaPath(this->GeneratorTarget->GetCMFSupportDirectory());
  1539. std::string const bmiDir = this->ConvertToNinjaPath(
  1540. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1541. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1542. std::string const bmiFileName =
  1543. this->ConvertToNinjaPath(this->GetBmiFilePath(source, config));
  1544. std::string const bmiFileDir = cmSystemTools::GetFilenamePath(bmiFileName);
  1545. int const commandLineLengthLimit = this->ForceResponseFile() ? -1 : 0;
  1546. cmNinjaBuild bmiBuild(
  1547. this->LanguageCompilerRule(language, config, WithScanning::Yes));
  1548. cmNinjaVars& vars = bmiBuild.Variables;
  1549. vars["FLAGS"] =
  1550. this->ComputeFlagsForObject(source, language, config, bmiFileName);
  1551. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1552. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1553. vars["CONFIG"] = config;
  1554. if (this->GetMakefile()->GetSafeDefinition(
  1555. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1556. bool replaceExt = false;
  1557. if (!language.empty()) {
  1558. std::string repVar =
  1559. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1560. replaceExt = this->Makefile->IsOn(repVar);
  1561. }
  1562. this->AddDepfileBinding(
  1563. vars,
  1564. replaceExt
  1565. ? cmStrCat(bmiFileDir, '/',
  1566. cmSystemTools::GetFilenameWithoutLastExtension(bmiFileName),
  1567. ".d")
  1568. : cmStrCat(bmiFileName, ".d"));
  1569. }
  1570. std::string d =
  1571. this->GeneratorTarget->GetClangTidyExportFixesDirectory(language);
  1572. if (!d.empty()) {
  1573. this->GlobalCommonGenerator->AddClangTidyExportFixesDir(d);
  1574. std::string fixesFile =
  1575. this->GetClangTidyReplacementsFilePath(d, *source, config);
  1576. this->GlobalCommonGenerator->AddClangTidyExportFixesFile(fixesFile);
  1577. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(fixesFile));
  1578. fixesFile = this->ConvertToNinjaPath(fixesFile);
  1579. vars["CLANG_TIDY_EXPORT_FIXES"] = fixesFile;
  1580. }
  1581. this->SetMsvcTargetPdbVariable(vars, config);
  1582. if (firstForConfig) {
  1583. this->ExportObjectCompileCommand(
  1584. language, sourceFilePath, bmiDir, targetSupportDir, bmiFileName,
  1585. bmiFileDir, vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"],
  1586. vars["TARGET_COMPILE_PDB"], vars["TARGET_PDB"], config,
  1587. WithScanning::Yes);
  1588. }
  1589. bmiBuild.Outputs.push_back(bmiFileName);
  1590. bmiBuild.ExplicitDeps.push_back(sourceFilePath);
  1591. std::vector<std::string> depList;
  1592. bmiBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1593. // For some cases we scan to dynamically discover dependencies.
  1594. std::string modmapFormat;
  1595. if (true) {
  1596. std::string const modmapFormatVar =
  1597. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1598. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1599. }
  1600. {
  1601. bool const compilePPWithDefines = this->CompileWithDefines(language);
  1602. std::string scanRuleName = this->LanguageScanRule(language, config);
  1603. std::string ppFileName = cmStrCat(bmiFileName, ".ddi.i");
  1604. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1605. scanRuleName, ppFileName, false, compilePPWithDefines, true, bmiBuild,
  1606. vars, bmiFileName, this);
  1607. ScanningFiles scanningFiles;
  1608. if (firstForConfig) {
  1609. scanningFiles.ScanningOutput = cmStrCat(bmiFileName, ".ddi");
  1610. }
  1611. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1612. source, ppBuild.Variables);
  1613. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1614. ppBuild, commandLineLengthLimit);
  1615. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1616. bmiBuild.OrderOnlyDeps.push_back(dyndep);
  1617. vars["dyndep"] = dyndep;
  1618. if (!modmapFormat.empty()) {
  1619. std::string ddModmapFile = cmStrCat(bmiFileName, ".modmap");
  1620. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1621. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1622. }
  1623. if (!scanningFiles.IsEmpty()) {
  1624. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1625. }
  1626. }
  1627. this->EnsureParentDirectoryExists(bmiFileName);
  1628. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1629. bmiDir, cmOutputConverter::SHELL);
  1630. vars["TARGET_SUPPORT_DIR"] =
  1631. this->GetLocalGenerator()->ConvertToOutputFormat(targetSupportDir,
  1632. cmOutputConverter::SHELL);
  1633. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1634. bmiFileDir, cmOutputConverter::SHELL);
  1635. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1636. source, vars);
  1637. bmiBuild.RspFile = cmStrCat(bmiFileName, ".rsp");
  1638. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1639. bmiBuild, commandLineLengthLimit);
  1640. }
  1641. void cmNinjaTargetGenerator::WriteSwiftObjectBuildStatement(
  1642. std::vector<cmSourceFile const*> const& sources, std::string const& config,
  1643. std::string const& fileConfig, bool firstForConfig)
  1644. {
  1645. // Swift sources are compiled as a module, not individually like with C/C++.
  1646. // Flags, header search paths, and definitions are passed to the entire
  1647. // module build, but we still need to emit compile-commands for each source
  1648. // file in order to support CMAKE_EXPORT_COMPILE_COMMANDS.
  1649. // In whole-module mode, with a single thread, the Swift compiler will
  1650. // only emit a single object file, but if more than one thread is specified,
  1651. // or building in other modes, the compiler will emit multiple object files.
  1652. // When building a single-output, we do not provide an output-file-map (OFM),
  1653. // and instead pass `-o` to tell the compiler where to write the object.
  1654. // When building multiple outputs, we provide an OFM to tell the compiler
  1655. // where to put each object.
  1656. //
  1657. //
  1658. // Per-Target (module):
  1659. // - Flags
  1660. // - Definitions
  1661. // - Include paths
  1662. // - (single-output) output object filename
  1663. // - Swiftmodule
  1664. //
  1665. // Per-File:
  1666. // - compile-command
  1667. // - (multi-output) OFM data
  1668. // - (multi-output) output object filename
  1669. //
  1670. // Note: Due to the differences in the build models, we are only able to
  1671. // build the object build-graph if we know what mode the target is built in.
  1672. // For that, we need the "NEW" behavior for CMP0157. Otherwise, we have to
  1673. // fall back on the old "linker" build. Otherwise, this should be
  1674. // indistinguishable from the old behavior.
  1675. if (sources.empty()) {
  1676. return;
  1677. }
  1678. cmSwiftCompileMode compileMode;
  1679. if (cm::optional<cmSwiftCompileMode> optionalCompileMode =
  1680. this->LocalGenerator->GetSwiftCompileMode(this->GeneratorTarget,
  1681. config)) {
  1682. compileMode = *optionalCompileMode;
  1683. } else {
  1684. // CMP0157 is not NEW, bailing early!
  1685. return;
  1686. }
  1687. std::string const language = "Swift";
  1688. std::string const objectDir = this->ConvertToNinjaPath(
  1689. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1690. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1691. cmGeneratorTarget const& target = *this->GeneratorTarget;
  1692. cmNinjaBuild objBuild(
  1693. this->LanguageCompilerRule(language, config, WithScanning::No));
  1694. cmNinjaVars& vars = objBuild.Variables;
  1695. // The swift toolchain leaves outputs untouched if there are no meaningful
  1696. // changes to input files (e.g. addition of a comment).
  1697. vars.emplace("restat", "1");
  1698. std::string const moduleName = target.GetSwiftModuleName();
  1699. std::string const moduleFilepath =
  1700. this->ConvertToNinjaPath(target.GetSwiftModulePath(config));
  1701. vars.emplace("description",
  1702. cmStrCat("Building Swift Module '", moduleName, "' with ",
  1703. sources.size(),
  1704. sources.size() == 1 ? " source" : " sources"));
  1705. bool const isSingleOutput = [this, compileMode]() -> bool {
  1706. bool isMultiThread = false;
  1707. if (cmValue numThreadStr =
  1708. this->GetMakefile()->GetDefinition("CMAKE_Swift_NUM_THREADS")) {
  1709. unsigned long numThreads;
  1710. cmStrToULong(*numThreadStr, &numThreads);
  1711. // numThreads == 1 is multi-threaded according to swiftc
  1712. isMultiThread = numThreads > 0;
  1713. }
  1714. return !isMultiThread && compileMode == cmSwiftCompileMode::Wholemodule;
  1715. }();
  1716. // Without `-emit-library` or `-emit-executable`, targets with a single
  1717. // source file parse as a Swift script instead of like normal source. For
  1718. // non-executable targets, append this to ensure that they are parsed like a
  1719. // normal source.
  1720. if (target.GetType() != cmStateEnums::EXECUTABLE) {
  1721. this->LocalGenerator->AppendFlags(vars["FLAGS"], "-parse-as-library");
  1722. }
  1723. if (target.GetType() == cmStateEnums::STATIC_LIBRARY) {
  1724. this->LocalGenerator->AppendFlags(vars["FLAGS"], "-static");
  1725. }
  1726. // Does this swift target emit a module file for importing into other
  1727. // targets?
  1728. auto isImportableTarget = [](cmGeneratorTarget const& tgt) -> bool {
  1729. // Everything except for executables that don't export anything should emit
  1730. // some way to import them.
  1731. if (tgt.GetType() == cmStateEnums::EXECUTABLE) {
  1732. return tgt.IsExecutableWithExports();
  1733. }
  1734. return true;
  1735. };
  1736. // Swift modules only make sense to emit from things that can be imported.
  1737. // Executables that don't export symbols can't be imported, so don't try to
  1738. // emit a swiftmodule for them. It will break.
  1739. if (isImportableTarget(target)) {
  1740. std::string const emitModuleFlag = "-emit-module";
  1741. std::string const modulePathFlag = "-emit-module-path";
  1742. this->LocalGenerator->AppendFlags(
  1743. vars["FLAGS"],
  1744. { emitModuleFlag, modulePathFlag,
  1745. this->LocalGenerator->ConvertToOutputFormat(
  1746. moduleFilepath, cmOutputConverter::SHELL) });
  1747. objBuild.Outputs.push_back(moduleFilepath);
  1748. }
  1749. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1750. cmStrCat("-module-name ", moduleName));
  1751. if (target.GetType() != cmStateEnums::EXECUTABLE) {
  1752. std::string const libraryLinkNameFlag = "-module-link-name";
  1753. std::string const libraryLinkName =
  1754. this->GetGeneratorTarget()->GetLibraryNames(config).Base;
  1755. this->LocalGenerator->AppendFlags(
  1756. vars["FLAGS"], cmStrCat(libraryLinkNameFlag, ' ', libraryLinkName));
  1757. }
  1758. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1759. this->GetFlags(language, config));
  1760. vars["DEFINES"] = this->GetDefines(language, config);
  1761. vars["INCLUDES"] = this->GetIncludes(language, config);
  1762. vars["CONFIG"] = config;
  1763. // target-level object filename
  1764. std::string const targetObjectFilename = this->ConvertToNinjaPath(cmStrCat(
  1765. objectDir, '/', moduleName,
  1766. this->GetGlobalGenerator()->GetLanguageOutputExtension(language)));
  1767. objBuild.RspFile = cmStrCat(targetObjectFilename, ".swift.rsp");
  1768. if (isSingleOutput) {
  1769. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1770. cmStrCat("-o ", targetObjectFilename));
  1771. objBuild.Outputs.push_back(targetObjectFilename);
  1772. this->Configs[config].Objects.push_back(targetObjectFilename);
  1773. }
  1774. for (cmSourceFile const* sf : sources) {
  1775. // Add dependency to object build on each source file
  1776. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(sf);
  1777. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1778. if (!isSingleOutput) {
  1779. // Object outputs
  1780. std::string const objectFilepath =
  1781. this->ConvertToNinjaPath(this->GetObjectFilePath(sf, config));
  1782. this->EnsureParentDirectoryExists(objectFilepath);
  1783. objBuild.Outputs.push_back(objectFilepath);
  1784. this->Configs[config].Objects.push_back(objectFilepath);
  1785. // Add OFM data
  1786. this->EmitSwiftDependencyInfo(sf, config);
  1787. }
  1788. }
  1789. if (!isSingleOutput) {
  1790. this->GenerateSwiftOutputFileMap(config, vars["FLAGS"]);
  1791. }
  1792. if (firstForConfig) {
  1793. this->ExportSwiftObjectCompileCommand(
  1794. sources, targetObjectFilename, vars["FLAGS"], vars["DEFINES"],
  1795. vars["INCLUDES"], config, isSingleOutput);
  1796. }
  1797. for (cmTargetDepend const& dep :
  1798. this->GetGlobalGenerator()->GetTargetDirectDepends(&target)) {
  1799. if (!dep->IsLanguageUsed("Swift", config)) {
  1800. continue;
  1801. }
  1802. // If the dependency emits a swiftmodule, add a dependency edge on that
  1803. // swiftmodule to the ninja build graph.
  1804. if (isImportableTarget(*dep)) {
  1805. std::string const depModuleFilepath =
  1806. this->ConvertToNinjaPath(dep->GetSwiftModulePath(config));
  1807. objBuild.ImplicitDeps.push_back(depModuleFilepath);
  1808. }
  1809. }
  1810. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1811. // Write object build
  1812. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1813. objBuild,
  1814. this->ForceResponseFile() ? -1 : 0);
  1815. }
  1816. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1817. std::string const& config)
  1818. {
  1819. Json::Value tdi(Json::objectValue);
  1820. tdi["language"] = lang;
  1821. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1822. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1823. tdi["compiler-simulate-id"] = this->Makefile->GetSafeDefinition(
  1824. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1825. tdi["compiler-frontend-variant"] = this->Makefile->GetSafeDefinition(
  1826. cmStrCat("CMAKE_", lang, "_COMPILER_FRONTEND_VARIANT"));
  1827. std::string mod_dir;
  1828. if (lang == "Fortran") {
  1829. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1830. this->Makefile->GetHomeOutputDirectory());
  1831. } else if (lang == "CXX") {
  1832. mod_dir = this->GetGlobalGenerator()->ExpandCFGIntDir(
  1833. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory),
  1834. config);
  1835. }
  1836. if (mod_dir.empty()) {
  1837. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1838. }
  1839. tdi["module-dir"] = mod_dir;
  1840. if (lang == "Fortran") {
  1841. tdi["submodule-sep"] =
  1842. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1843. tdi["submodule-ext"] =
  1844. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1845. } else if (lang == "CXX") {
  1846. // No extra information necessary.
  1847. }
  1848. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1849. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1850. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1851. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1852. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1853. std::vector<std::string> includes;
  1854. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1855. lang, config);
  1856. for (std::string const& i : includes) {
  1857. // Convert the include directories the same way we do for -I flags.
  1858. // See upstream ninja issue 1251.
  1859. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1860. }
  1861. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1862. Json::arrayValue;
  1863. auto const linked_directories =
  1864. this->GetLinkedTargetDirectories(lang, config);
  1865. for (std::string const& l : linked_directories.Direct) {
  1866. tdi_linked_target_dirs.append(l);
  1867. }
  1868. Json::Value& tdi_forward_modules_from_target_dirs =
  1869. tdi["forward-modules-from-target-dirs"] = Json::arrayValue;
  1870. for (std::string const& l : linked_directories.Forward) {
  1871. tdi_forward_modules_from_target_dirs.append(l);
  1872. }
  1873. cmDyndepGeneratorCallbacks cb;
  1874. cb.ObjectFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1875. return this->GetObjectFilePath(sf, cnf);
  1876. };
  1877. cb.BmiFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1878. return this->GetBmiFilePath(sf, cnf);
  1879. };
  1880. #if !defined(CMAKE_BOOTSTRAP)
  1881. cmDyndepCollation::AddCollationInformation(tdi, this->GeneratorTarget,
  1882. config, cb);
  1883. #endif
  1884. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1885. cmGeneratedFileStream tdif(tdin);
  1886. tdif << tdi;
  1887. }
  1888. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1889. cmSourceFile const* source, std::string const& config)
  1890. {
  1891. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1892. std::string const objectFilePath =
  1893. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1894. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1895. if (cmValue name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1896. return *name;
  1897. }
  1898. return cmStrCat(objectFilePath, ".swiftdeps");
  1899. }();
  1900. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1901. if (cmValue name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1902. return *name;
  1903. }
  1904. return cmStrCat(objectFilePath, ".dia");
  1905. }();
  1906. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1907. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1908. std::string const objectFileName =
  1909. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1910. std::string const objectFileDir =
  1911. cmSystemTools::GetFilenamePath(objectFileName);
  1912. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1913. std::string dependFileName = cmStrCat(
  1914. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1915. return local->ConvertToOutputFormat(
  1916. cmStrCat(objectFileDir, '/', dependFileName),
  1917. cmOutputConverter::SHELL);
  1918. }
  1919. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1920. cmOutputConverter::SHELL);
  1921. }();
  1922. // build the source file mapping
  1923. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1924. Json::Value entry = Json::Value(Json::objectValue);
  1925. entry["object"] = objectFilePath;
  1926. entry["dependencies"] = makeDepsPath;
  1927. entry["swift-dependencies"] = swiftDepsPath;
  1928. entry["diagnostics"] = swiftDiaPath;
  1929. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1930. }
  1931. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1932. std::string const& language, std::string const& sourceFileName,
  1933. std::string const& objectDir, std::string const& targetSupportDir,
  1934. std::string const& objectFileName, std::string const& objectFileDir,
  1935. std::string const& flags, std::string const& defines,
  1936. std::string const& includes, std::string const& targetCompilePdb,
  1937. std::string const& targetPdb, std::string const& outputConfig,
  1938. WithScanning withScanning)
  1939. {
  1940. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  1941. return;
  1942. }
  1943. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1944. compileObjectVars.Language = language.c_str();
  1945. std::string escapedSourceFileName = sourceFileName;
  1946. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1947. escapedSourceFileName =
  1948. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1949. this->GetGlobalGenerator()
  1950. ->GetCMakeInstance()
  1951. ->GetHomeOutputDirectory());
  1952. }
  1953. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1954. escapedSourceFileName, cmOutputConverter::SHELL);
  1955. std::string fullFlags = flags;
  1956. if (withScanning == WithScanning::Yes) {
  1957. std::string const modmapFormatVar =
  1958. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1959. std::string const modmapFormat =
  1960. this->Makefile->GetSafeDefinition(modmapFormatVar);
  1961. if (!modmapFormat.empty()) {
  1962. std::string modmapFlags = this->GetMakefile()->GetRequiredDefinition(
  1963. cmStrCat("CMAKE_", language, "_MODULE_MAP_FLAG"));
  1964. // XXX(modmap): If changing this path construction, change
  1965. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1966. // `cmNinjaTargetGenerator::WriteObjectBuildStatement` to expect the
  1967. // corresponding file path.
  1968. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  1969. cmStrCat(objectFileName, ".modmap"));
  1970. fullFlags += cmStrCat(' ', modmapFlags);
  1971. }
  1972. }
  1973. compileObjectVars.Source = escapedSourceFileName.c_str();
  1974. std::string escapedObjectFileName =
  1975. this->LocalGenerator->ConvertToOutputFormat(objectFileName,
  1976. cmOutputConverter::SHELL);
  1977. compileObjectVars.Object = escapedObjectFileName.c_str();
  1978. compileObjectVars.ObjectDir = objectDir.c_str();
  1979. compileObjectVars.TargetSupportDir = targetSupportDir.c_str();
  1980. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1981. compileObjectVars.Flags = fullFlags.c_str();
  1982. compileObjectVars.Defines = defines.c_str();
  1983. compileObjectVars.Includes = includes.c_str();
  1984. compileObjectVars.TargetCompilePDB = targetCompilePdb.c_str();
  1985. compileObjectVars.TargetPDB = targetPdb.c_str();
  1986. // Rule for compiling object file.
  1987. std::string cudaCompileMode;
  1988. if (language == "CUDA") {
  1989. if (this->GeneratorTarget->GetPropertyAsBool(
  1990. "CUDA_SEPARABLE_COMPILATION")) {
  1991. std::string const& rdcFlag =
  1992. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  1993. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, ' ');
  1994. }
  1995. static std::array<cm::string_view, 4> const compileModes{
  1996. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  1997. };
  1998. bool useNormalCompileMode = true;
  1999. for (cm::string_view mode : compileModes) {
  2000. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  2001. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  2002. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  2003. std::string const& flag =
  2004. this->Makefile->GetRequiredDefinition(defName);
  2005. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  2006. useNormalCompileMode = false;
  2007. break;
  2008. }
  2009. }
  2010. if (useNormalCompileMode) {
  2011. std::string const& wholeFlag =
  2012. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  2013. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  2014. }
  2015. compileObjectVars.CudaCompileMode = cudaCompileMode.c_str();
  2016. }
  2017. std::string const cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  2018. std::string const& compileCmd =
  2019. this->Makefile->GetRequiredDefinition(cmdVar);
  2020. cmList compileCmds(compileCmd);
  2021. auto rulePlaceholderExpander =
  2022. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  2023. for (auto& i : compileCmds) {
  2024. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  2025. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  2026. compileObjectVars);
  2027. }
  2028. std::string cmdLine = this->GetLocalGenerator()->BuildCommandLine(
  2029. compileCmds, outputConfig, outputConfig);
  2030. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName,
  2031. objectFileName);
  2032. }
  2033. void cmNinjaTargetGenerator::ExportSwiftObjectCompileCommand(
  2034. std::vector<cmSourceFile const*> const& moduleSourceFiles,
  2035. std::string const& moduleObjectFilename, std::string const& flags,
  2036. std::string const& defines, std::string const& includes,
  2037. std::string const& outputConfig, bool singleOutput)
  2038. {
  2039. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  2040. return;
  2041. }
  2042. auto escapeSourceFileName = [this](std::string srcFilename) -> std::string {
  2043. if (!cmSystemTools::FileIsFullPath(srcFilename)) {
  2044. srcFilename =
  2045. cmSystemTools::CollapseFullPath(srcFilename,
  2046. this->GetGlobalGenerator()
  2047. ->GetCMakeInstance()
  2048. ->GetHomeOutputDirectory());
  2049. }
  2050. return this->LocalGenerator->ConvertToOutputFormat(
  2051. srcFilename, cmOutputConverter::SHELL);
  2052. };
  2053. auto escapedModuleObjectFilename =
  2054. this->ConvertToNinjaPath(moduleObjectFilename);
  2055. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2056. compileObjectVars.Language = "Swift";
  2057. compileObjectVars.Flags = flags.c_str();
  2058. compileObjectVars.Defines = defines.c_str();
  2059. compileObjectVars.Includes = includes.c_str();
  2060. // Build up the list of source files in the module
  2061. std::vector<std::string> filenames;
  2062. filenames.reserve(moduleSourceFiles.size());
  2063. for (cmSourceFile const* sf : moduleSourceFiles) {
  2064. filenames.emplace_back(
  2065. escapeSourceFileName(this->GetCompiledSourceNinjaPath(sf)));
  2066. }
  2067. // Note that `escapedSourceFilenames` must remain alive until the
  2068. // compileObjectVars is consumed or Source will be a dangling pointer.
  2069. std::string const escapedSourceFilenames = cmJoin(filenames, " ");
  2070. compileObjectVars.Source = escapedSourceFilenames.c_str();
  2071. std::string const& compileCommand =
  2072. this->Makefile->GetRequiredDefinition("CMAKE_Swift_COMPILE_OBJECT");
  2073. cmList compileCmds(compileCommand);
  2074. auto rulePlaceholderExpander =
  2075. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  2076. for (cmSourceFile const* sf : moduleSourceFiles) {
  2077. std::string const sourceFilename = this->GetCompiledSourceNinjaPath(sf);
  2078. std::string objectFilename = escapedModuleObjectFilename;
  2079. if (!singleOutput) {
  2080. // If it's not single-output, each source file gets a separate object
  2081. objectFilename =
  2082. this->ConvertToNinjaPath(this->GetObjectFilePath(sf, outputConfig));
  2083. }
  2084. compileObjectVars.Objects = objectFilename.c_str();
  2085. for (std::string& cmd : compileCmds) {
  2086. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  2087. cmd, compileObjectVars);
  2088. }
  2089. std::string commandLine = this->GetLocalGenerator()->BuildCommandLine(
  2090. compileCmds, outputConfig, outputConfig);
  2091. this->GetGlobalGenerator()->AddCXXCompileCommand(
  2092. commandLine, sourceFilename, objectFilename);
  2093. }
  2094. }
  2095. void cmNinjaTargetGenerator::AdditionalCleanFiles(std::string const& config)
  2096. {
  2097. if (cmValue prop_value =
  2098. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  2099. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  2100. cmList cleanFiles(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  2101. this->GeneratorTarget));
  2102. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  2103. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  2104. for (auto const& cleanFile : cleanFiles) {
  2105. // Support relative paths
  2106. gg->AddAdditionalCleanFile(
  2107. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  2108. }
  2109. }
  2110. }
  2111. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(std::string const& config) const
  2112. {
  2113. auto const it = this->Configs.find(config);
  2114. if (it != this->Configs.end()) {
  2115. return it->second.Objects;
  2116. }
  2117. return {};
  2118. }
  2119. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  2120. std::string const& path) const
  2121. {
  2122. if (cmSystemTools::FileIsFullPath(path)) {
  2123. cmSystemTools::MakeDirectory(path);
  2124. } else {
  2125. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  2126. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  2127. // Also ensures there is a trailing slash.
  2128. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  2129. fullPath += path;
  2130. cmSystemTools::MakeDirectory(fullPath);
  2131. }
  2132. }
  2133. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  2134. std::string const& path) const
  2135. {
  2136. this->EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  2137. }
  2138. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  2139. cmSourceFile const& source, char const* pkgloc, std::string const& config)
  2140. {
  2141. // Skip OS X content when not building a Framework or Bundle.
  2142. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  2143. return;
  2144. }
  2145. std::string macdir =
  2146. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  2147. config);
  2148. // Reject files that collide with files from the Ninja file's native config.
  2149. if (config != this->FileConfig) {
  2150. std::string nativeMacdir =
  2151. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  2152. pkgloc, this->FileConfig);
  2153. if (macdir == nativeMacdir) {
  2154. return;
  2155. }
  2156. }
  2157. // Get the input file location.
  2158. std::string input = source.GetFullPath();
  2159. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  2160. // Get the output file location.
  2161. std::string output =
  2162. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  2163. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  2164. // Write a build statement to copy the content into the bundle.
  2165. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  2166. input, output, this->FileConfig);
  2167. // Add as a dependency to the target so that it gets called.
  2168. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  2169. }
  2170. void cmNinjaTargetGenerator::AddDepfileBinding(cmNinjaVars& vars,
  2171. std::string depfile) const
  2172. {
  2173. std::string depfileForShell =
  2174. this->GetLocalGenerator()->ConvertToOutputFormat(depfile,
  2175. cmOutputConverter::SHELL);
  2176. if (depfile != depfileForShell) {
  2177. vars["depfile"] = std::move(depfile);
  2178. }
  2179. vars["DEP_FILE"] = std::move(depfileForShell);
  2180. }
  2181. void cmNinjaTargetGenerator::RemoveDepfileBinding(cmNinjaVars& vars) const
  2182. {
  2183. vars.erase("DEP_FILE");
  2184. vars.erase("depfile");
  2185. }
  2186. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  2187. std::string const& pool_property, cmGeneratorTarget* target,
  2188. cmSourceFile const* source, cmNinjaVars& vars)
  2189. {
  2190. // First check the current source properties, then if not found, its target
  2191. // ones. Allows to override a target-wide compile pool with a source-specific
  2192. // one.
  2193. cmValue pool = {};
  2194. if (source) {
  2195. pool = source->GetProperty(pool_property);
  2196. }
  2197. if (!pool) {
  2198. pool = target->GetProperty(pool_property);
  2199. }
  2200. if (pool) {
  2201. vars["pool"] = *pool;
  2202. }
  2203. }
  2204. bool cmNinjaTargetGenerator::ForceResponseFile()
  2205. {
  2206. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  2207. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  2208. cmSystemTools::HasEnv(forceRspFile));
  2209. }