cmNinjaTargetGenerator.cxx 72 KB

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