cmNinjaTargetGenerator.cxx 72 KB

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