cmNinjaTargetGenerator.cxx 63 KB

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