cmNinjaTargetGenerator.cxx 66 KB

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