cmNinjaTargetGenerator.cxx 63 KB

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