cmNinjaTargetGenerator.cxx 63 KB

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