cmNinjaTargetGenerator.cxx 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmNinjaTargetGenerator.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <functional>
  8. #include <iterator>
  9. #include <map>
  10. #include <ostream>
  11. #include <unordered_map>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/string_view>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include <cm3p/json/value.h>
  20. #include <cm3p/json/writer.h>
  21. #include "cmBuildDatabase.h"
  22. #include "cmComputeLinkInformation.h"
  23. #include "cmCustomCommandGenerator.h"
  24. #include "cmDyndepCollation.h"
  25. #include "cmFileSet.h"
  26. #include "cmGeneratedFileStream.h"
  27. #include "cmGeneratorExpression.h"
  28. #include "cmGeneratorTarget.h"
  29. #include "cmGlobalCommonGenerator.h"
  30. #include "cmGlobalNinjaGenerator.h"
  31. #include "cmList.h"
  32. #include "cmListFileCache.h"
  33. #include "cmLocalGenerator.h"
  34. #include "cmLocalNinjaGenerator.h"
  35. #include "cmMakefile.h"
  36. #include "cmMessageType.h"
  37. #include "cmNinjaNormalTargetGenerator.h"
  38. #include "cmNinjaUtilityTargetGenerator.h"
  39. #include "cmOutputConverter.h"
  40. #include "cmPolicies.h"
  41. #include "cmRange.h"
  42. #include "cmRulePlaceholderExpander.h"
  43. #include "cmSourceFile.h"
  44. #include "cmState.h"
  45. #include "cmStateTypes.h"
  46. #include "cmStringAlgorithms.h"
  47. #include "cmSystemTools.h"
  48. #include "cmTarget.h"
  49. #include "cmTargetDepend.h"
  50. #include "cmValue.h"
  51. #include "cmake.h"
  52. class cmCustomCommand;
  53. std::unique_ptr<cmNinjaTargetGenerator> cmNinjaTargetGenerator::New(
  54. cmGeneratorTarget* target)
  55. {
  56. switch (target->GetType()) {
  57. case cmStateEnums::EXECUTABLE:
  58. case cmStateEnums::SHARED_LIBRARY:
  59. case cmStateEnums::STATIC_LIBRARY:
  60. case cmStateEnums::MODULE_LIBRARY:
  61. case cmStateEnums::OBJECT_LIBRARY:
  62. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  63. case cmStateEnums::INTERFACE_LIBRARY:
  64. if (target->HaveCxx20ModuleSources()) {
  65. return cm::make_unique<cmNinjaNormalTargetGenerator>(target);
  66. }
  67. CM_FALLTHROUGH;
  68. case cmStateEnums::UTILITY:
  69. case cmStateEnums::GLOBAL_TARGET:
  70. return cm::make_unique<cmNinjaUtilityTargetGenerator>(target);
  71. default:
  72. return std::unique_ptr<cmNinjaTargetGenerator>();
  73. }
  74. }
  75. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  76. : cmCommonTargetGenerator(target)
  77. , OSXBundleGenerator(nullptr)
  78. , LocalGenerator(
  79. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  80. {
  81. for (auto const& fileConfig : this->LocalGenerator->GetConfigNames()) {
  82. this->Configs[fileConfig].MacOSXContentGenerator =
  83. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  84. }
  85. }
  86. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  87. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  88. const std::string& config) const
  89. {
  90. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  91. }
  92. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  93. {
  94. return *this->GetGlobalGenerator()->GetCommonFileStream();
  95. }
  96. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  97. {
  98. return *this->GetGlobalGenerator()->GetRulesFileStream();
  99. }
  100. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  101. {
  102. return this->LocalGenerator->GetGlobalNinjaGenerator();
  103. }
  104. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  105. const std::string& lang, const std::string& config,
  106. WithScanning withScanning) const
  107. {
  108. return cmStrCat(
  109. lang, "_COMPILER__",
  110. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  111. withScanning == WithScanning::Yes ? "_scanned_" : "_unscanned_", config);
  112. }
  113. std::string cmNinjaTargetGenerator::LanguagePreprocessAndScanRule(
  114. std::string const& lang, const std::string& config) const
  115. {
  116. return cmStrCat(
  117. lang, "_PREPROCESS_SCAN__",
  118. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  119. '_', config);
  120. }
  121. std::string cmNinjaTargetGenerator::LanguageScanRule(
  122. std::string const& lang, const std::string& config) const
  123. {
  124. return cmStrCat(
  125. lang, "_SCAN__",
  126. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  127. '_', config);
  128. }
  129. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  130. std::string const& lang) const
  131. {
  132. return lang == "Fortran" || lang == "Swift";
  133. }
  134. bool cmNinjaTargetGenerator::CompileWithDefines(std::string const& lang) const
  135. {
  136. return this->Makefile->IsOn(
  137. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  138. }
  139. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  140. const std::string& lang, const std::string& config) const
  141. {
  142. return cmStrCat(
  143. lang, "_DYNDEP__",
  144. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  145. '_', config);
  146. }
  147. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  148. const std::string& config)
  149. {
  150. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  151. this->GeneratorTarget, config);
  152. }
  153. std::string cmNinjaTargetGenerator::OrderDependsTargetForTargetPrivate(
  154. const std::string& config)
  155. {
  156. return this->GetGlobalGenerator()->OrderDependsTargetForTargetPrivate(
  157. this->GeneratorTarget, config);
  158. }
  159. // TODO: Most of the code is picked up from
  160. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  161. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  162. // Refactor it.
  163. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  164. cmSourceFile const* source, const std::string& language,
  165. const std::string& config, const std::string& objectFileName)
  166. {
  167. std::unordered_map<std::string, std::string> pchSources;
  168. std::vector<std::string> pchArchs =
  169. this->GeneratorTarget->GetPchArchs(config, language);
  170. std::string filterArch;
  171. for (const std::string& arch : pchArchs) {
  172. const std::string pchSource =
  173. this->GeneratorTarget->GetPchSource(config, language, arch);
  174. if (pchSource == source->GetFullPath()) {
  175. filterArch = arch;
  176. }
  177. if (!pchSource.empty()) {
  178. pchSources.insert(std::make_pair(pchSource, arch));
  179. }
  180. }
  181. std::string flags;
  182. // Explicitly add the explicit language flag before any other flag
  183. // so user flags can override it.
  184. this->GeneratorTarget->AddExplicitLanguageFlags(flags, *source);
  185. if (!flags.empty()) {
  186. flags += " ";
  187. }
  188. flags += this->GetFlags(language, config, filterArch);
  189. // Add Fortran format flags.
  190. if (language == "Fortran") {
  191. this->AppendFortranFormatFlags(flags, *source);
  192. this->AppendFortranPreprocessFlags(flags, *source,
  193. PreprocessFlagsRequired::NO);
  194. }
  195. // Add source file specific flags.
  196. cmGeneratorExpressionInterpreter genexInterpreter(
  197. this->LocalGenerator, config, this->GeneratorTarget, language);
  198. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  199. if (cmValue cflags = source->GetProperty(COMPILE_FLAGS)) {
  200. this->LocalGenerator->AppendFlags(
  201. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  202. }
  203. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  204. if (cmValue coptions = source->GetProperty(COMPILE_OPTIONS)) {
  205. this->LocalGenerator->AppendCompileOptions(
  206. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  207. }
  208. // Add precompile headers compile options.
  209. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  210. std::string pchOptions;
  211. auto pchIt = pchSources.find(source->GetFullPath());
  212. if (pchIt != pchSources.end()) {
  213. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  214. config, language, pchIt->second);
  215. } else {
  216. pchOptions =
  217. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  218. }
  219. this->LocalGenerator->AppendCompileOptions(
  220. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  221. }
  222. auto const* fs = this->GeneratorTarget->GetFileSetForSource(config, source);
  223. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  224. if (source->GetLanguage() != "CXX"_s) {
  225. this->GetMakefile()->IssueMessage(
  226. MessageType::FATAL_ERROR,
  227. cmStrCat("Target \"", this->GeneratorTarget->Target->GetName(),
  228. "\" contains the source\n ", source->GetFullPath(),
  229. "\nin a file set of type \"", fs->GetType(),
  230. R"(" but the source is not classified as a "CXX" source.)"));
  231. }
  232. if (!this->GeneratorTarget->Target->IsNormal()) {
  233. auto flag = this->GetMakefile()->GetSafeDefinition(
  234. "CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  235. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  236. compileObjectVars.Object = objectFileName.c_str();
  237. auto rulePlaceholderExpander =
  238. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  239. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  240. flag, compileObjectVars);
  241. this->LocalGenerator->AppendCompileOptions(flags, flag);
  242. }
  243. }
  244. return flags;
  245. }
  246. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  247. std::string const& language,
  248. const std::string& config)
  249. {
  250. std::vector<std::string> includes;
  251. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  252. language, config);
  253. // Add include directory flags.
  254. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  255. includes, this->GeneratorTarget, language, config, false);
  256. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  257. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  258. }
  259. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  260. }
  261. // TODO: Refactor with
  262. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  263. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  264. const std::string& language,
  265. const std::string& config)
  266. {
  267. std::set<std::string> defines;
  268. cmGeneratorExpressionInterpreter genexInterpreter(
  269. this->LocalGenerator, config, this->GeneratorTarget, language);
  270. // Seriously??
  271. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  272. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  273. }
  274. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  275. if (cmValue compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  276. this->LocalGenerator->AppendDefines(
  277. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  278. }
  279. std::string defPropName =
  280. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  281. if (cmValue config_compile_defs = source->GetProperty(defPropName)) {
  282. this->LocalGenerator->AppendDefines(
  283. defines,
  284. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  285. }
  286. std::string definesString = this->GetDefines(language, config);
  287. this->LocalGenerator->JoinDefines(defines, definesString, language);
  288. return definesString;
  289. }
  290. std::string cmNinjaTargetGenerator::ComputeIncludes(
  291. cmSourceFile const* source, const std::string& language,
  292. const std::string& config)
  293. {
  294. std::vector<std::string> includes;
  295. cmGeneratorExpressionInterpreter genexInterpreter(
  296. this->LocalGenerator, config, this->GeneratorTarget, language);
  297. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  298. if (cmValue cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  299. this->LocalGenerator->AppendIncludeDirectories(
  300. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  301. *source);
  302. }
  303. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  304. includes, this->GeneratorTarget, language, config, false);
  305. this->LocalGenerator->AppendFlags(includesString,
  306. this->GetIncludes(language, config));
  307. return includesString;
  308. }
  309. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  310. const std::string& linkLanguage, const std::string& config,
  311. bool ignoreType) const
  312. {
  313. // Static libraries never depend on other targets for linking.
  314. if (!ignoreType &&
  315. (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  316. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
  317. return cmNinjaDeps();
  318. }
  319. cmComputeLinkInformation* cli =
  320. this->GeneratorTarget->GetLinkInformation(config);
  321. if (!cli) {
  322. return cmNinjaDeps();
  323. }
  324. const std::vector<std::string>& deps = cli->GetDepends();
  325. cmNinjaDeps result(deps.size());
  326. std::transform(deps.begin(), deps.end(), result.begin(),
  327. this->MapToNinjaPath());
  328. // Add a dependency on the link definitions file, if any.
  329. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  330. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  331. for (cmSourceFile const* src : mdi->Sources) {
  332. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  333. }
  334. }
  335. // Add a dependency on user-specified manifest files, if any.
  336. std::vector<cmSourceFile const*> manifest_srcs;
  337. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  338. for (cmSourceFile const* manifest_src : manifest_srcs) {
  339. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  340. }
  341. // Add user-specified dependencies.
  342. std::vector<std::string> linkDeps;
  343. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  344. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  345. this->MapToNinjaPath());
  346. return result;
  347. }
  348. std::string cmNinjaTargetGenerator::GetCompiledSourceNinjaPath(
  349. cmSourceFile const* source) const
  350. {
  351. // Pass source files to the compiler by absolute path.
  352. return this->ConvertToNinjaAbsPath(source->GetFullPath());
  353. }
  354. std::string cmNinjaTargetGenerator::GetObjectFileDir(
  355. const std::string& config) const
  356. {
  357. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  358. if (!path.empty()) {
  359. path += '/';
  360. }
  361. path +=
  362. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  363. this->GetGlobalGenerator()->ConfigDirectory(config));
  364. return path;
  365. }
  366. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  367. cmSourceFile const* source, const std::string& config) const
  368. {
  369. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  370. return cmStrCat(this->GetObjectFileDir(config), '/', objectName);
  371. }
  372. std::string cmNinjaTargetGenerator::GetBmiFilePath(
  373. cmSourceFile const* source, const std::string& config) const
  374. {
  375. auto& importedConfigInfo = this->Configs.at(config).ImportedCxxModules;
  376. if (!importedConfigInfo.Initialized()) {
  377. std::string configUpper = cmSystemTools::UpperCase(config);
  378. std::string propName = cmStrCat("IMPORTED_CXX_MODULES_", configUpper);
  379. auto value = this->GeneratorTarget->GetSafeProperty(propName);
  380. importedConfigInfo.Initialize(value);
  381. }
  382. std::string bmiName =
  383. importedConfigInfo.BmiNameForSource(source->GetFullPath());
  384. return cmStrCat(this->GetObjectFileDir(config), '/', bmiName);
  385. }
  386. std::string cmNinjaTargetGenerator::GetClangTidyReplacementsFilePath(
  387. std::string const& directory, cmSourceFile const& source,
  388. std::string const& config) const
  389. {
  390. auto path = this->LocalGenerator->GetHomeRelativeOutputPath();
  391. if (!path.empty()) {
  392. path += '/';
  393. }
  394. path = cmStrCat(directory, '/', path);
  395. auto const& objectName = this->GeneratorTarget->GetObjectName(&source);
  396. path =
  397. cmStrCat(std::move(path),
  398. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  399. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  400. objectName, ".yaml");
  401. return path;
  402. }
  403. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  404. cmSourceFile const* source, const std::string& config) const
  405. {
  406. // Choose an extension to compile already-preprocessed source.
  407. std::string ppExt = source->GetExtension();
  408. if (cmHasLiteralPrefix(ppExt, "F")) {
  409. // Some Fortran compilers automatically enable preprocessing for
  410. // upper-case extensions. Since the source is already preprocessed,
  411. // use a lower-case extension.
  412. ppExt = cmSystemTools::LowerCase(ppExt);
  413. }
  414. if (ppExt == "fpp") {
  415. // Some Fortran compilers automatically enable preprocessing for
  416. // the ".fpp" extension. Since the source is already preprocessed,
  417. // use the ".f" extension.
  418. ppExt = "f";
  419. }
  420. // Take the object file name and replace the extension.
  421. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  422. std::string const& objExt =
  423. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  424. assert(objName.size() >= objExt.size());
  425. std::string const ppName =
  426. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  427. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  428. if (!path.empty()) {
  429. path += '/';
  430. }
  431. path +=
  432. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  433. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  434. return path;
  435. }
  436. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  437. std::string const& lang, const std::string& config) const
  438. {
  439. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  440. if (!path.empty()) {
  441. path += '/';
  442. }
  443. path += cmStrCat(
  444. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  445. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  446. return path;
  447. }
  448. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  449. std::string const& lang, const std::string& config) const
  450. {
  451. std::string path =
  452. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  453. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  454. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  455. "DependInfo.json");
  456. return path;
  457. }
  458. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  459. const std::string& config) const
  460. {
  461. std::string dir = this->GeneratorTarget->GetDirectory(config);
  462. return this->ConvertToNinjaPath(dir);
  463. }
  464. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  465. const std::string& name, const std::string& config) const
  466. {
  467. std::string path = this->GetTargetOutputDir(config);
  468. if (path.empty() || path == ".") {
  469. return name;
  470. }
  471. path += cmStrCat('/', name);
  472. return path;
  473. }
  474. std::string cmNinjaTargetGenerator::GetTargetName() const
  475. {
  476. return this->GeneratorTarget->GetName();
  477. }
  478. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  479. cmNinjaVars& vars, const std::string& config) const
  480. {
  481. cmMakefile* mf = this->GetMakefile();
  482. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  483. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  484. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  485. std::string pdbPath;
  486. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  487. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  488. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  489. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  490. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  491. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  492. this->GeneratorTarget->GetPDBName(config));
  493. }
  494. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  495. this->ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  496. vars["TARGET_COMPILE_PDB"] =
  497. this->GetLocalGenerator()->ConvertToOutputFormat(
  498. this->ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  499. this->EnsureParentDirectoryExists(pdbPath);
  500. this->EnsureParentDirectoryExists(compilePdbPath);
  501. return true;
  502. }
  503. return false;
  504. }
  505. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  506. const std::string& config)
  507. {
  508. #ifdef NINJA_GEN_VERBOSE_FILES
  509. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  510. #endif
  511. this->WriteCompileRule(language, config);
  512. }
  513. namespace {
  514. // Create the command to run the dependency scanner
  515. std::string GetScanCommand(
  516. cm::string_view cmakeCmd, cm::string_view tdi, cm::string_view lang,
  517. cm::string_view srcFile, cm::string_view ddiFile,
  518. cm::optional<cm::string_view> srcOrigFile = cm::nullopt)
  519. {
  520. return cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi,
  521. " --lang=", lang, " --src=", srcFile, " --out=$out",
  522. " --dep=$DEP_FILE --obj=$OBJ_FILE --ddi=", ddiFile,
  523. srcOrigFile ? cmStrCat(" --src-orig=", *srcOrigFile) : "");
  524. }
  525. // Helper function to create dependency scanning rule that may or may
  526. // not perform explicit preprocessing too.
  527. cmNinjaRule GetScanRule(
  528. std::string const& ruleName, std::string const& ppFileName,
  529. std::string const& deptype,
  530. cmRulePlaceholderExpander::RuleVariables const& vars,
  531. const std::string& responseFlag, const std::string& flags,
  532. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  533. cmLocalNinjaGenerator* generator, std::vector<std::string> scanCmds,
  534. const std::string& outputConfig)
  535. {
  536. cmNinjaRule rule(ruleName);
  537. // Scanning always uses a depfile for preprocessor dependencies.
  538. if (deptype == "msvc"_s) {
  539. rule.DepType = deptype;
  540. rule.DepFile.clear();
  541. } else {
  542. rule.DepType.clear(); // no deps= for multiple outputs
  543. rule.DepFile = "$DEP_FILE";
  544. }
  545. cmRulePlaceholderExpander::RuleVariables scanVars;
  546. scanVars.CMTargetName = vars.CMTargetName;
  547. scanVars.CMTargetType = vars.CMTargetType;
  548. scanVars.Language = vars.Language;
  549. scanVars.Object = "$OBJ_FILE";
  550. scanVars.PreprocessedSource = ppFileName.c_str();
  551. scanVars.DynDepFile = "$DYNDEP_INTERMEDIATE_FILE";
  552. scanVars.DependencyFile = rule.DepFile.c_str();
  553. scanVars.DependencyTarget = "$out";
  554. // Scanning needs the same preprocessor settings as direct compilation would.
  555. scanVars.Source = vars.Source;
  556. scanVars.Defines = vars.Defines;
  557. scanVars.Includes = vars.Includes;
  558. // Scanning needs the compilation flags too.
  559. std::string scanFlags = flags;
  560. // If using a response file, move defines, includes, and flags into it.
  561. if (!responseFlag.empty()) {
  562. rule.RspFile = "$RSP_FILE";
  563. rule.RspContent =
  564. cmStrCat(' ', scanVars.Defines, ' ', scanVars.Includes, ' ', scanFlags);
  565. scanFlags = cmStrCat(responseFlag, rule.RspFile);
  566. scanVars.Defines = "";
  567. scanVars.Includes = "";
  568. }
  569. scanVars.Flags = scanFlags.c_str();
  570. // Rule for scanning a source file.
  571. for (std::string& scanCmd : scanCmds) {
  572. rulePlaceholderExpander->ExpandRuleVariables(generator, scanCmd, scanVars);
  573. }
  574. rule.Command =
  575. generator->BuildCommandLine(scanCmds, outputConfig, outputConfig);
  576. return rule;
  577. }
  578. }
  579. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  580. const std::string& config)
  581. {
  582. // For some cases we scan to dynamically discover dependencies.
  583. bool const needDyndep = this->GetGeneratorTarget()->NeedDyndep(lang, config);
  584. if (needDyndep) {
  585. this->WriteCompileRule(lang, config, WithScanning::Yes);
  586. }
  587. this->WriteCompileRule(lang, config, WithScanning::No);
  588. }
  589. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  590. const std::string& config,
  591. WithScanning withScanning)
  592. {
  593. cmRulePlaceholderExpander::RuleVariables vars;
  594. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  595. vars.CMTargetType =
  596. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  597. vars.Language = lang.c_str();
  598. vars.Source = "$in";
  599. vars.Object = "$out";
  600. vars.Defines = "$DEFINES";
  601. vars.Includes = "$INCLUDES";
  602. vars.TargetPDB = "$TARGET_PDB";
  603. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  604. vars.ObjectDir = "$OBJECT_DIR";
  605. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  606. vars.CudaCompileMode = "$CUDA_COMPILE_MODE";
  607. vars.ISPCHeader = "$ISPC_HEADER_FILE";
  608. cmMakefile* mf = this->GetMakefile();
  609. // For some cases we scan to dynamically discover dependencies.
  610. bool const compilationPreprocesses = !this->NeedExplicitPreprocessing(lang);
  611. std::string flags = "$FLAGS";
  612. std::string responseFlag;
  613. bool const lang_supports_response = lang != "RC";
  614. if (lang_supports_response && this->ForceResponseFile()) {
  615. std::string const responseFlagVar =
  616. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  617. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  618. if (responseFlag.empty() && lang != "CUDA") {
  619. responseFlag = "@";
  620. }
  621. }
  622. std::string const modmapFormatVar =
  623. cmStrCat("CMAKE_", lang, "_MODULE_MAP_FORMAT");
  624. std::string const modmapFormat =
  625. this->Makefile->GetSafeDefinition(modmapFormatVar);
  626. auto rulePlaceholderExpander =
  627. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  628. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  629. this->ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  630. cmLocalGenerator::SHELL);
  631. std::string launcher;
  632. std::string val = this->GetLocalGenerator()->GetRuleLauncher(
  633. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE", config);
  634. if (cmNonempty(val)) {
  635. launcher = cmStrCat(val, ' ');
  636. }
  637. std::string const cmakeCmd =
  638. this->GetLocalGenerator()->ConvertToOutputFormat(
  639. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  640. if (withScanning == WithScanning::Yes) {
  641. const auto& scanDepType = this->GetMakefile()->GetSafeDefinition(
  642. cmStrCat("CMAKE_", lang, "_SCANDEP_DEPFILE_FORMAT"));
  643. // Rule to scan dependencies of sources that need preprocessing.
  644. {
  645. cmList scanCommands;
  646. std::string scanRuleName;
  647. std::string ppFileName;
  648. if (compilationPreprocesses) {
  649. scanRuleName = this->LanguageScanRule(lang, config);
  650. ppFileName = "$PREPROCESSED_OUTPUT_FILE";
  651. std::string const& scanCommand = mf->GetRequiredDefinition(
  652. cmStrCat("CMAKE_", lang, "_SCANDEP_SOURCE"));
  653. scanCommands.assign(scanCommand);
  654. for (auto& i : scanCommands) {
  655. i = cmStrCat(launcher, i);
  656. }
  657. } else {
  658. scanRuleName = this->LanguagePreprocessAndScanRule(lang, config);
  659. ppFileName = "$out";
  660. std::string const& ppCommmand = mf->GetRequiredDefinition(
  661. cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE"));
  662. scanCommands.assign(ppCommmand);
  663. for (auto& i : scanCommands) {
  664. i = cmStrCat(launcher, i);
  665. }
  666. scanCommands.emplace_back(GetScanCommand(
  667. cmakeCmd, tdi, lang, "$out", "$DYNDEP_INTERMEDIATE_FILE", "$in"));
  668. }
  669. auto scanRule = GetScanRule(
  670. scanRuleName, ppFileName, scanDepType, vars, responseFlag, flags,
  671. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  672. std::move(scanCommands), config);
  673. scanRule.Comment =
  674. cmStrCat("Rule for generating ", lang, " dependencies.");
  675. if (compilationPreprocesses) {
  676. scanRule.Description =
  677. cmStrCat("Scanning $in for ", lang, " dependencies");
  678. } else {
  679. scanRule.Description =
  680. cmStrCat("Building ", lang, " preprocessed $out");
  681. }
  682. this->GetGlobalGenerator()->AddRule(scanRule);
  683. }
  684. if (!compilationPreprocesses) {
  685. // Compilation will not preprocess, so it does not need the defines
  686. // unless the compiler wants them for some other purpose.
  687. if (!this->CompileWithDefines(lang)) {
  688. vars.Defines = "";
  689. }
  690. // Rule to scan dependencies of sources that do not need preprocessing.
  691. std::string const& scanRuleName = this->LanguageScanRule(lang, config);
  692. std::vector<std::string> scanCommands;
  693. scanCommands.emplace_back(
  694. GetScanCommand(cmakeCmd, tdi, lang, "$in", "$out"));
  695. auto scanRule =
  696. GetScanRule(scanRuleName, "", scanDepType, vars, "", flags,
  697. rulePlaceholderExpander.get(), this->GetLocalGenerator(),
  698. std::move(scanCommands), config);
  699. // Write the rule for generating dependencies for the given language.
  700. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  701. " dependencies on non-preprocessed files.");
  702. scanRule.Description =
  703. cmStrCat("Generating ", lang, " dependencies for $in");
  704. this->GetGlobalGenerator()->AddRule(scanRule);
  705. }
  706. // Write the rule for ninja dyndep file generation.
  707. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  708. // Command line length is almost always limited -> use response file for
  709. // dyndep rules
  710. rule.RspFile = "$out.rsp";
  711. rule.RspContent = "$in";
  712. // Ninja's collator writes all outputs using `cmGeneratedFileStream`, so
  713. // they are only updated if contents actually change. Avoid running
  714. // dependent jobs if the contents don't change by telling `ninja` to check
  715. // the timestamp again.
  716. rule.Restat = "1";
  717. // Run CMake dependency scanner on the source file (using the preprocessed
  718. // source if that was performed).
  719. std::string ddModmapArg;
  720. if (!modmapFormat.empty()) {
  721. ddModmapArg += cmStrCat(" --modmapfmt=", modmapFormat);
  722. }
  723. {
  724. std::vector<std::string> ddCmds;
  725. {
  726. std::string ccmd = cmStrCat(
  727. cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi, " --lang=", lang,
  728. ddModmapArg, " --dd=$out @", rule.RspFile);
  729. ddCmds.emplace_back(std::move(ccmd));
  730. }
  731. rule.Command =
  732. this->GetLocalGenerator()->BuildCommandLine(ddCmds, config, config);
  733. }
  734. rule.Comment =
  735. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  736. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  737. this->GetGlobalGenerator()->AddRule(rule);
  738. }
  739. cmNinjaRule rule(this->LanguageCompilerRule(lang, config, withScanning));
  740. // If using a response file, move defines, includes, and flags into it.
  741. if (!responseFlag.empty()) {
  742. rule.RspFile = "$RSP_FILE";
  743. rule.RspContent =
  744. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  745. flags = cmStrCat(responseFlag, rule.RspFile);
  746. vars.Defines = "";
  747. vars.Includes = "";
  748. // Swift consumes all source files in a module at once, which reaches
  749. // command line length limits pretty quickly. Inject source files into the
  750. // response file in this case as well.
  751. if (lang == "Swift") {
  752. rule.RspContent = cmStrCat(rule.RspContent, ' ', vars.Source);
  753. vars.Source = "";
  754. }
  755. }
  756. // Tell ninja dependency format so all deps can be loaded into a database
  757. std::string cldeps;
  758. if (!compilationPreprocesses) {
  759. // The compiler will not do preprocessing, so it has no such dependencies.
  760. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  761. // For the MS resource compiler we need cmcldeps, but skip dependencies
  762. // for source-file try_compile cases because they are always fresh.
  763. if (!mf->GetIsSourceFileTryCompile()) {
  764. rule.DepType = "gcc";
  765. rule.DepFile = "$DEP_FILE";
  766. cmValue d = mf->GetDefinition("CMAKE_C_COMPILER");
  767. const std::string cl =
  768. d ? *d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  769. std::string cmcldepsPath;
  770. cmSystemTools::GetShortPath(cmSystemTools::GetCMClDepsCommand(),
  771. cmcldepsPath);
  772. cldeps = cmStrCat(cmcldepsPath, ' ', lang, ' ', vars.Source,
  773. " $DEP_FILE $out \"",
  774. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  775. "\" \"", cl, "\" ");
  776. }
  777. } else {
  778. const auto& depType = this->GetMakefile()->GetSafeDefinition(
  779. cmStrCat("CMAKE_", lang, "_DEPFILE_FORMAT"));
  780. if (depType == "msvc"_s) {
  781. rule.DepType = "msvc";
  782. rule.DepFile.clear();
  783. } else {
  784. rule.DepType = "gcc";
  785. rule.DepFile = "$DEP_FILE";
  786. }
  787. vars.DependencyFile = rule.DepFile.c_str();
  788. vars.DependencyTarget = "$out";
  789. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  790. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  791. if (!depfileFlags.empty()) {
  792. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  793. depfileFlags, vars);
  794. flags += cmStrCat(' ', depfileFlags);
  795. }
  796. }
  797. if (withScanning == WithScanning::Yes && !modmapFormat.empty()) {
  798. std::string modmapFlags =
  799. mf->GetRequiredDefinition(cmStrCat("CMAKE_", lang, "_MODULE_MAP_FLAG"));
  800. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  801. "$DYNDEP_MODULE_MAP_FILE");
  802. flags += cmStrCat(' ', modmapFlags);
  803. }
  804. vars.Flags = flags.c_str();
  805. vars.DependencyFile = rule.DepFile.c_str();
  806. std::string cudaCompileMode;
  807. if (lang == "CUDA") {
  808. if (this->GeneratorTarget->GetPropertyAsBool(
  809. "CUDA_SEPARABLE_COMPILATION")) {
  810. const std::string& rdcFlag =
  811. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  812. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  813. }
  814. static std::array<cm::string_view, 4> const compileModes{
  815. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  816. };
  817. bool useNormalCompileMode = true;
  818. for (cm::string_view mode : compileModes) {
  819. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  820. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  821. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  822. const std::string& flag =
  823. this->Makefile->GetRequiredDefinition(defName);
  824. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  825. useNormalCompileMode = false;
  826. break;
  827. }
  828. }
  829. if (useNormalCompileMode) {
  830. const std::string& wholeFlag =
  831. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  832. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  833. }
  834. vars.CudaCompileMode = cudaCompileMode.c_str();
  835. }
  836. // Rule for compiling object file.
  837. const std::string cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  838. const std::string& compileCmd = mf->GetRequiredDefinition(cmdVar);
  839. cmList compileCmds(compileCmd);
  840. if (!compileCmds.empty()) {
  841. compileCmds.front().insert(0, "${CODE_CHECK}");
  842. compileCmds.front().insert(0, "${LAUNCHER}");
  843. }
  844. if (!compileCmds.empty()) {
  845. compileCmds.front().insert(0, cldeps);
  846. }
  847. const auto& extraCommands = this->GetMakefile()->GetSafeDefinition(
  848. cmStrCat("CMAKE_", lang, "_DEPENDS_EXTRA_COMMANDS"));
  849. if (!extraCommands.empty()) {
  850. compileCmds.append(extraCommands);
  851. }
  852. for (auto& i : compileCmds) {
  853. i = cmStrCat(launcher, i);
  854. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  855. vars);
  856. }
  857. rule.Command =
  858. this->GetLocalGenerator()->BuildCommandLine(compileCmds, config, config);
  859. // Write the rule for compiling file of the given language.
  860. rule.Comment = cmStrCat("Rule for compiling ", lang, " files.");
  861. rule.Description = cmStrCat("Building ", lang, " object $out");
  862. this->GetGlobalGenerator()->AddRule(rule);
  863. }
  864. void cmNinjaTargetGenerator::WriteObjectBuildStatements(
  865. const std::string& config, const std::string& fileConfig,
  866. bool firstForConfig)
  867. {
  868. this->GeneratorTarget->CheckCxxModuleStatus(config);
  869. // Write comments.
  870. cmGlobalNinjaGenerator::WriteDivider(this->GetImplFileStream(fileConfig));
  871. this->GetImplFileStream(fileConfig)
  872. << "# Object build statements for "
  873. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  874. << " target " << this->GetTargetName() << "\n\n";
  875. std::vector<cmCustomCommand const*> customCommands;
  876. {
  877. std::vector<cmSourceFile const*> customCommandSources;
  878. this->GeneratorTarget->GetCustomCommands(customCommandSources, config);
  879. for (cmSourceFile const* sf : customCommandSources) {
  880. cmCustomCommand const* cc = sf->GetCustomCommand();
  881. this->GetLocalGenerator()->AddCustomCommandTarget(
  882. cc, this->GetGeneratorTarget());
  883. customCommands.push_back(cc);
  884. }
  885. }
  886. {
  887. std::vector<cmSourceFile const*> headerSources;
  888. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  889. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  890. headerSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  891. config);
  892. }
  893. {
  894. std::vector<cmSourceFile const*> extraSources;
  895. this->GeneratorTarget->GetExtraSources(extraSources, config);
  896. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  897. extraSources, this->Configs[fileConfig].MacOSXContentGenerator.get(),
  898. config);
  899. }
  900. if (firstForConfig) {
  901. cmValue pchExtension =
  902. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  903. std::vector<cmSourceFile const*> externalObjects;
  904. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  905. for (cmSourceFile const* sf : externalObjects) {
  906. auto objectFileName = this->GetGlobalGenerator()->ExpandCFGIntDir(
  907. this->ConvertToNinjaPath(sf->GetFullPath()), config);
  908. if (!cmHasSuffix(objectFileName, pchExtension)) {
  909. this->Configs[config].Objects.push_back(objectFileName);
  910. }
  911. }
  912. }
  913. if (!this->GetGlobalGenerator()->SupportsCWDDepend()) {
  914. // Ensure that the object directory exists. If there are no objects in the
  915. // target (e.g., an empty `OBJECT` library), the directory is still listed
  916. // as an order-only depends in the build files. Alternate `ninja`
  917. // implementations may not allow this (such as `samu`). See #25526.
  918. auto const objectDir = this->GetObjectFileDir(config);
  919. this->EnsureDirectoryExists(objectDir);
  920. }
  921. {
  922. cmNinjaBuild build("phony");
  923. build.Comment =
  924. cmStrCat("Order-only phony target for ", this->GetTargetName());
  925. build.Outputs.push_back(this->OrderDependsTargetForTarget(config));
  926. // Gather order-only dependencies on custom command outputs.
  927. std::vector<std::string> ccouts;
  928. std::vector<std::string> ccouts_private;
  929. bool usePrivateGeneratedSources = false;
  930. if (this->GeneratorTarget->Target->HasFileSets()) {
  931. switch (this->GetGeneratorTarget()->GetPolicyStatusCMP0154()) {
  932. case cmPolicies::WARN:
  933. case cmPolicies::OLD:
  934. break;
  935. case cmPolicies::REQUIRED_ALWAYS:
  936. case cmPolicies::REQUIRED_IF_USED:
  937. case cmPolicies::NEW:
  938. usePrivateGeneratedSources = true;
  939. break;
  940. }
  941. }
  942. for (cmCustomCommand const* cc : customCommands) {
  943. cmCustomCommandGenerator ccg(*cc, config, this->GetLocalGenerator());
  944. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  945. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  946. auto const nPreviousOutputs = ccouts.size();
  947. ccouts.insert(ccouts.end(), ccoutputs.begin(), ccoutputs.end());
  948. ccouts.insert(ccouts.end(), ccbyproducts.begin(), ccbyproducts.end());
  949. if (usePrivateGeneratedSources) {
  950. auto it = ccouts.begin();
  951. // Skip over outputs that were already detected.
  952. std::advance(it, nPreviousOutputs);
  953. while (it != ccouts.end()) {
  954. cmFileSet const* fileset =
  955. this->GeneratorTarget->GetFileSetForSource(
  956. config, this->Makefile->GetOrCreateGeneratedSource(*it));
  957. bool isVisible = fileset &&
  958. cmFileSetVisibilityIsForInterface(fileset->GetVisibility());
  959. bool isIncludeable =
  960. !fileset || cmFileSetTypeCanBeIncluded(fileset->GetType());
  961. if (fileset && isVisible && isIncludeable) {
  962. ++it;
  963. continue;
  964. }
  965. if (!fileset || isIncludeable) {
  966. ccouts_private.push_back(*it);
  967. }
  968. it = ccouts.erase(it);
  969. }
  970. }
  971. }
  972. cmNinjaDeps& orderOnlyDeps = build.OrderOnlyDeps;
  973. this->GetLocalGenerator()->AppendTargetDepends(
  974. this->GeneratorTarget, orderOnlyDeps, config, fileConfig,
  975. DependOnTargetOrdering);
  976. // Add order-only dependencies on other files associated with the target.
  977. cm::append(orderOnlyDeps, this->Configs[config].ExtraFiles);
  978. // Add order-only dependencies on custom command outputs.
  979. std::transform(ccouts.begin(), ccouts.end(),
  980. std::back_inserter(orderOnlyDeps), this->MapToNinjaPath());
  981. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  982. orderOnlyDeps.erase(
  983. std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  984. orderOnlyDeps.end());
  985. // The phony target must depend on at least one input or ninja will explain
  986. // that "output ... of phony edge with no inputs doesn't exist" and
  987. // consider the phony output "dirty".
  988. if (orderOnlyDeps.empty()) {
  989. std::string tgtDir;
  990. if (this->GetGlobalGenerator()->SupportsCWDDepend()) {
  991. tgtDir = ".";
  992. } else {
  993. // Any path that always exists will work here.
  994. tgtDir = cmStrCat(
  995. this->LocalGenerator->GetCurrentBinaryDirectory(), '/',
  996. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget));
  997. }
  998. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  999. }
  1000. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1001. build);
  1002. // Add order-only dependencies on custom command outputs that are
  1003. // private to this target.
  1004. this->HasPrivateGeneratedSources = !ccouts_private.empty();
  1005. if (this->HasPrivateGeneratedSources) {
  1006. cmNinjaBuild buildPrivate("phony");
  1007. cmNinjaDeps& orderOnlyDepsPrivate = buildPrivate.OrderOnlyDeps;
  1008. orderOnlyDepsPrivate.push_back(
  1009. this->OrderDependsTargetForTarget(config));
  1010. buildPrivate.Outputs.push_back(
  1011. this->OrderDependsTargetForTargetPrivate(config));
  1012. std::transform(ccouts_private.begin(), ccouts_private.end(),
  1013. std::back_inserter(orderOnlyDepsPrivate),
  1014. this->MapToNinjaPath());
  1015. std::sort(orderOnlyDepsPrivate.begin(), orderOnlyDepsPrivate.end());
  1016. orderOnlyDepsPrivate.erase(
  1017. std::unique(orderOnlyDepsPrivate.begin(), orderOnlyDepsPrivate.end()),
  1018. orderOnlyDepsPrivate.end());
  1019. this->GetGlobalGenerator()->WriteBuild(
  1020. this->GetImplFileStream(fileConfig), buildPrivate);
  1021. }
  1022. }
  1023. {
  1024. std::vector<cmSourceFile const*> objectSources;
  1025. this->GeneratorTarget->GetObjectSources(objectSources, config);
  1026. std::vector<cmSourceFile const*> swiftSources;
  1027. for (cmSourceFile const* sf : objectSources) {
  1028. if (this->GetLocalGenerator()->IsSplitSwiftBuild() &&
  1029. sf->GetLanguage() == "Swift") {
  1030. swiftSources.push_back(sf);
  1031. } else {
  1032. this->WriteObjectBuildStatement(sf, config, fileConfig,
  1033. firstForConfig);
  1034. }
  1035. }
  1036. WriteSwiftObjectBuildStatement(swiftSources, config, fileConfig,
  1037. firstForConfig);
  1038. }
  1039. {
  1040. std::vector<cmSourceFile const*> bmiOnlySources;
  1041. this->GeneratorTarget->GetCxxModuleSources(bmiOnlySources, config);
  1042. for (cmSourceFile const* sf : bmiOnlySources) {
  1043. this->WriteCxxModuleBmiBuildStatement(sf, config, fileConfig,
  1044. firstForConfig);
  1045. }
  1046. }
  1047. // Detect sources in `CXX_MODULES` which are not compiled.
  1048. {
  1049. std::vector<cmSourceFile*> sources;
  1050. this->GeneratorTarget->GetSourceFiles(sources, config);
  1051. for (cmSourceFile const* sf : sources) {
  1052. cmFileSet const* fs =
  1053. this->GeneratorTarget->GetFileSetForSource(config, sf);
  1054. if (!fs) {
  1055. continue;
  1056. }
  1057. if (fs->GetType() != "CXX_MODULES"_s) {
  1058. continue;
  1059. }
  1060. if (sf->GetLanguage().empty()) {
  1061. this->GeneratorTarget->Makefile->IssueMessage(
  1062. MessageType::FATAL_ERROR,
  1063. cmStrCat("Target \"", this->GeneratorTarget->GetName(),
  1064. "\" has source file\n ", sf->GetFullPath(),
  1065. "\nin a \"FILE_SET TYPE CXX_MODULES\" but it is not "
  1066. "scheduled for compilation."));
  1067. }
  1068. }
  1069. }
  1070. // Check if there are Fortran objects which need to participate in forwarding
  1071. // module requirements.
  1072. if (this->GeneratorTarget->HaveFortranSources(config) &&
  1073. !this->Configs[config].ScanningInfo.count("Fortran")) {
  1074. ScanningFiles files;
  1075. this->Configs[config].ScanningInfo["Fortran"].emplace_back(files);
  1076. this->WriteCompileRule("Fortran", config, WithScanning::Yes);
  1077. }
  1078. for (auto const& langScanningFiles : this->Configs[config].ScanningInfo) {
  1079. std::string const& language = langScanningFiles.first;
  1080. std::vector<ScanningFiles> const& scanningFiles = langScanningFiles.second;
  1081. cmNinjaBuild build(this->LanguageDyndepRule(language, config));
  1082. build.Outputs.push_back(this->GetDyndepFilePath(language, config));
  1083. build.ImplicitOuts.emplace_back(
  1084. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  1085. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  1086. this->GetGlobalGenerator()->ConfigDirectory(config), '/',
  1087. language, "Modules.json"));
  1088. build.ImplicitDeps.emplace_back(
  1089. this->GetTargetDependInfoPath(language, config));
  1090. {
  1091. auto bdb_path =
  1092. this->GeneratorTarget->BuildDatabasePath(language, config);
  1093. if (!bdb_path.empty()) {
  1094. build.ImplicitOuts.emplace_back(this->ConvertToNinjaPath(bdb_path));
  1095. }
  1096. }
  1097. auto bdb_path = this->GeneratorTarget->BuildDatabasePath(language, config);
  1098. if (!bdb_path.empty()) {
  1099. auto db = cmBuildDatabase::ForTarget(this->GeneratorTarget, config);
  1100. auto mcdb_template_path = cmStrCat(bdb_path, ".in");
  1101. db.Write(mcdb_template_path);
  1102. build.ImplicitDeps.emplace_back(std::move(mcdb_template_path));
  1103. build.ImplicitOuts.emplace_back(std::move(bdb_path));
  1104. }
  1105. for (auto const& scanFiles : scanningFiles) {
  1106. if (!scanFiles.ScanningOutput.empty()) {
  1107. build.ExplicitDeps.push_back(scanFiles.ScanningOutput);
  1108. }
  1109. if (!scanFiles.ModuleMapFile.empty()) {
  1110. build.ImplicitOuts.push_back(scanFiles.ModuleMapFile);
  1111. }
  1112. }
  1113. this->WriteTargetDependInfo(language, config);
  1114. auto const linked_directories =
  1115. this->GetLinkedTargetDirectories(language, config);
  1116. for (std::string const& l : linked_directories.Direct) {
  1117. build.ImplicitDeps.emplace_back(
  1118. cmStrCat(l, '/', language, "Modules.json"));
  1119. }
  1120. for (std::string const& l : linked_directories.Forward) {
  1121. build.ImplicitDeps.emplace_back(
  1122. cmStrCat(l, '/', language, "Modules.json"));
  1123. }
  1124. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1125. build);
  1126. }
  1127. this->GetImplFileStream(fileConfig) << "\n";
  1128. }
  1129. void cmNinjaTargetGenerator::GenerateSwiftOutputFileMap(
  1130. const std::string& config, std::string& flags)
  1131. {
  1132. if (this->Configs[config].SwiftOutputMap.empty()) {
  1133. return;
  1134. }
  1135. std::string const targetSwiftDepsPath = [this, config]() -> std::string {
  1136. cmGeneratorTarget const* target = this->GeneratorTarget;
  1137. if (cmValue name = target->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1138. return *name;
  1139. }
  1140. return this->GetLocalGenerator()->ConvertToOutputFormat(
  1141. this->ConvertToNinjaPath(cmStrCat(target->GetSupportDirectory(), '/',
  1142. config, '/', target->GetName(),
  1143. ".swiftdeps")),
  1144. cmOutputConverter::SHELL);
  1145. }();
  1146. std::string mapFilePath =
  1147. cmStrCat(this->GeneratorTarget->GetSupportDirectory(), '/', config, '/',
  1148. "output-file-map.json");
  1149. // build the global target dependencies
  1150. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1151. Json::Value deps(Json::objectValue);
  1152. deps["swift-dependencies"] = targetSwiftDepsPath;
  1153. this->Configs[config].SwiftOutputMap[""] = deps;
  1154. cmGeneratedFileStream output(mapFilePath);
  1155. output << this->Configs[config].SwiftOutputMap;
  1156. // Add flag
  1157. this->LocalGenerator->AppendFlags(flags, "-output-file-map");
  1158. this->LocalGenerator->AppendFlagEscape(
  1159. flags,
  1160. this->GetLocalGenerator()->ConvertToOutputFormat(
  1161. ConvertToNinjaPath(mapFilePath), cmOutputConverter::SHELL));
  1162. }
  1163. namespace {
  1164. cmNinjaBuild GetScanBuildStatement(const std::string& ruleName,
  1165. const std::string& ppFileName,
  1166. bool compilePP, bool compilePPWithDefines,
  1167. bool compilationPreprocesses,
  1168. cmNinjaBuild& objBuild, cmNinjaVars& vars,
  1169. const std::string& objectFileName,
  1170. cmNinjaTargetGenerator* tg)
  1171. {
  1172. cmNinjaBuild scanBuild(ruleName);
  1173. if (compilePP) {
  1174. // Move compilation dependencies to the scan/preprocessing build statement.
  1175. std::swap(scanBuild.ExplicitDeps, objBuild.ExplicitDeps);
  1176. std::swap(scanBuild.ImplicitDeps, objBuild.ImplicitDeps);
  1177. std::swap(scanBuild.OrderOnlyDeps, objBuild.OrderOnlyDeps);
  1178. std::swap(scanBuild.Variables["IN_ABS"], vars["IN_ABS"]);
  1179. // The actual compilation will now use the preprocessed source.
  1180. objBuild.ExplicitDeps.push_back(ppFileName);
  1181. } else {
  1182. // Copy compilation dependencies to the scan/preprocessing build statement.
  1183. scanBuild.ExplicitDeps = objBuild.ExplicitDeps;
  1184. scanBuild.ImplicitDeps = objBuild.ImplicitDeps;
  1185. scanBuild.OrderOnlyDeps = objBuild.OrderOnlyDeps;
  1186. scanBuild.Variables["IN_ABS"] = vars["IN_ABS"];
  1187. }
  1188. // Scanning and compilation generally use the same flags.
  1189. scanBuild.Variables["FLAGS"] = vars["FLAGS"];
  1190. if (compilePP && !compilePPWithDefines) {
  1191. // Move preprocessor definitions to the scan/preprocessor build statement.
  1192. std::swap(scanBuild.Variables["DEFINES"], vars["DEFINES"]);
  1193. } else {
  1194. // Copy preprocessor definitions to the scan/preprocessor build statement.
  1195. scanBuild.Variables["DEFINES"] = vars["DEFINES"];
  1196. }
  1197. // Copy include directories to the preprocessor build statement. The
  1198. // Fortran compilation build statement still needs them for the INCLUDE
  1199. // directive.
  1200. scanBuild.Variables["INCLUDES"] = vars["INCLUDES"];
  1201. // Tell dependency scanner the object file that will result from
  1202. // compiling the source.
  1203. scanBuild.Variables["OBJ_FILE"] = objectFileName;
  1204. // Tell dependency scanner where to store dyndep intermediate results.
  1205. std::string ddiFileName = cmStrCat(objectFileName, ".ddi");
  1206. scanBuild.Variables["DYNDEP_INTERMEDIATE_FILE"] = ddiFileName;
  1207. scanBuild.RspFile = cmStrCat(ddiFileName, ".rsp");
  1208. // Outputs of the scan/preprocessor build statement.
  1209. if (compilePP) {
  1210. scanBuild.Outputs.push_back(ppFileName);
  1211. scanBuild.ImplicitOuts.push_back(ddiFileName);
  1212. } else {
  1213. scanBuild.Outputs.push_back(ddiFileName);
  1214. scanBuild.Variables["PREPROCESSED_OUTPUT_FILE"] = ppFileName;
  1215. if (!compilationPreprocesses) {
  1216. // Compilation does not preprocess and we are not compiling an
  1217. // already-preprocessed source. Make compilation depend on the scan
  1218. // results to honor implicit dependencies discovered during scanning
  1219. // (such as Fortran INCLUDE directives).
  1220. objBuild.ImplicitDeps.emplace_back(ddiFileName);
  1221. }
  1222. }
  1223. // Scanning always provides a depfile for preprocessor dependencies. This
  1224. // variable is unused in `msvc`-deptype scanners.
  1225. tg->AddDepfileBinding(scanBuild.Variables,
  1226. cmStrCat(scanBuild.Outputs.front(), ".d"));
  1227. if (compilePP) {
  1228. // The actual compilation does not need a depfile because it
  1229. // depends on the already-preprocessed source.
  1230. tg->RemoveDepfileBinding(vars);
  1231. }
  1232. return scanBuild;
  1233. }
  1234. }
  1235. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  1236. cmSourceFile const* source, const std::string& config,
  1237. const std::string& fileConfig, bool firstForConfig)
  1238. {
  1239. std::string const language = source->GetLanguage();
  1240. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1241. std::string const objectDir = this->ConvertToNinjaPath(
  1242. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1243. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1244. std::string const objectFileName =
  1245. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1246. std::string const objectFileDir =
  1247. cmSystemTools::GetFilenamePath(objectFileName);
  1248. std::string cmakeVarLang = cmStrCat("CMAKE_", language);
  1249. // build response file name
  1250. std::string cmakeLinkVar = cmStrCat(cmakeVarLang, "_RESPONSE_FILE_FLAG");
  1251. cmValue flag = this->GetMakefile()->GetDefinition(cmakeLinkVar);
  1252. bool const lang_supports_response =
  1253. !(language == "RC" || (language == "CUDA" && !flag));
  1254. int const commandLineLengthLimit =
  1255. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  1256. cmValue pchExtension =
  1257. this->GetMakefile()->GetDefinition("CMAKE_PCH_EXTENSION");
  1258. bool const isPch = cmHasSuffix(objectFileName, pchExtension);
  1259. bool const needDyndep = !isPch &&
  1260. this->GeneratorTarget->NeedDyndepForSource(language, config, source);
  1261. WithScanning withScanning =
  1262. needDyndep ? WithScanning::Yes : WithScanning::No;
  1263. cmNinjaBuild objBuild(
  1264. this->LanguageCompilerRule(language, config, withScanning));
  1265. cmNinjaVars& vars = objBuild.Variables;
  1266. vars["FLAGS"] =
  1267. this->ComputeFlagsForObject(source, language, config, objectFileName);
  1268. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1269. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1270. auto compilerLauncher = this->GetCompilerLauncher(language, config);
  1271. cmValue const skipCodeCheck = source->GetProperty("SKIP_LINTING");
  1272. if (!skipCodeCheck.IsOn()) {
  1273. auto const cmakeCmd = this->GetLocalGenerator()->ConvertToOutputFormat(
  1274. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  1275. vars["CODE_CHECK"] =
  1276. this->GenerateCodeCheckRules(*source, compilerLauncher, cmakeCmd, config,
  1277. [this](const std::string& path) {
  1278. return this->ConvertToNinjaPath(path);
  1279. });
  1280. }
  1281. // If compiler launcher was specified and not consumed above, it
  1282. // goes to the beginning of the command line.
  1283. if (!compilerLauncher.empty()) {
  1284. cmList args{ compilerLauncher, cmList::EmptyElements::Yes };
  1285. if (!args.empty()) {
  1286. args[0] = this->LocalGenerator->ConvertToOutputFormat(
  1287. args[0], cmOutputConverter::SHELL);
  1288. for (std::string& i : cmMakeRange(args.begin() + 1, args.end())) {
  1289. i = this->LocalGenerator->EscapeForShell(i);
  1290. }
  1291. vars["LAUNCHER"] = args.join(" ") + " ";
  1292. }
  1293. }
  1294. if (this->GetMakefile()->GetSafeDefinition(
  1295. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1296. bool replaceExt = false;
  1297. if (!language.empty()) {
  1298. std::string repVar =
  1299. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1300. replaceExt = this->Makefile->IsOn(repVar);
  1301. }
  1302. this->AddDepfileBinding(
  1303. vars,
  1304. replaceExt ? cmStrCat(objectFileDir, '/',
  1305. cmSystemTools::GetFilenameWithoutLastExtension(
  1306. objectFileName),
  1307. ".d")
  1308. : cmStrCat(objectFileName, ".d"));
  1309. }
  1310. this->SetMsvcTargetPdbVariable(vars, config);
  1311. if (firstForConfig) {
  1312. this->ExportObjectCompileCommand(
  1313. language, sourceFilePath, objectDir, objectFileName, objectFileDir,
  1314. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"],
  1315. vars["TARGET_COMPILE_PDB"], vars["TARGET_PDB"], config, withScanning);
  1316. }
  1317. objBuild.Outputs.push_back(objectFileName);
  1318. if (firstForConfig && !isPch) {
  1319. // Add this object to the list of object files.
  1320. this->Configs[config].Objects.push_back(objectFileName);
  1321. }
  1322. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1323. // Add precompile headers dependencies
  1324. std::vector<std::string> depList;
  1325. std::vector<std::string> pchArchs =
  1326. this->GeneratorTarget->GetPchArchs(config, language);
  1327. std::unordered_set<std::string> pchSources;
  1328. for (const std::string& arch : pchArchs) {
  1329. const std::string pchSource =
  1330. this->GeneratorTarget->GetPchSource(config, language, arch);
  1331. if (!pchSource.empty()) {
  1332. pchSources.insert(pchSource);
  1333. }
  1334. }
  1335. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1336. for (const std::string& arch : pchArchs) {
  1337. depList.push_back(
  1338. this->GeneratorTarget->GetPchHeader(config, language, arch));
  1339. if (pchSources.find(source->GetFullPath()) == pchSources.end()) {
  1340. depList.push_back(
  1341. this->GeneratorTarget->GetPchFile(config, language, arch));
  1342. }
  1343. }
  1344. }
  1345. if (cmValue objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  1346. cmList objDepList{ *objectDeps };
  1347. std::copy(objDepList.begin(), objDepList.end(),
  1348. std::back_inserter(depList));
  1349. }
  1350. if (!depList.empty()) {
  1351. for (std::string& odi : depList) {
  1352. if (cmSystemTools::FileIsFullPath(odi)) {
  1353. odi = cmSystemTools::CollapseFullPath(odi);
  1354. }
  1355. }
  1356. std::transform(depList.begin(), depList.end(),
  1357. std::back_inserter(objBuild.ImplicitDeps),
  1358. this->MapToNinjaPath());
  1359. }
  1360. if (this->HasPrivateGeneratedSources) {
  1361. objBuild.OrderOnlyDeps.push_back(
  1362. this->OrderDependsTargetForTargetPrivate(config));
  1363. } else {
  1364. objBuild.OrderOnlyDeps.push_back(
  1365. this->OrderDependsTargetForTarget(config));
  1366. }
  1367. // If the source file is GENERATED and does not have a custom command
  1368. // (either attached to this source file or another one), assume that one of
  1369. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  1370. // will rebuild the file.
  1371. if (source->GetIsGenerated() &&
  1372. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  1373. !source->GetCustomCommand() &&
  1374. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFilePath)) {
  1375. this->GetGlobalGenerator()->AddAssumedSourceDependencies(
  1376. sourceFilePath, objBuild.OrderOnlyDeps);
  1377. }
  1378. // For some cases we scan to dynamically discover dependencies.
  1379. bool const compilationPreprocesses =
  1380. !this->NeedExplicitPreprocessing(language);
  1381. std::string modmapFormat;
  1382. if (needDyndep) {
  1383. std::string const modmapFormatVar =
  1384. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1385. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1386. }
  1387. if (needDyndep) {
  1388. // If source/target has preprocessing turned off, we still need to
  1389. // generate an explicit dependency step
  1390. const auto srcpp = source->GetSafeProperty("Fortran_PREPROCESS");
  1391. cmOutputConverter::FortranPreprocess preprocess =
  1392. cmOutputConverter::GetFortranPreprocess(srcpp);
  1393. if (preprocess == cmOutputConverter::FortranPreprocess::Unset) {
  1394. const auto& tgtpp =
  1395. this->GeneratorTarget->GetSafeProperty("Fortran_PREPROCESS");
  1396. preprocess = cmOutputConverter::GetFortranPreprocess(tgtpp);
  1397. }
  1398. bool const compilePP = !compilationPreprocesses &&
  1399. (preprocess != cmOutputConverter::FortranPreprocess::NotNeeded);
  1400. bool const compilePPWithDefines =
  1401. compilePP && this->CompileWithDefines(language);
  1402. std::string scanRuleName;
  1403. std::string ppFileName;
  1404. if (compilePP) {
  1405. scanRuleName = this->LanguagePreprocessAndScanRule(language, config);
  1406. ppFileName = this->ConvertToNinjaPath(
  1407. this->GetPreprocessedFilePath(source, config));
  1408. } else {
  1409. scanRuleName = this->LanguageScanRule(language, config);
  1410. ppFileName = cmStrCat(objectFileName, ".ddi.i");
  1411. }
  1412. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1413. scanRuleName, ppFileName, compilePP, compilePPWithDefines,
  1414. compilationPreprocesses, objBuild, vars, objectFileName, this);
  1415. if (compilePP) {
  1416. // In case compilation requires flags that are incompatible with
  1417. // preprocessing, include them here.
  1418. std::string const& postFlag = this->Makefile->GetSafeDefinition(
  1419. cmStrCat("CMAKE_", language, "_POSTPROCESS_FLAG"));
  1420. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  1421. // Prepend source file's original directory as an include directory
  1422. // so e.g. Fortran INCLUDE statements can look for files in it.
  1423. std::vector<std::string> sourceDirectory;
  1424. sourceDirectory.push_back(
  1425. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  1426. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  1427. sourceDirectory, this->GeneratorTarget, language, config, false);
  1428. vars["INCLUDES"] = cmStrCat(sourceDirectoryFlag, ' ', vars["INCLUDES"]);
  1429. }
  1430. ScanningFiles scanningFiles;
  1431. if (firstForConfig) {
  1432. scanningFiles.ScanningOutput = cmStrCat(objectFileName, ".ddi");
  1433. }
  1434. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1435. ppBuild.Variables);
  1436. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1437. ppBuild, commandLineLengthLimit);
  1438. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1439. objBuild.OrderOnlyDeps.push_back(dyndep);
  1440. vars["dyndep"] = dyndep;
  1441. if (!modmapFormat.empty()) {
  1442. // XXX(modmap): If changing this path construction, change
  1443. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1444. // `cmNinjaTargetGenerator::ExportObjectCompileCommand` to expect the
  1445. // corresponding file path.
  1446. std::string ddModmapFile = cmStrCat(objectFileName, ".modmap");
  1447. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1448. objBuild.ImplicitDeps.push_back(ddModmapFile);
  1449. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1450. }
  1451. if (!scanningFiles.IsEmpty()) {
  1452. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1453. }
  1454. }
  1455. this->EnsureParentDirectoryExists(objectFileName);
  1456. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1457. objectDir, cmOutputConverter::SHELL);
  1458. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1459. objectFileDir, cmOutputConverter::SHELL);
  1460. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1461. vars);
  1462. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1463. auto pchIt = pchSources.find(source->GetFullPath());
  1464. if (pchIt != pchSources.end()) {
  1465. this->addPoolNinjaVariable("JOB_POOL_PRECOMPILE_HEADER",
  1466. this->GetGeneratorTarget(), vars);
  1467. }
  1468. }
  1469. objBuild.RspFile = cmStrCat(objectFileName, ".rsp");
  1470. if (language == "ISPC") {
  1471. std::string const& objectName =
  1472. this->GeneratorTarget->GetObjectName(source);
  1473. std::string ispcSource =
  1474. cmSystemTools::GetFilenameWithoutLastExtension(objectName);
  1475. ispcSource = cmSystemTools::GetFilenameWithoutLastExtension(ispcSource);
  1476. cmValue ispcSuffixProp =
  1477. this->GeneratorTarget->GetProperty("ISPC_HEADER_SUFFIX");
  1478. assert(ispcSuffixProp);
  1479. std::string ispcHeaderDirectory =
  1480. this->GeneratorTarget->GetObjectDirectory(config);
  1481. if (cmValue prop =
  1482. this->GeneratorTarget->GetProperty("ISPC_HEADER_DIRECTORY")) {
  1483. ispcHeaderDirectory =
  1484. cmStrCat(this->LocalGenerator->GetBinaryDirectory(), '/', *prop);
  1485. }
  1486. std::string ispcHeader =
  1487. cmStrCat(ispcHeaderDirectory, '/', ispcSource, *ispcSuffixProp);
  1488. ispcHeader = this->ConvertToNinjaPath(ispcHeader);
  1489. // Make sure ninja knows what command generates the header
  1490. objBuild.ImplicitOuts.push_back(ispcHeader);
  1491. // Make sure ninja knows how to clean the generated header
  1492. this->GetGlobalGenerator()->AddAdditionalCleanFile(ispcHeader, config);
  1493. auto ispcSuffixes =
  1494. detail::ComputeISPCObjectSuffixes(this->GeneratorTarget);
  1495. if (ispcSuffixes.size() > 1) {
  1496. std::string rootObjectDir =
  1497. this->GeneratorTarget->GetObjectDirectory(config);
  1498. auto ispcSideEfffectObjects = detail::ComputeISPCExtraObjects(
  1499. objectName, rootObjectDir, ispcSuffixes);
  1500. for (auto sideEffect : ispcSideEfffectObjects) {
  1501. sideEffect = this->ConvertToNinjaPath(sideEffect);
  1502. objBuild.ImplicitOuts.emplace_back(sideEffect);
  1503. this->GetGlobalGenerator()->AddAdditionalCleanFile(sideEffect, config);
  1504. }
  1505. }
  1506. vars["ISPC_HEADER_FILE"] =
  1507. this->GetLocalGenerator()->ConvertToOutputFormat(
  1508. ispcHeader, cmOutputConverter::SHELL);
  1509. } else {
  1510. auto headers = this->GeneratorTarget->GetGeneratedISPCHeaders(config);
  1511. if (!headers.empty()) {
  1512. std::transform(headers.begin(), headers.end(), headers.begin(),
  1513. this->MapToNinjaPath());
  1514. objBuild.OrderOnlyDeps.insert(objBuild.OrderOnlyDeps.end(),
  1515. headers.begin(), headers.end());
  1516. }
  1517. }
  1518. if (language == "Swift") {
  1519. this->EmitSwiftDependencyInfo(source, config);
  1520. } else {
  1521. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1522. objBuild, commandLineLengthLimit);
  1523. }
  1524. if (cmValue objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  1525. std::string evaluatedObjectOutputs = cmGeneratorExpression::Evaluate(
  1526. *objectOutputs, this->LocalGenerator, config);
  1527. if (!evaluatedObjectOutputs.empty()) {
  1528. cmNinjaBuild build("phony");
  1529. build.Comment = "Additional output files.";
  1530. build.Outputs = cmList{ evaluatedObjectOutputs }.data();
  1531. std::transform(build.Outputs.begin(), build.Outputs.end(),
  1532. build.Outputs.begin(), this->MapToNinjaPath());
  1533. build.ExplicitDeps = objBuild.Outputs;
  1534. this->GetGlobalGenerator()->WriteBuild(
  1535. this->GetImplFileStream(fileConfig), build);
  1536. }
  1537. }
  1538. }
  1539. void cmNinjaTargetGenerator::WriteCxxModuleBmiBuildStatement(
  1540. cmSourceFile const* source, const std::string& config,
  1541. const std::string& fileConfig, bool firstForConfig)
  1542. {
  1543. std::string const language = source->GetLanguage();
  1544. if (language != "CXX"_s) {
  1545. this->GetMakefile()->IssueMessage(
  1546. MessageType::FATAL_ERROR,
  1547. cmStrCat("Source file '", source->GetFullPath(), "' of target '",
  1548. this->GetTargetName(), "' is a '", language,
  1549. "' source but must be 'CXX' in order to have a BMI build "
  1550. "statement generated."));
  1551. return;
  1552. }
  1553. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1554. std::string const bmiDir = this->ConvertToNinjaPath(
  1555. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1556. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1557. std::string const bmiFileName =
  1558. this->ConvertToNinjaPath(this->GetBmiFilePath(source, config));
  1559. std::string const bmiFileDir = cmSystemTools::GetFilenamePath(bmiFileName);
  1560. int const commandLineLengthLimit = this->ForceResponseFile() ? -1 : 0;
  1561. cmNinjaBuild bmiBuild(
  1562. this->LanguageCompilerRule(language, config, WithScanning::Yes));
  1563. cmNinjaVars& vars = bmiBuild.Variables;
  1564. vars["FLAGS"] =
  1565. this->ComputeFlagsForObject(source, language, config, bmiFileName);
  1566. vars["DEFINES"] = this->ComputeDefines(source, language, config);
  1567. vars["INCLUDES"] = this->ComputeIncludes(source, language, config);
  1568. if (this->GetMakefile()->GetSafeDefinition(
  1569. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT")) != "msvc"_s) {
  1570. bool replaceExt = false;
  1571. if (!language.empty()) {
  1572. std::string repVar =
  1573. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  1574. replaceExt = this->Makefile->IsOn(repVar);
  1575. }
  1576. this->AddDepfileBinding(
  1577. vars,
  1578. replaceExt
  1579. ? cmStrCat(bmiFileDir, '/',
  1580. cmSystemTools::GetFilenameWithoutLastExtension(bmiFileName),
  1581. ".d")
  1582. : cmStrCat(bmiFileName, ".d"));
  1583. }
  1584. std::string d =
  1585. this->GeneratorTarget->GetClangTidyExportFixesDirectory(language);
  1586. if (!d.empty()) {
  1587. this->GlobalCommonGenerator->AddClangTidyExportFixesDir(d);
  1588. std::string fixesFile =
  1589. this->GetClangTidyReplacementsFilePath(d, *source, config);
  1590. this->GlobalCommonGenerator->AddClangTidyExportFixesFile(fixesFile);
  1591. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(fixesFile));
  1592. fixesFile = this->ConvertToNinjaPath(fixesFile);
  1593. vars["CLANG_TIDY_EXPORT_FIXES"] = fixesFile;
  1594. }
  1595. this->SetMsvcTargetPdbVariable(vars, config);
  1596. if (firstForConfig) {
  1597. this->ExportObjectCompileCommand(
  1598. language, sourceFilePath, bmiDir, bmiFileName, bmiFileDir, vars["FLAGS"],
  1599. vars["DEFINES"], vars["INCLUDES"], vars["TARGET_COMPILE_PDB"],
  1600. vars["TARGET_PDB"], config, WithScanning::Yes);
  1601. }
  1602. bmiBuild.Outputs.push_back(bmiFileName);
  1603. bmiBuild.ExplicitDeps.push_back(sourceFilePath);
  1604. std::vector<std::string> depList;
  1605. bmiBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1606. // For some cases we scan to dynamically discover dependencies.
  1607. std::string modmapFormat;
  1608. if (true) {
  1609. std::string const modmapFormatVar =
  1610. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1611. modmapFormat = this->Makefile->GetSafeDefinition(modmapFormatVar);
  1612. }
  1613. {
  1614. bool const compilePPWithDefines = this->CompileWithDefines(language);
  1615. std::string scanRuleName = this->LanguageScanRule(language, config);
  1616. std::string ppFileName = cmStrCat(bmiFileName, ".ddi.i");
  1617. cmNinjaBuild ppBuild = GetScanBuildStatement(
  1618. scanRuleName, ppFileName, false, compilePPWithDefines, true, bmiBuild,
  1619. vars, bmiFileName, this);
  1620. ScanningFiles scanningFiles;
  1621. if (firstForConfig) {
  1622. scanningFiles.ScanningOutput = cmStrCat(bmiFileName, ".ddi");
  1623. }
  1624. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1625. ppBuild.Variables);
  1626. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1627. ppBuild, commandLineLengthLimit);
  1628. std::string const dyndep = this->GetDyndepFilePath(language, config);
  1629. bmiBuild.OrderOnlyDeps.push_back(dyndep);
  1630. vars["dyndep"] = dyndep;
  1631. if (!modmapFormat.empty()) {
  1632. std::string ddModmapFile = cmStrCat(bmiFileName, ".modmap");
  1633. vars["DYNDEP_MODULE_MAP_FILE"] = ddModmapFile;
  1634. scanningFiles.ModuleMapFile = std::move(ddModmapFile);
  1635. }
  1636. if (!scanningFiles.IsEmpty()) {
  1637. this->Configs[config].ScanningInfo[language].emplace_back(scanningFiles);
  1638. }
  1639. }
  1640. this->EnsureParentDirectoryExists(bmiFileName);
  1641. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1642. bmiDir, cmOutputConverter::SHELL);
  1643. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  1644. bmiFileDir, cmOutputConverter::SHELL);
  1645. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  1646. vars);
  1647. bmiBuild.RspFile = cmStrCat(bmiFileName, ".rsp");
  1648. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1649. bmiBuild, commandLineLengthLimit);
  1650. }
  1651. void cmNinjaTargetGenerator::WriteSwiftObjectBuildStatement(
  1652. std::vector<cmSourceFile const*> const& sources, std::string const& config,
  1653. std::string const& fileConfig, bool firstForConfig)
  1654. {
  1655. // Swift sources are compiled as a module, not individually like with C/C++.
  1656. // Flags, header search paths, and definitions are passed to the entire
  1657. // module build, but we still need to emit compile-commands for each source
  1658. // file in order to support CMAKE_EXPORT_COMPILE_COMMANDS.
  1659. // In whole-module mode, with a single thread, the Swift compiler will
  1660. // only emit a single object file, but if more than one thread is specified,
  1661. // or building in other modes, the compiler will emit multiple object files.
  1662. // When building a single-output, we do not provide an output-file-map (OFM),
  1663. // and instead pass `-o` to tell the compiler where to write the object.
  1664. // When building multiple outputs, we provide an OFM to tell the compiler
  1665. // where to put each object.
  1666. //
  1667. //
  1668. // Per-Target (module):
  1669. // - Flags
  1670. // - Definitions
  1671. // - Include paths
  1672. // - (single-output) output object filename
  1673. // - Swiftmodule
  1674. //
  1675. // Per-File:
  1676. // - compile-command
  1677. // - (multi-output) OFM data
  1678. // - (multi-output) output object filename
  1679. //
  1680. // Note: Due to the differences in the build models, we are only able to
  1681. // build the object build-graph if we know what mode the target is built in.
  1682. // For that, we need the "NEW" behavior for CMP0157. Otherwise, we have to
  1683. // fall back on the old "linker" build. Otherwise, this should be
  1684. // indistinguishable from the old behavior.
  1685. if (sources.empty()) {
  1686. return;
  1687. }
  1688. cmSwiftCompileMode compileMode;
  1689. if (cm::optional<cmSwiftCompileMode> optionalCompileMode =
  1690. this->LocalGenerator->GetSwiftCompileMode(this->GeneratorTarget,
  1691. config)) {
  1692. compileMode = *optionalCompileMode;
  1693. } else {
  1694. // CMP0157 is not NEW, bailing early!
  1695. return;
  1696. }
  1697. std::string const language = "Swift";
  1698. std::string const objectDir = this->ConvertToNinjaPath(
  1699. cmStrCat(this->GeneratorTarget->GetSupportDirectory(),
  1700. this->GetGlobalGenerator()->ConfigDirectory(config)));
  1701. cmGeneratorTarget const& target = *this->GeneratorTarget;
  1702. cmNinjaBuild objBuild(
  1703. this->LanguageCompilerRule(language, config, WithScanning::No));
  1704. cmNinjaVars& vars = objBuild.Variables;
  1705. // The swift toolchain leaves outputs untouched if there are no meaningful
  1706. // changes to input files (e.g. addition of a comment).
  1707. vars.emplace("restat", "1");
  1708. std::string const moduleName = target.GetSwiftModuleName();
  1709. std::string const moduleFilepath =
  1710. this->ConvertToNinjaPath(target.GetSwiftModulePath(config));
  1711. vars.emplace("description",
  1712. cmStrCat("Building Swift Module '", moduleName, "' with ",
  1713. sources.size(),
  1714. sources.size() == 1 ? " source" : " sources"));
  1715. bool const isSingleOutput = [this, compileMode]() -> bool {
  1716. bool isMultiThread = false;
  1717. if (cmValue numThreadStr =
  1718. this->GetMakefile()->GetDefinition("CMAKE_Swift_NUM_THREADS")) {
  1719. unsigned long numThreads;
  1720. cmStrToULong(*numThreadStr, &numThreads);
  1721. // numThreads == 1 is multi-threaded according to swiftc
  1722. isMultiThread = numThreads > 0;
  1723. }
  1724. return !isMultiThread && compileMode == cmSwiftCompileMode::Wholemodule;
  1725. }();
  1726. // Without `-emit-library` or `-emit-executable`, targets with a single
  1727. // source file parse as a Swift script instead of like normal source. For
  1728. // non-executable targets, append this to ensure that they are parsed like a
  1729. // normal source.
  1730. if (target.GetType() != cmStateEnums::EXECUTABLE) {
  1731. this->LocalGenerator->AppendFlags(vars["FLAGS"], "-parse-as-library");
  1732. }
  1733. if (target.GetType() == cmStateEnums::STATIC_LIBRARY) {
  1734. this->LocalGenerator->AppendFlags(vars["FLAGS"], "-static");
  1735. }
  1736. // Does this swift target emit a module file for importing into other
  1737. // targets?
  1738. auto isImportableTarget = [](cmGeneratorTarget const& tgt) -> bool {
  1739. // Everything except for executables that don't export anything should emit
  1740. // some way to import them.
  1741. if (tgt.GetType() == cmStateEnums::EXECUTABLE) {
  1742. return tgt.IsExecutableWithExports();
  1743. }
  1744. return true;
  1745. };
  1746. // Swift modules only make sense to emit from things that can be imported.
  1747. // Executables that don't export symbols can't be imported, so don't try to
  1748. // emit a swiftmodule for them. It will break.
  1749. if (isImportableTarget(target)) {
  1750. std::string const emitModuleFlag = "-emit-module";
  1751. std::string const modulePathFlag = "-emit-module-path";
  1752. this->LocalGenerator->AppendFlags(
  1753. vars["FLAGS"], { emitModuleFlag, modulePathFlag, moduleFilepath });
  1754. objBuild.Outputs.push_back(moduleFilepath);
  1755. }
  1756. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1757. cmStrCat("-module-name ", moduleName));
  1758. if (target.GetType() != cmStateEnums::EXECUTABLE) {
  1759. std::string const libraryLinkNameFlag = "-module-link-name";
  1760. std::string const libraryLinkName =
  1761. this->GetGeneratorTarget()->GetLibraryNames(config).Base;
  1762. this->LocalGenerator->AppendFlags(
  1763. vars["FLAGS"], cmStrCat(libraryLinkNameFlag, ' ', libraryLinkName));
  1764. }
  1765. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1766. this->GetFlags(language, config));
  1767. vars["DEFINES"] = this->GetDefines(language, config);
  1768. vars["INCLUDES"] = this->GetIncludes(language, config);
  1769. // target-level object filename
  1770. std::string const targetObjectFilename = this->ConvertToNinjaPath(cmStrCat(
  1771. objectDir, '/', moduleName,
  1772. this->GetGlobalGenerator()->GetLanguageOutputExtension(language)));
  1773. objBuild.RspFile = cmStrCat(targetObjectFilename, ".swift.rsp");
  1774. if (isSingleOutput) {
  1775. this->LocalGenerator->AppendFlags(vars["FLAGS"],
  1776. cmStrCat("-o ", targetObjectFilename));
  1777. objBuild.Outputs.push_back(targetObjectFilename);
  1778. this->Configs[config].Objects.push_back(targetObjectFilename);
  1779. }
  1780. for (cmSourceFile const* sf : sources) {
  1781. // Add dependency to object build on each source file
  1782. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(sf);
  1783. objBuild.ExplicitDeps.push_back(sourceFilePath);
  1784. if (!isSingleOutput) {
  1785. // Object outputs
  1786. std::string const objectFilepath =
  1787. this->ConvertToNinjaPath(this->GetObjectFilePath(sf, config));
  1788. this->EnsureParentDirectoryExists(objectFilepath);
  1789. objBuild.Outputs.push_back(objectFilepath);
  1790. this->Configs[config].Objects.push_back(objectFilepath);
  1791. // Add OFM data
  1792. this->EmitSwiftDependencyInfo(sf, config);
  1793. }
  1794. }
  1795. if (!isSingleOutput) {
  1796. this->GenerateSwiftOutputFileMap(config, vars["FLAGS"]);
  1797. }
  1798. if (firstForConfig) {
  1799. this->ExportSwiftObjectCompileCommand(
  1800. sources, targetObjectFilename, vars["FLAGS"], vars["DEFINES"],
  1801. vars["INCLUDES"], config, isSingleOutput);
  1802. }
  1803. for (cmTargetDepend const& dep :
  1804. this->GetGlobalGenerator()->GetTargetDirectDepends(&target)) {
  1805. if (!dep->IsLanguageUsed("Swift", config)) {
  1806. continue;
  1807. }
  1808. // If the dependency emits a swiftmodule, add a dependency edge on that
  1809. // swiftmodule to the ninja build graph.
  1810. if (isImportableTarget(*dep)) {
  1811. std::string const depModuleFilepath =
  1812. this->ConvertToNinjaPath(dep->GetSwiftModulePath(config));
  1813. objBuild.ImplicitDeps.push_back(depModuleFilepath);
  1814. }
  1815. }
  1816. objBuild.OrderOnlyDeps.push_back(this->OrderDependsTargetForTarget(config));
  1817. // Write object build
  1818. this->GetGlobalGenerator()->WriteBuild(this->GetImplFileStream(fileConfig),
  1819. objBuild,
  1820. this->ForceResponseFile() ? -1 : 0);
  1821. }
  1822. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang,
  1823. const std::string& config)
  1824. {
  1825. Json::Value tdi(Json::objectValue);
  1826. tdi["language"] = lang;
  1827. tdi["compiler-id"] = this->Makefile->GetSafeDefinition(
  1828. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  1829. tdi["compiler-simulate-id"] = this->Makefile->GetSafeDefinition(
  1830. cmStrCat("CMAKE_", lang, "_SIMULATE_ID"));
  1831. tdi["compiler-frontend-variant"] = this->Makefile->GetSafeDefinition(
  1832. cmStrCat("CMAKE_", lang, "_COMPILER_FRONTEND_VARIANT"));
  1833. std::string mod_dir;
  1834. if (lang == "Fortran") {
  1835. mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  1836. this->Makefile->GetHomeOutputDirectory());
  1837. } else if (lang == "CXX") {
  1838. mod_dir = this->GetGlobalGenerator()->ExpandCFGIntDir(
  1839. cmSystemTools::CollapseFullPath(this->GeneratorTarget->ObjectDirectory),
  1840. config);
  1841. }
  1842. if (mod_dir.empty()) {
  1843. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  1844. }
  1845. tdi["module-dir"] = mod_dir;
  1846. if (lang == "Fortran") {
  1847. tdi["submodule-sep"] =
  1848. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_SEP");
  1849. tdi["submodule-ext"] =
  1850. this->Makefile->GetSafeDefinition("CMAKE_Fortran_SUBMODULE_EXT");
  1851. } else if (lang == "CXX") {
  1852. // No extra information necessary.
  1853. }
  1854. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  1855. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  1856. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  1857. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  1858. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  1859. std::vector<std::string> includes;
  1860. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  1861. lang, config);
  1862. for (std::string const& i : includes) {
  1863. // Convert the include directories the same way we do for -I flags.
  1864. // See upstream ninja issue 1251.
  1865. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  1866. }
  1867. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  1868. Json::arrayValue;
  1869. auto const linked_directories =
  1870. this->GetLinkedTargetDirectories(lang, config);
  1871. for (std::string const& l : linked_directories.Direct) {
  1872. tdi_linked_target_dirs.append(l);
  1873. }
  1874. Json::Value& tdi_forward_modules_from_target_dirs =
  1875. tdi["forward-modules-from-target-dirs"] = Json::arrayValue;
  1876. for (std::string const& l : linked_directories.Forward) {
  1877. tdi_forward_modules_from_target_dirs.append(l);
  1878. }
  1879. cmDyndepGeneratorCallbacks cb;
  1880. cb.ObjectFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1881. return this->GetObjectFilePath(sf, cnf);
  1882. };
  1883. cb.BmiFilePath = [this](cmSourceFile const* sf, std::string const& cnf) {
  1884. return this->GetBmiFilePath(sf, cnf);
  1885. };
  1886. #if !defined(CMAKE_BOOTSTRAP)
  1887. cmDyndepCollation::AddCollationInformation(tdi, this->GeneratorTarget,
  1888. config, cb);
  1889. #endif
  1890. std::string const tdin = this->GetTargetDependInfoPath(lang, config);
  1891. cmGeneratedFileStream tdif(tdin);
  1892. tdif << tdi;
  1893. }
  1894. void cmNinjaTargetGenerator::EmitSwiftDependencyInfo(
  1895. cmSourceFile const* source, const std::string& config)
  1896. {
  1897. std::string const sourceFilePath = this->GetCompiledSourceNinjaPath(source);
  1898. std::string const objectFilePath =
  1899. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1900. std::string const swiftDepsPath = [source, objectFilePath]() -> std::string {
  1901. if (cmValue name = source->GetProperty("Swift_DEPENDENCIES_FILE")) {
  1902. return *name;
  1903. }
  1904. return cmStrCat(objectFilePath, ".swiftdeps");
  1905. }();
  1906. std::string const swiftDiaPath = [source, objectFilePath]() -> std::string {
  1907. if (cmValue name = source->GetProperty("Swift_DIAGNOSTICS_FILE")) {
  1908. return *name;
  1909. }
  1910. return cmStrCat(objectFilePath, ".dia");
  1911. }();
  1912. std::string const makeDepsPath = [this, source, config]() -> std::string {
  1913. cmLocalNinjaGenerator const* local = this->GetLocalGenerator();
  1914. std::string const objectFileName =
  1915. this->ConvertToNinjaPath(this->GetObjectFilePath(source, config));
  1916. std::string const objectFileDir =
  1917. cmSystemTools::GetFilenamePath(objectFileName);
  1918. if (this->Makefile->IsOn("CMAKE_Swift_DEPFLE_EXTNSION_REPLACE")) {
  1919. std::string dependFileName = cmStrCat(
  1920. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName), ".d");
  1921. return local->ConvertToOutputFormat(
  1922. cmStrCat(objectFileDir, '/', dependFileName),
  1923. cmOutputConverter::SHELL);
  1924. }
  1925. return local->ConvertToOutputFormat(cmStrCat(objectFileName, ".d"),
  1926. cmOutputConverter::SHELL);
  1927. }();
  1928. // build the source file mapping
  1929. // https://github.com/apple/swift/blob/master/docs/Driver.md#output-file-maps
  1930. Json::Value entry = Json::Value(Json::objectValue);
  1931. entry["object"] = objectFilePath;
  1932. entry["dependencies"] = makeDepsPath;
  1933. entry["swift-dependencies"] = swiftDepsPath;
  1934. entry["diagnostics"] = swiftDiaPath;
  1935. this->Configs[config].SwiftOutputMap[sourceFilePath] = entry;
  1936. }
  1937. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  1938. std::string const& language, std::string const& sourceFileName,
  1939. std::string const& objectDir, std::string const& objectFileName,
  1940. std::string const& objectFileDir, std::string const& flags,
  1941. std::string const& defines, std::string const& includes,
  1942. std::string const& targetCompilePdb, std::string const& targetPdb,
  1943. std::string const& outputConfig, WithScanning withScanning)
  1944. {
  1945. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  1946. return;
  1947. }
  1948. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  1949. compileObjectVars.Language = language.c_str();
  1950. std::string escapedSourceFileName = sourceFileName;
  1951. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  1952. escapedSourceFileName =
  1953. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1954. this->GetGlobalGenerator()
  1955. ->GetCMakeInstance()
  1956. ->GetHomeOutputDirectory());
  1957. }
  1958. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1959. escapedSourceFileName, cmOutputConverter::SHELL);
  1960. std::string fullFlags = flags;
  1961. if (withScanning == WithScanning::Yes) {
  1962. std::string const modmapFormatVar =
  1963. cmStrCat("CMAKE_", language, "_MODULE_MAP_FORMAT");
  1964. std::string const modmapFormat =
  1965. this->Makefile->GetSafeDefinition(modmapFormatVar);
  1966. if (!modmapFormat.empty()) {
  1967. std::string modmapFlags = this->GetMakefile()->GetRequiredDefinition(
  1968. cmStrCat("CMAKE_", language, "_MODULE_MAP_FLAG"));
  1969. // XXX(modmap): If changing this path construction, change
  1970. // `cmGlobalNinjaGenerator::WriteDyndep` and
  1971. // `cmNinjaTargetGenerator::WriteObjectBuildStatement` to expect the
  1972. // corresponding file path.
  1973. cmSystemTools::ReplaceString(modmapFlags, "<MODULE_MAP_FILE>",
  1974. cmStrCat(objectFileName, ".modmap"));
  1975. fullFlags += cmStrCat(' ', modmapFlags);
  1976. }
  1977. }
  1978. compileObjectVars.Source = escapedSourceFileName.c_str();
  1979. compileObjectVars.Object = objectFileName.c_str();
  1980. compileObjectVars.ObjectDir = objectDir.c_str();
  1981. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1982. compileObjectVars.Flags = fullFlags.c_str();
  1983. compileObjectVars.Defines = defines.c_str();
  1984. compileObjectVars.Includes = includes.c_str();
  1985. compileObjectVars.TargetCompilePDB = targetCompilePdb.c_str();
  1986. compileObjectVars.TargetPDB = targetPdb.c_str();
  1987. // Rule for compiling object file.
  1988. std::string cudaCompileMode;
  1989. if (language == "CUDA") {
  1990. if (this->GeneratorTarget->GetPropertyAsBool(
  1991. "CUDA_SEPARABLE_COMPILATION")) {
  1992. const std::string& rdcFlag =
  1993. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_RDC_FLAG");
  1994. cudaCompileMode = cmStrCat(cudaCompileMode, rdcFlag, " ");
  1995. }
  1996. static std::array<cm::string_view, 4> const compileModes{
  1997. { "PTX"_s, "CUBIN"_s, "FATBIN"_s, "OPTIX"_s }
  1998. };
  1999. bool useNormalCompileMode = true;
  2000. for (cm::string_view mode : compileModes) {
  2001. auto propName = cmStrCat("CUDA_", mode, "_COMPILATION");
  2002. auto defName = cmStrCat("_CMAKE_CUDA_", mode, "_FLAG");
  2003. if (this->GeneratorTarget->GetPropertyAsBool(propName)) {
  2004. const std::string& flag =
  2005. this->Makefile->GetRequiredDefinition(defName);
  2006. cudaCompileMode = cmStrCat(cudaCompileMode, flag);
  2007. useNormalCompileMode = false;
  2008. break;
  2009. }
  2010. }
  2011. if (useNormalCompileMode) {
  2012. const std::string& wholeFlag =
  2013. this->Makefile->GetRequiredDefinition("_CMAKE_CUDA_WHOLE_FLAG");
  2014. cudaCompileMode = cmStrCat(cudaCompileMode, wholeFlag);
  2015. }
  2016. compileObjectVars.CudaCompileMode = cudaCompileMode.c_str();
  2017. }
  2018. const std::string cmdVar = cmStrCat("CMAKE_", language, "_COMPILE_OBJECT");
  2019. const std::string& compileCmd =
  2020. this->Makefile->GetRequiredDefinition(cmdVar);
  2021. cmList compileCmds(compileCmd);
  2022. auto rulePlaceholderExpander =
  2023. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  2024. for (auto& i : compileCmds) {
  2025. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  2026. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  2027. compileObjectVars);
  2028. }
  2029. std::string cmdLine = this->GetLocalGenerator()->BuildCommandLine(
  2030. compileCmds, outputConfig, outputConfig);
  2031. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName,
  2032. objectFileName);
  2033. }
  2034. void cmNinjaTargetGenerator::ExportSwiftObjectCompileCommand(
  2035. std::vector<cmSourceFile const*> const& moduleSourceFiles,
  2036. std::string const& moduleObjectFilename, std::string const& flags,
  2037. std::string const& defines, std::string const& includes,
  2038. std::string const& outputConfig, bool singleOutput)
  2039. {
  2040. if (!this->GeneratorTarget->GetPropertyAsBool("EXPORT_COMPILE_COMMANDS")) {
  2041. return;
  2042. }
  2043. auto escapeSourceFileName = [this](std::string srcFilename) -> std::string {
  2044. if (!cmSystemTools::FileIsFullPath(srcFilename)) {
  2045. srcFilename =
  2046. cmSystemTools::CollapseFullPath(srcFilename,
  2047. this->GetGlobalGenerator()
  2048. ->GetCMakeInstance()
  2049. ->GetHomeOutputDirectory());
  2050. }
  2051. return this->LocalGenerator->ConvertToOutputFormat(
  2052. srcFilename, cmOutputConverter::SHELL);
  2053. };
  2054. auto escapedModuleObjectFilename =
  2055. this->ConvertToNinjaPath(moduleObjectFilename);
  2056. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2057. compileObjectVars.Language = "Swift";
  2058. compileObjectVars.Flags = flags.c_str();
  2059. compileObjectVars.Defines = defines.c_str();
  2060. compileObjectVars.Includes = includes.c_str();
  2061. // Build up the list of source files in the module
  2062. std::vector<std::string> filenames;
  2063. filenames.reserve(moduleSourceFiles.size());
  2064. for (cmSourceFile const* sf : moduleSourceFiles) {
  2065. filenames.emplace_back(
  2066. escapeSourceFileName(this->GetCompiledSourceNinjaPath(sf)));
  2067. }
  2068. // Note that `escapedSourceFilenames` must remain alive until the
  2069. // compileObjectVars is consumed or Source will be a dangling pointer.
  2070. std::string const escapedSourceFilenames = cmJoin(filenames, " ");
  2071. compileObjectVars.Source = escapedSourceFilenames.c_str();
  2072. std::string const& compileCommand =
  2073. this->Makefile->GetRequiredDefinition("CMAKE_Swift_COMPILE_OBJECT");
  2074. cmList compileCmds(compileCommand);
  2075. auto rulePlaceholderExpander =
  2076. this->GetLocalGenerator()->CreateRulePlaceholderExpander();
  2077. for (cmSourceFile const* sf : moduleSourceFiles) {
  2078. std::string const sourceFilename = this->GetCompiledSourceNinjaPath(sf);
  2079. std::string objectFilename = escapedModuleObjectFilename;
  2080. if (!singleOutput) {
  2081. // If it's not single-output, each source file gets a separate object
  2082. objectFilename =
  2083. this->ConvertToNinjaPath(this->GetObjectFilePath(sf, outputConfig));
  2084. }
  2085. compileObjectVars.Objects = objectFilename.c_str();
  2086. for (std::string& cmd : compileCmds) {
  2087. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  2088. cmd, compileObjectVars);
  2089. }
  2090. std::string commandLine = this->GetLocalGenerator()->BuildCommandLine(
  2091. compileCmds, outputConfig, outputConfig);
  2092. this->GetGlobalGenerator()->AddCXXCompileCommand(
  2093. commandLine, sourceFilename, objectFilename);
  2094. }
  2095. }
  2096. void cmNinjaTargetGenerator::AdditionalCleanFiles(const std::string& config)
  2097. {
  2098. if (cmValue prop_value =
  2099. this->GeneratorTarget->GetProperty("ADDITIONAL_CLEAN_FILES")) {
  2100. cmLocalNinjaGenerator* lg = this->LocalGenerator;
  2101. cmList cleanFiles(cmGeneratorExpression::Evaluate(*prop_value, lg, config,
  2102. this->GeneratorTarget));
  2103. std::string const& binaryDir = lg->GetCurrentBinaryDirectory();
  2104. cmGlobalNinjaGenerator* gg = lg->GetGlobalNinjaGenerator();
  2105. for (auto const& cleanFile : cleanFiles) {
  2106. // Support relative paths
  2107. gg->AddAdditionalCleanFile(
  2108. cmSystemTools::CollapseFullPath(cleanFile, binaryDir), config);
  2109. }
  2110. }
  2111. }
  2112. cmNinjaDeps cmNinjaTargetGenerator::GetObjects(const std::string& config) const
  2113. {
  2114. auto const it = this->Configs.find(config);
  2115. if (it != this->Configs.end()) {
  2116. return it->second.Objects;
  2117. }
  2118. return {};
  2119. }
  2120. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  2121. const std::string& path) const
  2122. {
  2123. if (cmSystemTools::FileIsFullPath(path)) {
  2124. cmSystemTools::MakeDirectory(path);
  2125. } else {
  2126. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  2127. std::string fullPath = gg->GetCMakeInstance()->GetHomeOutputDirectory();
  2128. // Also ensures there is a trailing slash.
  2129. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  2130. fullPath += path;
  2131. cmSystemTools::MakeDirectory(fullPath);
  2132. }
  2133. }
  2134. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  2135. const std::string& path) const
  2136. {
  2137. this->EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  2138. }
  2139. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  2140. cmSourceFile const& source, const char* pkgloc, const std::string& config)
  2141. {
  2142. // Skip OS X content when not building a Framework or Bundle.
  2143. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  2144. return;
  2145. }
  2146. std::string macdir =
  2147. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc,
  2148. config);
  2149. // Reject files that collide with files from the Ninja file's native config.
  2150. if (config != this->FileConfig) {
  2151. std::string nativeMacdir =
  2152. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(
  2153. pkgloc, this->FileConfig);
  2154. if (macdir == nativeMacdir) {
  2155. return;
  2156. }
  2157. }
  2158. // Get the input file location.
  2159. std::string input = source.GetFullPath();
  2160. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  2161. // Get the output file location.
  2162. std::string output =
  2163. cmStrCat(macdir, '/', cmSystemTools::GetFilenameName(input));
  2164. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  2165. // Write a build statement to copy the content into the bundle.
  2166. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(
  2167. input, output, this->FileConfig);
  2168. // Add as a dependency to the target so that it gets called.
  2169. this->Generator->Configs[config].ExtraFiles.push_back(std::move(output));
  2170. }
  2171. void cmNinjaTargetGenerator::AddDepfileBinding(cmNinjaVars& vars,
  2172. std::string depfile) const
  2173. {
  2174. std::string depfileForShell =
  2175. this->GetLocalGenerator()->ConvertToOutputFormat(depfile,
  2176. cmOutputConverter::SHELL);
  2177. if (depfile != depfileForShell) {
  2178. vars["depfile"] = std::move(depfile);
  2179. }
  2180. vars["DEP_FILE"] = std::move(depfileForShell);
  2181. }
  2182. void cmNinjaTargetGenerator::RemoveDepfileBinding(cmNinjaVars& vars) const
  2183. {
  2184. vars.erase("DEP_FILE");
  2185. vars.erase("depfile");
  2186. }
  2187. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  2188. const std::string& pool_property, cmGeneratorTarget* target,
  2189. cmNinjaVars& vars)
  2190. {
  2191. cmValue pool = target->GetProperty(pool_property);
  2192. if (pool) {
  2193. vars["pool"] = *pool;
  2194. }
  2195. }
  2196. bool cmNinjaTargetGenerator::ForceResponseFile()
  2197. {
  2198. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  2199. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  2200. cmSystemTools::HasEnv(forceRspFile));
  2201. }