cmNinjaTargetGenerator.cxx 80 KB

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