cmNinjaTargetGenerator.cxx 61 KB

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