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