cmNinjaTargetGenerator.cxx 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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 "cm_jsoncpp_value.h"
  5. #include "cm_jsoncpp_writer.h"
  6. #include <algorithm>
  7. #include <assert.h>
  8. #include <iterator>
  9. #include <map>
  10. #include <memory> // IWYU pragma: keep
  11. #include <sstream>
  12. #include "cmAlgorithms.h"
  13. #include "cmComputeLinkInformation.h"
  14. #include "cmCustomCommandGenerator.h"
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGeneratorExpression.h"
  17. #include "cmGeneratorTarget.h"
  18. #include "cmGlobalNinjaGenerator.h"
  19. #include "cmLocalGenerator.h"
  20. #include "cmLocalNinjaGenerator.h"
  21. #include "cmMakefile.h"
  22. #include "cmNinjaNormalTargetGenerator.h"
  23. #include "cmNinjaUtilityTargetGenerator.h"
  24. #include "cmOutputConverter.h"
  25. #include "cmRulePlaceholderExpander.h"
  26. #include "cmSourceFile.h"
  27. #include "cmState.h"
  28. #include "cmStateTypes.h"
  29. #include "cmSystemTools.h"
  30. #include "cmake.h"
  31. cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
  32. {
  33. switch (target->GetType()) {
  34. case cmStateEnums::EXECUTABLE:
  35. case cmStateEnums::SHARED_LIBRARY:
  36. case cmStateEnums::STATIC_LIBRARY:
  37. case cmStateEnums::MODULE_LIBRARY:
  38. case cmStateEnums::OBJECT_LIBRARY:
  39. return new cmNinjaNormalTargetGenerator(target);
  40. case cmStateEnums::UTILITY:
  41. case cmStateEnums::GLOBAL_TARGET:
  42. return new cmNinjaUtilityTargetGenerator(target);
  43. default:
  44. return nullptr;
  45. }
  46. }
  47. cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
  48. : cmCommonTargetGenerator(target)
  49. , MacOSXContentGenerator(nullptr)
  50. , OSXBundleGenerator(nullptr)
  51. , MacContentFolders()
  52. , LocalGenerator(
  53. static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
  54. , Objects()
  55. {
  56. MacOSXContentGenerator = new MacOSXContentGeneratorType(this);
  57. }
  58. cmNinjaTargetGenerator::~cmNinjaTargetGenerator()
  59. {
  60. delete this->MacOSXContentGenerator;
  61. }
  62. cmGeneratedFileStream& cmNinjaTargetGenerator::GetBuildFileStream() const
  63. {
  64. return *this->GetGlobalGenerator()->GetBuildFileStream();
  65. }
  66. cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
  67. {
  68. return *this->GetGlobalGenerator()->GetRulesFileStream();
  69. }
  70. cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
  71. {
  72. return this->LocalGenerator->GetGlobalNinjaGenerator();
  73. }
  74. std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  75. const std::string& lang) const
  76. {
  77. return lang + "_COMPILER__" +
  78. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  79. }
  80. std::string cmNinjaTargetGenerator::LanguagePreprocessRule(
  81. std::string const& lang) const
  82. {
  83. return lang + "_PREPROCESS__" +
  84. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  85. }
  86. bool cmNinjaTargetGenerator::NeedExplicitPreprocessing(
  87. std::string const& lang) const
  88. {
  89. return lang == "Fortran";
  90. }
  91. std::string cmNinjaTargetGenerator::LanguageDyndepRule(
  92. const std::string& lang) const
  93. {
  94. return lang + "_DYNDEP__" +
  95. cmGlobalNinjaGenerator::EncodeRuleName(this->GeneratorTarget->GetName());
  96. }
  97. bool cmNinjaTargetGenerator::NeedDyndep(std::string const& lang) const
  98. {
  99. return lang == "Fortran";
  100. }
  101. std::string cmNinjaTargetGenerator::OrderDependsTargetForTarget()
  102. {
  103. return "cmake_object_order_depends_target_" + this->GetTargetName();
  104. }
  105. // TODO: Most of the code is picked up from
  106. // void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
  107. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
  108. // Refactor it.
  109. std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
  110. cmSourceFile const* source, const std::string& language)
  111. {
  112. std::string flags = this->GetFlags(language);
  113. // Add Fortran format flags.
  114. if (language == "Fortran") {
  115. this->AppendFortranFormatFlags(flags, *source);
  116. }
  117. // Add source file specific flags.
  118. cmGeneratorExpressionInterpreter genexInterpreter(
  119. this->LocalGenerator, this->LocalGenerator->GetConfigName(),
  120. this->GeneratorTarget, language);
  121. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  122. if (const char* cflags = source->GetProperty(COMPILE_FLAGS)) {
  123. this->LocalGenerator->AppendFlags(
  124. flags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
  125. }
  126. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  127. if (const char* coptions = source->GetProperty(COMPILE_OPTIONS)) {
  128. this->LocalGenerator->AppendCompileOptions(
  129. flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
  130. }
  131. return flags;
  132. }
  133. void cmNinjaTargetGenerator::AddIncludeFlags(std::string& languageFlags,
  134. std::string const& language)
  135. {
  136. std::vector<std::string> includes;
  137. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  138. language, this->GetConfigName());
  139. // Add include directory flags.
  140. std::string includeFlags = this->LocalGenerator->GetIncludeFlags(
  141. includes, this->GeneratorTarget, language,
  142. language == "RC", // full include paths for RC needed by cmcldeps
  143. false, this->GetConfigName());
  144. if (this->GetGlobalGenerator()->IsGCCOnWindows()) {
  145. std::replace(includeFlags.begin(), includeFlags.end(), '\\', '/');
  146. }
  147. this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
  148. }
  149. bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const
  150. {
  151. return (this->GetMakefile()->GetSafeDefinition("CMAKE_NINJA_DEPTYPE_" +
  152. lang) == "msvc");
  153. }
  154. // TODO: Refactor with
  155. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  156. std::string cmNinjaTargetGenerator::ComputeDefines(cmSourceFile const* source,
  157. const std::string& language)
  158. {
  159. std::set<std::string> defines;
  160. const std::string config = this->LocalGenerator->GetConfigName();
  161. cmGeneratorExpressionInterpreter genexInterpreter(
  162. this->LocalGenerator, config, this->GeneratorTarget, language);
  163. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  164. if (const char* compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  165. this->LocalGenerator->AppendDefines(
  166. defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS));
  167. }
  168. std::string defPropName = "COMPILE_DEFINITIONS_";
  169. defPropName += cmSystemTools::UpperCase(config);
  170. if (const char* config_compile_defs = source->GetProperty(defPropName)) {
  171. this->LocalGenerator->AppendDefines(
  172. defines,
  173. genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS));
  174. }
  175. std::string definesString = this->GetDefines(language);
  176. this->LocalGenerator->JoinDefines(defines, definesString, language);
  177. return definesString;
  178. }
  179. std::string cmNinjaTargetGenerator::ComputeIncludes(
  180. cmSourceFile const* source, const std::string& language)
  181. {
  182. std::vector<std::string> includes;
  183. const std::string config = this->LocalGenerator->GetConfigName();
  184. cmGeneratorExpressionInterpreter genexInterpreter(
  185. this->LocalGenerator, config, this->GeneratorTarget, language);
  186. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  187. if (const char* cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  188. this->LocalGenerator->AppendIncludeDirectories(
  189. includes, genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES),
  190. *source);
  191. }
  192. std::string includesString = this->LocalGenerator->GetIncludeFlags(
  193. includes, this->GeneratorTarget, language, true, false, config);
  194. this->LocalGenerator->AppendFlags(includesString,
  195. this->GetIncludes(language));
  196. return includesString;
  197. }
  198. cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps(
  199. const std::string& linkLanguage) const
  200. {
  201. // Static libraries never depend on other targets for linking.
  202. if (this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  203. this->GeneratorTarget->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  204. return cmNinjaDeps();
  205. }
  206. cmComputeLinkInformation* cli =
  207. this->GeneratorTarget->GetLinkInformation(this->GetConfigName());
  208. if (!cli) {
  209. return cmNinjaDeps();
  210. }
  211. const std::vector<std::string>& deps = cli->GetDepends();
  212. cmNinjaDeps result(deps.size());
  213. std::transform(deps.begin(), deps.end(), result.begin(), MapToNinjaPath());
  214. // Add a dependency on the link definitions file, if any.
  215. if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  216. this->GeneratorTarget->GetModuleDefinitionInfo(
  217. this->GetConfigName())) {
  218. for (cmSourceFile const* src : mdi->Sources) {
  219. result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
  220. }
  221. }
  222. // Add a dependency on user-specified manifest files, if any.
  223. std::vector<cmSourceFile const*> manifest_srcs;
  224. this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
  225. for (cmSourceFile const* manifest_src : manifest_srcs) {
  226. result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
  227. }
  228. // Add user-specified dependencies.
  229. std::vector<std::string> linkDeps;
  230. this->GeneratorTarget->GetLinkDepends(linkDeps, this->ConfigName,
  231. linkLanguage);
  232. std::transform(linkDeps.begin(), linkDeps.end(), std::back_inserter(result),
  233. MapToNinjaPath());
  234. return result;
  235. }
  236. std::string cmNinjaTargetGenerator::GetSourceFilePath(
  237. cmSourceFile const* source) const
  238. {
  239. return ConvertToNinjaPath(source->GetFullPath());
  240. }
  241. std::string cmNinjaTargetGenerator::GetObjectFilePath(
  242. cmSourceFile const* source) const
  243. {
  244. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  245. if (!path.empty()) {
  246. path += "/";
  247. }
  248. std::string const& objectName = this->GeneratorTarget->GetObjectName(source);
  249. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  250. path += "/";
  251. path += objectName;
  252. return path;
  253. }
  254. std::string cmNinjaTargetGenerator::GetPreprocessedFilePath(
  255. cmSourceFile const* source) const
  256. {
  257. // Choose an extension to compile already-preprocessed source.
  258. std::string ppExt = source->GetExtension();
  259. if (cmHasLiteralPrefix(ppExt, "F")) {
  260. // Some Fortran compilers automatically enable preprocessing for
  261. // upper-case extensions. Since the source is already preprocessed,
  262. // use a lower-case extension.
  263. ppExt = cmSystemTools::LowerCase(ppExt);
  264. }
  265. if (ppExt == "fpp") {
  266. // Some Fortran compilers automatically enable preprocessing for
  267. // the ".fpp" extension. Since the source is already preprocessed,
  268. // use the ".f" extension.
  269. ppExt = "f";
  270. }
  271. // Take the object file name and replace the extension.
  272. std::string const& objName = this->GeneratorTarget->GetObjectName(source);
  273. std::string const& objExt =
  274. this->GetGlobalGenerator()->GetLanguageOutputExtension(*source);
  275. assert(objName.size() >= objExt.size());
  276. std::string const ppName =
  277. objName.substr(0, objName.size() - objExt.size()) + "-pp." + ppExt;
  278. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  279. if (!path.empty()) {
  280. path += "/";
  281. }
  282. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  283. path += "/";
  284. path += ppName;
  285. return path;
  286. }
  287. std::string cmNinjaTargetGenerator::GetDyndepFilePath(
  288. std::string const& lang) const
  289. {
  290. std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  291. if (!path.empty()) {
  292. path += "/";
  293. }
  294. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  295. path += "/";
  296. path += lang;
  297. path += ".dd";
  298. return path;
  299. }
  300. std::string cmNinjaTargetGenerator::GetTargetDependInfoPath(
  301. std::string const& lang) const
  302. {
  303. std::string path = this->Makefile->GetCurrentBinaryDirectory();
  304. path += "/";
  305. path += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  306. path += "/" + lang + "DependInfo.json";
  307. return path;
  308. }
  309. std::string cmNinjaTargetGenerator::GetTargetOutputDir() const
  310. {
  311. std::string dir = this->GeneratorTarget->GetDirectory(this->GetConfigName());
  312. return ConvertToNinjaPath(dir);
  313. }
  314. std::string cmNinjaTargetGenerator::GetTargetFilePath(
  315. const std::string& name) const
  316. {
  317. std::string path = this->GetTargetOutputDir();
  318. if (path.empty() || path == ".") {
  319. return name;
  320. }
  321. path += "/";
  322. path += name;
  323. return path;
  324. }
  325. std::string cmNinjaTargetGenerator::GetTargetName() const
  326. {
  327. return this->GeneratorTarget->GetName();
  328. }
  329. bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const
  330. {
  331. cmMakefile* mf = this->GetMakefile();
  332. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  333. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  334. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  335. std::string pdbPath;
  336. std::string compilePdbPath = this->ComputeTargetCompilePDB();
  337. if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE ||
  338. this->GeneratorTarget->GetType() == cmStateEnums::STATIC_LIBRARY ||
  339. this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY ||
  340. this->GeneratorTarget->GetType() == cmStateEnums::MODULE_LIBRARY) {
  341. pdbPath = this->GeneratorTarget->GetPDBDirectory(this->GetConfigName());
  342. pdbPath += "/";
  343. pdbPath += this->GeneratorTarget->GetPDBName(this->GetConfigName());
  344. }
  345. vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  346. ConvertToNinjaPath(pdbPath), cmOutputConverter::SHELL);
  347. vars["TARGET_COMPILE_PDB"] =
  348. this->GetLocalGenerator()->ConvertToOutputFormat(
  349. ConvertToNinjaPath(compilePdbPath), cmOutputConverter::SHELL);
  350. EnsureParentDirectoryExists(pdbPath);
  351. EnsureParentDirectoryExists(compilePdbPath);
  352. return true;
  353. }
  354. return false;
  355. }
  356. void cmNinjaTargetGenerator::WriteLanguageRules(const std::string& language)
  357. {
  358. #ifdef NINJA_GEN_VERBOSE_FILES
  359. this->GetRulesFileStream() << "# Rules for language " << language << "\n\n";
  360. #endif
  361. this->WriteCompileRule(language);
  362. }
  363. void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
  364. {
  365. cmRulePlaceholderExpander::RuleVariables vars;
  366. vars.CMTargetName = this->GetGeneratorTarget()->GetName().c_str();
  367. vars.CMTargetType =
  368. cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType());
  369. vars.Language = lang.c_str();
  370. vars.Source = "$in";
  371. vars.Object = "$out";
  372. vars.Defines = "$DEFINES";
  373. vars.Includes = "$INCLUDES";
  374. vars.TargetPDB = "$TARGET_PDB";
  375. vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
  376. vars.ObjectDir = "$OBJECT_DIR";
  377. vars.ObjectFileDir = "$OBJECT_FILE_DIR";
  378. // For some cases we do an explicit preprocessor invocation.
  379. bool const explicitPP = this->NeedExplicitPreprocessing(lang);
  380. bool const needDyndep = this->NeedDyndep(lang);
  381. cmMakefile* mf = this->GetMakefile();
  382. std::string flags = "$FLAGS";
  383. std::string responseFlag;
  384. bool const lang_supports_response = !(lang == "RC" || lang == "CUDA");
  385. if (lang_supports_response && this->ForceResponseFile()) {
  386. std::string const responseFlagVar =
  387. "CMAKE_" + lang + "_RESPONSE_FILE_FLAG";
  388. responseFlag = this->Makefile->GetSafeDefinition(responseFlagVar);
  389. if (responseFlag.empty()) {
  390. responseFlag = "@";
  391. }
  392. }
  393. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  394. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  395. std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
  396. ConvertToNinjaPath(this->GetTargetDependInfoPath(lang)),
  397. cmLocalGenerator::SHELL);
  398. std::string launcher;
  399. const char* val = this->GetLocalGenerator()->GetRuleLauncher(
  400. this->GetGeneratorTarget(), "RULE_LAUNCH_COMPILE");
  401. if (val && *val) {
  402. launcher = val;
  403. launcher += " ";
  404. }
  405. if (explicitPP) {
  406. // Lookup the explicit preprocessing rule.
  407. std::string const ppVar = "CMAKE_" + lang + "_PREPROCESS_SOURCE";
  408. std::string const ppCmd =
  409. this->GetMakefile()->GetRequiredDefinition(ppVar);
  410. // Explicit preprocessing always uses a depfile.
  411. std::string const ppDeptype; // no deps= for multiple outputs
  412. std::string const ppDepfile = "$DEP_FILE";
  413. cmRulePlaceholderExpander::RuleVariables ppVars;
  414. ppVars.CMTargetName = vars.CMTargetName;
  415. ppVars.CMTargetType = vars.CMTargetType;
  416. ppVars.Language = vars.Language;
  417. ppVars.Object = "$out"; // for RULE_LAUNCH_COMPILE
  418. ppVars.PreprocessedSource = "$out";
  419. ppVars.DependencyFile = ppDepfile.c_str();
  420. // Preprocessing uses the original source,
  421. // compilation uses preprocessed output.
  422. ppVars.Source = vars.Source;
  423. vars.Source = "$in";
  424. // Preprocessing and compilation use the same flags.
  425. std::string ppFlags = flags;
  426. // Move preprocessor definitions to the preprocessor rule.
  427. ppVars.Defines = vars.Defines;
  428. vars.Defines = "";
  429. // Copy include directories to the preprocessor rule. The Fortran
  430. // compilation rule still needs them for the INCLUDE directive.
  431. ppVars.Includes = vars.Includes;
  432. // If using a response file, move defines, includes, and flags into it.
  433. std::string ppRspFile;
  434. std::string ppRspContent;
  435. if (!responseFlag.empty()) {
  436. ppRspFile = "$RSP_FILE";
  437. ppRspContent = std::string(" ") + ppVars.Defines + " " +
  438. ppVars.Includes + " " + ppFlags;
  439. ppFlags = responseFlag + ppRspFile;
  440. ppVars.Defines = "";
  441. ppVars.Includes = "";
  442. }
  443. ppVars.Flags = ppFlags.c_str();
  444. // Rule for preprocessing source file.
  445. std::vector<std::string> ppCmds;
  446. cmSystemTools::ExpandListArgument(ppCmd, ppCmds);
  447. for (std::string& i : ppCmds) {
  448. i = launcher + i;
  449. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
  450. i, ppVars);
  451. }
  452. // Run CMake dependency scanner on preprocessed output.
  453. std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
  454. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  455. ppCmds.push_back(
  456. cmake +
  457. " -E cmake_ninja_depends"
  458. " --tdi=" +
  459. tdi +
  460. " --pp=$out"
  461. " --dep=$DEP_FILE" +
  462. (needDyndep ? " --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE" : ""));
  463. std::string const ppCmdLine =
  464. this->GetLocalGenerator()->BuildCommandLine(ppCmds);
  465. // Write the rule for preprocessing file of the given language.
  466. std::ostringstream ppComment;
  467. ppComment << "Rule for preprocessing " << lang << " files.";
  468. std::ostringstream ppDesc;
  469. ppDesc << "Building " << lang << " preprocessed $out";
  470. this->GetGlobalGenerator()->AddRule(
  471. this->LanguagePreprocessRule(lang), ppCmdLine, ppDesc.str(),
  472. ppComment.str(), ppDepfile, ppDeptype, ppRspFile, ppRspContent,
  473. /*restat*/ "",
  474. /*generator*/ false);
  475. }
  476. if (needDyndep) {
  477. // Write the rule for ninja dyndep file generation.
  478. std::vector<std::string> ddCmds;
  479. // Command line length is almost always limited -> use response file for
  480. // dyndep rules
  481. std::string ddRspFile = "$out.rsp";
  482. std::string ddRspContent = "$in";
  483. std::string ddInput = "@" + ddRspFile;
  484. // Run CMake dependency scanner on preprocessed output.
  485. std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
  486. cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
  487. ddCmds.push_back(cmake +
  488. " -E cmake_ninja_dyndep"
  489. " --tdi=" +
  490. tdi +
  491. " --dd=$out"
  492. " " +
  493. ddInput);
  494. std::string const ddCmdLine =
  495. this->GetLocalGenerator()->BuildCommandLine(ddCmds);
  496. std::ostringstream ddComment;
  497. ddComment << "Rule to generate ninja dyndep files for " << lang << ".";
  498. std::ostringstream ddDesc;
  499. ddDesc << "Generating " << lang << " dyndep file $out";
  500. this->GetGlobalGenerator()->AddRule(
  501. this->LanguageDyndepRule(lang), ddCmdLine, ddDesc.str(), ddComment.str(),
  502. /*depfile*/ "",
  503. /*deps*/ "", ddRspFile, ddRspContent,
  504. /*restat*/ "",
  505. /*generator*/ false);
  506. }
  507. // If using a response file, move defines, includes, and flags into it.
  508. std::string rspfile;
  509. std::string rspcontent;
  510. if (!responseFlag.empty()) {
  511. rspfile = "$RSP_FILE";
  512. rspcontent =
  513. std::string(" ") + vars.Defines + " " + vars.Includes + " " + flags;
  514. flags = responseFlag + rspfile;
  515. vars.Defines = "";
  516. vars.Includes = "";
  517. }
  518. // Tell ninja dependency format so all deps can be loaded into a database
  519. std::string deptype;
  520. std::string depfile;
  521. std::string cldeps;
  522. if (explicitPP) {
  523. // The explicit preprocessing step will handle dependency scanning.
  524. } else if (this->NeedDepTypeMSVC(lang)) {
  525. deptype = "msvc";
  526. depfile.clear();
  527. flags += " /showIncludes";
  528. } else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) {
  529. // For the MS resource compiler we need cmcldeps, but skip dependencies
  530. // for source-file try_compile cases because they are always fresh.
  531. if (!mf->GetIsSourceFileTryCompile()) {
  532. deptype = "gcc";
  533. depfile = "$DEP_FILE";
  534. const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER")
  535. ? mf->GetSafeDefinition("CMAKE_C_COMPILER")
  536. : mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
  537. cldeps = "\"";
  538. cldeps += cmSystemTools::GetCMClDepsCommand();
  539. cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \"";
  540. cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
  541. cldeps += "\" \"" + cl + "\" ";
  542. }
  543. } else {
  544. deptype = "gcc";
  545. const char* langdeptype = mf->GetDefinition("CMAKE_NINJA_DEPTYPE_" + lang);
  546. if (langdeptype) {
  547. deptype = langdeptype;
  548. }
  549. depfile = "$DEP_FILE";
  550. const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang;
  551. std::string depfileFlags = mf->GetSafeDefinition(flagsName);
  552. if (!depfileFlags.empty()) {
  553. cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
  554. cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>", "$out");
  555. cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>",
  556. mf->GetDefinition("CMAKE_C_COMPILER"));
  557. flags += " " + depfileFlags;
  558. }
  559. }
  560. vars.Flags = flags.c_str();
  561. vars.DependencyFile = depfile.c_str();
  562. // Rule for compiling object file.
  563. std::vector<std::string> compileCmds;
  564. if (lang == "CUDA") {
  565. std::string cmdVar;
  566. if (this->GeneratorTarget->GetPropertyAsBool(
  567. "CUDA_SEPARABLE_COMPILATION")) {
  568. cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  569. } else if (this->GeneratorTarget->GetPropertyAsBool(
  570. "CUDA_PTX_COMPILATION")) {
  571. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  572. } else {
  573. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  574. }
  575. std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
  576. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  577. } else {
  578. const std::string cmdVar =
  579. std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
  580. std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
  581. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  582. }
  583. // See if we need to use a compiler launcher like ccache or distcc
  584. std::string compilerLauncher;
  585. if (!compileCmds.empty() &&
  586. (lang == "C" || lang == "CXX" || lang == "Fortran" || lang == "CUDA")) {
  587. std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
  588. const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
  589. if (clauncher && *clauncher) {
  590. compilerLauncher = clauncher;
  591. }
  592. }
  593. // Maybe insert an include-what-you-use runner.
  594. if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
  595. std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
  596. const char* iwyu = this->GeneratorTarget->GetProperty(iwyu_prop);
  597. std::string const tidy_prop = lang + "_CLANG_TIDY";
  598. const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
  599. std::string const cpplint_prop = lang + "_CPPLINT";
  600. const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
  601. std::string const cppcheck_prop = lang + "_CPPCHECK";
  602. const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
  603. if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
  604. (cppcheck && *cppcheck)) {
  605. std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat(
  606. cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
  607. run_iwyu += " -E __run_co_compile";
  608. if (!compilerLauncher.empty()) {
  609. // In __run_co_compile case the launcher command is supplied
  610. // via --launcher=<maybe-list> and consumed
  611. run_iwyu += " --launcher=";
  612. run_iwyu += this->LocalGenerator->EscapeForShell(compilerLauncher);
  613. compilerLauncher.clear();
  614. }
  615. if (iwyu && *iwyu) {
  616. run_iwyu += " --iwyu=";
  617. run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu);
  618. }
  619. if (tidy && *tidy) {
  620. run_iwyu += " --tidy=";
  621. run_iwyu += this->GetLocalGenerator()->EscapeForShell(tidy);
  622. }
  623. if (cpplint && *cpplint) {
  624. run_iwyu += " --cpplint=";
  625. run_iwyu += this->GetLocalGenerator()->EscapeForShell(cpplint);
  626. }
  627. if (cppcheck && *cppcheck) {
  628. run_iwyu += " --cppcheck=";
  629. run_iwyu += this->GetLocalGenerator()->EscapeForShell(cppcheck);
  630. }
  631. if ((tidy && *tidy) || (cpplint && *cpplint) ||
  632. (cppcheck && *cppcheck)) {
  633. run_iwyu += " --source=$in";
  634. }
  635. run_iwyu += " -- ";
  636. compileCmds.front().insert(0, run_iwyu);
  637. }
  638. }
  639. // If compiler launcher was specified and not consumed above, it
  640. // goes to the beginning of the command line.
  641. if (!compileCmds.empty() && !compilerLauncher.empty()) {
  642. std::vector<std::string> args;
  643. cmSystemTools::ExpandListArgument(compilerLauncher, args, true);
  644. for (std::string& i : args) {
  645. i = this->LocalGenerator->EscapeForShell(i);
  646. }
  647. compileCmds.front().insert(0, cmJoin(args, " ") + " ");
  648. }
  649. if (!compileCmds.empty()) {
  650. compileCmds.front().insert(0, cldeps);
  651. }
  652. for (std::string& i : compileCmds) {
  653. i = launcher + i;
  654. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  655. vars);
  656. }
  657. std::string cmdLine =
  658. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  659. // Write the rule for compiling file of the given language.
  660. std::ostringstream comment;
  661. comment << "Rule for compiling " << lang << " files.";
  662. std::ostringstream description;
  663. description << "Building " << lang << " object $out";
  664. this->GetGlobalGenerator()->AddRule(
  665. this->LanguageCompilerRule(lang), cmdLine, description.str(),
  666. comment.str(), depfile, deptype, rspfile, rspcontent,
  667. /*restat*/ "",
  668. /*generator*/ false);
  669. }
  670. void cmNinjaTargetGenerator::WriteObjectBuildStatements()
  671. {
  672. // Write comments.
  673. cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  674. this->GetBuildFileStream()
  675. << "# Object build statements for "
  676. << cmState::GetTargetTypeName(this->GetGeneratorTarget()->GetType())
  677. << " target " << this->GetTargetName() << "\n\n";
  678. std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  679. std::vector<cmSourceFile const*> customCommands;
  680. this->GeneratorTarget->GetCustomCommands(customCommands, config);
  681. for (cmSourceFile const* sf : customCommands) {
  682. cmCustomCommand const* cc = sf->GetCustomCommand();
  683. this->GetLocalGenerator()->AddCustomCommandTarget(
  684. cc, this->GetGeneratorTarget());
  685. // Record the custom commands for this target. The container is used
  686. // in WriteObjectBuildStatement when called in a loop below.
  687. this->CustomCommands.push_back(cc);
  688. }
  689. std::vector<cmSourceFile const*> headerSources;
  690. this->GeneratorTarget->GetHeaderSources(headerSources, config);
  691. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  692. headerSources, this->MacOSXContentGenerator);
  693. std::vector<cmSourceFile const*> extraSources;
  694. this->GeneratorTarget->GetExtraSources(extraSources, config);
  695. this->OSXBundleGenerator->GenerateMacOSXContentStatements(
  696. extraSources, this->MacOSXContentGenerator);
  697. std::vector<cmSourceFile const*> externalObjects;
  698. this->GeneratorTarget->GetExternalObjects(externalObjects, config);
  699. for (cmSourceFile const* sf : externalObjects) {
  700. this->Objects.push_back(this->GetSourceFilePath(sf));
  701. }
  702. cmNinjaDeps orderOnlyDeps;
  703. this->GetLocalGenerator()->AppendTargetDepends(
  704. this->GeneratorTarget, orderOnlyDeps, DependOnTargetOrdering);
  705. // Add order-only dependencies on other files associated with the target.
  706. orderOnlyDeps.insert(orderOnlyDeps.end(), this->ExtraFiles.begin(),
  707. this->ExtraFiles.end());
  708. // Add order-only dependencies on custom command outputs.
  709. for (cmCustomCommand const* cc : this->CustomCommands) {
  710. cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
  711. this->GetLocalGenerator());
  712. const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
  713. const std::vector<std::string>& ccbyproducts = ccg.GetByproducts();
  714. std::transform(ccoutputs.begin(), ccoutputs.end(),
  715. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  716. std::transform(ccbyproducts.begin(), ccbyproducts.end(),
  717. std::back_inserter(orderOnlyDeps), MapToNinjaPath());
  718. }
  719. std::sort(orderOnlyDeps.begin(), orderOnlyDeps.end());
  720. orderOnlyDeps.erase(std::unique(orderOnlyDeps.begin(), orderOnlyDeps.end()),
  721. orderOnlyDeps.end());
  722. // The phony target must depend on at least one input or ninja will explain
  723. // that "output ... of phony edge with no inputs doesn't exist" and consider
  724. // the phony output "dirty".
  725. if (orderOnlyDeps.empty()) {
  726. // Any path that always exists will work here. It would be nice to
  727. // use just "." but that is not supported by Ninja < 1.7.
  728. std::string tgtDir;
  729. tgtDir += this->LocalGenerator->GetCurrentBinaryDirectory();
  730. tgtDir += "/";
  731. tgtDir += this->LocalGenerator->GetTargetDirectory(this->GeneratorTarget);
  732. orderOnlyDeps.push_back(this->ConvertToNinjaPath(tgtDir));
  733. }
  734. {
  735. cmNinjaDeps orderOnlyTarget;
  736. orderOnlyTarget.push_back(this->OrderDependsTargetForTarget());
  737. this->GetGlobalGenerator()->WritePhonyBuild(
  738. this->GetBuildFileStream(),
  739. "Order-only phony target for " + this->GetTargetName(), orderOnlyTarget,
  740. cmNinjaDeps(), cmNinjaDeps(), orderOnlyDeps);
  741. }
  742. std::vector<cmSourceFile const*> objectSources;
  743. this->GeneratorTarget->GetObjectSources(objectSources, config);
  744. for (cmSourceFile const* sf : objectSources) {
  745. this->WriteObjectBuildStatement(sf);
  746. }
  747. if (!this->DDIFiles.empty()) {
  748. std::string const ddComment;
  749. std::string const ddRule = this->LanguageDyndepRule("Fortran");
  750. cmNinjaDeps ddOutputs;
  751. cmNinjaDeps ddImplicitOuts;
  752. cmNinjaDeps const& ddExplicitDeps = this->DDIFiles;
  753. cmNinjaDeps ddImplicitDeps;
  754. cmNinjaDeps ddOrderOnlyDeps;
  755. cmNinjaVars ddVars;
  756. this->WriteTargetDependInfo("Fortran");
  757. ddOutputs.push_back(this->GetDyndepFilePath("Fortran"));
  758. // Make sure dyndep files for all our dependencies have already
  759. // been generated so that the 'FortranModules.json' files they
  760. // produced as side-effects are available for us to read.
  761. // Ideally we should depend on the 'FortranModules.json' files
  762. // from our dependencies directly, but we don't know which of
  763. // our dependencies produces them. Fixing this will require
  764. // refactoring the Ninja generator to generate targets in
  765. // dependency order so that we can collect the needed information.
  766. this->GetLocalGenerator()->AppendTargetDepends(
  767. this->GeneratorTarget, ddOrderOnlyDeps, DependOnTargetArtifact);
  768. this->GetGlobalGenerator()->WriteBuild(
  769. this->GetBuildFileStream(), ddComment, ddRule, ddOutputs, ddImplicitOuts,
  770. ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
  771. }
  772. this->GetBuildFileStream() << "\n";
  773. }
  774. void cmNinjaTargetGenerator::WriteObjectBuildStatement(
  775. cmSourceFile const* source)
  776. {
  777. std::string const language = source->GetLanguage();
  778. std::string const sourceFileName =
  779. language == "RC" ? source->GetFullPath() : this->GetSourceFilePath(source);
  780. std::string const objectDir =
  781. this->ConvertToNinjaPath(this->GeneratorTarget->GetSupportDirectory());
  782. std::string const objectFileName =
  783. this->ConvertToNinjaPath(this->GetObjectFilePath(source));
  784. std::string const objectFileDir =
  785. cmSystemTools::GetFilenamePath(objectFileName);
  786. bool const lang_supports_response =
  787. !(language == "RC" || language == "CUDA");
  788. int const commandLineLengthLimit =
  789. ((lang_supports_response && this->ForceResponseFile())) ? -1 : 0;
  790. cmNinjaVars vars;
  791. vars["FLAGS"] = this->ComputeFlagsForObject(source, language);
  792. vars["DEFINES"] = this->ComputeDefines(source, language);
  793. vars["INCLUDES"] = this->ComputeIncludes(source, language);
  794. if (!this->NeedDepTypeMSVC(language)) {
  795. bool replaceExt(false);
  796. if (!language.empty()) {
  797. std::string repVar = "CMAKE_";
  798. repVar += language;
  799. repVar += "_DEPFILE_EXTENSION_REPLACE";
  800. replaceExt = this->Makefile->IsOn(repVar);
  801. }
  802. if (!replaceExt) {
  803. // use original code
  804. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  805. objectFileName + ".d", cmOutputConverter::SHELL);
  806. } else {
  807. // Replace the original source file extension with the
  808. // depend file extension.
  809. std::string dependFileName =
  810. cmSystemTools::GetFilenameWithoutLastExtension(objectFileName) + ".d";
  811. vars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  812. objectFileDir + "/" + dependFileName, cmOutputConverter::SHELL);
  813. }
  814. }
  815. this->ExportObjectCompileCommand(
  816. language, sourceFileName, objectDir, objectFileName, objectFileDir,
  817. vars["FLAGS"], vars["DEFINES"], vars["INCLUDES"]);
  818. std::string comment;
  819. std::string rule = this->LanguageCompilerRule(language);
  820. cmNinjaDeps outputs;
  821. outputs.push_back(objectFileName);
  822. // Add this object to the list of object files.
  823. this->Objects.push_back(objectFileName);
  824. cmNinjaDeps explicitDeps;
  825. explicitDeps.push_back(sourceFileName);
  826. cmNinjaDeps implicitDeps;
  827. if (const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
  828. std::vector<std::string> depList;
  829. cmSystemTools::ExpandListArgument(objectDeps, depList);
  830. for (std::string& odi : depList) {
  831. if (cmSystemTools::FileIsFullPath(odi)) {
  832. odi = cmSystemTools::CollapseFullPath(odi);
  833. }
  834. }
  835. std::transform(depList.begin(), depList.end(),
  836. std::back_inserter(implicitDeps), MapToNinjaPath());
  837. }
  838. cmNinjaDeps orderOnlyDeps;
  839. orderOnlyDeps.push_back(this->OrderDependsTargetForTarget());
  840. // If the source file is GENERATED and does not have a custom command
  841. // (either attached to this source file or another one), assume that one of
  842. // the target dependencies, OBJECT_DEPENDS or header file custom commands
  843. // will rebuild the file.
  844. if (source->GetPropertyAsBool("GENERATED") &&
  845. !source->GetPropertyAsBool("__CMAKE_GENERATED_BY_CMAKE") &&
  846. !source->GetCustomCommand() &&
  847. !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFileName)) {
  848. this->GetGlobalGenerator()->AddAssumedSourceDependencies(sourceFileName,
  849. orderOnlyDeps);
  850. }
  851. // For some cases we need to generate a ninja dyndep file.
  852. bool const needDyndep = this->NeedDyndep(language);
  853. // For some cases we do an explicit preprocessor invocation.
  854. bool const explicitPP = this->NeedExplicitPreprocessing(language);
  855. if (explicitPP) {
  856. std::string const ppComment;
  857. std::string const ppRule = this->LanguagePreprocessRule(language);
  858. cmNinjaDeps ppOutputs;
  859. cmNinjaDeps ppImplicitOuts;
  860. cmNinjaDeps ppExplicitDeps;
  861. cmNinjaDeps ppImplicitDeps;
  862. cmNinjaDeps ppOrderOnlyDeps;
  863. cmNinjaVars ppVars;
  864. std::string const ppFileName =
  865. this->ConvertToNinjaPath(this->GetPreprocessedFilePath(source));
  866. ppOutputs.push_back(ppFileName);
  867. // Move compilation dependencies to the preprocessing build statement.
  868. std::swap(ppExplicitDeps, explicitDeps);
  869. std::swap(ppImplicitDeps, implicitDeps);
  870. std::swap(ppOrderOnlyDeps, orderOnlyDeps);
  871. std::swap(ppVars["IN_ABS"], vars["IN_ABS"]);
  872. // The actual compilation will now use the preprocessed source.
  873. explicitDeps.push_back(ppFileName);
  874. // Preprocessing and compilation generally use the same flags.
  875. ppVars["FLAGS"] = vars["FLAGS"];
  876. // In case compilation requires flags that are incompatible with
  877. // preprocessing, include them here.
  878. std::string const postFlag =
  879. this->Makefile->GetSafeDefinition("CMAKE_Fortran_POSTPROCESS_FLAG");
  880. this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
  881. // Move preprocessor definitions to the preprocessor build statement.
  882. std::swap(ppVars["DEFINES"], vars["DEFINES"]);
  883. // Copy include directories to the preprocessor build statement. The
  884. // Fortran compilation build statement still needs them for the INCLUDE
  885. // directive.
  886. ppVars["INCLUDES"] = vars["INCLUDES"];
  887. // Prepend source file's original directory as an include directory
  888. // so e.g. Fortran INCLUDE statements can look for files in it.
  889. std::vector<std::string> sourceDirectory;
  890. sourceDirectory.push_back(
  891. cmSystemTools::GetParentDirectory(source->GetFullPath()));
  892. std::string sourceDirectoryFlag = this->LocalGenerator->GetIncludeFlags(
  893. sourceDirectory, this->GeneratorTarget, language, false, false,
  894. this->GetConfigName());
  895. vars["INCLUDES"] = sourceDirectoryFlag + " " + vars["INCLUDES"];
  896. // Explicit preprocessing always uses a depfile.
  897. ppVars["DEP_FILE"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  898. ppFileName + ".d", cmOutputConverter::SHELL);
  899. // The actual compilation does not need a depfile because it
  900. // depends on the already-preprocessed source.
  901. vars.erase("DEP_FILE");
  902. if (needDyndep) {
  903. // Tell dependency scanner the object file that will result from
  904. // compiling the preprocessed source.
  905. ppVars["OBJ_FILE"] = objectFileName;
  906. // Tell dependency scanner where to store dyndep intermediate results.
  907. std::string const ddiFile = ppFileName + ".ddi";
  908. ppVars["DYNDEP_INTERMEDIATE_FILE"] = ddiFile;
  909. ppImplicitOuts.push_back(ddiFile);
  910. this->DDIFiles.push_back(ddiFile);
  911. }
  912. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  913. ppVars);
  914. std::string const ppRspFile = ppFileName + ".rsp";
  915. this->GetGlobalGenerator()->WriteBuild(
  916. this->GetBuildFileStream(), ppComment, ppRule, ppOutputs, ppImplicitOuts,
  917. ppExplicitDeps, ppImplicitDeps, ppOrderOnlyDeps, ppVars, ppRspFile,
  918. commandLineLengthLimit);
  919. }
  920. if (needDyndep) {
  921. std::string const dyndep = this->GetDyndepFilePath(language);
  922. orderOnlyDeps.push_back(dyndep);
  923. vars["dyndep"] = dyndep;
  924. }
  925. EnsureParentDirectoryExists(objectFileName);
  926. vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  927. objectDir, cmOutputConverter::SHELL);
  928. vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
  929. objectFileDir, cmOutputConverter::SHELL);
  930. this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetGeneratorTarget(),
  931. vars);
  932. this->SetMsvcTargetPdbVariable(vars);
  933. std::string const rspfile = objectFileName + ".rsp";
  934. this->GetGlobalGenerator()->WriteBuild(
  935. this->GetBuildFileStream(), comment, rule, outputs,
  936. /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps, orderOnlyDeps,
  937. vars, rspfile, commandLineLengthLimit);
  938. if (const char* objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
  939. std::vector<std::string> outputList;
  940. cmSystemTools::ExpandListArgument(objectOutputs, outputList);
  941. std::transform(outputList.begin(), outputList.end(), outputList.begin(),
  942. MapToNinjaPath());
  943. this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
  944. "Additional output files.",
  945. outputList, outputs);
  946. }
  947. }
  948. void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang)
  949. {
  950. Json::Value tdi(Json::objectValue);
  951. tdi["language"] = lang;
  952. tdi["compiler-id"] =
  953. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID");
  954. if (lang == "Fortran") {
  955. std::string mod_dir = this->GeneratorTarget->GetFortranModuleDirectory(
  956. this->Makefile->GetHomeOutputDirectory());
  957. if (mod_dir.empty()) {
  958. mod_dir = this->Makefile->GetCurrentBinaryDirectory();
  959. }
  960. tdi["module-dir"] = mod_dir;
  961. }
  962. tdi["dir-cur-bld"] = this->Makefile->GetCurrentBinaryDirectory();
  963. tdi["dir-cur-src"] = this->Makefile->GetCurrentSourceDirectory();
  964. tdi["dir-top-bld"] = this->Makefile->GetHomeOutputDirectory();
  965. tdi["dir-top-src"] = this->Makefile->GetHomeDirectory();
  966. Json::Value& tdi_include_dirs = tdi["include-dirs"] = Json::arrayValue;
  967. std::vector<std::string> includes;
  968. this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
  969. lang, this->GetConfigName());
  970. for (std::string const& i : includes) {
  971. // Convert the include directories the same way we do for -I flags.
  972. // See upstream ninja issue 1251.
  973. tdi_include_dirs.append(this->ConvertToNinjaPath(i));
  974. }
  975. Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
  976. Json::arrayValue;
  977. std::vector<std::string> linked = this->GetLinkedTargetDirectories();
  978. for (std::string const& l : linked) {
  979. tdi_linked_target_dirs.append(l);
  980. }
  981. std::string const tdin = this->GetTargetDependInfoPath(lang);
  982. cmGeneratedFileStream tdif(tdin);
  983. tdif << tdi;
  984. }
  985. void cmNinjaTargetGenerator::ExportObjectCompileCommand(
  986. std::string const& language, std::string const& sourceFileName,
  987. std::string const& objectDir, std::string const& objectFileName,
  988. std::string const& objectFileDir, std::string const& flags,
  989. std::string const& defines, std::string const& includes)
  990. {
  991. if (!this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS")) {
  992. return;
  993. }
  994. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  995. compileObjectVars.Language = language.c_str();
  996. std::string escapedSourceFileName = sourceFileName;
  997. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  998. escapedSourceFileName =
  999. cmSystemTools::CollapseFullPath(escapedSourceFileName,
  1000. this->GetGlobalGenerator()
  1001. ->GetCMakeInstance()
  1002. ->GetHomeOutputDirectory());
  1003. }
  1004. escapedSourceFileName = this->LocalGenerator->ConvertToOutputFormat(
  1005. escapedSourceFileName, cmOutputConverter::SHELL);
  1006. compileObjectVars.Source = escapedSourceFileName.c_str();
  1007. compileObjectVars.Object = objectFileName.c_str();
  1008. compileObjectVars.ObjectDir = objectDir.c_str();
  1009. compileObjectVars.ObjectFileDir = objectFileDir.c_str();
  1010. compileObjectVars.Flags = flags.c_str();
  1011. compileObjectVars.Defines = defines.c_str();
  1012. compileObjectVars.Includes = includes.c_str();
  1013. // Rule for compiling object file.
  1014. std::vector<std::string> compileCmds;
  1015. if (language == "CUDA") {
  1016. std::string cmdVar;
  1017. if (this->GeneratorTarget->GetPropertyAsBool(
  1018. "CUDA_SEPARABLE_COMPILATION")) {
  1019. cmdVar = std::string("CMAKE_CUDA_COMPILE_SEPARABLE_COMPILATION");
  1020. } else if (this->GeneratorTarget->GetPropertyAsBool(
  1021. "CUDA_PTX_COMPILATION")) {
  1022. cmdVar = std::string("CMAKE_CUDA_COMPILE_PTX_COMPILATION");
  1023. } else {
  1024. cmdVar = std::string("CMAKE_CUDA_COMPILE_WHOLE_COMPILATION");
  1025. }
  1026. std::string compileCmd =
  1027. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1028. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  1029. } else {
  1030. const std::string cmdVar =
  1031. std::string("CMAKE_") + language + "_COMPILE_OBJECT";
  1032. std::string compileCmd =
  1033. this->GetMakefile()->GetRequiredDefinition(cmdVar);
  1034. cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
  1035. }
  1036. std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
  1037. this->GetLocalGenerator()->CreateRulePlaceholderExpander());
  1038. for (std::string& i : compileCmds) {
  1039. // no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
  1040. rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
  1041. compileObjectVars);
  1042. }
  1043. std::string cmdLine =
  1044. this->GetLocalGenerator()->BuildCommandLine(compileCmds);
  1045. this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine, sourceFileName);
  1046. }
  1047. void cmNinjaTargetGenerator::EnsureDirectoryExists(
  1048. const std::string& path) const
  1049. {
  1050. if (cmSystemTools::FileIsFullPath(path)) {
  1051. cmSystemTools::MakeDirectory(path);
  1052. } else {
  1053. cmGlobalNinjaGenerator* gg = this->GetGlobalGenerator();
  1054. std::string fullPath =
  1055. std::string(gg->GetCMakeInstance()->GetHomeOutputDirectory());
  1056. // Also ensures their is a trailing slash.
  1057. gg->StripNinjaOutputPathPrefixAsSuffix(fullPath);
  1058. fullPath += path;
  1059. cmSystemTools::MakeDirectory(fullPath);
  1060. }
  1061. }
  1062. void cmNinjaTargetGenerator::EnsureParentDirectoryExists(
  1063. const std::string& path) const
  1064. {
  1065. EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
  1066. }
  1067. void cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
  1068. cmSourceFile const& source, const char* pkgloc)
  1069. {
  1070. // Skip OS X content when not building a Framework or Bundle.
  1071. if (!this->Generator->GetGeneratorTarget()->IsBundleOnApple()) {
  1072. return;
  1073. }
  1074. std::string macdir =
  1075. this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc);
  1076. // Get the input file location.
  1077. std::string input = source.GetFullPath();
  1078. input = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(input);
  1079. // Get the output file location.
  1080. std::string output = macdir;
  1081. output += "/";
  1082. output += cmSystemTools::GetFilenameName(input);
  1083. output = this->Generator->GetGlobalGenerator()->ConvertToNinjaPath(output);
  1084. // Write a build statement to copy the content into the bundle.
  1085. this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(input,
  1086. output);
  1087. // Add as a dependency to the target so that it gets called.
  1088. this->Generator->ExtraFiles.push_back(std::move(output));
  1089. }
  1090. void cmNinjaTargetGenerator::addPoolNinjaVariable(
  1091. const std::string& pool_property, cmGeneratorTarget* target,
  1092. cmNinjaVars& vars)
  1093. {
  1094. const char* pool = target->GetProperty(pool_property);
  1095. if (pool) {
  1096. vars["pool"] = pool;
  1097. }
  1098. }
  1099. bool cmNinjaTargetGenerator::ForceResponseFile()
  1100. {
  1101. static std::string const forceRspFile = "CMAKE_NINJA_FORCE_RESPONSE_FILE";
  1102. return (this->GetMakefile()->IsDefinitionSet(forceRspFile) ||
  1103. cmSystemTools::HasEnv(forceRspFile));
  1104. }