cmNinjaTargetGenerator.cxx 70 KB

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