cmNinjaTargetGenerator.cxx 63 KB

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