cmNinjaTargetGenerator.cxx 79 KB

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