cmNinjaTargetGenerator.cxx 59 KB

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