cmNinjaTargetGenerator.cxx 95 KB

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