cmNinjaTargetGenerator.cxx 69 KB

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