cmNinjaTargetGenerator.cxx 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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 "cm_jsoncpp_value.h"
  5. #include "cm_jsoncpp_writer.h"
  6. #include <algorithm>
  7. #include <assert.h>
  8. #include <iterator>
  9. #include <map>
  10. #include <memory> // IWYU pragma: keep
  11. #include <sstream>
  12. #include <string.h>
  13. #include "cmAlgorithms.h"
  14. #include "cmComputeLinkInformation.h"
  15. #include "cmCustomCommandGenerator.h"
  16. #include "cmGeneratedFileStream.h"
  17. #include "cmGeneratorExpression.h"
  18. #include "cmGeneratorTarget.h"
  19. #include "cmGlobalNinjaGenerator.h"
  20. #include "cmLocalGenerator.h"
  21. #include "cmLocalNinjaGenerator.h"
  22. #include "cmMakefile.h"
  23. #include "cmNinjaNormalTargetGenerator.h"
  24. #include "cmNinjaUtilityTargetGenerator.h"
  25. #include "cmOutputConverter.h"
  26. #include "cmRulePlaceholderExpander.h"
  27. #include "cmSourceFile.h"
  28. #include "cmState.h"
  29. #include "cmStateTypes.h"
  30. #include "cmSystemTools.h"
  31. #include "cmake.h"
  32. cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
  33. {
  34. switch (target->GetType()) {
  35. case cmStateEnums::EXECUTABLE:
  36. case cmStateEnums::SHARED_LIBRARY:
  37. case cmStateEnums::STATIC_LIBRARY:
  38. case cmStateEnums::MODULE_LIBRARY:
  39. case cmStateEnums::OBJECT_LIBRARY:
  40. return new cmNinjaNormalTargetGenerator(target);
  41. case cmStateEnums::UTILITY:
  42. case cmStateEnums::GLOBAL_TARGET:
  43. return new cmNinjaUtilityTargetGenerator(target);
  44. default:
  45. return nullptr;
  46. }
  47. }
  48. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  49. : cmCommonTargetGenerator(target)
  50. , MacOSXContentGenerator(nullptr)
  51. , OSXBundleGenerator(nullptr)
  52. , MacContentFolders()
  53. , LocalGenerator(
  54. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  55. , Objects()
  56. {
  57. MacOSXContentGenerator = new MacOSXContentGeneratorType(this);
  58. }
  59. cmNinjaTargetGenerator::~cmNinjaTargetGenerator()
  60. {
  61. delete this->MacOSXContentGenerator;
  62. }
  63. cmGeneratedFileStream& cmNinjaTargetGenerator::GetBuildFileStream() const
  64. {
  65. return *this->GetGlobalGenerator()->GetBuildFileStream();
  66. }
  67. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  68. {
  69. return *this->GetGlobalGenerator()->GetRulesFileStream();
  70. }
  71. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  72. {
  73. return this->LocalGenerator->GetGlobalNinjaGenerator();
  74. }
  75. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  76. const std::string& lang) const
  77. {
  78. return lang + "_COMPILER__" +
  79. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  80. }
  81. std::string cmNinjaTargetGenerator::LanguagePreprocessRule(
  82. std::string const& lang) const
  83. {
  84. return lang + "_PREPROCESS__" +
  85. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  86. }
  87. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  88. std::string const& lang) const
  89. {
  90. return lang == "Fortran";
  91. }
  92. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  93. const std::string& lang) const
  94. {
  95. return lang + "_DYNDEP__" +
  96. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  97. }
  98. bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const
  99. {
  100. return lang == "Fortran";
  101. }
  102. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget()
  103. {
  104. return "cmake_object_order_depends_target_" + this->GetTargetName();
  105. }
  106. // TODO: Most of the code is picked up from
  107. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  108. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  109. // Refactor it.
  110. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  111. cmSourceFile const* source, const std::string& language)
  112. {
  113. std::string flags = this->GetFlags(language);
  114. // Add Fortran format flags.
  115. if (language == "Fortran") {
  116. this->AppendFortranFormatFlags(flags, *source);
  117. }
  118. // Add source file specific flags.
  119. cmGeneratorExpressionInterpreter genexInterpreter(
  120. this->LocalGenerator, this->GeneratorTarget,
  121. this->LocalGenerator->GetConfigName(), this->GeneratorTarget->GetName(),
  122. language);
  123. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  124. if (const char* cflags = source->GetProperty(COMPILE_FLAGS)) {
  125. this->LocalGenerator->AppendFlags(
  126. flags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
  127. }
  128. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  129. if (const char* coptions = source->GetProperty(COMPILE_OPTIONS)) {
  130. this->LocalGenerator->AppendCompileOptions(
  131. flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
  132. }
  133. return flags;
  134. }
  135. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  136. std::string const& language)
  137. {
  138. std::vector<std::string> includes;
  139. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  140. language, this->GetConfigName());
  141. // Add include directory flags.
  142. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  143. includes, this->GeneratorTarget, language,
  144. language == "RC", // full include paths for RC needed by cmcldeps
  145. false, this->GetConfigName());
  146. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  147. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  148. }
  149. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  150. }
  151. bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const
  152. {
  153. return strcmp(this->GetMakefile()->GetSafeDefinition("CMAKE_NINJA_DEPTYPE_" +
  154. lang),
  155. "msvc") == 0;
  156. }
  157. // TODO: Refactor with
  158. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  159. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  160. const std::string& language)
  161. {
  162. std::set<std::string> defines;
  163. const std::string config = this->LocalGenerator->GetConfigName();
  164. cmGeneratorExpressionInterpreter genexInterpreter(
  165. this->LocalGenerator, this->GeneratorTarget, config,
  166. this->GeneratorTarget->GetName(), language);
  167. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  168. if (const char* compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  169. this->LocalGenerator->AppendDefines(
  170. defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS));
  171. }
  172. std::string defPropName = "COMPILE_DEFINITIONS_";
  173. defPropName += cmSystemTools::UpperCase(config);
  174. if (const char* config_compile_defs = source->GetProperty(defPropName)) {
  175. this->LocalGenerator->AppendDefines(
  176. defines,
  177. genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS));
  178. }
  179. std::string definesString = this->GetDefines(language);
  180. this->LocalGenerator->JoinDefines(defines, definesString, language);
  181. return definesString;
  182. }
  183. std::string cmNinjaTargetGenerator::ComputeIncludes(
  184. cmSourceFile const* source, const std::string& language)
  185. {
  186. std::vector<std::string> includes;
  187. const std::string config = this->LocalGenerator->GetConfigName();
  188. cmGeneratorExpressionInterpreter genexInterpreter(
  189. this->LocalGenerator, this->GeneratorTarget, config,
  190. this->GeneratorTarget->GetName(), language);
  191. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  192. if (const char* cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  193. this->LocalGenerator->AppendIncludeDirectories(
  194. includes, genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES),
  195. *source);
  196. }
  197. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  198. includes, this->GeneratorTarget, language, true, false, config);
  199. this->LocalGenerator->AppendFlags(includesString,
  200. this->GetIncludes(language));
  201. return includesString;
  202. }
  203. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps() const
  204. {
  205. // Static libraries never depend on other targets for linking.
  206. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  207. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  208. return cmNinjaDeps();
  209. }
  210. cmComputeLinkInformation* cli =
  211. this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
  212. if (!cli) {
  213. return cmNinjaDeps();
  214. }
  215. const std::vector<std::string>& deps = cli->GetDepends();
  216. cmNinjaDeps result(deps.size());
  217. std::transform(deps.begin(), deps.end(), result.begin(), MapToNinjaPath());
  218. // Add a dependency on the link definitions file, if any.
  219. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  220. this->GeneratorTarget->GetModuleDefinitionInfo(
  221. this->GetConfigName())) {
  222. for (cmSourceFile const* src : mdi->Sources) {
  223. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  224. }
  225. }
  226. // Add a dependency on user-specified manifest files, if any.
  227. std::vector<cmSourceFile const*> manifest_srcs;
  228. this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
  229. for (cmSourceFile const* manifest_src : manifest_srcs) {
  230. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  231. }
  232. // Add user-specified dependencies.
  233. if (const char* linkDepends =
  234. this->GeneratorTarget->GetProperty("LINK_DEPENDS")) {
  235. std::vector<std::string> linkDeps;
  236. cmSystemTools::ExpandListArgument(linkDepends, linkDeps);
  237. std::transform(linkDeps.begin(), linkDeps.end(),
  238. std::back_inserter(result), MapToNinjaPath());
  239. }
  240. return result;
  241. }
  242. std::string cmNinjaTargetGenerator::GetSourceFilePath(
  243. cmSourceFile const* source) const
  244. {
  245. return ConvertToNinjaPath(source->GetFullPath());
  246. }
  247. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  248. cmSourceFile const* source) const
  249. {
  250. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  251. if (!path.empty()) {
  252. path += "/";
  253. }
  254. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  255. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  256. path += "/";
  257. path += objectName;
  258. return path;
  259. }
  260. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  261. cmSourceFile const* source) const
  262. {
  263. // Choose an extension to compile already-preprocessed source.
  264. std::string ppExt = source->GetExtension();
  265. if (cmHasLiteralPrefix(ppExt, "F")) {
  266. // Some Fortran compilers automatically enable preprocessing for
  267. // upper-case extensions. Since the source is already preprocessed,
  268. // use a lower-case extension.
  269. ppExt = cmSystemTools::LowerCase(ppExt);
  270. }
  271. if (ppExt == "fpp") {
  272. // Some Fortran compilers automatically enable preprocessing for
  273. // the ".fpp" extension. Since the source is already preprocessed,
  274. // use the ".f" extension.
  275. ppExt = "f";
  276. }
  277. // Take the object file name and replace the extension.
  278. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  279. std::string const& objExt =
  280. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  281. assert(objName.size() >= objExt.size());
  282. std::string const ppName =
  283. objName.substr(0, objName.size() - objExt.size()) + "-pp." + ppExt;
  284. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  285. if (!path.empty()) {
  286. path += "/";
  287. }
  288. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  289. path += "/";
  290. path += ppName;
  291. return path;
  292. }
  293. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  294. std::string const& lang) const
  295. {
  296. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  297. if (!path.empty()) {
  298. path += "/";
  299. }
  300. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  301. path += "/";
  302. path += lang;
  303. path += ".dd";
  304. return path;
  305. }
  306. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  307. std::string const& lang) const
  308. {
  309. std::string path = this->Makefile->GetCurrentBinaryDirectory();
  310. path += "/";
  311. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  312. path += "/" + lang + "DependInfo.json";
  313. return path;
  314. }
  315. std::string cmNinjaTargetGenerator::GetTargetOutputDir() const
  316. {
  317. std::string dir = this->GeneratorTarget->GetDirectory(this->GetConfigName());
  318. return ConvertToNinjaPath(dir);
  319. }
  320. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  321. const std::string& name) const
  322. {
  323. std::string path = this->GetTargetOutputDir();
  324. if (path.empty() || path == ".") {
  325. return name;
  326. }
  327. path += "/";
  328. path += name;
  329. return path;
  330. }
  331. std::string cmNinjaTargetGenerator::GetTargetName() const
  332. {
  333. return this->GeneratorTarget->GetName();
  334. }
  335. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const
  336. {
  337. cmMakefile* mf = this->GetMakefile();
  338. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  339. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  340. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  341. std::string pdbPath;
  342. std::string compilePdbPath = this->ComputeTargetCompilePDB();
  343. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  344. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  345. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  346. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  347. pdbPath = this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
  348. pdbPath += "/";
  349. pdbPath += this->GeneratorTarget->GetPDBName(this->GetConfigName());
  350. }
  351. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  352. ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  353. vars["TARGET_COMPILE_PDB"] =
  354. this->GetLocalGenerator()->ConvertToOutputFormat(
  355. ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  356. EnsureParentDirectoryExists(pdbPath);
  357. EnsureParentDirectoryExists(compilePdbPath);
  358. return true;
  359. }
  360. return false;
  361. }
  362. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language)
  363. {
  364. #ifdef NINJA_GEN_VERBOSE_FILES
  365. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  366. #endif
  367. this->WriteCompileRule(language);
  368. }
  369. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
  370. {
  371. cmRulePlaceholderExpander::RuleVariables vars;
  372. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  373. vars.CMTargetType =
  374. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
  375. vars.Language = lang.c_str();
  376. vars.Source = "$in";
  377. vars.Object = "$out";
  378. vars.Defines = "$DEFINES";
  379. vars.Includes = "$INCLUDES";
  380. vars.TargetPDB = "$TARGET_PDB";
  381. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  382. vars.ObjectDir = "$OBJECT_DIR";
  383. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  384. // For some cases we do an explicit preprocessor invocation.
  385. bool const explicitPP = this->NeedExplicitPreprocessing(lang);
  386. bool const needDyndep = this->NeedDyndep(lang);
  387. cmMakefile* mf = this->GetMakefile();
  388. std::string flags = "$FLAGS";
  389. std::string rspfile;
  390. std::string rspcontent;
  391. bool const lang_supports_response = !(lang == "RC" || lang == "CUDA");
  392. if (lang_supports_response && this->ForceResponseFile()) {
  393. std::string const responseFlagVar =
  394. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  395. std::string responseFlag =
  396. this->Makefile->GetSafeDefinition(responseFlagVar);
  397. if (responseFlag.empty()) {
  398. responseFlag = "@";
  399. }
  400. rspfile = "$RSP_FILE";
  401. responseFlag += rspfile;
  402. rspcontent = " $DEFINES $INCLUDES $FLAGS";
  403. flags = std::move(responseFlag);
  404. vars.Defines = "";
  405. vars.Includes = "";
  406. }
  407. // Tell ninja dependency format so all deps can be loaded into a database
  408. std::string deptype;
  409. std::string depfile;
  410. std::string cldeps;
  411. if (explicitPP) {
  412. // The explicit preprocessing step will handle dependency scanning.
  413. } else if (this->NeedDepTypeMSVC(lang)) {
  414. deptype = "msvc";
  415. depfile.clear();
  416. flags += " /showIncludes";
  417. } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) {
  418. // For the MS resource compiler we need cmcldeps, but skip dependencies
  419. // for source-file try_compile cases because they are always fresh.
  420. if (!mf->GetIsSourceFileTryCompile()) {
  421. deptype = "gcc";
  422. depfile = "$DEP_FILE";
  423. const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER")
  424. ? mf->GetSafeDefinition("CMAKE_C_COMPILER")
  425. : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  426. cldeps = "\"";
  427. cldeps += cmSystemTools::GetCMClDepsCommand();
  428. cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \"";
  429. cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  430. cldeps += "\" \"" + cl + "\" ";
  431. }
  432. } else {
  433. deptype = "gcc";
  434. const char* langdeptype = mf->GetDefinition("CMAKE_NINJA_DEPTYPE_" + lang);
  435. if (langdeptype) {
  436. deptype = langdeptype;
  437. }
  438. depfile = "$DEP_FILE";
  439. const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang;
  440. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  441. if (!depfileFlags.empty()) {
  442. cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
  443. cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out");
  444. cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>",
  445. mf->GetDefinition("CMAKE_C_COMPILER"));
  446. flags += " " + depfileFlags;
  447. }
  448. }
  449. vars.Flags = flags.c_str();
  450. vars.DependencyFile = depfile.c_str();
  451. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  452. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  453. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  454. ConvertToNinjaPath(this->GetTargetDependInfoPath(lang)),
  455. cmLocalGenerator::SHELL);
  456. std::string launcher;
  457. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  458. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  459. if (val && *val) {
  460. launcher = val;
  461. launcher += " ";
  462. }
  463. if (explicitPP) {
  464. // Lookup the explicit preprocessing rule.
  465. std::string const ppVar = "CMAKE_" + lang + "_PREPROCESS_SOURCE";
  466. std::string const ppCmd =
  467. this->GetMakefile()->GetRequiredDefinition(ppVar);
  468. // Explicit preprocessing always uses a depfile.
  469. std::string const ppDeptype; // no deps= for multiple outputs
  470. std::string const ppDepfile = "$DEP_FILE";
  471. cmRulePlaceholderExpander::RuleVariables ppVars;
  472. ppVars.CMTargetName = vars.CMTargetName;
  473. ppVars.CMTargetType = vars.CMTargetType;
  474. ppVars.Language = vars.Language;
  475. ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
  476. ppVars.PreprocessedSource = "$out";
  477. ppVars.DependencyFile = ppDepfile.c_str();
  478. // Preprocessing uses the original source,
  479. // compilation uses preprocessed output.
  480. ppVars.Source = vars.Source;
  481. vars.Source = "$in";
  482. // Preprocessing and compilation use the same flags.
  483. ppVars.Flags = vars.Flags;
  484. // Move preprocessor definitions to the preprocessor rule.
  485. ppVars.Defines = vars.Defines;
  486. 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. // Rule for preprocessing source file.
  491. std::vector<std::string> ppCmds;
  492. cmSystemTools::ExpandListArgument(ppCmd, ppCmds);
  493. for (std::string& i : ppCmds) {
  494. i = launcher + i;
  495. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  496. i, ppVars);
  497. }
  498. // Run CMake dependency scanner on preprocessed output.
  499. std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
  500. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  501. ppCmds.push_back(
  502. cmake + " -E cmake_ninja_depends"
  503. " --tdi=" +
  504. tdi + " --pp=$out"
  505. " --dep=$DEP_FILE" +
  506. (needDyndep ? " --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE" : ""));
  507. std::string const ppCmdLine =
  508. this->GetLocalGenerator()->BuildCommandLine(ppCmds);
  509. // Write the rule for preprocessing file of the given language.
  510. std::ostringstream ppComment;
  511. ppComment << "Rule for preprocessing " << lang << " files.";
  512. std::ostringstream ppDesc;
  513. ppDesc << "Building " << lang << " preprocessed $out";
  514. this->GetGlobalGenerator()->AddRule(this->LanguagePreprocessRule(lang),
  515. ppCmdLine, ppDesc.str(),
  516. ppComment.str(), ppDepfile, ppDeptype,
  517. /*rspfile*/ "",
  518. /*rspcontent*/ "",
  519. /*restat*/ "",
  520. /*generator*/ false);
  521. }
  522. if (needDyndep) {
  523. // Write the rule for ninja dyndep file generation.
  524. std::vector<std::string> ddCmds;
  525. // Command line length is almost always limited -> use response file for
  526. // dyndep rules
  527. std::string ddRspFile = "$out.rsp";
  528. std::string ddRspContent = "$in";
  529. std::string ddInput = "@" + ddRspFile;
  530. // Run CMake dependency scanner on preprocessed output.
  531. std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
  532. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  533. ddCmds.push_back(cmake + " -E cmake_ninja_dyndep"
  534. " --tdi=" +
  535. tdi + " --dd=$out"
  536. " " +
  537. ddInput);
  538. std::string const ddCmdLine =
  539. this->GetLocalGenerator()->BuildCommandLine(ddCmds);
  540. std::ostringstream ddComment;
  541. ddComment << "Rule to generate ninja dyndep files for " << lang << ".";
  542. std::ostringstream ddDesc;
  543. ddDesc << "Generating " << lang << " dyndep file $out";
  544. this->GetGlobalGenerator()->AddRule(
  545. this->LanguageDyndepRule(lang), ddCmdLine, ddDesc.str(), ddComment.str(),
  546. /*depfile*/ "",
  547. /*deps*/ "", ddRspFile, ddRspContent,
  548. /*restat*/ "",
  549. /*generator*/ false);
  550. }
  551. // Rule for compiling object file.
  552. std::vector<std::string> compileCmds;
  553. if (lang == "CUDA") {
  554. std::string cmdVar;
  555. if (this->GeneratorTarget->GetPropertyAsBool(
  556. "CUDA_SEPARABLE_COMPILATION")) {
  557. cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  558. } else if (this->GeneratorTarget->GetPropertyAsBool(
  559. "CUDA_PTX_COMPILATION")) {
  560. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  561. } else {
  562. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  563. }
  564. std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
  565. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  566. } else {
  567. const std::string cmdVar =
  568. std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
  569. std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
  570. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  571. }
  572. // Maybe insert an include-what-you-use runner.
  573. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
  574. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  575. const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  576. std::string const tidy_prop = lang + "_CLANG_TIDY";
  577. const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  578. std::string const cpplint_prop = lang + "_CPPLINT";
  579. const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  580. std::string const cppcheck_prop = lang + "_CPPCHECK";
  581. const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  582. if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
  583. (cppcheck && *cppcheck)) {
  584. std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat(
  585. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  586. run_iwyu += " -E __run_co_compile";
  587. if (iwyu && *iwyu) {
  588. run_iwyu += " --iwyu=";
  589. run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu);
  590. }
  591. if (tidy && *tidy) {
  592. run_iwyu += " --tidy=";
  593. run_iwyu += this->GetLocalGenerator()->EscapeForShell(tidy);
  594. }
  595. if (cpplint && *cpplint) {
  596. run_iwyu += " --cpplint=";
  597. run_iwyu += this->GetLocalGenerator()->EscapeForShell(cpplint);
  598. }
  599. if (cppcheck && *cppcheck) {
  600. run_iwyu += " --cppcheck=";
  601. run_iwyu += this->GetLocalGenerator()->EscapeForShell(cppcheck);
  602. }
  603. if ((tidy && *tidy) || (cpplint && *cpplint) ||
  604. (cppcheck && *cppcheck)) {
  605. run_iwyu += " --source=$in";
  606. }
  607. run_iwyu += " -- ";
  608. compileCmds.front().insert(0, run_iwyu);
  609. }
  610. }
  611. // Maybe insert a compiler launcher like ccache or distcc
  612. if (!compileCmds.empty() &&
  613. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA")) {
  614. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  615. const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  616. if (clauncher && *clauncher) {
  617. std::vector<std::string> launcher_cmd;
  618. cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true);
  619. for (std::string& i : launcher_cmd) {
  620. i = this->LocalGenerator->EscapeForShell(i);
  621. }
  622. std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " ";
  623. compileCmds.front().insert(0, run_launcher);
  624. }
  625. }
  626. if (!compileCmds.empty()) {
  627. compileCmds.front().insert(0, cldeps);
  628. }
  629. for (std::string& i : compileCmds) {
  630. i = launcher + i;
  631. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  632. vars);
  633. }
  634. std::string cmdLine =
  635. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  636. // Write the rule for compiling file of the given language.
  637. std::ostringstream comment;
  638. comment << "Rule for compiling " << lang << " files.";
  639. std::ostringstream description;
  640. description << "Building " << lang << " object $out";
  641. this->GetGlobalGenerator()->AddRule(
  642. this->LanguageCompilerRule(lang), cmdLine, description.str(),
  643. comment.str(), depfile, deptype, rspfile, rspcontent,
  644. /*restat*/ "",
  645. /*generator*/ false);
  646. }
  647. void cmNinjaTargetGenerator::WriteObjectBuildStatements()
  648. {
  649. // Write comments.
  650. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  651. this->GetBuildFileStream()
  652. << "# Object build statements for "
  653. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  654. << " target " << this->GetTargetName() << "\n\n";
  655. std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  656. std::vector<cmSourceFile const*> customCommands;
  657. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  658. for (cmSourceFile const* sf : customCommands) {
  659. cmCustomCommand const* cc = sf->GetCustomCommand();
  660. this->GetLocalGenerator()->AddCustomCommandTarget(
  661. cc, this->GetGeneratorTarget());
  662. // Record the custom commands for this target. The container is used
  663. // in WriteObjectBuildStatement when called in a loop below.
  664. this->CustomCommands.push_back(cc);
  665. }
  666. std::vector<cmSourceFile const*> headerSources;
  667. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  668. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  669. headerSources, this->MacOSXContentGenerator);
  670. std::vector<cmSourceFile const*> extraSources;
  671. this->GeneratorTarget->GetExtraSources(extraSources, config);
  672. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  673. extraSources, this->MacOSXContentGenerator);
  674. std::vector<cmSourceFile const*> externalObjects;
  675. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  676. for (cmSourceFile const* sf : externalObjects) {
  677. this->Objects.push_back(this->GetSourceFilePath(sf));
  678. }
  679. cmNinjaDeps orderOnlyDeps;
  680. this->GetLocalGenerator()->AppendTargetDepends(
  681. this->GeneratorTarget, orderOnlyDeps, DependOnTargetOrdering);
  682. // Add order-only dependencies on other files associated with the target.
  683. orderOnlyDeps.insert(orderOnlyDeps.end(), this->ExtraFiles.begin(),
  684. this->ExtraFiles.end());
  685. // Add order-only dependencies on custom command outputs.
  686. for (cmCustomCommand const* cc : this->CustomCommands) {
  687. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
  688. this->GetLocalGenerator());
  689. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  690. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  691. std::transform(ccoutputs.begin(), ccoutputs.end(),
  692. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  693. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  694. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  695. }
  696. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  697. orderOnlyDeps.erase(std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  698. orderOnlyDeps.end());
  699. {
  700. cmNinjaDeps orderOnlyTarget;
  701. orderOnlyTarget.push_back(this->OrderDependsTargetForTarget());
  702. this->GetGlobalGenerator()->WritePhonyBuild(
  703. this->GetBuildFileStream(),
  704. "Order-only phony target for " + this->GetTargetName(), orderOnlyTarget,
  705. cmNinjaDeps(), cmNinjaDeps(), orderOnlyDeps);
  706. }
  707. std::vector<cmSourceFile const*> objectSources;
  708. this->GeneratorTarget->GetObjectSources(objectSources, config);
  709. for (cmSourceFile const* sf : objectSources) {
  710. this->WriteObjectBuildStatement(sf);
  711. }
  712. if (!this->DDIFiles.empty()) {
  713. std::string const ddComment;
  714. std::string const ddRule = this->LanguageDyndepRule("Fortran");
  715. cmNinjaDeps ddOutputs;
  716. cmNinjaDeps ddImplicitOuts;
  717. cmNinjaDeps const& ddExplicitDeps = this->DDIFiles;
  718. cmNinjaDeps ddImplicitDeps;
  719. cmNinjaDeps ddOrderOnlyDeps;
  720. cmNinjaVars ddVars;
  721. this->WriteTargetDependInfo("Fortran");
  722. ddOutputs.push_back(this->GetDyndepFilePath("Fortran"));
  723. // Make sure dyndep files for all our dependencies have already
  724. // been generated so that the 'FortranModules.json' files they
  725. // produced as side-effects are available for us to read.
  726. // Ideally we should depend on the 'FortranModules.json' files
  727. // from our dependencies directly, but we don't know which of
  728. // our dependencies produces them. Fixing this will require
  729. // refactoring the Ninja generator to generate targets in
  730. // dependency order so that we can collect the needed information.
  731. this->GetLocalGenerator()->AppendTargetDepends(
  732. this->GeneratorTarget, ddOrderOnlyDeps, DependOnTargetArtifact);
  733. this->GetGlobalGenerator()->WriteBuild(
  734. this->GetBuildFileStream(), ddComment, ddRule, ddOutputs, ddImplicitOuts,
  735. ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
  736. }
  737. this->GetBuildFileStream() << "\n";
  738. }
  739. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  740. cmSourceFile const* source)
  741. {
  742. std::string const language = source->GetLanguage();
  743. std::string const sourceFileName =
  744. language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
  745. std::string const objectDir =
  746. this->ConvertToNinjaPath(this->GeneratorTarget->GetSupportDirectory());
  747. std::string const objectFileName =
  748. this->ConvertToNinjaPath(this->GetObjectFilePath(source));
  749. std::string const objectFileDir =
  750. cmSystemTools::GetFilenamePath(objectFileName);
  751. cmNinjaVars vars;
  752. vars["FLAGS"] = this->ComputeFlagsForObject(source, language);
  753. vars["DEFINES"] = this->ComputeDefines(source, language);
  754. vars["INCLUDES"] = this->ComputeIncludes(source, language);
  755. if (!this->NeedDepTypeMSVC(language)) {
  756. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  757. objectFileName + ".d", cmOutputConverter::SHELL);
  758. }
  759. this->ExportObjectCompileCommand(
  760. language, sourceFileName, objectDir, objectFileName, objectFileDir,
  761. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"]);
  762. std::string comment;
  763. std::string rule = this->LanguageCompilerRule(language);
  764. cmNinjaDeps outputs;
  765. outputs.push_back(objectFileName);
  766. // Add this object to the list of object files.
  767. this->Objects.push_back(objectFileName);
  768. cmNinjaDeps explicitDeps;
  769. explicitDeps.push_back(sourceFileName);
  770. cmNinjaDeps implicitDeps;
  771. if (const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  772. std::vector<std::string> depList;
  773. cmSystemTools::ExpandListArgument(objectDeps, depList);
  774. for (std::string& odi : depList) {
  775. if (cmSystemTools::FileIsFullPath(odi)) {
  776. odi = cmSystemTools::CollapseFullPath(odi);
  777. }
  778. }
  779. std::transform(depList.begin(), depList.end(),
  780. std::back_inserter(implicitDeps), MapToNinjaPath());
  781. }
  782. cmNinjaDeps orderOnlyDeps;
  783. orderOnlyDeps.push_back(this->OrderDependsTargetForTarget());
  784. // If the source file is GENERATED and does not have a custom command
  785. // (either attached to this source file or another one), assume that one of
  786. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  787. // will rebuild the file.
  788. if (source->GetPropertyAsBool("GENERATED") && !source->GetCustomCommand() &&
  789. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFileName)) {
  790. this->GetGlobalGenerator()->AddAssumedSourceDependencies(sourceFileName,
  791. orderOnlyDeps);
  792. }
  793. // For some cases we need to generate a ninja dyndep file.
  794. bool const needDyndep = this->NeedDyndep(language);
  795. // For some cases we do an explicit preprocessor invocation.
  796. bool const explicitPP = this->NeedExplicitPreprocessing(language);
  797. if (explicitPP) {
  798. std::string const ppComment;
  799. std::string const ppRule = this->LanguagePreprocessRule(language);
  800. cmNinjaDeps ppOutputs;
  801. cmNinjaDeps ppImplicitOuts;
  802. cmNinjaDeps ppExplicitDeps;
  803. cmNinjaDeps ppImplicitDeps;
  804. cmNinjaDeps ppOrderOnlyDeps;
  805. cmNinjaVars ppVars;
  806. std::string const ppFileName =
  807. this->ConvertToNinjaPath(this->GetPreprocessedFilePath(source));
  808. ppOutputs.push_back(ppFileName);
  809. // Move compilation dependencies to the preprocessing build statement.
  810. std::swap(ppExplicitDeps, explicitDeps);
  811. std::swap(ppImplicitDeps, implicitDeps);
  812. std::swap(ppOrderOnlyDeps, orderOnlyDeps);
  813. std::swap(ppVars["IN_ABS"], vars["IN_ABS"]);
  814. // The actual compilation will now use the preprocessed source.
  815. explicitDeps.push_back(ppFileName);
  816. // Preprocessing and compilation generally use the same flags.
  817. ppVars["FLAGS"] = vars["FLAGS"];
  818. // In case compilation requires flags that are incompatible with
  819. // preprocessing, include them here.
  820. std::string const postFlag =
  821. this->Makefile->GetSafeDefinition("CMAKE_Fortran_POSTPROCESS_FLAG");
  822. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  823. // Move preprocessor definitions to the preprocessor build statement.
  824. std::swap(ppVars["DEFINES"], vars["DEFINES"]);
  825. // Copy include directories to the preprocessor build statement. The
  826. // Fortran compilation build statement still needs them for the INCLUDE
  827. // directive.
  828. ppVars["INCLUDES"] = vars["INCLUDES"];
  829. // Prepend source file's original directory as an include directory
  830. // so e.g. Fortran INCLUDE statements can look for files in it.
  831. std::vector<std::string> sourceDirectory;
  832. sourceDirectory.push_back(
  833. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  834. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  835. sourceDirectory, this->GeneratorTarget, language, false, false,
  836. this->GetConfigName());
  837. vars["INCLUDES"] = sourceDirectoryFlag + " " + vars["INCLUDES"];
  838. // Explicit preprocessing always uses a depfile.
  839. ppVars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  840. ppFileName + ".d", cmOutputConverter::SHELL);
  841. // The actual compilation does not need a depfile because it
  842. // depends on the already-preprocessed source.
  843. vars.erase("DEP_FILE");
  844. if (needDyndep) {
  845. // Tell dependency scanner the object file that will result from
  846. // compiling the preprocessed source.
  847. ppVars["OBJ_FILE"] = objectFileName;
  848. // Tell dependency scanner where to store dyndep intermediate results.
  849. std::string const ddiFile = ppFileName + ".ddi";
  850. ppVars["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  851. ppImplicitOuts.push_back(ddiFile);
  852. this->DDIFiles.push_back(ddiFile);
  853. }
  854. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  855. ppVars);
  856. this->GetGlobalGenerator()->WriteBuild(
  857. this->GetBuildFileStream(), ppComment, ppRule, ppOutputs, ppImplicitOuts,
  858. ppExplicitDeps, ppImplicitDeps, ppOrderOnlyDeps, ppVars);
  859. }
  860. if (needDyndep) {
  861. std::string const dyndep = this->GetDyndepFilePath(language);
  862. orderOnlyDeps.push_back(dyndep);
  863. vars["dyndep"] = dyndep;
  864. }
  865. EnsureParentDirectoryExists(objectFileName);
  866. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  867. objectDir, cmOutputConverter::SHELL);
  868. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  869. objectFileDir, cmOutputConverter::SHELL);
  870. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  871. vars);
  872. this->SetMsvcTargetPdbVariable(vars);
  873. bool const lang_supports_response =
  874. !(language == "RC" || language == "CUDA");
  875. int const commandLineLengthLimit =
  876. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  877. std::string const rspfile = objectFileName + ".rsp";
  878. this->GetGlobalGenerator()->WriteBuild(
  879. this->GetBuildFileStream(), comment, rule, outputs,
  880. /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps, orderOnlyDeps,
  881. vars, rspfile, commandLineLengthLimit);
  882. if (const char* objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  883. std::vector<std::string> outputList;
  884. cmSystemTools::ExpandListArgument(objectOutputs, outputList);
  885. std::transform(outputList.begin(), outputList.end(), outputList.begin(),
  886. MapToNinjaPath());
  887. this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
  888. "Additional output files.",
  889. outputList, outputs);
  890. }
  891. }
  892. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang)
  893. {
  894. Json::Value tdi(Json::objectValue);
  895. tdi["language"] = lang;
  896. tdi["compiler-id"] =
  897. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID");
  898. if (lang == "Fortran") {
  899. std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  900. this->Makefile->GetHomeOutputDirectory());
  901. if (mod_dir.empty()) {
  902. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  903. }
  904. tdi["module-dir"] = mod_dir;
  905. }
  906. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  907. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  908. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  909. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  910. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  911. std::vector<std::string> includes;
  912. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  913. lang, this->GetConfigName());
  914. for (std::string const& i : includes) {
  915. // Convert the include directories the same way we do for -I flags.
  916. // See upstream ninja issue 1251.
  917. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  918. }
  919. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  920. Json::arrayValue;
  921. std::vector<std::string> linked = this->GetLinkedTargetDirectories();
  922. for (std::string const& l : linked) {
  923. tdi_linked_target_dirs.append(l);
  924. }
  925. std::string const tdin = this->GetTargetDependInfoPath(lang);
  926. cmGeneratedFileStream tdif(tdin.c_str());
  927. tdif << tdi;
  928. }
  929. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  930. std::string const& language, std::string const& sourceFileName,
  931. std::string const& objectDir, std::string const& objectFileName,
  932. std::string const& objectFileDir, std::string const& flags,
  933. std::string const& defines, std::string const& includes)
  934. {
  935. if (!this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS")) {
  936. return;
  937. }
  938. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  939. compileObjectVars.Language = language.c_str();
  940. std::string escapedSourceFileName = sourceFileName;
  941. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  942. escapedSourceFileName = cmSystemTools::CollapseFullPath(
  943. escapedSourceFileName, this->GetGlobalGenerator()
  944. ->GetCMakeInstance()
  945. ->GetHomeOutputDirectory());
  946. }
  947. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  948. escapedSourceFileName, cmOutputConverter::SHELL);
  949. compileObjectVars.Source = escapedSourceFileName.c_str();
  950. compileObjectVars.Object = objectFileName.c_str();
  951. compileObjectVars.ObjectDir = objectDir.c_str();
  952. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  953. compileObjectVars.Flags = flags.c_str();
  954. compileObjectVars.Defines = defines.c_str();
  955. compileObjectVars.Includes = includes.c_str();
  956. // Rule for compiling object file.
  957. std::vector<std::string> compileCmds;
  958. if (language == "CUDA") {
  959. std::string cmdVar;
  960. if (this->GeneratorTarget->GetPropertyAsBool(
  961. "CUDA_SEPARABLE_COMPILATION")) {
  962. cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  963. } else if (this->GeneratorTarget->GetPropertyAsBool(
  964. "CUDA_PTX_COMPILATION")) {
  965. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  966. } else {
  967. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  968. }
  969. std::string compileCmd =
  970. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  971. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  972. } else {
  973. const std::string cmdVar =
  974. std::string("CMAKE_") + language + "_COMPILE_OBJECT";
  975. std::string compileCmd =
  976. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  977. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  978. }
  979. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  980. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  981. for (std::string& i : compileCmds) {
  982. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  983. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  984. compileObjectVars);
  985. }
  986. std::string cmdLine =
  987. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  988. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  989. }
  990. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  991. const std::string& path) const
  992. {
  993. if (cmSystemTools::FileIsFullPath(path)) {
  994. cmSystemTools::MakeDirectory(path);
  995. } else {
  996. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  997. std::string fullPath =
  998. std::string(gg->GetCMakeInstance()->GetHomeOutputDirectory());
  999. // Also ensures their is a trailing slash.
  1000. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1001. fullPath += path;
  1002. cmSystemTools::MakeDirectory(fullPath);
  1003. }
  1004. }
  1005. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1006. const std::string& path) const
  1007. {
  1008. EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1009. }
  1010. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1011. cmSourceFile const& source, const char* pkgloc)
  1012. {
  1013. // Skip OS X content when not building a Framework or Bundle.
  1014. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1015. return;
  1016. }
  1017. std::string macdir =
  1018. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc);
  1019. // Get the input file location.
  1020. std::string input = source.GetFullPath();
  1021. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1022. // Get the output file location.
  1023. std::string output = macdir;
  1024. output += "/";
  1025. output += cmSystemTools::GetFilenameName(input);
  1026. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1027. // Write a build statement to copy the content into the bundle.
  1028. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(input,
  1029. output);
  1030. // Add as a dependency to the target so that it gets called.
  1031. this->Generator->ExtraFiles.push_back(std::move(output));
  1032. }
  1033. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1034. const std::string& pool_property, cmGeneratorTarget* target,
  1035. cmNinjaVars& vars)
  1036. {
  1037. const char* pool = target->GetProperty(pool_property);
  1038. if (pool) {
  1039. vars["pool"] = pool;
  1040. }
  1041. }
  1042. bool cmNinjaTargetGenerator::ForceResponseFile()
  1043. {
  1044. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1045. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1046. cmSystemTools::HasEnv(forceRspFile));
  1047. }