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