cmNinjaTargetGenerator.cxx 81 KB

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