cmNinjaTargetGenerator.cxx 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmNinjaTargetGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <iterator>
  7. #include <map>
  8. #include <ostream>
  9. #include <unordered_map>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <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. const std::string& ddiFile)
  466. {
  467. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  468. " --lang=", lang, " --src=$in", " --pp=", ppFile,
  469. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=", ddiFile);
  470. }
  471. // Helper function to create dependency scanning rule that may or may
  472. // not perform explicit preprocessing too.
  473. cmNinjaRule GetScanRule(
  474. const std::string& ruleName,
  475. cmRulePlaceholderExpander::RuleVariables const& vars,
  476. const std::string& responseFlag, const std::string& flags,
  477. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  478. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds)
  479. {
  480. cmNinjaRule rule(ruleName);
  481. // Scanning always uses a depfile for preprocessor dependencies.
  482. rule.DepType = ""; // no deps= for multiple outputs
  483. rule.DepFile = "$DEP_FILE";
  484. cmRulePlaceholderExpander::RuleVariables scanVars;
  485. scanVars.CMTargetName = vars.CMTargetName;
  486. scanVars.CMTargetType = vars.CMTargetType;
  487. scanVars.Language = vars.Language;
  488. scanVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
  489. scanVars.PreprocessedSource = "$out";
  490. scanVars.DependencyFile = rule.DepFile.c_str();
  491. // Scanning needs the same preprocessor settings as direct compilation would.
  492. scanVars.Source = vars.Source;
  493. scanVars.Defines = vars.Defines;
  494. scanVars.Includes = vars.Includes;
  495. // Scanning needs the compilation flags too.
  496. std::string scanFlags = flags;
  497. // If using a response file, move defines, includes, and flags into it.
  498. if (!responseFlag.empty()) {
  499. rule.RspFile = "$RSP_FILE";
  500. rule.RspContent =
  501. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  502. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  503. scanVars.Defines = "";
  504. scanVars.Includes = "";
  505. }
  506. scanVars.Flags = scanFlags.c_str();
  507. // Rule for scanning a source file.
  508. for (std::string& scanCmd : scanCmds) {
  509. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  510. }
  511. rule.Command = generator->BuildCommandLine(scanCmds);
  512. return rule;
  513. }
  514. }
  515. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  516. const std::string& config)
  517. {
  518. cmRulePlaceholderExpander::RuleVariables vars;
  519. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  520. vars.CMTargetType =
  521. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  522. vars.Language = lang.c_str();
  523. vars.Source = "$in";
  524. vars.Object = "$out";
  525. vars.Defines = "$DEFINES";
  526. vars.Includes = "$INCLUDES";
  527. vars.TargetPDB = "$TARGET_PDB";
  528. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  529. vars.ObjectDir = "$OBJECT_DIR";
  530. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  531. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  532. cmMakefile* mf = this->GetMakefile();
  533. // For some cases we scan to dynamically discover dependencies.
  534. bool const needDyndep = this->NeedDyndep(lang);
  535. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  536. std::string flags = "$FLAGS";
  537. std::string responseFlag;
  538. bool const lang_supports_response = lang != "RC";
  539. if (lang_supports_response && this->ForceResponseFile()) {
  540. std::string const responseFlagVar =
  541. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  542. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  543. if (responseFlag.empty() && lang != "CUDA") {
  544. responseFlag = "@";
  545. }
  546. }
  547. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  548. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  549. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  550. ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  551. cmLocalGenerator::SHELL);
  552. std::string launcher;
  553. cmProp val = this->GetLocalGenerator()->GetRuleLauncher(
  554. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  555. if (cmNonempty(val)) {
  556. launcher = cmStrCat(*val, ' ');
  557. }
  558. std::string const cmakeCmd =
  559. this->GetLocalGenerator()->ConvertToOutputFormat(
  560. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  561. if (needDyndep) {
  562. // Rule to scan dependencies of sources that need preprocessing.
  563. {
  564. std::vector<std::string> scanCommands;
  565. std::string const& scanRuleName =
  566. this->LanguagePreprocessAndScanRule(lang, config);
  567. std::string const& ppCommmand = mf->GetRequiredDefinition(
  568. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  569. cmExpandList(ppCommmand, scanCommands);
  570. for (std::string& i : scanCommands) {
  571. i = cmStrCat(launcher, i);
  572. }
  573. scanCommands.emplace_back(GetScanCommand(cmakeCmd, tdi, lang, "$out",
  574. "$DYNDEP_INTERMEDIATE_FILE"));
  575. auto scanRule = GetScanRule(
  576. scanRuleName, vars, responseFlag, flags, rulePlaceholderExpander.get(),
  577. this->GetLocalGenerator(), std::move(scanCommands));
  578. scanRule.Comment =
  579. cmStrCat("Rule for generating ", lang, " dependencies.");
  580. scanRule.Description = cmStrCat("Building ", lang, " preprocessed $out");
  581. this->GetGlobalGenerator()->AddRule(scanRule);
  582. }
  583. {
  584. // Compilation will not preprocess, so it does not need the defines
  585. // unless the compiler wants them for some other purpose.
  586. if (!this->CompileWithDefines(lang)) {
  587. vars.Defines = "";
  588. }
  589. // Rule to scan dependencies of sources that do not need preprocessing.
  590. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  591. std::vector<std::string> scanCommands;
  592. scanCommands.emplace_back(
  593. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  594. auto scanRule = GetScanRule(
  595. scanRuleName, vars, "", flags, rulePlaceholderExpander.get(),
  596. this->GetLocalGenerator(), std::move(scanCommands));
  597. // Write the rule for generating dependencies for the given language.
  598. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  599. " dependencies on non-preprocessed files.");
  600. scanRule.Description =
  601. cmStrCat("Generating ", lang, " dependencies for $in");
  602. this->GetGlobalGenerator()->AddRule(scanRule);
  603. }
  604. // Write the rule for ninja dyndep file generation.
  605. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  606. // Command line length is almost always limited -> use response file for
  607. // dyndep rules
  608. rule.RspFile = "$out.rsp";
  609. rule.RspContent = "$in";
  610. // Run CMake dependency scanner on the source file (using the preprocessed
  611. // source if that was performed).
  612. {
  613. std::vector<std::string> ddCmds;
  614. {
  615. std::string ccmd =
  616. cmStrCat(cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi,
  617. " --lang=", lang, " --dd=$out @", rule.RspFile);
  618. ddCmds.emplace_back(std::move(ccmd));
  619. }
  620. rule.Command = this->GetLocalGenerator()->BuildCommandLine(ddCmds);
  621. }
  622. rule.Comment =
  623. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  624. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  625. this->GetGlobalGenerator()->AddRule(rule);
  626. }
  627. cmNinjaRule rule(this->LanguageCompilerRule(lang, config));
  628. // If using a response file, move defines, includes, and flags into it.
  629. if (!responseFlag.empty()) {
  630. rule.RspFile = "$RSP_FILE";
  631. rule.RspContent =
  632. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  633. flags = cmStrCat(responseFlag, rule.RspFile);
  634. vars.Defines = "";
  635. vars.Includes = "";
  636. }
  637. // Tell ninja dependency format so all deps can be loaded into a database
  638. std::string cldeps;
  639. if (!compilationPreprocesses) {
  640. // The compiler will not do preprocessing, so it has no such dependencies.
  641. } else if (this->NeedDepTypeMSVC(lang)) {
  642. rule.DepType = "msvc";
  643. rule.DepFile.clear();
  644. flags += " /showIncludes";
  645. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  646. // For the MS resource compiler we need cmcldeps, but skip dependencies
  647. // for source-file try_compile cases because they are always fresh.
  648. if (!mf->GetIsSourceFileTryCompile()) {
  649. rule.DepType = "gcc";
  650. rule.DepFile = "$DEP_FILE";
  651. cmProp d = mf->GetDefinition("CMAKE_C_COMPILER");
  652. const std::string cl =
  653. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  654. cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang,
  655. ' ', vars.Source, " $DEP_FILE $out \"",
  656. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  657. "\" \"", cl, "\" ");
  658. }
  659. } else {
  660. rule.DepType = "gcc";
  661. rule.DepFile = "$DEP_FILE";
  662. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  663. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  664. if (!depfileFlags.empty()) {
  665. cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
  666. cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out");
  667. cmSystemTools::ReplaceString(
  668. depfileFlags, "<CMAKE_C_COMPILER>",
  669. cmToCStr(mf->GetDefinition("CMAKE_C_COMPILER")));
  670. flags += cmStrCat(' ', depfileFlags);
  671. }
  672. }
  673. vars.Flags = flags.c_str();
  674. vars.DependencyFile = rule.DepFile.c_str();
  675. // Rule for compiling object file.
  676. std::vector<std::string> compileCmds;
  677. if (lang == "CUDA") {
  678. std::string cmdVar;
  679. if (this->GeneratorTarget->GetPropertyAsBool(
  680. "CUDA_SEPARABLE_COMPILATION")) {
  681. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  682. } else if (this->GeneratorTarget->GetPropertyAsBool(
  683. "CUDA_PTX_COMPILATION")) {
  684. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  685. } else {
  686. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  687. }
  688. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  689. cmExpandList(compileCmd, compileCmds);
  690. } else {
  691. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  692. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  693. cmExpandList(compileCmd, compileCmds);
  694. }
  695. // See if we need to use a compiler launcher like ccache or distcc
  696. std::string compilerLauncher;
  697. if (!compileCmds.empty() &&
  698. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA" ||
  699. lang == "ISPC" || lang == "OBJC" || lang == "OBJCXX")) {
  700. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  701. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  702. if (cmNonempty(clauncher)) {
  703. compilerLauncher = *clauncher;
  704. }
  705. }
  706. // Maybe insert an include-what-you-use runner.
  707. if (!compileCmds.empty() &&
  708. (lang == "C" || lang == "CXX" || lang == "OBJC" || lang == "OBJCXX")) {
  709. std::string const tidy_prop = cmStrCat(lang, "_CLANG_TIDY");
  710. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  711. cmProp iwyu = nullptr;
  712. cmProp cpplint = nullptr;
  713. cmProp cppcheck = nullptr;
  714. if (lang == "C" || lang == "CXX") {
  715. std::string const iwyu_prop = cmStrCat(lang, "_INCLUDE_WHAT_YOU_USE");
  716. iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  717. std::string const cpplint_prop = cmStrCat(lang, "_CPPLINT");
  718. cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  719. std::string const cppcheck_prop = cmStrCat(lang, "_CPPCHECK");
  720. cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  721. }
  722. if (cmNonempty(iwyu) || cmNonempty(tidy) || cmNonempty(cpplint) ||
  723. cmNonempty(cppcheck)) {
  724. std::string run_iwyu = cmStrCat(cmakeCmd, " -E __run_co_compile");
  725. if (!compilerLauncher.empty()) {
  726. // In __run_co_compile case the launcher command is supplied
  727. // via --launcher=<maybe-list> and consumed
  728. run_iwyu +=
  729. cmStrCat(" --launcher=",
  730. this->LocalGenerator->EscapeForShell(compilerLauncher));
  731. compilerLauncher.clear();
  732. }
  733. if (cmNonempty(iwyu)) {
  734. run_iwyu += cmStrCat(" --iwyu=",
  735. this->GetLocalGenerator()->EscapeForShell(*iwyu));
  736. }
  737. if (cmNonempty(tidy)) {
  738. run_iwyu += " --tidy=";
  739. cmProp p = this->Makefile->GetDefinition(
  740. cmStrCat("CMAKE_", lang, "_CLANG_TIDY_DRIVER_MODE"));
  741. std::string driverMode;
  742. if (cmNonempty(p)) {
  743. driverMode = *p;
  744. } else {
  745. driverMode = lang == "C" ? "gcc" : "g++";
  746. }
  747. run_iwyu += this->GetLocalGenerator()->EscapeForShell(
  748. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  749. }
  750. if (cmNonempty(cpplint)) {
  751. run_iwyu += cmStrCat(
  752. " --cpplint=", this->GetLocalGenerator()->EscapeForShell(*cpplint));
  753. }
  754. if (cmNonempty(cppcheck)) {
  755. run_iwyu +=
  756. cmStrCat(" --cppcheck=",
  757. this->GetLocalGenerator()->EscapeForShell(*cppcheck));
  758. }
  759. if (cmNonempty(tidy) || cmNonempty(cpplint) || cmNonempty(cppcheck)) {
  760. run_iwyu += " --source=$in";
  761. }
  762. run_iwyu += " -- ";
  763. compileCmds.front().insert(0, run_iwyu);
  764. }
  765. }
  766. // If compiler launcher was specified and not consumed above, it
  767. // goes to the beginning of the command line.
  768. if (!compileCmds.empty() && !compilerLauncher.empty()) {
  769. std::vector<std::string> args = cmExpandedList(compilerLauncher, true);
  770. if (!args.empty()) {
  771. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  772. args[0], cmOutputConverter::SHELL);
  773. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  774. i = this->LocalGenerator->EscapeForShell(i);
  775. }
  776. }
  777. compileCmds.front().insert(0, cmStrCat(cmJoin(args, " "), ' '));
  778. }
  779. if (!compileCmds.empty()) {
  780. compileCmds.front().insert(0, cldeps);
  781. }
  782. for (std::string& i : compileCmds) {
  783. i = cmStrCat(launcher, i);
  784. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  785. vars);
  786. }
  787. rule.Command = this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  788. // Write the rule for compiling file of the given language.
  789. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  790. rule.Description = cmStrCat("Building ", lang, " object $out");
  791. this->GetGlobalGenerator()->AddRule(rule);
  792. }
  793. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  794. const std::string& config, const std::string& fileConfig,
  795. bool firstForConfig)
  796. {
  797. // Write comments.
  798. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  799. this->GetImplFileStream(fileConfig)
  800. << "# Object build statements for "
  801. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  802. << " target " << this->GetTargetName() << "\n\n";
  803. {
  804. std::vector<cmSourceFile const*> customCommands;
  805. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  806. for (cmSourceFile const* sf : customCommands) {
  807. cmCustomCommand const* cc = sf->GetCustomCommand();
  808. this->GetLocalGenerator()->AddCustomCommandTarget(
  809. cc, this->GetGeneratorTarget());
  810. // Record the custom commands for this target. The container is used
  811. // in WriteObjectBuildStatement when called in a loop below.
  812. this->Configs[config].CustomCommands.push_back(cc);
  813. }
  814. }
  815. {
  816. std::vector<cmSourceFile const*> headerSources;
  817. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  818. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  819. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  820. config);
  821. }
  822. {
  823. std::vector<cmSourceFile const*> extraSources;
  824. this->GeneratorTarget->GetExtraSources(extraSources, config);
  825. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  826. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  827. config);
  828. }
  829. if (firstForConfig) {
  830. cmProp pchExtension = GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  831. std::vector<cmSourceFile const*> externalObjects;
  832. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  833. for (cmSourceFile const* sf : externalObjects) {
  834. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  835. this->GetSourceFilePath(sf), config);
  836. if (!cmSystemTools::StringEndsWith(objectFileName,
  837. cmToCStr(pchExtension))) {
  838. this->Configs[config].Objects.push_back(objectFileName);
  839. }
  840. }
  841. }
  842. {
  843. cmNinjaBuild build("phony");
  844. build.Comment =
  845. cmStrCat("Order-only phony target for ", this->GetTargetName());
  846. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  847. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  848. this->GetLocalGenerator()->AppendTargetDepends(
  849. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  850. DependOnTargetOrdering);
  851. // Add order-only dependencies on other files associated with the target.
  852. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  853. // Add order-only dependencies on custom command outputs.
  854. for (cmCustomCommand const* cc : this->Configs[config].CustomCommands) {
  855. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  856. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  857. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  858. std::transform(ccoutputs.begin(), ccoutputs.end(),
  859. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  860. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  861. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  862. }
  863. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  864. orderOnlyDeps.erase(
  865. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  866. orderOnlyDeps.end());
  867. // The phony target must depend on at least one input or ninja will explain
  868. // that "output ... of phony edge with no inputs doesn't exist" and
  869. // consider the phony output "dirty".
  870. if (orderOnlyDeps.empty()) {
  871. // Any path that always exists will work here. It would be nice to
  872. // use just "." but that is not supported by Ninja < 1.7.
  873. std::string tgtDir = cmStrCat(
  874. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  875. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  876. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  877. }
  878. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  879. build);
  880. }
  881. {
  882. std::vector<cmSourceFile const*> objectSources;
  883. this->GeneratorTarget->GetObjectSources(objectSources, config);
  884. for (cmSourceFile const* sf : objectSources) {
  885. this->WriteObjectBuildStatement(sf, config, fileConfig, firstForConfig);
  886. }
  887. }
  888. for (auto const& langDDIFiles : this->Configs[config].DDIFiles) {
  889. std::string const& language = langDDIFiles.first;
  890. cmNinjaDeps const& ddiFiles = langDDIFiles.second;
  891. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  892. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  893. build.ExplicitDeps = ddiFiles;
  894. this->WriteTargetDependInfo(language, config);
  895. // Make sure dyndep files for all our dependencies have already
  896. // been generated so that the '<LANG>Modules.json' files they
  897. // produced as side-effects are available for us to read.
  898. // Ideally we should depend on the '<LANG>Modules.json' files
  899. // from our dependencies directly, but we don't know which of
  900. // our dependencies produces them. Fixing this will require
  901. // refactoring the Ninja generator to generate targets in
  902. // dependency order so that we can collect the needed information.
  903. this->GetLocalGenerator()->AppendTargetDepends(
  904. this->GeneratorTarget, build.OrderOnlyDeps, config, fileConfig,
  905. DependOnTargetArtifact);
  906. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  907. build);
  908. }
  909. this->GetImplFileStream(fileConfig) << "\n";
  910. if (!this->Configs[config].SwiftOutputMap.empty()) {
  911. std::string const mapFilePath =
  912. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  913. "output-file-map.json");
  914. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  915. cmGeneratorTarget const* target = this->GeneratorTarget;
  916. if (cmProp name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  917. return *name;
  918. }
  919. return this->ConvertToNinjaPath(
  920. cmStrCat(target->GetSupportDirectory(), '/', config, '/',
  921. target->GetName(), ".swiftdeps"));
  922. }();
  923. // build the global target dependencies
  924. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  925. Json::Value deps(Json::objectValue);
  926. deps["swift-dependencies"] = targetSwiftDepsPath;
  927. this->Configs[config].SwiftOutputMap[""] = deps;
  928. cmGeneratedFileStream output(mapFilePath);
  929. output << this->Configs[config].SwiftOutputMap;
  930. }
  931. }
  932. namespace {
  933. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  934. const std::string& ppFileName,
  935. bool compilePP, bool compilePPWithDefines,
  936. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  937. const std::string& objectFileName,
  938. cmLocalGenerator* lg)
  939. {
  940. cmNinjaBuild scanBuild(ruleName);
  941. if (!ppFileName.empty()) {
  942. scanBuild.RspFile = cmStrCat(ppFileName, ".rsp");
  943. } else {
  944. scanBuild.RspFile = "$out.rsp";
  945. }
  946. if (compilePP) {
  947. // Move compilation dependencies to the scan/preprocessing build statement.
  948. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  949. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  950. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  951. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  952. // The actual compilation will now use the preprocessed source.
  953. objBuild.ExplicitDeps.push_back(ppFileName);
  954. } else {
  955. // Copy compilation dependencies to the scan/preprocessing build statement.
  956. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  957. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  958. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  959. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  960. }
  961. // Scanning and compilation generally use the same flags.
  962. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  963. if (compilePP && !compilePPWithDefines) {
  964. // Move preprocessor definitions to the scan/preprocessor build statement.
  965. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  966. } else {
  967. // Copy preprocessor definitions to the scan/preprocessor build statement.
  968. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  969. }
  970. // Copy include directories to the preprocessor build statement. The
  971. // Fortran compilation build statement still needs them for the INCLUDE
  972. // directive.
  973. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  974. // Tell dependency scanner the object file that will result from
  975. // compiling the source.
  976. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  977. // Tell dependency scanner where to store dyndep intermediate results.
  978. std::string const& ddiFile = cmStrCat(objectFileName, ".ddi");
  979. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  980. // Outputs of the scan/preprocessor build statement.
  981. if (!ppFileName.empty()) {
  982. scanBuild.Outputs.push_back(ppFileName);
  983. scanBuild.ImplicitOuts.push_back(ddiFile);
  984. } else {
  985. scanBuild.Outputs.push_back(ddiFile);
  986. }
  987. // Scanning always uses a depfile for preprocessor dependencies.
  988. std::string const& depFileName = cmStrCat(scanBuild.Outputs.front(), ".d");
  989. scanBuild.Variables["DEP_FILE"] =
  990. lg->ConvertToOutputFormat(depFileName, cmOutputConverter::SHELL);
  991. if (compilePP) {
  992. // The actual compilation does not need a depfile because it
  993. // depends on the already-preprocessed source.
  994. vars.erase("DEP_FILE");
  995. }
  996. return scanBuild;
  997. }
  998. }
  999. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1000. cmSourceFile const* source, const std::string& config,
  1001. const std::string& fileConfig, bool firstForConfig)
  1002. {
  1003. std::string const language = source->GetLanguage();
  1004. std::string const sourceFileName =
  1005. language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
  1006. std::string const objectDir = this->ConvertToNinjaPath(
  1007. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1008. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1009. std::string const objectFileName =
  1010. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1011. std::string const objectFileDir =
  1012. cmSystemTools::GetFilenamePath(objectFileName);
  1013. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1014. // build response file name
  1015. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1016. cmProp flag = GetMakefile()->GetDefinition(cmakeLinkVar);
  1017. bool const lang_supports_response =
  1018. !(language == "RC" || (language == "CUDA" && !flag));
  1019. int const commandLineLengthLimit =
  1020. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1021. cmNinjaBuild objBuild(this->LanguageCompilerRule(language, config));
  1022. cmNinjaVars& vars = objBuild.Variables;
  1023. vars["FLAGS"] = this->ComputeFlagsForObject(source, language, config);
  1024. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1025. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1026. if (!this->NeedDepTypeMSVC(language)) {
  1027. bool replaceExt(false);
  1028. if (!language.empty()) {
  1029. std::string repVar =
  1030. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1031. replaceExt = this->Makefile->IsOn(repVar);
  1032. }
  1033. if (!replaceExt) {
  1034. // use original code
  1035. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1036. cmStrCat(objectFileName, ".d"), cmOutputConverter::SHELL);
  1037. } else {
  1038. // Replace the original source file extension with the
  1039. // depend file extension.
  1040. std::string dependFileName = cmStrCat(
  1041. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1042. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1043. cmStrCat(objectFileDir, '/', dependFileName),
  1044. cmOutputConverter::SHELL);
  1045. }
  1046. }
  1047. this->ExportObjectCompileCommand(
  1048. language, sourceFileName, objectDir, objectFileName, objectFileDir,
  1049. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"]);
  1050. objBuild.Outputs.push_back(objectFileName);
  1051. if (firstForConfig) {
  1052. cmProp pchExtension =
  1053. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1054. if (!cmSystemTools::StringEndsWith(objectFileName,
  1055. cmToCStr(pchExtension))) {
  1056. // Add this object to the list of object files.
  1057. this->Configs[config].Objects.push_back(objectFileName);
  1058. }
  1059. }
  1060. objBuild.ExplicitDeps.push_back(sourceFileName);
  1061. // Add precompile headers dependencies
  1062. std::vector<std::string> depList;
  1063. std::vector<std::string> architectures;
  1064. this->GeneratorTarget->GetAppleArchs(config, architectures);
  1065. if (architectures.empty()) {
  1066. architectures.emplace_back();
  1067. }
  1068. std::unordered_set<std::string> pchSources;
  1069. for (const std::string& arch : architectures) {
  1070. const std::string pchSource =
  1071. this->GeneratorTarget->GetPchSource(config, language, arch);
  1072. if (!pchSource.empty()) {
  1073. pchSources.insert(pchSource);
  1074. }
  1075. }
  1076. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1077. for (const std::string& arch : architectures) {
  1078. depList.push_back(
  1079. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1080. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1081. depList.push_back(
  1082. this->GeneratorTarget->GetPchFile(config, language, arch));
  1083. }
  1084. }
  1085. }
  1086. if (cmProp objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1087. std::vector<std::string> objDepList = cmExpandedList(*objectDeps);
  1088. std::copy(objDepList.begin(), objDepList.end(),
  1089. std::back_inserter(depList));
  1090. }
  1091. if (!depList.empty()) {
  1092. for (std::string& odi : depList) {
  1093. if (cmSystemTools::FileIsFullPath(odi)) {
  1094. odi = cmSystemTools::CollapseFullPath(odi);
  1095. }
  1096. }
  1097. std::transform(depList.begin(), depList.end(),
  1098. std::back_inserter(objBuild.ImplicitDeps),
  1099. MapToNinjaPath());
  1100. }
  1101. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1102. // If the source file is GENERATED and does not have a custom command
  1103. // (either attached to this source file or another one), assume that one of
  1104. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1105. // will rebuild the file.
  1106. if (source->GetIsGenerated() &&
  1107. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1108. !source->GetCustomCommand() &&
  1109. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFileName)) {
  1110. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1111. sourceFileName, objBuild.OrderOnlyDeps);
  1112. }
  1113. // For some cases we scan to dynamically discover dependencies.
  1114. bool const needDyndep = this->NeedDyndep(language);
  1115. bool const compilationPreprocesses =
  1116. !this->NeedExplicitPreprocessing(language);
  1117. if (needDyndep) {
  1118. // If source/target has preprocessing turned off, we still need to
  1119. // generate an explicit dependency step
  1120. const auto srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1121. cmOutputConverter::FortranPreprocess preprocess =
  1122. cmOutputConverter::GetFortranPreprocess(srcpp);
  1123. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1124. const auto& tgtpp =
  1125. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1126. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1127. }
  1128. bool const compilePP = !compilationPreprocesses &&
  1129. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1130. bool const compilePPWithDefines =
  1131. compilePP && this->CompileWithDefines(language);
  1132. std::string scanRuleName;
  1133. std::string ppFileName;
  1134. if (compilePP) {
  1135. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1136. ppFileName = this->ConvertToNinjaPath(
  1137. this->GetPreprocessedFilePath(source, config));
  1138. } else {
  1139. scanRuleName = this->LanguageScanRule(language, config);
  1140. }
  1141. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1142. scanRuleName, ppFileName, compilePP, compilePPWithDefines, objBuild,
  1143. vars, objectFileName, this->LocalGenerator);
  1144. if (compilePP) {
  1145. // In case compilation requires flags that are incompatible with
  1146. // preprocessing, include them here.
  1147. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1148. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1149. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1150. // Prepend source file's original directory as an include directory
  1151. // so e.g. Fortran INCLUDE statements can look for files in it.
  1152. std::vector<std::string> sourceDirectory;
  1153. sourceDirectory.push_back(
  1154. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1155. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1156. sourceDirectory, this->GeneratorTarget, language, false, false,
  1157. config);
  1158. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1159. }
  1160. if (firstForConfig) {
  1161. std::string const ddiFile = cmStrCat(objectFileName, ".ddi");
  1162. this->Configs[config].DDIFiles[language].push_back(ddiFile);
  1163. }
  1164. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1165. ppBuild.Variables);
  1166. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1167. ppBuild, commandLineLengthLimit);
  1168. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1169. objBuild.OrderOnlyDeps.push_back(dyndep);
  1170. vars["dyndep"] = dyndep;
  1171. }
  1172. EnsureParentDirectoryExists(objectFileName);
  1173. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1174. objectDir, cmOutputConverter::SHELL);
  1175. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1176. objectFileDir, cmOutputConverter::SHELL);
  1177. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1178. vars);
  1179. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1180. auto pchIt = pchSources.find(source->GetFullPath());
  1181. if (pchIt != pchSources.end()) {
  1182. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1183. this->GetGeneratorTarget(), vars);
  1184. }
  1185. }
  1186. this->SetMsvcTargetPdbVariable(vars, config);
  1187. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1188. if (language == "ISPC") {
  1189. std::string const& objectName =
  1190. this->GeneratorTarget->GetObjectName(source);
  1191. std::string ispcSource =
  1192. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1193. std::string ispcDirectory = objectFileDir;
  1194. if (cmProp prop =
  1195. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1196. ispcDirectory = *prop;
  1197. }
  1198. ispcDirectory =
  1199. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', ispcDirectory);
  1200. std::string ispcHeader = cmStrCat(ispcDirectory, '/', ispcSource, ".h");
  1201. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1202. // Make sure ninja knows what command generates the header
  1203. objBuild.ImplicitOuts.push_back(ispcHeader);
  1204. // Make sure ninja knows how to clean the generated header
  1205. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1206. auto ispcSuffixes =
  1207. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1208. if (ispcSuffixes.size() > 1) {
  1209. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1210. objectName, ispcDirectory, ispcSuffixes);
  1211. for (auto sideEffect : ispcSideEfffectObjects) {
  1212. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1213. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1214. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1215. }
  1216. }
  1217. vars["ISPC_HEADER_FILE"] =
  1218. this->GetLocalGenerator()->ConvertToOutputFormat(
  1219. ispcHeader, cmOutputConverter::SHELL);
  1220. } else {
  1221. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1222. if (!headers.empty()) {
  1223. std::transform(headers.begin(), headers.end(), headers.begin(),
  1224. MapToNinjaPath());
  1225. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1226. headers.begin(), headers.end());
  1227. }
  1228. }
  1229. if (language == "Swift") {
  1230. this->EmitSwiftDependencyInfo(source, config);
  1231. } else {
  1232. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1233. objBuild, commandLineLengthLimit);
  1234. }
  1235. if (cmProp objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1236. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1237. *objectOutputs, this->LocalGenerator, config);
  1238. if (!evaluatedObjectOutputs.empty()) {
  1239. cmNinjaBuild build("phony");
  1240. build.Comment = "Additional output files.";
  1241. build.Outputs = cmExpandedList(evaluatedObjectOutputs);
  1242. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1243. build.Outputs.begin(), MapToNinjaPath());
  1244. build.ExplicitDeps = objBuild.Outputs;
  1245. this->GetGlobalGenerator()->WriteBuild(
  1246. this->GetImplFileStream(fileConfig), build);
  1247. }
  1248. }
  1249. }
  1250. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1251. const std::string& config)
  1252. {
  1253. Json::Value tdi(Json::objectValue);
  1254. tdi["language"] = lang;
  1255. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1256. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1257. if (lang == "Fortran") {
  1258. std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1259. this->Makefile->GetHomeOutputDirectory());
  1260. if (mod_dir.empty()) {
  1261. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1262. }
  1263. tdi["module-dir"] = mod_dir;
  1264. tdi["submodule-sep"] =
  1265. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1266. tdi["submodule-ext"] =
  1267. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1268. }
  1269. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1270. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1271. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1272. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1273. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1274. std::vector<std::string> includes;
  1275. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1276. lang, config);
  1277. for (std::string const& i : includes) {
  1278. // Convert the include directories the same way we do for -I flags.
  1279. // See upstream ninja issue 1251.
  1280. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1281. }
  1282. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1283. Json::arrayValue;
  1284. for (std::string const& l : this->GetLinkedTargetDirectories(config)) {
  1285. tdi_linked_target_dirs.append(l);
  1286. }
  1287. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1288. cmGeneratedFileStream tdif(tdin);
  1289. tdif << tdi;
  1290. }
  1291. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1292. cmSourceFile const* source, const std::string& config)
  1293. {
  1294. std::string const sourceFilePath =
  1295. this->ConvertToNinjaPath(this->GetSourceFilePath(source));
  1296. std::string const objectFilePath =
  1297. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1298. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1299. if (cmProp name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1300. return *name;
  1301. }
  1302. return cmStrCat(objectFilePath, ".swiftdeps");
  1303. }();
  1304. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1305. if (cmProp name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1306. return *name;
  1307. }
  1308. return cmStrCat(objectFilePath, ".dia");
  1309. }();
  1310. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1311. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1312. std::string const objectFileName =
  1313. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1314. std::string const objectFileDir =
  1315. cmSystemTools::GetFilenamePath(objectFileName);
  1316. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1317. std::string dependFileName = cmStrCat(
  1318. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1319. return local->ConvertToOutputFormat(
  1320. cmStrCat(objectFileDir, '/', dependFileName),
  1321. cmOutputConverter::SHELL);
  1322. }
  1323. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1324. cmOutputConverter::SHELL);
  1325. }();
  1326. // build the source file mapping
  1327. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1328. Json::Value entry = Json::Value(Json::objectValue);
  1329. entry["object"] = objectFilePath;
  1330. entry["dependencies"] = makeDepsPath;
  1331. entry["swift-dependencies"] = swiftDepsPath;
  1332. entry["diagnostics"] = swiftDiaPath;
  1333. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1334. }
  1335. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1336. std::string const& language, std::string const& sourceFileName,
  1337. std::string const& objectDir, std::string const& objectFileName,
  1338. std::string const& objectFileDir, std::string const& flags,
  1339. std::string const& defines, std::string const& includes)
  1340. {
  1341. if (!this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS")) {
  1342. return;
  1343. }
  1344. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1345. compileObjectVars.Language = language.c_str();
  1346. std::string escapedSourceFileName = sourceFileName;
  1347. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1348. escapedSourceFileName =
  1349. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1350. this->GetGlobalGenerator()
  1351. ->GetCMakeInstance()
  1352. ->GetHomeOutputDirectory());
  1353. }
  1354. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1355. escapedSourceFileName, cmOutputConverter::SHELL);
  1356. compileObjectVars.Source = escapedSourceFileName.c_str();
  1357. compileObjectVars.Object = objectFileName.c_str();
  1358. compileObjectVars.ObjectDir = objectDir.c_str();
  1359. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1360. compileObjectVars.Flags = flags.c_str();
  1361. compileObjectVars.Defines = defines.c_str();
  1362. compileObjectVars.Includes = includes.c_str();
  1363. // Rule for compiling object file.
  1364. std::vector<std::string> compileCmds;
  1365. if (language == "CUDA") {
  1366. std::string cmdVar;
  1367. if (this->GeneratorTarget->GetPropertyAsBool(
  1368. "CUDA_SEPARABLE_COMPILATION")) {
  1369. cmdVar = "CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION";
  1370. } else if (this->GeneratorTarget->GetPropertyAsBool(
  1371. "CUDA_PTX_COMPILATION")) {
  1372. cmdVar = "CMAKE_CUDA_COMPILE_PTX_COMPILATION";
  1373. } else {
  1374. cmdVar = "CMAKE_CUDA_COMPILE_WHOLE_COMPILATION";
  1375. }
  1376. const std::string& compileCmd =
  1377. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1378. cmExpandList(compileCmd, compileCmds);
  1379. } else {
  1380. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  1381. const std::string& compileCmd =
  1382. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1383. cmExpandList(compileCmd, compileCmds);
  1384. }
  1385. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1386. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  1387. for (std::string& i : compileCmds) {
  1388. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1389. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1390. compileObjectVars);
  1391. }
  1392. std::string cmdLine =
  1393. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  1394. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  1395. }
  1396. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  1397. {
  1398. if (cmProp prop_value =
  1399. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  1400. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  1401. std::vector<std::string> cleanFiles;
  1402. cmExpandList(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  1403. this->GeneratorTarget),
  1404. cleanFiles);
  1405. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  1406. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  1407. for (std::string const& cleanFile : cleanFiles) {
  1408. // Support relative paths
  1409. gg->AddAdditionalCleanFile(
  1410. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  1411. }
  1412. }
  1413. }
  1414. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  1415. {
  1416. auto const it = this->Configs.find(config);
  1417. if (it != this->Configs.end()) {
  1418. return it->second.Objects;
  1419. }
  1420. return {};
  1421. }
  1422. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1423. const std::string& path) const
  1424. {
  1425. if (cmSystemTools::FileIsFullPath(path)) {
  1426. cmSystemTools::MakeDirectory(path);
  1427. } else {
  1428. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1429. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  1430. // Also ensures their is a trailing slash.
  1431. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1432. fullPath += path;
  1433. cmSystemTools::MakeDirectory(fullPath);
  1434. }
  1435. }
  1436. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1437. const std::string& path) const
  1438. {
  1439. EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1440. }
  1441. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1442. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  1443. {
  1444. // Skip OS X content when not building a Framework or Bundle.
  1445. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1446. return;
  1447. }
  1448. std::string macdir =
  1449. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  1450. config);
  1451. // Reject files that collide with files from the Ninja file's native config.
  1452. if (config != this->FileConfig) {
  1453. std::string nativeMacdir =
  1454. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  1455. pkgloc, this->FileConfig);
  1456. if (macdir == nativeMacdir) {
  1457. return;
  1458. }
  1459. }
  1460. // Get the input file location.
  1461. std::string input = source.GetFullPath();
  1462. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1463. // Get the output file location.
  1464. std::string output =
  1465. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  1466. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1467. // Write a build statement to copy the content into the bundle.
  1468. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  1469. input, output, this->FileConfig);
  1470. // Add as a dependency to the target so that it gets called.
  1471. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  1472. }
  1473. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1474. const std::string& pool_property, cmGeneratorTarget* target,
  1475. cmNinjaVars& vars)
  1476. {
  1477. cmProp pool = target->GetProperty(pool_property);
  1478. if (pool) {
  1479. vars["pool"] = *pool;
  1480. }
  1481. }
  1482. bool cmNinjaTargetGenerator::ForceResponseFile()
  1483. {
  1484. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1485. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1486. cmSystemTools::HasEnv(forceRspFile));
  1487. }