cmNinjaTargetGenerator.cxx 95 KB

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