cmNinjaTargetGenerator.cxx 71 KB

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