cmNinjaTargetGenerator.cxx 95 KB

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