cmNinjaTargetGenerator.cxx 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  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 <cassert>
  6. #include <iterator>
  7. #include <map>
  8. #include <ostream>
  9. #include <unordered_map>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cm/string_view>
  14. #include <cmext/algorithm>
  15. #include <cmext/string_view>
  16. #include <cm3p/json/value.h>
  17. #include <cm3p/json/writer.h>
  18. #include "cmComputeLinkInformation.h"
  19. #include "cmCustomCommandGenerator.h"
  20. #include "cmGeneratedFileStream.h"
  21. #include "cmGeneratorExpression.h"
  22. #include "cmGeneratorTarget.h"
  23. #include "cmGlobalNinjaGenerator.h"
  24. #include "cmLocalGenerator.h"
  25. #include "cmLocalNinjaGenerator.h"
  26. #include "cmMakefile.h"
  27. #include "cmNinjaNormalTargetGenerator.h"
  28. #include "cmNinjaUtilityTargetGenerator.h"
  29. #include "cmOutputConverter.h"
  30. #include "cmProperty.h"
  31. #include "cmRange.h"
  32. #include "cmRulePlaceholderExpander.h"
  33. #include "cmSourceFile.h"
  34. #include "cmStandardLevelResolver.h"
  35. #include "cmState.h"
  36. #include "cmStateTypes.h"
  37. #include "cmStringAlgorithms.h"
  38. #include "cmSystemTools.h"
  39. #include "cmake.h"
  40. std::unique_ptr<cmNinjaTargetGenerator> cmNinjaTargetGenerator::New(
  41. cmGeneratorTarget* target)
  42. {
  43. switch (target->GetType()) {
  44. case cmStateEnums::EXECUTABLE:
  45. case cmStateEnums::SHARED_LIBRARY:
  46. case cmStateEnums::STATIC_LIBRARY:
  47. case cmStateEnums::MODULE_LIBRARY:
  48. case cmStateEnums::OBJECT_LIBRARY:
  49. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  50. case cmStateEnums::UTILITY:
  51. case cmStateEnums::INTERFACE_LIBRARY:
  52. case cmStateEnums::GLOBAL_TARGET:
  53. return cm::make_unique<cmNinjaUtilityTargetGenerator>(target);
  54. default:
  55. return std::unique_ptr<cmNinjaTargetGenerator>();
  56. }
  57. }
  58. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  59. : cmCommonTargetGenerator(target)
  60. , OSXBundleGenerator(nullptr)
  61. , LocalGenerator(
  62. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  63. {
  64. for (auto const& fileConfig :
  65. target->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)) {
  66. this->Configs[fileConfig].MacOSXContentGenerator =
  67. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  68. }
  69. }
  70. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  71. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  72. const std::string& config) const
  73. {
  74. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  75. }
  76. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  77. {
  78. return *this->GetGlobalGenerator()->GetCommonFileStream();
  79. }
  80. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  81. {
  82. return *this->GetGlobalGenerator()->GetRulesFileStream();
  83. }
  84. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  85. {
  86. return this->LocalGenerator->GetGlobalNinjaGenerator();
  87. }
  88. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  89. const std::string& lang, const std::string& config) const
  90. {
  91. return cmStrCat(
  92. lang, "_COMPILER__",
  93. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  94. '_', config);
  95. }
  96. std::string cmNinjaTargetGenerator::LanguagePreprocessAndScanRule(
  97. std::string const& lang, const std::string& config) const
  98. {
  99. return cmStrCat(
  100. lang, "_PREPROCESS_SCAN__",
  101. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  102. '_', config);
  103. }
  104. std::string cmNinjaTargetGenerator::LanguageScanRule(
  105. std::string const& lang, const std::string& config) const
  106. {
  107. return cmStrCat(
  108. lang, "_SCAN__",
  109. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  110. '_', config);
  111. }
  112. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  113. std::string const& lang) const
  114. {
  115. return lang == "Fortran";
  116. }
  117. bool cmNinjaTargetGenerator::CompileWithDefines(std::string const& lang) const
  118. {
  119. return this->Makefile->IsOn(
  120. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  121. }
  122. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  123. const std::string& lang, const std::string& config) const
  124. {
  125. return cmStrCat(
  126. lang, "_DYNDEP__",
  127. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  128. '_', config);
  129. }
  130. bool cmNinjaTargetGenerator::NeedCxxModuleSupport(
  131. std::string const& lang, std::string const& config) const
  132. {
  133. if (lang != "CXX") {
  134. return false;
  135. }
  136. if (!this->Makefile->IsOn("CMAKE_EXPERIMENTAL_CXX_MODULE_DYNDEP")) {
  137. return false;
  138. }
  139. cmGeneratorTarget const* tgt = this->GetGeneratorTarget();
  140. cmStandardLevelResolver standardResolver(this->Makefile);
  141. bool const uses_cxx20 =
  142. standardResolver.HaveStandardAvailable(tgt, "CXX", config, "cxx_std_20");
  143. return uses_cxx20 && this->GetGlobalGenerator()->CheckCxxModuleSupport();
  144. }
  145. bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang,
  146. std::string const& config) const
  147. {
  148. return lang == "Fortran" || this->NeedCxxModuleSupport(lang, config);
  149. }
  150. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  151. const std::string& config)
  152. {
  153. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  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)
  163. {
  164. std::vector<std::string> architectures;
  165. std::unordered_map<std::string, std::string> pchSources;
  166. this->GeneratorTarget->GetAppleArchs(config, architectures);
  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. }
  194. // Add source file specific flags.
  195. cmGeneratorExpressionInterpreter genexInterpreter(
  196. this->LocalGenerator, config, this->GeneratorTarget, language);
  197. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  198. if (cmProp cflags = source->GetProperty(COMPILE_FLAGS)) {
  199. this->LocalGenerator->AppendFlags(
  200. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  201. }
  202. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  203. if (cmProp coptions = source->GetProperty(COMPILE_OPTIONS)) {
  204. this->LocalGenerator->AppendCompileOptions(
  205. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  206. }
  207. // Add precompile headers compile options.
  208. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  209. std::string pchOptions;
  210. auto pchIt = pchSources.find(source->GetFullPath());
  211. if (pchIt != pchSources.end()) {
  212. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  213. config, language, pchIt->second);
  214. } else {
  215. pchOptions =
  216. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  217. }
  218. this->LocalGenerator->AppendCompileOptions(
  219. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  220. }
  221. return flags;
  222. }
  223. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  224. std::string const& language,
  225. const std::string& config)
  226. {
  227. std::vector<std::string> includes;
  228. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  229. language, config);
  230. // Add include directory flags.
  231. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  232. includes, this->GeneratorTarget, language, config, false,
  233. // full include paths for RC needed by cmcldeps
  234. language == "RC" ? cmLocalGenerator::IncludePathStyle::Absolute
  235. : cmLocalGenerator::IncludePathStyle::Default);
  236. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  237. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  238. }
  239. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  240. }
  241. // TODO: Refactor with
  242. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  243. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  244. const std::string& language,
  245. const std::string& config)
  246. {
  247. std::set<std::string> defines;
  248. cmGeneratorExpressionInterpreter genexInterpreter(
  249. this->LocalGenerator, config, this->GeneratorTarget, language);
  250. // Seriously??
  251. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  252. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  253. }
  254. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  255. if (cmProp compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  256. this->LocalGenerator->AppendDefines(
  257. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  258. }
  259. std::string defPropName =
  260. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  261. if (cmProp config_compile_defs = source->GetProperty(defPropName)) {
  262. this->LocalGenerator->AppendDefines(
  263. defines,
  264. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  265. }
  266. std::string definesString = this->GetDefines(language, config);
  267. this->LocalGenerator->JoinDefines(defines, definesString, language);
  268. return definesString;
  269. }
  270. std::string cmNinjaTargetGenerator::ComputeIncludes(
  271. cmSourceFile const* source, const std::string& language,
  272. const std::string& config)
  273. {
  274. std::vector<std::string> includes;
  275. cmGeneratorExpressionInterpreter genexInterpreter(
  276. this->LocalGenerator, config, this->GeneratorTarget, language);
  277. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  278. if (cmProp cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  279. this->LocalGenerator->AppendIncludeDirectories(
  280. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  281. *source);
  282. }
  283. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  284. includes, this->GeneratorTarget, language, config, false,
  285. cmLocalGenerator::IncludePathStyle::Absolute);
  286. this->LocalGenerator->AppendFlags(includesString,
  287. this->GetIncludes(language, config));
  288. return includesString;
  289. }
  290. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  291. const std::string& linkLanguage, const std::string& config,
  292. bool ignoreType) const
  293. {
  294. // Static libraries never depend on other targets for linking.
  295. if (!ignoreType &&
  296. (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  297. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  298. return cmNinjaDeps();
  299. }
  300. cmComputeLinkInformation* cli =
  301. this->GeneratorTarget->GetLinkInformation(config);
  302. if (!cli) {
  303. return cmNinjaDeps();
  304. }
  305. const std::vector<std::string>& deps = cli->GetDepends();
  306. cmNinjaDeps result(deps.size());
  307. std::transform(deps.begin(), deps.end(), result.begin(),
  308. this->MapToNinjaPath());
  309. // Add a dependency on the link definitions file, if any.
  310. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  311. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  312. for (cmSourceFile const* src : mdi->Sources) {
  313. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  314. }
  315. }
  316. // Add a dependency on user-specified manifest files, if any.
  317. std::vector<cmSourceFile const*> manifest_srcs;
  318. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  319. for (cmSourceFile const* manifest_src : manifest_srcs) {
  320. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  321. }
  322. // Add user-specified dependencies.
  323. std::vector<std::string> linkDeps;
  324. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  325. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  326. this->MapToNinjaPath());
  327. return result;
  328. }
  329. std::string cmNinjaTargetGenerator::GetCompiledSourceNinjaPath(
  330. cmSourceFile const* source) const
  331. {
  332. // Pass source files to the compiler by absolute path.
  333. return this->ConvertToNinjaAbsPath(source->GetFullPath());
  334. }
  335. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  336. cmSourceFile const* source, const std::string& config) const
  337. {
  338. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  339. if (!path.empty()) {
  340. path += '/';
  341. }
  342. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  343. path += cmStrCat(
  344. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  345. this->GetGlobalGenerator()->ConfigDirectory(config), '/', objectName);
  346. return path;
  347. }
  348. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  349. cmSourceFile const* source, const std::string& config) const
  350. {
  351. // Choose an extension to compile already-preprocessed source.
  352. std::string ppExt = source->GetExtension();
  353. if (cmHasLiteralPrefix(ppExt, "F")) {
  354. // Some Fortran compilers automatically enable preprocessing for
  355. // upper-case extensions. Since the source is already preprocessed,
  356. // use a lower-case extension.
  357. ppExt = cmSystemTools::LowerCase(ppExt);
  358. }
  359. if (ppExt == "fpp") {
  360. // Some Fortran compilers automatically enable preprocessing for
  361. // the ".fpp" extension. Since the source is already preprocessed,
  362. // use the ".f" extension.
  363. ppExt = "f";
  364. }
  365. // Take the object file name and replace the extension.
  366. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  367. std::string const& objExt =
  368. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  369. assert(objName.size() >= objExt.size());
  370. std::string const ppName =
  371. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  372. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  373. if (!path.empty()) {
  374. path += '/';
  375. }
  376. path +=
  377. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  378. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  379. return path;
  380. }
  381. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  382. std::string const& lang, const std::string& config) const
  383. {
  384. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  385. if (!path.empty()) {
  386. path += '/';
  387. }
  388. path += cmStrCat(
  389. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  390. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  391. return path;
  392. }
  393. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  394. std::string const& lang, const std::string& config) const
  395. {
  396. std::string path =
  397. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  398. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  399. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  400. "DependInfo.json");
  401. return path;
  402. }
  403. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  404. const std::string& config) const
  405. {
  406. std::string dir = this->GeneratorTarget->GetDirectory(config);
  407. return this->ConvertToNinjaPath(dir);
  408. }
  409. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  410. const std::string& name, const std::string& config) const
  411. {
  412. std::string path = this->GetTargetOutputDir(config);
  413. if (path.empty() || path == ".") {
  414. return name;
  415. }
  416. path += cmStrCat('/', name);
  417. return path;
  418. }
  419. std::string cmNinjaTargetGenerator::GetTargetName() const
  420. {
  421. return this->GeneratorTarget->GetName();
  422. }
  423. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  424. cmNinjaVars& vars, const std::string& config) const
  425. {
  426. cmMakefile* mf = this->GetMakefile();
  427. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  428. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  429. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  430. std::string pdbPath;
  431. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  432. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  433. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  434. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  435. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  436. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  437. this->GeneratorTarget->GetPDBName(config));
  438. }
  439. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  440. this->ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  441. vars["TARGET_COMPILE_PDB"] =
  442. this->GetLocalGenerator()->ConvertToOutputFormat(
  443. this->ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  444. this->EnsureParentDirectoryExists(pdbPath);
  445. this->EnsureParentDirectoryExists(compilePdbPath);
  446. return true;
  447. }
  448. return false;
  449. }
  450. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  451. const std::string& config)
  452. {
  453. #ifdef NINJA_GEN_VERBOSE_FILES
  454. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  455. #endif
  456. this->WriteCompileRule(language, config);
  457. }
  458. namespace {
  459. // Create the command to run the dependency scanner
  460. std::string GetScanCommand(const std::string& cmakeCmd, const std::string& tdi,
  461. const std::string& lang, const std::string& ppFile,
  462. const std::string& ddiFile)
  463. {
  464. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  465. " --lang=", lang, " --pp=", ppFile,
  466. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=", ddiFile);
  467. }
  468. // Helper function to create dependency scanning rule that may or may
  469. // not perform explicit preprocessing too.
  470. cmNinjaRule GetScanRule(
  471. std::string const& ruleName, std::string const& ppFileName,
  472. cmRulePlaceholderExpander::RuleVariables const& vars,
  473. const std::string& responseFlag, const std::string& flags,
  474. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  475. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds,
  476. const std::string& outputConfig)
  477. {
  478. cmNinjaRule rule(ruleName);
  479. // Scanning always uses a depfile for preprocessor dependencies.
  480. rule.DepType = ""; // no deps= for multiple outputs
  481. rule.DepFile = "$DEP_FILE";
  482. cmRulePlaceholderExpander::RuleVariables scanVars;
  483. scanVars.CMTargetName = vars.CMTargetName;
  484. scanVars.CMTargetType = vars.CMTargetType;
  485. scanVars.Language = vars.Language;
  486. scanVars.Object = "$OBJ_FILE";
  487. scanVars.PreprocessedSource = ppFileName.c_str();
  488. scanVars.DynDepFile = "$DYNDEP_INTERMEDIATE_FILE";
  489. scanVars.DependencyFile = rule.DepFile.c_str();
  490. scanVars.DependencyTarget = "$out";
  491. // Scanning needs the same preprocessor settings as direct compilation would.
  492. scanVars.Source = vars.Source;
  493. scanVars.Defines = vars.Defines;
  494. scanVars.Includes = vars.Includes;
  495. // Scanning needs the compilation flags too.
  496. std::string scanFlags = flags;
  497. // If using a response file, move defines, includes, and flags into it.
  498. if (!responseFlag.empty()) {
  499. rule.RspFile = "$RSP_FILE";
  500. rule.RspContent =
  501. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  502. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  503. scanVars.Defines = "";
  504. scanVars.Includes = "";
  505. }
  506. scanVars.Flags = scanFlags.c_str();
  507. // Rule for scanning a source file.
  508. for (std::string& scanCmd : scanCmds) {
  509. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  510. }
  511. rule.Command =
  512. generator->BuildCommandLine(scanCmds, outputConfig, outputConfig);
  513. return rule;
  514. }
  515. }
  516. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  517. const std::string& config)
  518. {
  519. cmRulePlaceholderExpander::RuleVariables vars;
  520. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  521. vars.CMTargetType =
  522. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  523. vars.Language = lang.c_str();
  524. vars.Source = "$in";
  525. vars.Object = "$out";
  526. vars.Defines = "$DEFINES";
  527. vars.Includes = "$INCLUDES";
  528. vars.TargetPDB = "$TARGET_PDB";
  529. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  530. vars.ObjectDir = "$OBJECT_DIR";
  531. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  532. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  533. cmMakefile* mf = this->GetMakefile();
  534. // For some cases we scan to dynamically discover dependencies.
  535. bool const needDyndep = this->NeedDyndep(lang, config);
  536. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  537. std::string flags = "$FLAGS";
  538. std::string responseFlag;
  539. bool const lang_supports_response = lang != "RC";
  540. if (lang_supports_response && this->ForceResponseFile()) {
  541. std::string const responseFlagVar =
  542. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  543. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  544. if (responseFlag.empty() && lang != "CUDA") {
  545. responseFlag = "@";
  546. }
  547. }
  548. std::string const modmapFormatVar =
  549. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_MODULE_MAP_FORMAT");
  550. std::string const modmapFormat =
  551. this->Makefile->GetSafeDefinition(modmapFormatVar);
  552. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  553. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  554. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  555. this->ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  556. cmLocalGenerator::SHELL);
  557. std::string launcher;
  558. cmProp val = this->GetLocalGenerator()->GetRuleLauncher(
  559. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  560. if (cmNonempty(val)) {
  561. launcher = cmStrCat(*val, ' ');
  562. }
  563. std::string const cmakeCmd =
  564. this->GetLocalGenerator()->ConvertToOutputFormat(
  565. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  566. if (needDyndep) {
  567. // Rule to scan dependencies of sources that need preprocessing.
  568. {
  569. std::vector<std::string> scanCommands;
  570. std::string scanRuleName;
  571. std::string ppFileName;
  572. if (compilationPreprocesses) {
  573. scanRuleName = this->LanguageScanRule(lang, config);
  574. ppFileName = "$PREPROCESSED_OUTPUT_FILE";
  575. std::string const& scanCommand = mf->GetRequiredDefinition(
  576. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_SCANDEP_SOURCE"));
  577. cmExpandList(scanCommand, scanCommands);
  578. for (std::string& i : scanCommands) {
  579. i = cmStrCat(launcher, i);
  580. }
  581. } else {
  582. scanRuleName = this->LanguagePreprocessAndScanRule(lang, config);
  583. ppFileName = "$out";
  584. std::string const& ppCommmand = mf->GetRequiredDefinition(
  585. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  586. cmExpandList(ppCommmand, scanCommands);
  587. for (std::string& i : scanCommands) {
  588. i = cmStrCat(launcher, i);
  589. }
  590. scanCommands.emplace_back(GetScanCommand(cmakeCmd, tdi, lang, "$out",
  591. "$DYNDEP_INTERMEDIATE_FILE"));
  592. }
  593. auto scanRule =
  594. GetScanRule(scanRuleName, ppFileName, vars, responseFlag, flags,
  595. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  596. std::move(scanCommands), config);
  597. scanRule.Comment =
  598. cmStrCat("Rule for generating ", lang, " dependencies.");
  599. if (compilationPreprocesses) {
  600. scanRule.Description =
  601. cmStrCat("Scanning $in for ", lang, " dependencies");
  602. } else {
  603. scanRule.Description =
  604. cmStrCat("Building ", lang, " preprocessed $out");
  605. }
  606. this->GetGlobalGenerator()->AddRule(scanRule);
  607. }
  608. if (!compilationPreprocesses) {
  609. // Compilation will not preprocess, so it does not need the defines
  610. // unless the compiler wants them for some other purpose.
  611. if (!this->CompileWithDefines(lang)) {
  612. vars.Defines = "";
  613. }
  614. // Rule to scan dependencies of sources that do not need preprocessing.
  615. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  616. std::vector<std::string> scanCommands;
  617. scanCommands.emplace_back(
  618. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  619. auto scanRule = GetScanRule(
  620. scanRuleName, "", vars, "", flags, rulePlaceholderExpander.get(),
  621. this->GetLocalGenerator(), std::move(scanCommands), config);
  622. // Write the rule for generating dependencies for the given language.
  623. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  624. " dependencies on non-preprocessed files.");
  625. scanRule.Description =
  626. cmStrCat("Generating ", lang, " dependencies for $in");
  627. this->GetGlobalGenerator()->AddRule(scanRule);
  628. }
  629. // Write the rule for ninja dyndep file generation.
  630. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  631. // Command line length is almost always limited -> use response file for
  632. // dyndep rules
  633. rule.RspFile = "$out.rsp";
  634. rule.RspContent = "$in";
  635. // Run CMake dependency scanner on the source file (using the preprocessed
  636. // source if that was performed).
  637. std::string ddModmapArg;
  638. if (!modmapFormat.empty()) {
  639. ddModmapArg += cmStrCat(" --modmapfmt=", modmapFormat);
  640. }
  641. {
  642. std::vector<std::string> ddCmds;
  643. {
  644. std::string ccmd = cmStrCat(
  645. cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, " --lang=", lang,
  646. ddModmapArg, " --dd=$out @", rule.RspFile);
  647. ddCmds.emplace_back(std::move(ccmd));
  648. }
  649. rule.Command =
  650. this->GetLocalGenerator()->BuildCommandLine(ddCmds, config, config);
  651. }
  652. rule.Comment =
  653. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  654. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  655. this->GetGlobalGenerator()->AddRule(rule);
  656. }
  657. cmNinjaRule rule(this->LanguageCompilerRule(lang, config));
  658. // If using a response file, move defines, includes, and flags into it.
  659. if (!responseFlag.empty()) {
  660. rule.RspFile = "$RSP_FILE";
  661. rule.RspContent =
  662. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  663. flags = cmStrCat(responseFlag, rule.RspFile);
  664. vars.Defines = "";
  665. vars.Includes = "";
  666. }
  667. // Tell ninja dependency format so all deps can be loaded into a database
  668. std::string cldeps;
  669. if (!compilationPreprocesses) {
  670. // The compiler will not do preprocessing, so it has no such dependencies.
  671. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  672. // For the MS resource compiler we need cmcldeps, but skip dependencies
  673. // for source-file try_compile cases because they are always fresh.
  674. if (!mf->GetIsSourceFileTryCompile()) {
  675. rule.DepType = "gcc";
  676. rule.DepFile = "$DEP_FILE";
  677. cmProp d = mf->GetDefinition("CMAKE_C_COMPILER");
  678. const std::string cl =
  679. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  680. cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang,
  681. ' ', vars.Source, " $DEP_FILE $out \"",
  682. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  683. "\" \"", cl, "\" ");
  684. }
  685. } else {
  686. const auto& depType = this->GetMakefile()->GetSafeDefinition(
  687. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  688. if (depType == "msvc"_s) {
  689. rule.DepType = "msvc";
  690. rule.DepFile.clear();
  691. } else {
  692. rule.DepType = "gcc";
  693. rule.DepFile = "$DEP_FILE";
  694. }
  695. vars.DependencyFile = rule.DepFile.c_str();
  696. vars.DependencyTarget = "$out";
  697. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  698. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  699. if (!depfileFlags.empty()) {
  700. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  701. depfileFlags, vars);
  702. flags += cmStrCat(' ', depfileFlags);
  703. }
  704. }
  705. if (needDyndep && !modmapFormat.empty()) {
  706. std::string modmapFlags = mf->GetRequiredDefinition(
  707. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_MODULE_MAP_FLAG"));
  708. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  709. "$DYNDEP_MODULE_MAP_FILE");
  710. flags += cmStrCat(' ', modmapFlags);
  711. }
  712. vars.Flags = flags.c_str();
  713. vars.DependencyFile = rule.DepFile.c_str();
  714. // Rule for compiling object file.
  715. std::vector<std::string> compileCmds;
  716. if (lang == "CUDA") {
  717. std::string cmdVar;
  718. if (this->GeneratorTarget->GetPropertyAsBool(
  719. "CUDA_SEPARABLE_COMPILATION")) {
  720. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  721. } else if (this->GeneratorTarget->GetPropertyAsBool(
  722. "CUDA_PTX_COMPILATION")) {
  723. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  724. } else {
  725. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  726. }
  727. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  728. cmExpandList(compileCmd, compileCmds);
  729. } else {
  730. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  731. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  732. cmExpandList(compileCmd, compileCmds);
  733. }
  734. // See if we need to use a compiler launcher like ccache or distcc
  735. std::string compilerLauncher;
  736. if (!compileCmds.empty() &&
  737. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  738. lang == "HIP" || lang == "ISPC" || lang == "OBJC" ||
  739. lang == "OBJCXX")) {
  740. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  741. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  742. if (cmNonempty(clauncher)) {
  743. compilerLauncher = *clauncher;
  744. }
  745. }
  746. // Maybe insert an include-what-you-use runner.
  747. if (!compileCmds.empty() &&
  748. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX")) {
  749. std::string const tidy_prop = cmStrCat(lang, "_CLANG_TIDY");
  750. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  751. cmProp iwyu = nullptr;
  752. cmProp cpplint = nullptr;
  753. cmProp cppcheck = nullptr;
  754. if (lang == "C" || lang == "CXX") {
  755. std::string const iwyu_prop = cmStrCat(lang, "_INCLUDE_WHAT_YOU_USE");
  756. iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  757. std::string const cpplint_prop = cmStrCat(lang, "_CPPLINT");
  758. cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  759. std::string const cppcheck_prop = cmStrCat(lang, "_CPPCHECK");
  760. cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  761. }
  762. if (cmNonempty(iwyu) || cmNonempty(tidy) || cmNonempty(cpplint) ||
  763. cmNonempty(cppcheck)) {
  764. std::string run_iwyu = cmStrCat(cmakeCmd, " -E __run_co_compile");
  765. if (!compilerLauncher.empty()) {
  766. // In __run_co_compile case the launcher command is supplied
  767. // via --launcher=<maybe-list> and consumed
  768. run_iwyu +=
  769. cmStrCat(" --launcher=",
  770. this->LocalGenerator->EscapeForShell(compilerLauncher));
  771. compilerLauncher.clear();
  772. }
  773. if (cmNonempty(iwyu)) {
  774. run_iwyu += cmStrCat(" --iwyu=",
  775. this->GetLocalGenerator()->EscapeForShell(*iwyu));
  776. }
  777. if (cmNonempty(tidy)) {
  778. run_iwyu += " --tidy=";
  779. cmProp p = this->Makefile->GetDefinition(
  780. cmStrCat("CMAKE_", lang, "_CLANG_TIDY_DRIVER_MODE"));
  781. std::string driverMode;
  782. if (cmNonempty(p)) {
  783. driverMode = *p;
  784. } else {
  785. driverMode = lang == "C" ? "gcc" : "g++";
  786. }
  787. run_iwyu += this->GetLocalGenerator()->EscapeForShell(
  788. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  789. }
  790. if (cmNonempty(cpplint)) {
  791. run_iwyu += cmStrCat(
  792. " --cpplint=", this->GetLocalGenerator()->EscapeForShell(*cpplint));
  793. }
  794. if (cmNonempty(cppcheck)) {
  795. run_iwyu +=
  796. cmStrCat(" --cppcheck=",
  797. this->GetLocalGenerator()->EscapeForShell(*cppcheck));
  798. }
  799. if (cmNonempty(tidy) || cmNonempty(cpplint) || cmNonempty(cppcheck)) {
  800. run_iwyu += " --source=$in";
  801. }
  802. run_iwyu += " -- ";
  803. compileCmds.front().insert(0, run_iwyu);
  804. }
  805. }
  806. // If compiler launcher was specified and not consumed above, it
  807. // goes to the beginning of the command line.
  808. if (!compileCmds.empty() && !compilerLauncher.empty()) {
  809. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  810. if (!args.empty()) {
  811. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  812. args[0], cmOutputConverter::SHELL);
  813. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  814. i = this->LocalGenerator->EscapeForShell(i);
  815. }
  816. }
  817. compileCmds.front().insert(0, cmStrCat(cmJoin(args, " "), ' '));
  818. }
  819. if (!compileCmds.empty()) {
  820. compileCmds.front().insert(0, cldeps);
  821. }
  822. const auto& extraCommands = this->GetMakefile()->GetSafeDefinition(
  823. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  824. if (!extraCommands.empty()) {
  825. auto commandList = cmExpandedList(extraCommands);
  826. compileCmds.insert(compileCmds.end(), commandList.cbegin(),
  827. commandList.cend());
  828. }
  829. for (std::string& i : compileCmds) {
  830. i = cmStrCat(launcher, i);
  831. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  832. vars);
  833. }
  834. rule.Command =
  835. this->GetLocalGenerator()->BuildCommandLine(compileCmds, config, config);
  836. // Write the rule for compiling file of the given language.
  837. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  838. rule.Description = cmStrCat("Building ", lang, " object $out");
  839. this->GetGlobalGenerator()->AddRule(rule);
  840. }
  841. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  842. const std::string& config, const std::string& fileConfig,
  843. bool firstForConfig)
  844. {
  845. // Write comments.
  846. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  847. this->GetImplFileStream(fileConfig)
  848. << "# Object build statements for "
  849. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  850. << " target " << this->GetTargetName() << "\n\n";
  851. {
  852. std::vector<cmSourceFile const*> customCommands;
  853. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  854. for (cmSourceFile const* sf : customCommands) {
  855. cmCustomCommand const* cc = sf->GetCustomCommand();
  856. this->GetLocalGenerator()->AddCustomCommandTarget(
  857. cc, this->GetGeneratorTarget());
  858. // Record the custom commands for this target. The container is used
  859. // in WriteObjectBuildStatement when called in a loop below.
  860. this->Configs[config].CustomCommands.push_back(cc);
  861. }
  862. }
  863. {
  864. std::vector<cmSourceFile const*> headerSources;
  865. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  866. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  867. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  868. config);
  869. }
  870. {
  871. std::vector<cmSourceFile const*> extraSources;
  872. this->GeneratorTarget->GetExtraSources(extraSources, config);
  873. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  874. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  875. config);
  876. }
  877. if (firstForConfig) {
  878. cmProp pchExtension =
  879. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  880. std::vector<cmSourceFile const*> externalObjects;
  881. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  882. for (cmSourceFile const* sf : externalObjects) {
  883. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  884. this->ConvertToNinjaPath(sf->GetFullPath()), config);
  885. if (!cmHasSuffix(objectFileName, pchExtension)) {
  886. this->Configs[config].Objects.push_back(objectFileName);
  887. }
  888. }
  889. }
  890. {
  891. cmNinjaBuild build("phony");
  892. build.Comment =
  893. cmStrCat("Order-only phony target for ", this->GetTargetName());
  894. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  895. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  896. this->GetLocalGenerator()->AppendTargetDepends(
  897. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  898. DependOnTargetOrdering);
  899. // Add order-only dependencies on other files associated with the target.
  900. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  901. // Add order-only dependencies on custom command outputs.
  902. for (cmCustomCommand const* cc : this->Configs[config].CustomCommands) {
  903. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  904. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  905. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  906. std::transform(ccoutputs.begin(), ccoutputs.end(),
  907. std::back_inserter(orderOnlyDeps),
  908. this->MapToNinjaPath());
  909. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  910. std::back_inserter(orderOnlyDeps),
  911. this->MapToNinjaPath());
  912. }
  913. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  914. orderOnlyDeps.erase(
  915. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  916. orderOnlyDeps.end());
  917. // The phony target must depend on at least one input or ninja will explain
  918. // that "output ... of phony edge with no inputs doesn't exist" and
  919. // consider the phony output "dirty".
  920. if (orderOnlyDeps.empty()) {
  921. // Any path that always exists will work here. It would be nice to
  922. // use just "." but that is not supported by Ninja < 1.7.
  923. std::string tgtDir = cmStrCat(
  924. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  925. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  926. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  927. }
  928. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  929. build);
  930. }
  931. {
  932. std::vector<cmSourceFile const*> objectSources;
  933. this->GeneratorTarget->GetObjectSources(objectSources, config);
  934. for (cmSourceFile const* sf : objectSources) {
  935. this->WriteObjectBuildStatement(sf, config, fileConfig, firstForConfig);
  936. }
  937. }
  938. for (auto const& langDDIFiles : this->Configs[config].DDIFiles) {
  939. std::string const& language = langDDIFiles.first;
  940. cmNinjaDeps const& ddiFiles = langDDIFiles.second;
  941. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  942. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  943. build.ExplicitDeps = ddiFiles;
  944. this->WriteTargetDependInfo(language, config);
  945. // Make sure dyndep files for all our dependencies have already
  946. // been generated so that the '<LANG>Modules.json' files they
  947. // produced as side-effects are available for us to read.
  948. // Ideally we should depend on the '<LANG>Modules.json' files
  949. // from our dependencies directly, but we don't know which of
  950. // our dependencies produces them. Fixing this will require
  951. // refactoring the Ninja generator to generate targets in
  952. // dependency order so that we can collect the needed information.
  953. this->GetLocalGenerator()->AppendTargetDepends(
  954. this->GeneratorTarget, build.OrderOnlyDeps, config, fileConfig,
  955. DependOnTargetArtifact);
  956. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  957. build);
  958. }
  959. this->GetImplFileStream(fileConfig) << "\n";
  960. if (!this->Configs[config].SwiftOutputMap.empty()) {
  961. std::string const mapFilePath =
  962. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  963. "output-file-map.json");
  964. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  965. cmGeneratorTarget const* target = this->GeneratorTarget;
  966. if (cmProp name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  967. return *name;
  968. }
  969. return this->ConvertToNinjaPath(
  970. cmStrCat(target->GetSupportDirectory(), '/', config, '/',
  971. target->GetName(), ".swiftdeps"));
  972. }();
  973. // build the global target dependencies
  974. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  975. Json::Value deps(Json::objectValue);
  976. deps["swift-dependencies"] = targetSwiftDepsPath;
  977. this->Configs[config].SwiftOutputMap[""] = deps;
  978. cmGeneratedFileStream output(mapFilePath);
  979. output << this->Configs[config].SwiftOutputMap;
  980. }
  981. }
  982. namespace {
  983. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  984. const std::string& ppFileName,
  985. bool compilePP, bool compilePPWithDefines,
  986. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  987. std::string const& modmapFormat,
  988. const std::string& objectFileName,
  989. cmLocalGenerator* lg)
  990. {
  991. cmNinjaBuild scanBuild(ruleName);
  992. scanBuild.RspFile = "$out.rsp";
  993. if (compilePP) {
  994. // Move compilation dependencies to the scan/preprocessing build statement.
  995. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  996. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  997. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  998. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  999. // The actual compilation will now use the preprocessed source.
  1000. objBuild.ExplicitDeps.push_back(ppFileName);
  1001. } else {
  1002. // Copy compilation dependencies to the scan/preprocessing build statement.
  1003. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1004. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1005. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1006. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1007. }
  1008. // Scanning and compilation generally use the same flags.
  1009. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  1010. if (compilePP && !compilePPWithDefines) {
  1011. // Move preprocessor definitions to the scan/preprocessor build statement.
  1012. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  1013. } else {
  1014. // Copy preprocessor definitions to the scan/preprocessor build statement.
  1015. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1016. }
  1017. // Copy include directories to the preprocessor build statement. The
  1018. // Fortran compilation build statement still needs them for the INCLUDE
  1019. // directive.
  1020. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1021. // Tell dependency scanner the object file that will result from
  1022. // compiling the source.
  1023. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1024. // Tell dependency scanner where to store dyndep intermediate results.
  1025. std::string const& ddiFile = cmStrCat(objectFileName, ".ddi");
  1026. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  1027. // Outputs of the scan/preprocessor build statement.
  1028. if (compilePP) {
  1029. scanBuild.Outputs.push_back(ppFileName);
  1030. scanBuild.ImplicitOuts.push_back(ddiFile);
  1031. } else {
  1032. scanBuild.Outputs.push_back(ddiFile);
  1033. scanBuild.Variables["PREPROCESSED_OUTPUT_FILE"] = ppFileName;
  1034. }
  1035. // Scanning always uses a depfile for preprocessor dependencies.
  1036. std::string const& depFileName = cmStrCat(scanBuild.Outputs.front(), ".d");
  1037. scanBuild.Variables["DEP_FILE"] =
  1038. lg->ConvertToOutputFormat(depFileName, cmOutputConverter::SHELL);
  1039. if (compilePP) {
  1040. // The actual compilation does not need a depfile because it
  1041. // depends on the already-preprocessed source.
  1042. vars.erase("DEP_FILE");
  1043. }
  1044. if (!modmapFormat.empty()) {
  1045. // XXX(modmap): If changing this path construction, change
  1046. // `cmGlobalNinjaGenerator::WriteDyndep` to expect the corresponding
  1047. // file path.
  1048. std::string const ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1049. scanBuild.Variables["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1050. scanBuild.ImplicitOuts.push_back(ddModmapFile);
  1051. }
  1052. return scanBuild;
  1053. }
  1054. }
  1055. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1056. cmSourceFile const* source, const std::string& config,
  1057. const std::string& fileConfig, bool firstForConfig)
  1058. {
  1059. std::string const language = source->GetLanguage();
  1060. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1061. std::string const objectDir = this->ConvertToNinjaPath(
  1062. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1063. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1064. std::string const objectFileName =
  1065. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1066. std::string const objectFileDir =
  1067. cmSystemTools::GetFilenamePath(objectFileName);
  1068. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1069. // build response file name
  1070. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1071. cmProp flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1072. bool const lang_supports_response =
  1073. !(language == "RC" || (language == "CUDA" && !flag));
  1074. int const commandLineLengthLimit =
  1075. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1076. cmNinjaBuild objBuild(this->LanguageCompilerRule(language, config));
  1077. cmNinjaVars& vars = objBuild.Variables;
  1078. vars["FLAGS"] = this->ComputeFlagsForObject(source, language, config);
  1079. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1080. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1081. if (this->GetMakefile()->GetSafeDefinition(
  1082. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1083. bool replaceExt(false);
  1084. if (!language.empty()) {
  1085. std::string repVar =
  1086. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1087. replaceExt = this->Makefile->IsOn(repVar);
  1088. }
  1089. if (!replaceExt) {
  1090. // use original code
  1091. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1092. cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL);
  1093. } else {
  1094. // Replace the original source file extension with the
  1095. // depend file extension.
  1096. std::string dependFileName = cmStrCat(
  1097. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1098. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1099. cmStrCat(objectFileDir, '/', dependFileName),
  1100. cmOutputConverter::SHELL);
  1101. }
  1102. }
  1103. this->ExportObjectCompileCommand(
  1104. language, sourceFilePath, objectDir, objectFileName, objectFileDir,
  1105. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"], config);
  1106. objBuild.Outputs.push_back(objectFileName);
  1107. if (firstForConfig) {
  1108. cmProp pchExtension =
  1109. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1110. if (!cmHasSuffix(objectFileName, pchExtension)) {
  1111. // Add this object to the list of object files.
  1112. this->Configs[config].Objects.push_back(objectFileName);
  1113. }
  1114. }
  1115. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1116. // Add precompile headers dependencies
  1117. std::vector<std::string> depList;
  1118. std::vector<std::string> architectures;
  1119. this->GeneratorTarget->GetAppleArchs(config, architectures);
  1120. if (architectures.empty()) {
  1121. architectures.emplace_back();
  1122. }
  1123. std::unordered_set<std::string> pchSources;
  1124. for (const std::string& arch : architectures) {
  1125. const std::string pchSource =
  1126. this->GeneratorTarget->GetPchSource(config, language, arch);
  1127. if (!pchSource.empty()) {
  1128. pchSources.insert(pchSource);
  1129. }
  1130. }
  1131. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1132. for (const std::string& arch : architectures) {
  1133. depList.push_back(
  1134. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1135. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1136. depList.push_back(
  1137. this->GeneratorTarget->GetPchFile(config, language, arch));
  1138. }
  1139. }
  1140. }
  1141. if (cmProp objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1142. std::vector<std::string> objDepList = cmExpandedList(*objectDeps);
  1143. std::copy(objDepList.begin(), objDepList.end(),
  1144. std::back_inserter(depList));
  1145. }
  1146. if (!depList.empty()) {
  1147. for (std::string& odi : depList) {
  1148. if (cmSystemTools::FileIsFullPath(odi)) {
  1149. odi = cmSystemTools::CollapseFullPath(odi);
  1150. }
  1151. }
  1152. std::transform(depList.begin(), depList.end(),
  1153. std::back_inserter(objBuild.ImplicitDeps),
  1154. this->MapToNinjaPath());
  1155. }
  1156. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1157. // If the source file is GENERATED and does not have a custom command
  1158. // (either attached to this source file or another one), assume that one of
  1159. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1160. // will rebuild the file.
  1161. if (source->GetIsGenerated() &&
  1162. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1163. !source->GetCustomCommand() &&
  1164. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFilePath)) {
  1165. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1166. sourceFilePath, objBuild.OrderOnlyDeps);
  1167. }
  1168. // For some cases we scan to dynamically discover dependencies.
  1169. bool const needDyndep = this->NeedDyndep(language, config);
  1170. bool const compilationPreprocesses =
  1171. !this->NeedExplicitPreprocessing(language);
  1172. std::string modmapFormat;
  1173. if (needDyndep) {
  1174. std::string const modmapFormatVar =
  1175. cmStrCat("CMAKE_EXPERIMENTAL_", language, "_MODULE_MAP_FORMAT");
  1176. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1177. }
  1178. if (needDyndep) {
  1179. // If source/target has preprocessing turned off, we still need to
  1180. // generate an explicit dependency step
  1181. const auto srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1182. cmOutputConverter::FortranPreprocess preprocess =
  1183. cmOutputConverter::GetFortranPreprocess(srcpp);
  1184. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1185. const auto& tgtpp =
  1186. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1187. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1188. }
  1189. bool const compilePP = !compilationPreprocesses &&
  1190. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1191. bool const compilePPWithDefines =
  1192. compilePP && this->CompileWithDefines(language);
  1193. std::string scanRuleName;
  1194. std::string ppFileName;
  1195. if (compilePP) {
  1196. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1197. ppFileName = this->ConvertToNinjaPath(
  1198. this->GetPreprocessedFilePath(source, config));
  1199. } else {
  1200. scanRuleName = this->LanguageScanRule(language, config);
  1201. ppFileName = cmStrCat(objectFileName, ".ddi.i");
  1202. }
  1203. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1204. scanRuleName, ppFileName, compilePP, compilePPWithDefines, objBuild,
  1205. vars, modmapFormat, objectFileName, this->LocalGenerator);
  1206. if (compilePP) {
  1207. // In case compilation requires flags that are incompatible with
  1208. // preprocessing, include them here.
  1209. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1210. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1211. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1212. // Prepend source file's original directory as an include directory
  1213. // so e.g. Fortran INCLUDE statements can look for files in it.
  1214. std::vector<std::string> sourceDirectory;
  1215. sourceDirectory.push_back(
  1216. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1217. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1218. sourceDirectory, this->GeneratorTarget, language, config, false,
  1219. cmLocalGenerator::IncludePathStyle::Default);
  1220. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1221. }
  1222. if (firstForConfig) {
  1223. std::string const ddiFile = cmStrCat(objectFileName, ".ddi");
  1224. this->Configs[config].DDIFiles[language].push_back(ddiFile);
  1225. }
  1226. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1227. ppBuild.Variables);
  1228. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1229. ppBuild, commandLineLengthLimit);
  1230. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1231. objBuild.OrderOnlyDeps.push_back(dyndep);
  1232. vars["dyndep"] = dyndep;
  1233. if (!modmapFormat.empty()) {
  1234. std::string const ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1235. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1236. objBuild.OrderOnlyDeps.push_back(ddModmapFile);
  1237. }
  1238. }
  1239. this->EnsureParentDirectoryExists(objectFileName);
  1240. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1241. objectDir, cmOutputConverter::SHELL);
  1242. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1243. objectFileDir, cmOutputConverter::SHELL);
  1244. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1245. vars);
  1246. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1247. auto pchIt = pchSources.find(source->GetFullPath());
  1248. if (pchIt != pchSources.end()) {
  1249. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1250. this->GetGeneratorTarget(), vars);
  1251. }
  1252. }
  1253. this->SetMsvcTargetPdbVariable(vars, config);
  1254. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1255. if (language == "ISPC") {
  1256. std::string const& objectName =
  1257. this->GeneratorTarget->GetObjectName(source);
  1258. std::string ispcSource =
  1259. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1260. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1261. cmProp ispcSuffixProp =
  1262. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1263. assert(ispcSuffixProp);
  1264. std::string ispcHeaderDirectory =
  1265. this->GeneratorTarget->GetObjectDirectory(config);
  1266. if (cmProp prop =
  1267. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1268. ispcHeaderDirectory =
  1269. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1270. }
  1271. std::string ispcHeader =
  1272. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1273. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1274. // Make sure ninja knows what command generates the header
  1275. objBuild.ImplicitOuts.push_back(ispcHeader);
  1276. // Make sure ninja knows how to clean the generated header
  1277. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1278. auto ispcSuffixes =
  1279. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1280. if (ispcSuffixes.size() > 1) {
  1281. std::string rootObjectDir =
  1282. this->GeneratorTarget->GetObjectDirectory(config);
  1283. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1284. objectName, rootObjectDir, ispcSuffixes);
  1285. for (auto sideEffect : ispcSideEfffectObjects) {
  1286. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1287. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1288. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1289. }
  1290. }
  1291. vars["ISPC_HEADER_FILE"] =
  1292. this->GetLocalGenerator()->ConvertToOutputFormat(
  1293. ispcHeader, cmOutputConverter::SHELL);
  1294. } else {
  1295. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1296. if (!headers.empty()) {
  1297. std::transform(headers.begin(), headers.end(), headers.begin(),
  1298. this->MapToNinjaPath());
  1299. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1300. headers.begin(), headers.end());
  1301. }
  1302. }
  1303. if (language == "Swift") {
  1304. this->EmitSwiftDependencyInfo(source, config);
  1305. } else {
  1306. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1307. objBuild, commandLineLengthLimit);
  1308. }
  1309. if (cmProp objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1310. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1311. *objectOutputs, this->LocalGenerator, config);
  1312. if (!evaluatedObjectOutputs.empty()) {
  1313. cmNinjaBuild build("phony");
  1314. build.Comment = "Additional output files.";
  1315. build.Outputs = cmExpandedList(evaluatedObjectOutputs);
  1316. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1317. build.Outputs.begin(), this->MapToNinjaPath());
  1318. build.ExplicitDeps = objBuild.Outputs;
  1319. this->GetGlobalGenerator()->WriteBuild(
  1320. this->GetImplFileStream(fileConfig), build);
  1321. }
  1322. }
  1323. }
  1324. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1325. const std::string& config)
  1326. {
  1327. Json::Value tdi(Json::objectValue);
  1328. tdi["language"] = lang;
  1329. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1330. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1331. std::string mod_dir;
  1332. if (lang == "Fortran") {
  1333. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1334. this->Makefile->GetHomeOutputDirectory());
  1335. } else if (lang == "CXX") {
  1336. mod_dir =
  1337. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory);
  1338. }
  1339. if (mod_dir.empty()) {
  1340. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1341. }
  1342. tdi["module-dir"] = mod_dir;
  1343. if (lang == "Fortran") {
  1344. tdi["submodule-sep"] =
  1345. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1346. tdi["submodule-ext"] =
  1347. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1348. } else if (lang == "CXX") {
  1349. // No extra information necessary.
  1350. }
  1351. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1352. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1353. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1354. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1355. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1356. std::vector<std::string> includes;
  1357. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1358. lang, config);
  1359. for (std::string const& i : includes) {
  1360. // Convert the include directories the same way we do for -I flags.
  1361. // See upstream ninja issue 1251.
  1362. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1363. }
  1364. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1365. Json::arrayValue;
  1366. for (std::string const& l : this->GetLinkedTargetDirectories(config)) {
  1367. tdi_linked_target_dirs.append(l);
  1368. }
  1369. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1370. cmGeneratedFileStream tdif(tdin);
  1371. tdif << tdi;
  1372. }
  1373. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1374. cmSourceFile const* source, const std::string& config)
  1375. {
  1376. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1377. std::string const objectFilePath =
  1378. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1379. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1380. if (cmProp name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1381. return *name;
  1382. }
  1383. return cmStrCat(objectFilePath, ".swiftdeps");
  1384. }();
  1385. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1386. if (cmProp name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1387. return *name;
  1388. }
  1389. return cmStrCat(objectFilePath, ".dia");
  1390. }();
  1391. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1392. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1393. std::string const objectFileName =
  1394. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1395. std::string const objectFileDir =
  1396. cmSystemTools::GetFilenamePath(objectFileName);
  1397. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1398. std::string dependFileName = cmStrCat(
  1399. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1400. return local->ConvertToOutputFormat(
  1401. cmStrCat(objectFileDir, '/', dependFileName),
  1402. cmOutputConverter::SHELL);
  1403. }
  1404. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1405. cmOutputConverter::SHELL);
  1406. }();
  1407. // build the source file mapping
  1408. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1409. Json::Value entry = Json::Value(Json::objectValue);
  1410. entry["object"] = objectFilePath;
  1411. entry["dependencies"] = makeDepsPath;
  1412. entry["swift-dependencies"] = swiftDepsPath;
  1413. entry["diagnostics"] = swiftDiaPath;
  1414. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1415. }
  1416. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1417. std::string const& language, std::string const& sourceFileName,
  1418. std::string const& objectDir, std::string const& objectFileName,
  1419. std::string const& objectFileDir, std::string const& flags,
  1420. std::string const& defines, std::string const& includes,
  1421. std::string const& outputConfig)
  1422. {
  1423. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  1424. return;
  1425. }
  1426. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1427. compileObjectVars.Language = language.c_str();
  1428. std::string escapedSourceFileName = sourceFileName;
  1429. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1430. escapedSourceFileName =
  1431. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1432. this->GetGlobalGenerator()
  1433. ->GetCMakeInstance()
  1434. ->GetHomeOutputDirectory());
  1435. }
  1436. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1437. escapedSourceFileName, cmOutputConverter::SHELL);
  1438. compileObjectVars.Source = escapedSourceFileName.c_str();
  1439. compileObjectVars.Object = objectFileName.c_str();
  1440. compileObjectVars.ObjectDir = objectDir.c_str();
  1441. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1442. compileObjectVars.Flags = flags.c_str();
  1443. compileObjectVars.Defines = defines.c_str();
  1444. compileObjectVars.Includes = includes.c_str();
  1445. // Rule for compiling object file.
  1446. std::vector<std::string> compileCmds;
  1447. if (language == "CUDA") {
  1448. std::string cmdVar;
  1449. if (this->GeneratorTarget->GetPropertyAsBool(
  1450. "CUDA_SEPARABLE_COMPILATION")) {
  1451. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  1452. } else if (this->GeneratorTarget->GetPropertyAsBool(
  1453. "CUDA_PTX_COMPILATION")) {
  1454. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  1455. } else {
  1456. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  1457. }
  1458. const std::string& compileCmd =
  1459. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1460. cmExpandList(compileCmd, compileCmds);
  1461. } else {
  1462. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  1463. const std::string& compileCmd =
  1464. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1465. cmExpandList(compileCmd, compileCmds);
  1466. }
  1467. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1468. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  1469. for (std::string& i : compileCmds) {
  1470. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1471. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1472. compileObjectVars);
  1473. }
  1474. std::string cmdLine = this->GetLocalGenerator()->BuildCommandLine(
  1475. compileCmds, outputConfig, outputConfig);
  1476. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  1477. }
  1478. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  1479. {
  1480. if (cmProp prop_value =
  1481. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1482. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  1483. std::vector<std::string> cleanFiles;
  1484. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  1485. this->GeneratorTarget),
  1486. cleanFiles);
  1487. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  1488. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  1489. for (std::string const& cleanFile : cleanFiles) {
  1490. // Support relative paths
  1491. gg->AddAdditionalCleanFile(
  1492. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  1493. }
  1494. }
  1495. }
  1496. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  1497. {
  1498. auto const it = this->Configs.find(config);
  1499. if (it != this->Configs.end()) {
  1500. return it->second.Objects;
  1501. }
  1502. return {};
  1503. }
  1504. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1505. const std::string& path) const
  1506. {
  1507. if (cmSystemTools::FileIsFullPath(path)) {
  1508. cmSystemTools::MakeDirectory(path);
  1509. } else {
  1510. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1511. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  1512. // Also ensures their is a trailing slash.
  1513. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1514. fullPath += path;
  1515. cmSystemTools::MakeDirectory(fullPath);
  1516. }
  1517. }
  1518. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1519. const std::string& path) const
  1520. {
  1521. this->EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1522. }
  1523. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1524. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  1525. {
  1526. // Skip OS X content when not building a Framework or Bundle.
  1527. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1528. return;
  1529. }
  1530. std::string macdir =
  1531. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  1532. config);
  1533. // Reject files that collide with files from the Ninja file's native config.
  1534. if (config != this->FileConfig) {
  1535. std::string nativeMacdir =
  1536. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  1537. pkgloc, this->FileConfig);
  1538. if (macdir == nativeMacdir) {
  1539. return;
  1540. }
  1541. }
  1542. // Get the input file location.
  1543. std::string input = source.GetFullPath();
  1544. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1545. // Get the output file location.
  1546. std::string output =
  1547. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  1548. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1549. // Write a build statement to copy the content into the bundle.
  1550. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  1551. input, output, this->FileConfig);
  1552. // Add as a dependency to the target so that it gets called.
  1553. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  1554. }
  1555. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1556. const std::string& pool_property, cmGeneratorTarget* target,
  1557. cmNinjaVars& vars)
  1558. {
  1559. cmProp pool = target->GetProperty(pool_property);
  1560. if (pool) {
  1561. vars["pool"] = *pool;
  1562. }
  1563. }
  1564. bool cmNinjaTargetGenerator::ForceResponseFile()
  1565. {
  1566. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1567. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1568. cmSystemTools::HasEnv(forceRspFile));
  1569. }