cmNinjaTargetGenerator.cxx 50 KB

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