cmNinjaTargetGenerator.cxx 61 KB

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