cmNinjaTargetGenerator.cxx 55 KB

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