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::GetSourceFilePath(
  330. cmSourceFile const* source) const
  331. {
  332. return this->ConvertToNinjaPath(source->GetFullPath());
  333. }
  334. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  335. cmSourceFile const* source, const std::string& config) const
  336. {
  337. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  338. if (!path.empty()) {
  339. path += '/';
  340. }
  341. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  342. path += cmStrCat(
  343. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  344. this->GetGlobalGenerator()->ConfigDirectory(config), '/', objectName);
  345. return path;
  346. }
  347. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  348. cmSourceFile const* source, const std::string& config) const
  349. {
  350. // Choose an extension to compile already-preprocessed source.
  351. std::string ppExt = source->GetExtension();
  352. if (cmHasLiteralPrefix(ppExt, "F")) {
  353. // Some Fortran compilers automatically enable preprocessing for
  354. // upper-case extensions. Since the source is already preprocessed,
  355. // use a lower-case extension.
  356. ppExt = cmSystemTools::LowerCase(ppExt);
  357. }
  358. if (ppExt == "fpp") {
  359. // Some Fortran compilers automatically enable preprocessing for
  360. // the ".fpp" extension. Since the source is already preprocessed,
  361. // use the ".f" extension.
  362. ppExt = "f";
  363. }
  364. // Take the object file name and replace the extension.
  365. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  366. std::string const& objExt =
  367. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  368. assert(objName.size() >= objExt.size());
  369. std::string const ppName =
  370. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  371. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  372. if (!path.empty()) {
  373. path += '/';
  374. }
  375. path +=
  376. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  377. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  378. return path;
  379. }
  380. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  381. std::string const& lang, const std::string& config) const
  382. {
  383. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  384. if (!path.empty()) {
  385. path += '/';
  386. }
  387. path += cmStrCat(
  388. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  389. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  390. return path;
  391. }
  392. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  393. std::string const& lang, const std::string& config) const
  394. {
  395. std::string path =
  396. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  397. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  398. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  399. "DependInfo.json");
  400. return path;
  401. }
  402. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  403. const std::string& config) const
  404. {
  405. std::string dir = this->GeneratorTarget->GetDirectory(config);
  406. return this->ConvertToNinjaPath(dir);
  407. }
  408. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  409. const std::string& name, const std::string& config) const
  410. {
  411. std::string path = this->GetTargetOutputDir(config);
  412. if (path.empty() || path == ".") {
  413. return name;
  414. }
  415. path += cmStrCat('/', name);
  416. return path;
  417. }
  418. std::string cmNinjaTargetGenerator::GetTargetName() const
  419. {
  420. return this->GeneratorTarget->GetName();
  421. }
  422. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  423. cmNinjaVars& vars, const std::string& config) const
  424. {
  425. cmMakefile* mf = this->GetMakefile();
  426. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  427. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  428. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  429. std::string pdbPath;
  430. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  431. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  432. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  433. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  434. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  435. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  436. this->GeneratorTarget->GetPDBName(config));
  437. }
  438. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  439. this->ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  440. vars["TARGET_COMPILE_PDB"] =
  441. this->GetLocalGenerator()->ConvertToOutputFormat(
  442. this->ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  443. this->EnsureParentDirectoryExists(pdbPath);
  444. this->EnsureParentDirectoryExists(compilePdbPath);
  445. return true;
  446. }
  447. return false;
  448. }
  449. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  450. const std::string& config)
  451. {
  452. #ifdef NINJA_GEN_VERBOSE_FILES
  453. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  454. #endif
  455. this->WriteCompileRule(language, config);
  456. }
  457. namespace {
  458. // Create the command to run the dependency scanner
  459. std::string GetScanCommand(const std::string& cmakeCmd, const std::string& tdi,
  460. const std::string& lang, const std::string& ppFile,
  461. const std::string& ddiFile)
  462. {
  463. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  464. " --lang=", lang, " --pp=", ppFile,
  465. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=", ddiFile);
  466. }
  467. // Helper function to create dependency scanning rule that may or may
  468. // not perform explicit preprocessing too.
  469. cmNinjaRule GetScanRule(
  470. const std::string& ruleName,
  471. cmRulePlaceholderExpander::RuleVariables const& vars,
  472. const std::string& responseFlag, const std::string& flags,
  473. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  474. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds,
  475. const std::string& outputConfig)
  476. {
  477. cmNinjaRule rule(ruleName);
  478. // Scanning always uses a depfile for preprocessor dependencies.
  479. rule.DepType = ""; // no deps= for multiple outputs
  480. rule.DepFile = "$DEP_FILE";
  481. cmRulePlaceholderExpander::RuleVariables scanVars;
  482. scanVars.CMTargetName = vars.CMTargetName;
  483. scanVars.CMTargetType = vars.CMTargetType;
  484. scanVars.Language = vars.Language;
  485. scanVars.Object = "$OBJ_FILE";
  486. scanVars.PreprocessedSource = "$out";
  487. scanVars.DynDepFile = "$DYNDEP_INTERMEDIATE_FILE";
  488. scanVars.DependencyFile = rule.DepFile.c_str();
  489. scanVars.DependencyTarget = "$out";
  490. // Scanning needs the same preprocessor settings as direct compilation would.
  491. scanVars.Source = vars.Source;
  492. scanVars.Defines = vars.Defines;
  493. scanVars.Includes = vars.Includes;
  494. // Scanning needs the compilation flags too.
  495. std::string scanFlags = flags;
  496. // If using a response file, move defines, includes, and flags into it.
  497. if (!responseFlag.empty()) {
  498. rule.RspFile = "$RSP_FILE";
  499. rule.RspContent =
  500. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  501. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  502. scanVars.Defines = "";
  503. scanVars.Includes = "";
  504. }
  505. scanVars.Flags = scanFlags.c_str();
  506. // Rule for scanning a source file.
  507. for (std::string& scanCmd : scanCmds) {
  508. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  509. }
  510. rule.Command =
  511. generator->BuildCommandLine(scanCmds, outputConfig, outputConfig);
  512. return rule;
  513. }
  514. }
  515. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  516. const std::string& config)
  517. {
  518. cmRulePlaceholderExpander::RuleVariables vars;
  519. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  520. vars.CMTargetType =
  521. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  522. vars.Language = lang.c_str();
  523. vars.Source = "$in";
  524. vars.Object = "$out";
  525. vars.Defines = "$DEFINES";
  526. vars.Includes = "$INCLUDES";
  527. vars.TargetPDB = "$TARGET_PDB";
  528. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  529. vars.ObjectDir = "$OBJECT_DIR";
  530. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  531. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  532. cmMakefile* mf = this->GetMakefile();
  533. // For some cases we scan to dynamically discover dependencies.
  534. bool const needDyndep = this->NeedDyndep(lang, config);
  535. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  536. std::string flags = "$FLAGS";
  537. std::string responseFlag;
  538. bool const lang_supports_response = lang != "RC";
  539. if (lang_supports_response && this->ForceResponseFile()) {
  540. std::string const responseFlagVar =
  541. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  542. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  543. if (responseFlag.empty() && lang != "CUDA") {
  544. responseFlag = "@";
  545. }
  546. }
  547. std::string const modmapFormatVar =
  548. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_MODULE_MAP_FORMAT");
  549. std::string const modmapFormat =
  550. this->Makefile->GetSafeDefinition(modmapFormatVar);
  551. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  552. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  553. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  554. this->ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  555. cmLocalGenerator::SHELL);
  556. std::string launcher;
  557. cmProp val = this->GetLocalGenerator()->GetRuleLauncher(
  558. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  559. if (cmNonempty(val)) {
  560. launcher = cmStrCat(*val, ' ');
  561. }
  562. std::string const cmakeCmd =
  563. this->GetLocalGenerator()->ConvertToOutputFormat(
  564. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  565. if (needDyndep) {
  566. // Rule to scan dependencies of sources that need preprocessing.
  567. {
  568. std::vector<std::string> scanCommands;
  569. std::string scanRuleName;
  570. if (compilationPreprocesses) {
  571. scanRuleName = this->LanguageScanRule(lang, config);
  572. std::string const& scanCommand = mf->GetRequiredDefinition(
  573. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_SCANDEP_SOURCE"));
  574. cmExpandList(scanCommand, scanCommands);
  575. for (std::string& i : scanCommands) {
  576. i = cmStrCat(launcher, i);
  577. }
  578. } else {
  579. scanRuleName = this->LanguagePreprocessAndScanRule(lang, config);
  580. std::string const& ppCommmand = mf->GetRequiredDefinition(
  581. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  582. cmExpandList(ppCommmand, scanCommands);
  583. for (std::string& i : scanCommands) {
  584. i = cmStrCat(launcher, i);
  585. }
  586. scanCommands.emplace_back(GetScanCommand(cmakeCmd, tdi, lang, "$out",
  587. "$DYNDEP_INTERMEDIATE_FILE"));
  588. }
  589. auto scanRule = GetScanRule(
  590. scanRuleName, vars, responseFlag, flags, rulePlaceholderExpander.get(),
  591. this->GetLocalGenerator(), std::move(scanCommands), config);
  592. scanRule.Comment =
  593. cmStrCat("Rule for generating ", lang, " dependencies.");
  594. if (compilationPreprocesses) {
  595. scanRule.Description =
  596. cmStrCat("Scanning $in for ", lang, " dependencies");
  597. } else {
  598. scanRule.Description =
  599. cmStrCat("Building ", lang, " preprocessed $out");
  600. }
  601. this->GetGlobalGenerator()->AddRule(scanRule);
  602. }
  603. if (!compilationPreprocesses) {
  604. // Compilation will not preprocess, so it does not need the defines
  605. // unless the compiler wants them for some other purpose.
  606. if (!this->CompileWithDefines(lang)) {
  607. vars.Defines = "";
  608. }
  609. // Rule to scan dependencies of sources that do not need preprocessing.
  610. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  611. std::vector<std::string> scanCommands;
  612. scanCommands.emplace_back(
  613. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  614. auto scanRule = GetScanRule(
  615. scanRuleName, vars, "", flags, rulePlaceholderExpander.get(),
  616. this->GetLocalGenerator(), std::move(scanCommands), config);
  617. // Write the rule for generating dependencies for the given language.
  618. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  619. " dependencies on non-preprocessed files.");
  620. scanRule.Description =
  621. cmStrCat("Generating ", lang, " dependencies for $in");
  622. this->GetGlobalGenerator()->AddRule(scanRule);
  623. }
  624. // Write the rule for ninja dyndep file generation.
  625. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  626. // Command line length is almost always limited -> use response file for
  627. // dyndep rules
  628. rule.RspFile = "$out.rsp";
  629. rule.RspContent = "$in";
  630. // Run CMake dependency scanner on the source file (using the preprocessed
  631. // source if that was performed).
  632. std::string ddModmapArg;
  633. if (!modmapFormat.empty()) {
  634. ddModmapArg += cmStrCat(" --modmapfmt=", modmapFormat);
  635. }
  636. {
  637. std::vector<std::string> ddCmds;
  638. {
  639. std::string ccmd = cmStrCat(
  640. cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, " --lang=", lang,
  641. ddModmapArg, " --dd=$out @", rule.RspFile);
  642. ddCmds.emplace_back(std::move(ccmd));
  643. }
  644. rule.Command =
  645. this->GetLocalGenerator()->BuildCommandLine(ddCmds, config, config);
  646. }
  647. rule.Comment =
  648. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  649. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  650. this->GetGlobalGenerator()->AddRule(rule);
  651. }
  652. cmNinjaRule rule(this->LanguageCompilerRule(lang, config));
  653. // If using a response file, move defines, includes, and flags into it.
  654. if (!responseFlag.empty()) {
  655. rule.RspFile = "$RSP_FILE";
  656. rule.RspContent =
  657. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  658. flags = cmStrCat(responseFlag, rule.RspFile);
  659. vars.Defines = "";
  660. vars.Includes = "";
  661. }
  662. // Tell ninja dependency format so all deps can be loaded into a database
  663. std::string cldeps;
  664. if (!compilationPreprocesses) {
  665. // The compiler will not do preprocessing, so it has no such dependencies.
  666. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  667. // For the MS resource compiler we need cmcldeps, but skip dependencies
  668. // for source-file try_compile cases because they are always fresh.
  669. if (!mf->GetIsSourceFileTryCompile()) {
  670. rule.DepType = "gcc";
  671. rule.DepFile = "$DEP_FILE";
  672. cmProp d = mf->GetDefinition("CMAKE_C_COMPILER");
  673. const std::string cl =
  674. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  675. cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang,
  676. ' ', vars.Source, " $DEP_FILE $out \"",
  677. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  678. "\" \"", cl, "\" ");
  679. }
  680. } else {
  681. const auto& depType = this->GetMakefile()->GetSafeDefinition(
  682. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  683. if (depType == "msvc"_s) {
  684. rule.DepType = "msvc";
  685. rule.DepFile.clear();
  686. } else {
  687. rule.DepType = "gcc";
  688. rule.DepFile = "$DEP_FILE";
  689. }
  690. vars.DependencyFile = rule.DepFile.c_str();
  691. vars.DependencyTarget = "$out";
  692. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  693. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  694. if (!depfileFlags.empty()) {
  695. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  696. depfileFlags, vars);
  697. flags += cmStrCat(' ', depfileFlags);
  698. }
  699. }
  700. if (needDyndep && !modmapFormat.empty()) {
  701. std::string modmapFlags = mf->GetRequiredDefinition(
  702. cmStrCat("CMAKE_EXPERIMENTAL_", lang, "_MODULE_MAP_FLAG"));
  703. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  704. "$DYNDEP_MODULE_MAP_FILE");
  705. flags += cmStrCat(' ', modmapFlags);
  706. }
  707. vars.Flags = flags.c_str();
  708. vars.DependencyFile = rule.DepFile.c_str();
  709. // Rule for compiling object file.
  710. std::vector<std::string> compileCmds;
  711. if (lang == "CUDA") {
  712. std::string cmdVar;
  713. if (this->GeneratorTarget->GetPropertyAsBool(
  714. "CUDA_SEPARABLE_COMPILATION")) {
  715. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  716. } else if (this->GeneratorTarget->GetPropertyAsBool(
  717. "CUDA_PTX_COMPILATION")) {
  718. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  719. } else {
  720. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  721. }
  722. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  723. cmExpandList(compileCmd, compileCmds);
  724. } else {
  725. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  726. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  727. cmExpandList(compileCmd, compileCmds);
  728. }
  729. // See if we need to use a compiler launcher like ccache or distcc
  730. std::string compilerLauncher;
  731. if (!compileCmds.empty() &&
  732. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  733. lang == "ISPC" || lang == "OBJC" || lang == "OBJCXX")) {
  734. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  735. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  736. if (cmNonempty(clauncher)) {
  737. compilerLauncher = *clauncher;
  738. }
  739. }
  740. // Maybe insert an include-what-you-use runner.
  741. if (!compileCmds.empty() &&
  742. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX")) {
  743. std::string const tidy_prop = cmStrCat(lang, "_CLANG_TIDY");
  744. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  745. cmProp iwyu = nullptr;
  746. cmProp cpplint = nullptr;
  747. cmProp cppcheck = nullptr;
  748. if (lang == "C" || lang == "CXX") {
  749. std::string const iwyu_prop = cmStrCat(lang, "_INCLUDE_WHAT_YOU_USE");
  750. iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  751. std::string const cpplint_prop = cmStrCat(lang, "_CPPLINT");
  752. cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  753. std::string const cppcheck_prop = cmStrCat(lang, "_CPPCHECK");
  754. cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  755. }
  756. if (cmNonempty(iwyu) || cmNonempty(tidy) || cmNonempty(cpplint) ||
  757. cmNonempty(cppcheck)) {
  758. std::string run_iwyu = cmStrCat(cmakeCmd, " -E __run_co_compile");
  759. if (!compilerLauncher.empty()) {
  760. // In __run_co_compile case the launcher command is supplied
  761. // via --launcher=<maybe-list> and consumed
  762. run_iwyu +=
  763. cmStrCat(" --launcher=",
  764. this->LocalGenerator->EscapeForShell(compilerLauncher));
  765. compilerLauncher.clear();
  766. }
  767. if (cmNonempty(iwyu)) {
  768. run_iwyu += cmStrCat(" --iwyu=",
  769. this->GetLocalGenerator()->EscapeForShell(*iwyu));
  770. }
  771. if (cmNonempty(tidy)) {
  772. run_iwyu += " --tidy=";
  773. cmProp p = this->Makefile->GetDefinition(
  774. cmStrCat("CMAKE_", lang, "_CLANG_TIDY_DRIVER_MODE"));
  775. std::string driverMode;
  776. if (cmNonempty(p)) {
  777. driverMode = *p;
  778. } else {
  779. driverMode = lang == "C" ? "gcc" : "g++";
  780. }
  781. run_iwyu += this->GetLocalGenerator()->EscapeForShell(
  782. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  783. }
  784. if (cmNonempty(cpplint)) {
  785. run_iwyu += cmStrCat(
  786. " --cpplint=", this->GetLocalGenerator()->EscapeForShell(*cpplint));
  787. }
  788. if (cmNonempty(cppcheck)) {
  789. run_iwyu +=
  790. cmStrCat(" --cppcheck=",
  791. this->GetLocalGenerator()->EscapeForShell(*cppcheck));
  792. }
  793. if (cmNonempty(tidy) || cmNonempty(cpplint) || cmNonempty(cppcheck)) {
  794. run_iwyu += " --source=$in";
  795. }
  796. run_iwyu += " -- ";
  797. compileCmds.front().insert(0, run_iwyu);
  798. }
  799. }
  800. // If compiler launcher was specified and not consumed above, it
  801. // goes to the beginning of the command line.
  802. if (!compileCmds.empty() && !compilerLauncher.empty()) {
  803. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  804. if (!args.empty()) {
  805. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  806. args[0], cmOutputConverter::SHELL);
  807. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  808. i = this->LocalGenerator->EscapeForShell(i);
  809. }
  810. }
  811. compileCmds.front().insert(0, cmStrCat(cmJoin(args, " "), ' '));
  812. }
  813. if (!compileCmds.empty()) {
  814. compileCmds.front().insert(0, cldeps);
  815. }
  816. const auto& extraCommands = this->GetMakefile()->GetSafeDefinition(
  817. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  818. if (!extraCommands.empty()) {
  819. auto commandList = cmExpandedList(extraCommands);
  820. compileCmds.insert(compileCmds.end(), commandList.cbegin(),
  821. commandList.cend());
  822. }
  823. for (std::string& i : compileCmds) {
  824. i = cmStrCat(launcher, i);
  825. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  826. vars);
  827. }
  828. rule.Command =
  829. this->GetLocalGenerator()->BuildCommandLine(compileCmds, config, config);
  830. // Write the rule for compiling file of the given language.
  831. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  832. rule.Description = cmStrCat("Building ", lang, " object $out");
  833. this->GetGlobalGenerator()->AddRule(rule);
  834. }
  835. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  836. const std::string& config, const std::string& fileConfig,
  837. bool firstForConfig)
  838. {
  839. // Write comments.
  840. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  841. this->GetImplFileStream(fileConfig)
  842. << "# Object build statements for "
  843. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  844. << " target " << this->GetTargetName() << "\n\n";
  845. {
  846. std::vector<cmSourceFile const*> customCommands;
  847. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  848. for (cmSourceFile const* sf : customCommands) {
  849. cmCustomCommand const* cc = sf->GetCustomCommand();
  850. this->GetLocalGenerator()->AddCustomCommandTarget(
  851. cc, this->GetGeneratorTarget());
  852. // Record the custom commands for this target. The container is used
  853. // in WriteObjectBuildStatement when called in a loop below.
  854. this->Configs[config].CustomCommands.push_back(cc);
  855. }
  856. }
  857. {
  858. std::vector<cmSourceFile const*> headerSources;
  859. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  860. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  861. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  862. config);
  863. }
  864. {
  865. std::vector<cmSourceFile const*> extraSources;
  866. this->GeneratorTarget->GetExtraSources(extraSources, config);
  867. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  868. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  869. config);
  870. }
  871. if (firstForConfig) {
  872. cmProp pchExtension =
  873. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  874. std::vector<cmSourceFile const*> externalObjects;
  875. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  876. for (cmSourceFile const* sf : externalObjects) {
  877. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  878. this->GetSourceFilePath(sf), config);
  879. if (!cmSystemTools::StringEndsWith(objectFileName,
  880. cmToCStr(pchExtension))) {
  881. this->Configs[config].Objects.push_back(objectFileName);
  882. }
  883. }
  884. }
  885. {
  886. cmNinjaBuild build("phony");
  887. build.Comment =
  888. cmStrCat("Order-only phony target for ", this->GetTargetName());
  889. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  890. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  891. this->GetLocalGenerator()->AppendTargetDepends(
  892. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  893. DependOnTargetOrdering);
  894. // Add order-only dependencies on other files associated with the target.
  895. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  896. // Add order-only dependencies on custom command outputs.
  897. for (cmCustomCommand const* cc : this->Configs[config].CustomCommands) {
  898. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  899. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  900. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  901. std::transform(ccoutputs.begin(), ccoutputs.end(),
  902. std::back_inserter(orderOnlyDeps),
  903. this->MapToNinjaPath());
  904. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  905. std::back_inserter(orderOnlyDeps),
  906. this->MapToNinjaPath());
  907. }
  908. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  909. orderOnlyDeps.erase(
  910. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  911. orderOnlyDeps.end());
  912. // The phony target must depend on at least one input or ninja will explain
  913. // that "output ... of phony edge with no inputs doesn't exist" and
  914. // consider the phony output "dirty".
  915. if (orderOnlyDeps.empty()) {
  916. // Any path that always exists will work here. It would be nice to
  917. // use just "." but that is not supported by Ninja < 1.7.
  918. std::string tgtDir = cmStrCat(
  919. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  920. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  921. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  922. }
  923. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  924. build);
  925. }
  926. {
  927. std::vector<cmSourceFile const*> objectSources;
  928. this->GeneratorTarget->GetObjectSources(objectSources, config);
  929. for (cmSourceFile const* sf : objectSources) {
  930. this->WriteObjectBuildStatement(sf, config, fileConfig, firstForConfig);
  931. }
  932. }
  933. for (auto const& langDDIFiles : this->Configs[config].DDIFiles) {
  934. std::string const& language = langDDIFiles.first;
  935. cmNinjaDeps const& ddiFiles = langDDIFiles.second;
  936. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  937. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  938. build.ExplicitDeps = ddiFiles;
  939. this->WriteTargetDependInfo(language, config);
  940. // Make sure dyndep files for all our dependencies have already
  941. // been generated so that the '<LANG>Modules.json' files they
  942. // produced as side-effects are available for us to read.
  943. // Ideally we should depend on the '<LANG>Modules.json' files
  944. // from our dependencies directly, but we don't know which of
  945. // our dependencies produces them. Fixing this will require
  946. // refactoring the Ninja generator to generate targets in
  947. // dependency order so that we can collect the needed information.
  948. this->GetLocalGenerator()->AppendTargetDepends(
  949. this->GeneratorTarget, build.OrderOnlyDeps, config, fileConfig,
  950. DependOnTargetArtifact);
  951. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  952. build);
  953. }
  954. this->GetImplFileStream(fileConfig) << "\n";
  955. if (!this->Configs[config].SwiftOutputMap.empty()) {
  956. std::string const mapFilePath =
  957. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  958. "output-file-map.json");
  959. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  960. cmGeneratorTarget const* target = this->GeneratorTarget;
  961. if (cmProp name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  962. return *name;
  963. }
  964. return this->ConvertToNinjaPath(
  965. cmStrCat(target->GetSupportDirectory(), '/', config, '/',
  966. target->GetName(), ".swiftdeps"));
  967. }();
  968. // build the global target dependencies
  969. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  970. Json::Value deps(Json::objectValue);
  971. deps["swift-dependencies"] = targetSwiftDepsPath;
  972. this->Configs[config].SwiftOutputMap[""] = deps;
  973. cmGeneratedFileStream output(mapFilePath);
  974. output << this->Configs[config].SwiftOutputMap;
  975. }
  976. }
  977. namespace {
  978. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  979. const std::string& ppFileName,
  980. bool compilePP, bool compilePPWithDefines,
  981. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  982. std::string const& modmapFormat,
  983. const std::string& objectFileName,
  984. cmLocalGenerator* lg)
  985. {
  986. cmNinjaBuild scanBuild(ruleName);
  987. if (!ppFileName.empty()) {
  988. scanBuild.RspFile = cmStrCat(ppFileName, ".rsp");
  989. } else {
  990. scanBuild.RspFile = "$out.rsp";
  991. }
  992. if (compilePP) {
  993. // Move compilation dependencies to the scan/preprocessing build statement.
  994. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  995. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  996. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  997. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  998. // The actual compilation will now use the preprocessed source.
  999. objBuild.ExplicitDeps.push_back(ppFileName);
  1000. } else {
  1001. // Copy compilation dependencies to the scan/preprocessing build statement.
  1002. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1003. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1004. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1005. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1006. }
  1007. // Scanning and compilation generally use the same flags.
  1008. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  1009. if (compilePP && !compilePPWithDefines) {
  1010. // Move preprocessor definitions to the scan/preprocessor build statement.
  1011. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  1012. } else {
  1013. // Copy preprocessor definitions to the scan/preprocessor build statement.
  1014. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1015. }
  1016. // Copy include directories to the preprocessor build statement. The
  1017. // Fortran compilation build statement still needs them for the INCLUDE
  1018. // directive.
  1019. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1020. // Tell dependency scanner the object file that will result from
  1021. // compiling the source.
  1022. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1023. // Tell dependency scanner where to store dyndep intermediate results.
  1024. std::string const& ddiFile = cmStrCat(objectFileName, ".ddi");
  1025. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  1026. // Outputs of the scan/preprocessor build statement.
  1027. if (!ppFileName.empty()) {
  1028. scanBuild.Outputs.push_back(ppFileName);
  1029. scanBuild.ImplicitOuts.push_back(ddiFile);
  1030. } else {
  1031. scanBuild.Outputs.push_back(ddiFile);
  1032. }
  1033. // Scanning always uses a depfile for preprocessor dependencies.
  1034. std::string const& depFileName = cmStrCat(scanBuild.Outputs.front(), ".d");
  1035. scanBuild.Variables["DEP_FILE"] =
  1036. lg->ConvertToOutputFormat(depFileName, cmOutputConverter::SHELL);
  1037. if (compilePP) {
  1038. // The actual compilation does not need a depfile because it
  1039. // depends on the already-preprocessed source.
  1040. vars.erase("DEP_FILE");
  1041. }
  1042. if (!modmapFormat.empty()) {
  1043. // XXX(modmap): If changing this path construction, change
  1044. // `cmGlobalNinjaGenerator::WriteDyndep` to expect the corresponding
  1045. // file path.
  1046. std::string const ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1047. scanBuild.Variables["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1048. scanBuild.ImplicitOuts.push_back(ddModmapFile);
  1049. }
  1050. return scanBuild;
  1051. }
  1052. }
  1053. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1054. cmSourceFile const* source, const std::string& config,
  1055. const std::string& fileConfig, bool firstForConfig)
  1056. {
  1057. std::string const language = source->GetLanguage();
  1058. std::string const sourceFileName =
  1059. language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
  1060. std::string const objectDir = this->ConvertToNinjaPath(
  1061. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1062. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1063. std::string const objectFileName =
  1064. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1065. std::string const objectFileDir =
  1066. cmSystemTools::GetFilenamePath(objectFileName);
  1067. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1068. // build response file name
  1069. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1070. cmProp flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1071. bool const lang_supports_response =
  1072. !(language == "RC" || (language == "CUDA" && !flag));
  1073. int const commandLineLengthLimit =
  1074. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1075. cmNinjaBuild objBuild(this->LanguageCompilerRule(language, config));
  1076. cmNinjaVars& vars = objBuild.Variables;
  1077. vars["FLAGS"] = this->ComputeFlagsForObject(source, language, config);
  1078. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1079. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1080. if (this->GetMakefile()->GetSafeDefinition(
  1081. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1082. bool replaceExt(false);
  1083. if (!language.empty()) {
  1084. std::string repVar =
  1085. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1086. replaceExt = this->Makefile->IsOn(repVar);
  1087. }
  1088. if (!replaceExt) {
  1089. // use original code
  1090. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1091. cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL);
  1092. } else {
  1093. // Replace the original source file extension with the
  1094. // depend file extension.
  1095. std::string dependFileName = cmStrCat(
  1096. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1097. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1098. cmStrCat(objectFileDir, '/', dependFileName),
  1099. cmOutputConverter::SHELL);
  1100. }
  1101. }
  1102. this->ExportObjectCompileCommand(
  1103. language, sourceFileName, objectDir, objectFileName, objectFileDir,
  1104. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"], config);
  1105. objBuild.Outputs.push_back(objectFileName);
  1106. if (firstForConfig) {
  1107. cmProp pchExtension =
  1108. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1109. if (!cmSystemTools::StringEndsWith(objectFileName,
  1110. cmToCStr(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(sourceFileName);
  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(sourceFileName)) {
  1165. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1166. sourceFileName, 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. }
  1202. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1203. scanRuleName, ppFileName, compilePP, compilePPWithDefines, objBuild,
  1204. vars, modmapFormat, objectFileName, this->LocalGenerator);
  1205. if (compilePP) {
  1206. // In case compilation requires flags that are incompatible with
  1207. // preprocessing, include them here.
  1208. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1209. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1210. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1211. // Prepend source file's original directory as an include directory
  1212. // so e.g. Fortran INCLUDE statements can look for files in it.
  1213. std::vector<std::string> sourceDirectory;
  1214. sourceDirectory.push_back(
  1215. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1216. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1217. sourceDirectory, this->GeneratorTarget, language, config, false,
  1218. cmLocalGenerator::IncludePathStyle::Default);
  1219. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1220. }
  1221. if (firstForConfig) {
  1222. std::string const ddiFile = cmStrCat(objectFileName, ".ddi");
  1223. this->Configs[config].DDIFiles[language].push_back(ddiFile);
  1224. }
  1225. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1226. ppBuild.Variables);
  1227. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1228. ppBuild, commandLineLengthLimit);
  1229. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1230. objBuild.OrderOnlyDeps.push_back(dyndep);
  1231. vars["dyndep"] = dyndep;
  1232. if (!modmapFormat.empty()) {
  1233. std::string const ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1234. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1235. objBuild.OrderOnlyDeps.push_back(ddModmapFile);
  1236. }
  1237. }
  1238. this->EnsureParentDirectoryExists(objectFileName);
  1239. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1240. objectDir, cmOutputConverter::SHELL);
  1241. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1242. objectFileDir, cmOutputConverter::SHELL);
  1243. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1244. vars);
  1245. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1246. auto pchIt = pchSources.find(source->GetFullPath());
  1247. if (pchIt != pchSources.end()) {
  1248. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1249. this->GetGeneratorTarget(), vars);
  1250. }
  1251. }
  1252. this->SetMsvcTargetPdbVariable(vars, config);
  1253. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1254. if (language == "ISPC") {
  1255. std::string const& objectName =
  1256. this->GeneratorTarget->GetObjectName(source);
  1257. std::string ispcSource =
  1258. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1259. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1260. cmProp ispcSuffixProp =
  1261. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1262. assert(ispcSuffixProp);
  1263. std::string ispcHeaderDirectory =
  1264. this->GeneratorTarget->GetObjectDirectory(config);
  1265. if (cmProp prop =
  1266. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1267. ispcHeaderDirectory =
  1268. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1269. }
  1270. std::string ispcHeader =
  1271. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1272. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1273. // Make sure ninja knows what command generates the header
  1274. objBuild.ImplicitOuts.push_back(ispcHeader);
  1275. // Make sure ninja knows how to clean the generated header
  1276. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1277. auto ispcSuffixes =
  1278. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1279. if (ispcSuffixes.size() > 1) {
  1280. std::string rootObjectDir =
  1281. this->GeneratorTarget->GetObjectDirectory(config);
  1282. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1283. objectName, rootObjectDir, ispcSuffixes);
  1284. for (auto sideEffect : ispcSideEfffectObjects) {
  1285. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1286. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1287. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1288. }
  1289. }
  1290. vars["ISPC_HEADER_FILE"] =
  1291. this->GetLocalGenerator()->ConvertToOutputFormat(
  1292. ispcHeader, cmOutputConverter::SHELL);
  1293. } else {
  1294. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1295. if (!headers.empty()) {
  1296. std::transform(headers.begin(), headers.end(), headers.begin(),
  1297. this->MapToNinjaPath());
  1298. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1299. headers.begin(), headers.end());
  1300. }
  1301. }
  1302. if (language == "Swift") {
  1303. this->EmitSwiftDependencyInfo(source, config);
  1304. } else {
  1305. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1306. objBuild, commandLineLengthLimit);
  1307. }
  1308. if (cmProp objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1309. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1310. *objectOutputs, this->LocalGenerator, config);
  1311. if (!evaluatedObjectOutputs.empty()) {
  1312. cmNinjaBuild build("phony");
  1313. build.Comment = "Additional output files.";
  1314. build.Outputs = cmExpandedList(evaluatedObjectOutputs);
  1315. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1316. build.Outputs.begin(), this->MapToNinjaPath());
  1317. build.ExplicitDeps = objBuild.Outputs;
  1318. this->GetGlobalGenerator()->WriteBuild(
  1319. this->GetImplFileStream(fileConfig), build);
  1320. }
  1321. }
  1322. }
  1323. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1324. const std::string& config)
  1325. {
  1326. Json::Value tdi(Json::objectValue);
  1327. tdi["language"] = lang;
  1328. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1329. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1330. std::string mod_dir;
  1331. if (lang == "Fortran") {
  1332. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1333. this->Makefile->GetHomeOutputDirectory());
  1334. } else if (lang == "CXX") {
  1335. mod_dir =
  1336. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory);
  1337. }
  1338. if (mod_dir.empty()) {
  1339. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1340. }
  1341. tdi["module-dir"] = mod_dir;
  1342. if (lang == "Fortran") {
  1343. tdi["submodule-sep"] =
  1344. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1345. tdi["submodule-ext"] =
  1346. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1347. } else if (lang == "CXX") {
  1348. // No extra information necessary.
  1349. }
  1350. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1351. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1352. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1353. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1354. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1355. std::vector<std::string> includes;
  1356. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1357. lang, config);
  1358. for (std::string const& i : includes) {
  1359. // Convert the include directories the same way we do for -I flags.
  1360. // See upstream ninja issue 1251.
  1361. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1362. }
  1363. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1364. Json::arrayValue;
  1365. for (std::string const& l : this->GetLinkedTargetDirectories(config)) {
  1366. tdi_linked_target_dirs.append(l);
  1367. }
  1368. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1369. cmGeneratedFileStream tdif(tdin);
  1370. tdif << tdi;
  1371. }
  1372. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1373. cmSourceFile const* source, const std::string& config)
  1374. {
  1375. std::string const sourceFilePath =
  1376. this->ConvertToNinjaPath(this->GetSourceFilePath(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. }