cmNinjaTargetGenerator.cxx 43 KB

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