cmNinjaTargetGenerator.cxx 63 KB

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