cmNinjaTargetGenerator.cxx 73 KB

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