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 : target->Makefile->GetGeneratorConfigs()) {
  61. this->Configs[fileConfig].MacOSXContentGenerator =
  62. cm::make_unique<MacOSXContentGeneratorType>(this, fileConfig);
  63. }
  64. }
  65. cmNinjaTargetGenerator::~cmNinjaTargetGenerator() = default;
  66. cmGeneratedFileStream& cmNinjaTargetGenerator::GetImplFileStream(
  67. const std::string& config) const
  68. {
  69. return *this->GetGlobalGenerator()->GetImplFileStream(config);
  70. }
  71. cmGeneratedFileStream& cmNinjaTargetGenerator::GetCommonFileStream() const
  72. {
  73. return *this->GetGlobalGenerator()->GetCommonFileStream();
  74. }
  75. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  76. {
  77. return *this->GetGlobalGenerator()->GetRulesFileStream();
  78. }
  79. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  80. {
  81. return this->LocalGenerator->GetGlobalNinjaGenerator();
  82. }
  83. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  84. const std::string& lang, const std::string& config) const
  85. {
  86. return cmStrCat(
  87. lang, "_COMPILER__",
  88. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  89. '_', config);
  90. }
  91. std::string cmNinjaTargetGenerator::LanguagePreprocessRule(
  92. std::string const& lang, const std::string& config) const
  93. {
  94. return cmStrCat(
  95. lang, "_PREPROCESS_SCAN__",
  96. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  97. '_', config);
  98. }
  99. std::string cmNinjaTargetGenerator::LanguageDependencyRule(
  100. std::string const& lang, const std::string& config) const
  101. {
  102. return cmStrCat(
  103. lang, "_SCAN__",
  104. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  105. '_', config);
  106. }
  107. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  108. std::string const& lang) const
  109. {
  110. return lang == "Fortran";
  111. }
  112. bool cmNinjaTargetGenerator::UsePreprocessedSource(
  113. std::string const& lang) const
  114. {
  115. return lang == "Fortran";
  116. }
  117. bool cmNinjaTargetGenerator::CompilePreprocessedSourceWithDefines(
  118. std::string const& lang) const
  119. {
  120. return this->Makefile->IsOn(
  121. cmStrCat("CMAKE_", lang, "_COMPILE_WITH_DEFINES"));
  122. }
  123. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  124. const std::string& lang, const std::string& config) const
  125. {
  126. return cmStrCat(
  127. lang, "_DYNDEP__",
  128. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName()),
  129. '_', config);
  130. }
  131. bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const
  132. {
  133. return lang == "Fortran";
  134. }
  135. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget(
  136. const std::string& config)
  137. {
  138. return this->GetGlobalGenerator()->OrderDependsTargetForTarget(
  139. this->GeneratorTarget, config);
  140. }
  141. // TODO: Most of the code is picked up from
  142. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  143. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  144. // Refactor it.
  145. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  146. cmSourceFile const* source, const std::string& language,
  147. const std::string& config)
  148. {
  149. std::vector<std::string> architectures;
  150. std::unordered_map<std::string, std::string> pchSources;
  151. this->GeneratorTarget->GetAppleArchs(config, architectures);
  152. if (architectures.empty()) {
  153. architectures.emplace_back();
  154. }
  155. std::string filterArch;
  156. for (const std::string& arch : architectures) {
  157. const std::string pchSource =
  158. this->GeneratorTarget->GetPchSource(config, language, arch);
  159. if (pchSource == source->GetFullPath()) {
  160. filterArch = arch;
  161. }
  162. if (!pchSource.empty()) {
  163. pchSources.insert(std::make_pair(pchSource, arch));
  164. }
  165. }
  166. std::string flags;
  167. // explicitly add the explicit language flag before any other flag
  168. // this way backwards compatibility with user flags is maintained
  169. if (source->GetProperty("LANGUAGE")) {
  170. this->LocalGenerator->AppendFeatureOptions(flags, language,
  171. "EXPLICIT_LANGUAGE");
  172. flags += " ";
  173. }
  174. flags += this->GetFlags(language, config, filterArch);
  175. // Add Fortran format flags.
  176. if (language == "Fortran") {
  177. this->AppendFortranFormatFlags(flags, *source);
  178. this->AppendFortranPreprocessFlags(flags, *source);
  179. }
  180. // Add source file specific flags.
  181. cmGeneratorExpressionInterpreter genexInterpreter(
  182. this->LocalGenerator, config, this->GeneratorTarget, language);
  183. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  184. if (cmProp cflags = source->GetProperty(COMPILE_FLAGS)) {
  185. this->LocalGenerator->AppendFlags(
  186. flags, genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  187. }
  188. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  189. if (cmProp coptions = source->GetProperty(COMPILE_OPTIONS)) {
  190. this->LocalGenerator->AppendCompileOptions(
  191. flags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  192. }
  193. // Add precompile headers compile options.
  194. if (!pchSources.empty() && !source->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  195. std::string pchOptions;
  196. auto pchIt = pchSources.find(source->GetFullPath());
  197. if (pchIt != pchSources.end()) {
  198. pchOptions = this->GeneratorTarget->GetPchCreateCompileOptions(
  199. config, language, pchIt->second);
  200. } else {
  201. pchOptions =
  202. this->GeneratorTarget->GetPchUseCompileOptions(config, language);
  203. }
  204. this->LocalGenerator->AppendCompileOptions(
  205. flags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  206. }
  207. return flags;
  208. }
  209. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  210. std::string const& language,
  211. const std::string& config)
  212. {
  213. std::vector<std::string> includes;
  214. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  215. language, config);
  216. // Add include directory flags.
  217. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  218. includes, this->GeneratorTarget, language,
  219. language == "RC", // full include paths for RC needed by cmcldeps
  220. false, config);
  221. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  222. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  223. }
  224. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  225. }
  226. bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const
  227. {
  228. std::string const& deptype = this->GetMakefile()->GetSafeDefinition(
  229. cmStrCat("CMAKE_NINJA_DEPTYPE_", lang));
  230. if (deptype == "msvc") {
  231. return true;
  232. }
  233. if (deptype == "intel") {
  234. // Ninja does not really define "intel", but we use it to switch based
  235. // on whether this environment supports "gcc" or "msvc" deptype.
  236. if (!this->GetGlobalGenerator()->SupportsMultilineDepfile()) {
  237. // This ninja version is too old to support the Intel depfile format.
  238. // Fall back to msvc deptype.
  239. return true;
  240. }
  241. if ((this->Makefile->GetHomeDirectory().find(' ') != std::string::npos) ||
  242. (this->Makefile->GetHomeOutputDirectory().find(' ') !=
  243. std::string::npos)) {
  244. // The Intel compiler does not properly escape spaces in a depfile.
  245. // Fall back to msvc deptype.
  246. return true;
  247. }
  248. }
  249. return false;
  250. }
  251. // TODO: Refactor with
  252. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  253. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  254. const std::string& language,
  255. const std::string& config)
  256. {
  257. std::set<std::string> defines;
  258. cmGeneratorExpressionInterpreter genexInterpreter(
  259. this->LocalGenerator, config, this->GeneratorTarget, language);
  260. // Seriously??
  261. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  262. defines.insert(cmStrCat("CMAKE_INTDIR=\"", config, '"'));
  263. }
  264. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  265. if (cmProp compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  266. this->LocalGenerator->AppendDefines(
  267. defines, genexInterpreter.Evaluate(*compile_defs, COMPILE_DEFINITIONS));
  268. }
  269. std::string defPropName =
  270. cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
  271. if (cmProp config_compile_defs = source->GetProperty(defPropName)) {
  272. this->LocalGenerator->AppendDefines(
  273. defines,
  274. genexInterpreter.Evaluate(*config_compile_defs, COMPILE_DEFINITIONS));
  275. }
  276. std::string definesString = this->GetDefines(language, config);
  277. this->LocalGenerator->JoinDefines(defines, definesString, language);
  278. return definesString;
  279. }
  280. std::string cmNinjaTargetGenerator::ComputeIncludes(
  281. cmSourceFile const* source, const std::string& language,
  282. const std::string& config)
  283. {
  284. std::vector<std::string> includes;
  285. cmGeneratorExpressionInterpreter genexInterpreter(
  286. this->LocalGenerator, config, this->GeneratorTarget, language);
  287. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  288. if (cmProp cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  289. this->LocalGenerator->AppendIncludeDirectories(
  290. includes, genexInterpreter.Evaluate(*cincludes, INCLUDE_DIRECTORIES),
  291. *source);
  292. }
  293. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  294. includes, this->GeneratorTarget, language, true, false, config);
  295. this->LocalGenerator->AppendFlags(includesString,
  296. this->GetIncludes(language, config));
  297. return includesString;
  298. }
  299. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  300. const std::string& linkLanguage, const std::string& config) const
  301. {
  302. // Static libraries never depend on other targets for linking.
  303. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  304. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  305. return cmNinjaDeps();
  306. }
  307. cmComputeLinkInformation* cli =
  308. this->GeneratorTarget->GetLinkInformation(config);
  309. if (!cli) {
  310. return cmNinjaDeps();
  311. }
  312. const std::vector<std::string>& deps = cli->GetDepends();
  313. cmNinjaDeps result(deps.size());
  314. std::transform(deps.begin(), deps.end(), result.begin(), MapToNinjaPath());
  315. // Add a dependency on the link definitions file, if any.
  316. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  317. this->GeneratorTarget->GetModuleDefinitionInfo(config)) {
  318. for (cmSourceFile const* src : mdi->Sources) {
  319. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  320. }
  321. }
  322. // Add a dependency on user-specified manifest files, if any.
  323. std::vector<cmSourceFile const*> manifest_srcs;
  324. this->GeneratorTarget->GetManifests(manifest_srcs, config);
  325. for (cmSourceFile const* manifest_src : manifest_srcs) {
  326. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  327. }
  328. // Add user-specified dependencies.
  329. std::vector<std::string> linkDeps;
  330. this->GeneratorTarget->GetLinkDepends(linkDeps, config, linkLanguage);
  331. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  332. MapToNinjaPath());
  333. return result;
  334. }
  335. std::string cmNinjaTargetGenerator::GetSourceFilePath(
  336. cmSourceFile const* source) const
  337. {
  338. return ConvertToNinjaPath(source->GetFullPath());
  339. }
  340. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  341. cmSourceFile const* source, const std::string& config) const
  342. {
  343. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  344. if (!path.empty()) {
  345. path += '/';
  346. }
  347. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  348. path += cmStrCat(
  349. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  350. this->GetGlobalGenerator()->ConfigDirectory(config), '/', objectName);
  351. return path;
  352. }
  353. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  354. cmSourceFile const* source, const std::string& config) const
  355. {
  356. // Choose an extension to compile already-preprocessed source.
  357. std::string ppExt = source->GetExtension();
  358. if (cmHasLiteralPrefix(ppExt, "F")) {
  359. // Some Fortran compilers automatically enable preprocessing for
  360. // upper-case extensions. Since the source is already preprocessed,
  361. // use a lower-case extension.
  362. ppExt = cmSystemTools::LowerCase(ppExt);
  363. }
  364. if (ppExt == "fpp") {
  365. // Some Fortran compilers automatically enable preprocessing for
  366. // the ".fpp" extension. Since the source is already preprocessed,
  367. // use the ".f" extension.
  368. ppExt = "f";
  369. }
  370. // Take the object file name and replace the extension.
  371. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  372. std::string const& objExt =
  373. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  374. assert(objName.size() >= objExt.size());
  375. std::string const ppName =
  376. cmStrCat(objName.substr(0, objName.size() - objExt.size()), "-pp.", ppExt);
  377. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  378. if (!path.empty()) {
  379. path += '/';
  380. }
  381. path +=
  382. cmStrCat(this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  383. this->GetGlobalGenerator()->ConfigDirectory(config), '/', ppName);
  384. return path;
  385. }
  386. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  387. std::string const& lang, const std::string& config) const
  388. {
  389. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  390. if (!path.empty()) {
  391. path += '/';
  392. }
  393. path += cmStrCat(
  394. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  395. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang, ".dd");
  396. return path;
  397. }
  398. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  399. std::string const& lang, const std::string& config) const
  400. {
  401. std::string path =
  402. cmStrCat(this->Makefile->GetCurrentBinaryDirectory(), '/',
  403. this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget),
  404. this->GetGlobalGenerator()->ConfigDirectory(config), '/', lang,
  405. "DependInfo.json");
  406. return path;
  407. }
  408. std::string cmNinjaTargetGenerator::GetTargetOutputDir(
  409. const std::string& config) const
  410. {
  411. std::string dir = this->GeneratorTarget->GetDirectory(config);
  412. return ConvertToNinjaPath(dir);
  413. }
  414. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  415. const std::string& name, const std::string& config) const
  416. {
  417. std::string path = this->GetTargetOutputDir(config);
  418. if (path.empty() || path == ".") {
  419. return name;
  420. }
  421. path += cmStrCat('/', name);
  422. return path;
  423. }
  424. std::string cmNinjaTargetGenerator::GetTargetName() const
  425. {
  426. return this->GeneratorTarget->GetName();
  427. }
  428. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(
  429. cmNinjaVars& vars, const std::string& config) const
  430. {
  431. cmMakefile* mf = this->GetMakefile();
  432. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  433. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  434. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  435. std::string pdbPath;
  436. std::string compilePdbPath = this->ComputeTargetCompilePDB(config);
  437. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  438. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  439. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  440. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  441. pdbPath = cmStrCat(this->GeneratorTarget->GetPDBDirectory(config), '/',
  442. this->GeneratorTarget->GetPDBName(config));
  443. }
  444. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  445. ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  446. vars["TARGET_COMPILE_PDB"] =
  447. this->GetLocalGenerator()->ConvertToOutputFormat(
  448. ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  449. EnsureParentDirectoryExists(pdbPath);
  450. EnsureParentDirectoryExists(compilePdbPath);
  451. return true;
  452. }
  453. return false;
  454. }
  455. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language,
  456. const std::string& config)
  457. {
  458. #ifdef NINJA_GEN_VERBOSE_FILES
  459. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  460. #endif
  461. this->WriteCompileRule(language, config);
  462. }
  463. namespace {
  464. // Create the command to run the dependency scanner
  465. std::string GetScanCommand(const std::string& cmakeCmd, const std::string& tdi,
  466. const std::string& lang, const std::string& ppFile,
  467. bool needDyndep, const std::string& ddiFile)
  468. {
  469. std::string ccmd =
  470. cmStrCat(cmakeCmd, " -E cmake_ninja_depends --tdi=", tdi, " --lang=", lang,
  471. " --pp=", ppFile, " --dep=$DEP_FILE");
  472. if (needDyndep) {
  473. ccmd = cmStrCat(ccmd, " --obj=$OBJ_FILE --ddi=", ddiFile);
  474. }
  475. return ccmd;
  476. }
  477. // Helper function to create dependency scanning rule, with optional
  478. // explicit preprocessing step if preprocessCommand is non-empty
  479. cmNinjaRule GetPreprocessScanRule(
  480. const std::string& ruleName, cmRulePlaceholderExpander::RuleVariables& vars,
  481. const std::string& responseFlag, const std::string& flags,
  482. const std::string& launcher,
  483. cmRulePlaceholderExpander* const rulePlaceholderExpander,
  484. std::string scanCommand, cmLocalNinjaGenerator* generator,
  485. const std::string& preprocessCommand = "")
  486. {
  487. cmNinjaRule rule(ruleName);
  488. // Explicit preprocessing always uses a depfile.
  489. rule.DepType = ""; // no deps= for multiple outputs
  490. rule.DepFile = "$DEP_FILE";
  491. cmRulePlaceholderExpander::RuleVariables ppVars;
  492. ppVars.CMTargetName = vars.CMTargetName;
  493. ppVars.CMTargetType = vars.CMTargetType;
  494. ppVars.Language = vars.Language;
  495. ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
  496. ppVars.PreprocessedSource = "$out";
  497. ppVars.DependencyFile = rule.DepFile.c_str();
  498. // Preprocessing uses the original source, compilation uses
  499. // preprocessed output or original source
  500. ppVars.Source = vars.Source;
  501. vars.Source = "$in";
  502. // Copy preprocessor definitions to the preprocessor rule.
  503. ppVars.Defines = vars.Defines;
  504. // Copy include directories to the preprocessor rule. The Fortran
  505. // compilation rule still needs them for the INCLUDE directive.
  506. ppVars.Includes = vars.Includes;
  507. // Preprocessing and compilation use the same flags.
  508. std::string ppFlags = flags;
  509. // If using a response file, move defines, includes, and flags into it.
  510. if (!responseFlag.empty()) {
  511. rule.RspFile = "$RSP_FILE";
  512. rule.RspContent =
  513. cmStrCat(' ', ppVars.Defines, ' ', ppVars.Includes, ' ', ppFlags);
  514. ppFlags = cmStrCat(responseFlag, rule.RspFile);
  515. ppVars.Defines = "";
  516. ppVars.Includes = "";
  517. }
  518. ppVars.Flags = ppFlags.c_str();
  519. // Rule for preprocessing source file.
  520. std::vector<std::string> ppCmds;
  521. if (!preprocessCommand.empty()) {
  522. // Lookup the explicit preprocessing rule.
  523. cmExpandList(preprocessCommand, ppCmds);
  524. for (std::string& i : ppCmds) {
  525. i = cmStrCat(launcher, i);
  526. rulePlaceholderExpander->ExpandRuleVariables(generator, i, ppVars);
  527. }
  528. }
  529. // Run CMake dependency scanner on either preprocessed output or source file
  530. ppCmds.emplace_back(std::move(scanCommand));
  531. rule.Command = generator->BuildCommandLine(ppCmds);
  532. return rule;
  533. }
  534. }
  535. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang,
  536. const std::string& config)
  537. {
  538. cmRulePlaceholderExpander::RuleVariables vars;
  539. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  540. vars.CMTargetType =
  541. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType()).c_str();
  542. vars.Language = lang.c_str();
  543. vars.Source = "$in";
  544. vars.Object = "$out";
  545. vars.Defines = "$DEFINES";
  546. vars.Includes = "$INCLUDES";
  547. vars.TargetPDB = "$TARGET_PDB";
  548. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  549. vars.ObjectDir = "$OBJECT_DIR";
  550. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  551. cmMakefile* mf = this->GetMakefile();
  552. // For some cases we do an explicit preprocessor invocation.
  553. bool const explicitPP = this->NeedExplicitPreprocessing(lang);
  554. bool const compilePPWithDefines = this->UsePreprocessedSource(lang) &&
  555. this->CompilePreprocessedSourceWithDefines(lang);
  556. bool const needDyndep = this->NeedDyndep(lang);
  557. std::string flags = "$FLAGS";
  558. std::string responseFlag;
  559. bool const lang_supports_response = lang != "RC";
  560. if (lang_supports_response && this->ForceResponseFile()) {
  561. std::string const responseFlagVar =
  562. cmStrCat("CMAKE_", lang, "_RESPONSE_FILE_FLAG");
  563. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  564. if (responseFlag.empty() && lang != "CUDA") {
  565. responseFlag = "@";
  566. }
  567. }
  568. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  569. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  570. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  571. ConvertToNinjaPath(this->GetTargetDependInfoPath(lang, config)),
  572. cmLocalGenerator::SHELL);
  573. std::string launcher;
  574. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  575. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  576. if (val && *val) {
  577. launcher = cmStrCat(val, ' ');
  578. }
  579. std::string const cmakeCmd =
  580. this->GetLocalGenerator()->ConvertToOutputFormat(
  581. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  582. if (explicitPP) {
  583. // Combined preprocessing and dependency scanning
  584. const auto ppScanCommand = GetScanCommand(
  585. cmakeCmd, tdi, lang, "$out", needDyndep, "$DYNDEP_INTERMEDIATE_FILE");
  586. const auto ppVar = cmStrCat("CMAKE_", lang, "_PREPROCESS_SOURCE");
  587. auto ppRule = GetPreprocessScanRule(
  588. this->LanguagePreprocessRule(lang, config), vars, responseFlag, flags,
  589. launcher, rulePlaceholderExpander.get(), ppScanCommand,
  590. this->GetLocalGenerator(), mf->GetRequiredDefinition(ppVar));
  591. // Write the rule for preprocessing file of the given language.
  592. ppRule.Comment = cmStrCat("Rule for preprocessing ", lang, " files.");
  593. ppRule.Description = cmStrCat("Building ", lang, " preprocessed $out");
  594. this->GetGlobalGenerator()->AddRule(ppRule);
  595. if (!compilePPWithDefines) {
  596. // Remove preprocessor definitions from compilation step
  597. vars.Defines = "";
  598. }
  599. // Just dependency scanning for files that have preprocessing turned off
  600. const auto scanCommand =
  601. GetScanCommand(cmakeCmd, tdi, lang, "$in", needDyndep, "$out");
  602. auto scanRule = GetPreprocessScanRule(
  603. this->LanguageDependencyRule(lang, config), vars, "", flags, launcher,
  604. rulePlaceholderExpander.get(), scanCommand, this->GetLocalGenerator());
  605. // Write the rule for generating dependencies for the given language.
  606. scanRule.Comment = cmStrCat("Rule for generating ", lang,
  607. " dependencies on non-preprocessed files.");
  608. scanRule.Description =
  609. cmStrCat("Generating ", lang, " dependencies for $in");
  610. this->GetGlobalGenerator()->AddRule(scanRule);
  611. }
  612. if (needDyndep) {
  613. // Write the rule for ninja dyndep file generation.
  614. cmNinjaRule rule(this->LanguageDyndepRule(lang, config));
  615. // Command line length is almost always limited -> use response file for
  616. // dyndep rules
  617. rule.RspFile = "$out.rsp";
  618. rule.RspContent = "$in";
  619. // Run CMake dependency scanner on the source file (using the preprocessed
  620. // source if that was performed).
  621. {
  622. std::vector<std::string> ddCmds;
  623. {
  624. std::string ccmd =
  625. cmStrCat(cmakeCmd, " -E cmake_ninja_dyndep --tdi=", tdi,
  626. " --lang=", lang, " --dd=$out @", rule.RspFile);
  627. ddCmds.emplace_back(std::move(ccmd));
  628. }
  629. rule.Command = this->GetLocalGenerator()->BuildCommandLine(ddCmds);
  630. }
  631. rule.Comment =
  632. cmStrCat("Rule to generate ninja dyndep files for ", lang, '.');
  633. rule.Description = cmStrCat("Generating ", lang, " dyndep file $out");
  634. this->GetGlobalGenerator()->AddRule(rule);
  635. }
  636. cmNinjaRule rule(this->LanguageCompilerRule(lang, config));
  637. // If using a response file, move defines, includes, and flags into it.
  638. if (!responseFlag.empty()) {
  639. rule.RspFile = "$RSP_FILE";
  640. rule.RspContent =
  641. cmStrCat(' ', vars.Defines, ' ', vars.Includes, ' ', flags);
  642. flags = cmStrCat(responseFlag, rule.RspFile);
  643. vars.Defines = "";
  644. vars.Includes = "";
  645. }
  646. // Tell ninja dependency format so all deps can be loaded into a database
  647. std::string cldeps;
  648. if (explicitPP) {
  649. // The explicit preprocessing step will handle dependency scanning.
  650. } else if (this->NeedDepTypeMSVC(lang)) {
  651. rule.DepType = "msvc";
  652. rule.DepFile.clear();
  653. flags += " /showIncludes";
  654. } else if (mf->IsOn(cmStrCat("CMAKE_NINJA_CMCLDEPS_", lang))) {
  655. // For the MS resource compiler we need cmcldeps, but skip dependencies
  656. // for source-file try_compile cases because they are always fresh.
  657. if (!mf->GetIsSourceFileTryCompile()) {
  658. rule.DepType = "gcc";
  659. rule.DepFile = "$DEP_FILE";
  660. auto d = mf->GetDefinition("CMAKE_C_COMPILER");
  661. const std::string cl =
  662. d ? d : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  663. cldeps = cmStrCat('"', cmSystemTools::GetCMClDepsCommand(), "\" ", lang,
  664. ' ', vars.Source, " $DEP_FILE $out \"",
  665. mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX"),
  666. "\" \"", cl, "\" ");
  667. }
  668. } else {
  669. rule.DepType = "gcc";
  670. rule.DepFile = "$DEP_FILE";
  671. const std::string flagsName = cmStrCat("CMAKE_DEPFILE_FLAGS_", lang);
  672. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  673. if (!depfileFlags.empty()) {
  674. cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
  675. cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out");
  676. cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>",
  677. 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 == "OBJC" || lang == "OBJCXX")) {
  708. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  709. cmProp clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  710. if (clauncher && !clauncher->empty()) {
  711. compilerLauncher = *clauncher;
  712. }
  713. }
  714. // Maybe insert an include-what-you-use runner.
  715. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
  716. std::string const iwyu_prop = cmStrCat(lang, "_INCLUDE_WHAT_YOU_USE");
  717. cmProp iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  718. std::string const tidy_prop = cmStrCat(lang, "_CLANG_TIDY");
  719. cmProp tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  720. std::string const cpplint_prop = cmStrCat(lang, "_CPPLINT");
  721. cmProp cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  722. std::string const cppcheck_prop = cmStrCat(lang, "_CPPCHECK");
  723. cmProp cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  724. if ((iwyu && !iwyu->empty()) || (tidy && !tidy->empty()) ||
  725. (cpplint && !cpplint->empty()) || (cppcheck && !cppcheck->empty())) {
  726. std::string run_iwyu = cmStrCat(cmakeCmd, " -E __run_co_compile");
  727. if (!compilerLauncher.empty()) {
  728. // In __run_co_compile case the launcher command is supplied
  729. // via --launcher=<maybe-list> and consumed
  730. run_iwyu +=
  731. cmStrCat(" --launcher=",
  732. this->LocalGenerator->EscapeForShell(compilerLauncher));
  733. compilerLauncher.clear();
  734. }
  735. if (iwyu && !iwyu->empty()) {
  736. run_iwyu += cmStrCat(" --iwyu=",
  737. this->GetLocalGenerator()->EscapeForShell(*iwyu));
  738. }
  739. if (tidy && !tidy->empty()) {
  740. run_iwyu += " --tidy=";
  741. const char* driverMode = this->Makefile->GetDefinition(
  742. cmStrCat("CMAKE_", lang, "_CLANG_TIDY_DRIVER_MODE"));
  743. if (!(driverMode && *driverMode)) {
  744. driverMode = lang == "C" ? "gcc" : "g++";
  745. }
  746. run_iwyu += this->GetLocalGenerator()->EscapeForShell(
  747. cmStrCat(*tidy, ";--extra-arg-before=--driver-mode=", driverMode));
  748. }
  749. if (cpplint && !cpplint->empty()) {
  750. run_iwyu += cmStrCat(
  751. " --cpplint=", this->GetLocalGenerator()->EscapeForShell(*cpplint));
  752. }
  753. if (cppcheck && !cppcheck->empty()) {
  754. run_iwyu +=
  755. cmStrCat(" --cppcheck=",
  756. this->GetLocalGenerator()->EscapeForShell(*cppcheck));
  757. }
  758. if ((tidy && !tidy->empty()) || (cpplint && !cpplint->empty()) ||
  759. (cppcheck && !cppcheck->empty())) {
  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. }