cmNinjaTargetGenerator.cxx 63 KB

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